query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Return the filename of this script with frozen compatibility the filename of THIS script.
def __get_this_filename(): return __file__ if not getattr(sys, 'frozen', False) else sys.executable
[ "def script_name(self):\n return os.path.basename(self.script)", "def _get_filename(self) -> \"std::string\" :\n return _core.SATImportOptions__get_filename(self)", "def _get_filename(self) -> \"std::string\" :\n return _core.ImportOptions__get_filename(self)", "def workflow_filename():\n stacks = inspect.stack()\n frame = inspect.stack()[len(stacks) - 1]\n full_path = frame[0].f_code.co_filename\n filename, _ = os.path.splitext(os.path.basename(full_path))\n filename = argo_safe_name(filename)\n return filename", "def filename(self):\n return f\"{self.sha}{self.extension}\"", "def get_filename(self) -> str:\n return self._filename", "def get_frozen_version(self):\n # todo: put this to use\n basedir = os.path.dirname(sys.executable)\n versions = []\n for dname in os.listdir(basedir):\n dirname = op.join(basedir, dname)\n if op.isdir(dirname) and dname.startswith(self.get_name() + '_'):\n versions.append((dname.split('_')[-1], dirname))\n versions.sort(key=lambda x: versionstring(x[0]))\n if versions:\n return versions[-1]\n return None, None", "def get_script_filepath():\n for frame_info in inspect.stack():\n module = inspect.getmodule(frame_info[0])\n if module is None or module.__name__.split(\".\", 1)[0] != \"verta\":\n filepath = frame_info[1]\n if os.path.exists(filepath): # e.g. Jupyter fakes the filename for cells\n return filepath\n else:\n break # continuing might end up returning a built-in\n raise OSError(\"unable to find script file\")", "def get_installer_filename(self, fullname ):\n\t\ttry:\n\t\t\timport Numeric\n\t\t\tnumeric_version = 'numpy%s'%( string.split(Numeric.__version__, '.')[0], )\n\t\texcept ImportError:\n\t\t\tnumeric_version = 'nonum'\n\t\tif self.target_version:\n\t\t\treturn os.path.join(\n\t\t\t\tself.dist_dir,\n\t\t\t\t\"%s.py%s-%s.exe\" % (\n\t\t\t\t\tfullname,\n\t\t\t\t\tself.target_version,\n\t\t\t\t\tnumeric_version,\n\t\t\t\t)\n\t\t\t)\n\t\telse:\n\t\t\treturn os.path.join(\n\t\t\t\tself.dist_dir,\n\t\t\t\t\"%s.%s.exe\" %(\n\t\t\t\t\tfullname,\n\t\t\t\t\tnumeric_version,\n\t\t\t\t)\n\t\t\t)", "def definition_filename(self):\n return self._frame.f_code.co_filename", "def get_installer_filename(self, fullname ):\n\t\t\tif self.target_version:\n\t\t\t\treturn os.path.join(\n\t\t\t\t\tself.dist_dir,\n\t\t\t\t\t\"%s.win32-py%s.exe\" % (\n\t\t\t\t\t\tfullname,\n\t\t\t\t\t\tself.target_version\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\telse:\n\t\t\t\treturn os.path.join(\n\t\t\t\t\tself.dist_dir,\n\t\t\t\t\t\"%s.win32.exe\" % fullname\n\t\t\t\t)", "def workflow_name():\n wf_name = os.getenv(\"workflow_name\")\n if wf_name != \"\":\n return wf_name\n stacks = inspect.stack()\n frame = inspect.stack()[len(stacks) - 1]\n full_path = frame[0].f_code.co_filename\n filename, _ = os.path.splitext(os.path.basename(full_path))\n filename = _argo_safe_name(filename)\n return filename", "def get_filename(self):\n return self.source.get_filename()", "def current_filename(self):\n return self.dr.fileName()", "def GetScriptName(self):\n\n return string.split(self.__url, \"/\")[-1]", "def get_filename_old(self):\n\n # NOTE: This is just the filename, not the absolute filename path\n return self.validfilenameold", "def get_filename(self):\n\n return \"-\".join([\n str(self.paper.module.code),\n str(self.paper.year_start),\n str(self.paper.year_stop),\n str(self.paper.sitting),\n PaperPDF.period_map[self.paper.period]]\n ) + \".pdf\"", "def get_filename(self, migration):\n return os.path.join(self.directory, '{}{}'.format(migration, self.ext))", "def filename(self):\n return get_product_filename(self)", "def remote_file_name(self) -> str:\n if self._run_name is None:\n raise RuntimeError('The run name is not set. The engine should have been set on Event.INIT')\n name = format_name_with_dist(self.remote_file_name_format, run_name=self._run_name)\n\n name.lstrip('/')\n\n return name" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if path2Test is a subpath of path. Only for clean, absolute (unix) paths without trailing /. No filesystemaccess involved!
def is_subpath(path2Test, path_, allowEquals=False): assert path2Test[-1] != '/' and path_[-1] != '/' if allowEquals and path2Test == path_: return True return path2Test.startswith(path_ + '/')
[ "def _isSubpathInPath(self, path, subpath):\n path = self._getAbsPath(path)\n subpath = self._getAbsPath(subpath)\n\n # If the parent path is the root directory ('/') or otherwise already\n # ends in a separator character, we need to strip the separator from\n # the end so we don't double it when we do the containment check.\n if path.endswith('/') or path.endswith('\\\\'):\n path = path[:-1]\n\n # Check for identical paths, either with or without a trailing\n # directory separator.\n if (\n (subpath == path) or\n (subpath == path + '/') or (subpath == path + '\\\\')\n ):\n return False\n\n # Check for subpath containment. This should work on either Windows or\n # *nix systems.\n return (\n subpath.startswith(path + '\\\\') or subpath.startswith(path + '/')\n )", "def is_subpath(d1: str, d2: str) -> bool:\n real_d1 = os.path.realpath(d1) + os.path.sep\n real_d2 = os.path.realpath(os.path.join(real_d1, d2))\n return os.path.commonprefix([real_d1, real_d2 + os.path.sep]) == real_d1", "def check_path(path, curr_dir):\n if not os.path.isabs(path):\n path = os.path.join(curr_dir, path)\n\n return path", "def is_subpath_of_benchmark(path, benchmark):\n benchmark_path = os.path.join(benchmark_utils.BENCHMARKS_DIR, benchmark)\n common_path = os.path.commonpath([path, benchmark_path])\n return common_path == benchmark_path", "def test_trailing_slash_multi(self):\n path = utils.safe_join(\"base_url/\", \"path/to/\", \"somewhere/\")\n self.assertEqual(path, \"base_url/path/to/somewhere/\")", "def test_trailing_slash(self):\n path = utils.safe_join(\"base_url/\", \"path/to/somewhere/\")\n self.assertEqual(path, \"base_url/path/to/somewhere/\")", "def is_match_path(input_path, smb_share_details):\n input_path = input_path[:-1] if input_path[-1] == \"/\" else input_path\n if smb_share_details['path'] != input_path:\n return False\n return True", "def testSplitPath(self):\n path_spec = fake_path_spec.FakePathSpec(location='/')\n\n test_file_system = TestFileSystem(self._resolver_context, path_spec)\n\n expected_path_segments = ['test1', 'test2', 'test3']\n\n path_segments = test_file_system.SplitPath('/test1/test2/test3')\n self.assertEqual(path_segments, expected_path_segments)\n\n path_segments = test_file_system.SplitPath('/test1/test2/test3/')\n self.assertEqual(path_segments, expected_path_segments)\n\n path_segments = test_file_system.SplitPath('/test1///test2/test3')\n self.assertEqual(path_segments, expected_path_segments)", "def fix_path(path):\n correct_path = '/' + path if not path.startswith('/') else path\n correct_path = correct_path + '/' if not correct_path.endswith('/') else correct_path\n return correct_path", "def is_unc_path(path: Path):\n\n return PureWindowsPath(path).anchor.startswith(r\"\\\\\")", "def absPathAndVerify(path):\n absolutePath = absPath(path)\n if os.path.exists(absolutePath):\n return absolutePath\n else:\n print \"%s is not an absolute path that exists. Exiting controller.py.\" % absolutePath\n exit(3)", "def test_split_path(self):\n zope_root = self.root.getPhysicalRoot()\n self.assertEqual(\n split_path('publication/document', self.root),\n (['root', 'publication', 'document'], zope_root))\n self.assertEqual(\n split_path('/publication/document', self.root),\n (['publication', 'document'], zope_root))\n self.assertEqual(\n split_path('./../root/publication/document', self.root),\n (['root', 'publication', 'document'], zope_root))\n self.assertEqual(\n split_path('./document', self.root.publication),\n (['root', 'publication', 'document'], zope_root))\n self.assertEqual(\n split_path('.//document', self.root.publication, self.root),\n (['publication', 'document'], self.root))\n self.assertEqual(\n split_path('./.././publication/document',\n self.root.publication, self.root),\n (['publication', 'document'], self.root))", "def CheckPath(Path):\n\n NormalInput = \":\\\\\"\n ExitCall = \"e\"\n ExitCall01 = \"E\"\n\n if NormalInput not in Path and ExitCall not in Path and ExitCall01 not in Path:\n return False\n else:\n return True", "def test_is_subpath_of_benchmark():\n assert benchmark_dependencies.is_subpath_of_benchmark(\n BENCHMARK_YAML_PATH, OSS_FUZZ_BENCHMARK)\n assert not benchmark_dependencies.is_subpath_of_benchmark(\n STANDARD_BUILD_SH_PATH, OSS_FUZZ_BENCHMARK)", "def _clean_path(path, path_prefix=\"\"):\n if path != path_prefix + '/' and path.endswith('/'):\n return path[:-1]\n return path", "def testJoinPath(self):\n path_spec = fake_path_spec.FakePathSpec(location='/')\n\n test_file_system = TestFileSystem(self._resolver_context, path_spec)\n\n expected_path = '/test1/test2/test3'\n\n path = test_file_system.JoinPath(['test1', 'test2', 'test3'])\n self.assertEqual(path, expected_path)\n\n path = test_file_system.JoinPath(['/test1', 'test2//', 'test3/'])\n self.assertEqual(path, expected_path)\n\n path = test_file_system.JoinPath(['/test1/test2/', '/test3/'])\n self.assertEqual(path, expected_path)\n\n path = test_file_system.JoinPath(['/test1///test2', 'test3'])\n self.assertEqual(path, expected_path)", "def test_path_segment_expansion(self):\n self._test(\"3.2.6 Path Segment Expansion\")", "def validate_path(self, path: str) -> bool:\n pass", "def _is_path(s):\n if isinstance(s, string_types):\n return op.exists(s)\n else:\n return False" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The exercise knows when it was solved by a particular user.
def test_wasSolvedBy(self): store = Store() exercise = makeExercise(store=store) someUser = User(store=store, email="foo@example.com") self.assertFalse(exercise.wasSolvedBy(someUser)) exercise.solvedBy(someUser) self.assertTrue(exercise.wasSolvedBy(someUser)) someOtherUser = User(store=store, email="bar@example.com") self.assertFalse(exercise.wasSolvedBy(someOtherUser))
[ "def wasSolved(self):\n return self.exercise.wasSolvedBy(self.user)", "def is_solved_by(self, user):\n try:\n return user.student.solution_set.filter(task=self).count() == 1\n except ObjectDoesNotExist:\n # TODO: Handle properly\n return False", "def meet(self):\n\t\treturn \"Employees will meet in the Hackery at 12PM.\"", "def test_api_challenge_solves_user_ctftime():\n app = create_ctfd()\n with app.app_context(), freeze_time(\"2017-10-7\"):\n set_config(\n \"start\", \"1507089600\"\n ) # Wednesday, October 4, 2017 12:00:00 AM GMT-04:00 DST\n set_config(\n \"end\", \"1507262400\"\n ) # Friday, October 6, 2017 12:00:00 AM GMT-04:00 DST\n gen_challenge(app.db)\n register_user(app)\n client = login_as_user(app)\n r = client.get(\"/api/v1/challenges/1/solves\")\n assert r.status_code == 403\n destroy_ctfd(app)", "def who_can_work(day, time):\n\n employees = get_day_prefs(day)\n\n for empl in employees:\n hours_available = can_work(empl.prefs, time)\n\n # hours_available is either 0 or an amount of time they can work\n if hours_available:\n time2 = decimal_to_time(time_to_decimal(time) + hours_available)\n print(\"{0}, from {1} until {2}\".format(empl.name, time, time2))", "def trackEx(self, userexercise):\n exname = userexercise.exercise.name\n idx = self.exIndexTracked(exname)\n if idx is not None:\n self.tracked[idx].combine(userexercise)\n elif self.exIndexUntracked(exname) is None:\n self.tracked.append(userexercise)\n else:\n idx = self.exIndexUntracked(exname)\n uex = self.untracked[idx]\n del self.untracked[idx]\n uex.combine(userexercise)\n self.tracked.append(uex)", "def meet(self):\n\t\treturn \"Employees will meet in the Parking Lot at 11AM.\"", "def test_get_run_as_user(self):\n pass", "def test_user_tracked_times(self):\n pass", "async def usercurrent(self, ctx, user: discord.User):\n server = ctx.guild\n args = [now_date(), server.id, user.id]\n await self.queryAndPrint(ctx, server, GET_DATE_POINTS_QUERY, args)", "def get_exercise_status(course_code, username):\n\n\n ans = DatabaseConnector.get_values(\"SELECT S.username, S.total_score, S.req_score, C.course_name FROM \"\n \"status_exercise AS S, course AS C WHERE S.course_code = \\\"\" + course_code + \"\\\" \"\n \"and S.course_code = C.course_code AND S.username = \\\"\" + username + \"\\\" GROUP BY \"\n \"S.username ;\")\n try:\n score = str(ans[0][1])\n course_name = ans[0][3]\n required = str(ans[0][2])\n if required == \"None\":\n return \"You have done \" + score + \" exercises in \" + course_code + \" \" + course_name + \".\"\n else:\n return \"You have done \" + score + \" out of \" + required + \" required exercises in \" + course_code + \" \" + course_name + \".\"\n except:\n return \"Sorry, I could not get the exercise status.\"", "def test_api_challenge_solves_user_visibility():\n app = create_ctfd()\n with app.app_context(), freeze_time(\"2017-10-5\"):\n set_config(\n \"start\", \"1507089600\"\n ) # Wednesday, October 4, 2017 12:00:00 AM GMT-04:00 DST\n set_config(\n \"end\", \"1507262400\"\n ) # Friday, October 6, 2017 12:00:00 AM GMT-04:00 DST\n gen_challenge(app.db)\n register_user(app)\n client = login_as_user(app)\n r = client.get(\"/api/v1/challenges/1/solves\")\n assert r.status_code == 200\n set_config(\"challenge_visibility\", \"public\")\n r = client.get(\"/api/v1/challenges/1/solves\")\n assert r.status_code == 200\n destroy_ctfd(app)", "def test_user_current_tracked_times(self):\n pass", "def show_exercise(name_of_person):\n f = open((name_of_person + \"_exercise.txt\"), \"r\")\n print(f.read())\n f.close()", "def get_days_until_first_exam(username):\n\n course_list = get_course_codes_list(username)\n\n if len(course_list) == 0:\n return \"Sorry, i cannot find the number of days until your exam.\"\n\n dates = []\n\n for course_code in course_list:\n ans = DatabaseConnector.get_values(\"SELECT exam_date, course_name FROM course WHERE \"\n \"course.course_code = \\\"\" + course_code[\n 0] + \"\\\" AND exam_date > Date('now');\")\n\n try:\n date = ans[0][0]\n course_name = ans[0][1]\n except:\n continue\n\n if date == \"null\" or course_name == \"null\":\n continue\n else:\n time1 = time.strptime(date, \"%Y-%m-%d\")\n dates.append((time1, course_name))\n\n closestDate = sorted(dates, key=lambda tup: tup[0])\n\n from time import mktime\n from datetime import datetime\n\n dt = datetime.fromtimestamp(mktime(closestDate[0][0]))\n\n days_to_exam = (dt - datetime.now())\n\n return \"There is \" + str(days_to_exam.days) + \" days to your first exam in \" + closestDate[0][1]", "def _compute_is_user_working(self):\n for order in self:\n if order.task_timer:\n order.is_user_working = True\n else:\n order.is_user_working = False", "def Upd_non_hourly_task(user_id, habit_id):\n #Need to add database to track users info before writing this code\n #also need to add keeping track of user_id everywhere I grab username\n return True", "def main():\n aoc_day = 5\n exercise_input = get_exercise_input_from_file(aoc_day)\n part_one, part_two = solution_part_one(exercise_input)\n print(\"Advent of Code part one:\", part_one)\n print(\"Advent of Code part two:\", solution_part_two(part_two))", "def Mark(self, user, title_or_id):\n uid = user['id']\n name = user['first_name']\n #Add user if unknown\n if uid not in self.users:\n self.users[uid] = {}\n self.userNameMap[uid] = name\n if title_or_id not in self.problems:\n raise Exception('Problem does not exist')\n\n #mark as done for that user, by id\n p = self.problems[title_or_id]\n self.users[uid][p.id] = 'done' #this can be extended to other states" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The current exercise has been marked as sovled by the current user.
def wasSolved(self): return self.exercise.wasSolvedBy(self.user)
[ "def trackEx(self, userexercise):\n exname = userexercise.exercise.name\n idx = self.exIndexTracked(exname)\n if idx is not None:\n self.tracked[idx].combine(userexercise)\n elif self.exIndexUntracked(exname) is None:\n self.tracked.append(userexercise)\n else:\n idx = self.exIndexUntracked(exname)\n uex = self.untracked[idx]\n del self.untracked[idx]\n uex.combine(userexercise)\n self.tracked.append(uex)", "def is_solved_by(self, user):\n try:\n return user.student.solution_set.filter(task=self).count() == 1\n except ObjectDoesNotExist:\n # TODO: Handle properly\n return False", "def verify_problem_answer(self, answer: models.ProblemAnswer):", "def test_wasSolvedBy(self):\n store = Store()\n exercise = makeExercise(store=store)\n\n someUser = User(store=store, email=\"foo@example.com\")\n self.assertFalse(exercise.wasSolvedBy(someUser))\n\n exercise.solvedBy(someUser)\n self.assertTrue(exercise.wasSolvedBy(someUser))\n\n someOtherUser = User(store=store, email=\"bar@example.com\")\n self.assertFalse(exercise.wasSolvedBy(someOtherUser))", "def correcting(self):\n self.current = State.CORRECTING", "def test_teacher_exclude_a_question_from_already_worked_assign_14702(self):\n self.ps.test_updates['name'] = 't2.11.009' \\\n + inspect.currentframe().f_code.co_name[4:]\n self.ps.test_updates['tags'] = [\n 't2',\n 't2.11',\n 't2.11.009',\n '14702'\n ]\n self.ps.test_updates['passed'] = False\n\n # Test steps and verification assertions\n raise NotImplementedError(inspect.currentframe().f_code.co_name)\n\n self.ps.test_updates['passed'] = True", "def solved(self, update, context):\n\t SOLVED_PARAM_COUNT = 0\n\t usageMessage = \"usage: /solved\"\n\t solvedProblems = self.problemsLog.get_solved_problems()\n\t # problems descriptions are appended here later\n\t text = \"\"\n\n\t if len(context.args) != SOLVED_PARAM_COUNT:\n\t if len(context.args) > SOLVED_PARAM_COUNT:\n\t text = \"Please don't add anyting to the command\\n\" + usageMessage\n\t context.bot.send_message(chat_id=update.effective_chat.id, text=text)\n\n\t return False\n\t \n\t if len(solvedProblems) == 0:\n\t text = \"No solved problems to show\"\n\t context.bot.send_message(chat_id=update.effective_chat.id, text=text)\n\n\t return True\n\n\t for problem in solvedProblems:\n\t solveDate = problem.get_date_solved()\n\t if solveDate != date.today():\n\t text = \"{0}\\nID {1}: {2} [closed on {3}]\".format(text, problem.id, problem.description, solveDate)\n\t else:\n\t text = \"{0}\\nID {1}: {2} [closed today]\".format(text, problem.id, problem.description, solveDate)\n\t context.bot.send_message(chat_id=update.effective_chat.id, text=text)\n\n\t return True", "def sov(self) -> bool:\n return self._sov", "def confirmed(self) -> int:\n pass", "def suggest_exercise(training_id):\n\n weights_exercises = ('Weighted Pull-Ups', 'Bench Press', 'Deadlifts', 'Core')\n fingerboarding_exercises = ('Max hangs', 'Repeaters', 'Density Hangs', 'Injury Prevention')\n bouldering_exercises = ('4x4', 'Limit Bouldering', 'Skills Session', 'Open Session')\n sport_exercises = ('Redpointing', 'Onsighting', '4x4', 'Open Session')\n exercises = [weights_exercises, fingerboarding_exercises, bouldering_exercises, sport_exercises]\n\n # Ask user what exercise they want to do within a given training type\n print(f\"For {training_types[training_id]} what exercise do you want to log:\")\n\n for i in range(len(exercises[training_id])):\n print(f\"[{i + 1}] {exercises[training_id][i]}\")\n\n exercise_id = input(\"Please enter a number:\")\n\n while exercise_id not in '1234':\n exercise_id = input(\"Please enter a value between 1-4:\")\n print('')\n\n log_exercise(training_types[training_id], exercises[training_id][int(exercise_id) - 1])", "def test_change_an_unopened_homework_314(self):\n self.ps.test_updates['name'] = 't1.14.034' \\\n + inspect.currentframe().f_code.co_name[\n 4:]\n self.ps.test_updates['tags'] = ['t1', 't1.14', 't1.14.034', '8025']\n self.ps.test_updates['passed'] = False\n\n # Test steps and verification assertions\n assignment_name = 'hw_014_%s' % randint(100, 999)\n assignment = Assignment()\n today = datetime.date.today()\n start = randint(1, 3)\n finish = start + randint(1, 5)\n begin = (today + datetime.timedelta(days=start)) \\\n .strftime('%m/%d/%Y')\n end = (today + datetime.timedelta(days=finish)) \\\n .strftime('%m/%d/%Y')\n\n # Create a draft homework\n self.teacher.add_assignment(\n assignment='homework',\n args={\n 'title': assignment_name,\n 'description': 'description',\n 'periods': {'all': (begin, end)},\n 'problems': {'1.1': 'all', },\n # 'problems': {'1.1': (2, 3), },\n # if there are too few problems selected, then removing\n # a problem in a later step will leave it with no problems\n # and thus unable to publish\n 'status': 'publish',\n 'feedback': 'immediate',\n }\n )\n\n # Locate the draft homework\n try:\n self.teacher.wait.until(\n expect.presence_of_element_located(\n (By.XPATH, '//div[@class=\"month-wrapper\"]')\n )\n )\n self.teacher.find(\n By.XPATH,\n '//label[contains(text(),\"{0}\")]'.format(assignment_name)\n ).click()\n except NoSuchElementException:\n self.teacher.find(\n By.XPATH,\n '//a[contains(@class,\"header-control next\")]'\n ).click()\n self.teacher.wait.until(\n expect.presence_of_element_located(\n (By.XPATH, '//div[@class=\"month-wrapper\"]')\n )\n )\n self.teacher.find(\n By.XPATH,\n '//label[contains(text(),\"{0}\")]'.format(assignment_name)\n ).click()\n # self.teacher.find(By.ID, 'edit-assignment-button').click()\n Metrics_Button = self.teacher.driver.find_element(\n By.XPATH, '//a[contains(., \"Metrics\")]')\n actions = ActionChains(self.teacher.driver)\n actions.move_to_element(Metrics_Button)\n actions.move_by_offset(100, 0)\n actions.click()\n actions.perform()\n sleep(1)\n\n # Change the title\n self.teacher.wait.until(\n expect.element_to_be_clickable(\n (By.ID, 'reading-title')\n )\n ).send_keys('new')\n\n # Change the description\n self.teacher.find(\n By.XPATH,\n '//div[contains(@class,\"assignment-description\")]' +\n '//textarea[contains(@class,\"form-control\")]'\n ).send_keys('new')\n\n # set new due dates\n today = datetime.date.today()\n start = randint(1, 3)\n end = start + randint(1, 6)\n opens_on = (today + datetime.timedelta(days=1)) \\\n .strftime('%m/%d/%Y')\n closes_on = (today + datetime.timedelta(days=end)) \\\n .strftime('%m/%d/%Y')\n assignment.assign_periods(\n self.teacher.driver,\n {'all': (opens_on, closes_on)}\n )\n sleep(3)\n\n # Change show feedback\n feedback = self.teacher.find(By.ID, 'feedback-select')\n Assignment.scroll_to(self.teacher.driver, feedback)\n feedback.click()\n self.teacher.find(\n By.XPATH, '//option[@value=\"due_at\"]'\n ).click()\n '''\n actions = ActionChains(self.teacher.driver)\n actions.move_by_offset(0, -10)\n actions.click()\n actions.perform()\n '''\n\n # Remove problems from the assignment\n self.teacher.find(\n By.XPATH, \"//button[contains(@class,'-remove-exercise')]\"\n ).click()\n self.teacher.find(\n By.XPATH, '//button[text()=\"Remove\"]'\n ).click()\n sleep(3)\n\n # Publish\n '''\n self.teacher.find(\n By.XPATH,\n # '//a[contains(@id,\"save-button\")]'\n '//button[contains(@class,\"-publish\")]'\n ).click()\n '''\n publish_button = self.teacher.find(\n By.XPATH,\n '//button[contains(@class,\"-publish\")]')\n Assignment.scroll_to(self.teacher.driver, publish_button)\n publish_button.click()\n\n try:\n self.teacher.find(\n By.XPATH,\n '//label[contains(text(),\"{0}\")]'.format(\n assignment_name + 'new')\n )\n except NoSuchElementException:\n self.teacher.find(\n By.XPATH,\n '//a[contains(@class,\"header-control next\")]'\n ).click()\n self.teacher.find(\n By.XPATH,\n '//label[contains(text(),\"{0}\")]'.format(\n assignment_name + 'new')\n )\n self.ps.test_updates['passed'] = True", "def is_solved(self):\n if self.revealed_puzzle.count(\"_\") > 0:\n return False\n return True", "def mark_due(self):\n # TODO: Notify reviewer who pays.\n pass", "def mark_inspection(self, did_pass):\n\n self.passed_inspection = did_pass", "def test_student_report_errata_about_assessments_in_tutor_14700(self):\n self.ps.test_updates['name'] = 't2.11.008' \\\n + inspect.currentframe().f_code.co_name[4:]\n self.ps.test_updates['tags'] = [\n 't2',\n 't2.11',\n 't2.11.008',\n '14700'\n ]\n self.ps.test_updates['passed'] = False\n\n # Test steps and verification assertions\n self.student.login()\n self.student.select_course(appearance='physics')\n self.student.sleep(5)\n\n # Find a homework from past work\n self.student.find(\n By.XPATH, \"//ul[@class='nav nav-tabs']/li[2]/a\").click()\n self.student.find(\n By.XPATH,\n \"//div[@class='-weeks-events panel panel-default']/div[@class\" +\n \"='panel-body']/div[@class='task row homework workable']\").click()\n self.student.sleep(3)\n\n # Go to the errata form\n self.student.driver.execute_script(\"window.scrollTo(0, 0);\")\n self.student.driver.execute_script(\n \"window.scrollTo(0, document.body.scrollHeight);\")\n self.student.find(\n By.XPATH, \"//span[@class='exercise-identifier-link']/a\").click()\n self.student.sleep(3)\n self.student.driver.switch_to_window(\n self.student.driver.window_handles[-1])\n\n assert('docs.google' in self.student.current_url()), \\\n 'Not viewing the errata page'\n\n self.ps.test_updates['passed'] = True", "def finish_exercise(self, winner_id):\n pass", "def test_teacher_specify_whether_context_is_required_for_quest_14721(self):\n self.ps.test_updates['name'] = 't2.11.027' \\\n + inspect.currentframe().f_code.co_name[4:]\n self.ps.test_updates['tags'] = [\n 't2',\n 't2.11',\n 't2.11.027',\n '14721'\n ]\n self.ps.test_updates['passed'] = False\n\n # Test steps and verification assertions\n self.teacher.login()\n self.teacher.sleep(2)\n self.teacher.driver.get(\"https://exercises-qa.openstax.org/\")\n self.teacher.sleep(2)\n self.teacher.find(By.PARTIAL_LINK_TEXT, \"SIGN IN\").click()\n self.teacher.sleep(2)\n self.teacher.find(By.PARTIAL_LINK_TEXT, \"WRITE A NEW EXERCISE\").click()\n self.teacher.sleep(5)\n\n # Switch to Tags tab and check Requires Context\n self.teacher.find(\n By.XPATH, \"//ul[@class='nav nav-tabs']/li[2]/a\").click()\n self.teacher.sleep(1)\n self.teacher.find(By.XPATH, \"//div[@class='tag']/input\").click()\n self.teacher.sleep(3)\n\n if self.teacher.find(\n By.XPATH, \"//div[@class='tag']/input\"\n ).is_selected():\n self.ps.test_updates['passed'] = True", "def test_getUnsolvedExerciseDetails(self):\n details = self.locator.getExerciseDetails(identifier=b\"2\")\n self.assertEqual(details, {\n b\"identifier\": \"2\",\n b\"title\": u\"Exercise 2\",\n b\"description\": u\"\\N{CLOUD}\",\n b\"solved\": False\n })", "def satisfied(self, what, inquiry=None):\n pass" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A user can get previously solved exercises.
def test_getSolvedExercises(self): response = self.locator.getExercises(solved=True) exercises = list(response["exercises"]) exercises.sort(key=lambda d: d["identifier"]) self.assertEqual(exercises, [ {b"title": u"Exercise 1", b"identifier": b"1"}, ])
[ "def test_load_manage_exercises(self):\n resp = self.client.get('/networking/Fall2012/problemsets/P2/manage_exercise', HTTP_USER_AGENT=self.userAgent)\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(len(resp.context['exercises']), 2)", "def exercises_from_workout(workout_id):\n\n exercises_from_workout = Workout_exercise.query.filter(Workout_exercise.workout_id == workout_id).all()\n \n return exercises_from_workout", "def test_get_exercises(self):\n print('(' + self.test_get_exercises.__name__ + ')', self.test_get_exercises.__doc__)\n resp = self.client.get(flask.url_for('exercises'))\n self.assertEqual(200, resp.status_code)\n self.assertEqual(resources.MASON + ';' + resources.EXERCISE_PROFILE, resp.headers.get(CONTENT_TYPE))\n data = json.loads(resp.data.decode('utf-8'))\n self.assertDictEqual(data, GOT_EXERCISES)", "def get_exercise(request, kind):\n ex = get_class(kind)\n if request.method == 'GET':\n exercise = ex.random()\n serializer_class = get_class(kind, 'Serializer')\n serializer = serializer_class(exercise)\n return JsonResponse(serializer.data)\n\n elif request.method == 'POST':\n ex_id = request.COOKIES.get('id')\n body = json.loads(request.body.decode(\"utf-8\").replace(\"'\", '\"'))\n database = get_object_or_404(ex, id=ex_id)\n db_czech = database.czech[2:-2].split(\"', '\")\n status = body['answer'] in db_czech\n return JsonResponse({'status': status, 'correct_answer': db_czech})", "def add_exercise(dte):\n\n selected_date = dte[:2] + \"/\" + dte[2:4] + \"/\" + dte[4:]\n tablename = \"workouts_\" + selected_date\n\n # get all exercises that exist in database\n exercises = db.execute(\"SELECT name FROM exercises ORDER BY name\")\n exercises = [elem['name'] for elem in exercises]\n\n if request.method == \"GET\":\n return render_template(\"add_exercise.html\", date=selected_date, dte=dte, exercises=exercises)\n\n else:\n\n exercise_name = request.form.get(\"exercise_select\")\n sets = request.form.get(\"sets\")\n reps = request.form.get(\"reps\")\n\n # get the id of the exercise\n exercise_id = db.execute(\"SELECT id FROM exercises WHERE name=:name\", name=exercise_name)[0]['id']\n\n # insert exercise into table of workouts for current date\n db.execute(\"INSERT INTO :tablename (user_id,exercise_id,sets,reps) VALUES (:user_id,:exercise_id,:sets,:reps);\", tablename=tablename,\n user_id=session[\"user_id\"], exercise_id=exercise_id, sets=sets, reps=reps)\n\n # get new workout\n workout = db.execute(\"SELECT * FROM :name WHERE user_id=:user_id\", name=tablename, user_id=session[\"user_id\"])\n for elem in workout:\n # get the name of the exercise with exercise_id\n exercise_name = db.execute(\"SELECT name FROM exercises WHERE id=:exercise_id;\", exercise_id=elem[\"exercise_id\"])[0][\"name\"]\n elem[\"exercise_name\"] = exercise_name\n\n return render_template(\"index.html\", workout=workout, date=selected_date, date2=dte)", "def suggest_exercise(training_id):\n\n weights_exercises = ('Weighted Pull-Ups', 'Bench Press', 'Deadlifts', 'Core')\n fingerboarding_exercises = ('Max hangs', 'Repeaters', 'Density Hangs', 'Injury Prevention')\n bouldering_exercises = ('4x4', 'Limit Bouldering', 'Skills Session', 'Open Session')\n sport_exercises = ('Redpointing', 'Onsighting', '4x4', 'Open Session')\n exercises = [weights_exercises, fingerboarding_exercises, bouldering_exercises, sport_exercises]\n\n # Ask user what exercise they want to do within a given training type\n print(f\"For {training_types[training_id]} what exercise do you want to log:\")\n\n for i in range(len(exercises[training_id])):\n print(f\"[{i + 1}] {exercises[training_id][i]}\")\n\n exercise_id = input(\"Please enter a number:\")\n\n while exercise_id not in '1234':\n exercise_id = input(\"Please enter a value between 1-4:\")\n print('')\n\n log_exercise(training_types[training_id], exercises[training_id][int(exercise_id) - 1])", "def _get_equipped_exercise(self, exercises: Dict[str, Equipment]) -> str:\n return self._get_equipped_exercises(exercises)[0]", "def wasSolved(self):\n return self.exercise.wasSolvedBy(self.user)", "def generate_exercise_ind():\r\n global num_exercises\r\n num_exercises += 1\r\n return num_exercises - 1", "def get(self, exerciseid):\n # check if exercise exists\n exercise_db = g.con.get_exercise(exerciseid)\n if not exercise_db:\n return missing_exercise_response(exerciseid)\n\n # fetch the query list-moves\n proposed_solution = request.args.get('solution')\n\n # check if the query is valid for the board\n if not _check_chess_data(exercise_db['initial_state'], proposed_solution, False):\n return BAD_SOLUTION_QUERY\n\n # compare query with real solution\n result = _compare_exercise_solution(exercise_db['list_moves'], proposed_solution)\n\n # create and return the envelope object\n envelope = ChessApiObject(api.url_for(Solver, exerciseid=exerciseid), EXERCISE_PROFILE)\n envelope.add_control('up', api.url_for(Exercise, exerciseid=exerciseid))\n envelope['value'] = result[0]\n envelope['opponent-move'] = result[1] if len(result) > 1 else None\n return Response(json.dumps(envelope), 200, mimetype=MASON+';'+EXERCISE_PROFILE)", "def test_wasSolvedBy(self):\n store = Store()\n exercise = makeExercise(store=store)\n\n someUser = User(store=store, email=\"foo@example.com\")\n self.assertFalse(exercise.wasSolvedBy(someUser))\n\n exercise.solvedBy(someUser)\n self.assertTrue(exercise.wasSolvedBy(someUser))\n\n someOtherUser = User(store=store, email=\"bar@example.com\")\n self.assertFalse(exercise.wasSolvedBy(someOtherUser))", "def _get_equipped_exercises(self, exercises: Dict[str, Equipment]) -> List[str]:\n equipped_exercises = []\n\n for ex, eq in exercises.items():\n if eq is None and not self._equipment_only:\n equipped_exercises.append(ex)\n continue\n if self._equipment:\n if Equipment.dumbbells in self._equipment and eq == Equipment.dumbbells:\n equipped_exercises.append(ex)\n elif Equipment.kettle_bell in self._equipment and eq == Equipment.kettle_bell:\n equipped_exercises.append(ex)\n elif Equipment.trx in self._equipment and eq == Equipment.trx:\n equipped_exercises.append(ex)\n elif Equipment.jump_rope in self._equipment and eq == Equipment.jump_rope:\n equipped_exercises.append(ex)\n\n random.shuffle(equipped_exercises)\n return equipped_exercises", "def view_question(request):\n if authenticated_userid(request) == None or 'user' not in request.session.keys():\n return HTTPFound(location='/')\n main = get_renderer('templates/master.pt').implementation()\n ###load the question number and test id###\n test_id = int(request.GET[\"id\"])\n quesiton_num = 1\n try:\n question_num = int(request.GET[\"question\"])\n except:\n question_num = 1\n\n ###load the test and it's questions and their answers from the database###\n dbsession = DBSession()\n test = dbsession.query(Test).filter(Test.id==test_id).first()\n if attempts_remaining(dbsession, test.id, request.session['user']['name']) <= 0:\n return HTTPFound(location='/') #if no more attempts left\n if (test.start_time - datetime.datetime.now()) > (datetime.timedelta(0)):\n return HTTPFound(location='/') #if it's too early to take\n if (test.end_time - datetime.datetime.now()) < (datetime.timedelta(0)):\n return HTTPFound(location='/') #if it's too late to take\n all_questions = dbsession.query(Question).filter(\n Question.test_id==test.id).all()\n total_questions = len(all_questions)\n for q in all_questions:\n \n if q.question_num == question_num:\n question = q\n\n ###create \"current_test\" in the session object###\n session = request.session\n user_choice = ''\n if \"current_test\" not in session.keys() or (\n session[\"current_test\"][\"name\"] != test.name):\n session[\"current_test\"] = {\"name\": test.name}\n\n ###load any previously selected answer to this question###\n if str(question_num) in session['current_test'].keys():\n user_choice = session['current_test'][str(question_num)]\n\n ###check if a question was submited and put the answer in the session###\n post = request.POST\n if 'review test' in post or 'next question' in post:\n controls = post.items()\n answer = \"na\"\n i = 0\n if question.question_type == \"shortAnswer\":\n for control in controls:\n if control[0] == 'answer':\n answer = str(control[1])\n if question.question_type == \"multipleChoice\":\n for control in controls:\n if control[0] == 'deformField1':\n answer = str(control[1])\n if question.question_type == \"selectTrue\":\n answer = []\n for control in controls:\n if control[0] == 'checkbox':\n answer.append(control[1])\n session[\"current_test\"][str(question_num)]=answer \n #store selected answer\n if 'next question' in post:\n return HTTPFound(location='/question?id='+str(test.id)+\n ';question='+str(question_num+1))\n if 'review test' in post: #check if it was the last question\n #if so redirect to the test's submit page\n return HTTPFound(location='/test?id='+str(test.id))\n\n ###create the question's form###\n if question.question_type == \"multipleChoice\":\n schema = create_multiple_choice_form(question, \n dbsession, user_choice)\n if question.question_type == \"selectTrue\":\n schema = create_select_all_form(question,\n dbsession, user_choice)\n if question.question_type == \"shortAnswer\":\n schema = create_short_answer_form(question, \n dbsession, user_choice)\n if question_num == total_questions: #check if this is the last question\n form = deform.Form(schema[0],\n buttons=('review test',))\n else:\n form = deform.Form(schema[0],\n buttons=('next question',))\n if question.question_type == \"shortAnswer\":\n return {\"test\":test,'form':form.render(schema[1]),\n 'link':'/test?id='+str(test.id), 'main': main} #if it's a short answer question (returns default value)\n return {\"test\":test,'form':form.render(), 'link':'/test?id='+str(test.id), 'main': main}", "def get_exercises_left(course_code, username):\n\n ans = DatabaseConnector.get_values(\"SELECT S.username, S.total_score, S.req_score, C.course_name FROM \"\n \"status_exercise AS S, course AS C WHERE S.course_code = \\\"\" + course_code + \"\\\" \"\n \"and S.course_code = C.course_code AND S.username = \\\"\" + username + \"\\\" GROUP BY \"\n \"S.username ;\")\n\n try:\n score = str(ans[0][1])\n course_name = ans[0][3]\n required = str(ans[0][2])\n\n if required == \"None\":\n left = str(8 - int(score))\n else:\n left = str(required - int(score))\n\n if int(left) >= 0:\n return \"You have \" + left + \" exercises left in \" + course_code + \" \" + course_name + \".\"\n else:\n return \"You don't have any exercises left in \" + course_code + \" \" + course_name + \".\"\n\n except:\n return \"You haven't done any exercises in this course yet.\"", "def show_exercise(name_of_person):\n f = open((name_of_person + \"_exercise.txt\"), \"r\")\n print(f.read())\n f.close()", "def get(self):\n # create envelope and add controls to it\n envelope = ChessApiObject(api.url_for(Exercises), EXERCISE_PROFILE)\n envelope.add_add_exercise_control()\n envelope.add_users_all_control()\n\n # get the list of exercises from the database and add them to the envelope - with a minimal format\n exercises_from_db = g.con.get_exercises()\n items = _create_exercise_items_list(exercises_from_db)\n\n envelope['items'] = items\n return Response(json.dumps(envelope), 200, mimetype=MASON + ';' + EXERCISE_PROFILE)", "def test_get_solver(self):\n print('(' + self.test_get_solver.__name__ + ')', self.test_get_solver.__doc__)\n exercise_id = 1\n resp = self.client.get(resources.api.url_for(resources.Solver, exerciseid=exercise_id) +\n '?solution='+urllib.parse.quote_plus(OTHER_FOOLS_MATE_MOVES))\n self.assertEqual(200, resp.status_code)\n self.assertDictEqual(GOT_SOLVER, json.loads(resp.data.decode('utf-8')))", "def trackEx(self, userexercise):\n exname = userexercise.exercise.name\n idx = self.exIndexTracked(exname)\n if idx is not None:\n self.tracked[idx].combine(userexercise)\n elif self.exIndexUntracked(exname) is None:\n self.tracked.append(userexercise)\n else:\n idx = self.exIndexUntracked(exname)\n uex = self.untracked[idx]\n del self.untracked[idx]\n uex.combine(userexercise)\n self.tracked.append(uex)", "def test_getSolvedExerciseDetails(self):\n details = self.locator.getExerciseDetails(identifier=b\"1\")\n self.assertEqual(details, {\n b\"identifier\": b\"1\",\n b\"title\": u\"Exercise 1\",\n b\"description\": u\"\\N{CLOUD}\",\n b\"solved\": True\n })" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A user can get details about a solved exercise.
def test_getSolvedExerciseDetails(self): details = self.locator.getExerciseDetails(identifier=b"1") self.assertEqual(details, { b"identifier": b"1", b"title": u"Exercise 1", b"description": u"\N{CLOUD}", b"solved": True })
[ "def show_exercise(name_of_person):\n f = open((name_of_person + \"_exercise.txt\"), \"r\")\n print(f.read())\n f.close()", "def test_getUnsolvedExerciseDetails(self):\n details = self.locator.getExerciseDetails(identifier=b\"2\")\n self.assertEqual(details, {\n b\"identifier\": \"2\",\n b\"title\": u\"Exercise 2\",\n b\"description\": u\"\\N{CLOUD}\",\n b\"solved\": False\n })", "def exam_info(request, exam_id):\n\n exam = get_object_or_404(Exam, pk=exam_id)\n tasks = exam.task_set.all().prefetch_related('scenario_set')\n return render(request, 'frontend/exams/exam.html', {\n 'exam': exam,\n 'tasks': tasks\n })", "def test_getSolvedExercises(self):\n response = self.locator.getExercises(solved=True)\n exercises = list(response[\"exercises\"])\n exercises.sort(key=lambda d: d[\"identifier\"])\n self.assertEqual(exercises, [\n {b\"title\": u\"Exercise 1\", b\"identifier\": b\"1\"},\n ])", "def get_exercise(request, kind):\n ex = get_class(kind)\n if request.method == 'GET':\n exercise = ex.random()\n serializer_class = get_class(kind, 'Serializer')\n serializer = serializer_class(exercise)\n return JsonResponse(serializer.data)\n\n elif request.method == 'POST':\n ex_id = request.COOKIES.get('id')\n body = json.loads(request.body.decode(\"utf-8\").replace(\"'\", '\"'))\n database = get_object_or_404(ex, id=ex_id)\n db_czech = database.czech[2:-2].split(\"', '\")\n status = body['answer'] in db_czech\n return JsonResponse({'status': status, 'correct_answer': db_czech})", "def test_load_manage_exercises(self):\n resp = self.client.get('/networking/Fall2012/problemsets/P2/manage_exercise', HTTP_USER_AGENT=self.userAgent)\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(len(resp.context['exercises']), 2)", "def test_get_exercises(self):\n print('(' + self.test_get_exercises.__name__ + ')', self.test_get_exercises.__doc__)\n resp = self.client.get(flask.url_for('exercises'))\n self.assertEqual(200, resp.status_code)\n self.assertEqual(resources.MASON + ';' + resources.EXERCISE_PROFILE, resp.headers.get(CONTENT_TYPE))\n data = json.loads(resp.data.decode('utf-8'))\n self.assertDictEqual(data, GOT_EXERCISES)", "def _get_equipped_exercise(self, exercises: Dict[str, Equipment]) -> str:\n return self._get_equipped_exercises(exercises)[0]", "def gather_exerciseresult(username, dbHandler, logger, exerciseResultID):\n\t\n\texerciseResult = {}\n\tif (exerciseResultID is None): \n\t\tlogger.debug(\"exerciseResultID=None\")\n\telse:\n\t\tdbMsg = json.loads(dbHandler.get_exerciseresult(username, exerciseResultID))\n\t\t#logger.debug(dbMsg)\n\t\tif dbMsg.get(\"status_code\") == \"200\":\n\t\t\texerciseResult = dbMsg.get(\"ExerciseResult\")[0]\n\t\telse:\n\t\t\tlogger.debug(\"for ID: \" + str(exerciseResultID) + \" - \" + str(dbMsg))\n\tlogger.debug(\"exerciseResult: \" + str(exerciseResult))\n\treturn exerciseResult", "def exercise_calculation(self, exercise):\n url = f'{self.url}/natural/exercise'\n params = {\n 'query': exercise,\n 'gender': self.gender,\n 'weight_kg': self.weight_kg,\n 'height_cm': self.height_cm,\n 'age': self.age\n }\n response = requests.post(url, headers=self.headers, json=params)\n exercise = response.json()\n data = {}\n for activity in exercise['exercises']:\n data['exercise'] = activity['name']\n data['duration'] = activity['duration_min']\n data['calories'] = activity['nf_calories']\n return data", "def get(self, exerciseid):\n # check if exercise exists\n exercise_db = g.con.get_exercise(exerciseid)\n if not exercise_db:\n return missing_exercise_response(exerciseid)\n\n # fetch the query list-moves\n proposed_solution = request.args.get('solution')\n\n # check if the query is valid for the board\n if not _check_chess_data(exercise_db['initial_state'], proposed_solution, False):\n return BAD_SOLUTION_QUERY\n\n # compare query with real solution\n result = _compare_exercise_solution(exercise_db['list_moves'], proposed_solution)\n\n # create and return the envelope object\n envelope = ChessApiObject(api.url_for(Solver, exerciseid=exerciseid), EXERCISE_PROFILE)\n envelope.add_control('up', api.url_for(Exercise, exerciseid=exerciseid))\n envelope['value'] = result[0]\n envelope['opponent-move'] = result[1] if len(result) > 1 else None\n return Response(json.dumps(envelope), 200, mimetype=MASON+';'+EXERCISE_PROFILE)", "def get_exercise_status(course_code, username):\n\n\n ans = DatabaseConnector.get_values(\"SELECT S.username, S.total_score, S.req_score, C.course_name FROM \"\n \"status_exercise AS S, course AS C WHERE S.course_code = \\\"\" + course_code + \"\\\" \"\n \"and S.course_code = C.course_code AND S.username = \\\"\" + username + \"\\\" GROUP BY \"\n \"S.username ;\")\n try:\n score = str(ans[0][1])\n course_name = ans[0][3]\n required = str(ans[0][2])\n if required == \"None\":\n return \"You have done \" + score + \" exercises in \" + course_code + \" \" + course_name + \".\"\n else:\n return \"You have done \" + score + \" out of \" + required + \" required exercises in \" + course_code + \" \" + course_name + \".\"\n except:\n return \"Sorry, I could not get the exercise status.\"", "def add_exercise(dte):\n\n selected_date = dte[:2] + \"/\" + dte[2:4] + \"/\" + dte[4:]\n tablename = \"workouts_\" + selected_date\n\n # get all exercises that exist in database\n exercises = db.execute(\"SELECT name FROM exercises ORDER BY name\")\n exercises = [elem['name'] for elem in exercises]\n\n if request.method == \"GET\":\n return render_template(\"add_exercise.html\", date=selected_date, dte=dte, exercises=exercises)\n\n else:\n\n exercise_name = request.form.get(\"exercise_select\")\n sets = request.form.get(\"sets\")\n reps = request.form.get(\"reps\")\n\n # get the id of the exercise\n exercise_id = db.execute(\"SELECT id FROM exercises WHERE name=:name\", name=exercise_name)[0]['id']\n\n # insert exercise into table of workouts for current date\n db.execute(\"INSERT INTO :tablename (user_id,exercise_id,sets,reps) VALUES (:user_id,:exercise_id,:sets,:reps);\", tablename=tablename,\n user_id=session[\"user_id\"], exercise_id=exercise_id, sets=sets, reps=reps)\n\n # get new workout\n workout = db.execute(\"SELECT * FROM :name WHERE user_id=:user_id\", name=tablename, user_id=session[\"user_id\"])\n for elem in workout:\n # get the name of the exercise with exercise_id\n exercise_name = db.execute(\"SELECT name FROM exercises WHERE id=:exercise_id;\", exercise_id=elem[\"exercise_id\"])[0][\"name\"]\n elem[\"exercise_name\"] = exercise_name\n\n return render_template(\"index.html\", workout=workout, date=selected_date, date2=dte)", "def suggest_exercise(training_id):\n\n weights_exercises = ('Weighted Pull-Ups', 'Bench Press', 'Deadlifts', 'Core')\n fingerboarding_exercises = ('Max hangs', 'Repeaters', 'Density Hangs', 'Injury Prevention')\n bouldering_exercises = ('4x4', 'Limit Bouldering', 'Skills Session', 'Open Session')\n sport_exercises = ('Redpointing', 'Onsighting', '4x4', 'Open Session')\n exercises = [weights_exercises, fingerboarding_exercises, bouldering_exercises, sport_exercises]\n\n # Ask user what exercise they want to do within a given training type\n print(f\"For {training_types[training_id]} what exercise do you want to log:\")\n\n for i in range(len(exercises[training_id])):\n print(f\"[{i + 1}] {exercises[training_id][i]}\")\n\n exercise_id = input(\"Please enter a number:\")\n\n while exercise_id not in '1234':\n exercise_id = input(\"Please enter a value between 1-4:\")\n print('')\n\n log_exercise(training_types[training_id], exercises[training_id][int(exercise_id) - 1])", "def details(user, metric, sort, event_type, task, sha1, n, output):\n if not RepoManager.get().has_task(task):\n click.echo(\"no results for the specified task {}, use another task\".format(task))\n return\n\n event_type = EVENT_TYPES.get(event_type, None)\n if event_type is None:\n click.echo(\"we do not have results for the event type: {}\".format(event_type))\n return\n\n result_frame = RepoManager.get().experiment_details(user, metric, sort, task, event_type, sha1, n)\n if result_frame is not None:\n click.echo(result_frame)\n else:\n click.echo(\"no result found for this query\")\n if output is not None:\n result_frame.to_csv(os.path.expanduser(output), index=False)", "def test_get_problem_answer(self):\n\n problem_id = self.problem_id\n answer = self.api.get_problem_answer(problem_id)\n\n self.assertIsInstance(answer, models.ProblemAnswer)\n self.verify_problem_answer(answer)", "def exploreid(id):\r\n form = QuestionForm()\r\n furniture = get_Furniture(id)\r\n return render_template(\"exploresid.html\" , \r\n form = form, furniture = furniture,\r\n user=current_user)", "def exercises_from_workout(workout_id):\n\n exercises_from_workout = Workout_exercise.query.filter(Workout_exercise.workout_id == workout_id).all()\n \n return exercises_from_workout", "def test_get_solver(self):\n print('(' + self.test_get_solver.__name__ + ')', self.test_get_solver.__doc__)\n exercise_id = 1\n resp = self.client.get(resources.api.url_for(resources.Solver, exerciseid=exercise_id) +\n '?solution='+urllib.parse.quote_plus(OTHER_FOOLS_MATE_MOVES))\n self.assertEqual(200, resp.status_code)\n self.assertDictEqual(GOT_SOLVER, json.loads(resp.data.decode('utf-8')))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A user can get details about an unsolved exercise.
def test_getUnsolvedExerciseDetails(self): details = self.locator.getExerciseDetails(identifier=b"2") self.assertEqual(details, { b"identifier": "2", b"title": u"Exercise 2", b"description": u"\N{CLOUD}", b"solved": False })
[ "def test_getSolvedExerciseDetails(self):\n details = self.locator.getExerciseDetails(identifier=b\"1\")\n self.assertEqual(details, {\n b\"identifier\": b\"1\",\n b\"title\": u\"Exercise 1\",\n b\"description\": u\"\\N{CLOUD}\",\n b\"solved\": True\n })", "def test_missingExercise(self):\n self.assertRaises(UnknownExercise,\n self.locator.getExerciseDetails, identifier=\"BOGUS\")", "def test_getSolvedExercises(self):\n response = self.locator.getExercises(solved=True)\n exercises = list(response[\"exercises\"])\n exercises.sort(key=lambda d: d[\"identifier\"])\n self.assertEqual(exercises, [\n {b\"title\": u\"Exercise 1\", b\"identifier\": b\"1\"},\n ])", "def _get_equipped_exercise(self, exercises: Dict[str, Equipment]) -> str:\n return self._get_equipped_exercises(exercises)[0]", "def test_load_manage_exercises(self):\n resp = self.client.get('/networking/Fall2012/problemsets/P2/manage_exercise', HTTP_USER_AGENT=self.userAgent)\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(len(resp.context['exercises']), 2)", "def test_get_exercises(self):\n print('(' + self.test_get_exercises.__name__ + ')', self.test_get_exercises.__doc__)\n resp = self.client.get(flask.url_for('exercises'))\n self.assertEqual(200, resp.status_code)\n self.assertEqual(resources.MASON + ';' + resources.EXERCISE_PROFILE, resp.headers.get(CONTENT_TYPE))\n data = json.loads(resp.data.decode('utf-8'))\n self.assertDictEqual(data, GOT_EXERCISES)", "def get_exercise_status(course_code, username):\n\n\n ans = DatabaseConnector.get_values(\"SELECT S.username, S.total_score, S.req_score, C.course_name FROM \"\n \"status_exercise AS S, course AS C WHERE S.course_code = \\\"\" + course_code + \"\\\" \"\n \"and S.course_code = C.course_code AND S.username = \\\"\" + username + \"\\\" GROUP BY \"\n \"S.username ;\")\n try:\n score = str(ans[0][1])\n course_name = ans[0][3]\n required = str(ans[0][2])\n if required == \"None\":\n return \"You have done \" + score + \" exercises in \" + course_code + \" \" + course_name + \".\"\n else:\n return \"You have done \" + score + \" out of \" + required + \" required exercises in \" + course_code + \" \" + course_name + \".\"\n except:\n return \"Sorry, I could not get the exercise status.\"", "def show_exercise(name_of_person):\n f = open((name_of_person + \"_exercise.txt\"), \"r\")\n print(f.read())\n f.close()", "def exam_info(request, exam_id):\n\n exam = get_object_or_404(Exam, pk=exam_id)\n tasks = exam.task_set.all().prefetch_related('scenario_set')\n return render(request, 'frontend/exams/exam.html', {\n 'exam': exam,\n 'tasks': tasks\n })", "def get_exercise(request, kind):\n ex = get_class(kind)\n if request.method == 'GET':\n exercise = ex.random()\n serializer_class = get_class(kind, 'Serializer')\n serializer = serializer_class(exercise)\n return JsonResponse(serializer.data)\n\n elif request.method == 'POST':\n ex_id = request.COOKIES.get('id')\n body = json.loads(request.body.decode(\"utf-8\").replace(\"'\", '\"'))\n database = get_object_or_404(ex, id=ex_id)\n db_czech = database.czech[2:-2].split(\"', '\")\n status = body['answer'] in db_czech\n return JsonResponse({'status': status, 'correct_answer': db_czech})", "def wrong(request, task):\n ctx = {}\n ctx[\"task\"] = get_object_or_404(Task, pk=task)\n ctx[\"lesson\"] = ctx[\"task\"].section.lesson\n ctx[\"wrong\"] = [uot.wrong_answers.all() for uot in ctx[\"task\"].uots.all()]\n \n return render(request, \"stats/wrong.html\", ctx)", "def view_ungraded_tests(request):\n if 'user' not in request.session.keys() or 'teacher' not in request.session['user']['roles'] :\n return HTTPFound(location='/') \n main = get_renderer('templates/master.pt').implementation()\n if \"current_test\" in request.session.keys():\n request.session.pop('current_test')\n test_id = int(request.GET[\"id\"])\n dbsession = DBSession()\n test = dbsession.query(Test).filter(Test.id==test_id).first()\n taken_tests = dbsession.query(TakenTest).filter(TakenTest.test_id == test_id).all()\n ungraded_tests = []\n for taken_test in taken_tests:\n if taken_test.has_ungraded:\n ungraded_tests.append(taken_test)\n taken_test.url = \"grade_submitted_test?id=\"+str(taken_test.id)\n taken_test.link = \"grade test by \" + taken_test.student_name\n message = ''\n if len(ungraded_tests) == 0: message = 'There are no tests to grade'\n return {'test': test, 'taken_tests': ungraded_tests, 'message':message, 'main': main}", "def get(self, exerciseid):\n # check if exercise exists\n exercise_db = g.con.get_exercise(exerciseid)\n if not exercise_db:\n return missing_exercise_response(exerciseid)\n\n # fetch the query list-moves\n proposed_solution = request.args.get('solution')\n\n # check if the query is valid for the board\n if not _check_chess_data(exercise_db['initial_state'], proposed_solution, False):\n return BAD_SOLUTION_QUERY\n\n # compare query with real solution\n result = _compare_exercise_solution(exercise_db['list_moves'], proposed_solution)\n\n # create and return the envelope object\n envelope = ChessApiObject(api.url_for(Solver, exerciseid=exerciseid), EXERCISE_PROFILE)\n envelope.add_control('up', api.url_for(Exercise, exerciseid=exerciseid))\n envelope['value'] = result[0]\n envelope['opponent-move'] = result[1] if len(result) > 1 else None\n return Response(json.dumps(envelope), 200, mimetype=MASON+';'+EXERCISE_PROFILE)", "def gather_exerciseresult(username, dbHandler, logger, exerciseResultID):\n\t\n\texerciseResult = {}\n\tif (exerciseResultID is None): \n\t\tlogger.debug(\"exerciseResultID=None\")\n\telse:\n\t\tdbMsg = json.loads(dbHandler.get_exerciseresult(username, exerciseResultID))\n\t\t#logger.debug(dbMsg)\n\t\tif dbMsg.get(\"status_code\") == \"200\":\n\t\t\texerciseResult = dbMsg.get(\"ExerciseResult\")[0]\n\t\telse:\n\t\t\tlogger.debug(\"for ID: \" + str(exerciseResultID) + \" - \" + str(dbMsg))\n\tlogger.debug(\"exerciseResult: \" + str(exerciseResult))\n\treturn exerciseResult", "def add_exercise(dte):\n\n selected_date = dte[:2] + \"/\" + dte[2:4] + \"/\" + dte[4:]\n tablename = \"workouts_\" + selected_date\n\n # get all exercises that exist in database\n exercises = db.execute(\"SELECT name FROM exercises ORDER BY name\")\n exercises = [elem['name'] for elem in exercises]\n\n if request.method == \"GET\":\n return render_template(\"add_exercise.html\", date=selected_date, dte=dte, exercises=exercises)\n\n else:\n\n exercise_name = request.form.get(\"exercise_select\")\n sets = request.form.get(\"sets\")\n reps = request.form.get(\"reps\")\n\n # get the id of the exercise\n exercise_id = db.execute(\"SELECT id FROM exercises WHERE name=:name\", name=exercise_name)[0]['id']\n\n # insert exercise into table of workouts for current date\n db.execute(\"INSERT INTO :tablename (user_id,exercise_id,sets,reps) VALUES (:user_id,:exercise_id,:sets,:reps);\", tablename=tablename,\n user_id=session[\"user_id\"], exercise_id=exercise_id, sets=sets, reps=reps)\n\n # get new workout\n workout = db.execute(\"SELECT * FROM :name WHERE user_id=:user_id\", name=tablename, user_id=session[\"user_id\"])\n for elem in workout:\n # get the name of the exercise with exercise_id\n exercise_name = db.execute(\"SELECT name FROM exercises WHERE id=:exercise_id;\", exercise_id=elem[\"exercise_id\"])[0][\"name\"]\n elem[\"exercise_name\"] = exercise_name\n\n return render_template(\"index.html\", workout=workout, date=selected_date, date2=dte)", "def test_get_problem_answer(self):\n\n problem_id = self.problem_id\n answer = self.api.get_problem_answer(problem_id)\n\n self.assertIsInstance(answer, models.ProblemAnswer)\n self.verify_problem_answer(answer)", "def exercise_calculation(self, exercise):\n url = f'{self.url}/natural/exercise'\n params = {\n 'query': exercise,\n 'gender': self.gender,\n 'weight_kg': self.weight_kg,\n 'height_cm': self.height_cm,\n 'age': self.age\n }\n response = requests.post(url, headers=self.headers, json=params)\n exercise = response.json()\n data = {}\n for activity in exercise['exercises']:\n data['exercise'] = activity['name']\n data['duration'] = activity['duration_min']\n data['calories'] = activity['nf_calories']\n return data", "def _get_practice_exam_view(exam, context, exam_id, user_id, course_id):\n student_view_template = None\n\n attempt = get_exam_attempt(exam_id, user_id)\n\n attempt_status = attempt['status'] if attempt else None\n\n if not attempt_status:\n student_view_template = 'practice_exam/entrance.html'\n elif attempt_status == ProctoredExamStudentAttemptStatus.started:\n # when we're taking the exam we should not override the view\n return None\n elif attempt_status in [ProctoredExamStudentAttemptStatus.created,\n ProctoredExamStudentAttemptStatus.download_software_clicked]:\n provider = get_backend_provider()\n student_view_template = 'proctored_exam/instructions.html'\n context.update({\n 'exam_code': attempt['attempt_code'],\n 'software_download_url': provider.get_software_download_url(),\n })\n elif attempt_status == ProctoredExamStudentAttemptStatus.ready_to_start:\n student_view_template = 'proctored_exam/ready_to_start.html'\n elif attempt_status == ProctoredExamStudentAttemptStatus.error:\n student_view_template = 'practice_exam/error.html'\n elif attempt_status == ProctoredExamStudentAttemptStatus.submitted:\n student_view_template = 'practice_exam/submitted.html'\n elif attempt_status == ProctoredExamStudentAttemptStatus.ready_to_submit:\n student_view_template = 'proctored_exam/ready_to_submit.html'\n\n if student_view_template:\n template = loader.get_template(student_view_template)\n django_context = Context(context)\n django_context.update(_get_proctored_exam_context(exam, attempt, course_id, is_practice_exam=True))\n return template.render(django_context)", "def exercises_from_workout(workout_id):\n\n exercises_from_workout = Workout_exercise.query.filter(Workout_exercise.workout_id == workout_id).all()\n \n return exercises_from_workout" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When attempting to get details for an exercise that doesn't exist, an error is raised.
def test_missingExercise(self): self.assertRaises(UnknownExercise, self.locator.getExerciseDetails, identifier="BOGUS")
[ "def test_getSolvedExerciseDetails(self):\n details = self.locator.getExerciseDetails(identifier=b\"1\")\n self.assertEqual(details, {\n b\"identifier\": b\"1\",\n b\"title\": u\"Exercise 1\",\n b\"description\": u\"\\N{CLOUD}\",\n b\"solved\": True\n })", "def test_getUnsolvedExerciseDetails(self):\n details = self.locator.getExerciseDetails(identifier=b\"2\")\n self.assertEqual(details, {\n b\"identifier\": \"2\",\n b\"title\": u\"Exercise 2\",\n b\"description\": u\"\\N{CLOUD}\",\n b\"solved\": False\n })", "def test_get_exercises(self):\n print('(' + self.test_get_exercises.__name__ + ')', self.test_get_exercises.__doc__)\n resp = self.client.get(flask.url_for('exercises'))\n self.assertEqual(200, resp.status_code)\n self.assertEqual(resources.MASON + ';' + resources.EXERCISE_PROFILE, resp.headers.get(CONTENT_TYPE))\n data = json.loads(resp.data.decode('utf-8'))\n self.assertDictEqual(data, GOT_EXERCISES)", "def test_load_manage_exercises(self):\n resp = self.client.get('/networking/Fall2012/problemsets/P2/manage_exercise', HTTP_USER_AGENT=self.userAgent)\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(len(resp.context['exercises']), 2)", "def test_getSolvedExercises(self):\n response = self.locator.getExercises(solved=True)\n exercises = list(response[\"exercises\"])\n exercises.sort(key=lambda d: d[\"identifier\"])\n self.assertEqual(exercises, [\n {b\"title\": u\"Exercise 1\", b\"identifier\": b\"1\"},\n ])", "def test_missing_datasets_raise_errors():\n with pytest.raises(KeyError):\n eio.path_to_example(\"\")", "def _get_equipped_exercise(self, exercises: Dict[str, Equipment]) -> str:\n return self._get_equipped_exercises(exercises)[0]", "def test_delete_exercise(self):\n print('(' + self.test_delete_exercise.__name__ + ')', self.test_delete_exercise.__doc__)\n exercise_id = 1\n resp = self.client.delete(resources.api.url_for(resources.Exercise, exerciseid=exercise_id)\n + '?author_email=mystery%40mymail.com')\n self.assertEqual(204, resp.status_code)\n resp = self.client.get(resources.api.url_for(resources.Exercise, exerciseid=exercise_id))\n self._assertErrorMessage(resp, 404, 'Exercise does not exist')", "def show_exercise(name_of_person):\n f = open((name_of_person + \"_exercise.txt\"), \"r\")\n print(f.read())\n f.close()", "def test_get_nonexistent_task(self, client):\n\n nonexistent_id = '0e4fac17-f367-4807-8c28-8a059a2f82ac'\n url = f'http://127.0.0.1:8000/check/?id={nonexistent_id}'\n response = client.get(url)\n assert response.status_code == 404", "def test_get_a_non_existent_interest_fails(self):\n # setup: make test user organisation admin\n add_manager_to_organisation(self.test_organisation, self.test_user)\n response = self.client.get(\n self.non_existent_interest_url,\n headers={\"Authorization\": self.session_token},\n )\n response_body = response.get_json()\n error_details = response_body[\"error\"]\n self.assertEqual(response.status_code, 404)\n self.assertEqual(error_details[\"message\"], INTEREST_NOT_FOUND_MESSAGE)\n self.assertEqual(error_details[\"sub_code\"], INTEREST_NOT_FOUND_SUB_CODE)", "def test_detail_recipe_not_found(self):\n response = self.client.get('/recipes/99/')\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)", "def test_invalid_datasets_raise_errors():\n with pytest.raises(KeyError):\n eio.path_to_example(\"Non-existent dataset\")", "def test_cant_get_missing_fixture(collection):\n\n with pytest.raises(KeyError):\n collection.get(\"missing\")", "def suggest_exercise(training_id):\n\n weights_exercises = ('Weighted Pull-Ups', 'Bench Press', 'Deadlifts', 'Core')\n fingerboarding_exercises = ('Max hangs', 'Repeaters', 'Density Hangs', 'Injury Prevention')\n bouldering_exercises = ('4x4', 'Limit Bouldering', 'Skills Session', 'Open Session')\n sport_exercises = ('Redpointing', 'Onsighting', '4x4', 'Open Session')\n exercises = [weights_exercises, fingerboarding_exercises, bouldering_exercises, sport_exercises]\n\n # Ask user what exercise they want to do within a given training type\n print(f\"For {training_types[training_id]} what exercise do you want to log:\")\n\n for i in range(len(exercises[training_id])):\n print(f\"[{i + 1}] {exercises[training_id][i]}\")\n\n exercise_id = input(\"Please enter a number:\")\n\n while exercise_id not in '1234':\n exercise_id = input(\"Please enter a value between 1-4:\")\n print('')\n\n log_exercise(training_types[training_id], exercises[training_id][int(exercise_id) - 1])", "def test_get_current_collection_exercise_with_blank_collection_exercise(self):\n with open(\n f\"{project_root}/test_data/collection_exercise/single_new_collection_exercise_for_survey.json\"\n ) as json_data:\n collection_exercise_list = json.load(json_data)\n\n expected_output = {}\n output = get_current_collection_exercise(collection_exercise_list)\n self.assertEqual(output, expected_output)", "def test_get_episode_method_with_bad_input(self):\n show = Show(show_id=1)\n self.assertIsNone(show.get_episode('taco'))", "def gen_test_read_notfound():\n \n name = make_name(\"resource_impl_read_notfound\")\n doc = make_doc(\"Reading a %s resource that doesn't exist\" % impl_instance.iontype)\n add_test_method(name, doc, test_read_notfound_fun)", "def test_fail_get_single_question(self):\n with self.client:\n response = self.client.get(\n URL_PREFIX + 'questions/x',)\n data = json.loads(response.data.decode())\n self.assertTrue(data[\"error\"] == \"Only integers are required\")\n truncate_tables()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the user has no secret yet, gets a new secret. Asserts that the secret requests a sufficient number of bytes from urandom.
def test_new(self): self.patch(os, "urandom", self._urandom) self.assertEqual(self.store.query(Secret).count(), 0) secret = Secret.forUser(self.user) self.assertEqual(secret.entropy, "sikrit") self.assertEqual(secret.user, self.user)
[ "def random_secret():\n while True:\n secret = os.urandom(32)\n if secret != EMPTY_SECRET:\n return secret", "def test_update_secret(self):\n pass", "def test_secret_create_defaults_valid_bit_length(self, bit_length):\n secret = self.barbicanclient.secrets.create(\n **secret_create_defaults_data)\n secret.bit_length = bit_length\n\n secret_ref = self.cleanup.add_entity(secret)\n self.assertIsNotNone(secret_ref)\n\n resp = self.barbicanclient.secrets.get(secret_ref)\n self.assertEqual(secret.bit_length, resp.bit_length)", "def generate_secret(self):\n bits = self.args.get('length')\n # Bits should dividable by 8, because we will ask the os for random\n # bytes and because we can't encode partial bytes. Base32 will cause a\n # 160% inflation of the data and we can't have padding for TOTP secrets\n # so `bits * 1.6` can not be a fraction.\n if (bits % 8 > 0):\n self.msg('not_common_totp_val')\n exit(2)\n if bits not in [80, 160] and not self.args['expert']:\n self.msg('not_common_totp_val')\n exit(2)\n return base64.b32encode(os.urandom(bits // 8)).decode('utf-8')", "def make_totp_secret():\n return pyotp.random_base32()", "def puffer():\n if not app.settings.getboolean('security','puffer_response'):\n return ''\n return base64.b64encode(hashlib.sha256(hashlib.sha256(os.urandom(32)).digest()).digest())[:random.randint(16,32)]", "async def secret_new(self, ctx: commands.Context, *desc):\n desc = ' '.join(desc)\n if not desc.strip(): # no description provided\n await ctx.send('I need some kind of description for what\\'s in this secret.'\n ' (You\\'ll be glad for it later too, I suspect.)')\n return\n await ctx.author.send((\"I'm listening for your secret about `{}`; simply\"\n \" reply to this message.\").format(desc))\n try:\n content = await ctx.bot.wait_for(\n 'message',\n check=lambda m: m.guild is None and m.author == ctx.author,\n timeout=300)\n except asyncio.TimeoutError:\n await ctx.author.send(\"Sorry, make your request again when you're ready.\")\n else:\n digest, salt = await self.make_digest(ctx.guild, content.content)\n created = time.time()\n\n guild_secrets = self.config.guild(ctx.guild).secrets\n secrets_dict = await guild_secrets.all()\n secrets_dict['_' + digest] = {\n 'content': content.content,\n 'salt': salt,\n 'created': created,\n 'creator': ctx.author.mention,\n 'desc': desc,\n 'peek': ['u:' + str(ctx.author.id)],\n 'reveal': ['u:' + str(ctx.author.id)]\n }\n await guild_secrets.set(secrets_dict)\n\n await ctx.author.send(\n ':thumbsup: Stored your secret about {} as `{}...`'.format(\n desc, digest[:8]))", "def test_without_uuid_and_no_existing_secrets(self):\n\n url = reverse('secret')\n\n data = {}\n\n self.client.force_authenticate(user=self.test_user3_obj)\n response = self.client.get(url, data)\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)", "def _ensure_cookie_secret():\n global _cookie_master_secret\n entry = _db.config.find_one({'_id': 'cookie_master_secret'})\n if not entry:\n tmp_cookie_master_secret = misc_util.generate_random_id(length=32)\n try:\n entry = {\n '_id': 'cookie_master_secret',\n 'value': tmp_cookie_master_secret,\n }\n _db.config.insert_one(entry)\n except pymongo.errors.DuplicateKeyError:\n entry = _db.config.find_one({'_id': 'cookie_master_secret'})\n assert entry\n _cookie_master_secret = entry['value']", "def test_secret_create_defaults_invalid_bit_length(self, bit_length):\n secret = self.barbicanclient.secrets.create(\n **secret_create_defaults_data)\n secret.bit_length = bit_length\n\n e = self.assertRaises(\n exceptions.HTTPClientError,\n secret.store\n )\n\n self.assertEqual(400, e.status_code)", "def urandom(size: int) -> str:\n ...", "def test_secret_create_defaults_valid_secret_type(\n self, secret_type, algorithm, bit_length, payload):\n secret = self.barbicanclient.secrets.create(\n **secret_create_defaults_data)\n secret.secret_type = secret_type\n secret.algorithm = algorithm\n secret.bit_length = bit_length\n # payload should not be encoded.\n secret.payload = payload\n\n secret_ref = self.cleanup.add_entity(secret)\n self.assertIsNotNone(secret_ref)\n\n resp = self.barbicanclient.secrets.get(secret_ref)\n self.assertEqual(secret_type, resp.secret_type)", "def get_secret(self):\r\n return self.secret", "def generate_new_secret_key(key_length=32):\n\n symbols = string.ascii_letters + str(string.digits) + '!@#$%^&*()+-'\n secret_key = \"\".join(random.sample(symbols*2, key_length))\n warn(\"New secret key: \" + green(secret_key))\n return secret_key", "def test_secret_create_defaults_valid_payload(self, payload):\n\n secret = self.barbicanclient.secrets.create(\n **secret_create_defaults_data)\n secret.payload = payload\n\n secret_ref = self.cleanup.add_entity(secret)\n self.assertIsNotNone(secret_ref)\n\n resp = self.barbicanclient.secrets.get(secret_ref)\n self.assertEqual(secret.payload, resp.payload)", "def oauth():\n print _get_rand_hash()\n print _get_rand_hash()", "def test_secret_create_defaults_valid_expiration(self, **kwargs):\n\n timestamp = utils.create_timestamp_w_tz_and_offset(**kwargs)\n secret = self.barbicanclient.secrets.create(\n **secret_create_defaults_data)\n secret.expiration = timestamp\n\n secret_ref = self.cleanup.add_entity(secret)\n self.assertIsNotNone(secret_ref)\n\n resp = self.barbicanclient.secrets.get(secret_ref)\n self.assertIsNotNone(resp)\n self.assertEqual(secret.name, resp.name)", "def generate_secret_key():\r\n try:\r\n secure_generator = random.SystemRandom()\r\n allowed_chars='abcdefghijklmnopqrstuvwxyz'\\\r\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'\\\r\n '!@#$%^&*(-_=+'\r\n key_length = 50\r\n # This gives log2((26+26+10+14)**50) == 312 bits of entropy\r\n return ''.join(\r\n [secure_generator.choice(allowed_chars) for i in range(key_length)])\r\n except NotImplementedError:\r\n # The system does not support generation of secure random\r\n # numbers. Return something that raises parsing error and\r\n # points the user to a place where secret key needs to be\r\n # filled manually.\r\n message = ('Your system does not allow to automatically '\r\n 'generate secure secret keys.')\r\n print >> sys.stderr, ('WARNING: You need to edit configuration file '\r\n 'manually. ' + message)\r\n return ('\\'---' + message + ' Replace this text with a long, '\r\n 'unpredictable secret string (at least 50 characters).')", "def oauth():\r\n print _get_rand_hash()\r\n print _get_rand_hash()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The user attribute of secrets is indexed.
def test_indexed(self): self.assertTrue(Secret.user.indexed)
[ "def protected_index(self):\n return self.__protected_index", "def getsecretuserinfo(self, authinfo, userinfo):\n dict_secret = self.list_dict_secret_data( authinfo, userinfo, access_type='ldif' )\n raw_secrets = {}\n for key in dict_secret.keys():\n raw_secrets.update( dict_secret[key] )\n return raw_secrets", "def index(self):\n return self.auth_tag.index", "def test_user_list_keys(self):\n pass", "def showsecrets(username):\n user = User.load(username)\n if user is None:\n print('No such user: \"{}\"'.format(username))\n return 1\n else:\n print('Client secret: ' + user.client_secret)\n print('Server secret: ' + user.server_secret)", "def test_user_current_list_keys(self):\n pass", "def _get_user_cache_key(self, user):\n return 'privacy-consent:%s' % user.pk", "def test_secret_read_with_acls(self):\n secret_ref = self._create_test_secret()\n\n secret_entity = self.barbicanclient.secrets.get(secret_ref)\n self.assertIsNotNone(secret_entity.acls)\n self.assertIsNotNone(secret_entity.acls.read)\n self.assertEqual([], secret_entity.acls.read.users)", "def user_key(user_number=DEFAULT_USER_NUMBER):\n\treturn ndb.Key('User', user_number)", "def user_keys(self, user):\n if user not in self.ssh_keys:\n return []\n return self.ssh_keys[user]", "def save_indexes_for_each_user(self):\n products_grouped_by_users = load_pickle(prepr.data_sources[\"products_grouped_by_users\"])\n products_grouped_by_users = products_grouped_by_users[[\"user_id\", \"product_id\", \"freq\"]]\n products_grouped_by_users.columns = [\"user_id\", \"product_id\", \"count\"]\n\n users_id = np.unique(products_grouped_by_users[\"user_id\"])\n\n index_collection = {}\n count = 1\n for user_id in users_id:\n ith_user = products_grouped_by_users[products_grouped_by_users[\"user_id\"] == user_id]\n index_collection[user_id] = ith_user.index \n if count % 1000 == 0:\n print(count)\n count += 1\n \n pickle.dump(index_collection, open(\"../pickles/index_collection_for_each_user.p\", \"wb\"))", "def get_secret(self):\r\n return self.secret", "def lookup_user_idxs(self, user_ids):\n user_ids = user_ids.tolist()\n user_index = [self.user_dict[u] for u in user_ids]\n return torch.tensor(user_index)", "def index(self):\n m=hashlib.sha256()\n m.update(self.serialize())\n return self.pubkey.serialize() + m.digest()", "def user_key(id):\n return ndb.Key(User, id)", "def list_dict_secret_data( self, authinfo, userinfo, access_type=None ):\n access_userid = userinfo.userid\n access_provider = authinfo.provider\n secret_dict = {}\n try: \n label_selector = 'access_userid=' + access_userid + ',' + \\\n 'access_provider=' + access_provider \n if type(access_type) is str :\n label_selector += ',access_type=' + access_type \n \n ksecret_list = self.kubeapi.list_namespaced_secret(self.namespace, label_selector=label_selector)\n \n for mysecret in ksecret_list.items:\n secret_dict[mysecret.metadata.name] = { 'type': mysecret.type, 'data': {} }\n for mysecretkey in mysecret.data:\n b64data = mysecret.data[mysecretkey]\n data = oc.od.secret.ODSecret.b64todata( b64data )\n secret_dict[mysecret.metadata.name]['data'][mysecretkey] = data \n\n except ApiException as e:\n self.logger.error(\"Exception %s\", str(e) )\n return secret_dict", "def anonymize_identifiable_data(self, username):\n # Timer used to simulate REST Service Call\n time.sleep(0.1)\n\n profile = model_access.get_profile(username)\n\n if not profile:\n return True\n\n user_accesses_json = profile.access_control\n user_accesses = json.loads(user_accesses_json)\n\n user_visas = user_accesses['visas']\n\n if 'PKI' in user_visas:\n return True\n return False", "def secret(self) -> Optional[pulumi.Input['ResourceReferenceArgs']]:\n return pulumi.get(self, \"secret\")", "def eachUser(self):\n db={\n \"id\":self.number_of_users,\n \"firstname\":self.firstname,\n \"lastname\":self.lastname,\n \"othername\":self.othername,\n \"username\":self.username,\n \"email\":self.email,\n \"phoneNumber\":self.phoneNumber,\n \"password\":self.password\n }\n users.update({self.number_of_users:db})\n return users" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create chirp phase. Ascending and descending. Same as scipy.signal.waveforms._chirp_phase with constant frequency extension for t >= tEnd.
def chirp_phase(t, freqStart, tEnd, freqEnd, method='linear', vertex_zero=True): if (tEnd <= t[0]) or (freqStart == freqEnd): # Only constant frequency return TAU * freqEnd * t phase = _chirp_phase(t, f0=freqStart, t1=tEnd, f1=freqEnd, method=method, vertex_zero=vertex_zero) if t[-1] < tEnd: # Only chirping return phase # Mixture between chirp and constant frequency constFreq = (t >= tEnd) mid = constFreq.argmax() phaseOffset = phase[mid] - TAU * freqEnd * t[mid] phase[mid:] = TAU * freqEnd * t[mid:] + phaseOffset return phase
[ "def phase(dp):\n from tayph.vartests import typetest\n import numpy as np\n from astropy.io import ascii\n from astropy.time import Time\n from astropy import units as u, coordinates as coord\n import tayph.util as ut\n dp=check_dp(dp)#Path object\n d=ascii.read(dp/'obs_times',comment=\"#\")#,names=['mjd','time','exptime','airmass'])\n #Not using the named columns because I may not know for sure how many columns\n #there are, and read-ascii breaks if only some columns are named.\n #The second column has to be a date array though.\n\n # t = Time(d['col2'],scale='utc', location=coord.EarthLocation.of_site('paranal'))# I determined that the difference between this and geodetic 0,0,0 is zero.\n t = Time(d['col2'],scale='utc', location=coord.EarthLocation.from_geodetic(0,0,0))\n\n jd = t.jd\n P=paramget('P',dp)\n RA=paramget('RA',dp)\n DEC=paramget('DEC',dp)\n Tc=paramget('Tc',dp)#Needs to be given in BJD!\n\n typetest(P,float,'P in sp.phase()')\n typetest(Tc,float,'Tc in sp.phase()')\n typetest(RA,str,'RA in sp.phase()')\n typetest(DEC,str,'DEC in sp.phase()')\n\n ip_peg = coord.SkyCoord(RA,DEC,unit=(u.hourangle, u.deg), frame='icrs')\n ltt_bary = t.light_travel_time(ip_peg)\n\n n=0.0\n Tc_n=Time(Tc,format='jd',scale='tdb')\n while Tc_n.jd >= min(jd):\n Tc_n=Time(Tc-100.0*n*P,format='jd',scale='tdb')#This is to make sure that the Transit central time PRECEDES the observations (by tens or hundreds or thousands of years). Otherwise, the phase could pick up a minus sign somewhere and be flipped. I wish to avoid that.\n n+=1\n BJD = t.tdb + ltt_bary\n diff = BJD-Tc_n\n phase=((diff.jd) % P)/P\n return phase", "def sample_phase(frequency, startPhase=0.):\n constFrequency = (np.ndim(frequency) == 0)\n if constFrequency:\n t = get_time(BUFFER_SIZE + 1, DT)\n phase = TAU * frequency * t + startPhase\n else:\n phase = np.empty(BUFFER_SIZE + 1)\n phase[0] = startPhase\n phase[1:] = TAU * DT * np.cumsum(frequency) + startPhase\n\n phase = np.mod(phase, TAU)\n return phase[:-1], phase[-1]", "def _make_phase_command(channel, phase_degrees):\r\n return _make_command(channel, 'P%.3f' % (phase_degrees % 360))", "def phase_of_times(self, times , sampling_rate = 1000.):\n if self.time_line.size>1:\n old_dt = self.time_line[1]-self.time_line[0]\n x = numpy.arange(self.time_start, self.time_stop+old_dt, 1./sampling_rate)\n else:\n x=self.time_line\n v = self.value_line\n \n # BAD\n #y = numpy.angle(v)\n #y = signal.resample( y, x.size)\n \n \n \n # bad 2\n #~ y = numpy.cos(numpy.angle(v))\n #~ y = signal.resample( y, x.size)\n #~ ind = numpy.diff(y)>0\n #~ ind = numpy.concatenate( (ind , [ind[-1]]))\n #~ y2 = numpy.arccos(y)\n #~ y2[ind] = -y2[ind]\n \n #ok\n # Before resampling, in order to avoid slow down due the use of ifft in scipy.resample\n # y is padded with 0 proportionnally to the distance from x.size to the next 2**N \n # QUESTION: does it lead to some strange edge effects???\n N=numpy.ceil(numpy.log2(x.size))\n vv=numpy.r_[v,numpy.zeros(numpy.floor(v.size*(2**N-x.size)/x.size))]\n vv = signal.resample( vv, 2**N)\n v = vv[:x.size]\n\n #~ y = numpy.cos(numpy.angle(v))\n y2 = numpy.angle(v)\n\n\n\n d = digitize( times , x )\n d[d==len(v)] = 0 # points above the highest time value where the oscillation phase is known\n phases = y2[d]\n phases[ d==0 ] = nan # all points outside the range where the oscillation is known\n return phases", "def phase(angle):\n return angle % (2*math.pi)", "def spectral_phase(self):\r\n return lib.phase(self._spectrum)", "def chirp(*args, **kwargs):\n numSamples = kwargs.get('nsamples', 1024*5)\n sampleRate = kwargs.get('sample_rate', 8000)\n peakAmplitude = kwargs.get('peakAmplitude', 0.8)\n freqStart = kwargs.get('freqStart', 100)\n freqStop = kwargs.get('freqStop', 4000)\n method = kwargs.get('method', 'linear')\n assert freqStart > 0\n assert freqStart < freqStop\n assert freqStop <= sampleRate / 2\n \n chirp = None\n if method is 'linear': \n chirpRate = (freqStop - freqStart) / float(numSamples)\n samplePts = numpy.arange(numSamples, dtype=numpy.float64)\n f = freqStart + 0.5 * chirpRate * samplePts\n chirp = numpy.sin(2.0 * numpy.pi * (f * samplePts) / sampleRate)\n elif method is 'exponential': \n chirpRate = (freqStop/freqStart)**(1 / float(numSamples))\n samplePts = numpy.arange(numSamples, dtype=numpy.float64)\n chirp = numpy.sin((2.0 * numpy.pi * freqStart / numpy.log(chirpRate)) * (chirpRate**samplePts - 1.0) / sampleRate)\n else: \n raise Exception('Unkown chirp method')\n \n scalingFactor = float(peakAmplitude) / max(chirp)\n chirp *= scalingFactor\n return sampled_waveform(chirp, sample_rate=sampleRate, domain='time')", "def wavelet_phase(coeffs):\n if 'numpy' in str(type(coeffs)):\n phase = np.angle(coeffs)\n else:\n epochs = coeffs[0].shape[0]\n phase = list()\n channels = len(coeffs)\n for c in range(channels):\n dummy = np.zeros(coeffs[0].shape,dtype=np.float64)\n for i in range(epochs):\n dummy[i,:,:] = np.angle(coeffs[c][i,:,:])\n phase.append(dummy)\n\n return phase", "def pink_tsp():\n \n import primes\n import cmath\n import numpy as np\n from scipy.io import wavfile\n from utility import float2pcm\n \n # User settings\n dur = 5 # length of signal (seconds)\n fs = 48000 # number of samples per second (Hz)\n nbits = 16 # number of bits per sample (bit)\n reps = 4 # number of repeated measurements (times)\n \n N = 2 ** (nextpow2(dur * fs))\n m = primes.primes_below(N / 4)\n m = m[-1]\n \n a = 2 * m * np.pi / ((N / 2) * np.log(N / 2))\n j = cmath.sqrt(-1)\n pi = (cmath.log(-1)).imag\n \n H = np.array([1])\n H = np.hstack(\n [H, np.exp(j * a * np.arange(1, N / 2 + 1) * np.log(np.arange(1, N / 2 + 1))) / np.sqrt(np.arange(1, N / 2 + 1))])\n H = np.hstack([H, np.conj(H[int((N / 2 - 1)):0:-1])])\n h = (np.fft.ifft(H)).real\n mvBefore = np.abs(h)\n mv = min(mvBefore)\n mi = np.where(mvBefore == mvBefore.min())\n mi = int(mi[0])\n h = np.hstack([h[mi:len(h)], h[0:mi]])\n h = h[::-1]\n \n Hinv = np.array([1])\n Hinv = np.hstack([Hinv, np.exp(j * a * np.arange(1, N / 2 + 1) * np.log(np.arange(1, N / 2 + 1))) * np.sqrt(\n np.arange(1, N / 2 + 1))])\n Hinv = np.hstack([Hinv, np.conj(Hinv[int((N / 2 - 1)):0:-1])])\n hinv = (np.fft.ifft(Hinv)).real\n \n hh = np.hstack((np.tile(h, (reps, 1)).flatten(), np.zeros(len(h))))\n out = hh / max(np.abs(hh)) / np.sqrt(2)\n \n wavfile.write('pinktsp.wav', fs, float2pcm(out, 'int16'))\n \n plt.specgram(out, Fs=fs)\n plt.show()", "def make_chord(voices):\n sampling = 4096\n chord = waveform(voice[v], sampling)\n for v in len(voices):\n chord = sum(sine_wave(freq[v], voices[v]*64, sample_rate))\n return chord", "def chirpf(self,cr=160e3):\n L=self.conf.n_samples_per_block\n sr=self.conf.sample_rate\n f0=0.0\n tv=n.arange(L,dtype=n.float64)/float(sr)\n dphase=0.5*tv**2*cr*2*n.pi\n chirp=n.exp(1j*n.mod(dphase,2*n.pi))*n.exp(1j*2*n.pi*f0*tv)\n return(n.array(chirp,dtype=n.complex64))", "def simple_harmonic_oscillator(p, t):\n return p[0] + p[1] * np.cos(p[2] * t - p[3])", "def phase_spectrum(self, x, Fs=None, Fc=None, window=None,\n pad_to=None, sides=None, **kwargs):\n if Fc is None:\n Fc = 0\n\n spec, freqs = mlab.phase_spectrum(x=x, Fs=Fs, window=window,\n pad_to=pad_to, sides=sides)\n freqs += Fc\n\n lines = self.plot(freqs, spec, **kwargs)\n self.set_xlabel('Frequency')\n self.set_ylabel('Phase (radians)')\n\n return spec, freqs, lines[0]", "def phase(dp):\n from lib.utils import typetest\n import numpy as np\n import pdb\n from astropy.io import ascii\n from astropy.time import Time\n from astropy import units as u, coordinates as coord\n import lib.utils as ut\n typetest('dp',dp,str)\n d=ascii.read(dp+'obs_times',comment=\"#\")#,names=['mjd','time','exptime','airmass'])\n #Removed the named columns because I may not know for sure how many columns\n #there are, and read-ascii breaks if only some columns are named.\n #The second column has to be a date array though.\n # t1=ut.start()\n # t = Time(d['col2'],scale='utc', location=coord.EarthLocation.of_site('paranal'))# I determined that the difference between this and geodetic 0,0,0 is zero.\n # ut.end(t1)\n # t2=ut.start()\n t = Time(d['col2'],scale='utc', location=coord.EarthLocation.from_geodetic(0,0,0))\n # ut.end(t2)\n\n jd = t.jd\n P=paramget('P',dp)\n RA=paramget('RA',dp)\n DEC=paramget('DEC',dp)\n Tc=paramget('Tc',dp)#Needs to be given in BJD!\n\n typetest('P',P,float)\n typetest('Tc',Tc,float)\n\n ip_peg = coord.SkyCoord(RA,DEC,unit=(u.hourangle, u.deg), frame='icrs')\n ltt_bary = t.light_travel_time(ip_peg)\n\n n=0.0\n Tc_n=Time(Tc,format='jd',scale='tdb')\n while Tc_n.jd >= min(jd):\n Tc_n=Time(Tc-100.0*n*P,format='jd',scale='tdb')#This is to make sure that the Transit central time PRECEDES the observations (by tens or hundreds or thousands of years). Otherwise, the phase could pick up a minus sign somewhere and be flipped. I hate that.\n n+=1\n BJD = t.tdb + ltt_bary\n diff = BJD-Tc_n\n phase=((diff.jd) % P)/P\n return phase", "def damped_harmonic_oscillator(p, t):\n return p[0] + np.exp(-p[4] * t / 2.) * simple_harmonic_oscillator([0, p[1], p[2], p[3]], t)", "def phase_vocoder(spec, ratio):\n\n time_steps = np.arange(spec.shape[1]) * ratio\n time_steps = time_steps[time_steps < spec.shape[1]]\n\n # interpolate magnitude\n yy = np.meshgrid(np.arange(time_steps.size), np.arange(spec.shape[0]))[1]\n xx = np.zeros_like(yy)\n coordiantes = [yy, time_steps + xx]\n warped_spec = map_coordinates(np.abs(spec), coordiantes, mode='reflect',\n order=1).astype(np.complex)\n\n # phase vocoder\n # Phase accumulator; initialize to the first sample\n spec_angle = np.pad(np.angle(spec), [(0, 0), (0, 1)], mode='constant')\n phase_acc = spec_angle[:, 0]\n\n for (t, step) in enumerate(np.floor(time_steps).astype(np.int)):\n # Store to output array\n warped_spec[:, t] *= np.exp(1j * phase_acc)\n\n # Compute phase advance\n dphase = (spec_angle[:, step + 1] - spec_angle[:, step])\n\n # Wrap to -pi:pi range\n dphase = np.mod(dphase - np.pi, 2 * np.pi) - np.pi\n\n # Accumulate phase\n phase_acc += dphase\n\n return warped_spec", "def calculate_phase_inc(self):\n if self.integral_freq == False:\n self.phase_inc[:] = [self.master.phase_incs[x] for x in self.curr_freq][:]\n if self.integral_freq == True:\n self.phase_inc[:] = [self.master.phase_incs[self.master.curr_master_freq+(x*12)] for x in self.curr_freq][:]", "def phase(self):\n PP = self._complex_amplitude.real\n QQ = self._complex_amplitude.imag\n return math.atan2(QQ, PP) # result between -pi and pi.", "def s11_phase_func(x, *p):\n return np.angle(((p[2] - p[1]) / p[2] + 2 * 1j * (x - p[0]) * p[1] / p[0]) / (\n (p[1] + p[2]) / p[2] + 2 * 1j * (x - p[0]) * p[1] / p[0]))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get BUFFER_SIZE many phase samples for a given frequency. Also supports an array of frequencies (varying frequency). If so has to be BUFFER_SIZE long.
def sample_phase(frequency, startPhase=0.): constFrequency = (np.ndim(frequency) == 0) if constFrequency: t = get_time(BUFFER_SIZE + 1, DT) phase = TAU * frequency * t + startPhase else: phase = np.empty(BUFFER_SIZE + 1) phase[0] = startPhase phase[1:] = TAU * DT * np.cumsum(frequency) + startPhase phase = np.mod(phase, TAU) return phase[:-1], phase[-1]
[ "def freq_from_pcm(pcm, window, step, channels):\n\n # XXX doesn't pad data with zeroes at the start\n offset = 0\n while offset < pcm.shape[0]:\n data = numpy.zeros(window, numpy.float64)\n for ch in channels:\n chunk = pcm[offset : offset + window, ch]\n if len(chunk) < window:\n chunk = numpy.pad(chunk, [(0, window - len(chunk))])\n data += chunk\n result = numpy.fft.rfft(data * kaiser(len(data)))\n\n # some transformations suggested by\n # https://lo.calho.st/posts/numpy-spectrogram/\n result = result[: window // 2]\n result = numpy.absolute(result) * 2.0 / window\n # result = (20 * numpy.log10(result)).clip(-120)\n yield result\n offset += step", "def _decodeFrequencies(freq_buffer, freq_byte_count):\n\n # Invalid input\n if (freq_byte_count <= 0 or freq_byte_count > 4):\n raise ValueError(\"Invalid frequency byte count, must be greater than zero and less than or equal to 4\");\n elif (len(freq_buffer) % freq_byte_count != 0):\n raise ValueError(\"Invalid length for the frequency buffer, must be a multiple of \" + freq_byte_count);\n \n res = [];\n \n # Loop over all the frequencies\n for i in range(0, len(freq_buffer), freq_byte_count):\n \n bytes = freq_buffer[i:i + freq_byte_count];\n \n # Unpack the frequency value\n res.append(_convertBytesToInt(bytes));\n \n return res;", "def fftfreq(n, dtype=torch.float, device=torch.device(\"cpu\")):\n return (torch.arange(n, dtype=dtype, device=device) + n // 2) % n - n // 2", "def get_pitch(signal, width, step, fs, threshold, method=autocorrelation, extend=True):\n step_len = int(fs*step/1000)\n frames = split(normalize(signal), width, step, fs)\n pitch = []\n\n for f in frames:\n p = method(f, fs, threshold)\n pitch += [p] * (step_len if extend else 1) if p != 0 or extend else []\n\n return np.array(pitch)", "def get_num_fft(sample_rate, window_len):\n frame_length = sample_rate * window_len\n num_fft = 1\n while num_fft < frame_length:\n num_fft *= 2\n return num_fft", "def make_buffer_from_bit_pattern(pattern, DATASIZE, freqs, off_freq):\n # the key's middle value is the bit's value and the left and right bits are the bits before and after\n # the buffers are enveloped to cleanly blend into each other\n\n last_bit = pattern[-1]\n output_buffer = []\n offset = 0\n counter = 1\n\n for i in range(len(pattern)):\n bit = pattern[i]\n if i < len(pattern) - 1:\n next_bit = pattern[i+1]\n else:\n next_bit = pattern[0]\n\n freq = freqs[counter] if bit == '1' else off_freq\n tone = ttone(freq, DATASIZE, offset=offset)\n # output_buffer += envelope(tone, left=last_bit=='0', right=next_bit=='0')\n output_buffer.append(tone)\n # offset += DATASIZE\n last_bit = bit\n\n if counter == 8:\n counter = 1\n else:\n counter += 1\n\n output_buffer = [struct.pack('f'*len(frame), *frame) for frame in output_buffer]\n # print output_buffer\n\n # return struct.pack('s'*len(output_buffer), *output_buffer)\n return output_buffer", "def pitch_detect(sndarray, fs, chunk_size):\n new_sndarray = numpy.asarray(numpy.float64(sndarray))\n f0 = pysptk.swipe(numpy.asarray(new_sndarray), fs,\n chunk_size, 65, 500, 0.001, 1)\n\n return f0", "def getNumSamples(sound):\n return getLength(sound)", "def generateSpecgram(audioFile, windowFn = np.hanning, NFFT=1024, hop_size=-1):\n \n #Inits\n audio = audioFile.audio.copy()\n L = audioFile.length\n if hop_size < 0:\n hop_size = NFFT\n \n nslices = int( (L-NFFT)*1.0/hop_size )\n \n window = windowFn(NFFT)\n\n time_slice = audio[0 : NFFT] \n analysis_window = np.multiply(time_slice, window)\n stft = np.fft.fft(analysis_window, n=NFFT) \n spectrogram = stft \n\n for w_index in range(1, nslices):\n time_slice = audio[w_index*hop_size : w_index*hop_size + NFFT] \n analysis_window = np.multiply(time_slice, window)\n stft = np.fft.fft(analysis_window, n=NFFT) \n spectrogram = np.c_[spectrogram, stft] \n \n return spectrogram", "def chunk_sound(bits):\n global buffer\n buffer = np.append(buffer, bits)\n abs_buffer = np.absolute(buffer)\n # Keep accumulating if not enough silence has been detected\n if len(buffer) <= SILENCE_FRAME_THRESHOLD:\n return np.array([])\n # If enough silence, clear the buffer\n last_timespan = abs_buffer[-SILENCE_FRAME_THRESHOLD:]\n if np.average(last_timespan) < SILENCE_AVR_THRESHOLD:\n # If there is enough sound, return it\n if np.average(abs_buffer) >= OVERALL_THRESHOLD:\n result = buffer\n buffer = np.array([])\n return result\n buffer = np.array([])\n return np.array([])", "def play_frequencies(self, stream, length, volume, attack, decay, *freqs):\n\n def _create_waveform(freq):\n wave = [self.wave(freq, length, self.sample_rate)]\n waveform = (np.concatenate(wave) * volume / 16)\n\n fade_in = np.arange(0., 1., 1./attack)\n fade_out = np.arange(1., 0., -1./decay)\n\n waveform[:attack] = np.multiply(waveform[:attack], fade_in)\n waveform[-decay:] = np.multiply(waveform[-decay:], fade_out)\n\n return waveform\n\n all_tones = map(_create_waveform, freqs)\n all_tones = sum(all_tones)\n\n # plt.plot(chunk[])\n # plt.show()\n\n return stream.write(all_tones.astype(np.float32).tostring())", "def angular_cumsum(angular_frequency, chunk_size=1000):\n # Get tensor shapes.\n n_batch = angular_frequency.shape[0]\n n_time = angular_frequency.shape[1]\n n_dims = len(angular_frequency.shape)\n n_ch_dims = n_dims - 2\n\n # Pad if needed.\n remainder = n_time % chunk_size\n if remainder:\n pad_amount = chunk_size - remainder\n angular_frequency = pad_axis(angular_frequency, [0, pad_amount], axis=1)\n\n # Split input into chunks.\n length = angular_frequency.shape[1]\n n_chunks = int(length / chunk_size)\n chunks = tf.reshape(angular_frequency,\n [n_batch, n_chunks, chunk_size] + [-1] * n_ch_dims)\n phase = tf.cumsum(chunks, axis=2)\n\n # Add offsets.\n # Offset of the next row is the last entry of the previous row.\n offsets = phase[:, :, -1:, ...] % (2.0 * np.pi)\n offsets = pad_axis(offsets, [1, 0], axis=1)\n offsets = offsets[:, :-1, ...]\n\n # Offset is cumulative among the rows.\n offsets = tf.cumsum(offsets, axis=1) % (2.0 * np.pi)\n phase = phase + offsets\n\n # Put back in original shape.\n phase = phase % (2.0 * np.pi)\n phase = tf.reshape(phase, [n_batch, length] + [-1] * n_ch_dims)\n\n # Remove padding if added it.\n if remainder:\n phase = phase[:, :n_time]\n return phase", "def to_samples(time_length: Union[str, int], sfreq: float) -> int:\n validate_type(time_length, (str, int))\n if isinstance(time_length, str):\n time_length = time_length.lower()\n err_msg = ('filter_length, if a string, must be a '\n 'human-readable time, e.g. \"0.7s\", or \"700ms\", not '\n '\"%s\"' % time_length)\n low = time_length.lower()\n if low.endswith('us'):\n mult_fact = 1e-6\n time_length = time_length[:-2]\n elif low.endswith('ms'):\n mult_fact = 1e-3\n time_length = time_length[:-2]\n elif low[-1] == 's':\n mult_fact = 1\n time_length = time_length[:-1]\n elif low.endswith('sec'):\n mult_fact = 1\n time_length = time_length[:-3]\n elif low[-1] == 'm':\n mult_fact = 60\n time_length = time_length[:-1]\n elif low.endswith('min'):\n mult_fact = 60\n time_length = time_length[:-3]\n else:\n raise ValueError(err_msg)\n # now get the number\n try:\n time_length = float(time_length)\n except ValueError:\n raise ValueError(err_msg)\n time_length = max(int(np.ceil(time_length * mult_fact * sfreq)), 1)\n time_length = ensure_int(time_length, 'filter_length')\n return time_length", "def chunks(data_list, chunk_size):\n data_info, frequency, bits = data_list\n\n some_data_list = []\n for i in range(0, len(data_info), chunk_size):\n some_data_list.append(data_info[i:i+chunk_size])\n return some_data_list", "def create_int_buffer(number_of_channels, samples_per_channel):\r\n # type: (int, int) -> Array[int]\r\n ull_array = c_ulonglong * (number_of_channels * samples_per_channel) # type: type\r\n return ull_array()", "def split_sample(sample, length, n_samples=None):\n (time_steps, pitch_level) = sample.shape\n if n_samples == None:\n n_samples = int(time_steps / length)\n samples = np.zeros((n_samples, length, pitch_level))\n max_start = time_steps - length\n for i in range(0, n_samples):\n start = int(i * max_start / n_samples)\n end = start + length\n samples[i] = sample[start:end, :]\n return samples", "def singleFreqLUT(f, iq, sampleRate=540e6, resolution=1e4, phase=0, amplitude=2**15-1):\r\n size = int(sampleRate/resolution)\r\n data = []\r\n for i in range(0, size):\r\n t = i/sampleRate\r\n if iq == 'I':\r\n data.append(int(amplitude*math.cos(2*math.pi*f*t+phase)))\r\n else:\r\n data.append(int(-amplitude*math.sin(2*math.pi*f*t+phase)))\r\n\r\n return data", "def get_burst_samples(is_oscillating, fs, freq):\n\n n_samples_cycle = compute_nsamples(1 / freq, fs)\n bursts = np.repeat(is_oscillating, n_samples_cycle)\n\n return bursts", "def packet_get_samples_per_frame(cls, data: bytes) -> int:\n return _lib.opus_packet_get_samples_per_frame(data, cls.SAMPLING_RATE)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pivoted QR factorization, where the pivots are used as a heuristic for subsampling.
def get_qr_column_pivoting(Ao, number_of_subsamples): A = deepcopy(Ao) _, _, pvec = qr(A.T, pivoting=True) z = pvec[0:number_of_subsamples] return z
[ "def qr_to_rq_decomposition(self):\n Q, R = np.linalg.qr(np.flipud(self.P).T)\n R = np.flipud(R.T)\n return R[:, ::-1], Q.T[::-1, :]", "def QRDecompositionExample():\n A = np.array([[1,1,0],[1,2,1],[-2,-3,1]])\n print(A)\n Q,R = QRDecomposition(A)\n print(Q)\n print(R)", "def QRSteps(self):\n V = numpy.eye(self._m)\n for shift in self._Shifts:\n Q, R = numpy.linalg.qr(\n self._H[:self._k+1, :self._k+1] - shift*numpy.eye(self._k+1) )\n\n self._H[:self._k+1,:] = numpy.dot(Q.transpose(), self._H[:self._k+1,:])\n self._H[:,:self._k+1] = numpy.dot(self._H[:, :self._k+1], Q)\n V[:, :self._k+1] = numpy.dot(V[:, :self._k+1], Q)\n\n # Clean up rounding error below subdiagonal\n for i in xrange(len(self._H)):\n for j in xrange(i-1):\n self._H[i,j] = 0\n\n return V", "def test_pivot(self):\n x = []\n for i in range(300): \n x.append(random.randint(-100,100))\n self.sorter = QuickSort.QuickSort(x, verbose = False)\n j = self.sorter.pivot(0,len(self.sorter.getData()) -1)\n D = self.sorter.getData()\n for i in range(0,j):\n self.assertTrue(D[i] <= D[j])\n for i in range(j+1, len(D)):\n self.assertTrue(D[j] <= D[i])", "def qr_householder(A):\n sign = lambda x: 1 if x >= 0 else -1\n m, n = np.shape(A)\n R = np.copy(A)\n Q = np.eye(m) \n\n \n for k in range(n):\n u = np.copy(R[k:,k])\n u[0] = u[0] + (sign(u[0]) * la.norm(u))\n u = u / (1.0 * la.norm(u)) \n R[k:,k:] = R[k:,k:] - (2*np.outer(u, (u.T @ R[k:,k:])))\n Q[k:,:] = Q[k:,:] - (2*np.outer(u, (u.T @ Q[k:,:]))) \n \n return Q.T, R\n #raise NotImplementedError(\"Problem 4 Incomplete\")", "def QRDecomposition(A):\n \n if (A.shape[0] != A.shape[1]) or np.abs(np.linalg.det(A))<0.0001:\n print(\"Input matrix is not a basis\")\n \n else:\n Q = np.zeros(A.shape)\n R = np.zeros(A.shape)\n \n #First vector\n Q[:,0] = A[:,0]/np.linalg.norm(A[:,0])\n R[0,0] = np.linalg.norm(A[:,0])\n \n #Q is the matrix of the new orthonormal vectors\n #R contains the scaling factors that are applied in each linear combination in the Gram Schmidt process\n for j in range(1, A.shape[1]):\n Q[:,j] = A[:,j]\n \n for k in range(0, j):\n Q[:,j] -= (Q[:,k].T.dot(A[:,j]))*Q[:,k]\n R[k,j] = Q[:,k].T.dot(A[:,j])\n \n #Normalize\n Q[:,j] = Q[:,j]/np.linalg.norm(Q[:,j])\n R[j,j] = Q[:,j].T.dot(A[:,j])\n \n return Q, R", "def _qr_full_pullback(cls, Qbar_data, Rbar_data, A_data, Q_data, R_data, out = None):\n\n\n if out == None:\n raise NotImplementedError('need to implement that...')\n\n Abar_data = out\n A_shp = A_data.shape\n D,P,M,N = A_shp\n\n if M < N:\n raise NotImplementedError('supplied matrix has more columns that rows')\n\n # STEP 1: compute: tmp1 = PL * ( Q.T Qbar - Qbar.T Q + R Rbar.T - Rbar R.T)\n PL = numpy.array([[ r > c for c in range(M)] for r in range(M)],dtype=float)\n tmp = cls._dot(cls._transpose(Q_data), Qbar_data) + cls._dot(R_data, cls._transpose(Rbar_data))\n tmp = tmp - cls._transpose(tmp)\n\n for d in range(D):\n for p in range(P):\n tmp[d,p] *= PL\n\n # STEP 2: compute H = K * R1^{-T}\n R1 = R_data[:,:,:N,:]\n K = tmp[:,:,:,:N]\n H = numpy.zeros((D,P,M,N))\n\n cls._solve(R1, cls._transpose(K), out = cls._transpose(H))\n\n H += Rbar_data\n\n Abar_data += cls._dot(Q_data, H, out = numpy.zeros_like(Abar_data))\n\n # tmp2 = cls._solve(cls._transpose(R_data[:,:,:N,:]), cls._transpose(tmp), out = numpy.zeros((D,P,M,N)))\n # tmp = cls._dot(tmp[:,:,:,:N], cls._transpose\n # print Rbar_data.shape", "def _itq(self, X):\n # Dimension reduction\n # shape: (n_samples, encode_len)\n V = self._project(X)\n\n # Initialize with a orthogonal random rotation\n R = np.random.randn(self.encode_len, self.encode_len)\n R = np.linalg.svd(R)[0]\n\n # ITQ to find optimal rotation\n for _ in range(self.n_iter):\n # Fix R and updata B:\n # shape: (n_samples, encode_len)\n Z = np.matmul(V, R)\n B = sign(Z)\n # Fix B and update R:\n # shape: (encode_len, encode_len)\n C = np.matmul(B.T, V)\n S, _, S_hat_T = np.linalg.svd(C)\n # R = S_hat @ S.T = (S @ S_hat_T).T\n R = np.matmul(S, S_hat_T).T\n return R", "def QR_QRsolve(Q, R, b):\n x = zeros(R.shape[1], get_typecode(R))\n _gslwrap.gsl_linalg_QR_QRsolve(Q, R, b, x)\n return x", "def PartialPivot(A,v):\r\n\r\n N = len(v)\r\n \r\n # Gaussian elimination\r\n for m in range(N):\r\n heads = A[::,m] #collecting leading elements of the m-th stel in the elimination to ultimately select a good candidate. \r\n abs_heads = list(abs(heads))\r\n winning = abs_heads.index(max(abs_heads))\r\n if heads[m] == 0:\r\n A[m, :], A[winning, :] = copy(A[winning, :]), copy(A[m, :])\r\n v[m], v[winning] = copy(v[winning]), copy(v[m])\r\n else:\r\n pass\r\n # Divide by the diagonal element\r\n div = A[m,m]\r\n A[m,:] /= div\r\n v[m] /= div\r\n \r\n # Now subtract from the lower rows\r\n for i in range(m+1,N):\r\n mult = A[i,m]\r\n A[i,:] -= mult*A[m,:]\r\n v[i] -= mult*v[m]\r\n \r\n # Backsubstitution\r\n x = empty(N,float)\r\n for m in range(N-1,-1,-1):\r\n x[m] = v[m]\r\n for i in range(m+1,N):\r\n x[m] -= A[m,i]*x[i]\r\n return x", "def _qr_tf(\n self: Any,\n tensor: Tensor,\n pivot_axis: int = -1,\n non_negative_diagonal: bool = False,\n) -> Tuple[Tensor, Tensor]:\n from .tf_ops import tfqr\n\n left_dims = tf.shape(tensor)[:pivot_axis]\n right_dims = tf.shape(tensor)[pivot_axis:]\n\n tensor = tf.reshape(tensor, [tf.reduce_prod(left_dims), tf.reduce_prod(right_dims)])\n q, r = tfqr(tensor)\n if non_negative_diagonal:\n phases = tf.math.sign(tf.linalg.diag_part(r))\n q = q * phases\n r = phases[:, None] * r\n center_dim = tf.shape(q)[1]\n q = tf.reshape(q, tf.concat([left_dims, [center_dim]], axis=-1))\n r = tf.reshape(r, tf.concat([[center_dim], right_dims], axis=-1))\n return q, r", "def fattorizzazione_lu_pivot(A):\n\n def swap_rows(M, r1, r2):\n M[[r1, r2], :] = M[[r2, r1], :]\n\n m, n = A.shape\n if m != n:\n print(\"Matrice non quadrata\")\n return [], [], [], False\n\n U = A.copy()\n P = np.eye(n)\n for k in range(n - 1):\n if U[k, k] == 0:\n print(\"Elemento diagonale nullo\")\n return [], [], [], False\n for i in range(k + 1, n):\n pivot = k + np.argmax(abs(U[k:, k]))\n if k != pivot:\n swap_rows(U, k, pivot)\n swap_rows(P, k, pivot)\n U[i, k] /= U[k, k]\n for j in range(k + 1, n):\n U[i, j] -= U[i, k] * U[k, j]\n\n L = np.tril(U, -1) + np.eye(n)\n U = np.triu(U)\n return L, U, P, True", "def qr_householder(A):\r\n s = lambda x: 1 if x >= 0 else -1\r\n\r\n m,n = A.shape\r\n R = A.copy().astype(float)\r\n #create m x m identity matrix\r\n Q = np.eye(m)\r\n for k in range(0,n):\r\n u = R[k:,k].copy().astype(float)\r\n #u[0] will be the first entry of u\r\n u[0] = u[0] + s(u[0]) * la.norm(u)\r\n #normalize u\r\n u = u/la.norm(u)\r\n #apply reflection to R\r\n R[k:,k:] = R[k:,k:] - np.outer(2*u,(u.T@R[k:,k:]))\r\n #apply reflection to Q\r\n Q[k:,:] = Q[k:,:] - np.outer(2*u,(u.T@Q[k:,:]))\r\n return Q.T,R", "def manipPivot(posValid=bool, resetPos=bool, reset=bool, pinPivot=bool, valid=bool, oriValid=bool, snapOri=bool, ori=float, resetOri=bool, pos=float, snapPos=bool):\n pass", "def _rq_tf(\n self: Any,\n tensor: Tensor,\n pivot_axis: int = 1,\n non_negative_diagonal: bool = False,\n) -> Tuple[Tensor, Tensor]:\n from .tf_ops import tfqr\n\n left_dims = tf.shape(tensor)[:pivot_axis]\n right_dims = tf.shape(tensor)[pivot_axis:]\n\n tensor = tf.reshape(tensor, [tf.reduce_prod(left_dims), tf.reduce_prod(right_dims)])\n q, r = tfqr(tf.math.conj(tf.transpose(tensor)))\n if non_negative_diagonal:\n phases = tf.math.sign(tf.linalg.diag_part(r))\n q = q * phases\n r = phases[:, None] * r\n r, q = (\n tf.math.conj(tf.transpose(r)),\n tf.math.conj(tf.transpose(q)),\n ) # M=r*q at this point\n center_dim = tf.shape(r)[1]\n r = tf.reshape(r, tf.concat([left_dims, [center_dim]], axis=-1))\n q = tf.reshape(q, tf.concat([[center_dim], right_dims], axis=-1))\n return r, q", "def factor(self):\n if self.K is not None and self.R is not None:\n return self.K, self.R, self.t # Already been factorized or supplied\n\n K, R = self.qr_to_rq_decomposition()\n # make diagonal of K positive\n T = np.diag(np.sign(np.diag(K)))\n if np.linalg.det(T) < 0:\n T[1, 1] *= -1\n\n self.K = np.dot(K, T)\n self.R = np.dot(T, R) # T is its own inverse\n self.t = np.dot(np.linalg.inv(self.K), self.P[:, 3])\n\n return self.K, self.R, self.t", "def triangular_form(self):\r\n pivot_row = 0\r\n pivot_col = 0\r\n size = self.__len__()\r\n\r\n copy_of_matrix = []\r\n for line in self.matrix_value:\r\n new_line = []\r\n for values in line:\r\n new_line.append(values)\r\n copy_of_matrix.append(new_line)\r\n\r\n while pivot_row < size[0] and pivot_col < size[1]:\r\n line_max = 0\r\n val_max = 0\r\n for new_pivot in range(pivot_row, size[0]):\r\n if abs(copy_of_matrix[new_pivot][pivot_col]) > val_max:\r\n line_max = new_pivot\r\n\r\n if copy_of_matrix[line_max][pivot_col] == 0:\r\n pivot_col += 1\r\n else:\r\n swap = copy_of_matrix[pivot_row]\r\n copy_of_matrix[pivot_row] = copy_of_matrix[new_pivot]\r\n copy_of_matrix[new_pivot] = swap\r\n for rows in range(pivot_row + 1, size[0]):\r\n coefficient = copy_of_matrix[rows][pivot_col] / copy_of_matrix[pivot_row][pivot_col]\r\n copy_of_matrix[rows][pivot_col] = 0\r\n for col in range(pivot_col + 1, size[1]):\r\n copy_of_matrix[rows][col] = copy_of_matrix[rows][col] - \\\r\n copy_of_matrix[pivot_row][col] * coefficient\r\n\r\n pivot_row += 1\r\n pivot_col += 1\r\n to_return = Matrix()\r\n to_return.list_2dimension_convert(copy_of_matrix)\r\n return to_return", "def _setup_Q(self):\n self.Q_s = [None for _ in range(self.p+1)]\n self.Q_s[self.p] = np.eye(self.layers[self.p-1])\n for i in range(self.p-1, -1, -1):\n self.Q_s[i] = np.dot(self.U_s[i], self.Q_s[i+1])", "def _find_itq_rotation(self, v, n_iter):\n # initialize with an orthogonal random rotation\n bit = v.shape[1]\n r = numpy.random.randn(bit, bit)\n u11, s2, v2 = numpy.linalg.svd(r)\n r = u11[:, :bit]\n\n # ITQ to find optimal rotation\n self._log.debug(\"ITQ iterations to determine optimal rotation: %d\",\n n_iter)\n for i in range(n_iter):\n self._log.debug(\"ITQ iter %d\", i + 1)\n z = numpy.dot(v, r)\n ux = numpy.ones(z.shape) * (-1)\n ux[z >= 0] = 1\n c = numpy.dot(ux.transpose(), v)\n ub, sigma, ua = numpy.linalg.svd(c)\n r = numpy.dot(ua, ub.transpose())\n\n # Make B binary matrix using final rotation matrix\n # - original code returned B transformed by second to last rotation\n # matrix, there by returning, de-synchronized matrices\n # - Recomputing Z here so as to generate up-to-date B for the final\n # rotation matrix computed.\n # TODO: Could move this step up one level and just return rotation mat\n z = numpy.dot(v, r)\n b = numpy.zeros(z.shape, dtype=numpy.uint8)\n b[z >= 0] = True\n\n return b, r" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retain rows with largest pivots in LU factorisation. AKA Leja sequence.
def get_lu_row_pivoting(Ao, number_of_subsamples): A = Ao.copy() P = lu(A)[0] z = np.where(P==1)[1][:number_of_subsamples] return z
[ "def fattorizzazione_lu_pivot(A):\n\n def swap_rows(M, r1, r2):\n M[[r1, r2], :] = M[[r2, r1], :]\n\n m, n = A.shape\n if m != n:\n print(\"Matrice non quadrata\")\n return [], [], [], False\n\n U = A.copy()\n P = np.eye(n)\n for k in range(n - 1):\n if U[k, k] == 0:\n print(\"Elemento diagonale nullo\")\n return [], [], [], False\n for i in range(k + 1, n):\n pivot = k + np.argmax(abs(U[k:, k]))\n if k != pivot:\n swap_rows(U, k, pivot)\n swap_rows(P, k, pivot)\n U[i, k] /= U[k, k]\n for j in range(k + 1, n):\n U[i, j] -= U[i, k] * U[k, j]\n\n L = np.tril(U, -1) + np.eye(n)\n U = np.triu(U)\n return L, U, P, True", "def max_tableau90 (t):\n if len(t)==0:\n return None\n m=0\n for i in range (len(t)):\n if t[i]>t[m]:\n m=i\n return m", "def lowrank_matricize(self):\n\n\t\tU, l = self.U, self.lmbda\n\t\tdim = self.ndim\n\t\t\n\t\tulst, vlst = [], []\n\t\tL = np.diag(l)\n\t\t\n\t\tfor n in range(dim):\n\t\t\tlst = list(range(n)) + list(range(n + 1, dim))\n\n\t\t\tutemp = [U[l] for l in lst]\n\t\t\tmat = khatrirao(tuple(utemp), reverse = True).conj().T\n\n\t\t\t\n\t\t\tulst.append(U[n])\n\t\t\tvlst.append(dot(L,mat))\n\n\t\treturn ulst, vlst", "def PartialPivot(A,v):\r\n\r\n N = len(v)\r\n \r\n # Gaussian elimination\r\n for m in range(N):\r\n heads = A[::,m] #collecting leading elements of the m-th stel in the elimination to ultimately select a good candidate. \r\n abs_heads = list(abs(heads))\r\n winning = abs_heads.index(max(abs_heads))\r\n if heads[m] == 0:\r\n A[m, :], A[winning, :] = copy(A[winning, :]), copy(A[m, :])\r\n v[m], v[winning] = copy(v[winning]), copy(v[m])\r\n else:\r\n pass\r\n # Divide by the diagonal element\r\n div = A[m,m]\r\n A[m,:] /= div\r\n v[m] /= div\r\n \r\n # Now subtract from the lower rows\r\n for i in range(m+1,N):\r\n mult = A[i,m]\r\n A[i,:] -= mult*A[m,:]\r\n v[i] -= mult*v[m]\r\n \r\n # Backsubstitution\r\n x = empty(N,float)\r\n for m in range(N-1,-1,-1):\r\n x[m] = v[m]\r\n for i in range(m+1,N):\r\n x[m] -= A[m,i]*x[i]\r\n return x", "def raw_max_hairpin(seq):\n length = len(seq)\n score = 0\n loop_size = 3\n start_index = loop_size + 2 \n # Start at 5:\n # * * * * * * * * * (Original sequence and index)\n # 1 2 3 4 5 6 7 8 9\n\n # 3 2 1 \n # * * * (First possible loop)\n # 4 * | |\n # * * * * * \n # 5 6 7 8 9 \n # Thus top = 2 1 \n # bottom = 6 7 8 9\n for index in range(start_index,length):\n # only consider loop of size 3\n # smaller loop are assummed to be sterically impossible\n # and case where top and bottom with\n # only 1 bp is not considered\n top = seq[:index-loop_size][::-1]\n bottom = seq[index:]\n new_score = weighted_num_complement(top,bottom,\n gc_weight = self.gc_weight)\n if new_score > score:\n score = new_score\n return score", "def llull(profile):\n \n candidates = profile.candidates\n llull_scores = {c:len([1 for c2 in candidates if profile.margin(c,c2) >= 0])\n for c in candidates}\n max_llull_score = max(llull_scores.values())\n return sorted([c for c in candidates if llull_scores[c] == max_llull_score])", "def maximum_tableau(t):\n assert len(t) > 0 , \"COMPLETE OR PERISH\"\n m = 0\n for i in range(len(t)):\n if t[i] > t[m]:\n m = i\n print(m)\n return m", "def max_fold_enrichment (self):\n peaks = self.peaks\n chrs = peaks.keys()\n chrs.sort()\n x = 0\n for chrom in chrs:\n if peaks[chrom]:\n m = max([i[7] for i in peaks[chrom]])\n if m>x:\n x=m\n return x", "def relu(Z):\r\n \r\n A = np.maximum(0, Z)\r\n return A", "def fattorizzazione_lu_no_pivot(A):\n m, n = A.shape\n if m != n:\n print(\"Matrice non quadrata\")\n return [], [], False\n\n U = A.copy()\n for k in range(n - 1):\n if U[k, k] == 0:\n print(\"Elemento diagonale nullo\")\n return [], [], False\n for i in range(k + 1, n):\n U[i, k] /= U[k, k]\n for j in range(k + 1, n):\n U[i, j] -= U[i, k] * U[k, j]\n\n L = np.tril(U, -1) + np.eye(n)\n U = np.triu(U)\n return L, U, True", "def quicksort_choose_last_as_pivot(self, ul):\n\n if len(ul) < 2:\n return ul, 0\n\n pivot_idx = len(ul) - 1\n pivot = ul[pivot_idx]\n\n START_IDX = 1\n idx_include_greater_than_pivot = START_IDX\n\n # TODO\n# print(\"before sorting: \", ul)\n\n # Swap pivot to first element to ensure same comparison counts\n tmp = ul[0]\n ul[0] = pivot\n ul[pivot_idx] = tmp\n pivot_idx = 0\n\n # TODO\n# print(\"swapped pivot: \", ul)\n\n for idx in range(START_IDX, len(ul)):\n if ul[idx] < pivot and idx != idx_include_greater_than_pivot:\n tmp = ul[idx_include_greater_than_pivot]\n ul[idx_include_greater_than_pivot] = ul[idx]\n ul[idx] = tmp\n idx_include_greater_than_pivot += 1\n elif ul[idx] < pivot:\n idx_include_greater_than_pivot += 1\n\n # TODO\n# print(\"after sorting: \", ul)\n\n new_pivot_idx = idx_include_greater_than_pivot - 1\n tmp = ul[new_pivot_idx]\n ul[new_pivot_idx] = pivot\n ul[pivot_idx] = tmp\n\n # TODO\n# print(\"after swapping pivot:\", ul)\n\n comp_count = len(ul) - 1\n\n # Remaining partitions need sorting\n # Check left\n if new_pivot_idx > 1:\n ul[:new_pivot_idx], tmp_count_left = \\\n self.quicksort_choose_last_as_pivot(ul[:new_pivot_idx])\n comp_count += tmp_count_left\n\n # Check right\n if new_pivot_idx < len(ul) - 1:\n ul[new_pivot_idx+1:], tmp_count_right = \\\n self.quicksort_choose_last_as_pivot(ul[new_pivot_idx+1:])\n comp_count += tmp_count_right\n\n return ul, comp_count", "def lu_solve(self, LU_data, LU_pivots): # real signature unknown; restored from __doc__\n pass", "def relu(z):\n return np.maximum(0, z)", "def max_pchembl_val():\n t_m_pairs = make_t_m_pairs('max_pchembl_value')\n return t_m_pairs", "def estimate_lmax(L, sparse_flag=True, dummy=False):\n\n if dummy:\n return 2.0\n\n if L.shape[0] == 0:\n return\n\n L = deal_with_sparse(L, sparse_flag)\n\n try:\n if sparse_flag:\n lmax = sparse.linalg.eigs(L, k=1, tol=5e-3, ncv=10)[0][0]\n else:\n lmax = np.max(np.linalg.eigvals(L))\n except:\n lmax = 2. * np.max(L.diagonal())\n\n lmax = np.real(lmax)\n return lmax.sum()", "def clear_pivot_column(self, pivot):\n for k in range(pivot+1,self.n_rows):\n factor = -self.A[k,pivot]/self.A[pivot,pivot]\n self.add_to_row(pivot, k, factor)", "def test_pivot(self):\n x = []\n for i in range(300): \n x.append(random.randint(-100,100))\n self.sorter = QuickSort.QuickSort(x, verbose = False)\n j = self.sorter.pivot(0,len(self.sorter.getData()) -1)\n D = self.sorter.getData()\n for i in range(0,j):\n self.assertTrue(D[i] <= D[j])\n for i in range(j+1, len(D)):\n self.assertTrue(D[j] <= D[i])", "def pick_canonical_longest_transcript_from_ensembl_table(ensembl_rows, field):\n return ensembl_rows.sort_values('is_canonical protein_length gene_stable_id'.split(), ascending=False)[field].values[0]", "def pivot(A, first, last):\n raise Exception('TODO IMPLEMENT ME !')" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method adds a handler to ``evaluator`` to save ``n_saved`` of best models based on the metric (named by ``metric_name``) provided by ``evaluator`` (i.e. ``evaluator.state.metrics[metric_name]``). Models with highest metric value will be retained. The logic of how to store objects is delegated to ``save_handler``.
def gen_save_best_models_by_val_score( save_handler: Union[Callable, BaseSaveHandler], evaluator: Engine, models: Union[torch.nn.Module, Dict[str, torch.nn.Module]], metric_name: str, n_saved: int = 3, trainer: Optional[Engine] = None, tag: str = "val", score_sign: float = 1.0, **kwargs: Any, ) -> Checkpoint: global_step_transform = None if trainer is not None: global_step_transform = global_step_from_engine(trainer) if isinstance(models, nn.Module): to_save: Dict[str, nn.Module] = {"model": models} else: to_save = models best_model_handler = Checkpoint( to_save, save_handler, filename_prefix="best", n_saved=n_saved, global_step_transform=global_step_transform, score_name=f"{tag}_{metric_name.lower()}", score_function=get_default_score_fn(metric_name, score_sign=score_sign), **kwargs, ) evaluator.add_event_handler(Events.COMPLETED, best_model_handler) return best_model_handler
[ "def save_best_model_by_val_score(\n output_path: str,\n evaluator: Engine,\n model: torch.nn.Module,\n metric_name: str,\n n_saved: int = 3,\n trainer: Optional[Engine] = None,\n tag: str = \"val\",\n score_sign: float = 1.0,\n **kwargs: Any,\n) -> Checkpoint:\n return gen_save_best_models_by_val_score(\n save_handler=DiskSaver(dirname=output_path, require_empty=False),\n evaluator=evaluator,\n models=model,\n metric_name=metric_name,\n n_saved=n_saved,\n trainer=trainer,\n tag=tag,\n score_sign=score_sign,\n **kwargs,\n )", "def save_metrics(model_type, actual_value, models_prediction, db_model):\n if model_type == \"classification\":\n metrics = classification_eval(actual_value, actual_value)\n elif model_type == \"regression\":\n metrics = regressioneval(actual_value, actual_value)\n else:\n metrics = {}\n # json_metrics = json.dumps(metrics)\n\n db_model.metrics = metrics\n db_model.save()", "def save_best_model(self, _ = None, __ = None):\n max_val_blue = max(self.metrics_collector.val_blue_scores) \n last_val_blue = self.metrics_collector.val_blue_scores[-1]\n if last_val_blue == max_val_blue:\n torch.save(self.model, self.fpath_model)\n print (f\"best model so far saved\")\n else:\n print()", "def save_pool():\n for i in range(total_models):\n with open(os.path.join(pool_dir, 'model_{}.pickle'.format(i)), 'wb') as f:\n pickle.dump(current_pool[i], f)", "def save(self, folder, save_model=False):\n\n # Check paths\n create_missing_folders([folder])\n\n # Save ensemble settings\n logger.debug(\"Saving ensemble setup to %s/ensemble.json\", folder)\n settings = {\"estimator_type\": self.estimator_type, \"n_estimators\": self.n_estimators}\n\n with open(folder + \"/ensemble.json\", \"w\") as f:\n json.dump(settings, f)\n\n # Save estimators\n for i, estimator in enumerate(self.estimators):\n estimator.save(folder + \"/estimator_\" + str(i), save_model=save_model)", "def save_models(self, finally_epoch: int):\n for key, v in self.models_dict.items():\n save_path = os.path.join(self.summary.write_dir,\n f'{key}-{finally_epoch}.h5')\n if isinstance(v, k.Model):\n k.models.save_model(v, save_path)\n print(INFO, f'Save {key} as {save_path}')", "def persist_evaluation(\n estimator_name: str,\n dataset: str,\n evaluation: Dict[str, float],\n evaluation_path: str = \"./\",\n):\n path = Path(evaluation_path) / dataset / f\"{estimator_name}.json\"\n\n os.makedirs(path.parent, exist_ok=True)\n\n evaluation = {\n m: v for m, v in evaluation.items() if m in metrics_persisted\n }\n evaluation[\"dataset\"] = dataset\n evaluation[\"estimator\"] = estimator_name\n\n with open(path, \"w\") as f:\n f.write(json.dumps(evaluation, indent=4, sort_keys=True))", "def save_model(self, estimator: Any, metadata: Any) -> None: # type: ignore\n super().save_model(estimator, metadata)", "def save(self, folder, save_model=False):\n\n # Check paths\n Path(folder).mkdir(parents=True, exist_ok=True)\n\n # Save ensemble settings\n logger.debug(\"Saving ensemble setup to %s/ensemble.json\", folder)\n settings = {\"estimator_type\": self.estimator_type, \"n_estimators\": self.n_estimators}\n\n with open(f\"{folder}/ensemble.json\", \"w\") as f:\n json.dump(settings, f)\n\n # Save estimators\n for i, estimator in enumerate(self.estimators):\n estimator.save(f\"{folder}/estimator_{i}\", save_model=save_model)", "def save_model(self, save_folder: str, save_file: str):\n\n pass", "def save_model(self, name_addition=None):\n\t\tname = self.model_name\n\t\tif name_addition is not None:\n\t\t\tname += name_addition\n\n\t\tmodel_json = self.model.to_json()\n\t\twith open(name+'.json', 'w') as json_file:\n\t\t json_file.write(model_json)\n\n\t\tself.model.save_weights(name+'_weights.h5')\n\t\tprint('Model saved to disk with name: ' + name)", "def _register_evaluator_handlers(self, engine: Engine):\n\n engine.add_event_handler(Events.EPOCH_STARTED, self._evaluator_epoch_started)\n engine.add_event_handler(Events.EPOCH_COMPLETED, self._evaluator_epoch_completed)\n engine.add_event_handler(Events.ITERATION_COMPLETED, self._evaluator_iteration_completed)", "def save_model(self):\n saver = PolicySaver(self.agent.policy)\n saver.save(self.model_dir)", "def step(self,\n metric: float,\n epoch: int = None):\n\n # Get the current epoch, either explicitly or by counting from the\n # initial `last_epoch` the CheckpointManager was instantiated with.\n if not epoch:\n epoch = self.last_epoch + 1\n self.last_epoch = epoch\n\n # ---------------------------------------------------------------------\n # Save best model checkpoint if applicable\n # ---------------------------------------------------------------------\n\n # Check if the current model is the best we have seen so far according\n # to the provided metric and mode\n if (self.mode == \"min\" and metric < self.best_metric) or \\\n (self.mode == \"max\" and metric > self.best_metric):\n # Update the value for the best metric\n self.best_metric = metric\n \n # Save the current checkpoint as the best checkpoint\n self.save_checkpoint(checkpoint=self.get_current_checkpoint(),\n name='best.pth')\n\n # ---------------------------------------------------------------------\n # Save regular checkpoint (every `step_size` epochs)\n # ---------------------------------------------------------------------\n \n if (self.step_size > 0) and (self.last_epoch % self.step_size == 0):\n self.save_checkpoint(checkpoint=self.get_current_checkpoint(),\n name=f'epoch_{epoch}.pth')", "def save_model(self, estimator: Any, metadata: Optional[Any] = None) -> None:\n fname = \"model.joblib\" if metadata is None else f\"model-{metadata}.joblib\"\n joblib.dump(estimator, self.model_dir / fname)", "def save_model(self):\n torch.save(\n {\n 'epoch': self.epoch,\n 'model_state_dict': self.model.state_dict(),\n 'optimizer_state_dict': self.opt.state_dict(),\n 'acc': self.val_stats[\"acc\"],\n }, os.path.join(self.params.model_dir,\"snapshot.ep{}.pth\".format(self.epoch)))\n if self.val_stats[\"best_acc\"] <= self.val_stats[\"acc\"]:\n self.val_stats[\"best_acc\"] = self.val_stats[\"acc\"]\n self.val_stats[\"best_epoch\"] = self.epoch\n print(\"Saving model after epoch {}\".format(self.epoch))\n torch.save(\n {\n 'epoch': self.epoch,\n 'model_state_dict': self.model.state_dict(),\n 'acc': self.val_stats[\"acc\"],\n }, os.path.join(self.params.model_dir,\"model.acc.best\"))\n #else:\n # checkpoint = torch.load(os.path.join(self.params.model_dir,\"model.acc.best\"))\n # self.model.load_state_dict(checkpoint[\"model_state_dict\"])", "def enable_save_next_step_handlers(self, delay=120, filename=\"./.handler-saves/step.save\"):\n self.next_step_backend = FileHandlerBackend(self.next_step_backend.handlers, filename, delay)", "def mt_save(self, epoch, loss):\n if self.opt.SAVE_BEST_MODEL and loss < self.best_loss:\n log(\"Your best model is renewed\")\n if len(self.threads) > 0:\n self.threads[-1].join()\n self.threads.append(MyThread(self.opt, self, epoch, self.best_loss, loss))\n self.threads[-1].start()\n if self.opt.SAVE_BEST_MODEL and loss < self.best_loss:\n log(\"Your best model is renewed\")\n self.best_loss = loss", "def best_weights(\n filepath, metric=\"loss\", method=\"min\", key=\"saved\"\n) -> torchtools.CallbackProtocol:\n\n # pylint: disable=unused-argument\n def callback(model, summaries, collections):\n saved = False\n summaries_df = pd.json_normalize(summaries)\n best_idx = (\n summaries_df[metric].idxmax()\n if method == \"max\"\n else summaries_df[metric].idxmin()\n )\n if best_idx == len(summaries_df) - 1:\n model.save_weights(filepath)\n saved = True\n return {key: saved}\n\n return callback" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method adds a handler to ``evaluator`` to save on a disk ``n_saved`` of best models based on the metric (named by ``metric_name``) provided by ``evaluator`` (i.e. ``evaluator.state.metrics[metric_name]``). Models with highest metric value will be retained.
def save_best_model_by_val_score( output_path: str, evaluator: Engine, model: torch.nn.Module, metric_name: str, n_saved: int = 3, trainer: Optional[Engine] = None, tag: str = "val", score_sign: float = 1.0, **kwargs: Any, ) -> Checkpoint: return gen_save_best_models_by_val_score( save_handler=DiskSaver(dirname=output_path, require_empty=False), evaluator=evaluator, models=model, metric_name=metric_name, n_saved=n_saved, trainer=trainer, tag=tag, score_sign=score_sign, **kwargs, )
[ "def gen_save_best_models_by_val_score(\n save_handler: Union[Callable, BaseSaveHandler],\n evaluator: Engine,\n models: Union[torch.nn.Module, Dict[str, torch.nn.Module]],\n metric_name: str,\n n_saved: int = 3,\n trainer: Optional[Engine] = None,\n tag: str = \"val\",\n score_sign: float = 1.0,\n **kwargs: Any,\n) -> Checkpoint:\n global_step_transform = None\n if trainer is not None:\n global_step_transform = global_step_from_engine(trainer)\n\n if isinstance(models, nn.Module):\n to_save: Dict[str, nn.Module] = {\"model\": models}\n else:\n to_save = models\n\n best_model_handler = Checkpoint(\n to_save,\n save_handler,\n filename_prefix=\"best\",\n n_saved=n_saved,\n global_step_transform=global_step_transform,\n score_name=f\"{tag}_{metric_name.lower()}\",\n score_function=get_default_score_fn(metric_name, score_sign=score_sign),\n **kwargs,\n )\n evaluator.add_event_handler(Events.COMPLETED, best_model_handler)\n\n return best_model_handler", "def save_metrics(model_type, actual_value, models_prediction, db_model):\n if model_type == \"classification\":\n metrics = classification_eval(actual_value, actual_value)\n elif model_type == \"regression\":\n metrics = regressioneval(actual_value, actual_value)\n else:\n metrics = {}\n # json_metrics = json.dumps(metrics)\n\n db_model.metrics = metrics\n db_model.save()", "def persist_evaluation(\n estimator_name: str,\n dataset: str,\n evaluation: Dict[str, float],\n evaluation_path: str = \"./\",\n):\n path = Path(evaluation_path) / dataset / f\"{estimator_name}.json\"\n\n os.makedirs(path.parent, exist_ok=True)\n\n evaluation = {\n m: v for m, v in evaluation.items() if m in metrics_persisted\n }\n evaluation[\"dataset\"] = dataset\n evaluation[\"estimator\"] = estimator_name\n\n with open(path, \"w\") as f:\n f.write(json.dumps(evaluation, indent=4, sort_keys=True))", "def save_best_model(self, _ = None, __ = None):\n max_val_blue = max(self.metrics_collector.val_blue_scores) \n last_val_blue = self.metrics_collector.val_blue_scores[-1]\n if last_val_blue == max_val_blue:\n torch.save(self.model, self.fpath_model)\n print (f\"best model so far saved\")\n else:\n print()", "def save_model(self, name_addition=None):\n\t\tname = self.model_name\n\t\tif name_addition is not None:\n\t\t\tname += name_addition\n\n\t\tmodel_json = self.model.to_json()\n\t\twith open(name+'.json', 'w') as json_file:\n\t\t json_file.write(model_json)\n\n\t\tself.model.save_weights(name+'_weights.h5')\n\t\tprint('Model saved to disk with name: ' + name)", "def save_pool():\n for i in range(total_models):\n with open(os.path.join(pool_dir, 'model_{}.pickle'.format(i)), 'wb') as f:\n pickle.dump(current_pool[i], f)", "def save_models(self, finally_epoch: int):\n for key, v in self.models_dict.items():\n save_path = os.path.join(self.summary.write_dir,\n f'{key}-{finally_epoch}.h5')\n if isinstance(v, k.Model):\n k.models.save_model(v, save_path)\n print(INFO, f'Save {key} as {save_path}')", "def save_recommender(model,filepath):\n model.save(filepath)", "def save_bestk(current_best,k):\n## if os.access('%s_best%d.blif'%(f_name,k),os.R_OK):\n## res = get_bestk_value(k)\n## else: \n res = current_best\n if n_nodes() < res:\n res = n_nodes()\n abc('write_blif %s_best%d.blif'%(f_name,k))\n print '\\n*** best%d for %s *** = %d\\n'%(k,f_name,res)\n assert check_blif(),'inequivalence'\n return res", "def save(self, folder, save_model=False):\n\n # Check paths\n create_missing_folders([folder])\n\n # Save ensemble settings\n logger.debug(\"Saving ensemble setup to %s/ensemble.json\", folder)\n settings = {\"estimator_type\": self.estimator_type, \"n_estimators\": self.n_estimators}\n\n with open(folder + \"/ensemble.json\", \"w\") as f:\n json.dump(settings, f)\n\n # Save estimators\n for i, estimator in enumerate(self.estimators):\n estimator.save(folder + \"/estimator_\" + str(i), save_model=save_model)", "def save(self, name) -> None:\n self.actor_model.save_weights('actor' + name)\n self.critic_model.save_weights('critic' + name)", "def best_weights(\n filepath, metric=\"loss\", method=\"min\", key=\"saved\"\n) -> torchtools.CallbackProtocol:\n\n # pylint: disable=unused-argument\n def callback(model, summaries, collections):\n saved = False\n summaries_df = pd.json_normalize(summaries)\n best_idx = (\n summaries_df[metric].idxmax()\n if method == \"max\"\n else summaries_df[metric].idxmin()\n )\n if best_idx == len(summaries_df) - 1:\n model.save_weights(filepath)\n saved = True\n return {key: saved}\n\n return callback", "def save_model(self, estimator: Any, metadata: Any) -> None: # type: ignore\n super().save_model(estimator, metadata)", "def save_metrics(self):\n if not os.path.exists(\"metrics\"):\n os.mkdir(\"metrics\")\n with open(\"metrics/trainingloss.metric\", \"w+\") as f:\n json.dump(str(self.train_loss), f)\n with open(\"metrics/testloss.metric\", \"w+\") as f:\n json.dump(str(self.test_loss), f)\n with open(\"metrics/trainingaccuracy.metric\", \"w+\") as f:\n json.dump(str(self.train_accuracy), f)\n with open(\"metrics/testaccuracy.metric\", \"w+\") as f:\n json.dump(str(self.test_accuracy), f)", "def save(self, folder, save_model=False):\n\n # Check paths\n Path(folder).mkdir(parents=True, exist_ok=True)\n\n # Save ensemble settings\n logger.debug(\"Saving ensemble setup to %s/ensemble.json\", folder)\n settings = {\"estimator_type\": self.estimator_type, \"n_estimators\": self.n_estimators}\n\n with open(f\"{folder}/ensemble.json\", \"w\") as f:\n json.dump(settings, f)\n\n # Save estimators\n for i, estimator in enumerate(self.estimators):\n estimator.save(f\"{folder}/estimator_{i}\", save_model=save_model)", "def save_weights(self, h5_filename):\n self._model.save_weights(h5_filename)", "def save_model(self, save_folder: str, save_file: str):\n\n pass", "def save_bestind(mode, run, enemies, best_ind, avg_best_fitness):\n map_name = f'{mode}_enemies_{str(enemies)}'\n \n with open(map_name + '/' + mode + str(run) + '_best_' + str(enemies) + \"_avg_\" + str(avg_best_fitness), \"wb\") as file:\n pickle.dump(best_ind, file)", "def saveModelMetrics(self, file_path:str):\n print('INFO: Saving model metrics to: ' + file_path)\n metrics = {\n \"training\":\n {\n \"accuracy\": np.asarray(self.training_metrics_accuracy),\n \"loss\": np.asarray(self.training_metrics_loss),\n },\n \"test\":\n {\n \"accuracy\": np.asarray(self.test_metrics_accuracy),\n \"loss\": np.asarray(self.test_metrics_loss),\n },\n }\n\n\n with open(file_path, \"w\") as write_file:\n json.dump(metrics, write_file,cls=NumpyEncoder, indent=4)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method setups early stopping handler based on the score (named by `metric_name`) provided by `evaluator`. Metric value should increase in order to keep training and not early stop.
def add_early_stopping_by_val_score( patience: int, evaluator: Engine, trainer: Engine, metric_name: str, score_sign: float = 1.0, ) -> EarlyStopping: es_handler = EarlyStopping( patience=patience, score_function=get_default_score_fn(metric_name, score_sign=score_sign), trainer=trainer ) evaluator.add_event_handler(Events.COMPLETED, es_handler) return es_handler
[ "def build_early_stopping_callback(name, params, outdir='out'):\n if name == 'basic':\n patience_loss = params['patience_loss']\n patience = params['patience']\n callback = EarlyStopping(monitor=patience_loss,\n patience=patience,\n verbose=1,\n mode='auto')\n return callback\n elif name == 'none':\n return Dummy()", "def early_stopping(self) -> float:\n return self.scores[self.early_stop][-1]", "def test_init_rule(self) -> None:\n\n hook = EarlyStoppingHook(interval=5)\n with pytest.raises(KeyError):\n hook._init_rule(\"Invalid Key\", \"Invalid Indicator\")\n with pytest.raises(ValueError):\n hook._init_rule(None, \"Invalid Indicator\")\n hook._init_rule(\"greater\", \"acc\")\n assert hook.rule == \"greater\"\n assert hook.key_indicator == \"acc\"\n assert hook.compare_func(5, 9) is False\n hook._init_rule(\"less\", \"loss\")\n assert hook.rule == \"less\"\n assert hook.key_indicator == \"loss\"\n assert hook.compare_func(5, 9) is True", "def _update_trainer_metrics(self, metric_name: str, new_value: torch.tensor) -> None:\n self._trainer_metrics[metric_name] = self._trainer_metrics.get(metric_name, Average())\n self._trainer_metrics[metric_name](new_value.detach().cpu())", "def early_stopping_queue_and_trial_tracker() -> DSATTrialTracker:\n args = copy.deepcopy(DEFAULT_ARGS_DICT[\"_test\"])\n args.early_stopping = 3\n _, trial_tracker = queue_and_trial_tracker_builder(args)\n # One successful initial trial.\n trial = trial_tracker.queue.popleft()\n assert trial.searcher_metric_name\n trial_tracker.update_trial_metric(trial, {trial.searcher_metric_name: 0.0})\n for _ in range(args.early_stopping):\n trial = trial_tracker.queue.popleft()\n trial_tracker.report_trial_early_exit(trial)\n return trial_tracker", "def on_loss_calculation_start(self, training_context):\n\n pass", "def default_callback(self):\n raise ScoreExceededError(\"Score has been exceeded!\")", "def check_stopping(self, eval_result):\n\n if isinstance(self.metric, str):\n eval_value = eval_result[self.head][self.metric]\n else:\n eval_value = self.metric(eval_result)\n self.eval_values.append(float(eval_value))\n stopprocessing, savemodel = False, False\n if len(self.eval_values) <= self.min_evals:\n return stopprocessing, savemodel, eval_value\n if self.mode == \"min\":\n delta = self.best_so_far - eval_value\n else:\n delta = eval_value - self.best_so_far\n if delta > self.min_delta:\n self.best_so_far = eval_value\n self.n_since_best = 0\n if self.save_dir:\n savemodel = True\n else:\n self.n_since_best += 1\n if self.n_since_best > self.patience:\n stopprocessing = True\n return stopprocessing, savemodel, eval_value", "def check_learning_achieved(\n tune_results: \"tune.ResultGrid\",\n min_value,\n evaluation=False,\n metric: str = \"episode_reward_mean\",\n):\n # Get maximum reward of all trials\n # (check if at least one trial achieved some learning)\n recorded_values = [\n (row[metric] if not evaluation else row[f\"evaluation/{metric}\"])\n for _, row in tune_results.get_dataframe().iterrows()\n ]\n best_value = max(recorded_values)\n if best_value < min_value:\n raise ValueError(f\"`{metric}` of {min_value} not reached!\")\n print(f\"`{metric}` of {min_value} reached! ok\")", "def training_step(self, batch, batch_idx):\n x, y = batch\n if self.auxiliary_loss_weight:\n y_hat, y_aux = self(x)\n loss_main = self.criterion(y_hat, y)\n loss_aux = self.criterion(y_aux, y)\n self.log('train_loss_main', loss_main)\n self.log('train_loss_aux', loss_aux)\n loss = loss_main + self.auxiliary_loss_weight * loss_aux\n else:\n y_hat = self(x)\n loss = self.criterion(y_hat, y)\n self.log('train_loss', loss, prog_bar=True)\n for name, metric in self.metrics.items():\n self.log('train_' + name, metric(y_hat, y), prog_bar=True)\n return loss", "def step(self,\n metric: float,\n epoch: int = None):\n\n # Get the current epoch, either explicitly or by counting from the\n # initial `last_epoch` the CheckpointManager was instantiated with.\n if not epoch:\n epoch = self.last_epoch + 1\n self.last_epoch = epoch\n\n # ---------------------------------------------------------------------\n # Save best model checkpoint if applicable\n # ---------------------------------------------------------------------\n\n # Check if the current model is the best we have seen so far according\n # to the provided metric and mode\n if (self.mode == \"min\" and metric < self.best_metric) or \\\n (self.mode == \"max\" and metric > self.best_metric):\n # Update the value for the best metric\n self.best_metric = metric\n \n # Save the current checkpoint as the best checkpoint\n self.save_checkpoint(checkpoint=self.get_current_checkpoint(),\n name='best.pth')\n\n # ---------------------------------------------------------------------\n # Save regular checkpoint (every `step_size` epochs)\n # ---------------------------------------------------------------------\n \n if (self.step_size > 0) and (self.last_epoch % self.step_size == 0):\n self.save_checkpoint(checkpoint=self.get_current_checkpoint(),\n name=f'epoch_{epoch}.pth')", "def update_metric(self, trainer, new_value: float, epoch: int, disk_backup_filename: str) -> None:\n LogUtil.info(f\"*** After E{epoch}, validation accuracy = {new_value:.6f} \"\n f\"vs. {self.total_metric_value:.6f} on the previous epoch.\")\n if new_value > self.total_metric_value:\n LogUtil.info(\"*** Saving parameters.\")\n trainer.save_params()\n trainer.save_params_to_disk(disk_backup_filename)\n self.total_metric_value = new_value\n else:\n LogUtil.info(\"*** Restoring parameters and halting.\")\n trainer.restore_params()\n self.should_stop = True", "def start_or_resume_from_checkpoint():\n max_checkpoint_iteration = get_last_checkpoint_iteration()\n\n obsv_dim, action_dim, continuous_action_space = get_env_space()\n actor = Actor(obsv_dim,\n action_dim,\n continuous_action_space=continuous_action_space,\n trainable_std_dev=hp.trainable_std_dev,\n init_log_std_dev=hp.init_log_std_dev)\n critic = Critic(obsv_dim)\n var_critic = Var_Critic(obsv_dim)\n\n actor_optimizer = optim.AdamW(actor.parameters(), lr=hp.actor_learning_rate)\n critic_optimizer = optim.AdamW(critic.parameters(), lr=hp.critic_learning_rate)\n\n var_critic_optimizer = optim.AdamW(var_critic.parameters(), lr=hp.var_critic_learning_rate)\n\n stop_conditions = StopConditions()\n\n # If max checkpoint iteration is greater than zero initialise training with the checkpoint.\n if max_checkpoint_iteration > 0:\n actor_state_dict, critic_state_dict, var_critic_state_dict, \\\n actor_optimizer_state_dict, critic_optimizer_state_dict, \\\n var_critic_optimizer_state_dict, stop_conditions = load_checkpoint(max_checkpoint_iteration)\n\n actor.load_state_dict(actor_state_dict, strict=True)\n critic.load_state_dict(critic_state_dict, strict=True)\n var_critic.load_state_dict(var_critic_state_dict, strict=True)\n\n actor_optimizer.load_state_dict(actor_optimizer_state_dict)\n critic_optimizer.load_state_dict(critic_optimizer_state_dict)\n var_critic_optimizer.load_state_dict(var_critic_optimizer_state_dict)\n\n '''We have to move manually move optimizer states to \n TRAIN_DEVICE manually since optimizer doesn't yet have a \"to\" method.#'''\n\n for state in actor_optimizer.state.values():\n for k, v in state.items():\n if isinstance(v, torch.Tensor):\n state[k] = v.to(TRAIN_DEVICE)\n\n for state in critic_optimizer.state.values():\n for k, v in state.items():\n if isinstance(v, torch.Tensor):\n state[k] = v.to(TRAIN_DEVICE)\n\n for state in var_critic_optimizer.state.values():\n for k, v in state.items():\n if isinstance(v, torch.Tensor):\n state[k] = v.to(TRAIN_DEVICE)\n\n return actor, critic, var_critic, actor_optimizer, critic_optimizer, var_critic_optimizer, \\\n max_checkpoint_iteration, stop_conditions", "def set_callback_metric(self, metric: Union[str, Callable], greater_is_better: Optional[bool]=None, metric_params: Optional[Dict]=None, task_name: Optional[str]=None):\n if self.loss in _sk_force_metric:\n metric, greater_is_better, metric_params = _sk_force_metric[self.loss]\n logger.info2('For sklearn {0} callback metric switched to {1}'.format(self.loss, metric))\n super().set_callback_metric(metric, greater_is_better, metric_params, task_name)", "def on_optimization_step_start(self, training_context):\n\n pass", "def test_init_rule(self) -> None:\n\n hook = ReduceLROnPlateauLrUpdaterHook(interval=5, min_lr=1e-5)\n with pytest.raises(KeyError):\n hook._init_rule(\"Invalid Key\", \"Invalid Indicator\")\n with pytest.raises(ValueError):\n hook._init_rule(None, \"Invalid Indicator\")\n hook._init_rule(\"greater\", \"acc\")\n assert hook.rule == \"greater\"\n assert hook.key_indicator == \"acc\"\n assert hook.compare_func(5, 9) is False\n hook._init_rule(\"less\", \"loss\")\n assert hook.rule == \"less\"\n assert hook.key_indicator == \"loss\"\n assert hook.compare_func(5, 9) is True", "def before_train_iter(self, trainer):\n self.before_iter(trainer)", "def every_before_train_step_callback_fn(self, sess):\n pass", "def update(self, epoch, avg_seg_loss_train, avg_nonadjloss_train,\n avg_seg_loss_val, has_train_nan):\n # Init lambda after first epoch\n if epoch == 0:\n self.lambda_ = 0.3 * (avg_seg_loss_train / avg_nonadjloss_train)\n self.good_seg_metric_value = avg_seg_loss_val\n elif epoch == self.tuning_epoch:\n self.update_counter = 4\n\n # if no issue was detected, check dice and update\n if has_train_nan is False and self.train_nan_count < 3:\n # automatic update of lambda\n if epoch < self.tuning_epoch:\n if self.good_seg_metric_value - avg_seg_loss_val >= 0.02:\n print('--High decrease in dice detected, no lambda update for 5 epochs')\n self.update_counter = 0\n elif self.good_seg_metric_value - avg_seg_loss_val >= 0.01:\n print('--Small decrease in dice detected')\n\n elif epoch > 0:\n if self.update_counter >= 4:\n print('--Increase lambda')\n self.lambda_ *= self.lambda_factor\n self.update_counter = 0\n else:\n self.update_counter += 1\n\n self.train_nan_count = 0\n else:\n dice_diff = self.good_seg_metric_value - avg_seg_loss_val\n if dice_diff > 0:\n if self.update_counter >= 4:\n print('--Decrease lambda to improve dice {:.4f}'.format(dice_diff))\n self.lambda_ *= 0.9\n self.update_counter = 0\n else:\n print('--Dice is not good enough {:.4f}'.format(dice_diff))\n self.update_counter += 1\n else:\n self.update_counter = 0\n\n if avg_seg_loss_val >= self.good_seg_metric_value - 0.01:\n print('--Logging as good epoch')\n self.last_good_epoch = epoch\n\n # if an error was detected decrease factor\n elif has_train_nan is True and self.train_nan_count < 3:\n print('--Decreasing lambda factor')\n self.lambda_ *= 0.9\n self.lambda_factor *= 0.98\n self.update_counter = 0\n self.train_nan_count += 1\n\n if epoch - self.last_good_epoch >= 5 and (epoch - self.last_good_epoch) % 5 == 0:\n if epoch - self.last_good_epoch >= 10:\n print('--Insufficient dice for 15 epochs, reboot')\n print('--Decreasing lambda factor')\n self.lambda_ *= 0.9\n return -2\n else:\n print('--Decreasing lambda because of deacreasing dice')\n self.lambda_ *= 0.95\n\n self.lambda_factor *= 0.98\n self.update_counter = 0\n\n if self.lambda_factor < 1:\n print('lambda_factor is < 1, ending.')\n return -1\n elif self.train_nan_count >= 3:\n print('--Too many errors, restart from a previous epoch')\n return -2\n else:\n return 0" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a component of the given type to the GameObject
def add_component(self, component: GameObjectComponent): self.__component_container.append(component)
[ "def add_component(self, component):\n self.components.append(component)", "def add(self, component):\n # check if component is valid\n if component == None:\n return False\n # according to the object type the component will be added\n if type(component) == place.Place:\n return self.add_place(component)\n if type(component) == transition.Transition:\n return self.add_transition(component)\n if type(component) == arc.Arc or type(component) == inhibitory_arc.InhibitoryArc or type(component) == test_arc.TestArc:\n return self.add_arc(component)\n return False", "def add_component(self, component):\r\n self.subcomponents.append(component)", "def addType(self, type):\n\t\tself.types.append(type)", "def add_component(self, component):\n self.__components.append(copy.deepcopy(component))", "def register_component(component: _ComponentType, component_types: typing.Set[str]) -> None:\n # if component_types.intersection({\"hardware_source_manager\", \"stem_controller\", \"hardware_source\", \"scan_hardware_source\", \"scan_device\", \"document_model\"}):\n # print(f\">> REGISTER {component} {component_types}\")\n # if component_types.intersection({\"stem_controller\"}):\n # print(f\">> REGISTER {component} {component_types}\")\n # import traceback\n # traceback.print_stack()\n ComponentManager().register(component, component_types)", "def _load_and_add_components(\n self,\n component_type: ComponentType,\n resources: Resources,\n agent_name: str,\n **kwargs,\n ) -> None:\n for configuration in self._package_dependency_manager.get_components_by_type(\n component_type\n ).values():\n if configuration.is_abstract_component:\n load_aea_package(configuration)\n continue\n\n if configuration in self._component_instances[component_type].keys():\n component = self._component_instances[component_type][configuration]\n if configuration.component_type != ComponentType.SKILL:\n component.logger = cast(\n logging.Logger, make_logger(configuration, agent_name)\n )\n else:\n configuration = deepcopy(configuration)\n _logger = make_logger(configuration, agent_name)\n component = load_component_from_config(\n configuration, logger=_logger, **kwargs\n )\n\n resources.add_component(component)", "def addChildType(self, typeToAdd: 'SoType') -> \"void\":\n return _coin.SoNodeKitListPart_addChildType(self, typeToAdd)", "def add_object(self, game_object: GameObject) -> None:\n\n self.objects.append(game_object)", "def pushType(type):\n Ptypes.append(type)", "def add_object_type(self, name: str, objtype: ObjType) -> None:\n self.object_types[name] = objtype\n if objtype.roles:\n self._type2role[name] = objtype.roles[0]\n else:\n self._type2role[name] = ''\n\n for role in objtype.roles:\n self._role2type.setdefault(role, []).append(name)", "def add_item(self, name, type_, attr, react, dur, stage):\r\n assert type(name) == str and type(attr) == dict and type(react) == dict\\\r\n and type(dur) == int and type(type_) in constants.TYPES\r\n\r\n new_item = Item(name, type_, attr, react, dur)\r\n self.items[stage].append(new_item)", "def add(self, component):\n if len(self.track['reputation']) + len(self.track['diplomacy']) < self.tile_max:\n if isinstance(component, cp.ReputationTile):\n if len(self.track['reputation']) < self.reputation_max:\n self.track['reputation'].append(component)\n elif isinstance(component, cp.AmbassadorTile):\n if len(self.track['diplomacy']) < self.diplomacy_max:\n self.track['diplomacy'].append(component)", "def add_component(\n self,\n component_type: ComponentType,\n directory: PathLike,\n skip_consistency_check: bool = False,\n ) -> \"AEABuilder\":\n directory = Path(directory)\n configuration = ComponentConfiguration.load(\n component_type, directory, skip_consistency_check\n )\n self._check_can_add(configuration)\n # update dependency graph\n self._package_dependency_manager.add_component(configuration)\n configuration.directory = directory\n\n return self", "def add_component(self, entity_number, component):\n self.table[entity_number] = component\n if self.parent is not None:\n self.parent.add_component(entity_number, component)", "def add_node(self,node_type):\n #Our start node is more specific than this... Need to have another validation method\n if node_type not in node_types:\n raise Exception('node type must be one of greent.node_types')\n self.definition.node_types.append(node_type)", "def add(self, cname, **kwargs):\n # Load and immediately instantiate.\n component = get_component(cname)(**kwargs)\n # Part of the contract: we must add ourselves as an entity reference.\n component.entity = self.entity\n # Add for easy iteration as well as easy reference.\n self._index[component._cname] = component\n if component.doprocess:\n self._list.append(component)", "def SoGLRenderAction_addMethod(type: 'SoType', method: 'SoActionMethod') -> \"void\":\n return _coin.SoGLRenderAction_addMethod(type, method)", "def add(fieldType, tag=-1):\n ierr = c_int()\n api__result__ = lib.gmshModelMeshFieldAdd(\n c_char_p(fieldType.encode()),\n c_int(tag),\n byref(ierr))\n if ierr.value != 0:\n raise ValueError(\n \"gmshModelMeshFieldAdd returned non-zero error code: \",\n ierr.value)\n return api__result__" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to get a component from the GameObject of the specified type Will return an empty list if no component is found
def get_component(self, component_type): components = [] for component in self.__component_container: # Iterate through all components if isinstance(component, component_type): # If the component is of the required type add it to the list components.append(component) return components # Return the list
[ "def get_component(component_type: str) -> typing.Optional[typing.Any]:\n components = get_components_by_type(component_type)\n\n def attrgetter(attrname: str, default: typing.Optional[int] = None) -> typing.Callable[[typing.Any], int]:\n def inside(obj: typing.Any) -> int:\n return int(typing.cast(int, getattr(obj, attrname, default)))\n\n return inside\n\n sorted_components = sorted(components, key=attrgetter(\"priority\", 50), reverse=True)\n\n if len(sorted_components) > 0:\n return tuple(sorted_components)[0]\n\n return None", "def pick_component(self, enum_types: List[ComponentTypes]) -> Union[Component, None]:\n if not isinstance(enum_types, list):\n enum_types = [enum_types]\n\n for enum_type in enum_types:\n if enum_type in self.__components:\n return self.__components[enum_type]\n\n raise HostrayWebException(\n LocalCode_Component_Type_Not_Exist, enum_type)", "def find_component(self, block):\n obj = block\n for name, idx, types in reversed(self._cids):\n try:\n if len(idx) and idx != '**' and types.strip('*'):\n obj = getattr(obj, name)[idx]\n else:\n obj = getattr(obj, name)\n except KeyError:\n if '.' not in types:\n return None\n tList = ComponentUID.tList\n def _checkIntArgs(_idx, _t, _i):\n if _i == -1:\n try:\n return getattr(obj, name)[tuple(_idx)]\n except KeyError:\n return None\n _orig = _idx[_i]\n for _cast in tList:\n try:\n _idx[_i] = _cast(_orig)\n ans = _checkIntArgs(_idx, _t, _t.find('.',_i+1))\n if ans is not None:\n return ans\n except ValueError:\n pass\n _idx[_i] = _orig\n return None\n obj = _checkIntArgs(list(idx), types, types.find('.'))\n except AttributeError:\n return None\n return obj", "def test_get_system_by_component_type(self):\n game_services = create_entman_testing_services()\n entman = game_services.get_entity_manager()\n entity = entman.create_entity()\n component = MockComponent(entity, game_services, Config())\n entman.add_component(component)\n assert isinstance(entman.get_system_by_component_type(MockComponent), MockSystem)", "def get_component_by_name(self, name):\n\n for component in self.__component_container: # Iterate through all components\n if component.name == name: # If the component has the required name\n return component\n return None", "def find_by_type(\n self,\n type_: type | tuple[type, ...],\n member: str,\n ) -> list[T]:\n objects = [\n object_ for object_ in getattr(self._model, member)()\n if isinstance(object_, type_)\n ]\n return self._formulate(objects)", "def get_components(self, coord = None, component_type = None):\n if coord is None:\n if component_type is None:\n return self.hex_grid\n return dict([(coord, sector.get_components(component_type)) for coord,sector in self.hex_grid.iteritems()])\n if coord not in self.hex_grid:\n return None\n if component_type is Sector:\n return self.hex_grid[coord]\n if component_type is not None:\n return self.hex_grid[coord].get_components(component_type)\n return [self.hex_grid[coord]] + self.hex_grid[coord].get_components()", "def _get_object_by_type(results, type_value):\n return [obj for obj in results\n if obj._type == type_value]", "def _get_components(self, component_name):\n if component_name == '':\n return list()\n component_names = component_name.split(':')\n\n split_names = []\n for name in component_names:\n split_names.append(name)\n\n component_list = self.components\n try:\n for key in split_names:\n component_list = component_list[key]\n except (KeyError):\n logging.error(\"No entry for {}\".format(key))\n except (TypeError):\n pass\n\n return component_list", "def find_component(self, name, required=True):\n\n for component in self.components:\n if component.name == name:\n return component\n\n if required:\n self._missing_component(name)\n\n return None", "def create_primitive_type_components(pipeline_name: str) -> List[BaseComponent]:\n hello_world = HelloWorldComponent(word=pipeline_name)\n bye_world = ByeWorldComponent(hearing=hello_world.outputs['greeting'])\n\n return [hello_world, bye_world]", "def __get_component(self, components_name_list):\r\n\r\n components_list = []\r\n for comp in self.line.components:\r\n if comp.name in components_name_list:\r\n components_list.append(comp)\r\n return components_list", "def find_component(\n self, comp_id\n ) -> Room | Zone | Ventilation | HotWater | Circulation | None:\n for comp in self.data:\n if comp.id == comp_id:\n return comp\n return None", "def processes_by_type(cls, type_name):\n\t\tprocess_list = []\n\t\t\n\t\tfor obj in cls.processes:\n\t\t\tif type(type_name) == type(\"\"):\n\t\t\t\tif cls.processes[obj].__class__.__name__ == type_name:\n\t\t\t\t\tprocess_list.append(cls.processes[obj])\n\t\t\telse:\n\t\t\t\tif isinstance(cls.processes[obj], type_name):\n\t\t\t\t\tprocess_list.append(cls.processes[obj])\n\t\t\t\t\n\t\treturn process_list", "def find_components(self) -> None:\n pass", "async def get_object(self, obj_type: typing.Union[str, type], obj_id: typing.Optional[int] = None,\n **kwargs) -> typing.Union[typing.Type[Object], typing.List[typing.Type[Object]]]:\n if not isinstance(obj_type, str):\n if not obj_type.is_instantiable():\n raise TypeError(f\"The type {obj_type.__name__} is not instantiable!\")\n obj_type = obj_type.get_type()\n async with self._session.get(self.get_api_url(obj_type, obj_id, action=None, **kwargs)) as resp:\n data = (await resp.json())[\"d\"][\"results\"]\n if isinstance(data, list):\n return [TYPES_DICT[obj_type](self, obj_data) for obj_data in data]\n else:\n return TYPES_DICT[obj_type](self, (await resp.json())[\"d\"][\"results\"])", "def get_inventory_of_component(self, component):\n return None", "def check_component_type(component_type, component):\n\n # TODO stub\n return True", "def get_component(self, key):\n component = self.get_place(key)\n if component == None:\n component = self.get_transition(key)\n if component == None:\n component = self.get_arc(key)\n return component" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to get a component from the GameObject with the given name Will return None if there is no matched Component
def get_component_by_name(self, name): for component in self.__component_container: # Iterate through all components if component.name == name: # If the component has the required name return component return None
[ "def find_component(self, name, required=True):\n\n for component in self.components:\n if component.name == name:\n return component\n\n if required:\n self._missing_component(name)\n\n return None", "def get_component_by_name( app, name ):\n sa_session = app.model.context.current\n return sa_session.query( app.model.Component ) \\\n .filter( app.model.Component.table.c.name == name ) \\\n .first()", "def component(self, name):\n return self._component_map[name]", "def get(scene, name):\n for fbx_object in get_all(scene):\n if fbx_object.GetName() == name:\n return fbx_object\n\n return None", "def extract_model_component(self, model_name, component): \n assert(model_name in self.fitted_models), \"\\n[ERROR]: Invalid model name.\"\n model_fit = self.json[ self.fields.model_fits ][ model_name ]\n try:\n component = model_fit[component]\n except: \n raise KeyError(\"\\n[ERROR]: Invalid model component.\")\n \n return component", "def get_component(self, key):\n component = self.get_place(key)\n if component == None:\n component = self.get_transition(key)\n if component == None:\n component = self.get_arc(key)\n return component", "def find_component(\n self, comp_id\n ) -> Room | Zone | Ventilation | HotWater | Circulation | None:\n for comp in self.data:\n if comp.id == comp_id:\n return comp\n return None", "def get_component_class(name):\n return _COMPONENT_CLASSES[name]", "def find_component(self, block):\n obj = block\n for name, idx, types in reversed(self._cids):\n try:\n if len(idx) and idx != '**' and types.strip('*'):\n obj = getattr(obj, name)[idx]\n else:\n obj = getattr(obj, name)\n except KeyError:\n if '.' not in types:\n return None\n tList = ComponentUID.tList\n def _checkIntArgs(_idx, _t, _i):\n if _i == -1:\n try:\n return getattr(obj, name)[tuple(_idx)]\n except KeyError:\n return None\n _orig = _idx[_i]\n for _cast in tList:\n try:\n _idx[_i] = _cast(_orig)\n ans = _checkIntArgs(_idx, _t, _t.find('.',_i+1))\n if ans is not None:\n return ans\n except ValueError:\n pass\n _idx[_i] = _orig\n return None\n obj = _checkIntArgs(list(idx), types, types.find('.'))\n except AttributeError:\n return None\n return obj", "def get_actor_by_name(self, partialname):\n for actor in self.players:\n if partialname.lower() in actor.name.lower():\n return actor\n return None", "def get_component( app, id ):\n sa_session = app.model.context.current\n return sa_session.query( app.model.Component ).get( app.security.decode_id( id ) )", "def GetObjectWithName(name):\r\n nodeList = getAllNodes()\r\n for n in nodeList:\r\n if name in n.Name:\r\n return n\r\n return None", "def get_plugin_by_name(self, name: str) -> dict:\n plugins = self.get_plugins_by_name(name)\n if len(plugins) == 1:\n return plugins[0]\n elif len(plugins) == 0:\n return None\n else:\n return None", "def parse_component_name(filename):\n name, ext = os.path.splitext(os.path.split(filename)[-1])\n if ext.lower() in ['.c', '.cpp', '.cc', '.h']:\n return name\n return None", "def get_component(component_type: str) -> typing.Optional[typing.Any]:\n components = get_components_by_type(component_type)\n\n def attrgetter(attrname: str, default: typing.Optional[int] = None) -> typing.Callable[[typing.Any], int]:\n def inside(obj: typing.Any) -> int:\n return int(typing.cast(int, getattr(obj, attrname, default)))\n\n return inside\n\n sorted_components = sorted(components, key=attrgetter(\"priority\", 50), reverse=True)\n\n if len(sorted_components) > 0:\n return tuple(sorted_components)[0]\n\n return None", "def get_player(self, name):\n\n try:\n name = name.name\n except AttributeError: pass\n\n for i in self.players:\n if i.name == name:\n return i", "def collect_and_verify_name(self, component, modules_repo):\n if component is None:\n component = questionary.autocomplete(\n f\"{'Tool' if self.component_type == 'modules' else 'Subworkflow'} name:\",\n choices=sorted(modules_repo.get_avail_components(self.component_type, commit=self.sha)),\n style=nf_core.utils.nfcore_question_style,\n ).unsafe_ask()\n\n # Check that the supplied name is an available module/subworkflow\n if component and component not in modules_repo.get_avail_components(self.component_type, commit=self.sha):\n log.error(\n f\"{self.component_type[:-1].title()} '{component}' not found in list of available {self.component_type}.\"\n )\n log.info(f\"Use the command 'nf-core {self.component_type} list' to view available software\")\n return False\n\n if not modules_repo.component_exists(component, self.component_type, commit=self.sha):\n warn_msg = f\"{self.component_type[:-1].title()} '{component}' not found in remote '{modules_repo.remote_url}' ({modules_repo.branch})\"\n log.warning(warn_msg)\n return False\n\n return component", "async def get_game_by_name(self, name):\n raise NotImplementedError()", "def load_component(component_name, *args, **kwargs):\n path = dirname(abspath((stack()[1])[1]))\n return _load_component(path, component_name, *args, **kwargs)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the floored X position Returns int The floored X position of the GameObject
def get_x(self): return math.floor(self.position.x)
[ "def get_x(self):\r\n return self.get_3d_position()[\"position\"].x", "def get_pos_x(self):\n return self._position[0]", "def xposition(self):\n return self._xposition", "def OriginX(self) -> float:", "def get_xcoord(self, x):\n return (x - self.xlimits[0]) / self.dx", "def get_x_pos(self):\n if(type(self._x_pos) != float):\n self._logger.write(\"Error! x_pos must be of type float\")\n elif(self._x_pos == None):\n self._logger.write(\"Error! x_pos contains no value\")\n else:\n try:\n return self._x_pos\n except Exception as e:\n self._logger.write(\"Error! Could not fetch the x_pos: \\n %s\" % e)", "def current_x(self):\n return self._current_position[0]", "def correct_x_position(self, value=0):\n if self.COORD_X + value > self.BOUNDARIES[0] - self.PLAYER_WIDTH:\n return (self.COORD_X + value) - (self.BOUNDARIES[0] - self.PLAYER_WIDTH)\n elif self.COORD_X + value < 0 < self.COORD_X:\n return (self.COORD_X + value) + self.PLAYER_WIDTH\n\n return 0", "def x(self):\n return self.center[0]", "def border_box_x(self):\r\n return self.position_x + self.margin_left", "def get_start(self) -> int:\n return self.__pos_x", "def _xdist(self):\n\t\treturn self.geom.x - self.last.x", "def hole_offset_x(self):\n self._hole_offset_x = self._hole_params[3].ToString()\n return self._hole_offset_x", "def min_x(self):\n return self.origin[0]", "def xcoord(pt):\n return pt.x", "def content_box_x(self):\r\n return self.position_x + self.margin_left + self.padding_left + \\\r\n self.border_left_width", "def DisplayMinX(self) -> float:", "def get_min_x(self):\n\n return self.x0", "def getoriginx(self):\n return self.origin[0]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the floored Y position Returns int The floored Y position of the GameObject
def get_y(self): return math.floor(self.position.y)
[ "def get_y(self):\r\n return self.get_3d_position()[\"position\"].y", "def get_pos_y(self):\n return self._position[1]", "def getY(self):\n return self.pos.y", "def OriginY(self) -> float:", "def yposition(self):\n return self._yposition", "def get_ycoord(self, y):\n return (y - self.ylimits[0]) / self.dy", "def y(self):\n return self.center[1]", "def current_y(self):\n return self._current_position[1]", "def to_pygame(y_coord, height, obj_height):\n return height - y_coord - obj_height", "def y(self):\n return Tile.SIZE * (3 / 2) * self.r", "def to_pygame(y_coord, height):\n return height - y_coord", "def get_end(self) -> int:\n return self.__pos_y", "def get_y_pos(self):\n if(type(self._y_pos) != float):\n self._logger.write(\"Error! y_pos must be of type float\")\n elif(self._y_pos == None):\n self._logger.write(\"Error! y_pos contains no value\")\n else:\n try:\n return self._y_pos\n except Exception as e:\n self._logger.write(\"Error! Could not fetch the y_pos: \\n %s\" % e)", "def correct_y_position(self, value=0):\n if self.COORD_Y + value > self.BOUNDARIES[1] - self.PLAYER_HEIGHT:\n return (self.COORD_Y + value) - (self.BOUNDARIES[0] - self.PLAYER_HEIGHT)\n elif self.COORD_Y + value < 0 < self.COORD_Y:\n return (self.COORD_Y + value) + self.PLAYER_HEIGHT\n\n return 0", "def get_y_bot(self) -> float:\n return self.y_bar", "def _get_y(self) -> \"double\" :\n return _core.Point2D__get_y(self)", "def bottom_y(self):\n if self._bottom_y is None:\n max_y = 0\n \n for line_obj in self.line_objs:\n if line_obj.y1 > max_y:\n max_y = line_obj.y1\n \n if line_obj.y2 > max_y:\n max_y = line_obj.y2\n \n self._bottom_y = int(max_y)\n \n return self._bottom_y", "def DisplayMaxY(self) -> float:", "def get_y_velocity(self):\n return self.__dy" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Basic integration function using uniform sampling. The cube size is determined based on the fact that almost all the mass in a bivariate standar normal distribution is within 5,5 x 5,5.
def montecarlo_integration_uniform(f, n=1000): cube_size = 5 z1_trials = rnd.uniform(-cube_size, cube_size, n) z2_trials = rnd.uniform(-cube_size, cube_size, n) V = 2 * cube_size * 2 * cube_size integral = np.sum(f(z1_trials, z2_trials)) return V * integral / n
[ "def generate_integration(self, each_sample: int) -> float:\r\n x_rand = np.random.uniform(low=0, high=1.0, size=each_sample)\r\n x_rand = [self.f(i) for i in x_rand]\r\n\r\n result: float = round((self.high_bound-self.low_bound)\r\n * np.sum(x_rand)/each_sample, 5)\r\n return result", "def mc_integrate(f, mins, maxs, N=10000):\n #Cast mins and maxes to arrays\n mins = np.array(mins)\n maxs = np.array(maxs)\n\n #Get n, sample points, and volume\n n = len(mins)\n x = np.random.uniform(0,1,(n,N))\n V = np.prod(maxs-mins)\n\n #Put sample points in correct interval\n for i in range(n):\n x[i] = x[i]*(maxs[i] - mins[i]) + mins[i]\n\n #Evaluate sample points\n y = [f(x[:, i]) for i in range(N)]\n #Return volume\n return V * np.sum(y) / N", "def gaussian_3d(\n grid,\n mu_z,\n mu_y,\n mu_x,\n sigma_z,\n sigma_yx,\n voxel_size_z,\n voxel_size_yx,\n amplitude,\n background,\n precomputed=None):\n # get grid data to design a volume V\n meshgrid_z = grid[0]\n meshgrid_y = grid[1]\n meshgrid_x = grid[2]\n\n # use precomputed tables\n if precomputed is not None:\n # get tables\n table_erf_z = precomputed[0]\n table_erf_y = precomputed[1]\n table_erf_x = precomputed[2]\n\n # get indices for the tables\n i_z = np.abs(meshgrid_z - mu_z).astype(np.int64)\n i_y = np.abs(meshgrid_y - mu_y).astype(np.int64)\n i_x = np.abs(meshgrid_x - mu_x).astype(np.int64)\n\n # get precomputed values\n voxel_integral_z = table_erf_z[i_z, 1]\n voxel_integral_y = table_erf_y[i_y, 1]\n voxel_integral_x = table_erf_x[i_x, 1]\n\n # compute erf value\n else:\n # get voxel coordinates\n meshgrid_z_minus = meshgrid_z - voxel_size_z / 2\n meshgrid_z_plus = meshgrid_z + voxel_size_z / 2\n meshgrid_y_minus = meshgrid_y - voxel_size_yx / 2\n meshgrid_y_plus = meshgrid_y + voxel_size_yx / 2\n meshgrid_x_minus = meshgrid_x - voxel_size_yx / 2\n meshgrid_x_plus = meshgrid_x + voxel_size_yx / 2\n\n # compute gaussian function for each voxel (i, j, k) of volume V\n voxel_integral_z = _rescaled_erf(\n low=meshgrid_z_minus,\n high=meshgrid_z_plus,\n mu=mu_z,\n sigma=sigma_z)\n voxel_integral_y = _rescaled_erf(\n low=meshgrid_y_minus,\n high=meshgrid_y_plus,\n mu=mu_y,\n sigma=sigma_yx)\n voxel_integral_x = _rescaled_erf(\n low=meshgrid_x_minus,\n high=meshgrid_x_plus,\n mu=mu_x,\n sigma=sigma_yx)\n\n # compute 3-d gaussian values\n factor = amplitude / (voxel_size_yx ** 2 * voxel_size_z)\n voxel_integral = voxel_integral_z * voxel_integral_y * voxel_integral_x\n values = background + factor * voxel_integral\n\n return values", "def test_runup_sinusoid(self):\n\n points, vertices, boundary = anuga.rectangular_cross(20,20, len1=1., len2=1.)\n\n\n domain=Domain(points,vertices,boundary) # Create Domain\n domain.set_flow_algorithm('DE1')\n\n domain.set_name('runup_sinusoid_de1') # Output to file runup.sww\n domain.set_datadir('.') # Use current folder\n domain.set_quantities_to_be_stored({'stage': 2, 'xmomentum': 2, 'ymomentum': 2, 'elevation': 2})\n #domain.set_store_vertices_uniquely(True)\n \n #------------------\n # Define topography\n #------------------\n scale_me=1.0\n\n def topography(x,y):\n return (-x/2.0 +0.05*num.sin((x+y)*50.0))*scale_me\n\n def stagefun(x,y):\n stge=-0.2*scale_me #+0.01*(x>0.9)\n return stge\n\n domain.set_quantity('elevation',topography) \n domain.get_quantity('elevation').smooth_vertex_values()\n domain.set_quantity('friction',0.03) \n\n\n domain.set_quantity('stage', stagefun) \n domain.get_quantity('stage').smooth_vertex_values()\n\n\n #--------------------------\n # Setup boundary conditions\n #--------------------------\n Br=anuga.Reflective_boundary(domain) # Solid reflective wall\n\n #----------------------------------------------\n # Associate boundary tags with boundary objects\n #----------------------------------------------\n domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom':Br})\n\n #------------------------------\n #Evolve the system through time\n #------------------------------\n\n for t in domain.evolve(yieldstep=7.0,finaltime=7.0):\n #print domain.timestepping_statistics()\n #xx = domain.quantities['xmomentum'].centroid_values\n #yy = domain.quantities['ymomentum'].centroid_values\n #dd = domain.quantities['stage'].centroid_values - domain.quantities['elevation'].centroid_values\n\n #dd = (dd)*(dd>1.0e-03)+1.0e-03\n #vv = ( (xx/dd)**2 + (yy/dd)**2)**0.5\n #vv = vv*(dd>1.0e-03)\n #print 'Peak velocity is: ', vv.max(), vv.argmax()\n #print 'Volume is', sum(dd_raw*domain.areas)\n pass\n\n xx = domain.quantities['xmomentum'].centroid_values\n yy = domain.quantities['ymomentum'].centroid_values\n dd = domain.quantities['stage'].centroid_values - domain.quantities['elevation'].centroid_values\n #dd_raw=1.0*dd\n dd = (dd)*(dd>1.0e-03)+1.0e-03\n vv = ((xx/dd)**2 + (yy/dd)**2)**0.5\n\n assert num.all(vv<2.0e-02)", "def gauss(dim,width):\n x = np.arange(dim) - dim//2\n xy = np.meshgrid(x,x)\n rr = np.sqrt(xy[0]**2 + xy[1]**2)\n beam = np.exp(-(rr/width)**2)\n return beam", "def phys_oversampled_cart(x, y, z, yso, temp_func, oversample=5, \n logger=get_logger(__name__)):\n # Hydrogen mass\n mH = ct.m_p + ct.m_e\n\n # Special case\n if oversample==1:\n logger.info('Evaluating the grid')\n ZN, YN, XN = np.meshgrid(z, y, x, indexing='ij')\n n, vx, vy, vz, temp = yso.get_all(XN, YN, ZN,\n temperature=temp_func, component='gas')\n n = n / (2.33 * mH)\n temp[temp<2.7*u.K] = 2.7*u.K\n assert n.cgs.unit == 1/u.cm**3\n assert temp.unit == u.K\n assert vx.cgs.unit == u.cm/u.s\n assert vy.cgs.unit == u.cm/u.s\n assert vz.cgs.unit == u.cm/u.s\n return n, (vx, vy, vz), temp\n\n logger.info('Resampling grid')\n # Create new grid\n dx = np.abs(x[0]-x[1])\n dy = np.abs(y[0]-y[1])\n dz = np.abs(z[0]-z[1])\n xw,xstep = np.linspace(np.min(x)-dx/2., np.max(x)+dx/2., num=len(x)*oversample+1,\n endpoint=True, retstep=True)\n xover = (xw[:-1] + xw[1:]) / 2.\n logger.info('Resampled grid x-step = %s', xstep.to(u.au))\n yw,ystep = np.linspace(np.min(y)-dy/2., np.max(y)+dy/2., num=len(y)*oversample+1,\n endpoint=True, retstep=True)\n yover = (yw[:-1] + yw[1:]) / 2.\n logger.info('Resampled grid y-step = %s', ystep.to(u.au))\n zw,zstep = np.linspace(np.min(z)-dz/2., np.max(z)+dz/2., num=len(z)*oversample+1,\n endpoint=True, retstep=True)\n zover = (zw[:-1] + zw[1:]) / 2.\n logger.info('Resampled grid z-step = %s', zstep.to(u.au))\n ZN, YN, XN = np.meshgrid(zover, yover, xover, indexing='ij')\n\n # Volumes\n vol = dx*dy*dz\n vol_over = xstep*ystep*zstep\n\n # Number density\n bins = get_walls(z, y, x)\n n_over, vx_over, vy_over, vz_over, temp = yso.get_all(XN, YN, ZN,\n temperature=temp_func, component='gas', nquad=oversample)\n n_over = n_over / (2.33 * mH)\n assert n_over.cgs.unit == 1/u.cm**3\n N = vol_over * rebin_regular_nd(n_over.cgs.value, zover, yover, xover, bins=bins,\n statistic='sum') * n_over.cgs.unit\n dens = N / vol\n assert dens.cgs.unit == 1/u.cm**3\n\n # Temperature\n temp = rebin_regular_nd(temp.value*n_over.cgs.value, zover, yover, \n xover, bins=bins, statistic='sum') * \\\n temp.unit * n_over.cgs.unit\n temp = vol_over * temp / N\n temp[temp<2.7*u.K] = 2.7*u.K\n assert temp.unit == u.K\n\n # Velocity\n assert vx_over.cgs.unit == u.cm/u.s\n assert vy_over.cgs.unit == u.cm/u.s\n assert vz_over.cgs.unit == u.cm/u.s\n v = []\n for vi in (vx_over, vy_over, vz_over):\n vsum = rebin_regular_nd(vi.cgs.value*n_over.cgs.value, zover, yover, \n xover, bins=bins, statistic='sum') * \\\n vi.cgs.unit * n_over.cgs.unit\n vsum = vol_over * vsum / N\n vsum[np.isnan(vsum)] = 0.\n assert vsum.cgs.unit == u.cm/u.s\n v += [vsum]\n\n return dens, v, temp", "def test_sampling(variant_scalar_rgb, center, radius):\n from mitsuba.core import Vector3f\n\n center_v = Vector3f(center)\n sphere = example_shape(radius, center_v)\n sensor = sphere.sensor()\n num_samples = 100\n\n wav_samples = np.random.rand(num_samples)\n pos_samples = np.random.rand(num_samples, 2)\n dir_samples = np.random.rand(num_samples, 2)\n\n for i in range(100):\n ray = sensor.sample_ray_differential(0.0, wav_samples[i], pos_samples[i], dir_samples[i])[0]\n\n # assert that the ray starts at the sphere surface\n assert ek.allclose(ek.norm(center_v - ray.o), radius)\n # assert that all rays point away from the sphere center\n assert ek.dot(ek.normalize(ray.o - center_v), ray.d) > 0.0", "def testGaussian(self):\n random.seed(42)\n\n us = UniformSample()\n for _ in range(300):\n us.update(random.gauss(42.0, 13.0))\n self.assertAlmostEqual(us.mean, 43.143067271195235, places=5)\n self.assertAlmostEqual(us.stddev, 13.008553229943168, places=5)\n\n us.clear()\n for _ in range(30000):\n us.update(random.gauss(0.0012, 0.00005))\n self.assertAlmostEqual(us.mean, 0.0012015284549517493, places=5)\n self.assertAlmostEqual(us.stddev, 4.9776450250869146e-05, places=5)", "def integration_constant(x, mu, nu, H, N, m):\r\n return integrate.quad(lambda t: G(x, t, mu, nu, H, N), 0.01, np.inf)[0]", "def init_W(rng, dim):\n temp, rng = random.split(rng)\n W = random.normal(temp, (dim,))\n print(W)\n print(W.shape)\n print(W.dtype)\n print(type(W))\n exit()\n W = unit_projection(W)\n temp, rng = random.split(rng)\n W = random.uniform(temp, ()) * W\n return W", "def my_cube (x):\n return (x**3)", "def sample(self, shape=(), seed=None):\n raise TypeError(\"cannot sample from a half flat distribution\")", "def supercontinuumgeneration():\n\n betas = [0,0,-11.830e-3*1e-24, 8.1038e-5*1e-36, -9.5205e-8*1e-48, 2.0737e-10*1e-60,\n -5.3943e-13*1e-72, 1.3486e-15*1e-84, -2.5495e-18*1e-96, 3.0524e-21*1e-108,\n -1.7140e-24*1e-120];\n gamma = 0.1\n flength = 0.15\n simparams = prepare_sim_params(0.0, \n betas ,\n 835e-9,\n gamma,\n flength,\n 13, # Npoints\n 1.0, #tempspread\n zpoints=200, \n integratortype='dop853', \n reltol=1e-3, \n abstol=1e-6 ,\n shock=True,\n raman = True,\n ramantype = 'blowwood',#'hollenbeck', #or 'blowwood', 'linagrawal'\n fr=0.18 )\n t0 = 28.4e-15\n p = 10e3\n inifield = np.sqrt(p) * 1./np.cosh(simparams['tvec']/t0) \n tf,ff,zv = perform_simulation( simparams, inifield)\n saveoutput('scg.demo', tf, ff, zv, simparams)\n #\n # output plot\n #\n d = loadoutput('scg.demo')\n inoutplot(d,zparams={\"fignr\":3, \"clim\":(-360,-220),'fylim':(-360,-220)})\n plt.show()", "def sample(self, size):", "def randSphere( n=1 , dim=3):\n \n # get starting vector\n vec = 2*NPR.rand( n, dim )- 1\n\n norm2 = NP.sum( vec**2, 1 ) \n \n # get within unit sphere \n for i in range(0,n):\n while norm2[i] > 1.0:\n vec[i,:] = 2*NPR.rand( 1, dim )- 1\n norm2[i] = NP.sum( vec[i,:]**2 )\n \n if( i % 10000 == 0 ): stderr.write( \"finished %i\\n\" % i )\n\n return (vec, norm2)", "def boxmuller():\n i = np.random.random_sample(1) # picks random float [0, 1)\n j = np.random.random_sample(1) # picks random float [0, 1)\n return np.sqrt(-2.0 * np.log10(i)) * np.sin(2.0 * np.pi * j)", "def setup_cubes():\n vertical_updraught_data = np.zeros((2, 2), dtype=np.float32)\n vertical_updraught = set_up_variable_cube(\n vertical_updraught_data,\n \"maximum_vertical_updraught\",\n \"m s-1\",\n spatial_grid=\"equalarea\",\n attributes=COMMON_ATTRS,\n standard_grid_metadata=\"gl_ens\",\n )\n\n hail_size_data = np.zeros((2, 2), dtype=np.float32)\n hail_size = set_up_variable_cube(\n hail_size_data,\n \"size_of_hail_stones\",\n \"m\",\n spatial_grid=\"equalarea\",\n attributes=COMMON_ATTRS,\n standard_grid_metadata=\"gl_ens\",\n )\n\n cloud_condensation_level_data = np.zeros((2, 2), dtype=np.float32)\n cloud_condensation_level = set_up_variable_cube(\n cloud_condensation_level_data,\n \"air_temperature_at_condensation_level\",\n \"K\",\n spatial_grid=\"equalarea\",\n attributes=COMMON_ATTRS,\n standard_grid_metadata=\"gl_ens\",\n )\n\n convective_cloud_top_data = np.zeros((2, 2), dtype=np.float32)\n convective_cloud_top = set_up_variable_cube(\n convective_cloud_top_data,\n \"air_temperature_at_convective_cloud_top\",\n \"K\",\n spatial_grid=\"equalarea\",\n attributes=COMMON_ATTRS,\n standard_grid_metadata=\"gl_ens\",\n )\n\n hail_melting_level_data = np.zeros((2, 2), dtype=np.float32)\n hail_melting_level = set_up_variable_cube(\n hail_melting_level_data,\n \"altitude_of_rain_from_hail_falling_level\",\n \"m\",\n spatial_grid=\"equalarea\",\n attributes=COMMON_ATTRS,\n standard_grid_metadata=\"gl_ens\",\n )\n\n altitude_data = np.zeros((2, 2), dtype=np.float32)\n altitude = set_up_variable_cube(\n altitude_data,\n \"altitude\",\n \"m\",\n spatial_grid=\"equalarea\",\n attributes=COMMON_ATTRS,\n standard_grid_metadata=\"gl_ens\",\n )\n return (\n vertical_updraught,\n hail_size,\n cloud_condensation_level,\n convective_cloud_top,\n hail_melting_level,\n altitude,\n )", "def integrand(t, N, h, a, eizw, L):", "def test_02(self): \n # ------------------------------------------------------------------------\n # Test: vol_halfspace_unitcube\n # ------------------------------------------------------------------------\n block = BlockFunction(np.array([0,1]), lambda x: 1, lambda x: 0)\n \n # 2D\n w = np.array([-2,-1])\n z = -2\n v = block.vol_halfspace_unitcube(w,z)\n assert abs(v-0.25) < 1e-12, 'Volume should be 1/4.'\n \n v = block.vol_halfspace_unitcube(-w,-z)\n assert abs(v-0.75) < 1e-12, 'Volumes should add up to 1'\n \n # 3D\n w = np.array([0,1,0])\n z = 1\n v = block.vol_halfspace_unitcube(w,z)\n assert v is None, 'Degeneracy, answer should be None.'\n \n w = np.array([1,1,1])\n z = 1\n v = block.vol_halfspace_unitcube(w,z)\n assert abs(v-1/6) < 1e-12, 'Volume should be 1/6.'\n \n # ------------------------------------------------------------------------\n # Test slab_vol\n # ------------------------------------------------------------------------\n \n # Horizontal hyperplane: unit hypercube\n f1 = lambda x: x[1]\n bnd = np.array([[0,0,0],[1,1,1]]).transpose()\n df1_dx = lambda x: np.array([0,1,0]).transpose()\n bf = BlockFunction(bnd, f1, df1_dx)\n v = bf.slab_vol(0.5,1)\n assert abs(v-0.5)< 1e-12, 'Volume should be 1/2.'\n \n # Horizontal hyperplane, nonstandard hypercube\n bnd = np.array([[0,1,0],[0.5,2,2]]).transpose()\n bf = BlockFunction(bnd, f1, df1_dx)\n assert abs(bf.slab_vol(-1,1)) < 1e-12, 'Volume should be 0'\n assert abs(bf.slab_vol(1,4)-1) < 1e-12, 'Volume should be 1' \n \n # Skew hyperplane\n f2 = lambda x: x[0] + x[1] - 2\n df2_dx = lambda x: np.array([1,1])\n bnd = np.array([[1,1],[2,4]]).transpose()\n bf = BlockFunction(bnd, f2, df2_dx)\n assert abs(bf.slab_vol(0.5,3.5)-2.75)<1e-12, 'Volume should be 2.75'\n \n # 1d function\n f3 = lambda x: x**2\n bnd = np.array([0,1])\n df3_dx = lambda x: 2*x\n bf = BlockFunction(bnd, f3, df3_dx)\n assert abs(bf.slab_vol(0,1)-0.75) < 1e-12\n assert abs(bf.slab_vol(0.5,1)-0.25) < 1e-12" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds an inverse CDF function given a sorted vector of values defining a marginal distribution.
def build_empirical_inverse_cdf(X): n = len(X) def f(prob): """ Args: prob (ndarray): vector with probablities to compute the inverse """ # assert 0<=prob<=1, 'Argument of inverse function is a probability >=0 and <= 1.' return X[np.minimum((n * np.array(prob)).astype(int), n - 1)] return f
[ "def inverse_transform(inv_cdf, **params):\n return inv_cdf(np.random.uniform(), **params)", "def invCDF(val):\n a = density(0)*crossSection\n b = scaleHeight/np.cos(particleTheta)\n c = np.exp(-particleHeight/scaleHeight)\n if b>0:\n n = 1-np.exp(-a*b*c)\n else:\n n = 1\n # Catch negative logarithms and assume they should be nearly log(0)\n if 1+np.log(1-n*val)/(a*b*c)<0:\n return 1e99\n\n return -b*np.log(1+ np.log(1-n*val)/(a*b*c))", "def ccdf_inv(self, points):\n\n\t\tpts = np.array(points)\n\t\taccdfinv = self.__c*( np.power((1-pts)/(pts+self.__d), self.__beta) )\n\t\treturn accdfinv", "def cdf_inv(self, points):\n\n\t\tpts = np.array(points)\n\t\tacdfinv = self.__c*np.power(pts/(1 + self.__d - pts), self.__beta)\n\n\t\treturn acdfinv", "def ccdf_inv(self, points):\n\n\t\tpts = np.array(points)\n\t\taccdfinv = self.__k/np.power(pts, 1/self.__alpha)\n\n\t\treturn accdfinv", "def igrcdf(norm, dim):\n\n\treturn sqrt(2.) * sqrt(gammaincinv(dim / 2., norm))", "def __idiv__(self, *args):\n return _vnl_vectorPython.vnl_vectorF___idiv__(self, *args)", "def cdf_inv(self, points):\n\n\t\tpts = np.array(points)\n\n\t\tacdfinv = self.__k/np.power((1 - pts), 1/self.__alpha)\n\n\t\treturn acdfinv", "def estimate_cinv(self):\n C = self.C * (1.0 / self.count_val)\n Cinv = np.linalg.inv(C)\n self.Cinv = Cinv\n print(C)\n print(Cinv)", "def inverse_cumulative(solver, values, S, max_sum):\n N = len(values)\n # cumulative sums\n c_values = [solver.Sum(values[:(i+1)]) for i in range(N)]\n return index_of_surpass(solver, c_values, S, max_sum)", "def drawFromCumulativeDistributionFunction(cpdf, x, number):\n luck = np.random.random(number)\n tck = interpolate.splrep(cpdf, x)\n out = interpolate.splev(luck, tck)\n return out", "def __idiv__(self, *args):\n return _vnl_vectorPython.vnl_vectorD___idiv__(self, *args)", "def to_cdf(pdf):\n return np.cumsum(pdf)", "def _uniform_order_statistic_cdf(i, n, t):\r\n return betainc(i+1, n-i, t)", "def laplace_inv_cdf(p, mu=0, b=1):\n return mu - b * np.sign(p-0.5) * np.log(1-2*abs(p-0.5))", "def _build_inv_delta_C(self, F, C):\n hat_C = np.zeros((F, F), dtype=float) # F x F\n for i in range(0, F):\n for j in range(i, F):\n r = np.linalg.norm(C[i] - C[j])\n hat_C[i, j] = r\n hat_C[j, i] = r\n np.fill_diagonal(hat_C, 1)\n hat_C = (hat_C**2) * np.log(hat_C)\n # print(C.shape, hat_C.shape)\n delta_C = np.concatenate( # F+3 x F+3\n [\n np.concatenate([np.ones((F, 1)), C, hat_C], axis=1), # F x F+3\n np.concatenate([np.zeros(\n (2, 3)), np.transpose(C)], axis=1), # 2 x F+3\n np.concatenate([np.zeros(\n (1, 3)), np.ones((1, F))], axis=1), # 1 x F+3\n ],\n axis=0,\n )\n inv_delta_C = np.linalg.inv(delta_C)\n return inv_delta_C # F+3 x F+3", "def _pdf_dblexp(mu, cov, xs):\n return np.exp(-np.sqrt(2) * np.abs(xs - mu) / cov) / (np.sqrt(2) * cov)", "def filter(n_order,n_c,s,vander):\n s_even = 2*s\n f_diagonal = np.ones(n_order+1)\n alpha = -np.log(np.finfo(np.float).eps)\n\n for i in range(n_c,n_order+1):\n f_diagonal[i] = np.exp(-alpha*((i-n_c)/(n_order-n_c))**s_even)\n\n # F = V*diag(Fdiagonal)*Vinv\n f_i = np.matmul(vander,np.diag(f_diagonal))\n v_inv = np.linalg.inv(vander)\n filter = np.matmul(f_i,v_inv)\n return filter", "def von_mises_cdf(x, concentration):\n x = tf.convert_to_tensor(x)\n concentration = tf.convert_to_tensor(concentration)\n dtype = x.dtype\n\n # Map x to [-pi, pi].\n num_periods = tf.round(x / (2. * np.pi))\n x = x - (2. * np.pi) * num_periods\n\n # We take the hyperparameters from Table I of [1], the row for D=8\n # decimal digits of accuracy. ck is the cut-off for concentration:\n # if concentration < ck, the series expansion is used;\n # otherwise, the Normal approximation is used.\n ck = 10.5\n # The number of terms in the series expansion. [1] chooses it as a function\n # of concentration, n(concentration). This is hard to implement in TF.\n # Instead, we upper bound it over concentrations:\n # num_terms = ceil ( max_{concentration <= ck} n(concentration) ).\n # The maximum is achieved for concentration = ck.\n num_terms = 20\n\n cdf_series, dcdf_dconcentration_series = _von_mises_cdf_series(\n x, concentration, num_terms, dtype)\n cdf_normal, dcdf_dconcentration_normal = _von_mises_cdf_normal(\n x, concentration, dtype)\n\n use_series = concentration < ck\n cdf = tf.where(use_series, cdf_series, cdf_normal)\n cdf = cdf + num_periods\n dcdf_dconcentration = tf.where(use_series, dcdf_dconcentration_series,\n dcdf_dconcentration_normal)\n\n def grad(dy):\n prob = tf.exp(concentration * cosxm1(x)) / (\n (2. * np.pi) * tf.math.bessel_i0e(concentration))\n return dy * prob, dy * dcdf_dconcentration\n\n return cdf, grad" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setup a scout database.
def database(context, institute_name, user_name, user_mail, api_key): LOG.info("Running scout setup database") # Fetch the omim information api_key = api_key or current_app.config.get('OMIM_API_KEY') if not api_key: LOG.warning("Please provide a omim api key with --api-key") raise click.Abort() institute_name = institute_name or context.obj['institute_name'] user_name = user_name or context.obj['user_name'] user_mail = user_mail or context.obj['user_mail'] adapter = context.obj['adapter'] LOG.info("Setting up database %s", context.obj['mongodb']) setup_scout( adapter=adapter, institute_id=institute_name, user_name=user_name, user_mail = user_mail, api_key=api_key )
[ "def setup_db():\n create_service_db()", "def test_setup_database(mock_app):\n\n runner = mock_app.test_cli_runner()\n assert runner\n\n # test the CLI command for seting up scout\n result = runner.invoke(cli, [\"setup\", \"demo\"])\n\n # Make sure that setup function works correctly\n assert result.exit_code == 0\n assert \"Scout instance setup successful\" in result.output", "def dbSetUp(self):\n pass", "def setupAllDB():\n createDatabase(CONFIG_DB['db_name'])\n runMigrations()\n setupJobTrackerDB()\n setupErrorDB()\n setupUserDB()\n setupJobQueueDB()\n setupValidationDB()", "def initialize_database(self):\n self.database = self.loader.request_library(\"common_libs\", \"database\")\n self.database.create_connection(\"production\")\n self.database.load_mappings()\n\n self.migrator = self.loader.request_library(\"database_tools\", \"migrator\")\n self.migrator.migrate()", "def setUp(self):\n db.create_all()\n self.db = db", "def init_cmd(context, reset, snps):\n LOG.info(\"Running init database\")\n database_api = context.obj[\"db\"]\n if reset:\n database_api.drop_all()\n\n database_api.create_all()\n snp_records = read_snps(snps)\n try:\n database_api.add_commit(*snp_records)\n except (IntegrityError, FlushError):\n LOG.warning(\"database already setup with genotypes\")\n database_api.session.rollback()\n raise click.Abort\n\n LOG.info(\"Database successfully setup\")", "def initialize_database(self):\n self.database = DBConnect(CACHE_DIR / f'_placeholder_app-{self.name}.db')\n self.user_table = self.database.db.create_table(\n 'users', primary_id='username', primary_type=self.database.db.types.text)\n self.inventory_table = self.database.db.create_table(\n 'inventory', primary_id='table_name', primary_type=self.database.db.types.text)\n # Add default data to be used if user hasn't uploaded any test data\n self.default_table = self.database.db.create_table('default')\n if self.default_table.count() == 0:\n self.default_table.insert_many(px.data.tips().to_dict(orient='records'))", "def __call__(self):\n self.create_database()", "def db_setup():\n from config._logger import logger\n\n home = os.environ.get(\"HOMEDIR\") or Path.home()\n home = Path(str(home))\n\n backup = os.environ.get(\"backup\", False)\n if backup:\n backup = True\n\n confirm(\n \"Setting up Snowfall databases is a potentially destructive operation. Continue?\",\n abort=True\n )\n logger.info(\"Preparing to setup snowtuft\")\n\n if not home.exists():\n return error(\"Invalid user specified for primary_user\")\n\n with open(\"/etc/sysctl.conf\", \"w\") as sysctl_file:\n lines = [\n \"fs.file-max=17500\",\n \"vm.overcommit_memory = 1\"\n ]\n sysctl_file.write(\"\\n\".join(lines))\n \n with Popen([\"sysctl\", \"-p\"], env=os.environ, stdout=DEVNULL) as proc:\n proc.wait()\n \n if Path(\"/snowfall/docker/env_done\").exists():\n logger.info(\"Existing docker setup found. Backing it up...\")\n try:\n if backup:\n db_backup()\n except Exception as exc:\n logger.error(f\"Backup failed. Error is {exc}\")\n confirm(\"Continue? \", abort=True)\n\n with Popen([\"systemctl\", \"stop\", \"snowfall-dbs\"], env=os.environ) as proc:\n proc.wait()\n \n logger.info(\"Removing/Renaming old files\")\n \n def _rm_force(f_name):\n try:\n Path(f_name).unlink()\n except Exception:\n pass\n \n _rm_force(\"/etc/systemd/system/snowfall-dbs.service\")\n \n if Path(\"/snowfall\").exists():\n uid = str(uuid.uuid4())\n logger.info(f\"Moving /snowfall to /snowfall.old/{uid}\")\n Path(\"/snowfall.old\").mkdir(exist_ok=True)\n Path(\"/snowfall\").rename(f\"/snowfall.old/{uid}\")\n \n Path(\"/snowfall/docker/db/postgres\").mkdir(parents=True)\n Path(\"/snowfall/docker/db/redis\").mkdir(parents=True)\n \n pg_pwd = secrets.token_urlsafe()\n \n with open(\"/snowfall/docker/env.pg\", \"w\") as env_pg:\n lines = [\n \"POSTGRES_DB=fateslist\",\n \"POSTGRES_USER=fateslist\",\n f\"POSTGRES_PASSWORD={pg_pwd}\"\n ]\n env_pg.write(\"\\n\".join(lines))\n \n shutil.copytree(\"data/snowfall/docker/scripts\", \"/snowfall/docker/scripts\", dirs_exist_ok=True)\n shutil.copy2(\"data/snowfall/docker/config/docker-compose.yml\", \"/snowfall/docker\")\n \n logger.info(\"Starting up docker compose...\")\n cmd = [\n \"docker-compose\", \n \"-f\",\n \"/snowfall/docker/docker-compose.yml\",\n \"up\",\n \"-d\"\n ]\n \n with Popen(cmd, env=os.environ) as proc:\n proc.wait()\n \n time.sleep(5)\n \n logger.info(\"Fixing postgres password. Do not worry if this fails\")\n \n cmd = [\n \"docker\", \"exec\", \"snowfall.postgres\", \n \"psql\", \"-U\", \"fateslist\", \n \"-d\", \"fateslist\", \n \"-c\", f\"ALTER USER fateslist WITH PASSWORD '{pg_pwd}'\"\n ]\n \n with Popen(cmd, env=os.environ) as proc:\n proc.wait()\n \n for op in (\"start\", \"stop\"):\n script_path = Path(f\"/usr/bin/snowfall-dbs-{op}\")\n with script_path.open(\"w\") as action_script:\n lines = [\n \"#!/bin/bash\",\n f\"/usr/bin/docker {op} snowfall.postgres\",\n f\"/usr/bin/docker {op} snowfall.redis\",\n ]\n action_script.write(\"\\n\".join(lines))\n \n script_path.chmod(755)\n \n with open(\"/etc/systemd/system/snowfall-dbs.service\", \"w\") as sf_service:\n lines = [\n \"[Unit]\",\n \"Description=Docker Compose Snowfall 2.0\",\n \"Requires=docker.service\",\n \"After=docker.service\",\n \"\",\n \"[Service]\",\n \"Type=oneshot\",\n \"RemainAfterExit=yes\",\n \"WorkingDirectory=/snowfall/docker\",\n \"ExecStart=/usr/bin/snowfall-dbs-start\",\n \"ExecStop=/usr/bin/snowfall-dbs-stop\"\n \"TimeoutStartSec=0\",\n \"\",\n \"[Install]\",\n \"WantedBy=multi-user.target\"\n ]\n \n sf_service.write(\"\\n\".join(lines))\n \n cmds = (\n [\"systemctl\", \"daemon-reload\"], \n [\"snowfall-dbs-stop\"],\n [\"systemctl\", \"start\", \"snowfall-dbs\"],\n [\"systemctl\", \"restart\", \"snowfall-dbs\"]\n )\n \n for cmd in cmds:\n with Popen(cmd, env=os.environ) as proc:\n proc.wait()\n \n time.sleep(2)\n \n logger.info(\"Fixing up user env\")\n \n with open(\"/snowfall/userenv\", \"w\") as sf_userenv:\n lines = [\n \"source /etc/profile\",\n \"export PGUSER=fateslist\",\n \"export PGHOST=localhost\",\n \"export PGPORT=1000\",\n f\"export PGPASSWORD='{pg_pwd}'\",\n \"export PGDATABASE=fateslist\"\n ]\n \n sf_userenv.write(\"\\n\".join(lines))\n \n lines = [\n \"source /snowfall/userenv\",\n ]\n \n with Path(home / \".bashrc\").open(\"a\") as bashrc_f:\n bashrc_f.write(\"\\n\".join(lines))\n \n with open(\"/root/.bashrc\", \"w\") as bashrc_f:\n bashrc_f.write(\"\\n\".join(lines))\n \n if Path(\"/backups/latest.bak\").exists():\n logger.info(\"Restoring backup...\")\n \n with open(\"/tmp/s2.bash\", \"w\") as sf_s2_f:\n lines = [\n \"source /snowfall/userenv\",\n 'psql -c \"CREATE ROLE meow\"',\n 'psql -c \"CREATE ROLE readaccess\"',\n 'psql -c \"CREATE ROLE postgres\"',\n 'psql -c \"CREATE ROLE root\"',\n 'psql -c \"CREATE SCHEMA IF NOT EXISTS public\"',\n \"psql -c 'CREATE EXTENSION IF NOT EXISTS \" + '\"uuid-ossp\"' + \"'\",\n \"pg_restore -cvd fateslist /backups/latest.bak\"\n ]\n sf_s2_f.write(\"\\n\".join(lines))\n \n with Popen([\"bash\", \"/tmp/s2.bash\"]) as proc:\n proc.wait()\n \n Path(\"/snowfall/docker/env_done\").touch()\n logger.info(f\"Postgres password is {pg_pwd}\")\n logger.success(\"Done setting up databases\")", "def create_database(self):\n self._create_tables()\n self._create_functions()\n self._create_triggers()", "def setup(self):\n scripts = []\n script = '''CREATE TABLE settings (\n id INTEGER PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n value TEXT NOT NULL) WITHOUT ROWID\n '''\n scripts.append(script)\n script = '''INSERT INTO settings (id, name, value)\n VALUES (1, \"out_path\", \"output\")'''\n scripts.append(script)\n self.db.put(scripts)", "def setup_database(config=None):\n if config is None:\n # TODO: How could we support orion.core.config.storage.database as well?\n config = orion.core.config.database.to_dict()\n\n db_opts = config\n dbtype = db_opts.pop(\"type\")\n\n log.debug(\"Creating %s database client with args: %s\", dbtype, db_opts)\n\n return database_factory.create(dbtype, **db_opts)", "def setup():\n \n if os.path.exists(settings.DATABASE_NAME):\n os.remove(settings.DATABASE_NAME)\n \n call_command(\"syncdb\")\n\n for user in [User(username='test'), User(username='test2')]:\n user.set_password('password')\n user.save()", "def bootstrap_catalog(self):\n LoggingManager().log(\"Bootstrapping catalog\", LoggingLevel.INFO)\n init_db()", "def setUp(self):\n self.source = MysqlDatasource()\n dbsetup = SETUP_DB\n dbsetup[\"transform\"] = DBTransformer()\n self.source.setup(\"test\", SETUP_DB)\n # Try tearing down the database in case a previous run ran wihtou cleanup\n try: \n self.source.test_teardown_db()\n self.source.close(True)\n except:\n pass", "def database_setup(self):\r\n self.db = self.dbconn.cursor()\r\n\r\n try:\r\n self.db.execute(\"SELECT * FROM user LIMIT 1\")\r\n except sqlite3.OperationalError:\r\n self.db.execute(\r\n \"CREATE TABLE user (hostname TEXT UNIQUE, nickname TEXT, level INT, activity INT)\")\r\n self.dbconn.commit()", "def initialize_db():\n\n # Load database config from environment\n postgres_db = playhouse.postgres_ext.PostgresqlExtDatabase(\n host=os.environ['DB_HOST'],\n user=os.environ['DB_USER'],\n password=os.environ['DB_PASS'],\n database=os.environ['DB_NAME'],\n port=os.environ['DB_PORT'],\n )\n\n # Configure proxy database to use configured postgres\n typer.secho('Initialising database connection...', fg=typer.colors.BRIGHT_BLACK)\n understatdb.db.DB.initialize(postgres_db)", "def _initialize_db():\n # TODO(metzman): Most of the strings in this function should probably be\n # configurable.\n\n db_utils.initialize()\n # One time set up for any db used by FuzzBench.\n models.Base.metadata.create_all(db_utils.engine)\n\n # Now set up the experiment.\n with db_utils.session_scope() as session:\n experiment_name = 'oss-fuzz-on-demand'\n experiment_exists = session.query(models.Experiment).filter(\n models.Experiment.name == experiment_name).first()\n if experiment_exists:\n raise Exception('Experiment already exists in database.')\n\n db_utils.add_all([\n db_utils.get_or_create(models.Experiment,\n name=experiment_name,\n git_hash='none',\n private=True,\n experiment_filestore='/out/filestore',\n description='none'),\n ])\n\n # Set up the trial.\n trial = models.Trial(fuzzer=os.environ['FUZZER'],\n experiment='oss-fuzz-on-demand',\n benchmark=os.environ['BENCHMARK'],\n preemptible=False,\n time_started=scheduler.datetime_now(),\n time_ended=scheduler.datetime_now())\n db_utils.add_all([trial])" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setup a scout demo instance. This instance will be populated with a case, a gene panel and some variants.
def demo(context): LOG.info("Running scout setup demo") institute_name = context.obj['institute_name'] user_name = context.obj['user_name'] user_mail = context.obj['user_mail'] adapter = context.obj['adapter'] setup_scout( adapter=adapter, institute_id=institute_name, user_name=user_name, user_mail = user_mail, demo=True )
[ "def setup(self):\n # Name of the pipeline reduction step\n self.name = 'noiseplots'\n self.description = \"Make Noise Plots\"\n\n # Shortcut for pipeline reduction step and identifier for\n # saved file names.\n self.procname = 'npl'\n\n # Clear Parameter list\n self.paramlist = []", "def test_demo(self):\n self.cbct.run_demo(show=False)", "def setup(self):\n # Name of the pipeline reduction step\n self.name = 'wcs'\n self.description = 'Add WCS'\n\n # Shortcut for pipeline reduction step and identifier for\n # saved file names.\n self.procname = 'wcs'\n\n # Clear Parameter list\n self.paramlist = []\n\n # Append parameters\n self.paramlist.append(['add180vpa', True,\n 'Add 180 degrees to the SIBS_VPA'])\n self.paramlist.append(['offsibs_x', [0.0, 0.0, 0.0, 0.0, 0.0],\n 'Small offset (in pixels along X) between '\n 'SIBS_X and actual target position'])\n self.paramlist.append(['offsibs_y', [0.0, 0.0, 0.0, 0.0, 0.0],\n 'Small offset (in pixels along Y) between '\n 'SIBS_Y and actual target position'])\n self.paramlist.append(['labmode', False,\n 'If labmode = True, will ignore keywords '\n 'and input parameters and create fake '\n 'astrometry'])", "def _create_services(self):\n self.show_runner = ShowRunner(model=self.hex_model,\n channel=self.channel,\n one_channel=self.one_channel,\n max_show_time=self.max_show_time)\n\n if args.shows:\n named_show = args.shows[0]\n print(\"setting show: \".format(named_show))\n self.show_runner.next_show(named_show)", "def setUp(self):\r\n\r\n self.DUT = Component()", "def __init__(self, envs, discrete_sampler=DiscreteUniformSampler()):\n np.random.seed(None)\n self.envs = envs\n self.sampler = discrete_sampler", "def test_setup_database(mock_app):\n\n runner = mock_app.test_cli_runner()\n assert runner\n\n # test the CLI command for seting up scout\n result = runner.invoke(cli, [\"setup\", \"demo\"])\n\n # Make sure that setup function works correctly\n assert result.exit_code == 0\n assert \"Scout instance setup successful\" in result.output", "def stager_init(self):\n tc_log_file = os.path.join(self.test_case_feature, self.test_case_name, 'stage.log')\n\n # args data\n args = dict(self.default_args)\n\n # override default log level if profiled\n args['tc_log_level'] = 'warning'\n\n # set log path to be the feature and test case name\n args['tc_log_file'] = tc_log_file\n\n # set a logger name to have a logger specific for stager\n args['tc_logger_name'] = 'tcex-stager'\n\n tcex = TcEx(config=args)\n return Stager(tcex, logger, self.log_data)", "def setup(self):\n self.site = SiteFactory(is_default_site=True)", "def __init__(self, subject, session, bids_dir, output_dir):\n SegmentationStage.__init__(self, subject, session, bids_dir, output_dir)\n self.config = SegmentationConfigUI()", "def setUp(self):\n self.epg = epg()", "def initialize_experiment_setup():\n arrays = [['R1', 'R1', 'R2', 'R2', 'R3', 'R3', 'R4', 'R4'],\n ['Scenario', 'SSD', 'Scenario', 'SSD', 'Scenario', 'SSD', 'Scenario', 'SSD']]\n\n experiment_setup = pd.DataFrame(columns=np.arange(1,13,1), index=arrays)\n experiment_setup.loc[(['R1', 'R3'], 'Scenario'), :] = 'S1'\n experiment_setup.loc[(['R2', 'R4'], 'Scenario'), :] = 'S2'\n\n experiment_setup.loc[(['R1', 'R2'], 'SSD'), [1, 2, 3, 7, 8, 9]] = 'OFF'\n experiment_setup.loc[(['R3', 'R4'], 'SSD'), [4, 5, 6, 10, 11, 12]] = 'OFF'\n\n experiment_setup.loc[(['R3', 'R4'], 'SSD'), [1, 2, 3, 7, 8, 9]] = 'ON'\n experiment_setup.loc[(['R1', 'R2'], 'SSD'), [4, 5, 6, 10, 11, 12]] = 'ON'\n\n return experiment_setup", "def test_unit_mysgen_init(self):\n mysgen = MySGEN(CONFIG_FILE)\n\n assert mysgen.config_file == CONFIG_FILE\n assert mysgen.base == {}\n assert mysgen.template == {}\n assert mysgen.posts == {}\n assert mysgen.pages == {}\n assert mysgen.markdown is None", "def _setup_catalogue(self):\n return Catalogue()", "def scene_setting_init():\n sce = bpy.context.scene.name\n bpy.data.scenes[sce].render.engine = 'CYCLES'\n bpy.data.scenes[sce].cycles.film_transparent = True\n\n #output\n bpy.data.scenes[sce].render.image_settings.color_mode = 'RGB'\n bpy.data.scenes[sce].render.image_settings.color_depth = '16'\n bpy.data.scenes[sce].render.image_settings.file_format = 'PNG'\n\n #dimensions\n #bpy.data.scenes[sce].render.resolution_x = g_resolution_x\n #bpy.data.scenes[sce].render.resolution_y = g_resolution_y\n #bpy.data.scenes[sce].render.resolution_percentage = g_resolution_percentage", "def _simple_scene_setup(self):\n colors = {\n \"body_color\": [0.5, 0.5, 0.7], \n \"cloth_color\": [0.8, 0.2, 0.2] if 'garment_color' not in self.config else self.config['garment_color'],\n \"floor_color\": [0.8, 0.8, 0.8]\n }\n\n self.scene = {\n 'floor': self._add_floor(self.body)\n }\n # materials\n self.scene['body_shader'], self.scene['body_SG'] = self._new_lambert(colors['body_color'], self.body)\n self.scene['cloth_shader'], self.scene['cloth_SG'] = self._new_lambert(colors['cloth_color'], self.body)\n self.scene['floor_shader'], self.scene['floor_SG'] = self._new_lambert(colors['floor_color'], self.body)\n\n self.scene['light'] = mutils.createLocator('aiSkyDomeLight', asLight=True)\n\n # Put camera\n self.cameras = [self._add_simple_camera()]\n\n # save config\n self.config['garment_color'] = colors['cloth_color']", "def setUpContainer(self):\n self.dev1 = Device('dev1')\n self.optical_series = OpticalSeries(\n name='OpticalSeries',\n distance=8.,\n field_of_view=(4., 5.),\n orientation='upper left',\n data=np.ones((10, 3, 3)),\n unit='m',\n format='raw',\n timestamps=np.arange(10.),\n device=self.dev1,\n )\n return self.optical_series", "def setup():\n si = SimInterface()\n mb = MatlabBridge()\n si._matlab_bridge = mb\n si._load_dataframes()\n si._setup_internal_sp_info()\n si.reset()\n return si", "def setup_dataset(\n dataset_id: str,\n gpf_instance: GPFInstance,\n *studies: GenotypeData,\n dataset_config_udate: str = \"\") -> GenotypeData:\n # pylint: disable=import-outside-toplevel\n from box import Box\n from dae.studies.study import GenotypeDataGroup\n\n dataset_config = {\n \"id\": dataset_id\n }\n if dataset_config_udate:\n config_update = yaml.safe_load(dataset_config_udate)\n dataset_config.update(config_update)\n\n dataset = GenotypeDataGroup(\n Box(dataset_config, default_box=True), studies)\n # pylint: disable=protected-access\n gpf_instance._variants_db.register_genotype_data(dataset)\n\n return dataset" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of songs given an expression
def read_songs_criteria(expression): logging.debug("{songs_controller} BEGIN function read_song_criteria()") try: songs = CRUD.read_songs_by_criteria(expression) except Exception: return RESP.response_500(message='Database is down!') array = [] for song in songs: array.append(song.dump()) return RESP.response_200(message=array)
[ "def get_search_queries(self):\n artists_songs = []\n\n # Iterating through the playlist track objects inside the paging object.\n for playlist_track in self.playlist[\"tracks\"][\"items\"]:\n # Getting the track itself from the playlist track object.\n track = playlist_track[\"track\"]\n\n # Extracting the list of artists and track name and creating the corresponding string.\n artists_song_str = \", \".join([artists[\"name\"] for artists in track[\"artists\"]]) + \" - \" + track[\"name\"]\n\n artists_songs.append(artists_song_str)\n\n # Adding the duration of the track to the total duration of the playlist.\n self.duration_ms += track[\"duration_ms\"]\n\n return artists_songs", "def getSongs(tracks):\r\n sp = getSP()\r\n songs = tracks[\"items\"]\r\n while tracks['next']:\r\n tracks = sp.next(tracks)\r\n for item in tracks[\"items\"]:\r\n songs.append(item)\r\n return songs", "def get_songs(artist):\r\n\tsongs = []\r\n\tresponse = requests.get(base_url + f'/2.0/?method=artist.gettoptracks&artist={artist}&api_key={last_fm_api_key}&format=json')\r\n\tjson_text = json.loads(response.text)\r\n\ttracks = json_text['toptracks']\r\n\ttrack = tracks['track']\r\n\tfor json_obj in track:\r\n\t\tsong_name = json_obj['name']\r\n\t\tsongs.append(song_name)\r\n\treturn songs", "def get_spotify_tracks(url):\n if 'track' in url:\n return [get_spotify_track(url)]\n if 'album' in url:\n return get_spotify_album(url)\n if 'playlist' in url:\n return get_spotify_playlist(url)\n return []", "def get_songs_names(playlist):\n songs = []\n for song in playlist:\n song = song['track']\n name = ''\n for artist in song['artists']:\n name += artist['name'] + ', '\n name = name[:-2]\n name += ' - ' + song['name']\n songs.append(name)\n return songs", "def search(self, artist=None, album=None, title=None) -> List[Dict]:\n results = []\n\n hits_needed = 1 if artist is not None else 0\n hits_needed += 1 if album is not None else 0\n hits_needed += 1 if title is not None else 0\n\n for tag in self.linear_song_list:\n hits = 0\n for tag_key, tag_value in tag.items():\n if artist is not None and tag_key == \"artist\" and \\\n artist.lower() in tag_value[0].lower():\n hits += 1\n if album is not None and tag_key == \"album\" and \\\n album.lower() in tag_value[0].lower():\n hits += 1\n if title is not None and tag_key == \"title\" and \\\n title.lower() in tag_value[0].lower():\n hits += 1\n if hits == hits_needed:\n results.append(tag)\n\n return results", "def buildArtistList(minimum=2,search=\"\"):\r\n\r\n \r\n \r\n library = MpGlobal.Player.library\r\n if search != \"\":\r\n so = SearchObject(search);\r\n library = so.search(library)\r\n \r\n g = lambda x : [x,]\r\n h = lambda x : [ item.strip() for item in x.replace(',',';').replace('\\\\',';').replace('/',';').split(';') ]\r\n \r\n MpGlobal.Player.quickList = buildQuickList(library,minimum,MpMusic.ARTIST,g)\r\n MpGlobal.Player.quickList_Genre = buildQuickList(library,0,MpMusic.GENRE,h)\r\n # sort the resulting list and update the quick selection tab\r\n MpGlobal.Window.tab_quickselect.sortData()", "def get_song(Song):\r\n song_name = Song[0]\r\n artist = Song[1]\r\n # get song info\r\n song_info = get_song_info(song_name, artist)\r\n if song_info:\r\n return song_info\r\n\r\n # search by song + artist\r\n song_info = get_song_info(song_name + ' ' + artist, artist)\r\n if song_info:\r\n return song_info\r\n\r\n # delete words between bracket\r\n if '(' in song_name:\r\n song_name = re.sub(r'\\([^)]*\\)', '', song_name)\r\n song_info = get_song_info(song_name + ' ' + artist, artist)\r\n if song_info:\r\n return song_info\r\n\r\n # shorten song_name by ('and', '&', 'with')\r\n song_name = song_name.lower()\r\n if 'and' in artist:\r\n SongName = song_name.split('And', 1)[0]\r\n song_info = get_song_info(SongName + ' ' + artist, artist)\r\n if song_info:\r\n return song_info\r\n\r\n if '&' in artist:\r\n SongName = song_name.split('&', 1)[0]\r\n song_info = get_song_info(SongName + ' ' + artist, artist)\r\n if song_info:\r\n return song_info\r\n\r\n if 'with' in artist:\r\n SongName = song_name.split('with', 1)[0]\r\n song_info = get_song_info(SongName + ' ' + artist, artist)\r\n if song_info:\r\n return song_info\r\n\r\n # shorten artist name by ('and', '&', 'with')\r\n artist = artist.lower()\r\n if 'and' in artist:\r\n Artist = artist.split('And', 1)[0]\r\n song_info = get_song_info(song_name + ' ' + Artist, Artist)\r\n if song_info:\r\n return song_info\r\n\r\n if '&' in artist:\r\n Artist = artist.split('&', 1)[0]\r\n song_info = get_song_info(song_name + ' ' + Artist, Artist)\r\n if song_info:\r\n return song_info\r\n\r\n if 'with' in artist:\r\n Artist = artist.split('with', 1)[0]\r\n song_info = get_song_info(song_name + ' ' + Artist, Artist)\r\n if song_info:\r\n return song_info\r\n print(f'Unable to scrap {song_name}')\r\n return song_info", "def query_spotify(querystring):\n # get results for a query\n track_results = spotify.search(f'{querystring}', type='track', limit=10, offset=0, market='US')\n # list of tracks to serve\n to_serve = []\n # convert each song into a dict\n for item in track_results['tracks']['items']:\n songdict = {'track_id': item['id'], 'track_name': item['name'], \n 'artist_name': item['artists'][0]['name'], 'album_art': item['album']['images'][1]['url']}\n to_serve.append(songdict)\n return to_serve", "def get_songs_with_lyrics(self):\n try:\n for row in self.db.execute('SELECT track_id from lyrics'):\n yield row[0]\n except:\n pass", "def list_songs(self):\n response = requests.get('http://localhost:5000/song/all')\n song_names = []\n for s in response.json():\n song_names.append(s['title'])\n self._player.list_songs(song_names)", "def fetch_songs(self):\n if len(self.songs) == 0:\n for file in self.MUSIC_DIR.joinpath (\"./songs\").iterdir():\n if file.is_file():\n self.songs.append (file)\n return self.songs", "def parseMusicExp(text, useInfo):\n \n ll = text.split('_')\n \n result = {\n 'names': ll[:2],\n 'prefixes': [],\n }\n \n unused, endnames, suffix = ccpGenUtil.parseEndNames(useInfo['endnames'], \n '_'.join(ll[2:]))\n result['unused'] = unused\n result['endnames'] = endnames\n result['suffix'] = suffix\n if unused:\n result['status'] = 'partial'\n else:\n result ['status'] = 'OK'\n #\n return result", "def _get_all_songs(self):\n return self.call.AudioLibrary.GetSongs(fields=self.SONG_FIELDS)['songs']", "def read_songs(file_name):\n songs = []\n with open(file_name) as f:\n reader = csv.reader(f, delimiter=\",\")\n for row in reader:\n artist_raw = row[1]\n track_raw = row[2]\n date = row[0]\n artist = artist_raw.replace(\"Artist: \", \"\")\n track = track_raw.replace(\"Track: \", \"\")\n song = Song(artist, track, date)\n yield song", "def list_mp3(self):\n os.chdir(self.dir)\n return glob.glob(\"*.mp3\")", "def _search_album_songs(self, album: Optional[str] = None, artist: Optional[str] = None) ->\\\n Iterator[Tuple[str, Tuple[SongInformation, ...]]]:\n for result in self._search(query_type=\"album\", album=album, artist=artist):\n album_id: str = result['id']\n album_name: str = result['name']\n\n image_url: str = result.get('images', [{}])[0].get('url', None)\n image: Optional[Union[PNGSongImage, JPEGSongImage]] = self._fetch_image(image_url) \\\n if image_url is not None else None\n\n songs_raw = self._all_items(self.api.album_tracks(album_id))\n songs = [self._parse_track(song_result).altered(album=album_name, cover_image=image)\n for song_result in songs_raw]\n\n yield album_name, tuple(songs)", "async def sxm_songs(self, ctx: Context, search: str) -> None:\n\n await self._search_archive(ctx, search, True)", "def spotify_parser(phrase: str, limit: int):\n\n # # a random api call to spotify based on a trackID in database\n # songs = db.query(Songdb).order_by(func.random()).all()\n\n # Search Spotify for a keyword:\n result = sp.search(phrase, limit)\n \"\"\"\n > result.keys()\n dict_keys(['tracks'])\n \n > result['tracks'].keys()\n dict_keys(['href', 'items', 'limit', 'next', 'offset', 'previous', 'total'])\n \n > len(result['tracks']['items'])\n 5\n \n > result['tracks']['items'][0].keys()\n dict_keys(['album', 'artists', 'available_markets', 'disc_number', \n 'duration_ms', 'explicit', 'external_ids', 'external_urls', 'href', \n 'id', 'is_local', 'name', 'popularity', 'preview_url', 'track_number', 'type', 'uri'])\n\n > result['tracks']['items'][0]['artists'][0].keys()\n dict_keys(['external_urls', 'href', 'id', 'name', 'type', 'uri'])\n\n > result['tracks']['items'][0]['album'].keys()\n dict_keys(['album_type', 'artists', 'available_markets', 'external_urls', \n 'href', 'id', 'images', 'name', 'release_date', 'release_date_precision', \n 'total_tracks', 'type', 'uri'])\n\n > result['tracks']['items'][0]['name']\n \"California Dreamin' - Single Version\" \n \"\"\"\n\n record_list = []\n for item in range(len(result['tracks']['items'])):\n \"\"\"\n The memory location of keyword_dict needs to change to avoid list mutation \n hence the keyword_dict construct is inside the loop and not outside.\n \"\"\"\n keyword_dict = {}\n keyword_dict['artist'] = result['tracks']['items'][item]['artists'][0]['name']\n keyword_dict['album'] = result['tracks']['items'][item]['album']['name']\n keyword_dict['track'] = result['tracks']['items'][item]['name']\n record_list.append(keyword_dict)\n\n return record_list", "def get_all_movies_from_quote(search_term):\n\n parsed_term = quote_plus(search_term)\n url = \"http://api.quodb.com/search/\" + parsed_term + \"?titles_per_page=100&phrases_per_title=1000&page=1\"\n movie_list = []\n http_output = get(url)\n try:\n json_data = json.loads(json.dumps(http_output.json()))\n search_term = search_term.translate(str.maketrans('', '', punctuation))\n iterations = len(json_data[\"docs\"])\n for i in range(iterations):\n title = json_data[\"docs\"][i][\"title\"]\n phrase = json_data[\"docs\"][i][\"phrase\"].translate(str.maketrans('', '', punctuation))\n if phrase.find(search_term) != -1:\n movie_list.append(title)\n return movie_list\n except:\n return \"None\"" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates an active song matching a given id with given parameters such as title, artist, album, release year and path. When a parameter is empty it is not updated
def update_song(id, body): logging.debug("{songs_controller} BEGIN function update_song()") if id is '': return RESP.response_400(message='The id parameter is empty!') try: song = CRUD.read_song_by_song_id(id) except Exception: return RESP.response_500(message='Database is down!') if song is None: return RESP.response_404(message='Song not found!') try: CRUD.update_song(song, body['title'], body['artist'], body['album'], body['release_year'], body['path']) CRUD.commit() except Exception: CRUD.rollback() return RESP.response_500(message='Database is down!') return RESP.response_200(message='Song updated with success!')
[ "def _update_audio_(course_id, audio_info):\n course = Course.objects.get(course_id=course_id)\n dir = audio_info[\"url\"].split(\"/\")\n if dir[-2] == \"audio_temp\":\n audio = AudioTemp.objects.get(pk=audio_info[\"id\"]).position\n course.audio_url = File(audio, dir[-1])\n audio.close()\n course.save()", "def update_song(self, song_title, song):\n session = self._db_session()\n\n existing_song = session.query(Song).filter(Song.title == song.title).first()\n if existing_song is None:\n raise ValueError(\"Song %s does not exist\" % song.title)\n\n existing_song.update(song)\n\n session.commit()\n session.close()", "def update(self, obj, id):", "def test_update_song_existing(self):\n self.seed_db()\n num_songs = len(session.query(Song).all())\n\n response = self.client.put(\n '/api/songs/1', data=json.dumps({'filename': 'new_file_name.mp3'}),\n headers={'Content-type': 'application/json'})\n self.assertEqual(response.status_code, 201)\n\n song = json.loads(response.data)\n self.assertEqual(song.get('file').get('name'), 'new_file_name.mp3')\n self.assertEqual(len(session.query(Song).all()), num_songs)", "def update_audio_file(\n db: Session,\n audio_type: AudioFileType,\n audio_id: int,\n audio_file_metadata: AudioCreateTypeSchemas,\n):\n\n audio_model = get_audio_model(audio_type)\n audio_object_id = (\n db.query(audio_model).filter_by(id=audio_id).update(audio_file_metadata.dict())\n )\n\n if not audio_object_id:\n raise AudioDoesNotExist()\n\n if audio_object_id != 1:\n raise UpdateError()\n\n db.commit()\n return audio_object_id", "def test_update_kwargs_id(self):\n self.equad.update(id=6)\n self.assertEqual(self.equad.id, 6)", "def test_update_song_nonexisting(self):\n self.assertEqual(len(session.query(Song).all()), 0)\n response = self.client.put(\n '/api/songs/1', data=json.dumps({'filename': 'new_file_name.mp3'}),\n headers={'Content-type': 'application/json'})\n self.assertEqual(response.status_code, 201)\n\n song = json.loads(response.data)\n self.assertEqual(song.get('file').get('name'), 'new_file_name.mp3')\n self.assertEqual(len(session.query(Song).all()), 1)", "def update_stream(id_, m3u8_URL):\n db = get_db()\n db.execute(\n \"UPDATE streaming\"\n \" SET m3u8_URL = (?)\"\n \" WHERE id = (?)\",\n (m3u8_URL, id_),\n )\n db.commit()", "def update_id(self,id):\n self.id = id", "def guitars_update(guitar_id):\n updated_guitar = {\n 'name': request.form.get('name'),\n 'description': request.form.get('description'),\n }\n guitars.update_one(\n {'_id': ObjectId(guitar_id)},\n {'$set': updated_guitar})\n return redirect(url_for('guitars_show', guitar_id=guitar_id))", "def task_6_song_edit_album():\n song = Song.objects.get(title='Superstition')\n song.album_name = 'Way to Go'\n song.save()", "def stock_update_by_id(current_user, stock_id):\n stock = Stock.query.filter_by(id=stock_id).first()\n\n data = request.get_json()\n\n try:\n if data[\"quantity\"]:\n stock.quantity = data[\"quantity\"]\n\n if data[\"buying_price\"]:\n stock.buying_price = data[\"buying_price\"]\n\n except KeyError:\n return jsonify({\"message\": \"Wrong data passed\"})\n\n db.session.commit()\n return jsonify({\"message\": \"Stock updated successfully\"})", "def test_9_3_update_kwargs_id(self):\n\n r = Rectangle(4, 3, 1, 2, 98)\n self.assertEqual(Rectangle.__str__\n (r), \"[Rectangle] (98) 1/2 - 4/3\")\n r.update(id=22)\n self.assertEqual(r.id, 22)\n self.assertEqual(Rectangle.__str__\n (r), \"[Rectangle] (22) 1/2 - 4/3\")", "def update_artist(artist, new_name):\n conn = sqlite3.connect(\"mydatabase.db\")\n cursor = conn.cursor()\n \n sql = \"\"\"\n UPDATE albums\n SET artist = ?\n WHERE artist = ?\n \"\"\"\n cursor.execute(sql, (new_name, artist))\n conn.commit()\n cursor.close()\n conn.close()", "def playid(self, song_id):\n self.call.AudioPlaylist.Play(song_id)", "async def update(self, session_id: ID, data: SessionModel) -> None:\n raise NotImplementedError()", "def update_mp4(mp4obj, tagobj):\n valid_keys = [\n ('\\xa9alb', 'album'),\n ('\\xa9wrt', 'composer'),\n ('\\xa9gen', 'genre'),\n ('\\xa9day', 'date'),\n #no lyricist field\n ('\\xa9nam', 'title'),\n #no version field\n ('\\xa9ART', 'artist'),\n #('trkn', 'tracknumber')\n #missing asin, mbalbumartistid, mbalbumid, mbtrackid\n ]\n\n for key, field_name in valid_keys:\n if mp4obj.has_key(key):\n if isinstance(mp4obj[key], list):\n tagobj[field_name] = ','.join(mp4obj[key])\n \n if mp4obj.has_key('trkn') and len(mp4obj['trkn']) > 0:\n trkn = mp4obj['trkn'][0]\n if type(trkn) == tuple and len(trkn) == 2:\n tagobj['tracknumber'], tagobj['totaltracks'] = trkn\n elif type(trkn) == unicode:\n tagobj['tracknumber'] = trkn\n else:\n log.info('Unknown type of mp4 track number: %s' % trkn)", "def put(self, id):\n data = request.json\n update_trucker(id, data)\n return None, 204", "def update(identifier, car_info):\n _car = cars[identifier]\n _car.update_info(car_info)", "def update_repository(self, id, element):\r\n if len(self.__elements) != 0:\r\n for i in range(0, len(self.__elements)):\r\n if self.__elements[i].get_id() == element.get_id():\r\n raise ValueError(\"exista un element cu idul acesta\")\r\n for i in range(0, len(self.__elements)):\r\n if self.__elements[i].get_id() == id:\r\n self.__elements[i].set_id(element.get_id())\r\n self.__elements[i].set_data(element.get_data())\r\n self.__elements[i].set_timp(element.get_timp())\r\n self.__elements[i].set_descriere(element.get_descriere())" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes an active song given an id
def delete_song(id): logging.debug("{songs_controller} BEGIN function delete_song()") if id is '': return RESP.response_400(message='The id parameter is empty!') try: song = CRUD.read_song_by_song_id(id) except Exception: return RESP.response_500(message='Database is down!') if song is None: return RESP.response_404(message='Song not found!') try: CRUD.delete_song(song) CRUD.commit() except Exception: CRUD.rollback() return RESP.response_500(message='Database is down!') return RESP.response_200(message='Song deleted with success')
[ "def delete(self, _id):\n raise NotImplementedError(\"delete item\")", "def delete(cls, id_):\n try:\n title = cls.query.filter_by(id=id_).one()\n db.session.delete(title)\n db.session.commit()\n except sqlalchemy.exc.SQLAlchemyError:\n db.session.rollback()\n raise", "def delete_song(self, song_title):\n if song_title is None or type(song_title) != str:\n raise ValueError(\"Invalid Song Id\")\n\n session = self._db_session()\n\n song = session.query(Song).filter(Song.title == song_title).first()\n if song is None:\n session.close()\n raise ValueError('Song does not exist.')\n\n session.delete(song)\n session.commit()\n\n session.close()", "def test_delete_song(self):\n podcast = add_podcast('Python Daily', 300, 'Dan Bader')\n with self.client:\n response = self.client.delete(\n f'/api/v1/audio/podcast/{podcast.id}/'\n )\n self.assertEqual(response.status_code, 200)\n self.assertTrue(response.json, {'detail': \"deleted\"})\n print(\"\\n=============================================================\")", "def remove(self, args):\n self.logger.info(\"removing song \" + args.id + \" from library\")\n self.databaser.remove(args.id)", "def delete_title(id):\n\n item_to_delete = Netflix.query.filter_by(show_id=id).first()\n\n if item_to_delete is not None:\n db.session.delete(item_to_delete)\n db.session.commit()\n\n return {\"status\": \"success\"}", "def audio_remove(self, audio_id=None):\n self.command('audio_remove', audio_id)", "def deleteSong(self):\n if self.selectedTitle:\n self.database.pop(self.selectedTitle)\n index = self.listBox.getSelectedIndex()\n self.listBox.delete(index)\n if self.listBox.size() > 0:\n if index > 0:\n index -= 1\n self.listBox.setSelectedIndex(index)\n self.listItemSelected(index)\n else:\n self.listItemSelected(-1)\n self.editMenu[\"state\"] = DISABLED", "def delete_audio_file(db: Session, audio_type: AudioFileType, audio_id: int):\n audio_model = get_audio_model(audio_type)\n audio_object_id = db.query(audio_model).filter_by(id=audio_id).first()\n\n if not audio_object_id:\n raise AudioDoesNotExist()\n\n try:\n db.delete(audio_object_id)\n except UnmappedInstanceError:\n raise DeleteError()\n\n db.commit()\n return audio_object_id", "def task_3_songs_delete():\n song = Song.objects.filter(title__contains=\"t\")\n song.delete()", "def delete_item(ctx, id, text):\n keep = ctx.obj['keep']\n gnote = keep.get(id)\n item = search_item(gnote.items, text)\n item.delete()\n keep.sync()", "def delete_music(mid):\n try:\n conn = dbi.connect()\n music.deleteMusic(conn,mid) # delete the user\n return redirect(url_for('my_music'))\n except Exception:\n flash('Failed to delete music')\n return redirect(url_for('musicItem', mid=mid))", "def delete(self, id):\n sql = f\"DELETE FROM {self.table} WHERE id=?\"\n self.connect()\n self.cur.execute(sql, (id,))\n self.conn.commit()", "def delete_player(cls, player_id, database=db_constants.DATABASE_PATH):\n\t\tconn = sqlite3.connect(database) # connect to that database (will create if it doesn't already exist)\n\t\tc = conn.cursor() # make cursor into database (allows us to execute commands)\n\t\t# Delete player from player table with given id\n\t\tc.execute('''DELETE FROM player_table WHERE id = ?;''',(player_id,))\n\t\tconn.commit() # commit commands\n\t\tconn.close() # close connection to database", "def delete(id=None, track_id=None):\n\n track = Track.get(track_id)\n Track.delete(track)\n\n log.info('DELETED: {0} - {1}'.format(track.title, track.page_url))\n\n return jsonify(track.to_json())", "def stock_delete_by_id(current_user, stock_id):\n stock = Stock.query.filter_by(id=stock_id).first()\n\n if stock:\n db.session.delete(stock)\n db.session.commit()\n return jsonify({\"message\": \"Stock deleted successfully\"})\n else:\n return jsonify({\"message\": \"Could not delete stock\"})", "def delete_search(search_id):\n ss = SavedSearch.query.filter_by(id=search_id).first_or_404()\n db.session.delete(ss)\n db.session.commit()\n flash('Search <em>{}</em> successfully deleted'.format(ss.name), 'success')\n return redirect(url_for('.show_searches'))", "def delete_track(song, track, show_message=None):\n try:\n name = track.name\n if track in song.tracks:\n song.delete_track(list(song.tracks).index(track))\n elif track in song.return_tracks:\n song.delete_return_track(list(song.return_tracks).index(track))\n if show_message:\n show_message('Track Deleted', name)\n except:\n pass", "def delete_record(self, id):\n sql = 'DELETE FROM %s WHERE id=%s' % (self.table, id)\n print(sql)\n self.curs.execute(sql)\n self.conn.commit()", "def delete(self, id):\n return self.trackfilter(lambda t: t.id() != id).activityfilter(lambda a: a.id() != id)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check booking confirmation and price for a given Flight.
async def confirm_flight(self, flight: Flight) -> (Flight, bool): log.info(f'Checking {flight}') confirm_flight_endpoint = self.CONFIRM_FLIGHT_ENDPOINT.format( booking_token=flight.booking_token ) flights_checked = False while not flights_checked: try: async with self._client_session.get(confirm_flight_endpoint) as confirm_flight_response: data = await confirm_flight_response.json(content_type='text/html') except Exception: return flight, False flights_checked = data.get('flights_checked', False) if not flights_checked: await asyncio.sleep(5) if data['flights_invalid'] or data['price_change']: return flight, False return flight, True
[ "def book_flight(token, pass_info, currency_name):\r\n # request booking from server\r\n booking_payload = {'currency': currency_name, 'booking_token': token,\r\n \"passengers\": pass_info,\r\n }\r\n booking = request_server_response(requests.post, \"http://37.139.6.125:8080/booking\", json_payload=booking_payload)\r\n\r\n try:\r\n booking_confirmation = booking.json()\r\n except json.decoder.JSONDecodeError:\r\n print(\"Invalid response from booking server.\\n\"\r\n \"Server responded with \" + str(booking))\r\n sys.exit(1)\r\n\r\n if booking_confirmation[\"status\"] == \"confirmed\":\r\n return booking.json()[\"pnr\"]\r\n else:\r\n print(\"Booking not successful\\n\"+str(booking_confirmation))\r\n sys.exit(1)", "def test_admin_booking_customer_price(app, tickets):\n app.refresh_page()\n app.booking.select_event(tickets)\n app.booking.apply_custom_price(tickets)\n app.booking.fill_out_customer_info(tickets)\n app.booking.select_payment_method(tickets)\n app.booking.verify_payment_table(tickets)\n app.booking.submit_successful_booking()", "def test_admin_booking_declines(app, tickets):\n app.refresh_page()\n app.booking.select_event(tickets)\n app.booking.fill_out_customer_info(tickets)\n app.booking.submit_declined_card(tickets)\n app.booking.select_payment_method(tickets)\n app.booking.verify_payment_table(tickets)\n app.booking.submit_successful_booking()", "def req_real_time_price_check_end(self):\n for security in self.data:\n for ct in [self.data[security].bid_price,self.data[security].ask_price]: \n if ct < 0.0001:\n #print ct, 'not ready'\n return False\n return True", "def test_add_fee_cash_receipts(config):\n test = (CashReceipts(config)\n .navigate_to_cash_receipts_search()\n .create_fee_cash_receipt()\n .search_cash_receipt()\n .using_cash_receipt_matching_dialog()\n .match_fee()\n .open_fee()\n .verify_if_fee_status_is_paid()\n )", "def fare(self, age: int) -> None:\n if 18 <= age <= 60:\n print(\"The fare of this bus ride is $5.00. 🚌\")\n else:\n print(\"You ride free!~ 🚌\")", "def test_flight_creation_without_price(self):\n\n res1 = self.client().post('/api/v1/auth/signin', data=json.dumps(user_data[16]), content_type=\"application/json\")\n res1 = json.loads(res1.data)\n token = res1['data'][0]['token']\n\n res = self.client().post(\n '/api/v1/flight',\n data=json.dumps(flight[6]),\n headers={\n 'content-type': 'application/json',\n 'auth-token': token\n }\n )\n self.assertEqual(res.status_code, 400)\n response = json.loads(res.data)\n self.assertTrue(response['error'])", "def test_admin_booking_declines_not_finished(app, tickets):\n app.refresh_page()\n app.booking.select_event(tickets)\n app.booking.fill_out_customer_info(tickets)\n app.booking.submit_declined_card(tickets)", "def validateFlightNumbers(self, game_id, old_flight_number, flight_id, data):\n # pass if no flight_number supplied\n new_flight_number = data.get('flight_number', None)\n if new_flight_number is None:\n return (True, \"\")\n\n # flight_number must be of one of the two forms:\n # IATA XX0*<num> e.g. AA99, AA099, AA0099\n # or ICAO XXX0*<num> e.g. AAL99, AAL099, AAL0099\n m = flNum.search(new_flight_number)\n if m is None or m.group(2) == 0:\n return (False, \n \"Invalid flight_number: {}\".format(new_flight_number))\n digits = [m.group(2)]\n \n # if the URI flight_number and the new value are the same, pass\n if old_flight_number is not None:\n # do a full flight number comparison\n if old_flight_number == new_flight_number:\n return (True, \"\")\n \n # get the digits out\n q = flNum.search(old_flight_number)\n \n # success if numeric part of flight numbers match\n if int(m.group(2)) == int(q.group(2)):\n return (True, \"\")\n digits.append(q.group(2))\n \n # validate or set number field\n if 'number' in data:\n if int(data['number']) <= 0:\n return (False, \"Bad number field: {}\".format(data['number']))\n\n # number field does not match flight_number\n if int(m.group(2)) != int(data['number']):\n return (False, \n \"Mismatch flight_number/number: {}\".format(data))\n else:\n data['number'] = m.group(2)\n\n cursor = self.get_cursor()\n \n # validate against all other numbers\n query = \"\"\"SELECT DISTINCT number\n FROM flights\n WHERE game_id = {}\n AND number <> {}\n AND deleted = 'N'\"\"\".format(game_id, data['number'])\n cursor.execute(query)\n \n # it must not match \n all_numbers = [r['number'] for r in cursor]\n if any(data['number'] in [x, x+1] for x in all_numbers):\n return (False, \"flight_number already in use: {}\".format(\n new_flight_number))\n \n\n flt_num_condition = \"number IN ('{}')\".format(\"', '\".join(digits))\n\n flt_id_condition = \"\"\n if flight_id is not None:\n flt_id_condition = \"OR flight_id = {}\".format(flight_id)\n\n\n # get the route_ids for the new and old flight numbers and flight_id\n query = \"\"\"SELECT DISTINCT flight_number, route_id\n FROM flights\n WHERE game_id = {}\n AND ({} {})\n AND deleted = 'N'\"\"\".format(game_id, flt_num_condition, flt_id_condition)\n #print(query)\n cursor.execute(query)\n\n # if we see any change in route_id, fail\n route_id = 0\n for r in cursor:\n if route_id == 0:\n route_id = r['route_id']\n continue\n else:\n if r['route_id'] != route_id:\n return (False, \"Invalid change to new route\")\n\n # all flights are the same route\n return (True, \"\")", "def conf():\r\n ans = askyesno('M.Y. Hotel', f'Confirm if you want to book the room (ID: {self.id}) ?')\r\n if ans > 0:\r\n self.confirm_booking()\r\n pass\r\n else:\r\n return", "def test_361_private_party(app, order):\n app.refresh_page()\n app.booking.select_event(order)\n app.booking.fill_out_customer_info(order)\n app.booking.select_payment_method(order)\n app.booking.verify_payment_table(order)\n app.booking.submit_successful_booking()\n app.calendar.select_event(order)\n app.calendar.verify_event_manifest(order)\n app.calendar.verify_event_status(status=\"Pending\")", "def confirm(self):\n\n self.confirmed = True\n\n # open bookings are marked as denied during completion\n # and the booking costs are copied over permanently (so they can't\n # change anymore)\n b = object_session(self).query(Booking)\n b = b.filter(Booking.period_id == self.id)\n b = b.options(joinedload(Booking.occasion))\n b = b.options(\n defer(Booking.group_code),\n defer(Booking.attendee_id),\n defer(Booking.priority),\n defer(Booking.username),\n )\n\n for booking in b:\n if booking.state == 'open':\n booking.state = 'denied'\n\n booking.cost = booking.occasion.total_cost", "def test_feet_validate_list(self):\n foot = micrometers_to.feet([1.0, 2.0, 3.0, 4.0])\n comparison = np.array([3.28084e-6, 2*3.28084e-6, 3*3.28084e-6, 4*3.28084e-6])\n\n try:\n for i in range(len(comparison)):\n self.assertTrue(math.isclose(foot[i], comparison[i], rel_tol=self.accepted_error))\n print('{:.40s}{}'.format(sys._getframe().f_code.co_name + self.padding, self.passed))\n except AssertionError:\n print('{:.40s}{}'.format(sys._getframe().f_code.co_name + self.padding, self.failed))", "def freelancer_feedback_needed(booking):\n # Allow feedback on complete job requests that haven't already had feedback\n return booking.jobrequest.status == JobRequest.STATUS_COMPLETE and not \\\n BookingFeedback.objects.freelancer_feedback_exists(\n booking.jobrequest, booking.freelancer)", "def test_all_doublerooms_are_booked(self):\n blocked_day_room121 = BlockedDayFactory(date=datetime.datetime(2021, 4, 28), hotel_room=self.hotelroom121)\n blocked_day_room122 = BlockedDayFactory(date=datetime.datetime(2021, 4, 28), hotel_room=self.hotelroom122)\n \n params = {\n 'max_price':'800',\n 'check_in':'2021-04-27',\n 'check_out':'2021-04-29'\n }\n\n response = self.client.get(reverse('units'), params)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.data[0]['price'], float(self.bookinginfo_tripleroom.price))\n self.assertEqual(response.data[1]['price'], float(self.bookinginfo_apt.price))", "def test_admin_booking(app, tickets):\n app.refresh_page()\n app.booking.select_event(tickets)\n app.booking.fill_out_customer_info(tickets)\n app.booking.select_payment_method(tickets)\n app.booking.verify_payment_table(tickets)\n app.booking.submit_successful_booking()", "def fee(self):\n\n fees = 10\n if self.balance > 10.0 and self.balance < 1000.0:\n self.balance -= fees\n print(\" Your balance now is $\", self.balance, \"due to having less than $1000, which initiates a fee of $10\")\n return self.balance\n else:\n print(\"You will have no fees this month\")", "def check_budget(self):\n if self.invoice_line_ids:\n for line in self.invoice_line_ids:\n if line.budget_confirm_id.state in ('waiting_valid','complete','unvalid') and line.account_budget_required == True:\n line.budget_confirm_id.check_budget_invoice()\n self.change_state()\n else:\n raise ValidationError(_(\"You must enter at least one line in Bill Information!!!\"))", "def test_admin_booking_with_gift_certificate_and_promo_code(app, order):\n app.certificate.select_certificate(order)\n app.certificate.make_successful_payment(order)\n app.certificate.verify_created_certificate(order)\n app.certificate.copy_the_code(order)\n app.booking.select_event(order)\n app.booking.apply_valid_promo_code(order)\n app.booking.apply_valid_gift_cert(order)\n app.booking.fill_out_customer_info(order)\n app.booking.select_payment_method(order)\n app.booking.verify_payment_table(order)\n app.booking.submit_successful_booking()\n app.refresh_page()\n app.certificate.navigate_to()\n app.certificate.verify_remain_amount(order)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract content from an html table.
def table_extract(table): table_content = [] rows = table.find_elements_by_tag_name("tr") for row in rows: for tag in ("th", "td"): row_text = [e.text for e in row.find_elements_by_tag_name(tag)] if row_text: table_content.append(row_text) return table_content
[ "def extract_table(htmlstr):\n match = re.search(r'<table.*?/table>', htmlstr, re.DOTALL)\n tablehtml = match.group()\n tableList = re.findall(r'<tr>.*?</tr>', tablehtml, re.DOTALL)\n table = []\n for row in tableList:\n cell = re.findall('<td>(.*?)</td>', row, re.DOTALL)\n table.append(cell)\n return table", "def extract_tables(url):\n page = get_page(url)\n result = extract_tables_from_text(page)\n return result", "def get_table(url):\n xpath = '//*[@id=\"main_content\"]/div/div[1]/table'\n return lxml.html.parse(url).xpath(xpath)[0]", "def read_table(table):\r\n header = None\r\n rows = []\r\n for tr in table.find_all('tr'):\r\n if header is None:\r\n header = read_header(tr)\r\n if not header or header[0] != 'IP Address':\r\n return None\r\n else:\r\n row = read_row(tr)\r\n if row:\r\n rows.append('{}:{}'.format(row[0], row[1]))\r\n return rows", "def parse_table(element: WebElement) -> List[List[str]]:\n\n table_data = []\n\n # parse header columns\n header = []\n header_columns = element.find_elements_by_css_selector(\"thead tr th\")\n for column in header_columns:\n header.append(column.text)\n\n table_data.append(header)\n\n # parse data\n data_rows_elems = element.find_elements_by_css_selector(\"tbody tr\")\n for data_row_elem in data_rows_elems:\n data_row = []\n\n children_elems = data_row_elem.find_elements_by_css_selector(\"*\")\n\n for child_elem in children_elems:\n data_row.append(child_elem.text)\n\n table_data.append(data_row)\n\n return table_data", "def getdatabox(htmltext):", "def scrape_page(self, url):\n soup = self.create_soup(url)\n \n headers = self.find_headers(url)\n \n if headers != None:\n \n #each td tag represents an element in the table\n td_tags = soup.find_all(\"td\")\n \n num_columns = len(headers)\n num_rows = len(td_tags) // num_columns\n \n data_list = list()\n \n #for each row:\n for i in range(0, num_rows):\n curr_data = dict()\n #log the source\n curr_data[\"Source\"] = url\n \n #for each column in this row:\n for j in range(0, num_columns):\n curr_tag = td_tags[num_columns * i + j]\n #add this tag to the dictionary under the correct header\n curr_data[headers[j]] = curr_tag.get_text()\n \n data_list.append(curr_data)\n \n return data_list\n \n else:\n return None", "def html_table_to_dict(html):\n soup = BeautifulSoup(html, 'html.parser')\n tables = soup.find_all('table')\n results = []\n for table in tables:\n table_headers = [header.text for header in table.find('thead').find_all('th')]\n table_body = []\n for row in table.find('tbody').find_all('tr'):\n row_dict = {}\n for i, cell in enumerate(row.find_all('td')):\n row_dict[table_headers[i]] = cell.text\n table_body.append(row_dict)\n results.append(table_body)\n return results", "def get_table(url) -> list:\n return lh.fromstring(requests.get(url).content).xpath('//tr')", "def TableExtract(self):\n\n Regex = r\"\\\\begin\\{table\\}.*?\\\\end\\{table\\}\" # no closing brace on purpose -- this is so that table* is included\n self.TableRegex = re.compile(Regex, re.VERBOSE|re.DOTALL)\n Regex = r\"\\\\begin\\{table\\*\\}.*?\\\\end\\{table\\*}\"\n self.TableStarRegex = re.compile(Regex, re.VERBOSE|re.DOTALL)\n\n TableExtracted = self.TableRegex.findall(self.ParsedText) + self.TableStarRegex.findall(self.ParsedText)\n\n for TableText in TableExtracted:\n ThisUID = self.GenerateUID()\n self.ParsedTables[ThisUID] = Table(TableText, ThisUID)", "def scrape_page(html):\n # Note that criminal data is parsed exactly the same as non-criminal data.\n soup = Soup(html, 'html.parser')\n rows = soup.select(ROWS_SELECTOR)\n rows = rows[4:] # Skip the first four rows because those are headers.\n\n records = []\n # A single record exists in two rows of the table.\n for i in range(0, len(rows), 2):\n row_1 = rows[i]\n row_2 = rows[i + 1]\n data = parse_record(row_1, row_2)\n records.append(data)\n return records", "def fetch_table(url):\n \n \n # pretend to be the chrome brower to solve the forbidden problem\n header = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36\",\n \"X-Requested-With\": \"XMLHttpRequest\"\n }\n html_text = requests.get(url, headers=header)\n \n # to solve garbled text\n html_text.encoding = html_text.apparent_encoding\n pd_table = pd.read_html(html_text.text)[0]\n \n return pd_table", "def return_html( self ):\n\n htmltbl = []\n\n ts = self.__start_table()\n \n htmltbl.append( ts )\n\n for row in range( self.maxRow ):\n\n tr = self.__start_row( row )\n trc = self.__end_row ( )\n\n htmltbl.append( tr )\n\n for col in range( self.maxCol ):\n\n td = self.__resCell( row,col )\n\n if td: #Spanned cells return None\n htmltbl.append( td )\n\n htmltbl.append( trc + \"\\n\" )\n\n htmltbl.append( self.__end_table() + \"\\n\\n\" ) \n\n return string.join( htmltbl, '' )", "def parse_table(table_el):\n table_dict = {\"header\": [], \"value\": []}\n for tr in table_el.find_all(\"tr\"):\n th = None\n td = None\n if tr.find(\"th\"):\n th = tr.th.text\n if tr.find(\"td\"):\n td = tr.td.text\n\n table_dict[\"header\"].append(th)\n table_dict[\"value\"].append(td)\n return pd.DataFrame(table_dict)", "def get_logs_table_content(self):\n return self.find_element_by_css(adpl.LOGS_TABLE).text", "def get_soup_contents(page_data, filter_text):\n soup = BeautifulSoup(page_data, 'html5lib')\n # Get links to documents with 13F in them\n # The table on this page with the important info is named tableFile2.\n table = soup.find('table', {'class': 'tableFile2'})\n rows = table.findAll('tr')\n table_content = []\n matrices_rows = []\n for row in rows:\n matrix_row = []\n for cell in row.find_all('td'):\n matrix_row.append(cell)\n matrices_rows.append(matrix_row)\n for row in matrices_rows:\n try:\n doc_title = row[0].get_text().strip() # Title of doc\n filing_date = row[3].get_text().strip() # Save filing date so we can\n # uniquely identify each doc later.\n if filter_text in doc_title: # If 13F is in the document name..\n a_content = row[1].find('a') # Get link to document\n href = a_content['href'] \n full_link = 'https://www.sec.gov/' + href # Need to combine base site \n # URL with path from href\n tup = (doc_title, full_link, filing_date)\n table_content.append(tup) # Append values as tuples to list\n except:\n pass\n return table_content", "def data_from_html():\n Session = sql.prepare_database(blogabet.configuration.database_url, model.Base)\n data = Session.query(model.Bettor).all()\n for dat in data:\n tree = lxml.html.document_fromstring(dat.HTML)\n matches = []\n i = 0\n pom = tree.cssselect('div.media-body')\n for element in tree.cssselect('div.media-body'):\n reduced = []\n asstr = str(element.text_content()).splitlines()\n for s in asstr:\n tmp = s.strip()\n if tmp != \"\":\n reduced.append(tmp)\n match = parse_different(reduced, dat.name)\n if match is not None:\n matches.append(match)\n print(\"iteration {i} out of {j}\".format(i=i, j=len(pom)))\n i += 1\n for match in matches:\n sql.update(Session, match)", "def produce_rows_lst():\n\n soup = open_custom_html('')\n rows = soup.findChildren(\"tr\")[1:]\n return rows", "def _extract_info_from_table_task_page(task, table):\n task_source = table.find_all(\"tr\")[0].find_all(\"td\")[3].text\n task.set_source(task_source)\n task_author = table.find_all(\"tr\")[1].find_all(\"td\")[1].text\n task.set_author(task_author)\n task_time_limit = table.find_all(\"tr\")[2].find_all(\"td\")[1].text\n task.set_time_limit(task_time_limit)\n task_memory_limit = table.find_all(\"tr\")[2].find_all(\"td\")[3].text\n task.set_memory_limit(task_memory_limit)\n task_difficulty = table.find_all(\"tr\")[3].find_all(\"td\")[3].find_all(\"div\", attrs={'class': 'hidden'})[0].text\n task.set_difficulty(task_difficulty)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check to see if page update is blocked by "Please Wait" message Return True if blocked, False if not blocked
def check_page_blocked(self): blocker = self.driver.find_element_by_id("blockingDiv") return blocker.is_displayed()
[ "def isWaiting(self):\r\n return self.iswaiting", "def checkForEntertainmentWaitTime(self):\n self.waitTimeData = requests.get(\"https://disneyworld.disney.go.com/api/wdpro/facility-service/entertainments/{}/wait-times\".format(self.__id), headers=getHeaders()).json()\n # data = json.loads(s.content)\n try:\n check = self.waitTimeData['waitTime']['postedWaitMinutes']\n return True\n except:\n return False", "def is_busy(self):\n self.refresh()\n if self.status == 'BUSY':\n return True\n return False", "def is_blocking(self): # -> bool\n pass", "def check_is_blocked(cls, version):\n return version.is_blocked", "def waitingAELoading(self):\n loading = True\n attempts = 0\n while loading and attempts < 60:\n for t in CurrentWindows().getTitles():\n if self.aeWindowName.lower() in t.lower():\n loading = False\n break\n\n attempts += 1\n time.sleep(0.5)\n\n return not loading", "async def _waiting(self):\n now = time.time()\n diff = now - self._last_request_time\n if diff < self._delay:\n wait_time = self._delay - diff\n self._last_request_time += self._delay\n await asyncio.sleep(wait_time)\n else:\n self._last_request_time = now", "def wait(self):\n if self.allowed:\n while self.locked:\n pf.canvas.update()\n pf.app.processEvents()\n sleep(0.01) # to avoid overusing the cpu", "def sleep_and_check(self):\n time.sleep(self.seconds_to_sleep)\n return self.q_size != len(self.q)", "def age_limit_message_present(self):\n self.wait_for_ajax()\n return self.q(css='#u-field-message-account_privacy').visible", "def check_publish_block(self, block_header):\n\n # Only claim readiness if the wait timer has expired\n return self._wait_timer.has_expired(now=time.time())", "def waiting_precondition(self):\n return self._wait_precondition is True and self.triggered is False", "def is_waiting_for_server(self):\n return (not self.finished) and (self.server is None)", "def waitUntilUnlocked(self):\n while not self.isUnlocked():\n self.waitForEvent()", "def is_browser_on_page(self):\n try:\n self.wait_for_ajax()\n return self.wait_for_an_element_to_be_present(CREATE_ACCOUNT)\n except TimeoutException:\n print('Page is taking much time to load')", "def is_blocked(self, name):\n return name in self._name2plugin and self._name2plugin[name] is None", "def _is_loading_in_progress(self):\n query = self.q(css='.ui-loading-indicator')\n return query.present and 'is-hidden' not in query.attrs('class')[0].split()", "def checkBusy(self,funcUnit,currTime):\n\n waitVal = self.busyUntil[funcUnit]\n return (waitVal > currTime)", "def check_wait(self):\r\n\t\t\r\n\t\tif self.wait == 0:\r\n\t\t\tself.progressbar.destroy()\r\n\t\t\t# self.top_win.destroy()\r\n\t\telse:\r\n\t\t\tself.bytes += 20\r\n\t\t\tself.progressbar['value'] = self.bytes\r\n\t\t\tself.after(100, self.check_wait)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Login to Portal. Should work with both new and old Portals.
def login(self, username, password, url): # Default fail return result result = 1 # Create Webdriver instance self.driver = webdriver.Firefox() driver = self.driver #Move window off edge of screen (effecivtely hides it) if flag set if self.offscreen: driver.set_window_position(3000, 0) # driver.set_window_position(0, 0) to get it bac # Open URL self.driver.get(url) # Wait for page WebDriverWait(driver, 10).until(lambda driver: driver.title == "LAA Online Portal" or "By logging in to this Portal" in driver.page_source) # Login to Portal - New or Old # New Portal if driver.title == "LAA Online Portal": # Username and password, if values supplied driver.find_element_by_name("username").send_keys(username) driver.find_element_by_name("password").send_keys(password) driver.find_element_by_class_name("button-start").click() # Old Portal else: driver.find_element_by_name("ssousername").send_keys(username) driver.find_element_by_name("password").send_keys(password) driver.find_element_by_name("submit").click() # Wait for response try: WebDriverWait(self.driver, 20).until(lambda driver: ">Logged in as:" in driver.page_source or "An incorrect Username or Password was specified" in driver.page_source or "Authentication failed. Please try again" in driver.page_source or "t be displayed" in driver.page_source # Avoiding weird apostrophe! from "can't" or "Secure Connection Failed" in driver.page_source) except TimeoutException: pass # Check if login was successful if ">Logged in as:" in driver.page_source: # Do we have MI link? links = [e.text for e in driver.find_elements_by_tag_name("a")] if self.application_link in links: result = 0 return result
[ "def __login(self):\n self.__access_to_api(\"https://secure.nicovideo.jp/secure/login?site=niconico\", is_post=True, post_data={\n 'mail_tel': Constants.Niconico.LOGIN_ID,\n 'password': Constants.Niconico.PASSWORD,\n })", "def login(self):\n url = \"http://\"+self.ip+\"/cgi-bin/api.cgi\"\n #attempt to login\n self.username = \"admin\"\n self.password = \"admin\"\n response = pu.io.url(url+\"?command=login&user=admin&passwd=admin\",timeout=15)\n # get session id\n if(not response):\n return False\n response = response.strip().split('=')\n if(response[0].strip().lower()=='session' and len(response)>1):#login successful\n self.tdSession = response[1].strip() #extract the id\n return True\n # else:#could not log in - probably someone changed username/password\n return False", "def default_login(self):\n self.set_email('sharenet.admin@redhat.com')\n self.set_password('redhat')\n self.click_login_button()", "def login(self):\n if (\"password\" not in self.config or\n not self.config[\"password\"]): # is \"\", False, None\n if appuifw.query(u\"Password is not set! Would you like to set it now?\", 'query'):\n self.set_config_var(u\"Password\", \"code\", \"password\")\n appuifw.note(u\"Perform login again now.\", 'info')\n else:\n appuifw.note(u\"You can set it in\\nSet->Password menu\", 'info')\n else:\n self.ip = appuifw.InfoPopup()\n self.ip.show(u\"Logging in...\", (50, 50), 60000, 100, appuifw.EHLeftVTop)\n data, response = self.comm.login(self.config[\"username\"],\n self.config[\"password\"])\n # Check we got valid response\n if isinstance(data, dict) is False:\n appuifw.note(u\"Invalid response from web server!\", 'error')\n elif data[\"status\"].startswith(\"error\"):\n appuifw.note(u\"%s\" % data[\"message\"], 'error')\n self.ip.hide()\n message = u\"%s\" % (data[\"message\"])\n self.ip.show(message, (50, 50), 5000, 10, appuifw.EHLeftVTop)\n #appuifw.note(message, 'info')", "def login(self):\n\n formdata = {\"username\": self.username, \"password\": self.password}\n r = requests.get(os.path.join(self.toon_url, 'login'), params=formdata)\n self.sessiondata = r.json()", "def login(self):\n app = App.get_running_app()\n\n try:\n app.backend.login(self.ids.email.text, self.ids.password.text)\n app.show(Home, True)\n\n except BackEndError as e:\n Alert(title=\"Login Error\", text=e.error)\n except Exception as e:\n Alert(title=\"Login Error\", text=\"Unexpected error: \" + str(e))", "def login(self):\n login = self.session.get(LOGIN_URL)\n auth_url = login.url.replace(\"id.fantia.jp/auth/\", \"id.fantia.jp/authorize\")\n\n login_json = {\n \"Email\": self.email,\n \"Password\": self.password\n }\n\n login_headers = {\n \"X-Not-Redirection\": \"true\"\n }\n\n auth_response = self.session.post(auth_url, json=login_json, headers=login_headers).json()\n if auth_response[\"status\"] == \"OK\":\n auth_payload = auth_response[\"payload\"]\n\n callback = self.session.get(LOGIN_CALLBACK_URL.format(auth_payload[\"code\"], auth_payload[\"state\"]))\n if not callback.cookies[\"_session_id\"]:\n sys.exit(\"Error: Failed to retrieve session key from callback\")\n\n check_user = self.session.get(ME_API)\n if not check_user.status_code == 200:\n sys.exit(\"Error: Invalid session\")\n else:\n sys.exit(\"Error: Failed to login. Please verify your username and password\")", "def login():\n global default_session\n return default_session.login()", "def login(self, uname, pwd):\n self.username_field = uname\n self.password_field = pwd\n self.click_sign_in_button()", "def _do_calnet_login():\n WebDriverWait(driver, 9).until(EC.title_contains('Central Authentication Service'))\n calnet_id_input = driver.find_element_by_id('username')\n calnet_id_input.send_keys(calnet_id)\n passphrase_input = driver.find_element_by_id('password')\n passphrase_input.send_keys(passphrase)\n sign_in_button = driver.find_element_by_name('submit')\n sign_in_button.click()", "def login():\n opener = get_opener()\n card, zip_code = get_login_info()\n values = {\n 'loginButton': 'Login',\n 'loginButton.x': 58,\n 'loginButton.y': 13,\n 'myCplLogin': 'Login',\n 'patronId': card,\n 'zipCode': zip_code,\n }\n data = urllib.urlencode(values)\n req = urllib2.Request(LOGIN_URL, data, HEADERS)\n opener.open(req)\n return opener", "def login(username, password):", "def login(username, password):\n login_page = s.get(\"{}/Panopto/Pages/Auth/Login.aspx?instance=NUSCAST&AllowBounce=true\".format(PANOPTO_BASE))\n url = login_page.url\n resp = s.post(url, {\"UserName\": username, \"Password\": password, \"AuthMethod\": \"FormsAuthentication\"})\n parser = BeautifulSoup(resp.text, \"html.parser\")\n saml = parser.find(\"input\", {\"name\": \"SAMLResponse\"})\n if saml != None:\n s.post(\"{}/Panopto/Pages/Auth/Login.aspx\".format(PANOPTO_BASE), {\"SAMLResponse\": saml.get(\"value\"),\\\n \"RelayState\": \"{}/Panopto/Pages/Sessions/List.aspx\".format(PANOPTO_BASE)})\n return True\n return False", "def login():\n uber_auth_url = create_uber_auth()\n return redirect(uber_auth_url)", "def login_user(self):\n login_url = 'ADD LOGIN URL'\n post_url = '{website}{login_url}'.format(website=self.website, login_url=login_url)\n headers = {\n 'ADD': 'HEADERS HERE',\n }\n login_params = {\n 'username': os.environ['TEST_WEB_USER'],\n 'password': os.environ['TEST_WEB_PSWD'],\n # May need to add more login parameters, based on specific use cases\n }\n\n req = requests.Request('POST', post_url, headers=headers).prepare()\n req.body = urlencode(login_params)\n req.headers['Content-Length'] = len(req.body)\n self.session.send(req)\n\n # The use case I wrote this for only set cookies if it logged in -- that may not always\n # be true, so you may need to modify this check. \n if len(self.session.cookies) == 0:\n return False\n else:\n return True", "def login(self):\n\n self.driver.set_window_size(width=1000, height=900) # maximize_window()\n self.driver.get('https://fr.indeed.com')\n time.sleep(timer(1, 2))\n\n if self.log_in:\n print(f\"\\nLogin into {colored('https://fr.indeed.com', 'blue')} ...\")\n self.driver.find_element_by_class_name('gnav-LoggedOutAccountLink-text').click()\n time.sleep(timer(1, 2))\n\n email = self.driver.find_element_by_id('login-email-input')\n email.clear()\n email.send_keys(self.email)\n time.sleep(timer(1, 2))\n\n password = self.driver.find_element_by_id('login-password-input')\n password.clear()\n password.send_keys(self.password)\n time.sleep(timer(2, 3))\n\n password.send_keys(Keys.RETURN)", "def open_portal():\n url = 'https://portal.azure.com/#@chrisbilsoncalicoenergy.onmicrosoft.com/dashboard/private/60b7336f-622f-4867-943f-f37bbbe003cd'\n webbrowser.open(url)", "def login(self):\n if not self.server:\n raise LoginNoServerError()\n\n self.api.set_url(server=self.server, port=self.port)\n\n if not self.api.probe():\n raise LoginServerUnreachableError()\n\n self.api.login(self.user, self.passwd)", "def login(self):\n self.state = 'logged_in'" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Alternative login that uses firefox profile with Modify Headers to access Eric without using the portal (doesn't work in every Eric instance but does with DEV10).
def login_direct(self, url="http://ds01za003:7813/lscapps/eric-emi-murali/AutoLoginServlet", profile_path="" ): ffp_object = FirefoxProfile(profile_path) # Use Webdriver to open Firefox using chosen profile self.driver = webdriver.Firefox(ffp_object) # Open the URL self.driver.get(url) # Check expected page is present WebDriverWait(self.driver, 20).until(lambda driver: "reports found for" in driver.page_source or "0 report(s) found for user" in driver.page_source) # Wait for "please wait" message to go WebDriverWait(self.driver, 20).until(lambda driver: not self.check_page_blocked())
[ "def login_into_hasjob(driver):\n\tlogin_url = \"https://hasjob.co/login\"\n\t# login_url = \"https://auth.hasgeek.com/login\"\n\tdriver.get(login_url)\n\n\ttime.sleep(2)\n\ta = driver.find_element_by_id(\"showmore\")\n\ta.click()\n\ti = driver.find_element_by_id(\"username\")\n\ti.send_keys(\"vickyojha2@yahoo.com\")\n\tp = driver.find_element_by_id(\"password\")\n\tp.send_keys(\"ashposeidon!!1\")\n\tf = driver.find_element_by_id(\"passwordlogin\")\n\tf.submit()\n\ttime.sleep(7)", "def login(self):\n def get_password(password, verify_code):\n \"\"\"docstring for get_password\"\"\"\n try:\n from hashlib import md5\n except ImportError:\n from md5 import md5\n\n m = md5()\n m.update(password)\n md5pwd = m.hexdigest()\n m = md5()\n m.update(md5pwd)\n md5pwd = m.hexdigest()\n m = md5()\n m.update(md5pwd + verify_code)\n md5pwd = m.hexdigest()\n return md5pwd\n\n response = self.request('http://login.xunlei.com/check?u=%s&cachetime=%s' % (self.username, get_cache()))\n br = self.get_browser()\n check_result = br._ua_handlers['_cookies'].cookiejar._cookies['.xunlei.com']['/']['check_result'].value\n verify_code = check_result.split(':')[1]\n encrypt_password = get_password(self.password, verify_code)\n data = {\n 'u':self.username,\n 'p':encrypt_password,\n 'verifycode':verify_code,\n 'login_enable':'1',\n 'login_hour':'720',\n }\n response = self.request('http://login.xunlei.com/sec2login/', data)\n cache = get_cache()\n response = self.request('http://dynamic.lixian.vip.xunlei.com/login?cachetime=%s&cachetime=%s&from=0' % (cache, str(int(cache)+133)))\n return response", "def login_into_hasjob(driver):\n\tlogin_url = \"https://hasjob.co/login\"\n\t# login_url = \"https://auth.hasgeek.com/login\"\n\tdriver.get(login_url)\n\n\ttime.sleep(2)\n\ttry:\n\t\ta = driver.find_element_by_id(\"showmore\")\n\t\ta.click()\n\t\ttime.sleep(1)\n\texcept:\n\t\t# Log here, the element was not present\n\t\tprint \"Element with id `showmore` was not present\"\n\t\tpass\n\n\ti = driver.find_element_by_id(\"username\")\n\ti.send_keys(\"vickyojha2@yahoo.com\")\n\tp = driver.find_element_by_id(\"password\")\n\tp.send_keys(\"ashposeidon!!1\")\n\tf = driver.find_element_by_id(\"passwordlogin\")\n\tf.submit()\n\ttime.sleep(7)", "def login(request, login, password):\n hdrs, resp = _runcgi(request, \"serve-control\", method=\"POST\", login=login, password=password)\n if _xpath(resp, \"//title/text()\") == \"Invalid login\":\n return (None, None)\n else:\n sid = _breakdown_url(hdrs[\"Location\"])[\"SID\"]\n m = re.match(\"EJSID=([0-9a-f]+)(;.*)?$\", hdrs[\"Set-Cookie\"])\n assert m is not None\n print(f\"SID={sid}, cookie={m.group(1)}\")\n return (sid, m.group(1))", "def login(request):\n if settings.DEPLOYMENT_TYPE == 'localdev' and not request.session.get('fake_bceid_guid'):\n return redirect(settings.PROXY_BASE_URL + settings.FORCE_SCRIPT_NAME[:-1] + '/bceid')\n else:\n\n # get the Guid that was set in the middleware\n if request.bceid_user.guid is None:\n # Fix for weird siteminder behaviour......\n # If a user is logged into an IDIR then they can see the login page\n # but the SMGOV headers are missing. If this is the case, then log them out\n # of their IDIR, and redirect them back to here again....\n\n # FUTURE DEV NOTE: The DC elements of HTTP_SM_USERDN header will tell us exactly how the user is\n # logged in. But it doesn't seem like a very good idea at this time to rely on this magic string.\n # e.g. CN=Smith\\, John,OU=Users,OU=Attorney General,OU=BCGOV,DC=idir,DC=BCGOV\n\n if request.GET.get('noretry','') != 'true':\n return redirect(settings.LOGOUT_URL_TEMPLATE % (\n settings.PROXY_BASE_URL, settings.FORCE_SCRIPT_NAME[:-1] + '/login%3Fnoretry=true'))\n else:\n return render(request, '407.html')\n\n user, created = __get_bceid_user(request)\n\n # some later messaging needs to be shown or hidden based on whether\n # or not this is a returning user\n request.session[\"first_login\"] = created\n\n if timezone.now() - user.last_login > datetime.timedelta(minutes=1):\n user.last_login = timezone.now()\n user.save()\n\n copy_session_to_db(request, user)\n\n return redirect(settings.PROXY_BASE_URL + settings.FORCE_SCRIPT_NAME[:-1] + '/overview')", "def cookie_gen(self):\n url = 'https://compteperso.leboncoin.fr/store/verify_login/0'\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n payload = {'st_username': self.profile['username'], 'st_passwd': self.profile['password']}\n req_url = self.profile['session'].post(url, headers=headers, data=payload)\n # Generate a soup\n soup = BeautifulSoup(req_url.text, 'lxml')\n if soup.find('span', 'error'):\n print('Authentication failed...')\n else:\n with open(self.cookie_jar_path, 'w') as cookie_jar_file:\n dump(dict_from_cookiejar(self.profile['session'].cookies), cookie_jar_file)", "def login_to_acm():\n url = get_acm_url()\n log.info(f\"URL: {url}, {type(url)}\")\n driver = login_ui(url)\n validate_page_title(driver, title=ACM_PAGE_TITLE)\n\n return driver", "def login(first_name, last_name, phone):\n global url, browser\n try:\n area, prefix, suffix = phone[:3], phone[3:6], phone[6:10]\n browser = webdriver.Firefox()\n browser.get(url)\n\n select = Select(browser.find_element_by_name('officeId'))\n select.select_by_visible_text(\"SANTA CLARA\")\n\n click_by_id(\"one_task\")\n click_by_id(\"taskRWT\")\n form_names = [\"firstName\", \"lastName\", \"telArea\", \"telPrefix\", \"telSuffix\"]\n inputs = [first_name, last_name, area, prefix, suffix]\n for form, text in zip(form_names, inputs):\n type_into_form(form, text)\n click_by_xpath(\"//input[@type='submit']\")\n except Exception as e:\n print(\"An error occurred while trying to log in.\")\n sys.exit()", "def sign_in(self,username,password): \n \n # sign-in actions\n return self.browser", "def login(self) :\n url = \"https://www.nordnet.no/api/2/login/anonymous\"\n url2 = \"https://www.nordnet.no/api/2/authentication/basic/login\"\n payload = dict(username = self.user, password = self.password)\n ntag1= self.session.post(url, proxies=self.proxies, verify=False).headers[\"ntag\"]\n log = self.session.post(url2, data= payload, headers= {\"Referer\": \"https://www.nordnet.no/mux/login/start.html?state=signi\"},\n proxies=self.proxies, verify=False)\n self.session.get(\"https://next.nordnet.no\", proxies=self.proxies, verify=False)\n self.next = self.session.cookies.get(\"NEXT\", domain=\"next.nordnet.no\")\n self.ntag = log.headers[\"ntag\"]\n self.ntag1 = ntag1\n self.header = {\"Cookie\": \"NEXT=\"+self.next, \"client-id\": \"NEXT\"}\n return log", "def login(self):\r\n credentials = (self.username, self.password)\r\n auth_url = '%s/qcbin/' \\\r\n 'authentication-point/authenticate' % BASE_URL\r\n response = requests.request(\"POST\", url=auth_url, auth=credentials)\r\n LOG.info('URL: %s\\nResponse Code: %s', auth_url, response.status_code)\r\n\r\n if response.status_code != 200:\r\n raise Exception(response.reason)\r\n\r\n LOG.info('Authentication Successful')\r\n cookie = (response.headers['Set-Cookie'].split(';')[0].replace('LWSSO_COOKIE_KEY=', ''))\r\n self.cookies['LWSSO_COOKIE_KEY'] = cookie\r\n\r\n session_url = \"%s/qcbin/rest/site-session\" % BASE_URL\r\n session_response = requests.request(\"POST\", url=session_url, cookies=self.cookies)\r\n LOG.info('URL: %s\\nResponse Code: %s', session_url, session_response.status_code)\r\n\r\n if session_response.status_code != 201:\r\n raise Exception(session_response.reason)\r\n\r\n j_session_id = session_response.headers[\"Set-Cookie\"].split(',')[0].split(';')[0]. \\\r\n replace('JSESSIONID=', '').strip()\r\n qc_session = session_response.headers[\"Set-Cookie\"].split(',')[1].split(';')[0]. \\\r\n replace('QCSession=', '').strip()\r\n alm_user = session_response.headers[\"Set-Cookie\"].split(',')[2].split(';')[0]. \\\r\n replace('ALM_USER=', '').strip()\r\n xsrf_token = session_response.headers[\"Set-Cookie\"].split(',')[-1].split(';')[0]. \\\r\n replace('XSRF-TOKEN=', '').strip()\r\n self.cookies[\"QCSession\"] = qc_session\r\n self.cookies[\"XSRF-TOKEN\"] = xsrf_token\r\n self.cookies[\"JSESSIONID\"] = j_session_id\r\n self.cookies[\"ALM_USER\"] = alm_user\r\n self.header[\"Accept\"] = 'application/json'\r\n LOG.info('Login Successful')", "def browser_login(clearml_server=None):\n # type: (Optional[str]) -> ()\n\n # check if we are running inside a Jupyter notebook of a sort\n if not os.environ.get(\"JPY_PARENT_PID\"):\n return\n\n # if we are running remotely or in offline mode, skip login\n from clearml.config import running_remotely\n # noinspection PyProtectedMember\n if running_remotely():\n return\n\n # if we have working local configuration, nothing to do\n try:\n Session()\n # make sure we set environment variables to point to our api/app/files hosts\n ENV_WEB_HOST.set(Session.get_app_server_host())\n ENV_HOST.set(Session.get_api_server_host())\n ENV_FILES_HOST.set(Session.get_files_server_host())\n return\n except: # noqa\n pass\n\n # conform clearml_server address\n if clearml_server:\n if not clearml_server.lower().startswith(\"http\"):\n clearml_server = \"http://{}\".format(clearml_server)\n\n parsed = urlparse(clearml_server)\n if parsed.port:\n parsed = parsed._replace(netloc=parsed.netloc.replace(':%d' % parsed.port, ':8008', 1))\n\n if parsed.netloc.startswith('demoapp.'):\n parsed = parsed._replace(netloc=parsed.netloc.replace('demoapp.', 'demoapi.', 1))\n elif parsed.netloc.startswith('app.'):\n parsed = parsed._replace(netloc=parsed.netloc.replace('app.', 'api.', 1))\n elif parsed.netloc.startswith('api.'):\n pass\n else:\n parsed = parsed._replace(netloc='api.' + parsed.netloc)\n\n clearml_server = urlunparse(parsed)\n\n # set for later usage\n ENV_HOST.set(clearml_server)\n\n token = None\n counter = 0\n clearml_app_server = Session.get_app_server_host()\n while not token:\n # try to get authentication toke\n try:\n # noinspection PyProtectedMember\n token = Session._Session__get_browser_token(clearml_app_server)\n except ValueError:\n token = None\n except Exception: # noqa\n token = None\n # if we could not get a token, instruct the user to login\n if not token:\n if not counter:\n print(\n \"ClearML automatic browser login failed, please login or create a new account\\n\"\n \"To get started with ClearML: setup your own `clearml-server`, \"\n \"or create a free account at {}\\n\".format(clearml_app_server)\n )\n print(\"Please login to {} , then press [Enter] to connect \".format(clearml_app_server), end=\"\")\n input()\n elif counter < 1:\n print(\"Oh no we failed to connect \\N{worried face}, \"\n \"try to logout and login again - Press [Enter] to retry \", end=\"\")\n input()\n else:\n print(\n \"\\n\"\n \"We cannot connect automatically (adblocker / incognito?) \\N{worried face} \\n\"\n \"Please go to {}/settings/workspace-configuration \\n\"\n \"Then press \\x1B[1m\\x1B[48;2;26;30;44m\\x1B[37m + Create new credentials \\x1b[0m \\n\"\n \"And copy/paste your \\x1B[1m\\x1B[4mAccess Key\\x1b[0m here: \".format(\n clearml_app_server.lstrip(\"/\")), end=\"\")\n\n creds = input()\n if creds:\n print(\" Setting access key \")\n ENV_ACCESS_KEY.set(creds.strip())\n\n print(\"Now copy/paste your \\x1B[1m\\x1B[4mSecret Key\\x1b[0m here: \", end=\"\")\n creds = input()\n if creds:\n print(\" Setting secret key \")\n ENV_SECRET_KEY.set(creds.strip())\n\n if ENV_ACCESS_KEY.get() and ENV_SECRET_KEY.get():\n # store in conf file for persistence in runtime\n # noinspection PyBroadException\n try:\n with open(get_config_file(), \"wt\") as f:\n f.write(\"api.credentials.access_key={}\\napi.credentials.secret_key={}\\n\".format(\n ENV_ACCESS_KEY.get(), ENV_SECRET_KEY.get()\n ))\n except Exception:\n pass\n break\n\n counter += 1\n\n print(\"\")\n if counter:\n # these emojis actually requires python 3.6+\n # print(\"\\nHurrah! \\N{face with party horn and party hat} \\N{confetti ball} \\N{party popper}\")\n print(\"\\nHurrah! \\U0001f973 \\U0001f38a \\U0001f389\")\n\n if token:\n # set Token\n ENV_AUTH_TOKEN.set(token)\n\n if token or (ENV_ACCESS_KEY.get() and ENV_SECRET_KEY.get()):\n # make sure we set environment variables to point to our api/app/files hosts\n ENV_WEB_HOST.set(Session.get_app_server_host())\n ENV_HOST.set(Session.get_api_server_host())\n ENV_FILES_HOST.set(Session.get_files_server_host())\n # verify token\n Session()\n # success\n print(\"\\N{robot face} ClearML connected successfully - let's build something! \\N{rocket}\")", "def login_user(self):\n login_url = 'ADD LOGIN URL'\n post_url = '{website}{login_url}'.format(website=self.website, login_url=login_url)\n headers = {\n 'ADD': 'HEADERS HERE',\n }\n login_params = {\n 'username': os.environ['TEST_WEB_USER'],\n 'password': os.environ['TEST_WEB_PSWD'],\n # May need to add more login parameters, based on specific use cases\n }\n\n req = requests.Request('POST', post_url, headers=headers).prepare()\n req.body = urlencode(login_params)\n req.headers['Content-Length'] = len(req.body)\n self.session.send(req)\n\n # The use case I wrote this for only set cookies if it logged in -- that may not always\n # be true, so you may need to modify this check. \n if len(self.session.cookies) == 0:\n return False\n else:\n return True", "def default_login(self):\n self.set_email('sharenet.admin@redhat.com')\n self.set_password('redhat')\n self.click_login_button()", "def get_hydeauditor_cred():\n if \"hypeauditor_name\" in os.environ and \"hypeauditor_pass\" in os.environ:\n\n h_name = os.getenv('hypeauditor_name')\n h_pass = os.environ.get('hypeauditor_pass')\n else:\n h_name = input(\"Enter your Hypeauditor UserId: \").strip()\n h_pass = input(\"Enter your Hypeauditor Password: \").strip()\n\n os.environ[\"hypeauditor_name\"] = h_name\n os.environ[\"hypeauditor_pass\"] = h_pass\n return (h_name, h_pass)", "def premium_login(session,domain, username, password):\n login = '/premium/login'\n login_url = domain + login\n\n s = session.get(login_url)\n soup = BeautifulSoup(s.text, 'html.parser')\n token = soup.select(\"#token\")[0].attrs['value']\n\n payload = {'username': username,\n 'password': password,\n 'token': token,\n 'redirect': '',\n 'from': 'pc_premium_login',\n 'segment': 'straight'\n }\n\n try:\n s = session.post(domain + '/front/authenticate', data=payload)\n\n except Exception:\n print(\"Failed to login\")", "def authentificate():\n url = \"https://transkribus.eu/TrpServer/rest/auth/login\"\n payload = 'user=' + username + '&' + 'pw=' + password\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n response = requests.request(\"POST\", url, data=payload, headers=headers)\n\n try:\n soup = BeautifulSoup(response.text, \"xml\")\n session_id = soup.sessionId.string\n print(\"User successfully authentified.\")\n except Exception as e:\n print(\"Authentification failed: username or password are not correct. Check {}/config.py\".format(CWD))\n session_id = ''\n return session_id", "def get_login():\n return {\n 'server': os.environ.get(\"DERPY_SERVER\",\n \"https://crawl.kelbi.org/#lobby\"),\n 'username': os.environ.get(\"DERPY_USERNAME\", \"username\"),\n 'password': os.environ.get(\"DERPY_PASSWORD\", \"password\"),\n }", "def login(self):\n login = self.session.get(LOGIN_URL)\n auth_url = login.url.replace(\"id.fantia.jp/auth/\", \"id.fantia.jp/authorize\")\n\n login_json = {\n \"Email\": self.email,\n \"Password\": self.password\n }\n\n login_headers = {\n \"X-Not-Redirection\": \"true\"\n }\n\n auth_response = self.session.post(auth_url, json=login_json, headers=login_headers).json()\n if auth_response[\"status\"] == \"OK\":\n auth_payload = auth_response[\"payload\"]\n\n callback = self.session.get(LOGIN_CALLBACK_URL.format(auth_payload[\"code\"], auth_payload[\"state\"]))\n if not callback.cookies[\"_session_id\"]:\n sys.exit(\"Error: Failed to retrieve session key from callback\")\n\n check_user = self.session.get(ME_API)\n if not check_user.status_code == 200:\n sys.exit(\"Error: Invalid session\")\n else:\n sys.exit(\"Error: Failed to login. Please verify your username and password\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Click Eric link in portal and wait for Eric app to open
def open_eric(self): driver = self.driver # Click the Hyperlink driver.find_element_by_link_text(self.application_link).click() # Wait for the Eric Window to open, then switch to it. WebDriverWait(driver, 20).until(lambda x: len(x.window_handles) == 2, self.driver) newwindow = driver.window_handles[-1] driver.switch_to_window(newwindow) # Check expected page is present WebDriverWait(driver, 20).until(lambda driver: "reports found for" in driver.page_source or "0 report(s) found for user" in driver.page_source) # Wait for "please wait" message to go WebDriverWait(driver, 20).until(lambda driver: not self.check_page_blocked())
[ "def openApp(self, app_name):\n time.sleep(2)\n locatorStr = ('//*[@title=\"' + app_name + '\"]')\n self.double_click_object(By.XPATH, locatorStr)", "def _open_homepage(self):\r\n if(self.web_browser_name == \"ie\"):\r\n self.driver = webdriver.Ie()\r\n elif(self.web_browser_name == \"chrome\"):\r\n self.driver = webdriver.Chrome()\r\n elif(self.web_browser_name == \"ff\"):\r\n self.driver = webdriver.Firefox()\r\n \r\n self.driver.maximize_window()\r\n self.driver.get(self.myrta_homepage)\r\n time.sleep(self.action_wait_time)\r\n booking_btn = self.driver.find_element_by_link_text('Manage booking');\r\n booking_btn.click();\r\n time.sleep(self.action_wait_time)", "def linkClick(link_type, link_name, domain, adress, port):\n raise Exception(\"Fail while executing callback.\")", "async def open_link(sid, data):\n webbrowser.open(data)", "def click_manager_test(self):\r\n \r\n \r\n driver = self.driver\r\n \r\n input_element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id=\"NationManagerLink\"]'))) \r\n checkJquery(driver);\r\n input_element.click()\r\n input_element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, \"Publications\"))) \r\n expected = 'http://127.0.0.1:5981/apps/_design/bell/nation/index.html#dashboard'\r\n actual = driver.current_url\r\n driver.implicitly_wait(10)\r\n self.assertEqual(actual, expected)", "def click_search(self):\n self.click_element(self.ACL_SUBJECTS_SEARCH_SIMPLE_TAB)\n sleep(2)", "def open_link(self):\n try:\n webbrowser.open(self.url)\n except:\n self.ids.link.text = self.link_text", "def open_portal():\n url = 'https://portal.azure.com/#@chrisbilsoncalicoenergy.onmicrosoft.com/dashboard/private/60b7336f-622f-4867-943f-f37bbbe003cd'\n webbrowser.open(url)", "def step_impl(context):\n context.browser.find_element_by_id('Caisse').click()", "def open_likes_page(self):\n self.open(\"you/likes\")\n time.sleep(2)", "def test_open_link(self):\n link = create_tiny_link(\"https://vk.com/\")\n url = reverse('links:open', args=(link.tiny_link,))\n response = self.client.get(url)\n self.assertRedirects(response,\n link.orig_link,\n status_code=302,\n target_status_code=200,\n msg_prefix='',\n fetch_redirect_response=False)", "def test_hawk_can_sees_new_link_requests(self):\n self.browser.get(LOCALHOST)\n self.browser.find_element_by_link_text('requests')\n requests = self.browser.find_element_by_id('id_requests').text\n\n self.assertEqual('requests', requests)", "def click_link_by_name(step, name):\n world.browser.click_link_by_text(name)", "def about_us_quick_links(self, link):\n # Locating the footer container\n footer_container = My.search_presence_webelement(driver, By.XPATH, \"//*[@id='c411Footer']/div[3]\")\n if footer_container:\n pass\n else:\n return\n\n count = 1\n while count < 5:\n\n # Locating the link\n quick_link = My.search_clickable_webelement(\n driver, By.XPATH, \"//*[@id='c411Footer']/div[3]/ul[1]/li[\" + str(count + 1) + \"]/a\")\n if quick_link:\n quick_link.click()\n else:\n pass\n\n # Validating the URL of the current web page depending on the count\n if count == 1:\n # print(str(driver.current_url))\n if driver.current_url == link + \"about/contact.html\":\n Canada411Home.contact_us_is_success = True\n pass\n else:\n pass\n elif count == 2:\n # print(str(driver.current_url))\n if driver.current_url == \"https://jobs.ypg.com/\":\n Canada411Home.careers_is_success = True\n pass\n else:\n pass\n elif count == 3:\n # print(str(driver.current_url))\n if driver.current_url == My.corporate_web_link + \"legal-notice/privacy-statement/\":\n Canada411Home.privacy_policy_is_success = True\n pass\n else:\n pass\n elif count == 4:\n # print(str(driver.current_url))\n if driver.current_url == My.corporate_web_link + \"legal-notice/terms-of-use-agreement/\":\n Canada411Home.terms_conditions_is_success = True\n return\n else:\n return\n count += 1\n driver.back()", "def open_adobe(self):\n self.driver.start_activity(const.PACKAGE.ADOBE,const.LAUNCH_ACTIVITY.ADOBE, wait_activity=const.PACKAGE.ADOBE + \"*\")\n if self.driver.wait_for_object(\"welcome_screen_exit_button\", timeout=10, raise_e=False):\n self.driver.click(\"welcome_screen_exit_button\")\n if self.has_overlay_ui():\n self.turn_off_overlay_ui_guide()", "def _openWebsite(self):\n webbrowser.open(websiteUrl, 2, True)", "def click_and_open_subject(self):\n self.wait_until_jquery_ajax_loaded()\n element_rowtable = self.get_table_column_and_row_by_text_contains(self.ID_ACL_SUBJECTS_SEARCH, \"Security server owners\",\"TBODY/TR\",\"TD\")\n self.click_element(element_rowtable[0])", "def go_from_landing_page_to_qes_reports_page(browser: WebDriver):\n browser.get(landing_page_url)\n\n select_location_btn = browser.find_element_by_link_text(\"Select Location\")\n select_location_btn.click()\n\n sleep(1)\n\n non_us_btn = browser.find_element_by_class_name(\"nonus\")\n non_us_btn.click()\n\n sleep(1)\n\n select_profile_btn = browser.find_element_by_link_text(\"Select Profile\")\n select_profile_btn.click()\n\n sleep(1)\n\n professional_investor_btn = browser.find_element_by_link_text(\"Professional Investor\")\n professional_investor_btn.click()\n\n sleep(1)\n\n accept_btn = browser.find_element_by_xpath(\"//input[@aria-label='Accept']\")\n accept_btn.click()\n\n # next html page\n indices_btn = WebDriverWait(browser, 5).until(\n ec.presence_of_element_located((By.LINK_TEXT, \"Indices\"))\n )\n indices_btn.click()\n\n sleep(10)\n\n def click_qes_checkbox():\n qes_checkbox = browser.find_element_by_xpath(\"//label[@for='family_QES']\")\n qes_checkbox.click()\n\n attempt_func_num_times(click_qes_checkbox, 5)\n\n jpmorgan_us_qes_momentum_series_2_link = WebDriverWait(browser, 10).until(\n ec.presence_of_element_located((By.LINK_TEXT, \"J.P. Morgan US QES Momentum Series 2\"))\n )\n jpmorgan_us_qes_momentum_series_2_link.click()\n\n # jpmc US QES momentum series 2 html page\n\n sleep(2)\n\n def click_reports_btn():\n reports_btn = browser.find_element_by_xpath('//li[text()=\"Reports\"]')\n reports_btn.click()\n\n attempt_func_num_times(click_reports_btn, 5)\n\n sleep(1)", "def __ie_confirm_cert_exception(self):\n js_cmd = \"javascript:document.getElementById('overridelink').click();\"\n try:\n self.set_page_load_timeout(1)\n super(Remote, self).get(js_cmd)\n except selenium_ex.TimeoutException:\n # \"Certificate Error\" page is not present, moving on\n pass\n finally:\n self.set_page_load_timeout(self.PAGE_LOAD_TIMEOUT)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds which reports are listed Should either be 0 or the 4/6 standard reports "Civil financial statement", "Criminal financial statement" "Family mediation financial statement" "Financial statement summary" Returns search result message, list of report names, eg. "4 reports found for 2N875V", [u'Civil financial statement', u'Criminal financial statement', u'Family mediation financial statement', u'Financial statement summary']
def report_list_items(self): driver = self.driver # No convenient locators for these items. Also response message # in different location if search unsuccessful # If report search successful, there's a div on the page # If search was successful there's a "tableBoxIndHalf2" div results_div = driver.find_elements_by_class_name("tableBoxIndHalf2") # Search result has reports if results_div: div = results_div[0] report_names = [e.text for e in div.find_elements_by_tag_name("a")] message = div.find_element_by_tag_name("p").text # Search result has no reports else: report_names = [] message = driver.find_element_by_tag_name("ul").text return message, report_names
[ "def reports(simulation, action='find', report=None):\n lreports = []\n if action == 'find':\n simulation = simulation.lower()\n simulation = sanitize(simulation)\n app.logger.debug('Checking if '\n + _REPORT_PATH + ' exists.')\n for item in os.listdir(_REPORT_PATH):\n if simulation in item:\n lreports.append(item)\n return lreports\n\n if action == 'download':\n simulation = simulation.lower()\n app.logger.debug('Checking if '\n + _REPORT_PATH + report + ' exists.')\n if report:\n report = sanitize(report)\n if os.path.exists(_REPORT_PATH + report):\n app.logger.debug('Found the path, now lets zip it up')\n zippedfile = _TMP_PATH + report + '.zip'\n try:\n zipf = zipfile.ZipFile(zippedfile, 'w')\n zipdir(report, zipf)\n zipf.close()\n return app.send_static_file(report + '.zip')\n except Exception as e:\n return e\n else:\n return (\"<h2>Error: Report \" + report +\n \" does not exist.</h2>\", 404)\n else:\n return (\"<h2>Error: No report name supplied.</h2>\", 404)", "def read_report_choice(self):\n driver = self.driver\n # No convenient identifier.\n # Also not always present\n # Also report text is in the 2nd h3 tag\n h3_texts = [e.text for e in driver.find_elements_by_tag_name(\"h3\")]\n report_name = \"\"\n if len(h3_texts) == 2:\n report_name = h3_texts[-1]\n return report_name", "def _get_reports():\n if not CONFIG:\n raise ConfigError(\"Configuration is not passed\")\n\n try:\n return CONFIG[\"reports\"]\n except KeyError:\n raise ConfigError(\"Reports configurations are missing from config\")", "def Plan_Reports(self):\n rc = self._rc\n ReportCount, ReportNames = [], []\n res = rc.Plan_GetFilename(ReportCount, ReportNames)\n return res", "def at_search_result(msg_obj, ostring, results, global_search=False,\r\n nofound_string=None, multimatch_string=None):\r\n string = \"\"\r\n if not results:\r\n # no results.\r\n if nofound_string:\r\n # custom return string\r\n string = nofound_string\r\n else:\r\n string = _(\"Could not find '%s'.\" % ostring)\r\n results = None\r\n\r\n elif len(results) > 1:\r\n # we have more than one match. We will display a\r\n # list of the form 1-objname, 2-objname etc.\r\n\r\n # check if the msg_object may se dbrefs\r\n show_dbref = global_search\r\n\r\n if multimatch_string:\r\n # custom header\r\n string = multimatch_string\r\n else:\r\n string = \"More than one match for '%s'\" % ostring\r\n string += \" (please narrow target):\"\r\n string = _(string)\r\n\r\n for num, result in enumerate(results):\r\n invtext = \"\"\r\n dbreftext = \"\"\r\n if hasattr(result, _(\"location\")) and result.location == msg_obj:\r\n invtext = _(\" (carried)\")\r\n if show_dbref:\r\n dbreftext = \"(#%i)\" % result.dbid\r\n string += \"\\n %i-%s%s%s\" % (num + 1, result.name,\r\n dbreftext, invtext)\r\n results = None\r\n else:\r\n # we have exactly one match.\r\n results = results[0]\r\n\r\n if string:\r\n msg_obj.msg(string.strip())\r\n return results", "def show_reports(self):\n try:\n sql = \"select * from Report where team_no = ?\"\n result = cursor.execute(sql, (Supervisor.team_id,))\n for i in result:\n print(\"Report Id : {}\".format(i[0]))\n print(\"Root Cause : {}\".format(i[3]))\n print(\"Details : {}\".format(i[4]))\n print(\"Status : {}\".format(i[5]))\n print(\"Death Rate : {}\".format(i[6]))\n print(\"----------------------------\")\n\n except Exception as e:\n print(\"Error in reading data\")\n finally:\n Supervisor.supervisor_tasks(self)", "def parse_report(self):\n # Retrieve the results from the report.\n discoveries = {'directories': [], 'files': [], 'errors': []}\n type_disco = 'errors'\n status_code = -1\n for line in self.stream:\n match_dir_status = re.match(self._re_dir_status, line)\n match_file_status = re.match(self._re_file_status, line)\n if match_dir_status:\n type_disco = 'directories'\n status_code = match_dir_status.group('status')\n elif match_file_status:\n type_disco = 'files'\n status_code = match_file_status.group('status')\n elif line.startswith('/'): # This line contains a discovery\n status = int(status_code)\n # If this is the section of the successful ones (2xx).\n if status >= 200 and status < 300:\n discoveries[type_disco].append(line)\n # Match found discoveries against signatures database.\n vulns = []\n matching = ((DIRECTORIES, 'directories'), (FILES, 'files'))\n for signatures, type_disco in matching:\n try:\n signatures = signatures.iteritems()\n except AttributeError: # Python3\n signatures = signatures.items()\n for signature, ranking in signatures:\n matched = [True for disco in discoveries[type_disco] if re.match(signature, disco)]\n if True in matched:\n vulns.extend([{'ranking': ranking}])\n self.vulns = vulns\n return vulns", "def list_cicd_defect_reporters(self):\n return super().request('GET', '/cicd/defectReporting')", "def reports(self):\n return self.decoder.reports.getall()", "def get_reportingsystems():\n query = '''\n PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n PREFIX proms: <http://promsns.org/def/proms#>\n SELECT ?rs ?t\n WHERE {\n ?rs a proms:ReportingSystem .\n ?rs rdfs:label ?t .\n }\n '''\n reportingsystems = queries.query(query)\n reportingsystem_items = []\n # Check if nothing is returned\n if reportingsystems and 'results' in reportingsystems:\n for reportingsystem in reportingsystems['results']['bindings']:\n ret = {\n 'rs': urllib.parse.quote(str(reportingsystem['rs']['value'])),\n 'rs_u': str(reportingsystem['rs']['value'])\n }\n if reportingsystem.get('t'):\n ret['t'] = str(reportingsystem['t']['value'])\n reportingsystem_items.append(ret)\n return reportingsystem_items", "def search_result(self, search_text, limit=15):\n records = []\n limit = self.db.llen(self.redis_key)\n for item in self.db.lrange(self.redis_key, 0, limit-1):\n if(search_text !=None):\n record_obj = json.loads(item.decode('utf-8'))\n if search_text in record_obj['SC_NAME']:\n records.append(record_obj)\n\n else:\n record_obj = json.loads(item.decode('utf-8'))\n records.append(record_obj)\n\n #return sorted(records, key = lambda x : x['HIGH']) [:10]\n return records[:10]", "def check_subs_made(report_data, period):\n errors = []\n warnings = ['\\nSubmissions Made Report Warnings:\\n']\n for student in report_data: \n if student[1] in (None, ''):\n warnings.append('Name is missing for student with Student ID '\n '{}'.format(student[0]))\n if student[2] in (None, ''):\n warnings.append('Course is missing for student with Student '\n 'ID {}'.format(student[0]))\n if student[3] in (None, ''):\n warnings.append('Tutor is missing for student with Student '\n 'ID {}'.format(student[0]))\n if student[4] in (None, ''):\n warnings.append('Assignment name is missing for student with '\n 'Student ID {}'.format(student[0]))\n if student[5] in (None, ''):\n errors.append('Last submission date is missing for student '\n 'with Student ID {}'.format(student[0]))\n # Check if any errors have been identified, save error log if they have\n name = 'Submissions_Made_{}'.format(period)\n if len(errors) > 0:\n ft.process_error_log(errors, name)\n # Check if any warnings have been identified, save error log if they have\n if len(warnings) > 1:\n return True, warnings\n else:\n return False, warnings", "def checkUnusedReports(arguments, reportName):\n Reports = ''\n #reports we dont use in production\n if arguments.unusedreports:\n Reports = arguments.unusedreports\n\n if Reports!='':\n if reportName in Reports:\n return 1", "def generateLimitedReportList(self,dataframeColumn, reportType):\n reportList = dataframeColumn\n reports = []\n idx = 0\n\n for rep in reportList:\n if reportType in rep:\n jsonval = extract_value_report_as_json(rep)\n for jsonreport in jsonval:\n #if 'error' in jsonreport:\n # raise Exception(jsonreport['exception'])\n if 'error' not in jsonreport and reportType in jsonreport['report'][0]:\n try:\n reports.append(Report(jsonreport,idx,rep))\n except Exception as e:\n print('error when creating report {0} with ex {1}'.format(idx,e))\n idx += 1\n return reports", "def _get_report_from_name(self, report_name):\n res = super(ReportXML, self)._get_report_from_name(report_name)\n\n if res:\n return res\n\n report_obj = self.env['ir.actions.report']\n qwebtypes = ['qweb-pdf', 'qweb-html','pentaho']\n conditions = [('report_type', 'in', qwebtypes), ('report_name', '=', report_name)]\n context = self.env['res.users'].context_get()\n return report_obj.with_context(context).search(conditions, limit=1)", "def find_sandbox_reports_command(\n client: Client,\n limit: int = 50,\n filter: str = \"\",\n offset: str = \"\",\n sort: str = \"\",\n hashes: str = \"\"\n) -> CommandResults:\n if hashes and not filter:\n found_reports = []\n all_report_ids = []\n raw_results: List[RawCommandResults] = []\n\n for single_hash in argToList(hashes):\n response = client.find_sandbox_reports(limit, filter, offset, sort, hashes=single_hash)\n raw_result = parse_outputs(response, reliability=client.reliability, resources_fields=('id',))\n if report_ids := (raw_result.output or {}).get('resources', []):\n found_reports.append({'sha256': single_hash, 'reportIds': report_ids})\n all_report_ids.extend(report_ids)\n\n total_count = response.get('meta', {}).get('pagination', {}).get('total', 0)\n if total_count > len(report_ids):\n demisto.info(f'Warning: there are {total_count} reports, but only {len(report_ids)} were fetched.')\n else:\n found_reports.append({'sha256': single_hash, 'reportIds': []})\n\n outputs = {\n 'resources': all_report_ids,\n 'FindReport': found_reports,\n }\n\n readable_output = tableToMarkdown(\"CrowdStrike Falcon Intelligence Sandbox response:\", {'resource': all_report_ids}) \\\n if all_report_ids else f'No reports found for hashes {hashes}.'\n return CommandResults(\n outputs_key_field='id',\n outputs_prefix=OUTPUTS_PREFIX,\n outputs=outputs,\n readable_output=readable_output,\n raw_response=raw_results,\n )\n\n else:\n if filter:\n demisto.info('Both the hashes and filter arguments were provided to the find-reports command. '\n 'Hashes are ignored in this case.')\n response = client.find_sandbox_reports(limit, filter, offset, sort, hashes=None)\n result = parse_outputs(response, reliability=client.reliability, resources_fields=('id',))\n return CommandResults(\n outputs_key_field='id',\n outputs_prefix=OUTPUTS_PREFIX,\n outputs=result.output,\n readable_output=tableToMarkdown(\"CrowdStrike Falcon Intelligence Sandbox response:\", result.output),\n raw_response=result.response,\n )", "def select_report(self, report=0):\n #reports = [\"Civil financial statement\",\n # \"Criminal financial statement\",\n # \"Family mediation financial statement\",\n # \"Financial statement summary\"]\n\n # Find the report name present on screen\n\n driver = self.driver\n # If position provided, find the associated report name\n if type(report) is int:\n _, reports = self.report_list_items()\n report_text = reports[report]\n # Otherwise just use the supplied value\n else:\n report_text = report\n\n driver.find_element_by_link_text(report_text).click()\n # Wait for \"please wait\" to go\n WebDriverWait(driver, 20).until(lambda driver: not self.check_page_blocked())", "def _lookup_report(self, cr, name):\n opj = os.path.join\n\n # First lookup in the deprecated place, because if the report definition\n # has not been updated, it is more likely the correct definition is there.\n # Only reports with custom parser sepcified in Python are still there.\n if 'report.' + name in openerp.report.interface.report_int._reports:\n new_report = openerp.report.interface.report_int._reports['report.' + name]\n else:\n cr.execute(\"SELECT * FROM ir_act_report_xml WHERE report_name=%s\", (name,))\n r = cr.dictfetchone()\n if r:\n if r['report_type'] in ['qweb-pdf', 'qweb-html']:\n return r['report_name']\n elif r['report_type'] == 'aeroo':\n new_report = self.unregister_report(cr, r['report_name'])\n elif r['report_rml'] or r['report_rml_content_data']:\n if r['parser']:\n kwargs = {'parser': operator.attrgetter(r['parser'])(openerp.addons)}\n else:\n kwargs = {}\n new_report = report_sxw('report.' + r['report_name'], r['model'],\n opj('addons', r['report_rml'] or '/'), header=r['header'], register=False, **kwargs)\n elif r['report_xsl'] and r['report_xml']:\n new_report = report_rml('report.' + r['report_name'], r['model'],\n opj('addons', r['report_xml']),\n r['report_xsl'] and opj('addons', r['report_xsl']), register=False)\n else:\n raise Exception, \"Unhandled report type: %s\" % r\n else:\n raise Exception, \"Required report does not exist: %s (Type: %s\" % r\n\n return new_report", "def reports(self):\n try:\n for post in self.subreddit.mod.reports(limit=None):\n for mod_report in post.mod_reports:\n yield (str(mod_report[0]), mod_report[1], post)\n except prawcore.PrawcoreException as exception:\n logging.error(\"Error fetching reports: %s\", exception)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select Report on Eric Main Screen by position (from 0) or by name. Only selects, does not open.
def select_report(self, report=0): #reports = ["Civil financial statement", # "Criminal financial statement", # "Family mediation financial statement", # "Financial statement summary"] # Find the report name present on screen driver = self.driver # If position provided, find the associated report name if type(report) is int: _, reports = self.report_list_items() report_text = reports[report] # Otherwise just use the supplied value else: report_text = report driver.find_element_by_link_text(report_text).click() # Wait for "please wait" to go WebDriverWait(driver, 20).until(lambda driver: not self.check_page_blocked())
[ "def selectScreen(self, screen_name):\n time.sleep(1) #this is a hack. Otherwise it won't find the app consistently. Need to double-check implicit/explicit waits\n screen_tile = AppEditorPageLocators(screen_name)\n self.click_object_at_location(1, 1, *screen_tile.screen_tile) #clicking without specifying location opens the screen", "def select(specs):\n\tDataManager.clearSelections()\n\tDataManager.select(specs, True)", "def _get_report_from_name(self, report_name):\n res = super(ReportXML, self)._get_report_from_name(report_name)\n\n if res:\n return res\n\n report_obj = self.env['ir.actions.report']\n qwebtypes = ['qweb-pdf', 'qweb-html','pentaho']\n conditions = [('report_type', 'in', qwebtypes), ('report_name', '=', report_name)]\n context = self.env['res.users'].context_get()\n return report_obj.with_context(context).search(conditions, limit=1)", "def view_saved(cls):\n print(\"\")\n for index, report in enumerate(cls.data):\n print(f\"{index+1}. {report['name']}\")\n\n selection = input(\"\\nWhich report would you like to see? \")\n\n cls.view_report(cls.data[int(selection)-1]['report'], True)", "def selectComponent(self, component_name):\n time.sleep(1) #this is a hack. Otherwise it won't find the app consistently. Need to double-check implicit/explicit waits\n component_tiles = ScreenEditorPageLocators(component_name)\n self.click_object_at_location(1, 1, *component_tiles.component_name_tile) #clicking without specifying location opens the screen", "def _getspectra_selected( self, name, tbsel={} ):\n isthere=os.path.exists(name)\n self.assertEqual(isthere,True,\n msg='file %s does not exist'%(name)) \n tb.open(name)\n sp = []\n if len(tbsel) == 0:\n for i in range(tb.nrows()):\n sp.append(tb.getcell('SPECTRA', i).tolist())\n else:\n command = ''\n for key, val in tbsel.items():\n if len(command) > 0:\n command += ' AND '\n command += ('%s in %s' % (key, str(val)))\n newtb = tb.query(command)\n for i in range(newtb.nrows()):\n sp.append(newtb.getcell('SPECTRA', i).tolist())\n newtb.close()\n\n tb.close()\n return sp", "def read_report_choice(self):\n driver = self.driver\n # No convenient identifier.\n # Also not always present\n # Also report text is in the 2nd h3 tag\n h3_texts = [e.text for e in driver.find_elements_by_tag_name(\"h3\")]\n report_name = \"\"\n if len(h3_texts) == 2:\n report_name = h3_texts[-1]\n return report_name", "def selectTrack(self, track):\n\n if track:\n cmds.select(track)\n self.setCameraFocus()\n else:\n cmds.select(clear=True)", "def select_user_and_print_report(self):\n self.print_all_transaction(self.prompt_user_selection())", "def select(self):\r\n arg_str = p2e._base._util._convert_args_to_string(\"object.select\", self._object._eco_id)\r\n p2e._app.Exec(arg_str)", "def msselect(self, *args, **kwargs):\n return _ms.ms_msselect(self, *args, **kwargs)", "def view_report(self):\n driver = self.driver\n # Click \"View Report\" button\n # lacks a convenient identifier\n # Accessing via its parent form\n form = driver.find_element_by_id(\"ReportDetailsForm\")\n # Contains multiple \"input\" fields, filter to get right one\n input_elements = [e for e in form.find_elements_by_tag_name(\"input\")\n if e.get_attribute(\"value\") == \"View Report\"]\n button = input_elements[0]\n button.click()\n # Report is in a new window - switch to it\n driver.switch_to_window(driver.window_handles[-1])\n # Wait for \"Please Wait to go\"\n WebDriverWait(driver, 20).until(lambda driver: not self.check_page_blocked())", "def selectApp(self, app_name):\n time.sleep(2) #this is a hack. Otherwise it won't find the app consistently. Need to double-check implicit/explicit waits\n #locatorStr = ('//*[@title=\"' + app_name + '\"]')\n #self.click_object(By.XPATH, locatorStr)\n app_tile = WorkspacePageLocators(app_name)\n #self.highlight(*app_tile.app_tile)\n self.click_object_at_location(1, 1, *app_tile.app_tile)", "def select_qrev(self):\r\n\r\n # Get the current folder setting.\r\n folder = self.default_folder()\r\n\r\n # Get the full names (path + file) of the selected file\r\n self.fullName = QtWidgets.QFileDialog.getOpenFileName(\r\n self, self.tr('Open File'), folder,\r\n self.tr('QRev File (*_QRev.mat)'))[0]\r\n\r\n # Initialize parameters\r\n self.type = ''\r\n self.checked = False\r\n\r\n # Process fullName if selection was made\r\n if self.fullName:\r\n self.type = 'QRev'\r\n self.process_names()\r\n self.close()", "def select(button):\n changeLanguage(button.text)\n subscreen.clear_widgets()\n Subject()\n changeScreen(\"Subject\")", "def selectFrontView(self):\r\n basicFilter = \"Image Files (*.png *.tiff);;PNG (*.png);;TIFF (*.tiff);;All Files (*.*)\"\r\n self.hide()\r\n self.FrontImagePath = cmds.fileDialog2(caption=\"Please select front image\", fileFilter=basicFilter, fm=1)\r\n self.lineFront.setText(str(self.FrontImagePath[0]))\r\n self.show()", "def get_selections(screen_def, column_name ):\n if debug:\n logger.debug(\"Retrieving row selections from window {}\".format(screen_def['hlist']))\n hlist = screen_def['hlist'] \n # Step through the selected rows and return a list of the column\n # values for the designated column name\n try:\n selected_rows = hlist.info_selection()\n if debug:\n logger.debug('Row selections = {}'.format(selected_rows))\n # Step through the columns on the screen to find the\n # column number of the desired column name\n # Recall that column[0] is an Oracle column name and\n # column[1] is its corresponding header name\n for i,column in enumerate(screen_def['columns']):\n if column[0].lower().find(column_name.lower()) == 0:\n column_number = i\n # To retrieve the value of a displayed column we must pass the\n # row number and column number to the hlist item_get function\n column_values = []\n for row_number in selected_rows:\n column_value = hlist.item_cget(row_number,column_number,'-text') \n column_values.append(column_value.strip())\n\n if debug:\n logger.debug(\"Column values = {}\".format(column_values))\n \n if len(column_values) == 0: \n display_error(\"Selection ERROR\",\"Nothing selected \" )\n return None\n else:\n return column_values\n except Exception as e:\n logger.exception(str(e)) \n display_error(\"Selection ERROR\",str(e))\n return None", "def go_to_position_type(self, position_name):\n\n select = Select(self.driver.find_element_by_name(\"EmpListSkill\"))\n try:\n self.logger.info(\"{}:\".format(position_name))\n select.select_by_visible_text(position_name)\n except SeleniumExceptions.NoSuchElementException:\n raise SeleniumExceptions.NoSuchElementException(\"Unable to find '{}' in the list.\".format(position_name))", "def suites_option_select_by_visible_text(self, element_text):\n suite_selector_drp = Select(self.browser.find_element(*locators.SuiteManagerPageLocators.SUITE_SELECTOR_DPDN))\n suite_selector_drp.select_by_visible_text(element_text)\n time.sleep(10)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the name of the report currently selected
def read_report_choice(self): driver = self.driver # No convenient identifier. # Also not always present # Also report text is in the 2nd h3 tag h3_texts = [e.text for e in driver.find_elements_by_tag_name("h3")] report_name = "" if len(h3_texts) == 2: report_name = h3_texts[-1] return report_name
[ "def get_report_title(self):\n return None", "def _get_report_from_name(self, report_name):\n res = super(ReportXML, self)._get_report_from_name(report_name)\n\n if res:\n return res\n\n report_obj = self.env['ir.actions.report']\n qwebtypes = ['qweb-pdf', 'qweb-html','pentaho']\n conditions = [('report_type', 'in', qwebtypes), ('report_name', '=', report_name)]\n context = self.env['res.users'].context_get()\n return report_obj.with_context(context).search(conditions, limit=1)", "def select_report(self, report=0):\n #reports = [\"Civil financial statement\",\n # \"Criminal financial statement\",\n # \"Family mediation financial statement\",\n # \"Financial statement summary\"]\n\n # Find the report name present on screen\n\n driver = self.driver\n # If position provided, find the associated report name\n if type(report) is int:\n _, reports = self.report_list_items()\n report_text = reports[report]\n # Otherwise just use the supplied value\n else:\n report_text = report\n\n driver.find_element_by_link_text(report_text).click()\n # Wait for \"please wait\" to go\n WebDriverWait(driver, 20).until(lambda driver: not self.check_page_blocked())", "def name(self):\n return self._pr.title", "def form_name(self):\n return '%s_%s' % (self._report_code_name, self._name)", "def selected_title(self):\n return self.title", "def view_saved(cls):\n print(\"\")\n for index, report in enumerate(cls.data):\n print(f\"{index+1}. {report['name']}\")\n\n selection = input(\"\\nWhich report would you like to see? \")\n\n cls.view_report(cls.data[int(selection)-1]['report'], True)", "def instrument_name(self):\n return self.label['INSTRUMENT_NAME']", "def get_name(self):\n\t\treturn self._env.get_project_name()", "def _get_output_file_name(self):\n file_path = QFileDialog.getOpenFileName(parent=self)\n if file_path[0] != \"\":\n self._output_edit.setText(file_path[0])\n return", "def name(self):\r\n return self.delegate.BrowserName", "def current_filename(self):\n return self.dr.fileName()", "def name(self) -> str:\n return self.project.name", "def getProjectName(self):\n mapping = projects.get_project_mapping()\n if self.project in mapping:\n return mapping[self.project]\n else:\n return \"Unknown\"", "def _get_name(self) -> \"std::string\" :\n return _core.Workspace__get_name(self)", "def build_report_name(self, cr, uid, ids, data, context=None):\n from datetime import datetime\n res = self.read(cr, uid, ids, context=context)[0]\n period_id = res['period_id'][0]\n period_date = datetime.strptime(\n self.pool.get('account.period').browse(\n cr, uid, period_id).date_stop, \"%Y-%m-%d\"\n )\n company_id = self.pool.get('res.company')._company_default_get(\n cr, uid, object='account.print.chart.accounts.report',\n context=context\n )\n company = self.pool.get('res.company').browse(\n cr, uid, company_id, context=context\n )\n vat_split = company.partner_id.vat_split\n\n report_name_sat = ''.join([\n vat_split,\n str(period_date.year),\n str(period_date.month).rjust(2, '0'),\n 'PL']\n )\n return report_name_sat", "def instrument_name(self):\n return self.get('instrument_name', decode=True)", "def _get_name(self) -> \"std::string\" :\n return _core.DropDownControl__get_name(self)", "def get_menu_item_name(self):\n return self.menu_item_name" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Click the "View Report" button Switch focus to new report window that appears. Wait for "Please Wait" message to dissapear.
def view_report(self): driver = self.driver # Click "View Report" button # lacks a convenient identifier # Accessing via its parent form form = driver.find_element_by_id("ReportDetailsForm") # Contains multiple "input" fields, filter to get right one input_elements = [e for e in form.find_elements_by_tag_name("input") if e.get_attribute("value") == "View Report"] button = input_elements[0] button.click() # Report is in a new window - switch to it driver.switch_to_window(driver.window_handles[-1]) # Wait for "Please Wait to go" WebDriverWait(driver, 20).until(lambda driver: not self.check_page_blocked())
[ "def get_reports_window(self):\n self.gui.active_window.hide()\n\n self.associated_window = reports_window.ReportsWindow(self.gui)\n self.gui.active_window = self.associated_window\n\n self.gui.active_window.show()", "def switch_to_analysis_window():\n driver.switch_to.window(driver.window_handles[1])", "def close_report(self):\n driver = self.driver\n # Buttons lack convenient labels. Finding by tag name\n button_div = driver.find_element_by_id(\"buttons2\")\n buttons = button_div.find_elements_by_tag_name(\"a\")\n # Click the \"Close Report\" button (assuming its the last one)\n buttons[-1].click()\n # Return Window focus\n driver.switch_to_window(driver.window_handles[-1])", "def select_report(self, report=0):\n #reports = [\"Civil financial statement\",\n # \"Criminal financial statement\",\n # \"Family mediation financial statement\",\n # \"Financial statement summary\"]\n\n # Find the report name present on screen\n\n driver = self.driver\n # If position provided, find the associated report name\n if type(report) is int:\n _, reports = self.report_list_items()\n report_text = reports[report]\n # Otherwise just use the supplied value\n else:\n report_text = report\n\n driver.find_element_by_link_text(report_text).click()\n # Wait for \"please wait\" to go\n WebDriverWait(driver, 20).until(lambda driver: not self.check_page_blocked())", "def test_view_report_page(self):\n # check that there is comment\n # check that there is comment form\n ReportFactory.create(user=self.user, empty=True, mentor=self.mentor,\n month=datetime.date(2012, 1, 1))\n c = Client()\n response = c.get(reverse('reports_view_report',\n kwargs={'display_name': self.up.display_name,\n 'year': '2012',\n 'month': 'January'}))\n self.assertTemplateUsed(response, 'view_report.html')", "def viewallsi():\n tc('select to view all stage instances')\n e=g.wait.until(EC.presence_of_element_located((By.XPATH,\n \"//div[@class='iboDialogLoading']\")))\n sleep(3)\n #g.wait.until(EC.staleness_of(e))\n e=g.wait.until(EC.element_to_be_clickable((By.XPATH,\n \"//input[@id='cb_stageMetricsTable']\")))\n e.click()\n g.wait.until(EC.element_to_be_clickable((By.XPATH,\n \"//button[@id='smViewInstButton']\"))).click()\n g.wait.until(EC.element_to_be_clickable((By.XPATH,\n \"//table[@id='stageInstancesTable']//tr[@id='1']/td/a[contains\\\n (@href, 'siRedirectMWSProcessInstanceDetail')]\"))).click()", "def open_eric(self):\n driver = self.driver\n # Click the Hyperlink\n driver.find_element_by_link_text(self.application_link).click()\n # Wait for the Eric Window to open, then switch to it.\n WebDriverWait(driver, 20).until(lambda x: len(x.window_handles) == 2, self.driver)\n newwindow = driver.window_handles[-1]\n driver.switch_to_window(newwindow)\n # Check expected page is present\n WebDriverWait(driver, 20).until(lambda driver:\n \"reports found for\" in driver.page_source\n or \"0 report(s) found for user\" in driver.page_source)\n # Wait for \"please wait\" message to go\n WebDriverWait(driver, 20).until(lambda driver: not self.check_page_blocked())", "def open_browser(self):\n self.driver.maximize_window()\n self.driver.get(self.url)", "def Show(self):\n wx.Dialog.Show(self)\n wx.Yield()", "def test_report_bug(self, browser, login, close):\n self.open_run_test_page_for_1st_test(browser)\n run_test_page = RunTestPage(browser)\n # run_title = run_test_page.get_title()\n run_test_page.report_a_bug_btn_click()\n run_test_page.wait_new_page_load()\n page_title = run_test_page.get_title()\n assert page_title == 'Sign in to your account' or 'ADO', \"Should not be 'Cases' page'\"", "def view_saved(cls):\n print(\"\")\n for index, report in enumerate(cls.data):\n print(f\"{index+1}. {report['name']}\")\n\n selection = input(\"\\nWhich report would you like to see? \")\n\n cls.view_report(cls.data[int(selection)-1]['report'], True)", "def _select_main_window(self):\n self.driver.switch_to.window(self.main_window_handle)", "def open_expense_window(self):\n self.expense_window.show()", "def Show(msg, exc):\n dialog = BugReport()\n dialog.SetContent(msg, exc)\n dialog.ShowModal()\n dialog.Destroy()", "def _open_homepage(self):\r\n if(self.web_browser_name == \"ie\"):\r\n self.driver = webdriver.Ie()\r\n elif(self.web_browser_name == \"chrome\"):\r\n self.driver = webdriver.Chrome()\r\n elif(self.web_browser_name == \"ff\"):\r\n self.driver = webdriver.Firefox()\r\n \r\n self.driver.maximize_window()\r\n self.driver.get(self.myrta_homepage)\r\n time.sleep(self.action_wait_time)\r\n booking_btn = self.driver.find_element_by_link_text('Manage booking');\r\n booking_btn.click();\r\n time.sleep(self.action_wait_time)", "def wait_until_debit_card_tracker_displayed(self):\n self.wait_until_dashboard_displayed()\n tracker = BaseElement(self.driver, locators.DEBIT_CARD_TRACKER)\n # Sometimes the tracker doesn't display right away, added a refresh to cover this case\n if tracker.not_displayed():\n self.driver.refresh()\n tracker.wait_until_displayed()", "def go_from_landing_page_to_qes_reports_page(browser: WebDriver):\n browser.get(landing_page_url)\n\n select_location_btn = browser.find_element_by_link_text(\"Select Location\")\n select_location_btn.click()\n\n sleep(1)\n\n non_us_btn = browser.find_element_by_class_name(\"nonus\")\n non_us_btn.click()\n\n sleep(1)\n\n select_profile_btn = browser.find_element_by_link_text(\"Select Profile\")\n select_profile_btn.click()\n\n sleep(1)\n\n professional_investor_btn = browser.find_element_by_link_text(\"Professional Investor\")\n professional_investor_btn.click()\n\n sleep(1)\n\n accept_btn = browser.find_element_by_xpath(\"//input[@aria-label='Accept']\")\n accept_btn.click()\n\n # next html page\n indices_btn = WebDriverWait(browser, 5).until(\n ec.presence_of_element_located((By.LINK_TEXT, \"Indices\"))\n )\n indices_btn.click()\n\n sleep(10)\n\n def click_qes_checkbox():\n qes_checkbox = browser.find_element_by_xpath(\"//label[@for='family_QES']\")\n qes_checkbox.click()\n\n attempt_func_num_times(click_qes_checkbox, 5)\n\n jpmorgan_us_qes_momentum_series_2_link = WebDriverWait(browser, 10).until(\n ec.presence_of_element_located((By.LINK_TEXT, \"J.P. Morgan US QES Momentum Series 2\"))\n )\n jpmorgan_us_qes_momentum_series_2_link.click()\n\n # jpmc US QES momentum series 2 html page\n\n sleep(2)\n\n def click_reports_btn():\n reports_btn = browser.find_element_by_xpath('//li[text()=\"Reports\"]')\n reports_btn.click()\n\n attempt_func_num_times(click_reports_btn, 5)\n\n sleep(1)", "def report_filling_view(request):\n if request.method == 'POST':\n document_file_path = report_controller.generate_report(request)\n request.session['report_file_path'] = document_file_path\n request.session.modified = True\n return redirect(reverse('reports:final_report'))\n\n report_id = request.session['report_id']\n context = report_forms_util.get_report_body_filling_form(report_id)\n return render(request, 'reports/report_filling.html', context)", "def proceed_chosen_report_view(request, report_id):\n request.session['report_id'] = report_id\n request.session.modified = True\n\n report = Report.objects.get(id=report_id)\n if report.type == 'regular':\n return redirect(reverse('reports:users'))\n elif report.type == 'custom':\n return redirect(reverse('reports:edit_service_members_chain'))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Click close report button Return focus back to main Eric window.
def close_report(self): driver = self.driver # Buttons lack convenient labels. Finding by tag name button_div = driver.find_element_by_id("buttons2") buttons = button_div.find_elements_by_tag_name("a") # Click the "Close Report" button (assuming its the last one) buttons[-1].click() # Return Window focus driver.switch_to_window(driver.window_handles[-1])
[ "def cancel(self):\r\n\r\n self.parent.focus_set()\r\n self.window.destroy()", "def close_window(self):\r\n Window.close()", "def close(self):\n\n Dialog.close(self)\n gui.no_modal_dialog=True", "def click_button_close(self):\n # AutoGen method click_link: None\n self.click_element(self.BUTTON_CLOSE)", "def close_window(_):\n root.destroy()", "def closeEvent(self, event):\n\n # Remove the viewer widget from the main GUI and exit.\n self.parent_gui.display_widget(None, display=False)\n self.close()", "def OnCloseWindow(self):\n pass", "def closeEntry(self):\n\n # clear the entry from entryTabs\n self.clearEntry()\n\n # reset codebookEntries\n codebookEntries = self.getCodebookEntries()\n codebookEntries.setCurrentRow(-1)\n self.lastSelectedEntry = -1", "def closeWindowCallback(self, event):\n\t\tself.EndModal(self.status)", "def ev_windowclose(self, event: WindowEvent) -> None:", "def close_create_from_ado_query_window(self):\n self.visible_element_click(locators.SuiteManagerPageLocators.CLOSE_ICON,2)", "def close_active_document():\n wrap_and_run('close saving yes')", "def close_copy_test_suite_window(self):\n self.visible_element_click(locators.SuiteManagerPageLocators.CLOSE_ICON,4)", "def closeEvent(self, event):\n self.viewer_closing_sig.emit(False)\n QWidget.closeEvent(self,event)", "def close_alert(self):\n self.nottreal.view.wizard_window.close_alert()", "def close_window(window):\r\n window.destroy()", "def OnClose(self, event):\n event.Veto()\n if self.GetClosable():\n self.Close()\n evt = wxPageClosedEvent()\n wx.PostEvent(self, evt)", "def click_close(self) -> None:\r\n self.analyse_instances.clear()\r\n self.w.reinit_start_ui()", "def close_other_windows(self) -> None:\r\n while len(self.driver.window_handles) != 1:\r\n self.switch_to_window(1)\r\n self.close_window()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Log out from Eric and the Portal (if present) Note if accessed using Modify Headers, Portal logout not possible.
def log_out(self): driver = self.driver window_count = len(driver.window_handles) # Click Eric logout link driver.find_element_by_link_text("Log out").click() # Follow-up Portal logout if window_count ==2: # Wait for the Eric window to close WebDriverWait(driver, 20).until(lambda x: len(x.window_handles) == 1, self.driver) # Ensure focus is on the portal window driver.switch_to_window(driver.window_handles[0]) # Click the portqal log out link driver.find_element_by_link_text("Log Out").click() # Wait for confirmation message WebDriverWait(driver, 20).until(lambda driver: '<h1 class="heading-xlarge">Logged Out</h1>' in driver.page_source) # Non portal else: WebDriverWait(driver, 20).until(lambda driver: "You have successfully logged out of EMI application" in driver.page_source)
[ "def logout(self):\n self.session.get(EE_LOGOUT_URL)", "def logout():\n _logout()", "def logout():\n helper.set_login_state(False)\n helper.update_session('Authorization', None)", "def logout(self): #simple enough lol\n self.currentuser = None\n return self.post_request(**{'action': 'logout'})", "def logout_user(self):", "def persona_logout():\n if 'user_id' in session:\n del session['user_id']\n return 'OK'", "def logout(request):\n # make sure we reset any admin tab selection\n if 'active_admin_tab' in request.session:\n del request.session['active_admin_tab']\n messages.success(request, 'You are now logged out.')\n return logout_then_login(request)", "def logout_user():\n session['logged_in'] = False\n session['permission'] = ''\n session['name'] = ''", "def logout():\n session.pop('user')\n pass", "def logout(self):\n self.state = 'logged_out'", "def logout():\r\n client = load_portal_client()\r\n\r\n # Revoke the tokens with Globus Auth\r\n for token, token_type in (\r\n (token_info[ty], ty)\r\n # get all of the token info dicts\r\n for token_info in session['tokens'].values()\r\n # cross product with the set of token types\r\n for ty in ('access_token', 'refresh_token')\r\n # only where the relevant token is actually present\r\n if token_info[ty] is not None):\r\n client.oauth2_revoke_token(\r\n token, additional_params={'token_type_hint': token_type})\r\n\r\n # Destroy the session state\r\n session.clear()\r\n\r\n redirect_uri = url_for('index', _external=True)\r\n\r\n ga_logout_url = []\r\n ga_logout_url.append(app.config['GLOBUS_AUTH_LOGOUT_URI'])\r\n ga_logout_url.append('?client={}'.format(app.config['PORTAL_CLIENT_ID']))\r\n ga_logout_url.append('&redirect_uri={}'.format(redirect_uri))\r\n ga_logout_url.append('&redirect_name=NUCAPT DMS')\r\n\r\n # Redirect the user to the Globus Auth logout page\r\n return redirect(''.join(ga_logout_url))", "def logout(self):\n if self.currentUser is not None:\n self.currentUser = None\n self.run() #For return to login user\n else: print(\"There is not a login user.\")", "def staff_logout():\n print(colored('\\nYou have successfully logged out.', 'yellow',\n attrs=['bold']))\n print(colored('Please contact HR for any further queries.\\n',\n 'yellow', attrs=['bold']))\n exit()", "def logout(self):\n self.response.headers.add_header(\"Set-Cookie\", \"user_id=; Path=/\")", "def logout():\r\n logout_user()\r\n return redirect(url_for('explore'))", "def logout(request, config_loader_path=None):\n state = StateCache(request.session)\n conf = get_config(config_loader_path, request)\n\n client = Saml2Client(conf, state_cache=state,\n identity_cache=IdentityCache(request.session))\n subject_id = _get_subject_id(request.session)\n if subject_id is None:\n logger.warning(\n 'The session does not contain the subject id for user %s',\n request.user)\n\n result = client.global_logout(subject_id)\n\n state.sync()\n\n if not result:\n logger.error(\"Looks like the user %s is not logged in any IdP/AA\", subject_id)\n return HttpResponseBadRequest(\"You are not logged in any IdP/AA\")\n\n if len(result) > 1:\n logger.error('Sorry, I do not know how to logout from several sources. I will logout just from the first one')\n\n for entityid, logout_info in result.items():\n if isinstance(logout_info, tuple):\n binding, http_info = logout_info\n if binding == BINDING_HTTP_POST:\n logger.debug('Returning form to the IdP to continue the logout process')\n body = ''.join(http_info['data'])\n return HttpResponse(body)\n elif binding == BINDING_HTTP_REDIRECT:\n logger.debug('Redirecting to the IdP to continue the logout process')\n return HttpResponseRedirect(get_location(http_info))\n else:\n logger.error('Unknown binding: %s', binding)\n return HttpResponseServerError('Failed to log out')\n else:\n # We must have had a soap logout\n return finish_logout(request, logout_info)\n\n logger.error('Could not logout because there only the HTTP_REDIRECT is supported')\n return HttpResponseServerError('Logout Binding not supported')", "def test_log_out_user(self):\n pass", "def logout(self):\n next_url = request.args.get('next') or \"\"\n next_url = self.app.config['FRONT_SERVER'] + '#' + next_url\n self.logout_user(self.get_logged_in_user())\n return redirect(\n flask_cas.logout(self.app.config['AUTH_SERVER'], next_url))", "def logout():\n return render_template('logOut.html')" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the current selected text of a combo box.
def get_selected_text(self, widget): return widget.GetStringSelection()
[ "def get_active_text_in_combobox(self,combobox):\n model = combobox.get_model()\n active = combobox.get_active()\n if active < 0:\n return None\n\n return model[active][0]", "def get_value(self) -> str:\n text = self.combo.currentText()\n return self.options[text]", "def get_selected_text(self):\r\n editor = self._main.get_current_editor()\r\n if editor:\r\n return editor.textCursor().selectedText()\r\n return None", "def get_selected_value(self):\n return self.get_widget().get()", "def get_current_selection(self):\n return self.current_selection", "def get_text(self):\n data = self.txtbox.get(1.0, END)\n test = self.txtbox.selection_get()", "def get_selected_item(self):\r\n return self.selected_item", "def get_text(self):\n return self.widget.GetValue()", "def GetCurrentSelection(self):\n if self.current != -1:\n return self.ItemList[self.current]\n else:\n return None", "def get_text(self):\r\n editor = self._main.get_current_editor()\r\n if editor:\r\n return editor.get_text()\r\n return", "def _get_drop_down_widget_value(widget):\n return widget.itemData(widget.currentIndex()).toPyObject()", "def get_current_selection(self):\n\n return self.get_current_selection_folder().load_file_selection()", "def get_current_text(self) -> Optional[SccCaptionText]:\n return self._current_text", "def getCurrentCodebook(self):\n\n currentCodebookIndex = self.codebookTabs.currentIndex()\n cb_name = self.codebookTabs.tabText(currentCodebookIndex)\n return (cb_name, self.settings['codebooks'][cb_name])", "def get_selected_value_index(self):\n return self.__current", "def get_text(self, widget):\n return widget.GetLabel()", "def find_combo_box_item(self, text: str, raise_on_failure=True):\n wait_for_condition(lambda: self.find_control(\n 'ListItem', text, parent=self.suite.application.top_window(), raise_on_failure=False) is\n not None)\n return self.find_control('ListItem',\n text,\n parent=self.suite.application.top_window(),\n raise_on_failure=raise_on_failure)", "def GetNewCatStrHndlr(self):\r\n self.newCatStr = self.edtNewCat.selectedText()", "def get_text(self):\n data = self.txtbox.get(1.0, END)\n print(data)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the text of a combo box item at a particular index.
def get_item_text(self, widget, index): return widget.GetString(index)
[ "def get_value(self) -> str:\n text = self.combo.currentText()\n return self.options[text]", "def get_active_text_in_combobox(self,combobox):\n model = combobox.get_model()\n active = combobox.get_active()\n if active < 0:\n return None\n\n return model[active][0]", "def find_combo_box_item(self, text: str, raise_on_failure=True):\n wait_for_condition(lambda: self.find_control(\n 'ListItem', text, parent=self.suite.application.top_window(), raise_on_failure=False) is\n not None)\n return self.find_control('ListItem',\n text,\n parent=self.suite.application.top_window(),\n raise_on_failure=raise_on_failure)", "def get_selected_text(self, widget):\n return widget.GetStringSelection()", "def _get_drop_down_widget_value(widget):\n return widget.itemData(widget.currentIndex()).toPyObject()", "def _find_combo_data(widget, value):\n for i in range(widget.count()):\n if widget.itemData(i) == value:\n return i\n raise ValueError(\"%s not found in combo box\" % value)", "def get_text(self):\n return self.widget.GetValue()", "def get_text(self):\n data = self.txtbox.get(1.0, END)\n test = self.txtbox.selection_get()", "def get_text(self, widget):\n return widget.GetLabel()", "def getter(self, widget):\n return widget.itemData(widget.currentIndex())", "def get_item(self):\n text = self.item_id_edit.text()\n self.item_id = str.upper(text)\n \n self.item_id_edit.setText(self.item_id)\n \n self.get_item_signal.emit(self.item_index, self.item_id)", "def listItemSelected(self, index):\n self.selectedTitle = self.listBox.getSelectedItem()\n if self.selectedTitle == \"\":\n self.outputArea.setText(\"\")\n else:\n self.outputArea.setText(str(self.database[self.selectedTitle]))", "def get1(self, index: 'int const') -> \"SbString\":\n return _coin.SoMField_get1(self, index)", "def user32_GetComboBoxInfo(jitter):\n ret_ad, args = jitter.func_args_stdcall([\"hwndCombo\", \"pcbi\"])\n raise RuntimeError('API not implemented')\n jitter.func_ret_stdcall(ret_ad, ret_value)", "def test_combobox_texts(self):\n # The ComboBox on the sample app has following items:\n # 0. Combo Item 1\n # 1. Combo Item 2\n ref_texts = ['Combo Item 1', 'Combo Item 2']\n\n combo_box = self.dlg.ComboBox.find()\n self.assertEqual(combo_box.item_count(), len(ref_texts))\n for t in combo_box.texts():\n self.assertEqual((t in ref_texts), True)\n\n # Mock a 0 pointer to COM element\n combo_box.iface_item_container.FindItemByProperty = mock.Mock(return_value=0)\n self.assertEqual(combo_box.texts(), ref_texts)\n\n # Mock a combobox without \"ItemContainer\" pattern\n combo_box.iface_item_container.FindItemByProperty = mock.Mock(side_effect=uia_defs.NoPatternInterfaceError())\n self.assertEqual(combo_box.texts(), ref_texts)\n\n # Mock a combobox without \"ExpandCollapse\" pattern\n # Expect empty texts\n combo_box.iface_expand_collapse.Expand = mock.Mock(side_effect=uia_defs.NoPatternInterfaceError())\n self.assertEqual(combo_box.texts(), [])", "def choice_text(val, choices):\n for choice in choices:\n if choice[0]==val:\n return choice[1]\n return None", "def get_ascii_character(index):\n\n return characters.characters[index]", "def get_selected_value(self):\n return self.get_widget().get()", "def get_text(self):\n data = self.txtbox.get(1.0, END)\n print(data)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the GNG graph database
def __init_graph(self) -> None: self.graph = Graph()
[ "def _init_graph(self):\n\n self.graph = tf.Graph()\n with self.graph.as_default():\n self._init_network_variables()\n self._init_network_functions()", "def __init__(self):\n self.G = nx.Graph()\n self.node_attr_dfs = dict()\n self.unique_relations = set()\n self.node_types = dict()\n self.normalized_node_id_map = dict()\n self.train_edges = list()\n self.valid_edges = list()\n self.test_edges = list()\n self.relation_to_id = dict()\n self.id_to_relation = dict()\n self.nodeid2rowid = dict()\n self.rowid2nodeid = dict()\n self.rowid2vocabid = dict()", "def load_db_into_graph():\n graph = Graph()\n\n for category in models.Category.objects.all():\n data = {'title': category.title}\n added_vertex = graph.add_vertex('category', data, current_id='c-{}'.format(category.pk))\n\n for agency in models.Agency.objects.all():\n data = {'title': agency.title,\n 'short_name': agency.short_name}\n added_vertex = graph.add_vertex('agency', data, current_id='a-{}'.format(agency.pk))\n\n for listing in models.Listing.objects.all():\n data = {'title': listing.title,\n 'description': listing.description,\n 'is_private': listing.is_private,\n 'security_marking': listing.security_marking,\n 'is_enabled': listing.is_enabled,\n 'is_deleted': listing.is_deleted,\n 'is_featured': listing.is_featured,\n 'approval_status': listing.approval_status}\n\n if listing.is_enabled and not listing.is_deleted and listing.approval_status == models.Listing.APPROVED:\n added_vertex = graph.add_vertex('listing', data, current_id='l-{}'.format(listing.pk))\n\n # One Agency per listing\n current_agency = listing.agency\n added_vertex.add_edge('listingAgency', graph.get_vertex('a-{}'.format(current_agency.pk)))\n\n # Many Categories per listing\n for current_category in listing.categories.all():\n added_vertex.add_edge('listingCategory', graph.get_vertex('c-{}'.format(current_category.pk)))\n\n for profile in models.Profile.objects.all():\n data = {'username': profile.user.username,\n 'highest_role': profile.highest_role()}\n added_vertex = graph.add_vertex('profile', data, current_id='p-{}'.format(profile.pk))\n\n # Many Agencies per profile\n for current_agency in profile.organizations.all():\n added_vertex.add_edge('agency', graph.get_vertex('a-{}'.format(current_agency.pk)))\n\n # Many stewardedAgency Agencies per profile\n for current_agency in profile.stewarded_organizations.all():\n added_vertex.add_edge('stewardedAgency', graph.get_vertex('a-{}'.format(current_agency.pk)))\n\n for current_entry in models.ApplicationLibraryEntry.objects.filter(owner=profile):\n current_listing = current_entry.listing\n data = {'folder_name': current_entry.folder}\n added_vertex.add_edge('bookmarked', graph.get_vertex('l-{}'.format(current_listing.pk)), data)\n\n return graph", "def init_graph():\r\n graph = nx.Graph()\r\n graph.add_node(1)\r\n graph.add_edge(1, 1)\r\n return graph", "def construct_graph(self):\r\n\t\tedges = self.generate_edges()\r\n\t\tfor edge in edges:\r\n\t\t\tself.insert_edge(edge[0],edge[1],edge[2]) # adds all the edges to graph\r", "def init(self):\n self.graph = tf.Graph()\n return self.graph", "def init_with_database(self):\n\n with self._lock:\n self._metrics.init_with_database()", "def __init__(self) -> None:\r\n self.db = Db()\r\n self.init_db()", "def __init__(self):\n self.graph = Graph()\n self._configure_namespaces()\n self.dcat_vocabularies = URIRef(dcat_config['vocabularies'])\n self.language_map = dcat_config['language_map']\n self.dcat_spec = dcat_config['rdf']\n self.exclusion = self.dcat_spec['_exclusions']", "def _initialize():\n\n\t\t# Read the configuration from file:\n\t\tdbType = Config.get(\"localdb\", \"type\")\n\t\tdbName = Config.get(\"localdb\", \"name\")\n\t\tdbHost = Config.get(\"localdb\", \"hostname\")\n\t\tdbUser = Config.get(\"localdb\", \"username\")\n\t\tdbPass = Config.get(\"localdb\", \"password\")\n\t\t\n\t\t# Construct the dbPath string, or rais an exception if the dbtype is unknown.\n\t\tif(dbType == \"sqlite\"):\n\t\t\tdbpath = 'sqlite:///' + dbName\n\t\telif(dbType == \"mysql\"):\n\t\t\tdbpath = dbType + \"://\" + dbUser + \":\" + dbPass + \"@\" + dbHost + \"/\" + dbName\n\t\telse:\n\t\t\traise Exception(\"DatabaseConfiguration is not correct\")\n\t\t\n\t\t# Create a dbengine, and depending on the configfile maybe turn on the debug.\n\t\tif(Config.get(\"localdb\", \"debug\") == \"0\"):\n\t\t\tSession.engine = create_engine(dbpath)\n\t\telse:\n\t\t\tSession.engine = create_engine(dbpath, echo=True)\n\t\t\n\t\t# Create a session, and bind it to the engine.\n\t\tSession.session = sessionmaker(bind=Session.engine)\n\t\t\n\t\t# Making sure that the dbSchema is created.\n\t\tBase.metadata.create_all(Session.engine)", "def __create_graph(self):\n self.clear() \n self.__ordered_network()\n self.__create_new_random_connections()", "def __init__(self):\n self.G = nx.MultiDiGraph()\n self.registry = {}\n # self.load_biothings()\n self.all_edges_info = self.G.edges(data=True)\n self.all_labels = {d[-1]['label'] for d in self.all_edges_info}\n self.all_inputs = {d[-1]['input_type'] for d in self.all_edges_info}\n self.all_outputs = {d[-1]['output_type'] for d in self.all_edges_info}", "def __init__(self):\n self.g = nx.DiGraph()", "async def _init(self):\n\n self.postgres = await self.try_connect_postgres(\n host=self.config['postgres']['host'],\n database=self.config['postgres']['database'],\n user=self.config['postgres']['user'],\n password=self.config['postgres']['password'])\n\n try:\n async with self.postgres.acquire() as conn:\n async with conn.cursor() as curs:\n # create tables if they don't already exist\n await curs.execute('''\n CREATE TABLE body (\n id SERIAL PRIMARY KEY,\n sha256 text,\n content text\n );\n\n CREATE TABLE mailitem (\n id SERIAL PRIMARY KEY,\n datesent timestamp,\n subject text,\n fromaddress text,\n bodyid integer REFERENCES body (id)\n );\n\n CREATE TABLE recipient (\n id SERIAL PRIMARY KEY,\n emailaddress text\n );\n\n CREATE TABLE mailrecipient (\n id SERIAL PRIMARY KEY,\n recipientid integer REFERENCES recipient (id),\n mailid integer REFERENCES mailitem (id)\n );\n\n CREATE TABLE attachment (\n id SERIAL PRIMARY KEY,\n mailid integer REFERENCES mailitem (id),\n sha256 text,\n filename text\n );\n ''')\n logger.debug(\"Created fresh database\")\n except:\n pass", "def __init__ (self, gconf):\n self.gconf = gconf", "def initializeDataRegistry():\n\n dbcursor.execute(\"\"\"DROP TABLE IF EXISTS DataRegistry\"\"\")\n dbconnector.commit()\n\n dbcursor.execute(\n \"\"\"\n CREATE TABLE IF NOT EXISTS DataRegistry (\n Data_ID INTEGER PRIMARY KEY,\n Perm_No INTEGER,\n Date DATE NOT NULL,\n Open DOUBLE,\n High DOUBLE,\n Low DOUBLE,\n Close DOUBLE,\n Volume DOUBLE,\n Dividends DOUBLE,\n Stock_Splits DOUBLE,\n SAR DOUBLE,\n RSI DOUBLE,\n CCI DOUBLE,\n MACDHist DOUBLE,\n BBUpperBand DOUBLE,\n BBMiddleBand DOUBLE,\n BBLowerBand DOUBLE,\n EMA DOUBLE,\n Chaikin DOUBLE,\n StochK DOUBLE,\n StochD DOUBLE,\n WILLR DOUBLE,\n memPred DOUBLE,\n polyregPred DOUBLE,\n ranForPred DOUBLE,\n FOREIGN KEY (Perm_No)\n REFERENCES IDRegistry (Perm_No)\n );\n \"\"\"\n )\n\n dbcursor.execute(\n \"\"\"\n CREATE UNIQUE INDEX nix_permno_date ON DataRegistry (Perm_No, Date)\n \"\"\"\n )\n\n dbconnector.commit()", "def initialize():\n db = orderportal.database.get_db()\n orderportal.config.load_settings_from_db(db)\n orderportal.database.update_design_documents(db)", "def initialize(self):\n # setting the seed\n #pdb.set_trace()\n\n # create tf session\n self.sess = tf.Session()\n\n # tensorboard stuff\n self.add_summary()\n # initiliaze all variables\n init = tf.global_variables_initializer()\n self.sess.run(init)\n\n if self.config.use_baseline:\n self.baseline_network.set_session(self.sess)", "def __init__(self, number_of_vertices: int):\n super().__init__(number_of_vertices)\n\n self.__graph: Dict[int: List[int]] = {}\n\n for i in range(number_of_vertices):\n self.__graph[i] = []" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to load the header record and test that it actually loads it without exceptions
def test_header_record(header_record): rec = HeaderRecord() rec.load(header_record) assert rec.bank_app == 'T' assert rec.app_id == '363914' assert rec.edi_msg == 'HEADER' assert rec.separator is None assert rec.rec_typ == '00' assert rec.app_ver == '01.0000' assert rec.app_brand == 'BBCSOB'
[ "def test_advmul_header_record(advmul_header_record, advmuz_header_record):\n rec = AdvmulHeaderRecord()\n rec.load(advmul_header_record)\n\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'ADVMUL'\n assert rec.separator is None\n assert rec.rec_typ == '01'\n assert rec.msg_rno == '20140930925710'\n\n rec.load(advmuz_header_record)\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'ADVMUZ'\n assert rec.separator is None\n assert rec.rec_typ == '01'\n assert rec.msg_rno == '20140930925710'", "def test_read_header():\n header = get_header(AIA_193_JP2)[0]\n assert isinstance(header, FileHeader)", "def test_simple_with_incorrect_header(self):\r\n log.debug('CAG TEST: INCORRECT HEADER')\r\n stream_handle = StringIO(TEST_DATA_bts)\r\n parser = CtdpfCklWfpSioParser(self.config, stream_handle,\r\n self.exception_callback)\r\n # next get records\r\n result = parser.get_records(4)\r\n if result:\r\n log.debug('CAG TEST: FAILED TO DETECT INCORRECT HEADER')\r\n self.fail()\r\n else:\r\n log.debug('CAG TEST: INCORRECT HEADER DETECTED')\r\n pass", "def test_can_load_this_header(self):\n\n class TestImporter(Importer):\n def can_load_this_header(self, header) -> bool:\n return False\n\n def can_load_this_filename(self, filename):\n return True\n\n def can_load_this_type(self, suffix):\n return True\n\n def can_load_this_file(self, file_contents):\n return True\n\n def _load_this_file(self, data_store, path, file_contents, data_file):\n pass\n\n processor = FileProcessor()\n\n processor.register_importer(TestImporter(\"\", \"\", \"\", \"\"))\n self.assertEqual(len(processor.importers), 1)\n self.assertEqual(type(processor.importers[0]), TestImporter)\n\n temp_output = StringIO()\n with redirect_stdout(temp_output):\n processor.process(DATA_PATH, None, False)\n output = temp_output.getvalue()\n\n self.assertIn(\"Files got processed: 0 times\", output)", "def test_header_valid(self):\n header = self.capfile.header\n self.assertEqual(header.major, 2, 'invalid major version!')\n self.assertEqual(header.minor, 4, 'invalid minor version!')", "def verify_start_of_header_for_body(self):\r\n if self.compressed:\r\n next_line = str(self.file.readline(), 'utf-8')\r\n else:\r\n next_line = self.file.readline()\r\n\r\n if next_line.startswith(f'#CHROM'):\r\n self.body_header_line = Body_header_line(next_line)\r\n if self.body_header_line.invalid is True:\r\n self.invalid = True\r\n self.error_message = self.body_header_line.error_message\r\n else:\r\n self.invalid = True\r\n self.error_message = f'There is no second header line specifiying data in the body in file: {self.path}'", "def test_record_loading(self):\n test_record = self.db.lookup(accession = \"X55053\")\n assert test_record.name == \"ATCOR66M\"\n assert test_record.id == \"X55053.1\", test_record.id\n assert test_record.description == \"A.thaliana cor6.6 mRNA.\"\n assert isinstance(test_record.seq.alphabet, Alphabet.DNAAlphabet)\n assert test_record.seq[:10].tostring() == 'AACAAAACAC'\n\n test_record = self.db.lookup(accession = \"X62281\")\n assert test_record.name == \"ATKIN2\"\n assert test_record.id == \"X62281.1\", test_record.id\n assert test_record.description == \"A.thaliana kin2 gene.\"\n assert isinstance(test_record.seq.alphabet, Alphabet.DNAAlphabet)\n assert test_record.seq[:10].tostring() == 'ATTTGGCCTA'", "def test_read_header(self):\n self.test_dir = tempfile.mkdtemp(dir='./', prefix='TestHealSparse-')\n filename = os.path.join(self.test_dir, 'test_array.fits')\n\n data0 = np.zeros(10, dtype=np.int32)\n data1 = np.zeros(10, dtype=np.float64)\n header = healsparse.fits_shim._make_header({'AA': 0,\n 'BB': 1.0,\n 'CC': 'test'})\n self.write_testfile(filename, data0, data1, header)\n\n with HealSparseFits(filename) as fits:\n exts = [0, 1, 'COV', 'SPARSE']\n for ext in exts:\n header_test = fits.read_ext_header(ext)\n for key in header:\n self.assertEqual(header_test[key], header[key])", "def parse_header(self, line):\n bml.logger.debug(\"BssFile.parse_header(line=%s)\" % (line))\n # GJP 2021-04-16 Allow empty system names\n m = re.match(r\"(?P<file_type>.)00\\{(?P<system_name>[^\\}]*)\\}=NYYYYYY(?P<summary>.*$)\", line)\n assert m, \"line (%s) does not match header record\" % (line)\n self.file_type = m.group('file_type')\n self.system_name = m.group('system_name')\n self.summary = m.group('summary').rstrip()\n bml.logger.debug(\"file_type: %s; system_name: %s; summary: %s\" % (self.file_type, self.system_name, self.summary))\n self.state_nr = self.state_nr + 1 # only one header\n return True", "def test_bad_header(self):\n mock_filefield = generate_filefield('bad_ocdid_header_csv.csv')\n\n with self.assertRaisesRegexp(\n ValidationError, 'First column must be named \\'ocd_id\\''):\n validate_geodataset_upload(mock_filefield)", "def test_bad_headers(self):\n\n # this file does not have enough header lines\n file_handle = open(os.path.join(RESOURCE_PATH, 'short_header.mrg'), 'rU')\n\n with self.assertRaises(DatasetParserException):\n parser = GliderParser(self.config, file_handle, self.exception_callback)\n\n parser.get_records(1)\n\n # this file specifies a number of header lines other than 14\n file_handle = open(os.path.join(RESOURCE_PATH, 'bad_num_header_lines.mrg'), 'rU')\n\n with self.assertRaises(DatasetParserException):\n parser = GliderParser(self.config, file_handle, self.exception_callback)\n\n parser.get_records(1)\n\n # this file specifies a number of label lines other than 3\n file_handle = open(os.path.join(RESOURCE_PATH, 'bad_num_label_lines.mrg'), 'rU')\n\n with self.assertRaises(DatasetParserException):\n parser = GliderParser(self.config, file_handle, self.exception_callback)\n\n parser.get_records(1)", "def test_sesans_mandatory_headers(self):\n self.assertRaises(\n FileContentsException,\n self.loader,\n find(\"no_wavelength.ses\"))", "def test_translate_header(self):\n with io.StringIO() as out:\n with io.StringIO() as err:\n okay, failed = process_files(\n [TESTDATA],\n r\"^fitsheader.*yaml$\",\n 0,\n False,\n outstream=out,\n errstream=err,\n output_mode=\"none\",\n )\n self.assertEqual(self._readlines(out), [])\n lines = self._readlines(err)\n self.assertEqual(len(lines), 10)\n self.assertTrue(lines[0].startswith(\"Analyzing\"), f\"Line: '{lines[0]}'\")\n\n self.assertEqual(len(okay), 10)\n self.assertEqual(len(failed), 0)", "def test_get_header_data(session):\n # setup\n title = 'Test Title'\n # test\n data = report_utils.get_header_data(title)\n # verify\n assert data\n assert data.find(title) != -1", "def validate_header(header: str) -> None:\n header_pattern = r\"^sourceId,RTSsymbol$\"\n if not re.match(header_pattern, header):\n raise ImproperFileFormat(\"Improperly formatted header\")", "def test_wrong_load(self):\n from os.path import join\n bad_file = join(self.ocb_dir, \"test\", \"test_data\", \"test_vort\")\n header, data = ocb_ismag.load_supermag_ascii_data(bad_file)\n\n self.assertListEqual(header, list())\n self.assertDictEqual(data, dict())\n del bad_file, data, header", "def test_frame_load(self):\n self.init_capfile(layers=1)\n for packet in self.capfile.packets:\n for field in ['src', 'dst', 'type', 'payload']:\n self.assertTrue(hasattr(packet.packet, field),\n 'invalid frame!')", "def _ReadRecordHeader(self, file_object, record_header_offset):\n data_type_map = self._GetDataTypeMap('keychain_record_header')\n\n record_header, _ = self._ReadStructureFromFileObject(\n file_object, record_header_offset, data_type_map)\n\n return record_header", "def _validate_header(self, header):\n missing_fields = []\n for field in self.REQUIRED_FIELDS:\n if field not in header:\n missing_fields.append(field)\n if missing_fields:\n return False, missing_fields\n return True, None" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to load the lock record and test that it actually loads it without exceptions
def test_lock_record(lock_record): rec = LockRecord() rec.load(lock_record) assert rec.bank_app == 'T' assert rec.app_id == '363914' assert rec.edi_msg == 'LOCK' assert rec.separator is None assert rec.rec_typ == '99' assert rec.count == 0 assert rec.timestamp == datetime.datetime(year=2014, month=9, day=2, hour=7, minute=9, second=22) assert rec.seq_no == 11
[ "def load(self):\n self.__lockData = {}\n data = None\n try:\n with open(self.__path, 'r') as lockfile:\n data = json.load(lockfile)\n lockfile.close()\n except json.decoder.JSONDecodeError:\n Logger.warning(\"MEG Locking: Unable to read contents of lock file at {0}\".format(self.__path))\n return False\n except FileNotFoundError:\n Logger.info(\"MEG Locking: Lock file doesn't yet exist at {0}\".format(self.__path))\n return True\n if data is not None:\n self.__lockData = data\n return True", "def test_recordpersistance_load(self):\n rdict = {job.seq : job for job in self.records}\n records_copy = load_records('tests', self.config)\n rdict_copy = {job.seq : job for job in records_copy}\n for key in rdict.viewkeys():\n self.assertEqual(rdict[key].__dict__,\n rdict_copy[key].__dict__)", "def test_load(self):\n locker0 = Locker.create(self.tempdir, self.content_path(), b'01234567')\n locker = Locker.load(self.work_path(Locker.filename))\n locker.unpack(self.work_path('unpacked', create=True), b'01234567', locker0.mac)\n\n with open(self.work_path('unpacked/content/secrets.txt'), 'rb') as f:\n self.assertEqual(f.read(), b'testing')\n self.assertEqual(locker.mac, locker0.mac)", "def load_locks(self):\n self.db_locks = MongoClient().test_database.db.locks\n # drop db for testing, will not be in deployed version\n self.db_locks.drop()\n # print(self.db_locks)\n return True", "def test_lock_with_validity():\n ttl = 1000\n lock = RedLock(\"test_simple_lock\", [{\"host\": \"localhost\"}], ttl=ttl)\n locked, validity = lock.acquire_with_validity()\n lock.release()\n assert locked is True\n assert 0 < validity < ttl - ttl * CLOCK_DRIFT_FACTOR - 2", "def test_wait_for_db_read(self):\n # if retrieves operational error then db isn't available\n with patch('django.db.utils.ConnectionHandler.__getitem__') as gi:\n # means whenever django.db.utils.ConnectionHandles.__getitem__\n # is called during test, instead of performing the behaviour\n # replace with mock object and return True\n gi.return_velue = True\n call_command('wait_for_db')\n self.assertEqual(gi.call_count, 1)", "def test_lockfile(self):\n with lockfile(self.path) as lock:\n self.assertIsInstance(lock, LockFile)", "def test_record_loading(self):\n test_record = self.db.lookup(accession = \"X55053\")\n assert test_record.name == \"ATCOR66M\"\n assert test_record.id == \"X55053.1\", test_record.id\n assert test_record.description == \"A.thaliana cor6.6 mRNA.\"\n assert isinstance(test_record.seq.alphabet, Alphabet.DNAAlphabet)\n assert test_record.seq[:10].tostring() == 'AACAAAACAC'\n\n test_record = self.db.lookup(accession = \"X62281\")\n assert test_record.name == \"ATKIN2\"\n assert test_record.id == \"X62281.1\", test_record.id\n assert test_record.description == \"A.thaliana kin2 gene.\"\n assert isinstance(test_record.seq.alphabet, Alphabet.DNAAlphabet)\n assert test_record.seq[:10].tostring() == 'ATTTGGCCTA'", "def test_refreshing_unheld_lock_fails(self):\n time, thing, locker = self._create_locker()\n\n self.assertEqual(None, locker.get_holder(thing),\n \"Nobody holds the lock at this point.\")\n\n for is_editing in [True, False]:\n try:\n locker.refresh_lock(thing, self.user1, is_editing)\n self.fail(\"Refreshing an unheld lock cannot succeed.\")\n except models.LockException:\n pass", "def test_lockfile_failure(self):\n with lockfile(self.path) as lock1:\n with lockfile(self.path, max_retries=0) as lock2:\n self.assertIsInstance(lock1, LockFile)\n self.assertIsNone(lock2)", "def test_simple_lock():\n lock = RedLock(\"test_simple_lock\", [{\"host\": \"localhost\"}], ttl=1000)\n locked = lock.acquire()\n lock.release()\n assert locked is True", "def test_read_lock_acquired(self) -> None:\n # First to acquire this lock, so it should complete\n lock = self.get_success(\n self.store.try_acquire_read_write_lock(\"name\", \"key\", write=False)\n )\n assert lock is not None\n\n # Enter the context manager\n self.get_success(lock.__aenter__())\n\n # Attempting to acquire the write lock fails\n lock2 = self.get_success(\n self.store.try_acquire_read_write_lock(\"name\", \"key\", write=True)\n )\n self.assertIsNone(lock2)\n\n # Attempting to acquire a read lock succeeds\n lock3 = self.get_success(\n self.store.try_acquire_read_write_lock(\"name\", \"key\", write=False)\n )\n assert lock3 is not None\n self.get_success(lock3.__aenter__())\n\n # Calling `is_still_valid` reports true.\n self.assertTrue(self.get_success(lock.is_still_valid()))\n\n # Drop the first lock\n self.get_success(lock.__aexit__(None, None, None))\n\n # Attempting to acquire the write lock still fails, as lock3 is still\n # active.\n lock4 = self.get_success(\n self.store.try_acquire_read_write_lock(\"name\", \"key\", write=True)\n )\n self.assertIsNone(lock4)\n\n # Drop the still open third lock\n self.get_success(lock3.__aexit__(None, None, None))\n\n # We can now acquire the lock again.\n lock5 = self.get_success(\n self.store.try_acquire_read_write_lock(\"name\", \"key\", write=True)\n )\n assert lock5 is not None\n self.get_success(lock5.__aenter__())\n self.get_success(lock5.__aexit__(None, None, None))", "def testLockExclusivity(self):\n lock_path = os.path.join(self.tempdir, 'locked_file')\n with locking.PortableLinkLock(lock_path, max_retry=0):\n with self.assertRaises(locking.LockNotAcquiredError):\n with locking.PortableLinkLock(lock_path, max_retry=5, sleep=0.1):\n self.fail('We acquired a lock twice?')", "def test_default_connection_details_value():\n RedLock(\"test_simple_lock\")", "def test_lock_already_exists(self):\n\n # Create a lock using a new mutex\n new_mutex = RedisMutex(self.redis, block_time=10, expiry=12)\n new_mutex = new_mutex.acquire_lock(self.key)\n\n self.mutex.block_time = 1\n with self.assertRaises(BlockTimeExceedError):\n self.mutex.acquire_lock(self.key)\n\n # A blocking mutex will raise a MutexLockError instead of\n # BlockTimeExceedError as blcok time does not comes into play\n # during locking of a non blocking mutex.\n self.mutex.blocking = False\n with self.assertRaises(MutexLockError):\n self.mutex.acquire_lock(self.key)\n\n new_mutex.release_lock()", "def test_drop(self) -> None:\n\n lock = self.get_success(self.store.try_acquire_lock(\"name\", \"key\"))\n self.assertIsNotNone(lock)\n\n del lock\n\n # Wait for the lock to timeout.\n self.reactor.advance(2 * _LOCK_TIMEOUT_MS / 1000)\n\n lock2 = self.get_success(self.store.try_acquire_lock(\"name\", \"key\"))\n self.assertIsNotNone(lock2)", "def test_lockfunc_failure(self):\n myfunction_withlock = lockfunc(self.path, max_retries=0)(myfunction)\n with lockfile(self.path):\n self.assertIsNone(myfunction_withlock())\n self.assertEqual(myfunction_withlock(), \"In my function\")", "def test_try_lock():\n with throttle(b\"[semaphores]\\nA=1\") as url:\n # We hold the lease, all following calls are going to block\n first = Peer.from_server_url(url)\n first.acquire(\"A\")\n with pytest.raises(Timeout):\n with lock(BASE_URL, \"A\", timeout=timedelta(seconds=1)):\n pass", "def test_context_manager_failure_to_acquire(self):\n lock2 = self.locker.lock('test_it', blocking=False)\n assert lock2.acquire() is True\n\n with pytest.raises(pals.AcquireFailure):\n with self.locker.lock('test_it'):\n pass # we should never hit this line" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to load the advmul header record (in both variants) and test that it actually loads it without exceptions
def test_advmul_header_record(advmul_header_record, advmuz_header_record): rec = AdvmulHeaderRecord() rec.load(advmul_header_record) assert rec.bank_app == 'T' assert rec.app_id == '363914' assert rec.edi_msg == 'ADVMUL' assert rec.separator is None assert rec.rec_typ == '01' assert rec.msg_rno == '20140930925710' rec.load(advmuz_header_record) assert rec.bank_app == 'T' assert rec.app_id == '363914' assert rec.edi_msg == 'ADVMUZ' assert rec.separator is None assert rec.rec_typ == '01' assert rec.msg_rno == '20140930925710'
[ "def test_header_record(header_record):\n rec = HeaderRecord()\n rec.load(header_record)\n\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'HEADER'\n assert rec.separator is None\n assert rec.rec_typ == '00'\n assert rec.app_ver == '01.0000'\n assert rec.app_brand == 'BBCSOB'", "def test_advmul_record(advmul_record):\n rec = AdvmulRecord()\n rec.load(advmul_record)\n\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'ADVMUL'\n assert rec.separator is None\n assert rec.rec_typ == '02'\n assert rec.message_type is None\n assert rec.transact_no == 'IBATL58813'\n assert rec.weight == 100\n assert rec.route_no == '0300'\n assert rec.client_no == '9903252820'\n assert rec.client_name == 'Whatever corp Inc.'\n assert rec.client_account_no == '177148326'\n assert rec.client_reference is None\n assert rec.bank_reference == '20623'\n assert rec.date is None\n assert rec.date_process == datetime.datetime(2014, 10, 2, 0, 0)\n assert rec.date_process_other is None\n assert rec.amount == -6075\n assert rec.currency == 'CZK'\n assert rec.balance == Decimal('3608328.02')\n assert rec.balance_code == 'C'\n assert rec.offset_account_bank_code == '0100'\n assert rec.offset_account_no == '100060018432071'\n assert rec.offset_account_name == 'PO'\n assert rec.constant_symbol == 3558\n assert rec.variable_symbol == 26696797\n assert rec.specific_symbol == 0\n assert rec.variable_symbol_offset == 26696797\n assert rec.specific_symbol_offset == 0\n assert rec.message1 is None\n assert rec.message2 is None\n assert rec.message3 is None\n assert rec.message4 is None\n assert rec.note is None\n assert rec.balance_final is None\n assert rec.balance_final_code is None\n assert rec.balance_time is None", "def test_simple_with_incorrect_header(self):\r\n log.debug('CAG TEST: INCORRECT HEADER')\r\n stream_handle = StringIO(TEST_DATA_bts)\r\n parser = CtdpfCklWfpSioParser(self.config, stream_handle,\r\n self.exception_callback)\r\n # next get records\r\n result = parser.get_records(4)\r\n if result:\r\n log.debug('CAG TEST: FAILED TO DETECT INCORRECT HEADER')\r\n self.fail()\r\n else:\r\n log.debug('CAG TEST: INCORRECT HEADER DETECTED')\r\n pass", "def test_read_header():\n header = get_header(AIA_193_JP2)[0]\n assert isinstance(header, FileHeader)", "def test_header_valid(self):\n header = self.capfile.header\n self.assertEqual(header.major, 2, 'invalid major version!')\n self.assertEqual(header.minor, 4, 'invalid minor version!')", "def test_wrong_load(self):\n from os.path import join\n bad_file = join(self.ocb_dir, \"test\", \"test_data\", \"test_vort\")\n header, data = ocb_ismag.load_supermag_ascii_data(bad_file)\n\n self.assertListEqual(header, list())\n self.assertDictEqual(data, dict())\n del bad_file, data, header", "def test_load_failure(self):\n self.data = ocb_ivort.load_vorticity_ascii_data(\"fake_file\")\n\n self.assertIsNone(self.data)", "def test_advmuz_record(advmuz_record):\n rec = AdvmuzRecord()\n rec.load(advmuz_record)\n\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'ADVMUZ'\n assert rec.separator is None\n assert rec.rec_typ == '02'\n assert rec.message_type == 'CRE'\n assert rec.client_no == '9903252820'\n assert rec.order_reference == '019938742626501A'\n assert rec.reference_item == '4083604409'\n assert rec.weight == 90\n assert rec.client_account_no == '183861478'\n assert rec.creditor_address1 == 'Big Group a.s.'\n assert rec.creditor_address2 == 'Na Pankraci 1620/1214000 Praha 4'\n assert rec.creditor_address3 == 'CZ'\n assert rec.creditor_address4 is None\n assert rec.creditor_account_no == 'CZ2155000000005081107282'\n assert rec.creditor_bank1 is None\n assert rec.creditor_bank2 is None\n assert rec.creditor_bank3 is None\n assert rec.creditor_bank4 is None\n assert rec.payment_reason1 == '/ROC/NOT PROVIDED//174914'\n assert rec.payment_reason2 is None\n assert rec.payment_reason3 is None\n assert rec.payment_reason4 is None\n assert rec.amount == Decimal('760.00')\n assert rec.currency == 'EUR'\n assert rec.amount_account_currency == Decimal('760.00')\n assert rec.account_currency == 'EUR'\n assert rec.exchange_rate == Decimal('1.0000000')\n assert rec.local_fee == Decimal('70.00')\n assert rec.local_currency == 'CZK'\n assert rec.foreign_fee == Decimal('0.00')\n assert rec.foreign_currency == 'EUR'\n assert rec.other_fees == Decimal('0.00')\n assert rec.other_fees_currency is None\n assert rec.date == datetime.datetime(2014, 9, 19, 0, 0)\n assert rec.date_process == datetime.datetime(2014, 9, 19, 0, 0)\n assert rec.date_due is None\n assert rec.client_advice1 == '/ROC/NOT PROVIDED//174914'\n assert rec.client_advice2 is None\n assert rec.client_advice3 is None\n assert rec.client_advice4 is None\n assert rec.client_advice5 is None\n assert rec.fee_settling == 'SHA'\n assert rec.swift_code == 'RZBCCZPP'\n assert rec.payment_title is None\n assert rec.routing_code is None", "def verify_start_of_header_for_body(self):\r\n if self.compressed:\r\n next_line = str(self.file.readline(), 'utf-8')\r\n else:\r\n next_line = self.file.readline()\r\n\r\n if next_line.startswith(f'#CHROM'):\r\n self.body_header_line = Body_header_line(next_line)\r\n if self.body_header_line.invalid is True:\r\n self.invalid = True\r\n self.error_message = self.body_header_line.error_message\r\n else:\r\n self.invalid = True\r\n self.error_message = f'There is no second header line specifiying data in the body in file: {self.path}'", "def test_wrong_load(self):\n self.data = ocb_ivort.load_vorticity_ascii_data(self.bad_file)\n\n self.assertIsNone(self.data)", "def test_bad_headers(self):\n\n # this file does not have enough header lines\n file_handle = open(os.path.join(RESOURCE_PATH, 'short_header.mrg'), 'rU')\n\n with self.assertRaises(DatasetParserException):\n parser = GliderParser(self.config, file_handle, self.exception_callback)\n\n parser.get_records(1)\n\n # this file specifies a number of header lines other than 14\n file_handle = open(os.path.join(RESOURCE_PATH, 'bad_num_header_lines.mrg'), 'rU')\n\n with self.assertRaises(DatasetParserException):\n parser = GliderParser(self.config, file_handle, self.exception_callback)\n\n parser.get_records(1)\n\n # this file specifies a number of label lines other than 3\n file_handle = open(os.path.join(RESOURCE_PATH, 'bad_num_label_lines.mrg'), 'rU')\n\n with self.assertRaises(DatasetParserException):\n parser = GliderParser(self.config, file_handle, self.exception_callback)\n\n parser.get_records(1)", "def test_include_dblp_section(self, mock_docmeta):\n mock_docmeta.arxiv_identifier = Identifier('1806.00001')\n mock_docmeta.primary_archive = Archive('cs')\n self.assertTrue(include_dblp_section(mock_docmeta))\n self.assertEqual(get_computed_dblp_listing_path(mock_docmeta),\n 'db/journals/corr/corr1806.html#abs-1806-00001')\n\n mock_docmeta.arxiv_identifier = Identifier('cs/0501001')\n mock_docmeta.primary_archive = Archive('cs')\n self.assertTrue(include_dblp_section(mock_docmeta))\n self.assertEqual(get_computed_dblp_listing_path(mock_docmeta),\n 'db/journals/corr/corr0501.html#abs-cs-0501001')\n\n mock_docmeta.arxiv_identifier = Identifier('cs/0412001')\n mock_docmeta.primary_archive = Archive('cs')\n self.assertTrue(include_dblp_section(mock_docmeta))\n self.assertIsNone(get_computed_dblp_listing_path(mock_docmeta))\n\n mock_docmeta.arxiv_identifier = Identifier('1806.00002')\n mock_docmeta.primary_archive = Archive('math')\n self.assertFalse(include_dblp_section(mock_docmeta))", "def test_read_header(self):\n self.test_dir = tempfile.mkdtemp(dir='./', prefix='TestHealSparse-')\n filename = os.path.join(self.test_dir, 'test_array.fits')\n\n data0 = np.zeros(10, dtype=np.int32)\n data1 = np.zeros(10, dtype=np.float64)\n header = healsparse.fits_shim._make_header({'AA': 0,\n 'BB': 1.0,\n 'CC': 'test'})\n self.write_testfile(filename, data0, data1, header)\n\n with HealSparseFits(filename) as fits:\n exts = [0, 1, 'COV', 'SPARSE']\n for ext in exts:\n header_test = fits.read_ext_header(ext)\n for key in header:\n self.assertEqual(header_test[key], header[key])", "def test_frame_load(self):\n self.init_capfile(layers=1)\n for packet in self.capfile.packets:\n for field in ['src', 'dst', 'type', 'payload']:\n self.assertTrue(hasattr(packet.packet, field),\n 'invalid frame!')", "def test_can_load_this_header(self):\n\n class TestImporter(Importer):\n def can_load_this_header(self, header) -> bool:\n return False\n\n def can_load_this_filename(self, filename):\n return True\n\n def can_load_this_type(self, suffix):\n return True\n\n def can_load_this_file(self, file_contents):\n return True\n\n def _load_this_file(self, data_store, path, file_contents, data_file):\n pass\n\n processor = FileProcessor()\n\n processor.register_importer(TestImporter(\"\", \"\", \"\", \"\"))\n self.assertEqual(len(processor.importers), 1)\n self.assertEqual(type(processor.importers[0]), TestImporter)\n\n temp_output = StringIO()\n with redirect_stdout(temp_output):\n processor.process(DATA_PATH, None, False)\n output = temp_output.getvalue()\n\n self.assertIn(\"Files got processed: 0 times\", output)", "def _validate_header(self, header):\n missing_fields = []\n for field in self.REQUIRED_FIELDS:\n if field not in header:\n missing_fields.append(field)\n if missing_fields:\n return False, missing_fields\n return True, None", "def test_sesans_mandatory_headers(self):\n self.assertRaises(\n FileContentsException,\n self.loader,\n find(\"no_wavelength.ses\"))", "def test_translate_header(self):\n with io.StringIO() as out:\n with io.StringIO() as err:\n okay, failed = process_files(\n [TESTDATA],\n r\"^fitsheader.*yaml$\",\n 0,\n False,\n outstream=out,\n errstream=err,\n output_mode=\"none\",\n )\n self.assertEqual(self._readlines(out), [])\n lines = self._readlines(err)\n self.assertEqual(len(lines), 10)\n self.assertTrue(lines[0].startswith(\"Analyzing\"), f\"Line: '{lines[0]}'\")\n\n self.assertEqual(len(okay), 10)\n self.assertEqual(len(failed), 0)", "def _parse_header(self):\n log.debug('---In dcd.py, parse_header()')\n #process the first header block\n\n header1 = self._fo.read(92)\n header1_format=\\\n \"i---cccci---i---i---i---xxxxxxxxxxxxxxxxxxxxf---i---i---xxxxxxxxxxxxxxxxxxxxxxxxxxxxi---i---\"\n # |1 |5 |10 |15 |20 |25 |30 |35 |40 |45 |50 |55 |60 |65 |70 |75 |80 |85 |90\n #|header size=84 |nframes*tstep |tstep_size |charm_ver\n # |CORD=has coordinates |block_a |header_size=84\n # |nframes |block_b\n # |starting timestep\n # |timestep between coord sets \n header1_format = string.replace(header1_format, \"-\", \"\")\n header1 = struct.unpack(header1_format, header1)\n header1_size1, c1, c2, c3, c4, self._nframes, self._firsttstep, self._dcdfreq, self._ntsteps, self._tstep_size, self._block_a, self._block_b, self._charm_v, header1_size2 = header1 #unpack the tuple header1\n \n \n self._dcdtype = \"\".join((c1,c2,c3,c4)) #get the data-type field. I it should always be cord...\n if header1_size1 != 84 or header1_size2 !=84:\n log.error(\"error-- header size fields not correct (should be 84)\\n\")\n if self._block_a != 0 or self._block_b != 0:\n log.info(\"I've found a signal possibly indicating an extra record block\")\n log.info(\" I'll try to parse it, but it might fail. Also, I won't use\")\n log.info(\" any data from them.\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to load the advmul record and test that it actually loads it without exceptions
def test_advmul_record(advmul_record): rec = AdvmulRecord() rec.load(advmul_record) assert rec.bank_app == 'T' assert rec.app_id == '363914' assert rec.edi_msg == 'ADVMUL' assert rec.separator is None assert rec.rec_typ == '02' assert rec.message_type is None assert rec.transact_no == 'IBATL58813' assert rec.weight == 100 assert rec.route_no == '0300' assert rec.client_no == '9903252820' assert rec.client_name == 'Whatever corp Inc.' assert rec.client_account_no == '177148326' assert rec.client_reference is None assert rec.bank_reference == '20623' assert rec.date is None assert rec.date_process == datetime.datetime(2014, 10, 2, 0, 0) assert rec.date_process_other is None assert rec.amount == -6075 assert rec.currency == 'CZK' assert rec.balance == Decimal('3608328.02') assert rec.balance_code == 'C' assert rec.offset_account_bank_code == '0100' assert rec.offset_account_no == '100060018432071' assert rec.offset_account_name == 'PO' assert rec.constant_symbol == 3558 assert rec.variable_symbol == 26696797 assert rec.specific_symbol == 0 assert rec.variable_symbol_offset == 26696797 assert rec.specific_symbol_offset == 0 assert rec.message1 is None assert rec.message2 is None assert rec.message3 is None assert rec.message4 is None assert rec.note is None assert rec.balance_final is None assert rec.balance_final_code is None assert rec.balance_time is None
[ "def test_advmul_header_record(advmul_header_record, advmuz_header_record):\n rec = AdvmulHeaderRecord()\n rec.load(advmul_header_record)\n\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'ADVMUL'\n assert rec.separator is None\n assert rec.rec_typ == '01'\n assert rec.msg_rno == '20140930925710'\n\n rec.load(advmuz_header_record)\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'ADVMUZ'\n assert rec.separator is None\n assert rec.rec_typ == '01'\n assert rec.msg_rno == '20140930925710'", "def test_record_loading(self):\n test_record = self.db.lookup(accession = \"X55053\")\n assert test_record.name == \"ATCOR66M\"\n assert test_record.id == \"X55053.1\", test_record.id\n assert test_record.description == \"A.thaliana cor6.6 mRNA.\"\n assert isinstance(test_record.seq.alphabet, Alphabet.DNAAlphabet)\n assert test_record.seq[:10].tostring() == 'AACAAAACAC'\n\n test_record = self.db.lookup(accession = \"X62281\")\n assert test_record.name == \"ATKIN2\"\n assert test_record.id == \"X62281.1\", test_record.id\n assert test_record.description == \"A.thaliana kin2 gene.\"\n assert isinstance(test_record.seq.alphabet, Alphabet.DNAAlphabet)\n assert test_record.seq[:10].tostring() == 'ATTTGGCCTA'", "def test_advmuz_record(advmuz_record):\n rec = AdvmuzRecord()\n rec.load(advmuz_record)\n\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'ADVMUZ'\n assert rec.separator is None\n assert rec.rec_typ == '02'\n assert rec.message_type == 'CRE'\n assert rec.client_no == '9903252820'\n assert rec.order_reference == '019938742626501A'\n assert rec.reference_item == '4083604409'\n assert rec.weight == 90\n assert rec.client_account_no == '183861478'\n assert rec.creditor_address1 == 'Big Group a.s.'\n assert rec.creditor_address2 == 'Na Pankraci 1620/1214000 Praha 4'\n assert rec.creditor_address3 == 'CZ'\n assert rec.creditor_address4 is None\n assert rec.creditor_account_no == 'CZ2155000000005081107282'\n assert rec.creditor_bank1 is None\n assert rec.creditor_bank2 is None\n assert rec.creditor_bank3 is None\n assert rec.creditor_bank4 is None\n assert rec.payment_reason1 == '/ROC/NOT PROVIDED//174914'\n assert rec.payment_reason2 is None\n assert rec.payment_reason3 is None\n assert rec.payment_reason4 is None\n assert rec.amount == Decimal('760.00')\n assert rec.currency == 'EUR'\n assert rec.amount_account_currency == Decimal('760.00')\n assert rec.account_currency == 'EUR'\n assert rec.exchange_rate == Decimal('1.0000000')\n assert rec.local_fee == Decimal('70.00')\n assert rec.local_currency == 'CZK'\n assert rec.foreign_fee == Decimal('0.00')\n assert rec.foreign_currency == 'EUR'\n assert rec.other_fees == Decimal('0.00')\n assert rec.other_fees_currency is None\n assert rec.date == datetime.datetime(2014, 9, 19, 0, 0)\n assert rec.date_process == datetime.datetime(2014, 9, 19, 0, 0)\n assert rec.date_due is None\n assert rec.client_advice1 == '/ROC/NOT PROVIDED//174914'\n assert rec.client_advice2 is None\n assert rec.client_advice3 is None\n assert rec.client_advice4 is None\n assert rec.client_advice5 is None\n assert rec.fee_settling == 'SHA'\n assert rec.swift_code == 'RZBCCZPP'\n assert rec.payment_title is None\n assert rec.routing_code is None", "def test_recordpersistance_load(self):\n rdict = {job.seq : job for job in self.records}\n records_copy = load_records('tests', self.config)\n rdict_copy = {job.seq : job for job in records_copy}\n for key in rdict.viewkeys():\n self.assertEqual(rdict[key].__dict__,\n rdict_copy[key].__dict__)", "def load(self, record: Record) -> DataRecord: # pragma: no cover\n raise NotImplementedError()", "def test_load_failure(self):\n self.data = ocb_ivort.load_vorticity_ascii_data(\"fake_file\")\n\n self.assertIsNone(self.data)", "async def test_load_8_records_eeprom(self):\n async with LOCK:\n mgr = pub.getDefaultTopicMgr()\n mgr.delTopic(ALL_LINK_RECORD_RESPONSE)\n pub.subscribe(self.send_eeprom_response, SEND_READ_EEPROM_TOPIC)\n\n aldb = ModemALDB(random_address())\n aldb.read_write_mode = ReadWriteMode.EEPROM\n response = await aldb.async_load()\n await asyncio.sleep(0.01)\n _LOGGER.debug(\"Done LOAD function.\")\n _LOGGER.debug(\"Status: %s\", response.name)\n assert aldb.is_loaded\n _LOGGER.debug(\"ALDB Record Count: %d\", len(aldb))\n assert len(aldb) == 9 # Includes HWM record\n pub.unsubscribe(self.send_standard_response, SEND_READ_EEPROM_TOPIC)", "def test_record_wrong_format(self):\n\n self.dns_lookup.resolver.resolve = Mock(side_effect=NoAnswer())\n\n expected = None\n actual = self.dns_lookup.ptr_record(self.subject)\n\n self.assertEqual(expected, actual)", "def test_wrong_load(self):\n self.data = ocb_ivort.load_vorticity_ascii_data(self.bad_file)\n\n self.assertIsNone(self.data)", "def test_lock_record(lock_record):\n rec = LockRecord()\n rec.load(lock_record)\n\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'LOCK'\n assert rec.separator is None\n assert rec.rec_typ == '99'\n assert rec.count == 0\n assert rec.timestamp == datetime.datetime(year=2014, month=9, day=2,\n hour=7, minute=9, second=22)\n assert rec.seq_no == 11", "async def test_load_standard_empty(self):\n async with LOCK:\n mgr = pub.getDefaultTopicMgr()\n mgr.delTopic(ALL_LINK_RECORD_RESPONSE)\n aldb = ModemALDB(random_address())\n aldb.read_write_mode = ReadWriteMode.STANDARD\n pub.subscribe(send_nak_response, SEND_FIRST_TOPIC)\n\n response = await aldb.async_load()\n _LOGGER.debug(\"Done LOAD function.\")\n _LOGGER.debug(\"Status: %s\", response.name)\n assert aldb.is_loaded\n _LOGGER.debug(\"ALDB Record Count: %d\", len(aldb))\n assert len(aldb) == 0\n pub.unsubscribe(send_nak_response, SEND_FIRST_TOPIC)", "def test_network_load(self):\n self.init_capfile(layers=2)\n for packet in self.capfile.packets:\n for field in ['src', 'dst', 'v', 'hl', 'tos', 'ttl']:\n ipkt = packet.packet.payload\n self.assertTrue(hasattr(ipkt, field), 'invalid packet!')", "def test_get_record(self):\n with self._fms as server:\n server.login()\n fake_record = Record([u'name', u'drink'], [u'Do not delete record 1', u'Coffee'])\n record = server.get_record(1)\n self.assertEqual(fake_record.name, record.name)\n self.assertEqual(fake_record.drink, record.drink)", "def test_jarombek_io_a_record_exists(self) -> None:\n try:\n a_record = Route53.get_record('jarombek.io.', 'jarombek.io.', 'A')\n except IndexError:\n self.assertTrue(False)\n return\n \n self.assertTrue(a_record.get('Name') == 'jarombek.io.' and a_record.get('Type') == 'A')", "def test_load_file(self):\n loader = Loader('./tests/example.npz')\n loader.load_file()\n self.assertIsNotNone(loader.data)", "def test_www_jarombek_io_a_record_exists(self) -> None:\n try:\n a_record = Route53.get_record('jarombek.io.', 'www.jarombek.io.', 'A')\n except IndexError:\n self.assertTrue(False)\n return\n \n self.assertTrue(a_record.get('Name') == 'www.jarombek.io.' and a_record.get('Type') == 'A')", "def test_header_record(header_record):\n rec = HeaderRecord()\n rec.load(header_record)\n\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'HEADER'\n assert rec.separator is None\n assert rec.rec_typ == '00'\n assert rec.app_ver == '01.0000'\n assert rec.app_brand == 'BBCSOB'", "def test_recordpersistance_save(self):\n self.assertTrue(os.path.isfile(self.recordpath))", "def load_record(file_name, recordName, ch=None):\n valid_records = load_file_info(file_name)\n #valid_names = [r.record for r in valid_records]\n r = filter(lambda r: recordName == r.record, valid_records)\n if len(r) == 0:\n print \"Can't find record {} in file {}\".format(recordName, file_name)\n print \"valid records:\", valid_records\n print \"WARNING: falling back to first available record\"\n r = [valid_records[0]]\n recordName = r[0].record\n \n handlers = {'matZ':ZStack_mat,\n 'matT':Timelapse_mat,\n 'h5Z':ZStack_h5,\n 'h5T':Timelapse_h5}\n r = r[0]\n key = r.variant+r.get_kind()\n\n #print key\n if not 'U' in key:\n obj = handlers[key](file_name, recordName, ch)\n else:\n print \"Unknown type of file or record\"\n obj = None\n return obj" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to load the advmuz record and test that it actually loads it without exceptions
def test_advmuz_record(advmuz_record): rec = AdvmuzRecord() rec.load(advmuz_record) assert rec.bank_app == 'T' assert rec.app_id == '363914' assert rec.edi_msg == 'ADVMUZ' assert rec.separator is None assert rec.rec_typ == '02' assert rec.message_type == 'CRE' assert rec.client_no == '9903252820' assert rec.order_reference == '019938742626501A' assert rec.reference_item == '4083604409' assert rec.weight == 90 assert rec.client_account_no == '183861478' assert rec.creditor_address1 == 'Big Group a.s.' assert rec.creditor_address2 == 'Na Pankraci 1620/1214000 Praha 4' assert rec.creditor_address3 == 'CZ' assert rec.creditor_address4 is None assert rec.creditor_account_no == 'CZ2155000000005081107282' assert rec.creditor_bank1 is None assert rec.creditor_bank2 is None assert rec.creditor_bank3 is None assert rec.creditor_bank4 is None assert rec.payment_reason1 == '/ROC/NOT PROVIDED//174914' assert rec.payment_reason2 is None assert rec.payment_reason3 is None assert rec.payment_reason4 is None assert rec.amount == Decimal('760.00') assert rec.currency == 'EUR' assert rec.amount_account_currency == Decimal('760.00') assert rec.account_currency == 'EUR' assert rec.exchange_rate == Decimal('1.0000000') assert rec.local_fee == Decimal('70.00') assert rec.local_currency == 'CZK' assert rec.foreign_fee == Decimal('0.00') assert rec.foreign_currency == 'EUR' assert rec.other_fees == Decimal('0.00') assert rec.other_fees_currency is None assert rec.date == datetime.datetime(2014, 9, 19, 0, 0) assert rec.date_process == datetime.datetime(2014, 9, 19, 0, 0) assert rec.date_due is None assert rec.client_advice1 == '/ROC/NOT PROVIDED//174914' assert rec.client_advice2 is None assert rec.client_advice3 is None assert rec.client_advice4 is None assert rec.client_advice5 is None assert rec.fee_settling == 'SHA' assert rec.swift_code == 'RZBCCZPP' assert rec.payment_title is None assert rec.routing_code is None
[ "def test_record_loading(self):\n test_record = self.db.lookup(accession = \"X55053\")\n assert test_record.name == \"ATCOR66M\"\n assert test_record.id == \"X55053.1\", test_record.id\n assert test_record.description == \"A.thaliana cor6.6 mRNA.\"\n assert isinstance(test_record.seq.alphabet, Alphabet.DNAAlphabet)\n assert test_record.seq[:10].tostring() == 'AACAAAACAC'\n\n test_record = self.db.lookup(accession = \"X62281\")\n assert test_record.name == \"ATKIN2\"\n assert test_record.id == \"X62281.1\", test_record.id\n assert test_record.description == \"A.thaliana kin2 gene.\"\n assert isinstance(test_record.seq.alphabet, Alphabet.DNAAlphabet)\n assert test_record.seq[:10].tostring() == 'ATTTGGCCTA'", "def test_advmul_header_record(advmul_header_record, advmuz_header_record):\n rec = AdvmulHeaderRecord()\n rec.load(advmul_header_record)\n\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'ADVMUL'\n assert rec.separator is None\n assert rec.rec_typ == '01'\n assert rec.msg_rno == '20140930925710'\n\n rec.load(advmuz_header_record)\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'ADVMUZ'\n assert rec.separator is None\n assert rec.rec_typ == '01'\n assert rec.msg_rno == '20140930925710'", "def test_advmul_record(advmul_record):\n rec = AdvmulRecord()\n rec.load(advmul_record)\n\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'ADVMUL'\n assert rec.separator is None\n assert rec.rec_typ == '02'\n assert rec.message_type is None\n assert rec.transact_no == 'IBATL58813'\n assert rec.weight == 100\n assert rec.route_no == '0300'\n assert rec.client_no == '9903252820'\n assert rec.client_name == 'Whatever corp Inc.'\n assert rec.client_account_no == '177148326'\n assert rec.client_reference is None\n assert rec.bank_reference == '20623'\n assert rec.date is None\n assert rec.date_process == datetime.datetime(2014, 10, 2, 0, 0)\n assert rec.date_process_other is None\n assert rec.amount == -6075\n assert rec.currency == 'CZK'\n assert rec.balance == Decimal('3608328.02')\n assert rec.balance_code == 'C'\n assert rec.offset_account_bank_code == '0100'\n assert rec.offset_account_no == '100060018432071'\n assert rec.offset_account_name == 'PO'\n assert rec.constant_symbol == 3558\n assert rec.variable_symbol == 26696797\n assert rec.specific_symbol == 0\n assert rec.variable_symbol_offset == 26696797\n assert rec.specific_symbol_offset == 0\n assert rec.message1 is None\n assert rec.message2 is None\n assert rec.message3 is None\n assert rec.message4 is None\n assert rec.note is None\n assert rec.balance_final is None\n assert rec.balance_final_code is None\n assert rec.balance_time is None", "def test_recordpersistance_load(self):\n rdict = {job.seq : job for job in self.records}\n records_copy = load_records('tests', self.config)\n rdict_copy = {job.seq : job for job in records_copy}\n for key in rdict.viewkeys():\n self.assertEqual(rdict[key].__dict__,\n rdict_copy[key].__dict__)", "def test_load_failure(self):\n self.data = ocb_ivort.load_vorticity_ascii_data(\"fake_file\")\n\n self.assertIsNone(self.data)", "def test_wrong_load(self):\n self.data = ocb_ivort.load_vorticity_ascii_data(self.bad_file)\n\n self.assertIsNone(self.data)", "def load(self, record: Record) -> DataRecord: # pragma: no cover\n raise NotImplementedError()", "async def test_load_8_records_eeprom(self):\n async with LOCK:\n mgr = pub.getDefaultTopicMgr()\n mgr.delTopic(ALL_LINK_RECORD_RESPONSE)\n pub.subscribe(self.send_eeprom_response, SEND_READ_EEPROM_TOPIC)\n\n aldb = ModemALDB(random_address())\n aldb.read_write_mode = ReadWriteMode.EEPROM\n response = await aldb.async_load()\n await asyncio.sleep(0.01)\n _LOGGER.debug(\"Done LOAD function.\")\n _LOGGER.debug(\"Status: %s\", response.name)\n assert aldb.is_loaded\n _LOGGER.debug(\"ALDB Record Count: %d\", len(aldb))\n assert len(aldb) == 9 # Includes HWM record\n pub.unsubscribe(self.send_standard_response, SEND_READ_EEPROM_TOPIC)", "def test_load_file(self):\n loader = Loader('./tests/example.npz')\n loader.load_file()\n self.assertIsNotNone(loader.data)", "def test_jarombek_io_a_record_exists(self) -> None:\n try:\n a_record = Route53.get_record('jarombek.io.', 'jarombek.io.', 'A')\n except IndexError:\n self.assertTrue(False)\n return\n \n self.assertTrue(a_record.get('Name') == 'jarombek.io.' and a_record.get('Type') == 'A')", "def test_load_people(self):\n response = self.amity.load_people(\"people.txt\")\n self.assertIn(\"successfully\", response)", "async def test_load_standard_empty(self):\n async with LOCK:\n mgr = pub.getDefaultTopicMgr()\n mgr.delTopic(ALL_LINK_RECORD_RESPONSE)\n aldb = ModemALDB(random_address())\n aldb.read_write_mode = ReadWriteMode.STANDARD\n pub.subscribe(send_nak_response, SEND_FIRST_TOPIC)\n\n response = await aldb.async_load()\n _LOGGER.debug(\"Done LOAD function.\")\n _LOGGER.debug(\"Status: %s\", response.name)\n assert aldb.is_loaded\n _LOGGER.debug(\"ALDB Record Count: %d\", len(aldb))\n assert len(aldb) == 0\n pub.unsubscribe(send_nak_response, SEND_FIRST_TOPIC)", "def test_recordpersistance_save(self):\n self.assertTrue(os.path.isfile(self.recordpath))", "def test_www_jarombek_io_a_record_exists(self) -> None:\n try:\n a_record = Route53.get_record('jarombek.io.', 'www.jarombek.io.', 'A')\n except IndexError:\n self.assertTrue(False)\n return\n \n self.assertTrue(a_record.get('Name') == 'www.jarombek.io.' and a_record.get('Type') == 'A')", "def test_load_ok(self, schema):\n\n data = {\n 'title':'title',\n 'author':'author'\n }\n errors = schema.validate(data)\n assert not errors", "def test_network_load(self):\n self.init_capfile(layers=2)\n for packet in self.capfile.packets:\n for field in ['src', 'dst', 'v', 'hl', 'tos', 'ttl']:\n ipkt = packet.packet.payload\n self.assertTrue(hasattr(ipkt, field), 'invalid packet!')", "def test_load(self):\r\n Config.load()\r\n self.assertIsNotNone(Config.data)\r\n self.assertIsInstance(Config.data, dict)", "def test_get_record(self):\n with self._fms as server:\n server.login()\n fake_record = Record([u'name', u'drink'], [u'Do not delete record 1', u'Coffee'])\n record = server.get_record(1)\n self.assertEqual(fake_record.name, record.name)\n self.assertEqual(fake_record.drink, record.drink)", "def test_record_wrong_format(self):\n\n self.dns_lookup.resolver.resolve = Mock(side_effect=NoAnswer())\n\n expected = None\n actual = self.dns_lookup.ptr_record(self.subject)\n\n self.assertEqual(expected, actual)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get camera instances. Get camera instances to capture images from. RETURNS List[Tuple[cv2.VideoCapture, Dict]] List of camera instances and camera properties dictionaries.
def get_cameras(self) -> List[Tuple[cv2.VideoCapture, Dict]]: pass
[ "def cameraList(self):\r\n var = (CameraInfoEx*10)()\r\n self.dll.PvCameraListEx(byref(var), 1, None, sizeof(CameraInfoEx))\r\n return var", "def list_cameras(self):\n res = []\n camera_names = cmds.listCameras()\n for camera_name in camera_names:\n camera_shape = cmds.listRelatives(\n camera_name, type=\"camera\", s=True\n )[0]\n res.append((camera_name, camera_shape))\n return res", "def list_cameras(cls):\n return [cam.getTransform() for cam in pm.ls(type=\"camera\") if \"cam_\" in cam.name()]", "def get_all(cls, connection):\n resp = connection._get('/1/tenants/%s/networkCameras' % connection.tenant.tenant_id)\n netcams = resp.json()['data']\n return [CogniacNetworkCamera(connection, netcam) for netcam in netcams]", "def getCamera(self) -> \"SoCamera *\":\n return _coin.SoEventManager_getCamera(self)", "def find_available_camera_port():\n import time\n\n list_viable = []\n for source in range(8):\n cap = cv2.VideoCapture(source)\n # print(cap.isOpened())\n if cap is None or not cap.isOpened():\n # print('Warning: unable to open video source: ', source)\n pass\n else:\n list_viable.append(source)\n time.sleep(0.1)\n return list_viable", "def getActiveCamera(self) -> \"SoCamera *\":\n return _coin.SoScXMLStateMachine_getActiveCamera(self)", "def list_devices():\n system = PySpin.System.GetInstance()\n cam_list = system.GetCameras()\n num_cameras = cam_list.GetSize()\n print (\"There are\", num_cameras, \"cameras available\")\n return cam_list", "def getCamera(self) -> \"SoCamera *\":\n return _coin.SoRenderManager_getCamera(self)", "def getCamera(self) -> \"SoCamera *\":\n return _coin.SoSceneManager_getCamera(self)", "def list_video_inputs():\n index = 0\n arr = []\n while True:\n cap = cv2.VideoCapture(index)\n if not cap.read()[0]:\n break\n arr.append(index)\n cap.release()\n index += 1\n return arr", "def _getInstancesAt(self, clickpoint, layer):\n\t\treturn self._cameras['main'].getMatchingInstances(clickpoint, layer)", "def list_available_cameras(self) -> List[str]:\n\n raise NotImplementedError", "def list_ports() -> Tuple[List[int], List[int]]:\n \n working_ports = []\n available_ports = []\n devices = [dev for dev in os.listdir('/dev/') if 'video' in dev]\n for dev_port in range(len(devices)):\n camera = cv2.VideoCapture(dev_port)\n if camera.isOpened():\n is_reading, img = camera.read()\n if is_reading:\n working_ports.append(dev_port)\n else:\n available_ports.append(dev_port)\n camera.release()\n \n return working_ports, available_ports", "def _video_devices(params):\n\n vdevices = Runtime.list_camera_devices()\n ret = {}\n ret['devices'] = vdevices[0]\n ret['names'] = vdevices[1]\n return ret", "def listCameras(orthographic=bool, perspective=bool):\n pass", "def get_captures(self):\n return self.network.snapshots.keys()", "def get_captures(src, input_buffer):\n cap = cv2.VideoCapture(src)\n num_frame = 1 # maintain number of frames read\n \n try:\n while cap.isOpened() and num_frame < MAX_FRAME: # The MAX_FRAME condition is kept to measure FPS. This condition can be removed for indefinite webcam processing\n ret, frame = cap.read()\n if not ret:\n break\n input_buffer.append([num_frame, frame])\n num_frame += 1\n \n cv2.imshow('img', frame) # Unprocessed camera feed is shown to let the user know that camera is recording\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break \n\n cap.release()\n\n except:\n cap.release()", "def cameraById(self, cid):\n return self.get_camera(cid)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Capture images from cameras to file. Returns
def capture_images(self, img_path: str = 'tmp.jpg', warm_up: bool = True, preview: bool = True, save: bool = True): pass
[ "def take_picture(self):\n imgpath = \"\"\n # print(\"Take pic from device %d\" % (self.cv2_cam_dev1))\n try:\n self.lights.headlights(True)\n time.sleep(self.light_wakeup_t)\n cap = cv2.VideoCapture(self.cv2_cam_dev1)\n ret, frame = cap.read()\n self.lights.headlights(False)\n # print(\"Returned %d\" % (ret))\n imgname = \"roboimg\" + str(int(time.time())) + \".png\"\n imgpath = os.path.join(self.imgdir, imgname)\n # print(\"Pic name \" + imgpath)\n cv2.imwrite(imgpath, frame)\n self.logger.warning(\"Captured weed %s\" % (imgpath))\n # When everything done, release the capture\n except:\n print(\"take_picture failed\")\n self.logger.error(\"Take picture failed %s\" % (imgpath))\n raise\n finally:\n cap.release()\n # cv2.destroyAllWindows()\n return imgpath", "def getImageFromCam(self):\n\n\t\twith picamera.array.PiRGBArray(self.CAMERA) as output:\n\n\t\t\tself.CAMERA.capture(output, 'rgb')\n\t\t\t\n\t\t\tprint('Captured %dx%d image' % (output.array.shape[1], output.array.shape[0]))\n\n\t\t\treturn output.array", "def camera_thread(self):\n camera = picamera.PiCamera()\n camera.resolution = (640, 480)\n #camera.sensor_mode = 7\n #camera.shutter_speed = 10000\n camera.framerate = 30\n camera.rotation = 180\n\n cam_stream = io.BytesIO()\n for foo in camera.capture_continuous(output=cam_stream,\n format='jpeg',\n use_video_port=True,\n quality=15,\n thumbnail=None):\n cam_stream.seek(0)\n with self.image_lock:\n self.image = cam_stream.read()\n self.has_image = True\n cam_stream.seek(0)\n cam_stream.truncate()\n\n # if no clients are connected, just chill ad wait to save power.\n\n while(threading.active_count() < 3):\n pass", "def capture(self):\n self.camera = self.ids['camera']\n timestr = time.strftime(\"%Y%m%d_%H%M%S\")\n self.camera.export_to_png(\"IMG_{}.png\".format(timestr))\n print(\"Captured\")", "def webcameCapture():\r\n retval, frame = cap.read()\r\n cv2.imwrite(\"webcam.png\",frame)\r\n img=cv2.imread(\"webcam.png\")\r\n return(img)", "def render(self):\n time_stamps = []\n cam_imgs = []\n cur_time = rospy.get_time()\n\n for recorder in self._cameras:\n stamp, image = recorder.get_image()\n print(\"stamp:\", stamp)\n logging.getLogger('robot_logger').error(\"Checking for time difference: Current time {} camera time {}\".format(cur_time, stamp))\n if abs(stamp - cur_time) > 10 * self._obs_tol: # no camera ping in half second => camera failure\n logging.getLogger('robot_logger').error(\"DeSYNC - no ping in more than {} seconds!\".format(10 * self._obs_tol))\n raise Image_Exception\n time_stamps.append(stamp)\n cam_imgs.append(image)\n\n if self.ncam > 1:\n for index, i in enumerate(time_stamps[:-1]):\n for j in time_stamps[index + 1:]:\n if abs(i - j) > self._obs_tol:\n logging.getLogger('robot_logger').error('DeSYNC- Cameras are out of sync!')\n raise Image_Exception\n\n images = np.zeros((self.ncam, self._height, self._width, 3), dtype=np.uint8)\n for c, img in enumerate(cam_imgs):\n images[c] = img[:, :, ::-1]\n\n return images", "def capture():\r\n (x, y) = global_camera.get_coordinates()\r\n # Label snapshot image with the x- and y-coordinates:\r\n path = \"/capture/X{}Y{}.jpeg\".format(x,y)\r\n return redirect(path)", "def take_image_virtualcam(filename, pwi4):\r\n\r\n pwi4.virtualcamera_take_image_and_save(filename)", "def read(self):\n\t\t# This code is based on the picamera example at:\n\t\t# http://picamera.readthedocs.org/en/release-1.0/recipes1.html#capturing-to-an-opencv-object\n\t\t# Capture a frame from the camera.\n\t\tdata = io.BytesIO()\n\t\twith picamera.PiCamera() as camera:\n\t\t\tcamera.capture(data, format='jpeg')\n\t\tdata = np.fromstring(data.getvalue(), dtype=np.uint8)\n\t\t# Decode the image data and return an OpenCV image.\n\t\timage = cv2.imdecode(data, 1)\n\t\t# Save captured image for debugging.\n\t\tcv2.imwrite(DEBUG_IMAGE, image)\n\t\t\n\t\t# Return the captured image data.\n\t\treturn image", "def snapshot(self):\n ts = datetime.datetime.now() # grab the current timestamp\n filename = \"{}.png\".format(ts.strftime(\n \"%Y-%m-%d_%H-%M-%S\")) # construct filename\n\n ok, frame = self.cap.read()\n image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n image = Image.fromarray(image)\n\n # save image as jpeg file\n image.save('exports/snapshots/' + filename, \"PNG\")\n print(\"[INFO] saved {}\".format(filename))", "def test_all_captures(self):\n\n dir = os.path.join(os.path.dirname(__file__), \"../../../res/captures\")\n\n for c in os.listdir(dir):\n filename = \"../../../res/captures/{}\".format(c)\n try:\n img = cv2.imread(filename)\n except:\n continue\n\n if (img is None):\n continue\n\n playfield = capture.crop_to_playfield(img)", "def _individualCapture(self):\n functionName = '_individualCapture'\n logging.debug('%s' % (functionName))\n # Set Image Mode to \"Continuous\"\n if self.imageModeRBVPv.get() != 2:\n self.stopAcquire()\n self.imageModePv.put(2)\n self._setAcquire() # Turn acquisition on\n self.numCapturePv.put(1)\n if self.waitForNewImageFlag:\n self._waitForNewImage()\n # Capturing loop\n logging.debug('%s: capturing' % (functionName))\n for i in range(self.nImages):\n # Set FileTemplate PV and then grab image\n imageFilenameTemplate = '%s%s_' + timestamp(1) + '_%4.4d' + self.fileExt\n self.templatePv.put(imageFilenameTemplate + '\\0', wait=True)\n sleep(0.002) # This is to be sure the filename gets set\n self.capturePv.put(1, wait=True)\n # Build a list of filenames for (optional) tiff tag file naming\n if self.writeTiffTagsFlag:\n sleep(0.010)\n self.imageFilepaths.append(self.lastImagePv.get(as_string=True))\n logging.debug('%s: Done capturing' % (functionName))", "def snapshot(camera):\n #lamps(GPIO.HIGH)\n #reference to camera capture\n with PiRGBArray(camera) as raw:\n #raw = PiRGBArray(camera) \n #get image from camera\n lamps(GPIO.HIGH)\n camera.capture(raw, format='bgr')\n lamps(GPIO.LOW)\n #print('Captured')\n imRef = raw.array\n \n return imRef", "def capture_image(self, image_path, raw_file_path=None):\n pass", "def capture_pictures():\n\tglobal mode\n\tglobal language\n\tclear_temp_directory()\n\t\n\tif mode==\"5x15\":\n\t\tnum_captures=0\t\n\t\twhile num_captures<4:\n\t\t\tfor x in range(3,0,-1):\n\t\t\t\tprint(\"Taking picture in %s\" % x)\n\t\t\t\tprompt_screen(str(x),600)\n\t\t\t\ttime.sleep(1)\n\t\t\ttry:\n\t\t\t\tcommand=\"gphoto2 --capture-image-and-download --filename %s/capture_%s:%s:%s.jpg\"%(temp_photos_directory,time.strftime(\"%H\"),time.strftime(\"%M\"),time.strftime(\"%S\"))\n\t\t\t\tsubprocess.check_output(\"%s\"% command, shell=True)\n\t\t\t\tnum_captures+=1\n\t\t\texcept subprocess.CalledProcessError as e:\n\t\t\t\tprint(e.output)\t\n\telif mode==\"10x15\":\n\t\ttry:\n\t\t\tcommand=\"gphoto2 --capture-image-and-download --filename %s/capture_%s:%s:%s.jpg\"%(temp_photos_directory,time.strftime(\"%H\"),time.strftime(\"%M\"),time.strftime(\"%S\"))\n\t\t\tsubprocess.check_output(\"%s\"% command, shell=True)\n\t\texcept subprocess.CalledProcessError as e:\n\t\t\tprint(e.output)\n\telse: \n\t\tpass", "def get_camimage(self):\n return self._camimg", "def get_cameras(self) -> List[Tuple[cv2.VideoCapture, Dict]]:\n \n pass", "def run_make_camera_flat(self):\n outfile = 'camera_flat.fits'\n img_list = []\n for k in self.obs_dict:\n if self.obs_dict[k][1] == 'CAMERA': img_list.append(self.obs_dict[k][0])\n print img_list\n logging.info('\\nCreate a new camera flat with name %s\\n' % outfile) \n gr.make_camera_flat(img_list, outfile)", "def capture(self):\n # First verify initial capture status and update with subsequent capture results\n if self._status:\n self._status, frame = self._stream.read()\n print(\"Capture Complete\")\n print(frame)\n self._buffer.append(frame)\n else:\n print(bcolors.FAIL + \"VideoCapture status failure..\\t\" + bcolors.ENDC + \"Exiting\")\n raise IOError" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the ports and return a tuple with the available ports and the ones that are working. Returns Tuple[List[int], List[int]] List of working ports and list of available ports
def list_ports() -> Tuple[List[int], List[int]]: working_ports = [] available_ports = [] devices = [dev for dev in os.listdir('/dev/') if 'video' in dev] for dev_port in range(len(devices)): camera = cv2.VideoCapture(dev_port) if camera.isOpened(): is_reading, img = camera.read() if is_reading: working_ports.append(dev_port) else: available_ports.append(dev_port) camera.release() return working_ports, available_ports
[ "def run_scan(self):\n open_ports = []\n closed_ports = []\n for port in range(1, 3000):\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock = ssl.wrap_socket(s)\n sock.connect((target, port))\n sock.shutdown(socket.SHUT_RDWR)\n sock.close()\n ports.append(port)\n except Exception, e:\n closed_ports.append(port)\n return open_ports, closed_ports", "def filter_ports(\n desired_ports: Iterable[int], bad_ports: Optional[Iterable[int]] = None\n) -> Set[int]:\n return set(desired_ports) - set(bad_ports or used_ports())", "def used_ports() -> Set[int]:\n return {connection.laddr.port for connection in psutil.net_connections()}", "def port_testing(self):\n\n try:\n try:\n remoteServerIP = socket.gethostbyname(self.hostname)\n except socket.gaierror:\n remoteServerIP = socket.gethostbyname(self.url.split(\"/\")[0].split(\":\")[0])\n\n for port in PORTS_TO_SCAN:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.settimeout(0.3)\n result = sock.connect_ex((remoteServerIP, port[0]))\n sock.close()\n\n if result == 0 and port[1] is False:\n self.portWeight = 1\n return\n elif result != 0 and port[1] is True:\n self.portWeight = 1\n return\n self.portWeight = 0\n return\n\n except Exception as e:\n logger.error(e)\n return -2", "def test_ports_scanning():\n host = ipaddress.ip_address(u\"92.222.10.88\")\n scanner = Scanner(host, mock=True)\n\n assert scanner.is_local() is False\n assert scanner.run_ping_test() is True\n\n scanner.perform_scan()\n ports = scanner.extract_ports(\"tcp\")\n\n assert len(ports) >= 3\n for port in ports:\n assert port.__class__ == PortReport\n\n expected_ports = [22, 80, 443]\n port_numbers = [port.port_number for port in ports]\n for expected_port in expected_ports:\n assert expected_port in port_numbers", "def check_dbqp_ports(self):\n used_ports = []\n tmp_files = os.listdir('/tmp')\n for tmp_file in tmp_files:\n if tmp_file.startswith('dbqp_port'):\n used_ports.append(int(tmp_file.split('_')[-1]))\n return used_ports", "def get_ports(module, switch, peer_switch, task, msg):\n cli = pn_cli(module)\n cli += ' switch %s port-show hostname %s' % (switch, peer_switch)\n cli += ' format port no-show-headers '\n return run_command(module, cli, task, msg).split()", "def get_ports_in_use(self, *, agent_name: str) -> List[int]:", "def get_ports(node, interfaces, oxp_url):\n ports = list()\n for interface in interfaces.values():\n port_no = interface[\"port_number\"]\n if port_no != 4294967294:\n ports.append(get_port(node, interface, oxp_url))\n\n return ports", "def pick_unused_port():\n\n if _portpicker_import_error:\n raise _portpicker_import_error # pylint: disable=raising-bad-type\n\n global ASSIGNED_PORTS\n with lock:\n while True:\n try:\n port = portpicker.pick_unused_port()\n except portpicker.NoFreePortFoundError:\n raise unittest.SkipTest(\"Flakes in portpicker library do not represent \"\n \"TensorFlow errors.\")\n if port > 10000 and port not in ASSIGNED_PORTS:\n ASSIGNED_PORTS.add(port)\n logging.info(\"Using local port %r\", port)\n return port", "def get_ports(self):\n raise NotImplementedError() #pragma: no cover", "def scan(dstip,PortList):\n Ports = list()\n for i in PortList:\n pack = sr1(IP(dst=dstip)/UDP(dport=i),timeout=5)\n if pack is not None:\n if pack[0].haslayer(UDP):\n print \"port \"+ str(i) + \" is open\"\n Ports.append( \"port \"+ str(i) + \" is open\\r\\n\")\n elif pack[0].haslayer(ICMP):\n Ports.append( \"port \"+ str(i) + \" is closed/filtered\\r\\n\")\n print \"port \"+ str(i) + \" is closed/filtered\"\n else:\n Ports.append( \"port \"+ str(i) + \" is open/filtered\\r\\n\")\n print \"port \"+ str(i) + \" is open/filtered\"\n return Ports", "def scan_ports():\n system = platform.system() # Checks the current operating system\n if system == 'Windows': # Windows\n print('Windows system')\n for i in range(256):\n try: \n serial_port = serial.Serial(i)\n serial_port.close()\n yield i\n except serial.SerialException:\n pass\n elif system == 'Linux' or 'Darwin': # Linux or osX\n print('Unix system')\n for port in list_ports.comports():\n yield port[0]", "def _get_ports_and_patches(self):\n\n res = self.spp_ctl_cli.get('nfvs/%d' % self.sec_id)\n if res is not None:\n error_codes = self.spp_ctl_cli.rest_common_error_codes\n if res.status_code == 200:\n ports = res.json()['ports']\n patches = res.json()['patches']\n return ports, patches\n elif res.status_code in error_codes:\n pass\n else:\n print('Error: unknown response.')", "def test_list_port_tuples(self):\n with self.rbac_utils.override_role(self):\n self.port_tuple_client.list_port_tuples()", "def _get_vessel_usableports(resourcedata):\n # I think this code could stand to be in nmclient.r2py.\n\n connports = []\n messports = []\n\n for line in resourcedata.split('\\n'):\n\n if line.startswith('resource'):\n # Ignore the word \"resource\" and any comments at the end.\n (resourcetype, value) = line.split()[1:3]\n if resourcetype == 'connport':\n # We do int(float(x)) because value might be a string '13253.0'\n connports.append(int(float(value)))\n if resourcetype == 'messport':\n messports.append(int(float(value)))\n\n return listops.listops_intersect(connports, messports)", "def onSuggestDynamicPorts(self):\n return [], []", "def toggle_ports(module, curr_switch, internal_ports, task, msg):\n output = ''\n cli = pn_cli(module)\n clicopy = cli\n g_toggle_ports = {\n '25g': {'ports': [], 'speeds': ['10g']},\n '40g': {'ports': [], 'speeds': ['10g']},\n '100g': {'ports': [], 'speeds': ['10g', '25g', '40g']}\n }\n ports_25g = []\n ports_40g = []\n ports_100g = []\n\n cli += 'switch %s port-config-show format port,speed ' % curr_switch\n cli += 'parsable-delim ,'\n max_ports = run_command(module, cli, task, msg).split()\n\n all_next_ports = []\n for port_info in max_ports:\n if port_info:\n port, speed = port_info.strip().split(',')\n all_next_ports.append(str(int(port)+1))\n if port in internal_ports:\n continue\n if g_toggle_ports.get(speed, None):\n g_toggle_ports[speed]['ports'].append(port)\n\n # Get info on splitter ports\n g_splitter_ports = {}\n all_next_ports = ','.join(all_next_ports)\n cli = clicopy\n cli += 'switch %s port-show port %s format ' % (curr_switch, all_next_ports)\n cli += 'port,bezel-port parsable-delim ,'\n splitter_info = run_command(module, cli, task, msg).split()\n\n for sinfo in splitter_info:\n if not sinfo:\n break\n _port, _sinfo = sinfo.split(',')\n _port = int(_port)\n if '.2' in _sinfo:\n for i in range(4):\n g_splitter_ports[str(_port-1 + i)] = 1 + i\n else:\n for i in range(4):\n g_splitter_ports[str(_port-1 + i)] = 1 + i\n\n # Get info on Quad Ports\n g_quad_ports = {'25g': []}\n cli = clicopy\n cli += 'switch %s switch-info-show format model, layout horizontal ' % curr_switch\n cli += 'parsable-delim ,'\n model_info = run_command(module, cli, task, msg).split()\n\n for modinfo in model_info:\n if not modinfo:\n break\n model = modinfo\n if model == \"ACCTON-AS7316-54X\" and g_toggle_ports.get('25g', None):\n for _port in g_toggle_ports['25g']['ports']:\n if _port not in g_splitter_ports:\n g_quad_ports['25g'].append(_port)\n\n for port_speed, port_info in g_toggle_ports.iteritems():\n if port_info['ports']:\n output += toggle(module, curr_switch, port_info['ports'], port_info['speeds'], port_speed,\n g_splitter_ports, g_quad_ports.get(port_speed, []), task, msg)\n\n return output", "def check_if_port_available_factory(port):\n def check_if_port_available():\n \"\"\"\n Check if a port is in use\n :return bool not_in_use: True if not in use, False if in use\n \"\"\"\n check_port_command = \"netstat -tuna | grep -E \\\"{:d}\\s\\\"\".format(port)\n return not check_nonzero_exit(check_port_command)\n return check_if_port_available" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For every newly created `Hospital`, create a `Department` corresponding to each `Specialty`.
def create_departments_for_hospital(sender, instance, created, **kwargs): if created: departments = list() for specialty in Specialty.objects.all(): departments.append(Department( hospital=instance, name="Department of %s" % specialty.name, specialty=specialty, contact_name=instance.contact_name, contact_position=instance.contact_position, email=instance.email, phone=instance.phone, extension=instance.extension, has_requirement=instance.has_requirement, requirement_description=instance.requirement_description, requirement_file=instance.requirement_file, )) Department.objects.bulk_create(departments)
[ "def create_departments_for_specialty(sender, instance, created, **kwargs):\n if created:\n departments = list()\n for hospital in Hospital.objects.all():\n departments.append(Department(\n hospital=hospital,\n name=\"Department of %s\" % instance.name,\n specialty=instance,\n contact_name=hospital.contact_name,\n contact_position=hospital.contact_position,\n email=hospital.email,\n phone=hospital.phone,\n extension=hospital.extension,\n has_requirement=hospital.has_requirement,\n requirement_description=hospital.requirement_description,\n requirement_file=hospital.requirement_file,\n ))\n Department.objects.bulk_create(departments)", "def add_departments():\n logger.info('Working with Department class')\n logger.info('Creating Department records')\n\n DEPT_NUM = 0\n DEPT_NAME = 1\n DEPT_MGR = 2\n\n departments = [\n ('DA', 'Dark Arts', 'Voldemort'),\n ('STU', 'Student', 'Minerva McGonnigal'),\n ('ADM', 'Administration', 'Ministry of Magic'),\n ('EDU', 'Education', 'Albus Dumbledore')\n ]\n\n try:\n database.connect()\n database.execute_sql('PRAGMA foreign_keys = ON;')\n for dept in departments:\n with database.transaction():\n new_dept = Department.create(\n department_number=dept[DEPT_NUM],\n department_name=dept[DEPT_NAME],\n department_manager=dept[DEPT_MGR])\n new_dept.save()\n logger.info('Database add successful')\n\n logger.info(\n 'Reading and print all Department rows ...')\n for dept in Department:\n logger.info(f'{dept.department_number} : {dept.department_name} manager : {dept.department_manager}')\n\n except Exception as e:\n logger.info(f'Error creating = {dept[DEPT_NAME]}')\n logger.info(e)\n\n finally:\n logger.info('database closes')\n database.close()", "def setup_db_department():\n # Initialize key variables\n idx_department = 1\n\n # Create a dict of all the expected values\n expected = {\n 'enabled': 1,\n 'name': general.hashstring(general.randomstring()),\n 'idx_department': idx_department,\n 'code': general.hashstring(general.randomstring()),\n }\n\n # Drop the database and create tables\n initialize_db()\n\n # Insert data into database\n data = Department(\n code=general.encode(expected['code']),\n name=general.encode(expected['name']))\n database = db.Database()\n database.add_all([data], 1048)\n\n # Return\n return expected", "def new (deptCode = None,\n name = None,\n managerID = None,\n mission = None):\n newDepartment = Department (None,\n deptCode,\n name,\n managerID, 0, 1)\n newDepartment.updateMission (None)\n newDepartment.save ()\n newDepartment.updateMission (mission)\n newDepartment.save ()\n return newDepartment", "def populate_patients(endpoint, doctor):\n patients = endpoint.list({'doctor': doctor.id})\n for patient_data in patients:\n data = {\n 'doctor': doctor,\n 'first_name': patient_data['first_name'],\n 'last_name': patient_data['last_name'],\n 'gender': patient_data['gender'],\n 'date_of_birth': patient_data['date_of_birth'],\n 'social_security_number': patient_data['social_security_number'],\n 'address': patient_data['address'],\n 'city': patient_data['city'],\n 'state': patient_data['state'],\n 'zip_code': patient_data['zip_code'],\n 'email': patient_data['email'],\n 'home_phone': patient_data['home_phone'],\n 'cell_phone': patient_data['cell_phone']\n }\n\n patient, created = Patient.objects.update_or_create(pk=patient_data['id'], defaults=data)", "def test_create_department_succeeds(self, client, dept_data):\n\n data = dept_data['test_dept']\n response = client.post('/api/v1/department/', data)\n assert response.status_code == 201\n assert response.data['message'] == SUCCESS['create_entry'].format(\n data['name'])", "def create_departments_dict():\n\n departmentsJsonResult = get_deps()\n departmentsDict = dict()\n for row in departmentsJsonResult:\n departmentsDict[row[\"id\"]] = (row[\"name\"], row[\"code\"])\n return departmentsDict", "def create_subjects_and_period():\n\n print \"CREATE SUBJECTS\"\n for subject in subjects:\n item = SimplifiedSubject.create(logincookie, short_name=subject['short_name'], long_name=subject['long_name'], parentnode=ifi['id'])\n SimplifiedPeriod.create(logincookie, short_name='h2011',\n long_name='H2011',\n parentnode=item['id'],\n start_time='2011-08-01 00:00:01',\n end_time='2011-12-01 15:00:00')", "def get_department_children(self, department):\n data = []\n department_data = \\\n {\n 'name': department.name,\n 'type': 'department',\n 'id': department.id,\n 'className': 'o_hr_organization_chart_department',\n 'manager_name': department.manager_id.name,\n 'manager_title': get_position(department.manager_id),\n 'manager_image': get_image(department.manager_id),\n }\n employee_children = self.get_employee_data(department)\n if employee_children:\n data += employee_children\n department_children = self.env['hr.department']. \\\n search([('parent_id', '=', department.id)])\n for child in department_children:\n sub_children = self.env['hr.department']. \\\n search([('parent_id', '=', child.id)])\n if not sub_children:\n employee_children = self.get_employee_data(child)\n data.append({\n 'name': child.name,\n 'type': 'department',\n 'id': child.id,\n 'className': 'o_hr_organization_chart_department',\n 'manager_name': child.manager_id.name,\n 'manager_title': get_position(child.manager_id),\n 'manager_image': get_image(child.manager_id),\n 'children': employee_children\n })\n else:\n data.append(self.get_department_children(child))\n if department_children or employee_children:\n department_data['children'] = data\n return department_data", "def createTable (self):\n self.server.sql (\"\"\"create table Department (\n departmentID numeric (8, 0) identity not null,\n deptCode int,\n name varchar (50),\n mission text null,\n managerID numeric (8, 0) null)\"\"\")", "def test_create_department_invalid_values_fails(self, client, dept_data):\n data = dept_data['test_dept']\n data.update({'name': \"$$$\"})\n response = client.post('/api/v1/department/', data)\n assert response.status_code == 400\n assert response.data['message'] == VALIDATION['unsuccessful']\n assert 'name' in response.data['errors']", "def make_test_data(connection, cursor, num_employees, num_departments, num_cycles, num_expenses_per_day):\n\tprint 'make_test_data: num_departments=%d, num_employees=%d, num_cycles=%d, num_expenses_per_day=%d' \\\n\t % (num_departments, num_employees, num_cycles, num_expenses_per_day)\n\tprint ' (should give expenses of %d * n for department n)' % (num_employees * num_cycles * num_expenses_per_day)\n\t\n\t# Functions to generate values for each field\n\tfirst_name = 'Darren'\n\tdef get_name(employee_num):\n\t\treturn 'Smith.%03d' % employee_num\n\tdef get_date(day_num, fraction_of_day):\n\t\td = day_num % 28\n\t\tm = (day_num//28)%12\n\t\ty = 2000 + day_num//28//12\n\t\tseconds = int(24*60*60*fraction_of_day)\n\t\ts = seconds % 60\n\t\tn = (seconds//60) % 60\n\t\th = seconds//60//60\n\t\treturn '%04d-%02d-%02d %2d:%2d:%2d' % (y, m+1, d+1, h, n, s)\n\tdef get_cost(employee_num, department_num):\n\t\treturn department_num\n\tdef get_department(department_num):\n\t\treturn 'department %03d' % department_num\n\tdef get_description(employee_num, department_num, department_change_num):\n\t\treturn 'expense %03d:%03d for employee %03d' % (department_change_num, department_num, employee_num)\n\t\n\t# Create the employees\n\tdepartment_change_num = 0\n\tfor employee_num in range(num_employees): \n\t\tadd_employee(connection, cursor, first_name, get_name(employee_num), get_department(0))\n\t\n\t# Cycle each employee's department through all available num_cycles times\n\tfor c in range(num_cycles):\n\t\tfor department_num in range(0, num_departments): \n\t\t\tfor employee_num in range(num_employees): \n\t\t\t\tchange_department(cursor, first_name, get_name(employee_num), get_department(department_num), get_date(department_change_num, 0.0))\n\t\t\t\tfor expense_num in range(num_expenses_per_day):\n\t\t\t\t\tadd_expense(cursor, first_name, get_name(employee_num), get_date(department_change_num, (expense_num+1)/(num_expenses_per_day+2)), \n\t\t\t\t\t\t\t\tget_cost(employee_num, department_num), get_description(employee_num,department_num,department_change_num))\n\t\t\tdepartment_change_num += 1", "def add_department():\n\tcheck_admin()\n\tadd_dempartment = True\n\tform = DepartmentForm()\n\tif request.method == 'POST' and form.validate():\n\t\tdepartment = Department(name=form.name.data, description=form.description.data)\n\n\t\ttry:\n\t\t\t# Add the department in the database\n\t\t\tdb.session.add(department)\n\t\t\tdb.session.commit()\n\t\t\tflash('The department has successfully added in the database')\n\t\texcept:\n\t\t\t# In case there are some error (the department is in the database).\n\t\t\tflash(\"The department you are trying to add is already exist in the database\")\n\t\treturn redirect(url_for('admin.list_departments'))\n\n\treturn render_template('admin/departments/department.html', action='Add', form=form\n\t\t, add_department=add_department, title='Add Department')", "def create_today_dict(today_dept, yest_dict, icu_specialties, date2):\r\n today_dict = {}\r\n for row in today_dept:\r\n #if the dept specialty is an icu specialty\r\n if row[2] in icu_specialties:\r\n #if dept was not in yesterday's dictionary, create new Department\r\n if row[0] not in yest_dict:\r\n today_dict[row[0]] = Department(row[0], row[1], row[2], 'Yes', date2, date2)\r\n #else point today's entry for it at yesterday's entry and update\r\n else:\r\n today_dict[row[0]] = yest_dict[row[0]]\r\n today_dict[row[0]].name = row[1]\r\n today_dict[row[0]].specialty = row[2]\r\n today_dict[row[0]].icu = 'Yes'\r\n #populate first date if blank\r\n if not today_dict[row[0]].first:\r\n today_dict[row[0]].first = date2\r\n #update last with today's date\r\n today_dict[row[0]].last = date2\r\n #if the dept specialty is not an icu specialty\r\n else:\r\n #if dept was not in yesterday's dictionary, create new Department\r\n if row[0] not in yest_dict:\r\n today_dict[row[0]] = Department(row[0], row[1], row[2], 'No', None, None)\r\n #else point today's entry for it at yesterday's entry and update\r\n else:\r\n today_dict[row[0]] = yest_dict[row[0]]\r\n today_dict[row[0]].name = row[1]\r\n today_dict[row[0]].specialty = row[2]\r\n today_dict[row[0]].icu = 'No'\r\n return today_dict", "def test_department_model(self, add_org, dept_data):\n\n data = dept_data['test_dept']\n data.update({'organization': add_org})\n department = Department(**data)\n department.save()\n assert Department.objects.get(name=data['name'])\n assert len(Department.objects.all()) >= 1", "def test_portals_id_templates_fk_designs_generate_bulk_post(self):\n pass", "def _onchange_department_emp_categories(self):\n domain = []\n if self.department_ids:\n domain.append(('department_id', 'in', self.department_ids.ids))\n if self.category_ids:\n domain.append(('category_ids', 'in', self.category_ids.ids))\n return {'domain': {'employee_ids': domain}}", "def _process_organisational_units(self):\n if 'organisationalUnits' in self.item:\n self.data['organisationalUnits'] = []\n self.data['groupRestrictions'] = []\n\n for i in self.item['organisationalUnits']:\n sub_data = {}\n\n organisational_unit_name = get_value(i, ['names', 0, 'value'])\n organisational_unit_uuid = get_value(i, ['uuid'])\n organisational_unit_externalId = get_value(i, ['externalId'])\n\n sub_data['name'] = organisational_unit_name\n sub_data['uuid'] = organisational_unit_uuid\n sub_data['externalId'] = organisational_unit_externalId\n\n self.data['organisationalUnits'].append(sub_data)\n\n # Adding organisational unit as group owner\n self.data['groupRestrictions'].append(organisational_unit_externalId)\n\n # Create group\n self.groups.rdm_create_group(organisational_unit_externalId, organisational_unit_name)", "def create(self, validated_data):\n return Teacher.objects.create(**validated_data)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For every newly created `Specialty`, create a corresponding `Department` in each `Hospital`.
def create_departments_for_specialty(sender, instance, created, **kwargs): if created: departments = list() for hospital in Hospital.objects.all(): departments.append(Department( hospital=hospital, name="Department of %s" % instance.name, specialty=instance, contact_name=hospital.contact_name, contact_position=hospital.contact_position, email=hospital.email, phone=hospital.phone, extension=hospital.extension, has_requirement=hospital.has_requirement, requirement_description=hospital.requirement_description, requirement_file=hospital.requirement_file, )) Department.objects.bulk_create(departments)
[ "def create_departments_for_hospital(sender, instance, created, **kwargs):\n if created:\n departments = list()\n for specialty in Specialty.objects.all():\n departments.append(Department(\n hospital=instance,\n name=\"Department of %s\" % specialty.name,\n specialty=specialty,\n contact_name=instance.contact_name,\n contact_position=instance.contact_position,\n email=instance.email,\n phone=instance.phone,\n extension=instance.extension,\n has_requirement=instance.has_requirement,\n requirement_description=instance.requirement_description,\n requirement_file=instance.requirement_file,\n ))\n \n Department.objects.bulk_create(departments)", "def add_departments():\n logger.info('Working with Department class')\n logger.info('Creating Department records')\n\n DEPT_NUM = 0\n DEPT_NAME = 1\n DEPT_MGR = 2\n\n departments = [\n ('DA', 'Dark Arts', 'Voldemort'),\n ('STU', 'Student', 'Minerva McGonnigal'),\n ('ADM', 'Administration', 'Ministry of Magic'),\n ('EDU', 'Education', 'Albus Dumbledore')\n ]\n\n try:\n database.connect()\n database.execute_sql('PRAGMA foreign_keys = ON;')\n for dept in departments:\n with database.transaction():\n new_dept = Department.create(\n department_number=dept[DEPT_NUM],\n department_name=dept[DEPT_NAME],\n department_manager=dept[DEPT_MGR])\n new_dept.save()\n logger.info('Database add successful')\n\n logger.info(\n 'Reading and print all Department rows ...')\n for dept in Department:\n logger.info(f'{dept.department_number} : {dept.department_name} manager : {dept.department_manager}')\n\n except Exception as e:\n logger.info(f'Error creating = {dept[DEPT_NAME]}')\n logger.info(e)\n\n finally:\n logger.info('database closes')\n database.close()", "def setup_db_department():\n # Initialize key variables\n idx_department = 1\n\n # Create a dict of all the expected values\n expected = {\n 'enabled': 1,\n 'name': general.hashstring(general.randomstring()),\n 'idx_department': idx_department,\n 'code': general.hashstring(general.randomstring()),\n }\n\n # Drop the database and create tables\n initialize_db()\n\n # Insert data into database\n data = Department(\n code=general.encode(expected['code']),\n name=general.encode(expected['name']))\n database = db.Database()\n database.add_all([data], 1048)\n\n # Return\n return expected", "def populate_patients(endpoint, doctor):\n patients = endpoint.list({'doctor': doctor.id})\n for patient_data in patients:\n data = {\n 'doctor': doctor,\n 'first_name': patient_data['first_name'],\n 'last_name': patient_data['last_name'],\n 'gender': patient_data['gender'],\n 'date_of_birth': patient_data['date_of_birth'],\n 'social_security_number': patient_data['social_security_number'],\n 'address': patient_data['address'],\n 'city': patient_data['city'],\n 'state': patient_data['state'],\n 'zip_code': patient_data['zip_code'],\n 'email': patient_data['email'],\n 'home_phone': patient_data['home_phone'],\n 'cell_phone': patient_data['cell_phone']\n }\n\n patient, created = Patient.objects.update_or_create(pk=patient_data['id'], defaults=data)", "def new (deptCode = None,\n name = None,\n managerID = None,\n mission = None):\n newDepartment = Department (None,\n deptCode,\n name,\n managerID, 0, 1)\n newDepartment.updateMission (None)\n newDepartment.save ()\n newDepartment.updateMission (mission)\n newDepartment.save ()\n return newDepartment", "def create_today_dict(today_dept, yest_dict, icu_specialties, date2):\r\n today_dict = {}\r\n for row in today_dept:\r\n #if the dept specialty is an icu specialty\r\n if row[2] in icu_specialties:\r\n #if dept was not in yesterday's dictionary, create new Department\r\n if row[0] not in yest_dict:\r\n today_dict[row[0]] = Department(row[0], row[1], row[2], 'Yes', date2, date2)\r\n #else point today's entry for it at yesterday's entry and update\r\n else:\r\n today_dict[row[0]] = yest_dict[row[0]]\r\n today_dict[row[0]].name = row[1]\r\n today_dict[row[0]].specialty = row[2]\r\n today_dict[row[0]].icu = 'Yes'\r\n #populate first date if blank\r\n if not today_dict[row[0]].first:\r\n today_dict[row[0]].first = date2\r\n #update last with today's date\r\n today_dict[row[0]].last = date2\r\n #if the dept specialty is not an icu specialty\r\n else:\r\n #if dept was not in yesterday's dictionary, create new Department\r\n if row[0] not in yest_dict:\r\n today_dict[row[0]] = Department(row[0], row[1], row[2], 'No', None, None)\r\n #else point today's entry for it at yesterday's entry and update\r\n else:\r\n today_dict[row[0]] = yest_dict[row[0]]\r\n today_dict[row[0]].name = row[1]\r\n today_dict[row[0]].specialty = row[2]\r\n today_dict[row[0]].icu = 'No'\r\n return today_dict", "def create_subjects_and_period():\n\n print \"CREATE SUBJECTS\"\n for subject in subjects:\n item = SimplifiedSubject.create(logincookie, short_name=subject['short_name'], long_name=subject['long_name'], parentnode=ifi['id'])\n SimplifiedPeriod.create(logincookie, short_name='h2011',\n long_name='H2011',\n parentnode=item['id'],\n start_time='2011-08-01 00:00:01',\n end_time='2011-12-01 15:00:00')", "def test_portals_id_templates_fk_designs_generate_bulk_post(self):\n pass", "def test_create_department_succeeds(self, client, dept_data):\n\n data = dept_data['test_dept']\n response = client.post('/api/v1/department/', data)\n assert response.status_code == 201\n assert response.data['message'] == SUCCESS['create_entry'].format(\n data['name'])", "def make_test_data(connection, cursor, num_employees, num_departments, num_cycles, num_expenses_per_day):\n\tprint 'make_test_data: num_departments=%d, num_employees=%d, num_cycles=%d, num_expenses_per_day=%d' \\\n\t % (num_departments, num_employees, num_cycles, num_expenses_per_day)\n\tprint ' (should give expenses of %d * n for department n)' % (num_employees * num_cycles * num_expenses_per_day)\n\t\n\t# Functions to generate values for each field\n\tfirst_name = 'Darren'\n\tdef get_name(employee_num):\n\t\treturn 'Smith.%03d' % employee_num\n\tdef get_date(day_num, fraction_of_day):\n\t\td = day_num % 28\n\t\tm = (day_num//28)%12\n\t\ty = 2000 + day_num//28//12\n\t\tseconds = int(24*60*60*fraction_of_day)\n\t\ts = seconds % 60\n\t\tn = (seconds//60) % 60\n\t\th = seconds//60//60\n\t\treturn '%04d-%02d-%02d %2d:%2d:%2d' % (y, m+1, d+1, h, n, s)\n\tdef get_cost(employee_num, department_num):\n\t\treturn department_num\n\tdef get_department(department_num):\n\t\treturn 'department %03d' % department_num\n\tdef get_description(employee_num, department_num, department_change_num):\n\t\treturn 'expense %03d:%03d for employee %03d' % (department_change_num, department_num, employee_num)\n\t\n\t# Create the employees\n\tdepartment_change_num = 0\n\tfor employee_num in range(num_employees): \n\t\tadd_employee(connection, cursor, first_name, get_name(employee_num), get_department(0))\n\t\n\t# Cycle each employee's department through all available num_cycles times\n\tfor c in range(num_cycles):\n\t\tfor department_num in range(0, num_departments): \n\t\t\tfor employee_num in range(num_employees): \n\t\t\t\tchange_department(cursor, first_name, get_name(employee_num), get_department(department_num), get_date(department_change_num, 0.0))\n\t\t\t\tfor expense_num in range(num_expenses_per_day):\n\t\t\t\t\tadd_expense(cursor, first_name, get_name(employee_num), get_date(department_change_num, (expense_num+1)/(num_expenses_per_day+2)), \n\t\t\t\t\t\t\t\tget_cost(employee_num, department_num), get_description(employee_num,department_num,department_change_num))\n\t\t\tdepartment_change_num += 1", "def create_departments_dict():\n\n departmentsJsonResult = get_deps()\n departmentsDict = dict()\n for row in departmentsJsonResult:\n departmentsDict[row[\"id\"]] = (row[\"name\"], row[\"code\"])\n return departmentsDict", "def test_portals_id_designs_fk_put(self):\n pass", "def test_create_department_invalid_values_fails(self, client, dept_data):\n data = dept_data['test_dept']\n data.update({'name': \"$$$\"})\n response = client.post('/api/v1/department/', data)\n assert response.status_code == 400\n assert response.data['message'] == VALIDATION['unsuccessful']\n assert 'name' in response.data['errors']", "def test_department_model(self, add_org, dept_data):\n\n data = dept_data['test_dept']\n data.update({'organization': add_org})\n department = Department(**data)\n department.save()\n assert Department.objects.get(name=data['name'])\n assert len(Department.objects.all()) >= 1", "def _process_organisational_units(self):\n if 'organisationalUnits' in self.item:\n self.data['organisationalUnits'] = []\n self.data['groupRestrictions'] = []\n\n for i in self.item['organisationalUnits']:\n sub_data = {}\n\n organisational_unit_name = get_value(i, ['names', 0, 'value'])\n organisational_unit_uuid = get_value(i, ['uuid'])\n organisational_unit_externalId = get_value(i, ['externalId'])\n\n sub_data['name'] = organisational_unit_name\n sub_data['uuid'] = organisational_unit_uuid\n sub_data['externalId'] = organisational_unit_externalId\n\n self.data['organisationalUnits'].append(sub_data)\n\n # Adding organisational unit as group owner\n self.data['groupRestrictions'].append(organisational_unit_externalId)\n\n # Create group\n self.groups.rdm_create_group(organisational_unit_externalId, organisational_unit_name)", "def test_portals_id_templates_fk_designs_generate_post(self):\n pass", "def _create_districts(self, df):\n unique_districts = df.drop_duplicates()\n unique_districts.columns = [\"district_code\", \"name\"]\n\n list_district = []\n for _, row in unique_districts.iterrows():\n row = self.to_upper(row)\n list_district.append(District(**row))\n\n District.objects.bulk_create(list_district)", "def _onchange_department_emp_categories(self):\n domain = []\n if self.department_ids:\n domain.append(('department_id', 'in', self.department_ids.ids))\n if self.category_ids:\n domain.append(('category_ids', 'in', self.category_ids.ids))\n return {'domain': {'employee_ids': domain}}", "def get_department_children(self, department):\n data = []\n department_data = \\\n {\n 'name': department.name,\n 'type': 'department',\n 'id': department.id,\n 'className': 'o_hr_organization_chart_department',\n 'manager_name': department.manager_id.name,\n 'manager_title': get_position(department.manager_id),\n 'manager_image': get_image(department.manager_id),\n }\n employee_children = self.get_employee_data(department)\n if employee_children:\n data += employee_children\n department_children = self.env['hr.department']. \\\n search([('parent_id', '=', department.id)])\n for child in department_children:\n sub_children = self.env['hr.department']. \\\n search([('parent_id', '=', child.id)])\n if not sub_children:\n employee_children = self.get_employee_data(child)\n data.append({\n 'name': child.name,\n 'type': 'department',\n 'id': child.id,\n 'className': 'o_hr_organization_chart_department',\n 'manager_name': child.manager_id.name,\n 'manager_title': get_position(child.manager_id),\n 'manager_image': get_image(child.manager_id),\n 'children': employee_children\n })\n else:\n data.append(self.get_department_children(child))\n if department_children or employee_children:\n department_data['children'] = data\n return department_data" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test parsing a valid OFX document containing a 'success' message.
def test_successful_parse(self): self.assertEqual("SUCCESS", self.checkparse["body"]["OFX"]["SIGNONMSGSRSV1"]["SONRS"]["STATUS"]["MESSAGE"])
[ "def testParseContent(self):\n # XXX not sure it is good to store parsed document everytime\n self.assertTrue(isinstance(self.oodocument.parsed_content, etree._Element))\n self.assertTrue(self.oodocument.parsed_content.tag.endswith(\n 'document-content'))", "def assertStateOK(root):", "def success_checks(successf):\n au = ActionUnit(\"SuccessUnit\", \"this unit should always succeed\", successf)\n return ActionCollection([au])", "def test_parse_address(self):\n msg = \"Je veux l'adresse d'OpenClassrooms\"\n test_parse = ParsingMessage(msg)\n self.assertEqual(test_parse.msg_parsed, \"OpenClassrooms\")", "def test_ok_result(self):\n process_result = process_response(self.resp_ok)\n self.assertEqual(process_result[\"result\"], 0)", "def test_validate_notice(session, desc, valid, doc_type, notice, mhr_num, account, message_content):\n # setup\n json_data = get_valid_registration()\n json_data['note']['documentType'] = doc_type\n if notice:\n json_data['note']['givingNoticeParty'] = notice\n else:\n del json_data['note']['givingNoticeParty']\n del json_data['note']['effectiveDateTime']\n registration: MhrRegistration = MhrRegistration.find_by_mhr_number(mhr_num, account)\n error_msg = validator.validate_note(registration, json_data, True, STAFF_ROLE)\n current_app.logger.debug(error_msg)\n if valid:\n assert error_msg == ''\n else:\n assert error_msg != ''\n if message_content:\n assert error_msg.find(message_content) != -1", "def test_validation_ok(self, schema):\n data = {\n 'title': 'title',\n 'author': 'author',\n 'pages': 111,\n 'isReserved': False\n }\n\n errors = schema.validate(data)\n assert not errors", "def test_sta_status(self):\n \n message = \"begin ims1.0\\nmsg_type request\\nmsg_id ex029 any_ndc\\ne-mail foo@bar.com\\ntime 1999/07/01 0:01 to 1999/07/31 23:59\\nsta_list ARCES\\nsta_status gse2.0\\nstop\\n\"\n \n parser = IMSParser()\n \n result = parser.parse(message)\n \n #print(\"\\nresult = %s\\n\" %(result))\n \n # check mandatory fields\n self.assertEqual(result['MSGFORMAT'],'ims1.0')\n self.assertEqual(result['MSGTYPE'],'request')\n self.assertEqual(result['MSGID'],'ex029')\n self.assertEqual(result['TARGET'],'EMAIL')\n self.assertEqual(result['EMAILADDR'],'foo@bar.com')\n \n # optional for this request\n self.assertTrue(result.has_key('SOURCE'))\n self.assertEqual(result['SOURCE'],'any_ndc')\n \n # product_1\n self.assertTrue(result.has_key('PRODUCT_1'))\n \n # validate that there is a sta_list and a subtype\n self.assertEqual(result['PRODUCT_1'], {'STARTDATE': '1999/07/01 0:01', 'FORMAT': 'gse2.0', 'ENDDATE': '1999/07/31 23:59', 'STALIST': ['ARCES'], 'TYPE': 'STASTATUS'})", "def testGetContentXml(self):\n content_xml = self.oodocument.getContentXml()\n self.assertTrue('The content of this file is just' in content_xml)", "def test_parse_no_address(self):\n msg = \"C'est ou OpenClassrooms\"\n test_parse = ParsingMessage(msg)\n self.assertEqual(test_parse.msg_parsed, \"OpenClassrooms\")", "def test_elementtree_input(self):\n\n xml_root_element = etree.Element(\"test_example\")\n xml_test_element = etree.SubElement(xml_root_element, \"value_test\")\n xml_test_element.text = \"invalid value\"\n xml_tree = etree.ElementTree(xml_root_element)\n\n validation_result = validify.validate(input_elementtree=xml_tree, validation_rules=compile_test_rules(),\n log_to_console=False)\n\n assert len(validation_result) == 1\n if len(validation_result) == 1:\n assert validation_result[0][\"message_id\"] == \"0010\"", "def test_validate_value_success(self):\n name = os.path.join(conf.test_path_data, \"validate_value_success.json\")\n with open(name) as data_file:\n data = conf.json_load(data_file)\n\n for item in data:\n item.append(\"%s: %s != %s\" % tuple(item))\n item.insert(0, self.check_validate_value_success)\n yield tuple(item)", "def test_handle_success_iv(self):\n # setup\n oef_dialogue = self.prepare_skill_dialogue(\n dialogues=self.oef_dialogues,\n messages=self.list_of_messages_register_classification[:1],\n )\n incoming_message = self.build_incoming_message_for_skill_dialogue(\n dialogue=oef_dialogue,\n performative=OefSearchMessage.Performative.SUCCESS,\n agents_info=OefSearchMessage.AgentsInfo({\"address\": {\"key\": \"value\"}}),\n )\n\n # before\n assert self.service_registration_behaviour.is_registered is False\n\n # operation\n with patch.object(self.oef_search_handler.context.logger, \"log\") as mock_logger:\n self.oef_search_handler.handle(incoming_message)\n\n # after\n mock_logger.assert_any_call(\n logging.INFO,\n f\"received oef_search success message={incoming_message} in dialogue={oef_dialogue}.\",\n )\n mock_logger.assert_any_call(\n logging.INFO,\n \"the agent, with its genus and classification, and its service are successfully registered on the SOEF.\",\n )\n assert self.service_registration_behaviour.is_registered is True", "def test_assertXmlDocument(self):\n test_case = XmlTestCase(methodName='assertXmlDocument')\n data = b\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <root/>\"\"\"\n\n root = test_case.assertXmlDocument(data)\n self.assertIsInstance(root, etree._Element)\n\n with self.assertRaises(test_case.failureException):\n test_case.assertXmlDocument('not an XML document')", "def assert_parse(value, message):\n if not value:\n raise ParseError(message)", "def test_root_element_evaluation(self):\n\n validation_result = validify.validate(\"validify/tests/test_root_element_evaluation.xml\",\n validation_rules=compile_test_rules(), log_to_console=False)\n assert len(validation_result) == 1\n if len(validation_result) == 1:\n assert validation_result[0][\"message_id\"] == \"s0001\"", "def test_clang_format_parser_parse_empty_output():\n cfp = ClangFormatXMLParser()\n report = cfp.parse_xml_output(\"\", \"\")\n assert not report", "def test_valid_message():\n id_ = '12345'\n\n msg = Message({'@type': TEST_TYPE, '@id': id_})\n assert msg.type == TEST_TYPE\n assert msg.id == id_\n assert msg.doc_uri == 'test_type/'\n assert msg.protocol == 'protocol'\n assert msg.version == '1.0'\n assert msg.normalized_version == '1.0.0'\n assert msg.name == 'test'\n assert msg.version_info == Semver(1, 0, 0)", "def test_xml_exist(xml_parser):\n\n xml_data = xml_parser()\n assert xml_data.get_dict()", "def testFailure(self):\n msg = self.Message()\n msg['from'] = 'device@clayster.com'\n msg['to'] = 'master@clayster.com/amr'\n msg['failure']['seqnr'] = '3'\n msg['failure']['done'] = 'true'\n msg['failure']['error']['nodeId'] = 'Device01'\n msg['failure']['error']['timestamp'] = '2013-03-07T17:13:30'\n msg['failure']['error']['text'] = 'Timeout.'\n\n self.check(msg,\"\"\"\n <message from='device@clayster.com'\n to='master@clayster.com/amr'>\n <failure xmlns='urn:xmpp:iot:sensordata' seqnr='3' done='true'>\n <error nodeId='Device01' timestamp='2013-03-07T17:13:30'>\n Timeout.</error>\n </failure>\n </message>\n \"\"\"\n )" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test reading a value from deep in the body of the OFX document.
def test_body_read(self): self.assertEqual("-5128.16", self.creditcardparse["body"]["OFX"]["CREDITCARDMSGSRSV1"]["CCSTMTTRNRS"]["CCSTMTRS"]["LEDGERBAL"]["BALAMT"])
[ "def test_read_nested_val(self):\n sample_json = {'level1': {'level2': {'level3': {'int': 42}}}}\n self.assertEqual(\n chrome_defaults.get_json_field(\n sample_json, 'level1.level2.level3.int'),\n 42)", "def retrieve_value(node):\n\n return node.value", "def test33(self):\n self.check('aDict.nestedDict.one')", "def test_field_content(self):\n data = self.serializer.data\n\n self.assertEqual(data['name'], self.dog_attr['name'])", "def test_bolg_body(self):\n\t\tself.assertIn(testbolg_body, self.test_bolg['body'])", "def test_attribute_doc_in_json(hlwm, clsname, object_path, json_doc):\n path = object_path(hlwm)\n\n for _, attribute in json_doc['objects'][clsname]['attributes'].items():\n name = attribute['name']\n help_txt = hlwm.call(['help', f'{path}.{name}'.lstrip('.')]).stdout\n help_lines = help_txt.rstrip().split('\\n')\n doc_in_help = ''\n # the doc is everything after 'Current value: ..'\n for line_idx in range(0, len(help_lines) - 1):\n # a line starting with 'Current value: '\n found = help_lines[line_idx].startswith('Current value: ')\n # and the next line is empty:\n found = found and help_lines[line_idx + 1] == ''\n if found:\n # the doc is everything after the empty line:\n doc_in_help = '\\n'.join(help_lines[line_idx + 2:])\n break\n if not doc_in_help.startswith('Current value:'):\n # if there is a doc printed by 'help', then it\n # should also be present in the json:\n assert doc_in_help == attribute.get('doc', '').rstrip()", "def testParseContent(self):\n # XXX not sure it is good to store parsed document everytime\n self.assertTrue(isinstance(self.oodocument.parsed_content, etree._Element))\n self.assertTrue(self.oodocument.parsed_content.tag.endswith(\n 'document-content'))", "def value_of(self, reference): # real signature unknown; restored from __doc__\n pass", "def test_get_node_using_get(self):\n pass", "def test_get_input_value(self):\n # Element html\n # <input type=\"hidden\" name=\"p_instance\" value=\"355896116786\" id=\"pInstance\" />\n response = self.spider._get_input_value(self.fake_initial_principal_index_page, 'pInstance')\n self.assertEqual('355896116786', response)", "def test_post_get_document_tag_field_position(self):\n pass", "def test_models_xapi_fields_object_page_object_field(field):\n\n assert field.definition.type == \"http://activitystrea.ms/schema/1.0/page\"\n assert field.definition.name == {\"en\": \"page\"}", "def test_read_reference(self):\n REF_23ANDME_FILE = os.path.join(os.path.dirname(__file__),\n 'fixtures/test_reference.txt')\n ref = read_reference(REF_23ANDME_FILE)\n self.assertEqual(ref, {'1': {'82154': 'A', '752566': 'G'}})", "def test_getitem(self):\n r = self.TreeRoot\n n = self.TreeNode\n assert r[0] is n['b']\n items = n['c'][0:1]\n self.assertEqual(len(items), 1)\n assert items[0] is n['d']\n items = n['c'][0:2]\n self.assertEqual(len(items), 2)\n assert items[0] is n['d']\n assert items[1] is n['e']\n items = n['c'][:]\n self.assertEqual(len(items), 3)\n assert items[0] is n['d']\n assert items[-1] is n['f']", "def test_read_on_object(lwm2mserver, lwm2mclient):\n\n lwm2mclient.wait_for_text(\"STATE_READY\")\n # Test Procedure 1\n assert lwm2mserver.command_response(\"read 0 /1\", \"OK\")\n text = lwm2mserver.wait_for_packet()\n # Pass-Criteria A\n assert text.find(\"COAP_205_CONTENT\") > 0\n packet = re.findall(r\"(\\[.*\\])\", text)\n parsed = json.loads(packet[1])\n assert get_senml_json_record(parsed, \"0/0\", \"v\") == 123\n assert get_senml_json_record(parsed, \"0/0\", \"bn\") == \"/1/\"\n assert get_senml_json_record(parsed, \"0/1\", \"v\") == 300\n assert get_senml_json_record(parsed, \"0/2\", \"v\") == 0\n assert get_senml_json_record(parsed, \"0/3\", \"v\") == 0\n assert get_senml_json_record(parsed, \"0/5\", \"v\") == 0\n assert get_senml_json_record(parsed, \"0/6\", \"vb\") is False\n assert get_senml_json_record(parsed, \"0/7\", \"vs\") == 'U'\n # Test Procedure 2\n assert lwm2mserver.command_response(\"read 0 /3\", \"OK\")\n text = lwm2mserver.wait_for_packet()\n # Pass-Criteria B\n assert text.find(\"COAP_205_CONTENT\") > 0\n packet = re.findall(r\"(\\[.*\\])\", text)\n parsed = json.loads(packet[1])\n # assert that only instance 0 is of object 3 is populated\n for item in parsed:\n assert item[\"n\"].startswith(\"0/\")\n assert get_senml_json_record(parsed, \"0/0\", \"vs\") == \"Open Mobile Alliance\"\n assert get_senml_json_record(parsed, \"0/0\", \"bn\") == \"/3/\"\n assert get_senml_json_record(parsed, \"0/2\", \"vs\") == \"345000123\"\n assert get_senml_json_record(parsed, \"0/3\", \"vs\") == \"1.0\"\n assert get_senml_json_record(parsed, \"0/6/0\", \"v\") == 1\n assert get_senml_json_record(parsed, \"0/6/1\", \"v\") == 5\n assert get_senml_json_record(parsed, \"0/7/0\", \"v\") == 3800\n assert get_senml_json_record(parsed, \"0/7/1\", \"v\") == 5000\n assert get_senml_json_record(parsed, \"0/8/0\", \"v\") == 125\n assert get_senml_json_record(parsed, \"0/8/1\", \"v\") == 900\n assert get_senml_json_record(parsed, \"0/9\", \"v\") == 100\n assert get_senml_json_record(parsed, \"0/10\", \"v\") == 15\n assert get_senml_json_record(parsed, \"0/11/0\", \"v\") == 0\n assert get_senml_json_record(parsed, \"0/13\", \"v\") > 0 # current time\n assert get_senml_json_record(parsed, \"0/14\", \"vs\") == \"+01:00\"\n assert get_senml_json_record(parsed, \"0/15\", \"vs\") == \"Europe/Berlin\"\n assert get_senml_json_record(parsed, \"0/16\", \"vs\") == \"U\"", "def test_core_get_stored_value_v1(self):\n pass", "def testTagFunctionValues(self):\n template = '[tag|values]'\n self.assertEqual(self.parse(template, tag={'ham': 'eggs'}), \"['eggs']\")", "def test_thing_template_getters(exposed_thing):\n\n thing_template = exposed_thing.thing.thing_fragment\n\n assert exposed_thing.id == thing_template.id\n assert exposed_thing.title == thing_template.title\n assert exposed_thing.description == thing_template.description", "def test_parser_read_doc(fresh_aiida_env):\n\n path = data_path('incar', 'INCAR.copper_srf')\n parser = IncarParser(file_path=path)\n result = parser.incar\n assert result is None", "def body_a(self):\r\n return self._fixture_a.body" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test reading a header from the OFX document.
def test_header_read(self): self.assertEqual("100", self.checkparse["header"]["OFXHEADER"])
[ "def test_read_header():\n header = get_header(AIA_193_JP2)[0]\n assert isinstance(header, FileHeader)", "def test_header_record(header_record):\n rec = HeaderRecord()\n rec.load(header_record)\n\n assert rec.bank_app == 'T'\n assert rec.app_id == '363914'\n assert rec.edi_msg == 'HEADER'\n assert rec.separator is None\n assert rec.rec_typ == '00'\n assert rec.app_ver == '01.0000'\n assert rec.app_brand == 'BBCSOB'", "def test_get_header_data(session):\n # setup\n title = 'Test Title'\n # test\n data = report_utils.get_header_data(title)\n # verify\n assert data\n assert data.find(title) != -1", "def test_get__header(self):\n self.assertTrue('<h1>Contact Manager</h1>')", "def testReadFileHeader(self):\n output_writer = test_lib.TestOutputWriter()\n test_file = unified_logging.DSCFile(output_writer=output_writer)\n\n test_file_path = self._GetTestFilePath([\n 'uuidtext', 'dsc', '8E21CAB1DCF936B49F85CF860E6F34EC'])\n self._SkipIfPathNotExists(test_file_path)\n\n with open(test_file_path, 'rb') as file_object:\n test_file._ReadFileHeader(file_object)", "def test_vcf_header(self):\n hd = vcf_header(\n source='23andme',\n reference='http://example.com',\n format_info=['<ID=GT,Number=1,Type=String,Description=\"GT\">'])\n self.assertEqual(len(hd), 6)\n expected_header_fields = [\"##fileformat\",\n \"##fileDate\",\n '##source',\n '##reference',\n '##FORMAT',\n '#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER' +\n '\\tINFO\\tFORMAT\\t23ANDME_DATA']\n self.assertEqual([i.split(\"=\")[0] for i in hd], expected_header_fields)", "def test_simple_with_incorrect_header(self):\r\n log.debug('CAG TEST: INCORRECT HEADER')\r\n stream_handle = StringIO(TEST_DATA_bts)\r\n parser = CtdpfCklWfpSioParser(self.config, stream_handle,\r\n self.exception_callback)\r\n # next get records\r\n result = parser.get_records(4)\r\n if result:\r\n log.debug('CAG TEST: FAILED TO DETECT INCORRECT HEADER')\r\n self.fail()\r\n else:\r\n log.debug('CAG TEST: INCORRECT HEADER DETECTED')\r\n pass", "def testReadFileHeader(self):\n output_writer = test_lib.TestOutputWriter()\n test_file = unified_logging.UUIDTextFile(output_writer=output_writer)\n\n test_file_path = self._GetTestFilePath([\n 'uuidtext', '22', '0D3C2953A33917B333DD8366AC25F2'])\n self._SkipIfPathNotExists(test_file_path)\n\n with open(test_file_path, 'rb') as file_object:\n test_file._ReadFileHeader(file_object)", "def test_translate_header(self):\n with io.StringIO() as out:\n with io.StringIO() as err:\n okay, failed = process_files(\n [TESTDATA],\n r\"^fitsheader.*yaml$\",\n 0,\n False,\n outstream=out,\n errstream=err,\n output_mode=\"none\",\n )\n self.assertEqual(self._readlines(out), [])\n lines = self._readlines(err)\n self.assertEqual(len(lines), 10)\n self.assertTrue(lines[0].startswith(\"Analyzing\"), f\"Line: '{lines[0]}'\")\n\n self.assertEqual(len(okay), 10)\n self.assertEqual(len(failed), 0)", "def test_read_header(self):\n self.test_dir = tempfile.mkdtemp(dir='./', prefix='TestHealSparse-')\n filename = os.path.join(self.test_dir, 'test_array.fits')\n\n data0 = np.zeros(10, dtype=np.int32)\n data1 = np.zeros(10, dtype=np.float64)\n header = healsparse.fits_shim._make_header({'AA': 0,\n 'BB': 1.0,\n 'CC': 'test'})\n self.write_testfile(filename, data0, data1, header)\n\n with HealSparseFits(filename) as fits:\n exts = [0, 1, 'COV', 'SPARSE']\n for ext in exts:\n header_test = fits.read_ext_header(ext)\n for key in header:\n self.assertEqual(header_test[key], header[key])", "def test_simple_header(self):\n self.header_dict = {\n 'nchans': 1, 'nifs': 1, 'nbits': 8, 'fch1': 100.0, 'foff': 1e-5,\n 'tstart': 1e5, 'tsamp': 1e-5}", "def test_header_valid(self):\n header = self.capfile.header\n self.assertEqual(header.major, 2, 'invalid major version!')\n self.assertEqual(header.minor, 4, 'invalid minor version!')", "def test_read_headers():\n req = DataRequest(headers={'accept': 'nothing'})\n assert req.headers.get('accept') == 'nothing'\n req.read_headers(MockConfig())\n assert req.headers == MOCK_HEADERS", "def test_get_check_header(url, header):\n http_bin = HttpBin()\n response = http_bin.request_method_get(url, header)\n result_header_from_response = http_bin.response_method_get_headers(response)\n expected_header = header.keys()[0]\n expected_value = header.values()[0]\n actual_value = result_header_from_response.get(expected_header)\n status_code = 200\n actual_status_code = http_bin.response_get_status_code(response)\n assert status_code == actual_status_code\n assert expected_value == actual_value", "def testWriteHeader(self):\n expected_header = (\n 'date,time,timezone,MACB,source,sourcetype,type,user,host,short,desc,'\n 'version,filename,inode,notes,format,extra\\n')\n\n self._formatter.WriteHeader()\n\n header = self._output_writer.ReadOutput()\n self.assertEqual(header, expected_header)", "def testReadChunkHeader(self):\n output_writer = test_lib.TestOutputWriter()\n test_file = unified_logging.TraceV3File(output_writer=output_writer)\n\n test_file_path = self._GetTestFilePath(['0000000000000030.tracev3'])\n self._SkipIfPathNotExists(test_file_path)\n\n with open(test_file_path, 'rb') as file_object:\n test_file._ReadChunkHeader(file_object, 0)", "def read_header(req, param_name, **_):\n try:\n return req.get_header(param_name, required=True)\n except HTTPBadRequest:\n raise MissingValueError(Location.HEADER, param_name)", "def header_read(buf, begin=0):\n buf.seek(begin) # starting at the given offset\n stringvar = str(buf.read(56)) # reading header\n listvar = stringvar.split() # spliting header\n listvar.pop(0) # first element of header is \"FCS\" and it's useless\n while len(listvar) > 4: # listvar needs only 4 elements, and elements are removed from\n listvar.pop() # the tail until list is 4 elements long\n # offsets are converted into string\n listvar = [int(x) for x in listvar]\n next_offset = listvar[-1]+1 # next offset is calculated\n text_begin = listvar[0]\n # the difference of BEGIN and END gives size-1\n text_size = listvar[1]-listvar[0]\n data_begin = listvar[2]\n # the difference of BEGIN and END gives size-1\n data_size = listvar[3]-listvar[2]\n listvar = [text_begin, text_size, data_begin, data_size]\n return(next_offset, listvar)", "def test_input_first_line_header(self):\n self.convert.start(self.CSV_TEST_FILE_PATH,\n self.OUTPUT_BASE_FILE_PATH+'.xls',\n '{\"input_first_line_header\": true, \"moves\": {\"from\": \"3\", \"to\": \"1\", \"transform\": \"to_lower\"}}')\n self.assertEqual(self.TESTS_DATA[0][2], self.get_cell_in_xls(self.OUTPUT_BASE_FILE_PATH+'.xls', 1, 1))\n self.assertEqual(self.TESTS_DATA[1][2].lower(), self.get_cell_in_xls(self.OUTPUT_BASE_FILE_PATH+'.xls', 2, 1))", "def test_with_header_invalid_format(self):\n reader = DiffXReader(io.BytesIO(\n b'#diffx: key=value key=value\\n'\n ))\n\n message = (\n 'Error on line 1: Unexpected or improperly formatted header: '\n '%r'\n % b'#diffx: key=value key=value'\n )\n\n with self.assertRaisesMessage(DiffXParseError, message):\n list(reader)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert Matplotlib color spec to uint8 4tuple.
def uint8color(color): return tuple(int(255*v) for v in colorConverter.to_rgba(color))
[ "def colorTuple(c):\n return c.getRgb()", "def rgb_to_bytes(color):\n\treturn tuple(int(round(i * 255)) for i in color)", "def _convertColorsFromFloatToUint8(colors):\n # Each bin is [N, N+1[ except the last one: [255, 256]\n return numpy.clip(\n colors.astype(numpy.float64) * 256, 0., 255.).astype(numpy.uint8)", "def rgb_from_bytes(color):\n\treturn Vector4(*[i / 255 for i in color])", "def matplotlib_rgb_color(rgb_color):\n return tuple([i/255. for i in rgb_color])", "def __tuple__(self):\n return (self.color & 0xff0000, self.color & 0xff00, self.color & 0xff)", "def color_to_tuple(value):\n if isinstance(value, tuple):\n return value\n if isinstance(value, int):\n if value >> 24:\n raise ValueError(\"Only bits 0->23 valid for integer input\")\n r = value >> 16\n g = (value >> 8) & 0xFF\n b = value & 0xFF\n return [r, g, b]\n\n raise ValueError(\"Color must be a tuple or 24-bit integer value.\")", "def rgb_from_int(val):\n return tuple([\n ((val >> 16) & 0xff) / 0xff,\n ((val >> 8) & 0xff) / 0xff,\n (val & 0xff) / 0xff])", "def get_color_code(self):\n if self.color == 'r':\n return (254, 0, 0)\n else:\n return (0, 0, 0)", "def pink():\n\n return color2float(Uint8Tensor([[254, 194, 194]]))", "def _color_int2tuple(bitmask):\n return (\n (bitmask >> 2) & 1,\n (bitmask >> 1) & 1,\n bitmask & 1\n )", "def _color_to_tripple( color ):\n from paramio import pget, plist\n\n if color in plist(\"colors.par\"):\n rgb = pget('colors.par', color ) \n rgb = rgb.split()\n rgb = [float(x) for x in rgb]\n return rgb\n\n if len(color.split()) == 3:\n rgb = color.split()\n rgb = [float(x) for x in rgb]\n if max(rgb) > 1.0:\n rgb = [x/255.0 for x in rgb]\n if max(rgb) > 1.0 or min(rgb) < 0.0:\n raise ValueError(\"Color values must be between 0 and 255\")\n return rgb\n\n if len(color) == 8 and color.lower().startswith('0x') is True:\n def __hex_to_int(cc):\n return int( '0x'+cc, base=16 )\n \n rr = __hex_to_int( color[2:4])\n gg = __hex_to_int( color[4:6])\n bb = __hex_to_int( color[6:])\n rgb = [ rr/255.0, gg/255.0, bb/255.0] \n return rgb\n \n\n raise ValueError(\"Unable to parse color value and cannot locate color='{}' in colors.par\".format(color))", "def toRGB(self, _rgbu):\n newRGB = 0\n for iVal, val in enumerate(_rgbu):\n if self.bitDepths[iVal] > 0:\n depth = 2**self.bitDepths[iVal]\n newVal = min(depth-1, int(val *depth))\n newRGB = newRGB | (newVal << self.bitOffsets[iVal])\n #print(\"0x{:06X}\".format(newRGB))\n\n if self.blackBit > 0:\n newRGB = newRGB & ~self.blackBit\n\n rgb = [] \n rgb.append(int( newRGB & 0x0000FF))\n rgb.append(int((newRGB & 0x00FF00) >> 8))\n rgb.append(int((newRGB & 0xFF0000) >> 16))\n\n #print(_rgbu, \"0x{:024b}\".format(newRGB), rgb)\n return (tuple(rgb), newRGB)", "def reformat(color):\n return int(round(color[0] * 255)), \\\n int(round(color[1] * 255)), \\\n int(round(color[2] * 255))", "def red():\n\n return color2float(Uint8Tensor([237, 28, 36]))", "def _rgbtuple2int(t):\n r = int(round(t[0])) # Not all r,g,b values are necessarily\n g = int(round(t[1])) # integers, eg from _cmyk2rgb\n b = int(round(t[2])) # so we round and truncate them\n return long(r) * 65536 + g * 256 + b", "def color_to_triple(color: Optional[str] = None) -> Tuple[int, int, int]:\n if color is None:\n r = np.random.randint(0, 0x100)\n g = np.random.randint(0, 0x100)\n b = np.random.randint(0, 0x100)\n return (r, g, b)\n else:\n return ImageColor.getrgb(color)", "def hex_to_rgb(value):\n value = value.strip(\"#\") # removes hash symbol if present\n lv = len(value)\n return tuple(int(value[i:i + lv//3], 16) for i in range(0, lv, lv//3))", "def rgb8(r: int, g: int, b: int) -> str:\n return rgb_reduce(r, g, b, 8)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a Lambdaready zip file of the current virtualenvironment and working directory. Returns path to that file.
def create_lambda_zip(self, prefix='lambda_package', handler_file=None, minify=True, exclude=None, use_precompiled_packages=True, include=None, venv=None): import pip print("Packaging project as zip...") if not venv: if 'VIRTUAL_ENV' in os.environ: venv = os.environ['VIRTUAL_ENV'] elif os.path.exists('.python-version'): # pragma: no cover logger.debug("Pyenv's local virtualenv detected.") try: subprocess.check_output('pyenv', stderr=subprocess.STDOUT) except OSError: print("This directory seems to have pyenv's local venv" "but pyenv executable was not found.") with open('.python-version', 'r') as f: env_name = f.read()[:-1] logger.debug('env name = {}'.format(env_name)) bin_path = subprocess.check_output(['pyenv', 'which', 'python']).decode('utf-8') venv = bin_path[:bin_path.rfind(env_name)] + env_name logger.debug('env path = {}'.format(venv)) else: # pragma: no cover print("Zappa requires an active virtual environment.") quit() cwd = os.getcwd() zip_fname = prefix + '-' + str(int(time.time())) + '.zip' zip_path = os.path.join(cwd, zip_fname) # Files that should be excluded from the zip if exclude is None: exclude = list() # Exclude the zip itself exclude.append(zip_path) def splitpath(path): parts = [] (path, tail) = os.path.split(path) while path and tail: parts.append(tail) (path, tail) = os.path.split(path) parts.append(os.path.join(path, tail)) return map(os.path.normpath, parts)[::-1] split_venv = splitpath(venv) split_cwd = splitpath(cwd) # Ideally this should be avoided automatically, # but this serves as an okay stop-gap measure. if split_venv[-1] == split_cwd[-1]: # pragma: no cover print( "Warning! Your project and virtualenv have the same name! You may want " "to re-create your venv with a new name, or explicitly define a " "'project_name', as this may cause errors." ) # First, do the project.. temp_project_path = os.path.join(tempfile.gettempdir(), str(int(time.time()))) if minify: excludes = ZIP_EXCLUDES + exclude + [split_venv[-1]] copytree(cwd, temp_project_path, symlinks=False, ignore=shutil.ignore_patterns(*excludes)) else: copytree(cwd, temp_project_path, symlinks=False) # Then, do the site-packages.. temp_package_path = os.path.join(tempfile.gettempdir(), str(int(time.time() + 1))) if os.sys.platform == 'win32': site_packages = os.path.join(venv, 'Lib', 'site-packages') else: site_packages = os.path.join(venv, 'lib', 'python2.7', 'site-packages') if minify: excludes = ZIP_EXCLUDES + exclude copytree(site_packages, temp_package_path, symlinks=False, ignore=shutil.ignore_patterns(*excludes)) else: copytree(site_packages, temp_package_path, symlinks=False) # We may have 64-bin specific packages too. site_packages_64 = os.path.join(venv, 'lib64', 'python2.7', 'site-packages') if os.path.exists(site_packages_64): if minify: excludes = ZIP_EXCLUDES + exclude copytree(site_packages_64, temp_package_path, symlinks=False, ignore=shutil.ignore_patterns(*excludes)) else: copytree(site_packages_64, temp_package_path, symlinks=False) copy_tree(temp_package_path, temp_project_path, update=True) # Then the pre-compiled packages.. if use_precompiled_packages: installed_packages_name_set = {package.project_name.lower() for package in pip.get_installed_distributions()} for name, details in lambda_packages.items(): if name.lower() in installed_packages_name_set: tar = tarfile.open(details['path'], mode="r:gz") for member in tar.getmembers(): # If we can, trash the local version. if member.isdir(): shutil.rmtree(os.path.join(temp_project_path, member.name), ignore_errors=True) continue tar.extract(member, temp_project_path) # If a handler_file is supplied, copy that to the root of the package, # because that's where AWS Lambda looks for it. It can't be inside a package. if handler_file: filename = handler_file.split(os.sep)[-1] shutil.copy(handler_file, os.path.join(temp_project_path, filename)) # Then zip it all up.. try: # import zlib compression_method = zipfile.ZIP_DEFLATED except ImportError: # pragma: no cover compression_method = zipfile.ZIP_STORED zipf = zipfile.ZipFile(zip_path, 'w', compression_method) for root, dirs, files in os.walk(temp_project_path): for filename in files: # If there is a .pyc file in this package, # we can skip the python source code as we'll just # use the compiled bytecode anyway.. if filename[-3:] == '.py': abs_filname = os.path.join(root, filename) abs_pyc_filename = abs_filname + 'c' if os.path.isfile(abs_pyc_filename): # but only if the pyc is older than the py, # otherwise we'll deploy outdated code! py_time = os.stat(abs_filname).st_mtime pyc_time = os.stat(abs_pyc_filename).st_mtime if pyc_time > py_time: continue zipf.write(os.path.join(root, filename), os.path.join(root.replace(temp_project_path, ''), filename)) if '__init__.py' not in files: tmp_init = os.path.join(temp_project_path, '__init__.py') open(tmp_init, 'a').close() zipf.write(tmp_init, os.path.join(root.replace(temp_project_path, ''), os.path.join(root.replace(temp_project_path, ''), '__init__.py'))) # And, we're done! zipf.close() # Trash the temp directory shutil.rmtree(temp_project_path) shutil.rmtree(temp_package_path) # Warn if this is too large for Lambda. file_stats = os.stat(zip_path) if file_stats.st_size > 52428800: # pragma: no cover print("\n\nWarning: Application zip package is likely to be too large for AWS Lambda.\n\n") return zip_fname
[ "def build(function_name=None):\n if not function_name:\n abort('Must provide function_name')\n\n lambda_root = os.path.join(LAMBDA_DIR, function_name)\n module_dir = os.path.join(lambda_root, function_name)\n lambda_config_dir = os.path.join(lambda_root, LAMBDA_CONFIG_SUBDIR)\n staging_dir = os.path.join(lambda_root, STAGING_SUBDIR)\n builds_dir = os.path.join(lambda_root, BUILDS_SUBDIR)\n build_filename = '{0}-{1}.zip'.format(\n datetime.datetime.now().isoformat().replace(':', '.'), function_name)\n\n # Erase previous runs of the build task.\n local('rm -rf {0}'.format(staging_dir))\n\n # Set up staging and builds directories.\n local('mkdir -p {0}'.format(staging_dir))\n local('mkdir -p {0}'.format(builds_dir))\n\n # Install the lambda specific requirements.\n local('pip install -r {0}/requirements.txt -t {1}'.format(lambda_root, staging_dir))\n\n # Copy the top level *.py (e.g. index.py) and lambda_config dir into the staging_dir.\n local('cp -R {0}/*.py {1}'.format(lambda_root, staging_dir))\n local('cp -R {0} {1}'.format(lambda_config_dir, staging_dir))\n\n # Copy the module directory into the staging dir.\n local('cp -R {0} {1}'.format(module_dir, staging_dir))\n\n # Zip the whole thing up, and move it to the builds dir.\n local('cd {0}; zip -r {1} ./*; mv {1} {2}'.format(staging_dir, build_filename, builds_dir))", "def zip_lambda():\n # Don't zip these files\n ignore_files = [\"controller.zip\", \"role_policy.json\"] \n \n # Zip the files and store them in a buffer\n zip_data = BytesIO()\n zipf = zipfile.ZipFile(zip_data, \"w\")\n for root, dirs, files in os.walk(\"lambda\"):\n for fl in files:\n if fl not in ignore_files:\n path_to_file = os.path.join(root, fl)\n file_key = path_to_file[7:]\n zipf.write(path_to_file, arcname=file_key)\n zipf.close()\n \n # Write the buffer to a variable and return it\n zip_data.seek(0)\n data = zip_data.read()\n zip_data.close()\n return data", "def build_archive(mod, cache):\n\n mod_pathname = os.path.abspath(os.path.dirname(__file__) + \"/../lambdas/{}.py\".format(mod))\n awsflow_basedir = os.path.abspath(os.path.dirname(__file__) + \"/../../\")\n\n pkg_dir_suffix = \".lambda\"\n\n if cache:\n # Instead of generating a new temporary directory, reuse the existing one if existing,\n # so that we can avoid re-downloading all the dependencies again. this saves lots of time.\n # The cache is valid for any lamda function defined internally in the awsflow package.\n pkg_dir = \"/tmp/awsflow{}-{}\".format(pkg_dir_suffix, cache)\n\n # check if package directory is empty.\n pkg_dir_empty = not os.path.exists(pkg_dir)\n\n # make sure that the directory exists.\n local(\"mkdir -p {}\".format(pkg_dir))\n else:\n pkg_dir = mkdtemp(pkg_dir_suffix)\n\n logging.info(\"Assembling archive for lambda function ...\")\n\n local('cp {mod_pathname} {pkg_dir}'.format(mod_pathname=mod_pathname, pkg_dir=pkg_dir))\n\n if not cache or pkg_dir_empty:\n local('pip-3.6 install {awsflow_basedir} --find-links {awsflow_basedir} --target {pkg_dir} --upgrade'.format(\n awsflow_basedir=awsflow_basedir, pkg_dir=pkg_dir))\n else:\n logging.info(\"Using cached package directory\")\n\n local('cp -r {awsflow_basedir}/awsflow {pkg_dir}'.format(awsflow_basedir=awsflow_basedir,\n pkg_dir=pkg_dir))\n make_archive(base_name=pkg_dir, format='zip', root_dir=pkg_dir)\n\n logging.info(\"Archive ready.\")\n\n archive_contents = open('{}.zip'.format(pkg_dir), \"rb\").read()\n\n if not cache:\n local(\"rm -rf {pkg_dir}.zip {pkg_dir}\".format(pkg_dir=pkg_dir))\n\n return archive_contents", "def build_lambda():\n\n try:\n os.system(\"mkdir -p ./build\")\n os.system(\"cp -r ./lambda ./build\")\n os.system(\"pip3 install -r ./build/lambda/requirements.txt -t ./build/lambda\")\n shutil.make_archive(\"./build/lambda\", 'zip', \"./build/lambda\")\n os.system(\"rm -rf ./build/lambda\")\n\n print(\"Lambda deployment package built!\")\n\n except Exception as e:\n print(f\"Error building deployment package. Exception: {e}.\")", "def archive_file(self) -> Path:\n return self.project.build_directory / (\n f\"{self.project.source_code.root_directory.name}.\"\n + (\"layer.\" if self.usage_type == \"layer\" else \"\")\n + f\"{self.runtime}.{self.project.source_code.md5_hash}.zip\"\n )", "def create_wotmod_package(self):\n zip_filename = self.get_output_file_path()\n mkpath(os.path.dirname(zip_filename))\n\n log.info(\"creating '%s' and adding '%s' to it\", zip_filename, self.bdist_dir)\n\n archive_root = to_posix_separators(self.bdist_dir)\n\n with zipfile.ZipFile(zip_filename, 'w') as zip:\n for dirpath, dirnames, filenames in os.walk(archive_root):\n dirpath = to_posix_separators(dirpath)\n\n # Build relative path from bdist_dir forward\n archive_dirpath = dirpath.replace(posixpath.commonprefix(\n [dirpath, archive_root]), '').strip('/')\n\n # Create files\n for name in filenames:\n archive_path = posixpath.join(archive_dirpath, name)\n path = posixpath.normpath(posixpath.join(dirpath, name))\n if posixpath.isfile(path):\n log.info(\"adding '%s'\" % archive_path)\n zip.write(path, archive_path)\n\n # Set correct flags for directories\n for name in dirnames:\n archive_path = posixpath.join(archive_dirpath, name) + '/'\n log.info(\"adding '%s'\" % archive_path)\n zip.writestr(archive_path, '')\n\n return zip_filename", "def create_zip(self):\n current_time = datetime.now()\n zip_file_name = \"{}.zip\".format(current_time.strftime(\"%Y_%m_%d_%H_%M_%S_%f_%p\").lower())\n zip_file_pwd = str(current_time.timestamp())\n z = os.path.join(self.dest_path, zip_file_name)\n\n with zipfile.ZipFile(z, \"w\") as file:\n file.setpassword(bytes(zip_file_pwd, 'utf-8'))\n file.write(self.file, arcname=self.file_name)", "def build_zipapp(args, path_map):\n dest_dir = os.path.dirname(args.output)\n with tempfile.TemporaryDirectory(prefix=\"make_fbpy.\", dir=dest_dir) as tmpdir:\n inst_dir = os.path.join(tmpdir, \"tree\")\n populate_install_tree(inst_dir, path_map)\n\n tmp_output = os.path.join(tmpdir, \"output.exe\")\n zipapp.create_archive(\n inst_dir, target=tmp_output, interpreter=args.python, main=args.main\n )\n os.replace(tmp_output, args.output)", "def _MakeZip(input_dir, output_path):\n logging.info(\"Generating zip template file at %s\", output_path)\n basename, _ = os.path.splitext(output_path)\n # TODO(user):pytype: incorrect make_archive() definition in typeshed.\n # pytype: disable=wrong-arg-types\n shutil.make_archive(\n basename, \"zip\", base_dir=\".\", root_dir=input_dir, verbose=True)\n # pytype: enable=wrong-arg-types", "def zip_deploy_file(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"zip_deploy_file\")", "def _generate_lambda(appName, _lambda, roleARN, config, projPath):\n\n if( not os.path.exists(projPath+'/.tmp') ):\n os.mkdir(projPath+'/.tmp')\n\n if( not os.path.isfile(projPath+'/.tmp/dist.zip') ):\n AWSSetup._compress_app_package(\n projPath+'/.tmp/dist',\n projPath+'/.tmp/dist.zip',\n ['.git/']\n )\n\n funcName = appName+'-uxy-app-'+config['app:stage']\n zipFile = open(projPath+'/.tmp/dist.zip', 'rb')\n zipFileBin = zipFile.read()\n zipFile.close()\n\n statusCode = AWSSetup._function_exists(funcName, _lambda)\n if( statusCode == AWSSetup.FUNCTION_NOT_FOUND ):\n runtime = None\n if( config['app:runtime'] == 'go' ):\n runtime = 'go1.x'\n if( config['app:runtime'] == 'python' ):\n runtime = 'python3.9'\n\n AWSSetup._log(\"+ Creating lambda function...\")\n AWSSetup._log(\"+ Runtime: \"+runtime)\n response = _lambda.create_function(\n FunctionName = funcName,\n Runtime = runtime,\n Role = roleARN,\n Handler = config['aws:config']['lambda:handler'],\n Code = {\n 'ZipFile' : zipFileBin\n },\n Timeout = config['aws:config']['lambda:timeout']\n )\n AWSSetup._log(\"=> Lambda package deployed\")\n AWSSetup._add_function_permission(appName, _lambda, config)\n elif ( statusCode == AWSSetup.FUNCTION_FOUND ):\n AWSSetup._log('+ Updating lambda function...')\n response = _lambda.update_function_code(\n FunctionName = funcName,\n ZipFile = zipFileBin\n )\n AWSSetup._log(\"=> Lambda package deployed\")\n AWSSetup._add_function_permission(appName, _lambda, config)\n else:\n AWSSetup._log('=> ERROR: error getting lambda function')\n response = {}\n\n\n return response", "def make_zipfile (base_name, base_dir, verbose=0, dry_run=0):\r\n try:\r\n import zipfile\r\n except ImportError:\r\n zipfile = None\r\n\r\n zip_filename = base_name + \".zip\"\r\n mkpath(os.path.dirname(zip_filename), dry_run=dry_run)\r\n\r\n # If zipfile module is not available, try spawning an external\r\n # 'zip' command.\r\n if zipfile is None:\r\n if verbose:\r\n zipoptions = \"-r\"\r\n else:\r\n zipoptions = \"-rq\"\r\n\r\n try:\r\n spawn([\"zip\", zipoptions, zip_filename, base_dir],\r\n dry_run=dry_run)\r\n except DistutilsExecError:\r\n # XXX really should distinguish between \"couldn't find\r\n # external 'zip' command\" and \"zip failed\".\r\n raise DistutilsExecError, \\\r\n (\"unable to create zip file '%s': \"\r\n \"could neither import the 'zipfile' module nor \"\r\n \"find a standalone zip utility\") % zip_filename\r\n\r\n else:\r\n log.info(\"creating '%s' and adding '%s' to it\",\r\n zip_filename, base_dir)\r\n\r\n def visit (z, dirname, names):\r\n for name in names:\r\n path = os.path.normpath(os.path.join(dirname, name))\r\n if os.path.isfile(path):\r\n z.write(path, path)\r\n log.info(\"adding '%s'\" % path)\r\n\r\n if not dry_run:\r\n z = zipfile.ZipFile(zip_filename, \"w\",\r\n compression=zipfile.ZIP_DEFLATED)\r\n\r\n os.path.walk(base_dir, visit, z)\r\n z.close()\r\n\r\n return zip_filename", "def create_dependency_layer():\n\n # file paths\n requirements_file_path = \"requirements.txt\"\n target_directory = \"python\"\n zip_file_path = \"dependency-layer.zip\"\n\n # change directory so that relative paths work\n cwd = os.getcwd()\n os.chdir(\"lambda\")\n\n # create new dependency zip only if it doesn't exist\n if not os.path.isfile(zip_file_path):\n\n pip_main(\n [\n \"install\",\n \"-r\",\n requirements_file_path,\n \"--target\",\n target_directory,\n ]\n )\n\n # package dependencies as a zip file\n dep_zip = zipfile.ZipFile(zip_file_path, \"w\", zipfile.ZIP_DEFLATED)\n\n for root, dirs, files in os.walk(target_directory):\n for file in files:\n dep_zip.write(os.path.join(root, file))\n\n dep_zip.close()\n\n # change directory back\n os.chdir(cwd)", "def zipdir(self):\n return os.path.join(self.location, self.trunc + '_unzipped')", "def ziplib(self):\n temp_lib_dynload = self.prefix_lib / \"lib-dynload\"\n temp_os_py = self.prefix_lib / \"os.py\"\n\n self.remove(self.site_packages)\n self.lib_dynload.rename(temp_lib_dynload)\n self.copyfile(self.python_lib / \"os.py\", temp_os_py)\n\n zip_path = self.prefix_lib / f\"python{self.ver_nodot}\"\n shutil.make_archive(str(zip_path), \"zip\", str(self.python_lib))\n\n self.remove(self.python_lib)\n self.python_lib.mkdir()\n temp_lib_dynload.rename(self.lib_dynload)\n temp_os_py.rename(self.python_lib / \"os.py\")\n self.site_packages.mkdir()", "def toZip(directory, zipFile):\n\n pass", "def make_dir_zip(dirname, zipname):\r\n\r\n log.debug('zip -q -r %s %s' % (zipname, dirname))\r\n os.system('zip -q -r %s %s' % (zipname, dirname))", "def create_zip_addon(build_dir):\n ver = get_version()\n\n zip_addon = build_dir / f\"rprblender-{ver[0]}.{ver[1]}.{ver[2]}-{ver[3]}-{OS.lower()}.zip\"\n\n print(f\"Compressing addon files to: {zip_addon}\")\n with zipfile.ZipFile(zip_addon, 'w', compression=zipfile.ZIP_DEFLATED,\n compresslevel=zlib.Z_BEST_COMPRESSION) as myzip:\n for src, package_path in enumerate_addon_data():\n print(f\"adding {src} --> {package_path}\")\n\n arcname = str(Path('rprblender') / package_path)\n\n if str(package_path) == \"__init__.py\":\n print(f\" set version_build={ver[3]}\")\n text = src.read_text()\n text = text.replace('version_build = \"\"', f'version_build = \"{ver[3]}\"')\n myzip.writestr(arcname, text)\n continue\n\n myzip.write(str(src), arcname=arcname)\n\n return zip_addon", "def init_zip_dir(chat_name):\n zip_dir = os.path.join(config[\"download\"][\"target_dir\"], \"zips\")\n if not os.path.exists(zip_dir):\n os.mkdir(zip_dir)\n\n zip_dir = os.path.join(zip_dir, chat_name)\n if not os.path.exists(zip_dir):\n os.mkdir(zip_dir)\n\n return zip_dir" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
classes to extract the annotations and smart deploy instances form the abs program
def __init__(self): ABSVisitor.__init__(self) self.smart_dep_json = [] self.dc_json = {} self.deploy_annotations = [] self.module_name = "" self.classes = {} self.interfaces = {}
[ "def main():\n MODEL_URL = \"https://github.com/robmarkcole/object-detection-app/raw/master/model/MobileNetSSD_deploy.caffemodel\" # noqa: E501\n MODEL_LOCAL_PATH = HERE / \"./models/MobileNetSSD_deploy.caffemodel\"\n PROTOTXT_URL = \"https://github.com/robmarkcole/object-detection-app/raw/master/model/MobileNetSSD_deploy.prototxt.txt\" # noqa: E501\n PROTOTXT_LOCAL_PATH = HERE / \"./models/MobileNetSSD_deploy.prototxt.txt\"\n CLASSES_FILE = HERE / \"./info/classes.txt\" \n \n with open(CLASSES_FILE) as f:\n CLASSES = [line.rstrip() for line in f]\n \n COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))\n\n download_file(MODEL_URL, MODEL_LOCAL_PATH, expected_size=23147564)\n download_file(PROTOTXT_URL, PROTOTXT_LOCAL_PATH, expected_size=29353)\n\n DEFAULT_CONFIDENCE_THRESHOLD = 0.5\n\n class Detection(NamedTuple):\n name: str\n prob: float\n\n class MobileNetSSDVideoTransformer(VideoTransformerBase):\n confidence_threshold: float\n result_queue: \"queue.Queue[List[Detection]]\"\n\n def __init__(self) -> None:\n self._net = cv2.dnn.readNetFromCaffe(\n str(PROTOTXT_LOCAL_PATH), str(MODEL_LOCAL_PATH)\n )\n self.confidence_threshold = DEFAULT_CONFIDENCE_THRESHOLD\n self.result_queue = queue.Queue()\n\n def _annotate_image(self, image, detections):\n # loop over the detections\n (h, w) = image.shape[:2]\n result: List[Detection] = []\n for i in np.arange(0, detections.shape[2]):\n confidence = detections[0, 0, i, 2]\n\n if confidence > self.confidence_threshold:\n # extract the index of the class label from the `detections`,\n # then compute the (x, y)-coordinates of the bounding box for\n # the object\n idx = int(detections[0, 0, i, 1])\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n\n name = CLASSES[idx]\n result.append(Detection(name=name, prob=float(confidence)))\n\n # display the prediction\n label = f\"{name}: {round(confidence * 100, 2)}%\"\n cv2.rectangle(image, (startX, startY), (endX, endY), COLORS[idx], 2)\n y = startY - 15 if startY - 15 > 15 else startY + 15\n cv2.putText(\n image,\n label,\n (startX, y),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.5,\n COLORS[idx],\n 2,\n )\n return image, result\n\n def transform(self, frame: av.VideoFrame) -> np.ndarray:\n image = frame.to_ndarray(format=\"bgr24\")\n blob = cv2.dnn.blobFromImage(\n cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5\n )\n self._net.setInput(blob)\n detections = self._net.forward()\n annotated_image, result = self._annotate_image(image, detections)\n\n # NOTE: This `transform` method is called in another thread,\n # so it must be thread-safe.\n self.result_queue.put(result)\n\n return annotated_image\n\n webrtc_ctx = webrtc_streamer(\n key=\"object-detection\",\n mode=WebRtcMode.SENDRECV,\n client_settings=WEBRTC_CLIENT_SETTINGS,\n video_transformer_factory=MobileNetSSDVideoTransformer,\n async_transform=True,\n )\n\n confidence_threshold = st.slider(\n \"Confidence threshold\", 0.0, 1.0, DEFAULT_CONFIDENCE_THRESHOLD, 0.05\n )\n if webrtc_ctx.video_transformer:\n webrtc_ctx.video_transformer.confidence_threshold = confidence_threshold\n\n if st.checkbox(\"Show the detected labels\", value=True):\n if webrtc_ctx.state.playing:\n labels_placeholder = st.empty()\n # NOTE: The video transformation with object detection and\n # this loop displaying the result labels are running\n # in different threads asynchronously.\n # Then the rendered video frames and the labels displayed here\n # are not strictly synchronized.\n while True:\n if webrtc_ctx.video_transformer:\n try:\n result = webrtc_ctx.video_transformer.result_queue.get(\n timeout=1.0\n )\n except queue.Empty:\n result = None\n labels_placeholder.table(result)\n else:\n break\n\n st.markdown(\n \"This Template uses a model and code from \"\n \"https://github.com/robmarkcole/object-detection-app. and https://github.com/whitphx/streamlit-webrtc-example \"\n \"Many thanks to these projects.\"\n )", "def take_action(self, parsed_args):\n args = sys.argv[1:]\n self.log.info('Annotation Development')\n self.log.debug('debugging [Annotation]')\n\n url = parsed_args.url\n doc = parsed_args.doc\n self.log.info('Arguments: '+ str(args) + '\\n')\n\n if url:\n req_ob = requests.get(str(url).strip())\n soup = BeautifulSoup(req_ob.content, \"html.parser\")\n\n \n try: \n abstract = soup.find_all(\"p\", {\"id\" : \"p-2\"})[0]\n abs_text = trimlines(abstract.text).encode('ascii','ignore')\n data = {'content' : str(abs_text)}\n\n response = requests.get(server_url + '/annotations/entities', params = data)\n\n if response.status_code == 200:\n annotated_data = response.json()\n self.app.stdout.write(str(annotated_data))\n hpo_terms = []\n\n if parsed_args.output:\n fopen = open(str(parsed_args.output) + '_annotated_data.txt', 'w')\n fopen.write(str(annotated_data) + '\\n')\n\n fopen.close()\n\n for ob in annotated_data:\n token = ob['token']\n if 'Phenotype' in token['categories']:\n term = str(token['terms'][0])\n if term not in hpo_terms:\n hpo_terms.append(token['terms'][0])\n\n self.app.stdout.write('\\n HPO Terms:\\n')\n for term in hpo_terms:\n self.app.stdout.write(str(term) + '\\n')\n\n if parsed_args.output:\n fopen = open(str(parsed_args.output) + '_hpo_terms.txt', 'w' )\n fopen.write('HPO Terms:\\n')\n for term in hpo_terms:\n fopen.write(str(term) + '\\n')\n\n fopen.close()\n else:\n self.app.stdout.write(str(response.status_code))\n except:\n self.app.stdout.write(\"Abstract Not found\\n\")\n \n if doc:\n html_doc = open(str(doc), 'r')\n soup = BeautifulSoup(html_doc, 'html.parser')\n\n try:\n self.app.stdout.write('Title:' + str(soup.title.get_text()) + '\\n')\n except:\n pass\n\n try:\n meta_list = soup.find_all('meta', {'name' : 'dc.Description'})\n content_list= [k.get('content') for k in meta_list]\n content = ' '.join(content_list)\n data = {'content' : str(content)}\n \n response = requests.get(server_url + '/annotations/entities', params = data)\n\n if response.status_code == 200:\n annotated_data = response.json()\n self.app.stdout.write(str(annotated_data))\n hpo_terms = []\n\n if parsed_args.output:\n fopen = open(str(parsed_args.output) + '_annotated_data.txt', 'w')\n fopen.write(str(annotated_data) + '\\n')\n\n fopen.close()\n\n for ob in annotated_data:\n token = ob['token']\n if 'Phenotype' in token['categories']:\n term = str(token['terms'][0])\n if term not in hpo_terms:\n hpo_terms.append(token['terms'][0])\n\n self.app.stdout.write('\\n HPO Terms:\\n')\n for term in hpo_terms:\n self.app.stdout.write(str(term) + '\\n')\n\n if parsed_args.output:\n fopen = open(str(parsed_args.output) + '_hpo_terms.txt', 'w' )\n fopen.write('HPO Terms:\\n')\n for term in hpo_terms:\n fopen.write(str(term) + '\\n')\n\n fopen.close()\n else:\n self.app.stdout.write(str(response.status_code)+ '\\n')\n\n except:\n self.app.stdout.write('Meta Data not Found\\n')", "def generate_launch_description():\n\n robot_parameters_file = os.path.join(\n get_package_share_directory('pr_bringup'),\n 'config',\n 'pr_config_params.yaml'\n )\n\n controller_params_file = os.path.join(\n get_package_share_directory('pr_bringup'),\n 'config',\n 'pr_pdg.yaml'\n )\n\n mocap_config = os.path.join(\n get_package_share_directory('pr_bringup'),\n 'config',\n 'mocap_server.yaml'\n )\n\n robot_yaml_file = open(robot_parameters_file)\n pr_params = yaml.load(robot_yaml_file)\n\n controller_yaml_file = open(controller_params_file)\n controller_params = yaml.load(controller_yaml_file)\n\n mocap_yaml_file = open(mocap_config)\n mocap_params = yaml.load(mocap_yaml_file)\n\n robot = controller_params['robot']['robot_name']\n robot_config = controller_params['robot']['config'] \n\n pr_config_params = pr_params[robot]['config'][robot_config]\n pr_physical_properties = pr_params[robot]['physical_properties']\n\n ref_file_q = controller_params['ref_path']['q']\n ref_file_x = controller_params['ref_path']['x']\n\n with open(ref_file_q, 'r') as f:\n first_reference_q = fromstring(f.readline(), dtype=float, sep=\" \").tolist()\n \n with open(ref_file_x, 'r') as f:\n first_reference_x = fromstring(f.readline(), dtype=float, sep=\" \").tolist()\n\n pr_pdg = ComposableNodeContainer(\n node_name='pr_container',\n node_namespace='',\n package='rclcpp_components',\n node_executable='component_container',\n composable_node_descriptions=[\n ComposableNode(\n package='pr_sensors_actuators',\n node_plugin='pr_sensors_actuators::Motor',\n node_name='motor_0',\n remappings=[\n (\"control_action\", \"control_action\"),\n (\"end_flag\", \"end_flag\")\n ],\n parameters=[\n {\"vp_conversion\": controller_params['actuators']['vp_conversion'][0]},\n {\"max_v\": controller_params['actuators']['v_sat']}\n ]\n ),\n ComposableNode(\n package='pr_sensors_actuators',\n node_plugin='pr_sensors_actuators::Motor',\n node_name='motor_1',\n remappings=[\n (\"control_action\", \"control_action\"),\n (\"end_flag\", \"end_flag\")\n ],\n parameters=[\n {\"vp_conversion\": controller_params['actuators']['vp_conversion'][1]},\n {\"max_v\": controller_params['actuators']['v_sat']}\n ]\n ),\n ComposableNode(\n package='pr_sensors_actuators',\n node_plugin='pr_sensors_actuators::Motor',\n node_name='motor_2',\n remappings=[\n (\"control_action\", \"control_action\"),\n (\"end_flag\", \"end_flag\")\n ],\n parameters=[\n {\"vp_conversion\": controller_params['actuators']['vp_conversion'][2]},\n {\"max_v\": controller_params['actuators']['v_sat']}\n ]\n ),\n ComposableNode(\n package='pr_sensors_actuators',\n node_plugin='pr_sensors_actuators::Motor',\n node_name='motor_3',\n remappings=[\n (\"control_action\", \"control_action\"),\n (\"end_flag\", \"end_flag\")\n ],\n parameters=[\n {\"vp_conversion\": controller_params['actuators']['vp_conversion'][3]},\n {\"max_v\": controller_params['actuators']['v_sat']}\n ]\n ),\n ComposableNode(\n package='pr_aux',\n node_plugin='pr_aux::Derivator',\n node_name='derivator',\n remappings=[\n (\"joint_position\", \"joint_position\"),\n (\"joint_velocity\", \"joint_velocity\")\n ],\n parameters=[\n {\"initial_value\": first_reference_q},\n {\"ts\": controller_params['ts']}\n ]\n ),\n ComposableNode(\n package='pr_ref_gen',\n node_plugin='pr_ref_gen::RefPose',\n node_name='ref_pose_gen',\n remappings=[\n (\"ref_pose\", \"ref_pose\"),\n (\"end_flag\", \"end_flag\"),\n (\"joint_position\", \"joint_position\")\n ],\n parameters=[\n {\"ref_path\": ref_file_q},\n {\"is_cart\": False},\n {\"robot_config_params\": pr_config_params}\n ]\n ),\n\n ComposableNode(\n package='pr_modelling',\n node_plugin='pr_modelling::ForwardKinematics',\n node_name='for_kin',\n remappings=[\n (\"joint_position\", \"joint_position\"),\n (\"x_coord\", \"x_coord\"),\n ],\n parameters=[\n {\"robot_config_params\": pr_config_params},\n {\"initial_position\": first_reference_x},\n {\"tol\": controller_params['dir_kin']['tol']},\n {\"iter\": controller_params['dir_kin']['iter']},\n ]\n ),\n\n ComposableNode(\n package='pr_modelling',\n node_plugin='pr_modelling::InverseKinematics',\n node_name='inv_kin',\n remappings=[\n (\"x_coord\", \"x_coord\"),\n (\"q_sol\", \"q_sol\"),\n ],\n parameters=[\n {\"robot_config_params\": pr_config_params},\n ]\n ),\n\n ComposableNode(\n package='pr_modelling',\n node_plugin='pr_modelling::IndependentJacobian',\n node_name='ind_jac',\n remappings=[\n (\"q_sol\", \"q_sol\"),\n (\"ind_jac\", \"ind_jac\"),\n ],\n parameters=[\n ]\n ),\n\n ComposableNode(\n package='pr_modelling',\n node_plugin='pr_modelling::DependentJacobian',\n node_name='dep_jac',\n remappings=[\n (\"x_coord\", \"x_coord\"),\n (\"q_sol\", \"q_sol\"),\n (\"dep_jac\", \"dep_jac\")\n ],\n parameters=[\n {\"robot_config_params\": pr_config_params}\n ]\n ),\n\n ComposableNode(\n package='pr_modelling',\n node_plugin='pr_modelling::RastT',\n node_name='rast_t',\n remappings=[\n (\"dep_jac\", \"dep_jac\"),\n (\"ind_jac\", \"ind_jac\"),\n (\"rast_t\", \"rast_t\")\n ],\n parameters=[\n ]\n ),\n\n ComposableNode(\n package='pr_modelling',\n node_plugin='pr_modelling::QGrav',\n node_name='q_grav',\n remappings=[\n (\"x_coord\", \"x_coord\"),\n (\"q_sol\", \"q_sol\"),\n (\"rast_t\", \"rast_t\")\n ],\n parameters=[\n {\"p11\": pr_physical_properties['p11']},\n {\"p12\": pr_physical_properties['p12']},\n {\"p21\": pr_physical_properties['p21']},\n {\"p22\": pr_physical_properties['p22']},\n {\"p31\": pr_physical_properties['p31']},\n {\"p32\": pr_physical_properties['p32']},\n {\"p41\": pr_physical_properties['p41']},\n {\"p42\": pr_physical_properties['p42']},\n {\"pm\": pr_physical_properties['pm']},\n ]\n ),\n\n ComposableNode(\n package='pr_controllers',\n node_plugin='pr_controllers::PDGController',\n node_name='controller',\n remappings=[\n (\"ref_pose\", \"ref_pose\"),\n (\"joint_position\", \"joint_position\"),\n (\"joint_velocity\", \"joint_velocity\"),\n (\"q_grav\", \"q_grav\")\n ],\n parameters=[\n {\"kp_gain\": controller_params['controller']['kp']},\n {\"kv_gain\": controller_params['controller']['kv']},\n ]\n ),\n \n ComposableNode(\n package='pr_sensors_actuators',\n node_plugin='pr_sensors_actuators::Encoders',\n node_name='position_sensors',\n remappings=[\n (\"joint_position\", \"joint_position\")\n ],\n parameters=[\n {\"ts_ms\": controller_params['ts']*1000},\n {\"initial_position\": first_reference_q}\n ]\n ), \n ComposableNode(\n package='pr_mocap',\n node_plugin='pr_mocap::PRXMocap',\n node_name='mocap',\n remappings=[\n (\"x_coord_mocap\", \"x_coord_mocap\")\n ],\n parameters=[\n {\"server_address\": mocap_params[\"server_address\"]},\n {\"server_command_port\": mocap_params[\"server_command_port\"]},\n {\"server_data_port\": mocap_params[\"server_data_port\"]},\n {\"marker_names\": mocap_params[\"marker_names\"][robot]},\n {\"robot_5p\": robot==\"robot_5p\"},\n ]\n ),\n ComposableNode(\n package='pr_mocap',\n node_plugin='pr_mocap::ErrorModel',\n node_name='model_error',\n remappings=[\n (\"x_mocap_error\", \"x_mocap_error\")\n ],\n parameters=[\n {\"tol\": 0.01}\n ]\n ), \n ],\n output='screen',\n )\n\n return launch.LaunchDescription([pr_pdg])", "def test_create_annotations(self):\n segmentation = adapter.SFFSegmentation() # annotation\n segmentation.name = u\"name\"\n segmentation.software_list = adapter.SFFSoftwareList()\n segmentation.software_list.append(\n adapter.SFFSoftware(\n name=u\"Software\",\n version=u\"1.0.9\",\n processing_details=u\"Processing details\"\n )\n )\n segmentation.details = u\"Details\"\n # global external references\n segmentation.global_external_references = adapter.SFFGlobalExternalReferenceList()\n segmentation.global_external_references.append(\n adapter.SFFExternalReference(\n resource=u'one',\n url=u'two',\n accession=u'three'\n )\n )\n segmentation.global_external_references.append(\n adapter.SFFExternalReference(\n resource=u'four',\n url=u'five',\n accession=u'six'\n )\n )\n segmentation.segments = adapter.SFFSegmentList()\n segment = adapter.SFFSegment()\n biol_ann = adapter.SFFBiologicalAnnotation()\n biol_ann.name = u\"Segment1\"\n biol_ann.description = u\"Some description\"\n # external refs\n biol_ann.external_references = adapter.SFFExternalReferenceList()\n biol_ann.external_references.append(\n adapter.SFFExternalReference(\n resource=u\"sldjflj\",\n accession=u\"doieaik\"\n )\n )\n biol_ann.external_references.append(\n adapter.SFFExternalReference(\n resource=u\"sljd;f\",\n accession=u\"20ijalf\"\n )\n )\n biol_ann.external_references.append(\n adapter.SFFExternalReference(\n resource=u\"lsdjlsd\",\n url=u\"lsjfd;sd\",\n accession=u\"23ijlsdjf\"\n )\n )\n biol_ann.number_of_instances = 30\n segment.biological_annotation = biol_ann\n # colour\n segment.colour = adapter.SFFRGBA(\n red=1,\n green=0,\n blue=1,\n alpha=0\n )\n segmentation.segments.append(segment)\n # export\n # segmentation.export(os.path.join(TEST_DATA_PATH, u'sff', u'v0.7', u'test_annotated_segmentation.sff'))\n # assertions\n self.assertEqual(segmentation.name, u'name')\n self.assertEqual(segmentation.version, segmentation._local.schema_version) # automatically set\n software = segmentation.software_list[0]\n self.assertEqual(software.name, u\"Software\")\n self.assertEqual(software.version, u\"1.0.9\")\n self.assertEqual(software.processing_details, u\"Processing details\")\n self.assertEqual(segmentation.details, u\"Details\")\n # global external references\n self.assertEqual(segmentation.global_external_references[0].resource, u'one')\n self.assertEqual(segmentation.global_external_references[0].url, u'two')\n self.assertEqual(segmentation.global_external_references[0].accession, u'three')\n self.assertEqual(segmentation.global_external_references[1].resource, u'four')\n self.assertEqual(segmentation.global_external_references[1].url, u'five')\n self.assertEqual(segmentation.global_external_references[1].accession, u'six')\n # segment: biological_annotation\n self.assertEqual(segment.biological_annotation.name, u\"Segment1\")\n self.assertEqual(segment.biological_annotation.description, u\"Some description\")\n self.assertEqual(len(segment.biological_annotation.external_references), 3)\n self.assertEqual(segment.biological_annotation.external_references[0].resource, u\"sldjflj\")\n self.assertEqual(segment.biological_annotation.external_references[0].accession, u\"doieaik\")\n self.assertEqual(segment.biological_annotation.external_references[1].resource, u\"sljd;f\")\n self.assertEqual(segment.biological_annotation.external_references[1].accession, u\"20ijalf\")\n self.assertEqual(segment.biological_annotation.external_references[2].resource, u\"lsdjlsd\")\n self.assertEqual(segment.biological_annotation.external_references[2].url, u\"lsjfd;sd\")\n self.assertEqual(segment.biological_annotation.external_references[2].accession, u\"23ijlsdjf\")\n self.assertEqual(segment.biological_annotation.number_of_instances, 30)\n # colour\n self.assertEqual(segment.colour.value, (1, 0, 1, 0))", "def main(): \n\n all_tags = ['ADJ','ADV','ADP','CONJ','DET','NOUN','NUM','PRT','PRON','VERB','X','.']\n\n # Step 1: make tag dictionary from resources (either all resources, only AAVE specific or only Wiktionary)\n for (tagdict, tagdict_conf) in make_tagdict():\n \n # Step 2: annotate data with tags from tagdict, depending on the annotation configurations\n\n unlabelled = codecs.open(args.unlabelled, encoding='UTF-8', errors='replace')\n \n for num, line in enumerate(unlabelled):\n words = line.strip().split()\n tags = []\n \n for word in words:\n word_tags = get_tags(word, tagdict)\n tags.append(word_tags)\n\n assert(len(words) == len(tags))\n\n # Step 3: Make config dependent representations, add weights, write out. \n tag_representation = [len(tag) for tag in tags]\n \n config_dependent = {\n \"all\": [], # assign all tags to words without tags\n \"tagged_words_tags\": [], # only include words with tags\n \"tagged_words_words\": [], # only include the corresponding words\n }\n\n if all([x == 1 for x in tag_representation]):\n write_to_out(tagdict_conf, \"unambiguous\", words, tags, num) \n\n for n, tr in enumerate(tags):\n if len(tr) == 0:\n config_dependent[\"all\"].append(all_tags) \n \n else:\n config_dependent[\"all\"].append(tags[n])\n config_dependent[\"tagged_words_tags\"].append(tags[n])\n config_dependent[\"tagged_words_words\"].append(words[n]) \n\n write_to_out(tagdict_conf, \"all\", words, config_dependent[\"all\"], num)\n write_to_out(tagdict_conf, \"tagged_words\", config_dependent[\"tagged_words_words\"], config_dependent[\"tagged_words_tags\"], num)", "def __init__(\n self,\n approx_neb_wf_uuid,\n end_points_combo,\n mobile_specie,\n n_images,\n selective_dynamics_scheme,\n launch_mode=\"all\",\n db_file=DB_FILE,\n vasp_input_set=None,\n vasp_cmd=VASP_CMD,\n override_default_vasp_params=None,\n handler_group=None,\n parents=None,\n add_additional_fields=None,\n add_tags=None,\n **kwargs,\n ):\n fw_name = f\"hop: {mobile_specie} {end_points_combo}\"\n fw_spec = {\"tags\": [\"approx_neb\", approx_neb_wf_uuid, \"evaluate_path\"]}\n\n t = []\n # apply pathfinder pymatgen function and store outputs in approx_neb collection\n t.append(\n PathfinderToDb(\n db_file=db_file,\n n_images=n_images,\n end_points_combo=end_points_combo,\n approx_neb_wf_uuid=approx_neb_wf_uuid,\n )\n )\n # apply selective dynamics to pathfinder outputs to get images input structures\n t.append(\n AddSelectiveDynamics(\n approx_neb_wf_uuid=approx_neb_wf_uuid,\n pathfinder_key=end_points_combo,\n mobile_specie=mobile_specie,\n selective_dynamics_scheme=selective_dynamics_scheme,\n db_file=db_file,\n )\n )\n # add dynamic firetask that will launch image relaxations as desired\n t.append(\n GetImageFireworks(\n launch_mode=launch_mode,\n images_key=end_points_combo,\n approx_neb_wf_uuid=approx_neb_wf_uuid,\n vasp_cmd=vasp_cmd,\n db_file=db_file,\n vasp_input_set=vasp_input_set,\n override_default_vasp_params=override_default_vasp_params,\n handler_group=handler_group,\n add_additional_fields=add_additional_fields,\n add_tags=add_tags,\n )\n )\n\n super().__init__(tasks=t, spec=fw_spec, name=fw_name, parents=parents, **kwargs)", "def generate_instances(logger, conf, sa, interfaces, model, instance_maps):\n\n # todo: This should be done completely in another way. First we can prepare instance maps with implementations then\n # convert ExtendedProcesses into Processes at the same time applying instance maps. This would allow to avoid\n # unnecessary serialization of the whole collection at the end and reduce memory usage by avoiding\n # ExtendedProcess copying.\n model_processes, callback_processes = _yield_instances(logger, conf, sa, interfaces, model, instance_maps)\n\n # Now we can change names\n names = set()\n for process in callback_processes:\n # Change names into unique ones\n new_name = __add_pretty_name(logger, process, names)\n assert new_name not in names\n names.add(new_name)\n del names\n\n # According to new identifiers change signals peers\n for process in model_processes + callback_processes:\n if conf.get(\"convert statics to globals\", True):\n _remove_statics(logger, sa, process)\n\n # Simplify first and set ids then dump\n for process in model_processes + callback_processes:\n _simplify_process(logger, conf, sa, interfaces, process)\n\n model.environment = sortedcontainers.SortedDict({str(p): p for p in callback_processes})\n # todo: Here we can loose instances of model functions\n model.models = sortedcontainers.SortedDict({str(p): p for p in model_processes})\n filename = 'instances.json'\n\n # Save processes\n data = json.dumps(model, cls=CollectionEncoder, sort_keys=True, indent=2)\n with open(filename, mode='w', encoding='utf8') as fp:\n fp.write(data)\n\n return instance_maps, data", "def _yield_instances(logger, conf, sa, interfaces, model, instance_maps):\n logger.info(\"Generate automata for processes with callback calls\")\n identifiers = id_generator()\n identifiers_map = sortedcontainers.SortedDict()\n\n def rename_process(inst):\n inst.instance_number = int(identifiers.__next__())\n if str(inst) in identifiers_map:\n identifiers_map[str(inst)].append(inst)\n else:\n identifiers_map[str(inst)] = [inst]\n\n # Check configuraition properties first\n conf.setdefault(\"max instances number\", 1000)\n conf.setdefault(\"instance modifier\", 1)\n conf.setdefault(\"instances per resource implementation\", 1)\n instances_left = get_or_die(conf, \"max instances number\")\n\n # Returning values\n model_fsa, callback_fsa = list(), list()\n\n # Determine how many instances is required for a model\n for process in model.environment.values():\n base_list = [_copy_process(process, instances_left)]\n base_list = _fulfill_label_maps(logger, conf, sa, interfaces, base_list, process, instance_maps, instances_left)\n logger.info(\"Generate {} FSA instances for environment model processes {} with category {}\".\n format(len(base_list), process.name, process.category))\n\n for instance in base_list:\n rename_process(instance)\n callback_fsa.append(instance)\n\n # Generate automata for models\n logger.info(\"Generate automata for functions model processes\")\n for process in model.models.values():\n logger.info(\"Generate FSA for functions model process {}\".format(process.name))\n processes = _fulfill_label_maps(logger, conf, sa, interfaces, [process], process, instance_maps, instances_left)\n # todo: at the moment anyway several instances of function models are ignored, it is better to do it there until\n # the solution is found\n processes = processes[:1]\n for instance in processes:\n rename_process(instance)\n model_fsa.append(instance)\n\n # According to new identifiers change signals peers\n for process in model_fsa + callback_fsa:\n for action in process.actions.filter(include={Dispatch, Receive}):\n new_peers = []\n for peer in action.peers:\n if str(peer['process']) in identifiers_map:\n for instance in identifiers_map[str(peer['process'])]:\n new_peer = {\n \"process\": instance,\n \"action\": instance.actions[peer['action'].name]\n }\n new_peers.append(new_peer)\n action.peers = new_peers\n\n return model_fsa, callback_fsa", "def main(pattern, debug, verbose, hosts, platform, subnet, region):\n ec2 = boto3.client('ec2', region_name=region)\n try:\n response = ec2.describe_instances()\n if subnet:\n print(\"SubnetId,VpcId,NI-Id,SourceDestCheck,PublicDns,PublicIp,Primary,PrivateIp,PrivateDns\")\n if hosts:\n print(\"\\n##############################################\\n# Generated by name2hosts\\n# On {0}\\n\".format(datetime.today()))\n for reservation in response[\"Reservations\"]:\n for instance in reservation[\"Instances\"]:\n if instance[\"State\"][\"Name\"] == 'running':\n if debug:\n dump_instance_data(instance, region)\n if hosts:\n if platform:\n print(\"# {0}\".format(get_platform(instance)))\n output_host_entry(instance, pattern)\n if subnet:\n sn = output_subnet(instance, debug)\n for k in sn:\n print(\"{0}, {1}\".format(k, sn[k]))\n ##############################################\n # FIXME - Should really be NoCredentialsError\n except NoCredentialsError as e:\n print(\"\\nGot exception {e}\\n\".format(e=e))\n print(\"Credentials Error! Verify that you have setup ~/.aws/credentials and ~/.aws/config files\")\n print(\"See https://boto3.readthedocs.io/en/latest/guide/quickstart.html for more details.\")\n except Exception as e:\n print(\"\\nGot exception {e}\\n\".format(e=e))", "def test_get_annotation_base_with_manifest(self, mock_client):\n rc = ResultCollection(None)\n manifest = 'example.com'\n task = TaskFactory(info=dict(manifest=manifest))\n motivation = 'foo'\n base = rc._get_annotation_base(task, motivation)\n assert_equal(base, {\n 'type': 'Annotation',\n 'motivation': motivation,\n 'generator': [\n {\n \"id\": flask_app.config.get('GITHUB_REPO'),\n \"type\": \"Software\",\n \"name\": \"LibCrowds\",\n \"homepage\": flask_app.config.get('SPA_SERVER_NAME')\n },\n {\n \"id\": url_for('api.api_task', oid=task.id),\n \"type\": \"Software\"\n }\n ],\n 'partOf': manifest\n })", "def main():\n with open(\".auth_token\", mode=\"r\") as tokenfile:\n authtoken = tokenfile.read().strip()\n\n # Initialize connection to Archivist\n arch = Archivist(\n \"https://soak-0-avid.engineering-k8s-stage-2.dev.wild.jitsuin.io\",\n auth=authtoken,\n )\n\n # list all assets with required attributes and properties\n props = {\"confirmation_status\": \"CONFIRMED\"}\n attrs = {\"arc_display_type\": \"Traffic light\"}\n\n # iterate through the generator....\n for asset in arch.assets.list(props=props, attrs=attrs):\n print(\"asset\", asset)\n\n # alternatively one could pull the list and cache locally...\n assets = list(arch.assets.list(props=props, attrs=attrs))\n for asset in assets:\n print(\"asset\", asset)", "def main_parser(f):\n\n # Read inputs using pandas\n df = pd.read_csv(f)\n raw_tweets = df.tweet\n labels = df['class'].astype(int)\n instances = []\n\n # Process tweets and create instances\n for tweet, label in zip(raw_tweets, labels):\n # Raw tweet and label\n i = Instance()\n i.label = label\n i.fulltweet = tweet\n\n # Get just text\n clean_tweet = preprocess(tweet)\n i.clean_tweet = clean_tweet\n\n # Tokenize tweet\n # tokenized_tweet = basic_tokenize(clean_tweet)\n stemmed_tweet = tokenize(clean_tweet)\n # i.wordlist = tokenized_tweet\n i.wordlist = stemmed_tweet\n instances.append(i)\n\n return instances", "def __init__(self, metadata_url, class_prefix, input_loc, temp_loc):\n self.input_location = input_loc\n self.temp_location = temp_loc\n\n self.metadata_file = self.temp_location + METADATA_FILENAME\n\n self.odata_types = {}\n self.odata_containers = {}\n self.odata_properties = {}\n self.classes = {}\n\n # Download metadata file\n urlretrieve(metadata_url, self.metadata_file)\n\n # Create metadata object from file\n self.metadata = metadata.Metadata(self.metadata_file, class_prefix)\n\n # Save model to json file for review\n with open(self.temp_location + CLASSES_FILENAME, 'w') as f:\n json.dump(self.metadata.classes, f, indent=4)\n\n with open(self.temp_location + SETS_FILENAME, 'w') as f:\n json.dump(self.metadata.sets, f, indent=4)\n\n with open(self.temp_location + ODATA_TYPES_FILENAME, 'w') as f:\n json.dump(self.metadata.odata_types, f, indent=4)\n\n # Process classes\n for name, c in self.metadata.classes.items():\n\n if isinstance(c, metadata.EntityType):\n self.add_entitytype(name, c)\n\n elif isinstance(c, metadata.ComplexType):\n self.add_complextype(name, c)\n\n elif isinstance(c, metadata.EnumType):\n self.add_enumtype(name, c)\n\n else:\n logging.warning(\"Class \" + name + \" is not a known EDM type.\")\n\n # Process sets (and singletons)\n for name, s in self.metadata.sets.items():\n if isinstance(s, metadata.Singleton):\n self.add_singleton(name, s)\n\n elif isinstance(s, metadata.EntitySet):\n self.add_entityset(name, s)\n\n else:\n logging.warning(\"Class \" + name + \" is not a known EDM type.\")", "def create_ana_images(self):\n log.debug(\"start\")\n os.chdir(self._p_analysis_tmp)\n exif_attributes=self._exif_attributes\n exif_attributes=\" \".join([\"-\"+a for a in exif_attributes])\n\n # quiet option suppreses regular output\n cmd_exif=ImageAnalyzer.CMD_EXIFTOOL_JSON.replace(\"_EXIF_\",self._exiftool)\n cmd_exif=cmd_exif.replace(\"ATT\",exif_attributes)\n\n cmd_out = None\n runner = Runner()\n ret_code=runner.run_cmd(cmd_exif)\n if ret_code == 0:\n cmd_out=runner.get_output()\n files_metadata={}\n\n try:\n files_metadata=json.loads(cmd_out)\n except JSONDecodeError as e:\n err_details={\"msg\":e.msg,\"col\":str(e.colno),\"line\":str(e.lineno)}\n log.error(\"JSON Decode Error: %(msg)s error occured in output at column %(col)s, line %(line)s\",err_details)\n\n for file_metadata in files_metadata:\n\n filename=Path(file_metadata[\"SourceFile\"])\n filename=filename.stem+\"_ana\"+filename.suffix\n file_metadata[\"TargetFile\"]=os.path.join(self._p_analysis,filename)\n file_metadata[\"FocusBox\"]=ImageAnalyzer.get_focus_box(file_metadata)\n file_metadata[\"Description\"]=ImageAnalyzer.create_analysis_text(file_metadata)\n # convert to a os magick command\n draw_config=self._magick_box_config.copy()\n try:\n draw_config[\"_FILE_IN_\"]=file_metadata[\"SourceFile\"]\n draw_config[\"_FILE_OUT_\"]=file_metadata[\"TargetFile\"]\n draw_config[\"_TEXT_\"]=file_metadata[\"Description\"]\n draw_config[\"_X0_\"]=str(file_metadata[\"FocusBox\"][0][0])\n draw_config[\"_Y0_\"]=str(file_metadata[\"FocusBox\"][0][1])\n draw_config[\"_X1_\"]=str(file_metadata[\"FocusBox\"][2][0])\n draw_config[\"_Y1_\"]=str(file_metadata[\"FocusBox\"][2][1])\n except TypeError as e:\n log.error(\"not all metadata found to create focus box (%s)\",e)\n continue\n # replace template\n cmd_magick=ImageAnalyzer.CMD_MAGICK_DRAW_FOCUS_BOX\n for k,v in draw_config.items():\n cmd_magick=cmd_magick.replace(k,v)\n file_metadata[\"CmdMagick\"]=cmd_magick\n\n # writing files with focus box and meta data\n runner = Runner()\n for file_metadata in files_metadata:\n cmd=file_metadata.get(\"CmdMagick\")\n\n if not cmd:\n continue\n ret_code=runner.run_cmd(cmd)\n if ret_code == 0:\n log.info(\"Writing file %s\",file_metadata['TargetFile'])\n cmd_out=runner.get_output()\n else:\n log.error(\"Error writing file %s\",file_metadata['TargetFile'])\n\n return files_metadata", "def ratt(self):\n print(\"Running annotation transfer\")\n if (self._args.transfer_type != \"Strain\") and (\n self._args.transfer_type != \"Assembly\") and (\n self._args.transfer_type != \"Species\") and (\n self._args.transfer_type != \"Assembly.Repetitive\") and (\n self._args.transfer_type != \"Strain.Repetitive\") and (\n self._args.transfer_type != \"Species.Repetitive\") and (\n self._args.transfer_type != \"Multiple\") and (\n self._args.transfer_type != \"Free\"):\n print(\"Error: please assign correct --transfer_type!\")\n sys.exit()\n if (self._args.ref_embl_files is None) and (\n self._args.ref_gbk_files is None):\n print(\"Error: please assign proper embl or genbank folder\")\n sys.exit()\n elif (self._args.ref_embl_files is not None) and (\n self._args.ref_gbk_files is not None):\n print(\"Error: please choose embl as input or genbank as input\")\n sys.exit()\n self._args.ratt_path = self.check_execute_file(self._args.ratt_path)\n self.check_multi_files(\n [self._args.target_fasta_files, self._args.ref_fasta_files],\n [\"--target_fasta_files\", \"--ref_fasta_files\"])\n self.check_parameter([self._args.element, self._args.compare_pair],\n [\"--element\", \"--compare_pair\"])\n project_creator.create_subfolders(\n self._paths.required_folders(\"annotation_transfer\"))\n args_ratt = self.args_container.container_ratt(\n self._args.ratt_path, self._args.element, self._args.transfer_type,\n self._args.ref_embl_files, self._args.ref_gbk_files,\n self._args.target_fasta_files, self._args.ref_fasta_files,\n self._paths.ratt_folder, self._args.convert_to_gff_rnt_ptt,\n self._paths.tar_annotation_folder, self._args.compare_pair)\n ratt = RATT(args_ratt)\n ratt.annotation_transfer(args_ratt)", "def process_object( self, obj ):\n\n result = {}\n\n metadata = obj.get( 'metadata', {} )\n spec = obj.get( 'spec', {} )\n labels = metadata.get( 'labels', {} )\n annotations = metadata.get( 'annotations', {} )\n owners = metadata.get( 'ownerReferences', [] )\n\n pod_name = metadata.get( \"name\", '' )\n namespace = metadata.get( \"namespace\", '' )\n\n deployment_name = self._get_deployment_name_from_owners( owners, namespace )\n daemonset_name = self._get_daemonset_name_from_owners( owners, namespace )\n\n container_names = []\n for container in spec.get( 'containers', [] ):\n container_names.append( container.get( 'name', 'invalid-container-name' ) )\n\n try:\n annotations = annotation_config.process_annotations( annotations )\n except BadAnnotationConfig, e:\n self._logger.warning( \"Bad Annotation config for %s/%s. All annotations ignored. %s\" % (namespace, pod_name, str( e )),\n limit_once_per_x_secs=300, limit_key='bad-annotation-config-%s' % info.uid )\n annotations = JsonObject()\n\n\n self._logger.log( scalyr_logging.DEBUG_LEVEL_2, \"Annotations: %s\" % ( str( annotations ) ) )\n\n # create the PodInfo\n result = PodInfo( name=pod_name,\n namespace=namespace,\n uid=metadata.get( \"uid\", '' ),\n node_name=spec.get( \"nodeName\", '' ),\n labels=labels,\n container_names=container_names,\n annotations=annotations,\n deployment_name=deployment_name,\n daemonset_name=daemonset_name)\n return result", "def _load_display_annotation(self, index):\n\n annotation_file = os.path.join(\n self._data_path, 'annotations/instances_{}.txt'.format(self._image_set))\n assert os.path.isfile(annotation_file), annotation_file\n\n txt_annotations = open(annotation_file, 'r')\n annotations = txt_annotations.readlines()\n\n num_objs = 3\n boxes = np.zeros((num_objs, 4), dtype=np.uint16)\n gt_classes = np.zeros((num_objs), 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 width, height = 0, 0\n\n for i in range(0, len(annotations), 3):\n if i != index:\n continue\n temp = annotations[i].split(',')\n \n # data in ground truth file has 3 line for each img\n for j in range(0, 3):\n temp = annotations[i + j].split(',')\n x1 = int(temp[1]) \n y1 = int(temp[2]) \n x2 = int(temp[3]) \n y2 = int(temp[4]) \n width = x2 - x1\n height = y2 - y1\n box = [x1, y1, x2, y2] \n boxes[j, :] = box\n gt_classes[j] = int(temp[5][0]) + 1\n seg_areas[j] = (x2 - x1) * (y2 - y1)\n overlaps[j, int(temp[5][0]) + 1] = 1.0\n print(\"===================[display.py:173] \", overlaps)\n ds_utils.validate_boxes(boxes, width=width, height=height)\n overlaps = scipy.sparse.csr_matrix(overlaps)\n print(\"===================[display.py:173] \", overlaps)\n\n return {'width': width,\n 'height': height,\n 'boxes': boxes,\n 'gt_classes': gt_classes,\n 'gt_overlaps': overlaps,\n 'flipped': False,\n 'seg_areas': seg_areas}", "def _create_instances(self):\n #initialize the module\n _instance = self._module()\n self._instance_list = [_instance]", "def _split_into_instances(sa, interfaces, process, resource_new_insts, simplified_map=None):\n access_map = {}\n\n accesses = process.accesses()\n interface_to_value, value_to_implementation, basevalue_to_value, interface_to_expression, final_options_list = \\\n _extract_implementation_dependencies(access_map, accesses)\n\n # Generate access maps itself with base values only\n maps = []\n total_chosen_values = set()\n if final_options_list:\n ivector = [0 for _ in enumerate(final_options_list)]\n\n for _ in enumerate(interface_to_value[final_options_list[0]]):\n new_map = copy.deepcopy(access_map)\n chosen_values = sortedcontainers.SortedSet()\n\n # Set chosen implementations\n for interface_index, identifier in enumerate(final_options_list):\n expression = interface_to_expression[identifier]\n options = list(sorted([val for val in interface_to_value[identifier]\n if len(interface_to_value[identifier][val]) == 0]))\n chosen_value = options[ivector[interface_index]]\n implementation = value_to_implementation[chosen_value]\n\n # Assign only values without base values\n if not interface_to_value[identifier][chosen_value]:\n new_map[expression][identifier] = implementation\n chosen_values.add(chosen_value)\n total_chosen_values.add(chosen_value)\n\n # Iterate over values\n ivector[interface_index] += 1\n if ivector[interface_index] == len(options):\n ivector[interface_index] = 0\n maps.append([new_map, chosen_values])\n else:\n # Choose atleast one map\n if not maps:\n maps = [[access_map, sortedcontainers.SortedSet()]]\n\n # Then set the other values\n for expression in access_map.keys():\n for interface in access_map[expression].keys():\n intf_additional_maps = []\n # If container has values which depends on another container add a map with unitialized value for the\n # container\n if access_map[expression][interface] and [val for val in interface_to_value[interface]\n if interface_to_value[interface][val]]:\n new = [copy.deepcopy(maps[0][0]), copy.copy(maps[0][1])]\n new[1].remove(new[0][expression][interface])\n new[0][expression][interface] = None\n maps.append(new)\n\n for amap, chosen_values in maps:\n if not amap[expression][interface]:\n # Choose those values whose base values are already chosen\n\n # Try to avoid repeating values\n strict_suits = sorted(\n [value for value in interface_to_value[interface]\n if value not in total_chosen_values and\n (not interface_to_value[interface][value] or\n chosen_values.intersection(interface_to_value[interface][value]) or\n [cv for cv in interface_to_value[interface][value]\n if cv not in value_to_implementation and cv not in chosen_values])])\n if not strict_suits:\n # If values are repeated just choose random one\n suits = sorted(\n [value for value in interface_to_value[interface]\n if not interface_to_value[interface][value]or\n chosen_values.intersection(interface_to_value[interface][value]) or\n ([cv for cv in interface_to_value[interface][value]\n if cv not in value_to_implementation and cv not in chosen_values])])\n if suits:\n suits = [suits.pop()]\n else:\n suits = strict_suits\n\n if len(suits) == 1:\n amap[expression][interface] = value_to_implementation[suits[0]]\n chosen_values.add(suits[0])\n total_chosen_values.add(suits[0])\n elif len(suits) > 1:\n # There can be many useless resource implementations ...\n interface_obj = interfaces.get_intf(interface)\n if isinstance(interface_obj, Resource) and resource_new_insts > 0:\n suits = suits[0:resource_new_insts]\n elif isinstance(interface_obj, Container):\n # Ignore additional container values which does not influence the other interfaces\n suits = [v for v in suits if v in basevalue_to_value and len(basevalue_to_value) > 0]\n else:\n # Try not to repeate values\n suits = [v for v in suits if v not in total_chosen_values]\n\n value_map = _match_array_maps(expression, interface, suits, maps, interface_to_value,\n value_to_implementation)\n intf_additional_maps.extend(\n _fulfil_map(expression, interface, value_map, [[amap, chosen_values]],\n value_to_implementation, total_chosen_values, interface_to_value))\n\n # Add additional maps\n maps.extend(intf_additional_maps)\n\n if isinstance(simplified_map, list):\n # Forbid pointer implementations\n complete_maps = maps\n maps = []\n\n # Set proper given values\n for index, value in enumerate(simplified_map):\n smap = value[0]\n instance_map = sortedcontainers.SortedDict()\n used_values = sortedcontainers.SortedSet()\n\n for expression in smap.keys():\n instance_map[expression] = sortedcontainers.SortedDict()\n\n for interface in smap[expression].keys():\n if smap[expression][interface]:\n value = smap[expression][interface]\n if value in value_to_implementation:\n instance_map[expression][interface] = value_to_implementation[value]\n else:\n instance_map[expression][interface] = \\\n interfaces.get_value_as_implementation(sa, value, interface)\n\n used_values.add(smap[expression][interface])\n elif complete_maps[index][0][expression][interface]:\n # To avoid calls by pointer\n instance_map[expression][interface] = ''\n else:\n instance_map[expression][interface] = smap[expression][interface]\n maps.append([instance_map, used_values])\n else:\n # Prepare simplified map with values instead of Implementation objects\n simplified_map = list()\n for smap, cv in maps:\n instance_desc = [sortedcontainers.SortedDict(), list(cv)]\n\n for expression in smap.keys():\n instance_desc[0][expression] = sortedcontainers.SortedDict()\n for interface in smap[expression].keys():\n if smap[expression][interface]:\n instance_desc[0][expression][interface] = smap[expression][interface].value\n else:\n instance_desc[0][expression][interface] = smap[expression][interface]\n simplified_map.append(instance_desc)\n\n return [m for m, cv in maps], simplified_map" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Preload the dataframe of df_responses to prepare for the fit function in case you need to resume the fit function failed previously.
def preload_fit(self, df_responses, mapping_matrix): self.df_responses = df_responses self.mapping_matrix = mapping_matrix self.to_resume = True
[ "def set_results_df(context):\n context.results_df = pd.DataFrame()\n context.desired_outputs = []", "def res_df(self):\n if not hasattr(self, 'res_dict'):\n print('you must perform the fit first! ...e.g. call performfit()')\n return\n\n vals = self._assignvals(self.res_dict)\n for key, val in self._assignvals(self.res_dict).items():\n vals[key] = vals[key][~self.mask]\n\n resdf = pd.DataFrame(vals, list(chain(*self._orig_index))\n ).groupby(level=0).first()\n\n return resdf", "def prepare_dataframe(self):\n startURL = self.config.web_url\n df = waifu.DataFrame(self.dataframe, columns=[n for n in self.dataframe])\n\n print(\"Getting the available pages to scrape...\")\n all_pages = self.get_all_valid_pages(startURL)\n all_books_URLs = []\n\n chunky_size = 10\n processes = 10\n\n print(\"Getting all the books from each page...\")\n with Pool(processes=processes) as pool, tqdm.tqdm(total=len(all_pages)) as pbar:\n for data in pool.imap_unordered(self.get_all_books, all_pages , chunksize=chunky_size):\n all_books_URLs.extend(data)\n pbar.update()\n\n pool.terminate()\n pool.join()\n pbar.close()\n \n print(\"Getting each book's data\")\n with Pool(processes=processes) as pool, tqdm.tqdm(total=len(all_books_URLs)) as pbar:\n for book in pool.imap_unordered(self.get_book_meta, all_books_URLs, chunksize=chunky_size):\n df = df.append(book, ignore_index=True)\n pbar.update()\n\n pool.terminate()\n pool.join()\n pbar.close()\n\n return df", "def fit_if_needed(self):\n if not self._fitted:\n self.fit()", "def getTrainingDataset(transcript_feats, Y_df, return_df_full=False):\n\n df_full = transcript_feats[transcript_feats[\"event\"]==\"offer received\"].copy()\n df_full = df_full.merge(Y_df, on=[\"person\",\"time\"], how=\"left\").reset_index(drop=True)\n df = dropAuxFeatures(df_full)\n\n if return_df_full:\n return df_full, df\n else:\n return df", "def askForData(self,nbNeededObservation=32):\n numberOfDays = int(nbNeededObservation/8)+1 # the theorical number of days we need + 1 day for safety\n try:\n response = requests.get(self.infos[\"URL\"]+\"prediction/{}\".format(numberOfDays))\n if response.ok:\n data = response.json()\n except:\n Logger.log_error(\"Unable to ask the API for the content of prediction\")\n return(None)\n \n try:\n # convert to dataframe\n dfiq,dfsynop,dfp = pd.DataFrame.from_dict(data[0]),pd.DataFrame.from_dict(data[1]),pd.DataFrame.from_dict(data[2])\n \n \n # Shape the data:\n # 1 - mix the datasets: \n #(please see \"MixDatasets.ipynb\" in the data cleaning section of our researchs for more information)\n dfiq['date'] = pd.to_datetime(dfiq['date'],utc=True)\n dfsynop['date'] = pd.to_datetime(dfsynop['date'],utc=True)\n dfp['date'] = pd.to_datetime(dfp['date'],utc=True)\n \n # make sure we have the today data for the pollutant with ffil: \n dfp = dfp.append({\"date\": datetime.now().strftime(\"%Y-%m-%d\")+\" 00:00:00+00:00\"},ignore_index=True)\n dfp['date'] = pd.to_datetime(dfp['date'],utc=True)\n dfp = dfp.drop_duplicates()\n dfp = dfp.sort_values(by=\"date\")\n dfp = dfp.fillna(method = \"ffill\") \n \n def getDay(row):\n return(row[\"date\"].date())\n\n dfsynop[\"day\"] = dfsynop.apply(lambda row: getDay(row), axis=1)\n dfiq[\"day\"] = dfiq.apply(lambda row: getDay(row), axis=1)\n dfp[\"day\"] = dfp.apply(lambda row: getDay(row), axis=1)\n \n dfp = dfp.drop(columns=\"date\")\n \n df = pd.merge(dfiq, dfsynop, how='inner', on=\"day\")\n df = pd.merge(df,dfp, how='inner', on=\"day\")\n df = df.drop(columns=[\"date_x\",\"day\"])\n df = df.rename(columns={\"date_y\":\"date\", \"value\":\"IQ\"})\n df = df.drop_duplicates()\n \n # 2 - select what we need and shaping\n # Please see \"0_ResearchWork\\4_SecondModel\\ModelLSTM_Alex.ipynb\" for more information\n \n features_considered = ['IQ','pressure','wind_direction','wind_force','humidity','temperature','NO2','O3','PM10']\n features = df[features_considered]\n features.index = df['date']\n \n print(features)\n\n dataset_test = features.values\n\n def higher_value(features,i):\n return[row[i] for row in dataset_test]\n\n max_pressure = max(higher_value(dataset_test,1))\n max_wind_force = max(higher_value(dataset_test,3))\n max_temperature = max(higher_value(dataset_test, 5))\n\n #normalize\n features['NO2'] = features['NO2'].apply(lambda x: x/10)\n features['O3'] = features['O3'].apply(lambda x: x/10)\n features['PM10'] = features['PM10'].apply(lambda x: x/10)\n \n features['pressure'] = features['pressure'].apply(lambda x: x/max_pressure)\n features['wind_force'] = features['wind_force'].apply(lambda x: x/max_wind_force)\n features['humidity'] = features['humidity'].apply(lambda x: x/100)\n features['temperature'] = features['temperature'].apply(lambda x: (x-273.15)/(max_temperature-273.15)) \n\n # IQ dummy \n dummy = pd.get_dummies(features['IQ'])\n IQDummy = pd.DataFrame(columns = range(1,11,1))\n IQDummy[dummy.columns] = dummy.fillna(0)\n\n iqlist = list(range(1,11,1))\n for i,r in enumerate(iqlist):\n iqlist[i] = \"IQ\"+str(r)\n IQDummy.columns = iqlist\n\n #wind_direction to categorical\n dummy = pd.get_dummies(features['wind_direction'])\n windDummy = pd.DataFrame(columns = range(0,361,10))\n windDummy[dummy.columns] = dummy.fillna(0)\n\n features = pd.concat([features, windDummy, IQDummy], axis=1)\n features = features.drop(columns=[\"wind_direction\",\"IQ\"])\n\n features = features.fillna(0)\n \n # 3- selecting the time period we need in the synop:\n # from the last 12:00 to the next \"numberOfObservations\" later\n countRow = 0\n x_pred = []\n for indexRow, rowx in features.iterrows():\n # for each day we found with a value at 12:00\n if indexRow.hour == 9:\n # indexes for x (the range is inversed as our data are from the oldest to the newest)\n batch = range(countRow, countRow - nbNeededObservation, -1)\n #application\n x_pred.append(features.iloc[batch].values)\n dayConsidered = str(indexRow)[:10]\n break\n countRow+=1\n except:\n Logger.log_error(\"Unable to shape the content for prediction\")\n return(None)\n \n return(np.array(x_pred),dayConsidered)", "def prepare_data(self) -> None:\n self.source = ExperienceSource(self.env, self.agent)\n self.buffer = ReplayBuffer(self.replay_size)\n self.populate(self.warm_start_size)\n\n self.dataset = RLDataset(self.buffer, self.sample_len)", "def fit(self, df: pd.DataFrame) -> \"_ProphetModel\":\n prophet_df = pd.DataFrame()\n prophet_df[\"y\"] = df[\"target\"]\n prophet_df[\"ds\"] = df[\"timestamp\"]\n for column_name in df.columns:\n if column_name.startswith(\"regressor\"):\n if column_name in [\"regressor_cap\", \"regressor_floor\"]:\n prophet_column_name = column_name[len(\"regressor_\") :]\n else:\n self.model.add_regressor(column_name)\n prophet_column_name = column_name\n prophet_df[prophet_column_name] = df[column_name]\n self.model.fit(prophet_df)\n return self", "def generate_pandas_data(fit_results):\n data = {}\n data[\"q\"] = fit_results.q\n for par in fit_results.parameter:\n data[str(par.values)] = fit_results.parameters.loc[par].values\n pd_data_frame = pd.DataFrame(data = data)\n return pd_data_frame", "def run(self):\n results_df = None\n for response in self.responses():\n if response.meets_criteria():\n if results_df is None:\n results_df = response.run()\n else: \n results_df = pd.concat([results_df, response.run()])\n return results_df", "def lacer(df, df1, train_start_date, train_end_date, test_start_date, test_end_date, request_type, CD, predictor_num): #Once model is ready, replace df with csv\n\n #Create Training and Testing Sets\n dftrain = preprocessing(df , train_start_date, train_end_date)\n dftrain = dftrain.reset_index(drop = True)\n dftest = preprocessing(df1, test_start_date, test_end_date)\n dftest = dftest.reset_index(drop = True)\n\n #Reserve test set for training on all 3 models. \n y_train, y_test = lc.CreateTestSet(dftest, predictor_num)\n y_test = y_test.reshape((-1, 1))\n\n\n## 2 Models\n #Model1: CD\n modelCD = SparseGaussianCRF(lamL=0.1, lamT=0.1, n_iter=10000)\n dftrainCD = dftrain[dftrain['CD'] == CD].reset_index(drop = True)\n\n X_trainCD, X_testCD = lc.CreateTrainSet(dftrainCD, predictor_num)\n X_testCD = X_testCD.reshape((-1, 1))\n modelCD.fit(X_trainCD, X_testCD)\n\n y_predCD = modelCD.predict(y_train)\n\n #Model2: Request_type\n modelRT = SparseGaussianCRF(lamL=0.1, lamT=0.1, n_iter=10000)\n dftrainRT = dftrain[dftrain['RequestType'] == request_type].reset_index(drop = True)\n\n X_trainRT, X_testRT = lc.CreateTrainSet(dftrainRT, predictor_num)\n X_testRT = X_testRT.reshape((-1, 1))\n\n modelRT.fit(X_trainRT, X_testRT)\n\n y_predRT = modelRT.predict(y_train)\n\n\n #Average out all predictions\n y_predFinal = (y_predCD + y_predRT )/2\n\n #Return metrics \n return lc.metrics(y_predFinal, y_test)", "def initialize_dataframe(self):\n # TODO: check if the set of columns in dataframe after initialiation is exactly\n # the set of base features.\n raise NotImplementedError", "def res_df_group(self):\n if not hasattr(self, 'res_dict'):\n print('you must perform the fit first! ...e.g. call performfit()')\n return\n\n series = []\n for key, val in self.res_dict.items():\n x = np.empty(len(self.meandatetimes_group), dtype=float)\n [x.put(ind, val_i) for val_i, ind in\n zip(val, self._param_assigns[key].values())]\n series.append(pd.Series(x,\n self.meandatetimes_group,\n name=key))\n resdf = pd.concat(series, axis=1)\n return resdf", "def _create_initial_frame_dataset(self):\n dataset = self._create_dataset(\n shuffle_files=self._simulation_random_starts\n )\n if self._simulation_random_starts:\n dataset = dataset.shuffle(buffer_size=1000)\n return dataset.repeat().batch(self._batch_size)", "def update_predictions(self):\n\n\n assert self._models != dict(), \"model must be fitted or loaded before predictions are possible\"\n self._base.delete_predictions()\n data = self._base.get_not_predicted()\n i = 0\n while data.shape[0] != 0:\n print(\"UPDATING PREDICTIONS FOR CHUNK {}\".format(i))\n x = self.bow_preprocessing(data)\n print(\"- performing predictions\")\n y = self._predict(x)\n y_val = y.values\n ids = data[\"id\"].values.reshape(-1,1)\n if y_val.shape[0] != ids.shape[0]:\n raise RuntimeError(\"internal error on binding results to sentence ids\")\n result_df = pd.DataFrame(np.concatenate((ids, y_val), axis=1), columns=[\"sentence_id\", *y.columns])\n print(\"- updating data base\")\n self._base.update_predictions(result_df)\n\n i += 1\n data = self._base.get_not_predicted()\n\n self.predicted = True", "def load(self):\n if not self._loaded:\n if self._response is None:\n self._next_page()\n data = self.data_from_response(self._response)\n self._apply(data)\n self._loaded = True", "def initialize_dataframe(self, overwrite=False):\n if (self.data is None) or overwrite:\n columns = self._build_column_list()\n self.data = pd.DataFrame(columns=columns)", "def _prepare_spikes_df_for_recurrsive_decoding(active_one_step_decoder, spikes_df):\n active_second_order_spikes_df = deepcopy(spikes_df)\n # TODO: figure it out instead of hacking -- Currently just dropping the last time bin because something is off \n invalid_timestamp = np.nanmax(active_second_order_spikes_df['binned_time'].astype(int).to_numpy()) # 11881\n active_second_order_spikes_df = active_second_order_spikes_df[active_second_order_spikes_df['binned_time'].astype(int) < invalid_timestamp] # drop the last time-bin as a workaround\n # backup measured columns because they will be replaced by the new values:\n active_second_order_spikes_df['x_measured'] = active_second_order_spikes_df['x'].copy()\n active_second_order_spikes_df['y_measured'] = active_second_order_spikes_df['y'].copy()\n spike_binned_time_idx = (active_second_order_spikes_df['binned_time'].astype(int)-1) # subtract one to get to a zero-based index\n # replace the x and y measured positions with the most-likely decoded ones for the next round of decoding\n active_second_order_spikes_df['x'] = active_one_step_decoder.most_likely_positions[spike_binned_time_idx.to_numpy(),0] # x-pos\n active_second_order_spikes_df['y'] = active_one_step_decoder.most_likely_positions[spike_binned_time_idx.to_numpy(),1] # y-pos\n return active_second_order_spikes_df", "def prepare_fit_kwargs(self) -> None:\n self.fit_kwargs = {\"model\": self.model}\n if self.datamodule is not None:\n self.fit_kwargs[\"datamodule\"] = self.datamodule" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a column on "curr_item" index to the IncrementalSparseMatrix matrix_builder with the samples inside response_df.
def add_sample_responses_to_matrix_builder(self, matrix_builder, agg_strategy, filter_sample_method, response_df, curr_item, mapping): filtered_response_df = self.FILTER_SAMPLES_METHODS[filter_sample_method].filter_samples(response_df) solution_list = self.AGGREGATORS[agg_strategy].get_aggregated_response(filtered_response_df) self._print("The aggregated response for item {} is {}".format(curr_item, solution_list)) row_indices = np.where(solution_list > 0)[0] matrix_builder.add_data_lists(mapping[row_indices], [curr_item] * len(row_indices), solution_list[row_indices])
[ "def build_similarity_matrix(self, df_responses, agg_strategy, filter_sample_method, mapping_matrix):\n n_items = self.URM_train.shape[1]\n if mapping_matrix is None:\n mapping_matrix = np.repeat(np.reshape(np.arange(0, n_items), newshape=(1, n_items)), repeats=n_items, axis=0)\n matrix_builder = IncrementalSparseMatrix(n_rows=n_items, n_cols=n_items)\n\n for currentItem in range(n_items):\n response_df = df_responses[df_responses.item_id == currentItem].copy()\n self.add_sample_responses_to_matrix_builder(matrix_builder, agg_strategy, filter_sample_method, response_df,\n currentItem, mapping_matrix[currentItem])\n\n return sps.csr_matrix(matrix_builder.get_SparseMatrix())", "def add_itemIdx():\n itemids = self.data[self.item_key].unique()\n self.n_items = len(itemids)\n self.itemidmap = pd.DataFrame({self.item_key: itemids, 'ItemIdx': np.arange(self.n_items)})\n self.data = pd.merge(self.data, self.itemidmap, on=self.item_key, how='inner')", "def _item_to_df_row(self, item):\r\n x = self.x\r\n a = item['actions']\r\n h = self.predict(a)\r\n nnz_idx = np.flatnonzero(a)\r\n row = {\r\n 'cost': float(item['cost']),\r\n 'size': len(nnz_idx),\r\n 'features': [self._variable_names[j] for j in nnz_idx],\r\n 'feature_idx': nnz_idx,\r\n 'x': x[nnz_idx],\r\n 'x_new': x[nnz_idx] + a[nnz_idx],\r\n 'score_new': self.score(a),\r\n 'yhat_new': h,\r\n 'feasible': item['feasible'],\r\n 'flipped': np.not_equal(h, self.yhat),\r\n }\r\n\r\n return row", "def update_column_item(item, item_nz, nnz_users_per_item, M,lambda_I,\n item_features_new):\n g = item_nz #- bias_user_nz - bias_item[item]\n b = M @ g\n A = M @ M.T + nnz_users_per_item[item] * lambda_I\n item_features_new[:, item] = np.linalg.solve(A, b)\n \n return item_features_new", "def _getitem_sparse2gensim(self, result):\n def row_sparse2gensim(row_idx, csr_matrix):\n indices = csr_matrix.indices[csr_matrix.indptr[row_idx]:csr_matrix.indptr[row_idx+1]]\n g_row = [(col_idx, csr_matrix[row_idx, col_idx]) for col_idx in indices]\n return g_row\n\n output = (row_sparse2gensim(i, result) for i in xrange(result.shape[0]))\n\n return output", "def _update_sparse_rewards(self, points_this_step):\n raise NotImplementedError(\"TODO\")", "def build_matrix_A(API2idx, apk2call, apk2idx):\n# matrix_A = np.zeros((len(apk2idx), len(API2idx)))\n matrix_A = scipy.sparse.lil_matrix((len(apk2idx), len(API2idx)))\n total = len(apk2idx)\n counter = 0\n for apk in apk2idx:\n counter += 1\n print(\"{:.2f}%\".format(counter / total * 100), apk)\n apk_idx = apk2idx[apk]\n API_indices = apk2call[apk]\n for API_idx in API_indices:\n matrix_A[apk_idx, API_idx] = 1\n return matrix_A", "def update_item_matrix(self, data, user_matrix, item_matrix, num_features, lambda_item):\n lambda_I = lambda_item * sp.eye(num_features)\n for i in range(self.num_items):\n indices = self.get_observed_users_per_item(data, i)\n U = user_matrix[indices, :]\n A = U.T @ U + lambda_I\n B = U.T @ data[indices, i]\n item_matrix[:, i] = np.linalg.solve(A, B).squeeze()\n return item_matrix", "def _item_expanded(self, tree_item):\r\n path = self.model().filePath(tree_item)\r\n if path not in self.state_index:\r\n self.state_index.append(path)", "def _build_index(self):\n row0 = list(map(len, self._lists))\n\n if len(row0) == 1:\n self._index[:] = row0\n self._offset = 0\n return\n\n head = iter(row0)\n tail = iter(head)\n row1 = list(starmap(add, zip(head, tail)))\n\n if len(row0) & 1:\n row1.append(row0[-1])\n\n if len(row1) == 1:\n self._index[:] = row1 + row0\n self._offset = 1\n return\n\n size = 2 ** (int(log2(len(row1) - 1)) + 1)\n row1.extend(repeat(0, size - len(row1)))\n tree = [row0, row1]\n\n while len(tree[-1]) > 1:\n head = iter(tree[-1])\n tail = iter(head)\n row = list(starmap(add, zip(head, tail)))\n tree.append(row)\n\n reduce(iadd, reversed(tree), self._index)\n self._offset = size * 2 - 1", "def update_matrix_lead_id(self, response, *args, **kwargs):\n pass", "def pushMatrix(state: 'SoState') -> \"SbMatrix\":\n return _coin.SoModelMatrixElement_pushMatrix(state)", "def add_meta_to_matrix(self, matrix, add_subject_id=True):\n df = pd.DataFrame(matrix, columns=self.column_names)\n if add_subject_id:\n df = pd.concat([self.subject_id_column, df], axis=1)\n return df", "def __create_sparse_matrix(self):\r\n n_qubits = self.n_qubits\r\n size = self.size\r\n\r\n # Create empty numpy array\r\n dense_matrix = np.zeros((size,size))\r\n\r\n # Loop for every row\r\n for i in range(size):\r\n state_binary = np.binary_repr(i, n_qubits)\r\n\r\n # Flip string and convert to integer\r\n state_flipped = state_binary[::-1]\r\n k = int(state_flipped, 2)\r\n\r\n #Assign relevant matrix element to 1\r\n dense_matrix[i,k] = 1\r\n\r\n # Convert dense matrix to csc_matrix\r\n return csc_matrix(dense_matrix)", "def SoModelMatrixElement_pushMatrix(state: 'SoState') -> \"SbMatrix\":\n return _coin.SoModelMatrixElement_pushMatrix(state)", "def feature_matrix_from_interactions(self, df):\n\n student_idxes = np.array(df[self.name_of_user_id].map(self.idx_of_student_id).values)\n assessment_idxes = np.array(df['module_id'].map(self.idx_of_assessment_id).values)\n\n num_ixns = len(df)\n ixn_idxes = np.concatenate((range(num_ixns), range(num_ixns)), axis=0)\n studa_idxes = np.concatenate((\n student_idxes, self.num_students + assessment_idxes), axis=0)\n\n return sparse.coo_matrix(\n (np.ones(2*num_ixns), (ixn_idxes, studa_idxes)),\n shape=(num_ixns, self.num_students + self.num_assessments)).tocsr()", "def feature_matrix_from_interactions(self, df):\n\n student_idxes = np.array(df[self.name_of_user_id].map(self.idx_of_student_id).values)\n assessment_idxes = np.array(df['module_id'].map(self.idx_of_assessment_id).values)\n\n num_ixns = len(df)\n ixn_idxes = np.concatenate((range(num_ixns), range(num_ixns)), axis=0)\n studa_idxes = np.concatenate((\n student_idxes * self.num_assessments + assessment_idxes,\n self.num_students * self.num_assessments + assessment_idxes), axis=0)\n\n return sparse.coo_matrix(\n (np.ones(2*num_ixns), (ixn_idxes, studa_idxes)),\n shape=(num_ixns, (self.num_students + 1) * self.num_assessments)).tocsr()", "def recommend_items(self, seed_item_name: str, similarity_metric: str, weight: float) -> DataFrame:\n\n \n #compute weighted average between similarity values determined by collaborative filtering and those determined by content recommendation\n #(\"why is reset_index applied to the component reclists?\" needed to properly compute the weighted average of the content/collaborative similarities for each item)\n #raise value error if an appropriate similarity metric is not provided\n \n if similarity_metric == \"cos\":\n\n collabrecs: DataFrame = self.cosine(seed_item_name, self.item_matrix_training).sort_values(by = \"Title\", ascending = False)\n collabrecs.reset_index(drop=True, inplace=True)\n \n contentrecs: DataFrame = self.cosine(seed_item_name, self.latent_content_features).sort_values(by = \"Title\", ascending = False)\n contentrecs.reset_index(drop=True, inplace=True)\n\n weighted_average_recs: DataFrame = DataFrame({'Title': collabrecs[\"Title\"], 'Similarity': weight*collabrecs[\"Similarity\"] + (1 - weight)*contentrecs[\"Similarity\"], 'Ratings_count': collabrecs[\"Ratings_count\"]})\n\n return weighted_average_recs.sort_values(by = [\"Similarity\", \"Ratings_count\"], ascending = False) \n\n elif similarity_metric == \"corr\":\n\n collabrecs: DataFrame = self.corr(seed_item_name, self.item_matrix_training)\n collabrecs.reset_index(drop=True, inplace=True)\n \n contentrecs: DataFrame = self.corr(seed_item_name, self.latent_content_features)\n contentrecs.reset_index(drop=True, inplace=True)\n \n weighted_average_recs: DataFrame = DataFrame({'Title': collabrecs[\"Title\"], 'Similarity': weight*collabrecs[\"Similarity\"] + (1 - weight)*contentrecs[\"Similarity\"], 'Ratings_count': collabrecs[\"Ratings_count\"]})\n\n return weighted_average_recs.sort_values(by = [\"Similarity\", \"Ratings_count\"], ascending = False) \n\n else: raise ValueError(\"The similarity metric must be 'corr', for correlation, or 'cos', for cosine similarity.\")", "def pushMatrix(state: 'SoState', localmatrix: 'SbMatrix') -> \"SbMatrix &\":\n return _coin.SoBBoxModelMatrixElement_pushMatrix(state, localmatrix)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It builds the similarity matrix by using a dataframe with all the samples collected from the solver in the fit function. The samples obtained from the solver are postprocessed with a filtering operation (i.e. filter_strategy) and an aggregation operation (i.e. agg_strategy). At the end of this pipeline, it outputs a single list containing a column of the similarity matrix.
def build_similarity_matrix(self, df_responses, agg_strategy, filter_sample_method, mapping_matrix): n_items = self.URM_train.shape[1] if mapping_matrix is None: mapping_matrix = np.repeat(np.reshape(np.arange(0, n_items), newshape=(1, n_items)), repeats=n_items, axis=0) matrix_builder = IncrementalSparseMatrix(n_rows=n_items, n_cols=n_items) for currentItem in range(n_items): response_df = df_responses[df_responses.item_id == currentItem].copy() self.add_sample_responses_to_matrix_builder(matrix_builder, agg_strategy, filter_sample_method, response_df, currentItem, mapping_matrix[currentItem]) return sps.csr_matrix(matrix_builder.get_SparseMatrix())
[ "def similarities(attributes_df, columns, joint = False, metric = \"eucl_dist\"):\n if len(columns) == 0:\n return None\n if len(attributes_df) == 0:\n return None\n\n if type(columns[0]) == float or type(columns[0]) == int:\n columns = [int(i) for i in columns]\n column_names = list(attributes_df)\n column_names = [column_names[i] for i in columns]\n elif type(columns[0]) == str:\n column_names = columns\n else:\n raise ValueError(\"Unsupported column type\")\n return None\n\n n = len(np.array(attributes_df[column_names[0]]))\n\n sims = []\n\n if joint:\n feature_array = []\n for c in column_names:\n scaler = MinMaxScaler()\n temp = np.array(attributes_df[c])\n temp = temp.reshape(-1, 1)\n scaler.fit(temp)\n scaled = scaler.transform(temp)\n feature_array.append(scaled)\n scaler = MinMaxScaler\n scaler.fit(attributes_df[column_names])\n feature_array_2 = scaler.transform(attributes_df[column_names])\n\n\n feature_array = np.array(feature_array)\n\n print(feature_array, feature_array_2)\n return\n\n\n\n # TODO\n scaler = MinMaxScaler()\n scaler.fit()\n print(\"\")\n else:\n for c in column_names:\n try:\n temp = np.array(attributes_df[c])\n except:\n raise ValueError(\"Unsupported or inconsistent column type\")\n return None\n\n s2 = np.var(temp, ddof = 1)\n temp_sim = np.zeros(shape = (n, n))\n\n for i in range(n):\n for k in range(i + 1, n):\n if metric == \"eucl_dist\" or metric == \"fuzzy_subset\":\n dist = (temp[i] - temp[k])**2\n temp_sim[i,k] = np.exp(-dist/s2)\n temp_sim[k,i] = temp_sim[i,k]\n\n sims.append(temp_sim)\n\n return sims", "def calculate_matrix_presamples(self):\n assert self.data, \"Must load parameter data before using this method\"\n\n substitutor = FormulaSubstitutor({v['original']: k for k, v in self.data.items()})\n\n interpreter = ParameterSet(\n self.data,\n self.global_params\n ).get_interpreter(evaluate_first=False)\n queryset = ParameterizedExchange.select().where(\n ParameterizedExchange.group == self.group\n )\n results = {obj.exchange: interpreter(substitutor(obj.formula))\n for obj in queryset}\n\n samples, indices = [], []\n queryset = ExchangeDataset.select().where(\n ExchangeDataset.id << tuple(results)\n )\n\n for obj in queryset:\n samples.append(np.array(results[obj.id]).reshape(1, -1))\n indices.append((\n (obj.input_database, obj.input_code),\n (obj.output_database, obj.output_code),\n obj.type\n ))\n\n self.matrix_data = split_inventory_presamples(np.vstack(samples), indices)\n return results", "def compute_similarities(self):\n\n construction_func = {'cosine': sims.cosine,\n 'msd': sims.msd,\n 'pearson': sims.pearson,\n 'pearson_baseline': sims.pearson_baseline}\n\n if self.sim_options['user_based']:\n n_x, yr = self.trainset.n_users, self.trainset.ir\n else:\n n_x, yr = self.trainset.n_items, self.trainset.ur\n\n min_support = self.sim_options.get('min_support', 1)\n\n args = [n_x, yr, min_support]\n\n name = self.sim_options.get('name', 'msd').lower()\n if name == 'pearson_baseline':\n shrinkage = self.sim_options.get('shrinkage', 100)\n bu, bi = self.compute_baselines()\n if self.sim_options['user_based']:\n bx, by = bu, bi\n else:\n bx, by = bi, bu\n\n args += [self.trainset.global_mean, bx, by, shrinkage]\n\n try:\n if getattr(self, 'verbose', False):\n print('Computing the {0} similarity matrix...'.format(name))\n sim = construction_func[name](*args)\n if getattr(self, 'verbose', False):\n print('Done computing similarity matrix.')\n return sim\n except KeyError:\n raise NameError('Wrong sim name ' + name + '. Allowed values ' +\n 'are ' + ', '.join(construction_func.keys()) + '.')", "def recommend_items(self, seed_item_name: str, similarity_metric: str, weight: float) -> DataFrame:\n\n \n #compute weighted average between similarity values determined by collaborative filtering and those determined by content recommendation\n #(\"why is reset_index applied to the component reclists?\" needed to properly compute the weighted average of the content/collaborative similarities for each item)\n #raise value error if an appropriate similarity metric is not provided\n \n if similarity_metric == \"cos\":\n\n collabrecs: DataFrame = self.cosine(seed_item_name, self.item_matrix_training).sort_values(by = \"Title\", ascending = False)\n collabrecs.reset_index(drop=True, inplace=True)\n \n contentrecs: DataFrame = self.cosine(seed_item_name, self.latent_content_features).sort_values(by = \"Title\", ascending = False)\n contentrecs.reset_index(drop=True, inplace=True)\n\n weighted_average_recs: DataFrame = DataFrame({'Title': collabrecs[\"Title\"], 'Similarity': weight*collabrecs[\"Similarity\"] + (1 - weight)*contentrecs[\"Similarity\"], 'Ratings_count': collabrecs[\"Ratings_count\"]})\n\n return weighted_average_recs.sort_values(by = [\"Similarity\", \"Ratings_count\"], ascending = False) \n\n elif similarity_metric == \"corr\":\n\n collabrecs: DataFrame = self.corr(seed_item_name, self.item_matrix_training)\n collabrecs.reset_index(drop=True, inplace=True)\n \n contentrecs: DataFrame = self.corr(seed_item_name, self.latent_content_features)\n contentrecs.reset_index(drop=True, inplace=True)\n \n weighted_average_recs: DataFrame = DataFrame({'Title': collabrecs[\"Title\"], 'Similarity': weight*collabrecs[\"Similarity\"] + (1 - weight)*contentrecs[\"Similarity\"], 'Ratings_count': collabrecs[\"Ratings_count\"]})\n\n return weighted_average_recs.sort_values(by = [\"Similarity\", \"Ratings_count\"], ascending = False) \n\n else: raise ValueError(\"The similarity metric must be 'corr', for correlation, or 'cos', for cosine similarity.\")", "def transform(self, df):\n # CATEGORICAL FEATURES\n if self.categorical_columns:\n df.fillna({col: 'other' for col in self.categorical_columns}, inplace=True)\n df.replace('', {col: 'other' for col in self.categorical_columns}, inplace=True)\n print(self.aggregation_strategy)\n agg_df = df.groupby(self.aggregation_keys).aggregate(self.aggregation_strategy).reset_index()\n if self.vectorizor_compatibility:\n for col in self.categorical_columns:\n agg_df[col] = agg_df[col].map(lambda v: my_instance(v))\n agg_df.rename(columns={col: CATEGORICAL_FEATURE.format(name=col) for col in self.categorical_columns},\n inplace=True)\n return agg_df", "def add_sample_responses_to_matrix_builder(self, matrix_builder, agg_strategy, filter_sample_method,\n response_df, curr_item, mapping):\n filtered_response_df = self.FILTER_SAMPLES_METHODS[filter_sample_method].filter_samples(response_df)\n solution_list = self.AGGREGATORS[agg_strategy].get_aggregated_response(filtered_response_df)\n\n self._print(\"The aggregated response for item {} is {}\".format(curr_item,\n solution_list))\n\n row_indices = np.where(solution_list > 0)[0]\n matrix_builder.add_data_lists(mapping[row_indices], [curr_item] * len(row_indices), solution_list[row_indices])", "def process(df, return_metrics = True, pathway_generator_df = pd.DataFrame()):\r\n ngenes=[]\r\n explained_ratios =[]\r\n pathway_generator_df = read_reactome(reactome_file)\r\n pathways= pathway_generator_df.index\r\n pathway_id = pathway_generator_df[\"pathway_id\"]\r\n pathway_name = pathway_generator_df[\"pathway_name\"]\r\n for i in pathways: #loop the pathways to embed ngene and ratio info\r\n genes = pathway_generator_df.loc[i]\r\n test = [x in df.columns for x in genes.tolist()[0]] #gene number calculation\r\n ngene = sum(test)\r\n test = any(test)\r\n if test:\r\n sub_df = df.loc[:,genes.tolist()[0]].transpose()\r\n components, explained_ratio = analyze.my_pca(sub_df) #ratio calculation\r\n #key function from analyze file, can be modified when data updated.\r\n explained_ratio = np.array(explained_ratio)\r\n else:\r\n explained_ratio = float('nan')\r\n ngene = 0\r\n ngenes.append(ngene)\r\n explained_ratios = np.append(explained_ratios, explained_ratio)\r\n out_df = pd.DataFrame(columns = [\"pathways\",'pathway_id', 'pathway_name', \"explained_ratios\",\"ngenes\"]) #set up columns beforehands\r\n if return_metrics:\r\n for i in range(len(pathways)): #fill up the column values from each lists\r\n out_df = out_df.append({\"pathways\":pathways[i],'pathway_id':pathway_id[i], 'pathway_name': pathway_name[i], \"explained_ratios\":explained_ratios[i], \"ngenes\":ngenes[i]}, ignore_index=True)\r\n return out_df", "def calculate(self, uid, metadata):\n\n # Parse column parameters\n fields, params = self.params(metadata)\n\n # Different type of calculations\n # 1. Similarity query\n # 2. Extractor query (similarity + question)\n # 3. Question-answering on other field\n queries, extractions, questions = [], [], []\n\n # Retrieve indexed document text for article\n sections = self.sections(uid)\n texts = [text for _, text in sections]\n\n for name, query, question, snippet, _, _, matches, _ in params:\n if query.startswith(\"$\"):\n questions.append((name, query.replace(\"$\", \"\"), question, snippet))\n elif matches:\n queries.append((name, query, matches))\n else:\n extractions.append((name, query, question, snippet))\n\n # Run all extractor queries against document text\n results = self.extractor.query([query for _, query, _ in queries], texts)\n\n # Only execute embeddings queries for columns with matches set\n for x, (name, query, matches) in enumerate(queries):\n if results[x]:\n # Get topn text matches\n topn = [text for _, text, _ in results[x]][:matches]\n\n # Join results into String and return\n value = [\n self.resolve(params, sections, uid, name, value) for value in topn\n ]\n fields[name] = \"\\n\\n\".join(value) if value else \"\"\n else:\n fields[name] = \"\"\n\n # Add extraction fields\n if extractions:\n for name, value in self.extractor(extractions, texts):\n # Resolves the full value based on column parameters\n fields[name] = (\n self.resolve(params, sections, uid, name, value) if value else \"\"\n )\n\n # Add question fields\n names, qa, contexts, snippets = [], [], [], []\n for name, query, question, snippet in questions:\n names.append(name)\n qa.append(question)\n contexts.append(fields[query])\n snippets.append(snippet)\n\n for name, value in self.extractor.answers(\n names, qa, contexts, contexts, snippets\n ):\n # Resolves the full value based on column parameters\n fields[name] = (\n self.resolve(params, sections, uid, name, value) if value else \"\"\n )\n\n return fields", "def compute_similarities(self,dataset,j):\r\n pass", "def __transform__(self, data: pd.DataFrame) -> pd.DataFrame:\n\n for pipeline_object in self.pipeline:\n # inside the pipeline all transformation should happen in place to avoid unnecessary memory usage.\n # once a set of transformation is encapsulated in a pipeline the intermediate results are abstracted from.\n data: pd.DataFrame = pipeline_object.transform(data)\n\n return data", "def _match_models(self, frame):\n results = (model.compute(frame, self) for model in self._models.values())\n return MatchResults(sum((i for i in results if i), ()))", "def similarity(dataframe):\r\n main = dataframe\r\n \r\n dataframe = feature_selection(dataframe)\r\n train_size = round((len(dataframe)*0.9))\r\n train = dataframe[:train_size]\r\n test = dataframe[train_size:]\r\n \r\n test_value = test.iloc[np.random.randint(0,10),:]\r\n \r\n #compute cosine similarity\r\n neighbors = {}\r\n for i, r in train.iterrows():\r\n similarity = np.dot(test_value,r)/(np.linalg.norm(test_value)*np.linalg.norm(r))\r\n neighbors[i] = similarity\r\n \r\n #get similary movies in descending order\r\n neighbors = {k: v for k, v in sorted(neighbors.items(), key=lambda item: item[1], reverse=True)}\r\n \r\n test_final = pd.concat([test, main], axis=1, sort=False)\r\n train_final = pd.concat([train, main], axis=1, sort=False)\r\n \r\n test_movie = test_final.loc[test_value.name,['Title', 'Rated', 'Genre', 'imdbRating']]\r\n similar_movies = train_final.loc[list(neighbors.keys())[:5],['Title','Rated', 'Genre', 'Released', 'imdbRating']]\r\n \r\n return test_movie, similar_movies", "def _generate_similarity_matrix(self, traces_dir):\r\n cfg_generator = CFGenerator(traces_dir, self._kernel_mode, self._attribute_mode)\r\n cfg_generator.gen_CFG_wrapper()\r\n cfg_generator.cfg_similarity()\r\n return cfg_generator.get_similarity_matrix()", "def featurize_site(self, df: pd.DataFrame, aliases: Optional[Dict[str, str]] = None) -> pd.DataFrame:\n\n if not self.site_featurizers:\n return pd.DataFrame([])\n\n LOG.info(\"Applying site featurizers...\")\n\n df = df.copy()\n df.columns = [\"Input data|\" + x for x in df.columns]\n\n for fingerprint in self.site_featurizers:\n site_stats_fingerprint = SiteStatsFingerprint(\n fingerprint,\n stats=self.site_stats\n )\n df = site_stats_fingerprint.featurize_dataframe(\n df,\n \"Input data|structure\",\n multiindex=False,\n ignore_errors=True\n )\n\n fingerprint_name = fingerprint.__class__.__name__\n if aliases:\n fingerprint_name = aliases.get(fingerprint_name, fingerprint_name)\n if \"|\" not in fingerprint_name:\n fingerprint_name += \"|\"\n df.columns = [f\"{fingerprint_name}{x}\" if \"|\" not in x else x for x in df.columns]\n\n return df", "def MakeModels(df= None, filter_2D = False, set_normy = False, set_scaler = True, set_pca = True,\n algs = ['ridge', 'lasso', 'knn', 'svr', 'dt', 'rf', 'gp', 'xgb', 'net'], save_fig = True, show_fig = False,\n set_kernel = 'RBF', svr_opt_kern = False, set_search = 'GSV', set_varthresh = None, gp_alpha = None,\n gp_opt = None):\n # Raise error if df not specified\n if df is None:\n raise ValueError('Must specify a dataframe.')\n if isinstance(df, pd.DataFrame) == False:\n raise ValueError('Input df must be a dataframe.')\n\n # If filter_2D is True, will only use 2D descriptors\n if filter_2D == True:\n df = Filter_2D(df)\n\n # Remove infinite values\n df[df.columns] = df[df.columns].astype(float)\n df = df.fillna(0.0).astype(float)\n df = df.replace([np.inf, -np.inf], np.nan)\n df = df.dropna(axis=0, how='any')\n\n # Set X and y\n X = df.iloc[:, :-1]\n y = df.iloc[:, -1]\n\n # Train Test Split\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)\n\n #AddPipelinestoDict\n pipe_dict = AddPipeLinestoDict(set_normy= set_normy, set_pca = set_pca, set_kernel = set_kernel,\n svr_opt_kern= svr_opt_kern, set_scaler = set_scaler, algs = algs,\n set_varthresh = set_varthresh, gp_alpha= gp_alpha, gp_opt = gp_opt)\n\n for alg in pipe_dict.keys():\n if set_search == 'GSV':\n search = GridSearchCV(pipe_dict[alg]['pipe'], pipe_dict[alg]['params'], cv=5, n_jobs=-1)\n search.fit(X_train, y_train)\n pipe_dict[alg]['best_estimator'] = search.best_estimator_\n if set_search == 'RSV':\n search = RandomizedSearchCV(pipe_dict[alg]['pipe'], pipe_dict[alg]['params'], cv=5,\n n_jobs=-1, n_iter=500)\n search.fit(X_train, y_train)\n pipe_dict[alg]['best_estimator'] = search.best_estimator_\n\n # Print training scores and params\n print(\"{}'s Best score is: {}\".format(alg, search.best_score_))\n print(\"{}'s Best params are: {}\".format(alg, search.best_params_))\n\n # Make and print predictions and scores\n if alg == 'gp':\n y_pred, sigma = pipe_dict[alg]['best_estimator'].predict(X_test, return_std = True)\n\n else:\n y_pred = pipe_dict[alg]['best_estimator'].predict(X_test)\n\n r2 = r2_score(y_pred=y_pred, y_true=y_test)\n rmse = mean_squared_error(y_true=y_test, y_pred=y_pred, squared=False)\n print(\"{}'s R2 is: {}\".format(alg, r2))\n print(\"{}'s RMSE is: {}\".format(alg, rmse))\n\n # Plot prediction with error bars if GP\n if alg == 'gp':\n f1, ax = plt.subplots(figsize=(12, 12))\n plt.plot(y_test, y_pred, 'r.')\n plt.errorbar(y_test, y_pred, yerr=sigma, fmt='none', ecolor='blue', alpha=0.8)\n\n else:\n f1, ax = plt.subplots(figsize=(12, 12))\n plt.plot(y_test, y_pred, 'r.')\n\n # Plot line with ideal slope of 1\n x_vals = np.array(ax.get_xlim())\n y_vals = 0 + 1*x_vals\n plt.plot(x_vals, y_vals, \"r--\")\n\n # Add title string\n titlestr = []\n if filter_2D is True:\n title2D = '2D'\n titlestr.append(title2D)\n if set_pca == True:\n titlepca = 'PCA'\n titlestr.append(titlepca)\n if set_scaler == True:\n titlescaler = 'Scaled'\n titlestr.append(titlescaler)\n titlename = str(alg)\n titlestr.append(titlename)\n titley = y.name\n titlestr.append(titley)\n if 'gp' in algs:\n titlekern = set_kernel\n titlestr.append(titlekern)\n if set_normy is True:\n titlenormy = 'NormY'\n titlestr.append(titlenormy)\n if set_varthresh is not None:\n titlevt = 'VT_{}'.format(set_varthresh)\n titlestr.append(titlevt)\n\n # place a text box in upper left in axes coords\n props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n textstr = '\\n'.join(f'{k}: {v}' for k, v in search.best_params_.items())\n textstr2 = 'R2 is: %.3f' % r2 + '\\n' + 'RMSE is %.3f' % rmse + '\\n' + '\\n'.join(titlestr)\n ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14,\n verticalalignment='top', bbox=props)\n ax.text(0.05, 0.80, textstr2, transform=ax.transAxes, fontsize=14,\n verticalalignment='top', bbox=props)\n\n # Plot Figure with relative path to folder\n filedir = os.path.dirname(os.path.abspath(__file__))\n parentdir = os.path.dirname(filedir)\n plotdir = os.path.join(parentdir, 'Plots')\n titledir = os.path.join(plotdir, titley)\n if save_fig == True:\n if not os.path.exists(titledir):\n os.makedirs(titledir)\n plt.title(titlename)\n plt.xlabel('{} Experimental'.format(titley))\n plt.ylabel('{} Predicted'.format(titley))\n if save_fig == True:\n figfile = os.path.join(titledir, '_'.join(titlestr))\n plt.savefig('{}.png'.format(figfile))\n if show_fig == True:\n plt.show()\n plt.close()\n\n return {'pipe_dict': pipe_dict, 'X_test': X_test, 'y_test': y_test, 'y_pred': y_pred, 'df': df, 'titlestr': titlestr}", "def process(results):\n \n results = results.copy()\n results['hyperparameters'] = results['hyperparameters'].map(ast.literal_eval)\n \n # Sort with best values on top\n results = results.sort_values('score', ascending = False).reset_index(drop = True)\n \n # Create dataframe of hyperparameters\n hyp_df = pd.DataFrame(columns = list(results.loc[0, 'hyperparameters'].keys()))\n\n # Iterate through each set of hyperparameters that were evaluated\n for i, hyp in enumerate(results['hyperparameters']):\n hyp_df = hyp_df.append(pd.DataFrame(hyp, index = [0]), \n ignore_index = True, sort= True)\n \n # Put the iteration and score in the hyperparameter dataframe\n hyp_df['iteration'] = results['iteration']\n hyp_df['score'] = results['score']\n \n return hyp_df", "def create_similarity_matrix(df, i):\n brands_keywords = get_keywords_combination(\n brands=BRANDS,\n brands_synonyms=BRANDS_SYNONYMS,\n )\n\n # brands_keywords dictionary with reversed key, values\n brands_keywords_rev = {v: k for k, v in brands_keywords.items()}\n\n new_df = pd.DataFrame(index=BRANDS, columns=BRANDS)\n for name in df.columns:\n brand_1, brand_2 = brands_keywords_rev[name]\n new_df.loc[brand_1, brand_2] = df.loc[i, name] / 100\n new_df.loc[brand_2, brand_1] = df.loc[i, name] / 100\n return new_df.loc[(new_df!=0).any(axis=1)].fillna(1).astype(np.float64)", "def compute(self):\n self._check_if_fitted()\n return self.shap_vals_df", "def transform(self, result):\n if not hasattr(result.estimator, \"dataset\"):\n raise AttributeError(\n \"MetaResult was not generated by an Estimator with a `dataset` attribute. \"\n \"This may be because the Estimator was a pairwise Estimator. \"\n \"The Jackknife method does not currently work with pairwise Estimators.\"\n )\n dset = result.estimator.dataset\n # We need to copy the estimator because it will otherwise overwrite the original version\n # with one missing a study in its inputs.\n estimator = copy.deepcopy(result.estimator)\n original_masker = estimator.masker\n\n # Collect the thresholded cluster map\n if self.target_image in result.maps:\n target_img = result.get_map(self.target_image, return_type=\"image\")\n else:\n available_maps = [f\"'{m}'\" for m in result.maps.keys()]\n raise ValueError(\n f\"Target image ('{self.target_image}') not present in result. \"\n f\"Available maps in result are: {', '.join(available_maps)}.\"\n )\n\n if self.voxel_thresh:\n thresh_img = image.threshold_img(target_img, self.voxel_thresh)\n else:\n thresh_img = target_img\n\n thresh_arr = thresh_img.get_fdata()\n\n # CBMAs have \"stat\" maps, while most IBMAs have \"est\" maps.\n # Fisher's and Stouffer's only have \"z\" maps though.\n if \"est\" in result.maps:\n target_value_map = \"est\"\n elif \"stat\" in result.maps:\n target_value_map = \"stat\"\n else:\n target_value_map = \"z\"\n\n stat_values = result.get_map(target_value_map, return_type=\"array\")\n\n # Use study IDs in inputs_ instead of dataset, because we don't want to try fitting the\n # estimator to a study that might have been filtered out by the estimator's criteria.\n meta_ids = estimator.inputs_[\"id\"]\n rows = [\"Center of Mass\"] + list(meta_ids)\n\n # Let's label the clusters in the thresholded map so we can use it as a NiftiLabelsMasker\n # This won't work when the Estimator's masker isn't a NiftiMasker... :(\n conn = np.zeros((3, 3, 3), int)\n conn[:, :, 1] = 1\n conn[:, 1, :] = 1\n conn[1, :, :] = 1\n labeled_cluster_arr, n_clusters = ndimage.measurements.label(thresh_arr, conn)\n labeled_cluster_img = nib.Nifti1Image(\n labeled_cluster_arr,\n affine=target_img.affine,\n header=target_img.header,\n )\n\n if n_clusters == 0:\n LGR.warning(\"No clusters found\")\n contribution_table = pd.DataFrame(index=rows)\n return contribution_table, labeled_cluster_img\n\n # Identify center of mass for each cluster\n # This COM may fall outside the cluster, but it is a useful heuristic for identifying them\n cluster_ids = list(range(1, n_clusters + 1))\n cluster_coms = ndimage.center_of_mass(\n labeled_cluster_arr,\n labeled_cluster_arr,\n cluster_ids,\n )\n cluster_coms = np.array(cluster_coms)\n cluster_coms = vox2mm(cluster_coms, target_img.affine)\n\n cluster_com_strs = []\n for i_peak in range(len(cluster_ids)):\n x, y, z = cluster_coms[i_peak, :].astype(int)\n xyz_str = f\"({x}, {y}, {z})\"\n cluster_com_strs.append(xyz_str)\n\n # Mask using a labels masker, so that we can easily get the mean value for each cluster\n cluster_masker = input_data.NiftiLabelsMasker(labeled_cluster_img)\n cluster_masker.fit(labeled_cluster_img)\n\n # Create empty contribution table\n contribution_table = pd.DataFrame(index=rows, columns=cluster_ids)\n contribution_table.index.name = \"Cluster ID\"\n contribution_table.loc[\"Center of Mass\"] = cluster_com_strs\n\n # For the private method that does the work of the analysis, we have a lot of constant\n # parameters, and only one that varies (the ID of the study being removed),\n # so we use functools.partial.\n transform_method = partial(\n self._transform,\n all_ids=meta_ids,\n dset=dset,\n estimator=estimator,\n target_value_map=target_value_map,\n stat_values=stat_values,\n original_masker=original_masker,\n cluster_masker=cluster_masker,\n )\n with Pool(self.n_cores) as p:\n jackknife_results = list(tqdm(p.imap(transform_method, meta_ids), total=len(meta_ids)))\n\n # Add the results to the table\n for expid, stat_prop_values in jackknife_results:\n contribution_table.loc[expid] = stat_prop_values\n\n return contribution_table, labeled_cluster_img" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SkinCluster Data Class Initializer
def __init__(self, skinCluster=''): # Execute Super Class Initilizer super(SkinClusterData, self).__init__() # SkinCluster Custom Attributes self._data['attrValueList'].append('skinningMethod') self._data['attrValueList'].append('useComponents') self._data['attrValueList'].append('normalizeWeights') self._data['attrValueList'].append('deformUserNormals') # Build SkinCluster Data if skinCluster: self.buildData(skinCluster)
[ "def __init__(self):\n\n self.clusters = [ ]", "def buildData(self, skinCluster):\n # ==========\n # - Checks -\n # ==========\n\n # Check skinCluster\n self.verifySkinCluster(skinCluster)\n\n # Clear Data\n self.reset()\n\n # =======================\n # - Build Deformer Data -\n # =======================\n\n # Start Timer\n timer = cmds.timerX()\n\n self._data['name'] = skinCluster\n self._data['type'] = 'skinCluster'\n\n # Get affected geometry\n skinGeoShape = cmds.skinCluster(skinCluster, q=True, g=True)\n if len(skinGeoShape) > 1: raise Exception(\n 'SkinCluster \"' + skinCluster + '\" output is connected to multiple shapes!')\n if not skinGeoShape: raise Exception(\n 'Unable to determine affected geometry for skinCluster \"' + skinCluster + '\"!')\n skinGeo = cmds.listRelatives(skinGeoShape[0], p=True, pa=True)\n if not skinGeo: raise Exception('Unable to determine geometry transform for object \"' + skinGeoShape + '\"!')\n self._data['affectedGeometry'] = skinGeo\n skinGeo = skinGeo[0]\n\n skinClusterSet = glTools.utils.deformer.getDeformerSet(skinCluster)\n\n self._data[skinGeo] = {}\n self._data[skinGeo]['index'] = 0\n self._data[skinGeo]['geometryType'] = str(cmds.objectType(skinGeoShape))\n self._data[skinGeo]['membership'] = glTools.utils.deformer.getDeformerSetMemberIndices(skinCluster, skinGeo)\n self._data[skinGeo]['weights'] = []\n\n if self._data[skinGeo]['geometryType'] == 'mesh':\n self._data[skinGeo]['mesh'] = meshData.MeshData(skinGeo)\n\n # ========================\n # - Build Influence Data -\n # ========================\n\n # Get skinCluster influence list\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n if not influenceList: raise Exception(\n 'Unable to determine influence list for skinCluster \"' + skinCluster + '\"!')\n\n # Get Influence Wieghts\n weights = glTools.utils.skinCluster.getInfluenceWeightsAll(skinCluster)\n\n # For each influence\n for influence in influenceList:\n\n # Initialize influence data\n self._influenceData[influence] = {}\n\n # Get influence index\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n self._influenceData[influence]['index'] = infIndex\n\n # Get Influence BindPreMatrix\n bindPreMatrix = cmds.listConnections(skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', s=True, d=False,\n p=True)\n if bindPreMatrix:\n self._influenceData[influence]['bindPreMatrix'] = bindPreMatrix[0]\n else:\n self._influenceData[influence]['bindPreMatrix'] = ''\n\n # Get Influence Type (Transform/Geometry)\n infGeocmdsonn = cmds.listConnections(skinCluster + '.driverPoints[' + str(infIndex) + ']')\n if infGeocmdsonn:\n self._influenceData[influence]['type'] = 1\n self._influenceData[influence]['polySmooth'] = cmds.skinCluster(skinCluster, inf=influence, q=True,\n ps=True)\n self._influenceData[influence]['nurbsSamples'] = cmds.skinCluster(skinCluster, inf=influence, q=True,\n ns=True)\n else:\n self._influenceData[influence]['type'] = 0\n\n # Get Influence Weights\n pInd = glTools.utils.skinCluster.getInfluencePhysicalIndex(skinCluster, influence)\n self._influenceData[influence]['wt'] = weights[pInd]\n\n # =========================\n # - Custom Attribute Data -\n # =========================\n\n # Add Pre-Defined Custom Attributes\n self.getDeformerAttrValues()\n self.getDeformerAttrConnections()\n\n # =================\n # - Return Result -\n # =================\n\n skinTime = cmds.timerX(st=timer)\n print('SkinClusterData: Data build time for \"' + skinCluster + '\": ' + str(skinTime))", "def __init_kmeans(self, data):\n N, _ = data.shape\n\n # init kmeans:\n k_means = KMeans(init='k-means++', n_clusters=self.__K)\n k_means.fit(data)\n category = k_means.labels_\n\n # init posteriori:\n self.__posteriori = np.zeros((self.__K, N))\n # init mu:\n self.__mu = k_means.cluster_centers_\n # init covariances\n self.__cov = np.asarray(\n [np.cov(data[category == k], rowvar=False) for k in range(self.__K)]\n )\n # init priori:\n value_counts = pd.Series(category).value_counts()\n self.__priori = np.asarray(\n [value_counts[k]/N for k in range(self.__K)]\n ).reshape((self.__K, 1))", "def __init__(self, name, cluster_dict):\n self.name = str(name)\n self.clusters = [Cluster(k, v[\"networks\"], v[\"security_level\"])\n for k, v in cluster_dict.items()]", "def __init__(self, dataset, minibatch, num_workers, size, rank):\n if dataset not in datasets_list:\n print(\"Existing datasets are: \", datasets_list)\n raise\n self.dataset = datasets_list.index(dataset)\n self.batch = minibatch * num_workers\n self.num_workers = num_workers\n self.num_ps = size - num_workers\n self.rank = rank", "def _init_centroids(self,data):\n\n\n centroids = random.sample(data,self.num_clust)\n return centroids", "def __init__(self, n_clusters = 2, max_iter = 300, tol = 0.001):\r\n self.K = n_clusters\r\n self.max_iter = max_iter\r\n self.tol = tol\r\n logging.info(\"KMeans values initialized with n_clusters = {0}, max_iter = {1}, tol = {2}\".format(n_clusters, max_iter, tol))", "def __init__(self, inputdata):\n #instance used data loader to assign data attributes\n self.data = self.data_loader(inputdata)\n self.shape = self.data.shape\n self.rows, self.cols = self.shape\n #attribute height/width defined as index of shape attribute\n self.height= self.shape[1]\n self.width= self.shape[0]", "def set_cluster(self, data):\n cluster = Cluster(data['name'])\n for host in data['hosts']:\n cluster.add_host(**host)\n self._cluster = cluster", "def _initialize_clusters(self):\n max_cap = self.config.capacity_cst\n total_demand = self.manager_stops.demand\n list_number_cluster = [int(total_demand/(i * max_cap)) for i in [0.75,1,1.25]]\n # list_number_cluster = [int(total_demand/(k * max_cap)) for k in [0.4]]\n\n Kmean_basic = basic_K_mean.basicKMeans(manager_cluster=self.manager_cluster,manager_stops=self.manager_stops)\n for k in list_number_cluster:\n Kmean_basic.run_K_mean(list(self.manager_stops.keys()),k)", "def generate_clusters(self):\n\n self.cluster_labels = None", "def __init__(self):\n self.dataNames = ['distance']\n self.initializeData()", "def __init__(self, dataset, class_value):\n self.class_value = class_value\n data = dataset[dataset[:,-1]==class_value]\n self.mean = np.array([np.mean(data[:,c]) for c in range(data.shape[1] - 1)])\n self.cov = np.cov([data[:, i] for i in range(data.shape[1] - 1)])\n self.prior = data.shape[0] / dataset.shape[0]", "def __init__(self, data, dims, legends=None):\n self.data = data\n self.num_cells = float(data.shape[0])\n self.dims = dims\n self.legends = legends", "def rebuild(self):\n # ==========\n # - Checks -\n # ==========\n\n # Check geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data for a different geometry!')\n\n # =======================\n # - Rebuild SkinCluster -\n # =======================\n\n # Start timer\n timer = cmds.timerX()\n\n # Initialize Temp Joint\n tempJnt = ''\n\n # Unlock Influences\n influenceList = self._influenceData.keys()\n for influence in influenceList:\n if cmds.objExists(influence + '.liw'):\n if cmds.getAttr(influence + '.liw', l=True):\n try:\n cmds.setAttr(influence + '.liw', l=False)\n except:\n print(\n 'Error unlocking attribute \"' + influence + '.liw\"! This could problems when rebuilding the skinCluster...')\n if cmds.getAttr(influence + '.liw'):\n try:\n cmds.setAttr(influence + '.liw', False)\n except:\n print(\n 'Error setting attribute \"' + influence + '.liw\" to False! This could problems when rebuilding the skinCluster...')\n\n # Check SkinCluster\n skinCluster = self._data['name']\n if not cmds.objExists(skinCluster):\n\n # Get Transform Influences\n jointList = [inf for inf in influenceList if not self._influenceData[inf]['type']]\n\n # Check Transform Influences\n if not jointList:\n\n # Create Temporary Bind Joint\n cmds.select(cl=1)\n tempJnt = cmds.joint(n=skinCluster + '_tempJoint')\n print(\n 'No transform influences specified for skinCluster \"' + skinCluster + '\"! Creating temporary bind joint \"' + tempJnt + '\"!')\n jointList = [tempJnt]\n\n else:\n\n # Get Surface Influences\n influenceList = [inf for inf in influenceList if self._influenceData[inf]['type']]\n\n # Create skinCluster\n skinCluster = cmds.skinCluster(jointList, skinGeo, tsb=True, n=skinCluster)[0]\n\n else:\n\n # Check Existing SkinCluster\n affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster)\n if affectedGeo.keys()[0] != skinGeo:\n raise Exception(\n 'SkinCluster \"' + skinCluster + '\" already exists, but is not connected to the expeced geometry \"' + skinGeo + '\"!')\n\n # Add skinCluster influences\n for influence in influenceList:\n\n # Check influence\n if not cmds.objExists(influence):\n raise Exception(\n 'Influence \"' + influence + '\" does not exist! Use remapInfluence() to apply data to a different influence!')\n\n # Check existing influence connection\n if not cmds.skinCluster(skinCluster, q=True, inf=True).count(influence):\n\n # Add influence\n if self._influenceData[influence]['type']:\n # Geometry\n polySmooth = self._influenceData[influence]['polySmooth']\n nurbsSamples = self._influenceData[influence]['nurbsSamples']\n cmds.skinCluster(skinCluster, e=True, ai=influence, ug=True, ps=polySmooth, ns=nurbsSamples, wt=0.0,\n lockWeights=True)\n\n else:\n # Transform\n cmds.skinCluster(skinCluster, e=True, ai=influence, wt=0.0, lockWeights=True)\n\n # Bind Pre Matrix\n if self._influenceData[influence]['bindPreMatrix']:\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n cmds.connectAttr(self._influenceData[influence]['bindPreMatrix'],\n skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', f=True)\n\n # Load skinCluster weights\n cmds.setAttr(skinCluster + '.normalizeWeights', 0)\n glTools.utils.skinCluster.clearWeights(skinGeo)\n self.loadWeights()\n cmds.setAttr(skinCluster + '.normalizeWeights', 1)\n\n # Restore Custom Attribute Values and Connections\n self.setDeformerAttrValues()\n self.setDeformerAttrConnections()\n\n # Clear Selection\n cmds.select(cl=True)\n\n # =================\n # - Return Result -\n # =================\n\n # Print Timed Result\n totalTime = cmds.timerX(st=timer)\n print('SkinClusterData: Rebuild time for skinCluster \"' + skinCluster + '\": ' + str(totalTime))\n\n return skinCluster", "def setWeights(self, componentList=[]):\n print('!!! - DEPRICATED: skinClusterData.setWeights()! Use loadWeights() method instead - !!!')\n\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Component List\n if not componentList: componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n indexList = OpenMaya.MIntArray()\n componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n componentFn.getElements(indexList)\n componentIndexList = list(indexList)\n\n # ===========================\n # - Set SkinCluster Weights -\n # ===========================\n\n # Build influence index array\n infIndexArray = OpenMaya.MIntArray()\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n [infIndexArray.append(i) for i in range(len(influenceList))]\n\n # Build master weight array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, False, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return influenceList", "def __init__(self):\n\n auth = PlainTextAuthProvider(username=\"cassandra\", password=\"password\")\n\n self.cluster = Cluster(['cassandra'], port=9042,\n protocol_version=3, auth_provider=auth)\n LOGGER.info(\"Connecting to cluster\")\n self.connection = self.cluster.connect()\n LOGGER.info(\"Connected to cluster\")\n\n LOGGER.info(\"Setting up keyspace: %s\" % KEYSPACE)\n self.connection.execute(\"\"\"CREATE KEYSPACE IF NOT EXISTS %s\n WITH replication = { 'class': 'SimpleStrategy',\n 'replication_factor': '1' }\n \"\"\" % KEYSPACE\n )\n\n self.connection.set_keyspace(KEYSPACE)\n LOGGER.info(\"Instantiating table stock-service\")\n self.connection.execute(\"\"\"CREATE TABLE IF NOT EXISTS stock (\n itemid uuid,\n price decimal,\n PRIMARY KEY (itemid))\n \"\"\"\n )\n self.connection.execute(\"\"\"CREATE TABLE IF NOT EXISTS stock_counts (\n itemid uuid,\n quantity counter,\n PRIMARY KEY (itemid))\n \"\"\"\n )", "def _initialization(self):\n # Clear the clusters\n self._clear_clusters()\n\n # Initialize the clusters\n self._init_clusters()\n\n # Assign each point to its closest cluster\n self._assign_point_to_closest_cluster()\n\n # Reassign the center of the clusters\n self._update_cluster_center()", "def init_cluster_regular(rows,columns,ki,img,bands):\n\n N = rows * columns\n \n #Setting up SLIC \n S = int((N/ki)**0.5) \n base = int(S/2)\n \n # Recompute k\n k = numpy.floor(rows/base)*numpy.floor(columns/base);\n\n # Allocate memory and initialise clusters, labels and distances.\n C = numpy.zeros([int(k),bands+3]) # Cluster centre data 1:times is mean on each band of series\n # times+1 and times+2 is row, col of centre, times+3 is No of pixels\n l = -numpy.ones([rows,columns]) # Matrix labels.\n d = numpy.full([rows,columns], numpy.inf) # Pixel distance matrix from cluster centres.\n\n vSpacing = int(numpy.floor(rows / ki**0.5))\n hSpacing = int(numpy.floor(columns / ki**0.5))\n\n kk=0\n\n # Initialise grid\n for x in range(base, rows, vSpacing):\n for y in range(base, columns, hSpacing):\n cc = int(numpy.floor(y)); rr = int(numpy.floor(x))\n ts = img[:,int(x),int(y)]\n st = numpy.append(ts,[int(x),int(y),0])\n C[kk, :] = st\n kk = kk+1\n \n w = S/2\n \n return C,int(S),l,d,int(kk)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build skinCluster data and store as class object dictionary entries
def buildData(self, skinCluster): # ========== # - Checks - # ========== # Check skinCluster self.verifySkinCluster(skinCluster) # Clear Data self.reset() # ======================= # - Build Deformer Data - # ======================= # Start Timer timer = cmds.timerX() self._data['name'] = skinCluster self._data['type'] = 'skinCluster' # Get affected geometry skinGeoShape = cmds.skinCluster(skinCluster, q=True, g=True) if len(skinGeoShape) > 1: raise Exception( 'SkinCluster "' + skinCluster + '" output is connected to multiple shapes!') if not skinGeoShape: raise Exception( 'Unable to determine affected geometry for skinCluster "' + skinCluster + '"!') skinGeo = cmds.listRelatives(skinGeoShape[0], p=True, pa=True) if not skinGeo: raise Exception('Unable to determine geometry transform for object "' + skinGeoShape + '"!') self._data['affectedGeometry'] = skinGeo skinGeo = skinGeo[0] skinClusterSet = glTools.utils.deformer.getDeformerSet(skinCluster) self._data[skinGeo] = {} self._data[skinGeo]['index'] = 0 self._data[skinGeo]['geometryType'] = str(cmds.objectType(skinGeoShape)) self._data[skinGeo]['membership'] = glTools.utils.deformer.getDeformerSetMemberIndices(skinCluster, skinGeo) self._data[skinGeo]['weights'] = [] if self._data[skinGeo]['geometryType'] == 'mesh': self._data[skinGeo]['mesh'] = meshData.MeshData(skinGeo) # ======================== # - Build Influence Data - # ======================== # Get skinCluster influence list influenceList = cmds.skinCluster(skinCluster, q=True, inf=True) if not influenceList: raise Exception( 'Unable to determine influence list for skinCluster "' + skinCluster + '"!') # Get Influence Wieghts weights = glTools.utils.skinCluster.getInfluenceWeightsAll(skinCluster) # For each influence for influence in influenceList: # Initialize influence data self._influenceData[influence] = {} # Get influence index infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence) self._influenceData[influence]['index'] = infIndex # Get Influence BindPreMatrix bindPreMatrix = cmds.listConnections(skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', s=True, d=False, p=True) if bindPreMatrix: self._influenceData[influence]['bindPreMatrix'] = bindPreMatrix[0] else: self._influenceData[influence]['bindPreMatrix'] = '' # Get Influence Type (Transform/Geometry) infGeocmdsonn = cmds.listConnections(skinCluster + '.driverPoints[' + str(infIndex) + ']') if infGeocmdsonn: self._influenceData[influence]['type'] = 1 self._influenceData[influence]['polySmooth'] = cmds.skinCluster(skinCluster, inf=influence, q=True, ps=True) self._influenceData[influence]['nurbsSamples'] = cmds.skinCluster(skinCluster, inf=influence, q=True, ns=True) else: self._influenceData[influence]['type'] = 0 # Get Influence Weights pInd = glTools.utils.skinCluster.getInfluencePhysicalIndex(skinCluster, influence) self._influenceData[influence]['wt'] = weights[pInd] # ========================= # - Custom Attribute Data - # ========================= # Add Pre-Defined Custom Attributes self.getDeformerAttrValues() self.getDeformerAttrConnections() # ================= # - Return Result - # ================= skinTime = cmds.timerX(st=timer) print('SkinClusterData: Data build time for "' + skinCluster + '": ' + str(skinTime))
[ "def __init__(self, skinCluster=''):\n # Execute Super Class Initilizer\n super(SkinClusterData, self).__init__()\n\n # SkinCluster Custom Attributes\n self._data['attrValueList'].append('skinningMethod')\n self._data['attrValueList'].append('useComponents')\n self._data['attrValueList'].append('normalizeWeights')\n self._data['attrValueList'].append('deformUserNormals')\n\n # Build SkinCluster Data\n if skinCluster: self.buildData(skinCluster)", "def rebuild(self):\n # ==========\n # - Checks -\n # ==========\n\n # Check geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data for a different geometry!')\n\n # =======================\n # - Rebuild SkinCluster -\n # =======================\n\n # Start timer\n timer = cmds.timerX()\n\n # Initialize Temp Joint\n tempJnt = ''\n\n # Unlock Influences\n influenceList = self._influenceData.keys()\n for influence in influenceList:\n if cmds.objExists(influence + '.liw'):\n if cmds.getAttr(influence + '.liw', l=True):\n try:\n cmds.setAttr(influence + '.liw', l=False)\n except:\n print(\n 'Error unlocking attribute \"' + influence + '.liw\"! This could problems when rebuilding the skinCluster...')\n if cmds.getAttr(influence + '.liw'):\n try:\n cmds.setAttr(influence + '.liw', False)\n except:\n print(\n 'Error setting attribute \"' + influence + '.liw\" to False! This could problems when rebuilding the skinCluster...')\n\n # Check SkinCluster\n skinCluster = self._data['name']\n if not cmds.objExists(skinCluster):\n\n # Get Transform Influences\n jointList = [inf for inf in influenceList if not self._influenceData[inf]['type']]\n\n # Check Transform Influences\n if not jointList:\n\n # Create Temporary Bind Joint\n cmds.select(cl=1)\n tempJnt = cmds.joint(n=skinCluster + '_tempJoint')\n print(\n 'No transform influences specified for skinCluster \"' + skinCluster + '\"! Creating temporary bind joint \"' + tempJnt + '\"!')\n jointList = [tempJnt]\n\n else:\n\n # Get Surface Influences\n influenceList = [inf for inf in influenceList if self._influenceData[inf]['type']]\n\n # Create skinCluster\n skinCluster = cmds.skinCluster(jointList, skinGeo, tsb=True, n=skinCluster)[0]\n\n else:\n\n # Check Existing SkinCluster\n affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster)\n if affectedGeo.keys()[0] != skinGeo:\n raise Exception(\n 'SkinCluster \"' + skinCluster + '\" already exists, but is not connected to the expeced geometry \"' + skinGeo + '\"!')\n\n # Add skinCluster influences\n for influence in influenceList:\n\n # Check influence\n if not cmds.objExists(influence):\n raise Exception(\n 'Influence \"' + influence + '\" does not exist! Use remapInfluence() to apply data to a different influence!')\n\n # Check existing influence connection\n if not cmds.skinCluster(skinCluster, q=True, inf=True).count(influence):\n\n # Add influence\n if self._influenceData[influence]['type']:\n # Geometry\n polySmooth = self._influenceData[influence]['polySmooth']\n nurbsSamples = self._influenceData[influence]['nurbsSamples']\n cmds.skinCluster(skinCluster, e=True, ai=influence, ug=True, ps=polySmooth, ns=nurbsSamples, wt=0.0,\n lockWeights=True)\n\n else:\n # Transform\n cmds.skinCluster(skinCluster, e=True, ai=influence, wt=0.0, lockWeights=True)\n\n # Bind Pre Matrix\n if self._influenceData[influence]['bindPreMatrix']:\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n cmds.connectAttr(self._influenceData[influence]['bindPreMatrix'],\n skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', f=True)\n\n # Load skinCluster weights\n cmds.setAttr(skinCluster + '.normalizeWeights', 0)\n glTools.utils.skinCluster.clearWeights(skinGeo)\n self.loadWeights()\n cmds.setAttr(skinCluster + '.normalizeWeights', 1)\n\n # Restore Custom Attribute Values and Connections\n self.setDeformerAttrValues()\n self.setDeformerAttrConnections()\n\n # Clear Selection\n cmds.select(cl=True)\n\n # =================\n # - Return Result -\n # =================\n\n # Print Timed Result\n totalTime = cmds.timerX(st=timer)\n print('SkinClusterData: Rebuild time for skinCluster \"' + skinCluster + '\": ' + str(totalTime))\n\n return skinCluster", "def __init__(self):\n\n self.clusters = [ ]", "def _generate_ids(self):\n clusterid = 0\n\n cluster2class = {}\n class2cluster = {}\n clusters = {}\n\n for (name,members) in self._clusters:\n classes = [self._class2idx[m] for m in members]\n for c in classes:\n class2cluster[c] = clusterid\n # print(c, clusterid)\n cluster2class[clusterid] = classes\n clusters[clusterid] = (name, classes)\n clusterid += 1\n self._clusters_map = clusters\n\n return cluster2class, class2cluster, clusterid-1", "def __init__(self, name, cluster_dict):\n self.name = str(name)\n self.clusters = [Cluster(k, v[\"networks\"], v[\"security_level\"])\n for k, v in cluster_dict.items()]", "def load(self):\n import os\n\n import pandas as pd\n\n dtype = {'names': ('cluster_id', 'group'), 'formats': ('i4', 'S10')}\n # One of these (cluster_groups.csv or cluster_group.tsv) is from\n # kilosort and the other from kilosort2\n # and is updated by the user when doing cluster assignment in phy\n # See comments above this class definition for a bit more info\n if fileExists(self.fname_root, \"cluster_groups.csv\"):\n self.cluster_id, self.group = np.loadtxt(\n os.path.join(self.fname_root, \"cluster_groups.csv\"),\n unpack=True,\n skiprows=1,\n dtype=dtype\n )\n if fileExists(self.fname_root, \"cluster_group.tsv\"):\n self.cluster_id, self.group = np.loadtxt(\n os.path.join(self.fname_root, \"cluster_group.tsv\"),\n unpack=True,\n skiprows=1,\n dtype=dtype,\n )\n\n \"\"\"\n Output some information to the user if self.cluster_id is still None\n it implies that data has not been sorted / curated\n \"\"\"\n # if self.cluster_id is None:\n # print(f\"Searching {os.path.join(self.fname_root)} and...\")\n # warnings.warn(\"No cluster_groups.tsv or cluster_group.csv file\n # was found.\\\n # Have you manually curated the data (e.g with phy?\")\n\n # HWPD 20200527\n # load cluster_info file and add X co-ordinate to it\n if fileExists(self.fname_root, \"cluster_info.tsv\"):\n self.cluster_info = pd.read_csv(\n os.path.join(self.fname_root, \"cluster_info.tsv\"), sep=\"\\t\"\n )\n if fileExists(\n self.fname_root, \"channel_positions.npy\") and fileExists(\n self.fname_root, \"channel_map.npy\"\n ):\n chXZ = np.load(\n os.path.join(self.fname_root, \"channel_positions.npy\"))\n chMap = np.load(\n os.path.join(self.fname_root, \"channel_map.npy\"))\n chID = np.asarray(\n [np.argmax(chMap == x) for x in\n self.cluster_info.ch.values]\n )\n self.cluster_info[\"chanX\"] = chXZ[chID, 0]\n self.cluster_info[\"chanY\"] = chXZ[chID, 1]\n\n dtype = {\"names\": (\"cluster_id\", \"KSLabel\"), \"formats\": (\"i4\", \"S10\")}\n # 'Raw' labels from a kilosort session\n if fileExists(self.fname_root, \"cluster_KSLabel.tsv\"):\n self.ks_cluster_id, self.ks_group = np.loadtxt(\n os.path.join(self.fname_root, \"cluster_KSLabel.tsv\"),\n unpack=True,\n skiprows=1,\n dtype=dtype,\n )\n if fileExists(self.fname_root, \"spike_clusters.npy\"):\n self.spk_clusters = np.squeeze(\n np.load(os.path.join(self.fname_root, \"spike_clusters.npy\"))\n )\n if fileExists(self.fname_root, \"spike_times.npy\"):\n self.spk_times = np.squeeze(\n np.load(os.path.join(self.fname_root, \"spike_times.npy\"))\n )\n return True\n warnings.warn(\n \"No spike times or clusters were found \\\n (spike_times.npy or spike_clusters.npy).\\\n You should run KiloSort\"\n )\n return False", "def collate_cluster_data(ensembles_data):\n\n clusters = {} # Loop through all ensemble data objects and build up a data tree\n cluster_method = None\n cluster_score_type = None\n truncation_method = None\n percent_truncation = None\n side_chain_treatments = []\n for e in ensembles_data:\n if not cluster_method:\n cluster_method = e['cluster_method']\n cluster_score_type = e['cluster_score_type']\n percent_truncation = e['truncation_percent']\n truncation_method = e['truncation_method']\n # num_clusters = e['num_clusters']\n cnum = e['cluster_num']\n if cnum not in clusters:\n clusters[cnum] = {}\n clusters[cnum]['cluster_centroid'] = e['cluster_centroid']\n clusters[cnum]['cluster_num_models'] = e['cluster_num_models']\n clusters[cnum]['tlevels'] = {}\n tlvl = e['truncation_level']\n if tlvl not in clusters[cnum]['tlevels']:\n clusters[cnum]['tlevels'][tlvl] = {}\n clusters[cnum]['tlevels'][tlvl]['truncation_variance'] = e['truncation_variance']\n clusters[cnum]['tlevels'][tlvl]['num_residues'] = e['num_residues']\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'] = {}\n srt = e['subcluster_radius_threshold']\n if srt not in clusters[cnum]['tlevels'][tlvl]['radius_thresholds']:\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt] = {}\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['num_models'] = e['subcluster_num_models']\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'] = {}\n sct = e['side_chain_treatment']\n if sct not in side_chain_treatments:\n side_chain_treatments.append(sct)\n if sct not in clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct']:\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'][sct] = {}\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'][sct]['name'] = e['name']\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'][sct]['num_atoms'] = e['ensemble_num_atoms']\n\n return {\n 'clusters': clusters,\n 'cluster_method': cluster_method,\n 'cluster_score_type': cluster_score_type,\n 'truncation_method': truncation_method,\n 'percent_truncation': percent_truncation,\n 'side_chain_treatments': side_chain_treatments,\n }", "def generate_clusters(self):\n\n self.cluster_labels = None", "def load_classes(self):\n # load class names (name -> label)\n categories = self.coco.loadCats(self.coco.getCatIds())\n categories.sort(key=lambda x: x['id'])\n\n self.classes = {}\n self.coco_labels = {}\n self.coco_labels_inverse = {}\n for c in categories:\n self.coco_labels[len(self.classes)] = c['id']\n self.coco_labels_inverse[c['id']] = len(self.classes)\n self.classes[c['name']] = len(self.classes)\n\n # also load the reverse (label -> name)\n self.labels = {}\n for key, value in self.classes.items():\n self.labels[value] = key\n print('GOT labels: {}'.format(self.labels))", "def execute(self):\n LOG.debug(\"Building latest Nova cluster data model\")\n\n model = model_root.ModelRoot()\n mem = element.Resource(element.ResourceType.memory)\n num_cores = element.Resource(element.ResourceType.cpu_cores)\n disk = element.Resource(element.ResourceType.disk)\n disk_capacity = element.Resource(element.ResourceType.disk_capacity)\n model.create_resource(mem)\n model.create_resource(num_cores)\n model.create_resource(disk)\n model.create_resource(disk_capacity)\n\n flavor_cache = {}\n nodes = self.wrapper.get_compute_node_list()\n for n in nodes:\n service = self.wrapper.nova.services.find(id=n.service['id'])\n # create node in cluster_model_collector\n node = element.ComputeNode(n.id)\n node.uuid = service.host\n node.hostname = n.hypervisor_hostname\n # set capacity\n mem.set_capacity(node, n.memory_mb)\n disk.set_capacity(node, n.free_disk_gb)\n disk_capacity.set_capacity(node, n.local_gb)\n num_cores.set_capacity(node, n.vcpus)\n node.state = n.state\n node.status = n.status\n model.add_node(node)\n instances = self.wrapper.get_instances_by_node(str(service.host))\n for v in instances:\n # create VM in cluster_model_collector\n instance = element.Instance()\n instance.uuid = v.id\n # nova/nova/compute/instance_states.py\n instance.state = getattr(v, 'OS-EXT-STS:vm_state')\n\n # set capacity\n self.wrapper.get_flavor_instance(v, flavor_cache)\n mem.set_capacity(instance, v.flavor['ram'])\n # FIXME: update all strategies to use disk_capacity\n # for instances instead of disk\n disk.set_capacity(instance, v.flavor['disk'])\n disk_capacity.set_capacity(instance, v.flavor['disk'])\n num_cores.set_capacity(instance, v.flavor['vcpus'])\n\n model.map_instance(instance, node)\n\n return model", "def build_cluster(self):\n self.redshift_client_create()\n self.iam_client_create()\n self.ec2_client_create()\n self.create_iam_role()\n # self.update_iam_config()\n self.create_redshift_cluster()\n # uses created redshift cluster's vpc_id\n self.open_tcp_port()", "def build_clusters(bins):\n clusters = []\n\n for num, clustered_bins in cluster_bins(bins).items():\n if len(clustered_bins) >= 3:\n cluster = Cluster(clustered_bins)\n clusters.append(cluster)\n print(cluster)\n\n return clusters", "def compose_cluster_map(self,filedir):\r\n self.cluster_map = np.zeros((SAT_SIZE,SAT_SIZE),dtype='uint16')\r\n #Search the directory for all matching npy files:\r\n file_list = os.listdir(filedir)\r\n for file in file_list:\r\n file_parts = file.split('_')\r\n if len(file_parts)==3 and file_parts[2]=='clusters.npy':\r\n x0 = int(file_parts[0])\r\n y0 = int(file_parts[1])\r\n x1 = x0 + 2*VIEW_SIZE\r\n y1 = y0 + 2*VIEW_SIZE\r\n cluster_area = np.load(filedir+file).reshape(2*VIEW_SIZE,2*VIEW_SIZE)\r\n self.cluster_map[y0:y1,x0:x1] = cluster_area\r\n np.save(filedir+'cluster_map.npy',self.cluster_map)", "def __cluster__(self,markings,user_ids,tools,reduced_markings,image_dimensions):\n assert len(markings) == len(user_ids)\n assert len(markings) == len(reduced_markings)\n assert isinstance(user_ids,tuple)\n user_ids = list(user_ids)\n start = time.time()\n\n if len(user_ids) == len(set(user_ids)):\n # all of the markings are from different users => so only one cluster\n # todo implement\n result = {\"users\":user_ids,\"cluster members\":markings,\"tools\":tools,\"num users\":len(user_ids)}\n result[\"center\"] = [np.median(axis) for axis in zip(*markings)]\n return [result],0\n\n all_users = set()\n\n # cluster based n the reduced markings, but list the clusters based on their original values\n\n # this converts stuff into panda format - probably a better way to do this but the labels do seem\n # necessary\n labels = [str(i) for i in reduced_markings]\n param_labels = [str(i) for i in range(len(reduced_markings[0]))]\n\n df = pd.DataFrame(np.array(reduced_markings), columns=param_labels, index=labels)\n row_dist = pd.DataFrame(squareform(pdist(df, metric='euclidean')), columns=labels, index=labels)\n # use ward metric to do the actual clustering\n row_clusters = linkage(row_dist, method='ward')\n\n # use the results to build a tree representation\n # nodes = [LeafNode(pt,ii,user=user) for ii,(user,pt) in enumerate(zip(user_ids,markings))]\n results = [{\"users\":[u],\"cluster members\":[p],\"tools\":[t],\"num users\":1} for u,p,t in zip(user_ids,markings,tools)]\n\n # read through the results\n # each row gives a cluster/node to merge\n # if one any two clusters have a user in common - don't merge them - and represent this by a None cluster\n # if trying to merge with a None cluster - this gives a None cluster as well\n for merge in row_clusters:\n rchild_index = int(merge[0])\n lchild_index = int(merge[1])\n\n rnode = results[rchild_index]\n lnode = results[lchild_index]\n\n # use \"center\" being in a dict to indicate that a node shouldn't be merged any more\n # use None to indicate that a \"child\" of the current node was a \"terminal\" node\n # if either node/cluster is None, we have already encountered overlapping users\n # if both are already terminal - just append None\n if ((rnode is None) or (\"center\" in rnode)) and ((lnode is None) or (\"center\" in lnode)):\n results.append(None)\n # maybe just the rnode was is already done - in which case \"finish\" the lnode\n elif (rnode is None) or (\"center\" in rnode):\n lnode[\"center\"] = [np.median(axis) for axis in zip(*lnode[\"cluster members\"])]\n results.append(None)\n # maybe just the lnode is done:\n elif (lnode is None) or (\"center\" in lnode):\n rnode[\"center\"] = [np.median(axis) for axis in zip(*rnode[\"cluster members\"])]\n results.append(None)\n else:\n # check if we should merge - only if there is no overlap\n # otherwise \"cap\" or terminate both nodes\n intersection = [u for u in rnode[\"users\"] if u in lnode[\"users\"]]\n\n # if there are users in common, add to the end clusters list (which consists of cluster centers\n # the points in each cluster and the list of users)\n if intersection != []:\n rnode[\"center\"] = [np.median(axis) for axis in zip(*rnode[\"cluster members\"])]\n lnode[\"center\"] = [np.median(axis) for axis in zip(*lnode[\"cluster members\"])]\n results.append(None)\n else:\n # else just merge\n merged_users = rnode[\"users\"]\n merged_points = rnode[\"cluster members\"]\n merged_tools = rnode[\"tools\"]\n # add in the values from the second node\n merged_users.extend(lnode[\"users\"])\n merged_points.extend(lnode[\"cluster members\"])\n merged_tools.extend(lnode[\"tools\"])\n num_users = rnode[\"num users\"] + lnode[\"num users\"]\n results.append({\"users\":merged_users,\"cluster members\":merged_points,\"tools\":merged_tools,\"num users\":num_users})\n\n # go and remove all non terminal nodes from the results\n for i in range(len(results)-1,-1,-1):\n # if None => corresponds to being above a terminal node\n # or center not in results => corresponds to being beneath a terminal node\n # in both cases does not mean immediately above or below\n if (results[i] is None) or (\"center\" not in results[i]):\n results.pop(i)\n\n # todo - this is just for debugging\n for j in results:\n assert \"num users\" in j\n\n end = time.time()\n return results,end-start", "def parse_cluster_composition(self,param_name,param_range,unique_paths,input_params):\n\n count = 0;\n# cluster_distribution = {};\n for path in unique_paths:\n traj_path = path.replace('Observables','Trajectory');\n p =sorted(os.listdir(traj_path));\n self.cluster_distribution[traj_path] = {};\n if p[0] == 'Movies':\n del(p[0])\n if p[-1] == 'Movies':\n del(p[-1])\n for file in p:\n self.cluster_distribution[traj_path][file]= {};\n gsd_file =traj_path + file;\n analysis_file = gsd_file.replace('Trajectory','Analysis');\n analysis_file = analysis_file.replace('gsd','text');\n with open(analysis_file,'r') as f:\n self.cluster_distribution[traj_path][file] = json.load(f);\n\n count = count+1;\n self.param_range = param_range;\n self.param_name = param_name;\n self.unique_paths = unique_paths;\n self.input_params = input_params;\n return(self.cluster_distribution)", "def create_splits(self):\n\n \n\n \n filepaths = collections.defaultdict(list)\n \n for i,row in data.iterrows():\n filepaths[row[info['category_column_name']]].append(row[info['image_column_name']]) \n \n keys = list(filepaths.keys())\n\n num_classes = len(keys)\n\n class_names = keys\n\n\n logging.debug('Verifying classes in create_dataset[...] function ...\\n')\n logging.debug('Total number of classes detected in labels.csv : \\\n {}'.format(num_classes))\n logging.debug('Detected classes names : {}'.format(class_names))\n\n\n # Split into train, validation and test splits that have 70% / 15% / 15%\n # of the data, respectively.\n num_trainval_classes = int(0.85 * num_classes)\n num_train_classes = int(0.7 * num_classes)\n num_valid_classes = num_trainval_classes - num_train_classes\n num_test_classes = num_classes - num_trainval_classes\n\n \n train_inds, valid_inds, test_inds = gen_rand_split_inds(\n num_train_classes, num_valid_classes, num_test_classes)\n\n splits = {\n 'train' : [class_names[i] for i in train_inds],\n 'valid' : [class_names[i] for i in valid_inds],\n 'test' : [class_names[i] for i in test_inds]\n }\n\n \n\n return splits", "def init_cluster_hex(img,bands,rows,columns,ki):\n\n N = rows * columns\n \n #Setting up SNITC\n S = (rows*columns / (ki * (3**0.5)/2))**0.5\n\n #Get nodes per row allowing a half column margin at one end that alternates\n nodeColumns = round(columns/S - 0.5);\n #Given an integer number of nodes per row recompute S\n S = columns/(nodeColumns + 0.5); \n\n # Get number of rows of nodes allowing 0.5 row margin top and bottom\n nodeRows = round(rows/((3)**0.5/2*S));\n vSpacing = rows/nodeRows;\n\n # Recompute k\n k = nodeRows * nodeColumns;\n\n # Allocate memory and initialise clusters, labels and distances.\n C = numpy.zeros([k,bands+3]) # Cluster centre data 1:times is mean on each band of series\n # times+1 and times+2 is row, col of centre, times+3 is No of pixels\n l = -numpy.ones([rows,columns]) # Matrix labels.\n d = numpy.full([rows,columns], numpy.inf) # Pixel distance matrix from cluster centres.\n\n # Initialise grid\n kk = 0;\n r = vSpacing/2;\n for ri in range(nodeRows):\n x = ri\n if x % 2:\n c = S/2\n else:\n c = S\n\n for ci in range(nodeColumns):\n cc = int(numpy.floor(c)); rr = int(numpy.floor(r))\n ts = img[:,rr,cc]\n st = numpy.append(ts,[rr,cc,0])\n C[kk, :] = st\n c = c+S\n kk = kk+1\n\n r = r+vSpacing\n \n #Cast S\n S = round(S)\n \n return C,S,l,d,k", "def setWeights(self, componentList=[]):\n print('!!! - DEPRICATED: skinClusterData.setWeights()! Use loadWeights() method instead - !!!')\n\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Component List\n if not componentList: componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n indexList = OpenMaya.MIntArray()\n componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n componentFn.getElements(indexList)\n componentIndexList = list(indexList)\n\n # ===========================\n # - Set SkinCluster Weights -\n # ===========================\n\n # Build influence index array\n infIndexArray = OpenMaya.MIntArray()\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n [infIndexArray.append(i) for i in range(len(influenceList))]\n\n # Build master weight array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, False, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return influenceList", "def set_cluster(self, data):\n cluster = Cluster(data['name'])\n for host in data['hosts']:\n cluster.add_host(**host)\n self._cluster = cluster" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rebuild the skinCluster using stored data
def rebuild(self): # ========== # - Checks - # ========== # Check geometry skinGeo = self._data['affectedGeometry'][0] if not cmds.objExists(skinGeo): raise Exception( 'SkinCluster geometry "' + skinGeo + '" does not exist! Use remapGeometry() to load skinCluster data for a different geometry!') # ======================= # - Rebuild SkinCluster - # ======================= # Start timer timer = cmds.timerX() # Initialize Temp Joint tempJnt = '' # Unlock Influences influenceList = self._influenceData.keys() for influence in influenceList: if cmds.objExists(influence + '.liw'): if cmds.getAttr(influence + '.liw', l=True): try: cmds.setAttr(influence + '.liw', l=False) except: print( 'Error unlocking attribute "' + influence + '.liw"! This could problems when rebuilding the skinCluster...') if cmds.getAttr(influence + '.liw'): try: cmds.setAttr(influence + '.liw', False) except: print( 'Error setting attribute "' + influence + '.liw" to False! This could problems when rebuilding the skinCluster...') # Check SkinCluster skinCluster = self._data['name'] if not cmds.objExists(skinCluster): # Get Transform Influences jointList = [inf for inf in influenceList if not self._influenceData[inf]['type']] # Check Transform Influences if not jointList: # Create Temporary Bind Joint cmds.select(cl=1) tempJnt = cmds.joint(n=skinCluster + '_tempJoint') print( 'No transform influences specified for skinCluster "' + skinCluster + '"! Creating temporary bind joint "' + tempJnt + '"!') jointList = [tempJnt] else: # Get Surface Influences influenceList = [inf for inf in influenceList if self._influenceData[inf]['type']] # Create skinCluster skinCluster = cmds.skinCluster(jointList, skinGeo, tsb=True, n=skinCluster)[0] else: # Check Existing SkinCluster affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster) if affectedGeo.keys()[0] != skinGeo: raise Exception( 'SkinCluster "' + skinCluster + '" already exists, but is not connected to the expeced geometry "' + skinGeo + '"!') # Add skinCluster influences for influence in influenceList: # Check influence if not cmds.objExists(influence): raise Exception( 'Influence "' + influence + '" does not exist! Use remapInfluence() to apply data to a different influence!') # Check existing influence connection if not cmds.skinCluster(skinCluster, q=True, inf=True).count(influence): # Add influence if self._influenceData[influence]['type']: # Geometry polySmooth = self._influenceData[influence]['polySmooth'] nurbsSamples = self._influenceData[influence]['nurbsSamples'] cmds.skinCluster(skinCluster, e=True, ai=influence, ug=True, ps=polySmooth, ns=nurbsSamples, wt=0.0, lockWeights=True) else: # Transform cmds.skinCluster(skinCluster, e=True, ai=influence, wt=0.0, lockWeights=True) # Bind Pre Matrix if self._influenceData[influence]['bindPreMatrix']: infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence) cmds.connectAttr(self._influenceData[influence]['bindPreMatrix'], skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', f=True) # Load skinCluster weights cmds.setAttr(skinCluster + '.normalizeWeights', 0) glTools.utils.skinCluster.clearWeights(skinGeo) self.loadWeights() cmds.setAttr(skinCluster + '.normalizeWeights', 1) # Restore Custom Attribute Values and Connections self.setDeformerAttrValues() self.setDeformerAttrConnections() # Clear Selection cmds.select(cl=True) # ================= # - Return Result - # ================= # Print Timed Result totalTime = cmds.timerX(st=timer) print('SkinClusterData: Rebuild time for skinCluster "' + skinCluster + '": ' + str(totalTime)) return skinCluster
[ "def rebuild(self, skinClusterList):\n # Start timer\n timer = cmds.timerX()\n\n # For Each SkinCluster\n for skinCluster in skinClusterList:\n\n # Check skinClusterData\n if not self._data.has_key(skinCluster):\n print('No data stored for skinCluster \"' + skinCluster + '\"! Skipping...')\n\n # Rebuild SkinCluster\n self._data[skinCluster].rebuild()\n\n # Print timed result\n totalTime = cmds.timerX(st=timer)\n print('SkinClusterListData: Total build time for skinCluster list: ' + str(skinTime))", "def buildData(self, skinCluster):\n # ==========\n # - Checks -\n # ==========\n\n # Check skinCluster\n self.verifySkinCluster(skinCluster)\n\n # Clear Data\n self.reset()\n\n # =======================\n # - Build Deformer Data -\n # =======================\n\n # Start Timer\n timer = cmds.timerX()\n\n self._data['name'] = skinCluster\n self._data['type'] = 'skinCluster'\n\n # Get affected geometry\n skinGeoShape = cmds.skinCluster(skinCluster, q=True, g=True)\n if len(skinGeoShape) > 1: raise Exception(\n 'SkinCluster \"' + skinCluster + '\" output is connected to multiple shapes!')\n if not skinGeoShape: raise Exception(\n 'Unable to determine affected geometry for skinCluster \"' + skinCluster + '\"!')\n skinGeo = cmds.listRelatives(skinGeoShape[0], p=True, pa=True)\n if not skinGeo: raise Exception('Unable to determine geometry transform for object \"' + skinGeoShape + '\"!')\n self._data['affectedGeometry'] = skinGeo\n skinGeo = skinGeo[0]\n\n skinClusterSet = glTools.utils.deformer.getDeformerSet(skinCluster)\n\n self._data[skinGeo] = {}\n self._data[skinGeo]['index'] = 0\n self._data[skinGeo]['geometryType'] = str(cmds.objectType(skinGeoShape))\n self._data[skinGeo]['membership'] = glTools.utils.deformer.getDeformerSetMemberIndices(skinCluster, skinGeo)\n self._data[skinGeo]['weights'] = []\n\n if self._data[skinGeo]['geometryType'] == 'mesh':\n self._data[skinGeo]['mesh'] = meshData.MeshData(skinGeo)\n\n # ========================\n # - Build Influence Data -\n # ========================\n\n # Get skinCluster influence list\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n if not influenceList: raise Exception(\n 'Unable to determine influence list for skinCluster \"' + skinCluster + '\"!')\n\n # Get Influence Wieghts\n weights = glTools.utils.skinCluster.getInfluenceWeightsAll(skinCluster)\n\n # For each influence\n for influence in influenceList:\n\n # Initialize influence data\n self._influenceData[influence] = {}\n\n # Get influence index\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n self._influenceData[influence]['index'] = infIndex\n\n # Get Influence BindPreMatrix\n bindPreMatrix = cmds.listConnections(skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', s=True, d=False,\n p=True)\n if bindPreMatrix:\n self._influenceData[influence]['bindPreMatrix'] = bindPreMatrix[0]\n else:\n self._influenceData[influence]['bindPreMatrix'] = ''\n\n # Get Influence Type (Transform/Geometry)\n infGeocmdsonn = cmds.listConnections(skinCluster + '.driverPoints[' + str(infIndex) + ']')\n if infGeocmdsonn:\n self._influenceData[influence]['type'] = 1\n self._influenceData[influence]['polySmooth'] = cmds.skinCluster(skinCluster, inf=influence, q=True,\n ps=True)\n self._influenceData[influence]['nurbsSamples'] = cmds.skinCluster(skinCluster, inf=influence, q=True,\n ns=True)\n else:\n self._influenceData[influence]['type'] = 0\n\n # Get Influence Weights\n pInd = glTools.utils.skinCluster.getInfluencePhysicalIndex(skinCluster, influence)\n self._influenceData[influence]['wt'] = weights[pInd]\n\n # =========================\n # - Custom Attribute Data -\n # =========================\n\n # Add Pre-Defined Custom Attributes\n self.getDeformerAttrValues()\n self.getDeformerAttrConnections()\n\n # =================\n # - Return Result -\n # =================\n\n skinTime = cmds.timerX(st=timer)\n print('SkinClusterData: Data build time for \"' + skinCluster + '\": ' + str(skinTime))", "def rebuild_and_update(self):\n self.generate_collectobot_data()\n self.make_graph_data()", "def rebuild():", "def __init__(self, skinCluster=''):\n # Execute Super Class Initilizer\n super(SkinClusterData, self).__init__()\n\n # SkinCluster Custom Attributes\n self._data['attrValueList'].append('skinningMethod')\n self._data['attrValueList'].append('useComponents')\n self._data['attrValueList'].append('normalizeWeights')\n self._data['attrValueList'].append('deformUserNormals')\n\n # Build SkinCluster Data\n if skinCluster: self.buildData(skinCluster)", "def rebuildWorldSpaceData(self, targetGeo='', method='closestPoint'):\n # Start timer\n timer = cmds.timerX()\n\n # Display Progress\n glTools.utils.progressBar.init(status=('Rebuilding world space skinCluster data...'), maxValue=100)\n\n # ==========\n # - Checks -\n # ==========\n\n # Get Source Geometry\n sourceGeo = self._data['affectedGeometry'][0]\n\n # Target Geometry\n if not targetGeo: targetGeo = sourceGeo\n\n # Check Deformer Data\n if not self._data.has_key(sourceGeo):\n glTools.utils.progressBar.end()\n raise Exception('No deformer data stored for geometry \"' + sourceGeo + '\"!')\n\n # Check Geometry\n if not cmds.objExists(targetGeo):\n glTools.utils.progressBar.end()\n raise Exception('Geometry \"' + targetGeo + '\" does not exist!')\n if not glTools.utils.mesh.isMesh(targetGeo):\n glTools.utils.progressBar.end()\n raise Exception('Geometry \"' + targetGeo + '\" is not a valid mesh!')\n\n # Check Mesh Data\n if not self._data[sourceGeo].has_key('mesh'):\n glTools.utils.progressBar.end()\n raise Exception('No world space mesh data stored for mesh geometry \"' + sourceGeo + '\"!')\n\n # =====================\n # - Rebuild Mesh Data -\n # =====================\n\n meshData = self._data[sourceGeo]['mesh']._data\n\n meshUtil = OpenMaya.MScriptUtil()\n numVertices = len(meshData['vertexList']) / 3\n numPolygons = len(meshData['polyCounts'])\n polygonCounts = OpenMaya.MIntArray()\n polygonConnects = OpenMaya.MIntArray()\n meshUtil.createIntArrayFromList(meshData['polyCounts'], polygonCounts)\n meshUtil.createIntArrayFromList(meshData['polyConnects'], polygonConnects)\n\n # Rebuild Vertex Array\n vertexArray = OpenMaya.MFloatPointArray(numVertices, OpenMaya.MFloatPoint.origin)\n vertexList = [vertexArray.set(i, meshData['vertexList'][i * 3], meshData['vertexList'][i * 3 + 1],\n meshData['vertexList'][i * 3 + 2], 1.0) for i in xrange(numVertices)]\n\n # Rebuild Mesh\n meshFn = OpenMaya.MFnMesh()\n meshDataFn = OpenMaya.MFnMeshData().create()\n meshObj = meshFn.create(numVertices, numPolygons, vertexArray, polygonCounts, polygonConnects, meshDataFn)\n\n # Create Mesh Intersector\n meshPt = OpenMaya.MPointOnMesh()\n meshIntersector = OpenMaya.MMeshIntersector()\n if method == 'closestPoint': meshIntersector.create(meshObj)\n\n # ========================================\n # - Rebuild Weights and Membership List -\n # ========================================\n\n # Initialize Influence Weights and Membership\n influenceList = self._influenceData.keys()\n influenceWt = [[] for inf in influenceList]\n membership = set([])\n\n # Get Target Mesh Data\n targetMeshFn = glTools.utils.mesh.getMeshFn(targetGeo)\n targetMeshPts = targetMeshFn.getRawPoints()\n numTargetVerts = targetMeshFn.numVertices()\n targetPtUtil = OpenMaya.MScriptUtil()\n\n # Initialize Float Pointers for Barycentric Coords\n uUtil = OpenMaya.MScriptUtil(0.0)\n vUtil = OpenMaya.MScriptUtil(0.0)\n uPtr = uUtil.asFloatPtr()\n vPtr = vUtil.asFloatPtr()\n\n # Get Progress Step\n progressInd = int(numTargetVerts * 0.01)\n if progressInd < 1: progressInd = 1\n\n for i in range(numTargetVerts):\n\n # Get Target Point\n targetPt = OpenMaya.MPoint(targetPtUtil.getFloatArrayItem(targetMeshPts, (i * 3) + 0),\n targetPtUtil.getFloatArrayItem(targetMeshPts, (i * 3) + 1),\n targetPtUtil.getFloatArrayItem(targetMeshPts, (i * 3) + 2))\n\n # Get Closest Point Data\n meshIntersector.getClosestPoint(targetPt, meshPt)\n\n # Get Barycentric Coords\n meshPt.getBarycentricCoords(uPtr, vPtr)\n u = OpenMaya.MScriptUtil(uPtr).asFloat()\n v = OpenMaya.MScriptUtil(vPtr).asFloat()\n baryWt = [u, v, 1.0 - (u + v)]\n\n # Get Triangle Vertex IDs\n idUtil = OpenMaya.MScriptUtil([0, 1, 2])\n idPtr = idUtil.asIntPtr()\n meshFn.getPolygonTriangleVertices(meshPt.faceIndex(), meshPt.triangleIndex(), idPtr)\n triId = [OpenMaya.MScriptUtil().getIntArrayItem(idPtr, n) for n in range(3)]\n memId = [self._data[sourceGeo]['membership'].count(t) for t in triId]\n wtId = [self._data[sourceGeo]['membership'].index(t) for t in triId]\n\n # For Each Influence\n for inf in range(len(influenceList)):\n\n # Calculate Weight and Membership\n wt = 0.0\n isMember = False\n for n in range(3):\n\n # Check Against Source Membership\n if memId[n]:\n wt += self._influenceData[influenceList[inf]]['wt'][wtId[n]] * baryWt[n]\n isMember = True\n\n # Check Member\n if isMember:\n # Append Weight Value\n influenceWt[inf].append(wt)\n # Append Membership\n membership.add(i)\n\n # Update Progress Bar\n if not i % progressInd: glTools.utils.progressBar.update(step=1)\n\n # ========================\n # - Update Deformer Data -\n # ========================\n\n # Remap Geometry\n self.remapGeometry(targetGeo)\n\n # Rename SkinCluster\n targetSkinCluster = glTools.utils.skinCluster.findRelatedSkinCluster(targetGeo)\n if targetSkinCluster:\n self._data['name'] = targetSkinCluster\n else:\n prefix = targetGeo.split(':')[-1]\n self._data['name'] = prefix + '_skinCluster'\n\n # Update Membership and Weights\n self._data[sourceGeo]['membership'] = list(membership)\n for inf in range(len(influenceList)):\n self._influenceData[influenceList[inf]]['wt'] = influenceWt[inf]\n\n # =================\n # - Return Result -\n # =================\n\n # End Progress\n glTools.utils.progressBar.end()\n\n # Print Timed Result\n buildTime = cmds.timerX(st=timer)\n print(\n 'SkinClusterData: Rebuild world space data for skinCluster \"' + self._data['name'] + '\": ' + str(buildTime))\n\n # Return Weights\n return", "def setWeights(self, componentList=[]):\n print('!!! - DEPRICATED: skinClusterData.setWeights()! Use loadWeights() method instead - !!!')\n\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Component List\n if not componentList: componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n indexList = OpenMaya.MIntArray()\n componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n componentFn.getElements(indexList)\n componentIndexList = list(indexList)\n\n # ===========================\n # - Set SkinCluster Weights -\n # ===========================\n\n # Build influence index array\n infIndexArray = OpenMaya.MIntArray()\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n [infIndexArray.append(i) for i in range(len(influenceList))]\n\n # Build master weight array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, False, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return influenceList", "def construct_cluster_rxn(cluster_file, scaffold, reactant_data):\n # Load_reactants and reacting groups\n reacting_groups = []\n reactants = []\n for reacting_group in reactant_data:\n\n reacting_groups.append(reacting_group[1])\n reactant = []\n with open(reacting_group[0], 'r') as f:\n lines = f.readlines()\n compounds = [line.strip('\\n').split('\\t') for line in lines if 'canonical_smiles' not in line]\n for compound in compounds:\n mol = Chem.MolFromSmiles(compound[0])\n if not mol:\n continue\n reactant.append(mol)\n reactants.append(reactant)\n\n # Unzipping cluster files and constructing list from lines\n with gzip.open(cluster_file, 'rt') as f:\n lines = f.readlines()\n\n mols_to_rebuild = [line.strip('\\n').split('\\t') for line in lines]\n\n # Create rdkit reaction from smart\n rxn_reaction = f\"{'.'.join(reacting_groups)}>>{scaffold}\"\n reaction = AllChem.ReactionFromSmarts(rxn_reaction)\n\n # Perform reaction and cleaup products.\n cluster = []\n for mol_to_rebuild in mols_to_rebuild:\n # Note to self: since I stored python lists as string I use eval to recreate lists. In other software this might\n # be a major security risk.\n building_block_indices, compound_index = mol_to_rebuild\n building_block_indices = eval(building_block_indices)\n building_blocks = [reactants[index][block] for index, block in enumerate(building_block_indices)]\n unfiltered_products = reaction.RunReactants(building_blocks)\n found_smiles = set()\n for product in unfiltered_products:\n product = product[0]\n smiles = Chem.MolToSmiles(product)\n if not smiles in found_smiles:\n # Chem.GetSSSR(product)\n Chem.SanitizeMol(product)\n cluster.append((product, compound_index, building_block_indices))\n found_smiles.add(smiles)\n\n return cluster", "def update_clusters(self):\n num_ratings = Rating.objects.count()\n \n if self.eligible_to_update(num_ratings):\n ratings_matrix, num_users, all_user_names = \\\n self.construct_ratings_matrix()\n\n k_clusters = int(num_users / 10) + 2 # \"Magical numbers that \n # work the best\"\n from sklearn.cluster import KMeans\n kmeans = KMeans(n_clusters=k_clusters)\n clusters = kmeans.fit(ratings_matrix.tocsr()) # Read sklearn\n # docs to read why tocsr() used. THE MAIN KMEANS CLUSTERING\n\n # Updating the clusters\n Cluster.objects.all().delete()\n new_clusters = {i: Cluster(name=i) for i in range(k_clusters)}\n for cluster in new_clusters.values():\n cluster.save()\n for i, cluster_label in enumerate(clusters.labels_):\n # Add the new users to clusters\n new_clusters[cluster_label].users.add(\n User.objects.get(username=all_user_names[i])\n )", "def rebuild(self):\n if self.board!=None:\n for tileSetWidget in self.getObjectsByType(TileSetWidget):\n tileSetWidget.Destroy()\n for tileWidget in self.getObjectsByType(TileWidget):\n tileWidget.Destroy()\n for set in self.board.getSets():\n tileSetWidget = TileSetWidget(self, set)\n tileSetWidget.setPos(set.getPos())\n tileSetWidget.rebuild()", "def __init__(self, data, refresh=False, clusters=True):\n self.data = data\n self.n_items = len(data)\n self.stop_list = analyse.get_stop_list()\n load_success = False\n\n self.dictionary = []\n # corpus = []\n self.lsi = []\n self.index = []\n self.bigram = []\n self.trigram = []\n\n if refresh is False:\n try:\n load_dir = \"tmp_articles/\"\n if clusters is True:\n load_dir = \"tmp_clusters/\"\n # corpus = corpora.MmCorpus(\"/tmp/corpus.mm\")\n self.dictionary = corpora.Dictionary.load(load_dir +\n \"dictionary.dict\")\n self.lsi = models.LsiModel.load(load_dir + \"model.lsi\")\n self.index = similarities.MatrixSimilarity.load(\n load_dir + \"nyt.index\")\n self.bigram = models.Phrases.load(load_dir + \"bigram\")\n self.trigram = models.Phrases.load(load_dir + \"trigram\")\n print \"Loaded from files\"\n load_success = True\n except:\n print \"Did not load from files\"\n load_success = False\n\n if not load_success or refresh is True:\n print \"Rebuilding indexes\"\n # texts = [[word for word in document.lower().split() if word not in\n # self.stop_list] for document in\n # [row[0] for row in self.data]]\n texts = [[word for word in document.lower().split() if word not in\n self.stop_list] for document in\n [row[0] + row[4] for row in self.data]]\n\n # Bigrams\n self.bigram = models.Phrases(min_count=2, threshold=1)\n for item in texts:\n self.bigram.add_vocab([item])\n print self.bigram\n texts = self.bigram[texts]\n self.bigram.save(\"tmp/bigram\")\n\n # Trigram\n self.trigram = models.Phrases(min_count=2, threshold=1)\n for item in texts:\n self.trigram.add_vocab([item])\n print self.trigram\n texts = self.trigram[texts]\n self.trigram.save(\"tmp/trigram\")\n\n self.dictionary = corpora.Dictionary(texts)\n self.dictionary.save(\"tmp/dictionary.dict\")\n corpus = [self.dictionary.doc2bow(text) for text in texts]\n # corpora.MmCorpus.serialize(\"/tmp/corpus.mm\", corpus)\n tfidf = models.TfidfModel(corpus)\n corpus_tfidf = tfidf[corpus]\n self.lsi = models.LsiModel(corpus_tfidf, id2word=self.dictionary,\n num_topics=200)\n self.lsi.save(\"tmp/model.lsi\")\n corpus_lsi = self.lsi[corpus]\n self.index = similarities.MatrixSimilarity(corpus_lsi)\n self.index.save(\"tmp/nyt.index\")", "def resume_cluster():\n log.info(\"Loading info from the IaaS\")\n global nodes, seeds, stash\n if not isfile(save_file):\n log.info(\"No existing created cluster\")\n return\n saved_cluster = loads(open(save_file, 'r').read())\n saved_nodes = list(set(saved_cluster['nodes']))\n saved_seeds = list(set(saved_cluster['seeds']))\n saved_stash = list(set(saved_cluster['stash']))\n nodes[:] = []\n seeds[:] = []\n\n in_nodes = Node.get_all_nodes(check_active=True)\n #check that all saved nodes actually exist\n for n in saved_nodes:\n if n not in [i.name for i in in_nodes]:\n log.error(\"node %s does actually exist in the cloud, re-create the cluster\" % n)\n remove(save_file)\n exit(-1)\n for n in in_nodes:\n if n.name not in saved_nodes+saved_seeds:\n if n.name in saved_stash:\n stash.append(n)\n if \"orchestrator\" in n.name:\n global orchestrator\n orchestrator = n\n continue\n else:\n if n.type == \"seed\":\n seeds.append(n)\n elif n.type == \"node\": nodes.append(n)\n #sort nodes by name\n nodes.sort(key=lambda x: x.name)\n stash.sort(key=lambda x: x.name)", "def unionfind_cluster_editing(filename, output_path, missing_weight, n, x):\n n_merges = 1\n merge_filter = 0.1\n repair_filter = 0.9\n union_threshold = 0.05\n big_border = 0.3\n graph_file = open(filename, mode=\"r\")\n\n\n### Preprocessing ###\n# Knotengrade berechnen je Knoten (Scan über alle Kanten)\n node_dgr = np.zeros(n, dtype=np.int64)\n\n for line in graph_file:\n # Kommentar-Zeilen überspringen\n if line[0] == \"#\":\n continue\n splitted = line.split()\n nodes = np.array(splitted[:-1], dtype=np.int64)\n weight = np.float64(splitted[2])\n\n # Falls Kante 'existiert' nach Threshold:\n if weight > 0:\n node_dgr[nodes[0]] += 1\n node_dgr[nodes[1]] += 1\n\n# Sequentiell für alle Lösungen (alle UF-Strukturen gleichzeitig, oder zumindest so viele wie passen):\n# Größe einer Lösung: Array mit n Einträgen aus je 64bit\n### Generate Solutions ###\n parents = np.full((x,n), np.arange(n, dtype=np.int64))\n sizes = np.zeros((x,n), dtype=np.int64)\n # Modellparameter einlesen:\n parameters_b = load_model_flexible_v2('params_below_100.csv')\n parameters_a = load_model_flexible_v2('params_above_100.csv')\n #cluster_count = np.full(x, n, dtype=np.int64)\n # Alle Parameter für die Modelle festlegen:\n cluster_model = np.full(x,17)\n def generate_solutions(first, c_opt):\n if first:\n k = int(x/37)\n j = 0\n c = 0\n\n for i in range(0,x):\n cluster_model[i] = c\n j += 1\n if j == k and c < 36:\n c += 1\n j = 0\n if not first:\n # Überschreibe Lösungen mit nicht-optimalem Parameter um danach neue zu generieren\n for i in range(0,x):\n if cluster_model[i] != c_opt:\n parents[i] = np.arange(n, dtype=np.int64)\n\n # 2. Scan über alle Kanten: Je Kante samplen in UF-Strukturen\n graph_file = open(filename, mode=\"r\")\n\n for line in graph_file:\n # Kommentar-Zeilen überspringen\n if line[0] == \"#\":\n continue\n splitted = line.split()\n nodes = np.array(splitted[:-1], dtype=np.int64)\n weight = np.float64(splitted[2])\n\n guess_n = (node_dgr[nodes[0]] + node_dgr[nodes[1]]) / 2\n\n decision_values = rand.rand(x)\n for i in range(0, x):\n if not first:\n if cluster_model[i] == c_opt:\n # Ändere in 2. Lauf nichts an den Lösungen, die bereits gut sind!\n continue\n # Samplingrate ermitteln\n sampling_rate = model_flexible_v2(parameters_b, parameters_a, guess_n, cluster_model[i])\n # Falls Kante gesamplet...\n if decision_values[i] < sampling_rate:\n # ...füge Kante ein in UF-Struktur\n rem_union(nodes[0], nodes[1], parents[i])\n\n generate_solutions(True, 0)\n\n\n\n### Solution Assessment ###\n# Nachbearbeitung aller Lösungen: Flache Struktur (= Knoten in selbem Cluster haben selben Eintrag im Array)\n# Und Berechnung benötigter Kanten je Cluster (n_c * (n_c-1) / 2) pro UF\n\n def calculate_costs(solutions_parents, x, merged):\n\n solution_costs = np.zeros(x, dtype=np.float64)\n vertex_costs = np.zeros((x,n), dtype=np.float64)\n c_edge_counter = np.zeros((x,n), dtype=np.int64)\n inner_sizes = np.zeros((x,n), dtype=np.int64)\n\n for i in range(x):\n for j in range(n):\n root = flattening_find(j,solutions_parents[i])\n inner_sizes[i, root] += 1\n for j in range(n):\n root = solutions_parents[i, j]\n n_c = inner_sizes[i, root]\n c_edge_counter[i, j] = n_c - 1\n\n # 3. Scan über alle Kanten: Kostenberechnung für alle Lösungen (Gesamtkosten und Clusterkosten)\n graph_file = open(filename, mode=\"r\")\n\n for line in graph_file:\n # Kommentar-Zeilen überspringen\n if line[0] == \"#\":\n continue\n splitted = line.split()\n nodes = np.array(splitted[:-1], dtype=np.int64)\n weight = np.float64(splitted[2])\n\n for i in range(0,x):\n if not merged:\n root1 = find(nodes[0],solutions_parents[i])\n root2 = find(nodes[1],solutions_parents[i])\n else:\n root1 = solutions_parents[i, nodes[0]]\n root2 = solutions_parents[i, nodes[1]]\n # Kante zwischen zwei Clustern\n if root1 != root2:\n # mit positivem Gewicht (zu viel)\n if weight > 0:\n vertex_costs[i, nodes[0]] += weight / 2\n vertex_costs[i, nodes[1]] += weight / 2\n solution_costs[i] += weight\n # Kante innerhalb von Cluster\n else:\n # mit negativem Gewicht (fehlt)\n if weight < 0:\n vertex_costs[i, nodes[0]] -= weight / 2\n vertex_costs[i, nodes[1]] -= weight / 2\n solution_costs[i] -= weight\n c_edge_counter[i, nodes[0]] -= 1\n c_edge_counter[i, nodes[1]] -= 1\n #print(\"missing edges for now: \", c_edge_counter[i][root1])\n\n for i in range(0,x):\n # über Cluster(-Repräsentanten, Keys) iterieren:\n for j in range(n):\n missing_edges = c_edge_counter[i, j]\n if missing_edges > 0:\n # Kosten für komplett fehlende Kanten zur Lösung addieren\n vertex_costs[i, j] += missing_edges * (-missing_weight) * 0.5\n solution_costs[i] += missing_edges * (-missing_weight) * 0.5 # Zwei Knoten innerhalb eines Clusters vermissen die selbe Kante, daher *0.5 bei Berechnung über die Knoten\n return (vertex_costs, solution_costs, inner_sizes)\n costs = calculate_costs(parents, x, False)\n vertex_costs = costs[0]\n solution_costs = costs[1]\n sizes = costs[2]\n\n### Solution Merge ###\n\n# Mithilfe der Bewertungen/Kosten Lösungen sinnvoll mergen/reparieren\n# Platzhalter: Beste Lösung direkt übernehmen\n\n mean_costs_c = np.zeros(37, dtype=np.float64)\n c_count = np.zeros(37, dtype= np.int64)\n # Summierte Kosten für selben Parameter\n for i in range(x):\n c = cluster_model[i]\n mean_costs_c[c] = mean_costs_c[c] + solution_costs[i]\n c_count[c] += 1\n # Teilen durch Anzahl Lösungen mit dem Parameter\n for i in range(37):\n mean_costs_c[i] = mean_costs_c[i]/c_count[i]\n # c_opt ist Parameter mit geringsten Durchschnittskosten der Lösungen\n c_opt = np.argsort(mean_costs_c)[0]\n\n generate_solutions(False, c_opt)\n costs = calculate_costs(parents, x, False)\n vertex_costs = costs[0]\n solution_costs = costs[1]\n print_solution_costs(solution_costs, output_path)\n # Optimierung: Filtern der \"besten\" Lösungen, um eine solidere Basis für den Merge zu schaffen.\n # best_costs_i = np.argmin(solution_costs)\n # best_costs = solution_costs[best_costs_i]\n # good_costs_i = np.where(solution_costs <= best_costs * 1.7)\n # Variante 2: Beste 10% verwenden\n top_percent = range(np.int64(x*merge_filter))\n mid_percent = range(np.int64(x*repair_filter))\n cost_sorted_i = np.argsort(solution_costs)\n good_costs_i = cost_sorted_i[top_percent]\n mid_costs_i = cost_sorted_i[mid_percent]\n # Artefakt aus Zeit mit n_merges > 1; sonst inkompatibel mit calculate_costs.\n merged_solutions = np.full((n_merges,n), np.arange(n, dtype=np.int64))\n final_solutions = np.full((n_merges,n), np.arange(n, dtype=np.int64))\n merged_sizes = np.zeros((n_merges,n), dtype=np.int64)\n for i in range(0,n_merges):\n merged = merged_solution_scan(solution_costs[good_costs_i], vertex_costs[good_costs_i], parents[good_costs_i], sizes[good_costs_i], missing_weight, n, filename, union_threshold)\n merged_save = np.copy(merged)\n merged_solutions[i] = merged\n merged_c = calculate_costs(merged_solutions, n_merges, True)\n merged_costs = merged_c[1]\n merged_vc = merged_c[0]\n #merged_to_file(merged_solutions, merged_costs, filename, missing_weight, n, len(good_costs_i), n_merges)\n # Glätten der Lösung + Berechnung der korrekten merged_sizes (vorher 0, innerhalb calculate_costs berechnet aber nicht verändert)\n print_result(output_path, \"merged_costs_v5.txt\", merged_costs[0])\n for j in range(0,n):\n r = flattening_find(j, merged_solutions[i])\n merged_sizes[i, r] += 1\n rep = repair_merged_v4_nd_rem(merged_solutions[i], merged_sizes[i], solution_costs[mid_costs_i], vertex_costs[mid_costs_i], parents[mid_costs_i], sizes[mid_costs_i], n, node_dgr, big_border, filename)\n merged_solutions[i] = rep\n merged_c = calculate_costs(merged_solutions, n_merges, True)\n merged_costs = merged_c[1]\n rep_vc = merged_c[0]\n print_result(output_path, \"rep_v5.txt\", merged_costs[0])\n final_solutions[0] = undo_merge_repair(merged_save, rep, merged_vc[0], rep_vc[0])\n final_costs = calculate_costs(final_solutions, 1, True)[1]\n print_result(output_path, \"final_v5.txt\", final_costs[0])\n # Da Merge auf x2 Lösungen basiert, nur diese angeben:\n x2 = len(mid_costs_i)\n #merged_to_file(merged_solutions, merged_costs, filename, missing_weight, n, x2, n_merges)\n merged_to_file(final_solutions, final_costs, filename, missing_weight, n, x2, n_merges, output_path)\n #all_solutions(solution_costs[good_costs_i], parents[good_costs_i], filename, missing_weight, n)\n #print_solution_costs(solution_costs[good_costs_i], filename)\n #merged_short_print(merged_solutions, merged_costs, filename, missing_weight, n, x2, n_merges)", "def collate_cluster_data(ensembles_data):\n\n clusters = {} # Loop through all ensemble data objects and build up a data tree\n cluster_method = None\n cluster_score_type = None\n truncation_method = None\n percent_truncation = None\n side_chain_treatments = []\n for e in ensembles_data:\n if not cluster_method:\n cluster_method = e['cluster_method']\n cluster_score_type = e['cluster_score_type']\n percent_truncation = e['truncation_percent']\n truncation_method = e['truncation_method']\n # num_clusters = e['num_clusters']\n cnum = e['cluster_num']\n if cnum not in clusters:\n clusters[cnum] = {}\n clusters[cnum]['cluster_centroid'] = e['cluster_centroid']\n clusters[cnum]['cluster_num_models'] = e['cluster_num_models']\n clusters[cnum]['tlevels'] = {}\n tlvl = e['truncation_level']\n if tlvl not in clusters[cnum]['tlevels']:\n clusters[cnum]['tlevels'][tlvl] = {}\n clusters[cnum]['tlevels'][tlvl]['truncation_variance'] = e['truncation_variance']\n clusters[cnum]['tlevels'][tlvl]['num_residues'] = e['num_residues']\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'] = {}\n srt = e['subcluster_radius_threshold']\n if srt not in clusters[cnum]['tlevels'][tlvl]['radius_thresholds']:\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt] = {}\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['num_models'] = e['subcluster_num_models']\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'] = {}\n sct = e['side_chain_treatment']\n if sct not in side_chain_treatments:\n side_chain_treatments.append(sct)\n if sct not in clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct']:\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'][sct] = {}\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'][sct]['name'] = e['name']\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'][sct]['num_atoms'] = e['ensemble_num_atoms']\n\n return {\n 'clusters': clusters,\n 'cluster_method': cluster_method,\n 'cluster_score_type': cluster_score_type,\n 'truncation_method': truncation_method,\n 'percent_truncation': percent_truncation,\n 'side_chain_treatments': side_chain_treatments,\n }", "def reconstruct_mesh(self):\n\n # NOTE: Before drawing the skeleton, create the materials once and for all to improve the\n # performance since this is way better than creating a new material per section or segment\n nmv.builders.create_skeleton_materials(builder=self)\n\n # Verify and repair the morphology, if required\n result, stats = nmv.utilities.profile_function(self.verify_morphology_skeleton)\n self.profiling_statistics += stats\n\n # Apply skeleton - based operation, if required, to slightly modify the skeleton\n result, stats = nmv.utilities.profile_function(\n nmv.builders.modify_morphology_skeleton, self)\n self.profiling_statistics += stats\n\n # Build the soma, with the default parameters\n result, stats = nmv.utilities.profile_function(nmv.builders.reconstruct_soma_mesh, self)\n self.profiling_statistics += stats\n\n # Build the arbors and connect them to the soma\n if self.options.mesh.soma_connection == nmv.enums.Meshing.SomaConnection.CONNECTED:\n\n # Build the arbors\n result, stats = nmv.utilities.profile_function(self.build_arbors, True)\n self.profiling_statistics += stats\n\n # Connect to the soma\n result, stats = nmv.utilities.profile_function(\n nmv.builders.connect_arbors_to_soma, self)\n self.profiling_statistics += stats\n\n # Build the arbors only without any connection to the soma\n else:\n # Build the arbors\n result, stats = nmv.utilities.profile_function(self.build_arbors, False)\n self.profiling_statistics += stats\n\n # Tessellation\n result, stats = nmv.utilities.profile_function(nmv.builders.decimate_neuron_mesh, self)\n self.profiling_statistics += stats\n\n # Surface roughness\n result, stats = nmv.utilities.profile_function(\n nmv.builders.add_surface_noise_to_arbor, self)\n self.profiling_statistics += stats\n\n # Add the spines\n result, stats = nmv.utilities.profile_function(nmv.builders.add_spines_to_surface, self)\n self.profiling_statistics += stats\n\n # Join all the objects into a single object\n result, stats = nmv.utilities.profile_function(\n nmv.builders.join_mesh_object_into_single_object, self)\n self.profiling_statistics += stats\n\n # Transform to the global coordinates, if required\n result, stats = nmv.utilities.profile_function(\n nmv.builders.transform_to_global_coordinates, self)\n self.profiling_statistics += stats\n\n # Collect the stats. of the mesh\n result, stats = nmv.utilities.profile_function(nmv.builders.collect_mesh_stats, self)\n self.profiling_statistics += stats\n\n # Done\n nmv.logger.header('Mesh Reconstruction Done!')\n nmv.logger.log(self.profiling_statistics)\n\n # Write the stats to file\n nmv.builders.write_statistics_to_file(builder=self, tag='skinning')", "def rebuild(self) -> None:\n # Hold a reference to the old textures\n textures = list(self._textures)\n # Clear the atlas but keep the uv slot mapping\n self.clear(clear_image_ids=False, clear_texture_ids=False)\n # Add textures back sorted by height to potentially make more room\n for texture in sorted(textures, key=lambda x: x.image.size[1]):\n self.add(texture)", "def __init__(self):\n\n self.clusters = [ ]", "def compose_cluster_map(self,filedir):\r\n self.cluster_map = np.zeros((SAT_SIZE,SAT_SIZE),dtype='uint16')\r\n #Search the directory for all matching npy files:\r\n file_list = os.listdir(filedir)\r\n for file in file_list:\r\n file_parts = file.split('_')\r\n if len(file_parts)==3 and file_parts[2]=='clusters.npy':\r\n x0 = int(file_parts[0])\r\n y0 = int(file_parts[1])\r\n x1 = x0 + 2*VIEW_SIZE\r\n y1 = y0 + 2*VIEW_SIZE\r\n cluster_area = np.load(filedir+file).reshape(2*VIEW_SIZE,2*VIEW_SIZE)\r\n self.cluster_map[y0:y1,x0:x1] = cluster_area\r\n np.save(filedir+'cluster_map.npy',self.cluster_map)", "def reset_settings(self):\n self.__init__(self.orig_clust_num, self.data_path)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply the stored skinCluster weights to the specified skinCluster.
def setWeights(self, componentList=[]): print('!!! - DEPRICATED: skinClusterData.setWeights()! Use loadWeights() method instead - !!!') # ========== # - Checks - # ========== # Check SkinCluster skinCluster = self._data['name'] self.verifySkinCluster(skinCluster) # Check Geometry skinGeo = self._data['affectedGeometry'][0] if not cmds.objExists(skinGeo): raise Exception( 'SkinCluster geometry "' + skinGeo + '" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!') # Check Component List if not componentList: componentList = glTools.utils.component.getComponentStrList(skinGeo) componentSel = glTools.utils.selection.getSelectionElement(componentList, 0) # Get Component Index List indexList = OpenMaya.MIntArray() componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1]) componentFn.getElements(indexList) componentIndexList = list(indexList) # =========================== # - Set SkinCluster Weights - # =========================== # Build influence index array infIndexArray = OpenMaya.MIntArray() influenceList = cmds.skinCluster(skinCluster, q=True, inf=True) [infIndexArray.append(i) for i in range(len(influenceList))] # Build master weight array wtArray = OpenMaya.MDoubleArray() oldWtArray = OpenMaya.MDoubleArray() for c in componentIndexList: for i in range(len(influenceList)): if self._influenceData.has_key(influenceList[i]): wtArray.append(self._influenceData[influenceList[i]]['wt'][c]) else: wtArray.append(0.0) # Get skinCluster function set skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster) # Set skinCluster weights skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, False, oldWtArray) # ================= # - Return Result - # ================= return influenceList
[ "def loadWeights(self,\n skinCluster=None,\n influenceList=None,\n componentList=None,\n normalize=True):\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n if not skinCluster: skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Influence List\n if not influenceList: influenceList = self._influenceData.keys() or []\n for influence in influenceList:\n if not influence in cmds.skinCluster(skinCluster, q=True, inf=True) or []:\n raise Exception(\n 'Object \"' + influence + '\" is not a valid influence of skinCluster \"' + skinCluster + '\"! Unable to load influence weights...')\n if not self._influenceData.has_key(influence):\n raise Exception('No influence data stored for \"' + influence + '\"! Unable to load influence weights...')\n\n # Check Component List\n if not componentList:\n componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n # indexList = OpenMaya.MIntArray()\n # componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n # componentFn.getElements(indexList)\n # componentIndexList = list(indexList)\n componentIndexList = glTools.utils.component.getSingleIndexComponentList(componentList)\n componentIndexList = componentIndexList[componentIndexList.keys()[0]]\n\n # =====================================\n # - Set SkinCluster Influence Weights -\n # =====================================\n\n # Get Influence Index\n infIndexArray = OpenMaya.MIntArray()\n for influence in influenceList:\n infIndex = glTools.utils.skinCluster.getInfluencePhysicalIndex(skinCluster, influence)\n infIndexArray.append(infIndex)\n\n # Build Weight Array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, normalize, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return list(wtArray)", "def rebuild(self):\n # ==========\n # - Checks -\n # ==========\n\n # Check geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data for a different geometry!')\n\n # =======================\n # - Rebuild SkinCluster -\n # =======================\n\n # Start timer\n timer = cmds.timerX()\n\n # Initialize Temp Joint\n tempJnt = ''\n\n # Unlock Influences\n influenceList = self._influenceData.keys()\n for influence in influenceList:\n if cmds.objExists(influence + '.liw'):\n if cmds.getAttr(influence + '.liw', l=True):\n try:\n cmds.setAttr(influence + '.liw', l=False)\n except:\n print(\n 'Error unlocking attribute \"' + influence + '.liw\"! This could problems when rebuilding the skinCluster...')\n if cmds.getAttr(influence + '.liw'):\n try:\n cmds.setAttr(influence + '.liw', False)\n except:\n print(\n 'Error setting attribute \"' + influence + '.liw\" to False! This could problems when rebuilding the skinCluster...')\n\n # Check SkinCluster\n skinCluster = self._data['name']\n if not cmds.objExists(skinCluster):\n\n # Get Transform Influences\n jointList = [inf for inf in influenceList if not self._influenceData[inf]['type']]\n\n # Check Transform Influences\n if not jointList:\n\n # Create Temporary Bind Joint\n cmds.select(cl=1)\n tempJnt = cmds.joint(n=skinCluster + '_tempJoint')\n print(\n 'No transform influences specified for skinCluster \"' + skinCluster + '\"! Creating temporary bind joint \"' + tempJnt + '\"!')\n jointList = [tempJnt]\n\n else:\n\n # Get Surface Influences\n influenceList = [inf for inf in influenceList if self._influenceData[inf]['type']]\n\n # Create skinCluster\n skinCluster = cmds.skinCluster(jointList, skinGeo, tsb=True, n=skinCluster)[0]\n\n else:\n\n # Check Existing SkinCluster\n affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster)\n if affectedGeo.keys()[0] != skinGeo:\n raise Exception(\n 'SkinCluster \"' + skinCluster + '\" already exists, but is not connected to the expeced geometry \"' + skinGeo + '\"!')\n\n # Add skinCluster influences\n for influence in influenceList:\n\n # Check influence\n if not cmds.objExists(influence):\n raise Exception(\n 'Influence \"' + influence + '\" does not exist! Use remapInfluence() to apply data to a different influence!')\n\n # Check existing influence connection\n if not cmds.skinCluster(skinCluster, q=True, inf=True).count(influence):\n\n # Add influence\n if self._influenceData[influence]['type']:\n # Geometry\n polySmooth = self._influenceData[influence]['polySmooth']\n nurbsSamples = self._influenceData[influence]['nurbsSamples']\n cmds.skinCluster(skinCluster, e=True, ai=influence, ug=True, ps=polySmooth, ns=nurbsSamples, wt=0.0,\n lockWeights=True)\n\n else:\n # Transform\n cmds.skinCluster(skinCluster, e=True, ai=influence, wt=0.0, lockWeights=True)\n\n # Bind Pre Matrix\n if self._influenceData[influence]['bindPreMatrix']:\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n cmds.connectAttr(self._influenceData[influence]['bindPreMatrix'],\n skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', f=True)\n\n # Load skinCluster weights\n cmds.setAttr(skinCluster + '.normalizeWeights', 0)\n glTools.utils.skinCluster.clearWeights(skinGeo)\n self.loadWeights()\n cmds.setAttr(skinCluster + '.normalizeWeights', 1)\n\n # Restore Custom Attribute Values and Connections\n self.setDeformerAttrValues()\n self.setDeformerAttrConnections()\n\n # Clear Selection\n cmds.select(cl=True)\n\n # =================\n # - Return Result -\n # =================\n\n # Print Timed Result\n totalTime = cmds.timerX(st=timer)\n print('SkinClusterData: Rebuild time for skinCluster \"' + skinCluster + '\": ' + str(totalTime))\n\n return skinCluster", "def normalizeSkinWeights(skin):\n weights = getSkinWeights(skin)\n normWeights = normalizeWeightsData(weights)\n setSkinWeights(skin, normWeights)", "def __init__(self, skinCluster=''):\n # Execute Super Class Initilizer\n super(SkinClusterData, self).__init__()\n\n # SkinCluster Custom Attributes\n self._data['attrValueList'].append('skinningMethod')\n self._data['attrValueList'].append('useComponents')\n self._data['attrValueList'].append('normalizeWeights')\n self._data['attrValueList'].append('deformUserNormals')\n\n # Build SkinCluster Data\n if skinCluster: self.buildData(skinCluster)", "def getMfnSkinCluster(self, skinCluster):\n selectionList = OpenMaya.MSelectionList()\n selectionList.add(skinCluster)\n mObj_skinCluster = OpenMaya.MObject()\n selectionList.getDependNode(0, mObj_skinCluster)\n mfnSkinCluster = OpenMayaAnim.MFnSkinCluster(mObj_skinCluster)\n return mfnSkinCluster", "def update_weights(self):\n for layer in xrange(len(self.weights)):\n self.update_weights_layer(layer)", "def applySkinWeightsFromFile(filePath, *skins):\n with open(filePath, 'rb') as fp:\n content = fp.read()\n\n skinWeights = meta.decodeMetaData(content)\n applySkinWeightsMap(skinWeights, *skins)", "def update_weights(self) :\n for layer in self.layers :\n try:\n layer.update_weights()\n except Exception as e :\n pass", "def bootstrap_weights(self):\n if not self.configuration.get_bool('weighting'):\n return\n if self.configuration.is_configured('pixeldata'):\n return\n if self.configuration.get_bool('uniform'):\n return\n\n self.get_differential_channel_weights()\n self.channels.census()\n log.debug(f\"Bootstrapping pixel weights \"\n f\"({self.scan.channels.n_mapping_channels} \"\n f\"active channels).\")", "def rebuild(self, skinClusterList):\n # Start timer\n timer = cmds.timerX()\n\n # For Each SkinCluster\n for skinCluster in skinClusterList:\n\n # Check skinClusterData\n if not self._data.has_key(skinCluster):\n print('No data stored for skinCluster \"' + skinCluster + '\"! Skipping...')\n\n # Rebuild SkinCluster\n self._data[skinCluster].rebuild()\n\n # Print timed result\n totalTime = cmds.timerX(st=timer)\n print('SkinClusterListData: Total build time for skinCluster list: ' + str(skinTime))", "def get_clustered_weight(self, pulling_indices, original_weight):\n\n if self.cluster_gradient_aggregation == GradientAggregation.SUM:\n cluster_centroids = self.cluster_centroids\n elif self.cluster_gradient_aggregation == GradientAggregation.AVG:\n cluster_centroids = self.cluster_centroids\n # Compute the size of each cluster\n # (number of weights belonging to each cluster)\n cluster_sizes = tf.math.bincount(\n arr=tf.cast(pulling_indices, dtype=tf.int32),\n minlength=tf.size(cluster_centroids),\n dtype=cluster_centroids.dtype,\n )\n # Modify the gradient of cluster_centroids to be averaged by cluster sizes\n cluster_centroids = self.average_centroids_gradient_by_cluster_size(\n cluster_centroids,\n tf.stop_gradient(cluster_sizes),\n )\n else:\n raise ValueError(f\"self.cluster_gradient_aggregation=\"\n f\"{self.cluster_gradient_aggregation} not implemented.\")\n\n # Gather the clustered weights based on cluster centroids and\n # pulling indices.\n clustered_weight = tf.gather(cluster_centroids, pulling_indices)\n\n # Add an estimated gradient to the original weight\n clustered_weight = self.add_gradient_to_original_weight(\n clustered_weight,\n # Fix the bug with MirroredVariable and tf.custom_gradient:\n # tf.identity will transform a MirroredVariable into a Variable\n tf.identity(original_weight),\n )\n\n return clustered_weight", "def transfer_weights_replace(source, target):\n skinToReset = set()\n\n # TODO : Ensure that the transfered lockInfluenceWeight attr work correctly (The lock icon doesn't appear in the skinCluster)\n if source.hasAttr('lockInfluenceWeights'):\n attr_lockInfluenceWeights_src = source.lockInfluenceWeights\n # The target bone could possibly not have the attribute\n if target.hasAttr('lockInfluenceWeights'):\n attr_lockInfluenceWeights_dst = target.lockInfluenceWeights\n else:\n target.addAttr(\"lockInfluenceWeights\", at=\"bool\")\n attr_lockInfluenceWeights_dst = target.lockInfluenceWeights\n attr_lockInfluenceWeights_dst.set(attr_lockInfluenceWeights_src.get())\n for plug in attr_lockInfluenceWeights_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n skinToReset.add(plug.node())\n pymel.disconnectAttr(attr_lockInfluenceWeights_src, plug)\n pymel.connectAttr(attr_lockInfluenceWeights_dst, plug)\n\n attr_objectColorRGB_src = source.attr('objectColorRGB')\n attr_objectColorRGB_dst = target.attr('objectColorRGB')\n for plug in attr_objectColorRGB_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n pymel.disconnectAttr(attr_objectColorRGB_src, plug)\n pymel.connectAttr(attr_objectColorRGB_dst, plug)\n\n attr_worldMatrix_dst = target.worldMatrix\n for attr_worldMatrix_src in source.worldMatrix:\n for plug in attr_worldMatrix_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n pymel.disconnectAttr(attr_worldMatrix_src, plug)\n pymel.connectAttr(attr_worldMatrix_dst, plug)\n\n # HACK : Evaluate back all skinCluster in which we changed connections\n pymel.dgdirty(skinToReset)\n\n '''\n skinClusters = set()\n for source in sources:\n for hist in source.listHistory(future=True):\n if isinstance(hist, pymel.nodetypes.SkinCluster):\n skinClusters.add(hist)\n\n for skinCluster in skinClusters:\n for geo in skinCluster.getGeometry():\n # Only mesh are supported for now\n if not isinstance(geo, pymel.nodetypes.Mesh):\n continue\n\n try:\n transfer_weights(geo, sources, target, **kwargs)\n except ValueError: # jnt_dwn not in skinCluster\n pass\n '''", "def getSkinWeightsMap(*skins):\n skinWeights = {}\n for skin in skins:\n weights = getSkinWeights(skin)\n skinWeights[skin.nodeName()] = weights\n return skinWeights", "def copySkinWeights(noMirror=bool, noBlendWeight=bool, surfaceAssociation=\"string\", influenceAssociation=\"string\", smooth=bool, mirrorInverse=bool, sampleSpace=int, uvSpace=\"string\", sourceSkin=\"string\", normalize=bool, mirrorMode=\"string\", destinationSkin=\"string\"):\n pass", "def set_weights(self, weights):\n\n weight_index = 0\n for layer in self.NN:\n for node in layer:\n for i in range(len(node.weights)):\n #print(weight_index)\n try:\n node.weights[i] = weights[weight_index]\n except Exception as e:\n print(weight_index)\n print(len(weights))\n sys.exit()\n\n weight_index += 1", "def __apply_weight_mask(self):\n with torch.no_grad():\n # apply the weight mask\n for para in self.weights:\n if para in self.weight_mask:\n self.weights[para].data *= self.weight_mask[para].data", "def skinCluster(dropoffRate=float, before=bool, exclusive=\"string\", split=bool, after=bool, smoothWeights=float, ignoreSelected=bool, nurbsSamples=int, ignoreHierarchy=bool, ignoreBindPose=bool, includeHiddenSelections=bool, weightDistribution=int, smoothWeightsMaxIterations=int, frontOfChain=bool, prune=bool, weight=float, normalizeWeights=int, baseShape=\"string\", volumeType=int, skinMethod=int, heatmapFalloff=float, obeyMaxInfluences=bool, unbind=bool, removeInfluence=\"string\", volumeBind=float, geometry=\"string\", useGeometry=bool, name=\"string\", unbindKeepHistory=bool, weightedInfluence=bool, moveJointsMode=bool, removeUnusedInfluence=bool, influence=\"string\", bindMethod=int, parallel=bool, forceNormalizeWeights=bool, addInfluence=\"string\", geometryIndices=bool, polySmoothness=float, afterReference=bool, remove=bool, maximumInfluences=int, selectInfluenceVerts=\"string\", addToSelection=bool, lockWeights=bool, deformerTools=bool, removeFromSelection=bool, recacheBindMatrices=bool, toSkeletonAndTransforms=bool, toSelectedBones=bool):\n pass", "def process_cluster(self, cluster):\n raise NotImplementedError", "def _update_weights(self, _batch_weight_gradients):\n for _weight_gradient in _batch_weight_gradients:\n _weight_gradient = list(reversed(_weight_gradient))\n for _layer in reversed(range(len(self._layers))):\n self._layers[_layer].update_weights(-self._learning_rate*_weight_gradient[_layer])" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply the stored skinCluster weights.
def loadWeights(self, skinCluster=None, influenceList=None, componentList=None, normalize=True): # ========== # - Checks - # ========== # Check SkinCluster if not skinCluster: skinCluster = self._data['name'] self.verifySkinCluster(skinCluster) # Check Geometry skinGeo = self._data['affectedGeometry'][0] if not cmds.objExists(skinGeo): raise Exception( 'SkinCluster geometry "' + skinGeo + '" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!') # Check Influence List if not influenceList: influenceList = self._influenceData.keys() or [] for influence in influenceList: if not influence in cmds.skinCluster(skinCluster, q=True, inf=True) or []: raise Exception( 'Object "' + influence + '" is not a valid influence of skinCluster "' + skinCluster + '"! Unable to load influence weights...') if not self._influenceData.has_key(influence): raise Exception('No influence data stored for "' + influence + '"! Unable to load influence weights...') # Check Component List if not componentList: componentList = glTools.utils.component.getComponentStrList(skinGeo) componentSel = glTools.utils.selection.getSelectionElement(componentList, 0) # Get Component Index List # indexList = OpenMaya.MIntArray() # componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1]) # componentFn.getElements(indexList) # componentIndexList = list(indexList) componentIndexList = glTools.utils.component.getSingleIndexComponentList(componentList) componentIndexList = componentIndexList[componentIndexList.keys()[0]] # ===================================== # - Set SkinCluster Influence Weights - # ===================================== # Get Influence Index infIndexArray = OpenMaya.MIntArray() for influence in influenceList: infIndex = glTools.utils.skinCluster.getInfluencePhysicalIndex(skinCluster, influence) infIndexArray.append(infIndex) # Build Weight Array wtArray = OpenMaya.MDoubleArray() oldWtArray = OpenMaya.MDoubleArray() for c in componentIndexList: for i in range(len(influenceList)): if self._influenceData.has_key(influenceList[i]): wtArray.append(self._influenceData[influenceList[i]]['wt'][c]) else: wtArray.append(0.0) # Get skinCluster function set skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster) # Set skinCluster weights skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, normalize, oldWtArray) # ================= # - Return Result - # ================= return list(wtArray)
[ "def setWeights(self, componentList=[]):\n print('!!! - DEPRICATED: skinClusterData.setWeights()! Use loadWeights() method instead - !!!')\n\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Component List\n if not componentList: componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n indexList = OpenMaya.MIntArray()\n componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n componentFn.getElements(indexList)\n componentIndexList = list(indexList)\n\n # ===========================\n # - Set SkinCluster Weights -\n # ===========================\n\n # Build influence index array\n infIndexArray = OpenMaya.MIntArray()\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n [infIndexArray.append(i) for i in range(len(influenceList))]\n\n # Build master weight array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, False, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return influenceList", "def normalizeSkinWeights(skin):\n weights = getSkinWeights(skin)\n normWeights = normalizeWeightsData(weights)\n setSkinWeights(skin, normWeights)", "def update_weights(self):\n for layer in xrange(len(self.weights)):\n self.update_weights_layer(layer)", "def bootstrap_weights(self):\n if not self.configuration.get_bool('weighting'):\n return\n if self.configuration.is_configured('pixeldata'):\n return\n if self.configuration.get_bool('uniform'):\n return\n\n self.get_differential_channel_weights()\n self.channels.census()\n log.debug(f\"Bootstrapping pixel weights \"\n f\"({self.scan.channels.n_mapping_channels} \"\n f\"active channels).\")", "def update_weights(self) :\n for layer in self.layers :\n try:\n layer.update_weights()\n except Exception as e :\n pass", "def rebuild(self):\n # ==========\n # - Checks -\n # ==========\n\n # Check geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data for a different geometry!')\n\n # =======================\n # - Rebuild SkinCluster -\n # =======================\n\n # Start timer\n timer = cmds.timerX()\n\n # Initialize Temp Joint\n tempJnt = ''\n\n # Unlock Influences\n influenceList = self._influenceData.keys()\n for influence in influenceList:\n if cmds.objExists(influence + '.liw'):\n if cmds.getAttr(influence + '.liw', l=True):\n try:\n cmds.setAttr(influence + '.liw', l=False)\n except:\n print(\n 'Error unlocking attribute \"' + influence + '.liw\"! This could problems when rebuilding the skinCluster...')\n if cmds.getAttr(influence + '.liw'):\n try:\n cmds.setAttr(influence + '.liw', False)\n except:\n print(\n 'Error setting attribute \"' + influence + '.liw\" to False! This could problems when rebuilding the skinCluster...')\n\n # Check SkinCluster\n skinCluster = self._data['name']\n if not cmds.objExists(skinCluster):\n\n # Get Transform Influences\n jointList = [inf for inf in influenceList if not self._influenceData[inf]['type']]\n\n # Check Transform Influences\n if not jointList:\n\n # Create Temporary Bind Joint\n cmds.select(cl=1)\n tempJnt = cmds.joint(n=skinCluster + '_tempJoint')\n print(\n 'No transform influences specified for skinCluster \"' + skinCluster + '\"! Creating temporary bind joint \"' + tempJnt + '\"!')\n jointList = [tempJnt]\n\n else:\n\n # Get Surface Influences\n influenceList = [inf for inf in influenceList if self._influenceData[inf]['type']]\n\n # Create skinCluster\n skinCluster = cmds.skinCluster(jointList, skinGeo, tsb=True, n=skinCluster)[0]\n\n else:\n\n # Check Existing SkinCluster\n affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster)\n if affectedGeo.keys()[0] != skinGeo:\n raise Exception(\n 'SkinCluster \"' + skinCluster + '\" already exists, but is not connected to the expeced geometry \"' + skinGeo + '\"!')\n\n # Add skinCluster influences\n for influence in influenceList:\n\n # Check influence\n if not cmds.objExists(influence):\n raise Exception(\n 'Influence \"' + influence + '\" does not exist! Use remapInfluence() to apply data to a different influence!')\n\n # Check existing influence connection\n if not cmds.skinCluster(skinCluster, q=True, inf=True).count(influence):\n\n # Add influence\n if self._influenceData[influence]['type']:\n # Geometry\n polySmooth = self._influenceData[influence]['polySmooth']\n nurbsSamples = self._influenceData[influence]['nurbsSamples']\n cmds.skinCluster(skinCluster, e=True, ai=influence, ug=True, ps=polySmooth, ns=nurbsSamples, wt=0.0,\n lockWeights=True)\n\n else:\n # Transform\n cmds.skinCluster(skinCluster, e=True, ai=influence, wt=0.0, lockWeights=True)\n\n # Bind Pre Matrix\n if self._influenceData[influence]['bindPreMatrix']:\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n cmds.connectAttr(self._influenceData[influence]['bindPreMatrix'],\n skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', f=True)\n\n # Load skinCluster weights\n cmds.setAttr(skinCluster + '.normalizeWeights', 0)\n glTools.utils.skinCluster.clearWeights(skinGeo)\n self.loadWeights()\n cmds.setAttr(skinCluster + '.normalizeWeights', 1)\n\n # Restore Custom Attribute Values and Connections\n self.setDeformerAttrValues()\n self.setDeformerAttrConnections()\n\n # Clear Selection\n cmds.select(cl=True)\n\n # =================\n # - Return Result -\n # =================\n\n # Print Timed Result\n totalTime = cmds.timerX(st=timer)\n print('SkinClusterData: Rebuild time for skinCluster \"' + skinCluster + '\": ' + str(totalTime))\n\n return skinCluster", "def __apply_weight_mask(self):\n with torch.no_grad():\n # apply the weight mask\n for para in self.weights:\n if para in self.weight_mask:\n self.weights[para].data *= self.weight_mask[para].data", "def _update_weighted_matrix(self) -> None:\n self.weighted_map = deepcopy(self.map)\n for connection in self.weighted_map:\n connections = self.weighted_map[connection]\n connections_count = sum(list(connections.values()))\n for key in self.weighted_map[connection]:\n self.weighted_map[connection][key] /= connections_count", "def set_weights(self, weights):\n\n weight_index = 0\n for layer in self.NN:\n for node in layer:\n for i in range(len(node.weights)):\n #print(weight_index)\n try:\n node.weights[i] = weights[weight_index]\n except Exception as e:\n print(weight_index)\n print(len(weights))\n sys.exit()\n\n weight_index += 1", "def _assign_node_weights(self):\n _CONFIG_SERVER_SCORE = 11\n _QUORUM_MANAGER_SCORE = 8\n _QUORUM_SCORE = 5\n _MANAGER_SCORE = 3\n _CLIENT_SCORE = 1\n\n for node in self.state['nodes'].keys():\n\n fullname = self.state['nodes'][node]['admin_node_name']\n\n if self.state['nodes'][node]['roles'] == 'quorum-manager':\n self.state['nodes'][node]['weight'] = _QUORUM_MANAGER_SCORE\n elif self.state['nodes'][node]['roles'] == 'quorum':\n self.state['nodes'][node]['weight'] = _QUORUM_SCORE\n elif self.state['nodes'][node]['roles'] == 'manager':\n self.state['nodes'][node]['weight'] = _MANAGER_SCORE\n else:\n self.state['nodes'][node]['weight'] = _CLIENT_SCORE\n\n\n # check to see if node is primary/secondary config server\n # - don't want them both in the same group\n if self.state['primary_server'] == fullname or \\\n self.state['secondary_server'] == fullname:\n self.state['nodes'][node]['weight'] = _CONFIG_SERVER_SCORE\n \n\n return", "def init_weights(self):\n def special_initilization(m):\n classname = m.__class__.__name__\n if 'Conv' in classname:\n nn.init.xavier_normal_(m.weight.data)\n elif 'InstanceNorm' in classname:\n nn.init.normal_(m.weight.data, 1.0, 0.02)\n nn.init.constant_(m.bias.data, 0.0)\n if self.backbone_name not in ['res18']:\n self.apply(special_initilization)\n self.lut_generator.init_weights()\n if self.en_adaint:\n self.adaint.init_weights()", "def do_change_nodes_weight(self, args):\n node_strings = args.nodes.split(',')\n lb = self.findlb(args.loadbalancer)\n for n in lb.nodes:\n destination = \"%s:%d\" % (n.address, n.port)\n if destination in node_strings:\n n.weight = args.weight\n n.update()", "def copy_weights(self, model):\n for layer in model.layers:\n weights = layer.get_weights()\n self.layer_map[layer.name].set_weights(weights)", "def init_weights(self):\r\n default_init_weights(self, 1)", "def aggregate_weights(self, clients_params):", "def applySkinWeightsFromFile(filePath, *skins):\n with open(filePath, 'rb') as fp:\n content = fp.read()\n\n skinWeights = meta.decodeMetaData(content)\n applySkinWeightsMap(skinWeights, *skins)", "def set_weights(self, weights):\n self.actor_critic.load_state_dict(weights)\n self.alpha_optimizer.step()\n self.alpha = self.log_alpha.detach().exp()\n\n # Update target networks by polyak averaging.\n self.iter += 1\n self.update_target_networks()", "def init_weights(self):\n # Prune heads if needed\n if self.config.pruned_heads:\n self.prune_heads(self.config.pruned_heads)\n\n self.apply(self._init_weights)\n\n # Tie weights should be skipped when not initializing all weights\n # since from_pretrained(...) calls tie weights anyways\n self.tie_weights()", "def get_clustered_weight(self, pulling_indices, original_weight):\n\n if self.cluster_gradient_aggregation == GradientAggregation.SUM:\n cluster_centroids = self.cluster_centroids\n elif self.cluster_gradient_aggregation == GradientAggregation.AVG:\n cluster_centroids = self.cluster_centroids\n # Compute the size of each cluster\n # (number of weights belonging to each cluster)\n cluster_sizes = tf.math.bincount(\n arr=tf.cast(pulling_indices, dtype=tf.int32),\n minlength=tf.size(cluster_centroids),\n dtype=cluster_centroids.dtype,\n )\n # Modify the gradient of cluster_centroids to be averaged by cluster sizes\n cluster_centroids = self.average_centroids_gradient_by_cluster_size(\n cluster_centroids,\n tf.stop_gradient(cluster_sizes),\n )\n else:\n raise ValueError(f\"self.cluster_gradient_aggregation=\"\n f\"{self.cluster_gradient_aggregation} not implemented.\")\n\n # Gather the clustered weights based on cluster centroids and\n # pulling indices.\n clustered_weight = tf.gather(cluster_centroids, pulling_indices)\n\n # Add an estimated gradient to the original weight\n clustered_weight = self.add_gradient_to_original_weight(\n clustered_weight,\n # Fix the bug with MirroredVariable and tf.custom_gradient:\n # tf.identity will transform a MirroredVariable into a Variable\n tf.identity(original_weight),\n )\n\n return clustered_weight" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Swap influence weight values between 2 skinCluster influeneces.
def swapWeights(self, inf1, inf2): # Check Influences if not self._influenceData.has_key(inf1): raise Exception('No influence data for "' + inf1 + '"! Unable to swap weights...') if not self._influenceData.has_key(inf2): raise Exception('No influence data for "' + inf2 + '"! Unable to swap weights...') # Swap Weights self._influenceData[inf1]['wt'][:], self._influenceData[inf2]['wt'][:] = self._influenceData[inf2]['wt'][:], \ self._influenceData[inf1]['wt'][:] # Return Result print('SkinClusterData: Swap Weights Complete - "' + inf1 + '" <> "' + inf2 + '"')
[ "def transfer_weights_replace(source, target):\n skinToReset = set()\n\n # TODO : Ensure that the transfered lockInfluenceWeight attr work correctly (The lock icon doesn't appear in the skinCluster)\n if source.hasAttr('lockInfluenceWeights'):\n attr_lockInfluenceWeights_src = source.lockInfluenceWeights\n # The target bone could possibly not have the attribute\n if target.hasAttr('lockInfluenceWeights'):\n attr_lockInfluenceWeights_dst = target.lockInfluenceWeights\n else:\n target.addAttr(\"lockInfluenceWeights\", at=\"bool\")\n attr_lockInfluenceWeights_dst = target.lockInfluenceWeights\n attr_lockInfluenceWeights_dst.set(attr_lockInfluenceWeights_src.get())\n for plug in attr_lockInfluenceWeights_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n skinToReset.add(plug.node())\n pymel.disconnectAttr(attr_lockInfluenceWeights_src, plug)\n pymel.connectAttr(attr_lockInfluenceWeights_dst, plug)\n\n attr_objectColorRGB_src = source.attr('objectColorRGB')\n attr_objectColorRGB_dst = target.attr('objectColorRGB')\n for plug in attr_objectColorRGB_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n pymel.disconnectAttr(attr_objectColorRGB_src, plug)\n pymel.connectAttr(attr_objectColorRGB_dst, plug)\n\n attr_worldMatrix_dst = target.worldMatrix\n for attr_worldMatrix_src in source.worldMatrix:\n for plug in attr_worldMatrix_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n pymel.disconnectAttr(attr_worldMatrix_src, plug)\n pymel.connectAttr(attr_worldMatrix_dst, plug)\n\n # HACK : Evaluate back all skinCluster in which we changed connections\n pymel.dgdirty(skinToReset)\n\n '''\n skinClusters = set()\n for source in sources:\n for hist in source.listHistory(future=True):\n if isinstance(hist, pymel.nodetypes.SkinCluster):\n skinClusters.add(hist)\n\n for skinCluster in skinClusters:\n for geo in skinCluster.getGeometry():\n # Only mesh are supported for now\n if not isinstance(geo, pymel.nodetypes.Mesh):\n continue\n\n try:\n transfer_weights(geo, sources, target, **kwargs)\n except ValueError: # jnt_dwn not in skinCluster\n pass\n '''", "def normalizeSkinWeights(skin):\n weights = getSkinWeights(skin)\n normWeights = normalizeWeightsData(weights)\n setSkinWeights(skin, normWeights)", "def setWeights(self, componentList=[]):\n print('!!! - DEPRICATED: skinClusterData.setWeights()! Use loadWeights() method instead - !!!')\n\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Component List\n if not componentList: componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n indexList = OpenMaya.MIntArray()\n componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n componentFn.getElements(indexList)\n componentIndexList = list(indexList)\n\n # ===========================\n # - Set SkinCluster Weights -\n # ===========================\n\n # Build influence index array\n infIndexArray = OpenMaya.MIntArray()\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n [infIndexArray.append(i) for i in range(len(influenceList))]\n\n # Build master weight array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, False, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return influenceList", "def loadWeights(self,\n skinCluster=None,\n influenceList=None,\n componentList=None,\n normalize=True):\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n if not skinCluster: skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Influence List\n if not influenceList: influenceList = self._influenceData.keys() or []\n for influence in influenceList:\n if not influence in cmds.skinCluster(skinCluster, q=True, inf=True) or []:\n raise Exception(\n 'Object \"' + influence + '\" is not a valid influence of skinCluster \"' + skinCluster + '\"! Unable to load influence weights...')\n if not self._influenceData.has_key(influence):\n raise Exception('No influence data stored for \"' + influence + '\"! Unable to load influence weights...')\n\n # Check Component List\n if not componentList:\n componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n # indexList = OpenMaya.MIntArray()\n # componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n # componentFn.getElements(indexList)\n # componentIndexList = list(indexList)\n componentIndexList = glTools.utils.component.getSingleIndexComponentList(componentList)\n componentIndexList = componentIndexList[componentIndexList.keys()[0]]\n\n # =====================================\n # - Set SkinCluster Influence Weights -\n # =====================================\n\n # Get Influence Index\n infIndexArray = OpenMaya.MIntArray()\n for influence in influenceList:\n infIndex = glTools.utils.skinCluster.getInfluencePhysicalIndex(skinCluster, influence)\n infIndexArray.append(infIndex)\n\n # Build Weight Array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, normalize, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return list(wtArray)", "def copySkinWeights(noMirror=bool, noBlendWeight=bool, surfaceAssociation=\"string\", influenceAssociation=\"string\", smooth=bool, mirrorInverse=bool, sampleSpace=int, uvSpace=\"string\", sourceSkin=\"string\", normalize=bool, mirrorMode=\"string\", destinationSkin=\"string\"):\n pass", "def moveWeights(self, sourceInf, targetInf, mode='add'):\n # Check Influences\n if not self._influenceData.has_key(sourceInf):\n raise Exception('No influence data for source influence \"' + sourceInf + '\"! Unable to move weights...')\n if not self._influenceData.has_key(targetInf):\n raise Exception('No influence data for target influence \"' + targetInf + '\"! Unable to move weights...')\n\n # Check Mode\n if not ['add', 'replace'].count(mode):\n raise Exception('Invalid mode value (\"' + mode + '\")!')\n\n # Move Weights\n sourceWt = self._influenceData[sourceInf]['wt']\n targetWt = self._influenceData[targetInf]['wt']\n if mode == 'add':\n self._influenceData[targetInf]['wt'] = [i[0] + i[1] for i in zip(sourceWt, targetWt)]\n elif mode == 'replace':\n self._influenceData[targetInf]['wt'] = [i for i in sourceWt]\n self._influenceData[sourceInf]['wt'] = [0.0 for i in sourceWt]\n\n # Return Result\n print('SkinClusterData: Move Weights Complete - \"' + sourceInf + '\" >> \"' + targetInf + '\"')", "def update(self):\n self.weight_mom[self.index] = self.sub_weight_mom\n self.weight[self.index] = self.sub_weight", "def translate_weights(self):\n pass", "def update_weights(self):\n for layer in xrange(len(self.weights)):\n self.update_weights_layer(layer)", "def rebuild(self):\n # ==========\n # - Checks -\n # ==========\n\n # Check geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data for a different geometry!')\n\n # =======================\n # - Rebuild SkinCluster -\n # =======================\n\n # Start timer\n timer = cmds.timerX()\n\n # Initialize Temp Joint\n tempJnt = ''\n\n # Unlock Influences\n influenceList = self._influenceData.keys()\n for influence in influenceList:\n if cmds.objExists(influence + '.liw'):\n if cmds.getAttr(influence + '.liw', l=True):\n try:\n cmds.setAttr(influence + '.liw', l=False)\n except:\n print(\n 'Error unlocking attribute \"' + influence + '.liw\"! This could problems when rebuilding the skinCluster...')\n if cmds.getAttr(influence + '.liw'):\n try:\n cmds.setAttr(influence + '.liw', False)\n except:\n print(\n 'Error setting attribute \"' + influence + '.liw\" to False! This could problems when rebuilding the skinCluster...')\n\n # Check SkinCluster\n skinCluster = self._data['name']\n if not cmds.objExists(skinCluster):\n\n # Get Transform Influences\n jointList = [inf for inf in influenceList if not self._influenceData[inf]['type']]\n\n # Check Transform Influences\n if not jointList:\n\n # Create Temporary Bind Joint\n cmds.select(cl=1)\n tempJnt = cmds.joint(n=skinCluster + '_tempJoint')\n print(\n 'No transform influences specified for skinCluster \"' + skinCluster + '\"! Creating temporary bind joint \"' + tempJnt + '\"!')\n jointList = [tempJnt]\n\n else:\n\n # Get Surface Influences\n influenceList = [inf for inf in influenceList if self._influenceData[inf]['type']]\n\n # Create skinCluster\n skinCluster = cmds.skinCluster(jointList, skinGeo, tsb=True, n=skinCluster)[0]\n\n else:\n\n # Check Existing SkinCluster\n affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster)\n if affectedGeo.keys()[0] != skinGeo:\n raise Exception(\n 'SkinCluster \"' + skinCluster + '\" already exists, but is not connected to the expeced geometry \"' + skinGeo + '\"!')\n\n # Add skinCluster influences\n for influence in influenceList:\n\n # Check influence\n if not cmds.objExists(influence):\n raise Exception(\n 'Influence \"' + influence + '\" does not exist! Use remapInfluence() to apply data to a different influence!')\n\n # Check existing influence connection\n if not cmds.skinCluster(skinCluster, q=True, inf=True).count(influence):\n\n # Add influence\n if self._influenceData[influence]['type']:\n # Geometry\n polySmooth = self._influenceData[influence]['polySmooth']\n nurbsSamples = self._influenceData[influence]['nurbsSamples']\n cmds.skinCluster(skinCluster, e=True, ai=influence, ug=True, ps=polySmooth, ns=nurbsSamples, wt=0.0,\n lockWeights=True)\n\n else:\n # Transform\n cmds.skinCluster(skinCluster, e=True, ai=influence, wt=0.0, lockWeights=True)\n\n # Bind Pre Matrix\n if self._influenceData[influence]['bindPreMatrix']:\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n cmds.connectAttr(self._influenceData[influence]['bindPreMatrix'],\n skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', f=True)\n\n # Load skinCluster weights\n cmds.setAttr(skinCluster + '.normalizeWeights', 0)\n glTools.utils.skinCluster.clearWeights(skinGeo)\n self.loadWeights()\n cmds.setAttr(skinCluster + '.normalizeWeights', 1)\n\n # Restore Custom Attribute Values and Connections\n self.setDeformerAttrValues()\n self.setDeformerAttrConnections()\n\n # Clear Selection\n cmds.select(cl=True)\n\n # =================\n # - Return Result -\n # =================\n\n # Print Timed Result\n totalTime = cmds.timerX(st=timer)\n print('SkinClusterData: Rebuild time for skinCluster \"' + skinCluster + '\": ' + str(totalTime))\n\n return skinCluster", "def do_change_nodes_weight(self, args):\n node_strings = args.nodes.split(',')\n lb = self.findlb(args.loadbalancer)\n for n in lb.nodes:\n destination = \"%s:%d\" % (n.address, n.port)\n if destination in node_strings:\n n.weight = args.weight\n n.update()", "def updateWeights(self, initialInputs):\n self.firstLayer.updateWeight(initialInputs)", "def _lockup_weights_one(self):\n for i in self._lockup_weights_ind:\n self.reward_weights[i] = 1.0", "def set_weights(self, weights):\n\n weight_index = 0\n for layer in self.NN:\n for node in layer:\n for i in range(len(node.weights)):\n #print(weight_index)\n try:\n node.weights[i] = weights[weight_index]\n except Exception as e:\n print(weight_index)\n print(len(weights))\n sys.exit()\n\n weight_index += 1", "def saliencyExchange(S,inst1, inst2, ratio):\n # darken the original salient instance\n box = inst1['bbox']\n for seg in inst1['segmentation']:\n poly = np.array(seg).reshape((-1,2)) \n swap_cols(poly,0,1)\n #print(\"origin salient \", poly.shape)\n polyPath = mplpath.Path(poly)\n darken(S, box, polyPath, ratio)\n # brighten the new salient instance \n box =inst2['bbox']\n for seg in inst2['segmentation']:\n poly = np.array(seg).reshape((-1,2)) \n swap_cols(poly,0,1)\n #print(\"new_salient\" , poly.shape)\n polyPath = mplpath.Path(poly)\n brighten(S, box,polyPath, ratio)", "def adjust_weight(self, new_weight):\n self.weight = new_weight", "def set_weights(self, weights):\n self.weights = copy.deepcopy(weights)", "def update_weights(self) :\n for layer in self.layers :\n try:\n layer.update_weights()\n except Exception as e :\n pass", "def __set_blend_weights(self, dagpath, components):\n blendWeights = OpenMaya.MDoubleArray(len(self.data['blendWeights']))\n for i, w in enumerate(self.data['blendWeights']):\n blendWeights.set(w, i)\n self.fnSkinCluster.setBlendWeights(dagpath, components, blendWeights)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move influence weight values from one skinCluster influenece to another.
def moveWeights(self, sourceInf, targetInf, mode='add'): # Check Influences if not self._influenceData.has_key(sourceInf): raise Exception('No influence data for source influence "' + sourceInf + '"! Unable to move weights...') if not self._influenceData.has_key(targetInf): raise Exception('No influence data for target influence "' + targetInf + '"! Unable to move weights...') # Check Mode if not ['add', 'replace'].count(mode): raise Exception('Invalid mode value ("' + mode + '")!') # Move Weights sourceWt = self._influenceData[sourceInf]['wt'] targetWt = self._influenceData[targetInf]['wt'] if mode == 'add': self._influenceData[targetInf]['wt'] = [i[0] + i[1] for i in zip(sourceWt, targetWt)] elif mode == 'replace': self._influenceData[targetInf]['wt'] = [i for i in sourceWt] self._influenceData[sourceInf]['wt'] = [0.0 for i in sourceWt] # Return Result print('SkinClusterData: Move Weights Complete - "' + sourceInf + '" >> "' + targetInf + '"')
[ "def transfer_weights_replace(source, target):\n skinToReset = set()\n\n # TODO : Ensure that the transfered lockInfluenceWeight attr work correctly (The lock icon doesn't appear in the skinCluster)\n if source.hasAttr('lockInfluenceWeights'):\n attr_lockInfluenceWeights_src = source.lockInfluenceWeights\n # The target bone could possibly not have the attribute\n if target.hasAttr('lockInfluenceWeights'):\n attr_lockInfluenceWeights_dst = target.lockInfluenceWeights\n else:\n target.addAttr(\"lockInfluenceWeights\", at=\"bool\")\n attr_lockInfluenceWeights_dst = target.lockInfluenceWeights\n attr_lockInfluenceWeights_dst.set(attr_lockInfluenceWeights_src.get())\n for plug in attr_lockInfluenceWeights_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n skinToReset.add(plug.node())\n pymel.disconnectAttr(attr_lockInfluenceWeights_src, plug)\n pymel.connectAttr(attr_lockInfluenceWeights_dst, plug)\n\n attr_objectColorRGB_src = source.attr('objectColorRGB')\n attr_objectColorRGB_dst = target.attr('objectColorRGB')\n for plug in attr_objectColorRGB_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n pymel.disconnectAttr(attr_objectColorRGB_src, plug)\n pymel.connectAttr(attr_objectColorRGB_dst, plug)\n\n attr_worldMatrix_dst = target.worldMatrix\n for attr_worldMatrix_src in source.worldMatrix:\n for plug in attr_worldMatrix_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n pymel.disconnectAttr(attr_worldMatrix_src, plug)\n pymel.connectAttr(attr_worldMatrix_dst, plug)\n\n # HACK : Evaluate back all skinCluster in which we changed connections\n pymel.dgdirty(skinToReset)\n\n '''\n skinClusters = set()\n for source in sources:\n for hist in source.listHistory(future=True):\n if isinstance(hist, pymel.nodetypes.SkinCluster):\n skinClusters.add(hist)\n\n for skinCluster in skinClusters:\n for geo in skinCluster.getGeometry():\n # Only mesh are supported for now\n if not isinstance(geo, pymel.nodetypes.Mesh):\n continue\n\n try:\n transfer_weights(geo, sources, target, **kwargs)\n except ValueError: # jnt_dwn not in skinCluster\n pass\n '''", "def swapWeights(self, inf1, inf2):\n # Check Influences\n if not self._influenceData.has_key(inf1):\n raise Exception('No influence data for \"' + inf1 + '\"! Unable to swap weights...')\n if not self._influenceData.has_key(inf2):\n raise Exception('No influence data for \"' + inf2 + '\"! Unable to swap weights...')\n\n # Swap Weights\n self._influenceData[inf1]['wt'][:], self._influenceData[inf2]['wt'][:] = self._influenceData[inf2]['wt'][:], \\\n self._influenceData[inf1]['wt'][:]\n\n # Return Result\n print('SkinClusterData: Swap Weights Complete - \"' + inf1 + '\" <> \"' + inf2 + '\"')", "def setWeights(self, componentList=[]):\n print('!!! - DEPRICATED: skinClusterData.setWeights()! Use loadWeights() method instead - !!!')\n\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Component List\n if not componentList: componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n indexList = OpenMaya.MIntArray()\n componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n componentFn.getElements(indexList)\n componentIndexList = list(indexList)\n\n # ===========================\n # - Set SkinCluster Weights -\n # ===========================\n\n # Build influence index array\n infIndexArray = OpenMaya.MIntArray()\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n [infIndexArray.append(i) for i in range(len(influenceList))]\n\n # Build master weight array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, False, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return influenceList", "def normalizeSkinWeights(skin):\n weights = getSkinWeights(skin)\n normWeights = normalizeWeightsData(weights)\n setSkinWeights(skin, normWeights)", "def loadWeights(self,\n skinCluster=None,\n influenceList=None,\n componentList=None,\n normalize=True):\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n if not skinCluster: skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Influence List\n if not influenceList: influenceList = self._influenceData.keys() or []\n for influence in influenceList:\n if not influence in cmds.skinCluster(skinCluster, q=True, inf=True) or []:\n raise Exception(\n 'Object \"' + influence + '\" is not a valid influence of skinCluster \"' + skinCluster + '\"! Unable to load influence weights...')\n if not self._influenceData.has_key(influence):\n raise Exception('No influence data stored for \"' + influence + '\"! Unable to load influence weights...')\n\n # Check Component List\n if not componentList:\n componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n # indexList = OpenMaya.MIntArray()\n # componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n # componentFn.getElements(indexList)\n # componentIndexList = list(indexList)\n componentIndexList = glTools.utils.component.getSingleIndexComponentList(componentList)\n componentIndexList = componentIndexList[componentIndexList.keys()[0]]\n\n # =====================================\n # - Set SkinCluster Influence Weights -\n # =====================================\n\n # Get Influence Index\n infIndexArray = OpenMaya.MIntArray()\n for influence in influenceList:\n infIndex = glTools.utils.skinCluster.getInfluencePhysicalIndex(skinCluster, influence)\n infIndexArray.append(infIndex)\n\n # Build Weight Array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, normalize, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return list(wtArray)", "def rebuild(self):\n # ==========\n # - Checks -\n # ==========\n\n # Check geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data for a different geometry!')\n\n # =======================\n # - Rebuild SkinCluster -\n # =======================\n\n # Start timer\n timer = cmds.timerX()\n\n # Initialize Temp Joint\n tempJnt = ''\n\n # Unlock Influences\n influenceList = self._influenceData.keys()\n for influence in influenceList:\n if cmds.objExists(influence + '.liw'):\n if cmds.getAttr(influence + '.liw', l=True):\n try:\n cmds.setAttr(influence + '.liw', l=False)\n except:\n print(\n 'Error unlocking attribute \"' + influence + '.liw\"! This could problems when rebuilding the skinCluster...')\n if cmds.getAttr(influence + '.liw'):\n try:\n cmds.setAttr(influence + '.liw', False)\n except:\n print(\n 'Error setting attribute \"' + influence + '.liw\" to False! This could problems when rebuilding the skinCluster...')\n\n # Check SkinCluster\n skinCluster = self._data['name']\n if not cmds.objExists(skinCluster):\n\n # Get Transform Influences\n jointList = [inf for inf in influenceList if not self._influenceData[inf]['type']]\n\n # Check Transform Influences\n if not jointList:\n\n # Create Temporary Bind Joint\n cmds.select(cl=1)\n tempJnt = cmds.joint(n=skinCluster + '_tempJoint')\n print(\n 'No transform influences specified for skinCluster \"' + skinCluster + '\"! Creating temporary bind joint \"' + tempJnt + '\"!')\n jointList = [tempJnt]\n\n else:\n\n # Get Surface Influences\n influenceList = [inf for inf in influenceList if self._influenceData[inf]['type']]\n\n # Create skinCluster\n skinCluster = cmds.skinCluster(jointList, skinGeo, tsb=True, n=skinCluster)[0]\n\n else:\n\n # Check Existing SkinCluster\n affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster)\n if affectedGeo.keys()[0] != skinGeo:\n raise Exception(\n 'SkinCluster \"' + skinCluster + '\" already exists, but is not connected to the expeced geometry \"' + skinGeo + '\"!')\n\n # Add skinCluster influences\n for influence in influenceList:\n\n # Check influence\n if not cmds.objExists(influence):\n raise Exception(\n 'Influence \"' + influence + '\" does not exist! Use remapInfluence() to apply data to a different influence!')\n\n # Check existing influence connection\n if not cmds.skinCluster(skinCluster, q=True, inf=True).count(influence):\n\n # Add influence\n if self._influenceData[influence]['type']:\n # Geometry\n polySmooth = self._influenceData[influence]['polySmooth']\n nurbsSamples = self._influenceData[influence]['nurbsSamples']\n cmds.skinCluster(skinCluster, e=True, ai=influence, ug=True, ps=polySmooth, ns=nurbsSamples, wt=0.0,\n lockWeights=True)\n\n else:\n # Transform\n cmds.skinCluster(skinCluster, e=True, ai=influence, wt=0.0, lockWeights=True)\n\n # Bind Pre Matrix\n if self._influenceData[influence]['bindPreMatrix']:\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n cmds.connectAttr(self._influenceData[influence]['bindPreMatrix'],\n skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', f=True)\n\n # Load skinCluster weights\n cmds.setAttr(skinCluster + '.normalizeWeights', 0)\n glTools.utils.skinCluster.clearWeights(skinGeo)\n self.loadWeights()\n cmds.setAttr(skinCluster + '.normalizeWeights', 1)\n\n # Restore Custom Attribute Values and Connections\n self.setDeformerAttrValues()\n self.setDeformerAttrConnections()\n\n # Clear Selection\n cmds.select(cl=True)\n\n # =================\n # - Return Result -\n # =================\n\n # Print Timed Result\n totalTime = cmds.timerX(st=timer)\n print('SkinClusterData: Rebuild time for skinCluster \"' + skinCluster + '\": ' + str(totalTime))\n\n return skinCluster", "def update(self):\n self.weight_mom[self.index] = self.sub_weight_mom\n self.weight[self.index] = self.sub_weight", "def copySkinWeights(noMirror=bool, noBlendWeight=bool, surfaceAssociation=\"string\", influenceAssociation=\"string\", smooth=bool, mirrorInverse=bool, sampleSpace=int, uvSpace=\"string\", sourceSkin=\"string\", normalize=bool, mirrorMode=\"string\", destinationSkin=\"string\"):\n pass", "def do_change_nodes_weight(self, args):\n node_strings = args.nodes.split(',')\n lb = self.findlb(args.loadbalancer)\n for n in lb.nodes:\n destination = \"%s:%d\" % (n.address, n.port)\n if destination in node_strings:\n n.weight = args.weight\n n.update()", "def update_weights(self):\n for layer in xrange(len(self.weights)):\n self.update_weights_layer(layer)", "def translate_weights(self):\n pass", "def updateWeights(self, initialInputs):\n self.firstLayer.updateWeight(initialInputs)", "def adjust_weight(self, new_weight):\n self.weight = new_weight", "def update_target_model(self):\n self.target_network.set_weights(self.q_network.get_weights())\n # vedere se funziona invece questo\n #for t, e in zip(self.target_network.trainable_variables,\n # self.primary_network.trainable_variables): t.assign(t * (1 - TAU) + e * TAU)", "def set_weights(self, weights):\n\n weight_index = 0\n for layer in self.NN:\n for node in layer:\n for i in range(len(node.weights)):\n #print(weight_index)\n try:\n node.weights[i] = weights[weight_index]\n except Exception as e:\n print(weight_index)\n print(len(weights))\n sys.exit()\n\n weight_index += 1", "def update_weights(self) -> None:\n for neuron in self.__neurons__:\n neuron.update_weight(self.__inputs__)", "def test_move_weights_new_variable(self):\n python_tile = self.get_tile(2, 3)\n cpp_tile = python_tile.tile\n\n def to_shape(mat):\n if python_tile.is_cuda:\n shape = mat.shape\n return mat.T.copy().flatten().reshape(*shape)\n return mat\n\n # Read the weights.\n initial_weights = cpp_tile.get_weights()\n\n # Move the weights to a new shared variable.\n weights_holder = python_tile.move_weights()\n weights_clone = weights_holder.clone().cpu().numpy()\n assert_array_equal(weights_clone, to_shape(initial_weights))\n\n # Modify the shared variable manually.\n weights_holder.add_(0.123) # in place\n current_weights = cpp_tile.get_weights()\n weights_clone = weights_holder.clone().cpu().numpy()\n assert_array_equal(weights_clone, to_shape(current_weights))\n\n # Modify the weights manually.\n cpp_tile.set_weights([[.2, .2, .2], [.3, .3, .3]])\n current_weights = cpp_tile.get_weights()\n weights_clone = weights_holder.clone().cpu().numpy()\n assert_array_equal(weights_clone, to_shape(current_weights))", "def clampVertInfluenceCount(self):\n if self.geo is None:\n activeSelection = pm.ls(sl=True)\n if activeSelection:\n self.geo = activeSelection[0]\n else:\n raise Exception(\"Found no geometry, use 'geo' flag or select a mesh in the scene.\")\n\n skinCluster = pm.listHistory(self.geo, type='skinCluster')\n if not skinCluster:\n raise Exception(\"'{0}' is not deformed by a skinCluster\".format(self.geo))\n\n skinCluster = skinCluster[0]\n # get skin\n self.mfnSkinCluster = self.getMfnSkinCluster(skinCluster.name())\n\n if self.maxInfluences is None:\n self.maxInfluences = skinCluster.getMaximumInfluences()\n\n if self.maxInfluences < 1:\n raise ValueError(\"maxInfluences must be 1 or greater, not {0}\".format(self.maxInfluences))\n\n self.dagPath, self.components = self.getGeomInfo()\n # get flat weight list (see MFnSkinCluster.setWeights for a description)\n weights = self.gatherInfluenceWeights()\n # init new weight MDoubleArray\n newWeights = OpenMaya.MDoubleArray()\n\n mod_vert_count = 0\n\n for vertexId in range(self.numComponents):\n\n weightsPerComponent = weights[self.numInfluenceObj * vertexId: self.numInfluenceObj * vertexId + self.numInfluenceObj]\n\n influenceWeights = [(index, weight) for index, weight in enumerate(weightsPerComponent) if weight]\n\n if len(influenceWeights) > self.maxInfluences:\n mod_vert_count += 1\n\n newWeightsPerComponent = [0] * self.numInfluenceObj\n\n # sort by weight\n influenceWeights.sort(key=lambda x: x[1])\n # drop the lowest weights\n influencesToKeep = influenceWeights[-self.maxInfluences:]\n\n weightSum = sum([v for i, v in influencesToKeep])\n\n for i, v in influencesToKeep:\n newWeightsPerComponent[i] = v / weightSum\n\n for weight in newWeightsPerComponent:\n newWeights.append(weight)\n else:\n for weight in weightsPerComponent:\n newWeights.append(weight)\n\n self.setInfluenceWeights(newWeights)\n print '{0} verts were modified'.format(mod_vert_count)\n return mod_vert_count", "def set_weights(self, weights):\n self.weights = copy.deepcopy(weights)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combine stored skinCluster influence data from a list of source influences to a single target influence. Source influences data will be removed.
def combineInfluence(self, sourceInfluenceList, targetInfluence, removeSource=False): # =========================== # - Check Source Influences - # =========================== skipSource = [] for i in range(len(sourceInfluenceList)): # Check influence if not self._influenceData.has_key(sourceInfluenceList[i]): print('No data stored for influence "' + sourceInfluenceList[i] + '" in skinCluster "' + self._data[ 'name'] + '"! Skipping...') skipSource.append(sourceInfluenceList[i]) # ============================= # - Initialize Influence Data - # ============================= if list(set(sourceInfluenceList) - set(skipSource)): if not self._influenceData.has_key(targetInfluence): self._influenceData[targetInfluence] = {'index': 0, 'type': 0, 'bindPreMatrix': ''} else: return # ========================== # - Combine Influence Data - # ========================== wtList = [] for i in range(len(sourceInfluenceList)): # Get Source Influence sourceInfluence = sourceInfluenceList[i] # Check Skip Source if skipSource.count(sourceInfluence): continue # Get Basic Influence Data from first source influence if not i: # Index self._influenceData[targetInfluence]['index'] = self._influenceData[sourceInfluence]['index'] # Type self._influenceData[targetInfluence]['type'] = self._influenceData[sourceInfluence]['type'] # Poly Smooth if self._influenceData[sourceInfluence].has_key('polySmooth'): self._influenceData[targetInfluence]['polySmooth'] = self._influenceData[sourceInfluence][ 'polySmooth'] else: if self._influenceData[targetInfluence].has_key('polySmooth'): self._influenceData[targetInfluence].pop('polySmooth') # Nurbs Samples if self._influenceData[sourceInfluence].has_key('nurbsSamples'): self._influenceData[targetInfluence]['nurbsSamples'] = self._influenceData[sourceInfluence][ 'nurbsSamples'] else: if self._influenceData[targetInfluence].has_key('nurbsSamples'): self._influenceData[targetInfluence].pop('nurbsSamples') # Get Source Influence Weights wtList = self._influenceData[sourceInfluence]['wt'] else: if wtList: # Combine Source Influence Weights wtList = [(x + y) for x, y in zip(wtList, self._influenceData[sourceInfluence]['wt'])] else: wtList = self._influenceData[sourceInfluence]['wt'] # ================================== # - Assign Combined Source Weights - # ================================== self._influenceData[targetInfluence]['wt'] = wtList # ======================================= # - Remove Unused Source Influence Data - # ======================================= if removeSource: # For Each Source Influence for sourceInfluence in sourceInfluenceList: # Check Skip Source if skipSource.count(sourceInfluence): continue # Check Source/Target if sourceInfluence != targetInfluence: # Remove Unused Source Influence self._influenceData.pop(sourceInfluence)
[ "def transfer_weights_replace(source, target):\n skinToReset = set()\n\n # TODO : Ensure that the transfered lockInfluenceWeight attr work correctly (The lock icon doesn't appear in the skinCluster)\n if source.hasAttr('lockInfluenceWeights'):\n attr_lockInfluenceWeights_src = source.lockInfluenceWeights\n # The target bone could possibly not have the attribute\n if target.hasAttr('lockInfluenceWeights'):\n attr_lockInfluenceWeights_dst = target.lockInfluenceWeights\n else:\n target.addAttr(\"lockInfluenceWeights\", at=\"bool\")\n attr_lockInfluenceWeights_dst = target.lockInfluenceWeights\n attr_lockInfluenceWeights_dst.set(attr_lockInfluenceWeights_src.get())\n for plug in attr_lockInfluenceWeights_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n skinToReset.add(plug.node())\n pymel.disconnectAttr(attr_lockInfluenceWeights_src, plug)\n pymel.connectAttr(attr_lockInfluenceWeights_dst, plug)\n\n attr_objectColorRGB_src = source.attr('objectColorRGB')\n attr_objectColorRGB_dst = target.attr('objectColorRGB')\n for plug in attr_objectColorRGB_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n pymel.disconnectAttr(attr_objectColorRGB_src, plug)\n pymel.connectAttr(attr_objectColorRGB_dst, plug)\n\n attr_worldMatrix_dst = target.worldMatrix\n for attr_worldMatrix_src in source.worldMatrix:\n for plug in attr_worldMatrix_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n pymel.disconnectAttr(attr_worldMatrix_src, plug)\n pymel.connectAttr(attr_worldMatrix_dst, plug)\n\n # HACK : Evaluate back all skinCluster in which we changed connections\n pymel.dgdirty(skinToReset)\n\n '''\n skinClusters = set()\n for source in sources:\n for hist in source.listHistory(future=True):\n if isinstance(hist, pymel.nodetypes.SkinCluster):\n skinClusters.add(hist)\n\n for skinCluster in skinClusters:\n for geo in skinCluster.getGeometry():\n # Only mesh are supported for now\n if not isinstance(geo, pymel.nodetypes.Mesh):\n continue\n\n try:\n transfer_weights(geo, sources, target, **kwargs)\n except ValueError: # jnt_dwn not in skinCluster\n pass\n '''", "def loadWeights(self,\n skinCluster=None,\n influenceList=None,\n componentList=None,\n normalize=True):\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n if not skinCluster: skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Influence List\n if not influenceList: influenceList = self._influenceData.keys() or []\n for influence in influenceList:\n if not influence in cmds.skinCluster(skinCluster, q=True, inf=True) or []:\n raise Exception(\n 'Object \"' + influence + '\" is not a valid influence of skinCluster \"' + skinCluster + '\"! Unable to load influence weights...')\n if not self._influenceData.has_key(influence):\n raise Exception('No influence data stored for \"' + influence + '\"! Unable to load influence weights...')\n\n # Check Component List\n if not componentList:\n componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n # indexList = OpenMaya.MIntArray()\n # componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n # componentFn.getElements(indexList)\n # componentIndexList = list(indexList)\n componentIndexList = glTools.utils.component.getSingleIndexComponentList(componentList)\n componentIndexList = componentIndexList[componentIndexList.keys()[0]]\n\n # =====================================\n # - Set SkinCluster Influence Weights -\n # =====================================\n\n # Get Influence Index\n infIndexArray = OpenMaya.MIntArray()\n for influence in influenceList:\n infIndex = glTools.utils.skinCluster.getInfluencePhysicalIndex(skinCluster, influence)\n infIndexArray.append(infIndex)\n\n # Build Weight Array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, normalize, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return list(wtArray)", "def setWeights(self, componentList=[]):\n print('!!! - DEPRICATED: skinClusterData.setWeights()! Use loadWeights() method instead - !!!')\n\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Component List\n if not componentList: componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n indexList = OpenMaya.MIntArray()\n componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n componentFn.getElements(indexList)\n componentIndexList = list(indexList)\n\n # ===========================\n # - Set SkinCluster Weights -\n # ===========================\n\n # Build influence index array\n infIndexArray = OpenMaya.MIntArray()\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n [infIndexArray.append(i) for i in range(len(influenceList))]\n\n # Build master weight array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, False, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return influenceList", "def merge_snapshots(target, list_source):\n for d in list_source:\n for edge in graph_dict[d].edges(data=True):\n if graph_dict[target].has_edge(edge[0], edge[1]):\n graph_dict[target].edge[edge[0]][edge[1]]['weight'] += graph_dict[d].edge[edge[0]][edge[1]]['weight']\n else:\n graph_dict[target].add_edge(edge[0], edge[1], weight=edge[2]['weight'])\n del graph_dict[d]", "def moveWeights(self, sourceInf, targetInf, mode='add'):\n # Check Influences\n if not self._influenceData.has_key(sourceInf):\n raise Exception('No influence data for source influence \"' + sourceInf + '\"! Unable to move weights...')\n if not self._influenceData.has_key(targetInf):\n raise Exception('No influence data for target influence \"' + targetInf + '\"! Unable to move weights...')\n\n # Check Mode\n if not ['add', 'replace'].count(mode):\n raise Exception('Invalid mode value (\"' + mode + '\")!')\n\n # Move Weights\n sourceWt = self._influenceData[sourceInf]['wt']\n targetWt = self._influenceData[targetInf]['wt']\n if mode == 'add':\n self._influenceData[targetInf]['wt'] = [i[0] + i[1] for i in zip(sourceWt, targetWt)]\n elif mode == 'replace':\n self._influenceData[targetInf]['wt'] = [i for i in sourceWt]\n self._influenceData[sourceInf]['wt'] = [0.0 for i in sourceWt]\n\n # Return Result\n print('SkinClusterData: Move Weights Complete - \"' + sourceInf + '\" >> \"' + targetInf + '\"')", "def rebuild(self):\n # ==========\n # - Checks -\n # ==========\n\n # Check geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data for a different geometry!')\n\n # =======================\n # - Rebuild SkinCluster -\n # =======================\n\n # Start timer\n timer = cmds.timerX()\n\n # Initialize Temp Joint\n tempJnt = ''\n\n # Unlock Influences\n influenceList = self._influenceData.keys()\n for influence in influenceList:\n if cmds.objExists(influence + '.liw'):\n if cmds.getAttr(influence + '.liw', l=True):\n try:\n cmds.setAttr(influence + '.liw', l=False)\n except:\n print(\n 'Error unlocking attribute \"' + influence + '.liw\"! This could problems when rebuilding the skinCluster...')\n if cmds.getAttr(influence + '.liw'):\n try:\n cmds.setAttr(influence + '.liw', False)\n except:\n print(\n 'Error setting attribute \"' + influence + '.liw\" to False! This could problems when rebuilding the skinCluster...')\n\n # Check SkinCluster\n skinCluster = self._data['name']\n if not cmds.objExists(skinCluster):\n\n # Get Transform Influences\n jointList = [inf for inf in influenceList if not self._influenceData[inf]['type']]\n\n # Check Transform Influences\n if not jointList:\n\n # Create Temporary Bind Joint\n cmds.select(cl=1)\n tempJnt = cmds.joint(n=skinCluster + '_tempJoint')\n print(\n 'No transform influences specified for skinCluster \"' + skinCluster + '\"! Creating temporary bind joint \"' + tempJnt + '\"!')\n jointList = [tempJnt]\n\n else:\n\n # Get Surface Influences\n influenceList = [inf for inf in influenceList if self._influenceData[inf]['type']]\n\n # Create skinCluster\n skinCluster = cmds.skinCluster(jointList, skinGeo, tsb=True, n=skinCluster)[0]\n\n else:\n\n # Check Existing SkinCluster\n affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster)\n if affectedGeo.keys()[0] != skinGeo:\n raise Exception(\n 'SkinCluster \"' + skinCluster + '\" already exists, but is not connected to the expeced geometry \"' + skinGeo + '\"!')\n\n # Add skinCluster influences\n for influence in influenceList:\n\n # Check influence\n if not cmds.objExists(influence):\n raise Exception(\n 'Influence \"' + influence + '\" does not exist! Use remapInfluence() to apply data to a different influence!')\n\n # Check existing influence connection\n if not cmds.skinCluster(skinCluster, q=True, inf=True).count(influence):\n\n # Add influence\n if self._influenceData[influence]['type']:\n # Geometry\n polySmooth = self._influenceData[influence]['polySmooth']\n nurbsSamples = self._influenceData[influence]['nurbsSamples']\n cmds.skinCluster(skinCluster, e=True, ai=influence, ug=True, ps=polySmooth, ns=nurbsSamples, wt=0.0,\n lockWeights=True)\n\n else:\n # Transform\n cmds.skinCluster(skinCluster, e=True, ai=influence, wt=0.0, lockWeights=True)\n\n # Bind Pre Matrix\n if self._influenceData[influence]['bindPreMatrix']:\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n cmds.connectAttr(self._influenceData[influence]['bindPreMatrix'],\n skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', f=True)\n\n # Load skinCluster weights\n cmds.setAttr(skinCluster + '.normalizeWeights', 0)\n glTools.utils.skinCluster.clearWeights(skinGeo)\n self.loadWeights()\n cmds.setAttr(skinCluster + '.normalizeWeights', 1)\n\n # Restore Custom Attribute Values and Connections\n self.setDeformerAttrValues()\n self.setDeformerAttrConnections()\n\n # Clear Selection\n cmds.select(cl=True)\n\n # =================\n # - Return Result -\n # =================\n\n # Print Timed Result\n totalTime = cmds.timerX(st=timer)\n print('SkinClusterData: Rebuild time for skinCluster \"' + skinCluster + '\": ' + str(totalTime))\n\n return skinCluster", "def mix_weighted(file_list, weights, output_file):\n args = [\"sox\", \"-m\"]\n for fname, weight in zip(file_list, weights):\n args.append(\"-v\")\n args.append(str(weight))\n args.append(fname)\n args.append(output_file)\n\n return sox(args)", "def copy_alembic_data(cls, source=None, target=None):\n selection = pm.ls(sl=1)\n if not source or not target:\n source = selection[0]\n target = selection[1]\n\n #\n # Move Alembic Data From Source To Target\n #\n # selection = pm.ls(sl=1)\n #\n # source = selection[0]\n # target = selection[1]\n\n source_nodes = source.listRelatives(ad=1, type=(pm.nt.Mesh, pm.nt.NurbsSurface))\n target_nodes = target.listRelatives(ad=1, type=(pm.nt.Mesh, pm.nt.NurbsSurface))\n\n source_node_names = []\n target_node_names = []\n\n for node in source_nodes:\n name = node.name().split(\":\")[-1].split(\"|\")[-1]\n source_node_names.append(name)\n\n for node in target_nodes:\n name = node.name().split(\":\")[-1].split(\"|\")[-1]\n target_node_names.append(name)\n\n lut = []\n\n for i, target_node in enumerate(target_nodes):\n target_node_name = target_node_names[i]\n try:\n index = source_node_names.index(target_node_name)\n except ValueError:\n pass\n else:\n lut.append((source_nodes[index], target_nodes[i]))\n\n for source_node, target_node in lut:\n if isinstance(source_node, pm.nt.Mesh):\n in_attr_name = \"inMesh\"\n out_attr_name = \"outMesh\"\n else:\n in_attr_name = \"create\"\n out_attr_name = \"worldSpace\"\n\n conns = source_node.attr(in_attr_name).inputs(p=1)\n if conns:\n for conn in conns:\n if isinstance(conn.node(), pm.nt.AlembicNode):\n conn >> target_node.attr(in_attr_name)\n break\n else:\n # no connection\n # just connect the shape itself\n source_node.attr(out_attr_name) >> target_node.attr(in_attr_name)", "def clampVertInfluenceCount(self):\n if self.geo is None:\n activeSelection = pm.ls(sl=True)\n if activeSelection:\n self.geo = activeSelection[0]\n else:\n raise Exception(\"Found no geometry, use 'geo' flag or select a mesh in the scene.\")\n\n skinCluster = pm.listHistory(self.geo, type='skinCluster')\n if not skinCluster:\n raise Exception(\"'{0}' is not deformed by a skinCluster\".format(self.geo))\n\n skinCluster = skinCluster[0]\n # get skin\n self.mfnSkinCluster = self.getMfnSkinCluster(skinCluster.name())\n\n if self.maxInfluences is None:\n self.maxInfluences = skinCluster.getMaximumInfluences()\n\n if self.maxInfluences < 1:\n raise ValueError(\"maxInfluences must be 1 or greater, not {0}\".format(self.maxInfluences))\n\n self.dagPath, self.components = self.getGeomInfo()\n # get flat weight list (see MFnSkinCluster.setWeights for a description)\n weights = self.gatherInfluenceWeights()\n # init new weight MDoubleArray\n newWeights = OpenMaya.MDoubleArray()\n\n mod_vert_count = 0\n\n for vertexId in range(self.numComponents):\n\n weightsPerComponent = weights[self.numInfluenceObj * vertexId: self.numInfluenceObj * vertexId + self.numInfluenceObj]\n\n influenceWeights = [(index, weight) for index, weight in enumerate(weightsPerComponent) if weight]\n\n if len(influenceWeights) > self.maxInfluences:\n mod_vert_count += 1\n\n newWeightsPerComponent = [0] * self.numInfluenceObj\n\n # sort by weight\n influenceWeights.sort(key=lambda x: x[1])\n # drop the lowest weights\n influencesToKeep = influenceWeights[-self.maxInfluences:]\n\n weightSum = sum([v for i, v in influencesToKeep])\n\n for i, v in influencesToKeep:\n newWeightsPerComponent[i] = v / weightSum\n\n for weight in newWeightsPerComponent:\n newWeights.append(weight)\n else:\n for weight in weightsPerComponent:\n newWeights.append(weight)\n\n self.setInfluenceWeights(newWeights)\n print '{0} verts were modified'.format(mod_vert_count)\n return mod_vert_count", "def enrich_techniques_data_sources(self, stix_object):\n # Get 'detects' relationships\n relationships = self.get_relationships(relationship_type='detects')\n\n # Get all data component objects\n data_components = self.get_data_components()\n\n # Get all data source objects without data components objects\n data_sources = self.get_data_sources()\n\n # Create Data Sources and Data Components lookup tables\n ds_lookup = {ds['id']:ds for ds in data_sources}\n dc_lookup = {dc['id']:dc for dc in data_components}\n\n # https://stix2.readthedocs.io/en/latest/guide/versioning.html\n for i in range(len(stix_object)):\n technique_ds = dict()\n for rl in relationships:\n if stix_object[i]['id'] == rl['target_ref']:\n dc = dc_lookup[rl['source_ref']]\n dc_ds_ref = dc['x_mitre_data_source_ref']\n if dc_ds_ref not in technique_ds.keys():\n technique_ds[dc_ds_ref] = ds_lookup[dc_ds_ref].copy()\n technique_ds[dc_ds_ref]['data_components'] = list()\n if dc not in technique_ds[dc_ds_ref]['data_components']:\n technique_ds[dc_ds_ref]['data_components'].append(dc)\n if technique_ds:\n new_data_sources = [ v for v in technique_ds.values()]\n stix_object[i] = stix_object[i].new_version(x_mitre_data_sources = new_data_sources)\n return stix_object", "def copySkinWeights(noMirror=bool, noBlendWeight=bool, surfaceAssociation=\"string\", influenceAssociation=\"string\", smooth=bool, mirrorInverse=bool, sampleSpace=int, uvSpace=\"string\", sourceSkin=\"string\", normalize=bool, mirrorMode=\"string\", destinationSkin=\"string\"):\n pass", "def compute_interaction_features(source, target, dag=None):\r\n if dag is None:\r\n dag = get_active_instance()\r\n\r\n if source is None or target is None:\r\n return None\r\n\r\n # Turn terms for the source protein into a list\r\n go_mf_source = _split_string(source.go_mf)\r\n go_mf_source = go_mf_source if go_mf_source is not None else []\r\n go_mf_source = [dag[tid].id for tid in go_mf_source]\r\n\r\n go_bp_source = _split_string(source.go_bp)\r\n go_bp_source = go_bp_source if go_bp_source is not None else []\r\n go_bp_source = [dag[tid].id for tid in go_bp_source]\r\n\r\n go_cc_source = _split_string(source.go_cc)\r\n go_cc_source = go_cc_source if go_cc_source is not None else []\r\n go_cc_source = [dag[tid].id for tid in go_cc_source]\r\n\r\n interpro_source = _split_string(source.interpro)\r\n interpro_source = interpro_source if interpro_source is not None else []\r\n\r\n pfam_source = _split_string(source.pfam)\r\n pfam_source = pfam_source if pfam_source is not None else []\r\n\r\n keywords_source = _split_string(source.keywords)\r\n keywords_source = keywords_source if keywords_source is not None else []\r\n\r\n # Turn terms for the target protein into a list\r\n go_mf_target = _split_string(target.go_mf)\r\n go_mf_target = go_mf_target if go_mf_target is not None else []\r\n go_mf_target = [dag[tid].id for tid in go_mf_target]\r\n\r\n go_bp_target = _split_string(target.go_bp)\r\n go_bp_target = go_bp_target if go_bp_target is not None else []\r\n go_bp_target = [dag[tid].id for tid in go_bp_target]\r\n\r\n go_cc_target = _split_string(target.go_cc)\r\n go_cc_target = go_cc_target if go_cc_target is not None else []\r\n go_cc_target = [dag[tid].id for tid in go_cc_target]\r\n\r\n interpro_target = _split_string(target.interpro)\r\n interpro_target = interpro_target if interpro_target is not None else []\r\n\r\n pfam_target = _split_string(target.pfam)\r\n pfam_target = pfam_target if pfam_target is not None else []\r\n\r\n keywords_target = _split_string(target.keywords)\r\n keywords_target = keywords_target if keywords_target is not None else []\r\n\r\n # Prepare the ulca terms and combined lists\r\n terms = get_up_to_lca(go_mf_source, go_mf_target) + \\\r\n get_up_to_lca(go_bp_source, go_bp_target) + \\\r\n get_up_to_lca(go_cc_source, go_cc_target)\r\n\r\n # The ulca inducer will mix up the ontology types since the part_of\r\n # relationship can cross-link between ontologies. This may result\r\n # in some terms being induced more than twice so re-group them\r\n # and apply a filter.\r\n grouped = group_terms_by_ontology_type(terms, max_count=2)\r\n ulca_go_mf = [dag[tid].id for tid in grouped['mf']]\r\n ulca_go_bp = [dag[tid].id for tid in grouped['bp']]\r\n ulca_go_cc = [dag[tid].id for tid in grouped['cc']]\r\n\r\n go_mf = list(go_mf_source) + list(go_mf_target)\r\n go_bp = list(go_bp_source) + list(go_bp_target)\r\n go_cc = list(go_cc_source) + list(go_cc_target)\r\n interpro = list(interpro_source) + list(interpro_target)\r\n pfam = list(pfam_source) + list(pfam_target)\r\n keywords = list(keywords_source) + list(keywords_target)\r\n\r\n features = dict(\r\n go_mf=go_mf, go_bp=go_bp, go_cc=go_cc,\r\n ulca_go_mf=ulca_go_mf, ulca_go_bp=ulca_go_bp, ulca_go_cc=ulca_go_cc,\r\n interpro=interpro, pfam=pfam, keywords=keywords\r\n )\r\n return features", "def convert_somamer_metadata_to_source(adats: List[Adat], source_adat: Adat) -> List[Adat]:\n new_meta_adats = []\n for adat in adats:\n new_meta_adat = adat.update_somamer_metadata_from_adat(source_adat)\n new_meta_adats.append(new_meta_adat)\n\n return new_meta_adats", "def gather(self, *bundles):\n for bun in bundles:\n self.data.Copy( bun )\n return", "def merge(c1, c2):\n global number_of_effective_clusters, all_clusters\n number_of_effective_clusters += 1\n new_cluster = Cluster(number_of_effective_clusters)\n new_cluster.guest_ids = list(set(c1.guest_ids + c2.guest_ids))\n new_cluster.mean = get_mean(new_cluster.guest_ids)\n all_clusters.append(new_cluster)\n\n for i, o in enumerate(all_clusters):\n if o.id == c1.id:\n del all_clusters[i]\n\n for i, o in enumerate(all_clusters):\n if o.id == c2.id:\n del all_clusters[i]", "def update_node_helper(source, target):\n for node in target:\n if node not in source:\n continue\n target.node[node].update(source.node[node])", "def get_soft_target_model_updates(target, source, tau):\n\n weights = map(lambda (x, y): x + y, zip(map(lambda w: (1 - tau) * w, target.get_weights()), \\\n map(lambda w: tau * w, source.get_weights())))\n\n target.set_weights(weights)", "def unmerge(self) -> None:\n for index, ime in enumerate(self._source_image_entries):\n if not ime.isChecked() or not ime.layer_data.is_merger:\n continue\n\n self._source_image_entries.pop(index)\n assert ime.layer_data.parent_layers is not None\n for parent_layer_index in ime.layer_data.parent_layers.copy():\n directory = os.path.dirname(self.__cluster_image_entry.image_path)\n path_no_ext = os.path.join(directory,\n f\"{self.__cluster_image_entry.basename}_layer_{parent_layer_index}\")\n image_path = f\"{path_no_ext}.png\"\n array_path = f\"{path_no_ext}.npy\"\n parent_ime = LayerImageEntry(self, load_image(image_path), np.load(array_path), str(parent_layer_index),\n layer_index=parent_layer_index)\n parent_ime.mouse_pressed.connect(self.image_entry_click_handler)\n parent_ime.state_changed.connect(self.change_merge_button_state)\n self.add_source_image_entry(parent_ime)\n ime.close()", "def add_weights(config, photon_data, source): # nbins=50):\n weight_file = check_weights(config, source)\n if weight_file is None:\n raise Exception(f'Weight file not found for {source}')\n\n ## NEW\n wtman = WeightMan(config, filename=weight_file)\n photon_data = wtman.add_weights(photon_data)\n\n ## OLD" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remap the skinCluster data for one geometry to another
def remapGeometry(self, geometry): # Checks oldGeometry = self._data['affectedGeometry'][0] if geometry == oldGeometry: return geometry # Check Skin Geo Data if not self._data.has_key(oldGeometry): raise Exception('SkinClusterData: No skin geometry data for affected geometry "' + oldGeometry + '"!') # Remap Geometry self._data['affectedGeometry'] = [geometry] # Update Skin Geo Data self._data[geometry] = self._data[oldGeometry] self._data.pop(oldGeometry) # Print Message print('Geometry for skinCluster "' + self._data[ 'name'] + '" remaped from "' + oldGeometry + '" to "' + geometry + '"') # Return result return self._data['affectedGeometry']
[ "def rebuild(self):\n # ==========\n # - Checks -\n # ==========\n\n # Check geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data for a different geometry!')\n\n # =======================\n # - Rebuild SkinCluster -\n # =======================\n\n # Start timer\n timer = cmds.timerX()\n\n # Initialize Temp Joint\n tempJnt = ''\n\n # Unlock Influences\n influenceList = self._influenceData.keys()\n for influence in influenceList:\n if cmds.objExists(influence + '.liw'):\n if cmds.getAttr(influence + '.liw', l=True):\n try:\n cmds.setAttr(influence + '.liw', l=False)\n except:\n print(\n 'Error unlocking attribute \"' + influence + '.liw\"! This could problems when rebuilding the skinCluster...')\n if cmds.getAttr(influence + '.liw'):\n try:\n cmds.setAttr(influence + '.liw', False)\n except:\n print(\n 'Error setting attribute \"' + influence + '.liw\" to False! This could problems when rebuilding the skinCluster...')\n\n # Check SkinCluster\n skinCluster = self._data['name']\n if not cmds.objExists(skinCluster):\n\n # Get Transform Influences\n jointList = [inf for inf in influenceList if not self._influenceData[inf]['type']]\n\n # Check Transform Influences\n if not jointList:\n\n # Create Temporary Bind Joint\n cmds.select(cl=1)\n tempJnt = cmds.joint(n=skinCluster + '_tempJoint')\n print(\n 'No transform influences specified for skinCluster \"' + skinCluster + '\"! Creating temporary bind joint \"' + tempJnt + '\"!')\n jointList = [tempJnt]\n\n else:\n\n # Get Surface Influences\n influenceList = [inf for inf in influenceList if self._influenceData[inf]['type']]\n\n # Create skinCluster\n skinCluster = cmds.skinCluster(jointList, skinGeo, tsb=True, n=skinCluster)[0]\n\n else:\n\n # Check Existing SkinCluster\n affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster)\n if affectedGeo.keys()[0] != skinGeo:\n raise Exception(\n 'SkinCluster \"' + skinCluster + '\" already exists, but is not connected to the expeced geometry \"' + skinGeo + '\"!')\n\n # Add skinCluster influences\n for influence in influenceList:\n\n # Check influence\n if not cmds.objExists(influence):\n raise Exception(\n 'Influence \"' + influence + '\" does not exist! Use remapInfluence() to apply data to a different influence!')\n\n # Check existing influence connection\n if not cmds.skinCluster(skinCluster, q=True, inf=True).count(influence):\n\n # Add influence\n if self._influenceData[influence]['type']:\n # Geometry\n polySmooth = self._influenceData[influence]['polySmooth']\n nurbsSamples = self._influenceData[influence]['nurbsSamples']\n cmds.skinCluster(skinCluster, e=True, ai=influence, ug=True, ps=polySmooth, ns=nurbsSamples, wt=0.0,\n lockWeights=True)\n\n else:\n # Transform\n cmds.skinCluster(skinCluster, e=True, ai=influence, wt=0.0, lockWeights=True)\n\n # Bind Pre Matrix\n if self._influenceData[influence]['bindPreMatrix']:\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n cmds.connectAttr(self._influenceData[influence]['bindPreMatrix'],\n skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', f=True)\n\n # Load skinCluster weights\n cmds.setAttr(skinCluster + '.normalizeWeights', 0)\n glTools.utils.skinCluster.clearWeights(skinGeo)\n self.loadWeights()\n cmds.setAttr(skinCluster + '.normalizeWeights', 1)\n\n # Restore Custom Attribute Values and Connections\n self.setDeformerAttrValues()\n self.setDeformerAttrConnections()\n\n # Clear Selection\n cmds.select(cl=True)\n\n # =================\n # - Return Result -\n # =================\n\n # Print Timed Result\n totalTime = cmds.timerX(st=timer)\n print('SkinClusterData: Rebuild time for skinCluster \"' + skinCluster + '\": ' + str(totalTime))\n\n return skinCluster", "def buildData(self, skinCluster):\n # ==========\n # - Checks -\n # ==========\n\n # Check skinCluster\n self.verifySkinCluster(skinCluster)\n\n # Clear Data\n self.reset()\n\n # =======================\n # - Build Deformer Data -\n # =======================\n\n # Start Timer\n timer = cmds.timerX()\n\n self._data['name'] = skinCluster\n self._data['type'] = 'skinCluster'\n\n # Get affected geometry\n skinGeoShape = cmds.skinCluster(skinCluster, q=True, g=True)\n if len(skinGeoShape) > 1: raise Exception(\n 'SkinCluster \"' + skinCluster + '\" output is connected to multiple shapes!')\n if not skinGeoShape: raise Exception(\n 'Unable to determine affected geometry for skinCluster \"' + skinCluster + '\"!')\n skinGeo = cmds.listRelatives(skinGeoShape[0], p=True, pa=True)\n if not skinGeo: raise Exception('Unable to determine geometry transform for object \"' + skinGeoShape + '\"!')\n self._data['affectedGeometry'] = skinGeo\n skinGeo = skinGeo[0]\n\n skinClusterSet = glTools.utils.deformer.getDeformerSet(skinCluster)\n\n self._data[skinGeo] = {}\n self._data[skinGeo]['index'] = 0\n self._data[skinGeo]['geometryType'] = str(cmds.objectType(skinGeoShape))\n self._data[skinGeo]['membership'] = glTools.utils.deformer.getDeformerSetMemberIndices(skinCluster, skinGeo)\n self._data[skinGeo]['weights'] = []\n\n if self._data[skinGeo]['geometryType'] == 'mesh':\n self._data[skinGeo]['mesh'] = meshData.MeshData(skinGeo)\n\n # ========================\n # - Build Influence Data -\n # ========================\n\n # Get skinCluster influence list\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n if not influenceList: raise Exception(\n 'Unable to determine influence list for skinCluster \"' + skinCluster + '\"!')\n\n # Get Influence Wieghts\n weights = glTools.utils.skinCluster.getInfluenceWeightsAll(skinCluster)\n\n # For each influence\n for influence in influenceList:\n\n # Initialize influence data\n self._influenceData[influence] = {}\n\n # Get influence index\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n self._influenceData[influence]['index'] = infIndex\n\n # Get Influence BindPreMatrix\n bindPreMatrix = cmds.listConnections(skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', s=True, d=False,\n p=True)\n if bindPreMatrix:\n self._influenceData[influence]['bindPreMatrix'] = bindPreMatrix[0]\n else:\n self._influenceData[influence]['bindPreMatrix'] = ''\n\n # Get Influence Type (Transform/Geometry)\n infGeocmdsonn = cmds.listConnections(skinCluster + '.driverPoints[' + str(infIndex) + ']')\n if infGeocmdsonn:\n self._influenceData[influence]['type'] = 1\n self._influenceData[influence]['polySmooth'] = cmds.skinCluster(skinCluster, inf=influence, q=True,\n ps=True)\n self._influenceData[influence]['nurbsSamples'] = cmds.skinCluster(skinCluster, inf=influence, q=True,\n ns=True)\n else:\n self._influenceData[influence]['type'] = 0\n\n # Get Influence Weights\n pInd = glTools.utils.skinCluster.getInfluencePhysicalIndex(skinCluster, influence)\n self._influenceData[influence]['wt'] = weights[pInd]\n\n # =========================\n # - Custom Attribute Data -\n # =========================\n\n # Add Pre-Defined Custom Attributes\n self.getDeformerAttrValues()\n self.getDeformerAttrConnections()\n\n # =================\n # - Return Result -\n # =================\n\n skinTime = cmds.timerX(st=timer)\n print('SkinClusterData: Data build time for \"' + skinCluster + '\": ' + str(skinTime))", "def transfer_weights_replace(source, target):\n skinToReset = set()\n\n # TODO : Ensure that the transfered lockInfluenceWeight attr work correctly (The lock icon doesn't appear in the skinCluster)\n if source.hasAttr('lockInfluenceWeights'):\n attr_lockInfluenceWeights_src = source.lockInfluenceWeights\n # The target bone could possibly not have the attribute\n if target.hasAttr('lockInfluenceWeights'):\n attr_lockInfluenceWeights_dst = target.lockInfluenceWeights\n else:\n target.addAttr(\"lockInfluenceWeights\", at=\"bool\")\n attr_lockInfluenceWeights_dst = target.lockInfluenceWeights\n attr_lockInfluenceWeights_dst.set(attr_lockInfluenceWeights_src.get())\n for plug in attr_lockInfluenceWeights_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n skinToReset.add(plug.node())\n pymel.disconnectAttr(attr_lockInfluenceWeights_src, plug)\n pymel.connectAttr(attr_lockInfluenceWeights_dst, plug)\n\n attr_objectColorRGB_src = source.attr('objectColorRGB')\n attr_objectColorRGB_dst = target.attr('objectColorRGB')\n for plug in attr_objectColorRGB_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n pymel.disconnectAttr(attr_objectColorRGB_src, plug)\n pymel.connectAttr(attr_objectColorRGB_dst, plug)\n\n attr_worldMatrix_dst = target.worldMatrix\n for attr_worldMatrix_src in source.worldMatrix:\n for plug in attr_worldMatrix_src.outputs(plugs=True):\n if isinstance(plug.node(), pymel.nodetypes.SkinCluster):\n pymel.disconnectAttr(attr_worldMatrix_src, plug)\n pymel.connectAttr(attr_worldMatrix_dst, plug)\n\n # HACK : Evaluate back all skinCluster in which we changed connections\n pymel.dgdirty(skinToReset)\n\n '''\n skinClusters = set()\n for source in sources:\n for hist in source.listHistory(future=True):\n if isinstance(hist, pymel.nodetypes.SkinCluster):\n skinClusters.add(hist)\n\n for skinCluster in skinClusters:\n for geo in skinCluster.getGeometry():\n # Only mesh are supported for now\n if not isinstance(geo, pymel.nodetypes.Mesh):\n continue\n\n try:\n transfer_weights(geo, sources, target, **kwargs)\n except ValueError: # jnt_dwn not in skinCluster\n pass\n '''", "def rebuildWorldSpaceData(self, targetGeo='', method='closestPoint'):\n # Start timer\n timer = cmds.timerX()\n\n # Display Progress\n glTools.utils.progressBar.init(status=('Rebuilding world space skinCluster data...'), maxValue=100)\n\n # ==========\n # - Checks -\n # ==========\n\n # Get Source Geometry\n sourceGeo = self._data['affectedGeometry'][0]\n\n # Target Geometry\n if not targetGeo: targetGeo = sourceGeo\n\n # Check Deformer Data\n if not self._data.has_key(sourceGeo):\n glTools.utils.progressBar.end()\n raise Exception('No deformer data stored for geometry \"' + sourceGeo + '\"!')\n\n # Check Geometry\n if not cmds.objExists(targetGeo):\n glTools.utils.progressBar.end()\n raise Exception('Geometry \"' + targetGeo + '\" does not exist!')\n if not glTools.utils.mesh.isMesh(targetGeo):\n glTools.utils.progressBar.end()\n raise Exception('Geometry \"' + targetGeo + '\" is not a valid mesh!')\n\n # Check Mesh Data\n if not self._data[sourceGeo].has_key('mesh'):\n glTools.utils.progressBar.end()\n raise Exception('No world space mesh data stored for mesh geometry \"' + sourceGeo + '\"!')\n\n # =====================\n # - Rebuild Mesh Data -\n # =====================\n\n meshData = self._data[sourceGeo]['mesh']._data\n\n meshUtil = OpenMaya.MScriptUtil()\n numVertices = len(meshData['vertexList']) / 3\n numPolygons = len(meshData['polyCounts'])\n polygonCounts = OpenMaya.MIntArray()\n polygonConnects = OpenMaya.MIntArray()\n meshUtil.createIntArrayFromList(meshData['polyCounts'], polygonCounts)\n meshUtil.createIntArrayFromList(meshData['polyConnects'], polygonConnects)\n\n # Rebuild Vertex Array\n vertexArray = OpenMaya.MFloatPointArray(numVertices, OpenMaya.MFloatPoint.origin)\n vertexList = [vertexArray.set(i, meshData['vertexList'][i * 3], meshData['vertexList'][i * 3 + 1],\n meshData['vertexList'][i * 3 + 2], 1.0) for i in xrange(numVertices)]\n\n # Rebuild Mesh\n meshFn = OpenMaya.MFnMesh()\n meshDataFn = OpenMaya.MFnMeshData().create()\n meshObj = meshFn.create(numVertices, numPolygons, vertexArray, polygonCounts, polygonConnects, meshDataFn)\n\n # Create Mesh Intersector\n meshPt = OpenMaya.MPointOnMesh()\n meshIntersector = OpenMaya.MMeshIntersector()\n if method == 'closestPoint': meshIntersector.create(meshObj)\n\n # ========================================\n # - Rebuild Weights and Membership List -\n # ========================================\n\n # Initialize Influence Weights and Membership\n influenceList = self._influenceData.keys()\n influenceWt = [[] for inf in influenceList]\n membership = set([])\n\n # Get Target Mesh Data\n targetMeshFn = glTools.utils.mesh.getMeshFn(targetGeo)\n targetMeshPts = targetMeshFn.getRawPoints()\n numTargetVerts = targetMeshFn.numVertices()\n targetPtUtil = OpenMaya.MScriptUtil()\n\n # Initialize Float Pointers for Barycentric Coords\n uUtil = OpenMaya.MScriptUtil(0.0)\n vUtil = OpenMaya.MScriptUtil(0.0)\n uPtr = uUtil.asFloatPtr()\n vPtr = vUtil.asFloatPtr()\n\n # Get Progress Step\n progressInd = int(numTargetVerts * 0.01)\n if progressInd < 1: progressInd = 1\n\n for i in range(numTargetVerts):\n\n # Get Target Point\n targetPt = OpenMaya.MPoint(targetPtUtil.getFloatArrayItem(targetMeshPts, (i * 3) + 0),\n targetPtUtil.getFloatArrayItem(targetMeshPts, (i * 3) + 1),\n targetPtUtil.getFloatArrayItem(targetMeshPts, (i * 3) + 2))\n\n # Get Closest Point Data\n meshIntersector.getClosestPoint(targetPt, meshPt)\n\n # Get Barycentric Coords\n meshPt.getBarycentricCoords(uPtr, vPtr)\n u = OpenMaya.MScriptUtil(uPtr).asFloat()\n v = OpenMaya.MScriptUtil(vPtr).asFloat()\n baryWt = [u, v, 1.0 - (u + v)]\n\n # Get Triangle Vertex IDs\n idUtil = OpenMaya.MScriptUtil([0, 1, 2])\n idPtr = idUtil.asIntPtr()\n meshFn.getPolygonTriangleVertices(meshPt.faceIndex(), meshPt.triangleIndex(), idPtr)\n triId = [OpenMaya.MScriptUtil().getIntArrayItem(idPtr, n) for n in range(3)]\n memId = [self._data[sourceGeo]['membership'].count(t) for t in triId]\n wtId = [self._data[sourceGeo]['membership'].index(t) for t in triId]\n\n # For Each Influence\n for inf in range(len(influenceList)):\n\n # Calculate Weight and Membership\n wt = 0.0\n isMember = False\n for n in range(3):\n\n # Check Against Source Membership\n if memId[n]:\n wt += self._influenceData[influenceList[inf]]['wt'][wtId[n]] * baryWt[n]\n isMember = True\n\n # Check Member\n if isMember:\n # Append Weight Value\n influenceWt[inf].append(wt)\n # Append Membership\n membership.add(i)\n\n # Update Progress Bar\n if not i % progressInd: glTools.utils.progressBar.update(step=1)\n\n # ========================\n # - Update Deformer Data -\n # ========================\n\n # Remap Geometry\n self.remapGeometry(targetGeo)\n\n # Rename SkinCluster\n targetSkinCluster = glTools.utils.skinCluster.findRelatedSkinCluster(targetGeo)\n if targetSkinCluster:\n self._data['name'] = targetSkinCluster\n else:\n prefix = targetGeo.split(':')[-1]\n self._data['name'] = prefix + '_skinCluster'\n\n # Update Membership and Weights\n self._data[sourceGeo]['membership'] = list(membership)\n for inf in range(len(influenceList)):\n self._influenceData[influenceList[inf]]['wt'] = influenceWt[inf]\n\n # =================\n # - Return Result -\n # =================\n\n # End Progress\n glTools.utils.progressBar.end()\n\n # Print Timed Result\n buildTime = cmds.timerX(st=timer)\n print(\n 'SkinClusterData: Rebuild world space data for skinCluster \"' + self._data['name'] + '\": ' + str(buildTime))\n\n # Return Weights\n return", "def __init__(self, skinCluster=''):\n # Execute Super Class Initilizer\n super(SkinClusterData, self).__init__()\n\n # SkinCluster Custom Attributes\n self._data['attrValueList'].append('skinningMethod')\n self._data['attrValueList'].append('useComponents')\n self._data['attrValueList'].append('normalizeWeights')\n self._data['attrValueList'].append('deformUserNormals')\n\n # Build SkinCluster Data\n if skinCluster: self.buildData(skinCluster)", "def setWeights(self, componentList=[]):\n print('!!! - DEPRICATED: skinClusterData.setWeights()! Use loadWeights() method instead - !!!')\n\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Component List\n if not componentList: componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n indexList = OpenMaya.MIntArray()\n componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n componentFn.getElements(indexList)\n componentIndexList = list(indexList)\n\n # ===========================\n # - Set SkinCluster Weights -\n # ===========================\n\n # Build influence index array\n infIndexArray = OpenMaya.MIntArray()\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n [infIndexArray.append(i) for i in range(len(influenceList))]\n\n # Build master weight array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, False, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return influenceList", "def merge(cluster1, cluster2):\n cluster1.extend(cluster2.g_num, cluster2.g_id, cluster2.g_ra, cluster2.g_dec, cluster2.g_z, cluster2.g_x, cluster2.g_y)", "def reconstruct_mesh(self):\n\n # NOTE: Before drawing the skeleton, create the materials once and for all to improve the\n # performance since this is way better than creating a new material per section or segment\n nmv.builders.create_skeleton_materials(builder=self)\n\n # Verify and repair the morphology, if required\n result, stats = nmv.utilities.profile_function(self.verify_morphology_skeleton)\n self.profiling_statistics += stats\n\n # Apply skeleton - based operation, if required, to slightly modify the skeleton\n result, stats = nmv.utilities.profile_function(\n nmv.builders.modify_morphology_skeleton, self)\n self.profiling_statistics += stats\n\n # Build the soma, with the default parameters\n result, stats = nmv.utilities.profile_function(nmv.builders.reconstruct_soma_mesh, self)\n self.profiling_statistics += stats\n\n # Build the arbors and connect them to the soma\n if self.options.mesh.soma_connection == nmv.enums.Meshing.SomaConnection.CONNECTED:\n\n # Build the arbors\n result, stats = nmv.utilities.profile_function(self.build_arbors, True)\n self.profiling_statistics += stats\n\n # Connect to the soma\n result, stats = nmv.utilities.profile_function(\n nmv.builders.connect_arbors_to_soma, self)\n self.profiling_statistics += stats\n\n # Build the arbors only without any connection to the soma\n else:\n # Build the arbors\n result, stats = nmv.utilities.profile_function(self.build_arbors, False)\n self.profiling_statistics += stats\n\n # Tessellation\n result, stats = nmv.utilities.profile_function(nmv.builders.decimate_neuron_mesh, self)\n self.profiling_statistics += stats\n\n # Surface roughness\n result, stats = nmv.utilities.profile_function(\n nmv.builders.add_surface_noise_to_arbor, self)\n self.profiling_statistics += stats\n\n # Add the spines\n result, stats = nmv.utilities.profile_function(nmv.builders.add_spines_to_surface, self)\n self.profiling_statistics += stats\n\n # Join all the objects into a single object\n result, stats = nmv.utilities.profile_function(\n nmv.builders.join_mesh_object_into_single_object, self)\n self.profiling_statistics += stats\n\n # Transform to the global coordinates, if required\n result, stats = nmv.utilities.profile_function(\n nmv.builders.transform_to_global_coordinates, self)\n self.profiling_statistics += stats\n\n # Collect the stats. of the mesh\n result, stats = nmv.utilities.profile_function(nmv.builders.collect_mesh_stats, self)\n self.profiling_statistics += stats\n\n # Done\n nmv.logger.header('Mesh Reconstruction Done!')\n nmv.logger.log(self.profiling_statistics)\n\n # Write the stats to file\n nmv.builders.write_statistics_to_file(builder=self, tag='skinning')", "def edit_singularity_mesh(pattern):", "def _spectral_to_original(self):\n # embedding is a nested list containing the indices of the points\n # that belong to each cluster.\n embedding = self.clusters.values()\n orig_clustering = [[self.orig_points[p_idx] for p_idx in cluster]\n for cluster in embedding]\n return orig_clustering", "def collate_cluster_data(ensembles_data):\n\n clusters = {} # Loop through all ensemble data objects and build up a data tree\n cluster_method = None\n cluster_score_type = None\n truncation_method = None\n percent_truncation = None\n side_chain_treatments = []\n for e in ensembles_data:\n if not cluster_method:\n cluster_method = e['cluster_method']\n cluster_score_type = e['cluster_score_type']\n percent_truncation = e['truncation_percent']\n truncation_method = e['truncation_method']\n # num_clusters = e['num_clusters']\n cnum = e['cluster_num']\n if cnum not in clusters:\n clusters[cnum] = {}\n clusters[cnum]['cluster_centroid'] = e['cluster_centroid']\n clusters[cnum]['cluster_num_models'] = e['cluster_num_models']\n clusters[cnum]['tlevels'] = {}\n tlvl = e['truncation_level']\n if tlvl not in clusters[cnum]['tlevels']:\n clusters[cnum]['tlevels'][tlvl] = {}\n clusters[cnum]['tlevels'][tlvl]['truncation_variance'] = e['truncation_variance']\n clusters[cnum]['tlevels'][tlvl]['num_residues'] = e['num_residues']\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'] = {}\n srt = e['subcluster_radius_threshold']\n if srt not in clusters[cnum]['tlevels'][tlvl]['radius_thresholds']:\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt] = {}\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['num_models'] = e['subcluster_num_models']\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'] = {}\n sct = e['side_chain_treatment']\n if sct not in side_chain_treatments:\n side_chain_treatments.append(sct)\n if sct not in clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct']:\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'][sct] = {}\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'][sct]['name'] = e['name']\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'][sct]['num_atoms'] = e['ensemble_num_atoms']\n\n return {\n 'clusters': clusters,\n 'cluster_method': cluster_method,\n 'cluster_score_type': cluster_score_type,\n 'truncation_method': truncation_method,\n 'percent_truncation': percent_truncation,\n 'side_chain_treatments': side_chain_treatments,\n }", "def face_sierpinski_mesh(partition, special_faces):\n\n graph = partition.graph\n # Get maximum node label.\n label = max(list(graph.nodes()))\n # Assign each node to its district in partition\n for node in graph.nodes():\n graph.nodes[node][config['ASSIGN_COL']] = partition.assignment[node]\n\n for face in special_faces:\n neighbors = [] # Neighbors of face\n locationCount = np.array([0,0]).astype(\"float64\")\n # For each face, add to neighbor_list and add to location count\n for vertex in face:\n neighbors.append(vertex)\n locationCount += np.array(graph.nodes[vertex][\"pos\"]).astype(\"float64\")\n # Save the average of each of the face's positions\n facePosition = locationCount / len(face)\n\n # In order, store relative position of each vertex to the position of the face\n locations = [graph.nodes[vertex]['pos'] - facePosition for vertex in face]\n # Sort neighbors according to each node's angle with the center of the face\n angles = [float(np.arctan2(x[0], x[1])) for x in locations]\n neighbors.sort(key=dict(zip(neighbors, angles)).get)\n\n newNodes = []\n newEdges = []\n # For each consecutive pair of nodes, remove their edge, create a new\n # node at their average position, and connect edge node to the new node:\n for vertex, next_vertex in zip(neighbors, neighbors[1:] + [neighbors[0]]):\n label += 1\n # Add new node to graph with corresponding label at the average position\n # of vertex and next_vertex, and with 0 population and 0 votes\n graph.add_node(label)\n avgPos = (np.array(graph.nodes[vertex]['pos']) +\n np.array(graph.nodes[next_vertex]['pos'])) / 2\n graph.nodes[label]['pos'] = avgPos\n graph.nodes[label][config['X_POSITION']] = avgPos[0]\n graph.nodes[label][config['Y_POSITION']] = avgPos[1]\n graph.nodes[label][config['POP_COL']] = 0\n graph.nodes[label][config['PARTY_A_COL']] = 0\n graph.nodes[label][config['PARTY_B_COL']] = 0\n\n # For each new node, 'move' a third of the population, Party A votes,\n # and Party B votes from its two adjacent nodes which previously exists\n # to itself (so that each previously existing node equally shares\n # its statistics with the two new nodes adjacent to it)\n # Note: should only be used when all special faces are NOT on edges\n if config['SIERPINSKI_POP_STYLE'] == 'uniform':\n for vert in [vertex, next_vertex]:\n for keyword, orig_keyword in zip(['POP_COL', 'PARTY_A_COL', 'PARTY_B_COL'],\n ['orig_pop', 'orig_A', 'orig_B']):\n # Save original values if not done already\n if orig_keyword not in graph.nodes[vert]:\n graph.nodes[vert][orig_keyword] = graph.nodes[vert][config[keyword]]\n\n # Increment values of new node and decrement values of old nodes\n # by the appropriate amount.\n graph.nodes[label][config[keyword]] += graph.nodes[vert][orig_keyword] // 3\n graph.nodes[vert][config[keyword]] -= graph.nodes[vert][orig_keyword] // 3\n\n # Assign new node to same district as neighbor. Note that intended\n # behavior is that special_faces do not correspond to cut edges,\n # and therefore both vertex and next_vertex will be of the same\n # district.\n graph.nodes[label][config['ASSIGN_COL']] = graph.nodes[vertex][config['ASSIGN_COL']]\n\n # Choose a random adjacent node, assign the new node to the same partition,\n # and move half of its votes and population to said node\n elif config['SIERPINSKI_POP_STYLE'] == 'random':\n chosenNode = random.choice([graph.nodes[vertex], graph.nodes[next_vertex]])\n graph.nodes[label][config['ASSIGN_COL']] = chosenNode[config['ASSIGN_COL']]\n for keyword in ['POP_COL', 'PARTY_A_COL', 'PARTY_B_COL']:\n graph.nodes[label][config[keyword]] += chosenNode[config[keyword]] // 2\n chosenNode[config[keyword]] -= chosenNode[config[keyword]] // 2\n # Set the population and votes of the new nodes to zero. Do not change\n # previously existing nodes. Assign to random neighbor.\n elif config['SIERPINSKI_POP_STYLE'] == 'zero':\n graph.nodes[label][config['ASSIGN_COL']] =\\\n random.choice([graph.nodes[vertex][config['ASSIGN_COL']],\n graph.nodes[next_vertex][config['ASSIGN_COL']]]\n )\n else:\n raise RuntimeError('SIERPINSKI_POP_STYLE must be \"uniform\", \"random\", or \"zero\"')\n\n # Remove edge between consecutive nodes if it exists\n if graph.has_edge(vertex, next_vertex):\n graph.remove_edge(vertex, next_vertex)\n\n # Add edge between both of the original nodes and the new node\n graph.add_edge(vertex, label)\n newEdges.append((vertex, label))\n graph.add_edge(label, next_vertex)\n newEdges.append((label, next_vertex))\n # Add node to connections\n newNodes.append(label)\n\n # Add an edge between each consecutive new node\n for vertex in range(len(newNodes)):\n graph.add_edge(newNodes[vertex], newNodes[(vertex+1) % len(newNodes)])\n newEdges.append((newNodes[vertex], newNodes[(vertex+1) % len(newNodes)]))\n # For each new edge of the face, set sibilings to be the tuple of all\n # new edges\n siblings = tuple(newEdges)\n for edge in newEdges:\n graph.edges[edge]['siblings'] = siblings", "def convert_snap_cluster_dist(self,snap,input_params):\n N = input_params['N_monomers']\n monomer_to_chain_map = input_params['MC_map'];\n chain_type = input_params['CT_map'];\n\n\n pos =snap.particles.position[0:N,:];\n box = freud.box.Box(snap.configuration.box[0],snap.configuration.box[1],snap.configuration.box[2]);\n cluster_g = freud.cluster.Cluster(box,rcut=1.4);\n cluster_g.computeClusters(pos)\n cluster_idx = cluster_g.getClusterIdx();\n cluster_prop = freud.cluster.ClusterProperties(box);\n cluster_prop.computeProperties(pos, cluster_idx)\n a = cluster_prop.getClusterSizes();\n rg = cluster_prop.getClusterG();\n all_a_index = numpy.where(a==max(a));\n a_index = all_a_index[0][0];\n monomers_in_largest_cluster = numpy.where(cluster_idx==a_index)\n # print(monomers_in_largest_cluster[0])\n count_types = {};\n chain_list = {};\n count_types['A'] =0;\n count_types['B'] =0;\n count_types['C'] =0;\n\n for monomer in monomers_in_largest_cluster[0]:\n chain_id = monomer_to_chain_map[monomer]\n\n if str(chain_id) not in chain_list.keys():\n ctype = chain_type[chain_id];\n chain_list[str(chain_id)] = 1;\n count_types[ctype] +=1;\n\n MI_rel = rg[a_index,:,:];\n eig, eig_val = numpy.linalg.eig(MI_rel);\n rg_max = numpy.sqrt(numpy.sum(eig))+0.5*max(snap.particles.diameter);\n c_max = a[a_index];\n return (c_max,rg_max,count_types,chain_list,monomers_in_largest_cluster[0])", "def __swap_and_recalculate_clusters(self):\n # http://www.math.le.ac.uk/people/ag153/homepage/KmeansKmedoids/Kmeans_Kmedoids.html\n print(\"swap and recompute\")\n cluster_dist = {}\n for medoid in self.medoids: # for each medoid\n is_shortest_medoid_found = False\n for data_index in self.clusters[\n medoid\n ]: # for each point in the current medoid's cluster\n if data_index != medoid: # exclude the medoid itself\n # create a list of the elements of the cluster\n cluster_list = list(self.clusters[medoid])\n # make the current point the temporary medoid\n cluster_list[\n self.clusters[medoid].index(data_index)\n ] = medoid\n # compute new cluster distance obtained by swapping the medoid\n new_distance = self.calculate_inter_cluster_distance(\n data_index, cluster_list\n )\n # if this new distance is smaller than the previous one\n if new_distance < self.cluster_distances[medoid]:\n print(\"new better medoid: \", data_index)\n cluster_dist[data_index] = new_distance\n is_shortest_medoid_found = True\n break # exit for loop for this medoid, since a better one has been found\n # if no better medoid has been found, keep the current one\n if is_shortest_medoid_found is False:\n print(\"no better medoids found, keep: \", medoid)\n cluster_dist[medoid] = self.cluster_distances[medoid]\n print(\"cluster_dist: \", cluster_dist)\n return cluster_dist", "def _updateCaster(self):\n\n self.caster.SetDataSet(self.mesh)\n self.caster.BuildLocator()", "def skinCluster(dropoffRate=float, before=bool, exclusive=\"string\", split=bool, after=bool, smoothWeights=float, ignoreSelected=bool, nurbsSamples=int, ignoreHierarchy=bool, ignoreBindPose=bool, includeHiddenSelections=bool, weightDistribution=int, smoothWeightsMaxIterations=int, frontOfChain=bool, prune=bool, weight=float, normalizeWeights=int, baseShape=\"string\", volumeType=int, skinMethod=int, heatmapFalloff=float, obeyMaxInfluences=bool, unbind=bool, removeInfluence=\"string\", volumeBind=float, geometry=\"string\", useGeometry=bool, name=\"string\", unbindKeepHistory=bool, weightedInfluence=bool, moveJointsMode=bool, removeUnusedInfluence=bool, influence=\"string\", bindMethod=int, parallel=bool, forceNormalizeWeights=bool, addInfluence=\"string\", geometryIndices=bool, polySmoothness=float, afterReference=bool, remove=bool, maximumInfluences=int, selectInfluenceVerts=\"string\", addToSelection=bool, lockWeights=bool, deformerTools=bool, removeFromSelection=bool, recacheBindMatrices=bool, toSkeletonAndTransforms=bool, toSelectedBones=bool):\n pass", "def compose_cluster_map(self,filedir):\r\n self.cluster_map = np.zeros((SAT_SIZE,SAT_SIZE),dtype='uint16')\r\n #Search the directory for all matching npy files:\r\n file_list = os.listdir(filedir)\r\n for file in file_list:\r\n file_parts = file.split('_')\r\n if len(file_parts)==3 and file_parts[2]=='clusters.npy':\r\n x0 = int(file_parts[0])\r\n y0 = int(file_parts[1])\r\n x1 = x0 + 2*VIEW_SIZE\r\n y1 = y0 + 2*VIEW_SIZE\r\n cluster_area = np.load(filedir+file).reshape(2*VIEW_SIZE,2*VIEW_SIZE)\r\n self.cluster_map[y0:y1,x0:x1] = cluster_area\r\n np.save(filedir+'cluster_map.npy',self.cluster_map)", "def update_centroids(labelled_data, centroids, id_to_name_mapping):\n for idx, cluster_name in id_to_name_mapping.items():\n single_cluster_datapoints = labelled_data[labelled_data[:, 2] == idx]\n new_centroid = single_cluster_datapoints[:, :2].mean(axis=0)\n centroids[cluster_name] = new_centroid\n return centroids", "def relabel_clusters_to_match(self, target_clustering):\n new_clu_labels = remap2match(self, target_clustering)\n self.from_clu2elm_dict({new_clu_labels[c]:el for c, el in self.clu2elm_dict.items()})\n return self" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rebuild the skinCluster deformer membership and weight arrays for the specified geometry using the stored world space geometry data.
def rebuildWorldSpaceData(self, targetGeo='', method='closestPoint'): # Start timer timer = cmds.timerX() # Display Progress glTools.utils.progressBar.init(status=('Rebuilding world space skinCluster data...'), maxValue=100) # ========== # - Checks - # ========== # Get Source Geometry sourceGeo = self._data['affectedGeometry'][0] # Target Geometry if not targetGeo: targetGeo = sourceGeo # Check Deformer Data if not self._data.has_key(sourceGeo): glTools.utils.progressBar.end() raise Exception('No deformer data stored for geometry "' + sourceGeo + '"!') # Check Geometry if not cmds.objExists(targetGeo): glTools.utils.progressBar.end() raise Exception('Geometry "' + targetGeo + '" does not exist!') if not glTools.utils.mesh.isMesh(targetGeo): glTools.utils.progressBar.end() raise Exception('Geometry "' + targetGeo + '" is not a valid mesh!') # Check Mesh Data if not self._data[sourceGeo].has_key('mesh'): glTools.utils.progressBar.end() raise Exception('No world space mesh data stored for mesh geometry "' + sourceGeo + '"!') # ===================== # - Rebuild Mesh Data - # ===================== meshData = self._data[sourceGeo]['mesh']._data meshUtil = OpenMaya.MScriptUtil() numVertices = len(meshData['vertexList']) / 3 numPolygons = len(meshData['polyCounts']) polygonCounts = OpenMaya.MIntArray() polygonConnects = OpenMaya.MIntArray() meshUtil.createIntArrayFromList(meshData['polyCounts'], polygonCounts) meshUtil.createIntArrayFromList(meshData['polyConnects'], polygonConnects) # Rebuild Vertex Array vertexArray = OpenMaya.MFloatPointArray(numVertices, OpenMaya.MFloatPoint.origin) vertexList = [vertexArray.set(i, meshData['vertexList'][i * 3], meshData['vertexList'][i * 3 + 1], meshData['vertexList'][i * 3 + 2], 1.0) for i in xrange(numVertices)] # Rebuild Mesh meshFn = OpenMaya.MFnMesh() meshDataFn = OpenMaya.MFnMeshData().create() meshObj = meshFn.create(numVertices, numPolygons, vertexArray, polygonCounts, polygonConnects, meshDataFn) # Create Mesh Intersector meshPt = OpenMaya.MPointOnMesh() meshIntersector = OpenMaya.MMeshIntersector() if method == 'closestPoint': meshIntersector.create(meshObj) # ======================================== # - Rebuild Weights and Membership List - # ======================================== # Initialize Influence Weights and Membership influenceList = self._influenceData.keys() influenceWt = [[] for inf in influenceList] membership = set([]) # Get Target Mesh Data targetMeshFn = glTools.utils.mesh.getMeshFn(targetGeo) targetMeshPts = targetMeshFn.getRawPoints() numTargetVerts = targetMeshFn.numVertices() targetPtUtil = OpenMaya.MScriptUtil() # Initialize Float Pointers for Barycentric Coords uUtil = OpenMaya.MScriptUtil(0.0) vUtil = OpenMaya.MScriptUtil(0.0) uPtr = uUtil.asFloatPtr() vPtr = vUtil.asFloatPtr() # Get Progress Step progressInd = int(numTargetVerts * 0.01) if progressInd < 1: progressInd = 1 for i in range(numTargetVerts): # Get Target Point targetPt = OpenMaya.MPoint(targetPtUtil.getFloatArrayItem(targetMeshPts, (i * 3) + 0), targetPtUtil.getFloatArrayItem(targetMeshPts, (i * 3) + 1), targetPtUtil.getFloatArrayItem(targetMeshPts, (i * 3) + 2)) # Get Closest Point Data meshIntersector.getClosestPoint(targetPt, meshPt) # Get Barycentric Coords meshPt.getBarycentricCoords(uPtr, vPtr) u = OpenMaya.MScriptUtil(uPtr).asFloat() v = OpenMaya.MScriptUtil(vPtr).asFloat() baryWt = [u, v, 1.0 - (u + v)] # Get Triangle Vertex IDs idUtil = OpenMaya.MScriptUtil([0, 1, 2]) idPtr = idUtil.asIntPtr() meshFn.getPolygonTriangleVertices(meshPt.faceIndex(), meshPt.triangleIndex(), idPtr) triId = [OpenMaya.MScriptUtil().getIntArrayItem(idPtr, n) for n in range(3)] memId = [self._data[sourceGeo]['membership'].count(t) for t in triId] wtId = [self._data[sourceGeo]['membership'].index(t) for t in triId] # For Each Influence for inf in range(len(influenceList)): # Calculate Weight and Membership wt = 0.0 isMember = False for n in range(3): # Check Against Source Membership if memId[n]: wt += self._influenceData[influenceList[inf]]['wt'][wtId[n]] * baryWt[n] isMember = True # Check Member if isMember: # Append Weight Value influenceWt[inf].append(wt) # Append Membership membership.add(i) # Update Progress Bar if not i % progressInd: glTools.utils.progressBar.update(step=1) # ======================== # - Update Deformer Data - # ======================== # Remap Geometry self.remapGeometry(targetGeo) # Rename SkinCluster targetSkinCluster = glTools.utils.skinCluster.findRelatedSkinCluster(targetGeo) if targetSkinCluster: self._data['name'] = targetSkinCluster else: prefix = targetGeo.split(':')[-1] self._data['name'] = prefix + '_skinCluster' # Update Membership and Weights self._data[sourceGeo]['membership'] = list(membership) for inf in range(len(influenceList)): self._influenceData[influenceList[inf]]['wt'] = influenceWt[inf] # ================= # - Return Result - # ================= # End Progress glTools.utils.progressBar.end() # Print Timed Result buildTime = cmds.timerX(st=timer) print( 'SkinClusterData: Rebuild world space data for skinCluster "' + self._data['name'] + '": ' + str(buildTime)) # Return Weights return
[ "def rebuild(self):\n # ==========\n # - Checks -\n # ==========\n\n # Check geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data for a different geometry!')\n\n # =======================\n # - Rebuild SkinCluster -\n # =======================\n\n # Start timer\n timer = cmds.timerX()\n\n # Initialize Temp Joint\n tempJnt = ''\n\n # Unlock Influences\n influenceList = self._influenceData.keys()\n for influence in influenceList:\n if cmds.objExists(influence + '.liw'):\n if cmds.getAttr(influence + '.liw', l=True):\n try:\n cmds.setAttr(influence + '.liw', l=False)\n except:\n print(\n 'Error unlocking attribute \"' + influence + '.liw\"! This could problems when rebuilding the skinCluster...')\n if cmds.getAttr(influence + '.liw'):\n try:\n cmds.setAttr(influence + '.liw', False)\n except:\n print(\n 'Error setting attribute \"' + influence + '.liw\" to False! This could problems when rebuilding the skinCluster...')\n\n # Check SkinCluster\n skinCluster = self._data['name']\n if not cmds.objExists(skinCluster):\n\n # Get Transform Influences\n jointList = [inf for inf in influenceList if not self._influenceData[inf]['type']]\n\n # Check Transform Influences\n if not jointList:\n\n # Create Temporary Bind Joint\n cmds.select(cl=1)\n tempJnt = cmds.joint(n=skinCluster + '_tempJoint')\n print(\n 'No transform influences specified for skinCluster \"' + skinCluster + '\"! Creating temporary bind joint \"' + tempJnt + '\"!')\n jointList = [tempJnt]\n\n else:\n\n # Get Surface Influences\n influenceList = [inf for inf in influenceList if self._influenceData[inf]['type']]\n\n # Create skinCluster\n skinCluster = cmds.skinCluster(jointList, skinGeo, tsb=True, n=skinCluster)[0]\n\n else:\n\n # Check Existing SkinCluster\n affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster)\n if affectedGeo.keys()[0] != skinGeo:\n raise Exception(\n 'SkinCluster \"' + skinCluster + '\" already exists, but is not connected to the expeced geometry \"' + skinGeo + '\"!')\n\n # Add skinCluster influences\n for influence in influenceList:\n\n # Check influence\n if not cmds.objExists(influence):\n raise Exception(\n 'Influence \"' + influence + '\" does not exist! Use remapInfluence() to apply data to a different influence!')\n\n # Check existing influence connection\n if not cmds.skinCluster(skinCluster, q=True, inf=True).count(influence):\n\n # Add influence\n if self._influenceData[influence]['type']:\n # Geometry\n polySmooth = self._influenceData[influence]['polySmooth']\n nurbsSamples = self._influenceData[influence]['nurbsSamples']\n cmds.skinCluster(skinCluster, e=True, ai=influence, ug=True, ps=polySmooth, ns=nurbsSamples, wt=0.0,\n lockWeights=True)\n\n else:\n # Transform\n cmds.skinCluster(skinCluster, e=True, ai=influence, wt=0.0, lockWeights=True)\n\n # Bind Pre Matrix\n if self._influenceData[influence]['bindPreMatrix']:\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n cmds.connectAttr(self._influenceData[influence]['bindPreMatrix'],\n skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', f=True)\n\n # Load skinCluster weights\n cmds.setAttr(skinCluster + '.normalizeWeights', 0)\n glTools.utils.skinCluster.clearWeights(skinGeo)\n self.loadWeights()\n cmds.setAttr(skinCluster + '.normalizeWeights', 1)\n\n # Restore Custom Attribute Values and Connections\n self.setDeformerAttrValues()\n self.setDeformerAttrConnections()\n\n # Clear Selection\n cmds.select(cl=True)\n\n # =================\n # - Return Result -\n # =================\n\n # Print Timed Result\n totalTime = cmds.timerX(st=timer)\n print('SkinClusterData: Rebuild time for skinCluster \"' + skinCluster + '\": ' + str(totalTime))\n\n return skinCluster", "def buildData(self, skinCluster):\n # ==========\n # - Checks -\n # ==========\n\n # Check skinCluster\n self.verifySkinCluster(skinCluster)\n\n # Clear Data\n self.reset()\n\n # =======================\n # - Build Deformer Data -\n # =======================\n\n # Start Timer\n timer = cmds.timerX()\n\n self._data['name'] = skinCluster\n self._data['type'] = 'skinCluster'\n\n # Get affected geometry\n skinGeoShape = cmds.skinCluster(skinCluster, q=True, g=True)\n if len(skinGeoShape) > 1: raise Exception(\n 'SkinCluster \"' + skinCluster + '\" output is connected to multiple shapes!')\n if not skinGeoShape: raise Exception(\n 'Unable to determine affected geometry for skinCluster \"' + skinCluster + '\"!')\n skinGeo = cmds.listRelatives(skinGeoShape[0], p=True, pa=True)\n if not skinGeo: raise Exception('Unable to determine geometry transform for object \"' + skinGeoShape + '\"!')\n self._data['affectedGeometry'] = skinGeo\n skinGeo = skinGeo[0]\n\n skinClusterSet = glTools.utils.deformer.getDeformerSet(skinCluster)\n\n self._data[skinGeo] = {}\n self._data[skinGeo]['index'] = 0\n self._data[skinGeo]['geometryType'] = str(cmds.objectType(skinGeoShape))\n self._data[skinGeo]['membership'] = glTools.utils.deformer.getDeformerSetMemberIndices(skinCluster, skinGeo)\n self._data[skinGeo]['weights'] = []\n\n if self._data[skinGeo]['geometryType'] == 'mesh':\n self._data[skinGeo]['mesh'] = meshData.MeshData(skinGeo)\n\n # ========================\n # - Build Influence Data -\n # ========================\n\n # Get skinCluster influence list\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n if not influenceList: raise Exception(\n 'Unable to determine influence list for skinCluster \"' + skinCluster + '\"!')\n\n # Get Influence Wieghts\n weights = glTools.utils.skinCluster.getInfluenceWeightsAll(skinCluster)\n\n # For each influence\n for influence in influenceList:\n\n # Initialize influence data\n self._influenceData[influence] = {}\n\n # Get influence index\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n self._influenceData[influence]['index'] = infIndex\n\n # Get Influence BindPreMatrix\n bindPreMatrix = cmds.listConnections(skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', s=True, d=False,\n p=True)\n if bindPreMatrix:\n self._influenceData[influence]['bindPreMatrix'] = bindPreMatrix[0]\n else:\n self._influenceData[influence]['bindPreMatrix'] = ''\n\n # Get Influence Type (Transform/Geometry)\n infGeocmdsonn = cmds.listConnections(skinCluster + '.driverPoints[' + str(infIndex) + ']')\n if infGeocmdsonn:\n self._influenceData[influence]['type'] = 1\n self._influenceData[influence]['polySmooth'] = cmds.skinCluster(skinCluster, inf=influence, q=True,\n ps=True)\n self._influenceData[influence]['nurbsSamples'] = cmds.skinCluster(skinCluster, inf=influence, q=True,\n ns=True)\n else:\n self._influenceData[influence]['type'] = 0\n\n # Get Influence Weights\n pInd = glTools.utils.skinCluster.getInfluencePhysicalIndex(skinCluster, influence)\n self._influenceData[influence]['wt'] = weights[pInd]\n\n # =========================\n # - Custom Attribute Data -\n # =========================\n\n # Add Pre-Defined Custom Attributes\n self.getDeformerAttrValues()\n self.getDeformerAttrConnections()\n\n # =================\n # - Return Result -\n # =================\n\n skinTime = cmds.timerX(st=timer)\n print('SkinClusterData: Data build time for \"' + skinCluster + '\": ' + str(skinTime))", "def update_mesh(self, obj, depsgraph):\n\n # Get/create the mesh instance and determine if we need\n # to reupload geometry to the GPU for this mesh\n rebuild_geometry = obj.name in self.updated_geometries\n if obj.name not in self.meshes:\n mesh = Mesh(obj.name)\n rebuild_geometry = True\n else:\n mesh = self.meshes[obj.name]\n\n mesh.update(obj)\n\n # If modified - prep the mesh to be copied to the GPU next draw\n if rebuild_geometry:\n mesh.rebuild(obj.evaluated_get(depsgraph))\n\n self.updated_meshes[obj.name] = mesh", "def gm_for_data_and_fill_grad_weight(self):\n # Allocate space for grad, indices and grad_weight on gm\n self.grad = self.tik_instance.Tensor(self.dtype_grad, self.grad_shape, name=\"grad\", scope=tik.scope_gm)\n self.indices = self.tik_instance.Tensor(self.dtype_indices, (self.new_numel_indices,), name=\"indices\",\n scope=tik.scope_gm)\n self.grad_weight = self.tik_instance.Tensor(self.dtype_grad, (self.num_weights, self.embedding_dim),\n name=\"grad_weight\", scope=tik.scope_gm)\n\n self.vector_max_repeat = 255\n self.vec_max_grad_element = self.vector_max_repeat * self.vector_mask_max_grad\n # Create a new space to initialize grad_weight\n with self.tik_instance.new_stmt_scope():\n # Initialize fill_tensor with 0, which is used to initialize grad_weight later\n fill_tensor = self.tik_instance.Tensor(self.dtype_grad, (1, self.embedding_dim), name=\"tmp_tensor_grad\",\n scope=tik.scope_ubuf)\n # Define scalar_float0 to fill grad_weight\n scalar_float0 = self.tik_instance.Scalar(init_value=0, dtype=self.dtype_grad)\n if self.embedding_dim//self.vector_mask_max_grad > 0:\n self.tik_instance.vec_dup(self.vector_mask_max_grad, fill_tensor, scalar_float0, self.embedding_dim\n // self.vector_mask_max_grad, 8)\n if self.embedding_dim % self.vector_mask_max_grad != 0:\n self.tik_instance.vec_dup(self.embedding_dim % self.vector_mask_max_grad, fill_tensor\n [self.embedding_dim // self.vector_mask_max_grad * self.vector_mask_max_grad],\n scalar_float0, 1, 8)\n # Use fill_tensor on ub to fill grad_weight on gm and do 0 initialization\n with self.tik_instance.for_range(0, self.num_weights) as i:\n self.tik_instance.data_move(self.grad_weight[i * self.embedding_dim],\n fill_tensor, 0, 1, self.embedding_dim // self.grad_each_block, 0, 0)\n\n self.ub_for_data_fill_counts()", "def deformGeometry(self):\r\n cmds.modelEditor('modelPanel4', e=True, nurbsCurves=True, polymeshes=True)\r\n #DeformLibrary.matchCircleDirectionTest(self.LocatorGrp)\r\n DeformLibrary.deformGeoToImage(self.LocatorGrp, self.ResolutionList)\r\n DeformLibrary.cleanUpforEdit2(self.LocatorGrp, self.Objects, self.relationshipList, self.mesh)\r\n self.Objects = []\r\n self.relationshipList = []", "def reconstruct_mesh(self):\n\n # NOTE: Before drawing the skeleton, create the materials once and for all to improve the\n # performance since this is way better than creating a new material per section or segment\n nmv.builders.create_skeleton_materials(builder=self)\n\n # Verify and repair the morphology, if required\n result, stats = nmv.utilities.profile_function(self.verify_morphology_skeleton)\n self.profiling_statistics += stats\n\n # Apply skeleton - based operation, if required, to slightly modify the skeleton\n result, stats = nmv.utilities.profile_function(\n nmv.builders.modify_morphology_skeleton, self)\n self.profiling_statistics += stats\n\n # Build the soma, with the default parameters\n result, stats = nmv.utilities.profile_function(nmv.builders.reconstruct_soma_mesh, self)\n self.profiling_statistics += stats\n\n # Build the arbors and connect them to the soma\n if self.options.mesh.soma_connection == nmv.enums.Meshing.SomaConnection.CONNECTED:\n\n # Build the arbors\n result, stats = nmv.utilities.profile_function(self.build_arbors, True)\n self.profiling_statistics += stats\n\n # Connect to the soma\n result, stats = nmv.utilities.profile_function(\n nmv.builders.connect_arbors_to_soma, self)\n self.profiling_statistics += stats\n\n # Build the arbors only without any connection to the soma\n else:\n # Build the arbors\n result, stats = nmv.utilities.profile_function(self.build_arbors, False)\n self.profiling_statistics += stats\n\n # Tessellation\n result, stats = nmv.utilities.profile_function(nmv.builders.decimate_neuron_mesh, self)\n self.profiling_statistics += stats\n\n # Surface roughness\n result, stats = nmv.utilities.profile_function(\n nmv.builders.add_surface_noise_to_arbor, self)\n self.profiling_statistics += stats\n\n # Add the spines\n result, stats = nmv.utilities.profile_function(nmv.builders.add_spines_to_surface, self)\n self.profiling_statistics += stats\n\n # Join all the objects into a single object\n result, stats = nmv.utilities.profile_function(\n nmv.builders.join_mesh_object_into_single_object, self)\n self.profiling_statistics += stats\n\n # Transform to the global coordinates, if required\n result, stats = nmv.utilities.profile_function(\n nmv.builders.transform_to_global_coordinates, self)\n self.profiling_statistics += stats\n\n # Collect the stats. of the mesh\n result, stats = nmv.utilities.profile_function(nmv.builders.collect_mesh_stats, self)\n self.profiling_statistics += stats\n\n # Done\n nmv.logger.header('Mesh Reconstruction Done!')\n nmv.logger.log(self.profiling_statistics)\n\n # Write the stats to file\n nmv.builders.write_statistics_to_file(builder=self, tag='skinning')", "def populate_mesh():\n # Read MeSH descriptor and supplementary terms\n desc_df = pd.read_table(os.path.join(DATA_DIR, 'data/descriptor-terms.tsv'))\n supp_df = pd.read_table(os.path.join(DATA_DIR, 'data/supplemental-terms.tsv'))\n desc_df.TermName = desc_df.TermName.str.lower()\n supp_df.TermName = supp_df.TermName.str.lower()\n # Get the preferred name for each term\n preferred_name = dict()\n for term, df in desc_df.groupby(\"DescriptorUI\"):\n preferred_name[term] = list(df[(df.PreferredConceptYN == \"Y\") & (df.ConceptPreferredTermYN == \"Y\") & (\n df.RecordPreferredTermYN == \"Y\")].TermName)[0]\n for term, df in supp_df.groupby(\"SupplementalRecordUI\"):\n preferred_name[term] = list(df[(df.PreferredConceptYN == \"Y\") & (df.ConceptPreferredTermYN == \"Y\") & (\n df.RecordPreferredTermYN == \"Y\")].TermName)[0]\n # Fix unicode nonsense\n upreferred_name = {k: unidecode(v.decode('utf-8')) for k, v in preferred_name.items()}\n\n # Check unicode munging\n # {preferred_name[k]:upreferred_name[k] for k,v in preferred_name.items() if preferred_name[k] != upreferred_name[k]}\n\n # Batch insert\n mesh_obj = [MeSH_Term(id=x[0], name=x[1]) for x in upreferred_name.items()]\n MeSH_Term.objects.bulk_create(mesh_obj, batch_size=10000)", "def update_geometries(self) -> None:\n\n # Reset containers\n dict_stones = {}\n dict_scenes = {}\n\n # Wait for the directory to recive files\n while(len(os.listdir(self.dump_dir)) == 0):\n time.sleep(1)\n\n # Get and fit files in dict stones/scenes\n for file_name in os.listdir(self.dump_dir):\n if file_name.endswith(\".ply\"):\n path_file = os.path.join(self.dump_dir, file_name)\n\n mesh = o3d.io.read_triangle_mesh(path_file)\n self._rotate_mesh(mesh) # to simulate axonometry\n\n pos = int(file_name.split('_')[0])\n\n if 'stone' in file_name:\n dict_stones[pos] = mesh\n\n elif 'scene' in file_name:\n pcd = mesh.sample_points_uniformly(number_of_points=6000) # cvt into pcd for visualization\n pcd.paint_uniform_color(self._rgb_2_norm([102,255,153]))\n dict_scenes[pos] = pcd\n \n # Sort the queries by stacking order\n dict_stones = {k: dict_stones[k] for k in sorted(dict_stones)}\n dict_scenes = {k: dict_scenes[k] for k in sorted(dict_scenes)}\n\n # Update stones: merge all the stones\n if len(list(dict_stones.values())) != 0:\n mesh = list(dict_stones.values())[0]\n for i, item in enumerate(list(dict_stones.values())):\n if i != len(list(dict_stones.values()))-1:\n item.paint_uniform_color([1, 0.706, 0]) # prev stones: yellow\n else:\n item.paint_uniform_color([1, 0, 0]) # last stone: red\n mesh += item\n\n # Update scene: refresh point cloud\n pcd = list(dict_scenes.values())[-1]\n\n # Replace values in geometries\n self.pcd_scene.points = pcd.points\n self.pcd_scene.colors = pcd.colors\n self.mesh_stones.vertices = mesh.vertices\n self.mesh_stones.vertex_normals = mesh.vertex_normals\n self.mesh_stones.vertex_colors = mesh.vertex_colors\n self.mesh_stones.triangles = mesh.triangles", "def setWeights(self, componentList=[]):\n print('!!! - DEPRICATED: skinClusterData.setWeights()! Use loadWeights() method instead - !!!')\n\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Component List\n if not componentList: componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n indexList = OpenMaya.MIntArray()\n componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n componentFn.getElements(indexList)\n componentIndexList = list(indexList)\n\n # ===========================\n # - Set SkinCluster Weights -\n # ===========================\n\n # Build influence index array\n infIndexArray = OpenMaya.MIntArray()\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n [infIndexArray.append(i) for i in range(len(influenceList))]\n\n # Build master weight array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, False, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return influenceList", "def reuseGeometryNodes(self, geometry: 'SbBool') -> \"void\":\n return _coin.SoToVRML2Action_reuseGeometryNodes(self, geometry)", "def remapGeometry(self, geometry):\n # Checks\n oldGeometry = self._data['affectedGeometry'][0]\n if geometry == oldGeometry: return geometry\n\n # Check Skin Geo Data\n if not self._data.has_key(oldGeometry):\n raise Exception('SkinClusterData: No skin geometry data for affected geometry \"' + oldGeometry + '\"!')\n\n # Remap Geometry\n self._data['affectedGeometry'] = [geometry]\n\n # Update Skin Geo Data\n self._data[geometry] = self._data[oldGeometry]\n self._data.pop(oldGeometry)\n\n # Print Message\n print('Geometry for skinCluster \"' + self._data[\n 'name'] + '\" remaped from \"' + oldGeometry + '\" to \"' + geometry + '\"')\n\n # Return result\n return self._data['affectedGeometry']", "def _preinitialize(self):\n from spatialdata.units.Nondimensional import Nondimensional\n normalizer = Nondimensional()\n normalizer._configure()\n\n # Setup mesh\n cs = CSCart()\n cs.inventory.spaceDim = 2\n cs._configure()\n from pylith.meshio.MeshIOAscii import MeshIOAscii\n importer = MeshIOAscii()\n importer.inventory.filename = \"data/tri3.mesh\"\n importer.inventory.coordsys = cs\n importer._configure()\n mesh = importer.read(debug=False, interpolate=False)\n\n # Setup material\n from pylith.feassemble.FIATSimplex import FIATSimplex\n cell = FIATSimplex()\n cell.inventory.dimension = 2\n cell.inventory.degree = 1\n cell.inventory.order = 1\n cell._configure()\n from pylith.feassemble.Quadrature import Quadrature\n quadrature = Quadrature()\n quadrature.inventory.cell = cell\n quadrature._configure()\n \n from spatialdata.spatialdb.SimpleDB import SimpleDB\n from spatialdata.spatialdb.SimpleIOAscii import SimpleIOAscii\n iohandler = SimpleIOAscii()\n iohandler.inventory.filename = \"data/elasticplanestrain.spatialdb\"\n iohandler._configure()\n db = SimpleDB()\n db.inventory.label = \"elastic plane strain\"\n db.inventory.iohandler = iohandler\n db._configure()\n\n from pylith.materials.ElasticPlaneStrain import ElasticPlaneStrain\n material = ElasticPlaneStrain()\n material.inventory.label = \"elastic plane strain\"\n material.inventory.id = 0\n material.inventory.dbProperties = db\n material.inventory.quadrature = quadrature\n material._configure()\n \n from pylith.meshio.OutputMatElastic import OutputMatElastic\n material.output = OutputMatElastic()\n material.output._configure()\n material.output.writer._configure()\n\n # Setup integrator\n integrator = ElasticityExplicitLgDeform()\n integrator.preinitialize(mesh, material)\n return (mesh, integrator)", "def loadWeights(self,\n skinCluster=None,\n influenceList=None,\n componentList=None,\n normalize=True):\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n if not skinCluster: skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Influence List\n if not influenceList: influenceList = self._influenceData.keys() or []\n for influence in influenceList:\n if not influence in cmds.skinCluster(skinCluster, q=True, inf=True) or []:\n raise Exception(\n 'Object \"' + influence + '\" is not a valid influence of skinCluster \"' + skinCluster + '\"! Unable to load influence weights...')\n if not self._influenceData.has_key(influence):\n raise Exception('No influence data stored for \"' + influence + '\"! Unable to load influence weights...')\n\n # Check Component List\n if not componentList:\n componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n # indexList = OpenMaya.MIntArray()\n # componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n # componentFn.getElements(indexList)\n # componentIndexList = list(indexList)\n componentIndexList = glTools.utils.component.getSingleIndexComponentList(componentList)\n componentIndexList = componentIndexList[componentIndexList.keys()[0]]\n\n # =====================================\n # - Set SkinCluster Influence Weights -\n # =====================================\n\n # Get Influence Index\n infIndexArray = OpenMaya.MIntArray()\n for influence in influenceList:\n infIndex = glTools.utils.skinCluster.getInfluencePhysicalIndex(skinCluster, influence)\n infIndexArray.append(infIndex)\n\n # Build Weight Array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, normalize, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return list(wtArray)", "def _update_materials(self):\n\n for rank in range(comm.size):\n number_i = comm.bcast(self.number, root=rank)\n\n for mat in number_i.materials:\n nuclides = []\n densities = []\n for nuc in number_i.nuclides:\n if nuc in self.nuclides_with_data:\n val = 1.0e-24 * number_i.get_atom_density(mat, nuc)\n\n # If nuclide is zero, do not add to the problem.\n if val > 0.0:\n if self.round_number:\n val_magnitude = np.floor(np.log10(val))\n val_scaled = val / 10**val_magnitude\n val_round = round(val_scaled, 8)\n\n val = val_round * 10**val_magnitude\n\n nuclides.append(nuc)\n densities.append(val)\n else:\n # Only output warnings if values are significantly\n # negative. CRAM does not guarantee positive\n # values.\n if val < -1.0e-21:\n print(f'WARNING: nuclide {nuc} in material'\n f'{mat} is negative (density = {val}'\n\n ' atom/b-cm)')\n\n number_i[mat, nuc] = 0.0\n\n # Update densities on C API side\n mat_internal = openmc.lib.materials[int(mat)]\n mat_internal.set_densities(nuclides, densities)\n\n # TODO Update densities on the Python side, otherwise the\n # summary.h5 file contains densities at the first time step", "def create_mesh_data(self):\n\n # if len(self.physical_surfaces) > 1:\n # self.geom.boolean_union(self.physical_surfaces)\n\n self.__physical_surfaces__()\n\n directory = os.getcwd() + '/debug/gmsh/'\n\n mesh_file = '{}{}.msh'.format(directory, self.filename)\n geo_file = '{}{}.geo'.format(directory, self.filename)\n vtk_file = '{}{}.vtu'.format(directory, self.filename)\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n mesh_data = pygmsh.generate_mesh(\n self.geom, verbose=False, dim=2,\n prune_vertices=False,\n remove_faces=False,\n geo_filename=geo_file\n )\n\n # meshio.write(mesh_file, mesh_data)\n # meshio.write(vtk_file, mesh_data)\n\n return mesh_data", "def old_generate_geometries(self):\n start = timeit.default_timer()\n intcos = self.generate_displacements() \n self.disps = []\n for gridpoint in intcos:\n tmp = OrderedDict([(self.mol.unique_geom_parameters[i], gridpoint[i]) for i in range(intcos.shape[1])])\n self.disps.append(tmp)\n # grab cartesians, internals, interatomics representations of geometry\n cartesians = []\n internals = []\n interatomics = []\n failed = 0 # keep track of failed 3 co-linear atom configurations\n # this loop of geometry transformations/saving is pretty slow, but scales linearly at least\n for i, disp in enumerate(self.disps):\n self.mol.update_intcoords(disp)\n try:\n cart = self.mol.zmat2xyz()\n except:\n failed += 1\n continue\n cartesians.append(cart)\n internals.append(disp)\n idm = gth.get_interatom_distances(cart)\n # remove float noise for duplicate detection\n idm = np.round(idm[np.tril_indices(len(idm),-1)],10)\n interatomics.append(idm)\n # preallocate dataframe space \n if failed > 0:\n print(\"Warning: {} configurations had invalid Z-Matrices with 3 co-linear atoms, tossing them out! Use a dummy atom to prevent.\".format(failed))\n df = pd.DataFrame(index=np.arange(0, len(self.disps)-failed), columns=self.bond_columns)\n df[self.bond_columns] = interatomics\n df['cartesians'] = cartesians\n df['internals'] = internals \n self.all_geometries = df\n print(\"Geometry grid generated in {} seconds\".format(round((timeit.default_timer() - start),2)))", "def GroupsFromGeometry(self, geoGroups):\n\n print('\\nBoundary assignment')\n\n \n # Create groups for boundary nodes\n # Nodes connected to less than 8 (3D) or 4 (2D) elements are on boundary\n\n\n ncon = 8\n\n if self.lmodel.D() == 2:\n ncon = 4\n\n \n \n bnd_criterion = self.smesh.GetCriterion(SMESH.NODE,SMESH.FT_NodeConnectivityNumber,SMESH.FT_LessThan,ncon)\n\n bnd_filter = self.smesh.GetFilterFromCriteria([bnd_criterion])\n\n bnd_ids = self.Mesh.GetIdsFromFilter(bnd_filter) \n\n\n\n # Create empty mesh groups based on geometry groups\n\n Mesh_groups = {}\n\n self.mg = {}\n\n for group in geoGroups:\n\n Mesh_groups[group.GetName()] = self.Mesh.CreateEmptyGroup(SMESH.NODE, group.GetName())\n\n self.mg[group.GetName()] = []\n \n \n\n # Look closest surface (group) and add to corresponding mesh group\n\n for node in bnd_ids:\n\n # node_xyz = self.Mesh.GetNodeXYZ( node )\n node_xyz = self.Mesh.GetNodeXYZ( node )\n \n # node_vertex = self.geompy.MakeVertex(node_xyz[0], node_xyz[1], node_xyz[2])\n node_vertex = self.geompy.MakeVertex(np.float64( node_xyz[0]), np.float64(node_xyz[1]), np.float64(node_xyz[2]) ) \n\n dist = float(1000)\n\n closest_bnd = \"\"\n\n for group in geoGroups:\n\n distAux = self.geompy.MinDistance( group, node_vertex )\n \n if distAux < dist:\n\n closest_bnd = group.GetName()\n\n dist = distAux\n \n \n Mesh_groups[ closest_bnd ].Add( [node] )\n\n self.mg[closest_bnd].append(node)", "def init_shards(self, output_prefix, corpus, shardsize=4096, dtype=_default_dtype):\n\n if not gensim.utils.is_corpus(corpus):\n raise ValueError('Cannot initialize shards without a corpus to read'\n ' from! (Got corpus type: {0})'.format(type(corpus)))\n\n proposed_dim = self._guess_n_features(corpus)\n if proposed_dim != self.dim:\n if self.dim is None:\n logger.info('Deriving dataset dimension from corpus: '\n '{0}'.format(proposed_dim))\n else:\n logger.warn('Dataset dimension derived from input corpus diffe'\n 'rs from initialization argument, using corpus.'\n '(corpus {0}, init arg {1})'.format(proposed_dim,\n self.dim))\n\n self.dim = proposed_dim\n self.offsets = [0]\n\n start_time = time.clock()\n\n logger.info('Running init from corpus.')\n\n for n, doc_chunk in enumerate(gensim.utils.grouper(corpus, chunksize=shardsize)):\n logger.info('Chunk no. {0} at {1} s'.format(n, time.clock() - start_time))\n\n current_shard = numpy.zeros((len(doc_chunk), self.dim), dtype=dtype)\n logger.debug('Current chunk dimension: '\n '{0} x {1}'.format(len(doc_chunk), self.dim))\n\n for i, doc in enumerate(doc_chunk):\n doc = dict(doc)\n current_shard[i][list(doc)] = list(gensim.matutils.itervalues(doc))\n\n # Handles the updating as well.\n if self.sparse_serialization:\n current_shard = sparse.csr_matrix(current_shard)\n\n self.save_shard(current_shard)\n\n end_time = time.clock()\n logger.info('Built {0} shards in {1} s.'.format(self.n_shards, end_time - start_time))", "def rebuild_and_update(self):\n self.generate_collectobot_data()\n self.make_graph_data()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mirror SkinCluster Data using search and replace for naming. This method doesn not perform closest point on surface mirroring.
def mirror(self, search='lf', replace='rt'): # ========== # - Checks - # ========== # =========================== # - Search and Replace Name - # =========================== if self._data['name'].count(search): self._data['name'] = self._data['name'].replace(search, replace) # =============================== # - Search and Replace Geometry - # =============================== for i in range(len(self._data['affectedGeometry'])): if self._data['affectedGeometry'][i].count(search): # Get 'mirror' geometry mirrorGeo = self._data['affectedGeometry'][i].replace(search, replace) # Check 'mirror' geometry if not cmds.objExists(mirrorGeo): print ('WARNING: Mirror geoemtry "' + mirrorGeo + '" does not exist!') # Assign 'mirror' geometry self.remapGeometry(mirrorGeo) # self._data['affectedGeometry'][i] = mirrorGeo # Search and Replace Inlfuences influenceList = self._influenceData.keys() for i in range(len(influenceList)): if influenceList[i].count(search): # Get 'mirror' influence mirrorInfluence = influenceList[i].replace(search, replace) # Check 'mirror' influence if not cmds.objExists(mirrorInfluence): print ('WARNING: Mirror influence "' + mirrorInfluence + '" does not exist!') # Assign 'mirror' influence self.remapInfluence(influenceList[i], mirrorInfluence)
[ "def rebuild(self):\n # ==========\n # - Checks -\n # ==========\n\n # Check geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data for a different geometry!')\n\n # =======================\n # - Rebuild SkinCluster -\n # =======================\n\n # Start timer\n timer = cmds.timerX()\n\n # Initialize Temp Joint\n tempJnt = ''\n\n # Unlock Influences\n influenceList = self._influenceData.keys()\n for influence in influenceList:\n if cmds.objExists(influence + '.liw'):\n if cmds.getAttr(influence + '.liw', l=True):\n try:\n cmds.setAttr(influence + '.liw', l=False)\n except:\n print(\n 'Error unlocking attribute \"' + influence + '.liw\"! This could problems when rebuilding the skinCluster...')\n if cmds.getAttr(influence + '.liw'):\n try:\n cmds.setAttr(influence + '.liw', False)\n except:\n print(\n 'Error setting attribute \"' + influence + '.liw\" to False! This could problems when rebuilding the skinCluster...')\n\n # Check SkinCluster\n skinCluster = self._data['name']\n if not cmds.objExists(skinCluster):\n\n # Get Transform Influences\n jointList = [inf for inf in influenceList if not self._influenceData[inf]['type']]\n\n # Check Transform Influences\n if not jointList:\n\n # Create Temporary Bind Joint\n cmds.select(cl=1)\n tempJnt = cmds.joint(n=skinCluster + '_tempJoint')\n print(\n 'No transform influences specified for skinCluster \"' + skinCluster + '\"! Creating temporary bind joint \"' + tempJnt + '\"!')\n jointList = [tempJnt]\n\n else:\n\n # Get Surface Influences\n influenceList = [inf for inf in influenceList if self._influenceData[inf]['type']]\n\n # Create skinCluster\n skinCluster = cmds.skinCluster(jointList, skinGeo, tsb=True, n=skinCluster)[0]\n\n else:\n\n # Check Existing SkinCluster\n affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster)\n if affectedGeo.keys()[0] != skinGeo:\n raise Exception(\n 'SkinCluster \"' + skinCluster + '\" already exists, but is not connected to the expeced geometry \"' + skinGeo + '\"!')\n\n # Add skinCluster influences\n for influence in influenceList:\n\n # Check influence\n if not cmds.objExists(influence):\n raise Exception(\n 'Influence \"' + influence + '\" does not exist! Use remapInfluence() to apply data to a different influence!')\n\n # Check existing influence connection\n if not cmds.skinCluster(skinCluster, q=True, inf=True).count(influence):\n\n # Add influence\n if self._influenceData[influence]['type']:\n # Geometry\n polySmooth = self._influenceData[influence]['polySmooth']\n nurbsSamples = self._influenceData[influence]['nurbsSamples']\n cmds.skinCluster(skinCluster, e=True, ai=influence, ug=True, ps=polySmooth, ns=nurbsSamples, wt=0.0,\n lockWeights=True)\n\n else:\n # Transform\n cmds.skinCluster(skinCluster, e=True, ai=influence, wt=0.0, lockWeights=True)\n\n # Bind Pre Matrix\n if self._influenceData[influence]['bindPreMatrix']:\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n cmds.connectAttr(self._influenceData[influence]['bindPreMatrix'],\n skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', f=True)\n\n # Load skinCluster weights\n cmds.setAttr(skinCluster + '.normalizeWeights', 0)\n glTools.utils.skinCluster.clearWeights(skinGeo)\n self.loadWeights()\n cmds.setAttr(skinCluster + '.normalizeWeights', 1)\n\n # Restore Custom Attribute Values and Connections\n self.setDeformerAttrValues()\n self.setDeformerAttrConnections()\n\n # Clear Selection\n cmds.select(cl=True)\n\n # =================\n # - Return Result -\n # =================\n\n # Print Timed Result\n totalTime = cmds.timerX(st=timer)\n print('SkinClusterData: Rebuild time for skinCluster \"' + skinCluster + '\": ' + str(totalTime))\n\n return skinCluster", "def __swap_and_recalculate_clusters(self):\n # http://www.math.le.ac.uk/people/ag153/homepage/KmeansKmedoids/Kmeans_Kmedoids.html\n print(\"swap and recompute\")\n cluster_dist = {}\n for medoid in self.medoids: # for each medoid\n is_shortest_medoid_found = False\n for data_index in self.clusters[\n medoid\n ]: # for each point in the current medoid's cluster\n if data_index != medoid: # exclude the medoid itself\n # create a list of the elements of the cluster\n cluster_list = list(self.clusters[medoid])\n # make the current point the temporary medoid\n cluster_list[\n self.clusters[medoid].index(data_index)\n ] = medoid\n # compute new cluster distance obtained by swapping the medoid\n new_distance = self.calculate_inter_cluster_distance(\n data_index, cluster_list\n )\n # if this new distance is smaller than the previous one\n if new_distance < self.cluster_distances[medoid]:\n print(\"new better medoid: \", data_index)\n cluster_dist[data_index] = new_distance\n is_shortest_medoid_found = True\n break # exit for loop for this medoid, since a better one has been found\n # if no better medoid has been found, keep the current one\n if is_shortest_medoid_found is False:\n print(\"no better medoids found, keep: \", medoid)\n cluster_dist[medoid] = self.cluster_distances[medoid]\n print(\"cluster_dist: \", cluster_dist)\n return cluster_dist", "def remapGeometry(self, geometry):\n # Checks\n oldGeometry = self._data['affectedGeometry'][0]\n if geometry == oldGeometry: return geometry\n\n # Check Skin Geo Data\n if not self._data.has_key(oldGeometry):\n raise Exception('SkinClusterData: No skin geometry data for affected geometry \"' + oldGeometry + '\"!')\n\n # Remap Geometry\n self._data['affectedGeometry'] = [geometry]\n\n # Update Skin Geo Data\n self._data[geometry] = self._data[oldGeometry]\n self._data.pop(oldGeometry)\n\n # Print Message\n print('Geometry for skinCluster \"' + self._data[\n 'name'] + '\" remaped from \"' + oldGeometry + '\" to \"' + geometry + '\"')\n\n # Return result\n return self._data['affectedGeometry']", "def mirror(s):", "def x_mirror(self, name: str, replace: Optional[str] = None) -> \"SimplePolygon\":\n # Grab some values from *simple_polygon* (i.e. *self*):\n simple_polygon: SimplePolygon = self\n simple_polygon_name: str = simple_polygon.name\n\n points: List[P2D] = simple_polygon.points\n\n # Compute *new_name* and *x_mirrored_points*:\n new_name: str = (name if replace is None\n else simple_polygon_name.replace(name, replace))\n point: P2D\n x_mirrored_points: List[P2D] = [P2D(point.x, -point.y) for point in points]\n\n # Construct the final *x_mirrored_simple_polygon* and return it.\n x_mirrored_simple_polygon: SimplePolygon = SimplePolygon(new_name,\n x_mirrored_points, lock=True)\n return x_mirrored_simple_polygon", "def cluster(player_data, team_data, stats):\n # prepare data\n player_data = player_data.loc[:, ['Name', 'Team'] + stats]\n cluster_data = player_data.loc[:, stats]\n sc_X = StandardScaler()\n cluster_data = sc_X.fit_transform(cluster_data)\n cluster_data = pd.DataFrame(cluster_data, columns=stats)\n kmeans = KMeans(n_clusters=4, init='k-means++', max_iter=300, n_init=10, random_state=0)\n predictions = kmeans.fit_predict(cluster_data)\n player_data['Cluster'] = predictions\n\n centroids = kmeans.cluster_centers_\n centroids = pd.DataFrame(centroids, columns=stats)\n centroidBarGraph(stats, centroids)\n\n player_data['Distance from Centroid'] = 0\n for index, row in player_data.iterrows():\n for stat in stats:\n player_data.loc[index, 'Distance from Centroid'] += pow(cluster_data.loc[index, stat] - centroids.loc[row['Cluster'], stat], 2)\n player_data.loc[index, 'Distance from Centroid'] = math.sqrt(player_data.loc[index, 'Distance from Centroid'])\n player_data.to_csv(\"df_withclusters.csv\")\n\n cluster0 = player_data.loc[player_data['Cluster'] == 0]\n cluster0 = cluster0.drop(columns='Cluster')\n cluster0 = cluster0.sort_values('Distance from Centroid', ascending=True)\n cluster0 = cluster0.reset_index(drop=True)\n cluster0.to_csv(\"Cluster0.csv\")\n cluster1 = player_data.loc[player_data['Cluster'] == 1]\n cluster1 = cluster1.drop(columns='Cluster')\n cluster1 = cluster1.sort_values('Distance from Centroid', ascending=True)\n cluster1 = cluster1.reset_index(drop=True)\n cluster1.to_csv(\"Cluster1.csv\")\n cluster2 = player_data.loc[player_data['Cluster'] == 2]\n cluster2 = cluster2.drop(columns='Cluster')\n cluster2 = cluster2.sort_values('Distance from Centroid', ascending=True)\n cluster2 = cluster2.reset_index(drop=True)\n cluster2.to_csv(\"Cluster2.csv\")\n cluster3 = player_data.loc[player_data['Cluster'] == 3]\n cluster3 = cluster3.drop(columns='Cluster')\n cluster3 = cluster3.sort_values('Distance from Centroid', ascending=True)\n cluster3 = cluster3.reset_index(drop=True)\n cluster3.to_csv(\"Cluster3.csv\")\n\n visualizeCluster(cluster_data, predictions)\n clusterVSwins(team_data, player_data)\n\n\n\n return cluster0, cluster1, cluster2, cluster3", "def clustering_experiment(dataset_name, params, verbose=0, random_seed=0):\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # loading data and breaking it into different dataset splits\n dataset = ClassificationDataset(data_path=CONFIG[\"paths\"][\"data_path\"],\n dataset_name=dataset_name,\n valid_size=0)\n imgs, labels = dataset.get_all_data()\n\n # computing scattering representations\n t0 = time.time()\n if(params.scattering):\n scattering_net, _ = scattering_layer(J=params.J, shape=(params.shape, params.shape),\n max_order=params.max_order, L=params.L)\n scattering_net = scattering_net.cuda() if device.type == 'cuda' else scattering_net\n print_(\"Computing scattering features for dataset...\", verbose=verbose)\n data = convert_images_to_scat(imgs, scattering=scattering_net,\n device=device, equalize=params.equalize,\n batch_size=params.batch_size,\n pad_size=params.shape)\n else:\n data = imgs\n n_labels = len(np.unique(labels))\n\n # reducing dimensionality of scattering features using pca\n if(params.pca == True):\n print_(f\"Reducidng dimensionality using PCA to {params.pca_dims}\", verbose=verbose)\n n_feats = data.shape[0]\n data = data.reshape(n_feats, -1)\n data = pca(data=data, target_dimensions=params.pca_dims)\n\n # POC preprocessing: removing the top directions of variance as a preprocessing step\n t1 = time.time()\n if(params.poc_preprocessing):\n print_(f\"POC algorithm removing {params.num_dims} directions\", verbose=verbose)\n poc = POC()\n poc.fit(data=data)\n proj_data = poc.transform(data=data, n_dims=params.num_dims)\n else:\n proj_data = data.reshape(data.shape[0], -1)\n\n # clustering using Ultra-Scalable Spectral Clustering\n t2 = time.time()\n if(params.uspec):\n print_(f\"Clustering using U-SPEC\", verbose=verbose)\n uspec = USPEC(p_interm=params.num_candidates, p_final=params.num_reps,\n n_neighbors=5, num_clusters=params.num_clusters,\n num_iters=100, random_seed=random_seed)\n preds = uspec.cluster(data=proj_data, verbose=verbose)\n else:\n print_(f\"Clustering using K-Means\", verbose=verbose)\n kmeans = KMeans(n_clusters=params.num_clusters, random_state=random_seed)\n kmeans = kmeans.fit(proj_data)\n preds = kmeans.labels_\n t3 = time.time()\n\n cluster_score, cluster_acc, cluster_nmi = compute_clustering_metrics(preds=preds,\n labels=labels)\n print_(f\"Clustering Accuracy: {round(cluster_acc,3)}\", verbose=verbose)\n print_(f\"Clustering ARI Score: {round(cluster_score,3)}\", verbose=verbose)\n print_(f\"Clustering ARI Score: {round(cluster_nmi,3)}\", verbose=verbose)\n\n # loading previous results, if any\n results_path = os.path.join(os.getcwd(), CONFIG[\"paths\"][\"results_path\"])\n _ = create_directory(results_path)\n if(params.fname != None and len(params.fname) > 0 and params.fname[-5:]==\".json\"):\n fname = params.fname\n else:\n poc = \"poc\" if params.poc_preprocessing==True else \"not-poc\"\n fname = f\"{dataset_name}_{poc}_clustering_results.json\"\n results_file = os.path.join(results_path, fname)\n if(os.path.exists(results_file)):\n with open(results_file) as f:\n data = json.load(f)\n n_exps = len(list(data.keys()))\n else:\n data = {}\n n_exps = 0\n # saving experiment parameters and results\n with open(results_file, \"w\") as f:\n cur_exp = {}\n cur_exp[\"params\"] = {}\n cur_exp[\"params\"][\"dataset\"] = dataset_name\n cur_exp[\"params\"][\"random_seed\"] = random_seed\n params = vars(params)\n for p in params:\n cur_exp[\"params\"][p] = params[p]\n cur_exp[\"results\"] = {}\n cur_exp[\"results\"][\"cluster_acc\"] = round(cluster_acc,3)\n cur_exp[\"results\"][\"cluster_ari\"] = round(cluster_score,3)\n cur_exp[\"results\"][\"cluster_nmi\"] = round(cluster_nmi,3)\n cur_exp[\"timing\"] = {}\n cur_exp[\"timing\"][\"scattering\"] = t1 - t0\n cur_exp[\"timing\"][\"preprocessing\"] = t2 - t1\n cur_exp[\"timing\"][\"clustering\"] = t3 - t2\n cur_exp[\"timing\"][\"total\"] = t3 - t0\n print_(cur_exp, verbose=verbose)\n data[f\"experiment_{n_exps}\"] = cur_exp\n json.dump(data, f)\n\n return", "def _spectral_to_original(self):\n # embedding is a nested list containing the indices of the points\n # that belong to each cluster.\n embedding = self.clusters.values()\n orig_clustering = [[self.orig_points[p_idx] for p_idx in cluster]\n for cluster in embedding]\n return orig_clustering", "def edit_singularity_mesh(pattern):", "def buildData(self, skinCluster):\n # ==========\n # - Checks -\n # ==========\n\n # Check skinCluster\n self.verifySkinCluster(skinCluster)\n\n # Clear Data\n self.reset()\n\n # =======================\n # - Build Deformer Data -\n # =======================\n\n # Start Timer\n timer = cmds.timerX()\n\n self._data['name'] = skinCluster\n self._data['type'] = 'skinCluster'\n\n # Get affected geometry\n skinGeoShape = cmds.skinCluster(skinCluster, q=True, g=True)\n if len(skinGeoShape) > 1: raise Exception(\n 'SkinCluster \"' + skinCluster + '\" output is connected to multiple shapes!')\n if not skinGeoShape: raise Exception(\n 'Unable to determine affected geometry for skinCluster \"' + skinCluster + '\"!')\n skinGeo = cmds.listRelatives(skinGeoShape[0], p=True, pa=True)\n if not skinGeo: raise Exception('Unable to determine geometry transform for object \"' + skinGeoShape + '\"!')\n self._data['affectedGeometry'] = skinGeo\n skinGeo = skinGeo[0]\n\n skinClusterSet = glTools.utils.deformer.getDeformerSet(skinCluster)\n\n self._data[skinGeo] = {}\n self._data[skinGeo]['index'] = 0\n self._data[skinGeo]['geometryType'] = str(cmds.objectType(skinGeoShape))\n self._data[skinGeo]['membership'] = glTools.utils.deformer.getDeformerSetMemberIndices(skinCluster, skinGeo)\n self._data[skinGeo]['weights'] = []\n\n if self._data[skinGeo]['geometryType'] == 'mesh':\n self._data[skinGeo]['mesh'] = meshData.MeshData(skinGeo)\n\n # ========================\n # - Build Influence Data -\n # ========================\n\n # Get skinCluster influence list\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n if not influenceList: raise Exception(\n 'Unable to determine influence list for skinCluster \"' + skinCluster + '\"!')\n\n # Get Influence Wieghts\n weights = glTools.utils.skinCluster.getInfluenceWeightsAll(skinCluster)\n\n # For each influence\n for influence in influenceList:\n\n # Initialize influence data\n self._influenceData[influence] = {}\n\n # Get influence index\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n self._influenceData[influence]['index'] = infIndex\n\n # Get Influence BindPreMatrix\n bindPreMatrix = cmds.listConnections(skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', s=True, d=False,\n p=True)\n if bindPreMatrix:\n self._influenceData[influence]['bindPreMatrix'] = bindPreMatrix[0]\n else:\n self._influenceData[influence]['bindPreMatrix'] = ''\n\n # Get Influence Type (Transform/Geometry)\n infGeocmdsonn = cmds.listConnections(skinCluster + '.driverPoints[' + str(infIndex) + ']')\n if infGeocmdsonn:\n self._influenceData[influence]['type'] = 1\n self._influenceData[influence]['polySmooth'] = cmds.skinCluster(skinCluster, inf=influence, q=True,\n ps=True)\n self._influenceData[influence]['nurbsSamples'] = cmds.skinCluster(skinCluster, inf=influence, q=True,\n ns=True)\n else:\n self._influenceData[influence]['type'] = 0\n\n # Get Influence Weights\n pInd = glTools.utils.skinCluster.getInfluencePhysicalIndex(skinCluster, influence)\n self._influenceData[influence]['wt'] = weights[pInd]\n\n # =========================\n # - Custom Attribute Data -\n # =========================\n\n # Add Pre-Defined Custom Attributes\n self.getDeformerAttrValues()\n self.getDeformerAttrConnections()\n\n # =================\n # - Return Result -\n # =================\n\n skinTime = cmds.timerX(st=timer)\n print('SkinClusterData: Data build time for \"' + skinCluster + '\": ' + str(skinTime))", "def change_cluster_unit(self, new_cluster_column_name):\n\n # 1. Check new cluster information exists in anndata.\n if new_cluster_column_name in self.adata.obs.columns:\n if not f\"{new_cluster_column_name}_colors\" in self.adata.uns.keys():\n sc.pl.scatter(self.adata,\n color=new_cluster_column_name,\n basis=self.embedding_name[2:])\n else:\n raise ValueError(f\"{new_cluster_column_name} was not found in anndata\")\n\n\n # 2. Reset previous GRN data and simoulation data\n attributes_remained = ['TFdict', 'adata', 'cv_mean_selected_genes',\n 'embedding_name', 'high_var_genes', 'knn',\n 'knn_smoothing_w', 'pca', 'cv_mean_score',\n 'cv_mean_selected', 'pcs', #'GRN_unit',\n 'active_regulatory_genes']\n\n attributes = list(self.__dict__.keys())\n for i in attributes:\n if i not in attributes_remained:\n delattr(self, i)\n\n # 4. Update cluster info\n self.cluster_column_name = new_cluster_column_name\n\n # 3. Update color information\n col_dict = _get_clustercolor_from_anndata(adata=self.adata,\n cluster_name=new_cluster_column_name,\n return_as=\"dict\")\n self.colorandum = np.array([col_dict[i] for i in self.adata.obs[new_cluster_column_name]])", "def set_cluster(self, data):\n cluster = Cluster(data['name'])\n for host in data['hosts']:\n cluster.add_host(**host)\n self._cluster = cluster", "def update_centroids(labelled_data, centroids, id_to_name_mapping):\n for idx, cluster_name in id_to_name_mapping.items():\n single_cluster_datapoints = labelled_data[labelled_data[:, 2] == idx]\n new_centroid = single_cluster_datapoints[:, :2].mean(axis=0)\n centroids[cluster_name] = new_centroid\n return centroids", "def _update_cluster_name_property(self, name):\n self.configuration_manager.apply_system_override({'cluster_name':\n name})", "def rebuildWorldSpaceData(self, targetGeo='', method='closestPoint'):\n # Start timer\n timer = cmds.timerX()\n\n # Display Progress\n glTools.utils.progressBar.init(status=('Rebuilding world space skinCluster data...'), maxValue=100)\n\n # ==========\n # - Checks -\n # ==========\n\n # Get Source Geometry\n sourceGeo = self._data['affectedGeometry'][0]\n\n # Target Geometry\n if not targetGeo: targetGeo = sourceGeo\n\n # Check Deformer Data\n if not self._data.has_key(sourceGeo):\n glTools.utils.progressBar.end()\n raise Exception('No deformer data stored for geometry \"' + sourceGeo + '\"!')\n\n # Check Geometry\n if not cmds.objExists(targetGeo):\n glTools.utils.progressBar.end()\n raise Exception('Geometry \"' + targetGeo + '\" does not exist!')\n if not glTools.utils.mesh.isMesh(targetGeo):\n glTools.utils.progressBar.end()\n raise Exception('Geometry \"' + targetGeo + '\" is not a valid mesh!')\n\n # Check Mesh Data\n if not self._data[sourceGeo].has_key('mesh'):\n glTools.utils.progressBar.end()\n raise Exception('No world space mesh data stored for mesh geometry \"' + sourceGeo + '\"!')\n\n # =====================\n # - Rebuild Mesh Data -\n # =====================\n\n meshData = self._data[sourceGeo]['mesh']._data\n\n meshUtil = OpenMaya.MScriptUtil()\n numVertices = len(meshData['vertexList']) / 3\n numPolygons = len(meshData['polyCounts'])\n polygonCounts = OpenMaya.MIntArray()\n polygonConnects = OpenMaya.MIntArray()\n meshUtil.createIntArrayFromList(meshData['polyCounts'], polygonCounts)\n meshUtil.createIntArrayFromList(meshData['polyConnects'], polygonConnects)\n\n # Rebuild Vertex Array\n vertexArray = OpenMaya.MFloatPointArray(numVertices, OpenMaya.MFloatPoint.origin)\n vertexList = [vertexArray.set(i, meshData['vertexList'][i * 3], meshData['vertexList'][i * 3 + 1],\n meshData['vertexList'][i * 3 + 2], 1.0) for i in xrange(numVertices)]\n\n # Rebuild Mesh\n meshFn = OpenMaya.MFnMesh()\n meshDataFn = OpenMaya.MFnMeshData().create()\n meshObj = meshFn.create(numVertices, numPolygons, vertexArray, polygonCounts, polygonConnects, meshDataFn)\n\n # Create Mesh Intersector\n meshPt = OpenMaya.MPointOnMesh()\n meshIntersector = OpenMaya.MMeshIntersector()\n if method == 'closestPoint': meshIntersector.create(meshObj)\n\n # ========================================\n # - Rebuild Weights and Membership List -\n # ========================================\n\n # Initialize Influence Weights and Membership\n influenceList = self._influenceData.keys()\n influenceWt = [[] for inf in influenceList]\n membership = set([])\n\n # Get Target Mesh Data\n targetMeshFn = glTools.utils.mesh.getMeshFn(targetGeo)\n targetMeshPts = targetMeshFn.getRawPoints()\n numTargetVerts = targetMeshFn.numVertices()\n targetPtUtil = OpenMaya.MScriptUtil()\n\n # Initialize Float Pointers for Barycentric Coords\n uUtil = OpenMaya.MScriptUtil(0.0)\n vUtil = OpenMaya.MScriptUtil(0.0)\n uPtr = uUtil.asFloatPtr()\n vPtr = vUtil.asFloatPtr()\n\n # Get Progress Step\n progressInd = int(numTargetVerts * 0.01)\n if progressInd < 1: progressInd = 1\n\n for i in range(numTargetVerts):\n\n # Get Target Point\n targetPt = OpenMaya.MPoint(targetPtUtil.getFloatArrayItem(targetMeshPts, (i * 3) + 0),\n targetPtUtil.getFloatArrayItem(targetMeshPts, (i * 3) + 1),\n targetPtUtil.getFloatArrayItem(targetMeshPts, (i * 3) + 2))\n\n # Get Closest Point Data\n meshIntersector.getClosestPoint(targetPt, meshPt)\n\n # Get Barycentric Coords\n meshPt.getBarycentricCoords(uPtr, vPtr)\n u = OpenMaya.MScriptUtil(uPtr).asFloat()\n v = OpenMaya.MScriptUtil(vPtr).asFloat()\n baryWt = [u, v, 1.0 - (u + v)]\n\n # Get Triangle Vertex IDs\n idUtil = OpenMaya.MScriptUtil([0, 1, 2])\n idPtr = idUtil.asIntPtr()\n meshFn.getPolygonTriangleVertices(meshPt.faceIndex(), meshPt.triangleIndex(), idPtr)\n triId = [OpenMaya.MScriptUtil().getIntArrayItem(idPtr, n) for n in range(3)]\n memId = [self._data[sourceGeo]['membership'].count(t) for t in triId]\n wtId = [self._data[sourceGeo]['membership'].index(t) for t in triId]\n\n # For Each Influence\n for inf in range(len(influenceList)):\n\n # Calculate Weight and Membership\n wt = 0.0\n isMember = False\n for n in range(3):\n\n # Check Against Source Membership\n if memId[n]:\n wt += self._influenceData[influenceList[inf]]['wt'][wtId[n]] * baryWt[n]\n isMember = True\n\n # Check Member\n if isMember:\n # Append Weight Value\n influenceWt[inf].append(wt)\n # Append Membership\n membership.add(i)\n\n # Update Progress Bar\n if not i % progressInd: glTools.utils.progressBar.update(step=1)\n\n # ========================\n # - Update Deformer Data -\n # ========================\n\n # Remap Geometry\n self.remapGeometry(targetGeo)\n\n # Rename SkinCluster\n targetSkinCluster = glTools.utils.skinCluster.findRelatedSkinCluster(targetGeo)\n if targetSkinCluster:\n self._data['name'] = targetSkinCluster\n else:\n prefix = targetGeo.split(':')[-1]\n self._data['name'] = prefix + '_skinCluster'\n\n # Update Membership and Weights\n self._data[sourceGeo]['membership'] = list(membership)\n for inf in range(len(influenceList)):\n self._influenceData[influenceList[inf]]['wt'] = influenceWt[inf]\n\n # =================\n # - Return Result -\n # =================\n\n # End Progress\n glTools.utils.progressBar.end()\n\n # Print Timed Result\n buildTime = cmds.timerX(st=timer)\n print(\n 'SkinClusterData: Rebuild world space data for skinCluster \"' + self._data['name'] + '\": ' + str(buildTime))\n\n # Return Weights\n return", "def skinCluster(dropoffRate=float, before=bool, exclusive=\"string\", split=bool, after=bool, smoothWeights=float, ignoreSelected=bool, nurbsSamples=int, ignoreHierarchy=bool, ignoreBindPose=bool, includeHiddenSelections=bool, weightDistribution=int, smoothWeightsMaxIterations=int, frontOfChain=bool, prune=bool, weight=float, normalizeWeights=int, baseShape=\"string\", volumeType=int, skinMethod=int, heatmapFalloff=float, obeyMaxInfluences=bool, unbind=bool, removeInfluence=\"string\", volumeBind=float, geometry=\"string\", useGeometry=bool, name=\"string\", unbindKeepHistory=bool, weightedInfluence=bool, moveJointsMode=bool, removeUnusedInfluence=bool, influence=\"string\", bindMethod=int, parallel=bool, forceNormalizeWeights=bool, addInfluence=\"string\", geometryIndices=bool, polySmoothness=float, afterReference=bool, remove=bool, maximumInfluences=int, selectInfluenceVerts=\"string\", addToSelection=bool, lockWeights=bool, deformerTools=bool, removeFromSelection=bool, recacheBindMatrices=bool, toSkeletonAndTransforms=bool, toSelectedBones=bool):\n pass", "def relabel_clusters_to_match(self, target_clustering):\n new_clu_labels = remap2match(self, target_clustering)\n self.from_clu2elm_dict({new_clu_labels[c]:el for c, el in self.clu2elm_dict.items()})\n return self", "def _do_clustering(self, tmp_dir):\r\n similarity_mat = self._generate_similarity_matrix(tmp_dir)\r\n self._similarity_mat = similarity_mat\r\n dist_mat = 1 - similarity_mat\r\n max_silhouette_score = -math.inf\r\n predicted_cluster = None\r\n continuous_decrease_cnt = 0\r\n\r\n for n_clusters_ in range(2, self._max_cluster + 1):\r\n clustering = cluster.SpectralClustering(\r\n n_clusters=n_clusters_, assign_labels=\"discretize\", random_state=0, affinity='precomputed').fit(\r\n similarity_mat)\r\n\r\n # Get clustering result and calculate the corresponding silhouette score.\r\n predicted = clustering.labels_\r\n sc = metrics.silhouette_score(dist_mat, predicted, metric='precomputed')\r\n\r\n # If a larger `n_clusters` leads to the same silhouette score as the smaller one,\r\n # we prefer the smaller `n_clusters`.\r\n if sc > max_silhouette_score:\r\n max_silhouette_score = sc\r\n predicted_cluster = predicted\r\n continuous_decrease_cnt = 0\r\n else:\r\n continuous_decrease_cnt += 1\r\n\r\n # If a second consecutive decrease on silhouette score is encountered, return the current best clustering\r\n # result(`predicted_cluster`).\r\n if continuous_decrease_cnt == 2:\r\n return predicted_cluster\r\n return predicted_cluster", "def _apply(self, dataset: Dataset) -> Dataset:\n dataset = copy.deepcopy(dataset)\n\n for pattern, replacement in self.replacement_map.items():\n replaced_col = dataset.data[self.columns[0]].str.replace(\n pat=pattern, repl=replacement\n )\n if self.derived_columns is not None:\n dataset.data[self.derived_columns[0]] = replaced_col\n else:\n dataset.data[self.columns[0]] = replaced_col\n\n return dataset" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rebuild a list of skinClusters from the stored SkinClusterListData
def rebuild(self, skinClusterList): # Start timer timer = cmds.timerX() # For Each SkinCluster for skinCluster in skinClusterList: # Check skinClusterData if not self._data.has_key(skinCluster): print('No data stored for skinCluster "' + skinCluster + '"! Skipping...') # Rebuild SkinCluster self._data[skinCluster].rebuild() # Print timed result totalTime = cmds.timerX(st=timer) print('SkinClusterListData: Total build time for skinCluster list: ' + str(skinTime))
[ "def rebuild(self):\n # ==========\n # - Checks -\n # ==========\n\n # Check geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data for a different geometry!')\n\n # =======================\n # - Rebuild SkinCluster -\n # =======================\n\n # Start timer\n timer = cmds.timerX()\n\n # Initialize Temp Joint\n tempJnt = ''\n\n # Unlock Influences\n influenceList = self._influenceData.keys()\n for influence in influenceList:\n if cmds.objExists(influence + '.liw'):\n if cmds.getAttr(influence + '.liw', l=True):\n try:\n cmds.setAttr(influence + '.liw', l=False)\n except:\n print(\n 'Error unlocking attribute \"' + influence + '.liw\"! This could problems when rebuilding the skinCluster...')\n if cmds.getAttr(influence + '.liw'):\n try:\n cmds.setAttr(influence + '.liw', False)\n except:\n print(\n 'Error setting attribute \"' + influence + '.liw\" to False! This could problems when rebuilding the skinCluster...')\n\n # Check SkinCluster\n skinCluster = self._data['name']\n if not cmds.objExists(skinCluster):\n\n # Get Transform Influences\n jointList = [inf for inf in influenceList if not self._influenceData[inf]['type']]\n\n # Check Transform Influences\n if not jointList:\n\n # Create Temporary Bind Joint\n cmds.select(cl=1)\n tempJnt = cmds.joint(n=skinCluster + '_tempJoint')\n print(\n 'No transform influences specified for skinCluster \"' + skinCluster + '\"! Creating temporary bind joint \"' + tempJnt + '\"!')\n jointList = [tempJnt]\n\n else:\n\n # Get Surface Influences\n influenceList = [inf for inf in influenceList if self._influenceData[inf]['type']]\n\n # Create skinCluster\n skinCluster = cmds.skinCluster(jointList, skinGeo, tsb=True, n=skinCluster)[0]\n\n else:\n\n # Check Existing SkinCluster\n affectedGeo = glTools.utils.deformer.getAffectedGeometry(skinCluster)\n if affectedGeo.keys()[0] != skinGeo:\n raise Exception(\n 'SkinCluster \"' + skinCluster + '\" already exists, but is not connected to the expeced geometry \"' + skinGeo + '\"!')\n\n # Add skinCluster influences\n for influence in influenceList:\n\n # Check influence\n if not cmds.objExists(influence):\n raise Exception(\n 'Influence \"' + influence + '\" does not exist! Use remapInfluence() to apply data to a different influence!')\n\n # Check existing influence connection\n if not cmds.skinCluster(skinCluster, q=True, inf=True).count(influence):\n\n # Add influence\n if self._influenceData[influence]['type']:\n # Geometry\n polySmooth = self._influenceData[influence]['polySmooth']\n nurbsSamples = self._influenceData[influence]['nurbsSamples']\n cmds.skinCluster(skinCluster, e=True, ai=influence, ug=True, ps=polySmooth, ns=nurbsSamples, wt=0.0,\n lockWeights=True)\n\n else:\n # Transform\n cmds.skinCluster(skinCluster, e=True, ai=influence, wt=0.0, lockWeights=True)\n\n # Bind Pre Matrix\n if self._influenceData[influence]['bindPreMatrix']:\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n cmds.connectAttr(self._influenceData[influence]['bindPreMatrix'],\n skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', f=True)\n\n # Load skinCluster weights\n cmds.setAttr(skinCluster + '.normalizeWeights', 0)\n glTools.utils.skinCluster.clearWeights(skinGeo)\n self.loadWeights()\n cmds.setAttr(skinCluster + '.normalizeWeights', 1)\n\n # Restore Custom Attribute Values and Connections\n self.setDeformerAttrValues()\n self.setDeformerAttrConnections()\n\n # Clear Selection\n cmds.select(cl=True)\n\n # =================\n # - Return Result -\n # =================\n\n # Print Timed Result\n totalTime = cmds.timerX(st=timer)\n print('SkinClusterData: Rebuild time for skinCluster \"' + skinCluster + '\": ' + str(totalTime))\n\n return skinCluster", "def __update_clusters(self):\n \n clusters = [[] for i in range(len(self.__centers))];\n for index_point in range(len(self.__pointer_data)):\n index_optim = -1;\n dist_optim = 0.0;\n \n for index in range(len(self.__centers)):\n # dist = euclidean_distance(data[index_point], centers[index]); # Slow solution\n dist = euclidean_distance_sqrt(self.__pointer_data[index_point], self.__centers[index]); # Fast solution\n \n if ( (dist < dist_optim) or (index is 0)):\n index_optim = index;\n dist_optim = dist;\n \n clusters[index_optim].append(index_point);\n \n # If cluster is not able to capture object it should be removed\n clusters = [cluster for cluster in clusters if len(cluster) > 0];\n \n return clusters;", "def kmeans_clustering(cluster_list, num_clusters, num_iterations):\n \n # initialize k-means clusters to be initial clusters with largest populations\n population_and_index = [(cluster_list[idx].total_population(), idx) \n for idx in range(len(cluster_list))] \n population_and_index.sort()\n population_order = [population_and_index[idx][1] for idx in range(len(population_and_index))]\n centers_list = []\n for idx in range(len(cluster_list), len(cluster_list)-num_clusters, -1):\n (hcoord, vcoord) = cluster_list[population_order[idx-1]].horiz_center(), cluster_list[population_order[idx-1]].vert_center()\n centers_list.append((hcoord, vcoord))\n\n for idx in range(0, num_iterations):\n # initialize k empty clusters\n k_list = [alg_cluster.Cluster(set([]),centers_list[idx][0], centers_list[idx][1], 0, 0.0) for idx in range(0, num_clusters)] \n answer_list = [alg_cluster.Cluster(set([]),centers_list[idx][0], centers_list[idx][1], 0, 0.0) for idx in range(0, num_clusters)]\n\n for jdx in range(0, len(cluster_list)):\n min_distance = float(\"inf\")\n min_kdx = -1\n for kdx in range(0, num_clusters):\n distance = k_list[kdx].distance(cluster_list[jdx])\n if distance < min_distance:\n min_distance = distance\n min_kdx = kdx\n\n answer_list[min_kdx].merge_clusters(cluster_list[jdx])\n \n # recompute its center\n for kdx in range(0, num_clusters):\n (new_hcoord, new_vcoord) = answer_list[kdx].horiz_center(), answer_list[kdx].vert_center()\n centers_list[kdx] = (new_hcoord, new_vcoord)\n \n return answer_list", "def setWeights(self, componentList=[]):\n print('!!! - DEPRICATED: skinClusterData.setWeights()! Use loadWeights() method instead - !!!')\n\n # ==========\n # - Checks -\n # ==========\n\n # Check SkinCluster\n skinCluster = self._data['name']\n self.verifySkinCluster(skinCluster)\n\n # Check Geometry\n skinGeo = self._data['affectedGeometry'][0]\n if not cmds.objExists(skinGeo):\n raise Exception(\n 'SkinCluster geometry \"' + skinGeo + '\" does not exist! Use remapGeometry() to load skinCluster data to a different geometry!')\n\n # Check Component List\n if not componentList: componentList = glTools.utils.component.getComponentStrList(skinGeo)\n componentSel = glTools.utils.selection.getSelectionElement(componentList, 0)\n\n # Get Component Index List\n indexList = OpenMaya.MIntArray()\n componentFn = OpenMaya.MFnSingleIndexedComponent(componentSel[1])\n componentFn.getElements(indexList)\n componentIndexList = list(indexList)\n\n # ===========================\n # - Set SkinCluster Weights -\n # ===========================\n\n # Build influence index array\n infIndexArray = OpenMaya.MIntArray()\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n [infIndexArray.append(i) for i in range(len(influenceList))]\n\n # Build master weight array\n wtArray = OpenMaya.MDoubleArray()\n oldWtArray = OpenMaya.MDoubleArray()\n for c in componentIndexList:\n for i in range(len(influenceList)):\n if self._influenceData.has_key(influenceList[i]):\n wtArray.append(self._influenceData[influenceList[i]]['wt'][c])\n else:\n wtArray.append(0.0)\n\n # Get skinCluster function set\n skinFn = glTools.utils.skinCluster.getSkinClusterFn(skinCluster)\n\n # Set skinCluster weights\n skinFn.setWeights(componentSel[0], componentSel[1], infIndexArray, wtArray, False, oldWtArray)\n\n # =================\n # - Return Result -\n # =================\n\n return influenceList", "def init_k_clusters(k):\n new_container = []\n for i in range(k):\n new_container.append([])\n return new_container", "def hierarchical_clustering(cluster_list, num_clusters):\n while len(cluster_list) > num_clusters:\n closest_pair = fast_closest_pair(cluster_list)\n cluster_i = cluster_list[closest_pair[1]]\n cluster_j = cluster_list[closest_pair[2]]\n cluster_i_union_j = cluster_i.merge_clusters(cluster_j)\n cluster_list.append(cluster_i_union_j)\n cluster_list.remove(cluster_i)\n cluster_list.remove(cluster_j)\n return cluster_list", "def build_clusters(bins):\n clusters = []\n\n for num, clustered_bins in cluster_bins(bins).items():\n if len(clustered_bins) >= 3:\n cluster = Cluster(clustered_bins)\n clusters.append(cluster)\n print(cluster)\n\n return clusters", "def generate_clusters(self):\n\n self.cluster_labels = None", "def list_clusters():\n path_list = [f.path for f in os.scandir(JUMBODIR) if f.is_dir()]\n clusters = []\n\n for p in path_list:\n if not check_config(p.split('/')[-1]):\n raise ex.LoadError('cluster', p.split('/')[-1], 'NoConfFile')\n\n with open(p + '/jumbo_config') as cfg:\n clusters += [json.load(cfg)]\n\n return clusters", "def __init__(self, skinCluster=''):\n # Execute Super Class Initilizer\n super(SkinClusterData, self).__init__()\n\n # SkinCluster Custom Attributes\n self._data['attrValueList'].append('skinningMethod')\n self._data['attrValueList'].append('useComponents')\n self._data['attrValueList'].append('normalizeWeights')\n self._data['attrValueList'].append('deformUserNormals')\n\n # Build SkinCluster Data\n if skinCluster: self.buildData(skinCluster)", "def _initialize_clusters(self):\n max_cap = self.config.capacity_cst\n total_demand = self.manager_stops.demand\n list_number_cluster = [int(total_demand/(i * max_cap)) for i in [0.75,1,1.25]]\n # list_number_cluster = [int(total_demand/(k * max_cap)) for k in [0.4]]\n\n Kmean_basic = basic_K_mean.basicKMeans(manager_cluster=self.manager_cluster,manager_stops=self.manager_stops)\n for k in list_number_cluster:\n Kmean_basic.run_K_mean(list(self.manager_stops.keys()),k)", "def buildData(self, skinCluster):\n # ==========\n # - Checks -\n # ==========\n\n # Check skinCluster\n self.verifySkinCluster(skinCluster)\n\n # Clear Data\n self.reset()\n\n # =======================\n # - Build Deformer Data -\n # =======================\n\n # Start Timer\n timer = cmds.timerX()\n\n self._data['name'] = skinCluster\n self._data['type'] = 'skinCluster'\n\n # Get affected geometry\n skinGeoShape = cmds.skinCluster(skinCluster, q=True, g=True)\n if len(skinGeoShape) > 1: raise Exception(\n 'SkinCluster \"' + skinCluster + '\" output is connected to multiple shapes!')\n if not skinGeoShape: raise Exception(\n 'Unable to determine affected geometry for skinCluster \"' + skinCluster + '\"!')\n skinGeo = cmds.listRelatives(skinGeoShape[0], p=True, pa=True)\n if not skinGeo: raise Exception('Unable to determine geometry transform for object \"' + skinGeoShape + '\"!')\n self._data['affectedGeometry'] = skinGeo\n skinGeo = skinGeo[0]\n\n skinClusterSet = glTools.utils.deformer.getDeformerSet(skinCluster)\n\n self._data[skinGeo] = {}\n self._data[skinGeo]['index'] = 0\n self._data[skinGeo]['geometryType'] = str(cmds.objectType(skinGeoShape))\n self._data[skinGeo]['membership'] = glTools.utils.deformer.getDeformerSetMemberIndices(skinCluster, skinGeo)\n self._data[skinGeo]['weights'] = []\n\n if self._data[skinGeo]['geometryType'] == 'mesh':\n self._data[skinGeo]['mesh'] = meshData.MeshData(skinGeo)\n\n # ========================\n # - Build Influence Data -\n # ========================\n\n # Get skinCluster influence list\n influenceList = cmds.skinCluster(skinCluster, q=True, inf=True)\n if not influenceList: raise Exception(\n 'Unable to determine influence list for skinCluster \"' + skinCluster + '\"!')\n\n # Get Influence Wieghts\n weights = glTools.utils.skinCluster.getInfluenceWeightsAll(skinCluster)\n\n # For each influence\n for influence in influenceList:\n\n # Initialize influence data\n self._influenceData[influence] = {}\n\n # Get influence index\n infIndex = glTools.utils.skinCluster.getInfluenceIndex(skinCluster, influence)\n self._influenceData[influence]['index'] = infIndex\n\n # Get Influence BindPreMatrix\n bindPreMatrix = cmds.listConnections(skinCluster + '.bindPreMatrix[' + str(infIndex) + ']', s=True, d=False,\n p=True)\n if bindPreMatrix:\n self._influenceData[influence]['bindPreMatrix'] = bindPreMatrix[0]\n else:\n self._influenceData[influence]['bindPreMatrix'] = ''\n\n # Get Influence Type (Transform/Geometry)\n infGeocmdsonn = cmds.listConnections(skinCluster + '.driverPoints[' + str(infIndex) + ']')\n if infGeocmdsonn:\n self._influenceData[influence]['type'] = 1\n self._influenceData[influence]['polySmooth'] = cmds.skinCluster(skinCluster, inf=influence, q=True,\n ps=True)\n self._influenceData[influence]['nurbsSamples'] = cmds.skinCluster(skinCluster, inf=influence, q=True,\n ns=True)\n else:\n self._influenceData[influence]['type'] = 0\n\n # Get Influence Weights\n pInd = glTools.utils.skinCluster.getInfluencePhysicalIndex(skinCluster, influence)\n self._influenceData[influence]['wt'] = weights[pInd]\n\n # =========================\n # - Custom Attribute Data -\n # =========================\n\n # Add Pre-Defined Custom Attributes\n self.getDeformerAttrValues()\n self.getDeformerAttrConnections()\n\n # =================\n # - Return Result -\n # =================\n\n skinTime = cmds.timerX(st=timer)\n print('SkinClusterData: Data build time for \"' + skinCluster + '\": ' + str(skinTime))", "def configure_clusters(self, centroids, dataPoints):\n # Create the empty clusters\n clusters = []\n for i in range(len(centroids)):\n cluster = []\n clusters.append(cluster)\n\n # For all the dataPoints, place them in initial clusters\n for i in range(int(userArgs.points)):\n idealCluster = self.points_best_cluster(centroids, dataPoints[i])\n clusters[idealCluster].append(dataPoints[i])\n\n return clusters", "def collate_cluster_data(ensembles_data):\n\n clusters = {} # Loop through all ensemble data objects and build up a data tree\n cluster_method = None\n cluster_score_type = None\n truncation_method = None\n percent_truncation = None\n side_chain_treatments = []\n for e in ensembles_data:\n if not cluster_method:\n cluster_method = e['cluster_method']\n cluster_score_type = e['cluster_score_type']\n percent_truncation = e['truncation_percent']\n truncation_method = e['truncation_method']\n # num_clusters = e['num_clusters']\n cnum = e['cluster_num']\n if cnum not in clusters:\n clusters[cnum] = {}\n clusters[cnum]['cluster_centroid'] = e['cluster_centroid']\n clusters[cnum]['cluster_num_models'] = e['cluster_num_models']\n clusters[cnum]['tlevels'] = {}\n tlvl = e['truncation_level']\n if tlvl not in clusters[cnum]['tlevels']:\n clusters[cnum]['tlevels'][tlvl] = {}\n clusters[cnum]['tlevels'][tlvl]['truncation_variance'] = e['truncation_variance']\n clusters[cnum]['tlevels'][tlvl]['num_residues'] = e['num_residues']\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'] = {}\n srt = e['subcluster_radius_threshold']\n if srt not in clusters[cnum]['tlevels'][tlvl]['radius_thresholds']:\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt] = {}\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['num_models'] = e['subcluster_num_models']\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'] = {}\n sct = e['side_chain_treatment']\n if sct not in side_chain_treatments:\n side_chain_treatments.append(sct)\n if sct not in clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct']:\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'][sct] = {}\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'][sct]['name'] = e['name']\n clusters[cnum]['tlevels'][tlvl]['radius_thresholds'][srt]['sct'][sct]['num_atoms'] = e['ensemble_num_atoms']\n\n return {\n 'clusters': clusters,\n 'cluster_method': cluster_method,\n 'cluster_score_type': cluster_score_type,\n 'truncation_method': truncation_method,\n 'percent_truncation': percent_truncation,\n 'side_chain_treatments': side_chain_treatments,\n }", "def update_clusters(self):\n num_ratings = Rating.objects.count()\n \n if self.eligible_to_update(num_ratings):\n ratings_matrix, num_users, all_user_names = \\\n self.construct_ratings_matrix()\n\n k_clusters = int(num_users / 10) + 2 # \"Magical numbers that \n # work the best\"\n from sklearn.cluster import KMeans\n kmeans = KMeans(n_clusters=k_clusters)\n clusters = kmeans.fit(ratings_matrix.tocsr()) # Read sklearn\n # docs to read why tocsr() used. THE MAIN KMEANS CLUSTERING\n\n # Updating the clusters\n Cluster.objects.all().delete()\n new_clusters = {i: Cluster(name=i) for i in range(k_clusters)}\n for cluster in new_clusters.values():\n cluster.save()\n for i, cluster_label in enumerate(clusters.labels_):\n # Add the new users to clusters\n new_clusters[cluster_label].users.add(\n User.objects.get(username=all_user_names[i])\n )", "def _cluster_list():\n\n CLUSTER_TABLE = storage.get_cluster_table()\n clusters = []\n cluster_items = CLUSTER_TABLE.scan()\n\n for cluster in cluster_items['Items']:\n clusters.append(cluster['id'])\n\n print(f'tracked clusters: {clusters}')\n\n return clusters", "def __update_centers(self):\n \n centers = [[] for i in range(len(self.__clusters))];\n \n for index in range(len(self.__clusters)):\n point_sum = [0] * len(self.__pointer_data[0]);\n \n for index_point in self.__clusters[index]:\n point_sum = list_math_addition(point_sum, self.__pointer_data[index_point]);\n \n centers[index] = list_math_division_number(point_sum, len(self.__clusters[index]));\n \n return centers;", "def mergeClusters(self, i, j):\r\n listi = self.clusters[i]\r\n listj = self.clusters[j]\r\n ltemp = listi[:] + listj[:]\r\n self.clusters.remove(listi)\r\n self.clusters.remove(listj)\r\n self.clusters.append(ltemp)", "def __init__(self):\n\n self.clusters = [ ]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds powers of the perm.
def __pow__(self, n): if n < 0: return pow(~self, -n) elif n == 0: return Perm() elif n == 1: return self elif n == 2: return self * self else: # binary exponentiation perm = self res = Perm() # identity while True: if n % 2 == 1: res = res * perm n = n - 1 if n == 0: break if n % 2 == 0: perm = perm * perm n = n / 2 return res
[ "def _compute_powers(self):\n self.base = self.theprime\n power = 1\n for idx in xrange(self.hashlen-1):\n power *= self.base\n power = to_int64(power)\n\n for idx in xrange(256):\n self.powers.append(to_int64(idx * power))", "def find_io_perms(n):\n global pi,po\n in_perm_1 = in_perm_2 = []\n out_perm = []\n N=2*n\n all1=[1]*N\n for k in range(n):\n #find next position for both the left and right summands\n max1 = 0\n for i in range(N):\n if i in in_perm_1+in_perm_2:\n continue\n xyp=list(all1)\n for j in range(N): # put 0's in the first found bits of the first summand\n if j in in_perm_1 or j == i:\n xyp[j]=0\n r =addp(xyp)#this is an adder where its inputs and outputs are permuted\n t = num1(r)\n if t > max1: #found a new max\n max1 = t\n maxi_1 = i\n continue\n if t == max1: #found the second max\n maxi_2 = i\n in_perm_1 = [maxi_1] + in_perm_1 \n in_perm_2 = [maxi_2] + in_perm_2\n #in_perm now has the correct permutation\n print 'computed pi perm = '\n print in_perm_1\n print in_perm_2\n print 'pi perm = '\n print pi[:n]\n print pi[n:]\n print '\\n'\n # now find the output permutation\n out_perm = []\n rng = range(n)\n rng.reverse()\n all0 = [0]*(2*n)\n for i in rng:\n xyp = list(all0)\n xyp[in_perm_1[i]]=1\n r=addp(xyp)\n j=operator.indexOf(r,1)\n out_perm = [j] + out_perm \n #find carry out bit.\n for i in range(n+1):\n if not i in out_perm:\n k = i\n break\n out_perm = [k] +out_perm\n out_perm = inv_perm(out_perm)\n print 'computed po perm = ',out_perm\n print 'po perm = ',po", "def powers(self):\n return [1]", "def perm(n):\n return Singleton.get_instance().perm(n).astype(np.int)", "def _solve_mod_prime_power(eqns, p, m, vars):\n from sage.rings.all import Integers, PolynomialRing\n from sage.modules.all import vector\n from sage.misc.all import cartesian_product_iterator\n\n mrunning = 1\n ans = []\n for mi in range(m):\n mrunning *= p\n R = Integers(mrunning)\n S = PolynomialRing(R, len(vars), vars)\n eqns_mod = [S(eq) for eq in eqns]\n if mi == 0:\n possibles = cartesian_product_iterator([range(len(R)) for _ in range(len(vars))])\n else:\n shifts = cartesian_product_iterator([range(p) for _ in range(len(vars))])\n pairs = cartesian_product_iterator([shifts, ans])\n possibles = (tuple(vector(t)+vector(shift)*(mrunning//p)) for shift, t in pairs)\n ans = list(t for t in possibles if all(e(*t) == 0 for e in eqns_mod))\n if not ans: return ans\n\n return ans", "def test_negative_powers(self):\n s = rangefunc([1, 2, 3, 0, 5, 6, 4]) # s.cycles() <-> (0,1,2,3)(4,5,6)\n a = Bijection(zip(range(7), \"abcdefg\")).conj(s)\n ii = rangefunc(range(7))\n ia = Permutation(zip(*([\"abcdefg\"]*2)))\n for i in range(13):\n self.assertEqual(ii, (s**i) * (s**-i))\n self.assertEqual(ii, (s**-i) * (s**i))\n self.assertEqual(ia, (a**i) * (a**-i))\n self.assertEqual(ia, (a**-i) * (a**i))", "def power_set(s):\n s = list(s)\n pset = []\n for x in range(pow(2, len(s))):\n sset = []\n for i in range(len(s)):\n if x & (1 << i):\n sset.append(s[i])\n pset.append(sset)\n return set(map(frozenset, pset))", "def patterns_needed(self) -> FrozenSet[Perm]:", "def permute(word, depth=2) -> set:\n mutations = set(word.permutations())\n if depth:\n new = list()\n for mutation in mutations:\n# printer(mutation)\n new += permute(mutation, depth-1)\n #new += novel\n return new\n return [word]", "def perm( n, k ):\r\n if not 0 <= k <= n:\r\n return 0\r\n if k == 0:\r\n return 1\r\n # calculate n!/(n-k)! as one product, avoiding factors that \r\n # just get canceled\r\n P = (n-k)+1\r\n for i in xrange(P+1, n+1):\r\n P *= i\r\n return P", "def modpow(k, n, m):\n ans = 1\n while n:\n if n & 1:\n ans = (ans*k) % m\n k = (k*k) % m\n n >>= 1\n return ans", "def sizeof_powerset(n):\n\n return (2 ** n) % int(1E6)", "def permutation_sign(perm):\n return (-1)**len(inversions(perm))", "def sum_of_powers(bases, powers):\n result = []\n\n #if one of the arguements is an empty list, return an empty list\n if powers == [] or bases == []:\n return result\n\n #creates the list of sum of powers\n i = 0\n while i < len(powers):\n j = 0\n sum = 0\n while j < len(bases):\n sum += bases[j] ** powers[i]\n j += 1\n result.append(sum)\n i += 1\n\n return result", "def powerset(U):\n for j in range(0,len(U)+1):\n for E in powersetj(U,j):\n yield E", "def power_list(numbers):\r\n powered_numbers = [\r\n n ** x\r\n for x,\r\n n in enumerate(numbers)\r\n ]\r\n\r\n return powered_numbers", "def powering_algorithm(p): \n max_factor = isqrt(2**p)\n if max_factor < 2:\n return p\n for f in primes_up_to_n(max_factor):\n if does_f_factor_p(f, p):\n return False #### can't return enumerated type ####\n else:\n return p", "def permcalculator(n):\r\n\r\n #Factorial is the product of all positive integers less than or equal to n\r\n print(math.factorial(n))\r\n\r\n perms = itertools.permutations(list(range(1, n+1)))\r\n\r\n for counter, perm in enumerate(list(perms)):\r\n permutation = ''\r\n for item in perm:\r\n permutation += str(item) + ' '\r\n print(permutation)", "def permute(n: int, p: int) -> float:\n return factorial(n) / factorial(n - p)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the available longitude and latitude list
def read_long_lat(url, longitude_start, longitude_end, latitude_start, latitude_end): # Download the list of the available coordinates from the server request = urllib2.Request(url) response = urllib2.urlopen(request) try: data = response.read() except URLError as e: print e.reason lines = data.splitlines() del lines[-1] long_lat_list = [] # Create the long/lat coordinate list for loc in lines: loc_conv = loc.split('_-') loc_conv = [int(i) for i in loc_conv] if loc_conv[0] >= longitude_start and loc_conv[0] <= longitude_end and loc_conv[1] >= latitude_start and loc_conv[1] <= latitude_end: long_lat_list.append(loc); return long_lat_list
[ "def gps_read_locations(lfile):\n gps_locations = list()\n\n if os.path.isfile(lfile):\n with open(lfile, \"r\") as file:\n for line in file:\n x = str(str(line).strip()).split(' ', 4)\n gps_tuple = list()\n gps_tuple.append(float(x[0]))\n gps_tuple.append(float(x[1]))\n gps_tuple.append(x[2])\n gps_tuple.append(x[3])\n gps_tuple.append(x[4])\n gps_locations.append(gps_tuple)\n\n return gps_locations", "def get_lat_lon_values():\n refcube = xr.open_dataset(settings.ACCESS_G_PATH + settings.access_g_filename('20190101'))\n return refcube.lat.values, refcube.lon.values", "def list_locations():", "def get_leland_location(self):\n req = requests.get(self.gps_source_url)\n return {\"lat\": req.json()['latitude'],\n \"lon\": req.json()['longitude']}", "def getlatlon():\n pass", "def print_lat_long(self):\n \n for data_point in self.sorted_files:\n lat = data_point[2]\n long = data_point[3]\n \n print (lat,',',long)", "def location_iss():\n\n api_iss = \"http://api.open-notify.org/iss-now.json\"\n response = requests.get(url=api_iss)\n response.raise_for_status()\n\n latitude = float(response.json()[\"iss_position\"][\"latitude\"])\n longitude = float(response.json()[\"iss_position\"][\"longitude\"])\n return (latitude, longitude)", "def get_lat_longs():\n with qdb.sql_connection.TRN:\n # getting all the public studies\n studies = qdb.study.Study.get_by_status('public')\n\n results = []\n if studies:\n # we are going to create multiple union selects to retrieve the\n # latigute and longitude of all available studies. Note that\n # UNION in PostgreSQL automatically removes duplicates\n sql_query = \"\"\"\n SELECT {0}, CAST(sample_values->>'latitude' AS FLOAT),\n CAST(sample_values->>'longitude' AS FLOAT)\n FROM qiita.sample_{0}\n WHERE sample_values->>'latitude' != 'NaN' AND\n sample_values->>'longitude' != 'NaN' AND\n isnumeric(sample_values->>'latitude') AND\n isnumeric(sample_values->>'longitude')\"\"\"\n sql = [sql_query.format(s.id) for s in studies]\n sql = ' UNION '.join(sql)\n qdb.sql_connection.TRN.add(sql)\n\n # note that we are returning set to remove duplicates\n results = qdb.sql_connection.TRN.execute_fetchindex()\n\n return results", "def GPScoords():\r\n \r\n my_gps = MicropyGPS()\r\n\r\n #Fetching the coordinates and the altitude from the GPS chip\r\n latitude = my_gps.latitude\r\n longitude = my_gps.longitude\r\n altitude = my_gps.altitude\r\n \r\n #Optimising data representation (latitutde)\r\n deg_lat = latitude[0] - 50 #The experiment area's latitude varies from 50° to 51° (Belgium)\r\n decimal_lat = np.int32(10000*latitude[1]/60) #Conversion of decimal minutes in decimals and multiplication by 10000\r\n #Getting binary representation of the data\r\n bin_deg_lat = format(deg_lat, 'b')\r\n bin_dec_lat = format(decimal_lat, 'b')\r\n\r\n #Optimising data representation (longitude)\r\n deg_long = longitude[0]-3 #The experiment area's longitude varies from 3° to 6° (Mons-Namur approx.)\r\n decimal_long = np.int32(10000*longitude[1]/60) #Conversion of decimal minutes in decimals\r\n #Getting binary representation of the data\r\n bin_deg_long = format(deg_long, 'b')\r\n bin_dec_long = format(decimal_long,'b')\r\n\r\n #Altitude data optimisation\r\n altitude = np.int16(altitude)\r\n #Getting binary representation of the data\r\n bin_alt = format(altitude, 'b')\r\n\r\n #Creating fixed size lists for each data (the size is in bits)\r\n list_deg_lat = ['0']*1\r\n list_dec_lat = ['0']*14\r\n\r\n list_deg_long = ['0']*2\r\n list_dec_long = ['0']*14\r\n\r\n list_alt = ['0']*9\r\n\r\n #Putting the strings in the fixed size lists (LSB is on the top right)\r\n list_deg_lat[0] = bin_deg_lat\r\n\t\r\n n = len(list_dec_lat)-1\r\n for i in reversed(range(len(bin_dec_lat))):\r\n list_dec_lat[n] = bin_dec_lat[i]\r\n n = n - 1\r\n\r\n n = len(list_deg_long) - 1\r\n for i in reversed(range(len(bin_deg_long))):\r\n list_deg_long[n] = bin_deg_long[i]\r\n n = n - 1 \r\n\r\n n = len(list_dec_long) - 1\r\n for i in reversed(range(len(bin_dec_long))):\r\n list_dec_long[n] = bin_dec_long[i]\r\n n = n - 1 \r\n\r\n n = len(list_alt)-1\r\n for i in reversed(range(len(bin_alt))):\r\n list_alt[n] = bin_alt[i]\r\n n = n - 1\r\n \r\n #Concatenating all the lists into one and transforming the binary data into a byte array\r\n coord = list_alt + list_dec_lat + list_deg_lat + list_dec_long + list_deg_long\r\n coord = ''.join(coord)\r\n coord = hex(int(coord,2))[2:]\r\n coord = bytearray.fromhex(coord)\r\n \r\n return(coord) #Return a byte array\r", "def get_location():\n result = _make_request('https://freegeoip.net/json/')\n\n data = result.json()\n\n return (data['latitude'], data['longitude'])", "def getLatLong(self):\n\t\t#Se obtiene la siguiente coordenada del objeto FakeGPS y se sobreescribe el json\n\t\t# con las ubicaciones para mantener la coordenada actual entre varias ejecuciones de \n\t\t# appCliente. \t\n\t\tcoord = self.fakeGPS.getCoordenada()\n\t\tself.fakeGPS.persistirUbicaciones()\n\t\tprint \"retornando coordenada calle: %s\\n\" % coord.getNombreCalle() \n\t\treturn coord.getLatitud(),coord.getLongitud()", "def artistLocationGeo(self):\n try:\n lat = float(self.locationGraph.objects(self.locationURI, self.latPredicate).next())\n lon = float(self.locationGraph.objects(self.locationURI, self.longPredicate).next())\n print \"Latitude is\", lat\n print \"Longitude is\", lon\n return lat, lon\n except StopIteration: # If generator is empty\n print \"No geodata!\"\n except AttributeError: # If locationURI hasn't been defined\n print \"LocationURI not defined!\"", "def test_get_coords_list_valid(self):\n coupon = COUPON_FACTORY.create_coupon()\n coords_list = coupon.get_location_coords_list()\n self.assertAlmostEqual(int(float(coords_list[0][0])), -73)\n self.assertAlmostEqual(int(float(coords_list[0][1])), 41)", "def location_list(self):\n \n self._send(\"location_list\")\n return [e2string(x) for x in self._read_json(220)]", "def read_cris_geo (filelist, ephemeris = False):\n \n if type(filelist) is str: filelist = [filelist]\n if len(filelist) ==0: return None\n \n geos = [h5py.File(filename, 'r') for filename in filelist]\n \n if ephemeris == False: \n Latitude = np.concatenate([f['All_Data']['CrIS-SDR-GEO_All']['Latitude'] [:] for f in geos])\n Longitude = np.concatenate([f['All_Data']['CrIS-SDR-GEO_All']['Longitude'][:] for f in geos])\n SatelliteAzimuthAngle = np.concatenate([f['All_Data']['CrIS-SDR-GEO_All']['SatelliteAzimuthAngle'][:] for f in geos])\n SatelliteRange = np.concatenate([f['All_Data']['CrIS-SDR-GEO_All']['SatelliteRange'][:] for f in geos])\n SatelliteZenithAngle = np.concatenate([f['All_Data']['CrIS-SDR-GEO_All']['SatelliteZenithAngle'][:] for f in geos])\n return Longitude, Latitude, SatelliteAzimuthAngle, SatelliteRange, SatelliteZenithAngle\n if ephemeris == True:\n FORTime = np.concatenate([f['All_Data']['CrIS-SDR-GEO_All']['FORTime'] [:] for f in geos])\n MidTime = np.concatenate([f['All_Data']['CrIS-SDR-GEO_All']['MidTime'] [:] for f in geos])\n SCPosition = np.concatenate([f['All_Data']['CrIS-SDR-GEO_All']['SCPosition'] [:] for f in geos])\n SCVelocity = np.concatenate([f['All_Data']['CrIS-SDR-GEO_All']['SCVelocity'] [:] for f in geos])\n SCAttitude = np.concatenate([f['All_Data']['CrIS-SDR-GEO_All']['SCAttitude'] [:] for f in geos])\n return FORTime, MidTime, SCPosition, SCVelocity, SCAttitude\n if ephemeris == 'Solar':\n SolarZenithAngle = np.concatenate([f['All_Data']['CrIS-SDR-GEO_All']['SolarZenithAngle'] [:] for f in geos])\n SolarAzimuthAngle = np.concatenate([f['All_Data']['CrIS-SDR-GEO_All']['SolarAzimuthAngle'] [:] for f in geos])\n return SolarAzimuthAngle, SolarZenithAngle", "def _get_latlon(radgrid):\n # Declare array, filled 0 in order to not have a masked array.\n lontot = np.zeros_like(radgrid.fields['reflectivity']['data'].filled(0))\n lattot = np.zeros_like(radgrid.fields['reflectivity']['data'].filled(0))\n\n for lvl in range(radgrid.nz):\n lontot[lvl, :, :], lattot[lvl, :, :] = radgrid.get_point_longitude_latitude(lvl)\n\n longitude = pyart.config.get_metadata('longitude')\n latitude = pyart.config.get_metadata('latitude')\n\n longitude['data'] = lontot\n latitude['data'] = lattot\n\n return longitude, latitude", "def location(locations):\r\n ctx = ssl.create_default_context(cafile=certifi.where())\r\n geopy.geocoders.options.default_ssl_context = ctx\r\n\r\n geo = Nominatim(user_agent=\"map_main.py\", timeout=10)\r\n location1 = geo.geocode(locations)\r\n return location1.latitude, location1.longitude", "def get_lat_lon_client(ip):\n try:\n url = 'http://freegeoip.net/json/%s' % (ip)\n data = simplejson.load(urlopen(url))\n lat = float(data['latitude'])\n lon = float(data['longitude'])\n if lat == 0.0 or lon == 0.0:\n lat, lon = 48.833, 2.333\n return lat, lon\n except:\n return 48.833, 2.333", "def long_lat():\n MAPQUEST_API_KEY = 'bvd5kR5ANCpY295vIH5qgDEcpKZzeuKR'\n\n url = f'http://www.mapquestapi.com/geocoding/v1/address?key={MAPQUEST_API_KEY}&location=Babson%20College'\n f = urllib.request.urlopen(url)\n response_text = f.read().decode('utf-8')\n response_data = json.loads(response_text)\n pprint(response_data['results'][0]['locations'][0]['latLng'])\n lat = response_data['results'][0]['locations'][0]['latLng']['lat']\n longitude = response_data['results'][0]['locations'][0]['latLng']['lng']\n return lat, longitude" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test osqlcliclient pipeline for sending request and receiving response works.
def test_osqlcliclient_request_response(self): def get_test_baseline(file_name): """ Helper method to get baseline file. """ return os.path.abspath( os.path.join( os.path.abspath(__file__), u'..', u'..', u'osqlcli', u'jsonrpc', u'contracts', u'tests', u'baselines', file_name)) with open(get_test_baseline(u'test_simple_query.txt'), u'r+b', buffering=0) as response_file: request_stream = io.BytesIO() self.sql_tools_client = sqltoolsclient.SqlToolsClient( input_stream=request_stream, output_stream=response_file) # The sleep is required because py.test and logging have an issue with closing the FileHandle # in a non-thread safe way # issue24262 sleep(0.5) self.osql_cli_options = create_osql_cli_options(integrated_auth=True) self.osql_cli_client = create_osql_cli_client(self.osql_cli_options, owner_uri=u'connectionservicetest', sql_tools_client=self.sql_tools_client, extra_bool_param=True, extra_string_param=u'stringparam', extra_int_param=5) self.osql_cli_client.shutdown()
[ "def test_send_result(self):\n pass", "def test_flow_triggered(self):\n message = Mock()\n message.id = \"test-id\"\n message.data = {\"_vnd\": {\"v1\": {\"chat\": {\"owner\": \"27820001001\"}}}}\n tasks.rapidpro = TembaClient(\"textit.in\", \"test-token\")\n responses.add(\n responses.GET,\n \"http://engage/v1/contacts/27820001001/messages\",\n json={\n \"messages\": [\n {\n \"_vnd\": {\n \"v1\": {\n \"direction\": \"outbound\",\n \"author\": {\n \"id\": \"2ab15df1-082a-4420-8f1a-1fed53b13eba\",\n \"type\": \"OPERATOR\",\n },\n }\n },\n \"from\": \"27820001002\",\n \"id\": message.id,\n \"text\": {\"body\": \"Operator response\"},\n \"timestamp\": \"1540803363\",\n \"type\": \"text\",\n },\n {\n \"_vnd\": {\"v1\": {\"direction\": \"inbound\", \"labels\": []}},\n \"from\": \"27820001001\",\n \"id\": \"ABGGJ3EVEUV_AhALwhRTSopsSmF7IxgeYIBz\",\n \"text\": {\"body\": \"Inbound question\"},\n \"timestamp\": \"1540802983\",\n \"type\": \"text\",\n },\n ]\n },\n )\n responses.add(\n responses.GET,\n \"https://textit.in/api/v2/contacts.json?urn=whatsapp:27820001001\",\n json={\n \"results\": [\n {\n \"uuid\": \"contact-id\",\n \"name\": \"\",\n \"language\": \"zul\",\n \"groups\": [],\n \"fields\": {\"facility_code\": \"123456\"},\n \"blocked\": False,\n \"stopped\": False,\n \"created_on\": \"2015-11-11T08:30:24.922024+00:00\",\n \"modified_on\": \"2015-11-11T08:30:25.525936+00:00\",\n \"urns\": [\"tel:+27820001001\"],\n }\n ],\n \"next\": None,\n },\n )\n responses.add(\n responses.POST,\n \"https://textit.in/api/v2/contacts.json?urn=whatsapp:27820001001\",\n json={},\n )\n responses.add(responses.POST, \"http://jembi/ws/rest/v1/helpdesk\", json={})\n\n handle_operator_message(message)\n [jembi_request] = JembiSubmission.objects.all()\n jembi_request.request_data.pop(\"eid\")\n self.assertEqual(\n jembi_request.request_data,\n {\n \"class\": \"Unclassified\",\n \"cmsisdn\": \"+27820001001\",\n \"data\": {\"answer\": \"Operator response\", \"question\": \"Inbound question\"},\n \"dmsisdn\": \"+27820001001\",\n \"encdate\": \"20181029084943\",\n \"faccode\": \"123456\",\n \"mha\": 1,\n \"op\": \"56748517727534413379787391391214157498\",\n \"repdate\": \"20181029085603\",\n \"sid\": \"contact-id\",\n \"swt\": 4,\n \"type\": 7,\n },\n )", "def test_make_request_method(self):\n make_request = self.adl.make_request()\n response = loop.run_until_complete(make_request)\n self.assertEqual(response.status, 200)", "def test_connections_request(self):\n pass", "def test_handle_request_2_c(self):\n ip_addr = self._session_ip_1\n user = self._user_1\n session = self.session_manager.create_session(ip_address=ip_addr, username=user)\n request = NWMRequest(session_secret=session.session_secret, version=2.0)\n\n dummy_scheduler_client = DummySchedulerClient(test_successful=True)\n self.handler._scheduler_client = dummy_scheduler_client\n\n response = asyncio.run(self.handler.handle_request(request=request), debug=True)\n self.assertEquals(response.job_id, dummy_scheduler_client.last_job_id)", "def test_rack_scenario1(self):\n call_scenario1(self)", "def setUp(self):\n self.host = os.getenv('RIAK_HOST', 'localhost')\n self.sink = ReplSink(host=self.host, port=8098, queue='q1_ttaaefs')\n self.test_data = b'{\"test\":\"data\"}'\n self.http = urllib3.HTTPConnectionPool(host=self.host, port=8098, retries=False)\n\n empty = False\n while not empty:\n rec = self.sink.fetch()\n empty = rec.empty", "def test_acceptor(self):\n # Also a regression test for #120\n # C-ECHO-RQ\n # 80 total length\n echo_rq = (\n b\"\\x04\\x00\\x00\\x00\\x00\\x4a\" # P-DATA-TF 74\n b\"\\x00\\x00\\x00\\x46\\x01\" # PDV Item 70\n b\"\\x03\" # PDV: 2 -> 69\n b\"\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x42\\x00\\x00\\x00\" # 12 Command Group Length\n b\"\\x00\\x00\\x02\\x00\\x12\\x00\\x00\\x00\\x31\\x2e\\x32\\x2e\\x38\"\n b\"\\x34\\x30\\x2e\\x31\\x30\\x30\\x30\\x38\\x2e\\x31\\x2e\\x31\\x00\" # 26\n b\"\\x00\\x00\\x00\\x01\\x02\\x00\\x00\\x00\\x30\\x00\" # 10 Command Field\n b\"\\x00\\x00\\x10\\x01\\x02\\x00\\x00\\x00\\x01\\x00\" # 10 Message ID\n b\"\\x00\\x00\\x00\\x08\\x02\\x00\\x00\\x00\\x01\\x01\" # 10 Command Data Set Type\n )\n\n # Send associate request then c-echo requests then release request\n commands = [\n (\"send\", a_associate_rq),\n (\"recv\", None),\n (\"send\", echo_rq),\n (\"recv\", None),\n (\"send\", echo_rq),\n (\"recv\", None),\n (\"send\", echo_rq),\n (\"recv\", None),\n (\"send\", echo_rq),\n (\"recv\", None),\n (\"send\", echo_rq),\n (\"recv\", None),\n (\"send\", echo_rq),\n (\"recv\", None),\n (\"send\", echo_rq),\n (\"recv\", None),\n (\"send\", echo_rq),\n (\"recv\", None),\n (\"send\", echo_rq),\n (\"recv\", None),\n (\"send\", echo_rq),\n (\"recv\", None),\n (\"send\", echo_rq),\n (\"recv\", None),\n (\"send\", echo_rq),\n (\"recv\", None),\n (\"send\", a_release_rq),\n (\"exit\", None),\n ]\n self.scp = scp = self.start_server(commands)\n\n assoc, fsm = self.get_acceptor_assoc()\n assoc.start()\n\n for ii in range(len(commands) - 1):\n scp.step()\n\n while assoc.dul.is_alive():\n time.sleep(0.001)\n\n scp.step()\n scp.shutdown()\n\n assert [\n (\"Sta1\", \"Evt5\", \"AE-5\"),\n (\"Sta2\", \"Evt6\", \"AE-6\"),\n (\"Sta3\", \"Evt7\", \"AE-7\"),\n (\"Sta6\", \"Evt10\", \"DT-2\"),\n (\"Sta6\", \"Evt9\", \"DT-1\"),\n (\"Sta6\", \"Evt10\", \"DT-2\"),\n (\"Sta6\", \"Evt9\", \"DT-1\"),\n (\"Sta6\", \"Evt10\", \"DT-2\"),\n (\"Sta6\", \"Evt9\", \"DT-1\"),\n (\"Sta6\", \"Evt10\", \"DT-2\"),\n (\"Sta6\", \"Evt9\", \"DT-1\"),\n (\"Sta6\", \"Evt10\", \"DT-2\"),\n (\"Sta6\", \"Evt9\", \"DT-1\"),\n (\"Sta6\", \"Evt10\", \"DT-2\"),\n (\"Sta6\", \"Evt9\", \"DT-1\"),\n (\"Sta6\", \"Evt10\", \"DT-2\"),\n (\"Sta6\", \"Evt9\", \"DT-1\"),\n (\"Sta6\", \"Evt10\", \"DT-2\"),\n (\"Sta6\", \"Evt9\", \"DT-1\"),\n (\"Sta6\", \"Evt10\", \"DT-2\"),\n (\"Sta6\", \"Evt9\", \"DT-1\"),\n (\"Sta6\", \"Evt10\", \"DT-2\"),\n (\"Sta6\", \"Evt9\", \"DT-1\"),\n (\"Sta6\", \"Evt10\", \"DT-2\"),\n (\"Sta6\", \"Evt9\", \"DT-1\"),\n (\"Sta6\", \"Evt10\", \"DT-2\"),\n (\"Sta6\", \"Evt9\", \"DT-1\"),\n (\"Sta6\", \"Evt12\", \"AR-2\"),\n (\"Sta8\", \"Evt14\", \"AR-4\"),\n (\"Sta13\", \"Evt17\", \"AR-5\"),\n ] == fsm._changes[:30]", "def test_operation_ls(client):\n # register get_endpoint mock data\n register_api_route_fixture_file(\n \"transfer\", f\"/operation/endpoint/{GO_EP1_ID}/ls\", \"operation_ls_goep1.json\"\n )\n ls_path = f\"https://transfer.api.globus.org/v0.10/operation/endpoint/{GO_EP1_ID}/ls\"\n\n # load the tutorial endpoint ls doc\n ls_doc = client.operation_ls(GO_EP1_ID)\n\n # check that the result is an iterable of file and dir dict objects\n count = 0\n for x in ls_doc:\n assert \"DATA_TYPE\" in x\n assert x[\"DATA_TYPE\"] in (\"file\", \"dir\")\n count += 1\n # not exact, just make sure the fixture wasn't empty\n assert count > 3\n\n req = get_last_request()\n assert req.url == ls_path\n\n # don't change the registered response\n # the resulting data might be \"wrong\", but we're just checking request formatting\n\n # orderby with a single str\n client.operation_ls(GO_EP1_ID, orderby=\"name\")\n req = get_last_request()\n parsed_qs = urllib.parse.parse_qs(urllib.parse.urlparse(req.url).query)\n assert parsed_qs == {\"orderby\": [\"name\"]}\n\n # orderby multiple strs\n client.operation_ls(GO_EP1_ID, orderby=[\"size DESC\", \"name\", \"type\"])\n req = get_last_request()\n parsed_qs = urllib.parse.parse_qs(urllib.parse.urlparse(req.url).query)\n assert parsed_qs == {\"orderby\": [\"size DESC,name,type\"]}\n\n # orderby + filter\n client.operation_ls(GO_EP1_ID, orderby=\"name\", filter=\"name:~*.png\")\n req = get_last_request()\n parsed_qs = urllib.parse.parse_qs(urllib.parse.urlparse(req.url).query)\n assert parsed_qs == {\"orderby\": [\"name\"], \"filter\": [\"name:~*.png\"]}\n\n # local_user\n client.operation_ls(GO_EP1_ID, local_user=\"my-user\")\n req = get_last_request()\n parsed_qs = urllib.parse.parse_qs(urllib.parse.urlparse(req.url).query)\n assert parsed_qs == {\"local_user\": [\"my-user\"]}", "def test_request_sends_parameters(self):\n self.register(json=self.RESPONSE)\n self.mock_request(self.RANGE_ID)\n self.assertDataSent(self.request_class.PRODUCT_RANGE_ID, self.RANGE_ID)\n self.assertDataSent(\n self.request_class.SALES_CHANNEL_ID,\n self.request_class.SALES_CHANNEL_ID_VALUE,\n )", "def test_get_events_command_success(mock_request, client):\n from FireEyeNX import get_events_command\n\n args = {\n 'duration': '48_hours',\n 'mvx_correlated_only': 'false',\n 'end_time': '2020-08-10T06:31:00.000+00:00',\n }\n\n with open('TestData/get_events_response.json') as f:\n expected_res = json.load(f)\n\n mock_request.return_value = expected_res\n\n cmd_res = get_events_command(client, args)\n with open('TestData/get_events_context.json', encoding='utf-8') as f:\n expected_outputs = json.load(f)\n\n with open('TestData/get_events.md') as f:\n expected_hr = f.read()\n\n assert cmd_res.raw_response == expected_res\n assert cmd_res.outputs == expected_outputs\n assert cmd_res.readable_output == expected_hr", "def test_status_request(self):\n pass", "def setUp(self):\n \n # Create fake remote client and server.\n # Add clean up to shut down properly.\n # Start remote server on a random port.\n self._remote_server = R3PCServer(self.consume_req, self.remote_server_close)\n self._remote_client = R3PCClient(self.consume_ack, self.remote_client_close)\n self.addCleanup(self._remote_server.stop)\n self.addCleanup(self._remote_client.stop)\n self._other_port = self._remote_server.start('*', 0)\n log.debug('Remote server binding to *:%i', self._other_port)\n \n # Set internal variables.\n self._other_host = 'localhost'\n self._xs_name = 'remote1'\n self._svc_name = 'terrestrial_endpoint'\n self._listen_name = self._svc_name + self._xs_name\n self._platform_resource_id = 'abc123'\n self._resource_id = 'fake_id'\n self._rmt_svc_name = 'fake_svc'\n self._no_requests = 10\n self._requests_sent = {}\n self._results_recv = {}\n self._workers = []\n self._done_evt = AsyncResult()\n self._queue_mod_evts = []\n self._cmd_tx_evts = []\n self._telem_evts = []\n self._no_telem_evts = 0\n self._no_queue_mod_evts = 0\n self._no_cmd_tx_evts = 0\n self._done_queue_mod_evts = AsyncResult()\n self._done_telem_evts = AsyncResult()\n self._done_cmd_tx_evts = AsyncResult()\n \n # Start container.\n log.debug('Staring capability container.')\n self._start_container()\n \n # Bring up services in a deploy file (no need to message)\n log.info('Staring deploy services.')\n self.container.start_rel_from_url('res/deploy/r2deploy.yml')\n\n # Create a container client.\n log.debug('Creating container client.')\n self._container_client = ContainerAgentClient(node=self.container.node,\n name=self.container.name)\n\n # The following spawn config creates the process with the remote\n # name tagged to the service name.\n \"\"\"\n listen_name = terrestrial_endpointremote1\n 2012-10-10 11:34:46,654 DEBUG ion.services.sa.tcaa.terrestrial_endpoint recv name: NP (ion_test_8257ab,terrestrial_endpointremote1,B: terrestrial_endpointremote1)\n 2012-10-10 11:34:46,654 DEBUG ion.services.sa.tcaa.terrestrial_endpoint startup listener recv name: NP (ion_test_8257ab,terrestrial_endpointremote1,B: terrestrial_endpointremote1)\n 2012-10-10 11:34:46,654 DEBUG ion.services.sa.tcaa.terrestrial_endpoint startup listener recv name: NP (ion_test_8257ab,Edwards-MacBook-Pro_local_2624.33,B: Edwards-MacBook-Pro_local_2624.33)\n \"\"\"\n \n # Create agent config.\n endpoint_config = {\n 'other_host' : self._other_host,\n 'other_port' : self._other_port,\n 'this_port' : 0,\n 'xs_name' : self._xs_name,\n 'platform_resource_id' : self._platform_resource_id,\n 'process' : {\n 'listen_name' : self._listen_name\n }\n }\n \n # Spawn the terrestrial enpoint process.\n log.debug('Spawning terrestrial endpoint process.')\n self._te_pid = self._container_client.spawn_process(\n name='remote_endpoint_1',\n module='ion.services.sa.tcaa.terrestrial_endpoint',\n cls='TerrestrialEndpoint',\n config=endpoint_config)\n log.debug('Endpoint pid=%s.', str(self._te_pid))\n\n # Create an endpoint client.\n # The to_name may be either the process pid or\n # the listen_name, which for this remote bridge\n # is svc_name + remote_name as above.\n self.te_client = TerrestrialEndpointClient(\n process=FakeProcess(),\n to_name=self._listen_name)\n log.debug('Got te client %s.', str(self.te_client))\n \n # Remember the terrestrial port.\n self._this_port = self.te_client.get_port()\n \n # Start the event publisher.\n self._event_publisher = EventPublisher()\n \n # Start the event subscriber.\n self._event_subscriber = EventSubscriber(\n event_type='PlatformEvent',\n callback=self.consume_event,\n origin=self._xs_name)\n self._event_subscriber.start()\n self._event_subscriber._ready_event.wait(timeout=CFG.endpoint.receive.timeout)\n self.addCleanup(self._event_subscriber.stop)\n\n # Start the result subscriber. \n self._result_subscriber = EventSubscriber(\n event_type='RemoteCommandResult',\n origin=self._resource_id,\n callback=self.consume_event)\n self._result_subscriber.start()\n self._result_subscriber._ready_event.wait(timeout=CFG.endpoint.receive.timeout)\n self.addCleanup(self._result_subscriber.stop)", "def testRequestSimpleCycle(self):\n\n # test post method\n requestName = self.insertRequest(self.rerecoCreateArgs)\n\n ## test get method\n # get by name\n response = self.getRequestWithNoStale('name=%s' % requestName)\n self.assertEqual(response[1], 200, \"get by name\")\n self.assertEqual(self.resultLength(response), 1)\n\n # get by status\n response = self.getRequestWithNoStale('status=new')\n self.assertEqual(response[1], 200, \"get by status\")\n self.assertEqual(self.resultLength(response), 1)\n\n #this create cache\n # need to find the way to reste Etag or not getting from the cache\n# response = self.getRequestWithNoStale('status=assigned')\n# self.assertEqual(response[1], 200, \"get by status\")\n# self.assertEqual(self.resultLength(response), 0)\n\n # get by prepID\n response = self.getRequestWithNoStale('prep_id=%s' % self.rerecoCreateArgs[\"PrepID\"])\n self.assertEqual(response[1], 200)\n self.assertEqual(self.resultLength(response), 1)\n #import pdb\n #pdb.set_trace()\n response = self.getRequestWithNoStale('campaign=%s' % self.rerecoCreateArgs[\"Campaign\"])\n self.assertEqual(response[1], 200)\n self.assertEqual(self.resultLength(response), 1)\n\n response = self.getRequestWithNoStale('inputdataset=%s' % self.rerecoCreateArgs[\"InputDataset\"])\n self.assertEqual(response[1], 200)\n self.assertEqual(self.resultLength(response), 1)\n\n response = self.getRequestWithNoStale('mc_pileup=%s' % self.rerecoCreateArgs[\"MCPileup\"])\n self.assertEqual(response[1], 200)\n self.assertEqual(self.resultLength(response), 1)\n\n response = self.getRequestWithNoStale('data_pileup=%s' % self.rerecoCreateArgs[\"DataPileup\"])\n self.assertEqual(response[1], 200)\n self.assertEqual(self.resultLength(response), 1)\n\n\n # test put request with just status change\n data = {'RequestStatus': 'assignment-approved'}\n self.putRequestWithAuth(requestName, data)\n response = self.getRequestWithNoStale('status=assignment-approved')\n self.assertEqual(response[1], 200, \"put request status change\")\n self.assertEqual(self.resultLength(response), 1)\n\n # assign with team\n # test put request with just status change\n data = {'RequestStatus': 'assigned'}\n data.update(self.rerecoAssignArgs)\n self.putRequestWithAuth(requestName, data)\n response = self.getRequestWithNoStale('status=assigned')\n self.assertEqual(response[1], 200, \"put request status change\")\n self.assertEqual(self.resultLength(response), 1)\n\n response = self.getRequestWithNoStale('status=assigned&team=%s' %\n self.rerecoAssignArgs['Team'])\n self.assertEqual(response[1], 200, \"put request status change\")\n self.assertEqual(self.resultLength(response), 1)\n\n response = self.getMultiRequestsWithAuth([requestName])\n self.assertEqual(self.resultLength(response), 1)\n self.assertEqual(list(response[0]['result'][0])[0], requestName)\n\n #response = self.cloneRequestWithAuth(requestName)\n #self.assertEqual(response[1], 200, \"put request clone\")\n #response = self.getRequestWithNoStale('status=new')\n #self.assertEqual(self.resultLength(response), 1)", "def test_reqrep(nsproxy, serializer, message, response):\n\n def rep_handler(agent, message):\n return response\n\n a0 = run_agent('a0')\n a1 = run_agent('a1')\n addr = a0.bind('REP', 'reply', rep_handler, serializer=serializer)\n a1.connect(addr, 'request')\n assert a1.send_recv('request', message) == response", "def test_custom_action_response_descriptor_octopus_server_web_api_actions_worker_connection_status_responder(self):\n pass", "def test_get_data(self):\n\n\t\t# Test to go here when best approach is decided for making requests.", "def test_standard_requests(self):\n get_msgs = self.client.message_recorder(\n blacklist=self.BLACKLIST, replies=True)\n nomid_req = partial(self.client.blocking_request, use_mid=False)\n nomid_req(katcp.Message.request(\"watchdog\"))\n nomid_req(katcp.Message.request(\"restart\"))\n nomid_req(katcp.Message.request(\"log-level\"))\n nomid_req(katcp.Message.request(\"log-level\", \"trace\"))\n nomid_req(katcp.Message.request(\"log-level\", \"unknown\"))\n nomid_req(katcp.Message.request(\"help\"))\n nomid_req(katcp.Message.request(\"help\", \"watchdog\"))\n nomid_req(katcp.Message.request(\"help\", \"unknown-request\"))\n nomid_req(katcp.Message.request(\"client-list\"))\n nomid_req(katcp.Message.request(\"version-list\"))\n nomid_req(katcp.Message.request(\"sensor-list\"))\n nomid_req(katcp.Message.request(\"sensor-list\", \"an.int\"))\n nomid_req(katcp.Message.request(\"sensor-list\", \"an.unknown\"))\n nomid_req(katcp.Message.request(\"sensor-value\"))\n nomid_req(katcp.Message.request(\"sensor-value\", \"an.int\"))\n nomid_req(katcp.Message.request(\"sensor-value\",\n \"an.unknown\"))\n nomid_req(katcp.Message.request(\"sensor-sampling\", \"an.int\"))\n nomid_req(katcp.Message.request(\"sensor-sampling\", \"an.int\",\n \"differential\", \"2\"))\n nomid_req(katcp.Message.request(\"sensor-sampling\", \"an.int\",\n \"event-rate\", \"2\", \"3\"))\n nomid_req(katcp.Message.request(\"sensor-sampling\"))\n nomid_req(katcp.Message.request(\"sensor-sampling\",\n \"an.unknown\", \"auto\"))\n nomid_req(katcp.Message.request(\"sensor-sampling\", \"an.int\", \"unknown\"))\n\n def tst():\n self.server.log.trace(\"trace-msg\")\n self.server.log.debug(\"debug-msg\")\n self.server.log.info(\"info-msg\")\n self.server.log.warn(\"warn-msg\")\n self.server.log.error(\"error-msg\")\n self.server.log.fatal(\"fatal-msg\")\n self.server.ioloop.add_callback(tst)\n\n self.assertEqual(self.server.restart_queue.get_nowait(), self.server)\n expected_msgs = [\n (r\"!watchdog ok\", \"\"),\n (r\"!restart ok\", \"\"),\n (r\"!log-level ok warn\", \"\"),\n (r\"!log-level ok trace\", \"\"),\n (r\"!log-level fail Unknown\\_logging\\_level\\_name\\_'unknown'\", \"\"),\n (r\"#help cancel-slow-command Cancel\\_slow\\_command\\_request,\\_\"\n \"resulting\\_in\\_it\\_replying\\_immediately\", \"\"),\n (r\"#help client-list\", \"\"),\n (r\"#help halt\", \"\"),\n (r\"#help help\", \"\"),\n (r\"#help log-level\", \"\"),\n (r\"#help new-command\", \"\"),\n (r\"#help raise-exception\", \"\"),\n (r\"#help raise-fail\", \"\"),\n (r\"#help restart\", \"\"),\n (r\"#help sensor-list\", \"\"),\n (r\"#help sensor-sampling\", \"\"),\n (r\"#help sensor-sampling-clear\", \"\"),\n (r\"#help sensor-value\", \"\"),\n (r\"#help slow-command\", \"\"),\n (r\"#help version-list\", \"\"),\n (r\"#help watchdog\", \"\"),\n (r\"!help ok %d\" % NO_HELP_MESSAGES, \"\"),\n (r\"#help watchdog\", \"\"),\n (r\"!help ok 1\", \"\"),\n (r\"!help fail\", \"\"),\n (r\"#client-list\", \"\"),\n (r\"!client-list ok 1\", \"\"),\n (r\"#version-list katcp-protocol\", \"\"),\n (r\"#version-list katcp-library\", \"\"),\n (r\"#version-list katcp-device\", \"\"),\n (r\"!version-list ok 3\", \"\"),\n (r\"#sensor-list an.int An\\_Integer. count integer -5 5\", \"\"),\n (r\"!sensor-list ok 1\", \"\"),\n (r\"#sensor-list an.int An\\_Integer. count integer -5 5\", \"\"),\n (r\"!sensor-list ok 1\", \"\"),\n (r\"!sensor-list fail\", \"\"),\n (r\"#sensor-value 12345.000000 1 an.int nominal 3\", \"\"),\n (r\"!sensor-value ok 1\", \"\"),\n (r\"#sensor-value 12345.000000 1 an.int nominal 3\", \"\"),\n (r\"!sensor-value ok 1\", \"\"),\n (r\"!sensor-value fail\", \"\"),\n (r\"!sensor-sampling ok an.int none\", \"\"),\n (r\"#sensor-status 12345.000000 1 an.int nominal 3\", \"\"),\n (r\"!sensor-sampling ok an.int differential 2\", \"\"),\n (r\"#sensor-status 12345.000000 1 an.int nominal 3\", \"\"),\n (r\"!sensor-sampling ok an.int event-rate 2 3\", \"\"),\n (r\"!sensor-sampling fail No\\_sensor\\_name\\_given.\", \"\"),\n (r\"!sensor-sampling fail Unknown\\_sensor\\_name:\\_an.unknown.\", \"\"),\n (r\"!sensor-sampling fail Unknown\\_strategy\\_name:\\_unknown.\", \"\"),\n (r\"#log trace\", r\"root trace-msg\"),\n (r\"#log debug\", r\"root debug-msg\"),\n (r\"#log info\", r\"root info-msg\"),\n (r\"#log warn\", r\"root warn-msg\"),\n (r\"#log error\", r\"root error-msg\"),\n (r\"#log fatal\", r\"root fatal-msg\"),\n ]\n self._assert_msgs_like(get_msgs(min_number=len(expected_msgs)),\n expected_msgs)", "def test_sdcrpc_origin_target(sdc_builder, sdc_executor):\n # test static\n sdc_rpc_id = get_random_string(string.ascii_letters, 10)\n raw_str = 'Hello World!'\n\n # Build the SDC RPC origin pipeline.\n builder = sdc_builder.get_pipeline_builder()\n\n sdc_rpc_origin = builder.add_stage(name='com_streamsets_pipeline_stage_origin_sdcipc_SdcIpcDSource')\n sdc_rpc_origin.sdc_rpc_listening_port = SDC_RPC_LISTENING_PORT\n sdc_rpc_origin.sdc_rpc_id = sdc_rpc_id\n\n sdc_rpc_origin >> (builder.add_stage(label='Trash'))\n rpc_origin_pipeline = builder.build('SDC RPC origin pipeline')\n\n # Build the SDC RPC target pipeline.\n builder = sdc_builder.get_pipeline_builder()\n\n dev_raw_data_source = builder.add_stage('Dev Raw Data Source')\n dev_raw_data_source.data_format = 'TEXT'\n dev_raw_data_source.raw_data = raw_str\n\n sdc_rpc_destination = builder.add_stage(name='com_streamsets_pipeline_stage_destination_sdcipc_SdcIpcDTarget')\n sdc_rpc_destination.sdc_rpc_connection.append('{}:{}'.format(sdc_executor.server_host, SDC_RPC_LISTENING_PORT))\n sdc_rpc_destination.sdc_rpc_id = sdc_rpc_id\n\n dev_raw_data_source >> sdc_rpc_destination\n rpc_target_pipeline = builder.build('SDC RPC target pipeline')\n\n sdc_executor.add_pipeline(rpc_origin_pipeline, rpc_target_pipeline)\n\n # Run pipelines and assert data.\n sdc_executor.start_pipeline(rpc_origin_pipeline)\n sdc_executor.start_pipeline(rpc_target_pipeline).wait_for_pipeline_output_records_count(1)\n snapshot = sdc_executor.capture_snapshot(rpc_origin_pipeline, start_pipeline=False).snapshot\n snapshot_data = snapshot[sdc_rpc_origin.instance_name].output[0].field['text'].value\n\n assert raw_str == snapshot_data\n\n sdc_executor.stop_pipeline(rpc_target_pipeline)\n sdc_executor.stop_pipeline(rpc_origin_pipeline)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper method to get baseline file.
def get_test_baseline(file_name): return os.path.abspath( os.path.join( os.path.abspath(__file__), u'..', u'..', u'osqlcli', u'jsonrpc', u'contracts', u'tests', u'baselines', file_name))
[ "def readBaseline(BASELINE):\n\tbaselineDictionnary={\"blast\":{},\"protProfiles\":{}}\n\ttry:\n\t\twith open(BASELINE, \"r\") as f:\n\t\t\tfor line in f:\n\t\t\t\t####\tcheck the content of the file and look for > character (It indicates if the keyword is specific or nonSpecific)\n\t\t\t\tkeywords=re.search(r'>([^\\n]+)', line)\n\t\t\t\t####\tFor specific keywords\n\t\t\t\tif not keywords:\n\t\t\t\t\treadBlastBaselineKeywords(line, baselineDictionnary)\n\t\t\t\t####\tFor nonSpecific keyword\n\t\t\t\telse:\n\t\t\t\t\treadProtProfilesBaselineKeywords(keywords.groups()[0], baselineDictionnary)\n\t\treturn baselineDictionnary\n\n\texcept (FileNotFoundError, NameError) as e:\n\t\tprint(\"/!\\\tError: {}\\n####\tClassification aborted\".format(e))\n\t\tsys.exit(1)", "def baseline(self, *args, **kwargs):\n return _measures.measures_baseline(self, *args, **kwargs)", "def create_baseline(target, save_baseline=to_csv, **kwargs):", "def readBaselineTable(fileName):\n print('Reading baseline table...')\n print()\n\n baselineTable = pd.read_csv(fileName, header=None, sep=' ') # Read table\n baselineTable.columns = ['Stem', 'numDate', 'sceneID', 'parBaseline', 'OrbitBaseline']\n baselineTable['Date'] = pd.to_datetime(baselineTable['Stem'].str.slice(start=15, stop=23)) # Scrape dates\n baselineTable = baselineTable.sort_values(by='numDate')\n baselineTable = baselineTable.reset_index(drop=True)\n\n return baselineTable", "def test(self):\n baseline_file = baselineDir + name + \".receipt\"\n # self.longMessage = True\n msg = \"Missing baseline for \" + name + \": \" + baseline_file\n self.assertTrue(os.path.exists(baseline_file), msg=msg)", "def get_mean_file(self):\n raise NotImplementedError('Please implement me')", "def baseline_sample(self):\n return self.sample_db[self.obj_function.default_params]", "def getBaseStrengthFile(self) -> str:\n ...", "def orig_file(self):\n if self._orig_file is None:\n self._orig_file = self.read_rpt(self.path)\n return self._orig_file", "def load_baseline_model():\n checkpoint_filepath = f\"{CURR_DIR}/model/baseline-cnn-model.hdf5\"\n global baseline_model\n baseline_model = load_model(checkpoint_filepath)\n baseline_model._make_predict_function()", "def _core_rrd_file(self, service):\n _LOGGER.info('Return %s', self._metrics_fpath(service))\n\n return _get_file(self._metrics_fpath(service), arch_extract=False)", "def _generic_baseline_paths(self, test_baseline_set):\n filesystem = self._tool.filesystem\n baseline_paths = []\n for test in test_baseline_set.all_tests():\n filenames = [\n self._file_name_for_expected_result(test, suffix)\n for suffix in BASELINE_SUFFIX_LIST\n ]\n baseline_paths += [\n filesystem.join(self._web_tests_dir(), filename)\n for filename in filenames\n ]\n baseline_paths.sort()\n return baseline_paths", "def getItemBaselineByBaselineId(self):\n sql = \"SELECT * FROM itembaseline WHERE baseline_id = '%s';\" %self.baseline_id \n try:\n cursor = self.db.cursor()\n cursor.execute(sql)\n resultset = cursor.fetchall() \n return resultset \n except:\n return \"Error!\"", "def create_baseline(output=None):\n output = output or \"baseline_pkg.txt\"\n with open(output, \"w\") as bl_file:\n bl_file.write(\"\\n\".join(sorted(_get_installed_pkgs())))\n print(f\"baseline packages written to {output}\")", "def getTrainFile(self):\n\n return self.trainFile", "def get_basefile(file=\"\"):\n\n\tbase = \"\"\n\tif file == \"\":\n\t\treturn base\n\n\t#[base, suffix] = file.rsplit(\".\",1)\n\t#[base, suffix] = string.rsplit(file, \".\")\n\tdot_index = file.rindex(\".\")\n\tbase = file[0:dot_index]\n\treturn base", "def data_for_baseline_adjustment():\n filename = 'baseline.h5'\n file = h5py.File(filename, 'w', libver='latest')\n wav_group = file.require_group('/rounds/round000/76487')\n # generate the data\n time_data = np.ones(50_000, dtype=np.float64)\n perp_data = np.ones(50_000, dtype=np.float64)\n par_data = np.empty(50_000, dtype=np.float64)\n par_data.fill(2.0)\n wav_group.create_dataset('time', data=time_data, dtype=np.float64)\n wav_group.create_dataset('perp', data=perp_data, dtype=np.float64)\n wav_group.create_dataset('par', data=par_data, dtype=np.float64)\n yield file\n # clean up\n file.close()\n remove(filename)", "def get_baseline(self, i, j, src='z'):\n bl = self[j] - self[i]\n if type(src) == str:\n if src == 'e': return n.dot(self._eq2now, bl)\n elif src == 'z': return n.dot(self._eq2zen, bl)\n elif src == 'r': return bl\n else: raise ValueError('Unrecognized source:' + src)\n try:\n if src.alt < 0:\n raise a.phs.PointingError('%s below horizon' % src.src_name)\n m = src.map\n except(AttributeError):\n ra,dec = a.coord.eq2radec(src)\n m = a.coord.eq2top_m(self.sidereal_time() - ra, dec)\n return n.dot(m, bl).transpose()", "def getSummaryFilePath() -> str:\n __checkBase()\n return os.path.join(FIRED_BASE_FOLDER, SUMMARY_FOLDER_NAME, ONE_HZ_FOLDER_NAME, COMBINED_FILE_NAME)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify osqlcliclient's tables, views, columns, and schema are populated.
def test_schema_table_views_and_columns_query(self): try: client = create_osql_cli_client() list(client.execute_query('CREATE TABLE tabletest1 (a int, b varchar(25));')) list(client.execute_query('CREATE TABLE tabletest2 (x int, y varchar(25), z bit);')) list(client.execute_query('CREATE VIEW viewtest as SELECT a from tabletest1;')) list(client.execute_query('CREATE SCHEMA schematest;')) list(client.execute_query('CREATE TABLE schematest.tabletest1 (a int);')) assert ('schematest', 'tabletest1') in set(client.get_tables()) assert ('dbo', 'viewtest') in set(client.get_views()) assert ('schematest', 'tabletest1', 'a', 'int', 'NULL') in set(client.get_table_columns()) assert ('dbo', 'viewtest', 'a', 'int', 'NULL') in set(client.get_view_columns()) assert 'schematest' in client.get_schemas() finally: list(client.execute_query('DROP TABLE tabletest1;')) list(client.execute_query('DROP TABLE tabletest2;')) list(client.execute_query('DROP VIEW viewtest IF EXISTS;')) list(client.execute_query('DROP TABLE schematest.tabletest1;')) list(client.execute_query('DROP SCHEMA schematest;')) shutdown(client)
[ "def verify(self):\n with self.connection() as conn:\n self._ensure_tables(conn)", "def test_create_tables(self):\n self._db.create_tables()\n tables = json.loads(self._db.get_database_info())\n expected_tables = db_connection.Database.get_columns().keys()\n for table in expected_tables:\n assert table in tables.keys()", "def test_schema(checker):\n assert checker.check() == 0, \"Schema consistency warnings\"", "def test_get_schema_of_query(self):\n pass", "def test_initial_state(self):\n tables = self.database_sig.keys()\n\n # Check that a few known tables are in the list, to make sure\n # the scan worked.\n self.assertTrue('auth_permission' in tables)\n self.assertTrue('auth_user' in tables)\n self.assertTrue('django_evolution' in tables)\n self.assertTrue('django_project_version' in tables)\n\n self.assertTrue('indexes' in self.database_sig['django_evolution'])\n\n # Check the Evolution model\n indexes = self.database_sig['django_evolution']['indexes']\n\n self.assertIn(\n {\n 'unique': False,\n 'columns': ['version_id'],\n },\n indexes.values())", "def CompareSchema(self):\n database = \"\"\n table = \"\"\n fileLocation = \"\"\n result = compareSchema(database, table, fileLocation)\n self.assertEqual(result, True)", "def test_tenant_schemas(self):\n # In a tenant app, the models are separated between \"public\" where\n # all the common data exists and the \"tenant\" which you would have\n # one or more of, the former is where you would add your specific\n # data. The tenant app keeps track of this, all tables just have a\n # name, no schema inside the `db_table` since that would limit you\n # to a single tenant.\n original_name = models.CustomSchemaView._meta.db_table\n schema_name, table_name = original_name.split('.')\n\n connection.schema_name = schema_name\n with connection.cursor() as cur:\n # Set up the conditions of how the tenant applications work\n models.CustomSchemaView._meta.db_table = table_name\n cur.execute(\"SET search_path = {0}\".format(','.join([schema_name,\n 'public'])))\n\n vs = ViewSyncer()\n vs.run_backlog([models.CustomSchemaView], True, True)\n\n # Clean up, lets put everything the way we found it.\n cur.execute(\"SET search_path = {0}\".format('public'))\n models.CustomSchemaView._meta.db_table = original_name\n del connection.schema_name", "def test_from_sql(self):\n ie = SqlImportEngine()\n schema_rt = ie.convert(DB)\n schemaview_rt = SchemaView(schema_rt)\n print(yaml_dumper.dumps(schema_rt))\n schemaview = self.schemaview\n for c in schemaview.all_classes().values():\n self.assertIn(c.name, schemaview_rt.all_classes())\n for s in schemaview.class_induced_slots(c.name):\n if s.name == \"knows\":\n # these slots are moved to join tables\n self.assertNotIn(s.name, schemaview_rt.all_slots().keys())\n else:\n self.assertIn(s.name, schemaview_rt.all_slots().keys())\n person = schemaview_rt.get_class('Person')\n person_knows_join = schemaview_rt.get_class('Person_knows')\n id_slot = person.attributes['id']\n age_slot = person.attributes['age']\n self.assertTrue(id_slot.identifier)\n self.assertEqual('integer', age_slot.range)\n self.assertEqual('Person', person_knows_join.attributes['Person_id'].range)\n self.assertEqual('Person', person_knows_join.attributes['knows_id'].range)", "def testAccessEmptyTable(self):\n results = [(idx,) for idx in self.manager.snimpyEmptyDescr]\n self.assertEqual(results, [])", "def test_empty_table(db_connection):\n with db_connection.cursor() as curs:\n curs.execute(\"SELECT * FROM order_item\")\n assert curs.rowcount is 0", "def test_check_schema_required():\n schema = {\"type\": \"type 1\"}\n\n returned_schema, artifacts = column.check_schema(\n schema=copy.deepcopy(schema), required=True\n )\n\n assert returned_schema == schema\n assert artifacts.nullable is False", "def __test_json_table_object(self, db_name, tbl_name):\n obj_url = self.CATALOG_OBJECT_URL + \\\n \"?json&object_type=TABLE&object_name={0}.{1}\".format(db_name, tbl_name)\n self.client.execute(\"invalidate metadata %s.%s\" % (db_name, tbl_name))\n responses = self.get_and_check_status(obj_url, ports_to_test=self.CATALOG_TEST_PORT)\n obj = json.loads(json.loads(responses[0].text)[\"json_string\"])\n assert obj[\"type\"] == 3, \"type should be TABLE\"\n assert \"catalog_version\" in obj, \"TCatalogObject should have catalog_version\"\n tbl_obj = obj[\"table\"]\n assert tbl_obj[\"db_name\"] == db_name\n assert tbl_obj[\"tbl_name\"] == tbl_name\n assert \"hdfs_table\" not in tbl_obj, \"Unloaded table should not have hdfs_table\"\n\n self.client.execute(\"refresh %s.%s\" % (db_name, tbl_name))\n responses = self.get_and_check_status(obj_url, ports_to_test=self.CATALOG_TEST_PORT)\n obj = json.loads(json.loads(responses[0].text)[\"json_string\"])\n assert obj[\"type\"] == 3, \"type should be TABLE\"\n assert \"catalog_version\" in obj, \"TCatalogObject should have catalog_version\"\n tbl_obj = obj[\"table\"]\n assert tbl_obj[\"db_name\"] == db_name\n assert tbl_obj[\"tbl_name\"] == tbl_name\n assert \"columns\" in tbl_obj, \"Loaded TTable should have columns\"\n assert tbl_obj[\"table_type\"] == 0, \"table_type should be HDFS_TABLE\"\n assert \"metastore_table\" in tbl_obj\n hdfs_tbl_obj = tbl_obj[\"hdfs_table\"]\n assert \"hdfsBaseDir\" in hdfs_tbl_obj\n assert \"colNames\" in hdfs_tbl_obj\n assert \"nullPartitionKeyValue\" in hdfs_tbl_obj\n assert \"nullColumnValue\" in hdfs_tbl_obj\n assert \"partitions\" in hdfs_tbl_obj\n assert \"prototype_partition\" in hdfs_tbl_obj", "def _db_checkup(self):\n self.validate_table(self._db_data_table)", "def test_load_output_schema(spark):\n schema = DataTransformer(spark, schema_path)\\\n .load_output_schema(schema_path=schema_path)\n assert set(schema.keys()) == {'col1', 'col2'}", "def check():\n from mephisto.abstractions.databases.local_database import LocalMephistoDB\n from mephisto.operations.utils import get_mock_requester\n\n try:\n db = LocalMephistoDB()\n get_mock_requester(db)\n except Exception as e:\n click.echo(\"Something went wrong.\")\n click.echo(e)\n return\n click.echo(\"Mephisto seems to be set up correctly.\")", "def test_setup_database_consistent(self):\n\t\tself.assertWeightsNonnegative()", "def test_proxy_columns(self):\n # We call it multiple times to make sure it doesn't change with time.\n for _ in range(2):\n self.assertEqual(\n len(Concert.band_1.manager._foreign_key_meta.proxy_columns), 2\n )\n self.assertEqual(\n len(Concert.band_1._foreign_key_meta.proxy_columns), 4\n )", "def test_compare_table_sanity_check(model, logger):\n description = description_for(model)\n assert compare_tables(model, description)\n assert not logger.caplog.record_tuples", "def test_check_schema_schema(schema):\n returned_schema, _ = column.check_schema(schema=copy.deepcopy(schema))\n\n assert returned_schema == schema" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify if the OsqlCliClient can successfully reset its connection
def test_osqlcliclient_reset_connection(self): try: osqlcli = create_osql_cli() osqlcli.reset() finally: shutdown(osqlcli.osqlcliclient_main)
[ "def test_master_reset_connection(self):\n with mock.patch(\"locust.runners.FALLBACK_INTERVAL\", new=0.1):\n with mock.patch(\"locust.rpc.rpc.Server\", mocked_rpc(raise_on_close=False)) as server:\n master = self.get_runner()\n self.assertEqual(0, len(master.clients))\n server.mocked_send(Message(\"client_ready\", NETWORK_BROKEN, \"fake_client\"))\n self.assertTrue(master.connection_broken)\n server.mocked_send(Message(\"client_ready\", __version__, \"fake_client\"))\n sleep(1)\n self.assertFalse(master.connection_broken)\n self.assertEqual(1, len(master.clients))\n master.quit()", "def check_connection():\n if _References.connection.status == comms.ConnectionStatus.DISCONNECTED:\n _References.connection.connect()\n elif _References.connection.status == comms.ConnectionStatus.CONNECTED:\n if not _References.connection.connected:\n _References.connection.reconnect()", "def verify_connection():\n global channel\n if not channel or channel.is_open == False:\n logger.error(\"broker not connected, reconnecting\")\n channel = None\n return reconnect()\n return True", "def test_check_connect(nodaq):\n logger.debug('test_check_connect')\n with pytest.raises(RuntimeError):\n nodaq.wait()", "def test_reconnect_all(self):\n pass", "def test_close_and_reconnect(self):\n assert self.client.is_active, 'Client must be active to test quit'\n\n self.client.close()\n\n assert not self.client.is_active, 'Client must be inactive following close call'\n\n self.client.reconnect()\n\n assert self.client.is_active, 'Client must be active after reconnecting'", "def reset() -> None:\n if __designated_connection is not None:\n __designated_connection.reset()\n else:\n connect()", "def test_reusing_connection(self):\n conn_context = self.rpc.create_connection(new=False)\n conn1 = conn_context.connection\n conn_context.close()\n conn_context = self.rpc.create_connection(new=False)\n conn2 = conn_context.connection\n conn_context.close()\n self.assertEqual(conn1, conn2)", "def test_basic_syn_tcp_diag_client(self):\n # connect/disconnect\n client = ModbusTcpDiagClient()\n client.socket = mockSocket()\n self.assertTrue(client.connect())\n client.close()", "def test_reconnect_if_mongodb_is_down(self):\n\n accounts_collection = sut.get_collection(\"accounts\")\n self.assertTrue(bool(accounts_collection))\n sut.disconnect()\n\n accounts_collection = sut.get_collection(\"accounts\")\n self.assertTrue(bool(accounts_collection))", "def _try_connected(self):\n try:\n self.connection.cursor().execute(\"SELECT 1;\")\n return True\n except (psycopg2.OperationalError, psycopg2.InterfaceError):\n return False", "def check_connection(self):\n # Send the client an echo signal to ask it to repeat back\n self.send(\"E\", \"z\");\n # Check if \"e\" gets sent back\n if (self.recv(2, \"e\") != \"z\"):\n # If the client didn't confirm, the connection might be lost\n self.__connection_lost();", "def test_reconnect(self):\n self.transport.client_service.delay = 0\n old_protocol = self.protocol\n yield self.protocol.transport.loseConnection()\n yield deferLater(reactor, 0, lambda: None) # Let the reactor run.\n self.assertNotEqual(old_protocol, self.protocol)\n yield self.process_login_commands('username', 'password')", "def test_0040_test_connection(self):\n self.assertTrue(self.api.test_connection())", "def test_20_delete_connection(self):\n\n # Create a connection with some properties so we can easily identify the connection\n connection = BlockingConnection(self.address(),\n properties=CONNECTION_PROPERTIES_UNICODE_STRING)\n query_command = 'QUERY --type=connection'\n outputs = json.loads(self.run_qdmanage(query_command))\n identity = None\n passed = False\n\n print()\n\n for output in outputs:\n if output.get('properties'):\n conn_properties = output['properties']\n # Find the connection that has our properties - CONNECTION_PROPERTIES_UNICODE_STRING\n # Delete that connection and run another qdmanage to see\n # if the connection is gone.\n if conn_properties.get('int_property'):\n identity = output.get(\"identity\")\n if identity:\n update_command = 'UPDATE --type=connection adminStatus=deleted --id=' + identity\n try:\n self.run_qdmanage(update_command)\n query_command = 'QUERY --type=connection'\n outputs = json.loads(\n self.run_qdmanage(query_command))\n no_properties = True\n for output in outputs:\n if output.get('properties'):\n no_properties = False\n conn_properties = output['properties']\n if conn_properties.get('int_property'):\n passed = False\n break\n else:\n passed = True\n if no_properties:\n passed = True\n except Exception as e:\n passed = False\n\n # The test has passed since we were allowed to delete a connection\n # because we have the policy permission to do so.\n self.assertTrue(passed)", "def test_execute_reset(self):\n self.assert_enter_command_mode()\n\n # Test RESET\n\n self.assert_reset()\n\n self.check_agent_state(ResourceAgentState.UNINITIALIZED)\n\n self.assert_enter_command_mode()", "def verify_connection(self, request, client_address):\n return 1", "def test_reopenLogErrorIfReconnect(self):\n class ConnectionCursorRaise(object):\n count = 0\n\n def reconnect(self):\n pass\n\n def cursor(self):\n if self.count == 0:\n self.count += 1\n raise RuntimeError(\"problem!\")\n\n pool = FakePool(None)\n transaction = Transaction(pool, ConnectionCursorRaise())\n transaction.reopen()\n errors = self.flushLoggedErrors(RuntimeError)\n self.assertEqual(len(errors), 1)\n self.assertEqual(errors[0].value.args[0], \"problem!\")", "def test_syn_tcp_diag_client_instantiation(self):\n client = get_client()\n self.assertNotEqual(client, None)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify the results of running a stored proc with multiple result sets
def test_stored_proc_multiple_result_sets(self): try: client = create_osql_cli_client() create_stored_proc = u"CREATE PROC sp_osqlcli_multiple_results " \ u"AS " \ u"BEGIN " \ u"SELECT 'Morning' as [Name] UNION ALL select 'Evening' " \ u"SELECT 'Dawn' as [Name] UNION ALL select 'Dusk' UNION ALL select 'Midnight' " \ u"END" exec_stored_proc = u"EXEC sp_osqlcli_multiple_results" del_stored_proc = u"DROP PROCEDURE sp_osqlcli_multiple_results" list(client.execute_query(create_stored_proc)) row_counts = [] for rows, columns, message, query, is_error in client.execute_query(exec_stored_proc): row_counts.append(len(rows)) self.assertTrue(row_counts[0] == 2) self.assertTrue(row_counts[1] == 3) list(client.execute_query(del_stored_proc)) finally: shutdown(client)
[ "def _test_large_result_set(self, schema, graphson):\n self.execute_graph(schema.fixtures.large(), graphson)\n g = self.fetch_traversal_source(graphson)\n traversal = g.V()\n vertices = self.execute_traversal(traversal, graphson)\n for vertex in vertices:\n self._validate_generic_vertex_result_type(g, vertex)", "def call_proc(self, proc, args=None, filters=None, skip_null=False):\n if not proc or not isinstance(proc, str):\n raise ValueError(\"stored procedure name is invalid\")\n\n if args is None:\n args = list()\n if not isinstance(args, list):\n raise ValueError(\"args value is invalid\")\n\n sets = list()\n data = list()\n conn = self.raw_connection()\n\n try:\n with closing(conn.cursor()) as cursor:\n cursor.callproc(proc, args)\n # capture the result set fields and data. cursor.fetchall() needs to be first.\n sets.append({\"data\": list(cursor.fetchall()), \"fields\": list(cursor.description)})\n\n # if multiple sets are returned, capture them as well.\n while cursor.nextset():\n try:\n sets.append({\"data\": list(cursor.fetchall()), \"fields\": list(cursor.description)})\n except TypeError:\n pass\n except:\n raise\n finally:\n conn.close()\n\n # reverse the set list, return the first set.\n sets.reverse()\n for item in sets:\n\n if not item[\"fields\"] or len(item[\"fields\"]) == 0:\n continue\n\n fields = item[\"fields\"]\n results = item[\"data\"]\n\n for row in results:\n od = collections.OrderedDict()\n\n for x in range(0, len(fields)):\n field = fields[x][0]\n value = row[x]\n\n if skip_null is True and value is None:\n continue\n if filters and field.lower() not in filters.lower():\n continue\n\n if isinstance(value, (datetime.datetime, datetime.date)):\n od[field] = value.isoformat()\n elif field == \"participant_id\":\n od[field] = \"P{0}\".format(value)\n else:\n od[field] = value\n\n data.append(od)\n\n # skip other sets.\n break\n\n return data", "def test_execute_2(self):\n results = querying.execute(self.mock_engine, self.mock_executable)\n\n self.assertEqual(results, [self.data_dict])", "def test_algo_multiprocess_sandboxing_success():\n params = dict(\n sample=0.2,\n resolution='location_level_1')\n result = run_algo('sample_algos/algo1.py', params)\n assert type(result) is list", "def test_processlist():\n _test_call(mysql.processlist, \"SHOW FULL PROCESSLIST\")", "def testCallProc(self):\n var = self.cursor.var(cx_Oracle.NUMBER)\n results = self.cursor.callproc(u\"proc_Test\", (u\"hi\", 5, var))\n self.failUnlessEqual(results, [u\"hi\", 10, 2.0])", "def test_query(self):\n # want to check 1) length of result and 2) that all values in result \n # are in the generator, although it would be pretty hard for them not\n # to be\n width = True #we'll only do one here since it really doesn't matter\n gen = self.db.init_insert(101, 101, width, True)\n compareresult = self.gen_to_list(gen)\n self.sequential_inserter(width)\n \n records = 10\n streams = 10\n result = self.db.query(records, streams, True)\n self.assertEqual(len(result), records*streams)\n for x in result:\n self.assert_(x in compareresult)\n \n print(\"test_query passed\")", "def read_single_result():\n # TODO: your code here\n # example return values\n return \"some_table1\", \"some_table2\", \"p1\", \"p2\", \"runtime\"", "def test_multiple_sqs_list_from_database():\r\n raise NotImplementedError", "def test_report_result_multiple_times(self):\n cl = _t_add_client()\n tc = _t_add_test(os.path.join(self.test_dir, 'test_case_name.dat'))\n pl, pv = _t_add_plugin(\n 'test_pl_name',\n os.path.join(self.plugin_dir, 'pl_file_test.tar.gz')\n )\n _t_add_plugin(\n 'test_pl_name_2',\n os.path.join(self.plugin_dir, 'pl_file_test.tar.gz')\n )\n plt = _t_add_plugin_test(pl, tc)\n\n result = _t_create_result(count=1)\n report = {\n 'duration':1200,\n 'iterations':10,\n 'mac':cl.mac_addr,\n 'has_result':True,\n 'plugin_name':pl.name,\n 'plugin_version':pv.name,\n 'classification':result['classification'],\n 'count':result['count'],\n 'defect':result['defect'],\n 'failure':result['failure'],\n 'file_name':result['file_name'],\n 'log':result['log'],\n 'name':result['name'],\n 'result_hash':result['result_hash']\n }\n for _ in range(2):\n _t_add_work_unit(cl, pv, plt)\n with open(result['temp_fs_name'], 'rb') as fp:\n report['attachment'] = fp\n response = self.client.post('/csserver/workreport/', report)\n self.assertEqual(response.status_code, 200)\n os.remove(result['temp_fs_name'])\n r = Result.objects.all()\n self.assertEqual(len(r), 1)\n r = r[0]\n self.assertEqual(r.count, 2)\n self.assertEqual(Result.objects.filter(triage_state=TriageState.objects.get(name='New')).count(), 1)", "def executeSQLProcStandOverlay(db_connection, sql_proc, param_value):\r\n cursor = db_connection.cursor()\r\n sql = \"\"\"EXEC {0}\r\n @OBJECTID = {1};\r\n \"\"\".format(sql_proc, param_value)\r\n try:\r\n rows = cursor.execute(sql)\r\n while rows.nextset():\r\n rows.fetchone()\r\n except:\r\n return False\r\n return True", "def libgen_execute_command_and_check_result(in_success_result, in_success_res_count, in_failure_result, in_failure_res_count, in_command, *in_args):\n if len(in_args) > 0:\n command = in_command % (in_args)\n else:\n command = in_command\n out = connections.execute_mml_without_check(command)\n \n if out.count(in_success_result) == int(in_success_res_count):\n return 'success'\n elif out.count(in_failure_result) == int(in_failure_res_count):\n return 'failure'\n else:\n return 'the return is wrong: '+out", "def test(result, map1):\n if len(result.index) == len(map1.index):\n #print(f\"Internal test SUCCESSFUL, {map} mapped on {key}\")\n pass\n else:\n print(f\"Internal test FAILED. Attention! Total rows of the result does not match total rows of the map {map}. Check if {map} is a perfect subset of {key}.\")", "def test_algo_singleprocess_sandboxing_success():\n params = dict(\n sample=0.2,\n resolution='location_level_1')\n result = run_algo('sample_algos/algo1.py', params, multiprocess=False)\n assert type(result) is list", "def _get_test_results(self, conn):\n return list(conn.execute(SA.select(\n columns=(\n self.reporter.TestResults,\n self.reporter.Tests,\n self.reporter.Failures,\n ),\n from_obj=self.reporter.TestResults.join(\n self.reporter.Tests,\n self.reporter.TestResults.c.test == self.reporter.Tests.c.id\n ).outerjoin(\n self.reporter.Failures,\n self.reporter.TestResults.c.failure == self.reporter.Failures.c.id\n )\n )))", "def load_data_from_staging(self,proc_name):\r\n try:\r\n connection = self.engine.raw_connection()\r\n connection.autocommit = False\r\n cursor = connection.cursor()\r\n\r\n sp_call = \"{0} {1}\".format('EXEC', proc_name)\r\n cursor.execute(sp_call)\r\n rows_affected = cursor.fetchone()[0]\r\n cursor.commit()\r\n\r\n logging.info(\"Executed stored procedure: {0}\".format(sp_call))\r\n logging.info(\"Inserted {} rows.\".format(rows_affected))\r\n except:\r\n logging.error(\"Unable to load data from staging. Exiting program.\")\r\n exit(1)", "def test_execute_value_subqueries_4(self):\n querying.execute_value_subqueries(self.mock_engine, \n self.mock_executable,\n self.mock_in_column,\n self.values)\n\n self.mock_in_column.in_.assert_called_with(self.values)", "def summariseResult(self, test):", "def verify_results(self, skip_verify_data=[], skip_verify_revid=[], sg_run=False):\n skip_key_validation = self._input.param(\"skip_key_validation\", False)\n self.__merge_all_buckets()\n for cb_cluster in self.get_cb_clusters():\n for remote_cluster_ref in cb_cluster.get_remote_clusters():\n try:\n src_cluster = remote_cluster_ref.get_src_cluster()\n dest_cluster = remote_cluster_ref.get_dest_cluster()\n\n if self._evict_with_compactor:\n for b in src_cluster.get_buckets():\n # only need to do compaction on the source cluster, evictions are propagated to the remote\n # cluster\n src_cluster.get_cluster().compact_bucket(src_cluster.get_master_node(), b)\n\n else:\n src_cluster.run_expiry_pager()\n dest_cluster.run_expiry_pager()\n\n src_cluster.wait_for_flusher_empty()\n dest_cluster.wait_for_flusher_empty()\n\n src_dcp_queue_drained = src_cluster.wait_for_dcp_queue_drain()\n dest_dcp_queue_drained = dest_cluster.wait_for_dcp_queue_drain()\n\n src_cluster.wait_for_outbound_mutations()\n dest_cluster.wait_for_outbound_mutations()\n except Exception as e:\n # just log any exception thrown, do not fail test\n self.log.error(e)\n if not skip_key_validation:\n try:\n if not sg_run:\n src_active_passed, src_replica_passed = \\\n src_cluster.verify_items_count(timeout=self._item_count_timeout)\n dest_active_passed, dest_replica_passed = \\\n dest_cluster.verify_items_count(timeout=self._item_count_timeout)\n\n src_cluster.verify_data(max_verify=self._max_verify, skip=skip_verify_data,\n only_store_hash=self.only_store_hash)\n dest_cluster.verify_data(max_verify=self._max_verify, skip=skip_verify_data,\n only_store_hash=self.only_store_hash)\n for _, cluster in enumerate(self.get_cb_clusters()):\n for bucket in cluster.get_buckets():\n h = httplib2.Http(\".cache\")\n resp, content = h.request(\n \"http://{0}:4984/db/_all_docs\".format(cluster.get_master_node().ip))\n self.assertEqual(json.loads(content)['total_rows'], self._num_items)\n client = SDKClient(scheme=\"couchbase\", hosts=[cluster.get_master_node().ip],\n bucket=bucket.name).cb\n for i in range(self._num_items):\n key = 'k_%s_%s' % (i, str(cluster).replace(' ', '_').\n replace('.', '_').replace(',', '_').replace(':', '_'))\n res = client.get(key)\n for xk, xv in res.value.items():\n rv = client.mutate_in(key, SD.get(xk, xattr=True))\n self.assertTrue(rv.exists(xk))\n self.assertEqual(xv, rv[xk])\n if sg_run:\n resp, content = h.request(\"http://{0}:4984/db/{1}\".format(cluster.get_master_node().ip, key))\n self.assertEqual(json.loads(content)['_id'], key)\n self.assertEqual(json.loads(content)[xk], xv)\n self.assertTrue('2-' in json.loads(content)['_rev'])\n except Exception as e:\n self.log.error(e)\n finally:\n if not sg_run:\n rev_err_count = self.verify_rev_ids(remote_cluster_ref.get_replications(),\n skip=skip_verify_revid)\n # we're done with the test, now report specific errors\n if (not (src_active_passed and dest_active_passed)) and \\\n (not (src_dcp_queue_drained and dest_dcp_queue_drained)):\n self.fail(\"Incomplete replication: Keys stuck in dcp queue\")\n if not (src_active_passed and dest_active_passed):\n self.fail(\"Incomplete replication: Active key count is incorrect\")\n if not (src_replica_passed and dest_replica_passed):\n self.fail(\"Incomplete intra-cluster replication: \"\n \"replica count did not match active count\")\n if rev_err_count > 0:\n self.fail(\"RevID verification failed for remote-cluster: {0}\".\n format(remote_cluster_ref))\n\n # treat errors in self.__report_error_list as failures\n if len(self.get_report_error_list()) > 0:\n error_logger = self.check_errors_in_goxdcr_logs()\n if error_logger:\n self.fail(\"Errors found in logs : {0}\".format(error_logger))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrapper for inserting floats features into Example proto.
def _floats_feature(value): return tf.train.Feature(float_list = tf.train.FloatList(value=[value]))
[ "def add_float(self, name, value):\r\n self.__add_field('float', name, value)\r\n return self", "async def put_float( # pylint: disable=inconsistent-return-statements\n self, complex_body: _models.FloatWrapper, *, content_type: str = \"application/json\", **kwargs: Any\n ) -> None:", "def append_float(self, value):\n self._stream.append_raw_bytes(struct.pack('f', value))", "def make_example(features):\n\n def _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=value))\n\n def _float32_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(value=value))\n\n def _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))\n\n feature_fns = {\n 'int64': _int64_feature,\n 'float32': _float32_feature,\n 'bytes': _bytes_feature\n }\n\n feature_dict = dict((key, feature_fns[feature_type](np.ravel(value)))\n for key, feature_type, value in features)\n\n # Create an example protocol buffer.\n example = tf.train.Example(features=tf.train.Features(feature=feature_dict))\n example_serial = example.SerializeToString()\n return example_serial", "def asGenericFloat(*args, **kwargs):\n \n pass", "def _as_feature(\n value_list: Union[List[int], List[str], List[float]]) -> tf.train.Feature:\n if not value_list:\n return None\n if isinstance(value_list[0], int):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=value_list))\n if isinstance(value_list[0], str):\n return tf.train.Feature(\n bytes_list=tf.train.BytesList(\n value=[value.encode('utf-8') for value in value_list]))\n if isinstance(value_list[0], float):\n return tf.train.Feature(float_list=tf.train.FloatList(value=value_list))\n # TODO(b/179309868)\n return None", "def setGenericFloat(*args, **kwargs):\n \n pass", "def float_func(self, fl, meta):\n fl = fl[0]\n constAddr = self.compiler.addConst(fl.value, fl.type)\n self.compiler.pushOperando(constAddr)\n self.compiler.pushTipo(fl.type)\n return fl", "def test_float_vector(capfd):\n attribute = 'optimize'\n name = 'State Vector'\n tag = 'STW'\n type_id = 'float_vec'\n default_value = None\n config_dict = {'STW': ['0.0 1.0 2.0', {'optimize': 'no'}]}\n result = convertXMLAttributesDictEntry(\n name, config_dict, tag, attribute, type_id, default_value=None)\n out, err = capfd.readouterr()\n ''' This test will check if it is returning [0.0 0.0 0.0] '''\n assert (result == np.array([0.0, 0.0, 0.0])).all()", "def test_univGroupsFromFloats(self):\n self.setAs(float)\n self._tester()", "def addFloat(self, ln, dv = 0):\n \n cmds.addAttr( ln = ln, at = 'float', dv = dv)", "def _float_serialiser(flag, logger):\n return Float64 if flag.data.get(\"max_precision\") else Float32", "def test_can_insert_double_and_float(self):\n\n class FloatingPointModel(Model):\n id = columns.Integer(primary_key=True)\n f = columns.Float()\n d = columns.Double()\n\n sync_table(FloatingPointModel)\n\n FloatingPointModel.create(id=0, f=2.39)\n output = FloatingPointModel.objects.first()\n self.assertEqual(2.390000104904175, output.f) # float loses precision\n\n FloatingPointModel.create(id=0, f=3.4028234663852886e+38, d=2.39)\n output = FloatingPointModel.objects.first()\n self.assertEqual(3.4028234663852886e+38, output.f)\n self.assertEqual(2.39, output.d) # double retains precision\n\n FloatingPointModel.create(id=0, d=3.4028234663852886e+38)\n output = FloatingPointModel.objects.first()\n self.assertEqual(3.4028234663852886e+38, output.d)", "def asFloatVector(*args, **kwargs):\n \n pass", "def testFloat(self):\n idx = self.d.GetHeaderNames().index('Float')\n \n query = 'Float == 0.10'\n result, ind = self.d.RunQuery(query)\n self.assertEqual('0.1', result[0][idx])\n \n query = 'Float == 1.0'\n result, ind = self.d.RunQuery(query)\n self.assertEqual('1.0', result[0][idx])\n \n query = 'Float < 0'\n result, ind = self.d.RunQuery(query)\n self.assertEqual('-1.5', result[0][idx])\n \n query = 'Float >= 4.3'\n result, ind = self.d.RunQuery(query)\n floats = []\n for i in range(len(result)):\n floats.append(result[i][idx])\n self.assertEqual(['4.3','7.1'], floats)", "def test_floating_point_data_types(tmp_path):\n test_file = GeneratedFile()\n test_file.add_segment(\n (\"kTocMetaData\", \"kTocRawData\", \"kTocNewObjList\"),\n segment_objects_metadata(\n channel_metadata(\"/'group'/'f32'\", 9, 4),\n channel_metadata(\"/'group'/'f64'\", 10, 4),\n ),\n hexlify_value('<f', 1) +\n hexlify_value('<f', 2) +\n hexlify_value('<f', 3) +\n hexlify_value('<f', 4) +\n hexlify_value('<d', 1) +\n hexlify_value('<d', 2) +\n hexlify_value('<d', 3) +\n hexlify_value('<d', 4)\n )\n\n tdms_data = test_file.load()\n h5_path = tmp_path / 'h5_data_test.h5'\n h5 = tdms_data.as_hdf(h5_path)\n\n for chan, expected_dtype in [\n ('f32', np.dtype('float32')),\n ('f64', np.dtype('float64'))]:\n h5_channel = h5['group'][chan]\n assert h5_channel.dtype == expected_dtype\n np.testing.assert_almost_equal(h5_channel[...], [1.0, 2.0, 3.0, 4.0])\n h5.close()", "def test_float_dtype_behavior(\n data: st.DataObject, dtype, constant, copy: bool, ndmin: int\n):\n\n data_strat = float_data if dtype is None else generic_data\n arr_data = data.draw(data_strat, label=\"arr_data\")\n tensor = mg.Tensor(arr_data, dtype=dtype, constant=constant, copy=copy, ndmin=ndmin)\n\n if constant is None:\n assert tensor.constant is False\n else:\n assert tensor.constant is constant\n\n assert np.issubdtype(tensor.dtype, np.floating)", "def _getFloatInput(self, data_block, plug, is_array=False):\r\n return self._getGenericInput(data_block, plug, float, \"asDouble\", is_array=is_array, array_type=self.FLOAT_LIST_TYPE)", "def record(self, value: typing.Union[float, int]) -> None:" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate and score the results of category elimination.
def validate(source, output, threshold=0.75, headers=True): src = Taxonomy(source) out = Taxonomy(output) def results(success=False, pairs=0, cats=0, supercats=0, merges=0, msg=None): return { "success": success, "pairs": pairs, "cats": cats, "supercats": supercats, "merges": merges, "message": msg} def error(msg): return results(False, 0, 0, 0, 0, msg) def union_find(cats, debug=False): """Return a UnionFind of homogeneous categories""" cats = list(cats) uf = UnionFind(cats) for i in range(0, len(cats)): for j in range(i + 1, len(cats)): artsi = src.cat_arts[cats[i]] artsj = src.cat_arts[cats[j]] if jaccard(artsi, artsj) > threshold: uf.union(cats[i], cats[j]) return uf # 1. Confirm that all articles are present if len(src.arts - out.arts) != 0: return error("Some articles are missing: %s..." % ", ".join(list(src.arts - out.arts)[:10])) # 2. Confirm that no new categories were introduced. if len(out.cats - src.cats) != 0: return error("Categories were introduced") # 3. Confirm that at least one set of possible valid merges contains # all of the articles in each super category. # # You should buckle in. # # Categories in the source but not the output missing = src.cats - out.cats # Possible supercategories: any category whose contents have changed. The # intention is to collect categories with more articles, but by comparing # the complete contents instead of the size we'll also catch categories # whose articles have only been rearranged (which is invalid). grown = [cat for cat in out.cats if src.cat_arts[cat] != out.cat_arts[cat]] # All possible merge operations keyed by supercategory. merges = {} if len(grown) > 0: if len(missing) == 0: return error("Some categories have additional articles, but no " + "categories were removed") # Identify possible merge candidates as categories whose articles are a # subset of the super category. maybe = {} for m in missing: for g in grown: if src.cat_arts[m] < out.cat_arts[g]: maybe.setdefault(g, set()) maybe[g].add(m) for merged in maybe: # {merged: [c1, c2, c3, ...]} # Map possible merge operations in a union-find / disjoint set. # Note: don't forget to include the supercategory! uf = union_find(list(maybe[merged]) + [merged]) # Retrieve a list of all sets with more than one member AND that # contain our suspected super category. sets = uf.sets(unary=False, contains=merged) # Possible merge explanations merges[merged] = [] # Size of the source category bearing the supercategory's label. msize = len(src.cat_arts[merged]) for union in sets: # For each set, consider all possible arrangements of members. # If an arrangement is 1) fully connected in that all members # have a Jaccard index above the threshold and 2) all members # have length equal to or less than the supercategory label, # then the arrangement represents a possible merge. for cats in all_combinations(union): # If the category label is acceptable... if msize >= max([len(src.cat_arts[c]) for c in cats]): # Again, use a union-find to find all connected sets. uf = union_find(cats).sets(unary=False, contains=merged) for union2 in uf: arts = set() for cat in union2: arts = arts | src.cat_arts[cat] # The merge candidate contains exactly the articles # found – we have a contender! if arts == out.cat_arts[merged]: merges[merged].append(cats) # When multiple explanations exist for a supercategory, we needn't # pick one. We just need to know that there was one possible # explanation. if len(merges[merged]) == 0: return error("Not all categories merged into %s are " + "connected by homogeneity OR the category " + "label is wrong" % merged) pairs = src.pairs - out.pairs cats = len(src.cats) - len(out.cats) supercats = len(grown) mergeops = sum([min([len(c) for c in merges[m]]) - 1 for m in merges.keys()]) return results(True, pairs, cats, supercats, mergeops, None)
[ "def test_compare_categories_categorical_variables(self):\n for method in self.cat_methods:\n compare_categories(self.dm1_fp, self.map1_fp, method,\n self.cat_categories, self.num_perms, self.test_dir)\n results_fp = join(self.test_dir, '%s_results.txt' % method)\n self.files_to_remove.append(results_fp)\n results_f = open(results_fp, 'U')\n results = results_f.readlines()\n results_f.close()\n\n # Make sure the files aren't empty.\n self.assertTrue(len(results) > 0)", "def cross_validate(data, k, distance_metric):\n right_classifications = 0\n for point in data:\n datas = data.copy()\n datas.remove(point)\n classification = knn_classify_point(point, datas, k, distance_metric)\n right_classifications += 1*(classification == point.classification)\n return right_classifications/len(data)", "def ci_test(self):\n removed_cols = []\n for col in self.cat_cols:\n print(f\"CI TEST FOR {col}\")\n if self.df[col].count() >= 120:# 130 was chosen because you need at least 30 values per cat and at least 100 values per column. \n ci = continuous_target.mean_confidence_interval(self.df[[col, self.target]])\n if len(ci) > 1:\n maxs = []\n mins = []\n totals = []\n for i in range(len(ci)):\n maxs.append(ci[i][1])\n mins.append(ci[i][0])\n totals.append(ci[i][1] - ci[i][0])\n drop_col = np.array(max(maxs)) - np.array(min(mins)) < sum(totals)\n if drop_col == True:\n self.dropped_cols_stats.update({col:0})\n removed_cols.append(col)\n if mins == maxs:\n self.dropped_cols_stats.update({col:0})\n removed_cols.append(col)\n else:\n removed_cols.append(col)\n self.dropped_cols_stats.update({col:0})\n\n self.df.drop(columns=removed_cols, inplace=True)\n [self.cat_cols.remove(item) for item in removed_cols]", "def delete_empty_categories(self):\n\n to_remove = [\"test\"]\n\n for key in self.category_to_list.keys():\n rows = self.category_to_list[key]\n\n should_remove = True\n\n for row in rows:\n result = row[ToolResult.RESULT]\n\n if result in ('holds', 'violated'):\n \n should_remove = False\n break\n\n if should_remove:\n to_remove.append(key)\n elif key != \"test\":\n ToolResult.all_categories.add(key)\n\n for key in to_remove:\n print(f\"deleting {key} in tool {self.tool_name}\")\n del self.category_to_list[key]\n\n ToolResult.num_categories[self.tool_name] = len(self.category_to_list)", "def test_compare_categories_numeric_variables(self):\n for method in self.num_methods:\n compare_categories(self.dm1_fp, self.map1_fp, method,\n self.num_categories, self.num_perms, self.test_dir)\n results_fp = join(self.test_dir, '%s_results.txt' % method)\n self.files_to_remove.append(results_fp)\n results_f = open(results_fp, 'U')\n results = results_f.readlines()\n results_f.close()\n self.assertTrue(len(results) > 0)", "def automated_data_cleaning(option):\r\n print(\"\\n\"*50)\r\n print(\"\\n A1 Automated Data Cleaning (Option %s):\\n\" % option)\r\n devfile = input(\"\\n Input training filename and path (dev-sample.csv): \")\r\n if devfile ==\"\":\r\n devfile=\"dev-sample.csv\"\r\n df_full= pd.read_csv(devfile)\r\n columns = ['ib_var_2','icn_var_22','ico_var_25','if_var_68','if_var_78','ob_target']\r\n df=df_full[list(columns)]\r\n print(\"\\nINPUT Data Set\")\r\n #df = pd.read_csv(\"dev-sample.csv\")\r\n print(df.head(10))\r\n print(\"\\nNumber of records:\", len(df.index))\r\n print(\"number of variables:\", len(df.columns))\r\n colnames = list(df.columns[0:len(df.columns)])\r\n print(\"columns name:\", colnames)\r\n #print(\"data type:\", dict(df.dtypes))\r\n for k,v in dict(df.dtypes).items():\r\n if v == 'O':\r\n #print(k)\r\n freq = dict(df.groupby(k)[k].count())\r\n sorted_freq = sorted(freq.items(), key=operator.itemgetter(1), reverse=True)\r\n #print(sorted_freq[0][0])\r\n for i in range(0,len(df.index)):\r\n if pd.isnull(df[k][i]):\r\n df[k][i] = sorted_freq[0][0] #Replaced by highest frequency value\r\n \r\n for k,v in dict(df.dtypes).items():\r\n if v != 'object':\r\n for i in range(0,len(df.index)):\r\n if np.isnan(df[k][i]):\r\n df[k][i] = 0\r\n \r\n for k,v in dict(df.dtypes).items():\r\n if v != 'object':\r\n #print(k)\r\n #print(\"mean:\" ,np.average(df[k]))\r\n #print(\"stdev:\" ,np.std(df[k]))\r\n total_pos = 0\r\n total_neg = 0\r\n for i in range(0,len(df.index)):\r\n if (df[k][i] >= 0):\r\n total_pos += 1\r\n if (df[k][i] < 0):\r\n total_neg += 1\r\n #print(\"total positive values:\", total_pos)\r\n #print(\"total negative values:\", total_neg)\r\n negSignMistake = total_neg / len(df.index)\r\n #print(\"percentage of negative values:\", negSignMistake)\r\n for i in range(0,len(df.index)):\r\n if (negSignMistake < 0.05):\r\n if (df[k][i] < 0):\r\n df[k][i] = df[k][i] * -1\r\n upThreshold = np.nanmean(df[k]) + 3 * np.std(df[k])\r\n botThreshold = np.nanmean(df[k]) - 3 * np.std(df[k])\r\n outliers = 0\r\n for i in range(0,len(df.index)):\r\n if (df[k][i] < botThreshold) or (df[k][i] > upThreshold):\r\n #print('outliers:', df[k][i])\r\n outliers =+ 1\r\n #print('outliers value:' ,df[k][i]) \r\n if (df[k][i] > upThreshold):\r\n df[k][i] = upThreshold\r\n if (df[k][i] < botThreshold):\r\n df[k][i] = botThreshold\r\n #print('new value:', df[k][i])\r\n #print(\"total outliers:\", outliers)\r\n #print(df[k][0])\r\n \r\n print(\"\\nOUTPUT Cleaned\")\r\n print(df.head(10))\r\n input(\" \\nPress enter to continue...\")\r\n return \"0\"", "def _get_category(self, text):\n pred = self.nlp(text)\n pred_val = max(pred.cats, key=lambda i: pred.cats[i])\n percent_val = pred.cats[pred_val]\n\n if percent_val >= 0.85:\n accurate = True\n else:\n accurate = False\n\n return pred_val, percent_val, accurate", "def __evaluation(self, data_clean, label):\n from sklearn.model_selection import train_test_split # type: ignore\n try:\n X_train, X_test, y_train, y_test = train_test_split(data_clean, label, test_size=0.4, random_state=0, stratify=label)\n except Exception:\n if self._verbose:\n print(\"cannot stratified sample, try random sample: \")\n X_train, X_test, y_train, y_test = train_test_split(data_clean, label, test_size=0.4, random_state=42)\n\n # remove the nan rows\n mask_train = np.isnan(X_train).any(axis=1) # nan rows index\n mask_test = np.isnan(X_test).any(axis=1)\n num_removed_test = sum(mask_test)\n X_train = X_train[~mask_train]\n y_train = y_train[~mask_train]\n X_test = X_test[~mask_test]\n y_test = y_test[~mask_test]\n\n model = self.model.fit(X_train, y_train.ravel())\n score = self.scorer(model, X_test, y_test) # refer to sklearn scorer: score will be * -1 with the real score value\n if self._verbose:\n print(\"score is: {}\".format(score))\n\n if self._verbose:\n print(\"===========>> max score is: {}\".format(score))\n if (num_removed_test > 0):\n print(\"BUT !!!!!!!!there are {} data (total test size: {})that cannot be predicted!!!!!!\\n\".format(num_removed_test, mask_test.shape[0]))\n return score", "def _get_valid_categories():\n\n return ExpertPicksCategory.objects.filter(expert__isnull=False, expertpickmovie__isnull=False).distinct()", "def Gerrity_score(contingency):\n \n def _Gerrity_S(a):\n \"\"\" Returns Gerrity scoring matrix, S \"\"\"\n\n categories = a.category.values\n K = len(categories)\n\n # Loop over reference categories\n ref_list = []\n for ref_category in categories:\n\n # Loop over comparison categories\n cmp_list = []\n for cmp_category in categories:\n\n i = ref_category\n j = cmp_category\n\n if i == j:\n cmp_list.append((1 / (K - 1)) * ((1 / a.sel(category=range(1,i))).sum(dim='category', skipna=True) + \\\n a.sel(category=range(j,K)).sum(dim='category', skipna=True)))\n elif i > j:\n cmp_list.append((1 / (K - 1)) * ((1 / a.sel(category=range(1,j))).sum(dim='category', skipna=True) - \\\n (i - j) + a.sel(category=range(i,K)).sum(dim='category', skipna=True)))\n else:\n cmp_list.append((1 / (K - 1)) * ((1 / a.sel(category=range(1,i))).sum(dim='category', skipna=True) - \\\n (j - i) + a.sel(category=range(j,K)).sum(dim='category', skipna=True)))\n\n # Concatenate comparison categories -----\n cmp = xr.concat(cmp_list, dim='comparison_category')\n cmp['comparison_category'] = categories\n\n # Add to reference list -----\n ref_list.append(cmp)\n\n # Concatenate reference categories -----\n S = xr.concat(ref_list, dim='reference_category')\n S['reference_category'] = categories\n\n return S\n \n # Compute 'a' -----\n sum_p = (_sum_contingency(contingency, 'reference') / \\\n _sum_contingency(contingency, 'total'))\n a = ((1 - sum_p.cumsum('category', skipna=True)) / sum_p.cumsum('category', skipna=True))\n \n # Compute 'S' -----\n S = _Gerrity_S(a)\n \n return ((contingency * S).sum(dim=('reference_category','comparison_category'), skipna=True) / \\\n _sum_contingency(contingency, 'total')).rename('Gerrity_score')", "def validate(self,X_validate,y_validate,j):\n y_pred = self.classify1(X_validate)\n count = 0\n length = y_pred.shape\n X3 = []\n Y3 = []\n X4 = []\n Y4 = []\n for i in range(0,length[0]):\n if y_pred[i] != y_validate[i]:\n X3.append(X_validate[i])\n Y3.append(y_validate[i])\n count +=1\n #print(j)\n if j != \"lda\" :\n if j!=\"kernel_lda\":\n length = y_pred.shape\n count = 0\n X3 = []\n Y3 = []\n count1 = 0\n count = 0\n for i in range(0,length[0]):\n if y_pred[i] != y_validate[i]:\n X3.append(X_validate[i])\n Y3.append(y_validate[i])\n count +=1\n else:\n X4.append(X_validate[i])\n Y4.append(y_validate[i])\n count1 +=1\n \n #print(Y3)\n\n X3 = np.array(X3)\n #print(X3.shape)\n\n N,H,W, C = count,32,32,3\n X3 = X3.reshape((N,H,W,C))\n\n\n Y3 = np.array(Y3)\n print(\"wrong classified images\")\n plt.imshow(X3[0])\n plt.show()\n plt.imshow(X3[1])\n plt.show()\n \n X4 = np.array(X4)\n #print(X3.shape)\n\n N,H,W, C = count1,32,32,3\n X4 = X4.reshape((N,H,W,C))\n print(\"correct classified images\")\n\n\n Y4 = np.array(Y4)\n plt.imshow(X4[0])\n plt.show()\n plt.imshow(X4[1])\n plt.show()\n \n # plt.imshow(X3[2])\n X3 = []\n Y3 = []\n X4 = []\n Y4 = []\n\n\n \n \n return self.confusion_matrix(y_validate,y_pred),accuracy_score(y_validate,y_pred),f1_score(y_validate,y_pred,average=\"macro\"),count/length[0],precision_score(y_validate,y_pred,average=\"macro\")", "def compute(self):\n\n # Gather up and sort the margins.\n\n dic = {}\n for tup in self.margins.keys():\n val = self.margins.get(tup, 0)\n if (val <= 0):\n continue\n ls = dic.get(val)\n if (not ls):\n dic[val] = [tup]\n else:\n ls.append(tup)\n\n # Create a blank Outcome.\n outcome = Outcome(self)\n\n if (not dic):\n # No information at all! Return the blank Outcome.\n return outcome\n \n # Determine the largest margin.\n maxmargin = max([ val for val in dic.keys() ])\n\n for level in range(maxmargin, 0, -1):\n # Get the list of facts at this margin level.\n ls = dic.get(level)\n if (not ls):\n continue\n \n # Discard any facts that contradict the outcome so far.\n compatls = [ tup for tup in ls if outcome.compatible(*tup) ]\n\n # Try adding all those facts.\n try:\n newout = outcome.clone()\n for tup in compatls:\n newout.accept(*tup)\n # Success! Continue with the next margin level.\n outcome = newout\n continue\n except:\n #print 'WARNING: Contradiction at level', level, '('+str(len(compatls)), 'pairs)'\n pass\n\n # Adding those facts resulted in a contradiction (even though\n # no single fact in the set contradicts the model). We must\n # go through the (hacky) algorithm to decide which facts to\n # discard.\n\n notguilty = []\n \n for avoid in compatls:\n try:\n newout = outcome.clone()\n for tup in compatls:\n if (tup == avoid):\n continue\n newout.accept(*tup)\n except:\n notguilty.append(avoid)\n\n if (len(notguilty) == 0 or len(notguilty) == len(compatls)):\n # If we eliminated all the facts, give up. If we \n # eliminated *no* facts, also give up.\n #print '...all pairs eliminated.'\n continue\n\n #print '...', len(notguilty), ' pairs remain.'\n\n # Once again, try adding all the remaining facts.\n\n try:\n newout = outcome.clone()\n for tup in notguilty:\n newout.accept(*tup)\n outcome = newout\n continue\n except:\n #print 'WARNING: Contradiction at level', level, 'still exists'\n pass\n\n return outcome", "def obtain_rules_discard(df_anomalies_no_sub, df_anomalies_yes_sub, X_train, sc,\n n_vertex_numerical, numerical_cols, categorical_cols,\n clustering_algorithm, use_inverse):\n\n def hyper_limits(vectors_bound_all, df_anomalies_yes_sub, numerical_cols):\n limits = obtain_limits(vectors_bound_all)\n df_anomalies_yes_sub[\"outside_hcube\"] = df_anomalies_yes_sub.apply(\n lambda x: function_check(x, limits, numerical_cols), axis=1)\n return df_anomalies_yes_sub, limits\n\n if clustering_algorithm == \"kprototypes\":\n feature_cols = numerical_cols + categorical_cols\n else:\n feature_cols = numerical_cols\n\n # Tolerance param\n max_iters = MAX_ITERS\n\n # Obtain vertices\n n = 0\n check = True\n\n # Drop duplicates\n df_anomalies_no_sub.drop_duplicates(inplace=True)\n df_anomalies_yes_sub.drop_duplicates(inplace=True)\n df_final = []\n \n # Ñapa: duplicate datapoints if below 2\n if len(df_anomalies_no_sub)<2:\n df_anomalies_no_sub = df_anomalies_no_sub.append(df_anomalies_no_sub)\n df_anomalies_no_sub = df_anomalies_no_sub.reset_index(drop=True)\n \n if len(df_anomalies_yes_sub)<2:\n df_anomalies_yes_sub = df_anomalies_yes_sub.append(df_anomalies_no_sub)\n df_anomalies_yes_sub = df_anomalies_yes_sub.reset_index(drop=True)\n \n # Data used -- start using all and 1 cluster\n dct_subdata = {\"data\": df_anomalies_no_sub, \"n_clusters\": 1}\n list_subdata = [dct_subdata]\n\n # Check until all non anomalous data is used for rule inferring\n j = 0\n while check:\n # When there is no data to infer rules, finish\n if len(list_subdata) == 0:\n break\n list_original = list_subdata.copy()\n list_subdata = [] # Reset list\n # For each subdata space, use two clusters to try and infer rules\n for dct_subdata in list_original:\n # Load data\n df_anomaly_no = dct_subdata['data']\n n = dct_subdata['n_clusters']\n j += 1\n\n # Check tolerance\n if j >= max_iters:\n check=False\n break\n # If there is only one point left, skip it\n elif n > len(df_anomaly_no):\n continue\n\n # Rules\n print(\"Iteration {0} | nº clusters used {1}\".format(j, n))\n # Returns n_vertex_numerical datapoints\n # if n_vertex_numerical > len(df_anomalies_no) for each cluster;\n # else returns df_anomalies_no\n dict_vectors_bound_all = obtain_vertices(\n df_anomaly_no,\n X_train,\n sc,\n n_vertex_numerical,\n numerical_cols,\n categorical_cols,\n clustering_algorithm,\n n_clusters=n)\n\n # For each cluster in that subdata\n for key, value in dict_vectors_bound_all.items():\n vectors_bound_all = value[0].copy()\n df_anomalies_yes_sub, limits = hyper_limits(\n vectors_bound_all, df_anomalies_yes_sub, feature_cols)\n list_check = list(\n df_anomalies_yes_sub[\"outside_hcube\"].unique())\n\n # Recover original indexes\n df_anomaly_iter = value[2]\n df_aux = df_anomaly_no.copy().reset_index()\n cols_merge = [\n column for column in list(df_anomaly_iter.columns)\n if column != \"distances\"\n ]\n df_anomaly_iter = df_anomaly_iter[cols_merge]\n df_anomaly_iter = df_anomaly_iter.merge(\n df_aux,\n how=\"left\",\n left_on=cols_merge,\n right_on=cols_merge)\n df_anomaly_iter.index = df_anomaly_iter['index']\n del df_anomaly_iter['index']\n\n # If there are points that belong to the other class,\n # retrain with one more cluster\n if False in list_check:\n dct_subdata = {'data': df_anomaly_iter, 'n_clusters': 2}\n list_subdata.append(dct_subdata)\n # When there are no points from the other class,\n # turn into rules (and do not use those points again)\n elif len(df_anomaly_no)==1.:\n df_final.append(limits)\n else:\n df_final.append(limits)\n\n return df_final", "def run_validate(X,y,cvtype):\n numsubs=X.shape[2]\n X=np.reshape(X,[-1,numsubs])\n\n \n if cvtype == 'LOO':\n behav_pred_pos=np.zeros([numsubs])\n behav_pred_neg=np.zeros([numsubs])\n for loo in range(0,numsubs):\n\n print(\"Running LOO, sub no:\",loo)\n \n train_mats=np.delete(X,[loo],axis=1)\n train_pheno=np.delete(pheno,[loo],axis=0)\n \n test_mat=X[:,loo]\n test_pheno=y[loo]\n\n pos_fit,neg_fit,posedges,negedges=train_cpm(train_mats,train_pheno)\n\n pe=np.sum(test_mat[posedges.flatten().astype(bool)])/2\n ne=np.sum(test_mat[negedges.flatten().astype(bool)])/2\n\n if len(pos_fit) > 0:\n behav_pred_pos[loo]=pos_fit[0]*pe + pos_fit[1]\n else:\n behav_pred_pos[loo]='nan'\n\n if len(neg_fit) > 0:\n behav_pred_neg[loo]=neg_fit[0]*ne + neg_fit[1]\n else:\n behav_pred_neg[loo]='nan'\n\n \n Rpos=stats.pearsonr(behav_pred_pos,pheno)[0]\n Rneg=stats.pearsonr(behav_pred_neg,pheno)[0]\n\n return Rpos,Rneg\n\n\n elif cvtype == '5k':\n bp,bn,ba=kfold_cpm(X,y,5)\n\n\n\n ccp=np.array([stats.pearsonr(bp[i,:],ba[i,:]) for i in range(0,5)])\n Rpos_mean=ccp.mean(axis=0)[0]\n\n ccn=np.array([stats.pearsonr(bn[i,:],ba[i,:]) for i in range(0,5)])\n Rneg_mean=ccn.mean(axis=0)[0]\n\n\n\n elif cvtype == '10k':\n bp,bn,ba=kfold_cpm(X,y,10)\n\n\n ccp=np.array([stats.pearsonr(bp[i,:],ba[i,:]) for i in range(0,10)])\n Rpos_mean=ccp.mean(axis=0)[0]\n\n ccn=np.array([stats.pearsonr(bn[i,:],ba[i,:]) for i in range(0,10)])\n Rneg_mean=ccn.mean(axis=0)[0]\n\n\n\n elif cvtype == 'splithalf':\n bp,bn,ba=kfold_cpm(X,y,2)\n\n ccp=np.array([stats.pearsonr(bp[i,:],ba[i,:]) for i in range(0,2)])\n Rpos_mean=ccp.mean(axis=0)[0]\n\n ccn=np.array([stats.pearsonr(bn[i,:],ba[i,:]) for i in range(0,2)])\n Rneg_mean=ccn.mean(axis=0)[0]\n\n\n else:\n raise Exception('cvtype must be LOO, 5k, 10k, or splithalf')\n\n\n return Rpos_mean,Rneg_mean", "def untrain(self, category, text):\n try:\n bayes_category = self.categories.get_category(category)\n except KeyError:\n return\n\n tokens = self.tokenizer(str(text))\n occurance_counts = self.count_token_occurrences(tokens)\n\n for word, count in occurance_counts.items():\n bayes_category.untrain_token(word, count)\n\n # Updating our per-category overall probabilities\n self.calculate_category_probability()", "def confirmClassifiersInSet(self):\r\n \r\n borrados = 0\r\n \tfor cl in self.clSet[:]:\r\n \t if cl.getNumerosity()==0:\r\n \t self.clSet.remove(cl)\r\n \t borrados = borrados + 1\r\n else:\r\n self.numerositySum = self.numerositySum + cl.getNumerosity()", "def validate(self,X_validate,y_validate):\n y_pred = self.classify1(X_validate)\n \n length = y_pred.shape\n count = 0\n for i in range(0,length[0]):\n if y_pred[i] != y_validate[i]:\n count +=1\n \n\n\n \n \n return self.confusion_matrix(y_validate,y_pred),accuracy_score(y_validate,y_pred),f1_score(y_validate,y_pred,average=\"macro\"),count/length[0]", "def validate_pruning(data_array, fold_size):\r\n\r\n # This is a nested x-fold of the validate function.\r\n # Count the labels\r\n labels = np.unique(data_array[:, data_array.shape[1]-1])\r\n # Initialize variables\r\n total_confusion_matrix = np.zeros((len(labels), len(labels)))\r\n total_depth = 0\r\n total_pruned_matrix = np.zeros((len(labels), len(labels)))\r\n total_pruned_depth = 0\r\n print_counter = 1\r\n for fold in range(fold_size):\r\n # Prints for visualisation purposes\r\n print(f\"Validating training set {print_counter}/{fold_size} \", end=\"\", flush=True)\r\n # Divide data into test data and the rest\r\n training_visualisation_data, test_data = divide_dataset(data_array, fold_size, fold)\r\n # Initialize variables for current training set\r\n confusion_matrix = np.zeros((len(labels), len(labels)))\r\n training_depth = 0\r\n pruned_matrix = np.zeros((len(labels), len(labels)))\r\n pruned_depth = 0\r\n for validation_fold in range(fold_size-1):\r\n # Prints for visualisation purposes\r\n print(\".\", end=\"\", flush=True)\r\n # Further divide data into training and validation data\r\n training_data, validation_data = divide_dataset(training_visualisation_data, fold_size-1, validation_fold)\r\n # train and test tree\r\n tree, depth = dt.decision_tree_learning(training_data)\r\n predicted_values, true_values = dt.classify_array(test_data, tree)\r\n # prune and test tree\r\n tree = dt.prune(tree, validation_data)\r\n new_depth = dt.get_depth(tree)\r\n # Append confusion matrices and depth of both trees\r\n predicted_pruned_values, true_pruned_values = dt.classify_array(test_data, tree)\r\n confusion_matrix += dt.get_confusion_matrix(predicted_values, true_values)\r\n training_depth += depth\r\n pruned_matrix += dt.get_confusion_matrix(predicted_pruned_values, true_pruned_values)\r\n pruned_depth += new_depth\r\n # Append the averages of confusion matrices and depths of all validation folds\r\n total_confusion_matrix += confusion_matrix/(fold_size-1)\r\n total_depth += training_depth/(fold_size-1)\r\n total_pruned_matrix += pruned_matrix/(fold_size-1)\r\n total_pruned_depth += pruned_depth/(fold_size-1)\r\n print_counter+=1\r\n print(\"\")\r\n # Average matrices and depths of all training folds\r\n average_confusion_matrix = total_confusion_matrix/fold_size\r\n average_depth = total_depth/fold_size\r\n average_pruned_matrix = total_pruned_matrix/fold_size\r\n average_pruned_depth = total_pruned_depth/fold_size\r\n\r\n return average_confusion_matrix, average_depth, average_pruned_matrix, average_pruned_depth", "def load_categories(self):\n self.cats = {}\n categories = ['PTS', 'FGM', 'FGA', 'FG%', 'FTM', 'FTA','FT%', \\\n '3PM', '3PA', 'REB', 'AST', 'A/TO', 'STL', 'BLK', 'TO']\n print \"Please asign point values to each category\"\n for cat in categories:\n while True:\n value = raw_input(\"{0} value? \".format(cat))\n if value in ['-2', '-1', '0', '1', '2', '']:\n break\n print \"Invalid Entry. Value must be in range of -2 to 2\"\n self.cats[cat] = 0 if value == \"\" else int(value)\n points = {k: v for (k, v) in self.cats.iteritems() if v is not 0}\n sure = raw_input(\"\\n{0} \\n\\nCorrect? y/n\\n\".format(points))\n if sure in ['n', 'N', 'no', 'No']:\n self.load_categories()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a UnionFind of homogeneous categories
def union_find(cats, debug=False): cats = list(cats) uf = UnionFind(cats) for i in range(0, len(cats)): for j in range(i + 1, len(cats)): artsi = src.cat_arts[cats[i]] artsj = src.cat_arts[cats[j]] if jaccard(artsi, artsj) > threshold: uf.union(cats[i], cats[j]) return uf
[ "def get_setunion(tree):\n class Visitor(L.NodeVisitor):\n def process(self, tree):\n self.parts = []\n super().process(tree)\n return self.parts\n \n def generic_visit(self, node):\n # Don't recurse. Only traverse BinOps of BitOrs.\n self.parts.append(node)\n \n def visit_BinOp(self, node):\n if isinstance(node.op, L.BitOr):\n self.visit(node.left)\n self.visit(node.right)\n else:\n self.parts.append(node)\n return Visitor.run(tree)", "def test_infer_category(query):\n graph = Graph()\n graph.parse(os.path.join(RESOURCE_DIR, \"goslim_generic.owl\"))\n [c] = infer_category(query[0], graph)\n assert c == query[1]", "def search_by_category(cls,category):\n image_categories = cls.objects.filter(category=category)\n return image_categories", "def get_all_unions(text):\n return get_all_composite_types(text, 'union')", "def Union(self, *args):\n return _snap.TUnionFind_Union(self, *args)", "def get_category(s):\n\n list_of_cat = ['food', 'clothings', 'gas', 'groceries', 'medical']\n possible_mapping = {'food':{'mcdonalds','orange'}, 'clothings':{'shirts','pants','skirts', 'dress'}}\n pass", "def non_associates(category):\n others = set.union(*[associates[cat] for cat in categories - {category}])\n return others - associates[category]", "def filter_food(selected_ethnic,selected_category):\n if not selected_category.exists() and not selected_ethnic.exists():\n return Food.objects.all()\n elif not selected_category.exists() or not selected_ethnic.exists():\n return Food.objects.filter(Q(ethnic_food_name__in=selected_ethnic) | Q(category__in=selected_category)).distinct()\n return Food.objects.filter(ethnic_food_name__in=selected_ethnic).filter(category__in=selected_category).distinct()", "def get_objs_with_tag(self, key=None, category=None, model=\"objects.objectdb\", tagtype=None):\r\n objclass = ContentType.objects.get_by_natural_key(*model.split(\".\", 1)).model_class()\r\n key_cands = Q(db_tags__db_key__iexact=key.lower().strip()) if key is not None else Q()\r\n cat_cands = Q(db_tags__db_category__iexact=category.lower().strip()) if category is not None else Q()\r\n tag_crit = Q(db_tags__db_model=model, db_tags__db_tagtype=tagtype)\r\n return objclass.objects.filter(tag_crit & key_cands & cat_cands)", "def filter_by_category(data: dict, category: str, match_category: Callable[[Iterable], bool] = any) -> dict:\n\n filtered_data = data | {\"places\": []}\n\n for place in data[\"places\"]:\n if match_category(cat in place[\"category\"] for cat in category):\n filtered_data[\"places\"].append(place)\n\n return filtered_data", "def union(kb_list):\n l = [k.facts for k in kb_list]\n k = KnowledgeBase(None, kb_list[0].entity_map, kb_list[0].relation_map)\n k.facts = np.concatenate(l, axis=0)\n logging.info(\"Created a union of {0} kbs. Total facts in union = {1}\\n\".format(len(kb_list), len(k.facts)))\n return k", "def getCatSet(self, word):\n cs = set()\n for c in self.catDict:\n if word in self.catDict[c][1]:\n if c not in cs:\n cs.add(c)\n return cs", "def filterParents(categories):\n return categories", "def _compute_category_sets() -> dict:\n category_sets = {}\n for cat in cat_store.get_usable_cats():\n children = {c for c in cat_store.get_children(cat) if cat_store.is_usable(c)}\n children_docs = {c: _remove_by_phrase(cat_nlp.parse_category(c)) for c in children}\n child_sets = _find_child_sets(cat, children_docs)\n if child_sets:\n category_sets[cat] = child_sets\n return category_sets", "def disjoint_union(G,H):\n R1=nx.convert_node_labels_to_integers(G)\n R2=nx.convert_node_labels_to_integers(H,first_label=len(R1))\n R=union(R1,R2)\n R.name=\"disjoint_union( %s, %s )\"%(G.name,H.name)\n return R", "def union(self, x, y):\n self._link(self.find_set(x), self.find_set(y))", "def parse_coco_categories(categories):\n cat_map = {c[\"id\"]: c for c in categories}\n\n classes = []\n supercategory_map = {}\n for cat_id in range(max(cat_map) + 1):\n category = cat_map.get(cat_id, None)\n try:\n name = category[\"name\"]\n except:\n name = str(cat_id)\n\n classes.append(name)\n if category is not None:\n supercategory_map[name] = category\n\n return classes, supercategory_map", "def branches(self, **kwargs):\r\n return [r.thesclass() for r in self.filtered_results(**kwargs)]", "def filter_by_category(contributions, categories):\n filtered_contributions = []\n for contribution in contributions:\n if contribution[\"json_metadata\"][\"type\"] in categories:\n filtered_contributions.append(contribution)\n return filtered_contributions" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a metering message for the counter and publish it.
def _publish_counter(self, counter): ctxt = context.get_admin_context() publish.publish_counter(ctxt, counter)
[ "def _create_meter(self, **kwargs):\n name = self._generate_random_name()\n samples = self.clients(\"ceilometer\").samples.create(\n counter_name=name, **kwargs)\n return samples[0]", "def meter(self, name, count):\n self.calls.append((\"meter\", name, count))", "def messageGenerator(self):\n sum = self.getMeasurementSum()\n message = self.generateMessage(sum)\n return message", "def write(self, message):\n self.count += 1", "def send_metric(s):\n pass", "def _create_prometheus_metric(prom_metric_name):\n if not prom_metrics.get(prom_metric_name):\n labels = [settings.TOPIC_LABEL]\n if settings.MQTT_EXPOSE_CLIENT_ID:\n labels.append(\"client_id\")\n\n prom_metrics[prom_metric_name] = Gauge(\n prom_metric_name, \"metric generated from MQTT message.\", labels\n )\n LOG.info(\"creating prometheus metric: %s\", prom_metric_name)", "def _publish_stats(self, counter_prefix, stats, instance):\n for stat_name, stat_value in ceph.flatten_dictionary(\n stats,\n prefix=counter_prefix,\n ):\n self.publish_gauge(stat_name, stat_value, instance=instance)", "def _publish_message(self, stats):\n LOGGER.info('Sending daily message digest at %s', self._current_time)\n\n sns_client = boto3.resource('sns').Topic(self._topic_arn)\n\n subject = 'Alert statistics for {} staged rule(s) [{} UTC]'.format(\n len(stats),\n self._current_time\n )\n\n sns_client.publish(\n Message=self._format_digest(stats),\n Subject=subject\n )", "def publish_create_metric_response(self, metric_info, metric_status):\n topic = 'metric_response'\n msg_key = 'create_metric_response'\n response_msg = {\"schema_version\":1.0,\n \"schema_type\":\"create_metric_response\",\n \"correlation_id\":metric_info['correlation_id'],\n \"metric_create_response\":\n {\n \"metric_uuid\":0,\n \"resource_uuid\":metric_info['metric_create']['resource_uuid'],\n \"status\":metric_status\n }\n }\n self.logger.info(\"Publishing response:\\nTopic={}\\nKey={}\\nValue={}\"\\\n .format(topic, msg_key, response_msg))\n #Core producer\n self.producer_metrics.publish(key=msg_key, value=json.dumps(response_msg), topic=topic)", "def _make_limit_message_counter(self):\n limit_counter_key = \"limit:{}:{}\".format(\n self.traptor_type, self.traptor_id\n )\n collection_window = int(os.getenv('LIMIT_COUNT_COLLECTION_WINDOW', 900))\n\n self.limit_counter = TraptorLimitCounter(\n key=limit_counter_key,\n window=collection_window\n )\n self.limit_counter.setup(redis_conn=self.redis_conn)", "def create_counter(self, metric_name: str, tags: dict = None, init_values: dict = None, reset: bool = True, help: str = None, unit: str = None, dynamic_tags: bool = False):\n\t\tif dynamic_tags:\n\t\t\tm = CounterWithDynamicTags(init_values=init_values)\n\t\telse:\n\t\t\tm = Counter(init_values=init_values)\n\t\tself._add_metric(m, metric_name, tags=tags, reset=reset, help=help, unit=unit)\n\t\treturn m", "def text_report(number, message):\n\tfrom twilio.rest import Client\n\taccountSID = 'yourAccountSID'\n\tauthToken = 'yourAuthToken'\n\ttwilioCli = Client(accountSID, authToken)\n\tmyTwilioNumber = '+14955551234'\n\tmsg = twilioCli.messages.create(body=message, from_=myTwilioNumber, to=number)", "def sending_gauge_msg(self,g_msg):\n Publisher.sendMessage('update_gauge', gauge_msg=g_msg)", "def send_metrics(self) -> None:\n\t\tself.get_cpu_metrics()\n\t\tself.get_memory_metrics()\n\t\tmessage = {\n\t\t\t'type': 'log',\n\t\t\t'content': {\n\t\t\t\t'mac_id': self.mac_id,\n\t\t\t\t'producer_id': self.client_id,\n\t\t\t\t'cpu_metrics': self.cpu_percentages,\n\t\t\t\t'memory_metrics': self.memory_percentages\n\t\t\t}\n\t\t}\n\t\tself.producer.send(self.kafka_topic, json.dumps(message).encode(\"utf-8\"))\n\t\tself.producer.flush()", "def parse_meter_message(message):\n session = DBSession()\n meter = findMeter(message)\n # compressed primary logs\n if re.match(\"^\\(l.*\\)$\", message.text):\n inflatedlogs = compactsms.inflatelogs([message.text])\n for log in inflatedlogs:\n m = reduce_message(parse_qs(log))\n circuit = findCircuit(m, meter)\n meter_funcs.make_pp(m, circuit, session)\n # old messages\n elif re.match(\"(\\w+) online\", message.text.lower()):\n meter_funcs.make_meter_online_alert(message, meter, session)\n elif re.match(\"^\\(.*\\)$\", message.text.lower()):\n if message.text.startswith('(pcu'):\n make_pcu_logs(message, meter, session)\n else:\n messageDict = clean_message(message)\n if messageDict[\"job\"] == \"delete\":\n getattr(meter_funcs, \"make_\" + messageDict[\"job\"])(messageDict, session)\n else:\n circuit = findCircuit(messageDict, meter)\n if circuit: # double check that we have a circuit\n if messageDict['job'] == \"pp\":\n getattr(meter_funcs, \"make_\" + messageDict[\"job\"])(messageDict, circuit, session)\n elif messageDict['job'] == \"alert\":\n if messageDict['alert'] == 'online':\n meter_funcs.make_meter_online_alert(message, meter, session)\n else:\n getattr(meter_funcs, \"make_\" + messageDict[\"alert\"])(messageDict, circuit, session)\n else:\n session.add(SystemLog(\n 'Unable to parse message %s' % message.uuid))", "def _publish(self, name, value, path, host, timestamp):\n if self.config['metrics_whitelist']:\n if not self.config['metrics_whitelist'].match(name):\n return\n elif self.config['metrics_blacklist']:\n if self.config['metrics_blacklist'].match(name):\n return\n ttl = float(self.config['interval']) * float(self.config['ttl_multiplier'])\n metric = Metric(path, value, timestamp=timestamp, host=host, metric_type='GAUGE', ttl=ttl)\n self.publish_metric(metric)", "def send(self, *args, **kwargs):\n self.send_count += 1\n super(CounterSession, self).send(*args, **kwargs)", "def MessageHandlerMethod(**kwargs):\n data: dict = kwargs['data']\n bus: AbstractPikaBus = kwargs['bus']\n payload: dict = kwargs['payload']\n print(payload)\n if 'count' in payload:\n payload['count'] += 1\n # bus.Publish(payload, topic='myTopic')", "def put_meter(self, meters, **kwargs):\n raise NotImplementedError" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables mediasite catalog downloads using provided catalog ID
def enable_catalog_downloads(self, catalog_id): logging.info("Enabling catalog downloads for catalog: '"+catalog_id) #prepare patch data to be sent to mediasite patch_data = {"AllowPresentationDownload":"True"} #make the mediasite request using the catalog id and the patch data found above to enable downloads result = self.mediasite.api_client.request("patch", "Catalogs('"+catalog_id+"')/Settings", "", patch_data) if self.mediasite.experienced_request_errors(result): return result else: return result
[ "def disable_catalog_allow_links(self, catalog_id):\r\n\r\n logging.info(\"Disabling catalog links for catalog: '\"+catalog_id)\r\n\r\n #prepare patch data to be sent to mediasite\r\n patch_data = {\"AllowCatalogLinks\":\"False\"}\r\n\r\n #make the mediasite request using the catalog id and the patch data found above to enable downloads\r\n result = self.mediasite.api_client.request(\"patch\", \"Catalogs('\"+catalog_id+\"')/Settings\", \"\", patch_data)\r\n \r\n if self.mediasite.experienced_request_errors(result):\r\n return result\r\n else:\r\n return result", "def add_module_to_catalog(self, catalog_id, module_guid):\r\n\r\n logging.info(\"Associating catalog: \"+catalog_id+\" to module: \"+module_guid)\r\n\r\n #prepare patch data to be sent to mediasite\r\n post_data = {\"MediasiteId\":catalog_id}\r\n\r\n #make the mediasite request using the catalog id and the patch data found above to enable downloads\r\n result = self.mediasite.api_client.request(\"post\", \"Modules('\"+module_guid+\"')/AddAssociation\", \"\", post_data)\r\n\r\n if self.mediasite.experienced_request_errors(result):\r\n return result\r\n else:\r\n return result", "def download_on():\n mw.note_download_action.setEnabled(True)\n mw.side_download_action.setEnabled(True)\n mw.manual_download_action.setEnabled(True)", "def media_download(insert_id):\r\n if cfg['media_download_instantly'] == 1:\r\n try:\r\n fnull = open(os.devnull, 'w')\r\n subprocess.Popen([\"python\", \"TweetPinnaImageDownloader.py\",\r\n sys.argv[1], str(insert_id)],\r\n shell=False, stdout=fnull,\r\n stderr=subprocess.STDOUT)\r\n except Exception as e:\r\n log.log_add(4, 'Could not instantly download media files ({})'.\r\n format(e))", "def apicatalog_enable(self, apicatalog_enable):\n\n self._apicatalog_enable = apicatalog_enable", "def download(self):\n url = 'https://github.com/drphilmarshall/OM10/raw/master/data/qso_mock.fits'\n self.catalog = url.split('/')[-1]\n if self.vb: print('OM10: Looking for local catalog {:s}'.format(self.catalog))\n if not os.path.isfile(self.catalog):\n urllib.request.urlretrieve(url, self.catalog)\n if self.vb: print('OM10: Downloaded catalog: {:s}'.format(self.catalog))\n else:\n if self.vb: print('OM10: File already exists, no need to download.')\n return", "def download_show(self, url):", "def is_catalog_id(id: str) -> bool:\n return True if [x for x, y in CATALOG_REGEXES if y.match(id)] else False", "def Download(id, filename):\n # Cleanup temp dir, we recomend you download/unzip your subs in temp folder and\n # pass that to XBMC to copy and activate\n if os.path.isdir(_temp):shutil.rmtree(_temp)\n xbmcvfs.mkdirs(_temp)\n if not os.path.isdir(_temp):xbmcvfs.mkdir(_temp)\n unpacked = str(uuid.uuid4())\n unpacked = unpacked.replace(\"-\",\"\")\n unpacked = unpacked[0:6]\n xbmcvfs.mkdirs(_temp + \"/\" + unpacked)\n _newtemp = xbmc.translatePath(os.path.join(_temp, unpacked)).decode(\"utf-8\")\n\n subtitles_list = []\n username = _addon.getSetting( 'LDuser' )\n password = _addon.getSetting( 'LDpass' )\n login_postdata = urllib.urlencode({'username' : username, 'password' : password, 'login' : 'Login', 'sid' : ''})\n cj = cookielib.CookieJar()\n my_opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))\n my_opener.addheaders = [('Referer', main_url + 'modules.php?name=Your_Account')]\n urllib2.install_opener(my_opener)\n request = urllib2.Request(main_url + 'forum/ucp.php?mode=login', login_postdata)\n response = urllib2.urlopen(request).read()\n content = my_opener.open(main_url + 'modules.php?name=Downloads&d_op=getit&lid=' + id + '&username=' + username)\n content = content.read()\n #### If user is not registered or User\\Pass is misspelled it will generate an error message and break the script execution!\n if 'Apenas Disponvel para utilizadores registados.' in content.decode('utf8', 'ignore'):\n xbmcplugin.endOfDirectory(int(sys.argv[1]))\n xbmc.executebuiltin(('Notification(%s,%s,%d)' % (_scriptname , _language(32019).encode('utf8'),5000)))\n if content is not None:\n header = content[:4]\n if header == 'Rar!':\n local_tmp_file = pjoin(_newtemp, str(uuid.uuid4())+\".rar\")\n packed = True\n elif header == 'PK\u0003\u0004':\n local_tmp_file = pjoin(_newtemp, str(uuid.uuid4())+\".zip\")\n packed = True\n else:\n # never found/downloaded an unpacked subtitles file, but just to be sure ...\n # assume unpacked sub file is an '.srt'\n local_tmp_file = pjoin(_newtemp, \"ldivx.srt\")\n subs_file = local_tmp_file\n packed = False\n log(u\"Saving subtitles to '%s'\" % (local_tmp_file,))\n try:\n with open(local_tmp_file, \"wb\") as local_file_handle:\n\n local_file_handle.write(content)\n local_file_handle.close()\n xbmc.sleep(500)\n except: log(u\"Failed to save subtitles to '%s'\" % (local_tmp_file,))\n if packed:\n xbmc.executebuiltin(\"XBMC.Extract(%s, %s)\" % (local_tmp_file.encode(\"utf-8\"), _newtemp))\n xbmc.sleep(1000)\n\n ## IF EXTRACTION FAILS, WHICH HAPPENS SOMETIMES ... BUG?? ... WE WILL BROWSE THE RAR FILE FOR MANUAL EXTRACTION ##\n searchsubs = recursive_glob(_newtemp, SUB_EXTS)\n searchsubscount = len(searchsubs)\n if searchsubscount == 0:\n dialog = xbmcgui.Dialog()\n subs_file = dialog.browse(1, _language(32024).encode('utf8'), 'files', '.srt|.sub|.aas|.ssa|.smi|.txt', False, True, _newtemp+'/').decode('utf-8')\n subtitles_list.append(subs_file)\n ## ELSE WE WILL GO WITH THE NORMAL PROCEDURE ##\n else:\n log(u\"Unpacked files in '%s'\" % (_newtemp,))\n os.remove(local_tmp_file)\n searchsubs = recursive_glob(_newtemp, SUB_EXTS)\n searchsubscount = len(searchsubs)\n log(u\"count: '%s'\" % (searchsubscount,))\n for file in searchsubs:\n # There could be more subtitle files in _temp, so make\n # sure we get the newly created subtitle file\n if searchsubscount == 1:\n # unpacked file is a newly created subtitle file\n log(u\"Unpacked subtitles file '%s'\" % (file.decode('utf-8'),))\n try: subs_file = pjoin(_newtemp, file.decode(\"utf-8\"))\n except: subs_file = pjoin(_newtemp, file.decode(\"latin1\"))\n subtitles_list.append(subs_file)\n break\n else:\n # If there are more than one subtitle in the temp dir, launch a browse dialog\n # so user can choose. If only one subtitle is found, parse it to the addon.\n\n dirs = os.walk(os.path.join(_newtemp,'.')).next()[1]\n dircount = len(dirs)\n if dircount == 0:\n filelist = os.listdir(_newtemp)\n for subfile in filelist:\n shutil.move(os.path.join(_newtemp, subfile), _temp+'/')\n os.rmdir(_newtemp)\n dialog = xbmcgui.Dialog()\n subs_file = dialog.browse(1, _language(32024).encode('utf8'), 'files', '.srt|.sub|.aas|.ssa|.smi|.txt', False, False, _temp+'/').decode(\"utf-8\")\n subtitles_list.append(subs_file)\n break\n else:\n for dir in dirs:\n shutil.move(os.path.join(_newtemp, dir), _temp+'/')\n os.rmdir(_newtemp)\n dialog = xbmcgui.Dialog()\n subs_file = dialog.browse(1, _language(32024).encode('utf8'), 'files', '.srt|.sub|.aas|.ssa|.smi|.txt', False, False, _temp+'/').decode(\"utf-8\")\n subtitles_list.append(subs_file)\n break\n else: subtitles_list.append(subs_file)\n return subtitles_list", "def when_the_apps_page_loads_open_manage_catalogs(driver):\n assert wait_on_element(driver, 10, '//div[contains(text(),\"Manage Catalogs\")]', 'clickable')\n driver.find_element_by_xpath('//div[contains(text(),\"Manage Catalogs\")]').click()\n assert wait_on_element(driver, 7, '//div[contains(.,\"Manage Catalogs\")]')", "def download(request, id):\n try: \n the_file = File.objects.get(pk=id)\n except:\n return HttpResponse(status=400)\n\n response = HttpResponse(settings.MEDIA_URL + the_file.file.name, status=200)\n response['Content-Disposition'] = f'attachment; filename={the_file.full_name}'\n\n the_file.inc_download()\n return response", "def setLicenseUrl(license):", "def enable_downloading(self, filenames, images, path, library):\n self._filenames = filenames\n self._images = images\n self._path = path\n self._library = library\n\n self._download_capable = True", "def fetch_product(identifier):", "def list_videos(show_id, section_id):\n\n # Get show sections\n if show_id in SHOW_SECTIONS:\n sections = SHOW_SECTIONS[show_id]\n else:\n SHOW_SECTIONS[show_id] = content.get_show_sections(SHOWS_BY_ID[show_id])\n sections = SHOW_SECTIONS[show_id]\n\n section = sections[section_id]\n\n # Set plugin category. It is displayed in some skins as the name of the current section.\n xbmcplugin.setPluginCategory(_handle, section['title'])\n # Set plugin content. It allows Kodi to select appropriate views for this type of content.\n xbmcplugin.setContent(_handle, 'videos')\n\n videos = section['items']\n # Iterate through videos.\n for key, video in videos.items():\n # Create a list item with a text label and a thumbnail image.\n list_item = xbmcgui.ListItem(label=video['title'])\n # Set additional info for the list item.\n list_item.setInfo('video', {'title': video['title']})\n # Set graphics (thumbnail, fanart, banner, poster, landscape etc.) for the list item.\n img_back = video['image-background']\n img_land = img_back\n if 'image-landscape' in video:\n img_land = video['image-landscape']\n list_item.setArt({'thumb': img_back,\n 'landscape': img_land,\n 'icon': img_back,\n 'fanart': img_back})\n # Set 'IsPlayable' property to 'true'.\n # This is mandatory for playable items!\n list_item.setProperty('IsPlayable', 'true')\n # Create a URL for a plugin recursive call.\n # Example: plugin://plugin.video.example/?action=play&video=http://www.vidsplay.com/wp-content/uploads/2017/04/crab.mp4\n url = get_url(action='play', video=video['id'])\n # Add the list item to a virtual Kodi folder.\n # is_folder = False means that this item won't open any sub-list.\n is_folder = False\n # Add our item to the Kodi virtual folder listing.\n xbmcplugin.addDirectoryItem(_handle, url, list_item, is_folder)\n # Add a sort method for the virtual folder items (alphabetically, ignore articles)\n xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)\n # Finish creating a virtual folder.\n xbmcplugin.endOfDirectory(_handle)", "def deriva_modify(servername, catalog_id, acls=None):\n catalog_id = str(int(catalog_id))\n # Format credentials in DerivaServer-expected format\n creds = {\n \"bearer-token\": get_deriva_token()\n }\n # Get the catalog model object to modify\n server = DerivaServer(\"https\", servername, creds)\n catalog = server.connect_ermrest(catalog_id)\n cat_model = catalog.getCatalogModel()\n\n # If modifying ACL, set ACL\n if acls:\n # Ensure catalog owner still in ACLs - DERIVA forbids otherwise\n acls['owner'] = list(set(acls['owner']).union(cat_model.acls['owner']))\n # Apply acls\n cat_model.acls.update(acls)\n\n # Submit changes to server\n cat_model.apply()\n\n return {\n \"success\": True\n }", "def download_track(self, id, artist, track):\n url = self.get_download_url(id)\n if self.download_dir:\n filename = \"{}\\{} - {}.mp3\".format(self.download_dir, artist, track)\n data = requests.get(url)\n with open(filename, 'wb') as f:\n f.write(data.content)\n else:\n self.errors = \"Error: Please select a download directory.\"", "def create_catalog(self, catalog_name, description=\"\", parent_id=None):\r\n\r\n logging.info(\"Creating catalog '\"+catalog_name+\"' under parent folder \"+str(parent_id))\r\n \r\n post_data = {\"Name\":catalog_name,\r\n \"Description\":description,\r\n \"LimitSearchToCatalog\":True\r\n }\r\n\r\n if parent_id:\r\n post_data[\"LinkedFolderId\"] = parent_id\r\n\r\n result = self.mediasite.api_client.request(\"post\", \"Catalogs\", \"\", post_data).json()\r\n \r\n if self.mediasite.experienced_request_errors(result):\r\n return result\r\n else: \r\n if \"odata.error\" in result:\r\n logging.error(result[\"odata.error\"][\"code\"]+\": \"+result[\"odata.error\"][\"message\"][\"value\"])\r\n\r\n return result", "def list_shows(category_id):\n\n # Get category details\n category = GENRES[category_id]\n\n # Set plugin category. It is displayed in some skins as the name of the current section.\n xbmcplugin.setPluginCategory(_handle, category['label'])\n # Set plugin content. It allows Kodi to select appropriate views for this type of content.\n xbmcplugin.setContent(_handle, 'videos')\n\n shows = category['items']\n # Iterate through shows\n for item_id in shows:\n item = SHOWS_BY_ID[item_id]\n # Create a list item with a text label and a thumbnail image.\n list_item = xbmcgui.ListItem(label=item['title'])\n # Set graphics (thumbnail, fanart, banner, poster, landscape etc.) for the list item.\n list_item.setArt({'thumb': item['image-background'],\n 'icon': item['image-background'],\n 'fanart': item['image-background'],\n 'landscape': item['image-landscape']})\n # Set additional info for the list item.\n # For available properties see the following link:\n # http://mirrors.xbmc.org/docs/python-docs/15.x-isengard/xbmcgui.html#ListItem-setInfo\n list_item.setInfo('video', {'title': item['title'],\n #'plot' : item['description'],\n 'genre': category['label']})\n # Create a URL for a plugin recursive call.\n # Example: plugin://plugin.video.example/?action=listing&category=Animals\n url = get_url(action='section-listing', show=item_id)\n # is_folder = True means that this item opens a sub-list of lower level items.\n is_folder = True\n # Add our item to the Kodi virtual folder listing.\n xbmcplugin.addDirectoryItem(_handle, url, list_item, is_folder)\n # Add a sort method for the virtual folder items (alphabetically, ignore articles)\n xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)\n # Finish creating a virtual folder.\n xbmcplugin.endOfDirectory(_handle)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disables mediasite catalog links using provided catalog ID
def disable_catalog_allow_links(self, catalog_id): logging.info("Disabling catalog links for catalog: '"+catalog_id) #prepare patch data to be sent to mediasite patch_data = {"AllowCatalogLinks":"False"} #make the mediasite request using the catalog id and the patch data found above to enable downloads result = self.mediasite.api_client.request("patch", "Catalogs('"+catalog_id+"')/Settings", "", patch_data) if self.mediasite.experienced_request_errors(result): return result else: return result
[ "def enable_catalog_downloads(self, catalog_id):\r\n\r\n logging.info(\"Enabling catalog downloads for catalog: '\"+catalog_id)\r\n\r\n #prepare patch data to be sent to mediasite\r\n patch_data = {\"AllowPresentationDownload\":\"True\"}\r\n\r\n #make the mediasite request using the catalog id and the patch data found above to enable downloads\r\n result = self.mediasite.api_client.request(\"patch\", \"Catalogs('\"+catalog_id+\"')/Settings\", \"\", patch_data)\r\n \r\n if self.mediasite.experienced_request_errors(result):\r\n return result\r\n else:\r\n return result", "def clean_dead_youtube_link(productionlink_id):\n try:\n production_link = ProductionLink.objects.get(id=productionlink_id)\n except ProductionLink.DoesNotExist:\n # guess it was deleted in the meantime, then.\n return\n\n try:\n production_link.link.get_embed_data(oembed_only=True)\n except urllib.error.HTTPError as e:\n if e.code == 404:\n print(\"404 on %s - deleting\" % production_link.link)\n production_link.delete()", "async def async_cancel_all_linking(self):\n await self._linked_device.put(False)", "def apicatalog_disable(self, apicatalog_disable):\n\n self._apicatalog_disable = apicatalog_disable", "def download_off():\n mw.note_download_action.setEnabled(False)\n mw.side_download_action.setEnabled(False)\n mw.manual_download_action.setEnabled(False)", "def allow_video(self, video_id: str) -> None:\n video = self._library.get_video(video_id)\n if video is None:\n print(\"Cannot remove flag from video: Video does not exist\")\n return\n\n if video_id not in self._flags:\n print(\"Cannot remove flag from video: Video is not flagged\")\n return\n\n del self._flags[video_id]\n print(f\"Successfully removed flag from video: {video.title}\")", "def skip_download(self, link, spider):\n return False", "def deny_access(self, share, access, share_server):", "def profile_remove_links_to_online_profiles(context: Context, supplier_alias: str):\n actor = get_actor(context, supplier_alias)\n company = get_company(context, actor.company_alias)\n\n facebook = True if company.facebook else False\n linkedin = True if company.linkedin else False\n twitter = True if company.twitter else False\n\n context.response = profile.edit_online_profiles.remove_links(\n actor, company, facebook=facebook, linkedin=linkedin, twitter=twitter\n )\n\n # Update company's details stored in context.scenario_data\n update_company(context, company.alias, facebook=None, linkedin=None, twitter=None)", "def unfurl_links(self):\n self._unfurl_links = True\n self._unfurl_media = True\n return self", "def hide_stream_item(request_ctx, id, **request_kwargs):\n\n path = '/v1/users/self/activity_stream/{id}'\n url = request_ctx.base_api_url + path.format(id=id)\n response = client.delete(request_ctx, url, **request_kwargs)\n\n return response", "def reject_link(self,\n net_id: str,\n link_id: ObjectId\n ):\n d = self.get_unsafe_link_document(link_id)\n if d['status'] != DetectedLinkStatus.PENDING.value:\n raise InvalidStateChange\n self.change_link_status(link_id, net_id, DetectedLinkStatus.DENIED.value)", "def dont_track_link_clicks(self, dont_track_link_clicks):\n\n self._dont_track_link_clicks = dont_track_link_clicks", "def disconnect_connector(self): \n if self.itemA is not None:\n if self in self.itemA.connectorList:\n self.itemA.connectorList.remove(self)\n if self.itemB is not None:\n if self in self.itemB.connectorList:\n self.itemB.connectorList.remove(self)", "def dont_track_link_clicks(self):\n return self._dont_track_link_clicks", "def removes_channel(channel):", "async def async_cancel_linking_mode():\n cmd = CancelAllLinkingCommandHandler()\n return await cmd.async_send()", "def del_link_id(self, id_link):\n\n try:\n self.link.get(id = id_link).delete()\n except ObjectDoesNotExist:\n pass", "def ad_removal_before_video(self):\n try:\n # self.driver.switch_to.frame(self.driver.find_element_by_id('player'))\n try:\n WebDriverWait(self.driver, 15).until(EC.element_to_be_clickable(\n (By.XPATH, \"//button[@class='ytp-ad-skip-button ytp-button']\"))).click()\n except TimeoutException as e:\n try:\n self.driver.execute_script(\"return document.getElementById('movie_player').playVideo()\")\n except:\n pass\n except NoSuchFrameException:\n print(\"The script could not find the video player. An ad may be playing right now!\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add mediasite module to catalog by catalog id and module guid
def add_module_to_catalog(self, catalog_id, module_guid): logging.info("Associating catalog: "+catalog_id+" to module: "+module_guid) #prepare patch data to be sent to mediasite post_data = {"MediasiteId":catalog_id} #make the mediasite request using the catalog id and the patch data found above to enable downloads result = self.mediasite.api_client.request("post", "Modules('"+module_guid+"')/AddAssociation", "", post_data) if self.mediasite.experienced_request_errors(result): return result else: return result
[ "def add_part(self, part: Part, rel_location):\n self.modules.insert(rel_location, Module(part))\n self.update_parts()\n return self", "def add_module( self, to_add ):\n self.modules.append( to_add )", "def addMedia(self, m):", "def add_module(self, module):\n self.modules.append(module())", "def attach_module(prog_id, mod_id, level_id):\n programme: DegreeProgramme = DegreeProgramme.query.get_or_404(prog_id)\n module: Module = Module.query.get_or_404(mod_id)\n\n if module not in programme.modules:\n programme.modules.append(module)\n\n try:\n db.session.commit()\n except SQLAlchemyError as e:\n db.session.rollback()\n current_app.logger.exception(\"SQLAlchemyError exception\", exc_info=e)\n flash('Could not save changes because of a database error. Please contact a system '\n 'administrator', 'error')\n\n return redirect(url_for('admin.attach_modules', id=prog_id, level_id=level_id))", "def add_module_event(self, event, data):\n item = data.items[0]\n self.controller.reset_pipeline_view = False\n self.noUpdate = True\n internal_version = -1L\n reg = get_module_registry()\n if reg.is_abstraction(item.descriptor):\n internal_version = item.descriptor.module.internal_version\n adder = self.controller.add_module_from_descriptor\n module = adder(item.descriptor, \n event.scenePos().x(),\n -event.scenePos().y(),\n internal_version)\n self.reset_module_colors()\n graphics_item = self.addModule(module)\n graphics_item.update()\n self.unselect_all()\n # Change selection\n graphics_item.setSelected(True)\n\n # controller changed pipeline: update ids\n self._old_connection_ids = set(self.controller.current_pipeline.connections)\n self._old_module_ids = set(self.controller.current_pipeline.modules)\n\n # We are assuming the first view is the real pipeline view \n self.views()[0].setFocus()\n\n self.noUpdate = False", "def copy_module(self, module):\n module = module.do_copy(True, self.controller.vistrail.idScope, {})\n self.operations.append(('add', module))\n self.all_modules.add(module)\n return module", "def add_recipe_to_media(media, recipe):\n\n media.recipes.append(recipe)\n db.session.commit()", "def insert(self, index, module):\n\n assert isinstance(module, Module)\n self.__modules.insert(index, module)", "def add_material_to_media(media, material):\n\n media.materials.append(material)\n db.session.commit()", "def register_dynamic_module(cls, module_name: str) -> None:\n cls._dynamic_modules.add(module_name)", "def add_module(self, module: Module) -> None:\n self._modules.append(module)", "def add_channel(channel):", "def create_module(self, module_name, module_id):\r\n\r\n logging.info(\"Creating module '\"+module_name+\"' with module id \"+module_id)\r\n \r\n post_data = {\"Name\":module_name,\r\n \"ModuleId\":module_id\r\n }\r\n\r\n result = self.controller.api_client.request(\"post\", \"Modules\", \"\", post_data).json()\r\n\r\n if self.controller.experienced_request_errors(result):\r\n return result\r\n else:\r\n if \"odata.error\" in result:\r\n logging.error(result[\"odata.error\"][\"code\"]+\": \"+result[\"odata.error\"][\"message\"][\"value\"])\r\n\r\n return result", "def add_clips_to_media_pool(resolve, project, media_path):\n resolve.OpenPage(\"media\")\n media_storage = resolve.GetMediaStorage()\n media_pool = project.GetMediaPool()\n media_storage.AddItemListToMediaPool(str(media_path))", "def save_module(self, name, module):\n self.modules[name] = module", "def add_module(self, name: str, module: Optional['Module']) -> None:\n\n raise NotImplementedError(\"ORTModule does not support adding modules to it.\")", "def _add_to_library(videoid, export_filename):\n library_node = g.library()\n for depth, id_item in enumerate(videoid.to_list()):\n if id_item not in library_node:\n # No entry yet at this level, create a new one and assign\n # it an appropriate videoid for later reference\n library_node[id_item] = {\n 'videoid': videoid.derive_parent(depth)}\n library_node = library_node[id_item]\n library_node['file'] = export_filename\n library_node['videoid'] = videoid\n g.save_library()", "def addMetadata(streamName=\"string\", scene=bool, channelName=\"string\", indexType=\"string\", channelType=\"string\", structure=\"string\"):\n pass" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates mediasite catalog using provided catalog name, description, and parent folder id
def create_catalog(self, catalog_name, description="", parent_id=None): logging.info("Creating catalog '"+catalog_name+"' under parent folder "+str(parent_id)) post_data = {"Name":catalog_name, "Description":description, "LimitSearchToCatalog":True } if parent_id: post_data["LinkedFolderId"] = parent_id result = self.mediasite.api_client.request("post", "Catalogs", "", post_data).json() if self.mediasite.experienced_request_errors(result): return result else: if "odata.error" in result: logging.error(result["odata.error"]["code"]+": "+result["odata.error"]["message"]["value"]) return result
[ "def create_catalog(self, prefix, parent_catalog_name, description):\n\n return OrderedDict(\n [\n (\"stac_version\", \"0.6.0\"),\n (\"id\", prefix),\n (\"description\", description),\n (\n \"links\",\n [\n {\n \"href\": f'{self.config[\"aws-domain\"]}/{prefix}/catalog.json',\n \"rel\": \"self\",\n },\n {\n \"href\": f'{self.config[\"aws-domain\"]}/{parent_catalog_name}',\n \"rel\": \"parent\",\n },\n {\"href\": self.config[\"root-catalog\"], \"rel\": \"root\"},\n ],\n ),\n ]\n )", "def create(catalog_id=None):\n catalogs = ([Catalog.find_by_id(catalog_id)] if catalog_id\n else Catalog.get_all())\n return render_template( 'items/create.html',\n item=None, error='', catalogs=catalogs)", "def initCatalog(parametro):\n catalog = model.newCatalog(parametro) \n return catalog", "def add_module_to_catalog(self, catalog_id, module_guid):\r\n\r\n logging.info(\"Associating catalog: \"+catalog_id+\" to module: \"+module_guid)\r\n\r\n #prepare patch data to be sent to mediasite\r\n post_data = {\"MediasiteId\":catalog_id}\r\n\r\n #make the mediasite request using the catalog id and the patch data found above to enable downloads\r\n result = self.mediasite.api_client.request(\"post\", \"Modules('\"+module_guid+\"')/AddAssociation\", \"\", post_data)\r\n\r\n if self.mediasite.experienced_request_errors(result):\r\n return result\r\n else:\r\n return result", "def create( self, trans, encoded_parent_folder_id, **kwd ):\n\n payload = kwd.get( 'payload', None )\n if payload is None:\n raise exceptions.RequestParameterMissingException( \"Missing required parameters 'encoded_parent_folder_id' and 'name'.\" )\n name = payload.get( 'name', None )\n description = payload.get( 'description', '' )\n if encoded_parent_folder_id is None:\n raise exceptions.RequestParameterMissingException( \"Missing required parameter 'encoded_parent_folder_id'.\" )\n elif name is None:\n raise exceptions.RequestParameterMissingException( \"Missing required parameter 'name'.\" )\n\n encoded_parent_folder_id = self.__cut_the_prefix( encoded_parent_folder_id )\n decoded_parent_folder_id = self.__decode_folder_id( trans, encoded_parent_folder_id )\n parent_folder = self.__load_folder( trans, decoded_parent_folder_id )\n \n library = parent_folder.parent_library\n if library.deleted:\n raise exceptions.ObjectAttributeInvalidException( 'You cannot create folder within a deleted library. Undelete it first.' )\n\n # TODO: refactor the functionality for use in manager instead of calling another controller\n params = dict( [ ( \"name\", name ), ( \"description\", description ) ] )\n status, output = trans.webapp.controllers['library_common'].create_folder( trans, 'api', encoded_parent_folder_id, '', **params )\n\n if 200 == status and len( output.items() ) == 1:\n for k, v in output.items():\n try:\n folder = trans.sa_session.query( trans.app.model.LibraryFolder ).get( v.id )\n except Exception, e:\n raise exceptions.InternalServerError( 'Error loading from the database.' + str( e ))\n if folder:\n update_time = folder.update_time.strftime( \"%Y-%m-%d %I:%M %p\" )\n return_dict = self.encode_all_ids( trans, folder.to_dict( view='element' ) )\n return_dict[ 'update_time' ] = update_time\n return_dict[ 'parent_id' ] = 'F' + return_dict[ 'parent_id' ]\n return_dict[ 'id' ] = 'F' + return_dict[ 'id' ]\n return return_dict\n else:\n raise exceptions.InternalServerError( 'Error while creating a folder.' + str( e ) )", "def createCategories(context):\n # Only run step if a flag file is present\n filenames = context.readDataFile('mars_categories_container.txt')\n if filenames is None:\n return\n #filenames = [f\n # for f in filenames.split('\\n')\n # if f and not f.startswith('#') ]\n site = context.getSite()\n if not CAT_CONTAINER in site.objectIds():\n _createObjectByType('Categories Container',\n site,\n id=CAT_CONTAINER,\n title='Mars Categories',\n excludeFromNav=True)\n container = getattr(site, CAT_CONTAINER)\n publish_all(container)\n #for filename in filenames:\n # datafile = context.readDataFile('categories/'+filename)\n # container.importCatsFromText(datafile, filename)", "def createItem(parent, **args):\n addCreator(args, parent)\n itemModel = loadModel('item')\n args['folder'] = parent\n return itemModel.createItem(**args)", "def add_to_catalog(catalog_dict, catalog_prefix, parent_catalog_name, item):\n\n if catalog_prefix in catalog_dict:\n if catalog_dict[catalog_prefix][\"parent\"] != parent_catalog_name:\n raise NameError(\"Incorrect parent catalog name for : \" + item)\n catalog_dict[catalog_prefix][\"links\"].add(item)\n else:\n catalog_dict[catalog_prefix] = {\n \"parent\": parent_catalog_name,\n \"links\": {item},\n }", "def create(\n cls,\n connection: \"Connection\",\n name: str,\n parent: str,\n description: str | None = None,\n ) -> \"Folder\":\n connection._validate_project_selected()\n response = folders.create_folder(connection, name, parent, description).json()\n if config.verbose:\n logger.info(\n f\"Successfully created folder named: '{response.get('name')}' \"\n f\"with ID: '{response.get('id')}'\"\n )\n return cls.from_dict(source=response, connection=connection)", "def create_catalog(\n self,\n ) -> Callable[[metastore.CreateCatalogRequest], metastore.Catalog]:\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"create_catalog\" not in self._stubs:\n self._stubs[\"create_catalog\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.bigquery.biglake.v1.MetastoreService/CreateCatalog\",\n request_serializer=metastore.CreateCatalogRequest.serialize,\n response_deserializer=metastore.Catalog.deserialize,\n )\n return self._stubs[\"create_catalog\"]", "def create(self,title=None,file_data=None,comment=None,rating=None,\n tags=[],album_id=None,album_name=None,action=None,\n multi=False):\n # check and see if they are creating new media\n\n try:\n if action:\n\n # validate our form info\n file_data = m.Media.validate_form_data(title,file_data,comment,rating,\n tags,album_id,album_name)\n\n for fd in file_data:\n # create our new media\n media = m.Media(title=title)\n\n # add our new media to the session\n m.session.add(media)\n\n # who uploaded this?\n media.user = cherrypy.request.user\n\n # set the extension as the type\n media.type = str(fd.type)\n\n # add the filename\n if fd.filename:\n ext = fd.filename.rsplit('.',1)[-1]\n if ext:\n media.extension = ext\n\n # if there is a comment from the author add it\n if comment:\n c = m.Comment(media=media,\n content=comment,\n rating=rating,\n user=cherrypy.request.user)\n m.session.add(c)\n\n # save file data to the drive\n media.set_data(fd.file.read())\n\n # add our tags\n for tag_name in tags:\n media.add_tag_by_name(tag_name)\n\n # the album can either be an id or a\n # new name\n if album_id or album_name:\n if album_id:\n album = m.Album.get(album_id)\n else:\n album = m.Album.get_by(name=album_name)\n if not album:\n album = m.Album(name=album_name,\n owner=cherrypy.request.user)\n m.session.add(album)\n media.albums.append(album)\n\n m.session.commit()\n\n # let our user know it worked\n add_flash('info','New media successfully created!')\n\n # if it's a multi upload than we don't want to redirect\n if multi:\n return '1'\n\n # send them to the new media's page\n if album_name:\n redirect('/album/%s' % album.id)\n else:\n redirect('/media/%s' % media.id)\n\n except e.ValidationException, ex:\n # woops, alert of error\n add_flash('error','%s' % ex)\n\n if multi:\n return render('/media/create_multi.html')\n\n return render('/media/create.html')", "def create_snapshot(self, *, snapshot_id: str, directory: str) -> None:", "def build_folder(cls, db, folder_name, multiversion, record):\n from PyCool import cool\n \n folderset_path = dirname(folder_name)\n try:\n db.getFolderSet(folderset_path)\n except Exception as error:\n caught_error = \"Folder set %s not found\" % folderset_path\n if caught_error not in error.args[0]:\n raise\n\n log.debug(\"Folderset doesn't exist - creating it.\")\n db.createFolderSet(folderset_path, \"\", True)\n\n if not isinstance(record, cool.RecordSpecification):\n record_spec = cool.RecordSpecification()\n for field in record:\n record_spec.extend(*field)\n else:\n record_spec = record\n \n FV = cool.FolderVersioning\n versioning = FV.MULTI_VERSION if multiversion else FV.SINGLE_VERSION\n folder_spec = cool.FolderSpecification(versioning, record_spec)\n folder = db.createFolder(folder_name, folder_spec)\n payload = cool.Record(record_spec)\n \n return folder, payload", "def initialize(self, storage):\n # \"0\" root directory, our first goes under that, sencond under first.\n parent_id, kwargs = \"0\", {}\n for name in ('.cloudstrype', storage.user.uid):\n kwargs['data'] = json.dumps({\n 'name': name,\n 'parent': {\n 'id': parent_id,\n },\n })\n # Create the directory:\n r = self.oauthsession.post(self.CREATE_URL, **kwargs)\n attrs = r.json()\n if r.status_code == 409:\n # The directory exists, so nab it's ID, and continue to child.\n parent_id = attrs['context_info']['conflicts'][0]['id']\n else:\n # We created it, so nab the ID and continue to child.\n parent_id = r.json()['id']\n storage.attrs = storage.attrs or {}\n storage.attrs.update({'root.id': parent_id})", "def get_root_catalog():\n caturl = f\"{ROOT_URL}/catalog.json\"\n if s3().exists(caturl):\n cat = Catalog.from_file(caturl)\n else:\n catid = DATA_BUCKET.split('-data-')[0]\n cat = Catalog(id=catid, description=DESCRIPTION)\n cat.normalize_and_save(ROOT_URL, CatalogType.ABSOLUTE_PUBLISHED)\n logger.debug(f\"Fetched {cat.describe()}\")\n return cat", "def new_folder():\r\n pass", "def init():\n main_backup_dir = '.wit'\n parent_dir = os.getcwd()\n new_dir = pathlib.Path() / parent_dir / main_backup_dir / 'images' #Changed syntax according to notes on submission\n new_dir.mkdir(parents=True, exist_ok=True)\n new_dir = pathlib.Path() / parent_dir / main_backup_dir / 'staging_area'\n new_dir.mkdir(parents=True, exist_ok=True)", "def create(container):\n return CatalogModule(\n logger=container.logger(),\n listing_repository=container.listing_repository(),\n )", "def create( self, trans, history_id, payload, **kwd ):\n # TODO: Flush out create new collection documentation above, need some\n # examples. See also bioblend and API tests for specific examples.\n\n history = self.history_manager.get_owned( self.decode_id( history_id ), trans.user,\n current_history=trans.history )\n\n type = payload.get( 'type', 'dataset' )\n if type == 'dataset':\n source = payload.get( 'source', None )\n if source == 'library_folder':\n return self.__create_datasets_from_library_folder( trans, history, payload, **kwd )\n else:\n return self.__create_dataset( trans, history, payload, **kwd )\n elif type == 'dataset_collection':\n return self.__create_dataset_collection( trans, history, payload, **kwd )\n else:\n return self.__handle_unknown_contents_type( trans, type )" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove all '\n's, ','s and ' 's
def prepare_str(_str): return _str.replace('\n', '').replace(',', '').replace(' ', '')
[ "def remove_from_text(text):\n # 0 - preprocessing\n \"\"\"text = re.sub(', ', ' ', str(text))\n text = re.sub(',', '', str(text))\"\"\"\n text = re.sub('\\n ', '', str(text))\n text = re.sub('\\n', '', str(text))\n\n return text", "def clean(s):\n # return dedent(s)\n return \"\\n\".join([line.strip() for line in s.split(\"\\n\")])", "def clean(seq):\n return seq.strip().replace(' ', '').replace('\\n', '').replace('\\r', '')", "def cleaning(text):\n txt = []\n for sentence in text:\n sen = ''\n for string in sentence:\n string = string.replace(\",\",\"\")\n string = string.replace(\"\\n\",\"\")\n sen += string\n txt += [sen]\n return txt", "def _remove_start_end_commas(chunk_text: str) -> str:\n if chunk_text.startswith(', '):\n chunk_text = chunk_text[2:]\n if chunk_text.endswith(' ,'):\n chunk_text = chunk_text[:-2]\n return chunk_text", "def remove_multiple_line_spaces(text):\n return \"\\n\".join([line.strip() for line in text.splitlines() if line.strip() != \"\"])", "def cleanup(self):\n text = ''\n try:\n paragraphs = self.text.split('\\n')\n except AttributeError:\n return text\n\n for par in paragraphs:\n par = par.strip()\n if par == '':\n continue\n\n par = RE_SPACES.sub(' ', par)\n text += par + '\\n'\n\n return text.strip()", "def _remove_line_breaks(str):\n str2 = str\n str2 = str2.replace(\"\\n\", \" \") # Replace line breaks\n str2 = str2.strip() # Remove leading and trailing spaces\n str2 = re.sub('\\s{2,}', ' ', str2) # At most one space\n return str2", "def clean_text(text):\r\n clean_text = text.replace('\\n', ' ').replace('\\r', '').strip()\r\n return clean_text", "def remove_commas(file_name):\n with open(file_name, 'r') as f:\n text = f.read()\n text = replace(text, ',', '\\n')\n with open(file_name, 'w') as f: # now writing\n f.write(text)\n return file_name", "def clean_text(txt):\n txt = re.sub(r' +', ' ', txt)\n txt = re.sub(r'\\n\\s*\\n', '\\n\\n', txt)\n return txt", "def text_cleanup(text: str) -> str:\n text.replace('\\n', '')\n return re.sub(r'\\s{2,}', ' ', text)", "def _strip_whitespace(self, s):\n\t s = s.replace('\\n', ' ').replace('\\r', ' ')\n\t s = re.sub(r'\\s+', ' ', s)\n\t return s", "def clean(sentences: list) -> list:\n cleaned = [sentence.replace(\"\\n\", \" \") for sentence in sentences]\n return cleaned", "def stripcommas(aText):\n import re\n # Replace by a space in case comma directly connects two words.\n aText = re.sub(\",\", \" \", aText)\n # Remove any multi-space sections (some may result from the above step)\n return re.sub(\" {2,}\", \" \", aText)", "def remove_blanks(input_str):\n \n temp_str = input_str.replace(' ', '')\n temp_str = temp_str.replace('\\n', '')\n return temp_str", "def remove_empty_lines(strIn):\n return os.linesep.join([s for s in strIn.splitlines() if s.strip()])", "def _remove_empty_lines(article_text: str) -> str:\n return '\\n'.join(\n filter(lambda s: s.strip() != '', article_text.split('\\n')))", "def clean_line(line):\n return line.replace(\"\\0\", \"\").strip()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
page number should in [1,200]
def correct_page_num(page): if page < 0 or page > 200: return 1 return page
[ "def pages_check(pages):\n if not pages:\n pages = 1\n return pages", "def check_pages(soup):\n review_count = int(soup.find(itemprop='reviewCount').text.strip('()'))\n pages = 1\n if review_count > 20:\n pages = ceil(review_count / 20)\n return pages", "def tiebaSpider(url, beginPage, endPage):\n for page in range(beginPage, endPage + 1):\n pn = (page - 1) * 50\n filename = 'page' + str(page) + '.html'\n fullurl = url + '&pn=' + str(pn)\n #print(fullurl)\n html = loadPage(fullurl, filename)\n print(html)", "def get_pages(url):\n return url.json()['size'] // 10", "def getPage(self, pageNum):\n pass", "def get_page(data, page):\n begin = page * 20\n end = page * 20 + 20\n if begin >= len(data):\n return []\n elif end >= len(data):\n return data[begin:]\n else:\n return data[begin:end]", "def lazy_pages(self, index):\n if index < 0:\n index += self.total\n return index // self.per_page + 1", "def test_it_includes_page_numbers():\n fh = open('fixtures/sample_data/AnimalExampleTables.pdf', 'rb')\n result = get_tables(fh)\n assert_equals(result[0].total_pages, 4)\n assert_equals(result[0].page_number, 2)\n assert_equals(result[1].total_pages, 4)\n assert_equals(result[1].page_number, 3)\n assert_equals(result[2].total_pages, 4)\n assert_equals(result[2].page_number, 4)", "def test_determine_page(self):\n req_args = {'page': 1}\n page = determine_page(req_args)\n self.assertEquals(page, 1)", "def test_setPage(self):\n\n self.positionController.setPage(3)\n assert self.positionController.startIndex == 15\n assert self.positionController.arePrev == True\n assert self.positionController.areMore == True\n assert self.positionController.page == 3\n assert self.positionController.pageNumber == 4\n assert self.positionController.currentPageItems == ['Item15', 'Item16', 'Item17', 'Item18',\n 'Item19']", "def test_get_page_size(self):\n GalleryFactory.create_batch(100)\n\n url = reverse('gallery-list')\n response = self.client.get(url)\n self.assertEqual(len(response.context['gallery_list']), 10)\n self.assertEqual(response.context['paginate_by'], 10)\n\n response = self.client.get(url, {'pageSize': '50'})\n self.assertEqual(len(response.context['gallery_list']), 50)\n self.assertEqual(response.context['paginate_by'], 50)\n\n response = self.client.get(url, {'pageSize': '87'})\n self.assertEqual(len(response.context['gallery_list']), 10)\n self.assertEqual(response.context['paginate_by'], 10)", "def get_page_no(payload):\n page_no = payload.get('page', 1)\n try:\n page_no = int(page_no)\n except ValueError:\n page_no = 1\n if page_no < 1:\n page_no = 1\n return page_no", "def test_pageList(self):\n pageList = self.positionController.pageList()\n assert len(pageList) == 4\n assert pageList == [0, 5, 10, 15]", "def test_pagination(self):\n for i in range(21):\n self.create_report()\n response = self._get(get_kwargs={'page': 2})\n self.assertEquals(response.status_code, 200)\n queryset, form = self._extract(response)\n self.assertEquals(queryset.count(), 21)\n page = response.context['table'].page\n self.assertEquals(page.object_list.data.count(), 1)", "def parse_page_number(url):\n if '?' not in url:\n return 1\n params = url.split('?')[1].split('=')\n params = {k: v for k, v in zip(params[0::2], params[1::2])}\n if 'page' not in params:\n return 1\n return int(params['page'])", "def test_pageIndex(self):\n assert self.positionController.pageIndex(0) == 0\n assert self.positionController.pageIndex(1) == 5\n assert self.positionController.pageIndex(2) == 10\n assert self.positionController.pageIndex(3) == 15\n assert self.positionController.pageIndex(4) == 20", "def pageCount(n, p):\r\n #\r\n # Write your code here.\r\n #\r\n middle = int(n/2)\r\n diff = n-p\r\n if p <= middle:\r\n return int(p/2)\r\n else:\r\n if (n%2 == 0 and diff == 0) or (n%2 != 0 and diff < 2):\r\n return 0\r\n elif n%2 == 0 and diff == 1 or (n%2 != 0 and diff < 5):\r\n return 1\r\n else:\r\n return int((diff)/2)", "def calculate_pages(self):\n\n current_page = int(self.request.GET.get('p', 1))\n return (current_page - 1, current_page, current_page + 1)", "def test_get_pager_params(self):\n self.assertEqual(self.spider._get_pager_params(1), 'pgR_min_row=16max_rows=15rows_fetched=15')\n self.assertEqual(self.spider._get_pager_params(5), 'pgR_min_row=76max_rows=15rows_fetched=15')" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
blog list page url
def page_blog_list(self, page=1): self.correct_page_num(page) return 'http://mypage.syosetu.com/mypageblog/list/userid/' \ + self.id + '/index.php?p=' + str(page)
[ "def get_blog_url(self, obj):\n return obj.blogs.all()[0].page", "def post_list(request, tag=''):\n page = request.GET.get('page', '')\n context_dict = {\n 'active_page': 'blog',\n 'page': page,\n 'tag': tag,\n }\n return render(request, 'blog/post_list.html', context_dict)", "def get_absolute_url(self):\n return reverse(\"blog-detail\", args=[str(self.id)])", "def blog_items_url(url, ebi, page_no):\n url = url.rstrip('/')\n return \"{}/action/v_frag-ebi_{}-pg_{}/entry/\".format(url, ebi, page_no)", "def get(self):\r\n blogposts = BlogPosts.query().order(-BlogPosts.posted_on)\r\n self.render(\"blog.html\", blogposts = blogposts)", "def blog_index(request):\n posts = Post.objects.all().order_by('-created_on')\n context = {\n \"posts\": posts,\n }\n return render(request, \"blog_index.html\", context)", "def blog_view(request):\n message = \"You have be signed before you can view our blog post\"\n movies_in_theater = NowPlayingMovie.objects.all().order_by('-movie_release_date')\n # Paginate page with 10 movies at a time\n paginator = Paginator(movies_in_theater, 10)\n # Current page of the movie\n page = request.GET.get('page')\n try:\n movies = paginator.page(page)\n except PageNotAnInteger:\n movies = paginator.page(1)\n except:\n message = \"You have be signed in before you can view our blog posts\"\n movies = paginator.page(paginator.num_pages)\n return render(request, 'suggestion/movies_suggestion.html', {'movies': movies, 'message':message} )", "def blog_index(request):\n posts = Post.objects.all().order_by('-created_on')\n context = {\n \"posts\": posts,\n }\n return render(request, \"blog/blog_index.html\", context)", "def index():\n db = get_db()\n query_response = db.execute(\n \"SELECT p.id, title, body, updated, author_id, username, public\"\n \" FROM blog p JOIN user u ON p.author_id = u.id\"\n \" ORDER BY updated DESC\"\n ).fetchall()\n\n blogs = []\n for row in query_response:\n if g.user:\n if row[\"author_id\"] != g.user[\"id\"] and row['public'] == 0:\n continue\n else:\n if row['public'] == 0:\n continue\n\n blogs.append(row)\n\n return render_template(\"blog/index.html\", blogs=blogs)", "def blog_page():\n try:\n return RichTextPage.objects.get(slug=settings.BLOG_SLUG)\n except RichTextPage.DoesNotExist:\n return None", "def blog_page():\n try:\n return ContentPage.objects.get(slug=blog_settings.BLOG_SLUG)\n except ContentPage.DoesNotExist:\n return None", "def retrieve_listing_page_urls(self) -> List[str]:\n return [\"https://fatabyyano.net/newsface/0/\"]", "def get(self, posts=\"\"):\n posts = list(Post.get_all())\n\n self.render(\"blog.html\", user=self.user, posts=posts)", "def post_list(request):\n posts = PostBlog.objects.filter(published_date__lte = timezone.now()\n ).order_by('-published_date')\n return render(request, \"blog/blog_posts.html\", {'posts': posts})", "def notebooks_index():\n return render_template('blog/index.html', posts=[])", "def list(self, request, *args, **kwargs):\n if request.GET.get('keyword', '') != '':\n queryset = Blog.objects.filter(\n Q(title__icontains=request.GET.get('keyword')) | Q(description__contains=request.GET.get('keyword'))\n )\n\n elif request.user.is_authenticated:\n queryset = Blog.objects.filter(Q(draft=False) | (Q(draft=True) & Q(owner=request.user)))\n\n else:\n queryset = Blog.objects.filter(Q(draft=False))\n\n page = self.paginate_queryset(queryset)\n serializer = BlogSerializer(page, many=True, context={'request': request})\n return self.get_paginated_response(serializer.data)", "def get(self, blog_id): # noqa\n blog_entry = BlogEntity.get_by_id_str(blog_id)\n if not blog_entry:\n self.error(404)\n return\n self.render(\"blog_permalink.html\",\n article=blog_entry,\n parser=self.render_blog_article)", "def blog_post_list(request, tag=None, year=None, month=None, username=None,\n category=None, template=\"blog/blog_post_list.html\"):\n settings.use_editable()\n templates = []\n blog_posts = BlogPost.objects.published(for_user=request.user)\n if tag is not None:\n tag = get_object_or_404(Keyword, slug=tag)\n blog_posts = blog_posts.filter(keywords__in=tag.assignments.all())\n if year is not None:\n blog_posts = blog_posts.filter(publish_date__year=year)\n if month is not None:\n blog_posts = blog_posts.filter(publish_date__month=month)\n month = month_name[int(month)]\n if category is not None:\n category = get_object_or_404(BlogCategory, slug=category)\n blog_posts = blog_posts.filter(categories=category)\n templates.append(\"blog/blog_post_list_%s.html\" % category.slug)\n author = None\n if username is not None:\n author = get_object_or_404(User, username=username)\n blog_posts = blog_posts.filter(user=author)\n templates.append(\"blog/blog_post_list_%s.html\" % username)\n blog_posts = paginate(blog_posts, request.GET.get(\"page\", 1),\n settings.BLOG_POST_PER_PAGE,\n settings.BLOG_POST_MAX_PAGING_LINKS)\n context = {\"blog_page\": blog_page(), \"blog_posts\": blog_posts,\n \"year\": year, \"month\": month, \"tag\": tag,\n \"category\": category, \"author\": author}\n templates.append(template)\n request_context = RequestContext(request, context)\n t = select_template(templates, request_context)\n return HttpResponse(t.render(request_context))", "def blogmain(request):\n ents = list(Entry.objects.all().order_by('-when')[:25])\n c = RequestContext(request)\n add_entries(c, ents)\n c['title'] = 'Blog'\n c['crumbs'] = c['crumbs'][:1]\n return render_to_response('blogmain.html', c)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
bookmark list page url
def page_bookmark_list(self, page=1): self.correct_page_num(page) return 'http://mypage.syosetu.com/mypagefavnovelmain/list/userid/' \ + self.id + '/index.php?p=' + str(page)
[ "def page_following_list(self, page=1):\n self.correct_page_num(page)\n return 'http://mypage.syosetu.com/mypagefavuser/list/userid/' \\\n + self.id + '/index.php?p=' + str(page)", "def retrieve_listing_page_urls(self) -> List[str]:\n return [\"https://fatabyyano.net/newsface/0/\"]", "def blog_items_url(url, ebi, page_no):\n url = url.rstrip('/')\n return \"{}/action/v_frag-ebi_{}-pg_{}/entry/\".format(url, ebi, page_no)", "def page_blog_list(self, page=1):\n self.correct_page_num(page)\n return 'http://mypage.syosetu.com/mypageblog/list/userid/' \\\n + self.id + '/index.php?p=' + str(page)", "def get_show_url(self, name):", "def getBookmarkedPage(self):\n\t\treturn self.book_marked_page", "def bookmark_delete_page(request):\n if request.GET.has_key('url'):\n url = request.GET['url']\n _delete_page(request, url)\n return HttpResponseRedirect('/bookmarks/user/%s'%request.user.username)", "def get_blog_url(self, obj):\n return obj.blogs.all()[0].page", "def bookmark(srcff, book):\n\n os.chdir(srcff)\n merger = PdfFileMerger()\n visual_feedback = \"creating bookmark...\"\n num = 0\n key_list = list(book.keys())\n val_list = list(book.values())\n while num != len(os.listdir(\".\")):\n pdf = \"page%s.pdf\" % num\n check = (\n num in book.values()\n ) \n\n if num and check:\n title = key_list[val_list.index(num)]\n merger.append(pdf, title)\n num += 1\n try:\n print(\n visual_feedback,\n key_list[num] + \".....@.....page number.....\" + str(num),\n )\n except IndexError:\n print(\"......@....page number....\" + str(num))\n else:\n merger.append(pdf)\n num += 1\n merger.setPageMode(\"/UseOutlines\")\n print(\"your bookmarked pdf will be stored at...\", srcff)\n print(\"what do you want to call this pdf file?(do not use .pdf at end)\\n\")\n result = input()\n merger.write(result + \".pdf\")\n merger.close()\n return result + \".pdf\"", "def homepage_url(self):\n return self.request.link(self.app.org)", "def _getOrgApplicationListPageListUrl(program):\n return '/gsoc/org/application/list/%s' % program.key().name()", "def list(request):\n urls = myURL.objects.order_by('-accessNb')\n return render(request, 'mini_url/list.html', locals())", "def page_review_list(self, page=1):\n self.correct_page_num(page)\n return 'http://mypage.syosetu.com/mypage/reviewlist/userid/' \\\n + self.id + '/index.php?p=' + str(page)", "def list_bookmarks(request):\n bookmarks = Bookmark.objects.filter(user=request.user)\n\n if request.POST:\n bookmarks = search_bookmarks(request.POST.get('query', None), bookmarks)\n\n context = {\n 'bookmarks': bookmarks,\n }\n return render(request, 'bookmarks/list_bookmarks.html', context)", "def _wikipedia_Page_linkedPages(self):\n return [page for page in toolserver.Generators.getPagelinks(self)]", "def page_url(self, page_pk): \n self.c.execute(\"SELECT url FROM pages WHERE id=%s\", (page_pk,))\n return self.c.fetchone()[0]", "def assign_url(context):", "def browse_url(self):\n return self._pr.html_url", "def get_url(self, nbfile):\n urls = self.urls\n if isinstance(urls, dict):\n return urls.get(nbfile)\n elif isstring(urls):\n if not urls.endswith('/'):\n urls += '/'\n return urls + nbfile" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
following list page url
def page_following_list(self, page=1): self.correct_page_num(page) return 'http://mypage.syosetu.com/mypagefavuser/list/userid/' \ + self.id + '/index.php?p=' + str(page)
[ "def retrieve_listing_page_urls(self) -> List[str]:\n return [\"https://fatabyyano.net/newsface/0/\"]", "def get_next_url(self):\n return None", "def page_bookmark_list(self, page=1):\n self.correct_page_num(page)\n return 'http://mypage.syosetu.com/mypagefavnovelmain/list/userid/' \\\n + self.id + '/index.php?p=' + str(page)", "def next_url(self):\n p = self.next_instance\n return p.url if p else \"\"", "def _next_url(self, response):\n return response.links.get(\"page-next\", {}).get(\"url\", None)", "def test_user_current_list_following(self):\n pass", "def test_user_list_following(self):\n pass", "def _find_next_url(self, page_soup: BeautifulSoup) -> str:", "def following(name):\n friendlist = fetch_following(api, name)\n newlist = sorted(friendlist, key = lambda k:k['followers'], reverse = True)\n return render_template('following.html', friends = newlist, name = name)", "def list_following(self) -> list:\n return [u.screen_name for u in self.following_list]", "def detail_url(self, response):\n sel = response.selector\n detail_url = sel.xpath(u\"//a[contains(text(),'查看详情')]/@href\").extract()\n url = 'http://www.dailianmeng.com'\n urls = [url+i for i in detail_url]\n redis_key = 'dai_lian_meng_redis_spider:start_urls' \n #redis_key是根据redisPpdaiScrapy.py中的redis_key设定的\n for url in urls:\n self.__class__.myRedis.lpush(redis_key, url)", "def get_show_url(self, name):", "def next_url(request):\n next_page = request.REQUEST.get(\"next\", \"\")\n host = request.get_host()\n return next_page if next_page and is_safe_url(\n next_page, host=host) else None", "def followed_sites_url(self):\n return self.properties.get(\"FollowedSitesUrl\", None)", "def urls(self):\n return [\n url('', include(self.get_list_urls()), {'flow_class': self.flow_class}),\n self.flow_class.instance.urls\n ]", "def followers():\n userid = session[\"user_id\"]\n\n following_user = following_users(userid)\n\n # check if you are going to look at another profile's list of followers or your own list\n username = request.args.get('username')\n\n # if you are going to watch another profile's list get the data of that profile\n if username:\n id_username = get_id(username)\n followers = db.execute(\"SELECT own_username, own_full_name FROM volgend WHERE following_id = :following_id\",\n following_id = id_username)\n\n # get the data of your own profile\n else:\n followers = db.execute(\"SELECT own_username, own_full_name FROM volgend WHERE following_id = :userid\", userid = userid)\n\n # print screen on page\n return render_template(\"followers.html\", users = followers, following_user=following_user)", "def page_blog_list(self, page=1):\n self.correct_page_num(page)\n return 'http://mypage.syosetu.com/mypageblog/list/userid/' \\\n + self.id + '/index.php?p=' + str(page)", "def page_commented_novel_list(self, page=1):\n self.correct_page_num(page)\n return 'http://mypage.syosetu.com/mypagenovelhyoka/list/userid/' \\\n + self.id + '/index.php?p=' + str(page)", "def get_next_url(self, request, obj):\n cm = obj.__class__._meta\n url = reverse(\"admin:app_list\", args=(cm.app_label, ))\n if '_continue' in request.POST:\n url = reverse(\"admin:%s_%s_change\" % (cm.app_label, cm.model_name),\n args=(obj.pk, ))\n elif '_addanother' in request.POST:\n url = reverse(\"admin:%s_%s_add\" % (cm.app_label, cm.model_name))\n return url" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
commented novel list page url
def page_commented_novel_list(self, page=1): self.correct_page_num(page) return 'http://mypage.syosetu.com/mypagenovelhyoka/list/userid/' \ + self.id + '/index.php?p=' + str(page)
[ "def list_commented_novels(self, page_num=10):\n count = self.get_count(self.page_commented_novel_list())\n if count == 0:\n return\n for i in range(1, (count - 1) / page_num + 2):\n soup = get_soup(self.page_commented_novel_list(i))\n if soup is None:\n continue\n soup_commented_novel_list = soup.find(id='novelpointlist')\n if soup_commented_novel_list is not None:\n li_titles = soup_commented_novel_list.find_all(class_='title')\n for li_title in li_titles:\n self.commentedNovels.append(li_title.find('a')['href'][25:-1].encode('unicode-escape'))", "def retrieve_listing_page_urls(self) -> List[str]:\n return [\"https://fatabyyano.net/newsface/0/\"]", "def page_review_list(self, page=1):\n self.correct_page_num(page)\n return 'http://mypage.syosetu.com/mypage/reviewlist/userid/' \\\n + self.id + '/index.php?p=' + str(page)", "def page_blog_list(self, page=1):\n self.correct_page_num(page)\n return 'http://mypage.syosetu.com/mypageblog/list/userid/' \\\n + self.id + '/index.php?p=' + str(page)", "def page_bookmark_list(self, page=1):\n self.correct_page_num(page)\n return 'http://mypage.syosetu.com/mypagefavnovelmain/list/userid/' \\\n + self.id + '/index.php?p=' + str(page)", "def page_following_list(self, page=1):\n self.correct_page_num(page)\n return 'http://mypage.syosetu.com/mypagefavuser/list/userid/' \\\n + self.id + '/index.php?p=' + str(page)", "def reddit_page_handler(url):\n\tpayload = urllib2.urlopen(url).read()\n\tpayload = json.loads(payload)\n\tcomment_pages = []\n\tfor story in payload['data']['children']:\n\t\tstory = story['data']\n\t\tcomment_url = story['permalink']\n\t\tcomment_pages.append(comment_url)\n\treturn (comment_pages,payload['data']['after'])", "def get_show_url(self, name):", "def list(request):\n urls = myURL.objects.order_by('-accessNb')\n return render(request, 'mini_url/list.html', locals())", "def NsUrl(self) -> str:", "def blog_items_url(url, ebi, page_no):\n url = url.rstrip('/')\n return \"{}/action/v_frag-ebi_{}-pg_{}/entry/\".format(url, ebi, page_no)", "def get_absolute_url(self):\n return reverse('comment-detail', args=[str(self.m_id)])", "def get_news_list(self, owner, root_url):\n raise NotImplementedError", "def test_list_get(self):\n with self.login(self.test_user):\n self.get_check_200(\n \"admin:organizer_newslink_changelist\"\n )", "def links():\n links_list = tasks.json_list(os.path.join(pathlib.Path(__file__).parent.absolute(),'static/links.json'))\n return render_template('links.html',title='collegeSmart - Helpful Links',links=links_list)", "def url(self):\n return \"http://www.reddit.com/r/getmotivated.json?limit=500\"", "def _getOrgApplicationListPageListUrl(program):\n return '/gsoc/org/application/list/%s' % program.key().name()", "def detail_url(self, response):\n sel = response.selector\n detail_url = sel.xpath(u\"//a[contains(text(),'查看详情')]/@href\").extract()\n url = 'http://www.dailianmeng.com'\n urls = [url+i for i in detail_url]\n redis_key = 'dai_lian_meng_redis_spider:start_urls' \n #redis_key是根据redisPpdaiScrapy.py中的redis_key设定的\n for url in urls:\n self.__class__.myRedis.lpush(redis_key, url)", "def index():\n return \"\"\"\n <p><a href=\"/users/facebook_oauth\">Go to Facebook</a></p>\n <p><a href=\"/users/google_oauth\">Go to Google</a></p>\n <p><a href=\"/users/github_oauth\">Go to GitHub</a></p>\n \"\"\"" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
review list page url
def page_review_list(self, page=1): self.correct_page_num(page) return 'http://mypage.syosetu.com/mypage/reviewlist/userid/' \ + self.id + '/index.php?p=' + str(page)
[ "def get_url(self):\n return '%s' % (self.review_url)", "def program_review_url(self, program_data):\n return self.review_url(program_data.program.id)", "def get_show_url(self, name):", "def parse_reviews_url(self, html):\n sel = Selector(html)\n url = sel.xpath(self.reviews_listing_url_xpath).extract()[0]\n return url", "def review_index(request):\n context = {'reviews': Review.objects.all()}\n return render(request, 'reviews/review_index.html', context)", "def get_success_url(self):\n reviewed_id = self.kwargs[\"user_id\"]\n return reverse(\"user_reviews\", kwargs={\"user_id\": reviewed_id})", "def assign_url(context):", "def _get_lti_view_url(self, resource):\n return f\"/lti/documents/{resource.pk}\"", "def review_view(request):\n return render(request, 'front/review.html')", "def view_reviews(request):\n user = request.user\n reviews = user.reviews.all().order_by('-created')\n review_paginator = Paginator(reviews, 4)\n page_number = request.GET.get('page')\n page_obj = review_paginator.get_page(page_number)\n\n context = {\n 'page_obj': page_obj,\n 'reviews': reviews,\n }\n return render(request, 'reviews/view_reviews.html', context)", "def render_review_page():\n title = 'Review'\n pending = Record.get_all_pending_records()\n return render_template('review.html', page_title=title, pending=pending)", "def get_absolute_url(self):\n return reverse('questions:question_paper_details', args=[self.id])", "def build_base_url(self):\n self.__base_url = \"https://www.tripadvisor.%s\" % (self.__review_language)", "def file_list_url(self):\n return self.request.link(GeneralFileCollection(self.app), name='json')", "def get_url_page(self, product):\n return product.get('url')", "def add_review(): \n return render_template('addReview.html')", "def NsUrl(self) -> str:", "def url(self):\n return reverse('api-project-code-list')", "def blog_items_url(url, ebi, page_no):\n url = url.rstrip('/')\n return \"{}/action/v_frag-ebi_{}-pg_{}/entry/\".format(url, ebi, page_no)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
decompose count from specific url
def get_count(url, pos_to=-2): soup = get_soup(url) if soup is None: return 0 if soup.find(class_='allcount') is None: return 0 return int(soup.find(class_='allcount').string[1:pos_to])
[ "def get_unique_counter_from_url(sp):\n ...", "def get_pages(url):\n return url.json()['size'] // 10", "def getUrlsCounter(self):\r\n return self.handledUrlsCounter", "def getCountOfPages(url):\n # Making BeautifulSoup object\n htmlResponse = getHtml(url)\n soup = bs(htmlResponse.text, \"html.parser\")\n countOfCurrentPage = int(soup.select(\"div.pages ul li\")[-1].text)\n linkToCurrentPage = URL + soup.select(\"div.pages ul li\")[-1].find(\"a\")[\"href\"]\n i = 5\n\n while True:\n htmlResponse = getHtml(linkToCurrentPage)\n soup = bs(htmlResponse.text, \"html.parser\")\n countOfCurrentPage = int(soup.select(\"div.pages ul li\")[-1].text)\n i += 2\n if i > countOfCurrentPage:\n break\n linkToCurrentPage = URL + soup.select(\"div.pages ul li\")[-1].find(\"a\")[\"href\"]\n\n return countOfCurrentPage", "def url_wordcount(url):\n\n f = urllib.urlopen(url)\n text = f.read()\n text = remove_html_tags(text)\n words = extract_words(text)\n worddict = count_words(words)\n wordcount100 = top100words(worddict)\n return wordcount100", "def get_num_pages():\n NUMBERS = \"http://www.omniglot.com/language/numbers/\"\n num = urllib2.urlopen(MULTILING_URLS['num']).read()\n return list(set([NUMBERS+str(re.findall(AHREF_REGEX,str(i))[0]) \\\n for i in bs(num).findAll('dd')]))", "def parse_to_n_digit(url: str) -> Optional[str]:\n\n n_digit_match = re.search('([1-9][0-9]*)', url)\n return n_digit_match.group(1) if n_digit_match is not None else None", "def get_review_page_number_from_url(url : str) -> int:\n return int(\n url[url.find(\n REVIEW_PAGE_NO_URL_IDENTIFIER[1]\n ) + len(REVIEW_PAGE_NO_URL_IDENTIFIER[1]):]\n )", "def feature_ctr_for_urls(self, session):\n shows = {}\n clicks = {}\n for url in self.urls:\n shows[url] = 0\n clicks[url] = 0\n\n for query in session.queries:\n for url in query.urls:\n if url in self.urls:\n shows[url] += 1\n for click in query.clicks:\n if click.url_id == url:\n clicks[url] += 1\n break\n ctrs = []\n for url in self.urls:\n if shows[url] > 0:\n ctrs.append(1.0 * clicks[url] / shows[url])\n return [1.0 * sum(ctrs) / len(ctrs)] if len(ctrs) else [0]", "def get_counts():\n raw_response = requests.get(EXTRACTION_URL).json()\n return format_extraction_response(raw_response)", "def __updateVisitCount(self, url, count):\n for index in range(len(self.__history)):\n if url == self.__history[index].url:\n self.__history[index].visitCount = count", "def count_redirects(url):\n try:\n response = requests.get(url, timeout=3)\n if response.history:\n return len(response.history)\n else:\n return 0\n except Exception:\n return '-1'", "def get_citation_needed_count(url):\n\n res = requests.get(url)\n\n content = res.content\n\n soup = bfs(content, 'html.parser')\n\n first_el = soup.find(id='mw-content-text')\n\n find_cites = first_el.find_all(\n class_='noprint Inline-Template Template-Fact')\n\n citations = len(find_cites)\n\n print(f'Number of citations needed are {citations}\\n')\n\n return f'Number of citations needed are {citations}'", "def _url_parser(self, url):\n pattern = re.compile(ur'.*\\_(.*kbit).*')\n match = re.match(pattern, url)\n self.report['url_bitrate'] = int(match.group(1).replace('kbit', ''))\n self.url_bitrate.append(self.report['url_bitrate'])\n self._stats_analysis('url_bitrate', self.url_bitrate)", "def count_publishers(url):\n params = {'rows': 0}\n resp = requests.get(url=url, params=params)\n data = json.loads(resp.text)\n return data['message']['total-results']", "def count_records(url):\n\n\n xml_content = urlopen(url)\n bsObj = BeautifulSoup(xml_content.read(),'lxml') \n xml_data = bsObj.find(attrs = {'name' :'response'})\n total_records = int(xml_data[\"numfound\"])\n return total_records", "def count_ips(url):\n if valid_ip(url['host']):\n return 1\n\n try:\n answers = resolver.query(url['host'], 'A')\n return len(answers)\n except Exception:\n return '-1'", "def parse_page_number(url):\n if '?' not in url:\n return 1\n params = url.split('?')[1].split('=')\n params = {k: v for k, v in zip(params[0::2], params[1::2])}\n if 'page' not in params:\n return 1\n return int(params['page'])", "def number_of_articles():" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get commented novel list
def list_commented_novels(self, page_num=10): count = self.get_count(self.page_commented_novel_list()) if count == 0: return for i in range(1, (count - 1) / page_num + 2): soup = get_soup(self.page_commented_novel_list(i)) if soup is None: continue soup_commented_novel_list = soup.find(id='novelpointlist') if soup_commented_novel_list is not None: li_titles = soup_commented_novel_list.find_all(class_='title') for li_title in li_titles: self.commentedNovels.append(li_title.find('a')['href'][25:-1].encode('unicode-escape'))
[ "def page_commented_novel_list(self, page=1):\n self.correct_page_num(page)\n return 'http://mypage.syosetu.com/mypagenovelhyoka/list/userid/' \\\n + self.id + '/index.php?p=' + str(page)", "def non_comment_lines(self):\n return [_ for _ in self.stripped_whole_lines() if not _.startswith(\"#\")]", "def __get_comments(self, root):\n comments_root = self.__expand_shadow_element_by_tag_name(root, 'mr-comment-list')\n\n list_of_comments = comments_root.find_elements_by_tag_name('mr-comment')\n print ('[*] %d comments' %len(list_of_comments))\n comments = []\n for c in list_of_comments:\n comment_root = self.__expand_shadow_element(c)\n comment_header = comment_root.find_element_by_css_selector('div>div').text.replace('\\n', ' ')\n \n m = re.match(self.comment_pattern, comment_header)\n blank_comment = { 'comment_id':'', 'comment_datetime':'', \n 'comment_author':'', 'comment_message': ' '} \n if m:\n comment_id = m.group(1).strip('\\n\\r ')\n if not 'Deleted' in comment_header:\n message_root = self.__expand_shadow_element_by_css_selector(comment_root, '.comment-body>mr-comment-content')\n lines = message_root.find_elements_by_css_selector('.line')\n\n comments.append({\n 'comment_id': comment_id,\n 'comment_datetime': m.group(4).strip('\\n\\r '),\n 'comment_author' : m.group(3).strip('\\n\\r '),\n 'comment_message': ' '.join([l.text.strip('\\n\\r ') for l in lines]) \n })\n else:\n blank_comment['comment_id'] = comment_id\n comments.append(blank_comment) \n else:\n comments.append(blank_comment) \n return comments", "def get_flattened_comments(self) -> List[Comment]:\n return self.comments.list()", "def GetComments(node):\n return [n for n in node.childNodes if n.nodeType == minidom.Node.COMMENT_NODE]", "def strip_comments(lines: list[str]) -> list[str]:\n global results\n results = []\n for line in lines:\n index = line.find('#')\n if index >= 0:\n modified = line[0:index]\n else:\n modified = line\n modified = modified.strip()\n if len(modified) > 0:\n results.append(modified)\n return results", "def get_comment_tokens(self) -> [str]:\r\n if self.comment:\r\n return self.comment.tokens\r\n return []", "def comments(self):\n comments = self.get_edges() \\\n .get(API_EDGE_TYPE.HAS_COMMENT_FROM, {}) \\\n .values()\n comments.sort(key=lambda x: x.created_ts)\n return comments", "def get_comments(self):\n if self.retrieved:\n raise errors.IllegalState('List has already been retrieved.')\n self.retrieved = True\n return objects.CommentList(self._results, runtime=self._runtime)", "def get_all_comments_at(self, _ea):\t\n\t\tnormal_comment = self.get_normal_comment(_ea)\n\t\trpt_comment = self.get_repeat_comment(_ea)\n\t\tcomment = normal_comment\n\n\t\tif (comment and rpt_comment):\n\t\t\tcomment += \":\" + rpt_command\n\t\t\n\t\treturn comment", "def skip_comments(self):\n return \"\"\"--skip-comments\"\"\"", "def extract_comments(self, sid, text):\n pass", "def test_skipComments(self):\r\n self.spitter.visitNode(Comment('foo'))\r\n self.assertNotIn('foo', ''.join(self.output))", "def test_sales_creditmemo_management_v1_get_comments_list_get(self):\n pass", "def get_comment_list(self, start=0, end=20, order='-publish_time'):\n size = end - start\n prev = next = False\n comments = Comment.objects.order_by(order)[start:end + 1]\n if len(comments) - size > 0:\n next = True\n if start != 0:\n prev = True\n\n return prev, next, comments[start:end]", "def fetch_comments(self):\n new_comments = []\n try:\n comments_gen = self.reddit_obj.get_comments(self.subreddit)\n\n for comment in comments_gen:\n if comment.created_utc > self.end_time:\n continue\n if comment.created_utc < self.start_time:\n break\n new_comments.append({\n 'timestamp': int(comment.created_utc),\n 'message': comment.body,\n 'type': datacluster_pb2.RedditMessage.comment,\n 'subreddit': self.subreddit\n })\n except praw.errors.InvalidSubreddit:\n print \"Invalid Subreddit: no results\"\n return new_comments", "def comments(self):\r\n from .._impl.comments import Comment\r\n cs = []\r\n start = 1\r\n num = 100\r\n nextStart = 0\r\n url = \"%s/sharing/rest/content/items/%s/comments\" % (self._portal.url, self.id)\r\n while nextStart != -1:\r\n params = {\r\n \"f\" : \"json\",\r\n \"start\" : start,\r\n \"num\" : num\r\n }\r\n res = self._portal.con.post(url, params)\r\n for c in res['comments']:\r\n cs.append(Comment(url=\"%s/%s\" % (url, c['id']),\r\n item=self, initialize=True))\r\n start += num\r\n nextStart = res['nextStart']\r\n return cs", "def _get_comment_text():\n comment_samples = [\n \"Malesu mauris nas lum rfusce vehicula bibend. Morbi.\",\n \"Nuncsed quamal felis donec rutrum class ipsumnam teger. Sedin metusd metusdo quamnunc utcras facilis nequen.\",\n \"Adipisci ent neque eger vehicula dis. Miquis auctorpr quamphas purusp phasel duifusce parturi. Ris liberoa ligula lacini risus nean. Arcualiq cubilia aenean nuncnunc ulum fringi uisque abitur rerit setiam. Nean miproin aliquet risusvi tempusp aliquete. Integer nequenu bulum ibulum laoree accumsan ellus mus odio uis. Amet curae ivamus congue aliquama liberofu que.\",\n \"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In justov volutpat mus habitas dapibusc nequenu volutp justo. Quam blandi tur maurisd egesta erossed morbi turpis risus tate. Lacusp facilis class vehicula varius iaculis setiam montes pharetra. Usce ecenas quispr naeos nec nibhphas lacinia roin. Abitur maurisma metusqui justop uscras llam enas. Magnaqu faucibus sduis arcualiq imperd teger egetlor teger.\",\n \"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Conseq tristiq enas duis sociosqu eduis enimsed tudin vel. Lus semnunc risusm nulla parturi atein at placerat. Tiam laut nibhnul turpisn vitaenul eleifen commodo euismo quat posuered. Egestas nullain justop maurisin purusp donec nas liberofu aptent. Nec aliquam tiam puruscra turpisp luctus proin. Lectusin turpisn usce orcivest nullam eget arcuduis tdonec min. Esent cursus vulput aenean bulum lacini congued pretiu. Portamor bulum tate isse llam cidunt estmae.\\n\\nSque leocras fusce nullap fusce convall laoreet nibhnull estsusp. Roin aliquet esent ctetur blandit etiam nequesed viverr. Nislqu sse orciduis lacusp in tasse gravida lla ullam. Itnunc id mauris rerit entum disse lacinia. Oin luctus velit musetiam onec potenti ipsump volutp. Tortor musetiam bibendum onec esent libero esque sim. Enas ras eclass placerat sedin risusut vulput enimdon montes. Rhoncus dolorma estsusp facilis etsed llaut esque cursus. Nisl ullamcor tincid llus nulla iaculis.\",\n ]\n return random.choice(comment_samples)", "def get_comments(comments):\n from utils import quick_encrypt\n if comments is None:\n return []\n elif isinstance(comments, praw.models.reddit.more.MoreComments):\n return []\n elif isinstance(comments, praw.models.reddit.comment.Comment):\n author = None\n if comments.author:\n author = quick_encrypt(comments.author.name)\n return [(comments.body, author)]\n elif isinstance(comments, praw.models.comment_forest.CommentForest):\n combined = []\n for comment in (comments.list()):\n combined = combined + get_comments(comment)\n return combined\n elif isinstance(comments, list):\n return []\n else:\n print(type(comments))\n print(comments)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the standardized Shannon entropy for the given string. (modificada por mim)
def calculate_shannon_entropy(string): #Não é mais necessário fazer essa checagem, já que string não faz mais parte do tipo 'unicode' #if isinstance(string, unicode): # string = string.encode("ascii") ent = 0.0 alphabet = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'] if len(string) < 2: return ent size = float(len(string)) for b in range(15): # Para usar ASCII, troque para 127 freq = string.count(alphabet[b]) if freq > 0: freq = float(freq) / size ent = ent + freq * log2(freq) return -ent/log2(size)
[ "def shannon_entropy(data: str, charset: str = BASE64_CHARS) -> float:\n char_freq = dict.fromkeys(charset, 0)\n\n for char in data:\n if char in char_freq:\n char_freq[char] += 1\n\n entropy = 0.0\n for char in char_freq:\n if char_freq[char] > 0:\n p_x = char_freq[char] * 1.0 / len(data)\n entropy += - p_x * math.log2(p_x)\n\n return entropy", "def entropy(s):\n b = bytearray.fromhex(s)\n freqs = [c / len(b) for c in Counter(b).values()]\n return -sum(f * math.log2(f) for f in freqs)", "def shannon_entropy(self, state_strings):\n symbols = dict.fromkeys(state_strings)\n symbol_probabilities = [float(state_strings.count(symbol)) / len(state_strings) for symbol in symbols]\n H = -sum([p_symbol * math.log(p_symbol, 2.0) for p_symbol in symbol_probabilities])\n return H + 0 # add 0 as a workaround so we don't end up with -0.0", "def compute_shannon(data):\n entropy = 0\n for x in range(256):\n it = float(data.count(x))/len(data)\n if it > 0:\n entropy += - it * math.log(it, 2)\n\n return entropy", "def raw_entropy(seq):\n seq = seq.upper()\n length = float(len(seq))\n prob = [seq.count(base)/length for base in set(seq)]\n return - sum( p * log(p) for p in prob)", "def calcShannonEnt(dataset): \r\n\tnumEntries = len(dataset) #get length\r\n\tlabelCounts = {}\r\n\t#here we get the frequency of the data label\r\n\t#set_trace()\r\n\r\n\tfor featVec in dataset:\r\n\t\tcurrentLabel = featVec[-1] #get the last value in the list. which is the label. eg [1,1, 'yes']\r\n\t\t'''\r\n\t\tif currentLabel not in labelCounts.keys(): #check if the label is not yet in the dictionary\r\n\t\t\tlabelCounts[currentLabel] = 0 #add it with an initial value of zero\r\n\t\tlabelCounts[currentLabel] += 1 #This will increment each time it sees the label.\r\n\t\t'''\r\n\t\tlabelCounts[currentLabel] = labelCounts.get(currentLabel,0) + 1\r\n\tshannonEnt = 0.0\t\r\n\t#here we calculate the log\r\n\tfor key in labelCounts:\r\n\t\tprob = float(labelCounts[key])/numEntries #calculate the probability [each label frequency/dataset length]\r\n\t\tshannonEnt -= prob * log(prob,2) #This is where the entropy formula is been applied P(xi)log2P(xi)\r\n\treturn shannonEnt", "def calcEntropy(tokens):\n # unit = U_BYTE nibble => ASCII ?!\n alphabet = dict()\n # get counts for each word of the alphabet\n for x in tokens:\n if x in alphabet:\n alphabet[x] += 1\n else:\n alphabet[x] = 1\n\n # len(alphabet) would give a dynamic alphabet length.\n # since we are working on bytes, we assume 256.\n alphabet_len = 2\n entropy = 0\n for x in alphabet:\n # probability of value in string\n p_x = float(alphabet[x]) / len(tokens)\n entropy += - p_x * math.log(p_x, alphabet_len)\n\n return entropy", "def entropy(x):\n\treturn stats.entropy(x)", "def entropy(hexstring, bits=128, raw=False):\n if not raw:\n onezero = bin(int(hexstring, 16))[2:]\n else:\n onezero = hexstring\n onezero = onezero.zfill(bits)\n assert len(onezero) == bits\n\n length = float(bits)\n prob = [onezero.count('0') / length, onezero.count('1') / length]\n entropy = -sum([p * math.log(p, 2) for p in prob])\n return entropy", "def shannon_entropy(V):\n E = 0\n for v in V:\n if v<1E-10:\n v=1E-10\n E -= v * math.log(v,2)\n return E", "def shannon_entropy(col, verbose=False):\n\n alpha=list(set(col))\n shannon=list()\n for a in alpha:\n freq = col.count(a)/len(col)\n # math.log() is base e by default\n logf = math.log(freq)\n shannon.append(freq*logf)\n if (verbose):\n print(\"\\tnumber of {0} is {1}\\n\\t\\tfrequency = {2}\\n\\t\\tlog of frequency = {3}\".format(a, col.count(a), freq, logf))\n \n entropy=abs(sum(shannon))\n if (verbose):\n print(\"shannon entropy of col {} is {}\\n\".format(col, entropy))\n return entropy", "def entropy_H(self, data):\n\n if not data:\n return 0.0\n\n occurences = Counter(bytearray(data))\n\n entropy = 0\n for x in occurences.values():\n p_x = float(x) / len(data)\n entropy -= p_x*math.log(p_x, 2)\n\n return entropy", "def compute_entropy(node):\r\n total = len(node)\r\n appearance = sum(node)\r\n not_appearance = len(node) - sum(node)\r\n entropy = 0\r\n if appearance > 0:\r\n entropy -= (appearance / total) * math.log(appearance / total, 2)\r\n if not_appearance > 0:\r\n entropy -= (not_appearance / total) * math.log(not_appearance / total, 2)\r\n return entropy", "def calc_entropy(data):\r\n\r\n col = data[:,-1]\r\n _, counts = np.unique(col, return_counts=True)\r\n entropy = (counts / len(col)) * np.log2(counts / len(col))\r\n entropy = -np.sum(entropy)\r\n ###########################################################################\r\n # END OF YOUR CODE #\r\n ###########################################################################\r\n return entropy", "def sqrt_shannon_entropy(filename):\n data = load_grid_data(filename, \"raw\")\n phenotypes = {}\n for r in data:\n for c in r:\n if phenotypes.has_key(c):\n phenotypes[c] += 1\n else:\n phenotypes[c] = 1\n\n for key in phenotypes.keys():\n phenotypes[key] = sqrt(phenotypes[key])\n\n return entropy(phenotypes)", "def entropy_given_normal_std(self, std_arr):\n entropy = np.log(std_arr) + np.log(np.sqrt(2 * np.pi)) + 0.5\n return entropy", "def bf_shannon_entropy(w: 'Tensor[N, N]') -> 'Tensor[1]':\n Z = torch.zeros(1).double().to(device)\n H = torch.zeros(1).double().to(device)\n for _, weight in all_single_root_trees(w):\n Z += weight\n H += weight * torch.log(weight)\n return torch.log(Z) - H / Z", "def entropy(self):\n sum = 0.0\n base = len(self.alpha)\n for sym in self.alpha:\n p = self.__getitem__(sym)\n if p == 0:\n p = 0.000001\n sum += p * math.log(p, base)\n return -sum", "def calc_entropy(self, species, T, units):\n if '%s_high' % species not in ThermoGenerator.NASA_poly.keys() or '%s_low' % species not in ThermoGenerator.NASA_poly.keys():\n raise ThermoError, \"The given species is not in the NASA polynomial database\"\n\n temp = self.unit_converter.convert_units(T[0], T[1], 'K')\n if temp < 1000:\n qual = 'low'\n else:\n qual = 'high'\n polys = ThermoGenerator.NASA_poly['%s_%s' % (species, qual)]\n S_SI = ThermoGenerator.R[0] * (polys[0]*np.log(temp) + polys[1] * temp + polys[2] * np.power(temp,2)/2.0 + polys[3] * np.power(temp,3)/3.0 + polys[4] * np.power(temp,4)/4.0+polys[6])\n return self.unit_converter.convert_units(S_SI, ThermoGenerator.R[1], units)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }