query
stringlengths 9
9.05k
| document
stringlengths 10
222k
| metadata
dict | negatives
sequencelengths 30
30
| negative_scores
sequencelengths 30
30
| document_score
stringlengths 4
10
| document_rank
stringclasses 2
values |
---|---|---|---|---|---|---|
Test Vimeo iframe tag generation | def test_vimeo(disable_vimeo_api_query):
sample = ".. vimeo:: VID\n :height: 400\n :width: 600"
html = get_html_from_rst(sample)
assert_html_contains(
html,
"iframe",
attributes={
"src": ("https://player.vimeo.com/" "video/VID"),
"height": "400",
"width": "600",
},
) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_embed_ok(self):\n self.go200('minus_upload')\n self.formfile('minus_upload', 'file', AUDIO_FILE)\n self.fv('minus_upload', 'id_embed_video', YOUTUBE_URL) \n self.submit200()\n self.notfind(\"Невірний\")\n self.show()\n self.find(\"youtube_video\")\n self.find(\"<object width\")\n self.go200('minus_upload')\n self.formfile('minus_upload', 'file', NOTAGS_FILE)\n self.fv('minus_upload', 'id_embed_video', YOUTUBE_EMBED) \n self.submit200()\n self.notfind(\"Невірний\")\n self.show()\n self.find(\"<object width\")",
"def vimeo(code,width=400,height=250):\n return XML(\"\"\"<object width=\"%(width)s\" height=\"%(height)s\"><param name=\"allowfullscreen\" value=\"true\" /><param name=\"allowscriptaccess\" value=\"always\" /><param name=\"movie\" value=\"http://vimeo.com/moogaloop.swf?clip_id=%(code)s&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1\" /><embed src=\"http://vimeo.com/moogaloop.swf?clip_id=%(code)s&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" allowscriptaccess=\"always\" width=\"%(width)s\" height=\"%(height)s\"></embed></object>\"\"\" % dict(code=code, width=width, height=height))",
"def test_youtube_iframe():\n\n sample = \".. youtube:: YID\\n :height: 400\\n :width: 600\"\n html = get_html_from_rst(sample)\n assert_html_contains(\n html,\n \"iframe\",\n attributes={\n \"src\": (\n \"https://www.youtube-nocookie.com\"\n \"/embed/YID?rel=0&\"\n \"wmode=transparent\"\n ),\n \"height\": \"400\",\n \"width\": \"600\",\n \"frameborder\": \"0\",\n \"allowfullscreen\": \"\",\n \"allow\": \"encrypted-media\",\n },\n )",
"def _handle_iframe_tag(self, attrs):\n\n def _get_source_from_attrs(attrs):\n for key, value in attrs:\n if key == \"src\":\n return value\n\n url = _get_source_from_attrs(attrs)\n video_url = \"\"\n video_id = url.split(\"?\")[0].rsplit(\"/\", 1)[1]\n if \"vimeo\" in url:\n # We need to get the video id from the url attribute and create a new URL.\n video_url = f\"https://vimeo.com/{video_id}\"\n elif \"youtube\" in url:\n # Not sure if youtube has been removed or not, but adding youtube videos seems impossible\n video_url = f\"https://youtu.be/{video_id}\"\n else:\n # Unclear what providers are supported or notself.\n # Full list https://github.com/wagtail/wagtail/blob/main/wagtail/embeds/oembed_providers.py\n return\n\n return f\"<embed embedtype='media' url='{video_url}'/>\"",
"def test_soundcloud_iframe():\n\n sample = \".. soundcloud:: SID\\n :height: 400\\n :width: 600\"\n html = get_html_from_rst(sample)\n assert_html_contains(\n html,\n \"iframe\",\n attributes={\n \"src\": (\n \"https://w.soundcloud.com/player/\"\n \"?url=http://api.soundcloud.com/\"\n \"tracks/SID\"\n ),\n \"height\": \"400\",\n \"width\": \"600\",\n },\n )",
"def __init__(self, url, params=None):\n super(VimeoVideo, self).__init__(url, params)\n self.video_id = self.get_video_id()\n self.thumbnail_url = ''",
"def get_embed_url(self):\n if not self.get_video_id():\n return ''\n \n return 'https://player.vimeo.com/video/%s' % self.get_video_id()",
"def test_video_embed(\n logged_in_client, settings\n): # pylint: disable=redefined-outer-name\n client, user = logged_in_client\n settings.GA_DIMENSION_CAMERA = \"camera1\"\n settings.GA_TRACKING_ID = \"UA-xyz-1\"\n settings.ENVIRONMENT = \"test\"\n settings.VERSION = \"1.2.3\"\n settings.ENABLE_VIDEO_PERMISSIONS = False\n settings.USE_WEBPACK_DEV_SERVER = False\n\n videofileHLS = VideoFileFactory(\n hls=True,\n video__collection__owner=user,\n video__multiangle=True,\n video__status=\"Complete\",\n )\n video = videofileHLS.video\n url = reverse(\"video-embed\", kwargs={\"video_key\": video.hexkey})\n response = client.get(url)\n js_settings_json = json.loads(response.context_data[\"js_settings_json\"])\n assert js_settings_json == {\n \"video\": VideoSerializer(video).data,\n \"gaTrackingID\": settings.GA_TRACKING_ID,\n \"release_version\": settings.VERSION,\n \"environment\": settings.ENVIRONMENT,\n \"sentry_dsn\": \"\",\n \"ga_dimension_camera\": settings.GA_DIMENSION_CAMERA,\n \"public_path\": \"/static/bundles/\",\n \"cloudfront_base_url\": settings.VIDEO_CLOUDFRONT_BASE_URL,\n \"user\": user.username,\n \"email\": user.email,\n \"is_app_admin\": False,\n \"support_email_address\": settings.EMAIL_SUPPORT,\n \"FEATURES\": {\n \"ENABLE_VIDEO_PERMISSIONS\": False,\n \"VIDEOJS_ANNOTATIONS\": False,\n },\n }",
"def test_video_constructor(self):\r\n context = self.item_descriptor.render('student_view').content\r\n\r\n sources = {\r\n 'main': u'example.mp4',\r\n u'mp4': u'example.mp4',\r\n u'webm': u'example.webm',\r\n }\r\n\r\n expected_context = {\r\n 'ajax_url': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',\r\n 'autoplay': settings.FEATURES.get('AUTOPLAY_VIDEOS', False),\r\n 'data_dir': getattr(self, 'data_dir', None),\r\n 'display_name': u'A Name',\r\n 'end': 3610.0,\r\n 'id': self.item_descriptor.location.html_id(),\r\n 'show_captions': 'true',\r\n 'handout': None,\r\n 'sources': sources,\r\n 'speed': 'null',\r\n 'general_speed': 1.0,\r\n 'start': 3603.0,\r\n 'saved_video_position': 0.0,\r\n 'sub': u'a_sub_file.srt.sjson',\r\n 'track': None,\r\n 'youtube_streams': create_youtube_string(self.item_descriptor),\r\n 'yt_test_timeout': 1500,\r\n 'yt_api_url': 'www.youtube.com/iframe_api',\r\n 'yt_test_url': 'gdata.youtube.com/feeds/api/videos/',\r\n 'transcript_download_format': 'srt',\r\n 'transcript_download_formats_list': [{'display_name': 'SubRip (.srt) file', 'value': 'srt'}, {'display_name': 'Text (.txt) file', 'value': 'txt'}],\r\n 'transcript_language': u'en',\r\n 'transcript_languages': json.dumps(OrderedDict({\"en\": \"English\", \"uk\": u\"Українська\"})),\r\n 'transcript_translation_url': self.item_descriptor.xmodule_runtime.handler_url(\r\n self.item_descriptor, 'transcript', 'translation'\r\n ).rstrip('/?'),\r\n 'transcript_available_translations_url': self.item_descriptor.xmodule_runtime.handler_url(\r\n self.item_descriptor, 'transcript', 'available_translations'\r\n ).rstrip('/?'),\r\n }\r\n\r\n self.assertEqual(\r\n context,\r\n self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context),\r\n )",
"def test_techtv_detail_embed_url(\n mock_user_moira_lists, user_view_list_data, logged_in_apiclient, url\n):\n client = logged_in_apiclient[0]\n ttv_video = TechTVVideoFactory(video=user_view_list_data.video)\n mock_user_moira_lists.return_value = {user_view_list_data.moira_list.name}\n result = client.get(url.format(ttv_video.ttv_id))\n assert result.status_code == status.HTTP_200_OK\n assert (\n json.loads(result.context_data[\"js_settings_json\"])[\"video\"][\"key\"]\n == user_view_list_data.video.hexkey\n )\n assert isinstance(result.context_data[\"view\"], TechTVEmbed)",
"def bb_youtube(hit):\n video = hit.group(1)\n return '<object width=\"425\" height=\"350\"><param name=\"movie\" value=\"http://www.youtube.com/v/%s\"></param><param name=\"wmode\" value=\"transparent\"></param><embed src=\"http://www.youtube.com/v/%s\" type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"425\" height=\"350\"></embed></object>' % (video, video)",
"async def igvideo(self, ctx, url):\n response = requests.get(url.replace(\"`\", \"\"), headers={\"Accept-Encoding\": \"utf-8\"})\n tree = html.fromstring(response.content)\n results = tree.xpath('//meta[@content]')\n sources = []\n for result in results:\n try:\n if result.attrib['property'] == \"og:video\":\n sources.append(result.attrib['content'])\n except KeyError:\n pass\n if sources:\n await ctx.send(sources[0])\n self.logger.info(misolog.format_log(ctx, f\"Success\"))\n else:\n await ctx.send(\"Found nothing, sorry!\")\n self.logger.warning(misolog.format_log(ctx, f\"Found nothing\"))",
"def _render_no_tracking(self, video_id):\n you_tube_url = (\n 'https://www.youtube.com/embed/%s'\n '?feature=player_embedded&rel=0') % video_id\n iframe = cElementTree.XML(\"\"\"\n<div class=\"gcb-video-container\">\n <iframe class=\"youtube-player\" title=\"YouTube Video Player\"\n type=\"text/html\" frameborder=\"0\" allowfullscreen=\"allowfullscreen\">\n </iframe>\n</div>\"\"\")\n iframe[0].set('src', you_tube_url)\n return iframe",
"def video():\n return render_template('video.html')",
"def get_video(soup, data, dictionary):\n video_markup = [] \n VIDEOS_TAGS = ['iframe', 'embed', 'object', 'video']\n VIDEO_PROVIDERS = ['youtube', 'vimeo', 'dailymotion', 'kewego']\n #print \",\".join(VIDEOS_TAGS)\n for t in VIDEOS_TAGS:\n if soup.find_all(t):\n for vid in soup.find_all(t):\n # youtube og vimeo kan avsløres ver src atributt til iframe tag\n #print vid\n for prov in VIDEO_PROVIDERS:\n if prov in vid['src']:\n video_markup.append(vid)\n\n #print video_markup \n #print \"antall videoer (ikke nrk): \", len(video_markup)\n\n # nrk-videoer (lastet via js, og må trikses med)\n # ser ut som eksistensen av en data-video-id=\"118648\" kan være en bedre indikator.. \n nrk_videoer = soup.select('figure.video')\n #print \"antall nrk-videoer: \", len(nrk_videoer)\n\n\n dictionary['video_files'] = len(video_markup)\n dictionary['video_files_nrk'] = len(nrk_videoer)\n return",
"def test_video_constructor(self):\r\n sources = {\r\n 'main': u'example.mp4',\r\n u'mp4': u'example.mp4',\r\n u'webm': u'example.webm',\r\n }\r\n\r\n context = self.item_descriptor.render('student_view').content\r\n\r\n expected_context = {\r\n 'ajax_url': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',\r\n 'data_dir': getattr(self, 'data_dir', None),\r\n 'show_captions': 'true',\r\n 'handout': None,\r\n 'display_name': u'A Name',\r\n 'end': 3610.0,\r\n 'id': self.item_descriptor.location.html_id(),\r\n 'sources': sources,\r\n 'speed': 'null',\r\n 'general_speed': 1.0,\r\n 'start': 3603.0,\r\n 'saved_video_position': 0.0,\r\n 'sub': u'a_sub_file.srt.sjson',\r\n 'track': None,\r\n 'youtube_streams': '1.00:OEoXaMPEzfM',\r\n 'autoplay': settings.FEATURES.get('AUTOPLAY_VIDEOS', True),\r\n 'yt_test_timeout': 1500,\r\n 'yt_api_url': 'www.youtube.com/iframe_api',\r\n 'yt_test_url': 'gdata.youtube.com/feeds/api/videos/',\r\n 'transcript_download_format': 'srt',\r\n 'transcript_download_formats_list': [{'display_name': 'SubRip (.srt) file', 'value': 'srt'}, {'display_name': 'Text (.txt) file', 'value': 'txt'}],\r\n 'transcript_language': u'en',\r\n 'transcript_languages': '{\"en\": \"English\"}',\r\n 'transcript_translation_url': self.item_descriptor.xmodule_runtime.handler_url(\r\n self.item_descriptor, 'transcript', 'translation'\r\n ).rstrip('/?'),\r\n 'transcript_available_translations_url': self.item_descriptor.xmodule_runtime.handler_url(\r\n self.item_descriptor, 'transcript', 'available_translations'\r\n ).rstrip('/?')\r\n }\r\n\r\n self.assertEqual(\r\n context,\r\n self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context),\r\n )",
"def test_youtube_iframe_start_at():\n\n sample = \".. youtube:: YID\\n :height: 400\\n :width: 600\\n :start_at: 60\"\n html = get_html_from_rst(sample)\n assert_html_contains(\n html,\n \"iframe\",\n attributes={\n \"src\": (\n \"https://www.youtube-nocookie.com\"\n \"/embed/YID?rel=0&\"\n \"wmode=transparent&start=60\"\n ),\n \"height\": \"400\",\n \"width\": \"600\",\n \"frameborder\": \"0\",\n \"allowfullscreen\": \"\",\n \"allow\": \"encrypted-media\",\n },\n )",
"def get_url(self):\n if not self.get_video_id():\n return ''\n \n return 'http://www.vimeo.com/%s' % self.get_video_id()",
"def test_embed(self):\r\n self.assertHtmlEqual(OpenEndedChild.sanitize_html(self.embed_dirty), self.embed_clean)",
"def test_691(self):\r\n test_id = 691\r\n sel = self.selenium\r\n testpage = \"/pagedemo/nytimes_youtube_embed\"\r\n subtextfile = os.path.join(testvars.MSTestVariables[\"DataDirectory\"],\"OctopusGarden.txt\")\r\n sel.open(testpage)\r\n sel.wait_for_page_to_load(testvars.timeout)\r\n sel.window_maximize()\r\n mslib.wait_for_element_present(self,sel,testvars.WebsiteUI[\"SubtitleMe_menu\"])\r\n time.sleep(5)\r\n sel.get_eval('this.browserbot.getUserWindow().unisubs.widget.Widget.getAllWidgets()[0].openMenu()')\r\n widget.open_starter_dialog(self,sel)\r\n widget.starter_dialog_fork(self,sel,to_lang='hr')\r\n widget.transcribe_video(self, sel, subtextfile)\r\n widget.sync_video(self, sel, subtextfile)\r\n widget.site_login_from_widget_link(self,sel)\r\n #verify subs still present\r\n print \"verifying subtitles are still present\"\r\n sel.select_window(\"null\")\r\n mslib.wait_for_element_present(self,sel,\"css=.unisubs-titlesList\")\r\n widget.verify_sub_text(self,sel,subtextfile)\r\n if sel.is_element_present(\"css=.unisubs-modal-login\"): #Login\r\n sel.click(\"css=.unisubs-log\")\r\n widget.site_login_auth(self,sel)\r\n sel.select_window(\"null\")\r\n widget.submit_sub_edits(self,sel,offsite=True)",
"def test_public_component_preview_html(self):\r\n self.validate_preview_html(self.video, 'student_view',\r\n can_edit=True, can_reorder=True, can_add=False)",
"def test_ui_load_video_to_video_initialized(uuid_namespace, event, platform_url):\n\n event.context.course_id = \"\"\n event.context.org_id = \"\"\n event.context.user_id = \"1\"\n event.session = \"af45a0e650c4a4fdb0bcde75a1e4b694\"\n session_uuid = \"af45a0e6-50c4-a4fd-b0bc-de75a1e4b694\"\n event_str = event.json()\n event = json.loads(event_str)\n xapi_event = convert_dict_event(\n event, event_str, UILoadVideoToVideoInitialized(uuid_namespace, platform_url)\n )\n xapi_event_dict = json.loads(xapi_event.json(exclude_none=True, by_alias=True))\n\n assert xapi_event_dict == {\n \"id\": str(uuid5(UUID(uuid_namespace), event_str)),\n \"actor\": {\"account\": {\"homePage\": platform_url, \"name\": \"1\"}},\n \"verb\": {\"id\": \"http://adlnet.gov/expapi/verbs/initialized\"},\n \"context\": {\n \"contextActivities\": {\n \"category\": [\n {\n \"id\": \"https://w3id.org/xapi/video\",\n \"definition\": {\n \"type\": \"http://adlnet.gov/expapi/activities/profile\"\n },\n }\n ],\n },\n \"extensions\": {\n \"https://w3id.org/xapi/video/extensions/length\": 0.0,\n \"https://w3id.org/xapi/video/extensions/session-id\": session_uuid,\n \"https://w3id.org/xapi/video/extensions/user-agent\": event[\"agent\"],\n },\n },\n \"object\": {\n \"id\": platform_url\n + \"/xblock/block-v1:\"\n + event[\"context\"][\"course_id\"]\n + \"-course-v1:+type@video+block@\"\n + event[\"event\"][\"id\"],\n \"definition\": {\n \"type\": \"https://w3id.org/xapi/video/activity-type/video\",\n \"name\": {\"en-US\": event[\"event\"][\"id\"]},\n },\n },\n \"timestamp\": event[\"time\"],\n \"version\": \"1.0.0\",\n }",
"def test_iframe(self):\r\n self.assertRegexpMatches(OpenEndedChild.sanitize_html(self.iframe_dirty), self.iframe_clean)",
"def test_ui_play_video_to_video_played(uuid_namespace, event, platform_url):\n\n event.context.course_id = \"\"\n event.context.org_id = \"\"\n event.context.user_id = \"1\"\n event.session = \"af45a0e650c4a4fdb0bcde75a1e4b694\"\n session_uuid = \"af45a0e6-50c4-a4fd-b0bc-de75a1e4b694\"\n event_str = event.json()\n event = json.loads(event_str)\n xapi_event = convert_dict_event(\n event, event_str, UIPlayVideoToVideoPlayed(uuid_namespace, platform_url)\n )\n xapi_event_dict = json.loads(xapi_event.json(exclude_none=True, by_alias=True))\n assert xapi_event_dict == {\n \"id\": str(uuid5(UUID(uuid_namespace), event_str)),\n \"actor\": {\"account\": {\"homePage\": platform_url, \"name\": \"1\"}},\n \"verb\": {\"id\": \"https://w3id.org/xapi/video/verbs/played\"},\n \"object\": {\n \"id\": platform_url\n + \"/xblock/block-v1:\"\n + event[\"context\"][\"course_id\"]\n + \"-course-v1:+type@video+block@\"\n + event[\"event\"][\"id\"],\n \"definition\": {\n \"type\": \"https://w3id.org/xapi/video/activity-type/video\",\n \"name\": {\"en-US\": event[\"event\"][\"id\"]},\n },\n },\n \"result\": {\n \"extensions\": {\n \"https://w3id.org/xapi/video/extensions/time\": event[\"event\"][\n \"currentTime\"\n ]\n }\n },\n \"context\": {\n \"contextActivities\": {\n \"category\": [\n {\n \"id\": \"https://w3id.org/xapi/video\",\n \"definition\": {\n \"type\": \"http://adlnet.gov/expapi/activities/profile\"\n },\n }\n ],\n },\n \"extensions\": {\n \"https://w3id.org/xapi/video/extensions/session-id\": session_uuid,\n },\n },\n \"timestamp\": event[\"time\"],\n \"version\": \"1.0.0\",\n }",
"def _render_with_tracking(self, video_id):\n video_id = jinja_utils.js_string_raw(video_id)\n uid = common_utils.generate_instance_id()\n dom = cElementTree.XML(\"\"\"\n<p>\n <script></script>\n <script></script>\n</p>\"\"\")\n dom.attrib['id'] = uid\n dom[0].attrib['src'] = os.path.join(RESOURCE_FOLDER, 'youtube_video.js')\n dom[1].text = 'gcbTagYoutubeEnqueueVideo(\"%s\", \"%s\");' % (video_id, uid)\n return dom",
"def AnnotateVideo(self, request, context):\n context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)",
"def getM3u8(driver, urlWebContainVideo):\n try:\n driver.get(urlWebContainVideo)\n time.sleep(SLEEP_TIME)\n\n # with open(\"dev_sth/h1.html\", \"w\") as f:\n # f.write(driver.page_source)\n fileTitle = driver.title\n print(\"fileTitle:\",fileTitle)\n\n folderName = driver.find_element_by_xpath('//ol[@aria-labelledby]/li[2]/a').get_attribute(\"innerHTML\")\n print(\"folderName:\",folderName)\n\n iframe_inner_html = driver.find_element_by_tag_name('iframe').get_attribute('src')\n # print(\"iframe_inner_html:\",iframe_inner_html)\n\n driver.get(iframe_inner_html)\n time.sleep(SLEEP_TIME)\n\n # with open(\"iframe.html\", \"w\") as f:\n # f.write(driver.page_source)\n\n a_doplayer_onclick = driver.find_element_by_xpath(\"//a[contains(@onclick,'doPlayer')]\").get_attribute('onclick')\n # print(a_doplayer_onclick)\n\n strRemovedoPlayer = a_doplayer_onclick.split('(')[1]\n strRemoveSecondThird = strRemovedoPlayer.split(',')[0]\n pieces = strRemoveSecondThird[1:-1].split('/')\n urlFileAWS = 'https://denawswz.uscden.net/aws/_definst_/smil:amazons3/gwz/' + pieces[0] + '/' + pieces[0] + '.smil/playlist.m3u8'\n print('urlFileAWS:', urlFileAWS)\n\n time.sleep(SLEEP_TIME)\n \n item = {\n \"foldername\": folderName,\n \"filetitle\": fileTitle,\n \"url\": urlFileAWS\n }\n return item\n except:\n return None",
"def embed():",
"def iframe(src, width=400, height=300):\n return TAG.iframe(_src=src, _width=width, _height=height)",
"def render_external(plugin, **kwargs):\n\n html = oembed_html(plugin.url)\n if 'youtube.com' in html:\n return mark_safe(\n '<div class=\"flex-video widescreen\">{}</div>'.format(html))\n if 'vimeo.com' in html:\n return mark_safe(\n '<div class=\"flex-video widescreen vimeo\">{}</div>'.format(html))\n return mark_safe(html)"
] | [
"0.6765384",
"0.6609938",
"0.6272188",
"0.6248358",
"0.6134915",
"0.59213513",
"0.5919659",
"0.57093745",
"0.5658802",
"0.5614822",
"0.5593409",
"0.5576847",
"0.552594",
"0.5473205",
"0.54101515",
"0.5403207",
"0.5376431",
"0.53059375",
"0.52948874",
"0.52918184",
"0.52411723",
"0.52288073",
"0.5228264",
"0.5212678",
"0.5209401",
"0.51961327",
"0.5191054",
"0.51845914",
"0.5183895",
"0.51685685"
] | 0.7844545 | 0 |
A base config of LocaleBorg. | def localeborg_base():
LocaleBorg.reset()
assert not LocaleBorg.initialized
LocaleBorg.initialize({}, "en")
assert LocaleBorg.initialized
assert LocaleBorg().current_lang == "en"
try:
yield
finally:
LocaleBorg.reset()
assert not LocaleBorg.initialized | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def config(settings):\n\n #T = current.T\n\n # Pre-Populate\n settings.base.prepopulate.append(\"locations/TH\")\n\n # Uncomment to restrict to specific country/countries\n settings.gis.countries.append(\"TH\")\n\n # -------------------------------------------------------------------------\n # L10n (Localization) settings\n settings.L10n.languages[\"th\"] = \"Thai\"\n # Default Language (put this in custom template if-required)\n #settings.L10n.default_language = \"th\"\n # Default timezone for users\n settings.L10n.timezone = \"Asia/Bangkok\"\n # Default Country Code for telephone numbers\n settings.L10n.default_country_code = 66\n\n settings.fin.currencies[\"THB\"] = \"Baht\"\n settings.fin.currency_default = \"THB\"",
"def config():",
"def config():",
"def base_config():\n return deepcopy(__CONFIG)",
"def configuration():",
"def init_config(self):\n pass",
"def generate_config():\n\n return {\n \"email_subject\": DEFAULT_EMAIL_SUBJECT,\n \"from_email\": DEFAULT_FROM_EMAIL,\n \"to_email\": DEFAULT_TO_EMAIL,\n \"url\": DEFAULT_URL,\n \"start_value\": DEFAULT_START_VALUE,\n \"look_ahead\": DEFAULT_LOOK_AHEAD,\n \"slide_window\": DEFAULT_SLIDE_WINDOW,\n }",
"def default_configs(cls):\n config: dict = super().default_configs()\n\n config.update({\n \"file_ext\": '.txt',\n \"num_sent_per_doc\": -1,\n \"doc_break_str\": None,\n \"column_format\": cls._DEFAULT_FORMAT,\n \"entity_mention_class\": None\n })\n return config",
"def default_configs(cls):\n config = super().default_configs()\n config['file_ext'] = '.txt'\n return config",
"def config( **kwargs ):",
"def default_configs(cls):\n config = super().default_configs()\n config.update(\n {\n \"entry_type\": \"ft.onto.base_ontology.Document\",\n \"model_name\": \"ktrapeznikov/biobert_v1.1_pubmed_squad_v2\",\n \"question\": \"Where do I live\",\n \"max_answer_len\": 15,\n \"cuda_devices\": -1,\n \"handle_impossible_answer\": False,\n }\n )\n return config",
"def config(self):\n pass",
"def config(self):\n pass",
"def __init__(self):\n locale_dir = resource_filename(__name__, 'locale')\n add_domain(self.env.path, locale_dir)",
"def configure(self, engine):\n # TODO: Set a units code as well\n code = engine.get_lang_code('basic', 'en')\n self['config']['StdReport']['BasicReport']['lang'] = code\n return True",
"def _default_config(cls):\n return dict()",
"def __init__(self):\n self.ext_folder = ckan_config.get('ckanext.needupdate.ext_folder', '/usr/lib/ckan/default/src')\n self.ext_prefix = ckan_config.get('ckanext.needupdate.ext_folder', 'ckanext-')\n self.ext_sufix = ckan_config.get('ckanext.needupdate.ext_folder', '')",
"def initialize_from_config(self):",
"def config(self):\n raise NotImplementedError",
"def config(settings):\n\n #T = current.T\n\n # PrePopulate data\n settings.base.prepopulate += (\"SHARE/LK\",)\n settings.base.prepopulate_demo += (\"SHARE/Demo\",)\n\n # Finance settings\n settings.fin.currencies = {\n #\"EUR\" : \"Euros\",\n #\"GBP\" : \"Great British Pounds\",\n \"LKR\" : \"Sri Lanka Rupees\",\n \"USD\" : \"United States Dollars\",\n }\n settings.fin.currency_default = \"USD\"",
"def get_full_config(self):\n\n raise Exception(\"Child classes must override get_full_config()\")",
"def get_default_config(self):\n config = super(NumaCollector, self).get_default_config()\n config.update(\n {\n \"path\": \"numa\",\n \"bin\": self.find_binary(\"numactl\"),\n }\n )\n\n return config",
"def _default_config(self):\n return {\n 'penalty': 'l1',\n 'solver': 'liblinear'\n }",
"def get_config_template() -> dict:\n return {\n VENE_PAYMENTS_BAMBORA_API_URL: (str, \"https://payform.bambora.com/pbwapi\"),\n VENE_PAYMENTS_BAMBORA_API_KEY: str,\n VENE_PAYMENTS_BAMBORA_API_SECRET: str,\n VENE_PAYMENTS_BAMBORA_PAYMENT_METHODS: list,\n }",
"def defaultconfig(self):\r\n\r\n config_data = {\r\n \"path_to_database\": \"FUDB/FOLLOWUP.DB\",\r\n \"path_to_frontend\": \"FUDB/\",\r\n \"path_to_dcs_info\": \"FUDB/\",\r\n \"path_to_bin\": \"bin/\",\r\n \"path_to_excels_exported_from_database\": \"excels exported/\",\r\n \"path_to_excels_to_be_imported_in_database\": \"excels to be imported/\",\r\n \"path_to_new_opfiles\": \"DC BATCHES IN WORK/0 NEW/\",\r\n \"path_to_batches_unassigned\": \"DC BATCHES IN WORK/1 UNASSIGNED/\",\r\n \"path_to_batches_prepfiles\": \"DC BATCHES IN WORK/2 PREPARED FILES/\",\r\n \"path_to_batches_assigned\": \"DC BATCHES IN WORK/3 ASSIGNED/\",\r\n \"path_to_batches_tobechecked\": \"DC BATCHES IN WORK/4 TO BE CHECKED/\",\r\n \"path_to_batches_tbimported\": \"DC BATCHES IN WORK/5 TO BE IMPORTED/\",\r\n \"path_to_batches_finished\": \"DC BATCHES IN WORK/6 FINISHED/\",\r\n \"path_to_batches_instandby\": \"DC BATCHES IN WORK/7 IN STANDBY/\",\r\n \"path_to_batches_unrecordable\": \"DC BATCHES IN WORK/8 UNRECORDABLE/\",\r\n \"batch_status_options_responsible\": \"PREP. OP FILE, IMPORTATION & SPLIT FILE, RELIABILITY & DATA UPGRADE, CHECK OP FILE, CHECK SPLIT FILE, CHECK FRONT END, **TO BE CHECKED\",\r\n \"batch_status_options_proofreader\": \"OP FILE OK, SPLIT FILE OK, FRONT END OK, **TO BE IMPORTED, **FINISHED, **REWORK, **STANDBY, **UNRECORDABLE\",\r\n \"batch_status_options_overall\": \"ONGOING, STANDBY, FINISHED, UNRECORDABLE\",\r\n \"aircrafts\": \"A300, A300-600, A310, A320, A330, A340, A350, A380\",\r\n \"split_batch_factor\": \"2, 3, 4, 5, 6, 7, 8, 9\",\r\n \"IDlentgh\": \"6\",\r\n \"port\": \"5000\"\r\n }\r\n \r\n if not os.path.isfile(os.path.join(self.cwd, \"config.json\")):\r\n self.func.write_json(config_data, self.cwd, fname=\"config.json\")",
"def get_config_template(self) -> cconfig.Config:",
"def __init__(self,MODULE_NAME='auto_amqp',config=None):\n newConfig = { MODULE_NAME : DEFAULT_CONFIG}\n Configurable.__init__(self,newConfig)\n self.load_conf(config)\n self.MODULE_NAME = MODULE_NAME",
"def load_config(self):\n pass",
"def cg_config():\n return {}",
"def config(self):\n return {}"
] | [
"0.64866304",
"0.61988604",
"0.61988604",
"0.61805487",
"0.60943705",
"0.60545963",
"0.6005034",
"0.5965607",
"0.5960212",
"0.593771",
"0.5922106",
"0.5899246",
"0.5899246",
"0.58565474",
"0.5805839",
"0.57934225",
"0.5767726",
"0.57531476",
"0.57386273",
"0.5731498",
"0.5722784",
"0.57159156",
"0.57026625",
"0.56979084",
"0.56597537",
"0.56474984",
"0.56438434",
"0.5641331",
"0.5632404",
"0.56214154"
] | 0.6423912 | 1 |
Create html output from rst string | def get_html_from_rst(rst):
compiler = nikola.plugins.compile.rest.CompileRest()
compiler.set_site(FakeSite())
return compiler.compile_string(rst)[0] | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def rst_to_html(input_string, source_path=None, destination_path=None,\n input_encoding='unicode', doctitle=1, initial_header_level=1):\n overrides = {'input_encoding': input_encoding,\n 'doctitle_xform': doctitle,\n 'initial_header_level': initial_header_level,\n # the next two are for security reasons, to prevent malicious\n # insertion of raw html code.\n 'file_insertion_enabled': False,\n 'raw_enabled': False,\n }\n parts = core.publish_parts(\n source=input_string, source_path=source_path,\n destination_path=destination_path,\n writer_name='html', settings_overrides=overrides)\n return parts['html_body']",
"def htmlise(s):\n return '<div><pre class=\"tablecell\">' + html.escape(s) + '</pre></div>'",
"def sqlhtml(input):\n output=sql(html(input))\n return output",
"def gen_html_output(strs,q):\n res = []\n res.append('<html>\\n')\n res.append('<head><title>SecPoint.com GoogleDB queries strings</title></head>\\n')\n res.append('<body>\\n')\n res.append('<p>Generated by: <a href=\"http://www.secpoint.com/\">SecPoint.com</a> GoogleDB tool</p>\\n')\n res.append('\\t<ul>\\n')\n for (x,v) in zip(strs,q):\n res.append('\\t\\t<li><a href=\"%s\">%s</a></li>\\n'%(v,x))\n res.append('\\t</ul>\\n')\n res.append('</body>\\n</html>')\n return res",
"def rest2html(s):\n return core.publish_string(s, writer=html_fragment_writer)",
"def gen_rst(txt):\n res = \"\"\n title_block = get_title_block(txt)\n title_rst = gen_title_rst(title_block)\n res += title_rst\n # add a blank line just to be sure\n res += \"\\n\"\n fun_blocks = get_fun_blocks(txt)\n for (name, fun_block) in fun_blocks:\n fun_rst = gen_fun_rst(name, fun_block)\n res += fun_rst\n return res",
"def output_to_html(string_data):\n raise NotImplementedError(\"This function is not yet Implemented!\")",
"def outputHtml(s):\n htmlFile.write(s + \"\\n\")",
"def generate_html(self):\n html_text_1 = \"\"\"\n <div class=\"concept\">\n\n \t\t<div class=\"concept-title\">\n\n \t\t\t\t\"\"\" + self.title\n\n html_text_2 = \"\"\"\n \t\t</div>\n\n \t\t<div class=\"concept-description\">\n\n\t\t <p>\n\t\t\t\n \t\t \t\t\"\"\" + self.description + \"\"\" \n \n </p>\"\"\"\n\n html_text_3 = '''\n\n \t\t</div>\n\n </div>'''\n\n return html_text_1 + html_text_2 + html_text_3",
"def get_html(self):\r\n # TODO: why are there nested html tags here?? Why are there html tags at all, in fact?\r\n html = '<html><html>%s</html><html>%s</html></html>' % (\r\n self.mathstr, saxutils.escape(self.xml.tail))\r\n try:\r\n xhtml = etree.XML(html)\r\n except Exception as err:\r\n if self.system.DEBUG:\r\n msg = '<html><div class=\"inline-error\"><p>Error %s</p>' % (\r\n str(err).replace('<', '<'))\r\n msg += ('<p>Failed to construct math expression from <pre>%s</pre></p>' %\r\n html.replace('<', '<'))\r\n msg += \"</div></html>\"\r\n log.error(msg)\r\n return etree.XML(msg)\r\n else:\r\n raise\r\n return xhtml",
"def html_wrapper(content):\n\n header = '''<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <title>''' + SITE_NAME + '''</title>\n</head>\n<body>\n'''\n\n footer = '''\n</body>\n</html>'''\n return header + content + footer",
"def rstjinja(app, docname, source):\n # Make sure we're outputting HTML\n if app.builder.format != 'html':\n return\n src = source[0]\n rendered = app.builder.templates.render_string(src, app.config.html_context)\n source[0] = rendered",
"def rstjinja(app, docname, source):\n # Make sure we're outputting HTML\n if app.builder.format != \"html\":\n return\n src = source[0]\n rendered = app.builder.templates.render_string(src, app.config.html_context)\n source[0] = rendered",
"def rstjinja(app, docname, source):\n # Make sure we're outputting HTML\n if app.builder.format != \"html\":\n return\n src = source[0]\n rendered = app.builder.templates.render_string(src, app.config.html_context)\n source[0] = rendered",
"def create_html(self):\n rows = self.check()\n htmlrows = \"\"\n for row in rows:\n data = self._format_row(row)\n htmlrows += data\n \n return self.TEMPLATE.format(content=htmlrows)",
"def html(input):\n output=atpic.cleaner_alex.clean(input)\n return output",
"def html_builder(s, meta, template_path):\n s = convert_text(s)\n \n # create right navigation panel: \n right = toc_panel(s)\n \n with open(template_path, 'r') as html:\n contents = html.read()\n\n soup = BeautifulSoup(contents, 'lxml')\n\n \n right_div = soup.find(id='sidebar-wrapper')\n book_main = soup.find(id='content')\n metadata = soup.find(id='metadata-content')\n\n for key, value in meta.items():\n\n new_p = soup.new_tag(\"label\")\n value = key + \": \" + value\n new_p.append((value)) \n metadata.insert(0, new_p)\n \n soup.new_tag(\"div\", right_div.append(BeautifulSoup(right, 'lxml')))\n soup.new_tag(\"div\", book_main.insert(1, BeautifulSoup(s, 'html.parser')))\n \n # format main text as html:\n \n full_html = soup\n return str(full_html)",
"def gen_example_rst(example):\n if not example:\n return \"\"\n res = \"\"\"**Example**\n\n.. literalinclude:: /samples/{example}/CMakeLists.txt\n :language: cmake\n\n\"\"\"\n return res.format(example=example)",
"def html_manual_format(string):\n return html_div(string, \"manualfmt\")",
"def convert_html():\n return",
"def mdhtml_to_html(data_str):\n mdrenderer = mistune.Renderer()\n markdown = mistune.Markdown(renderer=mdrenderer)\n return markdown(data_str)",
"def to_html(docstring: str) -> str:\n # careful: markdown2 returns a subclass of str with an extra\n # .toc_html attribute. don't further process the result,\n # otherwise this attribute will be lost.\n return pdoc.markdown2.markdown( # type: ignore\n docstring,\n extras=markdown_extensions,\n link_patterns=markdown_link_patterns,\n )",
"def get_html_string(self, **kwargs):\n ...",
"def htmlize(text):\n htmlized = markdown.markdown(\n text,\n output_format=\"xhtml5\", safe_mode=\"escape\",\n )\n htmlversion = htmltemplate.format(body=htmlized)\n return htmlversion",
"def rawHTMLrendered(self):",
"def generateHtml(self, tokens, html, css):\n\n\t\tf = open(html, \"w\")\n\t\tf.write(\"\"\"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<title>Document</title>\n</head>\n\t\t\"\"\")\n\t\tif os.path.exists(\"css/default.css\"):\n\t\t\tstyle = open(\"css/default.css\", \"r\").read()\n\t\telse:\n\t\t\tstyle = open(f\"{css}css/default.css\", \"r\").read()\n\t\tf.write(f\"<style>\\n{style}\\n</style>\\n\")\n\t\tf.write(\"<body>\")\n\t\tf.write('<div class=\"markdown-body\">')\n\t\tfor t in tokens:\n\t\t\tf.write(t.html)\n\t\tf.write(\"</div>\")\n\t\tf.write(\"</body>\")\n\t\tf.write(\"</html>\")\n\t\tf.close()",
"def html():\n env.file_ext = \".html\"\n local(\"pandoc {input_files} -o {output_file}{file_ext} --standalone --bibliography={bib_file} --csl={csl_file} --toc --number-sections\".format(**env))",
"def html(self):\n bop = ('<b>' if self._bold else '')\n iop = ('<i>' if self._italic else '')\n icl = ('</i>' if self._italic else '')\n bcl = ('</b>' if self._bold else '')\n txt = escape(self._text)\n s = '%s%s%s%s%s' % (bop, iop, txt, icl, bcl)\n return '%s' % s",
"def convert(text):\n return NewDocument.from_rst(text).format()",
"def write():\n \n st.title(\"All about me..!!\")\n st.markdown(\n \"\"\"\n\n:large_blue_diamond: **Data Engineer**\\n\nThe current role revolves around working with database management(AWS Redshift), automation of tasks (using Python), and helping out other teams at work with required data for BI reports. This involves me working with various ETL tools like Matillion. Apart from this, I have started some creative learning initiatives at work to develop and grow skills.\n\n:large_blue_diamond: **Speaker | Blogger | Community- Builder**\\n\nI have speaker at various meetups and workshops. Apart from this, I am a Lead organizer at **Kaggle Days Meetups - Surat** and **Pie and AI: Gujarat**. You will often find me on Saturdays at Integrated Mentoring Session - where we as a community believe in More Together Learning. I like to write blogs on data science, NLP, work learnings, and some general topics.\n\n:large_blue_diamond: **NLP- Practitioner**\\n\nSharing the learnings and practices of NLP with the community through various workshops and classes or through LinkedIn posts and videos. I have completed her thesis titled \"Neural Machine Translation on Indian Languages\". Currently, working on a research project. \n\n:large_blue_diamond: **Collaborations**\\n\nIf you are looking to collaborate on Research opportunities in NLP, \nCorporate training in NLP, \nteaching and mentoring students & professionals in NLP.\nPlease\n[email me](mailto:[email protected]) or reach out \nto me on [LinkedIn](https://www.linkedin.com/in/manpreet-budhraja/) \n\n\n\n\"\"\",\n unsafe_allow_html=True,\n )"
] | [
"0.709398",
"0.66510856",
"0.6648247",
"0.6646475",
"0.65572613",
"0.65189904",
"0.64840823",
"0.64663064",
"0.63909996",
"0.62470186",
"0.6201088",
"0.61976624",
"0.61944747",
"0.61944747",
"0.61889017",
"0.61869967",
"0.61695504",
"0.6117476",
"0.6104067",
"0.6102414",
"0.6075343",
"0.6041578",
"0.60278815",
"0.6026256",
"0.60131896",
"0.6013013",
"0.600518",
"0.5970168",
"0.596196",
"0.59525746"
] | 0.72522247 | 0 |
Test if HTML document includes an element with the given attributes and text content. The HTML is parsed with lxml for checking against the data you provide. The method takes an element argument, a string representing the name of an HTML tag, like "script" or "iframe". We will try to find this tag in the document and perform the tests on it. You can pass a dictionary to the attributes kwarg representing the name and the value of the tag attributes. The text kwarg takes a string argument, which will be tested against the contents of the HTML element. | def assert_html_contains(html, element, attributes=None, text=None):
html_doc = lxml_html.parse(StringIO(html))
try:
tag = next(html_doc.iter(element))
except StopIteration:
raise Exception("<{0}> not in {1}".format(element, html))
if attributes:
arg_attrs = set(attributes.items())
tag_attrs = set(tag.items())
assert arg_attrs.issubset(tag_attrs)
if text:
assert text in tag.text | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def find_by_contains_text(self, text, element_tag=\"*\"):\n return self.wait_until_element_find(locator_type=By.XPATH,\n locator=f\".//{element_tag}[contains(text(), '{text}')]\")",
"def element(tag, attrib={}, text=None):\n ele = Element(tag, attrib)\n if text:\n ele.text = text\n return ele",
"def doFindText(self, expectedText, timeout=10.0, name=None, tagName=None, className=None,\n id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None,\n location=None):\n TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout)\n \n if expectedText is None: \n raise TestAdapterLib.ValueException(TestAdapterLib.caller(), \"expectedText argument cannot be equal to none\" )\n\n ret = True\n \n if not self.cfg['wait-until']:\n cmdId = self.implicitlyWait(timeout=timeout)\n if self.isWait(timeout=timeout, commandId=cmdId) is None:\n ret = False\n return ret\n \n cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className,\n id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText,\n cssSelector=cssSelector, location=location)\n rsp = self.hasElement(timeout=timeout, commandId=cmdId) \n if rsp is None: ret = False\n else:\n elementVall = rsp.get('GUI', 'value')\n elementId = elementVall.get('element-id')\n \n cmdId = self.getTextElement(elementId=elementId)\n rsp = self.hasTextElement(timeout=timeout, commandId=cmdId, expectedText=expectedText)\n if rsp is None:\n ret = False\n return True\n return ret",
"def is_etree_element(obj: Any) -> bool:\n return hasattr(obj, 'append') and hasattr(obj, 'tag') and hasattr(obj, 'attrib')",
"def has_text(self, text, match_option=None):\n selector_text = UiSelector().attributes(\"text\", text, match_option)\n selector_content_desc = UiSelector().attributes(\"content-desc\", text,\n match_option)\n\n return UiObject(\n selector_text, self.android_device_driver).verify_exist() or UiObject(\n selector_content_desc, self.android_device_driver).verify_exist()",
"def assert_text_present(self, text, msg=None):\r\n e = driver.find_element_by_tag_name('body')\r\n assert text in e.text",
"def assert_has_text(self, xml_root, xpath, text, exact=True):\r\n element_list = xml_root.xpath(xpath)\r\n self.assertTrue(len(element_list) > 0,\r\n \"Could not find element at '%s'\" % str(xpath))\r\n\r\n if exact:\r\n self.assertEqual(text, element_list[0].text)\r\n else:\r\n self.assertIn(text, element_list[0].text)",
"def get_text_in_element():\n nonlocal text_\n if text_ is None:\n text_ = element.text\n element_text = element.text\n if element_text == text:\n return element\n if text.lower() == element_text.lower():\n return element\n if \"\".join(text.split()) == \"\".join(element_text.split()):\n return element\n return False",
"def contains(self, element) -> bool:\n\n return self.__find_node(element) is not None",
"def text_exists(self, text: str)-> bool:\n result = self.__content.find(text)\n if result == -1:\n return False\n else:\n return True",
"def element_to_contain_text(self, target: ElementType, text: str, timeout: TimeoutType = DEFAULT_TIMEOUT):\n\n def has_text_in_target():\n target.get_web_element_by_timeout(timeout)\n return target if text in target.text else False\n\n err_msg = f\"TimeoutException while waited {timeout} for the element {target.selector} to contain text '{text}'. \" \\\n f\"Actual text '{target.text}'\"\n\n return self.wait_fluently(has_text_in_target, timeout, err_msg)",
"def create_element_text( self, text, element, base_element = None ):\n if not etree.iselement( element ):\n element = self.get_element( element, base_element )\n if element is None:\n return False\n element.text = text\n return True",
"def contains(self, element):\n pass",
"def is_tagged_text(*a, **kw):\n return is_tagged_text(*a, **kw)",
"def test_textCondition(self):\n xp = XPathQuery(\"/foo[text() = 'somecontent']\")\n self.assertEqual(xp.matches(self.e), True)",
"def assert_in_html(member, container, **kwargs):\n member = markupsafe.escape(member)\n return assert_in(member, container, **kwargs)",
"def exists(self, **kwargs):\n if 'timeout' in kwargs:\n self.set_implicit_wait(kwargs['timeout'])\n\n if 'driver' in kwargs:\n d = kwargs['driver']\n else:\n d = self.driver\n\n if kwargs.has_key('element'):\n try:\n return kwargs['element']\n except:\n return False\n else:\n try:\n if 'accessibility_id' in kwargs:\n e = d.find_element_by_accessibility_id(kwargs['accessibility_id'])\n elif 'class_name' in kwargs:\n e = d.find_element_by_class_name(kwargs['class_name'])\n elif 'id' in kwargs:\n e = d.find_element_by_id(kwargs['id'])\n elif 'xpath' in kwargs:\n e = d.find_element_by_xpath(kwargs['xpath'])\n else:\n raise RuntimeError(\"exists() called with incorrect param. kwargs = %s\" % kwargs)\n\n return e\n except NoSuchElementException:\n return False\n finally:\n self.set_implicit_wait()",
"def do_checkTextInclusion(self, str_arg):\n # printLog(self.threadName + \"[running command 'checkTextInclusion %s']\" % str_arg)\n arg = validateString(str_arg)\n ret = arg.split(' ', 1)\n if len(ret) == 1:\n self.resultFlag = False\n raise ValueError('Lacking argument of checkTextInclusion.')\n if iDevice.dump_view:\n self.__dumpview()\n try:\n viewId = ret[0].strip()\n printLog(\"finding view by id %s ...\" % viewId, logging.DEBUG)\n tmpView = self.vc.findViewById(viewId)\n if not tmpView:\n self.resultFlag = False\n printLog(self.threadName + '%s is not visible.' % viewId, logging.ERROR)\n return\n else:\n # get element text, and compare it with the given text value\n tempText = tmpView.getText()\n printLog(self.threadName + '[text on screen: %s]' % tempText)\n if not ret[1].strip() in tempText.strip():\n self.resultFlag = False\n except Exception, e:\n self.resultFlag = False\n printLog(self.threadName + 'Exception in do_check: %s' % e.message, logging.ERROR)\n finally:\n return self.resultFlag",
"def _check_with_content(params):\r\n if 'with_content' in params and params['with_content'] != 'false':\r\n return True\r\n else:\r\n return False",
"def doWaitElement(self, timeout=10.0, name=None, tagName=None, className=None,\n id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None,\n location=None):\n TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout)\n \n ret = True\n more = {}\n if self.cfg['wait-until']:\n more = {\"wait-until\": True, \"wait-until-timeout\": timeout}\n\n if not self.cfg['wait-until']:\n cmdId = self.implicitlyWait(timeout=timeout)\n if self.isWait(timeout=timeout, commandId=cmdId) is None:\n ret = False\n return ret\n\n cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className,\n id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, cssSelector=cssSelector,\n location=location, more=more)\n rsp = self.hasElement(timeout=timeout+10, commandId=cmdId) \n if rsp is None: ret = False \n return ret",
"def hasTextElement(self, timeout=20.0, commandId=None, expectedText=None):\n TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout)\n \n valueLayer = TestTemplates.TemplateLayer(name=\"\")\n if expectedText is not None:\n valueLayer.addKey(name=\"value\", data=expectedText)\n return self.isActionAccepted(timeout=timeout, commandName=Command.GET_ELEMENT_TEXT, \n commandId=commandId, expectedValue=valueLayer)",
"def doTypeText(self, text, timeout=10.0, name=None, tagName=None, className=None,\n id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None,\n location=None):\n TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout)\n \n if text is None: \n raise TestAdapterLib.ValueException(TestAdapterLib.caller(), \"text argument cannot be equal to none\" )\n\n ret = True\n \n if not self.cfg['wait-until']:\n cmdId = self.implicitlyWait(timeout=timeout)\n if self.isWait(timeout=timeout, commandId=cmdId) is None:\n ret = False\n return ret\n \n cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className,\n id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, \n cssSelector=cssSelector, location=location)\n rsp = self.hasElement(timeout=timeout, commandId=cmdId) \n if rsp is None: ret = False\n else:\n elementVall = rsp.get('GUI', 'value')\n elementId = elementVall.get('element-id')\n\n cmdId = self.typeTextElement(elementId=elementId, text=str(text) )\n if self.hasTextEntered(timeout=timeout, commandId=cmdId) is None:\n ret = False\n return ret",
"def test_contains(self, element, env):\n return self.fam.c_test_contains(self, element, env)",
"def createElement(tag,attrib={},text={}):\n element = ET.Element(tag,attrib)\n element.text = text\n return element",
"def test_given_content(self):\r\n\r\n file_path = os.path.dirname(__file__)\r\n html_content = open(os.path.join(file_path, 'readable_sample.html'))\r\n\r\n read = ReadContent.parse(html_content)\r\n\r\n self.assertTrue(\r\n read.status == 1, \"The status is 1: \" + str(read.status))\r\n self.assertTrue(not read.is_image(), \"The content is not an image\")\r\n self.assertTrue(read.content is not None, \"Content should not be none\")\r\n self.assertTrue(\r\n 'Bookie' in read.content,\r\n u\"The word Bookie is in the content: \" + unicode(read.content))",
"def isHTML(content):\n\n return '<html' in content or 'html>' in content",
"def add_element(self, tag, *args):\n text_with_tag=\"{}\".format(_html_tags[tag].format(*args))\n if tag in _head_tags.keys():\n self.head.append(f\"\\n {text_with_tag}\")\n else:\n self.body.append(f\"\\n {text_with_tag}\")",
"def test_can_filter_attributes(self):\n text = '<b><a href=\"\" target=\"_blank\">Example</a></b>'\n filter = Bleach(\n tags=['a'],\n attributes=dict(a=['href', 'title'])\n )\n filtered = filter.filter(text)\n expected = '<a href=\"\">Example</a>'\n self.assertEquals(expected, filtered)",
"def doGetText(self, timeout=10.0, name=None, tagName=None, className=None,\n id=None, xpath=None, linkText=None, partialLinkText=None, cssSelector=None,\n location=None):\n TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(), timeout=timeout)\n \n ret = True\n \n if not self.cfg['wait-until']:\n cmdId = self.implicitlyWait(timeout=timeout)\n if self.isWait(timeout=timeout, commandId=cmdId) is None:\n ret = False\n return ret\n \n cmdId = self.findElement(elementId=None, name=name, tagName=tagName, className=className,\n id=id, xpath=xpath, linkText=linkText, partialLinkText=partialLinkText, \n cssSelector=cssSelector, location=location)\n rsp = self.hasElement(timeout=timeout, commandId=cmdId) \n if rsp is None: ret = False\n else:\n elementVall = rsp.get('GUI', 'value')\n elementId = elementVall.get('element-id')\n \n cmdId = self.getTextElement(elementId=elementId)\n rsp = self.hasTextElement(timeout=timeout, commandId=cmdId)\n if rsp is None: ret = False\n else:\n elementVall = rsp.get('GUI', 'value')\n ret = elementVall.get('value')\n \n return ret",
"def test_render_element():\n elem = hr.Element(\"this is some text\")\n elem.append(\"and this is some more text\")\n\n # This uses the render_results utility above\n file_contents = render_result(elem).strip()\n\n # making sure the content got in there.\n assert \"this is some text\" in file_contents\n assert \"and this is some more text\" in file_contents\n\n # make sure it's in the right order\n assert file_contents.index(\"this is\") < file_contents.index(\"and this\")\n\n # making sure the opening and closing tags are right.\n assert file_contents.startswith(\"<html>\")\n assert file_contents.endswith(\"</html>\")"
] | [
"0.57328683",
"0.5658947",
"0.53158635",
"0.5221668",
"0.5220453",
"0.514926",
"0.5106635",
"0.50902253",
"0.50742674",
"0.50740737",
"0.50482595",
"0.5032578",
"0.50092673",
"0.49938992",
"0.49458674",
"0.49129403",
"0.48839796",
"0.48828787",
"0.4844136",
"0.48328614",
"0.4786533",
"0.47715485",
"0.4745097",
"0.47356784",
"0.47308436",
"0.47182518",
"0.47127122",
"0.46947566",
"0.46918428",
"0.46735758"
] | 0.76333463 | 0 |
Disable query of the vimeo api over the wire Set Vimeo.request_size to False for avoiding querying the Vimeo api over the network. | def disable_vimeo_api_query():
before = vimeo.Vimeo.request_size
vimeo.Vimeo.request_size = False
try:
_reload(nikola.plugins.compile.rest)
yield
finally:
vimeo.Vimeo.request_size = before | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def disable_rate_limit_forward(self):\n self.headers = {\n 'Content-Type': 'application/json; charset=utf-8',\n 'X-Algolia-API-Key': self.api_key,\n 'X-Algolia-Application-Id': self.application_id,\n 'User-Agent': ('Algolia Search for python %s' % VERSION)\n }",
"def disable(self):\n\n super().disable()\n self._slo_image_size.disable()\n self._slo_neural_network.disable()\n self._slo_number_of_epochs.disable()\n self._slo_examples_per_batch.disable()",
"def EnableFreeAPIKeyRateLimit(self):\n self._hashes_per_batch = 4\n self._wait_after_analysis = 60.0",
"def disable_openapi_validation(self) -> Optional[pulumi.Input[bool]]:\n return pulumi.get(self, \"disable_openapi_validation\")",
"def _should_restore_default_page_size(self, params):\n params = True if params else False\n return params and not self.request_record_limit_is_reduced and self.last_api_call_is_successful",
"def EnableFreeAPIKeyRateLimit(self):\n self._analyzer.hashes_per_batch = 4\n self._analyzer.wait_after_analysis = 60\n self._analysis_queue_timeout = self._analyzer.wait_after_analysis + 1",
"def disable_vae_slicing(self):\n self.vae.disable_slicing()",
"def test_disable_limiter(monkeypatch):\n monkeypatch.setattr(planet.http, 'RATE_LIMIT', 0)\n monkeypatch.setattr(planet.http, 'MAX_ACTIVE', 0)",
"def disable_openapi_validation(self) -> pulumi.Output[Optional[bool]]:\n return pulumi.get(self, \"disable_openapi_validation\")",
"def is_unlimited(self) -> bool:\n return not self.is_limited",
"def Disable(self, request, global_params=None):\n config = self.GetMethodConfig('Disable')\n return self._RunMethod(\n config, request, global_params=global_params)",
"def Disable(self, request, global_params=None):\n config = self.GetMethodConfig('Disable')\n return self._RunMethod(\n config, request, global_params=global_params)",
"def Disable(self, request, global_params=None):\n config = self.GetMethodConfig('Disable')\n return self._RunMethod(\n config, request, global_params=global_params)",
"def test_vimeo(disable_vimeo_api_query):\n\n sample = \".. vimeo:: VID\\n :height: 400\\n :width: 600\"\n html = get_html_from_rst(sample)\n assert_html_contains(\n html,\n \"iframe\",\n attributes={\n \"src\": (\"https://player.vimeo.com/\" \"video/VID\"),\n \"height\": \"400\",\n \"width\": \"600\",\n },\n )",
"def disable_paging_requested(self):\n return self.request.GET.get('disablePaging', 'false') == 'true'",
"async def vcoffcmd(self, message):\n self._db.set(__name__, 'voicy', False)\n self._db.set(__name__, \"ratelimit\", [])\n await message.edit(self.strings['off'])",
"def test_api_requests_limited(self):\n\n did_reach_rate_limit = False\n for _ in range(110):\n response = self.send_get('Participant', expected_status=None)\n if response.status_code == TooManyRequests.code:\n did_reach_rate_limit = True\n break\n\n self.assertTrue(did_reach_rate_limit)",
"async def disable_paging(self):\n\n # Display info message\n log.info(\"disable_paging\")\n\n # Send command to the device to disable paging\n await self.send_command(self.cmd_disable_paging)",
"def _NoPadBufferSize(self, buffer_size):\n no_pad_size = self.block_size * (buffer_size // self.block_size)\n return max(no_pad_size, self.block_size)",
"def opt_pagesize(self, pagesize):\n if pagesize != \"auto\":\n pagesize = int(pagesize)\n self.conf[\"pagesize\"] = pagesize",
"def unique_size_not_in(self, unique_size_not_in):\n\n self._unique_size_not_in = unique_size_not_in",
"def is_vuln_mode_disabled(self):\n # Set this value if you want the vuln data to be collected in the S3 file.\n return os.environ.get('DISABLE_VULN_MODE', 'false').lower() in ('1', 'yes', 'true')",
"def use_in_clever(bundle):\n if 'limit' in bundle.request.GET:\n return False\n return True",
"def _options_from_req(self, req) -> ListApiOptions:\n limit = int(req.query.get(\"limit\"))\n # Only apply 80% of the timeout so that\n # the API will reply before client times out if query to the source fails.\n timeout = int(req.query.get(\"timeout\"))\n return ListApiOptions(limit=limit, timeout=timeout)",
"def test_protoDisable(self):\n options = Options()\n options.parseOptions([\"--no-pop3\"])\n self.assertEqual(options._getEndpoints(None, \"pop3\"), [])\n self.assertNotEqual(options._getEndpoints(None, \"smtp\"), [])\n\n options = Options()\n options.parseOptions([\"--no-smtp\"])\n self.assertNotEqual(options._getEndpoints(None, \"pop3\"), [])\n self.assertEqual(options._getEndpoints(None, \"smtp\"), [])",
"def resetProtocolOptions(self):",
"def resetProtocolOptions(self):",
"def message_no_limit(request):\n \n # this is only available in development - should use our\n # parse.decorators.dev_only decorator instead of this\n if PRODUCTION_SERVER:\n raise Http404 \n\n # insert the token in the session and return a plaintext response\n # confirming the success of the operation\n if request.method == \"GET\":\n request.session[\"message_limit_off\"] = True\n return HttpResponse(\"Limit for sending messages has been turned off.\" +\\\n \"To turn it back on, please log out and log back in.\")\n \n # only accept GET methods \n return HttpResponse(\"Bad Request\")",
"def test_exceed_limit_request(self):\n actions.login(ADMIN_EMAIL)\n ids_list = list(range(SkillAggregateRestHandler.MAX_REQUEST_SIZE))\n get_url = '%s?%s' % (self.URL, urllib.urlencode({\n 'ids': ids_list}, True))\n\n response = transforms.loads(self.get(get_url).body)\n self.assertEqual(412, response['status'])",
"def disable(self) -> None:"
] | [
"0.51495045",
"0.48969105",
"0.4848587",
"0.4836588",
"0.48320383",
"0.48153383",
"0.47671932",
"0.47585866",
"0.47426912",
"0.4658645",
"0.46517655",
"0.46517655",
"0.46517655",
"0.46294478",
"0.46228823",
"0.455569",
"0.45410028",
"0.4495744",
"0.44896275",
"0.44370815",
"0.44345236",
"0.4408083",
"0.43760732",
"0.4362124",
"0.43599355",
"0.43276638",
"0.43276638",
"0.4279596",
"0.42484778",
"0.42329317"
] | 0.8127371 | 0 |
Create a new ellipsoid | def newEllipsoid(**kwds):
# invoke the foundry to get to the class with the implementation
ellipsoid = core.ellipsoid()
# instantiate one and return it
return ellipsoid(**kwds) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def createEllipsoid( position=(0,0,0), radius=(1,1,1), colour=(0.6,0.6,0.6), samplesY = 20, samplesXZ = 20, exponentBottom = 2, exponentTop = 2, exponentSide = 2 ):\r\n \r\n if exponentBottom < 2.0 or exponentTop < 2.0 or exponentSide < 2.0 :\r\n raise ValueError( 'Exponents for ellipsoid must all be under 2.0!' )\r\n \r\n position = PyUtils.toPoint3d(position)\r\n vertices = []\r\n for i in range(1,samplesY):\r\n thetaI = i*math.pi/float(samplesY)\r\n if i < samplesY / 2 : \r\n n = exponentTop\r\n else:\r\n n = exponentBottom\r\n cos = math.cos(thetaI) \r\n y = cos * radius[1]\r\n scaleXZ = math.pow( 1-math.pow(math.fabs(cos),n), 1.0/float(n) )\r\n for j in range(0,samplesXZ):\r\n thetaJ = j*2.0*math.pi/float(samplesXZ)\r\n n = exponentSide\r\n cos = math.cos(thetaJ)\r\n x = cos * scaleXZ * radius[0]\r\n z = math.pow( 1-math.pow(math.fabs(cos),n), 1.0/float(n) ) * math.copysign(1, math.sin(thetaJ)) * scaleXZ * radius[2]\r\n vertices.append( position + Vector3d(x,y,z) )\r\n vertices.append( position + Vector3d(0,radius[1],0) )\r\n vertices.append( position + Vector3d(0,-radius[1],0) ) \r\n\r\n faces = []\r\n for i in range(0,(samplesY-2)*samplesXZ,samplesXZ) :\r\n for j in range(0,samplesXZ) :\r\n faces.append( (i+j, i+(j+1)%samplesXZ, i+samplesXZ+(j+1)%samplesXZ, i+samplesXZ+j) ) \r\n\r\n for i in range(0,samplesXZ) :\r\n base = (samplesY-2)*samplesXZ\r\n faces.append( ((i+1)%samplesXZ, i, (samplesY-1)*samplesXZ) ) \r\n faces.append( (base+i, base+(i+1)%samplesXZ, (samplesY-1)*samplesXZ+1) ) \r\n\r\n \r\n return create( vertices, faces, colour )",
"def construct_by_ellipse(a_xx, h_xy, b_yy, g_x, f_y, d, focal_length):\n gamma = - focal_length\n a = gamma**2 * a_xx\n b = gamma**2 * b_yy\n c = d\n d = gamma**2 * d\n f = -gamma*(f_y)\n g = -gamma*(g_x)\n h = gamma**2 * h_xy\n #Not needed\n u = gamma**2 * g_x\n v = gamma**2 * f_y\n w = -gamma*(d)\n return ConeCamera(a, b, c, f, g, h)",
"def createSphere( position=(0,0,0), radius=1, colour=(0.6,0.6,0.6), samplesY = 20, samplesXZ = 20 ):\r\n return createEllipsoid( position, (radius,radius,radius), colour, samplesY, samplesXZ )",
"def point2wgs84_9603(self, datum):\n \"\"\"\n h is the height above the ellipsoid. This is the height value that is \n delivered by GPS satellite observations but is not the gravity-related height \n value which is normally used for national mapping and levelling operations. The\n gravity-related height (H) is usually the height above mean sea level or an \n alternative level reference for the country. If one starts with a gravity-related \n height H, it will be necessary to convert it to an ellipsoid height (h) before \n using the above transformation formulas. See section 4.11.1. For the WGS 84 \n ellipsoid the difference between ellipsoid and mean sea level can vary between \n values of -100m in the Sri Lanka area to +80m in the North Atlantic.)\n \"\"\"\n h=0\n # a is the semi-major axis of the ellipsoid of the given datum.\n a = datum.axis\n\n # f is the flattening of the ellipsoid of the given datum \n # (get_flattening actually returns the inverse flattening).\n f = 1.0/datum.flattening\n \n # dx, dy, dz are the x, y, z offset parameters for the given datum transformation\n # to WGS84\n dx = datum.dx\n dy = datum.dy\n dz = datum.dz\n \n # latr, lngr are the latitude and longitude in radians\n latr = math.radians(self.lat)\n lngr = math.radians(self.lng)\n\n # e is the eccentricity of the ellipsoid\n e_squared = f*(2-f)\n\n # nu is the prime vertical radius of curvature at latr\n nu = a/math.pow((1-e_squared*sqr(math.sin(latr))),0.5)\n\n X = (nu+h)*math.cos(latr)*math.cos(vlambda)\n Y = (nu+h)*math.cos(latr)*math.sin(vlambda)\n Z = ((1 - math.pow(e,2))*nu + h)*math.sin(phi)\n\n Xwgs84 = X+dx\n Ywgs84 = Y+dy\n Zwgs84 = Z+dz\n\n epsilon = e_squared/(1-e_squared)\n b = a*(1-f)\n p = math.pow(sqr(Xwgs84)+sqr(Ywgs84),0.5)\n q = math.atan2((Zwgs84*a),(p*b))\n\n latrwgs84 = math.atan2( (Zwgs84 + epsilon*b*math.pow(math.sin(q)),3)), \\\n (p - e_squared*a*math.pow(math.cos(q),3) )\n lngrwgs84 = math.atan2(Ywgs84, Xwgs84)\n hwgs84 = (p/math.cos(latrwgs84))-nu\n newlng = lng180(math.degrees(lngrwgs84))\n newlat = math.degrees(latrwgs84)\n return Point(float(truncate(newlng,DEGREE_DIGITS)), float(truncate(newlat,DEGREE_DIGITS)))",
"def ellipse(self):\n f = self.img\n x = self.x\n y = self.y\n x2 = self.x2\n y2 = self.y2\n xy = self.xy\n self.a2 = (x2+y2) + sqrt(((x2-y2)/2.)**2 + xy**2)\n self.b2 = (x2+y2) - sqrt(((x2-y2)/2.)**2 + xy**2)\n self.a = sqrt(self.a2)\n self.b = sqrt(self.b2)\n tan2theta = 2* (xy/(x2-y2))\n self.theta = arctan(tan2theta)/2.\n denominator = sqrt(((x2-y2)/2)**2+xy**2)\n self.cxx = y2/denominator\n self.cyy = x2/denominator\n self.cxy = -2*xy/denominator",
"def createTaperedBox( position=(0,0,0), size=(1,1,1), colour=(0.6,0.6,0.6), samplesY = 20, samplesXZ = 20, exponentBottom = 4, exponentTop = 4, exponentSide = 4 ):\r\n\r\n return createEllipsoid( position, (size[0]/2.0,size[1]/2.0,size[2]/2.0), colour, samplesY, samplesXZ, exponentBottom, exponentTop, exponentSide )",
"def ellipsoid(center, radii, rotation, scales=None, shape=None, minarea=0):\n center = np.array(center)\n radii = np.array(radii)\n rotation = np.array(rotation)\n assert center.shape == (3,)\n assert radii.shape == (3,)\n assert 0 < radii.max(), \"radii should contain at least one positive value\"\n assert rotation.shape == (3, 3)\n if scales is None:\n scales = (1.,) * 3\n scales = np.array(scales)\n assert scales.shape == (3,)\n\n scaled_center = center / scales\n\n # The upper_left_bottom and lower_right_top corners of the smallest cuboid\n # containing the ellipsoid.\n factor = np.array([\n [i, j, k] for k in (-1, 1) for j in (-1, 1) for i in (-1, 1)]).T\n while True:\n radii_rot = np.abs(\n np.diag(1. / scales).dot(rotation.dot(np.diag(radii).dot(factor)))\n ).max(axis=1)\n # In the original scikit-image code, ceil and floor were replaced.\n # https://github.com/scikit-image/scikit-image/blob/master/skimage/draw/draw.py#L127\n upper_left_bottom = np.floor(scaled_center - radii_rot).astype(int)\n lower_right_top = np.ceil(scaled_center + radii_rot).astype(int)\n\n if shape is not None:\n # Constrain upper_left and lower_ight by shape boundary.\n upper_left_bottom = np.maximum(\n upper_left_bottom, np.array([0, 0, 0]))\n lower_right_top = np.minimum(\n lower_right_top, np.array(shape[:3]) - 1)\n\n bounding_shape = lower_right_top - upper_left_bottom + 1\n\n d_lim, r_lim, c_lim = np.ogrid[0:float(bounding_shape[0]),\n 0:float(bounding_shape[1]),\n 0:float(bounding_shape[2])]\n d_org, r_org, c_org = scaled_center - upper_left_bottom\n d_rad, r_rad, c_rad = radii\n rotation_inv = np.linalg.inv(rotation)\n conversion_matrix = rotation_inv.dot(np.diag(scales))\n d, r, c = (d_lim - d_org), (r_lim - r_org), (c_lim - c_org)\n distances = (\n ((d * conversion_matrix[0, 0] +\n r * conversion_matrix[0, 1] +\n c * conversion_matrix[0, 2]) / d_rad) ** 2 +\n ((d * conversion_matrix[1, 0] +\n r * conversion_matrix[1, 1] +\n c * conversion_matrix[1, 2]) / r_rad) ** 2 +\n ((d * conversion_matrix[2, 0] +\n r * conversion_matrix[2, 1] +\n c * conversion_matrix[2, 2]) / c_rad) ** 2\n )\n if distances.size < minarea:\n old_radii = radii.copy()\n radii *= 1.1\n print('Increase radii from ({}) to ({})'.format(old_radii, radii))\n else:\n break\n distance_thresh = 1\n while True:\n dd, rr, cc = np.nonzero(distances < distance_thresh)\n if len(dd) < minarea:\n distance_thresh *= 1.1\n else:\n break\n dd.flags.writeable = True\n rr.flags.writeable = True\n cc.flags.writeable = True\n dd += upper_left_bottom[0]\n rr += upper_left_bottom[1]\n cc += upper_left_bottom[2]\n return dd, rr, cc",
"def setCrsEllipsoid(self, a, rf=None):\n self.isgeographic = True\n self.ellipsoid_a = a\n if rf is None:\n self.ellipsoid_b = a\n else:\n self.ellipsoid_b = a * (1.0 - 1.0 / rf)\n self.a2 = self.ellipsoid_a * self.ellipsoid_a\n self.b2 = self.ellipsoid_b * self.ellipsoid_b",
"def set_earth(inclination, phases):\n cosi, sini = np.cos(inclination), np.sin(inclination)\n cosp = np.cos(2*np.pi*phases)\n sinp = np.sin(2*np.pi*phases)\n return CartesianRepresentation(sini*cosp, -sini*sinp, cosi)",
"def plot_ellipsoid(cls, ellipsoids, true_theta, config, title=\"\", figsize=(8, 6), save_to=None):\n # Figure creation\n sns.set(font_scale=1)\n # sns.set_style(\"white\")\n fig = plt.figure(figsize=figsize, tight_layout=True)\n ax = fig.add_subplot(1, 1, 1)\n plt.title(title)\n for ellipsoid in ellipsoids[:20:5] + ellipsoids[20:-1:20]:\n confidence_ellipse(ellipsoid, ax, facecolor=(1, 0.3, 0.3, 0.1),\n edgecolor=\"black\", linewidth=0.5, label=None)\n confidence_ellipse(ellipsoids[-1], ax, facecolor=(1, 0.3, 0.3, 0.1),\n edgecolor='red', label=r\"$\\hat{\\Theta}$\")\n plt.plot(true_theta[0], true_theta[1], '.', label=r\"$\\theta$\")\n plt.legend(loc=\"upper right\")\n bound = config[\"parameter_box\"]\n ax.set_xlim(bound[0][0], bound[1][0])\n ax.set_ylim(bound[0][1], bound[1][1])\n ax.set_xlabel(r\"$\\theta_1$\")\n ax.set_ylabel(r\"$\\theta_2$\")\n\n # Figure export\n if save_to is not None and len(ellipsoids) % 10 == 0:\n plt.savefig(save_to)\n plt.savefig(save_to.with_suffix(\".png\"))\n fig.canvas.draw()\n data_str = fig.canvas.tostring_rgb()\n plt.close()\n return data_str, fig.canvas.get_width_height()",
"def make_ellipsoid_faces(center, dims, nsubdivs=2):\n t = (1+sqrt(5))/2.0\n s = sqrt(1+t**2)\n \n vertices = [(t/s,1/s,0), (-t/s,1/s,0), (t/s,-1/s,0),\\\n (-t/s,-1/s,0), (1/s,0,t/s), (1/s,0,-t/s), (-1/s,0,t/s),(-1/s,0,-t/s),\\\n (0,t/s,1/s), (0,-t/s,1/s), (0,t/s,-1/s), (0,-t/s,-1/s)]\n\n v = vertices\n faces = [(v[0],v[8],v[4]),(v[1],v[10],v[7]),(v[2],v[9],v[11]),(v[7],v[3],v[1]),(v[0],v[5],v[10]),(v[3],v[9],v[6]),\\\n (v[3],v[11],v[9]),(v[8],v[6],v[4]),(v[2],v[4],v[9]),(v[3],v[7],v[11]),(v[4],v[2],v[0]),\\\n (v[9],v[4],v[6]),(v[2],v[11],v[5]),(v[0],v[10],v[8]),(v[5],v[0],v[2]),(v[10],v[5],v[7]),(v[1],v[6],v[8]),\\\n (v[1],v[8],v[10]),(v[6],v[1],v[3]),(v[11],v[7],v[5])]\n \n #subdivide each of the faces into 9 faces\n for i in xrange(nsubdivs):\n new_faces = []\n for face in faces:\n new_faces.extend(subdivide(face[0], face[1], face[2]))\n faces = new_faces\n faces = scale_faces(dims[0], dims[1], dims[2], faces)\n faces = translate_faces(center, faces)\n return faces",
"def _save_parameters(self):\n\n # eigenvectors are the coefficients of an ellipse in general form\n # a*x^2 + 2*b*x*y + c*y^2 + 2*d*x + 2*f*y + g = 0 [eqn. 15) from (**) or (***)\n a = self.coef[0, 0]\n b = self.coef[1, 0]/2.\n c = self.coef[2, 0]\n d = self.coef[3, 0]/2.\n f = self.coef[4, 0]/2.\n g = self.coef[5, 0]\n\n # finding center of ellipse [eqn.19 and 20] from (**)\n x0 = (c*d-b*f)/(b**2.-a*c)\n y0 = (a*f-b*d)/(b**2.-a*c)\n\n # Find the semi-axes lengths [eqn. 21 and 22] from (**)\n numerator = 2*(a*f*f+c*d*d+g*b*b-2*b*d*f-a*c*g)\n denominator1 = (b*b-a*c) * \\\n ((c-a)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))\n denominator2 = (b*b-a*c) * \\\n ((a-c)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))\n width = np.sqrt(numerator/denominator1)\n height = np.sqrt(numerator/denominator2)\n\n # angle of counterclockwise rotation of major-axis of ellipse to x-axis [eqn. 23] from (**)\n # or [eqn. 26] from (***).\n phi = .5*np.arctan((2.*b)/(a-c))\n\n self._center = [x0, y0]\n self._width = width\n self._height = height\n self._phi = phi",
"def plot_ellipsoid_2D(p, q, ax, n_points=100, color=\"r\"):\n plt.sca(ax)\n r = nLa.cholesky(q).T; # checks spd inside the function\n t = np.linspace(0, 2 * np.pi, n_points);\n z = [np.cos(t), np.sin(t)];\n ellipse = np.dot(r, z) + p;\n handle, = ax.plot(ellipse[0, :], ellipse[1, :], color)\n\n return ax, handle",
"def __init__(\n self,\n newE0=None,\n newE1=None,\n newE2=None,\n newMaximumHorizontalProjection=None,\n newMaximumVerticalProjection=None,\n newEquivalentHorizontalRadius=None,\n ):\n\n # Required Keys\n if newE0 is not None:\n self.e0 = newE0\n else:\n self.e0 = processingformats.errorEllipseAxis.ErrorEllipseAxis()\n\n if newE1 is not None:\n self.e1 = newE1\n else:\n self.e1 = processingformats.errorEllipseAxis.ErrorEllipseAxis()\n\n if newE2 is not None:\n self.e2 = newE2\n else:\n self.e2 = processingformats.errorEllipseAxis.ErrorEllipseAxis()\n\n if newMaximumHorizontalProjection is not None:\n self.maximumHorizontalProjection = newMaximumHorizontalProjection\n\n if newMaximumVerticalProjection is not None:\n self.maximumVerticalProjection = newMaximumVerticalProjection\n\n if newEquivalentHorizontalRadius is not None:\n self.equivalentHorizontalRadius = newEquivalentHorizontalRadius",
"def ellipsoid_area(radius1: number, radius2: number, radius3: number) -> number:\n p = 1.6075\n volume = 4*pi((radius1**p*radius2**p+radius2**p*radius3**p+radius3**p*radius1**p)**1/p)/3\n return volume",
"def polarization_ellipse(self):\n self.ellipse = {}\n self.ellipse['d_lin'] = sqrt(self.Q**2 + self.U**2)/self.I\n self.ellipse['d_cir'] = abs(self.V)/self.I\n self.ellipse['d'] = sqrt(self.Q**2 + self.U**2 + self.V**2)/self.I\n if self.Q:\n self.ellipse['theta'] = 0.5*atan(self.U/self.Q)\n else:\n self.ellipse['theta'] = float('NaN')\n self.logger.debug(\"polarization_ellipse: theta = %f\",\n self.ellipse['theta'])\n\n if (self.Q**2 + self.U**2):\n self.ellipse['beta'] = 0.5*atan(self.V/sqrt(self.Q**2 + self.U**2))\n if self.V:\n self.ellipse['eccen'] = tan(self.ellipse['beta'])\n else:\n self.ellipse['eccen'] = 0.\n else:\n self.ellipse['beta'] = pi/4\n self.ellipse['eccen'] = 1.\n self.logger.debug(\"polarization_ellipse: beta = %f\",\n self.ellipse['beta'])\n self.logger.debug(\"polarization_ellipse: eccen = %f\",\n self.ellipse['eccen'])",
"def ellipse(x,y,a,b):\n return ((x/float(a))**2 + (y/float(b))**2)",
"def create_ellipse(self, ratio):\n circ = Point(self.center).buffer(1.0)\n ell = affinity.scale(circ, float(\n self.lengths[0]*ratio), float(self.lengths[1]*ratio))\n ellr = affinity.rotate(ell, self.angle)\n return ellr",
"def make_mage_ellipsoids(ids, coord_dict, coord_low_dict,\n coord_high_dict, color, ellipsoid_prefs=\\\n {\"smoothness\":2,\"alpha\":.25}):\n alpha = ellipsoid_prefs['alpha']\n nsubdivs = ellipsoid_prefs['smoothness']\n result = []\n coord_lines = []\n for id_ in sorted(ids):\n if id_ in coord_dict:\n center = coord_dict[id_][:3]\n dims = coord_high_dict[id_][:3] - coord_low_dict[id_][:3]\n\n faces = make_ellipsoid_faces(center, dims, nsubdivs=nsubdivs)\n for face in faces:\n result.append(\"@trianglelist color=%s alpha=%f master={points} nobutton\" %(color, alpha))\n for point in face:\n result.append(' '.join(map(str,point)))\n return result",
"def __init__(self, x=0, y=0, a=2, b=1, ang=0):\n self.center = (x, y)\n self.lengths = (a, b)\n self.angle = ang\n # self.eps = create_ellipse(self.center, self.lengths, self.angle)",
"def ellipsoid_volume(radius1: number, radius2: number, radius3: number) -> number:\n volume = 4/3*(pi*radius1*radius2*radius3)\n return volume",
"def A_coefficients_ellipsoid(v, DD, bDDisDelta=False):\n #v can be given as an array with X/Y/Z cartesian dimensions being the last.\n #\"\"\"\n if bDDisDelta:\n delta=DD\n else:\n delta=Ddelta_ellipsoid(dd)\n #v=_sanitise_v(v)\n #v2=np.square(v)\n #v4=np.square(v2)\n #fact2=np.multiply(0.75,np.sum(v4))-0.25\n v2 = [ v[i]*v[i] for i in range(3) ]\n v4 = [ v2[i]*v2[i] for i in range(3) ]\n fact2 = 0.25*( 3.0*(v4[0]+v4[1]+v4[2])-1.0)\n fact3 = 1.0/12.0*(delta[0]*(3*v4[0]+6*v2[1]*v2[2]-1) + delta[1]*(3*v4[1]+6*v2[0]*v2[2]-1) + delta[2]*(3*v4[2]+6*v2[0]*v2[1]-1))\n A=np.zeros(5)\n A[0]= 3*v2[1]*v2[2]\n A[1]= 3*v2[0]*v2[2]\n A[2]= 3*v2[0]*v2[1]\n A[3]= fact2-fact3\n A[4]= fact2+fact3\n return A",
"def _gen_ellipse(twiss, ep=1, num=100):\n a, b, c = twiss\n\n t = np.linspace(0, 2 * np.pi, num)\n t0 = np.arctan(a)\n x = np.sqrt(b * ep) * np.cos(t)\n y = np.sqrt(c * ep) * np.sin(t - t0)\n\n return np.vstack([x, y])",
"def plot_ellipsoid_3D(p, q, ax, n_points=100):\n\n assert np.shape(p) == (3, 1), \"p needs to be a 3x1 vector\"\n assert np.shape(q) == (3, 3), \"q needs to be a spd 3x3 matrix\"\n assert np.allclose(q, 0.5 * (q + q.T), \"q needs to be spd\")\n # transform to radius/center parametrization\n U, s, rotation = linalg.svd(q)\n assert np.all(s > 0), \"q needs to be positive definite\"\n radii = 1.0 / np.sqrt(s)\n\n # get x,y,z of sphere and transform\n u = np.linspace(0.0, 2.0 * np.pi, n_points)\n v = np.linspace(0.0, np.pi, n_points)\n x = radii[0] * np.outer(np.cos(u), np.sin(v))\n y = radii[1] * np.outer(np.sin(u), np.sin(v))\n z = radii[2] * np.outer(np.ones_like(u), np.cos(v))\n for i in range(len(x)):\n for j in range(len(x)):\n [x[i, j], y[i, j], z[i, j]] = np.dot([x[i, j], y[i, j], z[i, j]],\n rotation) + center\n\n # plot the result\n ax.plot_wireframe(x, y, z, rstride=4, cstride=4, color='b', alpha=0.2)\n return ax",
"def get_proj(self):\n relev, razim = np.pi * self.elev/180, np.pi * self.azim/180\n\n xmin, xmax = self.get_xlim3d()/self.pbaspect[0]\n ymin, ymax = self.get_ylim3d()/self.pbaspect[1]\n zmin, zmax = self.get_zlim3d()/self.pbaspect[2]\n\n # transform to uniform world coordinates 0-1.0,0-1.0,0-1.0 \n worldM = proj3d.world_transformation(xmin, xmax,\n ymin, ymax,\n zmin, zmax)\n\n # look into the middle of the new coordinates \n R = np.array([0.5, 0.5, 0.5])\n\n xp = R[0] + np.cos(razim) * np.cos(relev) * self.dist\n yp = R[1] + np.sin(razim) * np.cos(relev) * self.dist\n zp = R[2] + np.sin(relev) * self.dist\n E = np.array((xp, yp, zp))\n\n self.eye = E\n self.vvec = R - E\n self.vvec = self.vvec / proj3d.mod(self.vvec)\n\n if abs(relev) > np.pi/2:\n # upside down \n V = np.array((0, 0, -1))\n else:\n V = np.array((0, 0, 1))\n\n zfront, zback = -self.dist, self.dist\n\n viewM = proj3d.view_transformation(E, R, V)\n perspM = proj3d.persp_transformation(zfront, zback)\n M0 = np.dot(viewM, worldM)\n M = np.dot(perspM, M0)\n return M",
"def ellipseDesc(lps):\r\n unit = 100 #units in QualiTree are in [mm], hence Pgl is in [dm] ?\r\n\r\n if isinstance(lps, pgl.Translated):\r\n cx, cy, cz = lps.translation\r\n else:\r\n print\"missing Translated from the bounding ellipse as a Translated(Rotated(Scaled(Sphere)))\"\r\n\r\n ori = lps.geometry\r\n\r\n if isinstance(ori, pgl.Oriented):\r\n rotMat = ori.transformation().getMatrix3()\r\n az, el, roll = rotMat.eulerAnglesZYX()\r\n else:\r\n print\"missing Oriented from the bounding ellipse as a Translated(Rotated(Scaled(Sphere)))\"\r\n az = 0\r\n \r\n scal = ori.geometry\r\n\r\n if isinstance(scal, pgl.Scaled):\r\n scMat = scal.transformation().getMatrix()\r\n rx, ry, rz, rt = scMat.getDiagonal()\r\n else:\r\n print\"missing Scaled from the bounding ellipse as a Translated(Rotated(Scaled(Sphere)))\"\r\n rx=ry=rz=1\r\n\r\n #x1, y1, z1 #Conversion repère MappleT (m) à reprère Qualitree (q) : Xq=Xm Yq=Zm Zq=-Ym. \r\n #Due to change of coordinate axis, rotation needs - pi <-- apparently not !\r\n #return cx*unit, cz*unit, -cy*unit, rx*unit, rz*unit, ry*unit, az-3.1415927\r\n\r\n return cx*unit, cz*unit, -cy*unit, rx*unit, rz*unit, ry*unit, az",
"def sample_ellipsoid(p0, covmat, size=1):\n return np.random.multivariate_normal(np.atleast_1d(p0),\n np.atleast_2d(covmat),\n size=size)",
"def add_ellipse(self, centroid, length, width, angle, asymmetry=0.0,\n **kwargs):\n ellipse = Ellipse(xy=centroid, width=length, height=width,\n angle=np.degrees(angle), fill=False, **kwargs)\n self.axes.add_patch(ellipse)\n self.update()\n return ellipse",
"def generate_sphere_full():\n \n num_voxels = 31\n c = (15.0, 15.0, 15.0)\n\n data_x = []\n data_y = []\n data_z = []\n data_intensity = []\n\n volume = numpy.zeros((num_voxels, num_voxels, num_voxels))\n\n for x in range(num_voxels):\n for y in range(num_voxels):\n for z in range(num_voxels):\n\n if numpy.sqrt((x-c[0])**2 + (y-c[1])**2 + (z-c[2])**2) - 7.5 < 1.5:\n data_x.append(x)\n data_y.append(y)\n data_z.append(z)\n data_intensity.append(200.0)\n\n volume[x,y,z] = 200.0\n\n\n return data_x, data_y, data_z, data_intensity, volume",
"def create_ellipse(width, height, color):\n num_segments = 64\n\n data = []\n\n for segment in range(num_segments + 1):\n theta = 2.0 * 3.1415926 * segment / num_segments\n\n x = width * math.cos(theta)\n y = height * math.sin(theta)\n\n data.extend([x, y])\n\n vbo_id = GL.GLuint()\n\n GL.glGenBuffers(1, ctypes.pointer(vbo_id))\n\n v2f = data\n data2 = (GL.GLfloat * len(v2f))(*v2f)\n\n GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo_id)\n GL.glBufferData(GL.GL_ARRAY_BUFFER, ctypes.sizeof(data2), data2,\n GL.GL_STATIC_DRAW)\n\n shape = VertexBuffer(vbo_id, len(v2f) // 2, width, height, color)\n return shape"
] | [
"0.6899035",
"0.6276094",
"0.6101649",
"0.60961974",
"0.6080594",
"0.6074945",
"0.59764946",
"0.59272504",
"0.5871167",
"0.58074254",
"0.5727118",
"0.5713009",
"0.56693137",
"0.5612375",
"0.55892706",
"0.5580605",
"0.55348873",
"0.5517559",
"0.54463154",
"0.5418912",
"0.54049337",
"0.53731424",
"0.532545",
"0.5321421",
"0.53190637",
"0.52909935",
"0.52643144",
"0.5263936",
"0.5253603",
"0.5247925"
] | 0.78283316 | 0 |
Render an inventory menu, which displays the items in the inventory, and the letter to select them. Will move to a different position based on where the player is located, so the player can always see where they are. | def render_inventory_menu(console: Console, engine: Engine) -> None:
console.draw_frame(80, 0, 20, 43, "INVENTORY", True,
fg=(255, 255, 255),
bg=(0, 0, 0))
number_of_items_in_inventory = len(engine.player.inventory.items)
width = 20
# number_of_items_in_inventory + 2
height = engine.player.inventory.capacity + 2
if height <= 3:
height = 3
# TODO: Fix these values, not quite right
if engine.player.x <= 20:
x = 20
else:
x = 0
if engine.player.y <= 20:
y = 20
else:
y = 0
# console.draw_frame(x=x, y=y, width=width, height=height, title="Inventory", clear=True, fg=(255, 255, 255),
# bg=(0, 0, 0))
letter_index = ord('a')
for i in range(engine.player.inventory.capacity):
try:
text = f"({chr(letter_index)}) {engine.player.inventory.items[i].name}"
except AttributeError:
text = f"({chr(letter_index)})"
console.print(81, y=i+1, string=text)
letter_index += 1 | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def inventory(game):\n\n # Offset for displaying list on-screen\n x, y = 6, 2\n # Currently selected item\n selection = 0\n # Max number of items shown at once\n max_items = 10\n # Number of items scrolled through so far\n scrolled = 0\n # Offset for messages\n x_msg, y_msg = 2, max_items + 4\n\n game.window.clear()\n while True:\n # Draw selection cursor\n game.window.addstr(y + selection - scrolled, x - 4, CURSOR)\n\n # Get items between current scroll amount and max_items\n items = list(enumerate(game.player.items))[scrolled:scrolled+max_items]\n\n # Print each item in inventory\n for i, item in items:\n # If more than 1, put the quantity\n if item.quantity > 1:\n formatted = '{}: {} x {}\\n'.format(i, item.quantity, item.name)\n else:\n formatted = '{}: {}\\n'.format(i, item.name)\n\n game.window.addstr(i + y - scrolled, x, formatted)\n\n # If equipped, put a little star next to the item\n if item in game.player.equipment.values():\n game.window.addstr(i + y - scrolled, x - 2, '*')\n\n key = game.window.getkey()\n\n if key == 'k' or key == 'KEY_UP':\n if selection > 0:\n selection -= 1\n\n # If the user tries to go above the screen, scroll up by one\n if selection < scrolled:\n scrolled -= 1\n\n game.window.clear()\n\n if key == 'j' or key == 'KEY_DOWN':\n if selection < len(game.player.items) - 1:\n selection += 1\n\n # If the user tries to go below the screen, scroll down by one\n if selection > scrolled + max_items - 1:\n scrolled += 1\n\n game.window.clear()\n\n if key == 'e':\n # Equip the selected item\n if game.player.items[selection].equippable:\n game.player.equip(game.player.items[selection])\n game.window.clear()\n else:\n game.window.addstr(y_msg, x_msg, \"Cannot equip non-equippable item\")\n\n if key == 'c':\n # Eat the selected item\n if game.player.items[selection].kind == 'food':\n heal = game.player.items[selection].stats['hp']\n game.player.eat(game.player.items[selection])\n\n # Put selection cursor back to an item\n selection -= 1\n game.window.clear()\n\n game.window.addstr(y_msg, x_msg, \"Healed for {} hp\".format(heal))\n else:\n game.window.addstr(y_msg, x_msg, \"Cannot eat non-food item\")\n\n if key == 'l':\n # Print the item name and description\n item = game.player.items[int(selection)]\n game.window.addstr(y_msg, x_msg, '{}\\n\\n{}'.format(item.name, item.desc))\n\n if key == 'q':\n break\n\n if key == '?':\n help_inventory(game)\n continue",
"def show_inventory(self):\n\t\tclear_screen()\n\n\t\tprint(\"# INVENTORY #\\n\")\n\t\tprint(\"Weapon{:.>15} \".format(self.inventory['Weapon']))\n\t\tprint(\"Clothing{:.>13} \".format(self.inventory['Clothing']))\n\t\tprint(\"Items{:.>16} \".format(self.inventory['Items']))\n\n\t\tpress_enter()",
"def print_menu():\r\n\r\n print('Menu\\n\\n[l] load Inventory from file\\n[a] Add CD\\n[i] Display Current Inventory')\r\n print('[d] Delete CD from Inventory\\n[s] Save Inventory to file\\n[x] exit\\n')",
"def print_menu():\r\n\r\n print('Menu\\n\\n[l] load Inventory from file\\n[a] Add CD\\n[i] Display Current Inventory')\r\n print('[d] delete CD from Inventory\\n[s] Save Inventory to file\\n[x] exit\\n')",
"def help_inventory(game):\n game.window.clear()\n\n res = \"\"\"Inventory screen\n\n up and down to select item\n\n e to equip item\n l to examine\n\n ? -- this help\n \"\"\"\n\n game.window.addstr(res)\n game.window.getch()",
"def __init__(self, inventory, player, npc):\n super().__init__(\"shop_menu.png\", (80, 1), world_bound=False)\n self._is_dead = False # Status of the event\n\n # Store arguments\n self._player = player\n self._npc = npc\n\n # Extract inventory from npc (store clerk)\n self._inventory = inventory\n\n # Concert inventory keys to a list so that cancel can be added and\n # looped over to concisely display all options.\n self._inventory_list = list(self._inventory.keys()) + [\"CANCEL\"]\n\n # Variable used to determine which 5 items from the store to display.\n self.start_item_index = 0\n\n # Cursor that keeps track of where the black cursor is on the menu.\n self.draw_cursor = Cursor(min(6, len(self._inventory_list)),\n initial_pos=(88, 13), line_height=16)\n\n # Cursor that keeps track of which item in the store is currently\n # selected. Two cursors are needed because it is possible for a store\n # to sell more than five items (the amount displayed on the screen at\n # once).\n self.item_cursor = Cursor(len(self._inventory_list))\n\n # Create bobbing cursors\n self.down_bobbing_cursor = TextCursor((153, 100),\n \"shop_menu_cursor.png\")\n self.up_bobbing_cursor = TextCursor((153, 3),\n \"shop_menu_cursor_f.png\",\n invert=True)\n\n # Decide if the down cursor should be updated right off of the start\n self._update_cursor_status()\n\n # Create the 5 item surfaces (which says the items name and price).\n self.create_item_surface()\n\n # Get the description of the first item for sale.\n self.create_item_desc_surf()\n self.create_item_pic_surf()\n\n # Instatiate the various sub events.\n self.select_count_event = None\n self.confirm_buy_response = None\n self.thanks_dialogue = None\n\n # Variable which when turned true will signal to the level manager\n # that it needs to redraw the current level to clear the events screen.\n self.turned = False\n\n # Variable which keeps track of an item that the user might buy.\n # Necessary because we double check if the user wants to buy the item.\n self.pending_buy = None\n\n # Variable which signals the PokeMartEvent that the user's money has\n # changed. In this case it will have decreased.\n self.player_money_updated = False",
"def openinv(cls): #THIS DOESN'T NEED TO BE MODIFIED!\n\n while True:\n inventory_items = {thing.id: thing.name for thing in cls.inventory}\n inventory_items[\"exit\"] = \"Exit Inventory\"\n inventory_items[\"newln\"] = \"\"\n inventory_items[\"playername\"] = str(gray('\"{}\"'.format(cls.name)))\n inventory_items[\"lv\"] = str(gray(\"LV: {}\".format(cls.lv)))\n inventory_items[\"hp\"] = str(gray(\"HP: {}/{}\".format(cls.hp, cls.max_hp)))\n inventory_items[\"exp\"] = str(gray(\"EXP: {}/40\".format(cls.exp)))\n\n choice = Menu.menu(\n title = \"Inventory\",\n contents = inventory_items \n )\n if choice == \"exit\":\n Terminal.clear_all()\n return\n while True:\n displayed_item = next((thing for thing in cls.inventory if thing.id == choice), None)\n final_choice = Menu.menu(\n title = displayed_item.name,\n contents = {\n \"interact\":displayed_item.interact_label,\n \"inspect\":\"Inspect\",\n \"drop\":\"Drop\",\n \"back\":\"Back\"\n }\n )\n if final_choice == \"back\":\n break\n if final_choice == \"interact\":\n use = displayed_item.interact()\n Terminal.clear_all()\n print(use[\"message\"])\n if \"heal_\" in use[\"action\"]:\n cls.hp += int(use[\"action\"].replace(\"heal_\", ''))\n if cls.hp > cls.max_hp:\n cls.hp = cls.max_hp\n cls.inventory.remove(displayed_item)\n Game.standard_wait()\n break\n if final_choice == \"inspect\":\n Terminal.clear_all()\n print(displayed_item)\n Game.standard_wait()\n continue\n if final_choice == \"drop\":\n Terminal.clear_all()\n print(\"You dropped the {}\".format(displayed_item.name))\n cls.inventory.remove(displayed_item)\n Game.standard_wait()\n break",
"def print_menu():\r\n \r\n print('Menu: \\n\\n[1] Load Inventory from File\\n[2] Add CD\\n[3] Display Current Inventory')\r\n print('[4] Delete CD from Inventory\\n[5] Save Inventory to file\\n[0] Exit Program\\n')",
"def menu(exits, room_items, inv_items):\r\n # Read player's input\r\n user_input = input(\"> \")\r\n\r\n # Normalise the input\r\n normalised_user_input = normalise_input(user_input)\r\n\r\n return normalised_user_input",
"def display_inventory(self) -> None:\n\n print(\"Your current inventory includes:\\n\" + \" | \".join(self.player.inventory))",
"def menu(self):\n ## This is a DICTIONARY, it's a list with custom index values. Python is cool.\n # Please feel free to change the menu and add options.\n print(\"\\n *** MENU ***\") \n menu = {\"c\": (\"Calibrate\", self.calibrate),\n \"d\": (\"Dance\", self.dance),\n \"h\": (\"Hold position\", self.hold_position),\n \"n\": (\"Navigate\", self.nav),\n \"o\": (\"Obstacle count\", self.obstacle_count),\n \"q\": (\"Quit\", self.quit),\n \"v\": (\"Veer\", self.slither)\n }\n # loop and print the menu...\n for key in sorted(menu.keys()):\n print(key + \":\" + menu[key][0])\n # store the user's answer\n ans = str.lower(input(\"Your selection: \"))\n # activate the item selected\n menu.get(ans, [None, self.quit])[1]()",
"def draw( self, screen, character):\r\n\r\n if self.is_visible == False: return\r\n \r\n window.Window.draw(self, screen)\r\n\r\n name_font = self.menu_font.render( character.name, True, COLOR_WHITE)\r\n\r\n screen.blit( name_font, (self.left+20, self.top+20))\r\n screen.blit( self.top_font, (self.left+20+name_font.get_width(), self.top+20))\r\n\r\n #draw the box on item selected\r\n if character.items != []:\r\n #draws rectangle on the menu item size of rectangle has width of window rectangle - edge_length*2\r\n #the height depends on the size of font\r\n pygame.draw.rect(screen, COLOR_GLAY, Rect( self.left+4, self.top+55 + 30*self.menu,(self.right-self.left)-8,30), 0)\r\n\r\n\r\n i = 0\r\n for item in character.items:\r\n item_font = self.menu_font.render( item.name, True, COLOR_WHITE)\r\n screen.blit ( item_font, (self.left+20, self.top+60+i*30))\r\n cost_font = self.menu_font.render( str(item.price/2) + \"TG\", True, COLOR_WHITE)\r\n screen.blit( cost_font, (self.right-20 - cost_font.get_width(), self.top+60+i*30))\r\n\r\n i += 1\r\n\r\n\r\n self.sold_item_window.draw(screen)",
"def menu(self):\n ## This is a DICTIONARY, it's a list with custom index values. Python is cool.\n # Please feel free to change the menu and add options.\n print(\"\\n *** MENU ***\") \n menu = {\"n\": (\"Navigate\", self.nav),\n \"d\": (\"Dance\", self.dance),\n \"o\": (\"Obstacle count\", self.obstacle_count),\n \"s\": (\"Shy\", self.shy),\n \"f\": (\"Follow\", self.follow),\n \"c\": (\"Calibrate\", self.calibrate),\n \"q\": (\"Quit\", self.quit)\n }\n # loop and print the menu...\n for key in sorted(menu.keys()):\n print(key + \":\" + menu[key][0])\n # store the user's answer\n ans = str.lower(input(\"Your selection: \"))\n # activate the item selected\n menu.get(ans, [None, self.quit])[1]()",
"def menu(self):\n ## This is a DICTIONARY, it's a list with custom index values. Python is cool.\n # Please feel free to change the menu and add options.\n print(\"\\n *** MENU ***\") \n menu = {\"n\": (\"Navigate\", self.nav),\n \"d\": (\"Dance\", self.dance),\n \"o\": (\"Obstacle count\", self.obstacle_count),\n \"s\": (\"Shy\", self.shy),\n \"f\": (\"Follow\", self.follow),\n \"c\": (\"Calibrate\", self.calibrate),\n \"q\": (\"Quit\", self.quit)\n }\n # loop and print the menu...\n for key in sorted(menu.keys()):\n print(key + \":\" + menu[key][0])\n # store the user's answer\n ans = str.lower(input(\"Your selection: \"))\n # activate the item selected\n menu.get(ans, [None, self.quit])[1]()",
"def switch_to_inventory_screen(self, player):\n\t\tcontrols = InventoryControls(player)\n\t\tcontrol_manager = ControlManager(controls)\n\t\tinventory_screen = InventoryScreen(control_manager, player)\n\t\tself.set_current_screen(inventory_screen)",
"def dumbmenu(screen, menu, x_pos = 100, y_pos = 100, font = None,\n size = 70, distance = 1.4, fgcolor = (255,255,255),\n cursorcolor = (255,0,0), exitAllowed = True):\n\n\n\t# Draw the Menupoints\n\tpygame.font.init()\n\tif font == None:\n\t\tmyfont = pygame.font.Font(None, size)\n\telse:\n\t\tmyfont = pygame.font.SysFont(font, size)\n\tcursorpos = 0\n\trenderWithChars = False\n\tfor i in menu:\n\t\tif renderWithChars == False:\n\t\t\ttext = myfont.render(str(cursorpos + 1)+\". \" + i,\n\t\t\t\tTrue, fgcolor)\n\t\telse:\n\t\t\ttext = myfont.render(chr(char)+\". \" + i,\n\t\t\t\tTrue, fgcolor)\n\t\t\tchar += 1\n\t\ttextrect = text.get_rect()\n\t\ttextrect = textrect.move(x_pos, \n\t\t (size // distance * cursorpos) + y_pos)\n\t\tscreen.blit(text, textrect)\n\t\tpygame.display.update(textrect)\n\t\tcursorpos += 1\n\t\tif cursorpos == 9:\n\t\t\trenderWithChars = True\n\t\t\tchar = 65\n\n\t# Draw the \">\", the Cursor\n\tcursorpos = 0\n\tcursor = myfont.render(\">\", True, cursorcolor)\n\tcursorrect = cursor.get_rect()\n\tcursorrect = cursorrect.move(x_pos - (size // distance),\n\t (size // distance * cursorpos) + y_pos)\n\n\t# The whole While-loop takes care to show the Cursor, move the\n\t# Cursor and getting the Keys (1-9 and A-Z) to work...\n\tArrowPressed = True\n\texitMenu = False\n\tclock = pygame.time.Clock()\n\tfiller = pygame.Surface.copy(screen)\n\tfillerrect = filler.get_rect()\n\twhile True:\n\t\tclock.tick(30)\n\t\tif ArrowPressed == True:\n\t\t\tscreen.blit(filler, fillerrect)\n\t\t\tpygame.display.update(cursorrect)\n\t\t\tcursorrect = cursor.get_rect()\n\t\t\tcursorrect = cursorrect.move(x_pos - (size // distance),\n\t\t\t (size // distance * cursorpos) + y_pos)\n\t\t\tscreen.blit(cursor, cursorrect)\n\t\t\tpygame.display.update(cursorrect)\n\t\t\tArrowPressed = False\n\t\tif exitMenu == True:\n\t\t\tbreak\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\treturn -1\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE and exitAllowed == True:\n\t\t\t\t\tif cursorpos == len(menu) - 1:\n\t\t\t\t\t\texitMenu = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tcursorpos = len(menu) - 1; ArrowPressed = True\n\n\n\t\t\t\t# This Section is huge and ugly, I know... But I don't\n\t\t\t\t# know a better method for this^^\n\t\t\t\tif event.key == pygame.K_1:\n\t\t\t\t\tcursorpos = 0; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_2 and len(menu) >= 2:\n\t\t\t\t\tcursorpos = 1; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_3 and len(menu) >= 3:\n\t\t\t\t\tcursorpos = 2; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_4 and len(menu) >= 4:\n\t\t\t\t\tcursorpos = 3; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_5 and len(menu) >= 5:\n\t\t\t\t\tcursorpos = 4; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_6 and len(menu) >= 6:\n\t\t\t\t\tcursorpos = 5; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_7 and len(menu) >= 7:\n\t\t\t\t\tcursorpos = 6; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_8 and len(menu) >= 8:\n\t\t\t\t\tcursorpos = 7; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_9 and len(menu) >= 9:\n\t\t\t\t\tcursorpos = 8; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_a and len(menu) >= 10:\n\t\t\t\t\tcursorpos = 9; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_b and len(menu) >= 11:\n\t\t\t\t\tcursorpos = 10; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_c and len(menu) >= 12:\n\t\t\t\t\tcursorpos = 11; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_d and len(menu) >= 13:\n\t\t\t\t\tcursorpos = 12; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_e and len(menu) >= 14:\n\t\t\t\t\tcursorpos = 13; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_f and len(menu) >= 15:\n\t\t\t\t\tcursorpos = 14; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_g and len(menu) >= 16:\n\t\t\t\t\tcursorpos = 15; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_h and len(menu) >= 17:\n\t\t\t\t\tcursorpos = 16; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_i and len(menu) >= 18:\n\t\t\t\t\tcursorpos = 17; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_j and len(menu) >= 19:\n\t\t\t\t\tcursorpos = 18; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_k and len(menu) >= 20:\n\t\t\t\t\tcursorpos = 19; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_l and len(menu) >= 21:\n\t\t\t\t\tcursorpos = 20; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_m and len(menu) >= 22:\n\t\t\t\t\tcursorpos = 21; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_n and len(menu) >= 23:\n\t\t\t\t\tcursorpos = 22; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_o and len(menu) >= 24:\n\t\t\t\t\tcursorpos = 23; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_p and len(menu) >= 25:\n\t\t\t\t\tcursorpos = 24; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_q and len(menu) >= 26:\n\t\t\t\t\tcursorpos = 25; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_r and len(menu) >= 27:\n\t\t\t\t\tcursorpos = 26; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_s and len(menu) >= 28:\n\t\t\t\t\tcursorpos = 27; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_t and len(menu) >= 29:\n\t\t\t\t\tcursorpos = 28; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_u and len(menu) >= 30:\n\t\t\t\t\tcursorpos = 29; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_v and len(menu) >= 31:\n\t\t\t\t\tcursorpos = 30; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_w and len(menu) >= 32:\n\t\t\t\t\tcursorpos = 31; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_x and len(menu) >= 33:\n\t\t\t\t\tcursorpos = 32; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_y and len(menu) >= 34:\n\t\t\t\t\tcursorpos = 33; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_z and len(menu) >= 35:\n\t\t\t\t\tcursorpos = 34; ArrowPressed = True; exitMenu = True\n\t\t\t\telif event.key == pygame.K_UP:\n\t\t\t\t\tArrowPressed = True\n\t\t\t\t\tif cursorpos == 0:\n\t\t\t\t\t\tcursorpos = len(menu) - 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tcursorpos -= 1\n\t\t\t\telif event.key == pygame.K_DOWN:\n\t\t\t\t\tArrowPressed = True\n\t\t\t\t\tif cursorpos == len(menu) - 1:\n\t\t\t\t\t\tcursorpos = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\tcursorpos += 1\n\t\t\t\telif event.key == pygame.K_KP_ENTER or \\\n\t\t\t\t event.key == pygame.K_RETURN:\n\t\t\t\t\t\t\texitMenu = True\n\t\n\treturn cursorpos",
"def display_inventory(self):\n header = \"Carrying:\\n\"\n nothing_func = lambda *args: None\n action_list = [(item, nothing_func) for item in self.inventory]\n if len(action_list) == 0:\n header += \"Nothing at all\"\n events.trigger_event(\"print_list\", action_list, header=header)",
"def print_inventory(self):\n\t\tfor item, amount in self.inventoryDictionary.items():\n\t\t\tprint (\"Item: \" + item.name + \" Quantity: \" + str(amount))\n\t\t\tprint (item.description + \"\\n\")\n\n\t\tprint(\"Currently equipped: \")\n\t\tprint(\"Main Hand: \" + self.equippedMainHand.name)\n\t\tprint(\"Armor: \" + self.equippedArmor.name)",
"def side_menu(self, screen):\n font = pg.font.Font('freesansbold.ttf', 30) \n text = font.render('Menu', True, (120,130,135))\n textRect = text.get_rect()\n textRect.center = (1100, 180)\n screen.blit(text, textRect)",
"def chooseInventoryItem(self, Title = \"\", Filter = []):\n InventoryMenu = UI.MenuClass()\n InventoryMenu.Title = Title\n\n #Show all inventory items if Filter not specified\n if Filter == []: ShowAll = 1\n else: ShowAll = 0\n\n #Generate inventory menu\n MyInvMenu = {} #Dictionary (item type : list of items)\n for InvItem in self.List:\n if InvItem.Base.Type in Filter or ShowAll:\n if not InvItem.Base.Type in MyInvMenu:\n #Create new dictionary key if it isn't here\n MyInvMenu[InvItem.Base.Type] = []\n MyInvMenu[InvItem.Base.Type].append(InvItem)\n\n #Merge list of all inventory items, sorted by type\n MyInvMenuData = []\n for InvItemKey in MyInvMenu:\n MyInvMenuData += MyInvMenu[InvItemKey]\n\n\n #Form the menu\n InventoryMenu.clear()\n\n for InvItemKey in MyInvMenu:\n InventoryMenu.addSeparator(\"--\" + InvItemKey + \"--\")\n for InvItem in MyInvMenu[InvItemKey]:\n if InvItem.Count == 1:\n Name = InvItem.Base.descString()\n else:\n Name = InvItem.Base.descString() + \" x\" + str(InvItem.Count)\n if InvItem.Equipped: Name = \"\".join((Name, \" (equipped)\"))\n InventoryMenu.addItem(Name)\n\n #Restore old menu position\n InventoryMenu.restoreMenuPos()\n\n Choice = InventoryMenu.doMenu()\n if InventoryMenu.Returned: return None\n return MyInvMenuData[Choice]",
"def inv(self, command):\n\n side = '|'\n blank = 30 * \" \"\n line = 30 * \"-\"\n diff2 = 11 * \" \"\n if not self.inventory:\n #check to see if the inventory is empty and if there is a weapon equipped\n if not self.weapon:\n print(\"Your inventory is empty and you have nothing in your hands.\")\n else:\n print('Your inventory is empty and you have a ' + self.weapon[0].name + ' in your hands')\n else:\n print(\"{}{}{}\".format('+', line, '+'))\n print(\"{}{}{} {}{}\".format(side, (\" \" * 12), 'Items', (\" \" * 12), side))\n for item in self.inventory:\n diff = (30 - len(item.name)) * \" \"\n print(\"{}{}{}{}\".format(side, item.name, diff, side))\n for thing in self.weapon:\n diff3 = (30 - len(thing.name)) * \" \"\n print(\"{}{}{}\".format('+', line, '+'))\n print(\"{}{}{}{}{}\".format(side, diff2, 'Equipped', diff2, side))\n print(\"{}{}{}{}\".format(side, thing.name, diff3, side))\n print(\"{}{}{}\".format('+', line, '+'))",
"def print_items(self):\n for items in inventory:\n print(f\"- {items.upper()}\")",
"def user_control(board, x_player, y_player, button_pressed, inventory):\n\n red = '\\033[31m'\n reset_color = '\\033[0m'\n item_colors = {\n '●': '\\033[33m', '⚛': '\\033[34m', '✿': '\\033[31m', '✡': '\\033[94m',\n '♦': '\\033[32m', 'ᴥ': '\\033[31m', '☀': '\\033[33m'}\n place_on_right_side = board[y_player][x_player + 1]\n place_on_left_side = board[y_player][x_player - 1]\n place_on_up_side = board[y_player - 1][x_player]\n place_on_down_side = board[y_player + 1][x_player]\n places_prohibited_to_stand_on = [\n 'X', red + '#' + reset_color, '☹', '☃', '♞', '☻', '☬', item_colors['☀'] + '☀' + reset_color, red\n + '☀' + reset_color]\n\n if button_pressed == 'd' and place_on_right_side not in places_prohibited_to_stand_on:\n x_player += 1\n elif button_pressed == 'a' and place_on_left_side not in places_prohibited_to_stand_on:\n x_player -= 1\n elif button_pressed == 'w' and place_on_up_side not in places_prohibited_to_stand_on:\n y_player -= 1\n elif button_pressed == 's' and place_on_down_side not in places_prohibited_to_stand_on:\n y_player += 1\n\n friends = ['☹', '☃', '♞', '☻', '☬']\n # conditions for level 4 (feeding friends)\n if button_pressed == 'd' and place_on_right_side in friends and inventory['●'] > 19:\n x_player += 1\n elif button_pressed == 'a' and place_on_left_side in friends and inventory['●'] > 19:\n x_player -= 1\n elif button_pressed == 'w' and place_on_up_side in friends and inventory['●'] > 19:\n y_player -= 1\n elif button_pressed == 's' and place_on_down_side in friends and inventory['●'] > 19:\n y_player += 1\n return x_player, y_player",
"def menu(selected):\n global levelNum, marioScore\n # Resetting volume and game variables\n if mixer.Channel(0).get_volume() == 0:\n globalSound(\"toggleVol\")\n levelNum = 0\n marioScore= [0, 0, 5]\n running = True\n globalSound(\"stop\") # Stop any music that's playing\n # Menu screen corresponding lists\n textPoints = [[360, 350], [290, 390], [333, 430], [360, 470]]\n textList = [playText, instructText, creditText, quitText]\n returnList = [\"loading\", \"instructions\", \"credit\", \"exit\"]\n while running:\n for evnt in event.get():\n if evnt.type == QUIT:\n return [\"exit\", None]\n if evnt.type == KEYDOWN:\n # Checking for menu screen inputs\n if evnt.key == K_UP or evnt.key == K_w: # Making the cursor go up\n selected -= 1\n elif evnt.key == K_DOWN or evnt.key == K_s: # Making the cursor go down\n selected += 1\n elif evnt.key == K_RETURN: # Selecting an option\n return [returnList[selected], selected]\n # Keeping the cursor within the bounds of the options\n if selected < 0:\n selected = 3\n elif selected > 3:\n selected = 0\n # Drawing the background and buttons\n screen.blit(backgroundPics[0],(0,0)) # Blitting background\n screen.blit(marioSprites[0][0], (40, 496)) # Blitting Mario\n screen.blit(titleLogo,(160,80)) # Blitting title\n for index in range(len(textList)): # Go through all of the menu text and blit it at the corresponding coordinates\n screen.blit(textList[index], (textPoints[index][0], textPoints[index][1]))\n screen.blit(titleSelect, (textPoints[selected][0] - 30, textPoints[selected][1] - 4 )) # Blitting the selected option icon\n display.flip()\n fpsCounter.tick(60)\n return [\"exit\", selected]",
"def choose_item():\n print_items()\n print(\"Type 'back' to go to main menu.\")\n print(\"You can view map by typing in 'blueprint'\")\n while True:\n item_choice = player_choice(\"\")\n if item_choice == 'back':\n break\n elif item_choice in inventory:\n if item_choice == 'blueprint':\n blueprint = ViewMap()\n blueprint.print_map()\n print(\"Type 'back' to go to main menu.\")\n else:\n print(\"Type 'back' to go to main menu.\")\n print(\"You can view map by typing in 'blueprint'\")\n else:\n print(\"Type 'back' to go to main menu.\")",
"def show_right_mouse_menu(self, pos):\n\n globalpos = self.viewport().mapToGlobal(pos)\n\n if not self.selectionModel().hasSelection():\n print(\"No selection\")\n # Build menu without selection, feed an empty list\n menu = self.build_item_menu([])\n menu.exec_(globalpos)\n return\n\n active = self.currentIndex() # index under mouse\n active = active.sibling(active.row(), 0) # get first column\n\n # move index under mouse\n indices = self.get_indices()\n if active in indices:\n indices.remove(active)\n\n indices.append(active)\n\n # Extend to the sub-items\n all_indices = self.extend_to_children(indices)\n nodes = [dict(i.data(InventoryModel.NodeRole)) for i in all_indices\n if i.parent().isValid()]\n\n if self._hierarchy_view:\n # Ensure no group node\n nodes = [n for n in nodes if not n.get(\"isGroupNode\")]\n\n menu = self.build_item_menu(nodes)\n menu.exec_(globalpos)",
"def print_items():\n for items in inventory:\n print(f\"- {items.upper()}\")",
"def create_menu():",
"def DisplayMenu():\n print(\"\\n\\t\\t\\t Video Store \\n\")\n print(\"\"\" 1. Add new Title\n 2. Check out a video\n 3. Return a video\n 4. Receive a rating\n 5. Delete title\n 6. List Inventory\n E. Exit\n \"\"\")",
"def action_menu(player):\n\n\tclear_screen()\n\n\trun_game_log(player, game_log)\t# runs the run_game_log function which gets output from game_log class\n\n\tprint('1. Move')\n\tprint('2. Show Map')\n\tprint('3. Show Player Inventory')\n\tprint('4. Show Player Stats')\n\tprint('5. Exit to Main Menu')\n\n\tpossible_choices = ['1','2','3','4','5']\n\tactive = True\n\n\twhile active:\n\t\tselection = input('\\nNow I shall... ')\n\t\tif selection in possible_choices:\n\t\t\tactive = False\n\t\t\treturn int(selection)\t# return always exits a function, right? so active = False is redundant?\n\t\telse:\n\t\t\tprint('That\\'s not one of the menu options!')"
] | [
"0.73191905",
"0.7254777",
"0.6703341",
"0.6687684",
"0.6648477",
"0.6551185",
"0.6543395",
"0.6526214",
"0.6485202",
"0.6290936",
"0.62841386",
"0.6232132",
"0.61900747",
"0.61900747",
"0.6124227",
"0.61190903",
"0.60794646",
"0.6059572",
"0.60148025",
"0.60062957",
"0.599472",
"0.5978888",
"0.5976128",
"0.5961144",
"0.59321624",
"0.59321207",
"0.5921423",
"0.5897498",
"0.58949125",
"0.5888743"
] | 0.80878377 | 0 |
Create latitudelongitudegrid for specified channel data. A latitudelogitude grid is created from geolocation information from 11 x 11 boxes corresponding to the image data. The resolution and dimension of the image and latitudelogitude grid depend on the specified channel. | def get_latlon_grid(self, channel="1"):
ImageDimension = namedtuple("ImageDimension", ["lon", "lat"])
imagedimension = ImageDimension(
*self._convert_metastr(self.meta[f"IMAGEDATAINFORMATION{channel}"], tuple)[
:2
]
)
lat, lon = self.read_coordinates(channel=channel)
latidx = np.arange(11) * imagedimension.lat / 10
lonidx = np.arange(11) * imagedimension.lon / 10
# Function for interpolation to full domain grid.
flat = interpolate.interp2d(lonidx, latidx, lat, kind="linear")
flon = interpolate.interp2d(lonidx, latidx, lon, kind="linear")
# Grid matching shifted corner coordinates (see above).
latgrid = np.arange(0, int(imagedimension.lat) + 1, 1)
longrid = np.arange(0, int(imagedimension.lon) + 1, 1)
# Apply lat-lon-function to grid and cut off last row and column to get
# the non-shifted grid.
lats = flat(longrid, latgrid)[:-1, :-1]
lons = flon(longrid, latgrid)[:-1, :-1]
return lats, lons | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def make_grid(dataset):\n top_left_lat = dataset[\"a\"][0]\n top_left_lng = dataset[\"a\"][1]\n top_right_lng = dataset[\"c\"][1]\n bot_left_lat = dataset[\"b\"][0]\n\n lng_row = []\n lat_col = []\n i = top_left_lng\n while i < top_right_lng:\n lng_row.append(round(i, 5))\n i += step\n j = bot_left_lat\n while j < top_left_lat:\n lat_col.append(round(j, 5))\n j += step\n out_grid = []\n for i in lat_col:\n row = []\n for j in lng_row:\n row.append(\"{0}:{1}:0\".format(i, j))\n out_grid.append(row)\n return out_grid",
"def make_grid(lat_values, lon_values, np_lat, np_lon):\n \n coordsys = iris.coord_systems.RotatedGeogCS(np_lat, np_lon)\n \n latitude = iris.coords.DimCoord(lat_values,\n standard_name='latitude',\n units='degrees_north',\n coord_system=coordsys)\n longitude = iris.coords.DimCoord(lon_values, \n standard_name='longitude',\n units='degrees_east',\n coord_system=coordsys)\n\n dummy_data = numpy.zeros((len(lat_values), len(lon_values)))\n new_cube = iris.cube.Cube(dummy_data, dim_coords_and_dims=[(latitude, 0), (longitude, 1)])\n \n return new_cube",
"def channel_maps_figure(source):\n # Load data cube\n data_filename = data_rebinned_filepaths[source]\n cube = SpectralCube.read(data_filename)\n # Switch units to km/s (optional)\n cube = cube.with_spectral_unit(u.km/u.s)\n # Get WCS object for 2D spatial image\n wcs_flat = cube[0, :, :].wcs\n # Calculate pixel scale for the spatial image\n pixel_scale = wcs_flat.proj_plane_pixel_scales()[0] # gives RA, Dec scales; pick one. They're almost certainly equal, so doesn't matter\n # Get velocity limits\n # For now, use all the channels in the saved FITS file; can limit them in the future if necessary\n v_lo, v_hi = cube.spectral_axis[0], cube.spectral_axis[-1]\n first_channel_idx = 0 # Using all channels\n last_channel_idx = cube.shape[0] - 1 # Using all channels\n print(\"First and last available channels \", v_lo, v_hi, \" at indices \", first_channel_idx, last_channel_idx)\n\n grid_shape = {\n 'ngc1977': (3, 4), # 12 channels\n 'rcw120': (4, 6), # 21 channels\n 'rcw49': (4, 8), # 31 channels\n }\n figsize = {\n # in inches; fine tune these to remove gaps between the channel maps\n 'ngc1977': (12, 8),\n 'rcw120': (16, 10),\n 'rcw49': (17, 11.5)\n }\n fig = plt.figure(figsize=figsize[source])\n # Matplotlib gridspec setup so that we can have a big colorbar on the side\n # mega_gridspec will contain all the channel maps and the Axes created within it serves as an anchor for the colorbar\n mega_gridspec = fig.add_gridspec(right=0.9, left=0.06, top=0.98, bottom=(0.08 if source=='rcw49' else 0.06))\n # Create a single Axes object from mega_gridspec; this will anchor the colorbar\n mega_axis = mega_gridspec.subplots()\n # Hide the bounding box for this large Axes object\n mega_axis.set_axis_off()\n # Create the channel map gridspec within the large gridspec\n gs = mega_gridspec[0,0].subgridspec(*grid_shape[source], hspace=0, wspace=0)\n # Memoize axes\n axes = {}\n def get_axis(index):\n # Index is 1D index of channel counting from first_channel_idx as 0.\n # In other words, index of the panel in the figure.\n # (if first_channel_idx == 0 then axis index == channel index)\n if index not in axes:\n axes[index] = fig.add_subplot(gs[np.unravel_index(index-first_channel_idx, grid_shape[source])], projection=wcs_flat)\n return axes[index]\n\n # Text defaults\n text_x = 0.05 if source=='rcw49' else 0.5\n text_y = 0.94\n # ha/va are horizontal and vertical alignment\n ha = 'left' if source=='rcw49' else 'center'\n # the color I use there is from Marc's collection of colorblind-friendly colors and works well against \"plasma\"\n default_text_kwargs = dict(fontsize=14, color='#ff7f00', ha=ha, va='center')\n tick_labelsize = 14\n tick_labelrotation = 50 if source=='rcw49' else 25\n tick_labelpad = 26 if source=='rcw49' else 13\n # Colors\n cmap = \"plasma\" # Image colormap\n beam_patch_ec = \"grey\" # edge color\n beam_patch_fc = \"white\" # face color\n # vlims for images (min and max for image colorscales in data units)\n vlims = {\n 'ngc1977': dict(vmin=0, vmax=40),\n 'rcw120': dict(vmin=0, vmax=25),\n 'rcw49': dict(vmin=0, vmax=17)\n }\n\n # Loop through channels and plot\n for channel_idx in range(first_channel_idx, last_channel_idx+1):\n velocity = cube.spectral_axis[channel_idx]\n channel_data = cube[channel_idx].to_value()\n\n print(first_channel_idx, channel_idx, last_channel_idx)\n ### print the [min, mean, median, max] for each panel so that we can find the best vlims (min, max) for all of them\n # print([f(channel_data) for f in (np.nanmin, np.nanmean, np.nanmedian, np.nanmax)])\n\n\n # Setup Axes\n ax = get_axis(channel_idx)\n # Remove x and y labels on individual panels (use the \"super\" titles)\n ax.set_xlabel(\" \")\n ax.set_ylabel(\" \")\n ss = ax.get_subplotspec()\n # Coordinate labels\n if ss.is_last_row() and ss.is_first_col():\n # Coordinates only on bottom left corner panel\n # Mess around with the rotation, position, and size of coordinate labels\n ax.coords[0].set_ticklabel(rotation=tick_labelrotation, rotation_mode='anchor', pad=tick_labelpad, fontsize=tick_labelsize, ha='right', va='top')\n ax.coords[1].set_ticklabel(fontsize=tick_labelsize)\n else:\n # If not the bottom left panel, no coordinates (panels have no space in between)\n # Hide coordinates\n ax.tick_params(axis='x', labelbottom=False)\n ax.tick_params(axis='y', labelleft=False)\n # Plot\n im = ax.imshow(channel_data, origin='lower', cmap=cmap, **vlims[source])\n # Label velocity on each panel\n ax.text(text_x, text_y, f\"{velocity.to_value():.0f} {velocity.unit.to_string('latex_inline')}\", transform=ax.transAxes, **default_text_kwargs)\n # Beam on every panel\n beam_patch = cube.beam.ellipse_to_plot(*(ax.transAxes + ax.transData.inverted()).transform([0.9, 0.1]), pixel_scale)\n beam_patch.set(alpha=0.9, facecolor=beam_patch_fc, edgecolor=beam_patch_ec)\n ax.add_artist(beam_patch)\n\n # Colorbar\n # Create a space to the right of the panels using the height/location of the mega_axis as an anchor\n cbar_ax = mega_axis.inset_axes([1.03, 0, 0.03, 1])\n cbar = fig.colorbar(im, cax=cbar_ax, label='T$_{\\\\rm MB}$ (K)')\n ticks = {\n # 'rcw120'\n }\n # cbar.set_ticks(ticks[source])\n # Titles\n fig.supxlabel(\"Right Ascension\")\n fig.supylabel(\"Declination\")\n\n dpi = 100\n dpi_stub = \"\" if dpi==100 else f\"_dpi{dpi}\"\n\n fig_save_name = f\"channel_maps_{source}{dpi_stub}.png\"\n fig.savefig(\n os.path.join(figure_save_path, fig_save_name),\n dpi=dpi\n )\n print(f\"Figure saved to {os.path.join(figure_save_path, fig_save_name)}\")",
"def googlestatic_mercator_grid(center_ll=None, nx=640, ny=640, zoom=12, scale=1):\n\n # Number of pixels in an image with a zoom level of 0.\n google_pix = 256 * scale\n # The equatorial radius of the Earth assuming WGS-84 ellipsoid.\n google_earth_radius = 6378137.0\n\n # Make a local proj\n lon, lat = center_ll\n projloc = check_crs('epsg:3857')\n\n # The size of the image is multiplied by the scaling factor\n nx *= scale\n ny *= scale\n\n # Meter per pixel\n mpix = (2 * np.pi * google_earth_radius) / google_pix / (2**zoom)\n xx = nx * mpix\n yy = ny * mpix\n\n e, n = transform_proj(wgs84, projloc, lon, lat)\n corner = (-xx / 2. + e, yy / 2. + n)\n dxdy = (xx / nx, - yy / ny)\n\n return Grid(proj=projloc, x0y0=corner,\n nxny=(nx, ny), dxdy=dxdy,\n pixel_ref='corner')",
"def read_pts_from_grid(jparams):\n print(\"=== Reading points from grid ===\")\n input_data = rasterio.open(jparams[\"input-file\"])\n nodata_value = input_data.nodata\n raw_data = input_data.read()\n ncols = input_data.width\n nrows = input_data.height\n shape = input_data.shape\n PixelSizeX = input_data.transform[0]\n PixelSizeY = -input_data.transform[4]\n #transform_matrix = input_data.transform\n #print(raw_data[0])\n #lower_left_corner = transform_matrix * (0,input_data.height)\n # outlist = []\n # row_cnt = 0\n # for rev_row in reversed(range(0,nrows)):\n # for col in range(0,ncols):\n # z=raw_data[0][row_cnt][col]\n # if z!=nodata_value:\n # outlist.append([(rev_row+0.5)*PixelSizeY, (col+0.5)*PixelSizeX, z])\n # row_cnt+=1\n # print(len(raw_data[0][1]))\n # print(len(np.array(generate_raster_points(nrows, ncols, raw_data, nodata_value, PixelSizeX, PixelSizeY))))\n return np.array(generate_raster_points(nrows, ncols, raw_data, nodata_value, PixelSizeX, PixelSizeY))\n # Tip: the most efficient implementation of this function does not use any loops. Use numpy functions instead.",
"def get_nc_BGrid_GFDL(grdfile, name='GFDL_CM2.1_North_Pacific', area='regional', \\\n xrange=(60,175), yrange=(120, 190), ystart=235):\n\n nc = pyroms.io.Dataset(grdfile)\n\n lon_t = nc.variables['geolon_t'][:]\n lat_t = nc.variables['geolat_t'][:]\n lon_uv = nc.variables['geolon_c'][:]\n lat_uv = nc.variables['geolat_c'][:]\n\n h = nc.variables['ht'][:]\n\n f = nc.variables['coriolis_param'][:]\n\n kmt = nc.variables['kmt'][:]\n z_t = nc.variables['st_ocean'][:]\n z_t_edges = nc.variables['st_edges_ocean'][:]\n\n kmu = nc.variables['kmu'][:]\n z_uv = nc.variables['sw_ocean'][:]\n z_uv_edges = nc.variables['sw_edges_ocean'][:]\n\n # compute mask at t-point\n M_t, L_t = kmt.shape\n N_t = z_t.shape[0]\n mask_t = np.zeros((N_t, M_t, L_t))\n for j in range(M_t):\n for i in range(L_t):\n try:\n mask_t[0:int(kmt[j,i]), j,i] = 1\n except:\n mask_t[:, j,i] = 0\n\n # compute mask at uv-point\n M_uv, L_uv = kmu.shape\n N_uv = z_uv.shape[0]\n mask_uv = np.zeros((N_uv, M_uv, L_uv))\n for j in range(M_uv):\n for i in range(L_uv):\n try:\n mask_uv[0:int(kmu[j,i]), j,i] = 1\n except:\n mask_uv[:, j,i] = 0\n\n if area == 'npolar':\n #add two rows in the north and the south\n lon_t = lon_t[np.r_[0,0,:np.size(lon_t,0),-1,-1]]\n lon_t = lon_t[:,np.r_[0,:np.size(lon_t,1),-1]]\n lon_t[:,0] = lon_t[:,1] - (lon_t[:,2]-lon_t[:,1])\n lon_t[:,-1] = lon_t[:,-2] + (lon_t[:,-2]-lon_t[:,-3])\n lat_t = lat_t[np.r_[0,0,:np.size(lat_t,0),-1,-1]]\n lat_t = lat_t[:,np.r_[0,:np.size(lat_t,1),-1]]\n lat_t[0,:] = -85\n lat_t[1,:] = -80\n lat_t[-2,:] = 90\n lat_t[-1,:] = 91\n lon_uv = lon_uv[np.r_[0,0,:np.size(lon_uv,0),-1,-1]]\n lon_uv = lon_uv[:,np.r_[0,:np.size(lon_uv,1),-1]]\n lon_uv[:,0] = lon_uv[:,1] - (lon_uv[:,2]-lon_t[:,1])\n lon_uv[:,-1] = lon_uv[:,-2] + (lon_uv[:,-2]-lon_uv[:,-3])\n lat_uv = lat_uv[np.r_[0,0,:np.size(lat_uv,0),-1,-1]]\n lat_uv = lat_uv[:,np.r_[0,:np.size(lat_uv,1),-1]]\n lat_uv[0,:] = -85\n lat_uv[1,:] = -80\n lat_uv[-2,:] = 90\n lat_uv[-1,:] = 91\n mask_t = mask_t[:,np.r_[0,0,:np.size(mask_t,1),-1,-1],:]\n mask_t = mask_t[:,:,np.r_[0,:np.size(mask_t,2),-1]]\n mask_t[:,:,0] = mask_t[:,:,-2]\n mask_t[:,:,-1] = mask_t[:,:,1]\n mask_uv = mask_uv[:,np.r_[0,0,:np.size(mask_uv,1),-1,-1],:]\n mask_uv = mask_uv[:,:,np.r_[0,:np.size(mask_uv,2),-1]]\n mask_uv[:,:,0] = mask_uv[:,:,-2]\n mask_uv[:,:,-1] = mask_uv[:,:,1]\n h = h[np.r_[0,0,:np.size(h,0),-1,-1]]\n h = h[:,np.r_[0,:np.size(h,1),-1]]\n h[:,0] = h[:,-2]\n h[:,-1] = h[:,1]\n f = f[np.r_[0,0,:np.size(f,0),-1,-1]]\n f = f[:,np.r_[0,:np.size(f,1),-1]]\n f[:,0] = f[:,-2]\n f[:,-1] = f[:,1]\n m,l = h.shape\n xrange=(1,l-2)\n yrange=(ystart+2,m-2)\n\n if area == 'tripole':\n #add two rows in the north and the south\n fold1 = L_t//2\n lon_t = lon_t[np.r_[0,0,:np.size(lon_t,0),-1,-1]]\n lon_t[-2,:fold1] = lon_t[-3,L_t:fold1-1:-1]\n lon_t[-2,L_t:fold1-1:-1] = lon_t[-3,:fold1]\n lon_t[-1,:fold1] = lon_t[-4,L_t:fold1-1:-1]\n lon_t[-1,L_t:fold1-1:-1] = lon_t[-4,:fold1]\n\n lon_t = lon_t[:,np.r_[0,:np.size(lon_t,1),-1]]\n lon_t[:,0] = lon_t[:,1] - (lon_t[:,2]-lon_t[:,1])\n lon_t[:,-1] = lon_t[:,-2] + (lon_t[:,-2]-lon_t[:,-3])\n lat_t = lat_t[np.r_[0,0,:np.size(lat_t,0),-1,-1]]\n lat_t = lat_t[:,np.r_[0,:np.size(lat_t,1),-1]]\n lat_t[0,:] = -85\n lat_t[1,:] = -80\n lat_t[-2,:] = lat_t[-3,:]\n lat_t[-1,:] = lat_t[-4,:]\n lon_uv = lon_uv[np.r_[0,0,:np.size(lon_uv,0),-1,-1]]\n\n lon_uv[-2,:fold1] = lon_uv[-4,L_t:fold1-1:-1]\n lon_uv[-2,L_t:fold1-1:-1] = lon_uv[-4,:fold1]\n lon_uv[-1,:fold1] = lon_uv[-5,L_t:fold1-1:-1]\n lon_uv[-1,L_t:fold1-1:-1] = lon_uv[-5,:fold1]\n\n lon_uv = lon_uv[:,np.r_[0,:np.size(lon_uv,1),-1]]\n lon_uv[:,0] = lon_uv[:,1] - (lon_uv[:,2]-lon_t[:,1])\n lon_uv[:,-1] = lon_uv[:,-2] + (lon_uv[:,-2]-lon_uv[:,-3])\n lat_uv = lat_uv[np.r_[0,0,:np.size(lat_uv,0),-1,-1]]\n lat_uv = lat_uv[:,np.r_[0,:np.size(lat_uv,1),-1]]\n lat_uv[0,:] = -85\n lat_uv[1,:] = -80\n lat_uv[-2,:] = lat_uv[-3,:]\n lat_uv[-1,:] = lat_uv[-4,:]\n mask_t = mask_t[:,np.r_[0,0,:np.size(mask_t,1),-1,-1],:]\n mask_t = mask_t[:,:,np.r_[0,:np.size(mask_t,2),-1]]\n mask_t[:,:,0] = mask_t[:,:,-2]\n mask_t[:,:,-1] = mask_t[:,:,1]\n mask_uv = mask_uv[:,np.r_[0,0,:np.size(mask_uv,1),-1,-1],:]\n mask_uv = mask_uv[:,:,np.r_[0,:np.size(mask_uv,2),-1]]\n mask_uv[:,:,0] = mask_uv[:,:,-2]\n mask_uv[:,:,-1] = mask_uv[:,:,1]\n h = h[np.r_[0,0,:np.size(h,0),-1,-1]]\n h = h[:,np.r_[0,:np.size(h,1),-1]]\n h[:,0] = h[:,-2]\n h[:,-1] = h[:,1]\n f = f[np.r_[0,0,:np.size(f,0),-1,-1]]\n f = f[:,np.r_[0,:np.size(f,1),-1]]\n f[:,0] = f[:,-2]\n f[:,-1] = f[:,1]\n m,l = h.shape\n xrange=(1,l-2)\n yrange=(ystart+2,m-2)\n\n return BGrid_GFDL(lon_t, lat_t, lon_uv, lat_uv, \\\n mask_t, mask_uv, h, z_t, z_t_edges, \\\n z_uv, z_uv_edges, f, \\\n name, xrange=xrange, yrange=yrange)",
"def gen_grids(self):\n self.dx = self.grid_width / self.grid_resol\n self.dk = 2 * np.pi/self.grid_width\n self.grid_x_shifted = -self.grid_width/2 + self.dx * np.arange(0, self.grid_resol)\n self.grid_x = self.grid_x_shifted + self.grid_center\n self.grid_k = - (np.pi * self.grid_resol)/self.grid_width + self.dk * np.arange(0, self.grid_resol)\n self.grid_k = np.roll(self.grid_k, int((self.grid_resol)/2))\n self.grid_kin = np.square(self.h)/ (2*self.m) * np.square(self.grid_k)",
"def _griddata(self):\n res = self.cfg.resolution\n\n # Get area of data\n xmin, xmax = np.nanmin(self.x), np.nanmax(self.x)\n ymin, ymax = np.nanmin(self.y), np.nanmax(self.y)\n\n # Add padding\n width = xmax-xmin\n height = ymax-ymin\n pad = np.amax([self.cfg.grid_pad_fraction*width, self.cfg.grid_pad_fraction*height])\n xmin = np.floor(xmin - pad)\n xmax = np.ceil(xmax + pad)\n ymin = np.floor(ymin - pad)\n ymax = np.ceil(ymax + pad)\n\n # Create Grid and no data mask\n self.lrx = np.arange(xmin, xmax+res, res)\n self.lry = np.arange(ymin, ymax+res, res)\n self.dem_x, self.dem_y = np.meshgrid(self.lrx, self.lry)\n self.nonan = np.where(np.logical_or(np.isfinite(self.x), np.isfinite(self.y)))\n\n # Create regular grid\n gridding_algorithm = self.cfg.griddata[\"algorithm\"]\n if gridding_algorithm == \"scipy.griddata\":\n self.dem_z = griddata((self.x[self.nonan].flatten(), self.y[self.nonan].flatten()),\n self.als.elevation[self.nonan].flatten(),\n (self.dem_x, self.dem_y),\n **self.cfg.griddata[\"keyw\"])\n else:\n raise NotImplementedError(\"Gridding algorithm: %s\" % gridding_algorithm)\n\n self.dem_z = np.ma.array(self.dem_z)\n self.dem_mask = np.zeros(self.dem_z.shape, dtype=np.bool)",
"def output_grid_information():\n # translate = [-74.26, 40.50]\n # scale = [0.02, 0.02]\n # step = 1\n\n translate = [0, 0]\n scale = [1, 1]\n step = 0.02\n\n lon_limits = [(-74.26 - translate[0]) / scale[0], (-73.76 - translate[0]) / scale[0]]\n lat_limits = [(40.48 - translate[1]) / scale[1], (40.94 - translate[1]) / scale[1]]\n\n lons = np.arange(lon_limits[0], lon_limits[1] - step, step)\n lats = np.arange(lat_limits[0], lat_limits[1] - step, step)\n\n all_json = {\n \"type\": \"FeatureCollection\"\n }\n\n gr_id = 0\n grid_df = pd.DataFrame(columns=['gr_id', 'c_lat', 'c_lon', 's_lon', 'w_lat', 'n_lon', 'e_lat'])\n features = []\n\n for lat in lats:\n for lon in lons:\n w_lon = lon\n e_lon = lon + step\n s_lat = lat\n n_lat = lat + step\n\n c_lon = lon + step / 2\n c_lat = lat + step / 2\n\n grid_df = grid_df.append(pd.DataFrame({\"gr_id\": [gr_id],\n \"c_lon\": [c_lon], \"c_lat\": [c_lat],\n \"w_lon\": [w_lon], \"s_lat\": [s_lat],\n \"e_lon\": [e_lon], \"n_lat\": [n_lat]}))\n\n coor = [[[s_lat, w_lon], [n_lat, w_lon], [n_lat, e_lon],\n [s_lat, e_lon], [s_lat, w_lon]]]\n\n feature = {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": coor\n },\n \"properties\": {\n \"id\": str(gr_id)\n }\n }\n\n features.append(feature)\n\n gr_id += 1\n\n all_json['features'] = features\n\n with open(BaseDir + '/grid.geojson', 'w') as f:\n json.dump(all_json, f)\n\n grid_df.to_csv(BaseDir + '/grid_locs.csv', index=False)",
"def makeCMSgridNodes(x0, y0, azi, dx, dy, z):\n # convert from node calculation to centric calculation\n # first move origin from vertex of grid to center of first grid cell\n\n # first convert to FRF coordinates\n FRF = gp.FRFcoord(x0, y0, coordType='ncsp')\n # shift origin to cell center instead of cell vertex\n x0N = FRF['xFRF'] - dx[0]/2\n y0N = FRF['yFRF'] - dy[0]/2\n # create new dx/dy array spaced with half of each of the 2 cells\n dxN = dx[:-1] + np.diff(dx)/2\n dyN = dy[:-1] + np.diff(dy)/2 # new nodes at the grid center - needed to fit into\n # create new nodes in FRF x and FRF Y using cell centric locations for accurate interpolation\n outXfrf, outYfrf = createGridNodesinFRF(x0N, y0N, dxN, dyN, dx.shape[0], dy.shape[0])\n xFRF, yFRF = np.meshgrid(outXfrf, sorted(outYfrf))\n # new work no need to loop as above\n convert2 = gp.FRFcoord(xFRF.flatten(), yFRF.flatten(), coordType='FRF')\n lat = convert2['Lat'].reshape(xFRF.shape)\n lon = convert2['Lon'].reshape(xFRF.shape)\n easting = convert2['StateplaneE'].reshape(xFRF.shape)\n northing = convert2['StateplaneN'].reshape(yFRF.shape)\n # making i's and j's for cell numbers\n ii = np.linspace(1, xFRF.shape[1], xFRF.shape[1])\n jj = np.linspace(1, yFRF.shape[0], yFRF.shape[0])\n\n BathyPacket = {'i': ii,\n 'j': jj,\n 'latitude': lat,\n 'longitude': lon,\n 'easting': easting,\n 'northing': northing,\n 'xFRF': sorted(xFRF[0, :]),\n 'yFRF': yFRF[:, 0],\n 'azimuth': azi,\n 'x0': x0,\n 'y0': y0,\n 'DX': dxN,\n 'DY': dyN,\n 'ni': len(ii),\n 'nj': len(jj),\n 'elevation': z, # exported as [t, x,y] dimensions\n 'gridFname': 'CMS GRid',\n 'time': 0}\n\n return BathyPacket",
"def get_grid(self, mol_data):\n\n if self.grid_info is None:\n\n try:\n\n x = mol_data['grid_points/x'][()]\n y = mol_data['grid_points/y'][()]\n z = mol_data['grid_points/z'][()]\n\n except BaseException:\n\n raise ValueError(\n \"Grid points not found in the data file\")\n\n else:\n\n center = mol_data['grid_points/center'][()]\n npts = np.array(self.grid_info['number_of_points'])\n res = np.array(self.grid_info['resolution'])\n\n halfdim = 0.5 * (npts * res)\n\n low_lim = center - halfdim\n hgh_lim = low_lim + res * (npts - 1)\n\n x = np.linspace(low_lim[0], hgh_lim[0], npts[0])\n y = np.linspace(low_lim[1], hgh_lim[1], npts[1])\n z = np.linspace(low_lim[2], hgh_lim[2], npts[2])\n\n # there is stil something strange\n # with the ordering of the grid\n # also noted in GridTools define_grid_points()\n y, x, z = np.meshgrid(y, x, z)\n grid = (x, y, z)\n npts = (len(x), len(y), len(z))\n return grid, npts",
"def get_grid_data(grid):\n indir = '/home/ivan/Tools/scrip/mapping/grids'\n infile = os.path.join(indir, grid + '.nc')\n fp = Nio.open_file(infile,'r')\n nlon, nlat = fp.variables['grid_dims'][:]\n tlat = fp.variables['grid_center_lat'][:]\n tlon = fp.variables['grid_center_lon'][:]\n fp.close()\n tlat = N.reshape(tlat,(nlat,nlon))[:,0]\n tlon = N.reshape(tlon,(nlat,nlon))[0,:]\n return nlon, nlat, tlon, tlat",
"def create_grid(data, drone_altitude, safety_distance):\n\n # minimum and maximum north coordinates\n north_min = np.floor(np.min(data[:, 0] - data[:, 3]))\n north_max = np.ceil(np.max(data[:, 0] + data[:, 3]))\n #print(north_min, north_max)\n\n # minimum and maximum east coordinates\n east_min = np.floor(np.min(data[:, 1] - data[:, 4]))\n east_max = np.ceil(np.max(data[:, 1] + data[:, 4]))\n #print(east_min, east_max)\n # given the minimum and maximum coordinates we can\n # calculate the size of the grid.\n north_size = int(np.ceil((north_max - north_min)))\n east_size = int(np.ceil((east_max - east_min)))\n #print(north_size, east_size)\n # Initialize an empty grid\n grid = np.zeros((north_size, east_size))\n # Center offset for grid\n north_min_center = np.min(data[:, 0])\n east_min_center = np.min(data[:, 1])\n \n # Populate the grid with obstacles\n for i in range(data.shape[0]):\n north, east, alt, d_north, d_east, d_alt = data[i, :]\n\n if alt + d_alt + safety_distance > drone_altitude:\n obstacle = [\n int(north - d_north - safety_distance - north_min_center),\n int(north + d_north + safety_distance - north_min_center),\n int(east - d_east - safety_distance - east_min_center),\n int(east + d_east + safety_distance - east_min_center),\n ]\n grid[obstacle[0]:obstacle[1], obstacle[2]:obstacle[3]] = 1\n\n return grid",
"def make_coordinate_grid(spatial_size, type):\n h, w = spatial_size\n x = torch.arange(w).type(type)\n y = torch.arange(h).type(type)\n x = 2 * (x / (w - 1)) - 1\n y = 2 * (y / (h - 1)) - 1\n yy = y.view(-1, 1).repeat(1, w)\n xx = x.view(1, -1).repeat(h, 1)\n meshed = torch.cat([xx.unsqueeze_(2), yy.unsqueeze_(2)], 2)\n return meshed",
"def cloudy_grid_map(**kwargs):\n\n p = copy.copy(params)\n for key,val in kwargs.items():\n setattr(p,key,val)\n\n cloudy_library = clo.library()\n model_number_matrix,grid_table = cloudy_library._restore_grid_table(grid_ext=p.grid_ext)\n # print(len(grid_table))\n # print(len(grid_table)/len(np.unique(grid_table.nH)))\n\n grid_table = grid_table.fillna(-10)\n grid_table['DTM'] = np.round(grid_table['DTM'] * 10.) / 10.\n grid_table['NH'] = np.round(grid_table['NH'] * 10.) / 10.\n\n # print(grid_table.DTM[np.isnan(grid_table['DTM'])])\n # print(grid_table.NH[np.isnan(grid_table['NH'])])\n # print(grid_table.FUV[np.isnan(grid_table['FUV'])])\n # print(grid_table.nH[np.isnan(grid_table.nH)])\n # print(grid_table.Z[np.isnan(grid_table.Z)])\n\n print('nHs: ',np.unique(grid_table.nH))\n print('DTMs: ',np.unique(grid_table.DTM))\n print('FUVs: ',np.unique(grid_table.FUV))\n print('NHs: ',np.unique(grid_table.NH))\n print('Zs: ',np.unique(grid_table.Z))\n\n fig,ax = plt.subplots(figsize=(8,5))\n\n key1, key2, key3 = list(p.cloudy_param.keys())[0],list(p.cloudy_param.keys())[1],list(p.cloudy_param.keys())[2]\n value1, value2, value3 = list(p.cloudy_param.values())[0],list(p.cloudy_param.values())[1],list(p.cloudy_param.values())[2]\n\n # Decide on what goes on x and y axis\n cloudy_parameters = np.array(['NH','FUV','nH','Z','DTM'])\n x_index = cloudy_parameters[(cloudy_parameters != key1) &\\\n (cloudy_parameters != key2) &\\\n (cloudy_parameters != key3)][0]\n y_index = cloudy_parameters[(cloudy_parameters != key1) &\\\n (cloudy_parameters != key2) &\\\n (cloudy_parameters != key3)][1]\n print(x_index,y_index)\n # Cut in grid table\n grid_table_cut = grid_table.iloc[np.where((grid_table[key1].values == value1) & \\\n (grid_table[key2].values == value2) & \\\n (grid_table[key3].values == value3))[0]]\n\n x, y = grid_table_cut[x_index].values, grid_table_cut[y_index].values\n X, Y = np.meshgrid(np.unique(grid_table_cut[x_index].values), np.unique(grid_table_cut[y_index].values))\n\n # Plot line ratio?\n if '_' in p.line:\n L1 = grid_table_cut[p.line.split('_')[0]].values\n L2 = grid_table_cut[p.line.split('_')[1]].values\n L2[L2 == 0] = 1e9\n line_lum = (L1/L2).astype(float)\n vmin = np.min(np.log10(line_lum[L2 < 1e9]))\n\n else:\n line_lum = grid_table_cut[p.line].values.astype(float)\n vmin = np.min(np.log10(line_lum[line_lum > 0]))\n\n\n # ########## Patching the grid !!\n # line_lum[np.isnan(line_lum)] = -1 # what are these?\n # # 0 values: not sure if we have any?\n # # Negative numbers: missing grid point\n # i_missing = np.where(line_lum <= 0)[0]\n # line_lum[line_lum == 0] = np.min(line_lum[line_lum > 0])\n # while len(i_missing) > 0:\n # print(i_missing)\n # lum = np.log10(line_lum)\n # for i in i_missing:\n # # print(lum[i-1],lum[i+1])\n # try: \n # lum[i] = (lum[i-1] + lum[i+1])/ 2\n # except:\n # pass\n # # print('he',np.isnan(lum[i]))\n # if np.isnan(lum[i]):\n # try:\n # lum[i] = lum[i-1] \n # except:\n # pass\n # if np.isnan(lum[i]):\n # try:\n # lum[i] = lum[i+1] \n # except:\n # pass \n # line_lum[i] = 10.**lum[i]\n # # print(i,lum[i])\n # i_missing = np.where(line_lum < 0)[0]\n # ########## End of patching\n \n lum = np.log10(line_lum)\n lum = lum.reshape([len(np.unique(x)), len(np.unique(y))]).T\n\n\n # pdb.set_trace()\n print(p.zlim)\n if p.zlim:\n print(p.zlim)\n lum[lum < p.zlim[0]] = p.zlim[0]\n lum[lum > p.zlim[1]] = p.zlim[1]\n cf = ax.contourf(X,Y, lum, cmap=\"jet\", vmin=p.zlim[0], vmax=p.zlim[1], lw=0, rstride=1, cstride=1,alpha=0.8, levels=20)\n else:\n cf = ax.contourf(X,Y, lum, cmap=\"jet\", vmin=vmin, lw=0, rstride=1, cstride=1,alpha=0.8)\n # print(lum)\n ax.set_xlabel('\\n\\n' + getlabel('l'+x_index))\n ax.set_ylabel('\\n\\n' + getlabel('l'+y_index))\n\n ax.set_xlim([np.min(X),np.max(X)])\n ax.set_ylim([np.min(Y),np.max(Y)])\n\n plt.colorbar(cf)\n\n plt.tight_layout()\n if p.savefig:\n if not os.path.isdir(p.d_plot + 'look-up/'): os.mkdir(p.d_plot + 'look-up/') \n plt.savefig(p.d_plot + 'look-up/cloudy_grid_map_%s%s%s.%s' % (p.line, p.grid_ext, p.ext, p.format), format=p.format, dpi=300)",
"def load_grd(filename):\n with open(filename, 'r') as f:\n meta = {}\n meta['header'] = []\n meta['header'].append(f.readline().rstrip('\\n'))\n while meta['header'][-1] != '++++':\n meta['header'].append(f.readline().rstrip('\\n'))\n # These determine the type of grid and the field format.\n meta['KTYPE'] = int(f.readline().split()[0])\n if meta['KTYPE'] != 1:\n raise ValueError(\"Not implemented.\")\n meta['NSET'], meta['ICOMP'], meta['NCOMP'], meta['IGRID'] = [int(s) for s in f.readline().split()]\n # The grid center in units of the x and y grid spacing.\n meta['IX'], meta['IY'] = [int(s) for s in f.readline().split()]\n # These are the x and y grid limits: S is lower, and E is upper.\n meta['XS'], meta['YS'], meta['XE'], meta['YE'] = [float(s) for s in f.readline().split()]\n # These are the numbers of grid points in x and y.\n meta['NX'], meta['NY'], meta['KLIMIT'] = [int(s) for s in f.readline().split()]\n # Implement this to read elliptically truncated grids.\n if meta['KLIMIT'] != 0:\n raise ValueError(\"Not implemented.\")\n # Load the field data. This returns an array with shape (NX * NY, 2 * NCOMP).\n conv = dict([(column, string_to_float) for column in range(2 * meta['NCOMP'])])\n data = np.loadtxt(f, dtype=float, converters=conv)\n # Determine the grid spacing and center values.\n meta['DX'] = (meta['XE'] - meta['XS']) / (meta['NX'] - 1)\n meta['DY'] = (meta['YE'] - meta['YS']) / (meta['NY'] - 1)\n meta['XCEN'] = meta['DX'] * meta['IX']\n meta['YCEN'] = meta['DY'] * meta['IY']\n # Reshape the data.\n map = np.empty((meta['NX'], meta['NY'], meta['NCOMP']),\n dtype=np.complex)\n for component in range(meta['NCOMP']):\n column = data[:, 2 * component] + 1j * data[:, 2 * component + 1]\n map[:, :, component] = column.reshape(meta['NX'], meta['NY'], order='F')\n return meta, map",
"def grid_points(self):\n for i in range(self.rows):\n for j in range(self.cols):\n min_lat,max_lat,min_lon,max_lon = self.coords_to_min_max_lat_lon((i,j))\n if i == 0:\n print_gps(max_lat,max_lon,\"grid\")\n if j == 0:\n print_gps(max_lat,min_lon,\"grid\")\n if j == 0:\n print_gps(min_lat,min_lon,\"grid\")\n print_gps(min_lat,max_lon,\"grid\")",
"def generate_grid(extent, grid_size):\r\n\r\n transformer = Transformer.from_crs(\"epsg:4326\", 'epsg:3301')\r\n\r\n # convert to planar\r\n exten_plain = box(transformer.transform(extent.bounds[1], extent.bounds[0])[1],\r\n transformer.transform(extent.bounds[1], extent.bounds[0])[0],\r\n transformer.transform(extent.bounds[3], extent.bounds[2])[1],\r\n transformer.transform(extent.bounds[3], extent.bounds[2])[0])\r\n\r\n # calculate parameters for the grid\r\n x_min = exten_plain.bounds[0]\r\n y_min = exten_plain.bounds[1]\r\n x_size = exten_plain.bounds[2] - exten_plain.bounds[0]\r\n y_size = exten_plain.bounds[3] - exten_plain.bounds[1]\r\n\r\n grid_x_res = x_size / grid_size\r\n grid_y_res = y_size / grid_size\r\n\r\n # calculate x,y of grid with real coordinates\r\n x_grid = [(x * grid_x_res) + x_min for x in range(grid_size)]\r\n y_grid = [(y * grid_y_res) + y_min for y in range(grid_size)]\r\n\r\n # calculate all x,y values of grid\r\n x_grid_coord, y_grid_coord = np.meshgrid(x_grid, y_grid)\r\n\r\n # create geoseries with grid points and assign projection\r\n int_grid = gpd.GeoSeries(map(Point, zip(x_grid_coord.flatten(), y_grid_coord.flatten())))\r\n int_grid.crs = \"EPSG:3301\"\r\n\r\n # transform back to lat/lon\r\n int_grid = int_grid.to_crs(\"EPSG:4326\")\r\n int_grid = gpd.GeoDataFrame({'geometry': int_grid})\r\n return int_grid",
"def _buildGridPoints(self):\n self.spacings = []\n for level in xrange(self.depth):\n levelSpacings = []\n refLevel = level + 1\n level = 2**level\n axisData = []\n for axis in self.size:\n spacing = axis / (level+1)\n levelSpacings.append(spacing)\n axisData.append([gridValue*spacing for gridValue in xrange(1, level+1)])\n pointList = [((i, j, k), np.array([axisData[0][i], axisData[1][j], axisData[2][k]]))\n for i in xrange(level)\n for j in xrange(level)\n for k in xrange(level)]\n self.grid[refLevel] = {point[0]: point[1] for point in pointList}\n self.spacings.append(levelSpacings)",
"def create_grid(data, drone_altitude, safety_distance):\n\n # minimum and maximum north coordinates\n north_min = np.floor(np.amin(data[:, 0] - data[:, 3]))\n north_max = np.ceil(np.amax(data[:, 0] + data[:, 3]))\n print(0, north_max - north_min)\n\n # minimum and maximum east coordinates\n east_min = np.floor(np.amin(data[:, 1] - data[:, 4]))\n east_max = np.ceil(np.amax(data[:, 1] + data[:, 4]))\n print(0, east_max - east_min)\n\n # given the minimum and maximum coordinates we can\n # calculate the size of the grid.\n north_size = int(np.ceil(north_max - north_min))\n east_size = int(np.ceil(east_max - east_min))\n\n # Initialize an empty grid\n grid = np.zeros((north_size, east_size))\n\n # Populate the grid with obstacles\n print(data.shape[0])\n for i in range(data.shape[0]):\n north, east, alt, d_north, d_east, d_alt = data[i, :]\n # Determine which cells contain obstacles\n nc = int(north - north_min)\n ec = int(east - east_min)\n dn = int(d_north)\n de = int(d_east)\n sd = int(safety_distance)\n x0 = int(ec - (de + sd))\n y0 = int(nc - (dn + sd))\n xm = int(ec + (de + sd))\n ym = int(nc + (dn + sd))\n nm = north_max - north_min\n em = east_max - east_min\n for e in range(x0, xm):\n for n in range(y0, ym):\n # skip out of range conditions\n if e < 0:\n continue\n if e >= em:\n continue\n if n < 0:\n continue\n if n >= nm:\n continue\n if (alt + d_alt + safety_distance) <= drone_altitude:\n continue\n # plot it\n grid[n][e] = 1\n\n return grid",
"def _getLatLonGrid(self, lats, lons):\n numLats, numLons = lats.shape\n\n #coordGrid = [[0 for lon in range(numLons)] for lat in range(numLats)]\n coordGrid = np.ndarray((numLats, numLons, 2))\n for lat in range(len(lats)):\n for lon in range(len(lons[lat])):\n # Moved handling of pygrib version hack to _getIndex. Since the\n # data matches up with the grid ordering given in lats and lons,\n # we have to maintain that ordering in our created grid.\n coordGrid[lat, lon, 0] = lats[lat][lon]\n coordGrid[lat, lon, 1] = lons[lat][lon]\n\n\n return coordGrid",
"def _cal_grid_coordinates(self, nc_handle):\n print(\"calculating grid coordinates\")\n #\n x = np.zeros(self._grid[\"counts\"][0], dtype=float)\n y = np.zeros(self._grid[\"counts\"][1], dtype=float)\n z = np.zeros(self._grid[\"counts\"][2], dtype=float)\n \n for i in range(self._grid[\"counts\"][0]):\n x[i] = self._grid[\"origin\"][0] + i*self._grid[\"d0\"][0]\n\n for j in range(self._grid[\"counts\"][1]):\n y[j] = self._grid[\"origin\"][1] + j*self._grid[\"d1\"][1]\n\n for k in range(self._grid[\"counts\"][2]):\n z[k] = self._grid[\"origin\"][2] + k*self._grid[\"d2\"][2]\n\n self._set_grid_key_value(\"x\", x)\n self._set_grid_key_value(\"y\", y)\n self._set_grid_key_value(\"z\", z)\n\n for key in [\"x\", \"y\", \"z\"]:\n self._write_to_nc(nc_handle, key, self._grid[key])\n return None",
"def Cloud2Grid(coords, grid_dim=10000, tile_size=256):\n grid_coords = np.array(coords)\n tile_dim = grid_dim // tile_size # tile count in x and y\n for i in range(2): # scale axes from 0 to tile_dim\n grid_coords[:, i] = grid_coords[:, i] - grid_coords[:, i].min()\n grid_coords[:, i] = grid_coords[:, i] * (\n tile_dim / (grid_coords[:, i].max() + 1)\n )\n grid_coords = np.floor(grid_coords)\n grid_coords = grid_coords * tile_size\n grid_coords[:, 1] = abs(grid_coords[:, 1] - grid_dim) # flip y axis index\n return grid_coords",
"def grid_spherical_decomposed(x, y, z, data, x_i, y_i, z_i, horz_res, missing_value=-32767):\n\n r_map = np.sqrt(x**2.0 + y**2.0) # cartesian radius from map (x,y) center\n az_map = np.arctan2(y,x) #azimuth in the cartesian system. might vary along a ray due to map projection curvature\n vcp = np.fromiter((np.median(az_map[:, i_az, :]) for i_az in range(az_map.shape[1])), np.float32)\n print x.shape\n \n r_i = np.arange(r_map.min(), r_map.max(), horz_res) # cartesian radius from map(x,y) center\n\n # also need to griddata the x, y, z geographic coordinates.\n # decomposed geometry in radar polar coordinates is a not a\n # geophysical coordinate system (it's really a tangent plane\n # coord sys without beam refraction effects), so really there \n # are two xyz systems in play here.\n\n # unless, if by using z and R = np.sqrt(x**2.0 + y**2.0), we remain in a cylinderical \n # system referenced to the map projection in use. I think this is true.\n\n # Interpolate from spherical to cylindrical.\n # Cylindrical system is a different\n # range coordinate than the radar range coordinate.\n az_idx = 1\n cyl_grid_shape = (r_i.shape[0], x.shape[az_idx], z_i.shape[0])\n cyl_grid = np.empty(cyl_grid_shape)\n \n for az_id in range(cyl_grid_shape[az_idx]):\n progress(az_id, cyl_grid_shape[az_idx], 'Gridding along azimuths')\n rhi_r = r_map[:, az_id, :]\n # rhi_y = y[:, az_id, :]\n # R_i = rhir = np.sqrt(x[:, az_id, :]**2.0 + y[:, az_id, :]**2.0)\n rhi_z = z[:, az_id, :]\n rhi_data = data[:, az_id, :]\n \n # input and output coordinates need to be taken from the same coordinate system\n cyl_grid[:, az_id, :] = griddata(rhi_r.flatten(), rhi_z.flatten(), rhi_data.flatten(), r_i, z_i).T\n print \"\\r\" + 'Gridding along azimuths ... done'\n # cyl_grid is r, az, z instead of r, az, el\n \n # get mesh of coordinates for all interpolated radii r_i and along the azimuth\n # since constant radar azimuth might have curvature induced by the map projection\n # it's tricky to do this.\n\n # steps:\n # Do new transform from r,az radar system to map system using r=r_i to get x,y\n # or \n # Just do naive assumption that azimuths are straight and accept the error (used this one)\n \n # interpolate from cylindrical to cartesian.\n grid = np.empty((len(x_i), len(y_i), len(z_i)), dtype=np.float32)\n for z_id in range(z_i.shape[0]):\n progress(z_id, z_i.shape[0], 'Gridding at constant altitude')\n cappi_x = r_i[:, None]*np.cos(vcp[None, :])\n cappi_y = r_i[:, None]*np.sin(vcp[None, :])\n cappi_data = cyl_grid[:,:,z_id]\n \n # input and output coordinates need to be taken from the same coordinate system\n grid_2d = griddata(cappi_x.flatten(), cappi_y.flatten(), cappi_data.flatten(), x_i, y_i).T\n grid[:, :, z_id] = grid_2d\n print \"\\r\" + 'Gridding at constant altitude ... done'\n \n grid[np.isnan(grid)] = missing_value\n \n return grid",
"def _build_grid(self):\n n = self.params['n']\n\n x_min, x_max = min(self.node[:, 0]), max(self.node[:, 0])\n y_min, y_max = min(self.node[:, 1]), max(self.node[:, 1])\n xv = np.linspace(x_min, x_max, num=n, endpoint=True)\n yv = np.linspace(y_min, y_max, num=n, endpoint=True)\n xg, yg = np.meshgrid(xv, yv, sparse=False, indexing='xy')\n\n return xg, yg",
"def create_grid(self):\n # Domain definition\n network = pp.FractureNetwork2d(self.frac_pts.T, self.frac_edges.T, domain=self.box)\n gb = network.mesh(self.mesh_args) \n pp.contact_conditions.set_projections(gb)\n\n self.gb = gb\n self.Nd = self.gb.dim_max()\n self._Nd = self.gb.dim_max()\n g2d = self.gb.grids_of_dimension(2)[0]\n self.min_face = np.copy(self.mesh_size) #np.min(g2d.face_areas)\n self.min_cell = np.min(g2d.cell_volumes)\n self.p, self.t = analysis.adjustmesh(g2d, self.tips, self.GAP)\n self.displacement = self.p*0\n self.fa_no = g2d.face_nodes.indices.reshape((2, g2d.num_faces), order='f').T \n return gb",
"def create_grid_map(self, scalar=20):\n self.grid_scalar = scalar\n if len(self.fem.Plates) == 0:\n raise ValueError(\"No plates to create image from\")\n\n height = self.height\n width = self.ring_n\n\n # TODO add scalar\n output = np.zeros(shape=(height * scalar, width * scalar))\n\n for xo in range(width):\n x = xo * scalar\n output[:, x] = 255\n\n for yo in range(height):\n y = yo * scalar\n output[y, :] = 255\n\n file_name = f'Grid_h{self.height}_ms{self.ring_n}_s{scalar}.jpg'\n plt.imshow(output, cmap='gray')\n plt.savefig('../../input/grids/{}'.format(file_name))\n plt.show()",
"def test_ndc_to_grid_sample_coords(self):\n\n # square image tests\n image_size_square = [100, 100]\n xy_ndc_gs_square = torch.FloatTensor(\n [\n # 4 corners\n [[-1.0, -1.0], [1.0, 1.0]],\n [[1.0, 1.0], [-1.0, -1.0]],\n [[1.0, -1.0], [-1.0, 1.0]],\n [[1.0, 1.0], [-1.0, -1.0]],\n # center\n [[0.0, 0.0], [0.0, 0.0]],\n ]\n )\n\n # non-batched version\n for xy_ndc, xy_gs in xy_ndc_gs_square:\n xy_gs_predicted = ndc_to_grid_sample_coords(\n xy_ndc,\n image_size_square,\n )\n self.assertClose(xy_gs_predicted, xy_gs)\n\n # batched version\n xy_ndc, xy_gs = xy_ndc_gs_square[:, 0], xy_ndc_gs_square[:, 1]\n xy_gs_predicted = ndc_to_grid_sample_coords(\n xy_ndc,\n image_size_square,\n )\n self.assertClose(xy_gs_predicted, xy_gs)\n\n # non-square image tests\n image_size = [100, 200]\n xy_ndc_gs = torch.FloatTensor(\n [\n # 4 corners\n [[-2.0, -1.0], [1.0, 1.0]],\n [[2.0, -1.0], [-1.0, 1.0]],\n [[-2.0, 1.0], [1.0, -1.0]],\n [[2.0, 1.0], [-1.0, -1.0]],\n # center\n [[0.0, 0.0], [0.0, 0.0]],\n # non-corner points\n [[4.0, 0.5], [-2.0, -0.5]],\n [[1.0, -0.5], [-0.5, 0.5]],\n ]\n )\n\n # check both H > W and W > H\n for flip_axes in [False, True]:\n\n # non-batched version\n for xy_ndc, xy_gs in xy_ndc_gs:\n xy_gs_predicted = ndc_to_grid_sample_coords(\n xy_ndc.flip(dims=(-1,)) if flip_axes else xy_ndc,\n list(reversed(image_size)) if flip_axes else image_size,\n )\n self.assertClose(\n xy_gs_predicted,\n xy_gs.flip(dims=(-1,)) if flip_axes else xy_gs,\n )\n\n # batched version\n xy_ndc, xy_gs = xy_ndc_gs[:, 0], xy_ndc_gs[:, 1]\n xy_gs_predicted = ndc_to_grid_sample_coords(\n xy_ndc.flip(dims=(-1,)) if flip_axes else xy_ndc,\n list(reversed(image_size)) if flip_axes else image_size,\n )\n self.assertClose(\n xy_gs_predicted,\n xy_gs.flip(dims=(-1,)) if flip_axes else xy_gs,\n )",
"def grid_results(infile, resolution = 0.01, clip_shp = None, \n overwrite=True, contour=False):\n outfile = infile.rstrip('().csv') + '_gridded.tif'\n # if not overwrite:\n if os.path.isfile(outfile):\n if not overwrite:\n print('Not creating file %s as already exists' % outfile)\n print('To re-create file (e.g if inputs changed) set overwrite=True)')\n return\n else:\n try:\n os.remove(outfile)\n os.remove((outfile.rstrip('.tif') + '_clip.tif'))\n except:\n pass\n data = np.genfromtxt(infile, delimiter=',')\n max_lon = max(data[:,0])\n min_lon = min(data[:,0])\n max_lat = max(data[:,1])\n min_lat = min(data[:,1])\n #print max_lon, min_lon, max_lat, min_lat\n xi = np.arange(min_lon, max_lon, resolution)\n yi = np.arange(min_lat, max_lat, resolution)\n XI,YI = np.meshgrid(xi,yi)\n xsize = len(xi)\n ysize = len(yi)\n\n print('Interpolating results')\n gridded_results = griddata((data[:,0],data[:,1]),data[:,2],(XI,YI),method='linear')\n #print gridded_results\n #outfile = infile.rstrip('().csv') + '_gridded.tif'\n print('Writing gridded data to %s' % outfile)\n driver = gdal.GetDriverByName('GTiff')\n ds = driver.Create(outfile, xsize, ysize, 1, gdal.GDT_Float32)\n srs = osr.SpatialReference()\n srs.ImportFromEPSG(4326)\n ds.SetProjection(srs.ExportToWkt())\n gt = [(min_lon - (resolution/2)), resolution, 0, \n (min_lat - (resolution/2)), 0, resolution]\n ds.SetGeoTransform(gt)\n outband=ds.GetRasterBand(1)\n outband.SetStatistics(np.min(gridded_results), np.max(gridded_results), np.average(gridded_results), np.std(gridded_results))\n outband.WriteArray(gridded_results)\n # Need to close output dataset before we can do clipping\n ds = None\n # now clip by shapefile\n if clip_shp is not None:\n clipfile = outfile.rstrip('.tif') + '_clip.tif'\n cmd = ['gdalwarp',\n '-cutline',\n clip_shp,\n '-crop_to_cutline',\n '-dstalpha',\n outfile,\n clipfile]\n print(cmd)\n call(cmd, shell=False)\n if contour is True:\n cmd = 'gdal_contour -i 1 -off 0.5 %s %s.shp' % (outfile, outfile.rstrip('.tif'))\n print(cmd)\n call(cmd, shell=True)\n cmd = 'gdal_contour -i 1 -off 0.5 %s %s.shp' % (clipfile, clipfile.rstrip('.tif'))\n print(cmd)\n call(cmd, shell=True)",
"def make_xy_grid(samples_x, samples_y=None, radius=1):\n if samples_y is None:\n samples_y = samples_x\n x = e.linspace(-radius, radius, samples_x, dtype=config.precision)\n y = e.linspace(-radius, radius, samples_y, dtype=config.precision)\n xx, yy = e.meshgrid(x, y)\n return xx, yy"
] | [
"0.6088046",
"0.6063031",
"0.60484874",
"0.59672564",
"0.5802529",
"0.57952696",
"0.57486963",
"0.5746483",
"0.5738083",
"0.5723963",
"0.5699488",
"0.5683187",
"0.5678278",
"0.5609553",
"0.56036705",
"0.55991954",
"0.5596098",
"0.55732584",
"0.5553073",
"0.5535441",
"0.55326617",
"0.551959",
"0.5496044",
"0.54706395",
"0.54660386",
"0.54629713",
"0.54557246",
"0.54510564",
"0.5448235",
"0.54445374"
] | 0.76141745 | 0 |
Estimate the cloud top height according to Baum et al., 2012 | def get_cloudtopheight(self):
bt = self.get_brightnesstemperature("14")
cloudmask = self.retrieve_cloudmask()
latitude = self.scenecenter.latitude
month = self.datetime.month
return cloudtopheight_IR(bt, cloudmask, latitude, month, method="modis") | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def cloud_top_height(\n r,\n azimuth,\n elevation,\n st_sweep,\n ed_sweep,\n refl,\n eth_thld=0,\n noise_thld=-2,\n min_range=15e3,\n verbose=False,\n):\n earth_radius = 6371000\n\n na0 = st_sweep[1]\n nsweep = len(st_sweep)\n cloudtop = np.zeros((na0, len(r))) + np.NaN\n ground_range = np.zeros((nsweep, len(r)))\n elev_ref = elevation[0]\n\n for i, st in enumerate(st_sweep):\n ground_range[i, :] = r * np.cos(np.pi * elevation[st + 1] / 180)\n\n for i in range(1, len(st_sweep)):\n st = st_sweep[i]\n ed = ed_sweep[i]\n elev_ref = elevation[st_sweep[i - 1]]\n elev_iter = elevation[st]\n\n st_ref = st_sweep[i - 1]\n ed_ref = ed_sweep[i - 1]\n\n if verbose:\n print(i, st, ed, elev_iter, elev_ref)\n\n for j in range(na0):\n nbeam_ref = np.argmin(np.abs(azimuth[st_ref:ed_ref] - azimuth[j])) + st_ref\n nbeam_iter = np.argmin(np.abs(azimuth[st:ed] - azimuth[j])) + st\n\n if np.abs(azimuth[nbeam_ref] - azimuth[nbeam_iter]) > 5:\n continue\n\n for k in range(len(r)):\n if r[k] < min_range:\n continue\n\n gr_ref = ground_range[i - 1, k]\n npos = np.argmin(np.abs(ground_range[i, :] - gr_ref))\n\n if np.abs(ground_range[i, npos] - ground_range[0, k] > 1000):\n continue\n\n refb = refl[nbeam_ref, k]\n refa = refl[nbeam_iter, npos]\n\n if refb < noise_thld:\n continue\n\n if refa < noise_thld or np.isnan(refa):\n refa = noise_thld\n\n height = np.NaN\n if refb > eth_thld and refa < eth_thld:\n if elev_iter == 90:\n theta_total = elev_iter + 0.5\n else:\n theta_total = (eth_thld - refa) * (elev_ref - elev_iter) / (refb - refa) + elev_ref\n\n # Include correction for Earth sphericity.\n height = (r[k] * np.sin(np.pi * theta_total / 180) +\n np.sqrt(r[k] ** 2 + earth_radius ** 2) - earth_radius)\n\n if np.isnan(height):\n continue\n\n if height > cloudtop[j, k] or np.isnan(cloudtop[j, k]):\n cloudtop[j, k] = height\n\n return cloudtop",
"def height(self) -> float:\n top = 0\n height_ = 0\n for part in self.line_parts:\n if part.state.rise > 0 and part.state.rise > top:\n top = part.state.rise\n if part.state.size > height_:\n height_ = part.state.size\n\n return height_ + self.top_margin + top",
"def height(self) -> int:",
"def height(self) -> int:",
"def height(self) -> int:",
"def top_height_px(self):\n return self.top_pieces * PipePair.PIECE_HEIGHT",
"def top(self) -> float:\n points = self.get_adjusted_points()\n y_points = [point[1] for point in points]\n return max(y_points)",
"def retrieve_EchoTopHeight(\n ds, threshold, variable=\"zFactorFinal\", radar_frequency=\"Ku\", min_threshold=0\n):\n # Retrieve required DataArrays\n da = get_variable_dataarray(ds, variable=variable)\n if len(da[\"radar_frequency\"].data) != 1:\n da = da.sel({\"radar_frequency\": radar_frequency})\n da_height = ds[\"height\"].copy()\n\n # Mask height bin where not raining\n da_mask_3d_rain = da > min_threshold\n da_height = da_height.where(da_mask_3d_rain)\n\n # Mask heights where Z is not above threshold\n da_mask_3d = da > threshold\n da_height_masked = da_height.where(da_mask_3d)\n\n # Retrieve max echo top height\n da_max_height = da_height_masked.max(dim=\"range\")\n\n # Add attributes\n da_max_height.name = f\"ETH{threshold}dBZ\"\n da_max_height.attrs[\"units\"] = \"m\"\n return da_max_height",
"def bb_top(self) -> float:\n return self._bb_top",
"def top_of_climb_index(self):\n return self.altitudes.argmax()",
"def top_y(self):\r\n return self.position.y + self.size.y + self.bulk",
"def mean_height(data):",
"def mean_height(data):",
"def height(self):\n yy = self.yy\n return max(yy) - min(yy)",
"def test_top_keyword(self):\n # Set top to 200\n byt = bytscl(self.array1, top=200)\n mx = numpy.max(byt)\n self.assertEqual(mx, 200)",
"def best_B(Ag):\n top = 0\n for i in range(len(Ag)):\n etop = np.min(cf.TD20[int(Ag[i]) - 1])\n top += etop\n return top",
"def worst_B(Ag):\n bottom = 0\n for i in range(len(Ag)):\n etop = np.max(cf.TD20[int(Ag[i]) - 1])\n bottom += etop\n return bottom",
"def get_height_of_surface_gate(data, setup={}):\n idx = get_index_of_surface_gate(data, setup)\n nt = range(len(idx))\n return data['alt'][nt, idx]",
"def well_diameter_at_top(self):\n return self.radius_from_liquid_depth(self.well_depth) * 2 # a generic impl; subclasses can optimize",
"def heights(self):\n height_curves = np.array(\n [0.35574718, 0.49558236, 0.57875287, 0.66370742, 0.95573868,\n 1., 0.72742333, 0.69203976]) * self.max_height_car\n height_curves[6] = height_curves[5] / self.middle_to_back_height_ratio\n height_curves[7] = height_curves[6] / 1.05\n return height_curves",
"def height(self):\n return self.y.max() - self.y.min()",
"def get_height(self,c):\r\n return self.h",
"def get_uthreshold(img):\n import noiselevel\n # sigma=Table.read('noiselevel.csv',format='csv')['sigma'][0]\n sigma = noiselevel.getnoiselevel(img,ranges=(-30,30),toplot=False)\n \n thres = sigma*np.sqrt(2*np.log(img.size))\n return thres, sigma",
"def first_top_bottom():\n identity = NB_CARDS * np.identity(NB_CARDS)\n # First outcome, the deck isn't changed\n shuffled_deck_1 = deepcopy(identity)\n # Second outcome, the first card is at the bottom and every other cards goes\n # up\n shuffled_deck_2 = deepcopy(identity)\n for i in range(NB_CARDS-1):\n shuffled_deck_2[i] = deepcopy(identity[i+1])\n shuffled_deck_2[NB_CARDS-1] = deepcopy(identity[0])\n # Now we have to combine the two outcome with probability half\n return (shuffled_deck_1 + shuffled_deck_2)/2",
"def compute_height_map(self, cloud, v_axis):\n if v_axis == 0:\n xy_axis = (1, 2)\n elif v_axis == 1:\n xy_axis = (0, 2)\n elif v_axis == 2:\n xy_axis = (0, 1)\n else:\n raise Exception('unknown value axis, {}'.format(v_axis))\n\n d_max = max(self.image_depth, self.image_width, self.image_height)\n im = np.zeros((self.image_pixel, self.image_pixel), dtype='float32')\n\n coords = (cloud[:, xy_axis] + (d_max / 2.0)) * ((self.image_pixel - 1) / d_max)\n coords[coords < 0] = 0\n coords[coords > (self.image_pixel - 1)] = self.image_pixel - 1\n\n values = ((cloud[:, v_axis] + (d_max / 2.0)) / d_max)\n\n self.set_image_max_value(im, coords, values)\n return im",
"def height(self):\n return (self.scene.shape[1] - self.size) // self.size + 1",
"def height(self):\n\t\tpass",
"def footprint_height():",
"def bottom(self) -> float:\n bottom = 0\n for part in self.line_parts:\n if part.state.rise < 0 and -part.state.rise > bottom:\n bottom = -part.state.rise\n return bottom",
"def top_distance(self):\n return self.y"
] | [
"0.6496436",
"0.64250344",
"0.63014233",
"0.63014233",
"0.63014233",
"0.62734956",
"0.62678087",
"0.6001903",
"0.59957576",
"0.5945909",
"0.5942711",
"0.59399575",
"0.59399575",
"0.5902483",
"0.5877307",
"0.58730364",
"0.58112586",
"0.5736717",
"0.573274",
"0.5731176",
"0.5710536",
"0.5707423",
"0.57036525",
"0.56934464",
"0.5687436",
"0.5685607",
"0.56842613",
"0.5672495",
"0.56088877",
"0.5607521"
] | 0.7790907 | 0 |
Estimate the date time per scanline. Based on the approximate recording time for one ASTER image a date time array is constructed along the flight direction and depending on the sensor resolution. | def dt_estimate_scanlines(self, sensor="vnir"):
dtdelta = datetime.timedelta(seconds=8, milliseconds=849)
scanlines = {"vnir": 4200, "swir": 2100, "tir": 700}
return np.linspace(-0.5, 0.5, scanlines[sensor]) * dtdelta + self.datetime | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def time_info(input_file):\n original_path = os.getcwd() #set original directory\n save_path = input_file['save_path']\n planet = input_file['exoplanet'] #set exoplanet name\n print '\\nObtain the images .... \\n'\n print 'Change to ', save_path\n os.chdir(save_path) #change to save directory where is our scvience images\n images = sorted(glob.glob('AB'+input_file['exoplanet']+'*.fits'))\n print '\\nImages = \\n',images\n tempo_loc = [] #time object\n SUN = [] #Sun coordinate object\n ra_sun, dec_sun, dsun = np.zeros(len(images)),np.zeros(len(images)),np.zeros(len(images)) #sun coordinates\n JD = np.zeros(len(images)) #julian date from time object\n ST = np.zeros(len(images))\n HJD = np.zeros(len(images))\n #create the exoplanet object coordianate\n exoplanet = SkyCoord(dec=input_file['DEC'],ra=input_file['RA'],unit=('deg','deg'),frame=input_file['frame'])\n print '\\nObtain data info from header ....\\n'\n for i in range(len(images)):\n hdr = fits.getheader(images[i])\n UTC = hdr['date-obs']+'T'+hdr['UT'] #string that contain the time in UTC in isot format\n tempo_loc.append(Time(UTC,scale=input_file['scale-time'],format='isot',location=(input_file['lon-obs'],input_file['lat-obs'])))#,input_data['altitude'])))\n JD[i] = tempo_loc[i].jd\n ST[i] = tempo_loc[i].sidereal_time('apparent').hour\n SUN.append(get_sun(tempo_loc[i]))\n ra_sun[i],dec_sun[i] = SUN[i].ra.deg, SUN[i].dec.deg\n dsun[i] = SUN[i].distance.value\n HJD[i] = use.hjd_date(JD[i],dsun[i],dec_sun[i],ra_sun[i],exoplanet.dec.deg,exoplanet.ra.deg,circular_orbit=input_file['circular_orbit'])\n use.update_progress((i+1.)/len(images))\n print '\\n.... done.\\n'\n print '\\n Time from header = \\n'\n #print '\\nImages ** UTC (YYYY-MM-DDTHH:MM:SS) ** JD (7d.5d) ** ST (hours) ** ST (HH:MM:SS) ** Sun Coordinate (epoch,RA,DEC,Distance) (deg,deg,AU) \\n'\n ST_string = []\n for i in range(len(images)):\n ST1 = int(ST[i])\n ST2 = int((ST[i]-ST1)*60.)\n ST3 = (((ST[i]-ST1)*60.)-ST2)*60\n ST_string.append(str(ST1)+':'+str(ST2)+':'+str(ST3))\n tempo_loc[i] = tempo_loc[i].value\n use.update_progress((i+1.)/len(images))\n #print images[i], ' ** ',tempo_loc[i], ' ** ', JD[i], ' ** ', ST[i],' ** ',ST_string[i],' ** ',sun_loc[i],' ** ',HJD[i]\n print '\\nSave data file ... \\n'\n data = DataFrame([images,tempo_loc,list(JD),list(ST),list(ST_string),list(ra_sun),list(dec_sun),list(dsun),list(HJD)]).T\n data.columns=['images','UTC','JD','ST','ST_isot','RA_SUN','DEC_SUN','D_SUN','HJD']\n print data\n data.to_csv('results.csv')\n os.chdir(original_path)\n return",
"def test_dateline():\n with rasterio.open(COG_DLINE) as src_dst:\n tile, _ = reader.tile(src_dst, 1, 42, 7, tilesize=64)\n assert tile.shape == (1, 64, 64)\n\n tile, _ = reader.tile(src_dst, 127, 42, 7, tilesize=64)\n assert tile.shape == (1, 64, 64)",
"def _get_time(\n date_sweep,\n time_sweep,\n first_angle_start,\n last_angle_stop,\n angle_step,\n nrays,\n ant_speed,\n scan_type=\"ppi\",\n):\n datetime_sweep = datetime.datetime.strptime(\n date_sweep + \" \" + time_sweep, \"%Y-%m-%d %H:%M:%S\"\n )\n sweep_start_epoch = (datetime_sweep - datetime.datetime(1970, 1, 1)).total_seconds()\n if scan_type == \"ppi\":\n if (last_angle_stop > first_angle_start) and (\n (last_angle_stop - first_angle_start) / nrays > angle_step\n ):\n sweep_duration = (last_angle_stop - first_angle_start) / ant_speed\n else:\n sweep_duration = (last_angle_stop + 360.0 - first_angle_start) / ant_speed\n else:\n if last_angle_stop > first_angle_start:\n sweep_duration = (last_angle_stop - first_angle_start) / ant_speed\n else:\n sweep_duration = (first_angle_start - last_angle_stop) / ant_speed\n\n time_angle = sweep_duration / nrays\n\n sweep_end_epoch = sweep_start_epoch + sweep_duration\n\n time_data = np.linspace(\n sweep_start_epoch + time_angle / 2.0,\n sweep_end_epoch - time_angle / 2.0,\n num=nrays,\n )\n\n return time_data, sweep_start_epoch",
"def time_calibration(input_file):\n original_path = os.getcwd()\n save_path = input_file['save_path']\n #change to save data reduction directory\n os.chdir(save_path)\n print '\\n Reading the list of images ....\\n'\n planet = input_file['exoplanet'] #set exoplanet name\n images = sorted(glob.glob('AB'+planet+'*.fits'))\n print images\n #include de RA,DEC and epoch of the exoplanet\n RA,DEC,epoch = input_file['RA'],input_file['DEC'],input_file['epoch']\n #obtain ST JD using iraf task and introduce in the header\n for i in range(len(images)):\n hdr = fits.getheader(images[i])\n if int(split(hdr['UT'],':')[0]) < int(hdr['timezone']):\n new_date = use.yesterday(hdr['date-obs'])\n #print images[i], new_date\n else:\n new_date = hdr['date-obs']\n year,month,day = split(new_date,'-')\n iraf.asttimes(year=year,month=month,day=day,time=hdr['loctime'],obs=input_file['observatory'])\n JD = iraf.asttimes.jd #obtain julian date\n LMST = iraf.asttimes.lmst #obtain the sideral time\n LMST = use.sexagesimal_format(LMST) #convert sideral time in sexagesimal format\n iraf.hedit(images[i],'ST',LMST,add='yes',verify='no',show='no',update='yes') #create the ST keyword in the header\n iraf.ccdhedit(images[i],'LMST',LMST,type='string') #include the mean sideral time in the header\n iraf.ccdhedit(images[i],'JD',JD,type='string') #include de julian date in the header\n #include RA, and DEC of the object in your header\n iraf.ccdhedit(images[i],\"RA\",RA,type=\"string\") #include right ascention in the header\n iraf.ccdhedit(images[i],\"DEC\",DEC,type=\"string\") #include declination in the header\n iraf.ccdhedit(images[i],\"epoch\",epoch,type=\"string\") #include epoch in the header\n # use.update_progress((i+1.)/len(images))\n print '\\n Setting airmass ....\\n'\n for i in range(len(images)):\n print '# ',images[i]\n #iraf.hedit(images[i],'airmass',airmass,add='yes')\n #iraf.hedit(images[i],'HJD',HJD,add='yes')\n iraf.setairmass.observatory = input_file['observatory']\n iraf.setairmass(images[i])\n iraf.setjd.time = 'ut'\n iraf.setjd(images[i])\n print '\\n.... done.\\n'\n #export information\n hjd, jd, airmass, st = [],[],[],[]\n for i in range(len(images)):\n hdr = fits.getheader(images[i])\n hjd.append(hdr['HJD'])\n jd.append(hdr['JD'])\n airmass.append(hdr['airmass'])\n st.append(hdr['st'])\n #saving the data\n data = DataFrame([list(hjd),list(jd),list(st),list(airmass)]).T\n data.columns = ['HJD','JD','ST','Airmass']\n data.to_csv('results_iraf_calibrations.csv')\n #change to workings directory\n os.chdir(original_path)\n return",
"def _calc_time(time_lines: list) -> np.ndarray:\n time = [time_to_fraction_hour(line.split()[1]) for line in time_lines]\n return np.array(time)",
"def timeCalc(image):\n telheader = astropy.io.fits.open(image)\n UT = telheader[0].header['UT']\n secs = float(UT[6:10])\n mins = float(UT[3:5])\n hours = float(UT[0:2])\n time = secs+mins*60.+hours*(60.*60.)\n\n return time",
"def doit(gts, hr):\n sts = gts - datetime.timedelta(hours=hr)\n times = [gts]\n if hr > 24:\n times.append(gts - datetime.timedelta(hours=24))\n if hr == 72:\n times.append(gts - datetime.timedelta(hours=48))\n metadata = {'start_valid': sts.strftime(\"%Y-%m-%dT%H:%M:%SZ\"),\n 'end_valid': gts.strftime(\"%Y-%m-%dT%H:%M:%SZ\")}\n # Create the image data\n # imgdata = np.zeros( (szy, szx), 'u1')\n # timestep = np.zeros( (szy, szx), 'f')\n total = None\n for now in times:\n gribfn = now.strftime((\"/mnt/a4/data/%Y/%m/%d/mrms/ncep/\"\n \"RadarOnly_QPE_24H/\"\n \"RadarOnly_QPE_24H_00.00_%Y%m%d-%H%M00\"\n \".grib2.gz\"))\n if not os.path.isfile(gribfn):\n print(\"mrms_raster_pXXh.py MISSING %s\" % (gribfn,))\n return\n fp = gzip.GzipFile(gribfn, 'rb')\n (tmpfp, tmpfn) = tempfile.mkstemp()\n tmpfp = open(tmpfn, 'wb')\n tmpfp.write(fp.read())\n tmpfp.close()\n grbs = pygrib.open(tmpfn)\n grb = grbs[1]\n os.unlink(tmpfn)\n\n # careful here, how we deal with the two missing values!\n if total is None:\n total = grb['values']\n else:\n maxgrid = np.maximum(grb['values'], total)\n total = np.where(np.logical_and(grb['values'] >= 0, total >= 0),\n grb['values'] + total, maxgrid)\n\n \"\"\"\n 255 levels... wanna do 0 to 20 inches\n index 255 is missing, index 0 is 0\n 0-1 -> 100 - 0.01 res || 0 - 25 -> 100 - 0.25 mm 0\n 1-5 -> 80 - 0.05 res || 25 - 125 -> 80 - 1.25 mm 100\n 5-20 -> 75 - 0.20 res || 125 - 500 -> 75 - 5 mm 180\n \"\"\"\n # total = np.flipud(total)\n # Off scale gets index 254\n imgdata = convert_to_image(total)\n\n (tmpfp, tmpfn) = tempfile.mkstemp()\n # Create Image\n png = Image.fromarray(imgdata.astype('u1'))\n png.putpalette(mrms.make_colorramp())\n png.save('%s.png' % (tmpfn,))\n # os.system(\"xv %s.png\" % (tmpfn,))\n # Now we need to generate the world file\n mrms.write_worldfile('%s.wld' % (tmpfn,))\n # Inject WLD file\n pqstr = (\"/home/ldm/bin/pqinsert -i -p 'plot ac %s \"\n \"gis/images/4326/mrms/p%sh.wld GIS/mrms/p%sh_%s.wld wld' %s.wld\"\n \"\") % (gts.strftime(\"%Y%m%d%H%M\"), hr, hr,\n gts.strftime(\"%Y%m%d%H%M\"), tmpfn)\n subprocess.call(pqstr, shell=True)\n\n # Now we inject into LDM\n pqstr = (\"/home/ldm/bin/pqinsert -i -p 'plot ac %s \"\n \"gis/images/4326/mrms/p%sh.png GIS/mrms/p%sh_%s.png png' %s.png\"\n \"\") % (gts.strftime(\"%Y%m%d%H%M\"), hr, hr,\n gts.strftime(\"%Y%m%d%H%M\"), tmpfn)\n subprocess.call(pqstr, shell=True)\n\n # Create 900913 image\n cmd = (\"gdalwarp -s_srs EPSG:4326 -t_srs EPSG:3857 -q -of GTiff \"\n \"-tr 1000.0 1000.0 %s.png %s.tif\") % (tmpfn, tmpfn)\n subprocess.call(cmd, shell=True)\n\n # Insert into LDM\n pqstr = (\"/home/ldm/bin/pqinsert -i -p 'plot c %s \"\n \"gis/images/900913/mrms/p%sh.tif GIS/mrms/p%sh_%s.tif tif' %s.tif\"\n \"\") % (gts.strftime(\"%Y%m%d%H%M\"), hr, hr,\n gts.strftime(\"%Y%m%d%H%M\"), tmpfn)\n subprocess.call(pqstr, shell=True)\n\n j = open(\"%s.json\" % (tmpfn,), 'w')\n j.write(json.dumps(dict(meta=metadata)))\n j.close()\n\n # Insert into LDM\n pqstr = (\"/home/ldm/bin/pqinsert -i -p 'plot c %s \"\n \"gis/images/4326/mrms/p%sh.json GIS/mrms/p%sh_%s.json json'\"\n \" %s.json\") % (gts.strftime(\"%Y%m%d%H%M\"), hr, hr,\n gts.strftime(\"%Y%m%d%H%M\"), tmpfn)\n subprocess.call(pqstr, shell=True)\n for suffix in ['tif', 'json', 'png', 'wld']:\n os.unlink('%s.%s' % (tmpfn, suffix))\n os.close(tmpfp)\n os.unlink(tmpfn)",
"def get_time_series(self, tile, year, loc, px, py, cols=1, rows=1, step=1, save_dir='txt/'):\n\n # keys = ['sza', 'saa', 'vza', 'vaa', 'qa', 'b01', 'b02', 'b03', 'b04', 'b05', 'b06', 'b07']\n\n timeBefore = time.clock()\n\n f_list = np.array(glob.glob(loc + '%s_%d_*_1km.nc' % (tile, year)))\n\n # if there are no files for this year\n if f_list.shape[0] == 0:\n print 'Data for year %d and tile %s not found' % (year, tile)\n return -1\n\n # get DOYs from file name\n doys0 = np.sort([int(s.split('_')[4]) for s in f_list])\n # print 'doys0', doys0\n\n # arrange DOYs according to step. I.e. we assume that...\n # step = 7\n doys = np.zeros(doys0.shape).astype(int)\n doys_real = np.zeros(doys0.shape).astype(int)\n\n for jj, ii in enumerate(xrange(0, doys0.shape[0], step)):\n # doys = np.append(doys, doys0[ii:ii+7])\n doys[ii:ii+step] = jj + 1#doys0[ii]\n doys_real[ii:ii+step] = doys0[ii]\n\n ind = np.argsort([int(s.split('_')[4]) for s in f_list])\n f_list = f_list[ind]\n\n # print 'loc:', loc\n # print 'tile:', tile\n # print 'year:', year\n # print 'f_list:', f_list[0]\n\n output = {}\n for f in f_list:\n print 'f:', f\n try:\n ds = nc.Dataset(f)\n except:\n print 'something wrong with %s' % f\n continue\n\n # if a dataset is empty\n # i.e. if it has less than 2 bands\n # i.e. vza, vaa, sza, saa, proj, geo, qa, b1, b2\n if len(ds.variables.keys()) < 9:\n print 'Dataset exists but empty:'\n print 'loc:', loc\n print 'tile:', tile\n print 'year:', year\n print 'f_list:', f_list[0]\n print ''\n # return -1\n else:\n break\n if f == f_list[-1]:\n print 'all datasets are empty'\n return -1\n\n for key in ds.variables.keys():\n if len(ds.variables[key].shape) == 2:\n # output[key] = np.zeros((f_list.shape[0], ds.variables[key].shape[0], ds.variables[key].shape[1]))\n output[key] = np.zeros((f_list.shape[0], cols, rows))\n if len(ds.variables[key].shape) == 1:\n output[key] = np.zeros(ds.variables[key].shape[0]).astype(str)\n\n for i, fname in enumerate(f_list):\n #print fname\n ds = nc.Dataset(fname)\n for key in ds.variables.keys():\n if len(ds.variables[key].shape) == 2:\n\n try:\n # print ds.variables[key][px:px+cols, py:py+rows]\n output[key][i, :, :] = ds.variables[key][px:px+cols, py:py+rows]\n except:\n print 'something wrong in output[%s][%d, :, :]' % (key, i)\n print 'output:', output[key][i, :, :].shape\n print 'ds.variables:', ds.variables[key][px:px+cols, py:py+rows].shape\n\n if len(ds.variables[key].shape) == 1:\n output[key][:] = ds.variables[key][:]\n\n # print 'output.keys:', output.keys()\n\n QA_OK = np.array([8, 72, 136, 200, 1288, 2056, 2120, 2184, 2248])\n qa_passer = np.logical_or.reduce([output['qa'] == x for x in QA_OK])\n\n for b in [1,2,3,4,5,7]:\n\n qa_passer[output[\"b0%d\" % b] <= 0] = 0.\n qa_passer[output[\"b0%d\" % b] >= 10000] = 0.\n\n # if, for this pixel, we have just a few observations we don't need them\n if np.sum(qa_passer) < 2:\n qa_passer[:] = 0\n\n output['qa_passer'] = qa_passer\n [bin(b) for b in QA_OK]\n\n #doys = np.array([int(g.GetRasterBand(b+1).GetMetadata()['DoY']) for b in xrange(g.RasterCount)])\n #years = np.array([int(g.GetRasterBand(b + 1).GetMetadata()['Year']) for b in xrange(g.RasterCount)])\n output['doys'] = doys\n output['doys_real'] = np.unique(doys_real)\n output['years'] = np.ones(doys.shape) * year\n\n output[\"sza\"] = output[\"sza\"] / 100.\n output[\"saa\"] = output[\"saa\"] / 100.\n output[\"vza\"] = output[\"vza\"] / 100.\n output[\"vaa\"] = output[\"vaa\"] / 100.\n output['b01'] = output['b01'] / 10000.\n output['b02'] = output['b02'] / 10000.\n output['b03'] = output['b03'] / 10000.\n output['b04'] = output['b04'] / 10000.\n output['b05'] = output['b05'] / 10000.\n output['b06'] = output['b06'] / 10000.\n output['b07'] = output['b07'] / 10000.\n\n # print 'qa_passer:', output['qa_passer']\n #print output['b01']\n\n #pkl.dump(output, open(f_out, 'wb'))\n\n timeAfter = time.clock()\n elapsed_time = timeAfter - timeBefore\n print 'read time series time (s): ', elapsed_time\n\n print 'Read MODIS for year %d data is done' % year\n return output",
"def define_secdate(self):\r\n \r\n # Since 2017\r\n self.start_date = datetime.datetime(2017,1,1) + (datetime.datetime(2017,12,31) - datetime.datetime(2017,1,1))/2 \r\n self.end_date = datetime.datetime(2050,1,1)\r\n self.ktime = (self.end_date - self.start_date).days + 1\r\n self.date = np.zeros(self.ktime,dtype=datetime.datetime)\r\n self.t = np.zeros(self.ktime)\r\n self.dt = 1/365.25\r\n \r\n for k in range(0,self.ktime):\r\n \r\n self.date[k] = self.start_date + datetime.timedelta(days=self.t[k]*365.25)\r\n\r\n if k < self.ktime-1:\r\n \r\n self.t[k+1] = self.t[k] + self.dt\r\n \r\n # Since 1990\r\n self.start_date_hist = datetime.datetime(1990,1,1) + (datetime.datetime(1990,12,31) - datetime.datetime(1990,1,1))/2 \r\n self.ktime_1990_2050 = (self.end_date - self.start_date_hist).days + 1\r\n self.date_1990_2050 = np.zeros(self.ktime_1990_2050,dtype=datetime.datetime)\r\n self.t_1990_2050 = np.zeros(self.ktime_1990_2050)\r\n \r\n for k in range(0,self.ktime_1990_2050):\r\n \r\n self.date_1990_2050[k] = self.start_date_hist + datetime.timedelta(days=self.t_1990_2050[k]*365.25)\r\n \r\n if (self.date_1990_2050[k].year == self.start_date.year and self.date_1990_2050[k].month == self.start_date.month and self.date_1990_2050[k].day == self.start_date.day):\r\n \r\n self.ktime_proj_crossing = k\r\n \r\n \r\n if k < self.ktime-1:\r\n \r\n self.t_1990_2050[k+1] = self.t_1990_2050[k] + self.dt \r\n \r\n return",
"def calc_frame_time(instrument, aperture, xdim, ydim, amps):\n instrument = instrument.lower()\n if instrument == \"nircam\":\n xs = xdim\n ys = ydim\n colpad = 12\n\n # Fullframe\n if amps == 4:\n rowpad = 1\n fullpad = 1\n else:\n # All subarrays\n rowpad = 2\n fullpad = 0\n if ((xdim <= 8) & (ydim <= 8)):\n # The smallest subarray\n rowpad = 3\n\n elif instrument == \"niriss\":\n xs = ydim\n ys = xdim\n colpad = 12\n\n # Fullframe\n if amps == 4:\n rowpad = 1\n fullpad = 1\n else:\n rowpad = 2\n fullpad = 0\n\n elif instrument == 'fgs':\n xs = ydim\n ys = xdim\n colpad = 6\n if 'acq1' in aperture.lower():\n colpad = 12\n rowpad = 1\n if amps == 4:\n fullpad = 1\n else:\n fullpad = 0\n\n return ((1.0 * xs / amps + colpad) * (ys + rowpad) + fullpad) * 1.e-5",
"def make_livetime_histogram(aHtgLt, nRegion, pathFileScAll, metStart, metStop, aFileToI, aCoordsPix_array, aAreaPix_array, origin_time=0, metExStart=0, metExStop=0):\n fmwStart = ConvertMetToFMW(metStart)\n fmwStop = ConvertMetToFMW(metStop)\n print '=========================================='\n print 'Going to look MET', metStart, '-', metStop\n print \"Fermi Mission Week:\", fmwStart, \"-\", fmwStop\n print '=========================================='\n print 'MET',metExStart, '-', metExStop, 'is excluded.'\n cmd = \"ls {0}\".format(pathFileScAll)\n ret = commands.getoutput(cmd)\n aPathFileScAll = ret.split(\"\\n\")\n for iFileSc in range(len(aPathFileScAll)):\n strPathFileSc = aPathFileScAll[iFileSc]\n #fmwFile = int(strPathFileSc[-27:-24])\n # Make file list\n #if fmwFile>=int(fmwStart-1) and fmwFile<=int(fmwStop+1) :\n aFileToI.append(aPathFileScAll[iFileSc])\n timeStart = datetime.datetime.now() # For progress bar\n for fileToI in aFileToI:\n hdulistSC = fits.open(fileToI)\n tbdataSC = hdulistSC[1].data\n aSTART, aSTOP = tbdataSC.field('START'), tbdataSC.field('STOP')\n aRA_ZENITH = tbdataSC.field('RA_ZENITH')\n aDEC_ZENITH = tbdataSC.field('DEC_ZENITH')\n aRA_SCZ = tbdataSC.field('RA_SCZ')\n aRA_SCX = tbdataSC.field('RA_SCX')\n aDEC_SCZ = tbdataSC.field('DEC_SCZ')\n aDEC_SCX = tbdataSC.field('DEC_SCX')\n aLIVETIME = tbdataSC.field('LIVETIME')\n aDATA_QUAL = tbdataSC.field('DATA_QUAL')\n aLAT_CONFIG = tbdataSC.field('LAT_CONFIG')\n nTI = len(aSTART)\n print \" \", fileToI, \"(\", nTI, \"intervals in total)\"\n\n dict_cut = {}\n dict_cut['time'] = np.array(( (aSTART>=metStart) * (aSTART<metStop) ) * ( ((metExStart==0) * (metExStop==0)) + (aSTOP<metExStart) + (aSTART>=metExStop)), dtype=bool)\n dict_cut['qual'] = aDATA_QUAL>0\n dict_cut['config'] = aLAT_CONFIG==1\n print '* Cuts'\n for k, v in dict_cut.items():\n print '{k}: {v}'.format(k=k, v=v[:100])\n cut_combined_interval = np.array(dict_cut['time'] * dict_cut['qual'] * dict_cut['config'], dtype=bool) #np.prod(dict_cut.values())\n print '* Combined cut'\n print cut_combined_interval[:100]\n\n # coordsSCZ_interval = SkyCoord(aRA_SCZ, aDEC_SCZ, unit=\"deg\")\n # coordsZenith_interval = SkyCoord(aRA_ZENITH, aDEC_ZENITH, unit=\"deg\")\n # tplot_interval = aSTART-origin_time\n #vecSCX = np.array(hppf.ang2vec(math.pi/2.-math.radians(aDEC_SCX), math.radians(aRA_SCX)))\n #vecSCZ = np.array(hppf.ang2vec(math.pi/2.-math.radians(aDEC_SCZ), math.radians(aRA_SCZ)))\n\n for iR in range(nRegion):\n if (isinstance(aAreaPix_array[iR], int) or isinstance(aAreaPix_array[iR], float)) and aAreaPix_array[iR]==0: # Point-like region\n angSCZ = coordsSCZ.separation(aCoordsPix_array[iR])\n radSCZ = float(angSCZ.to_string(unit=u.rad, decimal=True))\n angZenith = coordsZenith.separation(aCoordsPix_array[iR])\n degZenith = float(angZenith.to_string(unit=u.deg, decimal=True))\n aHtgLt[iR].Fill(cos(radSCZ), degZenith, tplot, tti)\n else: # Extended region\n npixel = len(aAreaPix_array[iR])\n coordsSCZ_interval = SkyCoord(np.array([aRA_SCZ]).T, np.array([aDEC_SCZ]).T, unit=\"deg\")\n print 'Telescope boresight has been reconstructed.'\n coordsZenith_interval = SkyCoord(np.array([aRA_ZENITH]).T, np.array([aDEC_ZENITH]).T, unit=\"deg\")\n print 'Zenith direction has been reconstructed.'\n #coordsPix_pixel = aCoordsPix_array[iR]\n\n angSCZ_interval_pixel = coordsSCZ_interval.separation(aCoordsPix_array[iR])\n cosSCZ_interval_pixel = np.cos(angSCZ_interval_pixel)\n print 'Inclination for each pixel has been calculated.'\n\n angZenith_interval_pixel = coordsZenith_interval.separation(aCoordsPix_array[iR])\n #degZenith = float(angZenith.to_string(unit=u.deg, decimal=True))\n print 'Zenith angle for each pixel has been calculated.'\n\n tplot_interval = aSTART-origin_time\n\n time_valid = cut_combined_interval * aLIVETIME #* aAreaPix_array[iR]\n print time_valid[:100]\n livetime_interval_pixel = np.dot(np.array([time_valid]).T, np.array([aAreaPix_array[iR]]))\n print 'Livetime for each pixel has been calculated.'\n\n for iTI in range(nTI):\n for jpix in range(len(aCoordsPix_array[iR])):\n# if iTI<10 and livetime_interval_pixel[iTI][jpix]>0:\n# print '''Inclination: {cth}\n# Zenith: {za}\n# Time: {tp}\n# Livetime: {lv}\n# '''.format(cth=cosSCZ_interval_pixel[iTI][jpix], za=float(angZenith_interval_pixel[iTI][jpix].to_string(unit=u.deg, decimal=True)), tp=tplot_interval[iTI], lv=livetime_interval_pixel[iTI][jpix])\n aHtgLt[iR].Fill(cosSCZ_interval_pixel[iTI][jpix], float(angZenith_interval_pixel[iTI][jpix].to_string(unit=u.deg, decimal=True)), tplot_interval[iTI], livetime_interval_pixel[iTI][jpix])\n if iTI%100==0:\n print '{0:2.0f}% have been filled.'.format(iTI*100/nTI)\n sys.stdout.flush()\n\n # nTI_included = 0\n # for iTI in range(nTI):\n # if ( aSTART[iTI]>=metStart and aSTART[iTI]<metStop ) and ( (metExStart==0 and metExStop==0) or aSTOP[iTI]<metExStart or aSTART[iTI]>=metExStop):\n # nTI_included = nTI_included+1\n # if not aDATA_QUAL[iTI]>0:\n # print 'Bad time interval', aSTART[iTI], '-', aSTOP[iTI], ':', aDATA_QUAL[iTI]\n # continue\n # if not aLAT_CONFIG[iTI]==1:\n # print 'LAT config:', aSTART[iTI], '-', aSTOP[iTI], ':', aLAT_CONFIG[iTI]\n # continue\n # tti = aLIVETIME[iTI]\n # coordsSCZ = SkyCoord(aRA_SCZ[iTI], aDEC_SCZ[iTI], unit=\"deg\")\n # coordsZenith = SkyCoord(aRA_ZENITH[iTI], aDEC_ZENITH[iTI], unit=\"deg\")\n # tplot = aSTART[iTI]-origin_time\n # vecSCX = np.array(hppf.ang2vec(math.pi/2.-math.radians(aDEC_SCX[iTI]), math.radians(aRA_SCX[iTI])))\n # vecSCZ = np.array(hppf.ang2vec(math.pi/2.-math.radians(aDEC_SCZ[iTI]), math.radians(aRA_SCZ[iTI])))\n # for iR in range(nRegion):\n # if aAreaPix_array[iR]==0:\n # angSCZ = coordsSCZ.separation(aCoordsPix_array[iR])\n # radSCZ = float(angSCZ.to_string(unit=u.rad, decimal=True))\n # angZenith = coordsZenith.separation(aCoordsPix_array[iR])\n # degZenith = float(angZenith.to_string(unit=u.deg, decimal=True))\n # aHtgLt[iR].Fill(cos(radSCZ), degZenith, tplot, tti)\n # else: \n # for (jpix, coordsPix) in enumerate(aCoordsPix_array[iR]):\n # angSCZ = coordsSCZ.separation(coordsPix)\n # radSCZ = float(angSCZ.to_string(unit=u.rad, decimal=True))\n # angZenith = coordsZenith.separation(coordsPix)\n # degZenith = float(angZenith.to_string(unit=u.deg, decimal=True))\n # aHtgLt[iR].Fill(cos(radSCZ), degZenith, tplot, tti*aAreaPix_array[iR][jpix])\n # if iTI%20==0:\n # print iTI, aSTART[iTI], aRA_SCZ[iTI], aDEC_SCZ[iTI], tbdataSC.field('LAT_MODE')[iTI], aDATA_QUAL[iTI]\n# sys.stdout.flush()\n print 'Histogram filling has been finished.' #print nTI_included, 'intervals are included.'",
"def _generate_time_values(self):\r\n # Populate time values\r\n log('writing times', 'INFO')\r\n d1970 = datetime(1970, 1, 1, tzinfo=utc)\r\n time_array = [[int((self.start_datetime - d1970).total_seconds())]]\r\n \r\n datetime_nc_start_simulation = self.start_datetime\r\n for raw_nc_index, raw_nc in enumerate(self.raw_nc_list):\r\n \r\n raw_nc_time = raw_nc.get_time_array(datetime_simulation_start=datetime_nc_start_simulation,\r\n simulation_time_step_seconds=self.time_step_array[raw_nc_index])\r\n \r\n time_array.append(raw_nc_time)\r\n datetime_nc_start_simulation = datetime.utcfromtimestamp(raw_nc_time[-1])\r\n \r\n self.cf_nc.variables['time'][:] = np.concatenate(time_array)\r\n end_date = datetime.utcfromtimestamp(self.cf_nc.variables['time'][-1])\r\n self.cf_nc.time_coverage_start = self.start_datetime.isoformat() + 'Z'\r\n self.cf_nc.time_coverage_end = end_date.isoformat() + 'Z'",
"def daily_observation(z, ncells, filename, total_int_time=4., int_time=10., boxsize=None, declination=30.):\n\tNbase, N_ant = from_antenna_config(filename, z)\n\tuv_map0 = get_uv_coverage(Nbase, z, ncells, boxsize=boxsize)\n\tuv_map\t = np.zeros(uv_map0.shape)\n\ttot_num_obs = int(3600.*total_int_time/int_time)\n\tfor i in xrange(tot_num_obs-1):\n\t\tnew_Nbase = earth_rotation_effect(Nbase, i+1, int_time, declination=declination)\n\t\tuv_map1 = get_uv_coverage(new_Nbase, z, ncells, boxsize=boxsize)\n\t\tuv_map += uv_map1\n\t\tprint i\n\tuv_map = (uv_map+uv_map1)/tot_num_obs\n\treturn uv_map, N_ant",
"def get_itime_section_data(date, time):\n return np.array([time, date.day, date.month, date.year, -2345, 1, 0, -2345, -2345, -2345, 0, 0, 0])",
"def calculation_time_analysis():\n\tfrom . import spectra as sp\n\tp_dict = {'Bfield':700,'rb85frac':1,'Btheta':88*np.pi/180,'Bphi':0*np.pi/180,'lcell':75e-3,'T':84,'Dline':'D2','Elem':'Cs'}\n\tchiL,chiR,chiZ = sp.calc_chi([-3500],p_dict)\n\t\n\tfor angle in [0, np.pi/32, np.pi/16, np.pi/8, np.pi/4, np.pi/2]:\n\t\tprint(('Angle (degrees): ',angle*180/np.pi))\n\t\tRotMat, n1, n2 = solve_diel(chiL,chiR,chiZ,angle)",
"def image_time(self, path_name, timezone='GMT', delta_hours=0, delta_minutes=0, delta_seconds=0):\n # Open the file for reading\n f = open(path_name, 'r')\n # And extract the tags\n tags = EXIF.process_file(f)\n f.close()\n if len(tags) == 0 or 'Image DateTime' not in tags:\n return None\n capture_time = tags['Image DateTime']\n # Add the timezone the camera time is set to\n img_time = capture_time.printable + timezone\n # Parse the timestap\n cdt = datetime.strptime(img_time, '%Y:%m:%d %H:%M:%S%Z')\n # And process the offset for clock skew\n delta = timedelta(hours=delta_hours, minutes=delta_minutes, seconds=delta_seconds)\n cdt = cdt - delta\n self.files_read += 1\n return cdt",
"def decodeSpaceTime(self, result):\r\n if self.case == 1:\r\n if self.granularity == 'day':\r\n return map(lambda x: [reader.formatTime(reader.inverseDaySinceEpoch(int(x[0]/self.scale))),\r\n reader.morton2coordsX2D(x[1], self.offx, self.scalex, self.roundNum), \r\n reader.morton2coordsY2D(x[1], self.offy, self.scaley, self.roundNum), x[2]], result)\r\n else:\r\n return map(lambda x: [int(x[0]/self.scale), reader.morton2coordsX2D(x[1], self.offx, self.scalex, self.roundNum), \r\n reader.morton2coordsY2D(x[1], self.offy, self.scaley, self.roundNum), x[2]], result)\r\n elif self.case == 2:\r\n if self.granularity == 'day':\r\n return map(lambda x: [reader.formatTime(reader.inverseDaySinceEpoch(int(x[0]/self.scale))), \r\n reader.morton2coordsX3D(x[1], self.offx, self.scalex, self.roundNum), \r\n reader.morton2coordsY3D(x[1], self.offy, self.scaley, self.roundNum), \r\n reader.morton2coordsZ3D(x[1], self.offz, self.scalez, self.roundNum)], result)\r\n else:\r\n return map(lambda x: [int(x[0]/self.scale), reader.morton2coordsX3D(x[1], self.offx, self.scalex, self.roundNum), \r\n reader.morton2coordsY3D(x[1], self.offy, self.scaley, self.roundNum), \r\n reader.morton2coordsZ3D(x[1], self.offz, self.scalez, self.roundNum)], result)\r\n elif self.case == 3:\r\n if self.granularity == 'day':\r\n return map(lambda x: [reader.formatTime(reader.inverseDaySinceEpoch(int(reader.morton2coordst3D(x[0])/self.scale))), \r\n reader.morton2coordsY3D(x[0], self.offx, self.scalex, self.roundNum),\r\n reader.morton2coordsZ3D(x[0], self.offy, self.scaley, self.roundNum), x[1]], result)\r\n else:\r\n return map(lambda x: [int(reader.morton2coordst3D(x[0])/self.scale), \r\n reader.morton2coordsY3D(x[0], self.offx, self.scalex, self.roundNum), \r\n reader.morton2coordsZ3D(x[0], self.offy, self.scaley, self.roundNum), x[1]], result)\r\n elif self.case == 4:\r\n if self.granularity == 'day':\r\n return map(lambda x: [reader.formatTime(reader.inverseDaySinceEpoch(int(reader.morton2coordst4D(x[0])/self.scale))), \r\n reader.morton2coordsX4D(x[0], self.offx, self.scalex, self.roundNum), \r\n reader.morton2coordsY4D(x[0], self.offy, self.scaley, self.roundNum), \r\n reader.morton2coordsZ4D(x[0], self.offz, self.scalez, self.roundNum)], result)\r\n else:\r\n return map(lambda x: [int(reader.morton2coordst4D(x[0])/self.scale), \r\n reader.morton2coordsX4D(x[0], self.offx, self.scalex, self.roundNum), \r\n reader.morton2coordsY4D(x[0], self.offy, self.scaley, self.roundNum), \r\n reader.morton2coordsZ4D(x[0], self.offz, self.scalez, self.roundNum)], result)",
"def UTC_times(times, \n trace, \n diff_thres = 30.0):\n # set times values to seconds\n \n #AUTOMATE THIS SECTION!\n #CHECK THAT THIS IS CORRECT\n times = times / trace.stats.sampling_rate\n #remove unwanted parts of times numpy array \n times = times[:,0]\n \n #remove the first instance of time because it is \n #somehow always of the wrong format!\n #times = np.delete(times, 0) \n \n event_times = []\n event = [times[0]]\n \n start_time = trace.stats.starttime\n \n #for item in times:\n # print start_time + item\n\n for i in range(1, len(times)):\n \n # check if two events in times array have a difference < diff_thres, \n #if not, run average of those times, if so append that events to a \n #new events_times list\n \n #time_diff = times[i + 1] - times[i]\n \n time_diff = times[i] - times[i-1]\n\n #save info until events are far enough apart! \n if time_diff < diff_thres:\n\n event.append(times[i])\n \n \n #raise conditional for if events are far enough apart! \n else:\n\n event_start = event[0] - 2 #minus 5 seconds\n event_end = max(event) + 2 #add 5 seconds\n\n event_times.append([event_start, event_end])\n \n event = [] \n \n event.append(times[i])\n\n #if event still contains something for any reason, add it to event times\n if len(event) > 0: \n event_start = event[0] - 2 #minus 5 seconds\n event_end = max(event) + 2 #add 5 seconds\n event_times.append([event_start, event_end])\n event = [] \n \n\n\n #if len(event_times) == 0 and len(event) > 0 or time_diff > diff_thres and len(event) > 0:\n \n #event_times.append(sum(event) / len(event))\n \n # event_start = event[0] - 2 #minus 5 seconds\n # event_end = event[-1] + 2 #add 5 seconds\n \n # event_times.append([event_start, event_end])\n \n # event = []\n \n #event_times.append(times[i])\n \n # else:\n # event.append(times[i])\n \n\n UTC_events = []\n\n #earthquake length threshold is 10 seconds and above!\n eq_len = 0#5.0\n\n for i in event_times:\n estart = start_time + i[0]\n eend = start_time + i[1]\n \n if eend - estart > eq_len:\n UTC_events.append([estart, eend])\n \n #UTC_events = np.unique(np.asarray(UTC_events))\n\n \n return UTC_events",
"def organize_data(path_dir, accelerometer_file, accelerometer_data):\n\n accelerometer_df = pd.read_csv(os.path.join(path_dir, accelerometer_file), usecols=['UTC time', 'x', 'y', 'z'])\n\n x_list = accelerometer_df['x']\n y_list = accelerometer_df['y']\n z_list = accelerometer_df['z']\n UTC_times_list = accelerometer_df['UTC time']\n\n x_y_z_list_for_hour = [] # will contain 60*60 values, that every value is [x,y,z]\n\n curr_line_index = 0\n curr_date_time = get_date_time_from_UTC_time(UTC_times_list[curr_line_index])\n for i in range(60):\n for j in range(60):\n if (curr_date_time.minute != i or curr_date_time.second != j) or curr_line_index + 1 == len(UTC_times_list): # the curr time is more or little then the wanted time, or we finished all the lines in the file --> there is a need to fulfill the values with 0,0,0\n continue\n else:\n x_y_z_list_for_hour.append([x_list[curr_line_index], y_list[curr_line_index], z_list[curr_line_index]])\n while curr_date_time.minute == i and curr_date_time.second <= j and curr_line_index + 1 != len(UTC_times_list):\n curr_line_index += 1\n curr_date_time = get_date_time_from_UTC_time(UTC_times_list[curr_line_index])\n date = get_date_from_file_name(accelerometer_file)\n hour = curr_date_time.hour\n if date not in accelerometer_data.data_dic:\n accelerometer_data.data_dic[date] = {}\n accelerometer_data.data_dic[date][hour] = x_y_z_list_for_hour",
"def make_times(night, runs, observatory, times, full, instrument, okwrite):\n\n # use this to check times are vaguely right. time of runs\n # must lie between 06.00 local time on date corresponding to\n # start of night date and 1.5 days later. Has picked up a\n # few erroneously dated nights on the TNT.\n mjd_ref = Time(night).mjd - observatory.lon.degree/360 + 0.25\n\n tdata = {}\n with open(times if okwrite else os.devnull,'w') as tout:\n for run in runs:\n if full:\n print(f'Analysing times for run {run}')\n dfile = os.path.join(night, run)\n try:\n ntotal = 0\n if instrument == 'HiPERCAM':\n rtime = hcam.hcam.Rtime(dfile)\n else:\n rtime = hcam.ucam.Rtime(dfile)\n\n # Find first good time, has to roughly match the start\n # date of the night because some times can just be\n # junk\n not_alerted = True\n for n, tdat in enumerate(rtime):\n if instrument == 'HiPERCAM':\n time, tinfo, tflag = tdat\n expose = 1000000\n for tmid,texp,tiflag in tinfo:\n expose = min(round(texp,3),expose)\n else:\n time, tinfo = tdat[:2]\n tflag = time.good\n expose = round(time.expose,3)\n\n if instrument == 'HiPERCAM' or tflag:\n mjd_start = time.mjd\n tdelta = mjd_start-mjd_ref\n if tdelta > 0 and tdelta < 1.5:\n ts = Time(mjd_start, format=\"mjd\", precision=2)\n ut_start = ts.hms_custom\n n_start = n+1\n if expose >= 0 and expose < 2000:\n break\n elif not_alerted and (tdelta < 0 or tdelta > 1.5):\n # maximum one warning per run\n not_alerted = False\n print(f' Bad time: tdelta = {tdelta} < 0 or > 1.5 on time {n} of {dfile}')\n else:\n ntotal = 0\n raise hcam.HipercamError(f'No good times found in {dfile}')\n\n # Find last good time. First we just go for times near the\n # end of the run. Failing that, we try again from the start,\n # to account for runs with time stamp issues.\n if instrument == 'HiPERCAM':\n nback = 4\n elif rtime.header['MODE'] == 'DRIFT':\n # ultracam or hipercam\n win = rtime.win[0]\n nyu = win.ny*rtime.ybin\n nback = int((1033/nyu + 1) / 2) + 3\n elif rtime.header['MODE'] == 'UDRIFT':\n # ultraspec\n win = rtime.win[0]\n nyu = win.ny*rtime.ybin\n nback = int((1037/nyu + 1) / 2) + 3\n else:\n # non drift mode\n nback = 4\n\n if instrument == 'HiPERCAM':\n ntotal = rtime.ntotal()\n else:\n nbytes = os.stat(dfile + '.dat').st_size\n ntotal = nbytes // rtime.framesize\n\n if instrument != 'HiPERCAM' and ntotal > 20000:\n # this is a risk-reducing strategy in case the end\n # of a long ultracam or ultraspec run is\n # corrupt. Better to look at more than the\n # necessary number of frames if it prevents us\n # from having to wind through the whole lot.\n nback = max(nback, 500)\n\n # next statement basically resets the frame\n # we are on\n nreset = max(1, ntotal - nback)\n rtime.set(nreset)\n\n flast = False\n for n, tdat in enumerate(rtime):\n if instrument == 'HiPERCAM':\n time, tinfo, tflag = tdat\n nexpose = 1000000\n for tmid,texp,tiflag in tinfo:\n nexpose = min(round(texp,3),expose)\n else:\n time, tinfo = tdat[:2]\n tflag = time.good\n nexpose = round(time.expose,3)\n\n if instrument == 'HiPERCAM' or tflag:\n mjd = time.mjd\n if mjd >= mjd_start and mjd < mjd_start + 0.4:\n mjd_end = mjd\n ts = Time(mjd_end, format=\"mjd\", precision=2)\n ut_end = ts.hms_custom\n n_end = nreset + n\n if nexpose < 2000:\n expose = max(expose, nexpose)\n flast = True\n\n if not flast:\n # no good time found near end. There must be\n # one or we wouldn't get to this point, so\n # grind it out the hard way by going through\n # the whole run, which can be slow.\n rtime.set()\n for n, tdat in enumerate(rtime):\n if instrument == 'HiPERCAM':\n time, tinfo, tflag = tdat\n nexpose = 1000000\n for tmid,texp,tiflag in tinfo:\n nexpose = min(round(texp,3),expose)\n else:\n time, tinfo = tdat[:2]\n tflag = time.good\n nexpose = round(time.expose,3)\n\n if tflag:\n mjd = time.mjd\n if mjd >= mjd_start and mjd < mjd_start + 0.4:\n mjd_end = mjd\n ts = Time(mjd_end, format=\"mjd\", precision=2)\n ut_end = ts.hms_custom\n n_end = n + 1\n if nexpose < 2000:\n expose = max(expose, nexpose)\n\n nok = n_end-n_start+1\n if n_end > n_start:\n cadence = round(86400*(mjd_end-mjd_start)/(n_end-n_start),3)\n tdata[run] = [ut_start,mjd_start,ut_end,mjd_end,cadence,expose,nok,ntotal]\n else:\n cadence = 'UNDEF'\n tdata[run] = [ut_start,mjd_start,ut_end,mjd_end,'',expose,nok,ntotal]\n tout.write(f'{run} {ut_start} {mjd_start} {ut_end} {mjd_end} {cadence} {expose} {nok} {ntotal}\\n')\n\n except hcam.ucam.PowerOnOffError:\n # Power on/off\n tdata[run] = ['power-on-off',]\n tout.write(f'{run} power-on-off\\n')\n if full: print(f'{run} was a power-on or -off')\n\n except hcam.HipercamError:\n # No good times\n tdata[run] = ['','','','','','',0,ntotal]\n tout.write(f'{run} UNDEF UNDEF UNDEF UNDEF UNDEF UNDEF 0 {ntotal}\\n')\n if full:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n traceback.print_tb(exc_traceback, limit=1)\n traceback.print_exc()\n print(f'No good times found for {run}; ntotal = {ntotal}')\n\n except:\n # some other failure\n exc_type, exc_value, exc_traceback = sys.exc_info()\n traceback.print_tb(exc_traceback, limit=1)\n traceback.print_exc()\n print(\"Problem on run = \", dfile)\n\n # Load of undefined\n tdata[run] = 8*['']\n tout.write(f'{run} {\" \".join(8*[\"UNDEF\"])}\\n')\n\n if okwrite:\n print('Written timing data to',times)\n\n return tdata",
"def rt_arr_time(self):\n return self._rt_arr_time",
"def RisetimeFinder(X, Y,startIndex,peakIndex,baseline):\n # Channel1Data is from first TOF\n # Channel2Data is from second TOF\n hitAmplitude = Y[peakIndex]\n UpperThreshold = baseline - (.7 * (baseline - hitAmplitude))\n LowerThreshold = baseline - (.3 * (baseline - hitAmplitude))\n riseTimestart = 0\n riseTimeend = 0\n riseIndex = 0\n fallIndex = 0\n diffs = Y[startIndex:peakIndex]-UpperThreshold\n value = np.min(abs(diffs))\n noiserms = np.std(Y[:50])*5\n YStart = Y[startIndex]\n YSign =np.sign(Y[startIndex])\n #print(value,diffs)\n #print(np.where(value == abs(diffs))[0][0])\n riseIndex = int(np.where(value == abs(diffs))[0][0]) + startIndex\n diffs = Y[startIndex:peakIndex]-LowerThreshold\n value = np.min(abs(diffs))\n fallIndex = int(np.where(value == abs(diffs))[0][0]) + startIndex\n riseTimestart = Interpolator(X, Y, riseIndex-1,riseIndex+1,UpperThreshold)\n riseTimeend = Interpolator(X, Y, fallIndex-1,fallIndex+1,LowerThreshold)\n #print(UpperThreshold,LowerThreshold)\n result = dict()\n result['risetime'] = riseTimestart-riseTimeend\n result['starttime'] = riseTimeend\n if riseTimestart < X[startIndex] or riseTimestart > X[EndIndex] or riseTimeend < X[startIndex] or riseTimeend > X[EndIndex]:\n result['risetime']= False\n if riseTimestart - riseTimeend > (X[EndIndex] - X[startIndex]):\n result['risetime']= False\n if riseTimestart - riseTimeend <= 0:\n result['risetime']= False\n if riseIndex == 0 or fallIndex ==0:\n result['risetime']= False\n if YSign > 0:\n if(YStart > baseline + noiserms):\n result['risetime']= False\n if YSign < 0:\n if(YStart < baseline - noiserms):\n result['risetime']= False\n if len(np.unique(np.sign(np.diff(Y[fallIndex:startIndex])))) > 1:\n result['risetime']= False\n\n return result",
"def ConvertTime( self ) :\n \n # modules:\n import logging\n import datetime\n import netCDF4\n import numpy\n \n #\n # Original 'Time' units and description:\n #\n # title = \"Time at Start of Scan (s, UNIX time / POSIX time), number of seconds that have elapsed since midnight Coordinated Universal Time (UTC), 1 January 1970.\"\n # units = \"s\"\n #\n # Create new field 'Datetime' field with units:\n # units = \"Seconds since 1970-01-01 00:00'\n #\n # select:\n varid = self.swaths[self.component]['Geolocation Fields']['Time']\n # values:\n tvalues = varid['data']\n # extract description:\n long_name = varid['long_name'].decode('latin-1')\n # check ...\n key = 'Time at Start of Scan (s, UNIX time / POSIX time), number of seconds that have elapsed since midnight Coordinated Universal Time (UTC),'\n if long_name.startswith(key) :\n # remove leading description:\n time0 = long_name.replace(key,'').replace('.','').strip()\n # extract datetime object:\n t0 = datetime.datetime.strptime(time0,'%d %B %Y')\n # convert:\n var = {}\n var['units' ] = t0.strftime('seconds since %Y-%m-%d %H:%M:%H')\n var['long_name'] = long_name\n if 'mask' in dir(tvalues) :\n values1d = netCDF4.num2date( tvalues.data, var['units'] )\n else :\n values1d = netCDF4.num2date( tvalues , var['units'] )\n #endif\n # alternative:\n # \"Time at Start of Scan (s, TAI93)\"\n elif 'TAI' in long_name :\n # find start:\n i0 = long_name.index('TAI')\n # extract:\n year = int(long_name[i0+3:].replace(')',''))\n # convert to 4-digits if necessary:\n if year < 100 :\n if year > 50 :\n year = 1900 + year\n else :\n year = 2000 + year\n #endif\n #endif\n # reference time:\n t0 = datetime.datetime(year,1,1,0,0,0)\n # convert:\n var = {}\n var['units' ] = t0.strftime('seconds since %Y-%m-%d %H:%M:%H')\n var['long_name'] = long_name\n values1d = netCDF4.num2date( tvalues, var['units'] )\n else :\n self.logger.error( 'could not convert time units \"%s\"' % long_name )\n self.logger.error( 'first value : %f' % tvalues[0] )\n raise Exception\n #endif\n \n # expand to 2D:\n var['data'] = numpy.zeros( (self.ntime,self.np), values1d.dtype )\n for ip in range(self.np) :\n var['data'][:,ip] = values1d\n #endfor\n \n # set dim names:\n var['dimnames'] = ('time','pixel')\n \n # store:\n self.swaths[self.component]['Geolocation Fields']['Datetime'] = var",
"def get_fntime(date_row, hour_row, header):\n #(DT, Hr tuples), which is the finish time column\n #http://www.meteor.wisc.edu/~hopkins/aos100/mos-doc.htm\n #https://mesonet.agron.iastate.edu/mos/fe.phtml\n dates = [m.strip() for m in date_row.split(\"/\")[1:]]\n hours = [dt.strip() for dt in hour_row.split()][1:]\n \n year = header['runtime'].year\n \n finish_times = []\n dt = 0\n first_stopped = 0\n for hour in hours:\n if first_stopped == 0:\n first_stopped = 1\n elif hour == '00':\n dt+=1\n try:\n currdate = dateutil.parser.parse(dates[dt])\n month, day = currdate.month, currdate.day\n if month == 1 and day == 1 and hour == '00':\n year += 1\n except:\n #if dt > 0:\n currdate = dateutil.parser.parse(str(year) + ' ' + dates[dt-1]) + datetime.timedelta(days=1)\n year, month, day = currdate.year, currdate.month, currdate.day\n #else:\n # prevmonth, prevday = dates[dt+1].split()\n # currdate = datetime.datetime(int(year), int(prevmonth), int(prevday)) - datetime.timedelta(days=1)\n # month, day = currdate.month, currdate.day\n \n # half the values are strings, so create full string to parse\n # otherwise would have to cast to string or int\n fntime = f'{year} {month} {day} {hour}'\n finish_times.append(dateutil.parser.parse(fntime))\n #forecast_times.append(int((((finish_times[-1])-(header['runtime'].replace(tzinfo=None))).total_seconds())/3600))\n return finish_times #also finish_times",
"def adjust_image_data(self):\r\n\r\n print('Adjusting image data: ')\r\n\r\n if self.removeFirstSequence: # used to remove the first trial from the sequence\r\n\r\n frames_per_rep = self.nFrames/self.nrepetitions\r\n\r\n self.imageData = self.imageData[frames_per_rep:, :, :]\r\n\r\n self.nFrames = self.imageData.shape[0]\r\n\r\n self.nrepetitions = int(self.nFrames/(self.period * self.framerate))\r\n\r\n self.times = np.arange(0, self.nFrames/self.framerate, 1.0/self.framerate)\r\n\r\n \r\n\r\n # first squeeze the image to 3d if it is 4d\r\n\r\n maxt = np.max(self.times) # find last image time\r\n\r\n sh = self.imageData.shape\r\n\r\n if len(sh) == 4:\r\n\r\n self.imageData = self.imageData.squeeze()\r\n\r\n sh = self.imageData.shape\r\n\r\n dt = np.mean(np.diff(self.times)) # get the mean dt\r\n\r\n n_Periods = int((maxt+dt)/self.period) # how many full periods in the image set - include the first?\r\n\r\n if self.nrepetitions > 0 and self.nrepetitions < n_Periods:\r\n\r\n n_Periods = self.nrepetitions\r\n\r\n n_PtsPerCycle = int(np.floor(self.period/dt)); # estimate image points in a stimulus cycle\r\n\r\n ndt = self.period/n_PtsPerCycle\r\n\r\n self.imageData = self.imageData[range(0, n_Periods*n_PtsPerCycle),:,:] # reduce to only what we need\r\n\r\n print (' Adjusted image info')\r\n\r\n print (\" # Periods: %d Pts/cycle: %d Cycle dt %8.4fs (%8.3fHz) Cycle: %7.4fs\" %(n_Periods, n_PtsPerCycle, ndt, 1.0/ndt, self.period))\r\n\r\n self.print_image_info()",
"def get_hour_offsets(self):\n starttime = self.parameters['startlocaltime']\n stoptime = self.parameters['stoplocaltime']\n timediff = (stoptime - starttime)\n logger.debug(\"Start time: {} | Stop time: {}\".format(starttime, stoptime))\n if timediff > config.TIME_THRESHOLD:\n logger.debug(\"Time delta is {}. This is significantly larger than anticipated\".format(timediff))\n else:\n logger.debug(\"Time delta is {}. Using start time as the global time\".format(timediff))\n\n \"\"\"\n timediff = (stoptime - starttime).total_seconds()\n logger.debug(\"Start time: {} | Stop time: {}\".format(starttime, stoptime))\n #TODO: How do we want to handle large images with huge time differences?\n if timediff > config.TIME_THRESHOLD:\n logger.debug(\"Time delta is {}. This is significantly larger than anticipated\".format(timediff))\n starttime = starttime\n else:\n logger.debug(\"Time delta is {}. Using start time as the global time\".format(timediff))\n \"\"\"\n #Given the image start time, find the nearest index and set to the middle,\n # then find the adjacent two nodes in both directions to get allow a\n # cubic interpolation.\n #image_time = starttime.hour + starttime.minute / 60.0\n # This grabs the hour that is nearest, but hour is circular\n image_time = starttime\n if abs(image_time - 24) < abs(image_time - 23.5):\n image_time -= 24\n mididx, midhour = utils.getnearest(self.times, image_time)\n logger.debug(\"Time is {}. The nearest lookup node is {}\".format(image_time, mididx))\n minidx = mididx - 2\n maxidx = mididx + 2\n\n hourslice = np.arange(minidx, maxidx + 1, dtype=np.int8)\n\n hourslice[hourslice < 0] += 18\n\n if hourslice[-1] >= len(self.times):\n #The hour slice needs to be shifted over the time break\n hourslice[hourslice >= len(self.times)] -= len(self.times)\n logger.debug(\"Using indices {} and start time of {}.\".format(hourslice, image_time))\n return hourslice, image_time",
"def process_one_date(self, date_string):\n metrics_dict = {}\n print(\"Processing date {}\".format(date_string))\n input_location = os.path.join(self.input_location, date_string, \"RAW\")\n for filename in self.list_directory(input_location, self.input_location_type):\n if filename.endswith(\".tif\"):\n name_variable = (filename.split('.'))[1]\n variable_array = cv.imread(self.get_file(os.path.join(input_location,\n filename),\n self.input_location_type),\n cv.IMREAD_ANYDEPTH)\n\n metrics_dict[name_variable] = variable_array.mean()\\\n .astype(np.float64)\n self.save_json(metrics_dict, \"weather_data.json\",\n os.path.join(self.output_location,\n date_string,\n \"JSON\",\"WEATHER\"),\n self.output_location_type)\n return True",
"def get_timings(self):\n exp=lib.is_Exposure_d8(self.hcam,7)*1E-3\n frame_rate=lib.is_SetFrameRate(self.hcam,0x8000)\n return self.AcqTimes(exp,1./frame_rate)",
"def read_iers_bulletin_a(fileID):\n # read contents from input file object\n file_contents = fileID.read().decode('utf8').splitlines()\n\n # parse header text to find time offsets\n # TT-TAI\n TT_TAI = 0\n # TAI-UTC\n TAI_UTC = 0\n # counts the number of lines in the header\n count = 0\n HEADER = False\n # Reading over header text\n while not HEADER:\n # file line at count\n l = file_contents[count]\n # check if line contains time offsets\n if re.search(r'TT\\s\\=\\sTAI',l):\n TT_TAI = np.float64(re.findall(r'(\\d+\\.\\d+)',l).pop())\n if re.search(r'TAI-UTC',l):\n TAI_UTC = np.float64(re.findall(r'=\\s(\\d+\\.\\d+)',l).pop())\n # find line to set HEADER flag to True\n HEADER = bool(re.search(r'COMBINED\\sEARTH\\sORIENTATION\\sPARAMETERS:',l))\n # add 1 to counter\n count += 1\n\n # convert variables to numpy arrays\n MJD = np.zeros((7))\n UT1_UTC = np.zeros((7))\n valid = 0\n # for each day in the week\n for i in range(7):\n try:\n # split numerical instances from data line\n line_contents = file_contents[count+i+4].split()\n # years are not always complete in the bulletin file\n # Modified Julian Day (days since 1858-11-17T00:00:00)\n MJD[i] = np.float64(line_contents[3])\n # difference between UT1 and UTC times\n UT1_UTC[i] = np.float64(line_contents[8])\n except (IndexError,ValueError):\n pass\n else:\n valid += 1\n\n # calculate components for delta time\n # TAI time is ahead of GPS by 19 seconds\n TAI_GPS = 19.0\n # calculate calendar dates from Modified Julian days\n Y,M,D,h,m,s = convert_julian(MJD[:valid]+2400000.5, format='tuple')\n # calculate GPS Time (seconds since 1980-01-06T00:00:00)\n # by converting the Modified Julian days (days since 1858-11-17T00:00:00)\n GPS_Time = convert_delta_time(MJD[:valid]*8.64e4, epoch1=_mjd_epoch,\n epoch2=_gps_epoch, scale=1.0) + TAI_UTC - TAI_GPS\n # number of leap seconds between GPS and UTC\n # this finds the daily correction for weeks with leap seconds\n GPS_UTC = count_leap_seconds(GPS_Time)\n # calculate delta time (TT - UT1) -->\n # (TT-TAI) + (TAI-GPS) + (GPS-UTC) - (UT1-UTC)\n DELTAT = TT_TAI + TAI_GPS + GPS_UTC - UT1_UTC[:valid]\n\n # return dates and delta times\n return (Y,M,D,DELTAT)",
"def data_read(variable):\t\t\r\n\tdef day2datetime(scenario,days):\r\n\t\t\"\"\"\r\n\t\t# convert days from a reference into int datetime \r\n\t\t# do not take leap years into account\r\n\t\t\"\"\"\r\n\t\tdate_int = np.empty((len(days)));date_int[:]=np.nan\r\n\t\tif scenario =='T1970C': start_year =1970\r\n\t\telse: start_year =2010\r\n\t\tstart =(start_year*365)\r\n\t\tith=0\t\r\n\t\tfor iday in days:\r\n\t\t\tmonth_days =np.array([31,28,31,30,31,30,31,31,30,31,30,31])\r\n\t\t\tcalendar_days = np.array([0,31,59,90,120,151,181,212,243,273,304,334,365])\r\n\t\t\ttotal_days = int(iday) + start; \r\n\t\t\tyear = total_days//365; \r\n\t\t\tremainder = total_days%365\r\n\t\t\tif remainder ==0: year=year-1;month=12;day=31\r\n\t\t\telse: \r\n\t\t\t\tmonth = 1+[layer for layer in range(len(calendar_days)) if calendar_days[layer]< remainder and calendar_days[layer+1]>=remainder][0]\r\n\t\t\t\tday = int(remainder - calendar_days[month-1])\r\n\t\t\t\tif day == 0: day = month_days[month-1]\r\n\t\t\tdate_int[ith] = year*10000+month*100+day\r\n\t\t\tith=ith+1\r\n\t\treturn date_int.astype(int)\r\n\t\t\r\n\tdef mon_mean2annual_mean(scenario,time,data):\r\n\t\tannual_mean=np.empty((30,192,288));annual_mean[:]=np.nan\r\n\t\tcalendar_day = np.array([31,28,31,30,31,30,31,31,30,31,30,31])\r\n\t\tif scenario=='T1970RCP':\r\n\t\t\tyear_series = range(2020,2050)\r\n\t\telif scenario=='EdgEne':\r\n\t\t\tyear_series = range(2200,2230)\r\n\t\telif scenario=='Edg70GO':\r\n\t\t\tyear_series = range(2070,2100)\r\n\t\telse:\r\n\t\t\tyear_series = range(2130,2160)\r\n\t\tfor iyear in year_series:\r\n\t\t\t\r\n\t\t\tif (iyear == year_series[0] and time[0]//100 >= year_series[0] *100+1):\r\n\t\t\t\tlayer_b=0\r\n\t\t\telse:\r\n\t\t\t\tlayer_b = [layer for layer in range(len(time)) if time[layer]//100 == iyear*100+1][0] #June01\r\n\t\t\tif (iyear == year_series[-1] and time[-1]//100 <= year_series[-1] *100+12):\r\n\t\t\t\tlayer_e=-2\r\n\t\t\telse:\r\n\t\t\t\tlayer_e = [layer for layer in range(len(time)) if time[layer]//100 == iyear*100+12][0] #August 31\r\n\t\t\tdata_cache = data[layer_b:layer_e+1,:,:]\r\n\t\t\tannual_mean[iyear-year_series[0],:,:] = stats.nanmean(data_cache,axis=0)\r\n\t\treturn annual_mean\r\n\r\n\tdef data_netcdf(scenario,variable):\r\n\t\tinput_path ='/exports/csce/datastore/geos/users/s1667168/CESM_EDGAR/ModelOutput/FullCp/'\r\n\t\tvar_path = input_path+scenario+'/mon/atm/'+scenario+'.atm.mon.'+variable+'.nc'\r\n\t\t# print var_path\r\n\t\tnc_fid = nc4.Dataset(var_path,mode='r')\r\n\t\tlat = nc_fid.variables['lat'][:]\r\n\t\tlon = nc_fid.variables['lon'][:]\r\n\t\tdays = nc_fid.variables['time'][:]; time = day2datetime(scenario,days);#print time\r\n\t\tif variable ==\"VQ\" or variable == \"VT\":\r\n\t\t\tdata = np.nanmean(nc_fid.variables[variable][:,23:30,:,:],axis=1) # 850hpa\r\n\t\telse:\r\n\t\t\tdata = nc_fid.variables[variable][:]#-273.15\r\n\t\tnc_fid.close()\r\n\t\tvar40map = mon_mean2annual_mean(scenario,time,data)\r\n\t\treturn lon,lat,var40map\r\n\t\r\n\tlon,lat,Edg70GO = data_netcdf('Edg70GO',variable)\r\n\t_,_,T1970 = data_netcdf('T1970RCP',variable)\r\n\t_,_,EdgRef = data_netcdf('EdgRef',variable)\r\n\t_,_,Edg70Oz = data_netcdf('Edg70Oz',variable)\r\n\t_,_,EdgEne = data_netcdf('EdgEne',variable)\r\n\t_,_,EdgTech = data_netcdf('EdgTech',variable)\r\n\treturn lon,lat,T1970,Edg70GO,Edg70Oz,EdgRef,EdgEne,EdgTech"
] | [
"0.5989216",
"0.59813",
"0.58474916",
"0.58234465",
"0.5804293",
"0.57660073",
"0.56493163",
"0.5617467",
"0.55724144",
"0.55497277",
"0.54996896",
"0.5426524",
"0.5376058",
"0.52915376",
"0.52908814",
"0.52493185",
"0.5246039",
"0.5241682",
"0.52151155",
"0.5198376",
"0.5192846",
"0.51911634",
"0.51864403",
"0.51504093",
"0.51494837",
"0.5146479",
"0.5122458",
"0.50989795",
"0.5093973",
"0.50771636"
] | 0.6219165 | 0 |
Calculate sensor zenith and azimuth angles. Angles are derived for each pixel depending on the channel and the corresponding ASTER subsensor ("VNIR", "SWIR", "TIR"), as well as on the subsensor geometry and settings. | def sensor_angles(self, channel="1"):
if channel != "3B":
sensor = self.channel2sensor[channel]
else:
sensor = "VNIRB"
# Angular data from ASTER metadata data.
S = float(self.meta["MAPORIENTATIONANGLE"])
FOV = {"VNIR": 6.09, "VNIRB": 5.19, "SWIR": 4.9, "TIR": 4.9}
P = {
"VNIR": float(self.meta["POINTINGANGLE.1"]),
"VNIRB": float(self.meta["POINTINGANGLE.1"]),
"SWIR": float(self.meta["POINTINGANGLE.2"]),
"TIR": float(self.meta["POINTINGANGLE.3"]),
}
# cut overlap area of backward pointing telescope
if channel != "3B":
field = self.read_digitalnumbers(channel)
elif channel == "3B" and self.meta["FLYINGDIRECTION"] == "DE":
field = self.read_digitalnumbers(channel)[400:]
elif channel == "3B" and self.meta["FLYINGDIRECTION"] == "AE":
field = self.read_digitalnumbers(channel)[:400]
# design n field
sidx = np.arange(np.shape(field)[1])
mid0 = sidx[np.isfinite(field[5, :])][[0, -1]].mean()
mid1 = sidx[np.isfinite(field[-5, :])][[0, -1]].mean()
f = interpolate.interp1d(
np.array([5, np.shape(field)[0] - 5]),
np.array([mid0, mid1]),
kind="linear",
fill_value="extrapolate",
)
mids = f(np.arange(np.shape(field)[0]))
# costructing an n-array indexing the pixels symmetric to the center of the
# swath. If pointing angle is zero, the sensor zenith angle is zero in the
# swath center.
n = sidx - mids[:, np.newaxis]
# left and right side of nadir are defined such that the sign follows the
# roll angle sign, which is negative on the right and positive on the left
# side of the sensor in flying direction (!), NOT in projected image. The
# sides therefore depend on the ascending / decending mode defined in the
# meta data.
flyingdir = self.meta["FLYINGDIRECTION"]
if flyingdir is "DE":
n *= -1
swath_widths = np.sum(np.isfinite(field), axis=1)
# average swath width, but exluding possible NaN-scanlines at beginning and
# end of the image.
swath_width = np.mean(swath_widths[swath_widths > 4200])
n_angles = n * FOV[sensor] / swath_width + P[sensor]
azimuth = np.full_like(field, np.nan)
if channel != "3B":
zenith = abs(n_angles)
if flyingdir is "DE":
azimuth[n_angles > 0] = 90 + S
azimuth[n_angles <= 0] = 270 + S
else:
azimuth[n_angles < 0] = 90 + S
azimuth[n_angles >= 0] = 270 + S
else:
h = 705000 # in km above the equator
zenith = np.rad2deg(
np.arctan(
np.sqrt(
(h * np.tan(np.deg2rad(P[sensor])) + 15 * n) ** 2
+ (h * np.tan(np.deg2rad(27.6)) / np.cos(np.deg2rad(P[sensor])))
** 2
)
/ h
)
)
x = np.rad2deg(np.arctan(0.6 / np.tan(np.deg2rad(n_angles))))
if flyingdir is "DE":
azimuth[n_angles > 0] = np.array(90 - x + S)[n_angles > 0]
azimuth[n_angles <= 0] = np.array(270 - x + S)[n_angles <= 0]
else:
azimuth[n_angles < 0] = np.array(90 - x + S)[n_angles < 0]
azimuth[n_angles >= 0] = np.array(270 - x + S)[n_angles >= 0]
zenith[np.isnan(field)] = np.nan
azimuth[np.isnan(field)] = np.nan
return zenith, azimuth | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def azizen(self):\n # x0,y0 array pixel coordinates relative to cx,cy\n# ndy0,ndx0=img.shape\n ndy0=self.ndy0\n ndx0=self.ndx0\n x0,y0=np.meshgrid(np.linspace(0,ndx0-1,ndx0)-self.cx,np.linspace(0,ndy0-1,ndy0)-self.cy)\n r0=np.sqrt(x0**2+y0**2)/self.pr0 # fractional radial distance from 0,0\n# self.roi=np.s_[ystart:ystart+self.ny0,xstart:xstart+self.nx0]\n # why not model the zenith angle dependence with polynomial directly\n # rather than linear interpolation between roots.\n roots=np.zeros(51)\n rr=np.arange(51)/100.0\n for i,ref in enumerate(rr):\n roots[i]=np.real(np.roots([self.c3,0,self.c2,0,self.c1,-ref])[-1])\n theta0 = np.interp(r0/2,rr,roots)\n \n phi0 = np.arctan2(x0,y0) - self.rot ####phi (i.e., azimuth) is reckoned with -pi corresponding to north, increasing clockwise, NOTE: pysolar use sub-standard definition\n phi0 = phi0%(2*np.pi)\n\n #####correction for the tilt of the camera\n k=np.array((np.sin(self.azm),np.cos(self.azm),0))\n a=np.array([np.sin(theta0)*np.cos(phi0),np.sin(theta0)*np.sin(phi0),np.cos(theta0)]); \n a = np.transpose(a,[1,2,0])\n b=np.cos(self.beta)*a + np.sin(self.beta)*np.cross(k,a,axisb=2) \\\n + np.reshape(np.outer(np.dot(a,k),k),(self.ndy0,self.ndx0,3))*(1-np.cos(self.beta))\n theta0=np.arctan(np.sqrt(b[:,:,0]**2+b[:,:,1]**2)/b[:,:,2])\n phi0=np.arctan2(b[:,:,1],b[:,:,0])%(2*np.pi)\n# max_theta *= deg2rad \n# valid0 = (theta0<max_theta) & (theta0>0); \n# theta0[valid0]=np.nan;\n self.theta0,self.phi0=theta0,phi0",
"def _dwd_get_sun_zenith_angles_channel(self):\n LOGGER.info('Retrieve sun zenith angles')\n try:\n self.check_channels(\"SUN_ZEN_CHN\")\n if self[\"SUN_ZEN_CHN\"].data.shape != self.area.shape:\n self._data_holder.channels.remove(self[\"SUN_ZEN_CHN\"])\n raise Exception()\n except:\n if self.area.lons is None or self.area.lats is None:\n self.area.lons, self.area.lats = self.area.get_lonlats()\n sun_zen_chn_data = np.zeros(shape=self.area.lons.shape)\n q = 500\n for start in xrange(0, sun_zen_chn_data.shape[1], q):\n sun_zen_chn_data[\n :, start: start + q] = sza(\n get_first(self.time_slot), self.area.lons[:, start: start + q],\n self.area.lats[:, start: start + q])\n sun_zen_chn = Channel(name=\"SUN_ZEN_CHN\",\n data=sun_zen_chn_data)\n self._data_holder.channels.append(sun_zen_chn)\n\n return self[\"SUN_ZEN_CHN\"]",
"def get_mean_sun_angles(self) -> (float, float):\n # Get MTD XML file\n root, _ = self.read_mtd()\n\n # Open zenith and azimuth angle\n zenith_angle = float(root.findtext(\".//SolarZenith\"))\n azimuth_angle = float(root.findtext(\".//SolarAzimuth\"))\n\n return azimuth_angle, zenith_angle",
"def calculate_angles(self, x, y):\n Oimat = inv(self.Omat)\n Mat = self.pixel_size * inv(self.Dmat) * Oimat\n polar_angles = []\n azimuthal_angles = []\n for i in range(len(x)):\n peak = Oimat * (vec(x[i], y[i]) - self.Cvec)\n v = norm(Mat * peak)\n polar_angle = np.arctan(v / self.distance)\n polar_angles.append(polar_angle)\n azimuthal_angles.append(np.arctan2(-peak[1, 0], peak[2, 0]))\n return (np.array(polar_angles) * degrees,\n np.array(azimuthal_angles) * degrees)",
"def _GetHorizonAnglesLegacy(its_elev, height_cbsd, height_rx, refractivity):\n num_points = int(its_elev[0])\n step = its_elev[1]\n dist = num_points * step\n\n # Find the refractivity at the average terrain height\n start_avg = int(3.0 + 0.1 * num_points)\n end_avg = num_points - start_avg + 6\n zsys = np.mean(its_elev[start_avg-1:end_avg])\n refractivity *= np.exp(-zsys/9460.0)\n\n # Find the ray down-curvature per meter\n gma = 157e-9\n gme = gma*(1.0 - 0.04665 * np.exp(refractivity/179.3))\n\n alt_cbsd = its_elev[2] + height_cbsd\n alt_rx = its_elev[num_points+2] + height_rx\n qc = 0.5 * gme\n q = qc * dist\n # theta0 and theta1 the slopes, dl0 and dl1 the horizon distances\n theta1 = (alt_rx - alt_cbsd) / dist\n theta0 = theta1 - q\n theta1 = -theta1 - q\n dl0 = dist\n dl1 = dist\n\n if num_points >= 2:\n sa = 0.0\n sb = dist\n wq = True\n for i in range(1, num_points):\n sa += step\n sb -= step\n q = its_elev[i+2] - (qc*sa + theta0) * sa - alt_cbsd\n if q > 0.0:\n theta0 += q/sa\n dl0 = sa\n wq = False\n if not wq:\n q = its_elev[i+2] - (qc*sb + theta1) * sb - alt_rx\n if q > 0.0:\n theta1 += q/sb\n dl1 = sb\n\n return (np.arctan(theta0) * 180/np.pi,\n np.arctan(theta1) * 180/np.pi,\n dl0,\n dl1)",
"def fun_azimuth(self):\n\n energy_kev = self.energy_kev.get()\n hkl = self.hkl_magnetic.get()\n hkl = hkl.replace(',', ' ') # remove commas\n hkl = hkl.replace('(', '').replace(')', '') # remove brackets\n hkl = hkl.replace('[', '').replace(']', '') # remove brackets\n hkl = np.fromstring(hkl, sep=' ')\n\n azi = self.azim_zero.get()\n azi = azi.replace(',', ' ') # remove commas\n azi = azi.replace('(', '').replace(')', '') # remove brackets\n azi = azi.replace('[', '').replace(']', '') # remove brackets\n azi = np.fromstring(azi, sep=' ')\n\n pol = self.polval.get()\n if pol == u'\\u03c3-\\u03c3':\n pol = 's-s'\n elif pol == u'\\u03c3-\\u03c0':\n pol = 's-p'\n elif pol == u'\\u03c0-\\u03c3':\n pol = 'p-s'\n else:\n pol = 'p-p'\n\n F0 = self.resF0.get()\n F1 = self.resF1.get()\n F2 = self.resF2.get()\n\n isres = self.isres.get()\n if isres:\n # Resonant scattering\n self.xtl.Plot.simulate_azimuth_resonant(\n hkl,\n energy_kev=energy_kev,\n azim_zero=azi,\n polarisation=pol,\n F0=F0, F1=F1, F2=F2)\n plt.show()\n else:\n # Non-Resonant scattering\n self.xtl.Plot.simulate_azimuth_nonresonant(\n hkl,\n energy_kev=energy_kev,\n azim_zero=azi,\n polarisation=pol)\n plt.show()",
"def optimal_angle_and_tilt(sensors_metadata_clean, latitude, sun_properties, Max_Isol, panel_properties):\n # calculate panel tilt angle (B) for flat roofs (tilt < 5 degrees), slope roofs and walls.\n optimal_angle_flat = calc_optimal_angle(180, latitude, sun_properties.trr_mean) # assume surface azimuth = 180 (N,E), south facing\n sensors_metadata_clean['tilt']= np.vectorize(acos)(sensors_metadata_clean['Zdir']) #surface tilt angle in rad\n sensors_metadata_clean['tilt'] = np.vectorize(degrees)(sensors_metadata_clean['tilt']) #surface tilt angle in degrees\n sensors_metadata_clean['B'] = np.where(sensors_metadata_clean['tilt'] >= 5, sensors_metadata_clean['tilt'],\n degrees(optimal_angle_flat)) # panel tilt angle in degrees\n\n # calculate spacing and surface azimuth of the panels for flat roofs\n module_length = panel_properties['module_length']\n optimal_spacing_flat = calc_optimal_spacing(sun_properties, optimal_angle_flat, module_length)\n sensors_metadata_clean['array_s'] = np.where(sensors_metadata_clean['tilt'] >= 5, 0, optimal_spacing_flat)\n sensors_metadata_clean['surface_azimuth'] = np.vectorize(calc_surface_azimuth)(sensors_metadata_clean['Xdir'],\n sensors_metadata_clean['Ydir'],\n sensors_metadata_clean['B']) # degrees\n\n # calculate the surface area required to install one pv panel on flat roofs with defined tilt angle and array spacing\n if panel_properties['type'] == 'PV':\n module_width = module_length # for PV\n else:\n module_width = panel_properties['module_area']/module_length # for FP, ET\n module_flat_surface_area = module_width * (sensors_metadata_clean.array_s / 2 + module_length * cos(optimal_angle_flat))\n area_per_module = module_width * module_length\n\n # calculate the pv/solar collector module area within the area of each sensor point\n sensors_metadata_clean['area_installed_module'] = np.where(sensors_metadata_clean['tilt'] >= 5, sensors_metadata_clean.AREA_m2,\n area_per_module * (sensors_metadata_clean.AREA_m2 / module_flat_surface_area))\n\n # categorize the sensors by surface_azimuth, B, GB\n result = np.vectorize(calc_categoriesroof)(sensors_metadata_clean.surface_azimuth, sensors_metadata_clean.B,\n sensors_metadata_clean.total_rad_Whm2, Max_Isol)\n sensors_metadata_clean['CATteta_z'] = result[0]\n sensors_metadata_clean['CATB'] = result[1]\n sensors_metadata_clean['CATGB'] = result[2]\n return sensors_metadata_clean",
"def getAxisAndAngleDegres(self):\n theta = numpy.arccos(self.real)\n angle = 360 * theta / numpy.pi\n xyz = self.pure / numpy.sin(theta)\n return xyz, angle",
"def check_angle(self):\n self.find_pixels()\n alpha_theta=np.deg2rad(70)\n alpha_phi=np.deg2rad(70)\n extreme_values=self.compute_extreme_values(alpha_phi, alpha_theta)\n x=np.linspace(extreme_values[0], extreme_values[1], self.number_of_pix[1])\n y=np.linspace(extreme_values[2], extreme_values[3], self.number_of_pix[0])\n phi_0=20\n phi_0=np.deg2rad(phi_0)\n j, diff=self.compute_phi(\"find_orient.png\")\n print \"j=\", j\n print \"diff=\", diff",
"def get_azimuth(self):\n self.degrees = self.azimuth_encoder.get_degrees()\n self.tele_azimuth = self.Calculations.convert_degrees(self.degrees)\n return self.tele_azimuth",
"def calc_surface_azimuth(xdir, ydir, B):\n B = radians(B)\n teta_z = degrees(asin(xdir / sin(B)))\n # set the surface azimuth with on the sing convention (E,N)=(+,+)\n if xdir < 0:\n if ydir <0:\n surface_azimuth = 180 + teta_z # (xdir,ydir) = (-,-)\n else: surface_azimuth = 360 + teta_z # (xdir,ydir) = (-,+)\n elif ydir < 0:\n surface_azimuth = 180 + teta_z # (xdir,ydir) = (+,-)\n else: surface_azimuth = teta_z # (xdir,ydir) = (+,+)\n return surface_azimuth # degree",
"def calculate_angles(self,chunk):\n import math\n import collections\n\n Angles = collections.namedtuple(\"Angles\", \"ev az\")\n x = float(chunk['x'])\n y = float(chunk['y'])\n z = float(chunk['z'])\n ev = round(90 - math.acos(z/math.sqrt(x*x+y*y+z*z))*180/math.pi)\n az = round(math.atan2(y,x)*180/math.pi)\n\n return(Angles(ev, az))",
"def Angles(self, degrees=True):\n\n self.__do_essential_memebers_exist__()\n if self.InferElementalDimension() != 2:\n raise ValueError(\"Angles can be computed only for 2D elements\")\n if self.InferSpatialDimension() != 2:\n raise ValueError(\"Angles can be computed only in 2-dimensional plane\")\n\n nodeperelem = self.InferNumberOfNodesPerLinearElement()\n angles = np.zeros((self.nelem, nodeperelem))\n\n norm = lambda x: np.linalg.norm(x,axis=1)\n\n edge_coords = self.points[self.elements[:,:],:]\n if self.element_type == \"tri\":\n AB = edge_coords[:,1,:] - edge_coords[:,0,:]\n AC = edge_coords[:,2,:] - edge_coords[:,0,:]\n BC = edge_coords[:,2,:] - edge_coords[:,1,:]\n\n angles[:,0] = np.einsum(\"ij,ij->i\",AB,AC) / (norm(AB)*norm(AC))\n angles[:,1] = np.einsum(\"ij,ij->i\",AC,BC) / (norm(AC)*norm(BC))\n angles[:,2] = np.einsum(\"ij,ij->i\",BC,-AB)/ (norm(BC)*norm(AB))\n angles = np.arccos(angles)\n\n elif self.element_type == \"quad\":\n AB = edge_coords[:,1,:] - edge_coords[:,0,:]\n BC = edge_coords[:,2,:] - edge_coords[:,1,:]\n CD = edge_coords[:,3,:] - edge_coords[:,2,:]\n DA = edge_coords[:,0,:] - edge_coords[:,3,:]\n\n angles[:,0] = np.einsum(\"ij,ij->i\",AB,BC) / (norm(AB)*norm(BC))\n angles[:,1] = np.einsum(\"ij,ij->i\",BC,CD) / (norm(BC)*norm(CD))\n angles[:,2] = np.einsum(\"ij,ij->i\",CD,DA) / (norm(CD)*norm(DA))\n angles[:,3] = np.einsum(\"ij,ij->i\",DA,-AB)/ (norm(DA)*norm(AB))\n angles = np.arccos(angles)\n\n if degrees:\n angles *= 180/np.pi\n\n return angles",
"def angle(z):",
"def get_internal_angles(self):\n\n angles = []\n\n for elx, elz in zip(self.grid['x'], self.grid['z']):\n el_angles = []\n xy = np.vstack((elx, elz))\n for i in range(0, elx.size):\n i1 = (i - 1) % elx.size\n i2 = (i + 1) % elx.size\n\n a = (xy[:, i] - xy[:, i1])\n b = (xy[:, i2] - xy[:, i])\n # note that nodes are ordered counter-clockwise!\n angle = np.pi - np.arctan2(\n a[0] * b[1] - a[1] * b[0],\n a[0] * b[0] + a[1] * b[1]\n )\n el_angles.append(angle * 180 / np.pi)\n angles.append(el_angles)\n return np.array(angles)",
"def _calc_azel(cache, name, ant):\n real_sensor = '%s_pos_actual_scan_%s' % \\\n (ant, 'azim' if name.endswith('az') else 'elev')\n cache[name] = sensor_data = katpoint.deg2rad(cache.get(real_sensor))\n return sensor_data",
"def getAngles(self):\n try:\n return self._angleList\n except AttributeError:\n pass\n forceConstant=self._raw_data[\"ANGLE_FORCE_CONSTANT\"]\n angleEquil=self._raw_data[\"ANGLE_EQUIL_VALUE\"]\n anglePointers = self._raw_data[\"ANGLES_INC_HYDROGEN\"] \\\n +self._raw_data[\"ANGLES_WITHOUT_HYDROGEN\"]\n self._angleList=[]\n forceConstConversionFactor = (units.kilocalorie_per_mole/(units.radian*units.radian)).conversion_factor_to(units.kilojoule_per_mole/(units.radian*units.radian))\n for ii in range(0,len(anglePointers),4):\n if int(anglePointers[ii])<0 or \\\n int(anglePointers[ii+1])<0 or \\\n int(anglePointers[ii+2])<0:\n raise Exception(\"Found negative angle atom pointers %s\"\n % ((anglePointers[ii],\n anglePointers[ii+1],\n anglePointers[ii+2]),))\n iType=int(anglePointers[ii+3])-1\n self._angleList.append((int(anglePointers[ii])//3,\n int(anglePointers[ii+1])//3,\n int(anglePointers[ii+2])//3,\n float(forceConstant[iType])*forceConstConversionFactor,\n float(angleEquil[iType])))\n return self._angleList",
"def get_odometry(self):\n acceleration = self.gyro.getValues()\n angles = self.imu.getRollPitchYaw()\n position = self.gps.getValues()\n\n compass = self.compass.getValues()\n north_deg = np.arctan2(compass[0], compass[1])\n north_deg = (north_deg - 1.5708) / np.pi * 180\n\n if north_deg < 0.:\n north_deg += 360.\n\n return acceleration, angles, position, north_deg",
"def read_image_and_angle(root_path, data, camera, index):\n image_path = os.path.join(root_path,\n data[cameras[camera]].values[index].strip())\n image = plt.image.imread(image_path)\n angle = data.steering.values[index] + cameras_correction[camera]\n\n return image, angle",
"def do_azangle(self):\n angle_1, angle_2 = cbp.potentiometer.main()\n current_angle = angle_2\n #print(current_angle)\n self.azangle = current_angle\n return current_angle",
"def areas(self):\n\n height_delta = (np.cos(self.polar_corners[:-1, :-1]) - np.cos(self.polar_corners[:-1, 1:]))\n azimuth_delta = (self.azimuthal_corners[1:, 1:] - self.azimuthal_corners[:-1, 1:])\n\n return height_delta * azimuth_delta",
"def getAngles(self) -> tuple:\n return self.getHeading(), self.getPitch(), self.getRoll()",
"def sensor_angles(self) -> np.ndarray:\n return self._sensor_angles",
"def nfw_physical2angle_fromNFWparams(self, rhos, rs, z):\n\n D_d = self.cosmo.D_A_z(z)\n Rs_angle = rs / D_d / self.cosmo.arcsec # Rs in arcsec\n theta_Rs = rhos * (4 * rs ** 2 * (1 + numpy.log(1. / 2.)))\n eps_crit = self.get_sigma_crit_lensing(z, self.z_source)\n\n return Rs_angle, theta_Rs / eps_crit / D_d / self.cosmo.arcsec",
"def calc(self,index, counter_values):\n try:\n angles = self.ik220_dev.read_attribute('Angles').value\n if index == 9:\n return sum(angles[:3])/3.0 # Excluded channel 4 of grating pitch encoder because of problems of Homing in the last header of the RON grating encoder.\n elif index == 10:\n return sum(angles[4:6])/2.0 # Modified from 4 channels to 2 channels because of problems of Homing in the 2 last headers of the RON mirror3 encoder.\n else:\n return angles[index - 1]\n except:\n return 1e-100",
"def getAzimuthAngle(self):\n return self._azimuth",
"def angles(self,compass=0,vertical=0,roll=0):\n self.matrix = makeMatrix(compass,vertical,roll)",
"def _calc_solar_from_clouds_and_angle(hr, ds_path):\n # Solar radiation [W/m^2] incident on top of atmosphere\n Q_o = 1368.0\n # Cloud model based on Dobson and Smith, table 5\n # SEA -- May 2010 : redid the cloud parametrization based on UBC\n # Solar data (/ocean/shared/SoG/met/solar/) fitting Q to cos_Z\n # (not Q/cos_Z as Kate did). Allen and Wolfe (2013). (0) no\n # clouds, (1) 1/10 cloud fraction (10) 100% clouds. Four sig\n # figs are what comes out of matlab but standard deviations are\n # 40W/m2 for low cloud fraction to 120 W/m2 for 6-9 cloud\n # fraction to 85 W/m2 for completely cloudy.\n cloud_consts = SimpleNamespace(\n A=numpy.array(\n [\n 0.6337,\n 0.6149,\n 0.5861,\n 0.5512,\n 0.5002,\n 0.4649,\n 0.4225,\n 0.3669,\n 0.2468,\n 0.1981,\n 0.0841,\n ]\n ),\n B=numpy.array(\n [\n 0.1959,\n 0.2119,\n 0.2400,\n 0.2859,\n 0.3192,\n 0.3356,\n 0.3339,\n 0.3490,\n 0.4427,\n 0.3116,\n 0.2283,\n ]\n ),\n )\n # Local standard time\n ## WARNING: .to(\"PST\") may be fragile and incorrect for summer-time dates\n lst = hr.to(\"PST\")\n # day_time is in seconds, LST\n day_time = (lst - lst.floor(\"day\")).seconds\n # hour of day as degrees from noon\n hour = (day_time / 3600 - 12) * 15\n # day is year-day\n day = (lst - lst.floor(\"year\")).days\n # solar declination [radians]\n declination = (\n 23.45 * numpy.pi / 180 * numpy.sin((284 + day) / 365.25 * 2 * numpy.pi)\n )\n # Latitude of approximate centre of model domain in radians\n lat = numpy.pi * 50 / 180\n # solar elevation\n elev_sin = numpy.sin(declination) * numpy.sin(lat)\n elev_cos = numpy.cos(declination) * numpy.cos(lat)\n cos_Z = elev_sin + elev_cos * numpy.cos(numpy.pi / 180 * hour)\n # cos of -hour_angle in radians\n hour_angle = numpy.tan(lat) * numpy.tan(declination)\n # assume we are south of the Arctic Circle\n day_length = numpy.arccos(-hour_angle) / 15 * 2 * 180 / numpy.pi\n sunrise = 12 - 0.5 * day_length # hours\n sunset = 12 + 0.5 * day_length # hours\n Qso = Q_o * (1 + 0.033 * numpy.cos(day / 365.25 * 2 * numpy.pi))\n with xarray.open_dataset(ds_path) as ds:\n cf_value = ds.percentcloud * 10\n fcf = numpy.floor(cf_value).astype(int) # integer below cf value\n fcf = xarray.where(fcf == 10, 9, fcf).data\n ccf = fcf + 1 # integer above cf value\n if (sunrise > day_time / 3600) or (day_time / 3600 > sunset):\n # nighttime\n return xarray.zeros_like(ds.percentcloud)\n return (\n Qso\n * (\n cloud_consts.A[fcf] * (ccf - cf_value)\n + cloud_consts.A[ccf] * (cf_value - fcf)\n + (\n cloud_consts.B[fcf] * (ccf - cf_value)\n + cloud_consts.B[ccf] * (cf_value - fcf)\n )\n * cos_Z\n )\n * cos_Z\n )",
"def calculate_orbiting_angle(orbiting_center, raft):\n\n # note the negative sign before the first component, the y component\n # it is to make the orbiting angle in a right-handed coordiante.\n angle = np.arctan2(-(raft[1] - orbiting_center[1]), (raft[0] - orbiting_center[0])) * 180 / np.pi\n\n return angle",
"def getTiltAnglesFromTiltSeries(self, TiltSeries_):\n from math import sin, cos, pi\n\n if len(TiltSeries_._projIndices) != self._ntilt:\n print(\"Houston: We have a problem!\")\n # initialize alignment in seperate array - easier for optimization\n # sin and cos\n self._tiltAngles = numpy.array(self._ntilt * [0.])\n self._cTilt = numpy.array(self._ntilt * [0.])\n self._sTilt = numpy.array(self._ntilt * [0.])\n for (kk, proj) in enumerate(TiltSeries_._ProjectionList._list):\n the = proj.getTiltAngle()\n self._tiltAngles[kk] = the\n self._sTilt[kk] = sin(the / 180. * pi)\n self._cTilt[kk] = cos(the / 180. * pi)\n return self._tiltAngles"
] | [
"0.64948094",
"0.61391693",
"0.6111236",
"0.5870285",
"0.58365667",
"0.58314174",
"0.5796266",
"0.5782998",
"0.57819575",
"0.57208097",
"0.56575197",
"0.56436014",
"0.5569998",
"0.5560468",
"0.55492103",
"0.55328006",
"0.5520764",
"0.5502953",
"0.5488787",
"0.5469046",
"0.5459621",
"0.5443421",
"0.5443419",
"0.54431415",
"0.5418043",
"0.54125035",
"0.54093075",
"0.5375867",
"0.5375745",
"0.5353975"
] | 0.73898125 | 0 |
Moist adiabatic lapse rate in [K/km]. | def lapserate_moist_adiabate():
return 6.5 | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def lam(freq):\n return C / freq",
"def lam(E):\n return (12398.4/E)*1e-10",
"def acc_rate(L_acc, R, M):\n mdot = 1.25*L_acc*u.W*R*u.R_sun/(G*M*u.M_sun)\n mdot = mdot.decompose().to(u.M_sun/u.yr)\n return(mdot/(u.M_sun/u.yr))",
"def lapse(self):\n pass",
"def lapserate(t, z, sigma, lat):\n import numpy as np\n dT = np.zeros((np.ma.size(sigma), np.ma.size(lat)))\n dz = np.zeros((np.ma.size(sigma), np.ma.size(lat)))\n for i in range(np.ma.size(sigma, axis=0)-1):\n dT[i, :] = t[i+1, :] - t[i, :]\n for i in range(np.ma.size(sigma, axis=0)-1):\n dz[i, :] = z[i+1, :] - z[i, :]\n lapse = -1000 * dT[0:-1] / dz[0:-1]\n # zonalplot(lapse, sigma[0:-1], lat, 'Lapse rate')\n return lapse",
"def lapserate(t, z, sigma, lat):\n import numpy as np\n dT = np.zeros((np.ma.size(sigma), np.ma.size(lat)))\n dz = np.zeros((np.ma.size(sigma), np.ma.size(lat)))\n for i in range(np.ma.size(sigma, axis=0)-1):\n dT[i, :] = t[i+1, :] - t[i, :]\n for i in range(np.ma.size(sigma, axis=0)-1):\n dz[i, :] = z[i+1, :] - z[i, :]\n lapse = -1000 * dT[0:-1] / dz[0:-1]\n # zonalplot(lapse, sigma[0:-1], lat, 'Lapse rate')\n return lapse",
"def glycolysis_rate_cal (self) :\n x = self.mitochondria.get_atp()\n y = self.mitochondria.get_adp()\n a = self.atp\n b = self.adp\n self.adp_to_atp(self.mitochondria.atp_translocase(math.ceil((x*b - a*y)/(a+b+x+y))))\n if a<1 :\n return\n else :\n self.set_glycolysis(int(5*b/a))",
"def M(latitude):\n return a*(1.0-e2)/pow((1.0-e2)*pow(math.sin(latitude),2.0),3.0/2.0);",
"def Klaiber_Rate(Uion,Eau):\n\n\treturn Klaiber_Rate_Avg(Uion,Eau)/Cycle_Averaging_Factor(Uion,Eau)",
"def n300(lam):\n return 1e-8 * ( 8060.51 + 2480990/(132.274 - lam**(-2)) + 17455.7/(39.32957 - lam**(-2))) + 1.",
"def molar_mass_dry_air():\n return 28.9647",
"def lamg(freq, w):\n la = lam(freq)\n return la / _np.sqrt(1.0 - (la / (2 * w)) ** 2) # wavelength in WG-62 waveguide",
"def maclaurin_ln(value,k):\n \n global first_value \n first_value = 0.0\n \n #attempt to Approximate ln(1+x) for a given value\n try:\n \n error(value)\n for item in xrange(1,k,2):\n next_value =(value**item)/float(item)\n first_value += next_value\n \n for item in xrange(2,k,2):\n next_value = -1*(value**item)/float(item)\n first_value += next_value\n \n return first_value\n\n #Raise TypeError if input is not within\n #the interval of convergence\n except TypeError,exception:\n print exception",
"def fp_from_milk(daily_L_milk):\n milk = kg_to_tonnes(daily_to_annual(daily_L_milk*267.7777)/1000)\n return milk",
"def abbott_elec():\n per_kwh = 0.08 # [$/kWh]\n return per_kwh",
"def lamda(Ei):\n Ej=Ei*1.6021*10**-22\n h_js=6.626*10**-34\n m_kg=1.674929*10**-27\n lam=h_js/np.sqrt(2*Ej*m_kg)\n return (lam)",
"def test_moist_lapse_scalar():\n temp = moist_lapse(np.array([800.]) * units.mbar, 19.85 * units.degC, 1000. * units.mbar)\n assert_almost_equal(temp, 284.64 * units.kelvin, 2)",
"def dloglam(self):\n # This number was determined using the resolution and sampling quoted on the FIRE website\n R = 6000.0 * 2.7\n dloglam = 1.0 / R / np.log(10.0)\n return dloglam",
"def hz2mel(hz):\n return 2595 * pylab.log10(1+hz/700.0)",
"def Lam(self):\n return self._properties['Lam']",
"def estimate_arpu(x):\n arpu = 0\n if x['mean_luminosity_km2'] > 5:\n # #10 year time horizon\n # for i in range(0, 10):\n # #discounted_arpu = (arpu*months) / (1 + discount_rate) ** year\n # arpu += (\n # (20*12) / (1 + 0.03) ** i\n # )\n return 20 * 12 * 10#arpu\n elif x['mean_luminosity_km2'] > 1:\n # for i in range(0, 10):\n # #discounted_arpu = (arpu*months) / (1 + discount_rate) ** year\n # arpu += (\n # (5*12) / (1 + 0.03) ** i\n # )\n return 5 * 12 * 10#arpu\n else:\n # for i in range(0, 10):\n # #discounted_arpu = (arpu*months) / (1 + discount_rate) ** year\n # arpu += (\n # (2*12) / (1 + 0.03) ** i\n # )\n return 2 * 12 * 10#arpu",
"def sma(self) -> float:\n return self._sma",
"def hz2mel(hz):\r\n return 2595 * np.log10(1+hz/700.0)",
"def hz2mel(f):\n return 1127.01048 * np.log(f/700 +1)",
"def LL_Rate(Uion,E):\n\treturn (4.0/E) * ((2*Uion)**2.5) * np.exp(-(2.0/3.0)*((2*Uion)**1.5)/E)",
"def hz2mel(hz):\n return 2595 * np.log10(1+hz/700.)",
"def hz2mel(hz):\n\treturn 2595 * numpy.log10(1 + hz / 700.0)",
"def hz2mel(hz):\n return 1127 * numpy.log(1+hz/700.0)",
"def get_rate(line_flux, d, t, R, M):\n l_line = line_lum(line_flux,d)\n l_acc = accr_lum(l_line, t)\n mdot = acc_rate(l_acc, R, M)\n \n return mdot",
"def length_vs_rate_2(Lmax=200, Lmin=102.4, p=75, fmax=1e12, p1=database['K+'],\r\n p2=database['pi+'], p3=database['p+'], E=1e6, n=20,\r\n ng=50, nl=50, nf=100, delta_p=1.6e-2, just_pi=False,\r\n set_freq=5.7e9, count=True):\r\n if set_freq == None:\r\n print('Estimated time: {0}'.format(timing(n*ng*nl*nf*3.84e-05)))\r\n else:\r\n print('Estimated time: {0}'.format(timing(n*ng*nl*3.84e-05)))\r\n i = 0\r\n while i < 1e7:\r\n i += 1\r\n start = time.time()\r\n L_range = np.linspace(Lmin, Lmax, n)\r\n opt_gap, opt_freq, opt_cav, opt_disp, rate = [], [], [], [], []\r\n for L in L_range:\r\n if count == True:\r\n print(f'L={L}')\r\n opt = cavity_gap_comp(L_t=L-22.8, p=p, fmax=fmax, p1=p1, p2=p2, p3=p3,\r\n E=E, plot=False, delta_p=delta_p, n=ng, nf=nf,\r\n nl=nl, just_pi=just_pi, set_freq=set_freq,\r\n count=count)\r\n opt_freq.append(opt[0])\r\n opt_gap.append(opt[1])\r\n opt_cav.append(opt[2])\r\n opt_disp.append(opt[3])\r\n rate.append(decay_rate(L, p1, p)*1e-6)\r\n opt_freq, opt_disp, rate = np.array(opt_freq), np.array(opt_disp), np.array(rate)\r\n# ratio = (opt_disp*rate)/(opt_freq*L)\r\n# ratio *= (np.max(opt_freq)-np.min(opt_freq))/(np.max(ratio)-np.min(ratio))\r\n# ratio += ((np.min(opt_freq))-np.min(ratio))\r\n fig = plt.figure(figsize=[14, 4])\r\n host = fig.add_subplot(1, 1, 1)\r\n fig.subplots_adjust(right=0.75)\r\n par1 = host.twinx()\r\n# par2 = host.twinx()\r\n# par2.spines['right'].set_position(('axes', 1.2))\r\n# make_patch_spines_invisible(par2)\r\n# par2.spines['right'].set_visible(True) \r\n p1, = host.plot(L_range, rate, 'r', alpha=0.8, lw=2, label='decay rate in decay region')\r\n p2, = par1.plot(L_range, opt_disp, 'b', alpha=0.8, lw=2, label='min disp')\r\n# p3, = par2.plot(L_range, opt_freq, 'b', alpha=0.8, lw=2, label='frequency')\r\n# p4, = par2.plot(L_range, ratio, 'g', alpha=0.8, lw=2, label='ratio')\r\n host.set_xlim(Lmin, Lmax)\r\n host.set_xlabel('Distance between Target and Decay Region / m', fontsize=15)\r\n host.set_ylabel('Decay Rate in Decay Region / MHz', fontsize=15)\r\n par1.set_ylabel('Minimum Displacement / mm', fontsize=15)\r\n# par2.set_ylabel('Frequency / Hz', fontsize=15)\r\n host.yaxis.label.set_color(p1.get_color())\r\n par1.yaxis.label.set_color(p2.get_color())\r\n# par2.yaxis.label.set_color(p3.get_color())\r\n host.tick_params(axis='y', colors=p1.get_color())\r\n par1.tick_params(axis='y', colors=p2.get_color())\r\n# par2.tick_params(axis='y', colors=p3.get_color())\r\n# lines = [p1, p2, p3, p4]\r\n# lines = [p1, p2]\r\n# host.legend(lines, [l.get_label() for l in lines], loc=[0.45, 0.8], fontsize=20)\r\n host.minorticks_on()\r\n par1.minorticks_on()\r\n host.set_ylim(0)\r\n par1.set_ylim(0)\r\n host.grid()\r\n host_yticks = np.arange(0, int(np.max(rate))+2, 1)\r\n par1_yticks = np.arange(0, (int(np.max(opt_disp)/100)+1)*100, 100)\r\n host.set_yticks(host_yticks)\r\n host.set_yticklabels(host_yticks)\r\n par1.set_yticks(par1_yticks)\r\n par1.set_yticklabels(par1_yticks)\r\n host.set_title(r'Unwanted particle displacement and observed $K^+$'+' decay rate\\nas a function of target distance', fontsize=15)\r\n plt.show()\r\n fig.savefig('Length_vs_Rate_75.pdf', bbox_inches='tight')\r\n index = np.argmax(opt_disp)\r\n# index = np.argmax(ratio)\r\n print(f'{timing(time.time()-start)}')\r\n return [opt_disp[index], L_range[index], opt_gap[index], opt_cav[index], opt_freq[index], rate[index]]"
] | [
"0.67962",
"0.65155506",
"0.633966",
"0.63099146",
"0.6259203",
"0.6259203",
"0.61408263",
"0.60732925",
"0.6028457",
"0.60240525",
"0.60038674",
"0.59975666",
"0.596127",
"0.58910197",
"0.5885583",
"0.5871205",
"0.58628464",
"0.5851471",
"0.58435106",
"0.581123",
"0.579676",
"0.5792142",
"0.5789073",
"0.5773548",
"0.57144326",
"0.5702221",
"0.5684961",
"0.5674683",
"0.56726956",
"0.56458926"
] | 0.716511 | 0 |
Translate geocentric to geodetic latitudes. | def geocentric2geodetic(latitude):
return np.rad2deg(np.arctan(1.0067395 * np.tan(np.deg2rad(latitude)))) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def cr2lonlat_for_geotif(path):\n old_cs, new_cs, gta, local_vars = _create_xform(path)\n transform = osr.CoordinateTransformation(old_cs, new_cs)\n\n def composite(c, r):\n \"\"\"xform from (c, r) to (lon, lat)\"\"\"\n x, y = gta * (c, r)\n lat, lon = transform.TransformPoint(x, y)[:2]\n if not -90 <= lat <= 90:\n raise ValueError('illegal lat value, did you switch coordinates')\n return lon, lat\n \n return composite",
"def lat_lons(self):",
"def lonlat2cr_for_geotif(path):\n old_cs, new_cs, gta, local_vars = _create_xform(path)\n transform = osr.CoordinateTransformation(new_cs, old_cs)\n\n def composite(lon, lat):\n \"\"\"xform from (lon, lat) to (c, r)\"\"\"\n if not -90 <= lat <= 90:\n raise ValueError('illegal lat value, did you switch coordinates')\n return (~gta * transform.TransformPoint(lat, lon)[:2])\n \n return composite",
"def _getlats(self):\n lats = 90. - np.degrees(self.zeros)\n return lats",
"def geo_transform(self):\n pass",
"def get_latlon():\n\t\n iss.compute() # Get the lat/long values from ephem\n long_value = [float(i) for i in str(iss.sublong).split(\":\")]\n if long_value[0] < 0:\n long_value[0] = abs(long_value[0])\n cam.exif_tags['GPS.GPSLongitudeRef'] = \"W\"\n else:\n cam.exif_tags['GPS.GPSLongitudeRef'] = \"E\"\n cam.exif_tags['GPS.GPSLongitude'] = '%d/1,%d/1,%d/10' % (long_value[0], long_value[1], long_value[2]*10)\n lat_value = [float(i) for i in str(iss.sublat).split(\":\")]\n if lat_value[0] < 0:\n lat_value[0] = abs(lat_value[0])\n cam.exif_tags['GPS.GPSLatitudeRef'] = \"S\"\n else:\n cam.exif_tags['GPS.GPSLatitudeRef'] = \"N\"\n cam.exif_tags['GPS.GPSLatitude'] = '%d/1,%d/1,%d/10' % (lat_value[0], lat_value[1], lat_value[2]*10)\n return (iss.sublat / degree, iss.sublong / degree)",
"def latitude(self, lat):\n data = float(lat[1:])\n if lat[0] == \"N\":\n return data\n else:\n return -data",
"def convert(self, lat, lon):\r\n a = self.a\r\n b = self.b\r\n long0 = self.long0\r\n k0 = self.k0\r\n dx = self.dx\r\n\r\n e = (1 - b ** 2 / a ** 2) ** 0.5\r\n e2 = e ** 2 / (1 - e ** 2)\r\n n = (a - b) / (a + b)\r\n nu = a / (1 - (e ** 2) * (sin(lat) ** 2)) ** 0.5\r\n p = lon - long0\r\n\r\n A = a * (1 - n + (5 / 4.0) * (n ** 2 - n ** 3) + (81 / 64.0)*(n ** 4 - n ** 5))\r\n B = (3 * a * n / 2.0) * (1 - n + (7 / 8.0) * (n ** 2 - n ** 3) + (55 / 64.0) * (n ** 4 - n ** 5))\r\n C = (15 * a * (n ** 2) / 16.0) * (1 - n + (3 / 4.0) * (n ** 2 - n ** 3))\r\n D = (35 * a * (n ** 3) / 48.0) * (1 - n + (11 / 16.0) * (n ** 2 - n ** 3))\r\n E = (315 * a * (n ** 4) / 51.0) * (1 - n)\r\n\r\n S = A * lat - B * sin(2 * lat) + C * sin(4 * lat) - D * sin(6 * lat) + E * sin(8 * lat)\r\n\r\n K1 = S * k0\r\n K2 = k0 * nu * sin(2 * lat)/4.0\r\n K3 = (k0 * nu * sin(lat) * (cos(lat) ** 3) / 24.0) * \\\r\n (5 - tan(lat) ** 2 + 9 * e2 * (cos(lat) ** 2) + 4 * (e2 ** 2) * (cos(lat) ** 4))\r\n\r\n y = K1 + K2 * (p ** 2) + K3 * (p ** 4)\r\n\r\n K4 = k0 * nu * cos(lat)\r\n K5 = (k0 * nu * (cos(lat) ** 3) / 6.0) * (1 - tan(lat) ** 2 + e2 * (cos(lat) ** 2))\r\n\r\n x = K4 * p + K5 * (p ** 3) + dx\r\n return x, y",
"def getLngLat(self):\n lat = None\n lng = None\n exif_data = self.get_exif_data()\n if \"GPS\" in exif_data:\n gps_data = exif_data[\"GPS\"]\n gps_latitude = self.get_if_exist(\n gps_data, piexif.GPSIFD.GPSLatitude)\n gps_latitude_ref = self.get_if_exist(\n gps_data, piexif.GPSIFD.GPSLatitudeRef)\n gps_longitude = self.get_if_exist(\n gps_data, piexif.GPSIFD.GPSLongitude)\n gps_longitude_ref = self.get_if_exist(\n gps_data, piexif.GPSIFD.GPSLongitudeRef)\n\t\t\t\t# \\ means backward slash which is used to repersent white space\n if gps_latitude and gps_latitude_ref \\\n and gps_longitude and gps_longitude_ref:\n gps_latitude_ref = gps_latitude_ref.decode(\"utf-8\")\n gps_longitude_ref = gps_longitude_ref.decode(\"utf-8\")\n lat = self.convert_to_degress(gps_latitude)\n if gps_latitude_ref != 'N':\n lat = 0 - lat\n lng = self.convert_to_degress(gps_longitude)\n if gps_longitude_ref != 'E':\n lng = 0 - lng\n return lat, lng",
"def get_lats(self, variables):\n\n return self._get_variable(variables, self.LATS_VARIABLE)",
"def latlong_to_cartsian():\n source = pyproj.CRS.from_epsg(4326) # WGS84\n destination = pyproj.CRS.from_epsg(8059) # GDA2020 / SA Lambert\n return pyproj.Transformer.from_crs(source, destination).transform",
"def g0(lat):\n return (980.6160 * (1. - 0.0026372 * np.cos(2*lat*np.pi/180.)\n + 0.0000059 * np.cos(2*lat*np.pi/180.)**2))",
"def calculate_latitude(source_lat, distance, heading):\n return math.asin(math.sin(source_lat)*math.cos(distance) + \\\n math.cos(source_lat)*math.sin(distance)*math.cos(heading))",
"def row_to_lat(self, row):\n return self.max_absolute_lat - row * self.lat_step",
"def latToTheta(lat):\n return (90.0 - lat) * (np.pi/180.0)",
"def project(self, (lng, lat)):\n x = lng * DEG_TO_RAD\n lat = max(min(MAX_LATITUDE, lat), -MAX_LATITUDE)\n y = lat * DEG_TO_RAD\n y = math.log(math.tan((math.pi / 4) + (y / 2)))\n return (x*EARTH_RADIUS, y*EARTH_RADIUS)",
"def _get_latitude(self, latitude, hemisphere):\n if not isinstance(latitude, float):\n latitude = float(latitude)\n if hemisphere.lower() == \"n\":\n return latitude\n if hemisphere.lower() == \"s\":\n return -1 * latitude",
"def lat_lng(row):\r\n lat = row[\"latitude\"]\r\n lng = row[\"longitude\"]\r\n n = int(lat/GRANULARITY)\r\n nlat_start = n * GRANULARITY\r\n nlat_end = nlat_start + GRANULARITY\r\n nlg=int(lng/GRANULARITY)\r\n nlng_start = nlg * GRANULARITY\r\n nlng_end = nlng_start + GRANULARITY\r\n latlng=[(nlat_start,nlng_start), (nlat_start,nlng_end), (nlat_end,nlng_end), (nlat_end,nlng_start)]\r\n return latlng",
"def cartesian2Geo(julian_date, x, y, z):\n\n\n # Calculate LLA\n lat, r_LST, ele = ecef2LatLonAlt(x, y, z)\n\n # Calculate proper longitude from the given JD\n lon, _ = LST2LongitudeEast(julian_date, np.degrees(r_LST))\n\n # Convert longitude to radians\n lon = np.radians(lon)\n\n\n return np.degrees(lat), np.degrees(lon), ele",
"def cartesian_to_geographical(coordinate_triples):\n if len(coordinate_triples.shape) == 1:\n x = coordinate_triples[0]\n y = coordinate_triples[1]\n z = coordinate_triples[2]\n elif len(coordinate_triples.shape) == 2:\n assert coordinate_triples.shape[1] == 3\n x = coordinate_triples[:, 0]\n y = coordinate_triples[:, 1]\n z = coordinate_triples[:, 2]\n radius = np.sqrt(x**2 + y**2 + z**2)\n longitudes = np.arctan2(y, x)\n latitudes = np.arcsin(z/radius)\n return (latitudes, longitudes)",
"def desiredENU2geo(self, x_L, y_L, z):\n\t\tx = cos(self.local_rot)*x_L - sin(self.local_rot)*y_L\n\t\ty = sin(self.local_rot)*x_L + cos(self.local_rot)*y_L\n\n\t\tlat0 = self.origin[0]\n\t\tlon0 = self.origin[1]\n\n\t\tlat, lon, alt = pm.enu2geodetic(x, y, z, lat0, lon0, self.h0)\n\t\treturn lat, lon, alt",
"def get_latitude0(self):\n return self.B",
"def geodetic_to_grid(self, latitude, longitude):\n\n φ = math.radians(latitude)\n λ = math.radians(longitude)\n\n φ_star = φ - math.sin(φ) * math.cos(φ) * (self.A +\n self.B * math.sin(φ) ** 2 +\n self.C * math.sin(φ) ** 4 +\n self.D * math.sin(φ) ** 6)\n\n δλ = λ - self.λ0\n ξ_prim = math.atan(math.tan(φ_star) / math.cos(δλ))\n η_prim = math.atanh(math.cos(φ_star) * math.sin(δλ))\n\n x = self.k0 * self.â * (ξ_prim +\n self.β1 * math.sin(2 * ξ_prim) * math.cosh(2 * η_prim) +\n self.β2 * math.sin(4 * ξ_prim) * math.cosh(4 * η_prim) +\n self.β3 * math.sin(6 * ξ_prim) * math.cosh(6 * η_prim) +\n self.β4 * math.sin(8 * ξ_prim) * math.cosh(8 * η_prim)) + self.fn\n\n y = self.k0 * self.â * (η_prim +\n self.β1 * math.cos(2 * ξ_prim) * math.sinh(2 * η_prim) +\n self.β2 * math.cos(4 * ξ_prim) * math.sinh(4 * η_prim) +\n self.β3 * math.cos(6 * ξ_prim) * math.sinh(6 * η_prim) +\n self.β4 * math.cos(8 * ξ_prim) * math.sinh(8 * η_prim)) + self.fe\n\n return x, y",
"def galactic_latlon(self):\n vector = _GALACTIC.dot(self.position.au)\n d, lat, lon = to_polar(vector)\n return (Angle(radians=lat, signed=True),\n Angle(radians=lon),\n Distance(au=d))",
"def get_lat_lon(data):\n from time import sleep\n from geopy import geocoders\n from geopy.exc import GeocoderTimedOut\n\n gn = geocoders.GeoNames(username='foobar')\n\n cities = get_cities(data).keys()\n\n coords = {}\n for city in cities:\n while True:\n try:\n loc = gn.geocode(city + \", Brazil\")\n except GeocoderTimedOut:\n sleep(2)\n else:\n break\n\n coords[city] = (loc.latitude, loc.longitude)\n\n return coords",
"def latitude(self):\n return self.coordinates[0]",
"def point_to_lng_lat(point_geometry):\n\n # cast as str\n point = str(point_geometry)\n\n # parse\n point = point.split('(')[-1]\n point = point.replace(')', '')\n\n # split lat/lng\n point = point.strip()\n lng_lat = point.split(' ')\n if(len(lng_lat) != 2):\n raise Exception('Input point is invalid')\n\n # parse\n lng, lat = lng_lat\n lng = lng.strip()\n lat = lat.strip()\n lat = float(lat)\n lng = float(lng)\n\n return [lng, lat]",
"def lat_lons(self):\n return _lat_lons_from_geojson(self._geojson['geometry']['coordinates'])",
"def ecliptic_latlon(self):\n vector = _ECLIPJ2000.dot(self.position.au)\n d, lat, lon = to_polar(vector)\n return (Angle(radians=lat, signed=True),\n Angle(radians=lon),\n Distance(au=d))",
"def cartesian_to_lon_lat(x, y, z, R = 1):\n lon = np.degrees(np.arctan2(y,x))\n lat = np.degrees(np.pi/2-np.arctan2((x**2+y**2)**0.5,z))\n\n return lon,lat"
] | [
"0.6625019",
"0.6440781",
"0.6332487",
"0.6251425",
"0.62414336",
"0.61743146",
"0.6173315",
"0.6170592",
"0.6166276",
"0.615443",
"0.61447704",
"0.6036489",
"0.59269917",
"0.5913509",
"0.58950084",
"0.5847361",
"0.58101594",
"0.5802549",
"0.57882667",
"0.57486916",
"0.57300293",
"0.5725146",
"0.56955475",
"0.56388754",
"0.5629305",
"0.5620556",
"0.5620087",
"0.56185293",
"0.56179225",
"0.559853"
] | 0.7091259 | 0 |
Constructor Copy the Pitcher object into the PitcherGameEntry fields | def __init__(self):
super(PregamePitcherGameEntry, self).__init__()
self.predicted_draftkings_points = 0
self.draftkings_salary = 0
# Season stats
self.season_bf = 0
self.season_ip = 0
self.season_so = 0
self.season_wins = 0
self.season_losses = 0
self.season_er = 0
self.season_h = 0
self.season_bb = 0
self.season_hr = 0
# Career stats
self.career_bf = 0
self.career_ip = 0
self.career_so = 0
self.career_wins = 0
self.career_losses = 0
self.career_er = 0
self.career_h = 0
self.career_bb = 0
self.career_hr = 0
# Versus stats
self.vs_bf = 0
self.vs_so = 0
self.vs_er = 0
self.vs_h = 0
self.vs_bb = 0
self.vs_hr = 0
# Month stats
self.recent_bf = 0
self.recent_ip = 0
self.recent_so = 0
self.recent_er = 0
self.recent_h = 0
self.recent_bb = 0
self.recent_hr = 0 | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def __init__(self, player):\n self._piece_type = 'pawn'\n self._value = 2 if player == \"white\" else -2\n self._summary = 'W-Pw' if player == \"white\" else 'B-Pw'\n\n self._directions = []\n if player == \"white\":\n self._directions.append([(-1, 1)])\n self._directions.append([(0, 1), (0, 2)])\n self._directions.append([(1, 1)])\n else:\n self._directions.append([(-1, -1)])\n self._directions.append([(0, -1), (0, -2)])\n self._directions.append([(1, -1)])",
"def __init__(self, player):\r\n other_player = \"lower\" if player == \"upper\" else \"upper\"\r\n \r\n #set our sides \r\n self.player_information[\"us\"][\"player_side\"] = player\r\n self.player_information[\"them\"][\"player_side\"] = other_player\r\n\r\n #create our board edge and board representation\r\n self.board_edge = hex_boundary_getter((0,0), 4, [])\r\n self.board_array = generate_board()",
"def __init__(self, game, player):\n self.game = game\n self.player = player",
"def __init__(self, players):\n\n self._players = players\n self._game = None",
"def __init__(self, player1, player2):\n # # players of the game {player1name: {color: , red_marbles:}}\n # self._players = {player1[0]: {\"name\": player1[0], \"color\": player1[1]},\n # player2[0]: {\"name\": player2[0], \"color\": player2[1]}}\n # # empty board, no marbles yet\n # self._board = self.create_board()\n # # current player's turn\n # self._turn = None\n # # winner state\n # self._winner = None\n # # red marbles captured for each player, needs addition of black and white marbles\n # self._captured = {player1[0]: 0, player2[0]: 0}\n pass",
"def __init__(self):\r\n self.players = {}",
"def __init__(self, ghost_players=[]):\n self.players = [Player(), Player(), Player(), Player()]\n self.hist = []\n self.round = 1\n self.current_player = 0\n self.first_winner_was = -1\n self.current_dice = -1\n self.observation_pending = False\n self.current_move_pieces = []\n self.current_enemys = []\n self.current_start_attempts = 0\n self.enemys_order = {\n 0: [1, 2, 3],\n 1: [2, 3, 0],\n 2: [3, 0, 1],\n 3: [0, 1, 2]\n }\n self.game_winners = []\n self.ghost_players = ghost_players",
"def __init__(self, player):\n self._piece_type = 'rook'\n self._value = 10 if player == \"white\" else -10\n self._summary = 'W-Rk' if player == \"white\" else 'B-Rk'\n\n self._directions = []\n for _ in range(4):\n self._directions.append([])\n\n for i in range(1, 8):\n self._directions[0].append((i, 0))\n self._directions[1].append((-i, 0))\n self._directions[2].append((0, i))\n self._directions[3].append((0, -i))",
"def __init__(self, players, turns, game, deterministic_cache):\n self.players = players\n self.turns = turns\n self.game = game\n self.deterministic_cache = deterministic_cache\n self.opponents = players",
"def __init__(self, player1, player2, base, game=1):\n self.q1 = player1 # .copy()\n self.q2 = player2 # .copy()\n self.hist1 = {}\n self.hist2 = {}\n self.hist = set()\n self.game = game\n self.base = base\n # See if we have played this game before\n self.gamehash = (self.hashdeck(q1), self.hashdeck(q2))",
"def __init__(self):\n # Mutual attributes (summoner_v1.4 & current_game_v1.0)\n self.id = None\n self.name = None\n self.profile_icon_id = None\n\n # summoner_v1.4 attributes\n self.revision_date = None\n self.level = None",
"def __init__(self, player):\n \n self.colour = player\n self.game_in_head = Board()",
"def __init__(self, players=None):\n self.game = Game()\n if players:\n self.player1 = players[0]\n self.player2 = players[1]\n else:\n self.player1 = Player('X')\n self.player2 = Player('O')\n self.record = Record()\n self.winning_moves = []",
"def __init__(self, players):\n self.players = players\n self.board = Board()",
"def __init__(self, player_id, player_name, chat_id):\n\n # find player info in a database\n with Player.client as client:\n db = client.game_db\n user = db.players.find_one({\"id\": player_id})\n if user is None:\n # add user to database\n user = {\"id\": player_id,\n \"name\": player_name,\n \"chat_id\": chat_id,\n \"games_num\": 0,\n \"rating\": Player.default_rating}\n db.players.insert(user)\n \n self.id = user[\"id\"]\n self.name = user[\"name\"]\n self.chat_id = user[\"chat_id\"]\n self.rating = user[\"rating\"]\n self.game = None\n self.balance = None\n self.stake = None\n self.timer = None\n self.out_of_time = False\n self.searching = False",
"def __init__(self):\n self.board_dict = dict()\n for i in range(self.BOARD_WIDTH):\n for j in range(self.BOARD_WIDTH):\n self.board_dict[i, j] = 0, None\n\n self.players_locations = dict()\n self.last_moved = None",
"def __init__(self):\n\t\tself.matches = {}\n\t\tself.usersInLobby = []\n\t\tself.lastID = 1",
"def __init__(self, lobby_id, players):\n self.card_wished = None\n self.wait_for_card_wish = False\n self.current_player = None\n self.direction_clock_wise = True\n self.current_draw_punishment = 1\n\n self.players = []\n self.lobby_id = lobby_id\n if isinstance(players, list):\n for player in players:\n self.players.append(player)\n else:\n self.players.append(players)\n\n players_len = len(self.players)\n if players_len > 0:\n self.current_player = self.players[random.randint(0, players_len) - 1]\n\n # Get the cards of the game\n game = Game.objects.get(name=\"maumau\")\n card_set = CardSet.objects.get(id=game.card_set_id)\n self.cards = list(card_set.cards.all())\n\n self.__shuffle_cards()\n for player in self.players:\n self.draw_cards(player, 5)\n\n self.discard_pile = []\n self.discard_pile.append(self.cards.pop())",
"def __init__(self, game: int) -> None:\n self.game = game\n self.players: List[object] = []",
"def __init__(self, player):\n\t\tself.player = player",
"def __init__(self, players):\n\n # Define the players\n self.players = players\n\n # Define who starts the game\n self.nplayer = 1 \n\n # Define the board\n self.board = [0] * 9",
"def Clone(self):\n st = PunterGameState()\n st.fullGraph = self.fullGraph\n st.score = self.score\n st.playerJustMoved = self.playerJustMoved\n st.pathes = copy.deepcopy(self.pathes)\n st.scores = copy.deepcopy(self.scores)\n st.endpoints = self.endpoints[:]\n return st",
"def __init__(self, players):\n\n self._players = players\n self._current_player = players.get()",
"def __init__(self, player, board):\n self.player = player\n self.board = board",
"def clone(self):\n copy = GamePiece((self.x, self.y), self.player)\n return copy",
"def __init__(self, hive):\n self.player = PlayerID(hive[\"player\"])\n self.position = make_position(hive[\"position\"])",
"def __init__(self):\n self.id = None\n self.name = None\n self.phone = None\n self.score = 0 # Running sum of player's score\n self.state = None\n self.ball_id = None\n self.start_x = None # start pos of object thrown in game\n self.angle = 0 # angle of ball movement\n self.velocity = 0 # velocity of ball\n # leaderboard\n self.game_over = False\n self.date = str(datetime.date.today()) # required for leaderboard",
"def __init__(self, player):\n self.player = player",
"def __init__(self, _gameBeingPlayed, _charcter):\n self.name = \"random\"\n random.seed(2)\n self.game = _gameBeingPlayed\n self.character = _charcter\n self.neutralCharacter = self.game.neutralCharacter",
"def __init__(self, contest=None, contest_id=None):\n\n if contest_id is not None:\n self.contest = Contest.objects.get(pk=contest_id)\n elif contest is not None:\n self.contest = contest\n else:\n raise Exception('contest must not be None')\n\n dgm = DraftGroupManager()\n self.draft_group_players = dgm.get_players(self.contest.draft_group)\n\n # a map where the player id points to their own id if their game\n # has started, or to 0xffff if they havent started yet\n #\n # i can see a reason we would want to cache the get_starter_map result ....\n self.starter_map = self.get_starter_map(self.draft_group_players)\n\n # determine the size of a lineup in bytes\n rm = RosterManager(self.contest.site_sport)\n self.players_per_lineup = rm.get_roster_spots_count()\n\n self.entries = Entry.objects.filter(contest=self.contest)"
] | [
"0.61979926",
"0.618096",
"0.6179797",
"0.60220015",
"0.59239674",
"0.592135",
"0.588046",
"0.5850027",
"0.58463913",
"0.5770918",
"0.57358724",
"0.57344246",
"0.57330227",
"0.57256836",
"0.57162654",
"0.57162297",
"0.5712789",
"0.571192",
"0.5684267",
"0.5645466",
"0.5638088",
"0.561811",
"0.55882776",
"0.5580367",
"0.55777097",
"0.557193",
"0.55579525",
"0.55564064",
"0.55556583",
"0.55556345"
] | 0.6979371 | 0 |
Calculate the predicted points per dollar for this player. Return 0 if the Draftkings salary is equal to zero | def points_per_dollar(self):
if float(self.draftkings_salary) == 0.0:
return 0.0
return float(self.predicted_draftkings_points) / float(self.draftkings_salary) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def dollars_per_point(self):\n if float(self.predicted_draftkings_points) == 0.0:\n return 0.0\n\n return float(self.draftkings_salary) / float(self.predicted_draftkings_points)",
"def score(self, predictions):\n return 0.",
"def predict(self):\n if ((self.kf.x[6] + self.kf.x[2]) <= 0):\n self.kf.x[6] *= 0.0\n self.kf.predict()\n self.age += 1\n if (self.time_since_update > 0):\n self.hit_streak = 0\n self.time_since_update += 1\n self.history.append(convert_x_to_bbox(self.kf.x))\n return self.history[-1]",
"def precision(y_true, y_pred):\n true_positives = bk.sum(bk.round(bk.clip(y_true * y_pred, 0, 1)))\n predicted_positives = bk.sum(bk.round(bk.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + bk.epsilon())\n return precision",
"def mapd(self) -> float:\n a = np.sum(np.abs(self.predicted - self.true))\n b = np.sum(np.abs(self.true))\n return float(a / b)",
"def calculate_score(self):\n\n correct_award = 150\n turns_total = self.turns.count()\n turns_correct = self.turns.filter(is_match=True).count()\n seconds_left = (60.0 - (self.turns.last().created - self.turns.first().created).total_seconds()) or 0\n maxpoints = turns_correct * correct_award\n deduction_for_errors = correct_award * 0.11123\n\n maxpoints -= ((turns_total - turns_correct) * 2 * deduction_for_errors)\n maxpoints += seconds_left * 5.123214\n\n return Decimal(maxpoints)",
"def RPS(y_true, y_pred) -> float:\n output = 0.\n data_num = len(y_true)\n for i in range(data_num):\n times = len(y_true[i]) - 1 \n cumulative_sum = 0.\n score = 0.\n for time in range(times):\n cumulative_sum += y_true[i,time] - y_pred[i,time]\n score += cumulative_sum ** 2\n score /= times\n output += score\n \n output /= data_num\n return output",
"def get_score(self):\n\n # if the prev was a spare we need to get the total of 2 balls\n # and the result of the first ball added\n if self.is_prev_spare:\n if self.is_strike():\n return self._total()\n else:\n return self.first_ball * 2 + self.second_ball\n # if the prev prev was a strike it is a special case\n elif self.is_prev_strike and self.is_prev_prev_strike:\n if self.is_strike():\n return self._total()\n else:\n return self._total() * 2 + self.first_ball\n elif self.is_prev_strike and not self.is_prev_prev_strike:\n if self.is_strike():\n return self._total()\n else:\n return self._total() * 2\n pass\n else:\n # it seems we don't have a special case here\n return self.first_ball + self.second_ball",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def evaluate(self):\n # initialize delta_weights\n Loss = 0\n for i, x_test in enumerate(self.X_test):\n Loss += (self.sigmoid(np.dot(self.weights,x_test))-self.y_test[i])**2\n return Loss",
"def _cls_score(self, X, y, output=True):\n _y = self.predict(X)\n y = np.array(y); _y = np.array(_y)\n precious = 1-(1.0*len(np.nonzero(y-_y)[0])/len(y))\n if output:\n print(f\"Accuracy: {precious}\")\n return precious",
"def dilutionneeded(self) -> float:\n return self.stock*1.0/self.final",
"def precision(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision",
"def precision(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision",
"def precision(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision",
"def precision(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision",
"def precision(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision",
"def precision(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision"
] | [
"0.7366089",
"0.6308235",
"0.6148629",
"0.6024777",
"0.6016563",
"0.6001432",
"0.5949691",
"0.59205437",
"0.5876416",
"0.58619565",
"0.5852512",
"0.5852342",
"0.5832806",
"0.5832806",
"0.5832806",
"0.5832806",
"0.5832806",
"0.5832806",
"0.5831876",
"0.5831876",
"0.5831876",
"0.5831876",
"0.5831876",
"0.5831876",
"0.5831876",
"0.5831876",
"0.5831876",
"0.5831876",
"0.5831876",
"0.5831876"
] | 0.8419467 | 0 |
Calculate the predicted points per dollar for this player. Return 0 if the Draftkings salary is equal to zero | def dollars_per_point(self):
if float(self.predicted_draftkings_points) == 0.0:
return 0.0
return float(self.draftkings_salary) / float(self.predicted_draftkings_points) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def points_per_dollar(self):\n if float(self.draftkings_salary) == 0.0:\n return 0.0\n\n return float(self.predicted_draftkings_points) / float(self.draftkings_salary)",
"def score(self, predictions):\n return 0.",
"def predict(self):\n if ((self.kf.x[6] + self.kf.x[2]) <= 0):\n self.kf.x[6] *= 0.0\n self.kf.predict()\n self.age += 1\n if (self.time_since_update > 0):\n self.hit_streak = 0\n self.time_since_update += 1\n self.history.append(convert_x_to_bbox(self.kf.x))\n return self.history[-1]",
"def precision(y_true, y_pred):\n true_positives = bk.sum(bk.round(bk.clip(y_true * y_pred, 0, 1)))\n predicted_positives = bk.sum(bk.round(bk.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + bk.epsilon())\n return precision",
"def mapd(self) -> float:\n a = np.sum(np.abs(self.predicted - self.true))\n b = np.sum(np.abs(self.true))\n return float(a / b)",
"def calculate_score(self):\n\n correct_award = 150\n turns_total = self.turns.count()\n turns_correct = self.turns.filter(is_match=True).count()\n seconds_left = (60.0 - (self.turns.last().created - self.turns.first().created).total_seconds()) or 0\n maxpoints = turns_correct * correct_award\n deduction_for_errors = correct_award * 0.11123\n\n maxpoints -= ((turns_total - turns_correct) * 2 * deduction_for_errors)\n maxpoints += seconds_left * 5.123214\n\n return Decimal(maxpoints)",
"def RPS(y_true, y_pred) -> float:\n output = 0.\n data_num = len(y_true)\n for i in range(data_num):\n times = len(y_true[i]) - 1 \n cumulative_sum = 0.\n score = 0.\n for time in range(times):\n cumulative_sum += y_true[i,time] - y_pred[i,time]\n score += cumulative_sum ** 2\n score /= times\n output += score\n \n output /= data_num\n return output",
"def get_score(self):\n\n # if the prev was a spare we need to get the total of 2 balls\n # and the result of the first ball added\n if self.is_prev_spare:\n if self.is_strike():\n return self._total()\n else:\n return self.first_ball * 2 + self.second_ball\n # if the prev prev was a strike it is a special case\n elif self.is_prev_strike and self.is_prev_prev_strike:\n if self.is_strike():\n return self._total()\n else:\n return self._total() * 2 + self.first_ball\n elif self.is_prev_strike and not self.is_prev_prev_strike:\n if self.is_strike():\n return self._total()\n else:\n return self._total() * 2\n pass\n else:\n # it seems we don't have a special case here\n return self.first_ball + self.second_ball",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def evaluate(self):\n # initialize delta_weights\n Loss = 0\n for i, x_test in enumerate(self.X_test):\n Loss += (self.sigmoid(np.dot(self.weights,x_test))-self.y_test[i])**2\n return Loss",
"def dilutionneeded(self) -> float:\n return self.stock*1.0/self.final",
"def _cls_score(self, X, y, output=True):\n _y = self.predict(X)\n y = np.array(y); _y = np.array(_y)\n precious = 1-(1.0*len(np.nonzero(y-_y)[0])/len(y))\n if output:\n print(f\"Accuracy: {precious}\")\n return precious",
"def precision(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision",
"def precision(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision",
"def precision(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision",
"def precision(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision",
"def precision(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision",
"def precision(y_true, y_pred):\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision",
"def precision(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision"
] | [
"0.8419284",
"0.63081765",
"0.6148541",
"0.6024131",
"0.6016389",
"0.600038",
"0.59496975",
"0.5920287",
"0.58757573",
"0.5860934",
"0.58529276",
"0.58520406",
"0.58322114",
"0.58322114",
"0.58322114",
"0.58322114",
"0.58322114",
"0.58322114",
"0.58312875",
"0.58312875",
"0.58312875",
"0.58312875",
"0.58312875",
"0.58312875",
"0.58312875",
"0.58312875",
"0.58312875",
"0.58312875",
"0.58312875",
"0.58312875"
] | 0.73660153 | 1 |
Check if given value is correct for gender number in ID code. | def is_valid_gender_number(gender_number: int) -> bool:
if gender_number in range(1, 7):
return True
return False | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def is_valid_gender_number(gender_number: int) -> bool:\n if gender_number in range(1, 7):\n return True\n else:\n return False",
"def is_id_valid(id_code: str) -> bool:\n if is_valid_gender_number(int(id_code[0:1])):\n if is_valid_year_number(int(id_code[1:3])):\n if is_valid_month_number(int(id_code[3:5])):\n if is_valid_day_number(int(id_code[0:1]), int(id_code[1:3]), int(id_code[3:5]), int(id_code[5:7])):\n if is_valid_birth_number(int(float(id_code[7:10]))):\n if is_valid_control_number(id_code):\n return True\n else:\n return False\n else:\n return False\n\n else:\n return False\n else:\n return False\n else:\n return False",
"def check_gender(input_string: str) -> str:\n n = input_string[1]\n if n == '1':\n return 'male'\n elif n == '2':\n return 'female'\n else:\n return None",
"def is_id_valid(id_code: str) -> bool:\n if id_code.isdigit():\n if len(str(id_code)) == 11:\n id_code = str(id_code)\n gender_number = int(id_code[0:1])\n day = int(id_code[5:7])\n month = int(id_code[3:5])\n year = id_code[1:3]\n birth_number = id_code[7:10]\n if is_valid_gender_number(gender_number) \\\n and is_valid_year_number(int(year)) \\\n and is_valid_month_number(int(month)) \\\n and is_valid_day_number(gender_number, int(year), int(month), int(day)) \\\n and is_valid_birth_number(int(birth_number)) \\\n and is_valid_control_number(str(id_code)):\n return True\n return False\n return False\n return False",
"def get_gender(gender_number: int) -> str:\n male = [1, 3, 5]\n female = [2, 4, 6]\n if gender_number in male:\n return \"male\"\n elif gender_number in female:\n return \"female\"",
"def genderizer(poke_id):\n \n female, male, genderless = gender_grouper()\n gender = \"\"\n\n if (poke_id in female) and (poke_id not in male):\n gender = 'F'\n elif (poke_id in male) and (poke_id not in female):\n gender = 'M'\n elif poke_id in male and female:\n gender = \"F/M\"\n elif poke_id in genderless:\n gender = 'N'\n\n return gender",
"def is_female(personal_number_string):\n digit_string = personal_number_string[-1]\n digit = int(digit_string)\n if digit % 2 == 0: #even digit\n return True\n else:\n return False",
"def validateGender(gender):\n if gender == \"male\" or gender == \"female\" or gender == None:\n return None\n else:\n return {'error': 'invalid value: %s (%s), valid values male/female/null' % (gender, pythonTypeToJSONType(gender))}",
"def test_IsCorrectGender(self):\n \n # load data\n ilist, flist = load_data()\n\n # test case 01\n for fm in flist:\n result, msg = IsCorrectGender(fm.WifeID,fm.HusbandID, ilist)\n self.assertTrue(result)\n\n # test case 02\n ilist[0].Gender = 'F'\n ilist[1].Gender = 'M'\n result, msg = IsCorrectGender(flist[0].WifeID,flist[0].HusbandID, ilist)\n self.assertFalse(result)",
"def get_gender(self, data: dict):\n try:\n gender = data.get(\"P21\")[0].get(\"mainsnak\").get(\"datavalue\").get(\"value\").get(\"id\")\n except TypeError:\n return \"Unknown\"\n return self._reference.get_gender(gender)",
"def is_female_gender(gender: Union[Gender, CommonGender, int]) -> bool:\n if gender is None:\n return False\n return int(gender) == int(Gender.FEMALE)",
"def test_set_gender_if_provided():\n\n # GIVEN a gender which is not Gender.OTHER as input\n gender: PlinkGender = PlinkGender.FEMALE\n\n # WHEN running \"set_gender_if_other\"\n validated_gender: str = set_gender_if_other(gender)\n\n # THEN the returned string should not have been altered\n assert validated_gender == gender",
"def is_valid_birth_number(birth_number: int):\n if birth_number in range(1, 1000):\n return True\n else:\n return False",
"def is_valid_birth_number(birth_number: int):\n if birth_number in range(1, 1000):\n return True\n return False",
"def get_gender(gender: int) -> str:\n if gender in [1, 3, 5]:\n gender = \"male\"\n elif gender in [2, 4, 6]:\n gender = \"female\"\n\n return gender",
"def test_gender_sex(self):\n gender_field = self.record.find('field[@name=\\'gender\\']')\n sex_field = self.record.find('field[@name=\\'sex\\']')\n self.assertIn(gender_field.text, self.gender_sex,\n 'Gender not in selection')\n self.assertIn(sex_field.text, self.gender_sex,\n 'Sex not in selection')\n self.assertEqual(gender_field.text, sex_field.text,\n 'Gender and Sex are not the same')",
"def is_male_gender(gender: Union[Gender, CommonGender, int]) -> bool:\n if gender is None:\n return False\n return int(gender) == int(Gender.MALE)",
"def getGender(self,number)->str:\n if number%2 == 0:\n return 'male'\n else:\n return 'female'",
"def test_set_gender_if_other():\n\n # GIVEN Gender.OTHER as input\n gender: Gender = Gender.OTHER\n\n # WHEN running \"set_gender_if_other\"\n validated_gender: str = set_gender_if_other(gender)\n\n # THEN the returned gender should be PlinkGender.UNKNOWN\n assert validated_gender == PlinkGender.UNKNOWN",
"def test_components_profile_gender(self):\r\n\t\tself.assertEqual(self.u1.profile.gender, 'female')",
"def validate(self,data):\r\n for person in data:\r\n #check the format is a letter and 3 digit e.g A002 or a002\r\n \r\n if (re.match(r'[A-Z][0-9]{3}', (person[0]).lower())):\r\n print (person[0])\r\n else:\r\n print(person[0] + \" \" + 'is incorrect ID, '\r\n ' must contains a letter and 3 digits e.g a002')\r\n \r\n #check the format is either M/F/Male/Female\r\n \r\n if (person[1] == \"M\" or (person[1]).upper() == \"F\" or\r\n person[1] == \"Male\" or person[1] == \"Female\"):\r\n print (person[1])\r\n else:\r\n print(person[1] + \" \" + 'is incorrect Gender, '\r\n ' must either be M and Male or F and Female')\r\n \r\n #check age is valid entry and match with date\r\n \r\n if (re.match(r'[0-9]{2}', person[2]) and person[2] == self.valid_age(person[6])):\r\n print (person[2])\r\n elif (person[2] != self.valid_age(person[2])):\r\n print(\"Does not match with your birthday, invalid age\")\r\n else:\r\n print(person[2] + \" \" + 'age must be an integer')\r\n \r\n #check sales is 3 interger value\r\n if (re.match(r'[0-9]{3}', person[3])):\r\n return (person[3])\r\n else:\r\n print(person[3] + \" \" + 'is incorrect sales number, '\r\n 'must be a 2 interger number')\r\n \r\n #check BMI is either Normal / Overweight / Obesity or Underweight\r\n if (re.match(r'\\b(NORMAL|OVERWEIGHT|OBESITY|UNDERWEIGHT)\\b',(person[4]).upper())):\r\n print (person[4])\r\n else:\r\n print(person[4] + \" \" ' is incorrect BMI value, '\r\n 'must select from Normal, Overweight, Obesity or Underweight')\r\n \r\n #check Income is float\r\n\r\n if (re.match(r'[0-9]{2,3}', person[5])):\r\n print (person[5])\r\n else:\r\n print(person[5] + \" \" + 'is incorrect income, '\r\n 'must be a interger number') \r\n \r\n #check birthday\r\n \r\n if (self.valid_date(person[6]) and person[2] == self.valid_age(person[6]) ):\r\n print (person[6])\r\n else:\r\n print(person[2] + \" \" + 'is incorrect date format, '\r\n 'must contain DD-MM-YYYY or DD-MM-YY and seperated by -')\r\n \r\n return readFile",
"def test_gender_bad_value(self):\n for val in self.bad_values:\n self.assertRaises(line_format_errors.FieldParseError,\n lambda: self.line._parse_gender(val))",
"def us21_correct_gender_for_role(repo):\n error = []\n for fam in repo.families.values():\n husb = fam['HUSB']['detail']\n wife = fam['WIFE']['detail']\n gender_of_husb = repo.individuals[husb]['SEX']['detail']\n gender_of_wife = repo.individuals[wife]['SEX']['detail']\n if gender_of_husb != 'M':\n error_message = 'Husband ' + husb + ' in family ' + fam.fam_id + ' should be male'\n error.append(('ANOMALY','FAMILY', 'US21', repo.individuals[husb]['SEX']['line'], fam.fam_id, error_message ))\n if gender_of_wife != 'F':\n error_message = 'Wife ' + wife + ' in family ' + fam.fam_id + ' should be female'\n error.append(('ANOMALY','FAMILY', 'US21', repo.individuals[wife]['SEX']['line'], fam.fam_id, error_message ))\n return error",
"def gender():\n return random.choice((GENDER_FEMALE, GENDER_MALE))",
"def is_valid_day_number(gender_number: int, year_number: int, month_number: int, day_number: int) -> bool:\n monthlist1 = [1, 3, 5, 7, 8, 10, 12]\n monthlist2 = [4, 6, 9, 11]\n monthlist3 = [2]\n if month_number in monthlist1:\n if day_number in range(1, 32):\n return True\n else:\n return False\n elif month_number in monthlist2:\n if day_number in range(1, 31):\n return True\n else:\n return False\n elif month_number in monthlist3:\n if is_leap_year(get_full_year(gender_number, year_number)):\n if day_number in range(1, 30):\n return True\n else:\n return False\n else:\n if day_number in range(1, 28):\n return True\n else:\n return False",
"def gender(self, value: str) -> None:\n gender_mapper = {\n 'Muž': 'm',\n 'm': 'm',\n 'Žena': 'z',\n 'z': 'z'\n }\n self._gender = gender_mapper[value]",
"def is_valid_day_number(gender_number: int, year_number: int, month_number: int, day_number: int) -> bool:\n year = get_full_year(gender_number, year_number)\n leap_year = is_leap_year(int(year))\n if month_number in [1, 3, 5, 7, 8, 10, 12]:\n day_in_month = 31\n elif month_number in [4, 6, 9, 11]:\n day_in_month = 30\n else:\n if leap_year:\n day_in_month = 29\n else:\n day_in_month = 28\n\n if day_number in range(1, (day_in_month + 1)):\n return True\n return False",
"def get_gender(self):\n genders = dict(GENDERS)\n return genders.get(self.gender, \"N/A\")",
"def recode_resend(sex_value):\n\tif sex_value == 'Male':\n\t\treturn 1\n\telif sex_value == 'Female':\n\t\treturn 0\n\telse:\n\t\treturn np.nan",
"def gender():\r\n\r\n return _random.choice(['Male', 'Female'])"
] | [
"0.7719618",
"0.69450635",
"0.68326753",
"0.6717552",
"0.6647802",
"0.6626832",
"0.66216373",
"0.6605458",
"0.6395822",
"0.6375869",
"0.62992686",
"0.62555933",
"0.6241217",
"0.62064004",
"0.61805654",
"0.6166287",
"0.61211264",
"0.6119617",
"0.6110498",
"0.597888",
"0.5960397",
"0.59081984",
"0.5902811",
"0.5852079",
"0.5819465",
"0.58168375",
"0.5801228",
"0.57638484",
"0.5763385",
"0.5747166"
] | 0.7697313 | 1 |
Check if given value is correct for month number in ID code. | def is_valid_month_number(month_number: int) -> bool:
if 0 < month_number <= 12:
return True
else:
return False | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def is_valid_month (val):\n if len(val) == 2 and count_digits(val) == 2:\n month = int(val)\n return month > 0 and month < 13\n return False",
"def is_valid_month_number(month_number: int) -> bool:\n if month_number in range(13):\n return True\n else:\n return False",
"def is_valid_month(month_number):\n\n if (type(month_number) == int) and (1 <= month_number <= 12):\n return True\n\n return False",
"def valid_day_of_month(value):\n if value.m == 2:\n month_length = 29\n if value.y is not None:\n if (value.y % 4) != 0:\n month_length = 28\n elif value.y == 0 and value.C is not None and (value.C % 4) != 0:\n month_length = 28\n else:\n # Odd-numbered months are longer through July, then even-numbered\n # months are longer for the rest of the year.\n month_length = 30 + ((value.m % 2) == (value.m < 8))\n return value.d <= month_length",
"def test_month_from_number(self):\r\n self.assertEqual(cds.month_from_number(1).lower(), \"january\")\r\n self.assertEqual(cds.month_from_number(2).lower(), \"february\")\r\n self.assertEqual(cds.month_from_number(3).lower(), \"march\")\r\n self.assertEqual(cds.month_from_number(4).lower(), \"april\")\r\n self.assertEqual(cds.month_from_number(5).lower(), \"may\")\r\n self.assertEqual(cds.month_from_number(6).lower(), \"june\")\r\n self.assertEqual(cds.month_from_number(7).lower(), \"july\")\r\n self.assertEqual(cds.month_from_number(8).lower(), \"august\")\r\n self.assertEqual(cds.month_from_number(9).lower(), \"september\")\r\n self.assertEqual(cds.month_from_number(10).lower(), \"october\")\r\n self.assertEqual(cds.month_from_number(11).lower(), \"november\")\r\n self.assertEqual(cds.month_from_number(12).lower(), \"december\")",
"def test_invalid_month_orig(self):\n year, month, error = clean_year_month(2014, 3, 13)\n self.assertEqual(year, 2014)\n self.assertEqual(month, timezone.localtime(timezone.now()).month)\n self.assertEqual(error, ERROR)",
"def test_valid_month(self):\n ar_month = self.ar[2009][11]\n self.assertTrue(isinstance(ar_month, awstats_reader.AwstatsMonth))",
"def test_month_from_number_raises_error_if_not_1_to_12(self):\r\n\r\n with self.assertRaises(ValueError, msg=\"Should raise a value error if month is 0\") as ctx:\r\n cds.month_from_number(0)\r\n with self.assertRaises(ValueError, msg=\"Should raise a value error if month is 13\") as ctx:\r\n cds.month_from_number(13)\r\n with self.assertRaises(ValueError, msg=\"Should raise a value error if month is 110\") as ctx:\r\n cds.month_from_number(110)",
"def is_id_valid(id_code: str) -> bool:\n if id_code.isdigit():\n if len(str(id_code)) == 11:\n id_code = str(id_code)\n gender_number = int(id_code[0:1])\n day = int(id_code[5:7])\n month = int(id_code[3:5])\n year = id_code[1:3]\n birth_number = id_code[7:10]\n if is_valid_gender_number(gender_number) \\\n and is_valid_year_number(int(year)) \\\n and is_valid_month_number(int(month)) \\\n and is_valid_day_number(gender_number, int(year), int(month), int(day)) \\\n and is_valid_birth_number(int(birth_number)) \\\n and is_valid_control_number(str(id_code)):\n return True\n return False\n return False\n return False",
"def is_id_valid(id_code: str) -> bool:\n if is_valid_gender_number(int(id_code[0:1])):\n if is_valid_year_number(int(id_code[1:3])):\n if is_valid_month_number(int(id_code[3:5])):\n if is_valid_day_number(int(id_code[0:1]), int(id_code[1:3]), int(id_code[3:5]), int(id_code[5:7])):\n if is_valid_birth_number(int(float(id_code[7:10]))):\n if is_valid_control_number(id_code):\n return True\n else:\n return False\n else:\n return False\n\n else:\n return False\n else:\n return False\n else:\n return False",
"def is_mmddyy (val):\n if len(val) == 6 and count_digits(val) == 6:\n return is_valid_day(val[2:4]) and is_valid_month(val[0:2])\n return False",
"def test_fix_year_month_next_gt_12(self):\n # 23 - 10 = next query of 13\n year, month, error = clean_year_month(2014, 23, 10)\n self.assertEqual(year, 2015)\n self.assertEqual(month, 11)\n self.assertEqual(error, False)",
"def month_digit(self, year, month, day):\n if (month[0] == '0' and len(month) > 2 or\n day.isdigit() and day[0] == '0' and len(day) > 2):\n Input.change_display(self, self.entries[4],\n 'Remove preceding zeros')\n else:\n Input.day_of_months(self, year, month, day.lstrip('0'))",
"def is_yymmdd (val):\n if len(val) == 6 and count_digits(val) == 6:\n return is_valid_day(val[2:4]) and is_valid_month(val[4:6])\n return False",
"def is_ddmmyy (val):\n if len(val) == 6 and count_digits(val) == 6:\n return is_valid_day(val[0:2]) and is_valid_month(val[2:4])\n return False",
"def check_date(y, m, d=None):\r\n months = [\"january\", \"february\", \"march\", \"april\", \"may\", \"june\", \"july\",\r\n \"august\", \"september\", \"october\", \"november\", \"december\"]\r\n days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\r\n if y.isdigit() and int(y) > 1899 and int(y) < 3000:\r\n if m in months:\r\n if d is None or d.isdigit() and int(d) > 0 \\\r\n and int(d) <= days[months.index(m)]:\r\n return True\r\n return False",
"def test_contains_month_true(self):\n ary = self.ar = awstats_reader.AwstatsReader(test_file_dir, 'jjncj.com')[2009]\n self.assertTrue(11 in ary)",
"def get_month():\n return handle_invalid_inputs(question_3, months)",
"def date_is_valid(year, month, day):\r\n \r\n if (datetime.date(year, month <= 12, day <= 31)):\r\n return True\r\n\r\n else:\r\n return False",
"def check_smonth(sdate, st_dict):\n \n # if data exists in a year after sdate.year....True\n years = [int(y) for y in st_dict['years']]\n if any(y > sdate.year for y in years):\n return True \n \n # if sdate.year is in years..check sdate.month \n if sdate.year in years:\n months = [int(m) for m in st_dict[str(sdate.year)]['months']]\n if any(m >= sdate.month for m in months):\n return True\n return False",
"def day_of_months(self, year, month, day):\n if month.isdigit() and int(month) < 13:\n if (int(month) in [1,3,5,7,8,10,12]):\n Input.condition(self, year, month, day, '31', '')\n elif (int(month) in [4,6,9,11]):\n Input.condition(self, year, month, day, '30', '')\n elif int(month) == 2:\n if (((int(year) % 4) == 0 and\n not (int(year) % 100) == 0)\n or (int(year) % 400) == 0):\n if int(year) == 1712 and int(day) == 30:\n \"\"\"Easter Egg.\"\"\"\n Input.condition(self, year, month, day, '30','')\n Input.special_case(self)\n else:\n Input.condition(self, year, month, day, '29',' ')\n else:\n Input.condition(self, year, month, day, '28', '29')\n else:\n Input.change_display(self, self.entries[4],\n 'Enter month between 1-12 or month name')",
"def sameSeason( pMonth, cMonth ):\r\n if pMonth == 12 or pMonth == 1 or pMonth == 2:\r\n if cMonth == 12 or cMonth == 1 or cMonth == 2:\r\n return True\r\n else:\r\n return False\r\n\r\n if pMonth == 3 or pMonth == 4 or pMonth == 5:\r\n if cMonth == 3 or cMonth == 4 or cMonth == 5:\r\n return True\r\n else:\r\n return False\r\n\r\n if pMonth == 6 or pMonth == 7 or pMonth == 8:\r\n if cMonth == 6 or cMonth == 7 or cMonth == 8:\r\n return True\r\n else:\r\n return False\r\n\r\n if pMonth == 9 or pMonth == 10 or pMonth == 11:\r\n if cMonth == 9 or cMonth == 10 or cMonth == 11:\r\n return True\r\n else:\r\n return False",
"def _validate(year, month, day):\n if day is not None and month is None:\n raise ValueError(\"Day without month\")\n if day is None:\n day = 1\n if month is None:\n month = 1\n if year is None:\n year = 2000\n # actual validation happens here\n datetime.date(year, month, day)",
"def isValid(t_id):\n\tstr_id=str(t_id).strip()\n\treturn str_id.isdigit()",
"def test_invalid_out_of_bounds_year(self):\n year, month, error = clean_year_month(2014, 100000, 1)\n self.assertEqual(year, now.year)\n self.assertEqual(month, timezone.localtime(timezone.now()).month)\n self.assertEqual(error, ERROR)",
"def test_fix_year_month_next(self):\n # 13 - 10 = next query of 3\n year, month, error = clean_year_month(2014, 13, 10)\n self.assertEqual(year, 2015)\n self.assertEqual(month, 1)\n self.assertEqual(error, False)",
"def is_valid_day_number(gender_number: int, year_number: int, month_number: int, day_number: int) -> bool:\n monthlist1 = [1, 3, 5, 7, 8, 10, 12]\n monthlist2 = [4, 6, 9, 11]\n monthlist3 = [2]\n if month_number in monthlist1:\n if day_number in range(1, 32):\n return True\n else:\n return False\n elif month_number in monthlist2:\n if day_number in range(1, 31):\n return True\n else:\n return False\n elif month_number in monthlist3:\n if is_leap_year(get_full_year(gender_number, year_number)):\n if day_number in range(1, 30):\n return True\n else:\n return False\n else:\n if day_number in range(1, 28):\n return True\n else:\n return False",
"def is_expunged(cls, month, year):\n return month != cls.lunar_from_fixed(HinduLunarFullMoonDate(year, month, False, 15, False).to_fixed()).month",
"def is_valid_control_number(id_code: str) -> bool:\n sum = 1 * int(id_code[:1]) + 2 * int(id_code[1:2]) + 3 * int(id_code[2:3]) + 4 * int(id_code[3:4]) + 5 * \\\n int(id_code[4:5]) + 6 * int(id_code[5:6]) + 7 * int(id_code[6:7]) + 8 * int(id_code[7:8]) + 9 *\\\n int(id_code[8:9]) + 1 * int(id_code[9:10])\n control_number = sum % 11\n if int(control_number) == int(id_code[10:11]):\n return True\n elif int(control_number) == 10:\n sum = 3 * int(id_code[:1]) + 4 * int(id_code[1:2]) + 5 * int(id_code[2:3]) + 6 * int(id_code[3:4]) + 7 * \\\n int(id_code[4:5]) + 8 * int(id_code[5:6]) + 9 * int(id_code[6:7]) + 1 * int(id_code[7:8]) + 2 * \\\n int(id_code[8:9]) + 3 * int(id_code[9:10])\n control_number = sum % 11\n if control_number == int(id_code[10:11]):\n return True\n elif control_number == 10:\n if int(id_code[10:11]) == 0:\n return True\n else:\n return False\n else:\n return False",
"def test_contains_month_false(self):\n ary = self.ar = awstats_reader.AwstatsReader(test_file_dir, 'jjncj.com')[2009]\n self.assertFalse(10 in ary)"
] | [
"0.78509146",
"0.752391",
"0.7422335",
"0.68609554",
"0.68215",
"0.67081577",
"0.67009896",
"0.668985",
"0.6498707",
"0.6488282",
"0.6337808",
"0.6278733",
"0.62254703",
"0.62079597",
"0.6181568",
"0.61379164",
"0.61099625",
"0.6058875",
"0.60411596",
"0.60232794",
"0.6012972",
"0.5981379",
"0.59512794",
"0.59446573",
"0.59358376",
"0.5911036",
"0.5882207",
"0.58756316",
"0.58455575",
"0.58290654"
] | 0.75445867 | 1 |
Check if given value is correct for birth number in ID code. | def is_valid_birth_number(birth_number: int):
if birth_number in range(1, 1000):
return True
return False | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def is_valid_birth_number(birth_number: int):\n if birth_number in range(1, 1000):\n return True\n else:\n return False",
"def is_id_valid(id_code: str) -> bool:\n if id_code.isdigit():\n if len(str(id_code)) == 11:\n id_code = str(id_code)\n gender_number = int(id_code[0:1])\n day = int(id_code[5:7])\n month = int(id_code[3:5])\n year = id_code[1:3]\n birth_number = id_code[7:10]\n if is_valid_gender_number(gender_number) \\\n and is_valid_year_number(int(year)) \\\n and is_valid_month_number(int(month)) \\\n and is_valid_day_number(gender_number, int(year), int(month), int(day)) \\\n and is_valid_birth_number(int(birth_number)) \\\n and is_valid_control_number(str(id_code)):\n return True\n return False\n return False\n return False",
"def is_id_valid(id_code: str) -> bool:\n if is_valid_gender_number(int(id_code[0:1])):\n if is_valid_year_number(int(id_code[1:3])):\n if is_valid_month_number(int(id_code[3:5])):\n if is_valid_day_number(int(id_code[0:1]), int(id_code[1:3]), int(id_code[3:5]), int(id_code[5:7])):\n if is_valid_birth_number(int(float(id_code[7:10]))):\n if is_valid_control_number(id_code):\n return True\n else:\n return False\n else:\n return False\n\n else:\n return False\n else:\n return False\n else:\n return False",
"def is_valid_birth_year(birth_year: int) -> bool:\n return birth_year.isnumeric() and 1920 <= int(birth_year) <= 2002",
"def validate_birth_year(passport: map) -> bool:\n if passport.get('byr'):\n if int(passport['byr']) >= 1920 and int(passport['byr']) <= 2002:\n return True\n\n return False",
"def validate(number):\n number = compact(number)\n if not isdigits(number):\n raise InvalidFormat()\n if len(number) != 10:\n raise InvalidLength()\n # check if birth date is valid\n get_birth_date(number)\n # TODO: check that the birth date is not in the future\n # check the check digit\n if calc_check_digit(number[:-1]) != number[-1]:\n raise InvalidChecksum()\n return number",
"def validate_birth_year(birth_year: str) -> None:\n if not 1920 <= int(birth_year) <= 2002:\n raise ValueError(\"Birth year is outside permissible range\")",
"def _validate_bbg_id(x):\n return len(x) == 12 and x[:3] == 'BBG' and str.isalnum(x[3:11]) and sum(map(\n lambda u: u in ['A', 'E', 'I', 'O', 'U'], x[3:11])) == 0 and str.isdigit(x[11])",
"def is_valid_year_number(year_number: int) -> bool:\n if year_number in range(100):\n return True\n else:\n return False",
"def isValid(t_id):\n\tstr_id=str(t_id).strip()\n\treturn str_id.isdigit()",
"def verify_format(isbn):\n\n return len(isbn) == 10 and (isbn[-1] == \"X\" or isbn[-1].isdigit()) \\\n and all(digit.isdigit() for digit in isbn[:-1])",
"def is_valid_year_number(year_number: int) -> bool:\n if 0 <= int(year_number) < 100:\n return True\n return False",
"def valid_age(line):\n dob = line.o_DOB\n if not _is_21(dob):\n rule = 'Allowed age'\n new_row = Error(e_name=rule, order_key=line.primary_key)\n line.errors.append(new_row)\n return False\n return True",
"def id_check(employee_id):\r\n# badge_pattern = re.compile('[A-Za-z]{2}-\\d{4}')\r\n# re.search(badge_pattern, employee_id)\r\n\r\n # if statement\r\n if not re.match('[A-Z]{2}-\\d{4}', employee_id):\r\n print(employee_id, 'is not a valid ID.')",
"def vet_pdb_id(pdbid):\n if len(pdbid) < 4 or not \\\n pdbid.isalnum() or not \\\n re.match(r'^[0-9][A-Za-z0-9]{3}$', pdbid):\n return False\n return True",
"def is_valid_gender_number(gender_number: int) -> bool:\n if gender_number in range(1, 7):\n return True\n else:\n return False",
"def is_valid_gender_number(gender_number: int) -> bool:\n if gender_number in range(1, 7):\n return True\n return False",
"def validate_issue_year(passport: map) -> bool:\n if passport.get('iyr'):\n if int(passport['iyr']) >= 2010 and int(passport['iyr']) <= 2020:\n return True\n\n return False",
"def is_valid_passport_id(passport_id: int) -> bool:\n return len(passport_id) == 9 and passport_id.isnumeric()",
"def validate_account_number(num, should_exist=True):\n if len(num) != 8:\n return False\n elif num[0] == '0':\n return False\n else:\n if should_exist:\n return account_number_exists(num)\n else:\n return not account_number_exists(num)",
"def is_valid_year(year_number):\n\n if (type(year_number) == int) and (START_YEAR <= year_number <= FINAL_YEAR):\n return True\n\n return False",
"def _validate(cls, pid_value):\n blop = re.compile('^[-\\w]+$')\n if not bool(blop.match(pid_value)):\n raise ValidationError(\n 'The ID should contain only letters with numbers or dashes.',\n field_name='id',\n )",
"def is_valid(self):\n return phonenumbers.is_valid_number(self)",
"def is_valid_control_number(id_code: str) -> bool:\n sum = 1 * int(id_code[:1]) + 2 * int(id_code[1:2]) + 3 * int(id_code[2:3]) + 4 * int(id_code[3:4]) + 5 * \\\n int(id_code[4:5]) + 6 * int(id_code[5:6]) + 7 * int(id_code[6:7]) + 8 * int(id_code[7:8]) + 9 *\\\n int(id_code[8:9]) + 1 * int(id_code[9:10])\n control_number = sum % 11\n if int(control_number) == int(id_code[10:11]):\n return True\n elif int(control_number) == 10:\n sum = 3 * int(id_code[:1]) + 4 * int(id_code[1:2]) + 5 * int(id_code[2:3]) + 6 * int(id_code[3:4]) + 7 * \\\n int(id_code[4:5]) + 8 * int(id_code[5:6]) + 9 * int(id_code[6:7]) + 1 * int(id_code[7:8]) + 2 * \\\n int(id_code[8:9]) + 3 * int(id_code[9:10])\n control_number = sum % 11\n if control_number == int(id_code[10:11]):\n return True\n elif control_number == 10:\n if int(id_code[10:11]) == 0:\n return True\n else:\n return False\n else:\n return False",
"def validate(self,data):\r\n for person in data:\r\n #check the format is a letter and 3 digit e.g A002 or a002\r\n \r\n if (re.match(r'[A-Z][0-9]{3}', (person[0]).lower())):\r\n print (person[0])\r\n else:\r\n print(person[0] + \" \" + 'is incorrect ID, '\r\n ' must contains a letter and 3 digits e.g a002')\r\n \r\n #check the format is either M/F/Male/Female\r\n \r\n if (person[1] == \"M\" or (person[1]).upper() == \"F\" or\r\n person[1] == \"Male\" or person[1] == \"Female\"):\r\n print (person[1])\r\n else:\r\n print(person[1] + \" \" + 'is incorrect Gender, '\r\n ' must either be M and Male or F and Female')\r\n \r\n #check age is valid entry and match with date\r\n \r\n if (re.match(r'[0-9]{2}', person[2]) and person[2] == self.valid_age(person[6])):\r\n print (person[2])\r\n elif (person[2] != self.valid_age(person[2])):\r\n print(\"Does not match with your birthday, invalid age\")\r\n else:\r\n print(person[2] + \" \" + 'age must be an integer')\r\n \r\n #check sales is 3 interger value\r\n if (re.match(r'[0-9]{3}', person[3])):\r\n return (person[3])\r\n else:\r\n print(person[3] + \" \" + 'is incorrect sales number, '\r\n 'must be a 2 interger number')\r\n \r\n #check BMI is either Normal / Overweight / Obesity or Underweight\r\n if (re.match(r'\\b(NORMAL|OVERWEIGHT|OBESITY|UNDERWEIGHT)\\b',(person[4]).upper())):\r\n print (person[4])\r\n else:\r\n print(person[4] + \" \" ' is incorrect BMI value, '\r\n 'must select from Normal, Overweight, Obesity or Underweight')\r\n \r\n #check Income is float\r\n\r\n if (re.match(r'[0-9]{2,3}', person[5])):\r\n print (person[5])\r\n else:\r\n print(person[5] + \" \" + 'is incorrect income, '\r\n 'must be a interger number') \r\n \r\n #check birthday\r\n \r\n if (self.valid_date(person[6]) and person[2] == self.valid_age(person[6]) ):\r\n print (person[6])\r\n else:\r\n print(person[2] + \" \" + 'is incorrect date format, '\r\n 'must contain DD-MM-YYYY or DD-MM-YY and seperated by -')\r\n \r\n return readFile",
"def test_date_of_birth_good_values(self):\n for input_val, output_val in self.known_values:\n self.line._parse_date_of_birth(input_val)\n self.assertEqual(output_val, self.line.date_of_birth)",
"def test_good_values_for_validate_guid(good_value):\n bcvalidators.validate_guid(good_value)",
"def verify_valid_num(self, user_num):\r\n if not self.range_between_0_and_9(user_num):\r\n print(\"\\033[1;31mJust what do you think you're doing, Dave? Choose a number between 0 and 8\\033[0m\")\r\n return False\r\n\r\n return True",
"def validate_identifier(identifier: str) -> bool:\n if identifier[:2] == 'NR':\n return True\n\n if len(identifier) < 9:\n return False\n\n try:\n d = int(identifier[-7:])\n if d == 0:\n return False\n except ValueError:\n return False\n # TODO This is not correct for entity types that are not Coops\n if identifier[:-7] not in ('CP', 'XCP', 'BC'):\n return False\n\n return True",
"def is_valid_bid(klass, bid):\n return bid and re.match(\"^\\d{3,5}$\", bid.strip())"
] | [
"0.7669592",
"0.743413",
"0.7362",
"0.7126994",
"0.7036078",
"0.6768026",
"0.67309767",
"0.6512103",
"0.62461853",
"0.6227174",
"0.6126266",
"0.6124072",
"0.6095114",
"0.60267437",
"0.6023427",
"0.5990033",
"0.59776306",
"0.5961712",
"0.5954568",
"0.5948722",
"0.59220415",
"0.59125686",
"0.58989924",
"0.5838958",
"0.58367103",
"0.5835581",
"0.5825121",
"0.5820996",
"0.58057576",
"0.5796009"
] | 0.7672838 | 0 |
Check if given value is correct for control number in ID code. Use algorithm made for creating this number. | def is_valid_control_number(id_code: str) -> bool:
check_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1]
check_sum = 0
for i in range(10):
check_sum += int(id_code[i]) * check_numbers[i]
check_sum = check_sum % 11
if check_sum == 10:
check_numbers = [3, 4, 5, 6, 7, 8, 9, 1, 2, 3]
check_sum = 0
for i in range(10):
check_sum += int(id_code[i]) * check_numbers[i]
check_sum = check_sum % 11
if check_sum == int(id_code[-1]):
return True
return False | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def is_valid_control_number(id_code: str) -> bool:\n sum = 1 * int(id_code[:1]) + 2 * int(id_code[1:2]) + 3 * int(id_code[2:3]) + 4 * int(id_code[3:4]) + 5 * \\\n int(id_code[4:5]) + 6 * int(id_code[5:6]) + 7 * int(id_code[6:7]) + 8 * int(id_code[7:8]) + 9 *\\\n int(id_code[8:9]) + 1 * int(id_code[9:10])\n control_number = sum % 11\n if int(control_number) == int(id_code[10:11]):\n return True\n elif int(control_number) == 10:\n sum = 3 * int(id_code[:1]) + 4 * int(id_code[1:2]) + 5 * int(id_code[2:3]) + 6 * int(id_code[3:4]) + 7 * \\\n int(id_code[4:5]) + 8 * int(id_code[5:6]) + 9 * int(id_code[6:7]) + 1 * int(id_code[7:8]) + 2 * \\\n int(id_code[8:9]) + 3 * int(id_code[9:10])\n control_number = sum % 11\n if control_number == int(id_code[10:11]):\n return True\n elif control_number == 10:\n if int(id_code[10:11]) == 0:\n return True\n else:\n return False\n else:\n return False",
"def is_id_valid(id_code: str) -> bool:\n if is_valid_gender_number(int(id_code[0:1])):\n if is_valid_year_number(int(id_code[1:3])):\n if is_valid_month_number(int(id_code[3:5])):\n if is_valid_day_number(int(id_code[0:1]), int(id_code[1:3]), int(id_code[3:5]), int(id_code[5:7])):\n if is_valid_birth_number(int(float(id_code[7:10]))):\n if is_valid_control_number(id_code):\n return True\n else:\n return False\n else:\n return False\n\n else:\n return False\n else:\n return False\n else:\n return False",
"def isValid(t_id):\n\tstr_id=str(t_id).strip()\n\treturn str_id.isdigit()",
"def _validate_bank_operation_code_23B(self, val):\n return val",
"def check_value(self, value):",
"def is_id_valid(id_code: str) -> bool:\n if id_code.isdigit():\n if len(str(id_code)) == 11:\n id_code = str(id_code)\n gender_number = int(id_code[0:1])\n day = int(id_code[5:7])\n month = int(id_code[3:5])\n year = id_code[1:3]\n birth_number = id_code[7:10]\n if is_valid_gender_number(gender_number) \\\n and is_valid_year_number(int(year)) \\\n and is_valid_month_number(int(month)) \\\n and is_valid_day_number(gender_number, int(year), int(month), int(day)) \\\n and is_valid_birth_number(int(birth_number)) \\\n and is_valid_control_number(str(id_code)):\n return True\n return False\n return False\n return False",
"def checkdigit(code):\n check = sum((i+1)*int(code[i]) for i in range(9)) % 11\n return 'X' if check == 10 else str(check)",
"def check_for_int(check):",
"def validate_CPF(value):\n\t\tif value in EMPTY_VALUES:\n\t\t\treturn u''\n\t\tif not value.isdigit():\n\t\t\tvalue = re.sub(\"[-\\.]\", \"\", value)\n\t\torig_value = value[:]\n\t\ttry:\n\t\t\tint(value)\n\t\texcept ValueError:\n\t\t\treturn False\n\t\tif len(value) != 11 or value == \"00000000000\" or value == \"11111111111\" or value == \"22222222222\" or value == \"33333333333\" or \\\n\t\t\tvalue == \"44444444444\" or value == \"55555555555\" or value == \"66666666666\" or value == \"77777777777\" or \\\n\t\t\tvalue == \"88888888888\" or value == \"99999999999\":\n\t\t\t\n\t\t\treturn False\n\n\t\torig_dv = value[-2:]\n\n\t\tnew_1dv = sum([i * int(value[idx]) for idx, i in enumerate(range(10, 1, -1))])\n\t\tnew_1dv = DV_maker(new_1dv % 11)\n\t\tvalue = value[:-2] + str(new_1dv) + value[-1]\n\t\tnew_2dv = sum([i * int(value[idx]) for idx, i in enumerate(range(11, 1, -1))])\n\t\tnew_2dv = DV_maker(new_2dv % 11)\n\t\tvalue = value[:-1] + str(new_2dv)\n\t\tif value[-2:] != orig_dv:\n\t\t\treturn False \n\n\n\t\treturn orig_value",
"def validate_pin_input(value):\n try:\n int(value)\n return f\"D{value}\"\n except ValueError:\n return value.upper()",
"def is_sedol(value):\n return re.match(r'^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}\\d$', value)",
"def is_isni(val):\n val = val.replace(\"-\", \"\").replace(\" \", \"\").upper()\n if len(val) != 16:\n return False\n try:\n r = 0\n for x in val[:-1]:\n r = (r + int(x)) * 2\n ck = (12 - r % 11) % 11\n return ck == _convert_x_to_10(val[-1])\n except ValueError:\n return False",
"def value_error(number):\n try:\n nbr = int(number)\n except ValueError:\n print(\"You can't sum letters, please write a number\")\n verification = False\n else:\n verification = True\n return verification",
"def _validate_details_of_charges_71A(self, val):\n return val",
"def check_digit(raw_code):\n s = sum(code(char) * 2**index for index, char in enumerate(raw_code))\n return s % 11 % 10",
"def check_digit(tracking_number):\n check_digit = 10 - ((sum(itertools.starmap(operator.mul, zip(itertools.cycle((3, 1)), map(int, str(tracking_number))))) + 1) % 10)\n if check_digit == 10:\n check_digit = 0\n return check_digit",
"def validate(number):\n number = compact(number)\n if not isdigits(number):\n raise InvalidFormat()\n if len(number) != 16:\n raise InvalidLength()\n if _calc_checksum(number) != 0:\n raise InvalidChecksum()\n i = info(number)\n if 'bank' not in i or 'branch' not in i:\n raise InvalidComponent()\n return number",
"def validate_pluginid(value):\n valid = string.ascii_letters + string.digits + '.'\n return all(c in valid for c in value)",
"def valid_checkdigit(ccnum):\n\n sum = 0\n num_digits = len(ccnum)\n oddeven = num_digits & 1\n\n for count in range(0, num_digits):\n digit = int(ccnum[count])\n\n if not ((count & 1) ^ oddeven):\n digit = digit * 2\n if digit > 9:\n digit = digit - 9\n\n sum = sum + digit\n\n return ((sum % 10) == 0)",
"def _validate_instructed_amount_33B(self, val):\n return val",
"def _validate_instruction_code_23E(self, val):\n validate_instruction_code(val)\n return val",
"def _check_value(self):\n value = str(self._value_field.toPlainText())\n if value=='': return True\n ACCEPTABLES_CHARS = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '0',\n '.', ',', ';', ' ', '\\n', '-')\n\n for char in value:\n if not char in ACCEPTABLES_CHARS:\n return False\n if Variable.is_acceptable_arg(value):\n rows, columns = np.matrix(value).shape\n return 1 <= rows <= 4 and 1 <= columns <= 4\n else:\n return False",
"def valid_barcode(s):\n # implement this function!\n odd_digits = 0\n even_digits = 0\n result = 0\n for i in range(len(s) - 1):\n if i % 2 == 0:\n odd_digits += int(s[i])\n else:\n even_digits += int(s[i])\n result = (3 * odd_digits + even_digits) % 10\n if result != 0:\n result = 10 - result\n\n try:\n if int(s[-1]) == result and len(s) == 12:\n return True\n else:\n return False\n except IndexError:\n return False",
"def test_good_values_for_validate_guid(good_value):\n bcvalidators.validate_guid(good_value)",
"def istele(number):\n if number[:3] == '140':\n return True\n return False",
"def validate(code):\n if not code.isdigit():\n raise IllegalCharacterError('[0-9]{%d}' % UPCA.digits)\n\n if len(code) != UPCA.digits:\n raise ValueError('Bar code %s requires %d digits' % (code, UPCA.digits))\n\n checksum = UPCA.calculate_checksum(code)\n if checksum != int(code[-1]):\n raise ValueError('Checksum character mismatch %s != %s' % (checksum, code[-1]))",
"def is_istc(val):\n val = val.replace(\"-\", \"\").replace(\" \", \"\").upper()\n if len(val) != 16:\n return False\n sequence = [11, 9, 3, 1]\n try:\n r = sum([int(x, 16) * sequence[i % 4] for i, x in enumerate(val[:-1])])\n ck = hex(r % 16)[2:].upper()\n return ck == val[-1]\n except ValueError:\n return False",
"def _validate(cls, pid_value):\n blop = re.compile('^[-\\w]+$')\n if not bool(blop.match(pid_value)):\n raise ValidationError(\n 'The ID should contain only letters with numbers or dashes.',\n field_name='id',\n )",
"def is_register(value):\n if REGISTER_0 <= value <= REGISTER_7:\n return True\n return False",
"def is_valid(self, value):\r\n pass"
] | [
"0.81619936",
"0.66532516",
"0.64845574",
"0.63289493",
"0.6275811",
"0.6214823",
"0.615628",
"0.6125417",
"0.6085542",
"0.60341203",
"0.6012941",
"0.6002289",
"0.5977511",
"0.59405285",
"0.59047055",
"0.5871564",
"0.58661366",
"0.58425516",
"0.5841846",
"0.5836206",
"0.5824502",
"0.5818448",
"0.58107626",
"0.581048",
"0.5802753",
"0.5792634",
"0.5787917",
"0.577792",
"0.577584",
"0.57733333"
] | 0.7822165 | 1 |
Get possible information about the person. Use given ID code and return a short message. Follow the template This is a born on in . | def get_data_from_id(id_code: str) -> str:
if is_id_valid(str(id_code)):
gender_number = int(id_code[0:1])
day = id_code[5:7]
month = id_code[3:5]
year = id_code[1:3]
gender = get_gender(gender_number)
full_year = str(get_full_year(gender_number, int(year)))
location = get_birth_place(int(id_code[7:10]))
return "This is a " + gender + " born on " + day + "." + month + "." + full_year + " in " + location + "."
return "Given invalid ID code!" | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_data_from_id(id_code: str) -> str:\n if is_valid_control_number(id_code):\n return f\"This is a {get_gender(int(id_code[0:1]))} born on {id_code[5:7]}.{id_code[3:5]}.\" \\\n f\"{get_full_year(int(id_code[0:1]), int(id_code[1:3]))} in {get_birth_place(int(id_code[7:10]))}\"\n else:\n return \"Given invalid ID code!\"",
"def who(id, client, name):\r\n exists = person.locate(id)\r\n\r\n if not exists:\r\n person.create(id, name)\r\n client.send_message(id, 'Hello ' + name + '''!\r\nI am your Journal Buddy :) My purpose is to help you manage your productivity!\r\n\r\nYou can:\r\n - Set up habits\r\n - Schedule events\r\n - Create a task pool\r\n - Set reminders\r\n - Add notes - tell me things you don’t want to forget! May it be a quote, or a movie you liked\r\n\r\nEvery month we can choose which tasks you would like to complete in the month ahead!\r\nEvery week I will help you set goals in terms of tasks and habits for the week ahead!\r\n\r\nThe more we get to know each other the more I will be able to help! Providing weekly analytics and suggestions for future performance. Tell me how you feel throughout your tasks, habits and events and I will share with you what I think will work best.\r\n\r\nType /setup to begin!''')\r\n\r\n users[id] = {\"last\": \"new user\"}\r\n elif not (users.keys().__contains__(id)):\r\n users[id] = {\"last\": \"welcome back\"}",
"def get_person_name(self, person_id):\n res = requests.get(url=\"https://api.ciscospark.com/v1/people/{}\".format(person_id),\n headers=self.headers)\n\n try:\n class person(object):\n firstName = res.json()['firstName']\n lastName = res.json()['lastName']\n\n return person\n except AttributeError as e:\n print(res.text)\n return None",
"def who_am_i():\n return {'name': 'Jonathan Martinez', 'id': '201095569', 'email': '[email protected]'}",
"def get_person(request, person_id):\n person = get_object_or_404(Person, pk=person_id)\n\n\n return render_to_response('people/person_detail.html', {\n 'person': person,\n })",
"def info(self):\n return f\"{self.get_first_name}, {self.get_last_name}. {self.get_age} y.o. #{self.get_id_number}\"",
"def showInfo(p,personDict):\n info1 = personDict['EnterpriseID'][p[0]]\n info2 = personDict['EnterpriseID'][p[1]]\n print (\"Person A:\",info1)\n print (\"Person B:\",info2)",
"def get(self,id):\r\n person = get_one(id=id)\r\n if not person:\r\n api.abort(404)\r\n else:\r\n return person",
"async def get_information():\n return {\n \"message\": f\"You are the Genome Researcher. \"\n f\"You are meddling with Coronavirus Sars-Cov-2 RNA... \"\n f\"Try to change the RNA at your disposal to uncover as many medical breakthroughs as possible. \"\n f\"use GET /sample to see the original RNA strand \"\n f\"use COPY /sample to create exact duplicate of original to perform experiments. \"\n f\"Try to change the RNA at your disposal to uncover as many medical breakthroughs as possible. \"\n f\"Good luck researcher. \"\n f\"Our souls fates' depend on you! \"\n }",
"async def lookup(self, ctx, user_id: int):\n if user_id <= 0:\n return await ctx.send(\n \"I can already tell you this guy does not exist. \"\n \"Try using an actual User ID.\"\n )\n elif len(str(user_id)) == 4:\n return await ctx.send(\n \"Did you mistake the User ID for their discriminator? For reference: \\n\"\n \"This is my discrim: `#{discrim}`.\\n\"\n \"This is my User ID: `{id}`\".format(\n discrim=ctx.me.discriminator, id=ctx.me.id\n )\n )\n\n user = await self.bot.fetch_user(user_id)\n if not user:\n return await ctx.send(\"Could not find this user.\")\n\n info_embed = discord.Embed(\n title=str(user) + \"'s info\",\n color=discord.Color.blurple(),\n )\n\n if user.bot:\n info_embed.add_field(name=\"This User is a Bot! :robot:\", value=\"\\u200b\")\n\n info_embed.set_thumbnail(url=user.avatar_url)\n info_embed.add_field(name=\"User ID\", value=user.id, inline=False)\n\n info_embed.add_field(\n name=\"Account created\",\n value=humanize.naturaldate(user.created_at),\n inline=False,\n )\n\n await ctx.send(embed=info_embed)",
"def get_person(self, id):\n try:\n person = Person.get(Person.id == id)\n data = model_to_dict(person)\n except DoesNotExist:\n response.status = 404\n data = \"Not found\"\n return dict(name='Person', data=data)",
"def info(self, id):",
"def get(self,id):\r\n person = get_one_by_persons_id(id=id)\r\n if not person:\r\n api.abort(404)\r\n else:\r\n return person",
"async def info(self,ctx,*,person:discord.Member = None):\n\n if not person:\n guild = len(self.bot.guilds)\n member = len(set(self.bot.get_all_members()))\n app = await self.bot.application_info()\n msg = \"Name:{}\".format(self.bot.user)\n if ctx.message.guild.me.nick:\n msg += \"\\nNickname:{}\".format(ctx.message.guild.me.nick)\n msg += \"\\nCreator: {}\".format(app.owner)\n msg += \"\\nServer:{}\\nMembers:{}\".format(guild,member)\n link = \"If you want to invite this bot to your server, you can check it out here <http://nurevam.site>!\"\n return await self.bot.say(ctx,content = \"```xl\\n{}\\n```\\n{}\\n\".format(msg,link))\n else:\n e = discord.Embed()\n e.title = \"{} - {}\".format(person,person.id)\n e.set_thumbnail(url = person.avatar_url)\n e.add_field(name = \"Created at\", value=\"{} - ({})\".format(person.created_at,self.get_time_delta(person.created_at)),inline=False)\n e.add_field(name = \"Joined at\", value=\"{} - ({})\".format(person.joined_at,self.get_time_delta(person.joined_at)),inline=False)\n e.add_field(name = \"Total Roles\", value=str(len(person.roles)),inline=False)\n\n if person.colour.value:\n e.colour = person.color\n await self.bot.say(ctx,embed = e)",
"def test_get_info_person_good_id_db(self):\n response = self.client.get('/api/status?id=15f4a3d4-0211-479a-a5c6-c85e56bd4d88', format='json')\n self.assertEqual(response.status_code, 200)",
"def display_person(person):\n name = person['name']\n followers = person['follower_count']\n description = person['description']\n country = person['country']\n print(f'{name}, a(n) {description}, from {country}.')\n return followers",
"def select_person():\r\n body = request.get_json()\r\n\r\n try:\r\n SELECT_PERSON_SCHEMA.validate(body)\r\n except SchemaError as err:\r\n raise ServiceBodyError(str(err))\r\n\r\n with sqlite_client:\r\n message = get_person(sqlite_client, body.get('id'))\r\n\r\n return jsonify({'name': message[0][1], 'cpf': message[0][2]})",
"def get_author_info(self, author: str):\n for writer_word in self._writer_words:\n data = json.loads(requests.get(WIKIDATA_SEARCH + \"&srsearch=\" + author + \" \" + writer_word).text)\n pages = data.get(\"query\").get(\"search\")\n if len(pages) >= 1:\n pageid = pages[0].get(\"title\")\n author_details = self._reference.author_map.get(author)\n if author_details:\n return author_details\n if pageid == -1:\n continue\n\n else:\n response = requests.get(WIKIDATA_PARSE + pageid + \".json\")\n data = json.loads(response.text)\n if author.lower() not in data.get(\"entities\").get(pageid).get(\"labels\").get(\"en\").get(\"value\").lower():\n continue\n else:\n try:\n id = data.get(\"entities\").get(pageid).get(\"claims\").get(\"P31\")[0].get(\"mainsnak\").get(\"datavalue\").get(\"value\").get(\"id\")\n if str(id) != \"Q5\": # the id for human\n continue\n except IndexError:\n continue\n properties = data.get(\"entities\").get(pageid).get(\"claims\")\n author_details = {\"id\": pageid, \"gender\": self.get_gender(properties)}\n country_details = self.get_country(properties)\n author_details[\"country\"] = country_details\n self._reference.author_map[author] = author_details\n return author_details\n return {\"id\": \"Unknown\", \"gender\": \"Unknown\", \"country\": [{\"name\": \"Unknown\", \"region\": \"Unknown\"}]}",
"def get_personal_info(self):\n self.get(\"INFO\",\"GetPersonalInfo\")\n response = self.send()\n return response",
"def current_person(self):\n d = self.people_table_data[self.row_i]\n\n # \"fullname\", \"lunaid\", \"age\", \"dob\", \"sex\", \"lastvisit\", \"maxdrop\", \"studies\",\n info = dict(zip(self.person_columns, d))\n info[\"pid\"] = d[8] # pid not shown\n\n # dont get fname and lname from table\n # could word split, but need to be accurate at least for edit module\n if self.sql:\n res = self.sql.query.get_name(pid=info[\"pid\"])\n info[\"fname\"] = res[0][0]\n info[\"lname\"] = res[0][1]\n return info\n # # main model\n # self.checkin_button.setEnabled(False)\n # print('people table: subject selected: %s' % d[8])\n # self.render_person(pid=d[8], fullname=d[0], age=d[2],\n # sex=d[4], lunaid=d[1])\n # self.render_schedule(ScheduleFrom.PERSON)",
"def get_donor_info(self):\n name = self.get_donor()\n if name in self.all_donors:\n person = self.r.hgetall(name)\n print(f\"Person: {name}\")\n for key, value in person.items():\n print(f\"{key}: {value}\")\n else:\n print(\"Name not in database.\")",
"def get_person(self, id):\n PERSON = \"\"\"SELECT name FROM Person\n WHERE id = %s\"\"\"\n\n ret = None\n try:\n self.db_cursor.execute(\"\"\"SELECT name, id FROM Person WHERE id = %s\"\"\", (id,))\n self.db_cursor.execute(PERSON, (id,))\n self.db_connection.commit()\n p_attribs = self.db_cursor.fetchall()\n ret = Person()\n ret.name = p_attribs[0][0]\n ret.id = id\n\n except:\n logging.warning(\"DBAdapter: Error- cannot retrieve person: \" + str(id))\n return None\n\n return ret",
"def person_id_for_name(name):\n person_ids = list(names.get(name.lower(), set()))\n if len(person_ids) == 0:\n return None\n elif len(person_ids) > 1:\n print(f\"Which '{name}'?\")\n for person_id in person_ids:\n person = people[person_id]\n name = person[\"name\"]\n birth = person[\"birth\"]\n print(f\"ID: {person_id}, Name: {name}, Birth: {birth}\")\n try:\n person_id = input(\"Intended Person ID: \")\n if person_id in person_ids:\n return person_id\n except ValueError:\n pass\n return None\n else:\n return person_ids[0]",
"def person_id_for_name(name):\n person_ids = list(names.get(name.lower(), set()))\n if len(person_ids) == 0:\n return None\n elif len(person_ids) > 1:\n print(f\"Which '{name}'?\")\n for person_id in person_ids:\n person = people[person_id]\n name = person[\"name\"]\n birth = person[\"birth\"]\n print(f\"ID: {person_id}, Name: {name}, Birth: {birth}\")\n try:\n person_id = input(\"Intended Person ID: \")\n if person_id in person_ids:\n return person_id\n except ValueError:\n pass\n return None\n else:\n return person_ids[0]",
"async def info(self, ctx):\n\t\tembed = discord.Embed(\n\t\t\tdescription=\"Created By Seperoph#1399 and AkaBaka#4654\",\n\t\t\tcolor=config[\"success\"]\n\t\t)\n\t\tembed.set_author(\n\t\t\tname=\"Bot Information\"\n\t\t)\n\t\tembed.add_field(\n\t\t\tname=\"Head Programmers:\",\n\t\t\tvalue=\"Seperoph#1399 and AkaBaka#4654\",\n\t\t\tinline=True\n\t\t)\n\t\tembed.add_field(\n\t\t\tname=\"Python Version:\",\n\t\t\tvalue=f\"{platform.python_version()}\",\n\t\t\tinline=True\n\t\t)\n\t\tawait ctx.respond(embed=embed)",
"def ask_info_player(self) -> str:\n\n print(\"Enter first name : \")\n while True:\n first_name = input()\n if check.check_input_string_special(first_name) is True:\n if check.check_input_string_len(first_name) is True:\n if check.check_input_string_integer(first_name) is True:\n break\n\n print(\"Enter last name : \")\n while True:\n last_name = input()\n if check.check_input_string_special(last_name) is True:\n if check.check_input_string_len(last_name) is True:\n if check.check_input_string_integer(last_name) is True:\n break\n\n print(\"Enter date of birth with this format YEAR-MONTH-DAY : \")\n birthday = check.check_date_input()\n\n print(\n \"Enter a number for choose the gender : \\n\"\n \"1 - Man \\n\"\n \"2 - Women\"\n )\n genre = check.request_selection_with_number(\"Man\", \"Women\", \"none\")\n\n print(\"\\n The player {} {}, {}, birth on {} has been added to the database !\".format(\n first_name,\n last_name,\n genre,\n birthday))\n\n return first_name, last_name, birthday, genre",
"def __str__(self):\n return \"Person: {}, {},{}\".format(self.get_id(),self.get_creation_date(),self.get_name())",
"def info():\n # -------- Task 1 -------------------------\n # Please complete the following information\n\n return {\"agent name\": \"?\", # COMPLETE HERE\n \"student name\": [\"?\"], # COMPLETE HERE\n \"student number\": [\"?\"]} # COMPLETE HERE",
"def get_info(self):\n if self.own_home:\n return print(f'Hi! My name is {self.name}, I\\'m {self.age}. Currently I have {self.own_home} house')\n return print(f'Hi! My name is {self.name}, I\\'m {self.age}. I don\\'t have any home now!')",
"def info(self):\n if str.__str__(self) in UID_dictionary:\n return UID_dictionary[self][2]\n\n return ''"
] | [
"0.67674786",
"0.63826096",
"0.62162644",
"0.6213492",
"0.6179912",
"0.61221534",
"0.61090523",
"0.6090255",
"0.6041029",
"0.5957511",
"0.5955492",
"0.59419584",
"0.5927061",
"0.59135956",
"0.5903609",
"0.5898696",
"0.5882936",
"0.5875469",
"0.5861774",
"0.57998204",
"0.5778792",
"0.57298106",
"0.5708797",
"0.5708797",
"0.5687516",
"0.5672735",
"0.564384",
"0.56349194",
"0.56127083",
"0.56089276"
] | 0.6758885 | 1 |
Check if given ID code is valid and return the result (True or False). Complete other functions before starting to code this one. You should use the functions you wrote before in this function. | def is_id_valid(id_code: str) -> bool:
if id_code.isdigit():
if len(str(id_code)) == 11:
id_code = str(id_code)
gender_number = int(id_code[0:1])
day = int(id_code[5:7])
month = int(id_code[3:5])
year = id_code[1:3]
birth_number = id_code[7:10]
if is_valid_gender_number(gender_number) \
and is_valid_year_number(int(year)) \
and is_valid_month_number(int(month)) \
and is_valid_day_number(gender_number, int(year), int(month), int(day)) \
and is_valid_birth_number(int(birth_number)) \
and is_valid_control_number(str(id_code)):
return True
return False
return False
return False | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def is_id_valid(id_code: str) -> bool:\n if is_valid_gender_number(int(id_code[0:1])):\n if is_valid_year_number(int(id_code[1:3])):\n if is_valid_month_number(int(id_code[3:5])):\n if is_valid_day_number(int(id_code[0:1]), int(id_code[1:3]), int(id_code[3:5]), int(id_code[5:7])):\n if is_valid_birth_number(int(float(id_code[7:10]))):\n if is_valid_control_number(id_code):\n return True\n else:\n return False\n else:\n return False\n\n else:\n return False\n else:\n return False\n else:\n return False",
"def verify_idcode(device, idcode, idcode_opcode):\n idcode_read = read_idcode_opcode(device, idcode_opcode)\n for i in range(len(idcode)):\n if idcode[i] == \"X\":\n continue # ignore 'don't cares'\n elif idcode_read[i] != idcode[i]:\n print(\"IDCODE read does not match real IDCODE from BSDL file\")\n print(f\"\\tidcode_read[{i}]: {idcode_read[i]}, idcode[{i}]: {idcode[i]}\")\n return False\n\n return True",
"def is_valid_control_number(id_code: str) -> bool:\n sum = 1 * int(id_code[:1]) + 2 * int(id_code[1:2]) + 3 * int(id_code[2:3]) + 4 * int(id_code[3:4]) + 5 * \\\n int(id_code[4:5]) + 6 * int(id_code[5:6]) + 7 * int(id_code[6:7]) + 8 * int(id_code[7:8]) + 9 *\\\n int(id_code[8:9]) + 1 * int(id_code[9:10])\n control_number = sum % 11\n if int(control_number) == int(id_code[10:11]):\n return True\n elif int(control_number) == 10:\n sum = 3 * int(id_code[:1]) + 4 * int(id_code[1:2]) + 5 * int(id_code[2:3]) + 6 * int(id_code[3:4]) + 7 * \\\n int(id_code[4:5]) + 8 * int(id_code[5:6]) + 9 * int(id_code[6:7]) + 1 * int(id_code[7:8]) + 2 * \\\n int(id_code[8:9]) + 3 * int(id_code[9:10])\n control_number = sum % 11\n if control_number == int(id_code[10:11]):\n return True\n elif control_number == 10:\n if int(id_code[10:11]) == 0:\n return True\n else:\n return False\n else:\n return False",
"def is_valid_control_number(id_code: str) -> bool:\n check_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1]\n check_sum = 0\n for i in range(10):\n check_sum += int(id_code[i]) * check_numbers[i]\n check_sum = check_sum % 11\n if check_sum == 10:\n check_numbers = [3, 4, 5, 6, 7, 8, 9, 1, 2, 3]\n check_sum = 0\n for i in range(10):\n check_sum += int(id_code[i]) * check_numbers[i]\n check_sum = check_sum % 11\n if check_sum == int(id_code[-1]):\n return True\n return False",
"def isValid(t_id):\n\tstr_id=str(t_id).strip()\n\treturn str_id.isdigit()",
"def id_check(employee_id):\r\n# badge_pattern = re.compile('[A-Za-z]{2}-\\d{4}')\r\n# re.search(badge_pattern, employee_id)\r\n\r\n # if statement\r\n if not re.match('[A-Z]{2}-\\d{4}', employee_id):\r\n print(employee_id, 'is not a valid ID.')",
"def check_code(self, code):\n\n try:\n # Check if the code is valid\n voucher = Voucher.objects.get(code=code)\n\n # Check if the valid code in not completely redeemed\n if voucher.still_valid():\n message = \"Voucher code is valid, your discount = %s\" \\\n % voucher.get_discount_value()\n valid = True\n voucher.redeem_code()\n voucher.save()\n else:\n message = \"Voucher code has been redeemed.\"\n valid = False\n\n except Voucher.DoesNotExist as err:\n message = \"Voucher code is invalid\"\n valid = False\n\n return {'valid': valid, 'message': message}",
"def checkValidId(self, id, prep_id = False):\n new_id = unquote(id)\n if prep_id: new_id = self.prepId(id)\n try:\n globalCheckValidId(self, new_id)\n return True\n except Exception:\n return str(sys.exc_info()[1])",
"def validate_individual_identifiers(identifier: str, cpf: bool = True) -> bool:\n identifier = re.sub(r\"\\-|\\.|/\", \"\", identifier)\n dv = identifier[:-2]\n\n CPF_WEIGHTS = (11, 10, 9, 8, 7, 6, 5, 4, 3, 2)\n CNPJ_WEIGHTS = (6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2)\n\n if cpf:\n check = calculate_id_digit(numbers=dv, weights=CPF_WEIGHTS[1:])\n check = calculate_id_digit(numbers=check, weights=CPF_WEIGHTS)\n else:\n check = calculate_id_digit(numbers=dv, weights=CNPJ_WEIGHTS[1:])\n check = calculate_id_digit(numbers=check, weights=CNPJ_WEIGHTS)\n\n return identifier == check",
"def check_code(item_code):\r\n # RA matches\r\n if re.match(r'^MCRNC[0-9]{4}\\.T$', item_code):\r\n return True\r\n\r\n if re.match(r'^RAN[0-9]{3,4}(\\.[0-9])?C?(\\.T)?$', item_code):\r\n return True\r\n\r\n if re.match(r'^RAS[0-9]{5}$', item_code):\r\n return True\r\n\r\n if re.match(r'^RNC[0-9]{4}\\.T$', item_code):\r\n return True\r\n\r\n if re.match(r'^RU[0-9]{5}(\\.T)?$', item_code):\r\n return True\r\n\r\n # Feature ID (RAN) matches\r\n if re.match(r'^RAN[0-9]{2,5}$', item_code):\r\n return True\r\n\r\n if re.match(r'^(?P<code>RAN[1,2](\\.[0-9]{3,4}))$', item_code):\r\n return True\r\n\r\n return False",
"def identify_id(id: str) -> bool:\n return validate_handle(id)",
"def check_id(self, id):",
"def pdb_id_valid(pdb_id, filename, user_rand):\n pdb_file_name = SimulationForm0_LoadPdb.download_pdb(pdb_id, filename, user_rand)\n return SimulationForm0_LoadPdb.pdb_file_valid(pdb_file_name, user_rand)",
"def validate_identifier(identifier: str) -> bool:\n if identifier[:2] == 'NR':\n return True\n\n if len(identifier) < 9:\n return False\n\n try:\n d = int(identifier[-7:])\n if d == 0:\n return False\n except ValueError:\n return False\n # TODO This is not correct for entity types that are not Coops\n if identifier[:-7] not in ('CP', 'XCP', 'BC'):\n return False\n\n return True",
"def verify(self, code) -> bool:\n totp = self.__initialize_totp()\n return totp.verify(code)",
"async def check(self, code):\n await self.bot.reply(self.bot.check_code(code))",
"def member_id_check(member_id):\n try:\n global mem_num\n mem_num=int(member_id)\n if 1000<=mem_num and 9999>=mem_num:\n member_id_check.mID=\"Accepted\"\n else:\n member_id_check.mID=\"Member number not recognised\"\n except ValueError:\n member_id_check.mID=\"Member number not valid\"\n return member_id_check.mID",
"def is_code_valid_checksum(processed_code):\n\n if processed_code.isnumeric():\n list_of_digits = [int(digit) for digit in processed_code]\n else:\n converted_digits = convert_code_to_decimal(processed_code)\n list_of_digits = [int(digit) for digit in converted_digits]\n\n return sum(list_of_digits) > 0 and get_calculated_checksum(list_of_digits) % 11 == 0",
"def _is_validation(video_id):\n hasher = md5()\n hasher.update(bytes(video_id, 'utf-8'))\n first = hasher.hexdigest()[0]\n return first in ['0', '1']",
"def test_uidvalidity(self):\n d = self._examineOrSelect()\n self._response(b'* OK [UIDVALIDITY 12345] UIDs valid')\n self.assertEqual(\n self.successResultOf(d),\n {'READ-WRITE': False, 'UIDVALIDITY': 12345})",
"def checkCode():\n code = {'code': request.json['code'], 'phone': request.json['phone']}\n # if code and phone exist authorize user\n user = models.User.query.filter_by(code=code['code'], phone=code['phone']).first()\n value = \"User and SMS code don't exist\"\n if (user):\n user.is_verified = True\n value = \"Code exists!\"\n db.session.commit()\n resp = Response(json.dumps(value), status=200, mimetype='application/json')\n return resp",
"def book_id_check(book_num):\n try:\n global book_id\n book_id=int(book_num)\n if str(book_id) in valid_books.valid_book_ids:\n book_id_check.bID=\"Accepted\"\n global max_book_id\n max_book_id=len(valid_books.valid_book_ids)\n else:\n book_id_check.bID=\"Book ID not recognised\"\n except ValueError:\n book_id_check.bID=\"Book ID number not recognised\"\n return book_id_check.bID",
"def valida_digital(id, codigo):\n id = str(id)\n codigo = str(codigo)\n sql = \"SELECT digital from eleitores WHERE id_eleitor=\" + \\\n id + \" AND digital=\" + codigo\n estado = consulta.execute(sql)\n\n if(estado):\n return True\n else:\n return False",
"def validateID(id):\n\n if re.compile('[0-9]+').match(id) == None:\n output.completeOutputError(InvalidArgumentCount(descape =\"'%s' is not a valid Id. ID should be numeric with Length = '%s' \" \n\t\t\t% (id, lib.constants._ATTR_ID_LENGHT)))\n return -1\n else:\n # Check for the lenght \n counter = 0\n for char in id:\n counter += 1\n print counter , lib.constants._ATTR_ID_LENGHT\n if counter > lib.constants._ATTR_ID_LENGHT :\n output.completeOutputError(InvalidArgumentCount(descape =\"'%s' exceeded the given length i.e Max Length = '%s'\" % \n\t\t\t(id, lib.constants._ATTR_ID_LENGHT)))\n return -1\n else:\n return 0\n return 0",
"def is_not_used(code):\n return 0 <= code <= 999",
"def id_is_valid(gal_id, query_id, data):\n return not ((data.cam_idx[query_id] == data.cam_idx[gal_id]) and (data.labels[query_id] == data.labels[gal_id]))",
"def verify(self, phone, code, case):\n key = self.get_key(phone, case)\n tried_count = self.get_tried_count(key)\n if tried_count > self.tried_count:\n return False, 'tried too many times'\n else:\n if tried_count == 0:\n self.set_tried_count(key, 1)\n else:\n self.incr_count(key)\n saved_code = self.get_code(phone, case)\n verified = saved_code == code\n if verified:\n self.rm_code(phone, case)\n return verified, None\n else:\n return verified, '%s code verify failed' % case",
"def validate_code(self, client_id, code, client, request, *args, **kwargs):\n client = client or self._clientgetter(client_id)\n log.debug('Validate code for client %r and code %r', client.client_id, code)\n grant = self._grantgetter(client_id=client.client_id, code=code)\n if not grant:\n log.debug('Grant not found.')\n return False\n if hasattr(grant, 'expires') and datetime.datetime.utcnow() > grant.expires:\n log.debug('Grant is expired.')\n return False\n\n request.state = kwargs.get('state')\n request.user = grant.user\n request.scopes = grant.scopes\n return True",
"def validate_id(show_id: int,\n database_connection: mysql.connector.connect) -> bool:\n try:\n show_id = int(show_id)\n except ValueError:\n return False\n\n try:\n cursor = database_connection.cursor()\n query = \"SELECT showid from ww_shows where showid = %s;\"\n cursor.execute(query, (show_id,))\n result = cursor.fetchone()\n cursor.close()\n\n return bool(result)\n except ProgrammingError as err:\n raise ProgrammingError(\"Unable to query the database\") from err\n except DatabaseError as err:\n raise DatabaseError(\"Unexpected database error\") from err",
"def _is_valid_code(self, code):\r\n return code in COUNTRY_CODES"
] | [
"0.8171919",
"0.7009382",
"0.6951882",
"0.6747619",
"0.6607008",
"0.65469337",
"0.6338607",
"0.6239265",
"0.6221646",
"0.6215547",
"0.6168626",
"0.6168274",
"0.6131262",
"0.6069979",
"0.60399467",
"0.5967491",
"0.5936222",
"0.5933184",
"0.5914988",
"0.5883124",
"0.5848718",
"0.5846751",
"0.58447784",
"0.5831616",
"0.58242416",
"0.5820281",
"0.5811707",
"0.578506",
"0.5770929",
"0.5770795"
] | 0.78821236 | 1 |
Reads in a raw SANS datafile and returns a SansData | def read_sample(myfilestr="MAY06001.SA3_CM_D545"):
detdata,metadata=data.readNCNRData(myfilestr) #note that it should be None for the default
return SansData(detdata, metadata) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def read(self):\n # open the .SPE file\n with open(self._input_file_path, 'rb') as f:\n lines = f.readlines()\n # Create an empty dictionary for the metadata\n metadata_dictionary = {}\n\n # Search through the file for the needed metadata\n metadata_dictionary['date_acquired'] = re.search(b'date=\"(.*?)\"', lines[1])[1].decode('ANSI') \n metadata_dictionary['width'] = int(re.search(b'width=\"(.*?)\"', lines[1])[1])\n metadata_dictionary['height'] = int(re.search(b'height=\"(.*?)\"', lines[1])[1])\n metadata_dictionary['size'] = metadata_dictionary['width']*metadata_dictionary['height']\n metadata_dictionary['exposure_time'] = int(re.search(b'<ExposureTime type=\"Double\">(.*?)</ExposureTime>', lines[1])[1])\n metadata_dictionary['excitation_wavelength'] = float(re.search(b'laserLine=\"(.*?)\"',lines[1])[1])\n metadata_dictionary['center_wavelength'] = float(re.search(b'<CenterWavelength type=\"Double\">(.*?)</CenterWavelength>',lines[1])[1])\n metadata_dictionary['orientation'] = re.search(b'orientation=\"(.*?)\"',lines[1])[1].decode('ANSI')\n\n # Get the wavelength and intensity\n wavelength_string = re.search(b'<Wavelength xml:space=\"preserve\">(.*?)</Wavelength>',lines[1])[1].decode('utf-8')\n wavelength = np.array(wavelength_string.split(','), dtype=np.float64)\n\n f.seek(4100)\n intensity = np.fromfile(f,dtype=np.float32,count=metadata_dictionary['size'])\n\n raman_shift_wavenumbers = 1e7*(1/metadata_dictionary['excitation_wavelength'] - 1/wavelength)\n\n f.close()\n \n # create the sidpy dataset\n data_set = Dataset.from_array(intensity, name='Raman Spectra')\n\n data_set.data_type = 'spectrum'\n data_set.units = 'counts'\n data_set.quantity = 'Intensity'\n\n # set dimensions\n data_set.set_dimension(0, Dimension(raman_shift_wavenumbers, name='Raman Shift',\n units = 'cm-1',\n quantity='Raman shift',\n dimension_type='spectral'))\n data_set.set_dimension(1, Dimension(intensity, name='Intensity',\n units = 'counts',\n quantity='intensity',\n dimension_type='spectral')) \n\n data_set.metadata = metadata_dictionary\n\n return data_set",
"def readSanchez(file, planet, species, state):\n # open and read whole file\n f = open(file, 'rU')\n lines = f.readlines()\n f.close()\n\n # start reading planet files for specific mol and state \n parsing = False\n for i in np.arange(len(lines)):\n if lines[i].startswith(planet):\n parsing = True\n elif lines[i].startswith('\\t\\t\\t'):\n parsing = False\n if parsing and lines[i].startswith(species + '\\t' + state):\n data = lines[i].split()\n\n return data",
"def read_psd_from_txt(filename):\n data = loadtxt(filename)\n return data",
"def load_spe(filename):\n def read_at(data, pos, size, ntype):\n raw.seek(pos)\n return np.fromfile(raw, ntype, size)\n raw = open(filename, 'rb')\n xdim = np.int64(read_at(raw, 42, 1, np.int16)[0])\n ydim = np.int64(read_at(raw, 656, 1, np.int16)[0])\n arr = read_at(raw, 4100, xdim*ydim, np.uint16)\n arr = arr.reshape((ydim, xdim))\n print('data shape: {}'.format(np.shape(arr)))\n if np.shape(arr)[0] == 1:\n arr = arr[0]\n print('data shape: {}'.format(np.shape(arr)))\n return arr",
"def read(cls, filename, unit_wav=u.micron, unit_freq=u.Hz,\n unit_flux=u.erg / u.cm ** 2 / u.s, order='nu'):\n\n # Instantiate SED class\n sed = cls()\n\n # Assume that the filename may be missing the .gz extension\n if not os.path.exists(filename) and os.path.exists(filename + '.gz'):\n filename += \".gz\"\n\n # Open FILE file\n hdulist = fits.open(filename, memmap=False)\n\n # Extract model name\n sed.name = hdulist[0].header['MODEL']\n\n # Check if distance is specified in header, otherwise assume 1kpc\n if 'DISTANCE' in hdulist[0].header:\n sed.distance = hdulist[0].header['DISTANCE'] * u.cm\n else:\n log.debug(\"No distance found in SED file, assuming 1kpc\")\n sed.distance = 1. * u.kpc\n\n # Extract SED values\n wav = hdulist[1].data.field('WAVELENGTH') * parse_unit_safe(hdulist[1].columns[0].unit)\n nu = hdulist[1].data.field('FREQUENCY') * parse_unit_safe(hdulist[1].columns[1].unit)\n ap = hdulist[2].data.field('APERTURE') * parse_unit_safe(hdulist[2].columns[0].unit)\n flux = hdulist[3].data.field('TOTAL_FLUX') * parse_unit_safe(hdulist[3].columns[0].unit)\n error = hdulist[3].data.field('TOTAL_FLUX_ERR') * parse_unit_safe(hdulist[3].columns[1].unit)\n\n # Set SED attributes\n sed.apertures = ap\n\n # Convert wavelength and frequencies to requested units\n sed.wav = wav.to(unit_wav)\n sed.nu = nu.to(unit_freq)\n\n # Set fluxes\n sed.flux = convert_flux(nu, flux, unit_flux)\n sed.error = convert_flux(nu, error, unit_flux)\n\n # Set stellar flux (if present)\n if 'STELLAR_FLUX' in hdulist[1].data.dtype.names:\n stellar_flux = hdulist[1].data.field('STELLAR_FLUX') * parse_unit_safe(hdulist[1].columns[2].unit)\n sed.stellar_flux = convert_flux(nu, stellar_flux, unit_flux)\n else:\n stellar_flux = None\n\n # Set polarization (if present)\n if len(hdulist) > 4:\n if 'LINPOL' in hdulist[4].data.dtype.names:\n sed.linpol = hdulist[4].data.field('LINPOL') * u.percent\n if 'LINPOL_ERROR' in hdulist[4].data.dtype.names:\n sed.linpol_error = hdulist[4].data.field('LINPOL_ERROR') * u.percent\n if 'CIRCPOL' in hdulist[4].data.dtype.names:\n sed.circpol = hdulist[4].data.field('CIRCPOL') * u.percent\n if 'CIRCPOL_ERROR' in hdulist[4].data.dtype.names:\n sed.circpol_error = hdulist[4].data.field('CIRCPOL_ERROR') * u.percent\n\n # Sort SED\n\n if order not in ('nu', 'wav'):\n raise ValueError('order should be nu or wav')\n\n if (order == 'nu' and sed.nu[0] > sed.nu[-1]) or \\\n (order == 'wav' and sed.wav[0] > sed.wav[-1]):\n sed.wav = sed.wav[::-1]\n sed.nu = sed.nu[::-1]\n sed.flux = sed.flux[..., ::-1]\n sed.error = sed.error[..., ::-1]\n\n return sed",
"def load_sfs(self, sfs):\n try:\n fs = dadi.Spectrum.from_file(sfs)\n except:\n print 'The spectrum file you provided is not valid!'\n exit(1)\n return fs",
"def _initFromData(self, data):\n # Read the standard header\n magic, bom, version, filesize, headersize, numblocks = \\\n _common.NDS_STD_FILE_HEADER.unpack_from(data, 0)\n if version != 0x100:\n raise ValueError(f'Unsupported SDAT version: {version}')\n\n if magic != b'SDAT':\n raise ValueError(\"Wrong magic (should be b'SDAT', instead found \"\n f'{magic})')\n\n # Read the block offsets and sizes\n (symbolsBlockOffset, symbolsBlockSize,\n infoBlockOffset, infoBlockSize,\n fatBlockOffset, fatBlockSize,\n fileBlockOffset, fileBlockSize,\n ) = struct.unpack_from('<8I', data, 0x10)\n\n # Read the symbols block\n (symbolsMagic, symbolsSize) = \\\n struct.unpack_from('<4sI', data, symbolsBlockOffset)\n\n if symbolsBlockOffset != 0:\n symbolsOffsets = struct.unpack_from('<8I', data,\n symbolsBlockOffset + 8)\n assert symbolsMagic == b'SYMB'\n else:\n symbolsOffsets = [None] * 8\n\n\n lastEndOfString = 0 # relative to SYMB block\n def readSymbolsList(offset, hasSubgroups):\n \"\"\"\n Read a list of symbols at offset offset. If hasSubgroups,\n it'll be parsed assuming that the symbol table has entries\n for sub-symbol-lists as well. (In practice, this only occurs\n for SSARs.)\n If there are no symbols, return an empty list.\n \"\"\"\n nonlocal lastEndOfString\n\n if offset is None: return []\n\n off = symbolsBlockOffset + offset\n count, = struct.unpack_from('<I', data, off); off += 4\n\n symbols = []\n for i in range(count):\n symbolOff, = struct.unpack_from('<I', data, off)\n off += 4\n\n if symbolOff == 0:\n thisSymbol = None\n else:\n thisSymbol = _common.loadNullTerminatedStringFrom(data,\n symbolsBlockOffset + symbolOff)\n lastEndOfString = symbolOff + len(thisSymbol) + 1\n\n if not hasSubgroups:\n symbols.append(thisSymbol)\n else:\n subSymbolsOff, = struct.unpack_from('<I', data, off)\n off += 4\n\n if subSymbolsOff == 0:\n subSymbols = []\n else:\n subSymbols = readSymbolsList(subSymbolsOff, False)\n\n symbols.append((thisSymbol, subSymbols))\n \n return symbols\n\n\n # Read the FAT block\n (fatMagic, fatSize, fatCount) = \\\n struct.unpack_from('<4sII', data, fatBlockOffset)\n assert fatMagic == b'FAT ' # note trailing space\n\n # Read the files from the FILES block\n files = []\n fatArrayPos = fatBlockOffset + 0x0C\n self.fileAlignment = 0x200\n self.fatLengthsIncludePadding = True\n finalFileEnd = fileBlockOffset + 8\n for i in range(fatCount):\n (fileOffset, fileSize) = \\\n struct.unpack_from('<II', data, fatArrayPos)\n fatArrayPos += 0x10 # There's 8 pad bytes.\n\n # We'll need this later\n finalFileEnd = fileOffset + fileSize\n\n if i != fatCount - 1:\n nextOffset, = struct.unpack_from('<I', data, fatArrayPos)\n paddedSize = nextOffset - fileOffset\n if paddedSize != fileSize:\n self.fatLengthsIncludePadding = False\n\n # Most SDATs require files to be padded to 0x20, but some\n # use other amounts. We check for that here, so that we can\n # rebuild it correctly later.\n if fileOffset % 0x200 == 0x100:\n self.fileAlignment = min(self.fileAlignment, 0x100)\n if fileOffset % 0x100 == 0x80:\n self.fileAlignment = min(self.fileAlignment, 0x80)\n if fileOffset % 0x80 == 0x40:\n self.fileAlignment = min(self.fileAlignment, 0x40)\n if fileOffset % 0x40 == 0x20:\n self.fileAlignment = min(self.fileAlignment, 0x20)\n if fileOffset % 0x20 == 0x10:\n self.fileAlignment = min(self.fileAlignment, 0x10)\n if fileOffset % 0x10 == 8:\n self.fileAlignment = min(self.fileAlignment, 8)\n if fileOffset % 8 == 4:\n self.fileAlignment = min(self.fileAlignment, 4)\n if fileOffset % 4 == 2:\n self.fileAlignment = min(self.fileAlignment, 2)\n if fileOffset % 2 == 1: # yes, this happens sometimes\n self.fileAlignment = min(self.fileAlignment, 1)\n\n if i == 0:\n self.firstFileAlignment = self.fileAlignment\n\n file = data[fileOffset : fileOffset + fileSize]\n files.append(file)\n\n if self.firstFileAlignment == self.fileAlignment:\n self.firstFileAlignment = None\n\n # Check if the end is definitely unpadded (that is, if there\n # should be padding and it's not present)\n if finalFileEnd == len(data) and finalFileEnd % self.fileAlignment != 0:\n self.padAtEnd = False\n\n # Do another quick pass to find if the FAT file lengths include\n # padding\n\n # Read the info block\n (infoMagic, infoSize) = \\\n struct.unpack_from('<4sI', data, infoBlockOffset)\n infoOffsets = struct.unpack_from('<8I', data,\n infoBlockOffset + 8)\n assert infoMagic == b'INFO'\n\n def getInfoEntryOffsets(partNum):\n off = infoOffsets[partNum]\n count, = struct.unpack_from('<I', data, infoBlockOffset + off)\n entryOffsets = struct.unpack_from(f'<{count}I', data,\n infoBlockOffset + off + 4)\n for entryOff in entryOffsets:\n if entryOff == 0:\n yield None\n else:\n yield infoBlockOffset + entryOff\n\n\n # Info part 0: SSEQ (references SBNK)\n for entryOff, symb in itertools.zip_longest(getInfoEntryOffsets(0),\n readSymbolsList(symbolsOffsets[0], False)):\n if entryOff is None:\n sseq = None\n else:\n (fileID, unk02, bankID, volume, channelPressure,\n polyphonicPressure, playerID) = \\\n struct.unpack_from('<3H4B', data, entryOff)\n sseq = soundSequence.SSEQ(files[fileID], unk02, bankID,\n volume, channelPressure, polyphonicPressure, playerID)\n sseq.dataMergeOptimizationID = fileID\n\n self.sequences.append((symb, sseq))\n\n # Info part 1: SSAR\n for entryOff, symb in itertools.zip_longest(getInfoEntryOffsets(1),\n readSymbolsList(symbolsOffsets[1], True)):\n if entryOff is None:\n ssar = None\n else:\n fileID, unk02 = struct.unpack_from('<HH', data, entryOff)\n subSymb = symb[1] if symb is not None else None\n ssar = soundSequenceArchive.SSAR(files[fileID], unk02, subSymb)\n ssar.dataMergeOptimizationID = fileID\n\n name = symb[0] if symb is not None else None\n self.sequenceArchives.append((name, ssar))\n\n # Info part 2: SBNK\n for entryOff, symb in itertools.zip_longest(getInfoEntryOffsets(2),\n readSymbolsList(symbolsOffsets[2], False)):\n if entryOff is None:\n sbnk = None\n else:\n fileID, unk02 = struct.unpack_from('<HH', data, entryOff)\n swarIDs = struct.unpack_from('<4h', data, entryOff + 4)\n swarIDs2 = []\n for x in swarIDs:\n if x == -1:\n swarIDs2.append(None)\n else:\n swarIDs2.append(x)\n\n sbnk = soundBank.SBNK(files[fileID], unk02, swarIDs2)\n sbnk.dataMergeOptimizationID = fileID\n\n self.banks.append((symb, sbnk))\n\n # Info part 3: SWAR\n for entryOff, symb in itertools.zip_longest(getInfoEntryOffsets(3),\n readSymbolsList(symbolsOffsets[3], False)):\n if entryOff is None:\n swar = None\n else:\n fileID, unk02 = struct.unpack_from('<HH', data, entryOff)\n swar = soundWaveArchive.SWAR(files[fileID], unk02)\n swar.dataMergeOptimizationID = fileID\n\n self.waveArchives.append((symb, swar))\n\n # Info part 4: Sequence players\n for entryOff, symb in itertools.zip_longest(getInfoEntryOffsets(4),\n readSymbolsList(symbolsOffsets[4], False)):\n if entryOff is None:\n sp = None\n else:\n maxSequences, channelMask, heapSize = \\\n struct.unpack_from('<HHI', data, entryOff)\n\n channels = set()\n for i in range(16):\n if (channelMask >> i) & 1:\n channels.add(i)\n\n sp = soundSequencePlayer.SequencePlayer(maxSequences,\n channels,\n heapSize)\n\n self.sequencePlayers.append((symb, sp))\n\n # Info part 5: Groups\n for groupOff, symb in itertools.zip_longest(getInfoEntryOffsets(5),\n readSymbolsList(symbolsOffsets[5], False)):\n if groupOff is None:\n entries = None\n else:\n entriesCount, = struct.unpack_from('<I', data, groupOff)\n\n entries = []\n arrayOff = groupOff + 4\n for i in range(entriesCount):\n type, options, id = struct.unpack_from('<BHxI', data, arrayOff)\n arrayOff += 8\n\n entries.append(soundGroup.GroupEntry(type, options, id))\n\n self.groups.append((symb, entries))\n\n # Info part 6: Stream players\n for entryOff, symb in itertools.zip_longest(getInfoEntryOffsets(6),\n readSymbolsList(symbolsOffsets[6], False)):\n if entryOff is None:\n sp = None\n else:\n count, = struct.unpack_from('<B', data, entryOff)\n channels = list(\n struct.unpack_from(f'<{count}B', data, entryOff + 1))\n sp = soundStreamPlayer.StreamPlayer(channels)\n\n self.streamPlayers.append((symb, sp))\n\n # Info part 7: Streams\n for entryOff, symb in itertools.zip_longest(getInfoEntryOffsets(7),\n readSymbolsList(symbolsOffsets[7], False)):\n if entryOff is None:\n strm = None\n else:\n fileID, unk02, volume, priority, playerID, unk07 = \\\n struct.unpack_from('<HH4B', data, entryOff)\n strm = soundStream.STRM(files[fileID], unk02, volume, priority, playerID, unk07)\n strm.dataMergeOptimizationID = fileID\n\n self.streams.append((symb, strm))\n\n\n # If the symbols block size is definitely padded, record that\n if symbolsBlockSize % 4 == 0 and lastEndOfString % 4 != 0:\n self.padSymbSizeTo4InSDATHeader = True",
"def read_data(self):\n data = np.genfromtxt(self.__file) # Planck SED\n self.__nu = 10.0**data[:,0]\n self.__nuF = 10.0**data[:,2]\n self.__err = 10.0**data[:,3]\n #self.__W = 10.0**data[:,4]\n self.__yerr = [ self.__nuF - self.__nuF / self.__err, \\\n self.__nuF * self.__err - self.__nuF ]\n self.__maxY = max( self.__nuF )\n self.__minY = min( self.__nuF )",
"def _read_smat(filename):\n return _read_hcore(filename)",
"def _read_data(self):\n with self._open(self.filename, 'rb') as f:\n try:\n f.seek(self._offset_data, self._offset_whence)\n except IOError:\n print('Error: hedp.io.HamamatsuFile seeking outside of file limits.')\n print(' Failed to parse file.')\n print(\" Either the 'offset' or 'dtype' input arguments must be wrong!\")\n raise\n except:\n raise\n\n data_len = np.prod(self.shape)*np.dtype(self._dtype).itemsize\n data_str = f.read(data_len)\n if data_len != len(data_str):\n print(data_len, len(data_str))\n raise ValueError('File ended before all data was read. Probably wrong offset or dtype!')\n\n\n self.data = np.fromstring(data_str, dtype=self._dtype).reshape(self.shape[::-1])\n self.data = np.ndarray.astype(self.data, 'float32')\n\n #self.data = np.fromfile(f, dtype=self._dtype,\n # count=np.prod(self.shape)).reshape(self.shape[::-1])",
"def ReadData(self, tstep):\n fname = self.fname[tstep]\n t0 = self.tind[tstep]\n \n print 'Reading SUNTANS data at time: %s...'%datetime.strftime(self.timei[tstep],'%Y-%m-%d %H:%M:%S') \n nc = Dataset(fname)\n \n self.time = nc.variables['time'][t0]\n \n self.temp = nc.variables['temp'][t0,:,:]\n self.salt = nc.variables['salt'][t0,:,:]\n self.uc = nc.variables['uc'][t0,:,:]\n self.vc = nc.variables['vc'][t0,:,:]\n self.nu_v = nc.variables['nu_v'][t0,:,:]\n self.rho = nc.variables['rho'][t0,:,:]\n self.tau_x = nc.variables['tau_x'][t0,:]\n self.tau_y = nc.variables['tau_y'][t0,:]\n self.eta = nc.variables['eta'][t0,:]",
"def read_single_analysis_data(f):\n \n data = np.loadtxt(f, dtype=np.float64)\n\n return data",
"def read_file(self,file_name):\r\n data = np.genfromtxt(file_name)\r\n return data;",
"def get_TESS_data(filename, fluxtype = 'PDCSAP_FLUX'):\n # Manipulate the fits file:\n data = fits.getdata(filename)\n\n # Identify zero-flux values to take them out of the data arrays:\n idx = np.where((data[fluxtype]!=0.)&(~np.isnan(data[fluxtype])))[0]\n\n # Return median-normalized flux:\n return data['TIME'][idx],data[fluxtype][idx]/np.median(data[fluxtype][idx]), \\\n data[fluxtype+'_ERR'][idx]/np.median(data[fluxtype][idx])",
"def loadtext2(infile):\n warrsn, farrsn =np.loadtxt(infile, usecols=(0, 1), unpack=True)\n return create_spectrum(warrsn, farrsn)",
"def load_sdss(sdss_filename=\"\", **extras):\n import astropy.io.fits as fits\n with fits.open(sdss_filename) as hdus:\n spec = np.array(hdus[1].data)\n info = np.array(hdus[2].data)\n line = np.array(hdus[3].data)\n return spec, info, line",
"def spectre_sdss_fits(f):\n hdul = fits.open(f)\n \n if 'SDSS' in hdul[0].header['TELESCOP']:\n # .fits from SDSS\n data = hdul[1].data\n \n # log10(wav) dans les .fits\n wav = 10.**data.field(1) # Angstrom\n \n # flux F_lambda en unités de 1e-17 erg/...\n flux = data.field(0)*1e-17 # erg/cm^2/s/Ang\n \n # c_ang = vitesse de la lumière en angstrom / s\n # flux *= wav**2/sc.c_ang # erg/cm^2/s/Hz\n \n hdul.close()\n return wav, flux\n \n else:\n raise Exception('.fits format inconnu')",
"def _read_stix_srm_file(srm_file):\n with fits.open(srm_file) as hdul:\n d0 = hdul[1].header\n d1 = hdul[1].data\n d3 = hdul[2].data\n\n pcb = np.concatenate((d1['ENERG_LO'][:, None], d1['ENERG_HI'][:, None]), axis=1)\n\n return {\"photon_energy_bin_edges\": pcb,\n \"count_energy_bin_edges\": np.concatenate((d3['E_MIN'][:, None], d3['E_MAX'][:, None]), axis=1),\n \"drm\": d1['MATRIX']*d0[\"GEOAREA\"]}",
"def loadtext(infile):\n warrsn, farrsn =np.loadtxt(infile, usecols=(0, 1), unpack=True)\n return create_spectrum(warrsn, farrsn)",
"def read_sas_file(filename):\n \n data = np.array([],dtype=np.float)\n \n with open(filename,'r') as f:\n \n for line in f:\n\n # Only the first 2 or 3 columns are parsed \n cols = parse_sas_data_line(line)\n \n if cols.any():\n\n if data.any():\n data = np.vstack((data,parse_sas_data_line(line)))\n else:\n data = parse_sas_data_line(line)\n \n return data",
"def read(self, sacc_data: sacc.Sacc) -> None:",
"def read(self, sacc_data: sacc.Sacc) -> None:",
"def read(self, sacc_data: sacc.Sacc) -> None:",
"def _read_sp(sp_file):\n content = sp_file.read()\n\n start_byte = 0\n n_bytes = 4\n signature = content[start_byte:start_byte + n_bytes]\n\n start_byte += n_bytes\n # the description is fixed to 40 bytes\n n_bytes = 40\n description = content[\n start_byte:start_byte + n_bytes].decode('utf8')\n\n meta = {'signature': signature,\n 'description': description}\n spectrum = []\n\n NBP = []\n start_byte += n_bytes\n n_bytes = 6\n block_id, block_size = _block_info(\n content[start_byte:start_byte + n_bytes])\n start_byte += n_bytes\n NBP.append(start_byte + block_size)\n while block_id != 122 and start_byte < len(content) - 2:\n next_block_id = content[start_byte:start_byte + 2]\n if indexbytes(next_block_id, 1) == 117:\n start_byte = NBP[-1]\n NBP = NBP[:-1]\n while start_byte >= NBP[-1]:\n NBP = NBP[-1]\n else:\n block_id, block_size = _block_info(\n content[start_byte:start_byte + n_bytes])\n start_byte += n_bytes\n NBP.append(start_byte + block_size)\n\n meta.update(_decode_5104(\n content[start_byte:start_byte + block_size]))\n\n start_byte = NBP[1]\n while start_byte < len(content):\n n_bytes = 6\n block_id, block_size = _block_info(\n content[start_byte:start_byte + n_bytes])\n start_byte += n_bytes\n if block_id in FUNC_DECODE.keys():\n decoded_data = FUNC_DECODE[block_id](\n content[start_byte:start_byte + block_size])\n if isinstance(decoded_data, dict):\n meta.update(decoded_data)\n else:\n spectrum = decoded_data\n start_byte += block_size\n\n wavelength = np.linspace(meta['min_wavelength'],\n meta['max_wavelength'],\n meta['n_points'])\n\n if isinstance(sp_file, string_types):\n meta['filename'] = basename(sp_file)\n else:\n meta['filename'] = basename(sp_file.name)\n\n return Spectrum(spectrum, wavelength, meta)",
"def data_parser(data, snp_neighbour):\n\n # Get only the features of the SNP of interest\n if snp_neighbour == 0:\n # The SNP of interest samples are located at the middle position of the data sequence\n index_SNPi = (data.shape[2] - 1) / 2 # -1 for the SNP of interest\n samples = data[:, :, int(index_SNPi)]\n\n # Get the features of the SNP of interest and neighbouring positions\n else:\n # The data should fit in a 2D array for performing neural network. The number of samples should be stay, and\n # the number of features will be the number of features times the number of nucleotides\n samples = data.reshape([data.shape[0], -1])\n\n return samples",
"def read_raw(self):\n return self._FITS.read_raw()",
"def read_raw(rawfile, shape, dtype=np.uint16, kind='middleton'):\n\n # -- alert\n print(\"READ_RAW: reading {0}...\".format(rawfile))\n\n\n # -- read file\n if kind=='middleton':\n return np.fromfile(open(rawfile),dtype) \\\n .reshape(shape[2],shape[0],shape[1])[:,:,::-1] \\\n .transpose(1,2,0) \\\n .astype(float)",
"def data_from_fits(fits_file):\n hdul = fits.open(fits_file)\n data = hdul[0].data\n return data",
"def ReadData( fName = '/tmp/chartdata' ):\n blocks = common.ReadDataFromFile( fName )\n\n return blocks",
"def read_raw(self, filename, ignore_data=False, open_dataset=None):\n twix, version_flag = self.get_twix(filename)\n\n # 'scan' returns data in [ncha, navg, npts] order - easy to convert to mrs_data_raw dims\n d = self._get_parameters(twix.current, index='scan')\n d[\"data_source\"] = filename\n\n data = d['data']\n prep = d['prep']\n nrep, _, navg, npts = data.shape\n\n if d[\"remove_os\"]:\n data = self._remove_oversampling_basic(data)\n if prep is not None:\n prep = self._remove_oversampling_basic(prep)\n d[\"sw\"] = d[\"sw\"] / 2.0\n\n data = np.conjugate(data)\n if prep is not None:\n prep = np.conjugate(prep)\n\n raws = []\n\n # dataset1 - scan 0, water unsuppressed for coil combine and (maybe) ECC\n\n # tmp = prep[:,:,0,:].copy()\n # tmp.shape = (tmp.shape[0], tmp.shape[1], 1, tmp.shape[2])\n d[\"data\"] = prep[:,:,0:1,:].copy() * RAWDATA_SCALE / float(1.0)\n d[\"data_source\"] = filename + '.combine'\n raws.append(DataRawCmrrSlaser(d))\n\n # dataset2 - scan 1-2, water unsuppressed for water scale\n\n if prep.shape[2] > 1:\n d[\"data\"] = prep[:,:,1:2,:].copy() * RAWDATA_SCALE / float(1.0)\n else:\n d[\"data\"] = prep[:,:,0:1,:].copy() * RAWDATA_SCALE / float(1.0)\n d[\"data_source\"] = filename + '.water1'\n raws.append(DataRawCmrrSlaser(d))\n\n # dataset3 - scans 5-68 (64 total), metabolite data with WS\n\n d[\"data\"] = data.copy() * RAWDATA_SCALE / float(navg)\n d[\"data_source\"] = filename + '.metab64'\n raws.append(DataRawCmrrSlaser(d))\n\n return raws"
] | [
"0.5751052",
"0.5526093",
"0.5446301",
"0.5305193",
"0.5246388",
"0.5217913",
"0.5203776",
"0.517204",
"0.51438344",
"0.51111645",
"0.504678",
"0.50407815",
"0.50394773",
"0.50265765",
"0.49560547",
"0.49271512",
"0.49130988",
"0.4911392",
"0.48963708",
"0.48891187",
"0.48800185",
"0.48800185",
"0.48800185",
"0.48606282",
"0.48557085",
"0.48354843",
"0.48203042",
"0.48188767",
"0.4809551",
"0.4806718"
] | 0.6675515 | 0 |
Given a SansData object, normalize the data to the provided monitor | def monitor_normalize(sansdata,mon0=1e8):
monitor=sansdata.metadata['run.moncnt']
result=sansdata.data*mon0/monitor
res=SansData()
res.data=result
res.metadata=deepcopy(sansdata.metadata)
res.qx=copy(sansdata.qx)
res.qy=copy(sansdata.qy)
res.theta=copy(sansdata.theta)
return res | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def monitor_normalize(ylist,yerrlist,monlist,monitor=None):\n mon0=monlist[0]\n if monitor!=None:\n mon0=N.float64(monitor)\n y_in=N.array([],'float64')\n yerr_in=N.array([],'float64')\n mon_in=N.array(monlist,'float64')\n correction=mon0/mon_in #assumes that none of the monitor rates given is 0\n #make sure that we're not changing the original data\n y_out=copy.deepcopy(ylist)\n yerr_out=copy.deepcopy(yerrlist)\n for i in range(len(ylist)):\n y_out[i]=y_out[i]*correction[i]\n yerr_out[i]=yerr_out[i]*correction[i]\n return y_out,yerr_out",
"def normalizeData(self, data):\n return _normalizeData(data)",
"def normalizeData(self, data):\n return _normalizeData(data)",
"def _normalize_detectors(self, data, index):\n vol = self.cell_volumes(index)\n for i, s in enumerate(data):\n data[i] = data[i] / vol\n full_index = list(range(len(self.axes)))\n other_axes = [item for item in full_index if item not in index]\n for i in other_axes:\n v = self.axes[i].total_volume\n data /= v\n return data",
"def normalize(data):\n data_range = data.max() - data.min()\n #if data_range == 0.:\n # sys.exit(\"data.max() - data.min() == 0. !\")\n if stddev != 0.:\n data = (data - data.min()) / data_range\n\n return data",
"def normalize_data(self, data):\n self.find_mean_std(data)\n return (data - self._data_mean) / self._data_std",
"def normalize_data(self):\n self.x_mean, self.x_std = du.get_mean_std(self.x_train)\n self.x_train = du.normalize(self.x_train, self.x_mean, self.x_std)\n if self.x_test is not None and self.y_test is not None:\n self.x_test = du.normalize(self.x_test, self.x_mean, self.x_std)\n self.normalized_data = True",
"def normalize(data):\n data = lowercase(data)\n data = remove_punct(data)\n data = remove_apostrophes(data)\n data = remove_stopwords(data)\n data = num_to_words(data)\n data = lemmatize(data)\n data = stemming(data)\n data = remove_punct(data)\n data = num_to_words(data)\n data = lemmatize(data)\n data = stemming(data)\n data = remove_punct(data) #done again to remove hyphens produced by num2words\n data = remove_stopwords(data) #done agan to remove stopwords produced by num2words\n return data",
"def normalize_dataset(self):",
"def _normalize_data_to_send(info):\n # Remove the parts of the data that are unbounded in size.\n info = copy.deepcopy(info)\n for key in ['model_config', 'epoch_history']:\n if key in info:\n del info[key]\n return info",
"def normalize_values(self, data):\n\n df = pd.DataFrame(data[1:], columns = data[0]).astype(str)\n\n df = df.replace(ami_md_constants.NAS)\n\n df = df.replace(ami_md_constants.REGEX_REPLACE_DICT, regex=True)\n df = df.replace(ami_md_constants.STRING_REPLACE_DICT)\n df['source.object.format_type'] = df['source.object.format'].map(ami_md_constants.FORMAT_TYPE)\n\n for key in ami_md_constants.MEASURE_UNIT_MAPS.keys():\n value_map = ami_md_constants.MEASURE_UNIT_MAPS[key]\n df = self.map_value(df,\n value_map['from_column'],\n value_map['to_column'],\n value_map['constant_value'],\n value_map['values_map_column'],\n value_map['values_map'])\n\n #force all the numerics back to numeric, and drop all empty columns\n df = df.apply(pd.to_numeric, errors='ignore').dropna(axis=1, how = \"all\")\n\n vals = df.values.tolist()\n cols = df.columns.tolist()\n vals.insert(0, cols)\n\n return vals",
"def normalize(data):\n\n p_means = np.mean(data,axis=0)\n p_vars = np.var(data,axis=0)\n\n # subtract dc component\n data = data-p_means\n\n # contrast normalize \n data = data/np.sqrt(p_vars+10) # plus 10 to account for small variances\n \n return data",
"def normalise(self, spectrum):\n\n return spectrum",
"def normalise(self, spectrum):\n\n return spectrum",
"def normalize(self):\n d = learning_utils.convert_data_to_2d(self._data)\n d = learning_utils.normalize_2d(d)\n self._data = learning_utils.convert_data_to_1d(d)",
"def preprocess(self, data, era):\n return data / np.max(data)",
"def _normalize(self, dataset):\n if self.max is None: # if we are normalizing the training set\n self.max, self.min = dataset.max(), dataset.min() # find max, min value for each columns\n for row in dataset.index: # for each row in dataset\n for col in self.features: # for each feature in the instance (exclude target)\n dataset.at[row, col] = (dataset.at[row, col] - self.min[col]) / (self.max[col] - self.min[col]) if col != \"Bias\" else 1",
"def normalize_and_clip(meas):\n frequency_weights = np.zeros(len(meas))\n\n for i in range(len(meas)):\n if(meas[i] > NORMALIZE_SENS[i]):\n meas[i] = NORMALIZE_SENS[i]\n frequency_weights[i] = meas[i] / NORMALIZE_SENS[i]\n\n return frequency_weights",
"def normalize_data(data):\n mean = np.mean(data)\n std = np.std(data)\n return (data - mean) / std",
"def preprocess_data(self, data, scale_data=True):\n print(\"preprocess_data not implemented\")\n return data",
"def set_normalization(self, dataloader):\n mean = 0\n square = 0\n for (data_in, _) in dataloader:\n mean += data_in.mean()\n square += data_in.pow(2).mean()\n\n mean /= len(dataloader)\n square /= len(dataloader)\n std = np.sqrt(square - mean ** 2)\n\n # The input data should be roughly normally distributed after\n # passing through net_fixed.\n self.scale_in.bias.data.fill_(- mean / std)\n self.scale_in.weight.data.fill_(1 / std)",
"def _preprocess(self, data, normalize=False) -> np.ndarray:\n \n preprocessor = StandardScaler() if not normalize else Normalizer()\n\n data = preprocessor.fit_transform(data)\n \n return data",
"def normalize_weather_data(self, weather_data):\n\n feat_means = np.array([self.summary[field][0] for field in self.weather_fields])\n feat_stds = np.array([self.summary[field][1] for field in self.weather_fields])\n\n # Standardize\n weather_standardized = (weather_data - feat_means) / feat_stds\n\n return weather_standardized",
"def data_normalize (self, data):\r\n data = data + (2**15)\r\n data = data / ((2**16) - 1)\r\n data = 2 * data\r\n data = data - 1\r\n\r\n return data",
"def standardizeData(tdata,vdata):\n tmean = tdata.mean(axis=0)\n tstd = tdata.std(axis=0)\n tdataNew = (tdata - tmean)/tstd\n vdataNew = (vdata - tmean)/tstd\n return tdataNew, vdataNew",
"def rescale_data(self):\n\n # Dividing every array of simulated data vectors by the mean of that array.\n '''# Didnt work\n for key in self.data.keys():\n self.data[key] /= np.mean(self.data[key])\n '''\n\n self.rescaled = True\n\n # Mean normalization\n \"\"\" didnt work\n for key in self.data.keys():\n self.data[key] -= np.mean(self.data[key])\n self.data[key] /= (np.max(self.data[key]) - np.min(self.data[key]))\n \"\"\"\n\n # Median normalization\n \"\"\" didnt work, still dividing by large number \n for key in self.data.keys():\n self.data[key] -= np.median(self.data[key])\n self.data[key] /= (np.max(self.data[key]) - np.min(self.data[key]))\n \"\"\"\n\n # Divide by median\n \"\"\" didnt work\n for key in self.data.keys():\n self.data[key] -= np.median(self.data[key])\n self.data[key] /= (np.median(self.data[key]))\n \"\"\"\n\n # Take logarithm of data\n \"\"\" didnt work\n for key in self.data.keys():\n self.data[key] = np.log10(self.data[key])\n \"\"\"\n\n # Scale by length of vector\n \"\"\"\n for key in self.data.keys():\n self.data[key] /= np.linalg.norm(self.Cl_noiseless)\n \"\"\"\n\n \n # Scale by negative of the natural logarithm \n for key in self.data.keys():\n self.data[key] = -1 * np.log(self.data[key]) \n \n \"\"\"\n # Scale by subtracting the mean and dividing by std\n std = np.nanstd(self.data['data'])\n mean = np.nanmean(self.data['data'])\n for key in self.data.keys():\n # self.data[key] -= np.log(self.Cl_noiseless) # -1* # scale this same way\n # self.data[key] -= self.Cl_noiseless # -1* # scale this same way\n self.data[key] -= mean \n self.data[key] /= std\n \"\"\"",
"def standardize_data(data):\n return (data - np.mean(data, axis=0)) / (np.std(data, axis=0) + 10 ** -16)",
"def correct_detector_efficiency(sansdata,sensitivity):\n result=sansdata.data/sensitivity #Could be done more elegantly by defining a division method on SansData\n res=SansData()\n res.data=result\n res.metadata=deepcopy(sansdata.metadata)\n res.qx=copy(sansdata.qx)\n res.qy=copy(sansdata.qy)\n res.theta=copy(sansdata.theta)\n return res",
"def standardize(data):\n stddev = data.std()\n #if stddev == 0.:\n # sys.exit(\"data.std() == 0. !\")\n if stddev != 0.:\n data = (data - data.mean()) / (data.std())\n\n return data",
"def determineNorm( self, monitorData, start, end, dt):\n self._norm = monitorData.integrate( start, end, dt)\n \n if self._norm == 0.0:\n msg = \"norm is zero: will generate inf's\"\n raise ValueError, msg\n \n self._sigma2 = self._norm*dt\n\n return"
] | [
"0.5822043",
"0.5605835",
"0.5605835",
"0.550023",
"0.5351501",
"0.5344585",
"0.53409696",
"0.53238094",
"0.53121114",
"0.52463055",
"0.5191288",
"0.50953764",
"0.5043982",
"0.5043982",
"0.5034275",
"0.50148374",
"0.49886858",
"0.49828744",
"0.49824554",
"0.49549466",
"0.49411273",
"0.49400884",
"0.4923966",
"0.4913478",
"0.49124584",
"0.49034035",
"0.48849347",
"0.48749194",
"0.48698407",
"0.48440394"
] | 0.748248 | 0 |
Given a SansData object and an sensitivity map generated from a div, correct for the efficiency of the detector. Recall that sensitivities are generated by taking a measurement of plexiglass and dividing by the mean value | def correct_detector_efficiency(sansdata,sensitivity):
result=sansdata.data/sensitivity #Could be done more elegantly by defining a division method on SansData
res=SansData()
res.data=result
res.metadata=deepcopy(sansdata.metadata)
res.qx=copy(sansdata.qx)
res.qy=copy(sansdata.qy)
res.theta=copy(sansdata.theta)
return res | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def _call(self, dataset):\n # first cast to floating point dtype, because noise is most likely\n # floating point as well and '+=' on int would not do the right thing\n # XXX should we already deepcopy here to keep orig dtype?\n if not N.issubdtype(dataset.samples.dtype, N.float):\n dataset.setSamplesDType('float32')\n\n if __debug__:\n nfeatures = dataset.nfeatures\n\n sens_map = []\n\n # compute the datameasure on the original dataset\n # this is used as a baseline\n orig_measure = self.__datameasure(dataset)\n\n # do for every _single_ feature in the dataset\n for feature in xrange(dataset.nfeatures):\n if __debug__:\n debug('PSA', \"Analyzing %i features: %i [%i%%]\" \\\n % (nfeatures,\n feature+1,\n float(feature+1)/nfeatures*100,), cr=True)\n\n # make a copy of the dataset to preserve data integrity\n wdata = deepcopy(dataset)\n\n # add noise to current feature\n wdata.samples[:, feature] += self.__noise(size=wdata.nsamples)\n\n # compute the datameasure on the perturbed dataset\n perturbed_measure = self.__datameasure(wdata)\n\n # difference from original datameasure is sensitivity\n sens_map.append(perturbed_measure - orig_measure)\n\n if __debug__:\n debug('PSA', '')\n\n return N.array(sens_map)",
"def rescale_data(self):\n\n # Dividing every array of simulated data vectors by the mean of that array.\n '''# Didnt work\n for key in self.data.keys():\n self.data[key] /= np.mean(self.data[key])\n '''\n\n self.rescaled = True\n\n # Mean normalization\n \"\"\" didnt work\n for key in self.data.keys():\n self.data[key] -= np.mean(self.data[key])\n self.data[key] /= (np.max(self.data[key]) - np.min(self.data[key]))\n \"\"\"\n\n # Median normalization\n \"\"\" didnt work, still dividing by large number \n for key in self.data.keys():\n self.data[key] -= np.median(self.data[key])\n self.data[key] /= (np.max(self.data[key]) - np.min(self.data[key]))\n \"\"\"\n\n # Divide by median\n \"\"\" didnt work\n for key in self.data.keys():\n self.data[key] -= np.median(self.data[key])\n self.data[key] /= (np.median(self.data[key]))\n \"\"\"\n\n # Take logarithm of data\n \"\"\" didnt work\n for key in self.data.keys():\n self.data[key] = np.log10(self.data[key])\n \"\"\"\n\n # Scale by length of vector\n \"\"\"\n for key in self.data.keys():\n self.data[key] /= np.linalg.norm(self.Cl_noiseless)\n \"\"\"\n\n \n # Scale by negative of the natural logarithm \n for key in self.data.keys():\n self.data[key] = -1 * np.log(self.data[key]) \n \n \"\"\"\n # Scale by subtracting the mean and dividing by std\n std = np.nanstd(self.data['data'])\n mean = np.nanmean(self.data['data'])\n for key in self.data.keys():\n # self.data[key] -= np.log(self.Cl_noiseless) # -1* # scale this same way\n # self.data[key] -= self.Cl_noiseless # -1* # scale this same way\n self.data[key] -= mean \n self.data[key] /= std\n \"\"\"",
"def freq_optimization(self):\n index = identify_scale(self.vz, True)\n # In case the patient is limping\n if index > 35:\n index = index / 2\n print(f\"Scale used is {index}\")",
"def test_sensitivity():\n n_ons = np.arange(0.1, 10, 0.3)\n n_offs = np.arange(0.1, 10, 0.3)\n alphas = np.array([1e-3, 1e-2, 0.1, 1, 10])\n for n_on in n_ons:\n for n_off in n_offs:\n for alpha in alphas:\n for method in ['simple', 'lima']:\n significance = significance_on_off(n_on, n_off, alpha, method=method)\n excess = sensitivity_on_off(n_off, alpha, significance, method=method)\n n_on2 = excess + alpha * n_off\n assert_allclose(n_on, n_on2, decimal=3)",
"def computeSensitivityMap(X, y, C_val, gamma_val, no_channels, no_timepoints):\n \n ### Compute SVM classifier ###\n y = np.squeeze(y)\n classifier = SVC(C=C_val, gamma=gamma_val)\n clf = classifier.fit(X, y)\n \n \n ### Extract classifier model coefficients and add zero indices ### \n coefficients = clf.dual_coef_\n support_array = clf.support_\n \n coefficients = np.squeeze(coefficients)\n \n trials = len(X[:,0])\n features = len(X[0])\n alpha = np.zeros(trials)\n alpha[support_array] = coefficients\n alpha = np.squeeze(alpha)\n \n no_zero_indices = trials - len(support_array)\n \n ### Compute training kernal matrix, K ###\n M = distance.pdist(X,'euclidean')\n \n M_exp = np.exp(gamma_val*(-(np.square(M))))\n K = distance.squareform(M_exp) \n \n ### Compute sensitivity map ###\n \n X = np.transpose(X) # Obtain training examples in columns for further computation\n\n mapping = np.matmul(X,np.matmul(np.diag(alpha),K))-(np.matmul(X,(np.diag(np.matmul(alpha,K)))))\n s = np.sum(np.square(mapping),axis=1)/np.size(alpha) \n\n s_matrix = np.reshape(s,[no_channels,no_timepoints])\n # np.save('sensitivity_map.npy',s_matrix)\n \n ### Generation of sensitivity map plot ###\n \n # Examples of x- and y-axis labels\n \n# channel_vector = ['P7','P4','Cz','Pz','P3','P8','O1','O2','T8','F8','C4','F4',\n# 'Fp2','Fz','C3','F3','Fp1','T7','F7','Oz','PO3','AF3','FC5',\n# 'FC1','CP5','CP1','CP2','CP6','AF4','FC2','FC6','PO4']\n#\n# time_vector = ['-100','0','100','200','300','400','500']\n\n plt.matshow(s_matrix)\n plt.xlabel('Time points')\n #plt.xticks(np.arange(0,no_timepoints,10),time_vector)\n #plt.yticks(np.arange(no_channels),channel_vector)\n plt.ylabel('EEG channels')\n plt.colorbar()\n plt.title('Sensitivity map SVM RBF kernel')\n # plt.show()\n \n return s_matrix, plt\n \n print('Sensitivity map computed. Number of support vectors for the classifier: {0}.'.format(len(support_array)))",
"def sharpen_model(common_words_file:TextIO ,kss: Dict[str, List[int]])->Dict:\n common_words_file = common_words_file.read().splitlines()\n kss_sharpened = {}\n for word, value in kss.items():\n if (judge(value[0]/value[1]) != 'neutral') or (word not in common_words_file):\n kss_sharpened[word] = value\n return kss_sharpened",
"def nominalSensitivities():\n #Scan ranges\n ang = np.linspace(-5*.3e-3,5*.3e-3,100)\n tx = np.linspace(-.3,.3,100)\n\n #Mirror Pair Sensitivities\n pitch2 = [mirrorPair(1000,primalign=[0,0,0,0,a,0]) for a in ang]\n yaw2 = [mirrorPair(1000,primalign=[0,0,0,a,0,0]) for a in ang]\n plt.figure('Pair')\n plt.plot(ang*180/pi*60,pitch2,label='Pitch')\n plt.plot(ang*180/pi*60,yaw2,label='Yaw')\n plt.title('SLF Mirror Pair Alignment Sensitivities')\n plt.grid()\n plt.legend(loc='upper center')\n plt.xlabel('Angular Error (arcmin)')\n plt.ylabel('HPD (arcsec)')\n\n #Secondary Sensitivities\n pitch = [mirrorPair(1000,secalign=[0,0,0,0,a,0]) for a in ang/20]\n yaw = [mirrorPair(1000,secalign=[0,0,0,a,0,0]) for a in ang/20]\n roll = [mirrorPair(1000,secalign=[0,0,0,0,0,a]) for a in ang/20]\n plt.figure('SecondaryAng')\n plt.semilogy(ang/20.*180/pi*60**2,pitch,label='Pitch')\n plt.plot(ang/20.*180/pi*60**2,yaw,label='Yaw')\n plt.plot(ang/20.*180/pi*60**2,roll,label='Roll')\n plt.grid()\n plt.legend(loc='upper center')\n plt.xlabel('Angular Error (arcsec)')\n plt.ylabel('HPD (arcsec)')\n plt.xlim([-5,5])\n plt.ylim([0,3])\n plt.title('SLF Secondary Alignment Sensitivities')\n decenter = [mirrorPair(1000,secalign=[t,0,0,0,0,0]) for t in tx]\n lateral = [mirrorPair(1000,secalign=[0,t,0,0,0,0]) for t in tx]\n despace = [mirrorPair(1000,secalign=[0,0,t,0,0,0]) for t in tx]\n plt.figure('SecondaryTx')\n plt.semilogy(tx,decenter,label='Decenter')\n plt.plot(tx,despace,label='Despace')\n plt.plot(tx,lateral,label='Lateral')\n plt.grid()\n plt.legend(loc='upper center')\n plt.xlabel('Translation Error (mm)')\n plt.ylabel('HPD (arcsec)')\n plt.title('SLF Secondary Translation Sensitivities')\n \n \n #Compensating behavior...\n \n\n return [pitch2,yaw2,pitch,yaw,decenter,lateral,despace]",
"def precompute_scoring():\n global volume_void_inclusion\n global attract_point_distances\n global perlin_values\n \n volume_void_inclusion = []\n for i,void in enumerate(volumes_void):\n inclusion = gh.PointInBrep(void,points_input,False)\n volume_void_inclusion.append(inclusion)\n \n attract_point_distances = []\n for i,point in enumerate(points_attractor):\n distances = gh.Division(gh.Distance(point,points_input),max_dist)\n attract_point_distances.append(distances)",
"def gain_standardization(self):\r\n \"\"\"\r\n load all gain factors from any hm stage (gains are identical for all SHM stages)\r\n \"\"\"\r\n gain_factors = []\r\n for i in range(self.number_of_paths):\r\n value = self.data_of_hm_cycle['coupon']['path_data'][0][0][0][i][4][0][0]\r\n gain_factors.append(value)\r\n gain_factors = np.array(gain_factors)\r\n gains_factor_new_dim = gain_factors[np.newaxis, ...]\r\n matrix_gains_2d = np.repeat(gains_factor_new_dim, self.signal_length, axis=0).T\r\n matrix_of_gains = matrix_gains_2d[:, :, np.newaxis]\r\n\r\n \"\"\"\r\n divide all signals by the gain factors such that all gains are standardized to one\r\n \"\"\"\r\n for i in range(self.num_of_hm_stages):\r\n entries = i*self.number_of_paths\r\n hm_cycle_set = self.sensor_data_flattened_[entries : entries + self.number_of_paths]\r\n divided_data = np.divide(hm_cycle_set, matrix_of_gains)\r\n self.sensor_data_flattened_[entries : entries + self.number_of_paths] = divided_data\r\n self.sensor_data_original_shape_[i, :, :, :] = divided_data\r\n\r\n return",
"def sensitivity(confusion):\n tp = np.array([confusion[i][i] for i in range(len(confusion))])\n return tp / np.sum(confusion, axis=1)",
"def evalFunctionsSens(self, funcsSens, config):\n nDV = self.DVGeo.getNDV()\n if nDV > 0:\n wfuncs = {}\n self.wimpress.evalFunctions(wfuncs)\n\n wSens = {}\n self.wimpress.evalFunctionsSens(wSens)\n\n # Accumulate the derivative into p1b and p2b\n p1b, p2b = geo_utils.eDist_b(self.coords[0, :], self.coords[1, :])\n if self.thickScaled:\n p1b /= self.D0\n p2b /= self.D0\n\n funcsSens[self.name + \"_thick\"] = self.DVGeo.totalSensitivity(\n np.array([[p1b, p2b]]), self.name, config=config\n )\n\n # And now we need the sensitivity of the conLoc calc\n p1b[:] = 0\n p2b[:] = 0\n p1b[0] += 0.5 / wfuncs[\"MAC\"]\n p2b[0] += 0.5 / wfuncs[\"MAC\"]\n\n tmpSens = self.DVGeo.totalSensitivity(np.array([[p1b, p2b]]), self.name, config=config)\n\n # And we need the sensitivity of conLoc wrt 'xLEMAC' and 'MAC'\n postLoc = 0.5 * (self.coords[0, 0] + self.coords[1, 0])\n for key in wSens[\"xLEMAC\"]:\n tmpSens[key] -= wSens[\"xLEMAC\"][key] / wfuncs[\"MAC\"]\n tmpSens[key] += wfuncs[\"xLEMAC\"] / wfuncs[\"MAC\"] ** 2 * wSens[\"MAC\"][key]\n tmpSens[key] -= postLoc / wfuncs[\"MAC\"] ** 2 * wSens[\"MAC\"][key]\n funcsSens[self.name + \"_MAC\"] = tmpSens",
"def get_sase(self, datain, points=None): \n try: #try to average over and array input\n\t\t\tdataout = np.mean(datain[-(points):])\n\t\t\tsigma = np.std( datain[-(points):])\n except: #if average fails use the scaler input\n print \"Detector is not a waveform PV, using scalar value\"\n dataout = datain\n sigma = -1\n return dataout, sigma",
"def analyze_datas(data_dict,analysis_attributes):\n analysis_methods = [\n ana_attr.method for ana_attr in analysis_attributes\n ]\n anal_fnc = {\n 'FSD': dec_tupl(ana_fixations_spatial_distribution, 'SMAP'),\n 'SD': dec_tupl(ana_saccades_distribution, 'PTS')\n }\n return [anal_fnc[ana_name](data_dict) for ana_name in analysis_methods]",
"def sense(p, Z):\n # TODO: insert your code here\n\n if Z == 'green':\n p = compute_measure_green(p, Z)\n elif Z == 'red':\n p = compute_measure_red(p, Z)\n\n norm = [float(i)/sum(p) for i in p]\n p = norm\n\n return p",
"def sense(p, Z):\n # TODO: insert your code here\n\n if Z == 'green':\n p = compute_measure_green(p, Z)\n elif Z == 'red':\n p = compute_measure_red(p, Z)\n\n norm = [float(i)/sum(p) for i in p]\n p = norm\n\n return p",
"def monitor_normalize(sansdata,mon0=1e8):\n monitor=sansdata.metadata['run.moncnt']\n result=sansdata.data*mon0/monitor\n res=SansData()\n res.data=result\n res.metadata=deepcopy(sansdata.metadata)\n res.qx=copy(sansdata.qx)\n res.qy=copy(sansdata.qy)\n res.theta=copy(sansdata.theta)\n return res",
"def sensitivity(gas, surf, old_data, temp, dk, thermo=False):\n rxns = []\n sens1 = []\n sens2 = []\n sens3 = []\n sens4 = []\n sens5 = []\n sens6 = []\n sens7 = []\n sens8 = []\n sens9 = []\n sens10 = []\n sens11 = []\n sens12 = []\n\n gas_out_data, gas_names_data, dist_array_data, T_array_data = old_data\n\n reference = []\n for a in range(len(gas_names_data)):\n reference.append([gas_names_data[a], [gas_out_data[:, a]]])\n\n # getting the ratio\n for x in reference:\n if x[0] == 'CH4(2)':\n ch4_in = x[1][0][0]\n if x[0] == 'O2(3)':\n o2_in = x[1][0][0]\n if x[0] == 'Ar':\n ar_in = x[1][0][0]\n ratio = ch4_in / (2 * o2_in)\n moles_in = [ch4_in, o2_in, ar_in]\n\n for x in reference:\n if x[0] == 'CH4(2)':\n ch4_in = x[1][0][0]\n ch4_out = x[1][0][-1]\n if ch4_out < 0:\n ch4_out = 0.\n ch4_depletion = ch4_in - ch4_out\n if ch4_depletion <= 1.0e-8:\n ch4_depletion = 1.0e-8\n reference_ch4_conv = 1.0e-8\n else:\n reference_ch4_conv = ch4_depletion / ch4_in # Sensitivity definition 7: CH4 conversion\n if x[0] == 'Ar':\n ar = x[1][0][-1]\n if x[0] == 'O2(3)':\n o2_out = x[1][0][-1]\n if o2_out < 0:\n o2_out = 1.0e-15 # O2 can't be negative\n elif o2_out > o2_in:\n o2_out = o2_in # O2 can't be created, to make it equal to O2 in\n if x[0] == 'CO(7)':\n co_out = x[1][0][-1]\n if x[0] == 'H2(6)':\n h2_out = x[1][0][-1]\n if x[0] == 'H2O(5)':\n h2o_out = x[1][0][-1]\n if x[0] == 'CO2(4)':\n co2_out = x[1][0][-1]\n\n if reference_ch4_conv <= 1.0e-8:\n reference_h2_sel = 1.0e-8\n reference_co_sel = 1.0e-8\n reference_syngas_selectivity = 1.0e-8\n reference_syngas_yield = 1.0e-8\n reference_co_yield = 1.0e-8\n reference_h2_yield = 1.0e-8\n reference_full_oxidation_selectivity = 1.0e-8\n reference_full_oxidation_yield = 1.0e-8\n else:\n # negative sensitivity is higher selectivity\n reference_h2_sel = h2_out / (ch4_depletion * 2) # Sensitivity definition 5: H2 selectivity\n if reference_h2_sel <= 0:\n reference_h2_sel = 1.0e-15 # selectivity can't be 0\n\n reference_co_sel = co_out / ch4_depletion # Sensitivity definition 3: CO selectivity\n if reference_co_sel <= 0:\n reference_co_sel = 1.0e-15 # selectivity can't be 0\n\n reference_syngas_selectivity = reference_co_sel + reference_h2_sel # Sensitivity definition 1: SYNGAS selectivity\n\n reference_syngas_yield = reference_syngas_selectivity * reference_ch4_conv # Sensitivity definition 2: SYNGAS yield\n if reference_syngas_yield <= 0:\n reference_syngas_yield = 1.0e-15 # yield can't be 0\n\n reference_co_yield = co_out / ch4_in # Sensitivity definition 4: CO % yield\n # reference_co_yield = reference_co_sel * reference_ch4_conv\n\n reference_h2_yield = h2_out / (2 * ch4_in) # Sensitivity definition 6: H2 % yield\n # reference_h2_yield = reference_h2_sel * reference_ch4_conv\n\n # Sensitivity definition 8: H2O + CO2 selectivity\n reference_h2o_sel = h2o_out / (ch4_depletion * 2)\n reference_co2_sel = co2_out / ch4_depletion\n if reference_h2o_sel <= 0:\n reference_h2o_sel = 1.0e-15 # H2O selectivity can't be 0\n if reference_co2_sel <= 0:\n reference_co2_sel = 1.0e-15 # CO2 selectivity can't be 0\n reference_full_oxidation_selectivity = reference_h2o_sel + reference_co2_sel\n\n # Sensitivity definition 9: H2O + CO2 yield\n reference_full_oxidation_yield = reference_full_oxidation_selectivity * reference_ch4_conv\n\n # Sensitivity definition 10: exit temperature\n reference_exit_temp = T_array_data[-1]\n\n # Sensitivity definition 11: peak temperature\n reference_peak_temp = max(T_array_data)\n\n # Sensitivity definition 12: distance to peak temperautre\n reference_peak_temp_dist = dist_array_data[T_array_data.index(max(T_array_data))]\n\n # run the simulations\n if thermo is True:\n for m in range(surf.n_species):\n s = surf.species(m)\n original_coeffs = s.thermo.coeffs\n perturbed_coeffs = np.ones_like(original_coeffs)\n perturbed_coeffs[0] = original_coeffs[0]\n perturbed_coeffs[1:6] = original_coeffs[1:6]\n perturbed_coeffs[7:13] = original_coeffs[7:13]\n perturbed_coeffs[14] = original_coeffs[14]\n # perturbed_coeffs[6] = original_coeffs[6] + original_coeffs[6]*dk\n # perturbed_coeffs[13] = original_coeffs[13] + original_coeffs[13]*dk\n perturbed_coeffs[6] = original_coeffs[6] + dk\n perturbed_coeffs[13] = original_coeffs[13] + dk\n s.thermo = ct.NasaPoly2(100.000, 5000.000, ct.one_atm, perturbed_coeffs)\n surf.modify_species(m, s)\n c = monolithFull(gas, surf, temp, moles_in)\n\n gas_out, surf_out, gas_names, surf_names, dist_array, T_array = c\n\n new_amts = []\n for a in range(len(gas_names)):\n new_amts.append([gas_names[a], [gas_out[:, a]]])\n\n for x in new_amts:\n if x[0] == 'CH4(2)':\n new_ch4_in = x[1][0][0]\n new_ch4_out = x[1][0][-1]\n if new_ch4_out < 0:\n new_ch4_out = 0.\n new_ch4_depletion = new_ch4_in - new_ch4_out\n if new_ch4_depletion <= 1e-8:\n new_ch4_depletion = 1e-8\n new_ch4_conv = 1e-8\n else:\n new_ch4_conv = new_ch4_depletion / new_ch4_in # Sensitivity definition 7: CH4 conversion\n if x[0] == 'Ar':\n ar = x[1][0][-1]\n if x[0] == 'O2(3)':\n new_o2_in = x[1][0][0]\n new_o2_out = x[1][0][-1]\n if new_o2_out < 0:\n new_o2_out = 1.0e-15\n elif new_o2_out > new_o2_in:\n new_o2_out = new_o2_in\n if x[0] == 'CO(7)':\n new_co_out = x[1][0][-1]\n if x[0] == 'H2(6)':\n new_h2_out = x[1][0][-1]\n if x[0] == 'H2O(5)':\n new_h2o_out = x[1][0][-1]\n if x[0] == 'CO2(4)':\n new_co2_out = x[1][0][-1]\n\n if new_ch4_conv <= 1e-8:\n new_h2_sel = 1.0e-8\n new_co_sel = 1.0e-8\n new_syngas_selectivity = 1.0e-8\n new_syngas_yield = 1.0e-8\n new_co_yield = 1.0e-8\n new_h2_yield = 1.0e-8\n new_full_oxidation_selectivity = 1.0e-8\n new_full_oxidation_yield = 1.0e-8\n else:\n new_h2_sel = new_h2_out / (new_ch4_depletion * 2) # Sensitivity definition 5: H2 selectivity\n new_co_sel = new_co_out / new_ch4_depletion # Sensitivity definition 3: CO selectivity\n new_syngas_selectivity = new_co_sel + new_h2_sel # Sensitivity definition 1: SYNGAS selectivity\n new_syngas_yield = new_syngas_selectivity * new_ch4_conv # Sensitivity definition 2: SYNGAS yield\n new_co_yield = new_co_out / new_ch4_in # Sensitivity definition 4: CO % yield\n new_h2_yield = new_h2_out / (2 * new_ch4_in) # Sensitivity definition 6: H2 % yield\n new_h2o_sel = new_h2o_out / (new_ch4_depletion * 2) # Sensitivity definition 8: H2O + CO2 selectivity\n new_co2_sel = new_co2_out / new_ch4_depletion\n new_full_oxidation_selectivity = new_h2o_sel + new_co2_sel\n new_full_oxidation_yield = new_full_oxidation_selectivity * new_ch4_conv # Sensitivity definition 9: C2O + CO2 yield\n\n Sens5 = (new_h2_sel - reference_h2_sel) / (reference_h2_sel * dk)\n sens5.append(Sens5)\n\n Sens3 = (new_co_sel - reference_co_sel) / (reference_co_sel * dk)\n sens3.append(Sens3)\n\n Sens1 = (new_syngas_selectivity - reference_syngas_selectivity) / (reference_syngas_selectivity * dk)\n sens1.append(Sens1)\n\n Sens2 = (new_syngas_yield - reference_syngas_yield) / (reference_syngas_yield * dk)\n sens2.append(Sens2)\n\n Sens4 = (new_co_yield - reference_co_yield) / (reference_co_yield * dk)\n sens4.append(Sens4)\n\n Sens6 = (new_h2_yield - reference_h2_yield) / (reference_h2_yield * dk)\n sens6.append(Sens6)\n\n Sens7 = (new_ch4_conv - reference_ch4_conv) / (\n reference_ch4_conv * dk)\n sens7.append(Sens7)\n\n Sens8 = (new_full_oxidation_selectivity - reference_full_oxidation_selectivity) / (\n reference_full_oxidation_selectivity * dk)\n sens8.append(Sens8)\n\n Sens9 = (new_full_oxidation_yield - reference_full_oxidation_yield) / (reference_full_oxidation_yield * dk)\n sens9.append(Sens9)\n\n new_exit_temp = T_array[-1] # Sensitivity definition 10: exit temperature\n Sens10 = (new_exit_temp - reference_exit_temp) / (reference_exit_temp * dk)\n sens10.append(Sens10)\n\n new_peak_temp = max(T_array) # Sensitivity definition 11: peak temperature\n Sens11 = (new_peak_temp - reference_peak_temp) / (reference_peak_temp * dk)\n sens11.append(Sens11)\n\n new_peak_temp_dist = dist_array[\n T_array.index(max(T_array))] # Sensitivity definition 12: dist to peak temperature\n Sens12 = (new_peak_temp_dist - reference_peak_temp_dist) / (reference_peak_temp_dist * dk)\n sens12.append(Sens12)\n\n print \"%d %s %.3F %.3F\" % (m, surf.species_name(m), Sens1, Sens2)\n rxns.append(surf.species_name(m))\n\n # this step is essential, otherwise mechanism will have been altered\n s.thermo = ct.NasaPoly2(100.000, 5000.000, ct.one_atm, original_coeffs)\n surf.modify_species(m, s)\n else:\n for rxn in range(surf.n_reactions):\n c = monolithFull(gas, surf, temp, moles_in, sens=[dk, rxn])\n gas_out, surf_out, gas_names, surf_names, dist_array, T_array = c\n\n new_amts = []\n for a in range(len(gas_names)):\n new_amts.append([gas_names[a], [gas_out[:, a]]])\n\n for x in new_amts:\n if x[0] == 'CH4(2)':\n new_ch4_in = x[1][0][0]\n new_ch4_out = x[1][0][-1]\n if new_ch4_out < 0:\n new_ch4_out = 0.\n new_ch4_depletion = new_ch4_in - new_ch4_out\n if new_ch4_depletion <= 1e-8:\n new_ch4_depletion = 1e-8\n new_ch4_conv = 1e-8\n else:\n new_ch4_conv = new_ch4_depletion / new_ch4_in # Sensitivity definition 7: CH4 conversion\n if x[0] == 'Ar':\n ar = x[1][0][-1]\n if x[0] == 'O2(3)':\n new_o2_in = x[1][0][0]\n new_o2_out = x[1][0][-1]\n if new_o2_out < 0:\n new_o2_out = 1.0e-15\n elif new_o2_out > new_o2_in:\n new_o2_out = new_o2_in\n if x[0] == 'CO(7)':\n new_co_out = x[1][0][-1]\n if x[0] == 'H2(6)':\n new_h2_out = x[1][0][-1]\n if x[0] == 'H2O(5)':\n new_h2o_out = x[1][0][-1]\n if x[0] == 'CO2(4)':\n new_co2_out = x[1][0][-1]\n\n if new_ch4_conv <= 1e-8:\n new_h2_sel = 1.0e-8\n new_co_sel = 1.0e-8\n new_syngas_selectivity = 1.0e-8\n new_syngas_yield = 1.0e-8\n new_co_yield = 1.0e-8\n new_h2_yield = 1.0e-8\n new_full_oxidation_selectivity = 1.0e-8\n new_full_oxidation_yield = 1.0e-8\n else:\n new_h2_sel = new_h2_out / (new_ch4_depletion * 2) # Sensitivity definition 5: H2 selectivity\n new_co_sel = new_co_out / new_ch4_depletion # Sensitivity definition 3: CO selectivity\n new_syngas_selectivity = new_co_sel + new_h2_sel # Sensitivity definition 1: SYNGAS selectivity\n new_syngas_yield = new_syngas_selectivity * new_ch4_conv # Sensitivity definition 2: SYNGAS yield\n new_co_yield = new_co_out / new_ch4_in # Sensitivity definition 4: CO % yield\n new_h2_yield = new_h2_out / (2 * new_ch4_in) # Sensitivity definition 6: H2 % yield\n new_h2o_sel = new_h2o_out / (new_ch4_depletion * 2) # Sensitivity definition 8: H2O + CO2 selectivity\n new_co2_sel = new_co2_out / new_ch4_depletion\n new_full_oxidation_selectivity = new_h2o_sel + new_co2_sel\n new_full_oxidation_yield = new_full_oxidation_selectivity * new_ch4_conv # Sensitivity definition 9: C2O + CO2 yield\n\n Sens5 = (new_h2_sel - reference_h2_sel) / (reference_h2_sel * dk)\n sens5.append(Sens5)\n\n Sens3 = (new_co_sel - reference_co_sel) / (reference_co_sel * dk)\n sens3.append(Sens3)\n\n Sens1 = (new_syngas_selectivity - reference_syngas_selectivity) / (reference_syngas_selectivity * dk)\n sens1.append(Sens1)\n\n Sens2 = (new_syngas_yield - reference_syngas_yield) / (reference_syngas_yield * dk)\n sens2.append(Sens2)\n\n Sens4 = (new_co_yield - reference_co_yield) / (reference_co_yield * dk)\n sens4.append(Sens4)\n\n Sens6 = (new_h2_yield - reference_h2_yield) / (reference_h2_yield * dk)\n sens6.append(Sens6)\n\n Sens7 = (new_ch4_conv - reference_ch4_conv) / (\n reference_ch4_conv * dk)\n sens7.append(Sens7)\n\n Sens8 = (new_full_oxidation_selectivity - reference_full_oxidation_selectivity) / (\n reference_full_oxidation_selectivity * dk)\n sens8.append(Sens8)\n\n Sens9 = (new_full_oxidation_yield - reference_full_oxidation_yield) / (reference_full_oxidation_yield * dk)\n sens9.append(Sens9)\n\n new_exit_temp = T_array[-1] # Sensitivity definition 10: exit temperature\n Sens10 = (new_exit_temp - reference_exit_temp) / (reference_exit_temp * dk)\n sens10.append(Sens10)\n\n new_peak_temp = max(T_array) # Sensitivity definition 11: peak temperature\n Sens11 = (new_peak_temp - reference_peak_temp) / (reference_peak_temp * dk)\n sens11.append(Sens11)\n\n new_peak_temp_dist = dist_array[T_array.index(max(T_array))] # Sensitivity definition 12: dist to peak temperature\n Sens12 = (new_peak_temp_dist - reference_peak_temp_dist) / (reference_peak_temp_dist * dk)\n sens12.append(Sens12)\n\n print \"%d %s %.3F %.3F\" % (rxn, surf.reaction_equations()[rxn], Sens1, Sens2)\n rxns.append(surf.reaction_equations()[rxn])\n\n return rxns, sens1, sens2, sens3, sens4, sens5, sens6, sens7, sens8, sens9, sens10, sens11, sens12",
"def sensitivity(base_case,init_df):\n SA_df = init_df.copy()\n M = init_df.index.size\n categories=list(init_df)\n N = len(categories)\n row = 0\n for x in range(M): \n if init_df.index[x] == base_case: \n basecase_index = row\n row += 1\n for x in range(M): \n if init_df.index[x] == base_case: \n for y in range(N): \n SA_df.iloc[x,y] = 0\n else: \n for y in range(N): \n if float(init_df.iloc[basecase_index,y]) == 0: \n SA_df.iloc[x,y] = np.nan\n else:\n SA_df.iloc[x,y] = (init_df.iloc[x,y]-init_df.iloc[basecase_index,y])/init_df.iloc[basecase_index,y]*100 \n return SA_df",
"def sensitivity_analysis(model, image_tensor, device, postprocess='abs'):\r\n if postprocess not in [None, 'abs', 'square']:\r\n raise ValueError(\"postprocess must be None, 'abs' or 'square'\")\r\n \r\n # Forward pass.\r\n X = torch.from_numpy(image_tensor) # convert numpy or list to tensor\r\n X.unsqueeze_(0) # add channel of 1\r\n X.unsqueeze_(0) # mimic batch of 1\r\n X = X.to(device)\r\n X.requires_grad_()\r\n output = model(X)\r\n \r\n # Backward pass.\r\n model.zero_grad()\r\n output.backward()\r\n \r\n relevance_map = X.grad.data[0,0].cpu().numpy()\r\n \r\n # Postprocess the relevance map.\r\n if postprocess == 'abs': # as in Simonyan et al. (2014)\r\n return np.abs(relevance_map)\r\n elif postprocess == 'square': # as in Montavon et al. (2018)\r\n return relevance_map**2\r\n elif postprocess is None:\r\n return relevance_map",
"def computeRmse(model, data, n , sc):\n truth = data.map( lambda x: ((x[0], x[1]), x[2]) )\n truth.cache()\n ##print 'test zhou 0.....', truth.count() , '............', truth.take(10)\n\n predictions = model.predictAll(data.map(lambda x: (x[0], x[1])))\n predictions.cache()\n # here let's rescale predicted ratings to 0-10 scale\n maxPrediction = predictions.map(lambda x: x[2]).max()\n minPrediction = predictions.map(lambda x: x[2]).min()\n maxRate = RatingScale\n minRate = RatingScaleMin\n ##print 'test zhou 1......', predictions.count(), '............', predictions.take(10)\n\n #predictionsAndRatings = predictions.map(lambda x: ((x[0], x[1]), (x[2]-minPrediction)/(maxPrediction-minPrediction)*(maxRate-minRate)+minRate )).join(data.map(lambda x: ((x[0], x[1]), x[2]))).values()\n\n\n #predictedRating = predictions.map(lambda x: ((x[0], x[1]), (x[2]-minPrediction)/(maxPrediction-minPrediction)*(maxRate-minRate)+minRate ) )\n predictedRating = predictions.map(lambda x: ((x[0], x[1]), x[2] ) )\n predictedRating.cache()\n ##predictedRating.checkpoint()\n ##print 'test zhou 2.......', predictedRating.count(), '............', predictedRating.take(10)\n\n\n \n\n\n predictionsAndRatings = predictedRating.join(truth).values()\n #predictionsAndRatings = sc.union(predictedRating, truth)\n predictionsAndRatings.cache()\n #print 'test zhou 3........', predictionsAndRatings.count(), '............', predictionsAndRatings.take(10)\n #predictionsAndRatings = predictions.map(lambda x: ((x[0], x[1]), x[2])).join(data.map(lambda x: ((x[0], x[1]), x[2]))).values()\n \n return sqrt(predictionsAndRatings.map(lambda x: (x[0] - x[1]) ** 2).reduce(add) / float(n))\n #return 1.0",
"def compute_class_sens_spec(pred, label, class_num):\n\n # extract sub-array for specified class\n class_pred = pred[class_num]\n class_label = label[class_num]\n\n ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n \n # compute:\n \n # true positives\n tp = np.sum((class_pred == 1) & (class_label == 1))\n\n # true negatives\n tn = np.sum((class_pred == 0) & (class_label == 1))\n \n #false positives\n fp = np.sum((class_pred == 1) & (class_label == 0))\n \n # false negatives\n fn = np.sum((class_pred == 0) & (class_label == 0))\n\n # compute sensitivity and specificity\n sensitivity = tp / (tp + fn)\n specificity = tn / (tn + fp)\n\n ### END CODE HERE ###\n\n return sensitivity, specificity",
"def stats(self, s_sample, d_sample, x_sample, wav_len):\n\t\tpass\n\t\t# s_STMS_sample, d_STMS_sample, x_STMS_sample = self.transfrom_stats(s_sample,\n\t\t# \td_sample, x_sample, wav_len)\n\t\t# smm_sample = tf.math.truediv(s_STMS_sample, x_STMS_sample)\n\t\t# self.smm_map.stats(smm_sample)",
"def calc_conditional_entropy(map,data_stat,attribute):\n #acquire the data info of the attribute stored in data_stat\n data_info = data_stat[attribute]\n #acquire the label info\n # label_col = len(data_stat)-1\n label_col = data_stat.keys()[-1]\n # print(data_stat.keys())\n label_info = data_stat[label_col]\n #acquire the data \n data = map[attribute]\n labels = map[label_col]\n conditional_entropy =0\n for data_type in data_info:\n specific_entropy = 0\n for label_type in label_info: \n #attribute data indices where all data entries are equal to a speicifc value\n data_with_spec_val_idx = data_info[data_type]\n #label indices where all labels are of same value\n spec_label_idx = label_info[label_type]\n #the intersection of the two indices above\n intersect_idx = np.intersect1d(data_with_spec_val_idx,spec_label_idx)\n #conditional probability of label being of specific value given speicific data value\n temp_prob = len(intersect_idx)/float(len(data_with_spec_val_idx))\n if temp_prob!=0:\n specific_entropy += temp_prob*math.log(temp_prob,2)\n specific_entropy = -specific_entropy\n prob = len(data_with_spec_val_idx)/float(len(data))\n conditional_entropy += prob * specific_entropy\n return conditional_entropy",
"def extractImpact(data):\n return {key : array([hellingerDistance(i.px, data['{}'].px) for i in val]) for key, val in data.items() if key != '{}'}",
"def _process(self, data: np.ndarray) -> np.ndarray:\n nominals = unp.nominal_values(data)\n min_y, max_y = np.min(nominals), np.max(nominals)\n\n return (data - min_y) / (max_y - min_y)",
"def sensitivityreport(self,whichstream_):\n res = __library__.MSK_XX_sensitivityreport(self.__nativep,whichstream_)\n if res != 0:\n _,msg = self.__getlasterror(res)\n raise Error(rescode(res),msg)",
"def process_pssm_data(self):\n\n self.pssm_data = self._mask_pssm(self.pssm_data,nmask=self.nmask)\n self.pssm_data = self._filter_pssm(self.pssm_data)\n self.pssm_data = self._smooth_pssm(self.pssm_data,msmooth=self.nsmooth)\n self.pssm_data = np.mean(self.pssm_data,1)",
"def selectedComparisons(samples_dict):\n sectors=\"peripherals\",\"intermediaries\",\"hubs\"\n ks_measures={}\n for analyses_type in samples_dict[sectors[0]]:\n ks_measures[analyses_type]={}\n for analysis_grouping in samples_dict[sectors[0]][analyses_type]:\n ks_measures[analyses_type][analysis_grouping]={}\n if samples_dict[sectors[0]][analyses_type][analysis_grouping]==dict:\n ks_measures[analyses_type][analysis_grouping]={}\n for analysis in samples_dict[sectors[0]][analyses_type][analysis_grouping]:\n for var in samples_dict[sectors[0]][analyses_type][analysis_grouping][analysis]:\n samples_peripherals=samples_dict[sectors[0]][analyses_type][analysis_grouping][analysis]\n samples_intermediaries=samples_dict[sectors[1]][analyses_type][analysis_grouping][analysis]\n samples_hubs=samples_dict[sectors[2]][analyses_type][analysis_grouping][analysis]\n ks_measures[analysis][\"peripherals_intermediaries\"]=P.kolmogorovSmirnovTest(samples_peripherals,samples_intermediaries)\n ks_measures[analysis][\"peripherals_hubs\"]=P.kolmogorovSmirnovTest(samples_peripherals,samples_hubs)\n ks_measures[analysis][\"hubs_intermediaries\"]=P.kolmogorovSmirnovTest(samples_hubs,samples_intermediaries)\n else:\n for var in samples_dict[sectors[0]][analyses_type][analysis_grouping]:\n samples_peripherals=samples_dict[sectors[0]][analyses_type][analysis_grouping]\n samples_intermediaries=samples_dict[sectors[1]][analyses_type][analysis_grouping]\n samples_hubs=samples_dict[sectors[2]][analyses_type][analysis_grouping]\n\n\n\n samples[sector][analyses][analysis_grouping]=updateDict(samples[sector][analyses][analysis_grouping],getSamples(authors_analysis[analyses][author][analysis_grouping]))",
"def scaling():\n \n for i in range(cfg.nfea):\n dm = 0\n var = 0\n for j in range(cfg.ntrain):\n dm += cfg.a[j,i]\n dm = dm/cfg.ntrain\n \n for j in range(cfg.ntrain):\n var += (cfg.a[j,i]-dm)**2\n\n var = var/cfg.ntrain\n var = np.sqrt(var)\n \n if var >= 10**(-5):\n cfg.clin[i] = 1.0/var \n cfg.dlin[i] = -dm/var \n \n else: \n if np.abs(dm)<=1.0:\n cfg.clin[i] = 1.0\n cfg.dlin[i] = 0.0 \n else: \n cfg.clin[i] = 1.0/dm\n cfg.dlin[i] = 0.0 \n \n for j in range(cfg.ntrain):\n cfg.a_scaled[j,i] = cfg.clin[i]*cfg.a[j,i] + cfg.dlin[i]\n \n return",
"def survey_detection_effieciency():\n baseline = 365 #days\n # TODO: Rerun with 1024, add praesepe line\n max_num_observations = 1024\n min_num_observations = 16\n num_clumps = 4\n num_iterations = 10000\n \n if not os.path.exists(\"data/aas_survey_detection_efficiency.pickle\"):\n data_dict = {\"clumpy\" : {1. : [], 10. : [], 100 : []}, \"uniform\" : {1. : [], 10. : [], 100 : []}}\n \n for timescale in [1., 10., 100.]:\n for sampling in [\"clumpy\", \"uniform\"]: #, \"random\"]:\n if sampling == \"random\":\n mjd = np.random.random(max_num_observations)*baseline\n elif sampling == \"clumpy\":\n sparse_samples = np.random.random(max_num_observations/2)*baseline\n \n clumps = []\n days = []\n sum = 0.\n pts_per_clump = max_num_observations / 2 / num_clumps\n for ii in range(num_clumps):\n day = np.random.randint(365)\n if day in days: continue\n \n days.append(day)\n clumpy_samples = np.linspace(day+0.1, day+0.6, pts_per_clump)\n clumps.append(clumpy_samples)\n \n clumps.append(sparse_samples)\n mjd = np.concatenate(tuple(clumps))\n \n plt.plot(mjd, [1.]*len(mjd), 'ro', alpha=0.4)\n plt.show()\n \n elif sampling == \"uniform\":\n mjd = np.linspace(0., baseline, max_num_observations)\n \n for jj in range(num_iterations):\n lc = random_praesepe_light_curve()\n if len(lc.mag) < 100: continue\n \n dupe_mags = np.array(lc.mag*15)\n dupe_err = np.array(list(lc.error)*15)\n \n shuffled_idx = np.arange(0, len(dupe_mags))\n np.random.shuffle(shuffled_idx)\n \n mags = dupe_mags[shuffled_idx]\n err = dupe_err[shuffled_idx]\n \n sim_light_curve = simu.SimulatedLightCurve(mjd=mjd, mag=mags[:len(mjd)], error=err[:len(mjd)])\n sim_light_curve.addMicrolensingEvent(tE=timescale)\n #sim_light_curve.plot()\n \n delta_chi_squareds = []\n sim_mjd = sim_light_curve.mjd\n sim_mag = sim_light_curve.mag\n sim_err = sim_light_curve.error\n while True:\n if len(sim_mjd) < min_num_observations: break\n \n dcs = simu.compute_delta_chi_squared((sim_mjd, sim_mag, sim_err), force_fit=True)\n delta_chi_squareds.append(dcs)\n \n prune = np.arange(len(sim_mjd))\n np.random.shuffle(prune)\n prune = prune[::2]\n sim_mjd = sim_mjd[prune]\n sim_mag = sim_mag[prune]\n sim_err = sim_err[prune]\n \n data_dict[sampling][timescale].append(delta_chi_squareds)\n \n f = open(\"data/aas_survey_detection_efficiency.pickle\", \"w\")\n pickle.dump(data_dict, f)\n f.close()\n \n f = open(\"data/aas_survey_detection_efficiency.pickle\", \"r\")\n data_dict = pickle.load(f)\n \n # Plotting stuff\n plt.figure(figsize=(15,15))\n dcs_cutoff = 300.\n num_observations = [2**x for x in range(int(np.log2(max_num_observations)), int(np.log2(min_num_observations))-1, -1)]\n linestyles = {\"uniform\" : \"--\", \"clumpy\" : \"-\"}\n linecolors = {1. : \"k\", 10. : \"r\", 100. : \"c\"}\n for sampling in data_dict.keys():\n for timescale in data_dict[sampling].keys():\n data = np.array(data_dict[sampling][timescale])\n \n efficiencies = []\n for col,num_obs in enumerate(num_observations):\n efficiencies.append(np.sum(data[:,col] > dcs_cutoff) / len(data[:,col]))\n \n plt.plot(np.log2(num_observations), efficiencies, ls=linestyles[sampling], color=linecolors[timescale], label=r\"$t_E={}$ day, {} sampling\".format(int(timescale), sampling), lw=3)\n \n #plt.axvline(np.log2(625.), c=\"g\", ls=\"--\", lw=2, label=\"PTF Praesepe fields\")\n \n plt.xlabel(\"Number of Observations / 1 year\", size=label_font_size)\n plt.ylabel(r\"Detection Efficiency $\\mathcal{E}(t_E)$\", size=label_font_size)\n plt.title(\"Simulated Detection Efficiency for\\nDifferent Sampling Patterns\", size=title_font_size)\n \n # Change tick label size\n ax = plt.gca()\n for label in ax.get_xticklabels() + ax.get_yticklabels():\n label.set_fontsize(tick_font_size)\n \n ax.set_xticklabels(num_observations[::-1])\n \n legend = plt.legend(loc=\"upper left\", shadow=True, fancybox=True)\n legendtext = legend.get_texts()\n plt.setp(legendtext, fontsize=tick_font_size) # the legend text fontsize\n plt.tight_layout()\n #plt.show()\n plt.savefig(\"plots/aas_survey_detection_efficiency.png\")"
] | [
"0.58871394",
"0.58342505",
"0.5490516",
"0.53566873",
"0.53259766",
"0.532161",
"0.5320019",
"0.52899104",
"0.52503693",
"0.52484775",
"0.52450603",
"0.5235667",
"0.5226603",
"0.5213607",
"0.5213607",
"0.5200309",
"0.5169606",
"0.51651996",
"0.5151721",
"0.5133345",
"0.5067943",
"0.50599563",
"0.5059527",
"0.5021012",
"0.5017073",
"0.50149",
"0.5010495",
"0.50048375",
"0.49885377",
"0.49829668"
] | 0.7324558 | 0 |
Given a SansData object, the transmissions and blocked beam, correct for the blocked beam. | def correct_blocked_beam(sample,blocked_beam,transmission):
#it would probably be more pleasant to have keyword arguments and to check
#for their presence so that a user of the class doesn't have to know the
#function signature. The advantage of the current method is that an error is
#automatically raised if the user doesn't pass a required parameter and there should
#be no question of whether a parameter is actually required or not. Here, I am letting
#the clarity trump convenience.
result=(sample.data-blocked_beam.data)/transmission
res=SansData()
res.data=result
res.metadata=deepcopy(sample.metadata)
res.qx=copy(sample.qx)
res.qy=copy(sample.qy)
res.theta=copy(sample.theta)
return res | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def dataPtoTB(self,u):\n n = self.ues[u].prbs\n [tbSbits,mod,bits,mcs__] = self.setMod(u,n)\n if self.schType[0:2]=='PF':\n if len(self.ues[u].pastTbsz)>self.promLen:\n self.ues[u].pastTbsz.popleft()\n self.ues[u].pastTbsz.append(self.ues[u].tbsz)\n\n self.ues[u].tbsz = tbSbits\n self.ues[u].MCS = mcs__\n self.setBLER(u)\n tbSize = int(float(tbSbits)/8) # TB size in bytes\n self.printDebDataDM('TBs: '+str(tbSize)+' nrb: '+str(n)+' FreeSp: '+str(self.queue.getFreeSpace())+'<br>')\n pks_s = 0\n list_p = []\n while pks_s<tbSize and len(self.ues[u].bearers[0].buffer.pckts)>0:\n pacD = self.ues[u].bearers[0].buffer.removePckt()\n pks_s = pks_s + pacD.size\n list_p.append(pacD.secNum)\n\n insrt = self.insertTB(self.ues[u].TBid,mod,u,'data',list_p,n,min(int(pks_s),tbSize))\n if (pks_s - tbSize)>0:\n pacD.size = pks_s - tbSize\n self.ues[u].bearers[0].buffer.insertPcktLeft(pacD)\n return self.ues[u].symb",
"def filter_beam(self, setting):\n\n self.beam_filter = setting\n\n # In manual mode determine number of raw invalid and number of 3 beam solutions\n # 3 beam solutions if selected\n if self.beam_filter > 0:\n\n # Find invalid raw data\n valid_vel = np.ones(self.raw_vel_mps.shape)\n valid_vel[np.isnan(self.raw_vel_mps)] = 0\n\n # Determine how many beams transformed coordinates are valid\n valid_vel_sum = np.sum(valid_vel, 0)\n valid = np.ones(valid_vel_sum.shape)\n\n # Compare number of valid beams or coordinates to filter value\n valid[valid_vel_sum < self.beam_filter] = False\n\n # Save logical of valid data to object\n self.valid_data[5, :] = valid\n\n else:\n\n # Apply automatic filter\n # ----------------------\n # Find all 3 beam solutions\n self.filter_beam(3)\n beam_3_valid_data = copy.deepcopy(self.valid_data)\n self.filter_beam(4)\n valid_3_beams = np.logical_xor(beam_3_valid_data[5, :], self.valid_data[5, :])\n n_ens = len(self.valid_data[5, :])\n idx = np.where(valid_3_beams == True)[0]\n\n # If 3 beam solutions exist evaluate there validity\n if len(idx) > 0:\n\n # Identify 3 beam solutions that appear to be invalid\n n3_beam_ens = len(idx)\n\n # Check each three beam solution for validity\n for m in range(n3_beam_ens):\n\n # Use before and after values to check 3-beam solution\n # but make sure the ensemble is not the first or last.\n if (idx[m] > 1) and (idx[m] < n_ens):\n\n # Find nearest 4 beam solutions before and after\n # 3 beam solution\n ref_idx_before = np.where(self.valid_data[5, :idx[m]] == True)[0]\n if len(ref_idx_before) > 0:\n ref_idx_before = ref_idx_before[-1]\n else:\n ref_idx_before = None\n\n ref_idx_after = np.where(self.valid_data[5, idx[m]:] == True)[0]\n if len(ref_idx_after) > 0:\n ref_idx_after = idx[m] + ref_idx_after[0]\n else:\n ref_idx_after = None\n\n if (ref_idx_after is not None) and (ref_idx_before is not None):\n u_ratio = (self.u_mps[idx[m]]) / ((self.u_mps[ref_idx_before]\n + self.u_mps[ref_idx_after]) / 2.) - 1\n v_ratio = (self.v_mps[idx[m]]) / ((self.v_mps[ref_idx_before]\n + self.v_mps[ref_idx_after]) / 2.) - 1\n else:\n u_ratio = 1\n v_ratio = 1\n\n # If 3-beam differs from 4-beam by more than 50% mark it invalid\n if (np.abs(u_ratio) > 0.5) and (np.abs(v_ratio) > 0.5):\n self.valid_data[5, idx[m]] = False\n else:\n self.valid_data[5, idx[m]] = True\n\n self.beam_filter = -1\n\n # Combine all filter data to composite valid data\n self.valid_data[0, :] = np.all(self.valid_data[1:, :], 0)\n self.num_invalid = np.sum(self.valid_data[0, :] == False)",
"def _beamstability_data(self):\n traces = unpack(self._bo + 'i', self.fh.read(4))[0]\n x = []\n data = []\n maxpoints = 0\n for _ in range(traces):\n points = unpack(self._bo + 'i', self.fh.read(4))[0]\n d = np.fromfile(self.fh, dtype=self._bo+'f8', count=2*points).reshape(2, points)\n data.append(d[1])\n if points > maxpoints:\n x = d[0]\n maxpoints = points\n\n for d in range(len(data)):\n pad_width = maxpoints - data[d].shape[0]\n data[d] = np.pad(data[d], (0, pad_width), 'constant')\n\n if self.header['file type'] == 31:\n if self.header['analysis type'].endswith('trolley step scan'):\n xprop = 'radius'\n xunit = 'mm'\n else:\n xprop = 'deflection'\n xunit = 'V'\n elif self.header['file type'] == 35:\n xprop = 'time'\n xunit = 's'\n\n self.data = xarray.DataArray(data, dims=('species', xprop),\n coords={\n 'species': ('species', list(self.header['label list'])),\n xprop: (xprop, x, {'unit': xunit})\n },\n attrs={\n 'unit': 'counts/s'\n })",
"def transmissionData(self, port='Substrate_bottom'):\n\n data = self.data['fluxes']\n # sorted_layers is an OrderedDict, and thus has the popitem method\n sorted_layers = self.conf.sorted_dict(self.conf['Layers'])\n # self.log.info('SORTED LAYERS: %s', str(sorted_layers))\n first_layer = sorted_layers.popitem(last=False)\n self.log.info('FIRST LAYER: %s', str(first_layer))\n # An ordered dict is actually just a list of tuples so we can access\n # the key directly like so\n first_name = first_layer[0]\n bfirst_name = first_name.encode('utf-8')\n self.log.info('FIRST LAYER NAME: %s', str(first_name))\n bport = port.encode('utf-8')\n # p_inc = data[first_name][0]\n # p_ref = np.abs(data[first_name][1])\n # p_trans = data[last_name][0]\n p_inc = np.absolute(data[data.layer == bfirst_name][0][1])\n p_ref = np.absolute(data[data.layer == bfirst_name][0][2])\n p_trans = np.absolute(data[data.layer == bport][0][1])\n reflectance = p_ref / p_inc\n transmission = p_trans / p_inc\n absorbance = 1 - reflectance - transmission\n tot = reflectance + transmission + absorbance\n delta = np.abs(tot - 1)\n self.log.info('Reflectance %f' % reflectance)\n self.log.info('Transmission %f' % transmission)\n self.log.info('Absorbance %f' % absorbance)\n self.log.info('Total = %f' % tot)\n assert(reflectance >= 0)\n assert(transmission >= 0)\n assert(absorbance >= 0)\n # assert(delta < .00001)\n # Try to get a prexisting array if it exists\n try:\n # If array has been computed before get it\n arr = self.data['transmission_data']\n # If we already have data at this port update that row, otherwise\n # resize the array to accomodate the new row and insert the data\n ind = np.where(arr.port == port.encode('utf-8'))[0]\n if len(ind) > 0:\n arr[ind[0]] = (port, reflectance, transmission, absorbance)\n else:\n arr = np.resize(arr, arr.shape[0]+1)\n arr[-1] = (port, reflectance, transmission, absorbance)\n except:\n # Otherwise we need to make a new one\n dt = [('port', 'S25'), ('reflection', 'f8'),\n ('transmission', 'f8'), ('absorption', 'f8')]\n arr = np.recarray((1,), dtype=dt)\n arr[-1] = (port, reflectance, transmission, absorbance)\n self.data['transmission_data'] = arr\n return reflectance, transmission, absorbance",
"def __init__(self, connection_type, steel, beam_dead_load, beam_live_load, span,\r\n left_beam=None, right_beam=None, top_column=None, bottom_column=None):\r\n self.connection_type = connection_type\r\n # The dictionary used to store the RBS dimensions\r\n self.left_RBS_dimension = {}\r\n self.right_RBS_dimension = {}\r\n # The dictionary used to store the probable moment\r\n self.moment = {}\r\n # The dictionary used to store the shear force\r\n self.shear_force = {} # keys:\r\n # A scalar used to denote the doubler plate thickness\r\n self.doubler_plate_thickness = 0\r\n # A dictionary used to store the failure mode (if any)\r\n self.is_feasible = {} # keys: 'geometry limit', 'flexural strength', 'shear strength', 'SCWB'\r\n # Define a boolean flag which denotes the overall check results (True means OK.)\r\n self.flag = None\r\n\r\n # Call methods to initialize the attributes listed above\r\n self.check_column_beam(connection_type, left_beam, right_beam, top_column, bottom_column)\r\n self.extract_reduced_beam_section(connection_type, left_beam, right_beam)\r\n self.compute_probable_moment_RBS(connection_type, steel, left_beam, right_beam)\r\n self.compute_shear_force_RBS(connection_type, beam_dead_load, beam_live_load, span, bottom_column)\r\n self.compute_probable_moment_column_face(connection_type)\r\n self.compute_plastic_moment(connection_type, steel, left_beam, right_beam)\r\n self.check_moment_column_face(connection_type)\r\n self.check_shear_strength(connection_type, beam_dead_load, beam_live_load, left_beam, right_beam)\r\n self.check_column_beam_relationships(connection_type, steel, left_beam, right_beam, top_column, bottom_column)\r\n self.determine_doubler_plate(connection_type, steel, left_beam, right_beam, bottom_column, top_column)",
"def set_beam(self, beam_dict):\n\n ds = xr.Dataset({'backscatter_r': (['frequency', 'ping_time', 'range_bin'], beam_dict['backscatter_r']),\n 'equivalent_beam_angle': (['frequency'], beam_dict['EBA']),\n 'gain_correction': (['frequency'], beam_dict['gain_correction']),\n 'sample_interval': (['frequency'], beam_dict['sample_interval'],\n {'units': 's'}),\n 'transmit_duration_nominal': (['frequency'], beam_dict['transmit_duration_nominal'],\n {'long_name': 'Nominal bandwidth of transmitted pulse',\n 'units': 's',\n 'valid_min': 0.0}),\n 'temperature_counts': (['ping_time'], beam_dict['temperature_counts']),\n 'tilt_x_count': (['ping_time'], beam_dict['tilt_x_count']),\n 'tilt_y_count': (['ping_time'], beam_dict['tilt_y_count']),\n 'tilt_x': (['ping_time'], beam_dict['tilt_x']),\n 'tilt_y': (['ping_time'], beam_dict['tilt_y']),\n 'cos_tilt_mag': (['ping_time'], beam_dict['cos_tilt_mag']),\n 'DS': (['frequency'], beam_dict['DS']),\n 'EL': (['frequency'], beam_dict['EL']),\n 'TVR': (['frequency'], beam_dict['TVR']),\n 'VTX': (['frequency'], beam_dict['VTX']),\n 'Sv_offset': (['frequency'], beam_dict['Sv_offset']),\n 'number_of_samples_digitized_per_pings': (['frequency'], beam_dict['range_samples']),\n 'number_of_digitized_samples_averaged_per_pings': (['frequency'],\n beam_dict['range_averaging_samples'])},\n coords={'frequency': (['frequency'], beam_dict['frequency'],\n {'units': 'Hz',\n 'valid_min': 0.0}),\n 'ping_time': (['ping_time'], beam_dict['ping_time'],\n {'axis': 'T',\n 'calendar': 'gregorian',\n 'long_name': 'Timestamp of each ping',\n 'standard_name': 'time',\n 'units': 'seconds since 1970-01-01'}),\n 'range_bin': (['range_bin'], beam_dict['range_bin'])},\n attrs={'beam_mode': '',\n 'conversion_equation_t': 'type_4',\n 'number_of_frequency': beam_dict['number_of_frequency'],\n 'number_of_pings_per_burst': beam_dict['number_of_pings_per_burst'],\n 'average_burst_pings_flag': beam_dict['average_burst_pings_flag'],\n # Temperature coefficients\n 'temperature_ka': beam_dict['temperature_ka'],\n 'temperature_kb': beam_dict['temperature_kb'],\n 'temperature_kc': beam_dict['temperature_kc'],\n 'temperature_A': beam_dict['temperature_A'],\n 'temperature_B': beam_dict['temperature_B'],\n 'temperature_C': beam_dict['temperature_C'],\n # Tilt coefficients\n 'tilt_X_a': beam_dict['tilt_X_a'],\n 'tilt_X_b': beam_dict['tilt_X_b'],\n 'tilt_X_c': beam_dict['tilt_X_c'],\n 'tilt_X_d': beam_dict['tilt_X_d'],\n 'tilt_Y_a': beam_dict['tilt_Y_a'],\n 'tilt_Y_b': beam_dict['tilt_Y_b'],\n 'tilt_Y_c': beam_dict['tilt_Y_c'],\n 'tilt_Y_d': beam_dict['tilt_Y_d']})\n n_settings = {}\n z_settings = {}\n if self.compress:\n n_settings = {'backscatter_r': {'zlib': True, 'complevel': 4}}\n z_settings = {'backscatter_r': {'compressor': zarr.Blosc(cname='zstd', clevel=3, shuffle=2)}}\n\n if self.format == '.nc':\n ds.to_netcdf(path=self.file_path, mode='a', group='Beam', encoding=n_settings)\n elif self.format == '.zarr':\n if not self.append_zarr:\n ds.to_zarr(store=self.file_path, mode='a', group='Beam', encoding=z_settings)\n else:\n ds.to_zarr(store=self.file_path, mode='a', group='Beam', append_dim='ping_time')",
"def wiener_filter_data(self, data):\n # set up fields\n t = np.copy(data)\n t[self.mask.bad_pix] = hp.UNSEEN\n t[self.mask.good_pix] *= self.weights_map[self.mask.good_pix]\n tlm = hp.map2alm(t, self.params.lmax, iter=0)\n # get cooling schedule\n lamb_list = self.cs.lamb_list\n eps_list = self.cs.eps_list\n for i in range(len(lamb_list)):\n xlm, tlm = self.solve_flm(tlm, data, lamb_list[i], eps_list[i], wf = True)\n return xlm",
"def check_column_beam(self, connection_type, left_beam, right_beam, top_column, bottom_column):\r\n # Extract the beam depth and weight\r\n if connection_type == 'typical exterior':\r\n # Connection only has one beam and two columns\r\n left_beam_depth = extract_depth(left_beam.section['section size'])\r\n left_beam_weight = extract_weight(left_beam.section['section size'])\r\n top_column_depth = extract_depth(top_column.section['section size'])\r\n bottom_column_depth = extract_depth(bottom_column.section['section size'])\r\n if (left_beam_depth <= 36 and left_beam_weight <= 300\r\n and top_column_depth <= 36 and bottom_column_depth <= 36):\r\n self.is_feasible['geometry limits'] = True\r\n else:\r\n sys.stderr.write('Beam and column depth & weight are not acceptable!\\n')\r\n self.is_feasible['geometry limits'] = False\r\n elif connection_type == 'top exterior':\r\n # ****************** Debug using only *************************\r\n # print(\"top exterior:\")\r\n # print(\"column size = \", bottom_column.section['section size'])\r\n # print(\"beam size = \", left_beam.section['section size'])\r\n # ****************** Debug ends here **************************\r\n # Connection only has one beam and one column\r\n left_beam_depth = extract_depth(left_beam.section['section size'])\r\n left_beam_weight = extract_weight(left_beam.section['section size'])\r\n bottom_column_depth = extract_depth(bottom_column.section['section size'])\r\n if left_beam_depth <= 36 and left_beam_weight <= 300 and bottom_column_depth <= 36:\r\n self.is_feasible['geometry limits'] = True\r\n else:\r\n sys.stderr.write('Beam and column depth & weight are not acceptable!\\n')\r\n self.is_feasible['geometry limits'] = False\r\n elif connection_type == 'typical interior':\r\n # Connection has two beams and two columns\r\n left_beam_depth = extract_depth(left_beam.section['section size'])\r\n left_beam_weight = extract_weight(left_beam.section['section size'])\r\n right_beam_depth = extract_depth(right_beam.section['section size'])\r\n right_beam_weight = extract_weight(right_beam.section['section size'])\r\n top_column_depth = extract_depth(top_column.section['section size'])\r\n bottom_column_depth = extract_depth(bottom_column.section['section size'])\r\n if (left_beam_depth <= 36 and right_beam_depth <= 36\r\n and left_beam_weight <= 300 and right_beam_weight <= 300\r\n and top_column_depth <= 36 and bottom_column_depth <= 36):\r\n self.is_feasible['geometry limits'] = True\r\n else:\r\n sys.stderr.write('Beam and beam depth & weight are not acceptable!\\n')\r\n self.is_feasible['geometry limits'] = False\r\n elif connection_type == 'top interior':\r\n # Connection has two beams and one column\r\n left_beam_depth = extract_depth(left_beam.section['section size'])\r\n left_beam_weight = extract_weight(left_beam.section['section size'])\r\n right_beam_depth = extract_depth(right_beam.section['section size'])\r\n right_beam_weight = extract_weight(right_beam.section['section size'])\r\n bottom_column_depth = extract_depth(bottom_column.section['section size'])\r\n if (left_beam_depth <= 36 and right_beam_depth <= 36\r\n and left_beam_weight <= 300 and right_beam_weight <= 300\r\n and bottom_column_depth <= 36):\r\n self.is_feasible['geometry limits'] = True\r\n else:\r\n sys.stderr.write('Beam and beam depth & weight are not acceptable!\\n')\r\n self.is_feasible['geometry limits'] = False\r\n else:\r\n sys.stderr.write('Error: wrong type of connection specified!\\n No such keyword for connection exists!\\n')\r\n sys.exit(2)",
"def _unique_beams(self):\n bmap, mask = self.single_pointing_telescope._unique_beams()\n block_bmap = linalg.block_diag(*[bmap+i*self.single_pointing_telescope.nfeed for i, _ in enumerate(self.pointings)])\n block_mask = linalg.block_diag(*[mask for _ in self.pointings])\n\n return block_bmap, block_mask",
"def prep(self):\n print\n print 'Filtering rawdata to data as masked array...'\n# using 0 as flag\n# self.data = n.ma.masked_array(self.rawdata[:self.nints,:, self.chans,:], self.rawdata[:self.nints,:, self.chans,:] == 0j)\n# using standard flags\n self.data = n.ma.masked_array(self.rawdata[:self.nints,:, self.chans,:], self.flags[:self.nints,:, self.chans,:] == 0) # mask of True for flagged data (flags=0 in tpipe, which is flags=False in Miriad and flags=True in MS)\n self.dataph = (self.data.mean(axis=3).mean(axis=1)).real #dataph is summed and detected to form TP beam at phase center, multi-pol\n self.min = self.dataph.min()\n self.max = self.dataph.max()\n print 'Shape of data:'\n print self.data.shape\n print 'Dataph min, max:'\n print self.min, self.max\n\n self.freq = self.freq_orig[self.chans]\n\n # set up ur tracks (lol)\n self.dmtrack0 = {}\n self.twidths = {}\n for dmbin in xrange(len(self.dmarr)):\n self.dmtrack0[dmbin] = self.dmtrack(self.dmarr[dmbin],0) # track crosses high-freq channel in first integration\n self.twidths[dmbin] = 0\n for k in self.dmtrack0[dmbin][1]:\n self.twidths[dmbin] = max(self.twidths[dmbin], len(n.where(n.array(self.dmtrack0[dmbin][1]) == k)[0]))\n\n print 'Track width in time: '\n for dmbin in self.twidths:\n print 'DM=%.1f, twidth=%d. Iteration could step by %d/2.' % (self.dmarr[dmbin], self.twidths[dmbin], self.twidths[dmbin])",
"def beam_align():\n\n # do nothing if there is a sample mounted to avoid collisions\n if smart_magnet.sample_detect.get() == 0:\n raise Exception(\"Sample mounted on gonio! Avoided collision\")\n\n # wait for attenuators to finish moving\n yield from bps.abs_set(mxatten, 0.002)\n yield from bps.sleep(5)\n\n # transition to BL and open shutter\n yield from bps.abs_set(gov_rbt, \"BL\", wait=True)\n yield from bps.mv(sht.r, 0)\n\n yield from bps.abs_set(rot_aligner.cam_hi.cam_mode, \"beam_align\")\n\n # which direction, x pos. pitch beam outboard (-), y pos. pitch beam up (+)\n scan_uid = yield from bp.count([rot_aligner.cam_hi], 1)\n centroid_x, centroid_y = (\n db[scan_uid].table()[rot_aligner.cam_hi.cv1.outputs.output1.name][1],\n db[scan_uid].table()[rot_aligner.cam_hi.cv1.outputs.output2.name][1],\n )\n\n if np.isclose(0, centroid_x) or np.isclose(0, centroid_y):\n raise Exception(\"No centroid detected!\")\n\n yield from bps.abs_set(kbt.hor.delta_px, (centroid_x - 320))\n yield from bps.abs_set(kbt.ver.delta_px, -(centroid_y - 256))\n\n def lin_reg(independent, dependent, goal, **kwargs) -> float:\n b = dependent\n A = np.matrix([[pos, 1] for pos in independent])\n p = (\n np.linalg.inv(A.transpose() * A)\n * A.transpose()\n * np.matrix(b.to_numpy()).transpose()\n )\n best = (goal - p[1]) / p[0]\n return best\n\n for axis, signal, center in (\n kbt.hor,\n rot_aligner.cam_hi.cv1.outputs.output1,\n 320,\n ), (kbt.ver, rot_aligner.cam_hi.cv1.outputs.output2, 256):\n # skip if we are within 1 um\n if abs(axis.delta_px.get()) > 2:\n scan_uid = yield from rel_scan_no_reset(\n [rot_aligner.cam_hi],\n axis,\n 0,\n 0.4 * -(axis.delta_px.get() / abs(axis.delta_px.get())),\n 10,\n )\n scan_df = db[scan_uid].table()\n best_voltage = lin_reg(\n scan_df[axis.readback.name],\n scan_df[signal.name],\n center,\n )\n yield from bps.mv(axis, best_voltage)\n yield from bps.sleep(1)\n\n # close shutters and reset attenuators for manual viewing\n yield from bps.mv(sht.r, 20)",
"def populate_data(self, source, vel_in, freq_in, coord_sys_in, nav_ref_in, beam_filter_in=3,\n bottom_mode_in='Variable'):\n\n # Identify invalid ensembles for SonTek data.\n if source == 'SonTek':\n vel_in = BoatData.filter_sontek(vel_in)\n\n # Store input data\n self.raw_vel_mps = vel_in\n self.frequency_khz = freq_in\n self.coord_sys = coord_sys_in\n self.orig_coord_sys = coord_sys_in\n self.nav_ref = nav_ref_in\n self.beam_filter = beam_filter_in\n self.bottom_mode = bottom_mode_in\n\n if nav_ref_in == 'BT':\n\n # Boat velocities are referenced to ADCP not the streambed and thus must be reversed\n self.u_mps = np.copy(-1 * vel_in[0, :])\n self.v_mps = np.copy(-1 * vel_in[1, :])\n self.w_mps = np.copy(vel_in[2, :])\n self.d_mps = np.copy(vel_in[3, :])\n\n # Default filtering applied during initial construction of object\n self.d_filter = 'Off'\n self.d_filter_threshold = 99\n self.w_filter = 'Off'\n self.w_filter_threshold = 99\n self.smooth_filter = 'Off'\n self.interpolate = 'None'\n\n else:\n\n # GPS referenced boat velocity\n self.u_mps = np.copy(vel_in[0, :])\n self.v_mps = np.copy(vel_in[1, :])\n self.w_mps = np.nan\n self.d_mps = np.nan\n\n # Default filtering\n self.gps_diff_qual_filter = 2\n self.gps_altitude_filter = 'Off'\n self.gps_altitude_filter_change = 3\n self.gps_HDOP_filter = 'Off'\n self.gps_HDOP_filter_max = 2.5\n self.gps_HDOP_filter_change = 1\n self.smooth_filter = 'Off'\n self.interpolate = 'None'\n\n # Assign data to processed property\n self.u_processed_mps = np.copy(self.u_mps)\n self.v_processed_mps = np.copy(self.v_mps)\n\n # Preallocate arrays\n n_ensembles = vel_in.shape[1]\n self.valid_data = repmat([True], 6, n_ensembles)\n self.smooth_speed = np.nan\n self.smooth_upper_limit = np.nan\n self.smooth_lower_limit = np.nan\n\n # Determine number of raw invalid\n # --------------------------------\n # Find invalid raw data\n valid_vel = np.tile([True], self.raw_vel_mps.shape)\n valid_vel[np.isnan(self.raw_vel_mps)] = False\n\n # Identify invalid ensembles\n if nav_ref_in == 'BT':\n self.valid_data[1, np.sum(valid_vel, 0) < 3] = False\n else:\n self.valid_data[1, np.sum(valid_vel, 0) < 2] = False\n\n # Combine all filter data to composite valid data\n self.valid_data[0, :] = np.all(self.valid_data[1:, :], 0)\n self.num_invalid = np.sum(self.valid_data[0, :] == False)\n self.processed_source = np.array([''] * self.u_mps.shape[0], dtype=object)\n self.processed_source[np.where(self.valid_data[0, :] == True)] = nav_ref_in\n self.processed_source[np.where(self.valid_data[0, :] == False)] = \"INT\"",
"def decode_faceshift_datastream(self, data):\n \n #block_id = struct.unpack_from('H', data)\n #print(\"Received block id \" + str(block_id)) ;\n\n offset = 0\n block_id, version, block_size = struct.unpack_from('HHI', data, offset)\n \n #print(\"ID, v, size = \" + str(block_id) + \",\" + str(version) + \",\" + str(block_size) )\n \n offset += 8\n\n if(block_id == BLOCK_ID_TRACKING_STATE):\n n_blocks, = struct.unpack_from('H', data, offset)\n #print(\"n_blocks = \" + str(n_blocks))\n offset += 2\n\n track_ok = 0 # Will be a byte: 1 if tracking ok, 0 otherwise.\n head_rotation_quat = None # Will be filled with the rotation using mathutils.Quaternion\n blend_shape_values = [] # Will be a list of float in the range 0-1\n #eyes_values = None # Will be a sequence of 4 angle values\n markers_position = [] # Will be a list of mathutils.Vector\n \n curr_block = 0\n while(curr_block < n_blocks):\n block_id, version, block_size = struct.unpack_from('HHI', data, offset)\n #print(\"ID, v, size = \" + str(block_id) + \",\" + str(version) + \",\" + str(block_size) )\n \n # put the offset at the beginning of the block\n offset += 8\n \n if(block_id == 101): # Frame Information blobk (timestamp and tracking status)\n ts, track_ok = struct.unpack_from('dB', data, offset)\n #print(\"timestamp, track_ok \" + str(ts) + \", \" + str(track_ok) )\n #offset += 9\n elif(block_id == 102): # Pose block (head rotation and position)\n x,y,z,w = struct.unpack_from('ffff', data, offset)\n #head_rotation_quat = mathutils.Quaternion((w,x,y,z))\n elif(block_id == 103): # Blendshapes block (blendshape values)\n n_coefficients, = struct.unpack_from('I', data, offset)\n #print(\"Blend shapes count=\"+ str(n_coefficients) )\n i = 0\n coeff_list = \"\"\n while(i < n_coefficients):\n # Offset of the block, plus the 4 bytes for int n_coefficients, plus 4 bytes per float\n val, = struct.unpack_from('f', data, offset + 4 + (i*4))\n blend_shape_values.append(val)\n coeff_list += repr(val) + \" \"\n i += 1\n print(\"Values: \" + coeff_list)\n elif(block_id == 104): # Eyes block (eyes gaze)\n leye_theta, leye_phi, reye_theta, reye_phi = struct.unpack_from('ffff', data, offset)\n elif(block_id == 105): # Markers block (absolute position of mark points)\n n_markers, = struct.unpack_from('H', data, offset)\n #print(\"n markers=\"+str(n_markers))\n i = 0\n while(i < n_markers):\n # Offset of the block, plus the 2 bytes for int n_markers, plus 4 bytes for each x,y,z floats\n x, y, z = struct.unpack_from('fff', data, offset + 2 + (i*4*3))\n #print(\"m\" + str(i) + \" \" + str(x) + \"\\t\" + str(y) + \"\\t\" + str(z))\n markers_position.append(mathutils.Vector((x,y,z)))\n i += 1\n \n curr_block += 1\n offset += block_size\n \n msg = fsMsgTrackingState()\n\n msg.m_timestamp = ts\n\n self.pub.publish(msg)\n\n # end -- while on blocks. Track State scan complete",
"def _fixDualBlockSram(self):\n # Note that as this function executes self.sram should be a tuple of\n # (block0,block1,delay) where block0 and block1 are strings\n if isinstance(self.sram, tuple):\n # update addresses in memory commands that call into SRAM\n self.mem = MemorySequence.fixSRAMaddresses(self.mem, self.sram, self.dev)\n\n # combine blocks into one sram sequence to be uploaded\n block0, block1, delayBlocks = self.sram\n # Prepend block0 with \\x00's so that the actual signal data\n # exactly fills the first physical SRAM block\n # Note block0 length in bytes = 4*block0 length in words\n data = '\\x00' * (self.dev.SRAM_BLOCK0_LEN * 4 -\n len(block0)) + block0 + block1\n self.sram = data\n self.blockDelay = delayBlocks",
"def fit_beam_and_baselines(self, pol='absI', circular_beam='auto', bl_degrees=(1, 3),\n refine_beam=True, spike_width=0, band=0):\n scan_coords = [scan.target_coords for scan in self.scans]\n scan_data = [remove_spikes(scan.pol(pol)[:, band], spike_width=spike_width) for scan in self.scans]\n # Auto beam shape picks a circular beam for dual-pol terms and elliptical beam for single-pol terms\n dual_pol = pol not in ('HH', 'VV')\n circular_beam = dual_pol if circular_beam == 'auto' else circular_beam\n # FWHM beamwidth (in radians) for uniformly illuminated circular dish is 1.03 lambda / D\n # FWHM beamwidth for Gaussian-tapered circular dish is 1.22 lambda / D\n # The antenna beamwidth factor is somewhere between 1.03 and 1.22\n ant = self.dataset.antenna\n expected_width = ant.beamwidth * katpoint.lightspeed / (self.dataset.freqs[band] * 1e6) / ant.diameter\n # An interferometer measures the beam voltage pattern while a single dish measures the beam power pattern\n # Since power = voltage ^ 2, a Gaussian voltage pattern ends up being sqrt(2) wider than the power pattern\n if self.dataset.antenna2:\n expected_width *= np.sqrt(2.0)\n if not circular_beam:\n expected_width = [expected_width, expected_width]\n # Degrees of freedom is time-bandwidth product (2 * BW * t_dump) of each sample\n dof = 2.0 * (self.dataset.bandwidths[band] * 1e6) / self.dataset.dump_rate\n # Stokes I etc has double the degrees of freedom, as it is the sum of the independent HH and VV samples\n dof = 2 * dof if dual_pol else dof\n # Refining the beam and baselines requires scan timestamps\n scan_timestamps = [scan.timestamps for scan in self.scans] if refine_beam else None\n # Fit beam and baselines directly to positive coherencies / Stokes params only, otherwise use I as proxy\n positive_pol = pol in ('absI', 'absHH', 'absVV', 'I', 'HH', 'VV', 'XX', 'YY')\n scan_total_power = [remove_spikes(scan.pol('absI')[:, band], spike_width=spike_width) for scan in self.scans] \\\n if not positive_pol else None\n logger.debug(\"Fitting beam and initial baseline of degree (%d, %d) to pol '%s' of target '%s':\" %\n (bl_degrees[0], bl_degrees[1], pol if positive_pol else 'absI', self.target.name))\n self.beam, baselines, self.baseline = fit_beam_and_baselines(scan_coords, scan_data, expected_width, dof,\n bl_degrees, scan_timestamps, scan_total_power)\n for scan, bl in zip(self.scans, baselines):\n scan.baseline = bl",
"def _create_bsm_params(self):\n return dict(\n data_usage_key=self.usage_key,\n data_version='DV',\n data_edit_timestamp=now(),\n transformers_schema_version='TV',\n block_structure_schema_version=str(1),\n )",
"def prep(self, deleteraw=False):\n print\n print 'Filtering rawdata to data as masked array...'\n# using 0 as flag\n# self.data = n.ma.masked_array(self.rawdata[:self.nints,:, self.chans,:], self.rawdata[:self.nints,:, self.chans,:] == 0j)\n# using standard flags\n self.data = n.ma.masked_array(self.rawdata[:self.nints,:, self.chans,:], self.flags[:self.nints,:, self.chans,:] == 0) # mask of True for flagged data (flags=0 in tpipe, which is flags=False in Miriad and flags=True in MS)\n self.dataph = (self.data.mean(axis=3).mean(axis=1)).real #dataph is summed and detected to form TP beam at phase center, multi-pol\n self.min = self.dataph.min()\n self.max = self.dataph.max()\n print 'Shape of data:'\n print self.data.shape\n print 'Dataph min, max:'\n print self.min, self.max\n\n if deleteraw:\n del self.rawdata\n del self.flags\n\n self.freq = self.freq_orig[self.chans]\n\n # set up ur tracks (lol)\n self.dmtrack0 = {}\n self.twidths = {}\n self.delay = {}\n for dmbin in xrange(len(self.dmarr)):\n self.dmtrack0[dmbin] = self.dmtrack(self.dmarr[dmbin],0) # track crosses high-freq channel in first integration\n (trackt, trackc) = self.dmtrack0[dmbin]\n if len(trackc)<len(self.chans):\n print 'Computed track for DM=%.1f is too long for the observation; only %d channels are computed' % (self.dmarr[dmbin],len(trackc))\n continue\n \n# old way\n# self.twidths[dmbin] = [len(n.where(trackc == (chan-self.chans[0]))[0]) for chan in self.chans] # width of track for each unflagged channel\n# self.delay[dmbin] = [n.int(trackt[n.where(trackc == (chan-self.chans[0]))[0][0]]) for chan in self.chans] # integration delay for each unflagged channel of a given dm.\n# new way\n\n self.twidths[dmbin] = [len(n.where(n.array(trackc) == chan)[0]) for chan in range(len(self.chans))] # width of track for each unflagged channel\n self.delay[dmbin] = [n.int(trackt[n.where(n.array(trackc) == chan)[0][0]]) for chan in range(len(self.chans))] # integration delay for each unflagged channel of a given dm.\n\n\n print 'Track width in time: '\n for dmbin in self.twidths:\n print 'DM=%.1f, max(twidth)=%d. Iteration could step by %d/2.' % (self.dmarr[dmbin], max(self.twidths[dmbin]), max(self.twidths[dmbin]))",
"def prep(self):\n print\n print 'Filtering rawdata to data as masked array...'\n# using 0 as flag\n# self.data = n.ma.masked_array(self.rawdata[:self.nints,:, self.chans,:], self.rawdata[:self.nints,:, self.chans,:] == 0j)\n# using standard flags\n self.data = n.ma.masked_array(self.rawdata[:self.nints,:, self.chans,:], self.flags[:self.nints,:, self.chans,:] == 0) # mask of True for flagged data (flags=0 in tpipe, which is flags=False in Miriad and flags=True in MS)\n self.dataph = (self.data.mean(axis=3).mean(axis=1)).real #dataph is summed and detected to form TP beam at phase center, multi-pol\n self.min = self.dataph.min()\n self.max = self.dataph.max()\n print 'Shape of data:'\n print self.data.shape\n print 'Dataph min, max:'\n print self.min, self.max\n\n self.freq = self.freq_orig[self.chans]\n\n self.track0 = self.track(0.)\n self.twidth = 0\n for k in self.track0[1]:\n self.twidth = max(self.twidth, len(n.where(n.array(self.track0[1]) == k)[0]))\n\n print 'Track width in time: %d. Iteration could step by %d/2.' % (self.twidth, self.twidth)",
"def prepare_funding(self):\n entity_miner = self.entities[0]\n\n entity_miner.send_bitcoins(entity_miner.address)\n entity_miner.purchase_mastercoins(500.0)\n\n self.generate_block()\n self.check_balance(entity_miner.address, MSC, '50000.00000000', '0.00000000')\n self.check_balance(entity_miner.address, TMSC, '50000.00000000', '0.00000000')",
"def cal_Beam_TheoRMS(n_ant, tobs, chan_width, sbid):\n \n BEAM_T_RMS = []\n\n coreff = 0.8 # correlator efficiency\n npol = 2.0 # Number of polarisation, npol = 2 for images in Stokes I, Q, U, or V\n\n obj = bf.load_beamset_class('SEFD_{}.hdf5'.format(sbid))\n freq = obj.frequencies\n data = obj.data #[time, antenna, beam, polarisation, channel, payload]\n pol_XX = 0 # polarisation 0 - 3 (XX,XY,YX,YY)\n pol_YY = 3\n \n for beam in range(36):\n med_XX_SEFD = np.median(data[0, :, beam, pol_XX, :, 0]) #use all available antennas\n med_YY_SEFD = np.median(data[0, :, beam, pol_YY, :, 0]) \n med_SEFD = 0.5*math.sqrt(med_XX_SEFD**2.0 + med_YY_SEFD**2.0) # SEFD of stokes I\n t_rms_mjy = 1000.*(med_SEFD/(coreff*math.sqrt(npol*n_ant*(n_ant-1)*chan_width*tobs)))\n BEAM_T_RMS.append(t_rms_mjy)\n\n return BEAM_T_RMS",
"def __send_broadcast_to_buses(self, sending_group=\"global\"):\n\n if sending_group == \"global\":\n data = self.__global_broadcast_entry.get()\n self.__global_broadcast_entry.delete(0, 'end')\n self.__message_sender.send_global(free_text=data)\n\n elif sending_group ==\"line\":\n line = self.__line_number_broadcast_entry.get()\n if not self.__bus_controller.check_line(line=line):\n print(f\"there are no buses for line {line}\")\n elif len(line) > 0 and line.isnumeric():\n data = self.__line_text_broadcast_entry.get()\n self.__line_text_broadcast_entry.delete(0, 'end')\n self.__line_number_broadcast_entry.delete(0, 'end')\n self.__message_sender.send_line(int(line), free_text=data)\n else:\n print(f\"line number must be a number, {line}\")\n else:\n print(f\"{sending_group} isn't a valid sending group\")",
"def EncodeDataWithCoupling(data,codingParams):\n # NEW: Determine block type and set a,b\n if(codingParams.blocksize < 2):\n b = codingParams.longBlockSize/2\n else:\n b = codingParams.shortBlockSize/2\n if(codingParams.blocksize == 1 or codingParams.blocksize == 2):\n a = codingParams.shortBlockSize/2\n else:\n a = codingParams.longBlockSize/2\n N = a+b\n halfN = N/2\n #print \"A: \", a\n #print \"B: \", b\n #print \"halfN: \", halfN\n\n # Reclaim nScaleBits from bands with 0 lines\n # vary bark width of bands\n # pass different flimits to AssignMDCTLines...\n\n nScaleBits = codingParams.nScaleBits\n maxMantBits = (1<<codingParams.nMantSizeBits) # 1 isn't an allowed bit allocation so n size bits counts up to 2^n\n if maxMantBits>16: maxMantBits = 16 # to make sure we don't ever overflow mantissa holders\n # vectorizing the Mantissa function call\n# vMantissa = np.vectorize(Mantissa)\n sfBands = codingParams.sfBands\n # db print \"Encode coupling: \", sfBands.nLines\n # NEW compute target bit rate based on block type\n bitBudget = codingParams.targetBitsPerSample * halfN # this is overall target bit rate\n #bitBudget -= nScaleBits*(sfBands.nBands + 1) # less scale factor bits (including overall scale factor)\n #bitBudget -= codingParams.nMantSizeBits*sfBands.nBands # less mantissa bit allocation bits\n #bitBudget -= 2 # block ID size TODO: make this a variable\n mdctLinesFull = []\n for iCh in range(codingParams.nChannels):\n if codingParams.doSBR == True:\n # Calculate Spectral Envelope based on original signal\n specEnv = calcSpecEnv(data[iCh],codingParams.sbrCutoff,codingParams.sampleRate)\n # Append in spectral envelope for this channel into empty container\n codingParams.specEnv[iCh][:] = specEnv\n\n #Decimate and lowpass signal by factor determined by cutoff frequency\n doDecimate = False\n if doDecimate==True:\n Wc = codingParams.sbrCutoff/float(codingParams.sampleRate/2.)# Normalized cutoff frequency\n B,A = signal.butter(4,Wn)\n data[iCh] = signal.lfilter(B,A,data[iCh])\n\n # window data for side chain FFT and also window and compute MDCT\n timeSamples = data[iCh]\n # Window data based on block size\n mdctTimeSamples = np.append(SineWindow(np.append(timeSamples[:a],np.zeros(a)))[:a],SineWindow(np.append(np.zeros(b),timeSamples[a:]))[b:])\n # Call MDCT with a, b reflecting block size\n mdctLines = MDCT(mdctTimeSamples, a, b)\n\n # compute overall scale factor for this block and boost mdctLines using it\n maxLine = np.max( np.abs(mdctLines) )\n overallScale = ScaleFactor(maxLine,nScaleBits) #leading zeroaes don't depend on nMantBits\n mdctLines *= (1<<overallScale)\n mdctLinesFull.append(mdctLines)\n\n uncoupledData, coupledChannel, couplingParams = ChannelCoupling(mdctLinesFull,codingParams.sampleRate,codingParams.nCouplingStart)\n codingParams.couplingParams = couplingParams\n codingParams.coupledChannel = coupledChannel\n mdctLinesFull = uncoupledData\n\n scaleFactorFull= []\n bitAllocFull = []\n mantissaFull = []\n overallScaleFull = []\n for iCh in range(codingParams.nChannels):\n # compute the mantissa bit allocations\n # compute SMRs in side chain FFT\n SMRs = CalcSMRs(timeSamples, mdctLines, overallScale, codingParams.sampleRate, sfBands)\n if codingParams.doSBR == True:\n # Critical band starting here are above cutoff\n cutBin = freqToBand(codingParams.sbrCutoff)\n # perform bit allocation using SMR results\n bitAlloc = BitAllocSBR(bitBudget, maxMantBits, sfBands.nBands, sfBands.nLines, SMRs, codingParams.bitReservoir, codingParams.blocksize, cutBin)\n else:\n bitAlloc = BitAlloc(bitBudget, maxMantBits, sfBands.nBands, sfBands.nLines, SMRs, codingParams.bitReservoir, codingParams.blocksize)\n codingParams.bitReservoir += bitBudget - np.sum(bitAlloc * sfBands.nLines)\n # db print \"blocksize: \", codingParams.blocksize\n # db print \"Bit Reservoir: \", codingParams.bitReservoir\n # db if codingParams.blocksize == 2:\n # db print bitAlloc\n # given the bit allocations, quantize the mdct lines in each band\n scaleFactor = np.empty(sfBands.nBands,dtype=np.int32)\n nMant = halfN\n\n for iBand in range(sfBands.nBands):\n if not bitAlloc[iBand]: nMant-= sfBands.nLines[iBand] # account for mantissas not being transmitted\n mantissa=np.empty(nMant,dtype=np.int32)\n iMant=0\n for iBand in range(sfBands.nBands):\n lowLine = sfBands.lowerLine[iBand]\n highLine = sfBands.upperLine[iBand] + 1 # extra value is because slices don't include last value\n nLines= sfBands.nLines[iBand]\n if(highLine - lowLine > 0):\n scaleLine = np.max(np.abs( mdctLines[lowLine:highLine] ) )\n else:\n scaleLine = abs(mdctLines[lowLine])\n scaleFactor[iBand] = ScaleFactor(scaleLine, nScaleBits, bitAlloc[iBand])\n if bitAlloc[iBand]:\n mantissa[iMant:iMant+nLines] = vMantissa(mdctLines[lowLine:highLine],scaleFactor[iBand], nScaleBits, bitAlloc[iBand])\n iMant += nLines\n # end of loop over scale factor bands\n scaleFactorFull.append(scaleFactor)\n bitAllocFull.append(bitAlloc)\n mantissaFull.append(mantissa)\n overallScaleFull.append(overallScale)\n # return results\n return (scaleFactorFull, bitAllocFull, mantissaFull, overallScaleFull)",
"def _rdm12_halffilling_blocked(self,\n bradata: Optional['FqeData'] = None,\n max_states: int = 100\n ) -> Tuple['Nparray', 'Nparray']:\n bradata = self if bradata is None else bradata\n\n mappings = self._core._get_block_mappings(max_states=max_states)\n norb = bradata.norb()\n coeff_a = self.coeff\n coeff_b = self.coeff.T.copy()\n bcoeff_a = bradata.coeff\n bcoeff_b = bradata.coeff.T.copy()\n\n rdm1 = numpy.zeros((norb,) * 2, dtype=bradata._dtype)\n rdm2 = numpy.zeros((norb,) * 4, dtype=bradata._dtype)\n for alpha_range, beta_range, alpha_maps, beta_maps in mappings:\n dvec = _make_dvec_part(coeff_a, alpha_maps, alpha_range, beta_range,\n norb, self.lena(), self.lenb(), True)\n dvec = _make_dvec_part(coeff_b,\n beta_maps,\n alpha_range,\n beta_range,\n norb,\n self.lena(),\n self.lenb(),\n False,\n out=dvec)\n\n dvec2 = _make_dvec_part(bcoeff_a, alpha_maps,\n alpha_range, beta_range, norb, self.lena(),\n self.lenb(), True)\n dvec2 = _make_dvec_part(bcoeff_b,\n beta_maps,\n alpha_range,\n beta_range,\n norb,\n self.lena(),\n self.lenb(),\n False,\n out=dvec2)\n\n dvec2conj = dvec2.conj()\n rdm1[:, :] += numpy.tensordot(\n dvec2conj, self.coeff[alpha_range.start:alpha_range.\n stop, beta_range.start:beta_range.stop])\n rdm2[:, :, :, :] += \\\n numpy.tensordot(dvec2conj, dvec, axes=((2, 3), (2, 3)))\n\n rdm2 = -rdm2.transpose(1, 2, 0, 3)\n for i in range(self.norb()):\n rdm2[:, i, i, :] += rdm1[:, :]\n return (numpy.transpose(rdm1), rdm2)",
"def __frame_tx(self,data):\n\n if self._spy_frame_tx is not None:\n self._spy_frame_tx(data)\n\n data=self.__pad(data)\n\n if len(data) < self.other_bufferlen:\n self.com.tx(data)\n else:\n chunks = (len(data)-1) // self.other_bufferlen\n #print(\"__frame_tx: %d full chunks + last\"%chunks,flush=True)\n for i in range(0,chunks):\n self.com.tx(data[i*self.other_bufferlen:(i+1)*self.other_bufferlen])\n self.com.rx_ack()\n self.com.tx(data[chunks*self.other_bufferlen:])\n #print(\"__frame_tx done\",flush=True)",
"def welded_beam(self, u):\n assert len(u) == 4, 'Welded Beam design needs to specify 4 parameters.'\n assert u[0] != 0 and u[1] != 0 and u[2] != 0 and u[3] != 0, ('Designvalues {} cannot be zero').format(u)\n em = 6000.0 * (14 + u[1] / 2.0)\n r = sqrt(u[1] ** 2 / 4.0 + ((u[0] + u[2]) / 2.0) ** 2)\n j = 2.0 * (u[0] * u[1] * sqrt(2) * (u[1] ** 2 / 12.0 + ((u[0] + u[2]) / 2.0) ** 2))\n tau_p = 6000.0 / (sqrt(2) * u[0] * u[1])\n tau_dp = em * r / j\n tau = sqrt(tau_p ** 2 + 2.0 * tau_p * tau_dp * u[1] / (2.0 * r) + tau_dp ** 2)\n sigma = 504000.0 / (u[3] * u[2] ** 2)\n delta = 65856000.0 / (30 * 1000000 * u[3] * u[2] ** 2)\n pc = 4.013 * (30.0 * 1000000) * sqrt(u[2] ** 2 * u[3] ** 6 / 36.0) / 196.0 * (1.0 - u[2] * sqrt(30.0 * 1000000 / (4.0 * (12.0 * 1000000))) / 28.0)\n fitness = 1.10471 * u[0] ** 2 * u[1] + 0.04811 * u[2] * u[3] * (14.0 + u[1])\n return fitness",
"def send_bus(self, bus, update_buses: bool = False, update_passengers: bool = False, free_text: str = \"\",\n kick_reason: str = \"\"):\n\n while self.__lock_data: # makes sure to not change the data while it's being proccessed and sent.\n sleep(0.01)\n if bus.line_num in self.__bus_messages.keys() and bus.id in self.__bus_messages[bus.line_num].keys():\n self.__bus_messages[bus.line_num][bus.id][\"passengers\"] = self.__line_messages[bus.line_num][bus.id][\n \"passengers\"] or update_passengers\n self.__bus_messages[bus.line_num][bus.id][\"buses\"] = self.__line_messages[bus.line_num][bus.id][\n \"buses\"] or update_buses\n if free_text != \"\":\n self.__bus_messages[bus.line_num][bus.id][\"free text\"] += free_text + \"\\n\"\n if kick_reason != \"\":\n self.__bus_messages[bus.line_num][bus.id][\"kick reason\"] += kick_reason + \"\\n\"\n else:\n self.__bus_messages[bus.line_num] = dict()\n self.__bus_messages[bus.line_num][bus.id] = dict()\n self.__bus_messages[bus.line_num][bus.id][\"passengers\"] = update_passengers\n self.__bus_messages[bus.line_num][bus.id][\"buses\"] = update_buses\n self.__bus_messages[bus.line_num][bus.id][\"free text\"] = \"\"\n self.__bus_messages[bus.line_num][bus.id][\"kick reason\"] = \"\"\n if free_text != \"\":\n self.__bus_messages[bus.line_num][bus.id][\"free text\"] = free_text + \"\\n\"\n\n if kick_reason != \"\":\n self.__bus_messages[bus.line_num][bus.id][\"kick reason\"] = kick_reason + \"\\n\"",
"def _processBurnData(self, burnInfo):\n self.decays = []\n self.trans = []\n for nuclideBurnCategory in burnInfo:\n # Check that the burn category has only one defined burn type\n if len(nuclideBurnCategory) > 1:\n raise ValueError(\n \"Improperly defined ``burn-chain`` of {}. {} should be a single burn type.\".format(\n self, nuclideBurnCategory.keys()\n )\n )\n nuclideBurnType = list(nuclideBurnCategory.keys())[0]\n if nuclideBurnType == self.TRANSMUTATION:\n self.trans.append(\n transmutations.Transmutation(\n self, nuclideBurnCategory[nuclideBurnType]\n )\n )\n elif nuclideBurnType == self.DECAY:\n self.decays.append(\n transmutations.DecayMode(self, nuclideBurnCategory[nuclideBurnType])\n )\n elif nuclideBurnType == self.SPONTANEOUS_FISSION:\n userSpontaneousFissionYield = nuclideBurnCategory.get(\n nuclideBurnType, None\n )\n\n # Check for user-defined value of nuSF within the burn-chain data. If this is\n # updated then prefer the user change and then note this to the user. Otherwise,\n # maintain the default loaded from the nuclide bases.\n if userSpontaneousFissionYield:\n if userSpontaneousFissionYield != self.nuSF:\n runLog.info(\n f\"nuSF provided for {self} will be updated from \"\n f\"{self.nuSF:<8.6e} to {userSpontaneousFissionYield:<8.6e} based on \"\n \"user provided burn-chain data.\"\n )\n self.nuSF = userSpontaneousFissionYield\n else:\n raise Exception(\n \"Undefined Burn Data {} for {}. Expected {}, {}, or {}.\"\n \"\".format(\n nuclideBurnType,\n self,\n self.TRANSMUTATION,\n self.DECAY,\n self.SPONTANEOUS_FISSION,\n )\n )",
"def get_box_for_sample(beam_num, bin_num, frame, beam_data):\n\n sample_start_delay = frame.samplestartdelay # usec\n sound_speed = frame.soundspeed # meters / sec\n sample_period = frame.sampleperiod # usec\n\n WindowStart = sample_start_delay * 1e-6 * sound_speed / 2 # meters\n sample_length = sample_period * 1e-6 * sound_speed / 2. # meters\n\n bin_front_edge_distance = WindowStart + sample_length * bin_num\n bin_back_edge_distance = WindowStart + sample_length* (bin_num + 1)\n\n beam_angles = beam_data[beam_data['beam_num'] == beam_num]\n a1 = beam_angles['beam_left'].iloc[0]\n a2 = beam_angles['beam_right'].iloc[0]\n c = beam_angles['beam_center'].iloc[0]\n\n # I can't figure out whats going on with the beam spacing in the files.\n # Once the center point crosses 0, the ordering of the left and right angles swap...\n # For now I'll assume the y axis is the common line. Positive angles go to the left,\n # negative angles go to the right\n left = max(a1, a2)\n right = min(a1, a2)\n\n # Left Edge\n beam_left_angle = np.deg2rad(left)\n rot_matrix = np.array([[np.cos(beam_left_angle), -np.sin(beam_left_angle)], [np.sin(beam_left_angle), np.cos(beam_left_angle)]])\n\n vec = np.array([0, bin_back_edge_distance])\n bin_left_back_point = np.matmul(rot_matrix, vec)\n\n vec = np.array([0, bin_front_edge_distance])\n bin_left_front_point = np.matmul(rot_matrix, vec)\n\n # Right Edge\n beam_right_angle = np.deg2rad(right)\n rot_matrix = np.array([[np.cos(beam_right_angle), -np.sin(beam_right_angle)], [np.sin(beam_right_angle), np.cos(beam_right_angle)]])\n\n vec = np.array([0, bin_front_edge_distance])\n bin_right_front_point = np.matmul(rot_matrix, vec)\n\n vec = np.array([0, bin_back_edge_distance])\n bin_right_back_point = np.matmul(rot_matrix, vec)\n\n\n return bin_left_back_point, bin_right_back_point, bin_right_front_point, bin_left_front_point",
"def rectangularize_transmit_ping_data(self, data_type: str) -> None:\n\n # Transmit data\n for k, v in self.ping_data_dict_tx[data_type].items():\n if all((x is None) or (x.size == 0) for x in v): # if no data in a particular channel\n self.ping_data_dict_tx[data_type][k] = None\n else:\n self.ping_data_dict_tx[data_type][k] = self.pad_shorter_ping(v)",
"def check_column_beam_relationships(self, connection_type, steel, left_beam, right_beam, top_column, bottom_column):\r\n if connection_type == 'top exterior':\r\n # For column in one-story building or top story:\r\n # Strong column weak beam is exempted if the column axial load ratio < 0.3 for all load combinations except\r\n # those using amplified seismic load.\r\n # If not the case, still need to check the Mpc/Mpb ratio.\r\n if bottom_column.demand['axial']/bottom_column.strength['axial'] < 0.3:\r\n self.is_feasible['SCWB'] = True\r\n else:\r\n Puc_bot = bottom_column.demand['axial']\r\n Ag_bot = bottom_column.section['A']\r\n ht_bot = bottom_column.unbraced_length['x']*12.2 # Be cautious: convert the unit from ft to inch\r\n Zx_bot = bottom_column.section['Zx']\r\n db = left_beam.section['d']\r\n # Compute the moment summation for column\r\n self.moment['Mpc'] = Zx_bot * (steel.Fy-Puc_bot/Ag_bot) * (ht_bot/(ht_bot-db/2))\r\n # Compute the moment summation for beam\r\n self.moment['Muv'] = self.shear_force['VRBS1'] * (self.left_RBS_dimension['a']\r\n + self.left_RBS_dimension['b']/2\r\n + bottom_column.section['d']/2)\r\n self.moment['Mpb'] = self.moment['Mpr1'] + self.moment['Muv']\r\n # Perform the strong column weak beam check\r\n if self.moment['Mpc']/self.moment['Mpb'] >= STRONG_COLUMN_WEAK_BEAM_RATIO:\r\n self.is_feasible['SCWB'] = True\r\n else:\r\n sys.stderr.write('Strong column weak beam (top exterior) is not satisfied!\\n')\r\n self.is_feasible['SCWB'] = False\r\n elif connection_type == 'top interior':\r\n # For column in one-story building or top story:\r\n # Strong column weak beam is exempted if the column axial load ratio < 0.3 for all load combinations except\r\n # those using amplified seismic load.\r\n # If not the case, still need to check the Mpc/Mpb ratio.\r\n if bottom_column.demand['axial']/bottom_column.strength['axial'] < 0.3:\r\n self.is_feasible['SCWB'] = True\r\n else:\r\n Puc_bot = bottom_column.demand['axial']\r\n Ag_bot = bottom_column.section['A']\r\n h_bot = bottom_column.unbraced_length['x']*12.0 # Be cautious: convert the unit from ft to inch\r\n Zx_bot = bottom_column.section['Zx']\r\n # Generally the left and right beams have the identical beam sizes\r\n db = (left_beam.section['d'] + right_beam.section['d']) / 2\r\n # Compute the moment summation for column\r\n self.moment['Mpc'] = Zx_bot * (steel.Fy-Puc_bot/Ag_bot) * (h_bot/(h_bot-db/2))\r\n # Compute the moment summation for beam\r\n self.moment['Muv'] = (self.shear_force['VRBS1']+self.shear_force['VRBS2']) \\\r\n * (self.left_RBS_dimension['a']+self.left_RBS_dimension['b']/2\r\n +bottom_column.section['d']/2)\r\n self.moment['Mpb'] = self.moment['Mpr1'] + self.moment['Mpr2'] + self.moment['Muv']\r\n # Perform the strong column weak beam check\r\n if self.moment['Mpc']/self.moment['Mpb'] >= STRONG_COLUMN_WEAK_BEAM_RATIO:\r\n self.is_feasible['SCWB'] = True\r\n else:\r\n sys.stderr.write('Strong column weak beam (top interior) is not satisfied!\\n')\r\n self.is_feasible['SCWB'] = False\r\n elif connection_type == 'typical exterior':\r\n # This connection has two columns and one beam\r\n Puc_top = top_column.demand['axial']\r\n Puc_bot = bottom_column.demand['axial']\r\n Ag_top = top_column.section['A']\r\n Ag_bot = bottom_column.section['A']\r\n ht_top = top_column.unbraced_length['x']*12.0 # Be cautious: convert the unit from ft to inch\r\n ht_bot = bottom_column.unbraced_length['x']*12.0 # Be cautious: convert the unit from ft to inch\r\n Zx_top = top_column.section['Zx']\r\n Zx_bot = bottom_column.section['Zx']\r\n db = left_beam.section['d']\r\n # Compute the moment summation for column\r\n self.moment['Mpc'] = Zx_top * (steel.Fy-Puc_top/Ag_top) * (ht_top/(ht_top-db/2)) \\\r\n + Zx_bot * (steel.Fy-Puc_bot/Ag_bot) * (ht_bot/(ht_bot-db/2))\r\n # Compute the moment summation for beam\r\n self.moment['Muv'] = self.shear_force['VRBS1'] * (self.left_RBS_dimension['a']\r\n + self.left_RBS_dimension['b']/2\r\n + bottom_column.section['d']/2)\r\n self.moment['Mpb'] = self.moment['Mpr1'] + self.moment['Muv']\r\n # Perform the strong column weak beam check\r\n if self.moment['Mpc']/self.moment['Mpb'] >= STRONG_COLUMN_WEAK_BEAM_RATIO:\r\n self.is_feasible['SCWB'] = True\r\n else:\r\n sys.stderr.write('Strong column weak beam is not satisfied!\\n')\r\n self.is_feasible['SCWB'] = False\r\n elif connection_type == 'typical interior':\r\n # This connection has two columns and two beams\r\n Puc_top = top_column.demand['axial']\r\n Puc_bot = bottom_column.demand['axial']\r\n Ag_top = top_column.section['A']\r\n Ag_bot = bottom_column.section['A']\r\n h_top = top_column.unbraced_length['x']*12.0 # Be cautious: convert the unit from ft to inch\r\n h_bot = bottom_column.unbraced_length['x']*12.0 # Be cautious: convert the unit from ft to inch\r\n Zx_top = top_column.section['Zx']\r\n Zx_bot = bottom_column.section['Zx']\r\n # Generally the left and right beams have the identical beam sizes\r\n db = (left_beam.section['d'] + right_beam.section['d']) / 2\r\n # Compute the moment summation for column\r\n self.moment['Mpc'] = Zx_top * (steel.Fy - Puc_top / Ag_top) * (h_top / (h_top - db / 2)) \\\r\n + Zx_bot * (steel.Fy - Puc_bot / Ag_bot) * (h_bot / (h_bot - db / 2))\r\n # Compute the moment summation for beam\r\n self.moment['Muv'] = (self.shear_force['VRBS1']+self.shear_force['VRBS2']) \\\r\n * (self.left_RBS_dimension['a']+self.left_RBS_dimension['b']/2\r\n + bottom_column.section['d']/2)\r\n self.moment['Mpb'] = self.moment['Mpr1'] + self.moment['Mpr2'] + self.moment['Muv']\r\n # Perform the strong column weak beam check\r\n if self.moment['Mpc'] / self.moment['Mpb'] >= STRONG_COLUMN_WEAK_BEAM_RATIO:\r\n self.is_feasible['SCWB'] = True\r\n else:\r\n sys.stderr.write('Strong column weak beam is not satisfied!\\n')\r\n self.is_feasible['SCWB'] = False\r\n else:\r\n sys.stderr.write('Error: wrong type of connection specified!\\nNo such keyword for connection exists!\\n')\r\n sys.exit(2)"
] | [
"0.554512",
"0.5537147",
"0.52834463",
"0.51064193",
"0.49272564",
"0.49100593",
"0.48409185",
"0.47785255",
"0.4760839",
"0.4692016",
"0.46784097",
"0.46771446",
"0.46669835",
"0.46640566",
"0.46454644",
"0.46390733",
"0.4620003",
"0.46098214",
"0.45902753",
"0.4568258",
"0.4552266",
"0.45495763",
"0.4536649",
"0.45279703",
"0.45000124",
"0.44975555",
"0.44936594",
"0.44897097",
"0.44885272",
"0.4486041"
] | 0.63880956 | 0 |
Given a SansData of sample and empty cell that have been corrected, subtract them | def correct_background(sample,empty_cell):
result=sample-empty_cell
return result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def subtract(self,*datas):\n\t\tdatas = list(datas)\n\t\tresult = datas.pop(0)\n\t\tfor data in datas:\n\t\t\tresult -= data\n\t\treturn result",
"def demeaned(self):\n return self.data - self.mean",
"def calculate_correction(filedic):\n lanczos_cera = xr.open_mfdataset(filedic['lanczos(CERA)'], combine='by_coords')\n lanczos_noaa = xr.open_mfdataset(filedic['lanczos(20CR)'], combine='by_coords')\n return lanczos_noaa.drop('number').squeeze() - lanczos_cera.drop('number').squeeze()",
"def test_BBBP_erroneous_data_removed_tailored(self):\n cp = Plotter.from_smiles(self.data_BBBP_erroneous_smiles[\"smiles\"], target=self.data_BBBP_erroneous_smiles[\"target\"], target_type=\"C\", sim_type=\"tailored\")\n self.assertEqual(len(cp._Plotter__df_descriptors.index), len(self.data_BBBP_erroneous_smiles.index) - (len(self.list_BBBP_erroneous_smiles) + len(self.list_BBBP_erroneous_descriptors)))",
"def _clean(\n data: np.ndarray, backsub: bool = True, xbad: Optional[np.ndarray] = None, ybad: Optional[np.ndarray] = None\n ) -> np.ndarray:\n (ny, nx) = data.shape\n\n # REMOVE BAD COLUMNS AND ROWS\n if xbad is not None:\n x1 = xbad - 1\n if x1 < 0:\n x1 = 1\n x2 = x1 + 2\n if x2 >= nx:\n x2 = nx - 1\n x1 = x2 - 2\n for j in range(ny):\n data[j][xbad] = 0.5 * (data[j][x1] + data[j][x2])\n if ybad is not None:\n y1 = ybad - 1\n if y1 < 0:\n y1 = 1\n y2 = y1 + 2\n if y2 >= ny:\n y2 = ny - 1\n y1 = y2 - 2\n for i in range(nx):\n data[ybad][i] = 0.5 * (data[y1][i] + data[y2][i])\n\n # REMOVE GLOBAL SLOPES\n if backsub:\n xsl = np.median(data, axis=0)\n ysl = np.median(data, axis=1).reshape((ny, 1))\n xsl -= np.mean(xsl)\n ysl -= np.mean(ysl)\n xslope = np.tile(xsl, (ny, 1))\n yslope = np.tile(ysl, (1, nx))\n return data - xslope - yslope\n else:\n return data",
"def background_subtract_data(data):\n bgsub_data = data.copy()\n bax_concs = data.columns.levels[0]\n lipo_concs = data.columns.levels[1]\n\n for bax_conc in data.columns.levels[0]:\n timecourses = data.xs(bax_conc, axis=1, level='Bax')\n bg = timecourses[0.]\n for lipo_conc in lipo_concs:\n bgsub_tc = timecourses[lipo_conc] - bg\n bgsub_data[(bax_conc, lipo_conc)] = bgsub_tc\n\n return bgsub_data",
"def test_CLINTOX_2_erroneous_data_removed_tailored(self):\n cp = Plotter.from_smiles(self.data_CLINTOX_2_erroneous_smiles[\"smiles\"], target=self.data_CLINTOX_2_erroneous_smiles[\"target\"], target_type=\"C\", sim_type=\"tailored\")\n self.assertEqual(len(cp._Plotter__df_descriptors.index), len(self.data_CLINTOX_2_erroneous_smiles.index) - (len(self.list_CLINTOX_2_erroneous_smiles) + len(self.list_CLINTOX_2_erroneous_descriptors)))",
"def clean_data(self, opz):\n# pdb.set_trace()\n mask = (opz['Opzetstuk Noord (°)']<-1) | (opz['Opzetstuk Noord (°)']>100)\n opz = opz.drop(opz.loc[mask].index)\n opz['open'] = opz[\"Opzetstuk Noord (°)\"].apply(lambda x: 1 if x < 80 else 0)\n #Deze klopt niet. We hebben het moment nodig van opengaan en het moment van dichtgaat. Moment van openen is: wanneer de verandering van de aantal graden >1 graad is. Moment van sluiten is de laatste verandering totdat het niet meer veranderd. Zie ook code van Pieter in C#.\n opz['diff'] = opz['open'].diff()\n beweegt=opz[opz['diff']!=0]\n return beweegt",
"def stripDataStd(d, t, std = 3):\n #First check if there are any 0 values\n index = []\n for i in range(len(d)):\n index.append(i)\n for j in range(len(d[i])):\n if d[i][j] == 0:\n index.pop()\n print \"Zero Value\"\n break\n\n d = d[index]\n t = t[index]\n\n #Now strip based on std\n avgData = np.average(d, axis = 0)\n res = d - avgData\n totalRes = np.sum(np.abs(res), axis = 1)\n resStd = totalRes.std()\n index = []\n for i in range(len(totalRes)):\n if totalRes[i] <= std * resStd:\n index.append(i)\n\n d = d[index]\n t = t[index]\n\n return d, t",
"def degen_translate(formatted_bands, en_tolerance=0.01, padding=False):\n tmp = np.array(formatted_bands)\n size = np.shape(tmp)\n\n # degen_bands = np.zeros(size) # assumption 1: missing data are assumed null, labeled by 0\n degen_bands = np.zeros(size) + 1 # assumption 2: missing data are assumed non-degenerate, labeled by 1\n\n # Need further test\n for i in range(size[1]):\n each_column = []\n count = 1\n for j in range(size[0]-1):\n if tmp[j][i] == 0:\n count = 0\n break\n else:\n if np.absolute(tmp[j+1][i]-tmp[j][i]) <= en_tolerance:\n count += 1\n else:\n for k in range(count):\n each_column.append(count)\n count = 1\n\n if count == 0:\n pass\n else:\n for k in range(count):\n each_column.append(count)\n degen_bands[:, i] = np.array(each_column)\n\n return degen_bands",
"def revert(self, data):\n\t\t#######################################################################\n\t\t# ** START OF YOUR CODE **\n\t\t#######################################################################\n\t\tif (data.min(axis=0) == self.data_min).all() and (data.max(axis=0) == self.data_max).all():\n\t\t\treturn data\n\t\treturn data*(self.data_max-self.data_min)+self.data_min\n\t\t#######################################################################\n\t\t# ** END OF YOUR CODE **\n\t\t#######################################################################",
"def remM3xZernike(tdata):\n idx = np.concatenate((np.arange(0,60),np.arange(61,80),np.arange(81,100),np.arange(101,120),np.arange(121,140)))\n datanew = tdata[:,idx]\n return datanew",
"def test_CLINTOX_2_erroneous_data_removed_structural(self):\n cp = Plotter.from_smiles(self.data_CLINTOX_2_erroneous_smiles[\"smiles\"], target=self.data_CLINTOX_2_erroneous_smiles[\"target\"], target_type=\"C\", sim_type=\"structural\")\n self.assertEqual(len(cp._Plotter__df_descriptors.index), len(self.data_CLINTOX_2_erroneous_smiles.index) - len(self.list_CLINTOX_2_erroneous_smiles))",
"def test_BBBP_erroneous_data_removed_structural(self):\n cp = Plotter.from_smiles(self.data_BBBP_erroneous_smiles[\"smiles\"], target=self.data_BBBP_erroneous_smiles[\"target\"], target_type=\"C\", sim_type=\"structural\")\n self.assertEqual(len(cp._Plotter__df_descriptors.index), len(self.data_BBBP_erroneous_smiles.index) - len(self.list_BBBP_erroneous_smiles))",
"def subtract(raster1, raster2):\n valid_mask = (\n (raster1 != nodata) &\n (raster2 != nodata))\n result = numpy.empty(raster1.shape, dtype=numpy.float32)\n result[:] = nodata\n result[valid_mask] = raster1[valid_mask] - raster2[valid_mask]\n return result",
"def complement(self):\n for cell in self.compact:\n cell.set(not cell.peg)",
"def remove_data():\n # Removing the existing data\n col_answer_given.remove()\n col_answer_not_given.remove()\n col_q_not_given.remove()\n col_to_summarize.remove()",
"def clean(self):\n\n if (self.clean_level == 'dusty') | (self.clean_level == 'clean'):\n idx, = np.where(self['B_flag'] == 0)\n self.data = self[idx, :]\n\n return",
"def subtract(self,ctSub):\n\n # First confirm eligible for subtraction\n if (not np.array_equal(self.x1_flat,ctSub.x1_flat)) or (not np.array_equal(self.x2_flat,ctSub.x2_flat)):\n raise Exception(\"Can't subtract because not meshed the same\")\n\n ctResult = copy.deepcopy(ctSub)# copy the class\n\n \n # Original method\n # ctResult.u = self.u - ctSub.u\n # ctResult.uMesh = griddata(np.column_stack([ctResult.y, ctResult.z]),ctResult.u,(ctResult.yMesh.flatten(), ctResult.zMesh.flatten()), method='cubic')\n\n # New method\n ctResult.u_mesh = self.u_mesh - ctSub.u_mesh\n ctResult.v_mesh = self.v_mesh - ctSub.v_mesh\n ctResult.w_mesh = self.w_mesh - ctSub.w_mesh\n ctResult.u_cubed = self.u_cubed - ctSub.u_cubed\n\n\n return ctResult",
"def original_clean():\n # load the data\n dataset = np.genfromtxt(\"wdbc.data\", dtype=np.float, delimiter=',', usecols=(2, 3, 4, 5, 6, 7, 8, 9, 10, 11,\n 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23, 24, 25, 26, 27,\n 28, 29, 30, 31), encoding=None)\n labels = np.genfromtxt(\"wdbc.data\", dtype=None, delimiter=',', usecols=(1), encoding=None)\n temp_labels = np.zeros(len(labels))\n for i in range(len(labels)):\n if labels[i] == 'B':\n temp_labels[i] = 0\n else:\n temp_labels[i] = 1\n # normalize\n temp_data = normalize(dataset)\n return temp_data, temp_labels",
"def test_negative_input(self):\n negative_data_down = np.full_like(\n self.cube_uv_down.data, dtype=np.float32, fill_value=-0.1\n )\n negative_uv_down = self.cube_uv_down.copy(data=negative_data_down)\n msg = (\n \"The radiation flux in UV downward contains data \"\n \"that is negative or NaN. Data should be >= 0.\"\n )\n with self.assertRaisesRegex(ValueError, msg):\n calculate_uv_index(negative_uv_down)",
"def test_mixed_incomplete_data_2():\n profiles = [[2, 0]]\n payoffs = [[1.0, 0.0]]\n game = paygame.game(2, 2, profiles, payoffs)\n devgains = regret.mixture_deviation_gains(game, [1, 0])\n assert np.allclose(\n devgains, [0, np.nan], equal_nan=True\n ), \"nonzero regret or deviation without payoff didn't return nan\"",
"def drop_table(self):\n for ss in self.spectrae:\n ss.tau[('H',1,1215)] = np.array([0])",
"def th_cell_diff(th_state, time, d):\n assert d[\"alpha_int\"] < d[\"alpha\"]\n \n # divide array into cell states\n tnaive = th_state[:d[\"alpha_int\"]]\n tint = th_state[d[\"alpha_int\"]:d[\"alpha\"]]\n teff = th_state[d[\"alpha\"]:]\n \n assert len(tnaive)+len(tint)+len(teff) == len(th_state)\n tnaive = np.sum(tnaive)\n tint = np.sum(tint)\n teff = np.sum(teff)\n \n # IL2 production\n il2_producers = tnaive+tint\n il2_consumers = teff+tint \n conc_il2 = d[\"rate_il2\"]*il2_producers/(d[\"K_il2\"]+il2_consumers)\n \n # IL7 production\n il7_consumers = il2_consumers\n conc_il7 = d[\"rate_il7\"] / (d[\"K_il2\"]+il7_consumers)\n \n # apply feedback on rate beta\n fb_ifn = 0\n if d[\"fb_ifn\"] != 0:\n conc_ifn = d[\"rate_ifn\"]*(il2_producers)\n fb_ifn = (d[\"fb_ifn\"]*conc_ifn**3)/(conc_ifn**3+d[\"K_ifn\"]**3)\n \n beta = (fb_ifn+1)*d[\"beta\"] \n beta_p = d[\"beta_p\"] \n rate_death = d[\"d_eff\"]\n\n # check homeostasis criteria\n if d[\"crit\"] == False:\n update_t0(d, time, conc_il2, conc_il7)\n elif d[\"death_mode\"] == False:\n beta_p = beta_p*np.exp(-d[\"decay_p\"]*(time-d[\"t0\"]))\n else:\n rate_death = rate_death*np.exp(0.1*(time-d[\"t0\"]))\n \n # differentiation \n dt_state = diff_effector_new(th_state, teff, d, beta, rate_death, beta_p)\n \n \n return dt_state",
"def subtractAllNumericHas (self, other):\n \n if self.hasOutErrorPackets():\n if other.hasOutErrorPackets():\n self.outErrorPackets -= other.outErrorPackets\n \n if self.hasInErrorPackets():\n if other.hasInErrorPackets():\n self.inErrorPackets -= other.inErrorPackets\n \n if self.hasInDiscardPackets():\n if other.hasInDiscardPackets():\n self.inDiscardPackets -= other.inDiscardPackets\n \n if self.hasOutUnicastPackets():\n if other.hasOutUnicastPackets():\n self.outUnicastPackets -= other.outUnicastPackets\n \n if self.hasInMulticastPackets():\n if other.hasInMulticastPackets():\n self.inMulticastPackets -= other.inMulticastPackets\n \n if self.hasOutBroadcastPackets():\n if other.hasOutBroadcastPackets():\n self.outBroadcastPackets -= other.outBroadcastPackets\n \n if self.hasInBroadcastPackets():\n if other.hasInBroadcastPackets():\n self.inBroadcastPackets -= other.inBroadcastPackets\n \n if self.hasOutMulticastPackets():\n if other.hasOutMulticastPackets():\n self.outMulticastPackets -= other.outMulticastPackets\n \n if self.hasInUnknownProtocolPackets():\n if other.hasInUnknownProtocolPackets():\n self.inUnknownProtocolPackets -= other.inUnknownProtocolPackets\n \n if self.hasOutDiscardPackets():\n if other.hasOutDiscardPackets():\n self.outDiscardPackets -= other.outDiscardPackets\n \n if self.hasInUnicastPackets():\n if other.hasInUnicastPackets():\n self.inUnicastPackets -= other.inUnicastPackets\n \n if self.hasOutOctets():\n if other.hasOutOctets():\n self.outOctets -= other.outOctets\n \n if self.hasInOctets():\n if other.hasInOctets():\n self.inOctets -= other.inOctets\n \n \n pass",
"def clean(self):\n # Perform the standard ACE cleaning\n max_status = mm_ace.clean(self)\n\n # Replace bad values with NaN and remove times with no valid data\n ecols = ['eflux_38-53', 'eflux_175-315']\n\n # Evaluate the electron flux data\n self[self.data['status_e'] > max_status, ecols] = np.nan\n\n # Evaluate the proton flux data\n pcols = ['pflux_47-68', 'pflux_115-195', 'pflux_310-580',\n 'pflux_795-1193', 'pflux_1060-1900']\n self[self.data['status_p'] > max_status, pcols] = np.nan\n\n # Include both fluxes and the anisotropy index in the removal eval\n eval_cols = ecols + pcols\n eval_cols.append('anis_ind')\n\n # Remove lines without any good data\n good_cols = (np.isfinite(self.data.loc[:, eval_cols])).sum(axis=1)\n bad_index = good_cols[good_cols == 0].index\n self.data = self.data.drop(index=bad_index)\n\n return",
"def cleaning (data):",
"def test_shapes(self):\n\n # Creates a raw layer\n self.validator.adata.raw = self.validator.adata\n self.validator.adata.raw.var.drop(\"feature_is_filtered\", axis=1, inplace=True)\n self.validator.adata.X = examples.adata_non_raw.X.copy()\n self.validator.adata.uns[\"X_normalization\"] = \"CPM\"\n\n # remove one gene\n self.validator.adata = self.validator.adata[:, 1:]\n self.validator.validate_adata()\n self.assertEqual(\n self.validator.errors,\n [\"ERROR: Number of genes in X (3) is different than raw.X (4).\"],\n )",
"def correct_pos():\n data[['currXcorrected','currYcorrected']] = data[['currBubbleX','currBubbleY']].copy()\n for i in data.index:\n x = int(data.loc[i,'currBubbleX'])\n y = int(data.loc[i,'currBubbleY'])\n if x<0:\n data.loc[i,'currXcorrected'] = np.nan\n data.loc[i,'currYcorrected'] = np.nan\n else: \n data.loc[i,'currXcorrected'] = int(x-77-320)\n data.loc[i,'currYcorrected'] = int(y-77-60)",
"def generate_negative_samples(self, data, sampled_data, zeros=[], validation=False):\n negative_sampled_data = []\n negative_sampled_indices = []\n for sample in sampled_data:\n i = data['pos'].index(sample) ## index of a particular move in a demo\n all_num = 0\n for which, num in enumerate(data['leng_pos']):\n all_num += num\n if all_num > i:\n which_demo = which ## index of a demo the move with index i comes from\n break\n\n sum_neg_lengths = sum(data['leng_neg'][:which_demo])\n\n key = sum_neg_lengths-1 \n value = sum_neg_lengths + data['leng_neg'][which_demo]\n demo_negative_data = data['neg'][key : value]\n state, action = sample\n for demo_state, demo_action in demo_negative_data:\n if demo_state == state:\n negative_sampled_data.extend([(demo_state, demo_action)])\n demo_index = data['neg'].index((demo_state, demo_action))\n negative_sampled_indices.append(demo_index)\n\n if not validation:\n num_pos = sum(self.pipeline_y == 1)\n num_neg = len(negative_sampled_data)\n pos_sample = self.pipeline_X[:num_pos, :]\n neg_sample = self.pipeline_X[num_pos + negative_sampled_indices, :]\n y_vector = [1] * num_pos + [0] * num_neg\n ######################### Mouselab ad-hc #########################\n ########################## Removing 0's ##########################\n non_zero = [self.pipeline_X[i, :] for i in range(num_pos)\n if i not in zeros]\n pos_sample = vstack(non_zero) if non_zero != [] else self.pipeline_X[0,:]\n num_pos = pos_sample.shape[0]\n y_vector = [1] * num_pos + [0] * num_neg\n ##################################################################\n\n self.pipeline_X = vstack((pos_sample, neg_sample))\n self.pipeline_y = np.array(y_vector, dtype='uint8')\n \n return negative_sampled_data"
] | [
"0.54819214",
"0.53857255",
"0.52367604",
"0.5233917",
"0.5160762",
"0.5151851",
"0.5135383",
"0.51290405",
"0.5119795",
"0.5117193",
"0.5094258",
"0.50864136",
"0.50637335",
"0.5048496",
"0.50484747",
"0.5044647",
"0.5031895",
"0.49805743",
"0.49659047",
"0.49646086",
"0.4936021",
"0.4932464",
"0.4893158",
"0.48830312",
"0.48783997",
"0.4877592",
"0.48601058",
"0.48538187",
"0.48529366",
"0.48489138"
] | 0.59561723 | 0 |
given a SansData with q,qx,qy,and theta images defined, correct for the fact that the detector is flat and the eswald sphere is curved. | def correct_solid_angle(sansdata):
result=sansdata.data*(np.cos(sansdata.theta)**3)
res=SansData()
res.data=result
res.metadata=deepcopy(sansdata.metadata)
res.qx=copy(sansdata.qx)
res.qy=copy(sansdata.qy)
res.theta=copy(sansdata.theta)
return res | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_plot_cspad(geometry, fname_data, amp_range=(0,0.5)):\n #rad1 = 93\n #rad2 = 146\n rad1 = 655\n rad2 = 670\n\n # get pixel coordinate index arrays:\n xyc = xc, yc = 500, 500# None\n\n #rows, cols = geometry.get_pixel_coord_indexes(xy0_off_pix=None)\n rows, cols = geometry.get_pixel_coord_indexes(xy0_off_pix=xyc, do_tilt=True)\n\n ixo, iyo = geometry.point_coord_indexes(xy0_off_pix=xyc, do_tilt=True)\n logger.info('Detector origin indexes ixo:%d iyo:%d' % (ixo, iyo))\n\n root, ext = os.path.splitext(fname_data)\n arr = np.load(fname_data) if ext == '.npy' else np.loadtxt(fname_data, dtype=np.float)\n arr.shape= (4,8,185,388)\n\n logger.info('shapes rows: %s cols: %s weight: %s' % (str(rows.shape), str(cols.shape), str(arr.shape)))\n\n arr.shape = rows.shape\n img = img_from_pixel_arrays(rows, cols, W=arr)\n\n rcc_ring = (iyo, ixo)\n axim = gg.plotImageLarge(img,amp_range=amp_range)\n gg.drawCircle(axim, rcc_ring, rad1, linewidth=1, color='w', fill=False)\n gg.drawCircle(axim, rcc_ring, rad2, linewidth=1, color='w', fill=False)\n gg.drawCenter(axim, rcc_ring, rad1, linewidth=1, color='w')\n gg.move(500,10)\n gg.show()",
"def sphere2img(lat,lon,latc,lonc,xcen,ycen,rSun,peff,hemi_out=False):\n # Correction of finite distance (1AU)\n sin_asd = 0.004660\n cos_asd = 0.99998914\n\n last_latc = 0.0\n cos_latc = 1.0\n sin_latc = 0.0\n\n if latc != last_latc:\n sin_latc = np.sin(latc)\n cos_latc = np.cos(latc)\n last_latc = latc\n\n sin_lat = np.sin(lat)\n cos_lat = np.cos(lat)\n cos_lat_lon = cos_lat*np.cos(lon-lonc)\n\n cos_cang = sin_lat*sin_latc + cos_latc*cos_lat_lon\n if cos_cang < 0.0:\n hemisphere = 1\n else:\n hemisphere = 0\n\n r = rSun*cos_asd/(1.0 - cos_cang*sin_asd)\n xr = r*cos_lat*np.sin(lon - lonc)\n yr = r*(sin_lat*cos_latc - sin_latc*cos_lat_lon)\n\n cospa = np.cos(peff)\n sinpa = np.sin(peff)\n xi = xr*cospa - yr*sinpa\n eta = xr*sinpa + yr*cospa\n\n xi = xi + xcen\n eta = eta + ycen\n\n if hemi_out == True:\n return xi,eta,hemisphere\n else:\n return xi,eta",
"def test_SIS():\r\n def is_symmetric_mode(beta, k0, g, a_over_d, h):\r\n \"\"\"\r\n Eq (7i) of paper\r\n beta is what I call kx\r\n k0 is vacuum angular wavenumber\r\n g is thickness of air layer\r\n h is thickness of corrugated layer\r\n a_over_d is the fraction of corrugated layer which is air\r\n \"\"\"\r\n lhs = ((cmath.sqrt(beta**2 - k0**2) / k0)\r\n * cmath.tanh(g/2 * cmath.sqrt(beta**2 - k0**2)))\r\n rhs = a_over_d * cmath.tan(k0 * h)\r\n return floats_are_equal(lhs, rhs, tol=1e-4)\r\n\r\n def is_antisymmetric_mode(beta, k0, g, a_over_d, h):\r\n \"\"\"\r\n Eq (7ii) of paper\r\n \"\"\"\r\n lhs = ((cmath.sqrt(beta**2 - k0**2) / k0)\r\n / cmath.tanh(g/2 * cmath.sqrt(beta**2 - k0**2)))\r\n rhs = a_over_d * cmath.tan(k0 * h)\r\n return floats_are_equal(lhs, rhs, tol=1e-4)\r\n # Choose some parameters (can be anything, these are from Fig. 3 caption)\r\n w = 2 * pi * (4 * nu.THz)\r\n h = 50 * nu.um\r\n g = 50 * nu.um\r\n a_over_d = 0.1\r\n \r\n # Now run analysis\r\n k0 = w / nu.c0\r\n d_over_a = a_over_d**-1\r\n # epsilon of a PEC (perfect electric conductor) is -infinity, but code\r\n # doesn't allow that. Use big value instead...\r\n PEC_eps = -1e11\r\n params = {'d_list': [inf, h, g, h, inf],\r\n 'ex_list': [PEC_eps, d_over_a, 1, d_over_a, PEC_eps],\r\n 'ez_list': [PEC_eps, PEC_eps, 1, PEC_eps, PEC_eps],\r\n 'mu_list': [1, a_over_d, 1, a_over_d, 1],\r\n 'w': w}\r\n \r\n kx_list = find_kx(params, grid_points=30, iterations=11, reduction_factor=14,\r\n plot_full_region=True,\r\n search_domain=[-1e5 * nu.m**-1, 1e5 * nu.m**-1, 0, 1e5 * nu.m**-1])\r\n \r\n print('kx_list -- ' + str(len(kx_list)) + ' entries...')\r\n print(['(%.5g+%.5gj) rad/um' % (kx.real / nu.um**-1, kx.imag / nu.um**-1)\r\n for kx in kx_list])\r\n # Here, I'm only interested in solutions on the positive real axis\r\n kx_list = [kx for kx in kx_list if abs(kx.real) > 1e5 * abs(kx.imag)]\r\n kx_list = [-kx if kx.real < 0 else kx for kx in kx_list]\r\n # Delete repeats with tolerance 1e-4\r\n kx_list_norepeat = []\r\n for kx in kx_list:\r\n if not any(floats_are_equal(kx, kx2, tol=1e-4) for kx2 in kx_list_norepeat):\r\n kx_list_norepeat.append(kx)\r\n kx_list = kx_list_norepeat\r\n print('kx_list (cleaned up) -- ' + str(len(kx_list)) + ' entries...')\r\n print(['(%.5g+%.5gj) rad/um' % (kx.real / nu.um**-1, kx.imag / nu.um**-1)\r\n for kx in kx_list])\r\n found_sym_mode = False\r\n for kx in kx_list:\r\n if is_symmetric_mode(kx, k0, g, a_over_d, h):\r\n found_sym_mode = True\r\n print('Found symmetric mode! ',\r\n '(%.5g+%.5gj) rad/um' % (kx.real / nu.um**-1, kx.imag / nu.um**-1))\r\n params2 = deepcopy(params)\r\n params2['kx'] = kx\r\n params2 = find_all_params_from_kx(params2)\r\n if check_mode(params2) is not True:\r\n print('Not a real mode? ... Error code:')\r\n print(check_mode(params2))\r\n else:\r\n plot_mode(params2)\r\n assert found_sym_mode\r\n found_anti_mode = False\r\n for kx in kx_list:\r\n if is_antisymmetric_mode(kx, k0, g, a_over_d, h):\r\n found_anti_mode = True\r\n print('Found antisymmetric mode! ',\r\n '(%.5g+%.5gj) rad/um' % (kx.real / nu.um**-1, kx.imag / nu.um**-1))\r\n params2 = deepcopy(params)\r\n params2['kx'] = kx\r\n params2 = find_all_params_from_kx(params2)\r\n if check_mode(params2) is not True:\r\n print('Not a real mode? ... Error code:')\r\n print(check_mode(params2))\r\n else:\r\n plot_mode(params2)\r\n assert found_anti_mode\r\n \r\n print('Congratulations, the solver found the correct kx for both the')\r\n print('symmetric and antisymmetric mode of the structure, consistent')\r\n print('with the analytical formula in the literature.')",
"def calculate_soma_surface(data: Data) -> float:\n\n soma = data.morphology.get_soma()\n return 4.0 * math.pi * soma['radius'] * soma['radius']",
"def correct_detector_efficiency(sansdata,sensitivity):\n result=sansdata.data/sensitivity #Could be done more elegantly by defining a division method on SansData\n res=SansData()\n res.data=result\n res.metadata=deepcopy(sansdata.metadata)\n res.qx=copy(sansdata.qx)\n res.qy=copy(sansdata.qy)\n res.theta=copy(sansdata.theta)\n return res",
"def test_cspad_xy_at_z():\n ## 'CxiDs1.0:Cspad.0)' or 'DscCsPad'\n basedir = '/reg/g/psdm/detector/alignment/cspad/calib-cxi-camera1-2014-09-24/'\n fname_geometry = basedir + '2016-06-03-geometry-cxi06216-r25-camera1-z175mm.txt'\n fname_data = basedir + '2016-06-03-chun-cxi06216-0025-DscCsPad-max.txt'\n\n geometry = GeometryAccess(fname_geometry, pbits=0o377)\n\n # get pixel coordinate index arrays:\n xyc = xc, yc = 1000, 1000\n #rows, cols = geometry.get_pixel_coord_indexes(xy0_off_pix=xyc)\n #rows, cols = geometry.get_pixel_coord_indexes(do_tilt=True)\n #rows, cols = geometry.get_pixel_xy_inds_at_z(zplane=None, xy0_off_pix=xyc)\n rows, cols = geometry.get_pixel_xy_inds_at_z(zplane=150000)\n\n root, ext = os.path.splitext(fname_data)\n arr = np.load(fname_data) if ext == '.npy' else np.loadtxt(fname_data, dtype=np.float)\n\n #logger.info('arr.shape=', arr.shape\n arr.shape= (32,185,388)\n\n #ave, rms = arr.mean(), arr.std()\n #amp_range = (ave-rms, ave+3*rms)\n amp_range = (0, 1000)\n logger.info('amp_range:' + str(amp_range))\n\n logger.info('shapes rows: %s cols: %s weight: %s' % (str(rows.shape), str(cols.shape), str(arr.shape)))\n img = img_from_pixel_arrays(rows,cols,W=arr)\n\n axim = gg.plotImageLarge(img,amp_range=amp_range)\n gg.move(500,10)\n gg.show()",
"def fix_sphere_h (center_x, center_y, center_z, radius, centers, radii, len_points, list_of_a):\n g_x = []\n g_y = []\n g_z = []\n points = [hydrogen_coord_gen(center_x, center_y, center_z, radius) for i in range(0, len_points)] \n x = [points[i][0] for i in range(0, len(points))] \n y = [points[i][1] for i in range(0, len(points))]\n z = [points[i][2] for i in range(0, len(points))]\n for i in range(0, len(points)):\n check = 0\n check_b = 0\n j = 0\n while (j <= (len(centers) - 1) and (check == 0)): \n if (calculate_3D_distance_2_centers(x[i], y[i], z[i], centers[j][0], centers[j][1], centers[j][2]) < radii[j]):\n check += 1\n j += 1\n h = 0\n while ((check_b == 0) and (h <= len(list_of_a) -1)):\n if (calculate_3D_distance_2_centers(x[i], y[i], z[i], list_of_a[h].x, list_of_a[h].y, list_of_a[h].z) <= 1.50): \n check_b += 1\n h += 1\n if ((check == 0) and (check_b == 0)):\n g_x.append(x[i])\n g_y.append(y[i])\n g_z.append(z[i])\n return g_x, g_y, g_z",
"def newMiniSurvey(cls, telescope, minRa, maxRa, direction):\n\n # TODO rotation isn't fully implemented yet\n rotation = next(cls.rotationGenerator.rotations(telescope))\n\n # get a tiling over the whole sphere\n tiling = Tiling.ThomsonTiling()\n allPointings = tiling.getTiling(config.tilingDensity)\n\n # now take the pointings and rotate them around the z and x\n # axes so they are randomly dithered on the sphere\n zDither = np.random.randn()\n xDither = np.random.randn()\n \n # rotating around z is easy\n allPointings[:,0] += zDither\n\n # rotating around x is harder\n sin = np.sin\n cos = np.cos\n phi = allPointings[:,0]\n theta = allPointings[:,1]\n newPhi = np.arctan2(-sin(xDither)*sin(theta) + cos(xDither)*cos(theta)*sin(phi),\n cos(theta)*cos(phi))\n newPhi %= 2 * np.pi\n newTheta = np.arcsin(cos(xDither)*sin(theta) + sin(xDither)*cos(theta)*sin(phi))\n allPointings = np.vstack([newPhi, newTheta]).T\n\n # TODO should rotate around y as well or else you get structured\n # noise in the final result\n\n # calculate min/maxDec that correspond to the passed-in direction\n # and modify min/maxRa if we're in the zenith dec band\n if direction == config.NORTH:\n minDec = telescope.latitude + config.zenithBuffer\n maxDec = config.maxDec\n # min/maxRa remain unchanged\n elif direction == config.SOUTH:\n minDec = config.minDec\n maxDec = telescope.latitude - config.zenithBuffer\n # min/maxRa remain unchanged\n elif direction == config.EAST:\n minDec = telescope.latitude - config.zenithBuffer\n maxDec = telescope.latitude + config.zenithBuffer\n minRa += config.zenithBuffer + config.zenithBufferOffset\n maxRa += config.zenithBuffer + config.zenithBufferOffset\n else:\n raise ValueError(\"Invalid direction: \" + str(direction))\n\n # choose the subset of pointings that lie in the min/maxRa/Dec rectangle\n validRa = utils.areRasInRange(allPointings[:,0], (minRa, maxRa))\n validDec = ((minDec < allPointings[:,1]) &\n (maxDec > allPointings[:,1]))\n validMask = validRa & validDec\n\n pointings = allPointings[np.where(validMask)]\n\n # create visitpairs from the calculated pointings\n visitPairs = [VisitPair(pointing[0], pointing[1], rotation)\n for pointing in pointings]\n\n return set(visitPairs)",
"def fit_galaxy(self, ypos, xpos, r_in, r_out = 0):\r\n count_out = []\r\n count_in = []\r\n for j, i in product(np.arange(ypos - (r_out + r_in), ypos + r_out + r_in + 1),np.arange(xpos - (r_out + r_in), xpos + 1 + r_out + r_in)): # Create square\r\n if (j - ypos) ** 2 + (i - xpos) ** 2 <= r_in ** 2 and 0<= j <= self.shapes[0] - 1 and 0<= i <= self.shapes[1] - 1: # make sure points are in a circle\r\n j = int(j)\r\n i = int(i)\r\n if self.raw_image_data[j,i] * self.masked[j,i] == self.raw_image_data[j,i]:\r\n count_in.append(self.raw_image_data[j,i])\r\n self.masked[j,i] = 0 # self.mask_region runs the for loop again\r\n if r_in ** 2 < (j - ypos) ** 2 + (i - xpos) ** 2 <= (r_in + r_out)**2 and 0<= j <= (self.shapes[0] - 1) and 0<= i <= self.shapes[1] - 1: # in the outer ring\r\n j = int(j)\r\n i = int(i)\r\n if self.raw_image_data[j,i] * self.masked[j,i] == self.raw_image_data[j,i]: \r\n count_out.append(self.raw_image_data[j][i]) \r\n self.masked[j,i]\r\n return count_in, count_out",
"def sph(grlat, elong, ht):\n\n # Initialize Variables\n global cth, sth, clg, slg, dif, radn, gl # common/obs/\n gn = 9.798277692\n ae = 6378140.0\n f = 0.00335281\n rm = 0.00344978\n dr = 0.01745329252\n\n clong = np.cos(elong * dr)\n slong = np.sin(elong * dr)\n # latitude difference\n dvert = f * (1.0 + 0.5 * f) * np.sin(2.0 * grlat * dr) - 0.5 * f * f * np.sin(\n 4.0 * grlat * dr\n )\n gcclat = (3.1415926535898 / 2.0) - (grlat * dr - dvert)\n cthet = np.cos(gcclat)\n sthet = np.sin(gcclat)\n # geocentric radius\n radn = 1 - f * (cthet ** 2) * (1 + 1.5 * f * (sthet ** 2))\n # formulae for g are from jeffreys, 4.022 and 4.023\n g = gn * (\n 1\n + f\n - 1.5 * rm\n + f * (f - (27 / 14) * rm)\n + (2.5 * rm - f - f * (f - (39 / 14) * rm)) * (cthet ** 2)\n - (f / 2) * (7 * f - 15.0 * rm) * ((cthet * sthet) ** 2)\n )\n # free air correction\n g = g - g * (2.0 * ht * (1.0 + f + rm - 2.0 * f * (cthet ** 2)) / ae)\n\n # Conversion Here for Globals\n cth = cthet\n sth = sthet\n clg = clong\n slg = slong\n dif = dvert\n gl = g",
"def drawSphere3D(x0,y0,z0, radius, hres, vres):\n dislin.sphe3d(x0,y0,z0, radius, hres, vres)",
"def fix_sphere_m (center_x, center_y, center_z, radius, centers, radii, len_points):\n \n g_x = []\n g_y = []\n g_z = []\n points = [hydrogen_coord_gen(center_x, center_y, center_z, radius) for i in range(0, len_points)] \n x = [points[i][0] for i in range(0, len(points))] \n y = [points[i][1] for i in range(0, len(points))]\n z = [points[i][2] for i in range(0, len(points))]\n\n for i in range(0, len(points)):\n check = 0\n j = 0\n while (j <= (len(centers) - 1) and (check == 0)): \n if (calculate_3D_distance_2_centers(x[i], y[i], z[i], centers[j][0], centers[j][1], centers[j][2]) < radii[j]):\n check += 1\n j += 1\n if (check == 0):\n g_x.append(x[i])\n g_y.append(y[i])\n g_z.append(z[i])\n\n return g_x, g_y, g_z",
"def py_SurfStatInflate(surf, w=0.5, spherefile=None):\n \n v = surf['coord'].shape[1]\n \n if v <= 81924:\n # MATLAB RAPPING FOR *obj FILE READ IN --> has to be changed...\n if spherefile is None:\n spherefile = 'sphere.obj'\n sphere_mat = eng.SurfStatReadSurf(spherefile)\n sphere = {}\n sphere['tri'] = np.array(sphere_mat['tri']) \n sphere['coord'] = np.array(sphere_mat['coord'])\n \n if v == 81924:\n sphere['tri'] = np.concatenate((sphere['tri'],\n sphere['tri']+v), axis=1)\n col1 = sphere['coord'][0,:] * (sphere['coord'][0,:] < 0)\n col2 = -1 *sphere['coord'][0,:] * (sphere['coord'][0,:] < 0)\n x = np.concatenate((col1,col2))\n x = x.reshape(1, len(x))\n row2 = row3 = sphere['coord'][1:3,:]\n y = np.concatenate((row2,row3), axis=1)\n sphere['coord'] = np.concatenate((x,y))\n else:\n if surf['coord'][0,:].mean()/abs(surf['coord'][0,:]).mean() <-0.5:\n row1 = sphere['coord'][0,:] * (sphere['coord'][0,:] < 0)\n row1 = row1.reshape(1, len(row1))\n sphere['coord'] = np.concatenate((row1,\n sphere['coord'][1:3,:]))\n else:\n row1 = -sphere['coord'][0,:] * (sphere['coord'][0,:] < 0) \n row1 = row1.reshape(1, len(row1))\n sphere['coord'] = np.concatenate((row1,\n sphere['coord'][1:3,:]))\n else:\n if spherefile is None:\n spherefile = 'lh.sphere'\n # MATLAB RAPPING FOR *sphere FILE READ IN --> has to be changed...\n sphere_mat = eng.SurfStatReadSurf(spherefile)\n sphere = {}\n sphere['tri'] = np.array(sphere_mat['tri'])\n sphere['coord'] = np.array(sphere_mat['coord'])\n \n if v == 327684:\n sphere['tri'] = np.concatenate((sphere['tri'],\n sphere['tri']+v), axis=1)\n col1 = sphere['coord'][0,:] * (sphere['coord'][0,:] < 0)\n col2 = sphere['coord'][0,:] * (sphere['coord'][0,:] > 0)\n x = np.concatenate((col1,col2))\n x = x.reshape(1, len(x))\n row2 = row3 = sphere['coord'][1:3,:]\n y = np.concatenate((row2,row3), axis=1)\n sphere['coord'] = np.concatenate((x,y))\n else:\n if surf['coord'][0,:].mean()/abs(surf['coord'][0,:]).mean() <-0.5:\n row1 = sphere['coord'][0,:] * (sphere['coord'][0,:] < 0)\n row1 = row1.reshape(1, len(row1))\n sphere['coord'] = np.concatenate((row1,\n sphere['coord'][1:3,:]))\n else:\n row1 = sphere['coord'][0,:] * (sphere['coord'][0,:] > 0)\n row1 = row1.reshape(1, len(row1))\n sphere['coord'] = np.concatenate((row1,\n sphere['coord'][1:3,:]))\n maxs = surf['coord'].max(1)\n mins = surf['coord'].min(1)\n maxsp = sphere['coord'].max(1)\n minsp = sphere['coord'].min(1)\n surfw = surf\n\n for i in range(0,3): \n surfw['coord'][i,:] = ((sphere['coord'][i,:] - minsp[i]) / \\\n (maxsp[i]-minsp[i]) * (maxs[i]-mins[i]) + mins[i]) * w + \\\n surf['coord'][i,:]*(1-w) \n\n return surfw",
"def sensitivity(gas, surf, old_data, temp, dk, thermo=False):\n rxns = []\n sens1 = []\n sens2 = []\n sens3 = []\n sens4 = []\n sens5 = []\n sens6 = []\n sens7 = []\n sens8 = []\n sens9 = []\n sens10 = []\n sens11 = []\n sens12 = []\n\n gas_out_data, gas_names_data, dist_array_data, T_array_data = old_data\n\n reference = []\n for a in range(len(gas_names_data)):\n reference.append([gas_names_data[a], [gas_out_data[:, a]]])\n\n # getting the ratio\n for x in reference:\n if x[0] == 'CH4(2)':\n ch4_in = x[1][0][0]\n if x[0] == 'O2(3)':\n o2_in = x[1][0][0]\n if x[0] == 'Ar':\n ar_in = x[1][0][0]\n ratio = ch4_in / (2 * o2_in)\n moles_in = [ch4_in, o2_in, ar_in]\n\n for x in reference:\n if x[0] == 'CH4(2)':\n ch4_in = x[1][0][0]\n ch4_out = x[1][0][-1]\n if ch4_out < 0:\n ch4_out = 0.\n ch4_depletion = ch4_in - ch4_out\n if ch4_depletion <= 1.0e-8:\n ch4_depletion = 1.0e-8\n reference_ch4_conv = 1.0e-8\n else:\n reference_ch4_conv = ch4_depletion / ch4_in # Sensitivity definition 7: CH4 conversion\n if x[0] == 'Ar':\n ar = x[1][0][-1]\n if x[0] == 'O2(3)':\n o2_out = x[1][0][-1]\n if o2_out < 0:\n o2_out = 1.0e-15 # O2 can't be negative\n elif o2_out > o2_in:\n o2_out = o2_in # O2 can't be created, to make it equal to O2 in\n if x[0] == 'CO(7)':\n co_out = x[1][0][-1]\n if x[0] == 'H2(6)':\n h2_out = x[1][0][-1]\n if x[0] == 'H2O(5)':\n h2o_out = x[1][0][-1]\n if x[0] == 'CO2(4)':\n co2_out = x[1][0][-1]\n\n if reference_ch4_conv <= 1.0e-8:\n reference_h2_sel = 1.0e-8\n reference_co_sel = 1.0e-8\n reference_syngas_selectivity = 1.0e-8\n reference_syngas_yield = 1.0e-8\n reference_co_yield = 1.0e-8\n reference_h2_yield = 1.0e-8\n reference_full_oxidation_selectivity = 1.0e-8\n reference_full_oxidation_yield = 1.0e-8\n else:\n # negative sensitivity is higher selectivity\n reference_h2_sel = h2_out / (ch4_depletion * 2) # Sensitivity definition 5: H2 selectivity\n if reference_h2_sel <= 0:\n reference_h2_sel = 1.0e-15 # selectivity can't be 0\n\n reference_co_sel = co_out / ch4_depletion # Sensitivity definition 3: CO selectivity\n if reference_co_sel <= 0:\n reference_co_sel = 1.0e-15 # selectivity can't be 0\n\n reference_syngas_selectivity = reference_co_sel + reference_h2_sel # Sensitivity definition 1: SYNGAS selectivity\n\n reference_syngas_yield = reference_syngas_selectivity * reference_ch4_conv # Sensitivity definition 2: SYNGAS yield\n if reference_syngas_yield <= 0:\n reference_syngas_yield = 1.0e-15 # yield can't be 0\n\n reference_co_yield = co_out / ch4_in # Sensitivity definition 4: CO % yield\n # reference_co_yield = reference_co_sel * reference_ch4_conv\n\n reference_h2_yield = h2_out / (2 * ch4_in) # Sensitivity definition 6: H2 % yield\n # reference_h2_yield = reference_h2_sel * reference_ch4_conv\n\n # Sensitivity definition 8: H2O + CO2 selectivity\n reference_h2o_sel = h2o_out / (ch4_depletion * 2)\n reference_co2_sel = co2_out / ch4_depletion\n if reference_h2o_sel <= 0:\n reference_h2o_sel = 1.0e-15 # H2O selectivity can't be 0\n if reference_co2_sel <= 0:\n reference_co2_sel = 1.0e-15 # CO2 selectivity can't be 0\n reference_full_oxidation_selectivity = reference_h2o_sel + reference_co2_sel\n\n # Sensitivity definition 9: H2O + CO2 yield\n reference_full_oxidation_yield = reference_full_oxidation_selectivity * reference_ch4_conv\n\n # Sensitivity definition 10: exit temperature\n reference_exit_temp = T_array_data[-1]\n\n # Sensitivity definition 11: peak temperature\n reference_peak_temp = max(T_array_data)\n\n # Sensitivity definition 12: distance to peak temperautre\n reference_peak_temp_dist = dist_array_data[T_array_data.index(max(T_array_data))]\n\n # run the simulations\n if thermo is True:\n for m in range(surf.n_species):\n s = surf.species(m)\n original_coeffs = s.thermo.coeffs\n perturbed_coeffs = np.ones_like(original_coeffs)\n perturbed_coeffs[0] = original_coeffs[0]\n perturbed_coeffs[1:6] = original_coeffs[1:6]\n perturbed_coeffs[7:13] = original_coeffs[7:13]\n perturbed_coeffs[14] = original_coeffs[14]\n # perturbed_coeffs[6] = original_coeffs[6] + original_coeffs[6]*dk\n # perturbed_coeffs[13] = original_coeffs[13] + original_coeffs[13]*dk\n perturbed_coeffs[6] = original_coeffs[6] + dk\n perturbed_coeffs[13] = original_coeffs[13] + dk\n s.thermo = ct.NasaPoly2(100.000, 5000.000, ct.one_atm, perturbed_coeffs)\n surf.modify_species(m, s)\n c = monolithFull(gas, surf, temp, moles_in)\n\n gas_out, surf_out, gas_names, surf_names, dist_array, T_array = c\n\n new_amts = []\n for a in range(len(gas_names)):\n new_amts.append([gas_names[a], [gas_out[:, a]]])\n\n for x in new_amts:\n if x[0] == 'CH4(2)':\n new_ch4_in = x[1][0][0]\n new_ch4_out = x[1][0][-1]\n if new_ch4_out < 0:\n new_ch4_out = 0.\n new_ch4_depletion = new_ch4_in - new_ch4_out\n if new_ch4_depletion <= 1e-8:\n new_ch4_depletion = 1e-8\n new_ch4_conv = 1e-8\n else:\n new_ch4_conv = new_ch4_depletion / new_ch4_in # Sensitivity definition 7: CH4 conversion\n if x[0] == 'Ar':\n ar = x[1][0][-1]\n if x[0] == 'O2(3)':\n new_o2_in = x[1][0][0]\n new_o2_out = x[1][0][-1]\n if new_o2_out < 0:\n new_o2_out = 1.0e-15\n elif new_o2_out > new_o2_in:\n new_o2_out = new_o2_in\n if x[0] == 'CO(7)':\n new_co_out = x[1][0][-1]\n if x[0] == 'H2(6)':\n new_h2_out = x[1][0][-1]\n if x[0] == 'H2O(5)':\n new_h2o_out = x[1][0][-1]\n if x[0] == 'CO2(4)':\n new_co2_out = x[1][0][-1]\n\n if new_ch4_conv <= 1e-8:\n new_h2_sel = 1.0e-8\n new_co_sel = 1.0e-8\n new_syngas_selectivity = 1.0e-8\n new_syngas_yield = 1.0e-8\n new_co_yield = 1.0e-8\n new_h2_yield = 1.0e-8\n new_full_oxidation_selectivity = 1.0e-8\n new_full_oxidation_yield = 1.0e-8\n else:\n new_h2_sel = new_h2_out / (new_ch4_depletion * 2) # Sensitivity definition 5: H2 selectivity\n new_co_sel = new_co_out / new_ch4_depletion # Sensitivity definition 3: CO selectivity\n new_syngas_selectivity = new_co_sel + new_h2_sel # Sensitivity definition 1: SYNGAS selectivity\n new_syngas_yield = new_syngas_selectivity * new_ch4_conv # Sensitivity definition 2: SYNGAS yield\n new_co_yield = new_co_out / new_ch4_in # Sensitivity definition 4: CO % yield\n new_h2_yield = new_h2_out / (2 * new_ch4_in) # Sensitivity definition 6: H2 % yield\n new_h2o_sel = new_h2o_out / (new_ch4_depletion * 2) # Sensitivity definition 8: H2O + CO2 selectivity\n new_co2_sel = new_co2_out / new_ch4_depletion\n new_full_oxidation_selectivity = new_h2o_sel + new_co2_sel\n new_full_oxidation_yield = new_full_oxidation_selectivity * new_ch4_conv # Sensitivity definition 9: C2O + CO2 yield\n\n Sens5 = (new_h2_sel - reference_h2_sel) / (reference_h2_sel * dk)\n sens5.append(Sens5)\n\n Sens3 = (new_co_sel - reference_co_sel) / (reference_co_sel * dk)\n sens3.append(Sens3)\n\n Sens1 = (new_syngas_selectivity - reference_syngas_selectivity) / (reference_syngas_selectivity * dk)\n sens1.append(Sens1)\n\n Sens2 = (new_syngas_yield - reference_syngas_yield) / (reference_syngas_yield * dk)\n sens2.append(Sens2)\n\n Sens4 = (new_co_yield - reference_co_yield) / (reference_co_yield * dk)\n sens4.append(Sens4)\n\n Sens6 = (new_h2_yield - reference_h2_yield) / (reference_h2_yield * dk)\n sens6.append(Sens6)\n\n Sens7 = (new_ch4_conv - reference_ch4_conv) / (\n reference_ch4_conv * dk)\n sens7.append(Sens7)\n\n Sens8 = (new_full_oxidation_selectivity - reference_full_oxidation_selectivity) / (\n reference_full_oxidation_selectivity * dk)\n sens8.append(Sens8)\n\n Sens9 = (new_full_oxidation_yield - reference_full_oxidation_yield) / (reference_full_oxidation_yield * dk)\n sens9.append(Sens9)\n\n new_exit_temp = T_array[-1] # Sensitivity definition 10: exit temperature\n Sens10 = (new_exit_temp - reference_exit_temp) / (reference_exit_temp * dk)\n sens10.append(Sens10)\n\n new_peak_temp = max(T_array) # Sensitivity definition 11: peak temperature\n Sens11 = (new_peak_temp - reference_peak_temp) / (reference_peak_temp * dk)\n sens11.append(Sens11)\n\n new_peak_temp_dist = dist_array[\n T_array.index(max(T_array))] # Sensitivity definition 12: dist to peak temperature\n Sens12 = (new_peak_temp_dist - reference_peak_temp_dist) / (reference_peak_temp_dist * dk)\n sens12.append(Sens12)\n\n print \"%d %s %.3F %.3F\" % (m, surf.species_name(m), Sens1, Sens2)\n rxns.append(surf.species_name(m))\n\n # this step is essential, otherwise mechanism will have been altered\n s.thermo = ct.NasaPoly2(100.000, 5000.000, ct.one_atm, original_coeffs)\n surf.modify_species(m, s)\n else:\n for rxn in range(surf.n_reactions):\n c = monolithFull(gas, surf, temp, moles_in, sens=[dk, rxn])\n gas_out, surf_out, gas_names, surf_names, dist_array, T_array = c\n\n new_amts = []\n for a in range(len(gas_names)):\n new_amts.append([gas_names[a], [gas_out[:, a]]])\n\n for x in new_amts:\n if x[0] == 'CH4(2)':\n new_ch4_in = x[1][0][0]\n new_ch4_out = x[1][0][-1]\n if new_ch4_out < 0:\n new_ch4_out = 0.\n new_ch4_depletion = new_ch4_in - new_ch4_out\n if new_ch4_depletion <= 1e-8:\n new_ch4_depletion = 1e-8\n new_ch4_conv = 1e-8\n else:\n new_ch4_conv = new_ch4_depletion / new_ch4_in # Sensitivity definition 7: CH4 conversion\n if x[0] == 'Ar':\n ar = x[1][0][-1]\n if x[0] == 'O2(3)':\n new_o2_in = x[1][0][0]\n new_o2_out = x[1][0][-1]\n if new_o2_out < 0:\n new_o2_out = 1.0e-15\n elif new_o2_out > new_o2_in:\n new_o2_out = new_o2_in\n if x[0] == 'CO(7)':\n new_co_out = x[1][0][-1]\n if x[0] == 'H2(6)':\n new_h2_out = x[1][0][-1]\n if x[0] == 'H2O(5)':\n new_h2o_out = x[1][0][-1]\n if x[0] == 'CO2(4)':\n new_co2_out = x[1][0][-1]\n\n if new_ch4_conv <= 1e-8:\n new_h2_sel = 1.0e-8\n new_co_sel = 1.0e-8\n new_syngas_selectivity = 1.0e-8\n new_syngas_yield = 1.0e-8\n new_co_yield = 1.0e-8\n new_h2_yield = 1.0e-8\n new_full_oxidation_selectivity = 1.0e-8\n new_full_oxidation_yield = 1.0e-8\n else:\n new_h2_sel = new_h2_out / (new_ch4_depletion * 2) # Sensitivity definition 5: H2 selectivity\n new_co_sel = new_co_out / new_ch4_depletion # Sensitivity definition 3: CO selectivity\n new_syngas_selectivity = new_co_sel + new_h2_sel # Sensitivity definition 1: SYNGAS selectivity\n new_syngas_yield = new_syngas_selectivity * new_ch4_conv # Sensitivity definition 2: SYNGAS yield\n new_co_yield = new_co_out / new_ch4_in # Sensitivity definition 4: CO % yield\n new_h2_yield = new_h2_out / (2 * new_ch4_in) # Sensitivity definition 6: H2 % yield\n new_h2o_sel = new_h2o_out / (new_ch4_depletion * 2) # Sensitivity definition 8: H2O + CO2 selectivity\n new_co2_sel = new_co2_out / new_ch4_depletion\n new_full_oxidation_selectivity = new_h2o_sel + new_co2_sel\n new_full_oxidation_yield = new_full_oxidation_selectivity * new_ch4_conv # Sensitivity definition 9: C2O + CO2 yield\n\n Sens5 = (new_h2_sel - reference_h2_sel) / (reference_h2_sel * dk)\n sens5.append(Sens5)\n\n Sens3 = (new_co_sel - reference_co_sel) / (reference_co_sel * dk)\n sens3.append(Sens3)\n\n Sens1 = (new_syngas_selectivity - reference_syngas_selectivity) / (reference_syngas_selectivity * dk)\n sens1.append(Sens1)\n\n Sens2 = (new_syngas_yield - reference_syngas_yield) / (reference_syngas_yield * dk)\n sens2.append(Sens2)\n\n Sens4 = (new_co_yield - reference_co_yield) / (reference_co_yield * dk)\n sens4.append(Sens4)\n\n Sens6 = (new_h2_yield - reference_h2_yield) / (reference_h2_yield * dk)\n sens6.append(Sens6)\n\n Sens7 = (new_ch4_conv - reference_ch4_conv) / (\n reference_ch4_conv * dk)\n sens7.append(Sens7)\n\n Sens8 = (new_full_oxidation_selectivity - reference_full_oxidation_selectivity) / (\n reference_full_oxidation_selectivity * dk)\n sens8.append(Sens8)\n\n Sens9 = (new_full_oxidation_yield - reference_full_oxidation_yield) / (reference_full_oxidation_yield * dk)\n sens9.append(Sens9)\n\n new_exit_temp = T_array[-1] # Sensitivity definition 10: exit temperature\n Sens10 = (new_exit_temp - reference_exit_temp) / (reference_exit_temp * dk)\n sens10.append(Sens10)\n\n new_peak_temp = max(T_array) # Sensitivity definition 11: peak temperature\n Sens11 = (new_peak_temp - reference_peak_temp) / (reference_peak_temp * dk)\n sens11.append(Sens11)\n\n new_peak_temp_dist = dist_array[T_array.index(max(T_array))] # Sensitivity definition 12: dist to peak temperature\n Sens12 = (new_peak_temp_dist - reference_peak_temp_dist) / (reference_peak_temp_dist * dk)\n sens12.append(Sens12)\n\n print \"%d %s %.3F %.3F\" % (rxn, surf.reaction_equations()[rxn], Sens1, Sens2)\n rxns.append(surf.reaction_equations()[rxn])\n\n return rxns, sens1, sens2, sens3, sens4, sens5, sens6, sens7, sens8, sens9, sens10, sens11, sens12",
"def generate_sphere_full():\n \n num_voxels = 31\n c = (15.0, 15.0, 15.0)\n\n data_x = []\n data_y = []\n data_z = []\n data_intensity = []\n\n volume = numpy.zeros((num_voxels, num_voxels, num_voxels))\n\n for x in range(num_voxels):\n for y in range(num_voxels):\n for z in range(num_voxels):\n\n if numpy.sqrt((x-c[0])**2 + (y-c[1])**2 + (z-c[2])**2) - 7.5 < 1.5:\n data_x.append(x)\n data_y.append(y)\n data_z.append(z)\n data_intensity.append(200.0)\n\n volume[x,y,z] = 200.0\n\n\n return data_x, data_y, data_z, data_intensity, volume",
"def skydip(scans):\n title = Path(scans[0]).name + \" \".join([Path(scan).name.split(\"_\")[4] for scan in scans[1:]])\n\n signal = []\n std = []\n elevation = []\n\n for scan in scans:\n kd = KissData(scan)\n kd.read_data(list_data=[\"A_masq\", \"I\", \"Q\", \"F_tone\", \"F_tl_Az\", \"F_tl_El\"])\n\n # TODO: Why do we need copy here, seems that numpy strides are making\n # funny things here !\n\n F_tone = 1e3 * kd.F_tone.copy().mean(1)[:, np.newaxis] + kd.continuum\n signal.append(F_tone.mean(1))\n std.append(F_tone.std(1))\n elevation.append(kd.F_tl_El.mean())\n\n signal = np.array(signal)\n std = np.array(std)\n elevation = np.array(elevation)\n detectors = kd.list_detector\n\n # rearrange signal to be coherent with the fit ?\n signal_new = 2 * signal[:, 0][:, np.newaxis] - signal\n\n air_mass = 1.0 / np.sin(np.radians(elevation))\n\n def T(\n airm, const, fact, tau_f\n ): # signal definition for skydip model: there is -1 before B to take into account the increasing resonance to lower optical load\n return const + 270.0 * fact * (1.0 - np.exp(-tau_f * airm))\n\n popts = []\n pcovs = []\n for _sig, _std in zip(signal_new.T, std.T):\n P0 = (4e8, 1e8, 1.0)\n popt, pcov = curve_fit(T, air_mass, _sig, sigma=_sig, p0=P0, maxfev=100000)\n\n popts.append(popt)\n pcovs.append(pcovs)\n\n popts = np.array(popts)\n\n ndet = popts.shape[0]\n fig_skydip_fit, axes = plt.subplots(\n np.int(np.sqrt(ndet)), np.int(ndet / np.sqrt(ndet)), sharex=True\n ) # , sharey=True)\n for _sig, _std, popt, detector, ax in zip(signal_new.T, std.T, popts, detectors, axes.flatten()):\n ax.errorbar(air_mass, _sig, _std)\n ax.plot(air_mass, T(air_mass, *popt))\n ax.set_title(detector, pad=-15)\n ax.label_outer()\n\n fig_skydip_fit.suptitle(title)\n fig_skydip_fit.tight_layout()\n fig_skydip_fit.subplots_adjust(wspace=0, hspace=0)\n\n Ao, Bo, tau = popts.T\n\n fig_skydip_stat, axes = plt.subplots(1, 3)\n for (item, value), ax in zip({r\"$A_0$\": Ao, r\"$B_0$\": Bo, \"tau\": tau}.items(), axes):\n mean_value = np.nanmedian(value)\n std_value = mad_std(value, ignore_nan=True)\n range_value = np.array([-3, 3]) * std_value + mean_value\n ax.hist(value, range=range_value)\n ax.set_xlabel(item)\n fig_skydip_stat.suptitle(title)\n\n return fig_skydip_fit, fig_skydip_stat",
"def fit_hypersphere(data, method=\"Hyper\"):\n num_points = len(data)\n# print >>stderr, \"DEBUG: num_points=\", num_points\n \n if num_points==0:\n return (0,None)\n if num_points==1:\n return (0,data[0])\n dimen = len(data[0]) # dimensionality of hypersphere\n# print >>stderr, \"DEBUG: dimen=\", dimen\n \n if num_points<dimen+1:\n raise ValueError(\\\n \"Error: fit_hypersphere needs at least {} points to fit {}-dimensional sphere, but only given {}\".format(dimen+1,dimen,num_points))\n \n # central dimen columns of matrix (data - centroid)\n central = np.matrix(data, dtype=float) # copy the data\n centroid = np.mean(central, axis=0)\n for row in central:\n row -= centroid\n# print >>stderr, \"DEBUG: central=\", repr(central)\n\n # squared magnitude for each centered point, as a column vector\n square_mag= [sum(a*a for a in row.flat) for row in central] \n square_mag = np.matrix(square_mag).transpose()\n# print >>stderr, \"DEBUG: square_mag=\", square_mag\n \n if method==\"Taubin\":\n # matrix of normalized squared magnitudes, data\n mean_square = square_mag.mean()\n data_Z = np.bmat( [[(square_mag-mean_square)/(2*sqrt(mean_square)), central]])\n # print >> stderr, \"DEBUG: data_Z=\",data_Z\n u,s,v = linalg.svd(data_Z, full_matrices=False)\n param_vect= v[-1,:]\n params = [ x for x in np.asarray(param_vect)[0]] # convert from (dimen+1) x 1 matrix to list\n params[0] /= 2*sqrt(mean_square)\n params.append(-mean_square*params[0])\n params=np.array(params)\n \n else:\n # matrix of squared magnitudes, data, 1s\n data_Z = np.bmat( [[square_mag, central, np.ones((num_points,1))]])\n # print >> stderr, \"DEBUG: data_Z=\",data_Z\n\n # SVD of data_Z\n # Note: numpy's linalg.svd returns data_Z = u * s * v\n # not u*s*v.H as the Release 1.4.1 documentation claims.\n # Newer documentation is correct.\n u,s,v = linalg.svd(data_Z, full_matrices=False)\n # print >>stderr, \"DEBUG: u=\",repr(u)\n # print >>stderr, \"DEBUG: s=\",repr(s)\n # print >>stderr, \"DEBUG: v=\",repr(v)\n # print >>stderr, \"DEBUG: v.I=\",repr(v.I)\n\n if s[-1]/s[0] < 1e-12:\n # singular case\n # param_vect as (dimen+2) x 1 matrix\n param_vect = v[-1,:]\n # Note: I get last ROW of v, while Chernov claims last COLUMN,\n # because of difference in definition of SVD for MATLAB and numpy\n\n # print >> stderr, \"DEBUG: singular, param_vect=\", repr(param_vect)\n # print >> stderr, \"DEBUG: data_Z*V=\", repr(data_Z*v)\n # print >> stderr, \"DEBUG: data_Z*VI=\", repr(data_Z*v.I)\n # print >> stderr, \"DEBUG: data_Z*A=\", repr(data_Z*v[:,-1])\n else: \n Y = v.H*np.diag(s)*v\n Y_inv = v.H*np.diag([1./x for x in s])*v\n # print >>stderr, \"DEBUG: Y=\",repr(Y)\n # print >>stderr, \"DEBUG: Y.I=\",repr(Y.I), \"\\nY_inv=\",repr(Y_inv)\n #Ninv is the inverse of the constraint matrix, after centroid has been removed\n Ninv = np.asmatrix(np.identity(dimen+2, dtype=float))\n if method==\"Hyper\":\n Ninv[0,0] = 0\n Ninv[0,-1]=0.5\n Ninv[-1,0]=0.5\n Ninv[-1,-1] = -2*square_mag.mean()\n elif method==\"Pratt\":\n Ninv[0,0] = 0\n Ninv[0,-1]=-0.5\n Ninv[-1,0]=-0.5\n Ninv[-1,-1]=0\n else: \n raise ValueError(\"Error: unknown method: {} should be 'Hyper', 'Pratt', or 'Taubin'\")\n # print >> stderr, \"DEBUG: Ninv=\", repr(Ninv)\n\n # get the eigenvector for the smallest positive eigenvalue\n matrix_for_eigen = Y*Ninv*Y\n # print >> stderr, \"DEBUG: {} matrix_for_eigen=\\n{}\".format(method, repr(matrix_for_eigen))\n eigen_vals,eigen_vects = linalg.eigh(matrix_for_eigen)\n # print >> stderr, \"DEBUG: eigen_vals=\", repr(eigen_vals)\n # print >> stderr, \"DEBUG: eigen_vects=\", repr(eigen_vects)\n\n positives = [x for x in eigen_vals if x>0]\n if len(positives)+1 != len(eigen_vals):\n # raise ValueError(\"Error: for method {} exactly one eigenvalue should be negative: {}\".format(method,eigen_vals))\n print>>stderr, \"Warning: for method {} exactly one eigenvalue should be negative: {}\".format(method,eigen_vals)\n smallest_positive = min(positives)\n # print >> stderr, \"DEBUG: smallest_positive=\", smallest_positive\n # chosen eigenvector as 1 x (dimen+2) matrix\n A_colvect =eigen_vects[:,list(eigen_vals).index(smallest_positive)]\n # print >> stderr, \"DEBUG: A_colvect=\", repr(A_colvect)\n # now have to multiply by Y inverse\n param_vect = (Y_inv*A_colvect).transpose()\n # print >> stderr, \"DEBUG: nonsingular, param_vect=\", repr(param_vect) \n params = np.asarray(param_vect)[0] # convert from (dimen+2) x 1 matrix to array of (dimen+2)\n\n \n# print >> stderr, \"DEBUG: params=\", repr(params)\n radius = 0.5* sqrt( sum(a*a for a in params[1:-1])- 4*params[0]*params[-1])/abs(params[0])\n center = -0.5*params[1:-1]/params[0]\n#y print >> stderr, \"DEBUG: center=\", repr(center), \"centroid=\", repr(centroid)\n center += np.asarray(centroid)[0]\n return (radius,center)",
"def get_coords(self,data,ifeed,mask):\n sky_data_flag = mask\n \n az = data['level1/spectrometer/pixel_pointing/pixel_az'][ifeed,:]\n el = data['level1/spectrometer/pixel_pointing/pixel_el'][ifeed,:]\n ra = data['level1/spectrometer/pixel_pointing/pixel_ra'][ifeed,:]\n dec = data['level1/spectrometer/pixel_pointing/pixel_dec'][ifeed,:]\n\n N = az.shape[0]//2 * 2\n daz = np.gradient(az[:])*50.\n daz = daz[sky_data_flag]\n az = az[sky_data_flag]\n el = el[sky_data_flag]\n ra = ra[sky_data_flag]\n dec=dec[sky_data_flag]\n cw = daz > 1e-2\n ccw = daz < 1e-2\n\n return {'az':az,\n 'el':el,\n 'ccw':ccw,\n 'cw':cw,\n 'ra':ra,\n 'dec':dec,\n 'sky_data_flag':sky_data_flag}",
"def wheels_radius_INV(ds):\n wr = ds[0]\n wl = ds[1]\n V = ds[2]\n Nsample = len(wr)\n H = np.zeros((Nsample,2))\n H[:,0] = wr*0.5\n H[:,1] = wl*0.5 \n X = np.dot(np.linalg.pinv(H),V) #X=rayons estimés\n Rl_est, Rr_est = X[1], X[0]\n return Rr_est, Rl_est",
"def Sphere_ExactSerendipityLagrangeQuad():\n\n mesh = Sphere_CubeToSerendipityLagrangeQuad(1)\n \n ################\n # Modifications for exact sphere\n ################\n # x=+1 side\n def posXvals(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.ones(xi1.shape);yb=np.array(-xi1);zb=np.array(xi2);\n xx=xb**2;yy=yb**2;zz=zb**2;\n x = xb*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n y = yb*np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n z = zb*np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)\n return np.vstack([x,y,z])\n def posXnormals(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.ones(xi1.shape);yb=np.array(-xi1);zb=np.array(xi2);\n xx=xb**2;yy=yb**2;zz=zb**2;\n dxdxi1 = -1.0 * xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-yb+2.0*yb*zz/3.0)\n dxdxi2 = 1.0 * xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-zb+2.0*yy*zb/3.0)\n dydxi1 = -1.0 * np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n dydxi2 = 1.0 * yb*0.5*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5 * (-zb+2.0*xx*zb/3.0)\n dzdxi1 = -1.0 * zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-yb+2.0*xx*yb/3.0)\n dzdxi2 = 1.0 * np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)\n J = np.array([[dxdxi1,dxdxi2],[dydxi1,dydxi2],[dzdxi1,dzdxi2]]).T\n J = np.cross(J[:,0,:],J[:,1,:])\n magnitude = np.sqrt(np.sum(J**2,axis=1))\n return J.T/magnitude\n def posXJ(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.ones(xi1.shape);yb=np.array(-xi1);zb=np.array(xi2);\n xx=xb**2;yy=yb**2;zz=zb**2;\n dxdxi1 = -1.0 * xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-yb+2.0*yb*zz/3.0)\n dxdxi2 = 1.0 * xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-zb+2.0*yy*zb/3.0)\n dydxi1 = -1.0 * np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n dydxi2 = 1.0 * yb*0.5*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5 * (-zb+2.0*xx*zb/3.0)\n dzdxi1 = -1.0 * zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-yb+2.0*xx*yb/3.0)\n dzdxi2 = 1.0 * np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)\n J = np.array([[dxdxi1,dxdxi2],[dydxi1,dydxi2],[dzdxi1,dzdxi2]]).T\n J = np.cross(J[:,0,:],J[:,1,:])\n return np.sqrt(np.sum(J**2,axis=1))\n mesh.eList[0].vals = posXvals\n mesh.eList[0].normals = posXnormals\n mesh.eList[0].J = posXJ\n \n def posYvals(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.array(xi1);yb=np.ones(xi1.shape);zb=np.array(xi2);\n xx=xb**2;yy=yb**2;zz=zb**2;\n x = xb*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n y = yb*np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n z = zb*np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)\n return np.vstack([x,y,z])\n def posYnormals(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.array(xi1);yb=np.ones(xi1.shape);zb=np.array(xi2);\n xx=xb**2;yy=yb**2;zz=zb**2;\n dxdxi1 = 1.0*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n dxdxi2 = 1.0*xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-zb+2.0*yy*zb/3.0)\n dydxi1 = 1.0*yb*0.5*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5 * (-xb+2.0*xb*zz/3.0)\n dydxi2 = 1.0*yb*0.5*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5 * (-zb+2.0*xx*zb/3.0)\n dzdxi1 = 1.0*zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-xb+2.0*xb*yy/3.0)\n dzdxi2 = 1.0*np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)\n J = np.array([[dxdxi1,dxdxi2],[dydxi1,dydxi2],[dzdxi1,dzdxi2]]).T\n J = np.cross(J[:,0,:],J[:,1,:])\n magnitude = np.sqrt(np.sum(J**2,axis=1))\n return J.T/magnitude\n def posYJ(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.array(xi1);yb=np.ones(xi1.shape);zb=np.array(xi2);\n xx=xb**2;yy=yb**2;zz=zb**2;\n dxdxi1 = 1.0*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n dxdxi2 = 1.0*xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-zb+2.0*yy*zb/3.0)\n dydxi1 = 1.0*yb*0.5*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5 * (-xb+2.0*xb*zz/3.0)\n dydxi2 = 1.0*yb*0.5*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5 * (-zb+2.0*xx*zb/3.0)\n dzdxi1 = 1.0*zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-xb+2.0*xb*yy/3.0)\n dzdxi2 = 1.0*np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)\n J = np.array([[dxdxi1,dxdxi2],[dydxi1,dydxi2],[dzdxi1,dzdxi2]]).T\n J = np.cross(J[:,0,:],J[:,1,:])\n return np.sqrt(np.sum(J**2,axis=1))\n mesh.eList[1].vals = posYvals\n mesh.eList[1].normals = posYnormals\n mesh.eList[1].J = posYJ\n \n # x=-1 side\n def negXvals(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=-np.ones(xi1.shape);yb=np.array(xi1);zb=np.array(xi2);\n xx=xb**2;yy=yb**2;zz=zb**2;\n x = xb*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n y = yb*np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n z = zb*np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)\n return np.vstack([x,y,z])\n def negXnormals(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=-np.ones(xi1.shape);yb=np.array(xi1);zb=np.array(xi2);\n xx=xb**2;yy=yb**2;zz=zb**2;\n dxdxi1 = 1.0*xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-yb+2.0*yb*zz/3.0)\n dxdxi2 = 1.0*xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-zb+2.0*yy*zb/3.0)\n dydxi1 = 1.0*np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n dydxi2 = 1.0*yb*0.5*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5 * (-zb+2.0*xx*zb/3.0)\n dzdxi1 = 1.0*zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-yb+2.0*xx*yb/3.0)\n dzdxi2 = 1.0*np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)\n J = np.array([[dxdxi1,dxdxi2],[dydxi1,dydxi2],[dzdxi1,dzdxi2]]).T\n J = np.cross(J[:,0,:],J[:,1,:])\n magnitude = np.sqrt(np.sum(J**2,axis=1))\n return J.T/magnitude\n def negXJ(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=-np.ones(xi1.shape);yb=np.array(xi1);zb=np.array(xi2);\n xx=xb**2;yy=yb**2;zz=zb**2;\n dxdxi1 = 1.0*xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-yb+2.0*yb*zz/3.0)\n dxdxi2 = 1.0*xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-zb+2.0*yy*zb/3.0)\n dydxi1 = 1.0*np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n dydxi2 = 1.0*yb*0.5*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5 * (-zb+2.0*xx*zb/3.0)\n dzdxi1 = 1.0*zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-yb+2.0*xx*yb/3.0)\n dzdxi2 = 1.0*np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)\n J = np.array([[dxdxi1,dxdxi2],[dydxi1,dydxi2],[dzdxi1,dzdxi2]]).T\n J = np.cross(J[:,0,:],J[:,1,:])\n return np.sqrt(np.sum(J**2,axis=1))\n mesh.eList[2].vals = negXvals\n mesh.eList[2].normals = negXnormals\n mesh.eList[2].J = negXJ\n\n # y=-1 side\n def negYvals(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.array(-xi1);yb=-np.ones(xi1.shape);zb=np.array(xi2);\n xx=xb**2;yy=yb**2;zz=zb**2;\n x = xb*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n y = yb*np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n z = zb*np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)\n return np.vstack([x,y,z])\n def negYnormals(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.array(-xi1);yb=-np.ones(xi1.shape);zb=np.array(xi2);\n xx=xb**2;yy=yb**2;zz=zb**2; \n dxdxi1 = -1.0*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n dxdxi2 = 1.0*0.5*xb*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5*(-zb+2.0*yy*zb/3.0)\n dydxi1 = -1.0*0.5*yb*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5*(-xb+2.0*xb*zz/3.0)\n dydxi2 = 1.0*0.5*yb*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5*(-zb+2.0*xx*zb/3.0)\n dzdxi1 = -1.0*0.5*zb*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5*(-xb+2.0*xb*yy/3.0)\n dzdxi2 = 1.0*np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0) \n J = np.array([[dxdxi1,dxdxi2],[dydxi1,dydxi2],[dzdxi1,dzdxi2]]).T\n J = np.cross(J[:,0,:],J[:,1,:])\n magnitude = np.sqrt(np.sum(J**2,axis=1))\n return J.T/magnitude\n def negYJ(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.array(-xi1);yb=-np.ones(xi1.shape);zb=np.array(xi2);\n xx=xb**2;yy=yb**2;zz=zb**2; \n dxdxi1 = -1.0*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n dxdxi2 = 1.0*0.5*xb*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5*(-zb+2.0*yy*zb/3.0)\n dydxi1 = -1.0*0.5*yb*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5*(-xb+2.0*xb*zz/3.0)\n dydxi2 = 1.0*0.5*yb*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5*(-zb+2.0*xx*zb/3.0)\n dzdxi1 = -1.0*0.5*zb*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5*(-xb+2.0*xb*yy/3.0)\n dzdxi2 = 1.0*np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0) \n J = np.array([[dxdxi1,dxdxi2],[dydxi1,dydxi2],[dzdxi1,dzdxi2]]).T\n J = np.cross(J[:,0,:],J[:,1,:])\n return np.sqrt(np.sum(J**2,axis=1))\n mesh.eList[3].vals = negYvals\n mesh.eList[3].normals = negYnormals\n mesh.eList[3].J = negYJ\n \n # z=+1 side\n def posZvals(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.array(xi1)\n yb=np.array(-xi2)\n zb=np.ones(xi1.shape)\n xx=xb**2;yy=yb**2;zz=zb**2;\n x = xb*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n y = yb*np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n z = zb*np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)\n return np.vstack([x,y,z])\n def posZnormals(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.array(xi1);yb=np.array(-xi2);zb=np.ones(xi1.shape);\n xx=xb**2;yy=yb**2;zz=zb**2;\n dxdxi1 = 1.0*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n dxdxi2 = -1.0*xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-yb+2.0*yb*zz/3.0)\n dydxi1 = 1.0*yb*0.5*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5 * (-xb+2.0*xb*zz/3.0)\n dydxi2 = -1.0*np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n dzdxi1 = 1.0*zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-xb+2.0*xb*yy/3.0)\n dzdxi2 = -1.0*zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-yb+2.0*xx*yb/3.0)\n J = np.array([[dxdxi1,dxdxi2],[dydxi1,dydxi2],[dzdxi1,dzdxi2]]).T\n J = np.cross(J[:,0,:],J[:,1,:])\n magnitude = np.sqrt(np.sum(J**2,axis=1))\n return J.T/magnitude\n def posZJ(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.array(xi1);yb=np.array(-xi2);zb=np.ones(xi1.shape);\n xx=xb**2;yy=yb**2;zz=zb**2;\n dxdxi1 = 1.0*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n dxdxi2 = -1.0*xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-yb+2.0*yb*zz/3.0)\n dydxi1 = 1.0*yb*0.5*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5 * (-xb+2.0*xb*zz/3.0)\n dydxi2 = -1.0*np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n dzdxi1 = 1.0*zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-xb+2.0*xb*yy/3.0)\n dzdxi2 = -1.0*zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-yb+2.0*xx*yb/3.0)\n J = np.array([[dxdxi1,dxdxi2],[dydxi1,dydxi2],[dzdxi1,dzdxi2]]).T\n J = np.cross(J[:,0,:],J[:,1,:])\n return np.sqrt(np.sum(J**2,axis=1))\n mesh.eList[4].vals = posZvals\n mesh.eList[4].normals = posZnormals\n mesh.eList[4].J = posZJ\n \n # z=-1 side\n def negZvals(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.array(xi1);yb=np.array(xi2);zb=-np.ones(xi1.shape);\n xx=xb**2;yy=yb**2;zz=zb**2;\n x = xb*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n y = yb*np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n z = zb*np.sqrt(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)\n return np.vstack([x,y,z])\n def negZnormals(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.array(xi1);yb=np.array(xi2);zb=-np.ones(xi1.shape);\n xx=xb**2;yy=yb**2;zz=zb**2;\n dxdxi1 = 1.0*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n dxdxi2 = 1.0*xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-yb+2.0*yb*zz/3.0)\n dydxi1 = 1.0*yb*0.5*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5 * (-xb+2.0*xb*zz/3.0)\n dydxi2 = 1.0*np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n dzdxi1 = 1.0*zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-xb+2.0*xb*yy/3.0)\n dzdxi2 = 1.0*zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-yb+2.0*xx*yb/3.0)\n J = np.array([[dxdxi1,dxdxi2],[dydxi1,dydxi2],[dzdxi1,dzdxi2]]).T\n J = np.cross(J[:,0,:],J[:,1,:])\n magnitude = np.sqrt(np.sum(J**2,axis=1))\n return J.T/magnitude\n def negZJ(xi1,xi2):\n xi1=np.asarray(xi1,np.float).reshape(-1,)\n xi2=np.asarray(xi2,np.float).reshape(-1,)\n xb=np.array(xi1);yb=np.array(xi2);zb=-np.ones(xi1.shape);\n xx=xb**2;yy=yb**2;zz=zb**2;\n dxdxi1 = 1.0*np.sqrt(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)\n dxdxi2 = 1.0*xb*0.5*(1.0 - yy/2.0 - zz/2.0 + yy*zz/3.0)**-0.5 * (-yb+2.0*yb*zz/3.0)\n dydxi1 = 1.0*yb*0.5*(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)**-0.5 * (-xb+2.0*xb*zz/3.0)\n dydxi2 = 1.0*np.sqrt(1.0 - xx/2.0 - zz/2.0 + xx*zz/3.0)\n dzdxi1 = 1.0*zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-xb+2.0*xb*yy/3.0)\n dzdxi2 = 1.0*zb*0.5*(1.0 - xx/2.0 - yy/2.0 + xx*yy/3.0)**-0.5 * (-yb+2.0*xx*yb/3.0)\n J = np.array([[dxdxi1,dxdxi2],[dydxi1,dydxi2],[dzdxi1,dzdxi2]]).T\n J = np.cross(J[:,0,:],J[:,1,:])\n return np.sqrt(np.sum(J**2,axis=1))\n mesh.eList[5].vals = negZvals\n mesh.eList[5].normals = negZnormals\n mesh.eList[5].J = negZJ\n \n for e in mesh.eList:\n e.ExactElement = True\n \n return mesh",
"def legacyhalos_ellipse(galaxy, galaxydir, data, galaxyinfo=None,\n pixscale=0.262, nproc=1, refband='r',\n bands=['g', 'r', 'z'], integrmode='median',\n nclip=3, sclip=3, sbthresh=REF_SBTHRESH,\n apertures=REF_APERTURES,\n delta_sma=1.0, delta_logsma=5, maxsma=None, logsma=True,\n copy_mw_transmission=False, \n input_ellipse=None, fitgeometry=False,\n verbose=False, debug=False, nowrite=False, clobber=False):\n from legacyhalos.io import get_ellipsefit_filename\n \n if bool(data):\n if data['missingdata']:\n if os.path.isfile(os.path.join(galaxydir, '{}-{}-coadds.isdone'.format(galaxy, data['filesuffix']))):\n return 1\n else:\n return 0\n\n if data['failed']: # all galaxies dropped\n return 1\n\n if 'galaxy_id' in data.keys():\n galaxy_id = np.atleast_1d(data['galaxy_id'])\n else:\n galaxy_id = ['']\n \n for igal, galid in enumerate(galaxy_id):\n ellipsefitfile = get_ellipsefit_filename(galaxy, galaxydir, galaxy_id=str(galid),\n filesuffix=data['filesuffix'])\n if os.path.isfile(ellipsefitfile) and not clobber:\n print('Skipping existing catalog {}'.format(ellipsefitfile))\n else:\n ellipsefit = ellipsefit_multiband(galaxy, galaxydir, data,\n galaxyinfo=galaxyinfo,\n igal=igal, galaxy_id=str(galid),\n delta_logsma=delta_logsma, maxsma=maxsma,\n delta_sma=delta_sma, logsma=logsma,\n refband=refband, nproc=nproc, sbthresh=sbthresh,\n apertures=apertures,\n integrmode=integrmode, nclip=nclip, sclip=sclip,\n input_ellipse=input_ellipse,\n copy_mw_transmission=copy_mw_transmission,\n verbose=verbose, fitgeometry=False,\n nowrite=False)\n return 1\n else:\n # An object can get here if it's a \"known\" failure, e.g., if the object\n # falls off the edge of the footprint (and therefore it will never have\n # coadds).\n if os.path.isfile(os.path.join(galaxydir, '{}-{}-coadds.isdone'.format(galaxy, 'custom'))):\n return 1\n else:\n return 0",
"def __init__(self, a, f):\n\n self.a = float(a)\n \"\"\"The equatorial radius in meters (readonly)\"\"\"\n self.f = float(f)\n \"\"\"The flattening (readonly)\"\"\"\n self._f1 = 1 - self.f\n self._e2 = self.f * (2 - self.f)\n self._ep2 = self._e2 / Math.sq(self._f1) # e2 / (1 - e2)\n self._n = self.f / ( 2 - self.f)\n self._b = self.a * self._f1\n # authalic radius squared\n self._c2 = (Math.sq(self.a) + Math.sq(self._b) *\n (1 if self._e2 == 0 else\n (Math.atanh(math.sqrt(self._e2)) if self._e2 > 0 else\n math.atan(math.sqrt(-self._e2))) /\n math.sqrt(abs(self._e2))))/2\n # The sig12 threshold for \"really short\". Using the auxiliary sphere\n # solution with dnm computed at (bet1 + bet2) / 2, the relative error in\n # the azimuth consistency check is sig12^2 * abs(f) * min(1, 1-f/2) / 2.\n # (Error measured for 1/100 < b/a < 100 and abs(f) >= 1/1000. For a given\n # f and sig12, the max error occurs for lines near the pole. If the old\n # rule for computing dnm = (dn1 + dn2)/2 is used, then the error increases\n # by a factor of 2.) Setting this equal to epsilon gives sig12 = etol2.\n # Here 0.1 is a safety factor (error decreased by 100) and max(0.001,\n # abs(f)) stops etol2 getting too large in the nearly spherical case.\n self._etol2 = 0.1 * Geodesic.tol2_ / math.sqrt( max(0.001, abs(self.f)) *\n min(1.0, 1-self.f/2) / 2 )\n if not(Math.isfinite(self.a) and self.a > 0):\n raise ValueError(\"Equatorial radius is not positive\")\n if not(Math.isfinite(self._b) and self._b > 0):\n raise ValueError(\"Polar semi-axis is not positive\")\n self._A3x = list(range(Geodesic.nA3x_))\n self._C3x = list(range(Geodesic.nC3x_))\n self._C4x = list(range(Geodesic.nC4x_))\n self._A3coeff()\n self._C3coeff()\n self._C4coeff()",
"def SED(**kwargs):\n\n p = copy.copy(params)\n for key,val in kwargs.items():\n setattr(p,key,val)\n\n GR = glo.global_results()\n gal_num = getattr(GR,'gal_num')[p.gal_index]\n\n # Look for powderday SED\n found = True\n\n # Load MIRI filter curves\n MIRI = pd.read_csv('look-up-tables/observations/ImPCE_TN-00072-ATC-Iss2.txt',sep='\\t',skiprows=2,\\\n names=['Wave','F560W','F770W','F1000W','F1280W','F1130W','F1500W','F1800W','F2100W','F2550W'])\n\n # gal_num=12\n # file_location = p.d_data + 'pd_data/%s/sed_%i' % (p.sim_run,gal_num)\n # pd_data = pickle.load(open(file_location,'rb'), encoding='latin1')\n # wav = np.array(pd_data[0,:])[0]\n # flux = np.array(pd_data[1,:])[0]\n try:\n file_location = p.d_data + 'pd_data/%s/sed_%i' % (p.sim_run,gal_num)\n pd_data = pickle.load(open(file_location,'rb'), encoding='latin1')\n wav = np.array(pd_data[0,:])[0]\n flux = np.array(pd_data[1,:])[0]\n print('Found powderday output found for gal_index = %i (gal_num = %i)!' % (p.gal_index,gal_num))\n except:\n print('No powderday output found for gal_index = %i (gal_num = %i)!' % (p.gal_index,gal_num))\n found = False\n\n if p.select == 'AGN': \n try:\n file_location = p.d_data + 'pd_data/%s/sed_%i_agn' % (p.sim_run,gal_num)\n pd_data = pickle.load(open(file_location,'rb'), encoding='latin1')\n wav_agn = np.array(pd_data[0,:])[0]\n flux_agn = np.array(pd_data[1,:])[0]\n except:\n if found: print('no AGN spectra for gal_num %i' % gal_num)\n\n if found == True:\n wav_lines = []\n tot_flux = [] \n if p.select == 'AGN': tot_flux_agn = [] \n for line in p.lines:\n\n L_line = getattr(GR,'L_%s_sun' % line)[p.gal_index]\n D_L = getattr(GR,'lum_dist')[p.gal_index]\n\n L_line_Jy_km_s = aux.Lsun_to_Jy_km_s(L_line,D_L,line)\n\n freq = p.freq[line]\n\n wav_line = c.c.value / (freq*1e9) * 1e6 # microns\n\n if wav_line < np.max(wav):\n flux[np.argmin(np.abs(wav-wav_line))] += L_line_Jy_km_s\n\n if p.select == 'AGN': \n try: \n flux_agn[np.argmin(np.abs(wav-wav_line))] += L_line_Jy_km_s\n except:\n pass\n\n wav_lines += [wav_line]\n tot_flux += [flux[np.argmin(np.abs(wav-wav_line))]]\n\n if p.select == 'AGN': \n try: \n tot_flux_agn += [flux_agn[np.argmin(np.abs(wav-wav_line))]]\n except:\n pass\n\n fig,ax = plt.subplots(figsize=(12,6))\n # Show MIRI band\n ax.fill_between([5,28],[1e10,1e10],color='forestgreen',alpha=0.4)\n ax.loglog(wav,flux,'-',lw=2,label='Modeled spectrum\\nof $z=0$ simulated galaxy')\n try: \n ax.loglog(wav,flux_agn,'-',color='r',lw=2,label='with AGN')\n except:\n pass\n ax.set_xlabel(r'$\\lambda$ [$\\mu$m]')\n ax.set_ylabel('Flux (mJy)')\n ax.set_ylim([np.max(flux)*5/1e5,np.max(flux)*5.5])\n ax.set_xlim(1,10**3.1)\n\n cmap = plt.get_cmap('gist_rainbow_r')\n cmap = plt.get_cmap('brg')\n tot_flux = np.array(tot_flux)[wav_lines < np.max(wav)]\n line_names = np.array(p.lines)[wav_lines < np.max(wav)]\n wav_lines = np.array(wav_lines)[wav_lines < np.max(wav)]\n tot_flux = tot_flux[wav_lines.argsort()]\n line_names = line_names[wav_lines.argsort()]\n wav_lines = wav_lines[wav_lines.argsort()]\n colors = [cmap(i) for i in np.linspace(0, 1, len(wav_lines))]\n for i in range(len(wav_lines)):\n print(line_names[i],wav_lines[i])\n ax.plot(wav_lines[i],tot_flux[i],'x',mew=2,ms=5,color=colors[i])#,label=line_names[i])\n # ax.text(wav_lines[i]*0.8,tot_flux[i],line_names[i],fontsize=10,color=colors[i])\n if line_names[i] in ['H2_S(1)','[NeII]12','[FeII]25','[OI]63','[CII]158','[CI]370','[CI]610','CO(3-2)']:\n ax.text(wav_lines[i]*0.8,tot_flux[i]*3.5,line_names[i],fontsize=10,color=colors[i])\n ax.plot([wav_lines[i],wav_lines[i]],[tot_flux[i],tot_flux[i]*3],'--',lw=1,color=colors[i])\n if line_names[i] in ['H2_S(6)','H2_S(4)','H2_S(6)','[NII]122','[NII]205','[SIII]18']:\n ax.text(wav_lines[i]*0.8,tot_flux[i]*6.5,line_names[i],fontsize=10,color=colors[i])\n ax.plot([wav_lines[i],wav_lines[i]],[tot_flux[i],tot_flux[i]*6],'--',lw=1,color=colors[i])\n if line_names[i] in ['[OIV]25','[OIII]88']:\n ax.text(wav_lines[i]*0.8,tot_flux[i]/4.,line_names[i],fontsize=10,color=colors[i])\n ax.plot([wav_lines[i],wav_lines[i]],[tot_flux[i],tot_flux[i]/3],'--',lw=1,color=colors[i])\n if line_names[i] in ['[NeIII]15']:\n ax.text(wav_lines[i]*0.8,tot_flux[i]/6.5,line_names[i],fontsize=10,color=colors[i])\n ax.plot([wav_lines[i],wav_lines[i]],[tot_flux[i],tot_flux[i]/5],'--',lw=1,color=colors[i])\n if line_names[i] in ['[OI]145','H2_S(5)','H2_S(3)','H2_S(2)','H2_S(7)']:\n ax.text(wav_lines[i]*0.8,tot_flux[i]/9.,line_names[i],fontsize=10,color=colors[i])\n ax.plot([wav_lines[i],wav_lines[i]],[tot_flux[i],tot_flux[i]/7],'--',lw=1,color=colors[i])\n\n ax.legend(fontsize=13,fancybox=True, framealpha=0.5)\n\n print(MIRI.head())\n for f in MIRI.keys():\n if f != 'Wave':\n ax.fill_between(MIRI['Wave'].values,MIRI[f].values*1e5,alpha=0.6)\n ax.text(30,1e4,'JWST/MIRI filter curves',fontsize=15,color='steelblue')\n\n if p.savefig:\n if not os.path.isdir(p.d_plot + 'SEDs/'): os.mkdir(p.d_plot + 'SEDs/') \n plt.savefig(p.d_plot + 'SEDs/sed_%s%s_%i.png' % (p.sim_name,p.sim_run,p.gal_index), format='png', dpi=300) \n\n # plt.close('all')",
"def test_isentropic_pressure_4d():\n lev = [100000., 95000., 90000., 85000.] * units.Pa\n tmp = np.ones((3, 4, 5, 5))\n tmp[:, 0, :] = 296.\n tmp[:, 1, :] = 292.\n tmp[:, 2, :] = 290\n tmp[:, 3, :] = 288.\n tmpk = tmp * units.kelvin\n rh = np.ones((3, 4, 5, 5))\n rh[:, 0, :] = 100.\n rh[:, 1, :] = 80.\n rh[:, 2, :] = 40.\n rh[:, 3, :] = 20.\n relh = rh * units.percent\n isentlev = [296., 297., 300.] * units.kelvin\n isentprs = isentropic_interpolation(isentlev, lev, tmpk, relh, vertical_dim=1)\n trueprs = 1000. * units.hPa\n trueprs2 = 936.213 * units.hPa\n trueprs3 = 879.50375588 * units.hPa\n truerh = 69.19706 * units.percent\n assert isentprs[0].shape == (3, 3, 5, 5)\n assert_almost_equal(isentprs[0][:, 0, :], trueprs, 3)\n assert_almost_equal(isentprs[0][:, 1, :], trueprs2, 3)\n assert_almost_equal(isentprs[0][:, 2, :], trueprs3, 3)\n assert_almost_equal(isentprs[1][:, 1, ], truerh, 3)",
"def test_SMEL_args():\n testing_function('sme', bilinear=False)",
"def sph(vs, ucs, A, C, x, y, z, rotx=0, roty=0, rotz=0, mode=\"C\"):\n sph = []\n\n if mode == \"A\":\n nA = (A-0.07)/(0.12-0.07)\n nC = (C+0.1)/(0.31+0.1)\n elif mode == \"C\":\n nA = (A-0.07)/(0.12-0.07)\n nC = C/0.307\n elif mode == \"AC\":\n nA = (A-0.07)/(0.12-0.07)\n nC = (C+0.1)/(0.31+0.1)\n else:\n nA = (A-0.07)/(0.12-0.07)\n nC = C/0.307\n\n if (type(nA) is np.float64):\n nA = np.full(len(vs), nA)\n if (type(nC) is np.float64):\n nC = np.full(len(vs), nC)\n\n for v, uc, a, c in zip(vs, ucs, nA, nC):\n if mode == \"A\":\n H0 = a\n L0 = 1/(1+np.exp((-2.8*((a-0.52)*2.4))))\n # R0, G0, B0 = colorsys.hls_to_rgb(0.02+H0*0.35, 0.5-L0*0.4, 1.0)\n R0, G0, B0 = colorsys.hls_to_rgb(1.0-H0*0.40, 0.5-L0*0.4, 1.0)\n\n elif mode == \"C\":\n H0 = c\n L0 = 1/(1+np.exp((-2.8*((c-0.52)*2.4))))\n R0, G0, B0 = colorsys.hls_to_rgb(0.02+H0*0.35, 0.5-L0*0.4, 1.0)\n\n elif mode == \"AC\":\n R0 = a*1.0\n # G0 = max(0.8-(max(a+c, 0)), 0)\n G0 = 0.0\n B0 = c*1.0\n\n else:\n R0 = 0.3\n G0 = 0.2\n B0 = 0.2\n\n R1 = 1.0 - R0\n G1 = 1.0 - G0\n B1 = 1.0 - B0\n\n sph.append(Sphere(v, 0.022,\n Texture(Pigment('color',\n [R0+uc*R1, G0+uc*G1, B0+uc*B1]),\n Finish('phong', 0.7,\n 'specular', 0.2,\n 'diffuse', 0.9,\n 'ambient', 0.1)),\n 'rotate', [rotx, 0, 0],\n 'rotate', [0, roty, 0],\n 'rotate', [0, 0, rotz],\n 'translate', [x, y, z],\n 'no_shadow'))\n\n return sph",
"def test_density_2d(self):\n # almost spherical case\n x = 1.\n y = 1.\n e1, e2 = 5e-5, 0.\n sigma = 1.\n amp = 2.\n f_ = self.gaussian_kappa_ellipse.density_2d(x, y, amp, sigma, e1, e2)\n f_sphere = amp / (2.*np.pi*sigma**2) * np.exp(-(x*x+y*y)/2./sigma**2)\n npt.assert_almost_equal(f_, f_sphere, decimal=4)",
"def delaz(eqlat, eqlon, stlat, stlon, flag):\n\n if flag==0: # convert geographic degrees to geocentric radians\n eqlat, eqlon = coortr(eqlat,eqlon,flag)\n stlat, stlon = coortr(stlat,stlon,flag) \n\n eqcolat = m.pi/2-eqlat\n stcolat = m.pi/2-stlat\n\n cos_eq = m.cos(eqcolat)\n sin_eq = m.sin(eqcolat)\n cos_st = m.cos(stcolat)\n sin_st = m.sin(stcolat)\n cos_eqst = m.cos(stlon-eqlon)\n sin_eqst = m.sin(stlon-eqlon)\n\n cos_delta = cos_eq * cos_st + sin_eq * sin_st * cos_eqst\n sin_delta = m.sqrt(1-cos_delta * cos_delta)\n delta = m.atan2(sin_delta,cos_delta)\n # if sin(delta)=0, set sin(delta)=eps=10**-16\n eps = 3.e-7\n sin_delta = sin_delta + (sin_delta==0)*eps\n\n # index is zero if expression is false, 1 if true; \n # if false, leave unchanged, if true azeqst=pi-azeqst\n # this puts azeqst into the correct quadrant\n azeqst = m.asin(sin_st*sin_eqst/sin_delta)\n index = (sin_eq*cos_st - cos_eq*sin_st*cos_eqst < 0)\n azeqst = azeqst + index*(m.pi-2*azeqst)\n azeqst = azeqst + (azeqst<0)*2*m.pi\n\n azsteq = m.asin(-sin_eq*sin_eqst/sin_delta)\n index = (cos_eq*sin_st - sin_eq*cos_st*cos_eqst < 0)\n azsteq = azsteq + index*(m.pi-2*azsteq)\n azsteq = azsteq + (azsteq<0)*2*m.pi\n\n # convert to degrees\n delta = delta*180/m.pi\n azeqst = azeqst*180/m.pi\n azsteq = azsteq*180/m.pi\n\n return delta, azeqst, azsteq",
"def _adj(self, sino):\n # image coordinate grid\n p_x = torch.linspace(\n -self.n[0] / 2.0 + 0.5,\n self.n[0] / 2.0 - 0.5,\n self.n[0],\n device=self.n.device,\n ).unsqueeze(1)\n p_y = torch.linspace(\n -self.n[1] / 2.0 + 0.5,\n self.n[1] / 2.0 - 0.5,\n self.n[1],\n device=self.n.device,\n ).unsqueeze(0)\n\n # check if coordinate is within circle\n if self.flat:\n max_gamma = torch.atan(\n (self.s_detect.abs() * (self.n_detect / 2.0))\n / (self.d_source + self._d_detect())\n )\n else:\n max_gamma = (self.s_detect.abs() * (self.n_detect / 2.0)) / (\n self.d_source + self._d_detect()\n )\n radius = self.d_source * torch.sin(max_gamma)\n p_r = torch.sqrt(p_x * p_x + p_y * p_y)\n mask = p_r <= radius\n\n # use batch and channel dimensions for vectorized interpolation\n original_dim = sino.ndim\n while sino.ndim < 4:\n sino = sino.unsqueeze(0)\n assert sino.shape[-3] == 1 # we can handle only single channel data\n sino = sino.transpose(-4, -3) # switch batch and channel dim\n\n # rotated coordinate grid\n pi = torch.acos(torch.zeros(1)).item() * 2.0\n cs = torch.cos(self.angles * pi / 180.0).unsqueeze(1).unsqueeze(1)\n sn = torch.sin(self.angles * pi / 180.0).unsqueeze(1).unsqueeze(1)\n p_x_r = cs * p_x + sn * p_y\n p_y_r = -sn * p_x + cs * p_y\n\n # find angles and detector positions defining rays through coordinate\n if self.flat:\n grid_d = (\n (self.d_source + self._d_detect())\n * p_x_r\n / (self.d_source - p_y_r)\n )\n else:\n grid_d = (self.d_source + self._d_detect()) * torch.atan(\n p_x_r / (self.d_source - p_y_r)\n )\n grid_a = (\n torch.arange(self.m[0], device=sino.device)\n .unsqueeze(1)\n .unsqueeze(1)\n .expand(-1, self.n[0], self.n[1])\n - self.m[0] / 2.0\n + 0.5\n )\n\n grid_d = grid_d / (\n (self.n_detect / 2.0 - 0.5) * self.s_detect\n ) # rescale valid detector positions to [-1,1]\n grid_a = grid_a / (self.m[0] / 2.0 - 0.5) # rescale angles to [-1,1]\n grid = torch.stack([grid_d, grid_a], dim=-1)\n inter = torch.nn.functional.grid_sample(\n sino.expand(self.m[0], -1, -1, -1), grid, align_corners=True\n )\n\n # compute integral reweighting factors and integrate\n if self.flat:\n weight = (self.d_source + self._d_detect()).pow(2) / (\n self.d_source - p_y_r\n ).pow(2)\n else:\n weight = (self.d_source + self._d_detect()).pow(2) / (\n (self.d_source - p_y_r).pow(2) + p_x_r.pow(2)\n )\n x = mask * (inter * (weight).unsqueeze(1)).sum(dim=0, keepdim=True)\n\n # undo batch and channel manipulations\n x = x.transpose(-4, -3) # unswitch batch and channel dim\n while x.ndim > original_dim:\n x = x.squeeze(0)\n\n return x / self.s_detect.abs()",
"def get_m1_m4_SEN_info(tx, ty, m1_info, y_k):\n \"\"\"\n 1 Get information from m1_info\n \"\"\"\n x_m1 = m1_info[0]\n y_m1 = m1_info[1]\n z_m = m1_info[2]\n t_m = z_m / 3\n\n t_sen = m1_info[4]\n\n m1_points = m1_info[3]\n\n m1_p0 = m1_points[0]\n m1_p1 = m1_points[1]\n m1_p2 = m1_points[2]\n m1_p3 = m1_points[3]\n\n b_p = (tx, ty)\n\n u_distance = rs.Distance(m1_p3, b_p) - y_k / 2\n l_distance = rs.Distance(m1_p0, b_p) - y_k / 2\n\n \"\"\"\n 2 Get SEN information\n \"\"\"\n # Automatically fixed---------------------------------------------------\n # t_sen = rs.GetReal(\"Put Int(mm): Thickness of material to cut SEN.\", t_m / 2, None, None)\n w_sen = t_sen\n n_w_sen = w_sen / 2\n h_sen = z_m\n\n u_max_n = u_distance / (2 * w_sen - n_w_sen) # NOTE: divide max_n by 2 to controll \"n\"\n u_max_n = int(u_max_n)\n\n u_n = u_max_n / 4\n u_n = int(u_n)\n\n l_max_n = l_distance / (2 * w_sen - n_w_sen) # NOTE: divide max_n by 2 to controll \"n\"\n l_max_n = int(l_max_n)\n\n l_n = l_max_n / 4\n l_n = int(l_n)\n\n\n set = 20\n u_offset = (u_distance - 2 * set) / (u_n - 1)\n l_offset = (l_distance - 2 * set) / (l_n - 1)\n\n SEN_info = [w_sen, n_w_sen, h_sen, t_sen, u_n, l_n, set, u_offset, l_offset]\n\n return SEN_info"
] | [
"0.5458695",
"0.54385436",
"0.54376864",
"0.54037213",
"0.5400784",
"0.53430015",
"0.5339209",
"0.5277438",
"0.52107674",
"0.51346415",
"0.5127246",
"0.5106323",
"0.50951827",
"0.50790733",
"0.50697833",
"0.5069102",
"0.5069075",
"0.5034315",
"0.50341034",
"0.5032487",
"0.5029466",
"0.50291604",
"0.50198257",
"0.5019039",
"0.50098044",
"0.5008056",
"0.4992728",
"0.49754417",
"0.49716675",
"0.49690187"
] | 0.59291625 | 0 |
a sample chain of corrections | def chain_corrections():
#read the files
sample_4m=read_sample(map_files('sample_4m'))
empty_cell_4m=read_sample(map_files('empty_cell_4m'))
empty_4m=read_sample(map_files('empty_4m'))
transmission_sample_cell_4m=read_sample(map_files('trans_sample_4m'))
transmission_empty_cell_4m=read_sample(map_files('trans_empty_cell_4m'))
blocked_beam_4m=read_sample(map_files('blocked_4m'))
sensitivity=read_div(map_files('div'))
#mask=read_sample(map_files('mask'))
#normalize the monitors
sample_4m_norm=monitor_normalize(sample_4m)
empty_cell_4m_norm=monitor_normalize(empty_cell_4m)
transmission_sample_cell_4m_norm=monitor_normalize(transmission_sample_cell_4m)
transmission_empty_cell_4m_norm=monitor_normalize(transmission_empty_cell_4m)
empty_4m_norm=monitor_normalize(empty_4m)
blocked_beam_4m_norm=monitor_normalize(blocked_beam_4m)
#calculate q
sample_4m_norm_q=convert_q(sample_4m_norm)
empty_cell_4m_norm_q=convert_q(empty_cell_4m)
blocked_beam_4m_norm_q=convert_q(blocked_beam_4m_norm)
transmission_sample_cell_4m_norm_q=convert_q(transmission_sample_cell_4m_norm)
transmission_empty_cell_4m_norm_q=convert_q(transmission_empty_cell_4m_norm)
empty_4m_norm_q=convert_q(empty_4m_norm)
print 'converted'
#convert flatness
sample_4m_solid=correct_solid_angle(sample_4m_norm_q)
empty_cell_4m_solid=correct_solid_angle(empty_cell_4m_norm_q)
blocked_beam_4m_solid=correct_solid_angle(blocked_beam_4m_norm_q)
transmission_sample_cell_4m_solid=correct_solid_angle(transmission_sample_cell_4m_norm_q)
transmission_empty_cell_4m_solid=correct_solid_angle(transmission_empty_cell_4m_norm_q)
empty_4m_solid=correct_solid_angle(empty_4m_norm_q)
#calculate transmission
coord_left=(60,60)
coord_right=(70,70)
transmission_sample_cell_4m_rat=generate_transmission(transmission_sample_cell_4m_solid,empty_4m_solid,
coord_left,coord_right)
transmission_empty_cell_4m_rat=generate_transmission(transmission_empty_cell_4m_solid,empty_4m_solid,
coord_left,coord_right)
print 'Sample transmission= {} (IGOR Value = 0.724)'.format(transmission_sample_cell_4m_rat)
print 'Empty Cell transmission= {} (IGOR Value = 0.929)'.format(transmission_empty_cell_4m_rat)
print 'hi'
#Initial Correction -- Not with the sub/mult tools,
#SAM = sample_4m_solid.data
#print SAM.x
#EMP = empty_4m_solid.data
#print "EMP: "
#print EMP.x
#BGD = blocked_beam_4m_solid.data
#print "BGD"
#print BGD.x
#Tsam = transmission_sample_cell_4m_rat
#Temp = transmission_empty_cell_4m_rat
#COR1 = SAM.__sub__(BGD)
#COR2 = (EMP.__sub__(BGD)).__mul__(Tsam/Temp)
#COR = COR1.__sub__(COR2)
#print "after initial correction: "
#print COR.x
SAM = sample_4m_solid
print SAM.data.x
EMP = empty_4m_solid
print "EMP: "
print EMP.data.x
BGD = blocked_beam_4m_solid
print "BGD:"
print BGD.data.x
Tsam = transmission_sample_cell_4m_rat
Temp = transmission_empty_cell_4m_rat
print "COR1:"
COR1 = SAM.__sub1__(BGD)
print COR1.data.x #check=works
#-----Problems Here-------
print "COR2:"
COR2 = (EMP.__sub1__(BGD)) #check=works
print COR2.data.x
print "COR3:"
#AJJ - __mul__ not working because Tsam and Temp are Measurement instances and not simply floats. See above.
COR3 = COR2.__mul__(Tsam/Temp) #mul not working
print COR3.data.x
#COR = COR1.__sub1__(COR2)
#print "after initial correction: "
#print COR.x
#COR2 = (EMP.__sub__(BGD)).__mul__(Tsam/Temp)
#COR = COR1.__sub__(COR2)
#print "after initial correction: "
#print COR.data.x | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def multiple_testing_correction(pvalues, correction_type=\"FDR\"):\n from numpy import array, empty\n pvalues = array(pvalues)\n sample_size = pvalues.shape[0]\n qvalues = empty(sample_size)\n if correction_type == \"Bonferroni\":\n # Bonferroni correction\n qvalues = sample_size * pvalues\n elif correction_type == \"Bonferroni-Holm\":\n # Bonferroni-Holm correction\n values = [(pvalue, i) for i, pvalue in enumerate(pvalues)]\n values.sort()\n for rank, vals in enumerate(values):\n pvalue, i = vals\n qvalues[i] = (sample_size-rank) * pvalue\n elif correction_type == \"FDR\":\n # Benjamini-Hochberg, AKA - FDR test\n values = [(pvalue, i) for i, pvalue in enumerate(pvalues)]\n values.sort()\n values.reverse()\n new_values = []\n for i, vals in enumerate(values):\n rank = sample_size - i\n pvalue, index = vals\n new_values.append((sample_size/rank) * pvalue)\n for i in range(0, int(sample_size)-1):\n if new_values[i] < new_values[i+1]:\n new_values[i+1] = new_values[i]\n for i, vals in enumerate(values):\n pvalue, index = vals\n qvalues[index] = new_values[i]\n return qvalues",
"def test_kw_correction(self):\r\n self.assertEqual(_corr_kw(10), 990)\r\n self.assertEqual(_corr_kw(5), 120)\r\n self.assertFloatEqual(_corr_kw(5.4), 152.064)",
"def _calc_corrections(self): \n searchIter= self._niter-1\n while searchIter > 0:\n trySavefilename= self._createSavefilename(searchIter)\n if os.path.exists(trySavefilename):\n trySavefile= open(trySavefilename,'rb')\n corrections= sc.array(pickle.load(trySavefile))\n trySavefile.close()\n break\n else:\n searchIter-= 1\n if searchIter == 0:\n corrections= sc.ones((self._npoints,2))\n for ii in range(searchIter,self._niter):\n if ii == 0:\n currentDF= self._dftype(surfaceSigma=self._surfaceSigmaProfile,\n beta=self._beta)\n else:\n currentDF= self._dftype(surfaceSigma=self._surfaceSigmaProfile,\n beta=self._beta,\n corrections=corrections,\n npoints=self._npoints,\n rmax=self._rmax,\n savedir=self._savedir,\n interp_k=self._interp_k)\n newcorrections= sc.zeros((self._npoints,2))\n for jj in range(self._npoints):\n thisSurface= currentDF.surfacemass(self._rs[jj],\n use_physical=False)\n newcorrections[jj,0]= currentDF.targetSurfacemass(self._rs[jj],use_physical=False)/thisSurface\n newcorrections[jj,1]= currentDF.targetSigma2(self._rs[jj],use_physical=False)*thisSurface\\\n /currentDF.sigma2surfacemass(self._rs[jj],\n use_physical=False)\n #print(jj, newcorrections[jj,:])\n corrections*= newcorrections\n #Save\n picklethis= []\n for arr in list(corrections):\n picklethis.append([float(a) for a in arr])\n save_pickles(self._savefilename,picklethis) #We pickle a list for platform-independence)\n return corrections",
"def _calculate_correction(self, telid):",
"def corrections(self):\n return self._corrections",
"def test_assign_seqs_error_correction(self):\r\n\r\n # Handles single fasta and single qual with error correction\r\n file_data = {}\r\n file_data['fasta_files'] = [self.valid_fasta_file_with_bc_errors]\r\n file_data['qual_files'] = [self.valid_qual_file_no_errors]\r\n file_data['demultiplexed_seqs_f'] = FakeOutFile()\r\n file_data['demultiplexed_qual_f'] = FakeOutFile()\r\n\r\n ids_bcs_added_field = {('AACTCGTCGATG', ''): 's1',\r\n ('AGCAGCACTTGT', ''): 's2', ('ACCGCAGAGTCA', ''): 's3'}\r\n bc_lens = [12]\r\n all_bcs = ['AACTCGTCGATG', 'AGCAGCACTTGT', 'ACCGCAGAGTCA']\r\n keep_barcode = False\r\n barcode_type = \"golay_12\"\r\n max_bc_errors = 1.5\r\n start_index = 1\r\n write_unassigned_reads = False\r\n disable_bc_correction = False\r\n added_demultiplex_field = None\r\n\r\n log_data, bc_freqs, seq_counts, corrected_bc_count =\\\r\n assign_seqs(file_data, ids_bcs_added_field, bc_lens, all_bcs,\r\n keep_barcode, barcode_type, max_bc_errors, start_index,\r\n write_unassigned_reads, disable_bc_correction,\r\n added_demultiplex_field)\r\n\r\n expected_demultiplexed_fasta_seq = '>s1_1 ABCD0001 orig_bc=TACTCGTCGATG new_bc=AACTCGTCGATG bc_diffs=1\\nCAGGACGAGACGAGGTT\\n>s3_2 EFGH0002 orig_bc=GCCGCAGAGTCA new_bc=ACCGCAGAGTCA bc_diffs=1\\nCCAGATTACGAGATTA\\n>s2_3 IJKL0003 orig_bc=AGCAGCACTTGT new_bc=AGCAGCACTTGT bc_diffs=0\\nGACCGATTACGATAACG\\n'\r\n expected_demultiplexed_qual_seq = '>s1_1 ABCD0001 orig_bc=TACTCGTCGATG new_bc=AACTCGTCGATG bc_diffs=1\\n30 26 11 11 29 20 19 16 24 17 29 28 11 27 14 24 24\\n>s3_2 EFGH0002 orig_bc=GCCGCAGAGTCA new_bc=ACCGCAGAGTCA bc_diffs=1\\n12 14 27 23 22 19 24 18 19 20 28 10 17 14 17 13\\n>s2_3 IJKL0003 orig_bc=AGCAGCACTTGT new_bc=AGCAGCACTTGT bc_diffs=0\\n10 20 16 20 25 27 22 28 16 22 16 18 12 13 16 25 17\\n'\r\n self.assertEqual(file_data['demultiplexed_seqs_f'].data,\r\n expected_demultiplexed_fasta_seq)\r\n self.assertEqual(file_data['demultiplexed_qual_f'].data,\r\n expected_demultiplexed_qual_seq)\r\n\r\n expected_log_data = {'ACCGCAGAGTCA,s3': 1, 'AACTCGTCGATG,s1': 1,\r\n 'AGCAGCACTTGT,s2': 1}\r\n expected_bc_freqs = {'TACTCGTCGATG': 1, 'GCCGCAGAGTCA': 1,\r\n 'AGCAGCACTTGT': 1}\r\n expected_seq_counts = 3\r\n expected_corrected_bc_count = [2, 0]\r\n\r\n self.assertEqual(log_data, expected_log_data)\r\n self.assertEqual(bc_freqs, expected_bc_freqs)\r\n self.assertEqual(seq_counts, expected_seq_counts)\r\n self.assertEqual(corrected_bc_count, expected_corrected_bc_count)",
"def test_best_result(origianl_waveform):\n origianl_waveform = origianl_waveform.flatten()\n recovery_waveform = []\n audio_length = len(origianl_waveform)\n noise = np.random.random_sample((audio_length,))\n noise_list = [x / 100 for x in noise]\n noise_count = 0\n \n for n in origianl_waveform:\n difference = n - noise_list[noise_count]\n recovery_waveform.append(difference)\n noise_count += 1\n \n return np.asarray(recovery_waveform)",
"def correction(self):\r\n \r\n # empirical coefficients:\r\n k3, k2, k1, k0 = 0.0892, 0.0544, 0.2511, -0.0017\r\n \r\n # thrust as a function of the azimuth angle and the loads:\r\n thrust = self.qn*np.sin(Turbine.t) + self.qt*np.cos(Turbine.t)\r\n \r\n # interpolator function for the thrust:\r\n function = interp1d(Turbine.t, thrust, kind='cubic')\r\n \r\n # vectorize the function so that it takes an array of angles:\r\n __function__ = np.vectorize(function)\r\n \r\n # thrust coefficient integrating according to phi:\r\n self.cth = simps(__function__(Turbine.p), Turbine.p)\r\n \r\n # induction factor:\r\n self.a = k3*self.cth**3 + k2*self.cth**2 + k1*self.cth + k0\r\n \r\n # correction factor:\r\n if self.a <= 0.15:\r\n self.ka = 1.0/(1.0 - self.a)\r\n else:\r\n self.ka = (1./(1 - self.a))*(0.65 + 0.35*exp(-4.5*(self.a - 0.15)))",
"def _corrections(self, *correction_models):\n corrections = 0 if self.time.isscalar else np.zeros(self.time.size)\n for name, correction_func, out_idx, factor in correction_models:\n if name not in self.models:\n continue\n\n correction_cache = self._correction_cache.setdefault(name, dict())\n if self.time.isscalar:\n mjd = self.time.tt.mjd\n if mjd not in correction_cache:\n correction_cache[mjd] = correction_func(mjd)\n corrections += factor * correction_cache[mjd][out_idx]\n else:\n for idx, mjd in enumerate(self.time.tt.mjd):\n if mjd not in correction_cache:\n correction_cache[mjd] = correction_func(mjd)\n\n corrections[idx] += factor * correction_cache[mjd][out_idx]\n\n return corrections",
"def testrescorr():\n tau = np.zeros((2,50))\n tau[0,25] = 2\n tau[1,23] = 3\n tau2 = spec_utils.res_corr(tau, 2, 8)\n #Check flux conserved\n assert np.abs(np.sum(tau2[0,:])/ np.sum(tau[0,:]) -1) < 1e-6\n assert np.abs(np.sum(tau2[1,:])/ np.sum(tau[1,:]) -1) < 1e-6\n #Check expanded by expected amount\n for i in (0,1):\n assert np.size(np.where(tau2[i,:]> 0)) == 15",
"def testCTIcorrection(log, files, sigma=0.75, iterations=4, xcen=1900, ycen=1900, side=20):\n settings = dict(sigma=sigma, iterations=iterations)\n\n eclean = []\n e1clean = []\n e2clean = []\n R2clean = []\n eCTI = []\n e1CTI = []\n e2CTI = []\n R2CTI = []\n for file in files:\n #load no cti data\n nocti = pf.getdata(file.replace('CTI', 'nocti'))[ycen-side:ycen+side, xcen-side:xcen+side]\n #subtract background\n nocti -= 27.765714285714285\n nocti[nocti < 0.] = 0. #remove negative numbers\n\n #load CTI data\n CTI = pf.getdata(file)[ycen-side:ycen+side, xcen-side:xcen+side]\n CTI[CTI < 0.] = 0. #remove negative numbers\n\n sh = shape.shapeMeasurement(nocti, log, **settings)\n results = sh.measureRefinedEllipticity()\n\n eclean.append(results['ellipticity'])\n e1clean.append(results['e1'])\n e2clean.append(results['e2'])\n R2clean.append(results['R2'])\n\n sh = shape.shapeMeasurement(CTI, log, **settings)\n results = sh.measureRefinedEllipticity()\n\n eCTI.append(results['ellipticity'])\n e1CTI.append(results['e1'])\n e2CTI.append(results['e2'])\n R2CTI.append(results['R2'])\n\n results = {'eclean' : np.asarray(eclean),\n 'e1clean' : np.asarray(e1clean),\n 'e2clean' : np.asarray(e2clean),\n 'R2clean' : np.asarray(R2clean),\n 'eCTI' : np.asarray(eCTI),\n 'e1CTI' : np.asarray(e1CTI),\n 'e2CTI' : np.asarray(e2CTI),\n 'R2CTI' : np.asarray(R2CTI)}\n\n #save to a file\n fileIO.cPickleDumpDictionary(results, 'results.pk')\n\n return results",
"def corr(self):\n pass",
"def auto_corr(sent, target_pos):\n for pos in target_pos:\n target_v = None\n t0 = time.time()\n if len(sent) > 1:\n context_v = model.context2vec(sent, pos) \n context_v = context_v / xp.sqrt((context_v * context_v).sum())\n else:\n context_v = None\n\n if target_v is not None and context_v is not None:\n similarity = mult_sim(w, target_v, context_v)\n else:\n if target_v is not None:\n v = target_v\n elif context_v is not None:\n v = context_v \n else:\n raise Exception(\"Can't find a target nor context.\") \n similarity = (w.dot(v)+1.0)/2 # Cosine similarity can be negative, mapping similarity to [0,1]\n\n old_word = sent[pos]\n if STATE == 'manual':\n print \"\\n>> For the correction of word: \", old_word\n print \">>>> Calculating the candidates ... ...\"\n candidats = candidates(old_word)\n\n l = []\n count = 0\n\n if len(candidats)!=0:\n for i in (-similarity).argsort():\n if index2word[i] not in candidats:\n continue\n else:\n count += 1\n if STATE == 'manual':\n print \"candidate %d:\\t\"%count, index2word[i], \", similarity:\\t\", similarity[i]\n l.append(i)\n if count == N_RESULT:\n break \n else:\n for i in (-similarity).argsort():\n if np.isnan(similarity[i]):\n continue\n #print sent[pos], index2word[i]\n dist = levenshtein(index2word[i], sent[pos])\n if dist <= LEVEN_DIST:\n count += 1\n if STATE == 'manual':\n print \"candidate %d:\\t\"%count, index2word[i],\", similarity:\\t\", similarity[i], \", levenshtein distance:\\t\", dist\n l.append(i)\n if count == N_RESULT:\n break \n if len(l) == 0:\n continue\n \n if STATE == 'manual':\n print \"Time: %.2fs\"%(time.time()-t0)\n print \"Please choose the replacement, enter the number of the candidate: (Enter 0 for no replacement)\"\n choice = six.moves.input('>> ')\n c = int(choice)\n if c == 0:\n continue # no change made\n elif c > 0:\n idx = l[c - 1]\n else:\n raise Exception(\"Invalid input!\") \n elif STATE == 'auto':\n idx = l[0]\n corr_word = index2word[idx]\n\n \n print \">>>> \\t\", old_word, \"\\t--->\\t\", corr_word\n sent[pos] = corr_word\n return sent",
"def sim_correlation_sample(n_items=1,\n n_part=6,\n log_signal=-1,\n corr=0.7,\n n_subj=16,\n rem_mpat=False,\n var_param='separate'):\n rng = np.random.default_rng()\n # Make Flexible model:\n Mflex = pcm.CorrelationModel('flex',num_items=n_items,\n corr=None,cond_effect=False)\n # Make models under the two hypotheses:\n Mtrue = pcm.CorrelationModel('r0',num_items=n_items,\n corr=corr,cond_effect=False)\n if var_param=='common':\n Mflex.common_param=[True,True,True]\n corr_indx = 2\n Mtrue.common_param=[True,True]\n else:\n Mflex.common_param=[False,False,True]\n corr_indx = 0\n Mtrue.common_param=[False,False]\n\n # Make the correlation models from -1 to 1\n nsteps = 21\n M=[]\n corr_list = np.linspace(0,1,nsteps)\n for r in corr_list:\n m=pcm.CorrelationModel(f\"{r:0.2f}\",num_items=1,corr=r,cond_effect=False)\n if var_param=='common':\n m.common_param=[True,True]\n else:\n m.common_param=[False,False] # For group fit, allow different variances\n M.append(m)\n\n cond_vec,part_vec = pcm.sim.make_design(n_items*2,n_part)\n D = pcm.sim.make_dataset(Mtrue, [0,0],\n cond_vec,\n part_vec=part_vec,\n n_sim=n_subj,\n signal=np.exp(log_signal),\n n_channel=50,\n rng=rng)\n\n # Approximate the posterior using the profile log-likelihood\n Tg,_ = pcm.inference.fit_model_group(D,M,fixed_effect=None,fit_scale=False)\n like_list = Tg.likelihood.values.sum(axis=0)\n like_list = like_list-like_list.mean()\n prop_list = exp(like_list)\n prop_list = prop_list/prop_list.sum()\n # Fit the group model and get second derivative:\n T,theta,dFdhh = pcm.fit_model_group(D,Mflex,fixed_effect=None,fit_scale=False,return_second_deriv=True)\n sd = np.sqrt(1/(dFdhh[0]+0.01))*0.2\n # cProfile.run('pcm.sample_model_group(D,Mflex,fixed_effect=None,fit_scale=False,theta0=theta[0],proposal_sd=sd)')\n # Sample the posterior\n sample_param = {'n_samples':8000,'burn_in':100}\n th,l = pcm.sample_model_group(D,Mflex,fixed_effect=None,fit_scale=False,theta0=theta[0],proposal_sd=sd,sample_param=sample_param)\n\n r = (exp(2*th[corr_indx])-1)/(exp(2*th[corr_indx])+1)\n\n plt.figure()\n plt.subplot(3,1,1)\n plt.plot(th[corr_indx])\n plt.subplot(3,1,2)\n plt.plot(l)\n plt.subplot(3,1,3)\n sb.histplot(r,stat='density',bins=corr_list)\n plt.plot(corr_list,prop_list/(corr_list[1]-corr_list[0]),'r')\n return T,theta,Mflex,th,l",
"def corrections(vec):\n bonf_all = vec * len(vec)\n bonf_within = vec.groupby(level=0).apply(lambda s: s * len(s))\n\n bh_all = H.bhCorrection(vec)\n bh_within = vec.groupby(level=0).apply(H.bhCorrection).order()\n\n two_step = bh_within * len(vec.groupby(level=0).size())\n q = pd.concat([vec, bh_within, bh_all, bonf_all, bonf_within, two_step],\n keys=['uncorrected', 'bh_within', 'bh_all', 'bonf_all', 'bonf_within',\n 'two_step'], axis=1)\n return q",
"def test_reciprocal_translations(self):\n for i in xrange(-1, 7):\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n #can't have reciprocal connection once None appears\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_chromosome(i)\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.cds_coordinate_to_transcript(i)\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n if tmp is not None:\n tmp = self.t.transcript_coordinate_to_cds(tmp)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(i)\n if tmp is not None:\n tmp = self.t.chromosome_coordinate_to_transcript(tmp)\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(self.t.transcript_coordinate_to_cds(i))\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)",
"def test_reciprocal_translations(self):\n for i in xrange(-1, 7):\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n #can't have reciprocal connection once None appears\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_chromosome(i)\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.cds_coordinate_to_transcript(i)\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n if tmp is not None:\n tmp = self.t.transcript_coordinate_to_cds(tmp)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(i)\n if tmp is not None:\n tmp = self.t.chromosome_coordinate_to_transcript(tmp)\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(self.t.transcript_coordinate_to_cds(i))\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)",
"def test_reciprocal_translations(self):\n for i in xrange(-1, 7):\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n #can't have reciprocal connection once None appears\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_chromosome(i)\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.cds_coordinate_to_transcript(i)\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n if tmp is not None:\n tmp = self.t.transcript_coordinate_to_cds(tmp)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(i)\n if tmp is not None:\n tmp = self.t.chromosome_coordinate_to_transcript(tmp)\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(self.t.transcript_coordinate_to_cds(i))\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)",
"def _compute_correction(self, initial_state, final_state, a, b, c, s):\r\n pertub = self.pertub\r\n pertub_s = pertub *10\r\n \r\n pred_no_pertub = self._motion_update_one_shot(initial_state, a, b, c, s)\r\n pred_pertub_a = self._motion_update_one_shot(initial_state, a +pertub, b, c, s)\r\n pred_pertub_b = self._motion_update_one_shot(initial_state, a, b +pertub, c, s)\r\n # no need to correct C, C is constrained by kappa_final\r\n # # pred_pertub_c = self._motion_update_one_shot(initial_state, a, b, c +pertub, s)\r\n pred_pertub_s = self._motion_update_one_shot(initial_state, a, b, c, s +pertub_s)\r\n\r\n d_state = np.zeros((3,1))\r\n d_pertub_state = np.zeros((3,3))\r\n Jacobian = np.zeros((3,3))\r\n for i in range(0, 3):\r\n d_pertub_state[i][0] = (final_state[i] - pred_pertub_a[i]) # a\r\n d_pertub_state[i][1] = (final_state[i] - pred_pertub_b[i]) # b\r\n # d_pertub_state[i][2] = (final_state[i] - pred_pertub_c[i]) # c (no update)\r\n d_pertub_state[i][2] = (final_state[i] - pred_pertub_s[i]) # s\r\n \r\n d_state[i] = final_state[i] - pred_no_pertub[i]\r\n \r\n Jacobian[i][0] = (d_pertub_state[i][0] - d_state[i])/pertub # a\r\n Jacobian[i][1] = (d_pertub_state[i][1] - d_state[i])/pertub # b\r\n # Jacobian[i][2] = (d_pertub_state[i][2] - d_state[i])/pertub # c (no update)\r\n Jacobian[i][2] = (d_pertub_state[i][2] - d_state[i])/pertub_s # s\r\n\r\n # inv_Jacobian = np.linalg.inv(Jacobian)\r\n inv_Jacobian = np.linalg.pinv(Jacobian)\r\n correction = np.dot(inv_Jacobian, d_state)\r\n # pdb.set_trace()\r\n return correction",
"def test_reciprocal_translations(self):\n for i in xrange(16):\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n #can't have reciprocal connection once None appears\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_chromosome(i)\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.cds_coordinate_to_transcript(i)\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n if tmp is not None:\n tmp = self.t.transcript_coordinate_to_cds(tmp)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(i)\n if tmp is not None:\n tmp = self.t.chromosome_coordinate_to_transcript(tmp)\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(self.t.transcript_coordinate_to_cds(i))\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)",
"def test_reciprocal_translations(self):\n for i in xrange(16):\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n #can't have reciprocal connection once None appears\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_chromosome(i)\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.cds_coordinate_to_transcript(i)\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n if tmp is not None:\n tmp = self.t.transcript_coordinate_to_cds(tmp)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(i)\n if tmp is not None:\n tmp = self.t.chromosome_coordinate_to_transcript(tmp)\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(self.t.transcript_coordinate_to_cds(i))\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)",
"def test_3_1_4D_rec_init(self):\n check = [(-1.0, -15.0, 0.0, 3.0), (4.0, -10.0, 1.0, 5.0),\n (4.0, -15.0, 0.0, 3.0), (4.0, -10.0, 0.0, 3.0),\n (4.0, -10.0, 1.0, 3.0), (4.0, -10.0, 0.0, 5.0),\n (4.0, -15.0, 1.0, 3.0), (4.0, -15.0, 1.0, 5.0),\n (4.0, -15.0, 0.0, 5.0), (-1.0, -10.0, 0.0, 3.0),\n (-1.0, -10.0, 1.0, 3.0), (-1.0, -10.0, 1.0, 5.0),\n (-1.0, -10.0, 0.0, 5.0), (-1.0, -15.0, 1.0, 3.0),\n (-1.0, -15.0, 1.0, 5.0), (-1.0, -15.0, 0.0, 5.0),\n (1.5, -12.5, 0.5, 4.0)]\n nn_checks = {(4.0, -15.0, 1.0, 5.0): [(-1, -15, 1, 5), (4, -15, 0, 5),\n (-1, -15, 0, 3), (4, -15, 1, 3),\n (4, -10, 1, 5), (-1, -15, 0, 5),\n (4, -15, 0, 3), (-1, -15, 1, 3),\n (1.5, -12.5, 0.5, 4.0)],\n (4.0, -15.0, 0.0, 5.0): [(4, -15, 1, 5), (4, -10, 0, 5),\n (-1, -15, 0, 3), (4, -10, 1, 5),\n (-1, -15, 0, 5), (4, -15, 0, 3),\n (1.5, -12.5, 0.5, 4.0)],\n (1.5, -12.5, 0.5, 4.0): [(4, -15, 1, 5), (-1, -10, 0, 5),\n (4, -10, 0, 5), (-1, -15, 1, 5),\n (4, -10, 1, 3), (-1, -10, 1, 5),\n (4, -15, 0, 5), (-1, -15, 1, 3),\n (-1, -15, 0, 3), (4, -15, 1, 3),\n (-1, -10, 0, 3), (4, -10, 1, 5),\n (-1, -10, 1, 3), (-1, -15, 0, 5),\n (4, -15, 0, 3), (4, -10, 0, 3)]}\n\n init_triangulation(4, 0, check, nn_checks,\n bounds=[(-1, 4), (-15, -10), (0, 1), (3, 5)])",
"def testCTIcorrectionNonoise(log, files, output, sigma=0.75, iterations=4):\n eclean = []\n e1clean = []\n e2clean = []\n R2clean = []\n xclean = []\n yclean = []\n eCTI = []\n e1CTI = []\n e2CTI = []\n R2CTI = []\n xCTI = []\n yCTI = []\n eCTIfixed = []\n e1CTIfixed = []\n e2CTIfixed = []\n R2CTIfixed = []\n xCTIfixed = []\n yCTIfixed = []\n\n fh = open(output.replace('pk', 'csv'), 'w')\n fh.write('#file, delta_e, delta_e1, delta_e2, delta_R2, delta_x, delta_y\\n')\n for f in files:\n print 'Processing: ', f\n\n #reset settings\n settings = dict(sigma=sigma, iterations=iterations)\n\n #load no cti data\n nocti = pf.getdata(f.replace('CUT', 'CUTnoctinonoise'))\n\n #load CTI data\n CTI = pf.getdata(f)\n\n sh = shape.shapeMeasurement(nocti, log, **settings)\n results = sh.measureRefinedEllipticity()\n\n eclean.append(results['ellipticity'])\n e1clean.append(results['e1'])\n e2clean.append(results['e2'])\n R2clean.append(results['R2'])\n xclean.append(results['centreX'])\n yclean.append(results['centreY'])\n\n #CTI, fitted centroid\n sh = shape.shapeMeasurement(CTI.copy(), log, **settings)\n results2 = sh.measureRefinedEllipticity()\n\n eCTI.append(results2['ellipticity'])\n e1CTI.append(results2['e1'])\n e2CTI.append(results2['e2'])\n R2CTI.append(results2['R2'])\n xCTI.append(results2['centreX'])\n yCTI.append(results2['centreY'])\n\n #fixed centroid\n settings['fixedPosition'] = True\n settings['fixedX'] = results['centreX']\n settings['fixedY'] = results['centreY']\n settings['iterations'] = 1\n sh = shape.shapeMeasurement(CTI.copy(), log, **settings)\n results3 = sh.measureRefinedEllipticity()\n\n eCTIfixed.append(results3['ellipticity'])\n e1CTIfixed.append(results3['e1'])\n e2CTIfixed.append(results3['e2'])\n R2CTIfixed.append(results3['R2'])\n xCTIfixed.append(results3['centreX'])\n yCTIfixed.append(results3['centreY'])\n\n text = '%s,%e,%e,%e,%e,%e,%e\\n' % (f, results['ellipticity'] - results2['ellipticity'],\n results['e1'] - results2['e1'], results['e2'] - results2['e2'], results['R2'] - results2['R2'],\n results['centreX'] - results2['centreX'], results['centreY'] - results2['centreY'])\n fh.write(text)\n print text\n\n fh.close()\n\n results = {'eclean' : np.asarray(eclean),\n 'e1clean' : np.asarray(e1clean),\n 'e2clean' : np.asarray(e2clean),\n 'R2clean' : np.asarray(R2clean),\n 'xclean' : np.asarray(xclean),\n 'yclean' : np.asarray(yclean),\n 'eCTI' : np.asarray(eCTI),\n 'e1CTI' : np.asarray(e1CTI),\n 'e2CTI' : np.asarray(e2CTI),\n 'R2CTI' : np.asarray(R2CTI),\n 'xCTI' : np.asarray(xCTI),\n 'yCTI' : np.asarray(yCTI),\n 'eCTIfixed': np.asarray(eCTIfixed),\n 'e1CTIfixed': np.asarray(e1CTIfixed),\n 'e2CTIfixed': np.asarray(e2CTIfixed),\n 'R2CTIfixed': np.asarray(R2CTIfixed),\n 'xCTIfixed': np.asarray(xCTIfixed),\n 'yCTIfixed': np.asarray(yCTIfixed)}\n\n #save to a file\n fileIO.cPickleDumpDictionary(results, output)\n\n return results",
"def test_markov_to_chain():\n chain = {\n 'PIKARD': [('Q', 2.0 / 3), ('DORF', 1.0 / 3)],\n 'Q': [('PIKARD', 2.0 / 3), ('ROKER', 1.0 / 3)],\n 'DORF': [('PIKARD', 1.0)],\n 'ROKER': [('Q', 1.0)],\n }\n with markov.DialogChainDatastore() as store:\n store.reinitialize()\n store.store_chain('speakers', chain)\n new_chain = store.to_chain('speakers')\n assert set(chain.keys()) == set(new_chain.keys())\n for speaker, probabilities in six.iteritems(chain):\n assert sort_probs(probabilities) == sort_probs(new_chain[speaker])",
"def test_affect_of_strategy(self):\n self.responses_test([C, C, C], [C, C, C], [C, C, C])\n # Make sure that the retaliations are increasing\n # Retaliate once and forgive\n self.responses_test([C], [D], [D])\n self.responses_test([C, D], [D, C], [C])\n self.responses_test([C, D, C], [D, C, C], [C])\n # Retaliate twice and forgive\n self.responses_test([C, D, C], [D, C, D], [D, D])\n self.responses_test([C, D, C, D, D], [D, C, D, C, C], [C])\n # Opponent defection during retaliation doesn't increase retaliation period\n self.responses_test([C, D, C, D, D], [D, C, D, D, C], [C])\n # Retaliate thrice and forgive\n self.responses_test([C, D, C, D, D, C], [D, C, D, C, C, D], [D, D, D])\n history_1 = [C, D, C, D, D, C, D, D, D]\n history_2 = [D, C, D, C, C, D, C, C, C]\n self.responses_test(history_1, history_2, [C])",
"def test_run_grouped_correlation(self):\r\n # hand calculation of spearman and pearson for 01\r\n # md_g1 = array([6.1, 0.0, 14.2, 6.5, 21])\r\n # md_g2 = array([.3, 9.1, .8, 5.0, 11])\r\n # o1_g1 = array([22, 48, 34, 0, 0])\r\n # o1_g2 = array([0, 15, 0, 76, 74])\r\n # c1_g1 = -0.6155870112510925 #spearman(md_g1, o1_g1)\r\n # c2_g2 = 0.66688592885535025 #spearman(md_g2, o1_g2)\r\n # fisher_population_correlation([-0.6155870112510925,\r\n # 0.66688592885535025], [5,5])\r\n # fpc, h = (0.043595171909468329, 0.12776325359984511)\r\n g1_rhos = [corrcoef(self.otus1[0][i], self.mds1[0])[0][1]\r\n for i in range(10)]\r\n g2_rhos = [corrcoef(self.otus1[1][i], self.mds1[1])[0][1]\r\n for i in range(10)]\r\n exp_rhos = [g1_rhos, g2_rhos]\r\n g1_pvals = [assign_correlation_pval(g1_rhos[i], 5,\r\n 'parametric_t_distribution') for i in range(10)]\r\n g2_pvals = [assign_correlation_pval(g2_rhos[i], 5,\r\n 'parametric_t_distribution') for i in range(10)]\r\n exp_pvals = [g1_pvals, g2_pvals]\r\n exp_f_pvals = [fisher([g1_pvals[i], g2_pvals[i]]) for i in range(10)]\r\n\r\n tmp = [fisher_population_correlation([g1_rhos[i], g2_rhos[i]], [5, 5])\r\n for i in range(10)]\r\n exp_f_rhos = [x[0] for x in tmp]\r\n exp_f_hs = [x[1] for x in tmp]\r\n\r\n obs_rhos, obs_pvals, obs_f_pvals, obs_f_rhos, obs_f_hs = \\\r\n run_grouped_correlation(self.mds1, self.otus1, 'pearson',\r\n CORRELATION_TEST_CHOICES, 'parametric_t_distribution')\r\n\r\n assert_almost_equal(obs_rhos, exp_rhos)\r\n assert_almost_equal(obs_pvals, exp_pvals)\r\n assert_almost_equal(obs_f_pvals, exp_f_pvals)\r\n assert_almost_equal(obs_f_rhos, exp_f_rhos)\r\n assert_almost_equal(obs_f_hs, exp_f_hs)",
"def test_reciprocal_translations(self):\n for i in xrange(-1, 12):\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n #can't have reciprocal connection once None appears\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_chromosome(i)\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.cds_coordinate_to_transcript(i)\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n if tmp is not None:\n tmp = self.t.transcript_coordinate_to_cds(tmp)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(i)\n if tmp is not None:\n tmp = self.t.chromosome_coordinate_to_transcript(tmp)\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(self.t.transcript_coordinate_to_cds(i))\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)",
"def test_reciprocal_translations(self):\n for i in xrange(-1, 12):\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n #can't have reciprocal connection once None appears\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_chromosome(i)\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.cds_coordinate_to_transcript(i)\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n if tmp is not None:\n tmp = self.t.transcript_coordinate_to_cds(tmp)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(i)\n if tmp is not None:\n tmp = self.t.chromosome_coordinate_to_transcript(tmp)\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(self.t.transcript_coordinate_to_cds(i))\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)",
"def test_reciprocal_translations(self):\n for i in xrange(-1, 12):\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n #can't have reciprocal connection once None appears\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_chromosome(i)\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.cds_coordinate_to_transcript(i)\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n if tmp is not None:\n tmp = self.t.transcript_coordinate_to_cds(tmp)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(i)\n if tmp is not None:\n tmp = self.t.chromosome_coordinate_to_transcript(tmp)\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(self.t.transcript_coordinate_to_cds(i))\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)",
"def test_reciprocal_translations(self):\n for i in xrange(-1, 12):\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n #can't have reciprocal connection once None appears\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_chromosome(i)\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.transcript_coordinate_to_cds(i)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_transcript(tmp), i)\n\n tmp = self.t.cds_coordinate_to_transcript(i)\n if tmp is not None:\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.chromosome_coordinate_to_transcript(i)\n if tmp is not None:\n tmp = self.t.transcript_coordinate_to_cds(tmp)\n if tmp is not None:\n self.assertEqual(self.t.cds_coordinate_to_chromosome(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(i)\n if tmp is not None:\n tmp = self.t.chromosome_coordinate_to_transcript(tmp)\n self.assertEqual(self.t.transcript_coordinate_to_cds(tmp), i)\n\n tmp = self.t.cds_coordinate_to_chromosome(self.t.transcript_coordinate_to_cds(i))\n if tmp is not None:\n self.assertEqual(self.t.chromosome_coordinate_to_transcript(tmp), i)"
] | [
"0.6057315",
"0.5711097",
"0.55673796",
"0.55620474",
"0.5417592",
"0.54044276",
"0.53824866",
"0.537402",
"0.53574383",
"0.5350013",
"0.533185",
"0.5309343",
"0.5293897",
"0.52858984",
"0.5236561",
"0.51909345",
"0.51909345",
"0.51909345",
"0.5171807",
"0.5168166",
"0.5168166",
"0.51652604",
"0.51581234",
"0.5146924",
"0.51398486",
"0.51302296",
"0.5126439",
"0.5126439",
"0.5126439",
"0.5126439"
] | 0.6975479 | 0 |
print all customers with the current time and id in CSV format. | def print_customers(self):
self.current_time = self.get_time()
return f'Supermarket("{self.customers}", "{self.current_time}")' | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def print_customers(self):\n output = ''\n for i in range(len(self.customers)):\n output += f'Customer no. {self.customers[i].id} is in {self.customers[i].state[0]} section\\n'\n #print(output)\n with open('oneday.csv','a') as outfile:\n for i in range(len(self.customers)):\n outfile.write(f'{self.get_time()};{self.customers[i].id};{self.customers[i].state[0]}\\n')",
"def table_info(self):\n for customer in self.customers:\n print(customer.get_name())",
"def customerReport(self):\n self._setFormat()\n for cust in self.getCustomerAccountData():\n self.output.write(self.form_line(cust))",
"def show_all_customers():\n return cr.show_all_customers()",
"def printCsv(self):\n self.printCsvHeader()\n for r in self._records:\n r.printCsv()",
"def list_apiscout_csv(self, destination):\n res = self.__make_api_call('list/apiscout/csv', raw=True)\n with open(destination, \"wb\") as csvfile:\n csvfile.write(res)",
"def get_all_customer_ids():\n\n # your code",
"def get_customers(cls, api, id='', **params):\n return api.get_customers(id, **params)",
"def csv(self):\n result = \"\"\n for cpu in self.cpus_current:\n result += str(cpu) + \",\"\n return result",
"def fetch_customer_info_full(self, client_id):\n\n try:\n return self._make_private_api_request(\n method=PyttributionIo.GET_REQUEST,\n endpoint='customers',\n subject_id=client_id,\n show_all='true'\n ).get('customer')\n except RequestException as e:\n logger.error('Pyttribution.io: Retrieval of full customer info failed with HTTP status {exception}'.format(\n exception=e))",
"def get_all_customers():\n data = user_obj.get_all_customers()\n return data",
"def make_csv(user_id, fobj):\n data = show_history(user_id)\n report = csv.writer(fobj)\n report.writerow([\n 'Status',\n 'Date',\n 'Amount',\n 'From Curr',\n 'To Curr',\n 'To Address',\n ])\n for row in data:\n report.writerow([\n row.exchange_status.capitalize(),\n row.created_at.strftime('%Y-%m-%d %H:%I:%M'),\n row.amount,\n row.from_curr,\n row.to_curr,\n row.address_out\n ])",
"def get_customer_info(self, customer_id):\n #requested_customer_RDD = self.sc.parallelize(movie_ids).map(lambda x: (user_id, x))\n # Get predicted ratings\n customers = self.__get_customers(customer_id).collect()\n\n return customers",
"def get_all_customer_ids():\n table = data_manager.get_table_from_file(\"sales/sales.csv\")\n return get_all_customer_ids_from_table(table)",
"def getCustomerAccountData(self):\n self.logger.debug(\"\")\n #Process each entry returned by getCustomersInfo through getAccountsInfo.\n customersInfoResponse = self.getCustomersInfo()\n if customersInfoResponse is None:\n self.logger.debug(\"did not get data from self.getCustomersInfo()\")\n raise RuntimeError()\n first = True\n cInfos = self.parseCustomerInfo(customersInfoResponse)\n self.logger.debug(\"%d cInfos\", len(cInfos))\n data = {}\n for cInfo in cInfos:\n if first:\n first = False\n else: # Adds a newline separator for text output.\n self.output.write(self.format({}))\n data['CustomerId'] = cInfo['Id']\n accountsInfoResponse = self.getAccountsInfo(cInfo['Id'], \"true\")\n if accountsInfoResponse is not None:\n data['accounts'] = self.parseAccountInfo(accountsInfoResponse)\n else:\n data['accounts'] = []\n self.logger.debug(\"yield %r\", data)\n yield data",
"def print(self):\n df = self.gen_test()\n # print(df)\n df.to_csv('some_dated_file.csv', index=False)\n return df",
"def get(self):\n return get_all_customers()",
"def show_table(table, has_customer_id=True):\n titles = [\"ID\", \"Title\", \"Price\", \"Date\"]\n if has_customer_id:\n titles.append(\"Customer ID\")\n output_table = [[row[ID], row[TITLE], row[PRICE],\n '/'.join((str(row[YEAR]), str(row[MONTH]), str(row[DAY]))), row[CUSTOMER_ID]] for row in table]\n else:\n output_table = [[row[ID], row[TITLE], row[PRICE],\n '/'.join((str(row[YEAR]), str(row[MONTH]), str(row[DAY])))] for row in table]\n\n ui.clear_scr()\n ui.print_table(output_table, titles, TITLE)",
"def PrintAllCosts():\n\n logs.logger.debug(\"After queries of all costs from database start to print\"\n \" the details (id, reg.date, date of payment, amount,\"\n \" description, category) of the costs to the consol.\")\n try:\n printedCosts = session.query(Cost.Cost).all()\n for cost in printedCosts:\n print(\n f'{cost.id}\\t{cost.registrationDate}\\t{cost.dateOfPayment} \\\n \\t{cost.amount}\\t{cost.description}\\t{cost.category.value}')\n logs.logger.info(\"After queries of all costs from database print\"\n \" the details (id, reg.date, date of payment, amount,\"\n \" description, category) of the costs to the consol.\")\n except Exception as e:\n logs.logger.error(e, exc_info=True)",
"def generate_customer_info(self):\n consecutive = check_consecutive(self.customerIds)\n print(\"consecutive\" + str(consecutive))\n if consecutive:\n for customer_id in self.customerIds:\n # next we need to 1) decide if the customer has insurance, and if yes, generate the EOB that gets sent to the customer\n insured = np.random.choice(\n self.distributions[\"insurance_status\"],\n 1,\n p=self.distributions[\"insurance_distribution\"],\n )[0]\n dob = self.dobs[customer_id - 1]\n customer = pd.DataFrame(\n {\n \"customer_id\": [customer_id],\n \"dob\": str(dob),\n \"insurance\": insured,\n \"experiment_id\": random.randint(1, 2),\n }\n )\n self.Customers = self.Customers.append(customer)\n else:\n print(\"Error generating customer info: customerIds aren't consecutive\")\n return True",
"def get_all_customers(connection):\n connection.command_path = \"customers\"\n extra_headers = {connection.header_key: connection.token}\n url = connection.build_url()\n verify_ssl = connection.verify_ssl\n res = requests.get(url=url, headers=extra_headers, verify=verify_ssl)\n if res.status_code > 210:\n return\n body = res.content\n return customers.parse_all_customers(body)",
"def list_customers():\n customers = db_helper.get_all_customers()\n return jsonify({\"customers\": customers})",
"def return_customers():\n with MY_CONNECTION as connection:\n cursor = connection.cursor()\n cursor.execute(\"SELECT id_customer, login, customer_name, phone, email, perm FROM Customers\")\n return cursor.fetchall()",
"def csvprint(self, data):\n import csv\n import sys\n # self._assert(data) CSV data row lenght can vary\n data = self._render(data) # make elements ascii\n writer = csv.writer(sys.stdout, delimiter=',',\n quotechar='\"', \n quoting=csv.QUOTE_MINIMAL,\n lineterminator=\"\\n\")\n for row in data: writer.writerow(row)",
"def export_to_csv(self, log):\n if os.path.isfile(self.GENERATE_FILE):\n os.remove(self.GENERATE_FILE)\n\n with open(self.GENERATE_FILE, \"w\") as f:\n f.write(\"date, time, username, succes, label\\n\")\n\n for entry in log:\n f.write(str(entry[0].date()) + \", \"\n + str(self.hms_to_seconds(entry[0])) + \", \"\n + str(entry[1]) + \", \"\n + str(entry[2]) + \", \"\n + str(entry[3])\n + \"\\n\")",
"def get_customer_list(self):\n return self._customer_repo.get_customer_list()",
"def print_csv(self, items, fields):\r\n writer = csv.writer(sys.stdout)\r\n writer.writerow(fields)\r\n for i in items:\r\n i_fields = [self.string(getattr(i, f)) for f in fields]\r\n writer.writerow(i_fields)",
"def customer_list(h):\n global html\n html = h\n\n common_elements = customer_common_elements()\n\n css_list = common_elements[\"css_list\"]\n\n javascript_list = common_elements[\"javascript_list\"]\n\n all_btn = common_elements[\"all_btn\"]\n\n html.new_header(\"Customers\", \"customer_management.py\", all_btn, css_list, javascript_list)\n customer_string = \"\"\"\n <div>\n <table id=\"customers\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"display\" style=\"text-align:center\">\n <thead>\n <tr>\n <th>\n Customer Name\n </th>\n <th>\n Customer Group\n </th>\n <th>\n Customer Company\n </th>\n <th>\n Email\n </th>\n <th>\n Mobile\n </th>\n <th>\n Usage\n </th>\n <th>\n Actions\n </th>\n </tr>\n </thead>\n </table>\n </div>\n \"\"\"\n customer_string += \"\"\"\n <script>\n get_customers();\n </script>\n \"\"\"\n html.write(customer_string)\n html.new_footer()",
"def write_csv(self, file):\n # Write header row\n file.write('Timestamp,MessageType,Queue,Price,Volume,OrderID\\n')\n # Write content\n for x in self.records:\n row = (str(x[0]) + ',' + x[1][\"MessageType\"] + ',' +\n x[1][\"Queue\"] + ',' + str(x[1][\"Price\"]) + ',' +\n str(x[1][\"Volume\"]) + ',' + str(x[1][\"OrderID\"]) + '\\n')\n file.write(row)",
"def fetch_customer_info_events(self, client_id):\n\n try:\n return self._make_private_api_request(\n method=PyttributionIo.GET_REQUEST,\n endpoint='customers',\n subject_id=client_id,\n show_events='true'\n ).get('customer')\n except RequestException as e:\n logger.error(\n 'Pyttribution.io: Retrieval of customer events failed with HTTP status {exception}'.format(exception=e))"
] | [
"0.81062955",
"0.6655075",
"0.6352781",
"0.62912863",
"0.60612553",
"0.5880387",
"0.57283247",
"0.57257265",
"0.57104826",
"0.57089424",
"0.57023174",
"0.57002157",
"0.56671035",
"0.5645103",
"0.55245644",
"0.55160266",
"0.5500443",
"0.54647124",
"0.54565537",
"0.54498583",
"0.54472107",
"0.54377854",
"0.54309314",
"0.5410538",
"0.54014885",
"0.5388533",
"0.5377149",
"0.53752697",
"0.5359638",
"0.5356558"
] | 0.7301803 | 1 |
removes every customer that is not active any more. | def remove_existing_customers(self):
# remove the customers which are not active (.is_active )
self.to_move = False
#for cust in self.customers:
# print(cust.state)
self.customers = [cust for cust in self.customers if cust.state != 'checkout']
#if cust.to_move():
# self.to_move = True | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def remove_existing_customers(self):\n\n for i in range(len(self.customers)):\n if self.customers[i].is_active() == False:\n self.customers[i]= 'out'\n self.customers = [item for item in self.customers if item!='out' ]",
"def test_list_active_users(_list_active_customers):\n for customer in _list_active_customers:\n bo.add_customer(\n customer[0],\n customer[1],\n customer[2],\n customer[3],\n customer[4],\n customer[5],\n customer[6],\n customer[7]\n )\n\n assert bo.list_active_customers() == 4\n\n for customer in _list_active_customers:\n bo.delete_customer(customer[0])\n \n assert bo.list_active_customers() == 0",
"def del_all_records():\n delete_alles = Customer.delete().where(Customer.name >= '')\n delete_alles.execute()",
"def delete_customer(self, customer_to_del):\n customer_list = self._customer_repo.get_customer_list()\n for customer in customer_list:\n if customer.get_customer_id() == customer_to_del: #Maybe need to find a more efficient way\n customer_list.remove(customer)\n self._customer_repo.overwrite_customer_list(customer_list)\n credit_card_list = self._customer_repo.get_credit_card_list()\n for credit_card in credit_card_list:\n if credit_card.get_customer_id() == customer_to_del: #Maybe need to find a more efficient way\n credit_card_list.remove(credit_card)\n self._customer_repo.overwrite_credit_card_list(credit_card_list)",
"def prune(cls):\n keep_ids = cls.objects.distinct(\"channel_id\", \"action\").order_by(\"channel_id\", \"action\", \"-performed\").values_list(\"id\", flat=True)\n cls.objects.exclude(id__in=keep_ids).delete()",
"def clean_customer_df(customer_df: pd.DataFrame) -> pd.DataFrame:\n \n # remove customers with more than 20 purchases\n if 'frequency' in customer_df.columns:\n customer_df = customer_df[customer_df.frequency < 20]\n \n return customer_df",
"def delete_expired_users(self):\n for profile in self.all():\n if profile.activation_key_expired():\n user = profile.user\n if not user.is_active:\n user.delete()",
"def delete_expired_users(self):\r\n for profile in self.all():\r\n if profile.activation_key_expired():\r\n user = profile.user\r\n if not user.is_active:\r\n user.delete()",
"def remove_customer(self, loginID):\n try:\n self.cursor.execute(\"\"\"SELECT COUNT(*) FROM customercredentials WHERE loginID=%s\"\"\", (loginID,))\n if not self.cursor.fetchone()[0]:\n return False\n self.cursor.execute(\"\"\"DELETE FROM customercredentials WHERE loginID=%s\"\"\", (loginID,))\n self.db.commit()\n self.cursor.execute(\"\"\"DELETE FROM customerpersonal WHERE phone NOT IN \n (SELECT phone FROM customercredentials)\"\"\")\n self.db.commit()\n self.update_book_scores()\n self.update_comment_usefulness()\n return True\n except Exception as e:\n return False",
"def remove_inactive_consumers():\n\n THRESHOLD_MINUTES = 5\n\n schema = get_schema()\n for subscription in schema.subscription_type.fields.keys():\n to_remove = []\n for consumer in frappe.cache().hkeys(get_subscription_redis_key(subscription)):\n subscription_info = frappe.cache().hget(\n get_subscription_redis_key(subscription), consumer)\n\n should_remove = True\n if subscription_info.last_ping:\n last_ping = get_datetime(subscription_info.last_ping)\n if last_ping + timedelta(minutes=THRESHOLD_MINUTES) >= now_datetime():\n should_remove = False\n\n if should_remove:\n to_remove.append(consumer)\n\n if len(to_remove):\n frappe.cache().hdel(\n get_subscription_redis_key(subscription), *to_remove)",
"def non_activated_account(delete=False):\r\n test_date = datetime.utcnow() - NON_ACTIVATION_AGE\r\n query = DBSession.query(Activation.id).\\\r\n filter(Activation.valid_until < test_date).\\\r\n subquery(name=\"query\")\r\n qry = DBSession.query(User).\\\r\n filter(User.activated.is_(False)).\\\r\n filter(User.last_login.is_(None)).\\\r\n filter(User.id.in_(query))\r\n # Delete the non activated accounts only if it is asked to.\r\n if delete:\r\n for user in qry.all():\r\n DBSession.delete(user)\r\n # If the non activated accounts are not asked to be deleted,\r\n # return their details.\r\n else:\r\n return qry.all()",
"def prune(self):\n target_user_ids = self.get_queryset().values_list('id', flat=True)\n exclude_user_ids = SentDrip.objects.filter(date__lt=conditional_now(),\n drip=self.drip_model,\n user__id__in=target_user_ids)\\\n .values_list('user_id', flat=True)\n self._queryset = self.get_queryset().exclude(id__in=exclude_user_ids)",
"def delete_expired_users(self):\n for profile in self.all():\n if profile.activation_key_expired():\n user = profile.user\n if not user.is_active:\n user.delete() # Removing the ``User`` will remove the ``RegistrationProfile``, too.",
"def list_active_customers():\n with cm.DATABASE.transaction():\n # .select() has a .where() method to specify criteria for searching\n active_customers = cm.Customer.select().where(\n cm.Customer.status == \"Active\").count()\n LOGGER.info(\"Active customers: %s\", active_customers)\n return active_customers",
"def remove_expired(cls):\n max_trailers = 10\n current_trailers = cls.get_all(collection='approved_trailers')\n current_trailers.reverse()\n queued_trailers = cls.get_all(collection='queued_trailers')\n\n if len(current_trailers) >= max_trailers and len(queued_trailers) > 0:\n for trailer in current_trailers:\n time_active = trailer.date.timetuple().tm_yday - datetime.now().timetuple().tm_yday\n if time_active >= 14 and len(queued_trailers) > 0:\n cls.move(trailer, 'approved_trailers', 'archived_trailers')\n cls.move(queued_trailers[0], 'queued_trailers', 'approved_trailers')",
"def test_list_active_customers(self):\n set_up_db()\n add_customer(*self.test_customer)\n add_customer(customer_id=2, name=\"Clark\", last_name=\"Kent\", home_address=None,\n phone_number=\"228-626-7899\", email=\"[email protected]\",\n status=True, credit_limit=200.00)\n add_customer(customer_id=3, name=\"Diana\", last_name=\"Prince\", home_address=None,\n phone_number=\"587-8423\", email=\"[email protected]\",\n status=False, credit_limit=100.00)\n self.assertEqual(2, list_active_customers())",
"def admin_delete_non_activated(request):\r\n UserMgr.non_activated_account(delete=True)\r\n return _api_response(request, {\r\n 'status': True,\r\n 'message': 'Removed non activated accounts'\r\n })",
"def _remove_unconfirmed_transactions(frame):\n\n frame.drop(frame.loc[frame['posted'] == False].index, inplace=True)\n return frame",
"def action_unselect_all(self):\n for statement in self:\n statement_lines = statement.credit_move_line_ids + statement.debit_move_line_ids\n statement_lines.write({'cleared_bank_account': False})\n return True",
"def trim_items(self, items):\r\n\t\tlogger.debug(\"Enter\")\r\n\t\t\r\n\t\tif self.transactions:\r\n\t\t\tall_items = set.union(*[self.transactions[u][-1] for u in self.transactions.keys()])\r\n\t\telse:\r\n\t\t\treturn items\r\n\t\t\t\r\n\t\ttmp = items.copy()\r\n\t\t\r\n\t\tfor i in items:\r\n\t\t\tif i in all_items:\r\n\t\t\t\tlogger.debug(\"Removing %r\" % i)\r\n\t\t\t\ttmp.remove(i)\r\n\t\t\t\t\r\n\t\tlogger.debug(\"Exit\")\r\n\t\treturn tmp",
"def list_active_customers():\n active_customers = 0\n for customer in cm.Customers:\n if customer.status == \"Active \":\n active_customers += 1\n return active_customers",
"def remove_obsolete_users(self, date_limit):\n for user in User.objects.filter(last_login__lt=date_limit):\n if not ServiceProvider.objects.filter(admins=user):\n self.output(\"Removing user: \" + user.username)\n if not self.list_only:\n user.delete()",
"def test_list_active_customers(self):\r\n create_empty_db()\r\n add_customer(**user_1)\r\n add_customer(**user_2)\r\n add_customer(**user_3)\r\n self.assertEqual(2, list_active_customers())\r\n drop_db()",
"def remove_accounts(self):\n current_creds = self._accounts.copy()\n for creds in current_creds:\n self.remove_account(current_creds[creds].credentials.token,\n current_creds[creds].credentials.url)",
"def test_delete_non_activated_accounts(self):\r\n res = self.testapp.delete(\r\n '/api/v1/a/nonactivated?api_key={0}'.format(\r\n self.api_key),\r\n status=200)\r\n data = json.loads(res.body)\r\n self.assertEqual(True, data['status'], \"Status should be True\")\r\n self.assertEqual(u'Removed non activated accounts', data['message'])",
"def delete_non_activated_account():\r\n trans = transaction.begin()\r\n UserMgr.delete_non_activated_account()\r\n trans.commit()",
"def delete(self, **params):\n return self._api.delete_customer(self.id, **params)",
"def filter_by_customer(table, customer):\n transactions = []\n for record in table:\n if record[CUSTOMER_ID] == customer:\n transactions.append(record)\n return transactions",
"def remove_all_recs(self):\n return self.storage.clear()",
"def remove_users(users_to_remove: list, users_dict: dict,\n end_of_service: str) -> None:\n for reciever in users_to_remove:\n if reciever in users_dict:\n send_message(reciever,\n 'Subscription expired\\n',\n end_of_service,\n users_dict[reciever]['carrier'])\n del users_dict[reciever]"
] | [
"0.82049865",
"0.6386044",
"0.6291869",
"0.6194914",
"0.592139",
"0.58056027",
"0.57563466",
"0.5755537",
"0.57454765",
"0.57091147",
"0.56706625",
"0.56473964",
"0.5646159",
"0.56140465",
"0.5576211",
"0.5538074",
"0.55353266",
"0.5534561",
"0.5497937",
"0.54871404",
"0.5482875",
"0.5482615",
"0.5465704",
"0.5459759",
"0.5442433",
"0.5422138",
"0.5414776",
"0.53915817",
"0.53833187",
"0.53804266"
] | 0.8266712 | 0 |
Remove a record with a given id from the table. | def remove(table, id_):
record = common.find_id(table, id_[0])
if record in table:
table = common.remove_record(table, record)
return table | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def remove(table, id_):\n table, successful = common.remove_record(table, id_)\n\n if not successful:\n ui.print_error_message('Error!')\n\n return table",
"def delete_record(self, id_: str) -> None:\n instance = self._get(id_)\n self._delete_from_db(instance)",
"def delete_record(self, record_id):\r\n self.record.deleteObject(id=record_id)",
"def delete(self, id):\n\n query = \"DELETE FROM {} WHERE id = {}\".format(self.table, id)\n\n self.remove(query)\n return True",
"def sqlite3_simple_delete_record(data_base, table, id_column, record_id):\n con = sqlite3.connect(data_base)\n cur = con.cursor()\n query = 'DELETE FROM ' + table + ' WHERE ' + id_column + \" = '\" + record_id + \"'\"\n cur.execute(query)\n con.commit()\n cur.close()\n con.close()",
"def delete(table_name, record_id):\n with get_connection() as conn:\n return rethink.table(table_name).get(record_id).delete().run(conn)",
"def delete(self, _id):\n self._db[_id].delete()",
"def destroy_user_record_by_id(record_id):\n session = get_session()\n with session.begin():\n session.query(models.UserAccountRecord).\\\n filter_by(id=record_id).\\\n update({'deleted': True,\n 'deleted_at': datetime.datetime.utcnow(),\n 'updated_at': datetime.datetime.utcnow()})",
"def delete(self, id=None):\n if id is not None:\n self.where('id', '=', id)\n\n sql = self._grammar.compile_delete(self)\n\n return self._connection.delete(sql, self.get_bindings())",
"def delete_item_by_id(self, id):\n response = self.table_connector.delete_item(Key={self.primary_key: id})\n print(response)",
"def delete_by_id(cls, id):\n\t\tbook = Book.query.get(id)\n\t\tdb.session.delete(book)\n\t\tdb.session.commit()",
"def remove_row(self, row_id):",
"def delete_row(self, id):\n logger.debug('Function delete_row start')\n\n cur = self.conn.cursor()\n\n logger.info(\"Deleting row with id: \"+str(id))\n print(\"Deleting row with id: \"+str(id))\n cur.execute(\"DELETE FROM sensor_data WHERE id=?\", (id,))\n\n self.conn.commit()\n\n logger.debug('Function delete_row end')",
"def remove(table, id_):\n count=0\n searched_index=-1\n in_it=False\n for i in table:\n if i[0]==id_:\n searched_index=count\n in_it=True\n count+=1\n\n if in_it: \n table.pop(searched_index)\n else:\n ui.print_error_message(\"ID not found\")\n \n return table",
"def remove(table, id_):\n return common.remove_line(table, id_)",
"def delete(self):\n query = \"DELETE FROM \" + self.table + \" WHERE \" + self.idfield + \"=%s\"\n dbh = dbstuff.getRW(self.dbh_key)\n try:\n c = dbh.cursor()\n c.execute(query, self.id)\n c.close()\n dbh.commit()\n finally:\n dbstuff.release(dbh,self.dbh_key)",
"def remove(table, id_):\n\n # your code\n for i, row in enumerate(table):\n if row[ID] == id_:\n table.pop(i)\n return table\n\n ui.print_error_message(\"Wrong ID!\")\n\n return table\n\n return table",
"def remove(table, id_):\n\n # 3\n for index in range(len(table)):\n if table[index][0] == id_:\n table.pop(index)\n data_manager.write_table_to_file('hr/persons.csv', table)\n return table",
"def remove(table, id_):\n\n common.toremoveid(\"inventory/inventory.csv\",data_manager.get_table_from_file(\"inventory/inventory.csv\"),id_)",
"def remove(table, id_):\n\n entry_index = 0\n for entry in table:\n entry_id_ = entry[0]\n if entry_id_ == id_:\n del table[entry_index]\n entry_index += 1\n data_manager.write_table_to_file(\"model/sales/sales.csv\", table)\n return table",
"def deleteFileRecordByID(file_id):\n session = Queries.createSession()\n try:\n file_db = session.query(FileTable).filter_by(id=file_id).first()\n servers = file_db.server_id[:]\n for server in servers:\n file_db.server_id.remove(server)\n session.commit()\n session.delete(file_db)\n session.commit()\n except sqlalchemy.exc.ArgumentError:\n print 'SQLAlchemy ERROR: Invalid or conflicting function argument is supplied'\n except sqlalchemy.exc.CompileError:\n print 'SQLAlchemy ERROR: Error occurs during SQL compilation'\n finally:\n session.close()",
"def delete_by_id(cls, id):\n\t\tauthor = Author.query.get(id)\n\t\tauthor.saved = False\n\t\tdb.session.commit()",
"def remove_employee(self, id):\n cursor = self.dbconnect.get_cursor()\n try:\n cursor.execute('DELETE FROM employee WHERE employeeID=%s', (id,))\n self.dbconnect.commit()\n except(Exception, self.dbconnect.get_error()) as error:\n self.dbconnect.rollback()\n raise Exception('\\nUnable to remove Employee!\\n(%s)' % (error))",
"def delete(self, id):\n self.cursor.execute(\"DELETE FROM Book WHERE Id = ?\", (id,))\n self.connection.commit()",
"def remove(table, id_):\n\n # your code\n\n key = common.check_for_key(id_,table)\n\n if key == None:\n ui.print_error_message('Key does not exist')\n else:\n table.pop(key)\n data_manager.write_table_to_file('hr/persons.csv', table) \n\n #print(table)\n return table",
"def delete(self, id):\n raise NotImplementedError",
"def remove(table, id_):\n\n for element in table:\n if id_ == element[0]:\n table.remove(element)\n\n return table",
"def delRR(self, name, record_id):\n reply = self.rpc.removeZoneRecord(self.username,\n self.password,\n self.domain,\n name,\n int(record_id))\n if reply != \"OK\":\n raise Exception(\"RPC returned error: \" + reply)",
"def rpc_database_delete_row_by_id(self, row_id):\n\t\ttable = DATABASE_TABLE_OBJECTS.get(self.path.split('/')[-2])\n\t\tassert table\n\t\tsession = db_manager.Session()\n\t\ttry:\n\t\t\tsession.delete(db_manager.get_row_by_id(session, table, row_id))\n\t\t\tsession.commit()\n\t\tfinally:\n\t\t\tsession.close()\n\t\treturn",
"def _remove_record(self, model, row_id) -> bool:\n try:\n model = self.session.query(model).filter_by(id=row_id).first()\n if model:\n self.session.delete(model)\n self.session.commit()\n\n return True\n else:\n return False\n\n except Exception:\n self.session.rollback()\n\n raise"
] | [
"0.81783557",
"0.80144393",
"0.76164657",
"0.74314255",
"0.72872585",
"0.7254864",
"0.7076816",
"0.70399606",
"0.70388323",
"0.6974754",
"0.6938418",
"0.69027793",
"0.68908036",
"0.68530244",
"0.6843683",
"0.6818457",
"0.6817199",
"0.6812474",
"0.68037313",
"0.6790502",
"0.67761993",
"0.6772351",
"0.67653686",
"0.67066634",
"0.67018646",
"0.6692761",
"0.66742605",
"0.66708493",
"0.6649046",
"0.66343373"
] | 0.8055196 | 1 |
Gets from user number of option to change, checks amount of options and data type. | def data_to_change():
title = "Which part of record You want to change?"
exit_message = "Back to main menu."
list_options = ["Name: ", "Manufacturer: ", "purchase_date: ", "Durability: "]
ui.print_menu(title, list_options, exit_message)
correct_input = False
while correct_input is not True:
try:
inputs = ui.get_inputs(['Number'], "Choose data to overwrite.")
option = int(inputs[0])
amount_data = len(list_options) + 1
data_info = list_options[option - 1]
correct_input = True
except ValueError:
ui.print_error_message("Only numbers!")
else:
return option, amount_data, data_info | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def _get_user_options(self, unit):\n print(unit)\n print(\"Options:\")\n for option in unit.options:\n print(option)\n\n user_input = input(\">> \")\n\n # santise and create list of options\n user_input2 = user_input.lower()\n user_input2 = user_input2.translate(str.maketrans('', '', string.punctuation))\n if user_input in {'q', 'quit', 'cancel', 'exit'}:\n print(\"Cancelling change wargear\")\n return False\n user_input2 = re.findall(r'[0-9][a-zA-Z]?', user_input2)\n\n if len(user_input2) == 0: # no suitable regexes found\n print('{} is not a valid option please input options in format <index><sub-index>'.format(user_input))\n wargear_to_add = self._get_user_options(unit)\n return wargear_to_add\n\n wargear_to_add = []\n\n for choice in user_input2:\n try:\n # convert the choice number into the index to select the item\n index = np.zeros(2, dtype=np.uint8)\n index[0] = int(choice[0]) - 1\n sel_option = unit.options[index[0]]\n\n if len(choice) == 2:\n # find the index corresponding to the lowercase letter\n for index[1], i in enumerate(string.ascii_lowercase):\n if i == choice[1]:\n break # index[1] will save as the last enumerate\n sel_option.select(index[1])\n\n elif len(choice) == 1:\n sel_option.select(0) # there will only eveer be one item to select\n else:\n raise IndexError(\n \"{} is not valid, input should be of format <index><sub-index>\".format(choice))\n wargear_to_add.append(sel_option)\n except IndexError:\n print(\n '{} is not a valid option please input options in format <index><sub-index>'.format(choice))\n wargear_to_add = self._get_user_options(unit)\n return wargear_to_add",
"def ask_options(self, msg, n_options, delta=0):\n opt_max = n_options\n new_option = n_options + 1\n ignore_option = n_options + 2\n res = map(int, click.prompt(msg, type=str).split(','))\n\n if res == [new_option]:\n return 'add-new'\n elif res == [ignore_option]:\n return 'ignore'\n elif all(1 <= n <= opt_max for n in res):\n return [n + delta for n in res]",
"def _get_user_size(self, unit):\n # print options if no user input\n if unit.mod_str is None: # only one type of model in the unit\n print(\"Enter size of unit ({}-{}):\".format(*unit.size_range))\n else:\n print(\"How many of each model would you like to add? ({}-{})\".format(*unit.size_range))\n for index, i in enumerate(unit.mod_str):\n print(str(index + 1) + '. ' + i)\n size = input(\">> \")\n\n size2 = [int(i) for i in re.findall(r'[1-9][0-9]*|0', size)] # find all input numbers\n if size2 == []: # no user input\n print(\"{} is invalid, please enter a number\".format(size))\n size2 = self._get_user_size(unit)\n if unit.mod_str is None: # more than one number or not in unit size range\n if len(size2) != 1 or size2[0] < unit.size_range[0] or size2[0] > unit.size_range[1]:\n print(\"{} is invalid, please enter a single number in the range {}-{}\".format(size,\n *unit.size_range))\n size2 = self._get_user_size(unit)\n else:\n if len(size2) != len(unit.mod_str):\n print(\"{} is invalid, please enter a number for each available model\".format(size))\n size2 = self._get_user_size(unit)\n return size2",
"def _num_select(question, options):\n while True:\n print(question)\n i = 0\n for option in options:\n print(\"\\t\" + str(i) + \") \" + option)\n i += 1\n response = input()\n if not _is_int(response):\n print(\"\\nPlease input an integer.\\n\")\n else:\n response = int(response)\n if response < 0 or response > i-1:\n print(\"\\nThat is not a valid response, please try again.\\n\")\n elif _yes_no_select(\"You selected '\" + options[response] + \"', is that correct?\"):\n return (response, options[response])",
"def get_options():\n print(\"1: Compute the sum of 1..n\")\n print(\"2: Compute the product of 1..n\")\n print(\"9: Quit\") \n\n return input(\"Choice: \")",
"def process_options(self):\n data = self.server.receive(self.clientsocket)\n # print(data)\n if 'option_selected' in data.keys() and 1 <= data['option_selected'] <= 6: # validates a valid option selected\n option = data['option_selected']\n if option == 1:\n self._send_user_list()\n elif option == 2:\n recipient_id = data['recipient_id']\n message = data['message']\n self._save_message(recipient_id, message)\n elif option == 3:\n self._send_messages()\n elif option == 4:\n room_id = data['room_id']\n\n chat_id = data['chat_id']\n host = data['chat_user']\n self._create_chat(room_id, chat_id, host)\n # self._create_chat(room_id)\n elif option == 5:\n room_id = data['room_id']\n user_id = data['chat_user']\n self._join_chat(room_id)\n elif option == 6:\n self._disconnect_from_server()\n else:\n mes = \"The option selected is invalid\"\n self.server.send(self.clientsocket, mes)\n print(\"User option selected is invalid\")",
"def check_options(option):\n while True:\n if sys.version_info >= (3,0):\n choice = input(option + '(Y or N): ').upper()\n else:\n choice = raw_input(option + '(Y or N): ').upper()\n\n if choice == 'Y':\n return 1\n elif choice == 'N':\n return 0\n else:\n print('That is not a valid answer. Y or N? ')",
"def optionSet(self):\n choice = self.optionVar.get()\n \n #if custom game is chosen\n if choice == 4:\n msg = \"Invalid Input!\"\n valid = True\n nums = []\n \n #make sure all inputs are integers\n for i in range(3):\n try:\n value = int(self.entry[i].get())\n nums.append(value)\n except ValueError:\n valid = False\n if i == 0: msg += \"\\nHeight \"\n elif i == 1: msg += \"\\nWidth \"\n elif i == 2: msg += \"\\nMines \"\n msg += \"input must be an integer.\"\n \n #check for other invalid inputs\n #(negative input, not wide enough, too many mines)\n if valid:\n if nums[0]<=0 or nums[1]<=0 or nums[2]<=0:\n valid = False\n msg += \"\\nInputs must be integers greater than zero\"\n elif nums[1] < 8 :\n valid = False\n msg += \"\\nMinimum width allowed is 8\"\n if nums[0]*nums[1] <= nums[2]:\n valid = False\n msg += \"\\nToo many mines to fit on the board!\"\n\n #start game according to specs if input was valid\n if valid: \n self.menuVar.set(choice)\n self.checkVar.set(4)\n self.resize(nums[0],nums[1],nums[2])\n self.optionsWindow.destroy()\n #otherwise popup error and keep options window open\n else:\n messagebox.showinfo('Custom Game Error', msg)\n\n #start game according to difficulty chosen \n else:\n self.menuVar.set(choice)\n if choice == 1: self.resize(8,8,10)\n elif choice == 2: self.resize(16,16,40)\n else: self.resize(16,30,99)\n self.optionsWindow.destroy()",
"def update(self): # pragma: no cover\n print(_choices)\n\n while True:\n try:\n user_input = int(input())\n if user_input < 1 or user_input > 5:\n raise ValueError\n # this will send it to the\n # print message and back to the input option\n break\n except ValueError:\n print(\"Invalid integer. \"\n \"The number must be in the range of 1-5.\")\n\n func = self.switcher.get(user_input, lambda: \"Invalid command\")\n print(func())",
"def get_input(self):\n option = input(\"Enter the number of your choice: \")\n return option",
"def options():\n print(\"1: Compute the sum of 1..n\")\n print(\"2: Compute the product of 1..n\")\n print(\"9: Quit\")\n try:\n option = int(input(\"Choice: \"))\n except:\n return None\n return option",
"def NUMBER_OF_REC_CHOICE():\n return 13",
"def read_element():\r\n option = 0\r\n while option != len(options) - 1:\r\n show_menu()\r\n input_data = _get_client_field('Options: ')\r\n if not __empty(input_data) and (input_data.isdigit() == True):\r\n option = int(input_data)\r\n switch(option)",
"def get_sorting_option_from_user():\n while True:\n try:\n sorting_option = int(input(\"Select the type of song you want to download:\\n\"\n \"1. New\\n\"\n \"2. Top\\n\"\n \"3. Most Difficult\\n\\n\"\n \"Enter: \"))\n except ValueError:\n print(\"\\nSorry, that is not a number.\\n\")\n continue\n\n valid_sorting_options = ['new', 'top', 'most-difficult']\n if sorting_option in range(1, 4):\n return valid_sorting_options[sorting_option - 1]\n\n print(f\"\\nSorry, {sorting_option} is not a valid option.\")",
"def option(number, default='no'):\n return answer(number).get('options', default)",
"def __len__(self):\n return len(self.options)",
"def onCheckParameters(self, evt): \n \n print(\"version\", self.config.version)\n \n if isinstance(self.config.iSPV, ( int, long )): pass\n else: \n msg = (\"SPV value should be an integer!\")\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg= msg,\n type=\"Error\")\n return False\n \n if isinstance(self.config.iScanTime, ( int, float )): pass\n else: \n msg = (\"Scan time value should be an integer or float!\")\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg= msg,\n type=\"Error\")\n return False\n \n if isinstance(self.config.iStartVoltage, ( int, float )): pass\n else: \n msg = (\"Start voltage should be an integer or float!\")\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg= msg,\n type=\"Error\")\n return False\n \n if isinstance(self.config.iEndVoltage, ( int, float )): pass\n else: \n msg = (\"End voltage should be an integer or float!\")\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg= msg,\n type=\"Error\")\n return False\n \n if isinstance(self.config.iStepVoltage, ( int, float )): pass\n else: \n msg = (\"Step voltage should be an integer or float!\")\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg= msg,\n type=\"Error\")\n return False\n \n if self.config.iActivationMode == \"Exponential\":\n if isinstance(self.config.iExponentPerct, ( int, float )): pass\n else: \n msg = (\"Exponential % value should be an integer or float!\")\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg= msg,\n type=\"Error\")\n return False\n \n if isinstance(self.config.iExponentIncre, ( int, float )): pass\n else: \n msg = (\"Exponential increment value should be an float!\")\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg= msg,\n type=\"Error\")\n return False\n \n elif self.config.iActivationMode == \"Boltzmann\":\n if isinstance(self.config.iBoltzmann, ( int, float )): pass\n else: \n msg = (\"Boltzmann offset value should be an integer or float!\")\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg=msg ,\n type=\"Error\")\n return False\n \n \n if (abs(self.config.iEndVoltage) <= abs(self.config.iStartVoltage)):\n msg = ('End voltage has to be larger than starting voltage')\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg=msg ,\n type=\"Error\")\n return\n \n if (abs(self.config.iEndVoltage) > 200):\n msg = ('The highest possible voltage is 200 V. Set to default: 200')\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg=msg ,\n type=\"Error\")\n self.config.iEndVoltage = 200\n self.view.panelControls.endVoltage_input.SetValue(str(self.config.iEndVoltage))\n \n if (abs(self.config.iStartVoltage) < 0):\n msg = ('The lowest possible voltage is 0 V. Set to default: 0')\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg=msg ,\n type=\"Error\")\n self.config.iStartVoltage = 0\n self.view.panelControls.startVoltage_input.SetValue(str(self.config.iStartVoltage))\n \n if self.config.iSPV <= 0:\n msg = ('SPV must be larger than 0! Set to default: 3')\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg=msg ,\n type=\"Error\")\n self.config.iSPV = 3\n self.view.panelControls.spv_input.SetValue(str(self.config.iSPV))\n \n if self.config.iScanTime <= 0:\n msg = ('Scan time must be larger than 0! Set to default: 5')\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg=msg ,\n type=\"Error\")\n self.config.iScanTime = 5\n self.view.panelControls.scanTime_input.SetValue(str(self.config.iScanTime))\n\n if self.config.iActivationMode == \"Exponential\":\n if self.config.iExponentPerct < 0:\n msg = ('Exponential % must be larger or equal to 0! Set to default: 0')\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg=msg ,\n type=\"Error\")\n self.config.iExponentPerct = 0\n elif self.config.iExponentPerct >= 100:\n msg = ('Exponential % must be smaller than 100! Set to default: 0')\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg=msg ,\n type=\"Error\")\n self.config.iExponentPerct = 0\n self.view.panelControls.exponentialPerct_input.SetValue(str(self.config.iExponentPerct))\n \n if self.config.iExponentIncre <= 0:\n msg = ('Exponential increment must be larger than 0! Set to default: 0.01')\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg=msg ,\n type=\"Error\")\n self.config.iExponentIncre = 0.01\n elif self.config.iExponentIncre > 0.075:\n msg = ('Exponential increment must be smaller than 0.075! Set to default: 0.075')\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg=msg ,\n type=\"Error\")\n self.config.iExponentIncre = 0.075\n self.view.panelControls.exponentialIncrm_input.SetValue(str(self.config.iExponentIncre))\n elif self.config.iActivationMode == \"Boltzmann\":\n if self.config.iBoltzmann < 10:\n msg = ('Boltzmann offset must be larger than 10! Set to default: 10')\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg=msg,\n type=\"Error\")\n self.config.iBoltzmann = 10\n elif self.config.iBoltzmann >= 100:\n msg = ('Boltzmann offset must be smaller than 100! Set to default: 25')\n dialogs.dlgBox(exceptionTitle='Mistake in the input', \n exceptionMsg=msg,\n type=\"Error\")\n self.config.iBoltzmann = 25\n self.view.panelControls.boltzmann_input.SetValue(str(self.config.iBoltzmann))\n \n # All good\n return True",
"def user_input_choices(self, msg, *options):\n choices = ['%s %s' % (self.prefix, msg)]\n choices += [\n \"%s. %s\" % (num, opt) for num, opt in enumerate(options, 1)]\n try:\n input_str = int(\n vim.eval('inputlist(%s)' % self.prepare_value(choices)))\n except (KeyboardInterrupt, ValueError):\n input_str = 0\n\n if not input_str:\n self.message('Cancelled!')\n return False\n\n try:\n return options[input_str - 1]\n except (IndexError, ValueError):\n self.error('Invalid option: %s' % input_str)\n return self.user_input_choices(msg, *options)",
"def get_user_analysis_preference():\n print(\"\")\n print(\"\")\n print(\n \"Which method of analysis on the data would you like to employ today?\"\n )\n print(\"\")\n for i, source in enumerate(analysis_methods_supported_long):\n print(\"[\" + str(i) + \"]: \" + source)\n print(\"\")\n print(\n \"Please pick just one analysis method and write the number associated\"\n \" with it (e.g. 3)\"\n )\n print(\">\")\n input_digits = input()\n while not (\n len(input_digits) == 1 and\n input_digits.isdigit() and\n int(input_digits) < len(analysis_methods_supported_short)\n ):\n print(\n \"Please pick just one analysis method and write the number\"\n \" associated with it (e.g. 3)\"\n )\n print(\">\")\n input_digits = input()\n\n print(\"Thank you\")\n return analysis_methods_supported_short[int(input_digits)]",
"def __get_user_choice(\n self,\n firstOption: str = 'Add transaction',\n secondOption: str = 'Mine Blocks',\n thirdOption: str = 'Print Participants',\n fourthOption: str = 'Print Blocks',\n fifthOption: str = 'Verify open transactions',\n sixthOption: str = 'Create Wallet',\n seventhOption: str = 'Load Wallet',\n eigthOption: str = 'Save Wallet',\n ninthOption: str = 'Add Peer Node',\n tenthOptipn: str = 'Delete Peer Node',\n offerQuit: bool = True,\n offerManipulate: bool = True) -> int:\n print('Please enter your desired command.')\n print(f'Option 1: {firstOption}')\n print(f'Option 2: {secondOption}')\n print(f'Option 3: {thirdOption}')\n print(f'Option 4: {fourthOption}')\n print(f'Option 5: {fifthOption}')\n print(f'Option 6: {sixthOption}')\n print(f'Option 7: {seventhOption}')\n print(f'Option 8: {eigthOption}')\n print(f'Option 9: {ninthOption}')\n print(f'Option 10: {tenthOptipn}')\n\n if offerQuit == True:\n print(f'Quit: Press \"q\" for quitting')\n if offerManipulate == True:\n print(f'Manipulate: Press \"m\" for manipulating')\n\n reply = input('Enter your command? ')\n if reply.lower() == 'm':\n return -1\n return 0 if reply.lower() == 'q' else int(reply)",
"def _take_option(self, options, print_out):\n user_choice = input(\"Please, choose one of the follewing options: \\n \" + print_out \n + \"\\n Your choice: \" )\n try:\n user_option = options[int(user_choice)]\n except KeyError:\n print(\"Please enter a vaild number\")\n self._take_option(options, print_out)\n \n except ValueError:\n print(\"Please a enter vaild number, not a string or some signs\")\n self._take_option(options, print_out)\n else:\n return user_option()",
"def data_verifier(self, section_num, newdata):\n validvalue = None\n section_selected = self.__teaColumns[section_num-1][0]\n\n if newdata == \"\":\n if section_selected == \"brand\" or section_selected == \"package\" or section_selected == \"price\" or \\\n section_selected == \"notes\" or section_selected == \"mood\" or section_selected == \"buy_again\" or \\\n section_selected == \"on_hand\":\n validvalue = newdata\n elif section_selected == \"tea_name\" or section_selected == \"tea_type\" or section_selected == \"brand\" or \\\n section_selected == \"mood\":\n validvalue = newdata\n elif section_selected == \"temperature\":\n if newdata.isdigit() and 35 <= int(newdata) <= 215:\n validvalue = int(newdata)\n elif section_selected == \"package\":\n ndatalower = newdata.lower()\n if ndatalower == \"loose\" or ndatalower == \"bag\" or ndatalower == \"pyramid\":\n validvalue = newdata.capitalize()\n elif section_selected == \"time\":\n timeparts = newdata.split(':')\n if len(timeparts) == 2:\n if timeparts[0].isdigit() and timeparts[1].isdigit() and \\\n len(timeparts[0]) <= 2 and len(timeparts[1]) <= 2:\n mins = int(timeparts[0])\n secs = int(timeparts[1])\n if 0 <= mins <= 59 and 0 <= secs <= 59:\n validvalue = \"{0:02d}:{1:02d}\".format(mins, secs)\n elif section_selected == \"price\":\n priceparts = newdata.split('.')\n if len(priceparts) == 2:\n if priceparts[0].isdigit() and priceparts[1].isdigit() and len(priceparts[1]) <= 2:\n dollar = int(priceparts[0])\n cents = int(priceparts[1])\n if dollar >= 0 and 0 <= cents <= 99:\n validvalue = float('.'.join([str(dollar), str(cents)]))\n elif len(priceparts) == 1:\n if priceparts[0].isdigit():\n if int(priceparts[0]) >= 0:\n validvalue = float(priceparts[0])\n elif section_selected == \"notes\":\n validvalue = newdata\n elif section_selected == \"buy_again\" or section_selected == \"on_hand\":\n ndatalower = newdata.lower()\n if ndatalower == \"no\" or ndatalower == \"yes\" or ndatalower == \"maybe\":\n if not(ndatalower == \"maybe\" and section_selected == \"on_hand\"):\n validvalue = newdata.capitalize()\n\n return validvalue",
"def _check(self):\n for molname in self.options.keys():\n for key in self.options[molname].keys():\n if key in [\"Ncopies\"]:\n try:\n self.options[molname][key]=int(self.options[molname][key])\n except:\n raise BaseException(\"Wrong type of the variable in molecule {} section {}\".format(molname,key))\n if key in [\"Cutoff\"]:\n try:\n self.options[molname][key]=float(self.options[molname][key])\n except:\n raise BaseException(\"Wrong type of the variable in molecule {} section {}\".format(molname,key))\n if key in [\"Addon\"]: # test the addon part and convert variables\n for item in self.options[molname][key]: # Iterate over all attachments\n if item is not None:\n # attachment point\n dtypes={\"attachment\":int}\n try:\n item[\"attachment\"]=int(item[\"attachment\"])\n except:\n raise BaseException(\"Wrong type of the variable in molecule {} section {}\".format(molname,key))\n # position\n #~ try:\n #~ print self.options[molname][key][\"position\"]\n #~ self.options[molname][key][\"position\"]=int(self.options[molname][key][\"position\"])\n #~ except:\n #~ raise BaseException(\"Wrong type of the variable in molecule {} section {}\".format(molname,key))",
"def check(options, rules = rules):\n s = [\"str\", \"unicode\"]\n for key in options:\n if not key.endswith(\" comment\"):\n if key in rules:\n c = rules[key]\n else:\n raise OptionKeyError(key)\n value = options[key]\n if c[0] == \"U\": continue\n elif c[0] == \"POT\":\n if not(((value & (value - 1)) == 0) and value):\n raise OptionPOTError(key)\n elif c[0] == \"R\":\n if value not in list(range(c[1], c[2]+1)):\n raise OptionRangeError(key, c[1], c[2]+1)\n elif c[0] == \"B\":\n if value not in list(range(0, 2)):\n #print (value)\n raise OptionRangeError(key, 0, 2)\n elif c[0] == \"N1+\":\n if value < 1:\n raise OptionRangeError(key, 1, float(\"inf\"))\n elif c[0] == \"N0+\":\n if value < 0:\n raise OptionRangeError(key, 0, float(\"inf\"))\n elif c[0] == \"FN0+\":\n if value < 0:\n raise OptionRangeError(key, 0, float(\"inf\"))\n elif c[0] == \"N-1+\":\n if value < -1:\n raise OptionRangeError(key, -1, float(\"inf\"))\n elif c[0] == \"S\":\n if value.__class__.__name__ not in s:\n raise OptionTypeError(key, \"text\")\n elif c[0] == \"Name\":check_name(value,key)\n\n elif c[0] == \"L\":\n if value.__class__.__name__ != \"list\":\n raise OptionTypeError(key, \"list\")\n\n elif c[0] == \"C\":\n if len(value) != 3:\n raise OptionError()\n if sum(value) < 1:\n raise OptionError()\n else:\n raise Exception(\"%s not valid rule type from %s\" % (c[0], key))",
"def checkDataParameters(self):\n while True:\n overideSamplesFlag = input(\"Default data parameters are:-\\n\\n Number of samples = %d\\n Number of replicates = %d\\n Number of QC replicates = %d\\n Number of solvent replicates = %d\\n File polarity mode = %s\\n Column type = %s\\n\\nChange these sample parameters (Y or N)? [N]: \" %\n (self.numberOfSamples, self.numberOfTechReps, self.numberOfQCReps, self.numberOfSolventReps, self.filePolarityMode, self.columnType)) or 'N'\n if overideSamplesFlag.upper() == 'N':\n break\n elif overideSamplesFlag.upper() == 'Y':\n self.setNumSamples()\n self.__setNumberOfTechReps__()\n self.__setNumberOfQCReps__()\n self.__setNumberOfSolventReps__()\n self.__setFilePolarityMode__()\n self.__setColumnType__()\n break\n else:\n print(\"\\nY or N required!\")",
"def get_user_input(choice_list,data_name):\r\n # ref https://stackoverflow.com/questions/58449700/how-to-create-a-sub-program-that-takes-user-input\r\n\r\n input_num = 0\r\n\r\n while True:\r\n # print out the options\r\n for i in range(len(choice_list)):\r\n print(str(i+1)+\":\", choice_list[i])\r\n # try to get the user to select an option\r\n try:\r\n input_num = int(input(\"Enter the number that represents the {0}:\".format(data_name)))\r\n if input_num in range(1, len(choice_list)+1):\r\n return_value = choice_list[input_num-1]\r\n print('Great, you have choosen the ' + data_name + \": \" + return_value + '\\n')\r\n return return_value\r\n else:\r\n print(\"invalid choice, please try again\")\r\n except ValueError:\r\n print('Thats not a valid number please try again')\r\n continue",
"def control_opt(self):\n\n\n if self.run_opt['refine']:\n self.run_opt['relaunch']=1\n \n #check value for 'madweight_main'\n for i in range(3,9)+[-1,-3]:\n if self.run_opt[num_to_tag[i]]==1:\n self.run_opt['madweight_main']=1\n break\n\n if self.run_opt['relaunch']==1:\n self.run_opt['control']=1",
"def __ui_choose_statistics(self):\n print(\"Please choose one statistic from below:\\n\"\n \" 1. Find all activities for a given date, in the order of their start time\\n\"\n \" 2. Check the availability of the upcoming days\\n\"\n \" 3. Find all the activities performed together with a certain person\\n\")\n user_choice = input(\"Type your option: \").strip()\n print(\"\")\n if user_choice == \"1\":\n self.__ui_search_activities_by_date()\n elif user_choice == \"2\":\n self.__ui_find_busiest_days()\n elif user_choice == \"3\":\n self.__ui_find_activities_by_participant()\n else:\n print(\"Invalid option!\\n\")\n return",
"def __options(self):\n\t\ta = 1 if self.random else 0\n\t\tb = 2 if self.topoftheday else 0\n\t\tc = 4 if self.offline else 0\n\t\treturn a+b+c",
"def HR_Options(employee, payScale):\n menu = (\n\n '\\nOptions\\n'\n '\\t1)Get Employee\\n'\n '\\t2)Add Employee\\n'\n '\\t3)Delete Employee\\n'\n '\\t4)Update Employee Grade\\n'\n '\\t5)Time-Sheet'\n '\\t6)Salary_SLip\\n'\n '\\t7)Get All Employee'\n '\\t8)Quit\\n'\n 'Choose from above mentioned options'\n )\n\n while True:\n Option_choice = get_employee_input_int(menu)\n if Option_choice == 1:\n get_employee()\n elif Option_choice == 2:\n add_employee()\n elif Option_choice == 3:\n delete_employee()\n elif Option_choice == 4:\n update_employee(employee)\n elif Option_choice == 5:\n enter_time_sheet()\n elif Option_choice == 6:\n emp_salary_slip(payScale)\n elif Option_choice ==7:\n get_all_employee()\n elif Option_choice == 8:\n exit(0);\n else:\n print(\"Invalid Entry !!! Please choose Option between (1-6)\")\n continue\n return"
] | [
"0.6109273",
"0.5759657",
"0.5718883",
"0.56589204",
"0.564493",
"0.5580262",
"0.55578375",
"0.5543662",
"0.5488127",
"0.5485002",
"0.54364794",
"0.5422494",
"0.54208136",
"0.5390141",
"0.5380995",
"0.53581625",
"0.5320768",
"0.53116024",
"0.5275301",
"0.5272488",
"0.52625513",
"0.525746",
"0.52525675",
"0.52508205",
"0.52461696",
"0.5240808",
"0.5205579",
"0.5202308",
"0.519319",
"0.51863074"
] | 0.6790623 | 0 |
Function creates dictionary with manufacturers as keys and average durability as items. | def get_average_durability_by_manufacturers(table):
average_durability = {}
for i in range(len(table)):
table[i][4] = int(table[i][4])
manufacturers = [name[2] for name in table]
single_manufacturers = list(set(manufacturers))
for i in range(len(single_manufacturers)):
durability_sum = 0
count = 0
for j in range(len(manufacturers)):
if single_manufacturers[i] == manufacturers[j]:
count += 1
durability_sum += int(table[j][4])
average_durability[single_manufacturers[i]] = durability_sum / count
return average_durability | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def dictionary_of_metrics(items):\n\n 'Initialize dict'\n d = {}\n\n # Add 'mean' key to the dict with the value of the mean calculate by using\n # np.mean rounded to 2 decimal places\n d['mean'] = round(np.mean(items), 2)\n\n # Add 'median' key to the dict with the value of the median calculate by\n # using np.median rounded to 2 decimal places\n d['median'] = round(np.median(items), 2)\n\n # Add 'var' key to the dict with the value of the varience calculate by\n # using np.var rounded to 2 decimal places\n d['var'] = round(np.var(items, ddof=1), 2)\n\n # Add 'std' key to the dict with the value of the standard deviation\n # calculate by using np.std to 2 decimal places\n d['std'] = round(np.std(items, ddof=1), 2)\n\n # Add 'min' key to the dict with the value of the minimum calculate by\n # using np.min to 2 decimal places\n d['min'] = round(np.min(items), 2)\n\n # Add 'max' key to the dict with the value of the maximum calculate by\n # using np.max to 2 decimal places\n d['max'] = round(np.max(items), 2)\n\n # returns dictionary, d\n return d",
"def dictionary_of_metrics(items):\n total = 0\n count = 0\n for value in items:\n total = total + value\n count = count + 1\n the_mean = round(total / count, 2)\n sorted_items = sorted(items)\n if count % 2 == 1:\n the_median = sorted_items[int(round(count+1)/2-1)]\n else:\n lower_median = sorted_items[int(round(count/2-1))]\n upper_median = sorted_items[int(round(count/2))]\n the_median = (lower_median + upper_median) / 2\n sum_of_sqz = 0 # Calculate Sum of squares for Varience\n for j in items:\n sqrz_calc = (j - the_mean)**2\n sum_of_sqz = sum_of_sqz + sqrz_calc\n the_varience = round(sum_of_sqz / (count - 1), 2)\n the_standard_dev = round((the_varience)**(1/2), 2)\n the_min = sorted_items[0]\n the_max = sorted_items[count - 1]\n dict = {\n 'mean': the_mean,\n 'median': the_median,\n 'var': the_varience,\n 'std': the_standard_dev,\n 'min': the_min,\n 'max': the_max\n }\n return dict",
"def dictionary_of_metrics(items):\n \n n = len(items)\n average = round(np.mean(items), 2)\n median = round(np.median(items), 2)\n variance = round((sum((items-np.mean(items))**2))/(n-1), 2)\n standard_dev = round(((sum((items-np.mean(items))**2))/(n-1))**(1/2), 2)\n minimum = round(min(items), 2)\n maximum = round(max(items), 2)\n \n return {'mean':average,'median':median,'var':variance,'std':standard_dev,'min':minimum,'max':maximum}\n pass",
"def mpg_by_make(self):\n ## create reference dict and aggregated dict\n reference_mpgs = defaultdict(list)\n make_avg_mpgs = defaultdict(str)\n ## loop through the data and add to both dicts\n for auto in self.data:\n ## get the year\n the_make = auto.make\n ## maintain a list of mpgs for each key=make\n reference_mpgs[the_make].append(auto.mpg)\n ## update the cumulative mpg as we read auto objects\n make_avg_mpgs[the_make] = sum(reference_mpgs[the_make]) / len(reference_mpgs[the_make])\n return make_avg_mpgs",
"def get_average_by_manufacturer(table, manufacturer):\n games_sum = 0\n games_occurance = 0\n for item in table:\n if item[2] == manufacturer:\n games_sum += int(item[4])\n games_occurance += 1\n\n average_amount = games_sum / games_occurance\n\n return average_amount",
"def get_counts_by_manufacturers(table):\n manufacturers_dict = {}\n for item in table:\n try:\n if item[2]:\n try:\n if item[2] in manufacturers_dict.keys():\n manufacturers_dict[item[2]] += 1\n else:\n manufacturers_dict[item[2]] = 1\n except IndexError:\n pass\n else:\n raise ValueError\n except ValueError:\n pass\n\n return manufacturers_dict",
"def createdictionary(bpm, extremes, duration, numbeats, time_beats):\n dict = {}\n dict[\"mean_hr_bpm\"] = bpm\n dict[\"voltage_extremes\"] = extremes\n dict[\"duration\"] = duration\n dict[\"num_beats\"] = numbeats\n dict[\"beats\"] = time_beats\n return dict",
"def dictionary_of_metrics(items):\n \n np_list = np.array(items) #create an array of list to use numpy functions on list\n metric_dict = {'mean': np.mean(np_list).round(2),\n 'median': np.median(np_list).round(2),\n 'var': np.var(np_list, ddof=1).round(2),\n 'std': np.std(np_list, ddof=1).round(2),\n 'min': np.min(np_list).round(2),\n 'max': np.max(np_list).round(2),} #create a dictionary that calculates the five metrics\n \n return metric_dict #return result as a dictionary",
"def get_averages(self):\t\n\t\t\n\t\taverages = {}\n\t\tfor subject in self.grades.iterkeys():\n\t\t\taverages[subject] = float(sum(self.grades[subject])) / len(self.grades[subject])\n\t\treturn averages",
"def calculate_averages(data):\n def mean(item_key):\n all_items = [i[item_key] for i in data]\n return sum(all_items)/float(len(all_items))\n\n return {\n \"mean_error_count\": mean('error_count'),\n \"mean_success_count\": mean('success_count'),\n \"mean_mean_response_time\": mean('mean_respone_time'),\n \"mean_data_sent_mb\": mean('data_sent_mb'),\n }",
"def format_odometer(raw: list) -> dict:\n instruments: dict = {}\n for instrument in raw:\n instruments[instrument[\"type\"]] = instrument[\"value\"]\n if \"unit\" in instrument:\n instruments[instrument[\"type\"] + \"_unit\"] = instrument[\"unit\"]\n\n return instruments",
"def aggregate_results(self, results):\n result = dict()\n result['MAE'] = self.average_dict_items(results, 'MAE')\n result['MdAE'] = self.average_dict_items(results, 'MdAE')\n result['RMSE'] = self.average_dict_items(results, 'RMSE')\n result['SMAPE'] = self.average_dict_items(results, 'SMAPE')\n result['num_values'] = self.average_dict_items(results, 'num_values')\n return result",
"def initDictionary(bands):\r\n for x in bands:\r\n d[\"{}\".format(x)] = {ProdCost: [], AlbumSales: []}",
"def get_average_by_manufacturer(table, manufacturer):\n games = 0\n manufacturer_apperance = 0\n\n for i in range(len(table)):\n try:\n if manufacturer.lower() == table[i][2].lower():\n games += int(table[i][-1])\n manufacturer_apperance += 1\n except (IndexError, ValueError):\n pass\n\n try:\n avrg_games_by_manufacturer = games / manufacturer_apperance\n except ZeroDivisionError as err:\n ui.print_error_message(\"No entry with that manufacturer\")\n\n avrg_games_by_manufacturer = round(avrg_games_by_manufacturer, 2)\n\n return avrg_games_by_manufacturer",
"def get_counts_by_manufacturers(table):\n manufacturers = []\n for item in table:\n if item[2] not in manufacturers:\n manufacturers.append(item[2])\n\n manufacturers_games = {}\n\n for record in manufacturers:\n games_counter = 0\n for item in table:\n if item[2] == record:\n games_counter += 1\n manufacturers_games[record] = games_counter\n\n return manufacturers_games",
"def dict_species_sums(mech):\n if mech == \"racm_esrl_vcp\":\n sum_dict = {}\n # Arrays for different gasses and pm groupings\n sum_dict.update(\n {\n \"noy_gas\": [\n \"hno3\",\n \"no\",\n \"no2\",\n \"no3\",\n \"pan\",\n \"tpan\",\n \"hono\",\n \"hno4\",\n \"onit\",\n \"n2o5\",\n \"ison\",\n \"nald\",\n \"mpan\",\n ]\n }\n )\n sum_dict.update({\"noy_gas_weight\": [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1]})\n sum_dict.update(\n {\"noy_aer\": [\"no3ai\", \"no3aj\"]}\n ) # Need to confirm here if there is a size cutoff for noy obs?\n sum_dict.update({\"nox\": [\"no\", \"no2\"]})\n sum_dict.update({\"pm25_cl\": [\"clai\", \"claj\"]})\n sum_dict.update({\"pm25_cl_weight\": [1, 1]})\n sum_dict.update({\"pm25_ec\": [\"eci\", \"ecj\"]})\n sum_dict.update({\"pm25_ec_weight\": [1, 1]})\n sum_dict.update({\"pm25_na\": [\"naai\", \"naaj\"]})\n sum_dict.update({\"pm25_na_weight\": [1, 1]})\n sum_dict.update({\"pm25_nh4\": [\"nh4ai\", \"nh4aj\"]})\n sum_dict.update({\"pm25_nh4_weight\": [1, 1]})\n sum_dict.update({\"pm25_no3\": [\"no3ai\", \"no3aj\"]})\n sum_dict.update({\"pm25_no3_weight\": [1, 1]})\n sum_dict.update({\"pm25_so4\": [\"so4ai\", \"so4aj\"]})\n sum_dict.update({\"pm25_so4_weight\": [1, 1]})\n sum_dict.update(\n {\n \"pm25_om\": [\n \"asoa1i\",\n \"asoa1j\",\n \"asoa2i\",\n \"asoa2j\",\n \"asoa3i\",\n \"asoa3j\",\n \"asoa4i\",\n \"asoa4j\",\n \"bsoa1i\",\n \"bsoa1j\",\n \"bsoa2i\",\n \"bsoa2j\",\n \"bsoa3i\",\n \"bsoa3j\",\n \"bsoa4i\",\n \"bsoa4j\",\n \"orgpai\",\n \"orgpaj\",\n ]\n }\n )\n elif mech == \"redhc\":\n sum_dict = {}\n # Arrays for different gasses and pm groupings\n sum_dict.update({\"noy_gas\": [\"hno3\", \"no\", \"no2\", \"no3\", \"pan\", \"ho2no2\", \"onit\", \"n2o5\"]})\n sum_dict.update({\"noy_gas_weight\": [1, 1, 1, 1, 1, 1, 1, 2]})\n sum_dict.update(\n {\"noy_aer\": [\"no3ai\", \"no3aj\"]}\n ) # Need to confirm here if there is a size cutoff for noy obs?\n sum_dict.update({\"nox\": [\"no\", \"no2\"]})\n sum_dict.update({\"pm25_cl\": [\"clai\", \"claj\"]})\n sum_dict.update({\"pm25_cl_weight\": [1, 1]})\n sum_dict.update({\"pm25_ec\": [\"eci\", \"ecj\"]})\n sum_dict.update({\"pm25_ec_weight\": [1, 1]})\n sum_dict.update({\"pm25_na\": [\"naai\", \"naaj\"]})\n sum_dict.update({\"pm25_na_weight\": [1, 1]})\n sum_dict.update({\"pm25_nh4\": [\"nh4ai\", \"nh4aj\"]})\n sum_dict.update({\"pm25_nh4_weight\": [1, 1]})\n sum_dict.update({\"pm25_no3\": [\"no3ai\", \"no3aj\"]})\n sum_dict.update({\"pm25_no3_weight\": [1, 1]})\n sum_dict.update({\"pm25_so4\": [\"so4ai\", \"so4aj\"]})\n sum_dict.update({\"pm25_so4_weight\": [1, 1]})\n sum_dict.update(\n {\n \"pm25_om\": [\n \"asoa0j\",\n \"asoa0i\",\n \"asoa1i\",\n \"asoa1j\",\n \"asoa2i\",\n \"asoa2j\",\n \"asoa3i\",\n \"asoa3j\",\n \"bsoa1i\",\n \"bsoa1j\",\n \"bsoa2i\",\n \"bsoa2j\",\n \"bsoa3i\",\n \"bsoa3j\",\n \"poa0j\",\n \"poa0i\",\n \"poa1j\",\n \"poa1i\",\n \"poa2j\",\n \"poa2i\",\n \"poa3j\",\n \"poa3i\",\n ]\n }\n )\n\n else:\n raise NotImplementedError(\"Mechanism not supported, update _wrfchem_mm.py file in MONETIO\")\n\n return sum_dict",
"def rank_by_manufacturer(table):\n\n manufacturers_counts = {}\n product_id_index = 3\n amount_sold_index = 4\n id_index = 0\n manufacturer_index = 2\n\n store_table = store.get_table()\n store.check_table(store_table)\n\n for record in table:\n product_id = record[product_id_index]\n amount_sold = record[amount_sold_index]\n for game in store_table:\n game_id = game[id_index]\n manufacturer = game[manufacturer_index]\n if product_id == game_id:\n if manufacturer in manufacturers_counts:\n manufacturers_counts[manufacturer] += int(amount_sold)\n else:\n manufacturers_counts[manufacturer] = int(amount_sold)\n\n return manufacturers_counts",
"def format_odometer(raw) -> dict:\r\n instruments: dict = {}\r\n for instrument in raw:\r\n instruments[instrument[\"type\"]] = instrument[\"value\"]\r\n if \"unit\" in instrument:\r\n instruments[instrument[\"type\"] + \"_unit\"] = instrument[\"unit\"]\r\n\r\n return instruments",
"def get_average_emission_factors(prefix: str, year: int):\n genavg = pd.read_csv(\n outputs_folder(f\"{prefix}annual_generation_averages_by_fuel_{year}.csv\"),\n index_col=\"fuel_category\",\n )\n efs = {}\n for pol in POLLUTANTS:\n efs[pol] = {}\n for adjustment in ADJUSTMENTS:\n efs[pol][adjustment] = {}\n for fuel in SRC:\n column = get_rate_column(pol, adjustment, generated=True)\n if FUEL_TYPE_MAP[fuel] not in genavg.index:\n logger.warning(\n f\"fuel {FUEL_TYPE_MAP[fuel]} not found in file annual_generation_averages_by_fuel_{year}.csv, using average\"\n )\n efs[pol][adjustment][fuel] = genavg.loc[\"total\", column]\n else:\n efs[pol][adjustment][fuel] = genavg.loc[FUEL_TYPE_MAP[fuel], column]\n return efs",
"def compute_average_metrics(meters):\n metrics = {m: vs.avg for m, vs in meters.items()}\n metrics = {\n m: v if isinstance(v, float) else v.item()\n for m, v in metrics.items()\n }\n return metrics",
"def _agg_by_mean(self):\n return self._data_grouped_by_manufacturer.agg('mean')[['car_value']]",
"def dictagdur(kind, fname):\n\n with open(fname, 'r') as g:\n g.next()\n g.next()\n m = g.next()\n startdict = agline(m)\n genold = startdict['gen']\n\n f = open(fname)\n f.next()\n f.next()\n d = {}\n y = '1'\n nb = []\n for l in f:\n adict = agline(l)\n kdur = kind + 'dur'\n gen = adict['gen']\n well = adict['well']\n\n if adict['gen'] not in d:\n d[gen] = []\n \n if gen != genold:\n d[genold].append(sum(nb))\n nb = []\n else: \n if adict['well'] != y:\n #print(sum(nb))\n d[gen].append(sum(nb))\n nb = []\n \n if adict[kdur] == '':\n nb.append(0)\n elif int(adict[kdur]) >= 0:\n nb.append(int(adict[kdur]))\n elif adict[ks] == '-':\n pass\n \n\n y = adict['well']\n genold = adict['gen']\n \n d[gen].append(sum(nb))\n\n return(d)",
"def compute_average_separability_score(self) -> Dict:\n avg_sep_score = {}\n for class_pair_key, class_pair_val in self.separability_scores.items():\n avg_sep_score[class_pair_key] = np.mean(np.array([val for _, val in class_pair_val.items()]))\n avg_sep_score['agg_with_risk'] = sum(\n np.array([val for _, val in avg_sep_score.items()]) *\n RISK\n ) \n avg_sep_score['agg'] = sum([val for key, val in avg_sep_score.items() if type(key)==int]) \n return avg_sep_score",
"def compute_average_metrics(meters):\n metrics = {m: vs.avg for m, vs in meters.items()}\n metrics = {\n m: float(v) if isinstance(v, float) or isinstance(v, int) else v.item()\n for m, v in metrics.items()\n }\n return metrics",
"def recommendations_to_dd(recommendations):\n res = defaultdict(lambda: 0.0)\n for rec in recommendations:\n res[rec.product] = rec.rating\n return res",
"def createDict( self ):\n d = {}\n devTup = ( 'endcap', 'comp', 'shutter','397intensity' )\n for dev in devTup:\n d[dev] = {'devChannels':{}}\n endcap = ( ( 1, 1 ), ( 2, 0 ) )\n comp = ( ( 1, 4 ), ( 2, 2 ), ( 'common', 3 ) )\n shutter = ( ( 1, 5 ), ( 2, 6 ), ( 3, 7 ) )\n intensity397 = (('397intensity',8),)\n chanTup = ( endcap, comp, shutter ,intensity397 )\n for dev, value in zip( devTup, chanTup ):\n for chanPair in value:\n d[dev]['devChannels'][chanPair[0]] = {'value':None, 'channel':chanPair[1]}\n ecRange = ( 0.0, 40.0 )\n compRange = ( -40.0, 40.0 )\n shutterRange = ( 0.0, 5.0 )\n intensity397Range = (0.0,2500.0)\n rangeTup = ( ecRange, compRange, shutterRange, intensity397Range )\n for dev, value in zip( devTup, rangeTup ): d[dev]['range'] = value\n self.dcDict = d",
"def process_medians(helst, shelst, authlst):\n d = {\"he\": [], \"she\": [], \"book\": []}\n for num in range(len(helst)):\n if helst[num] > 0 and shelst[num] > 0:\n res = helst[num] - shelst[num]\n if res >= 0:\n d[\"he\"].append(helst[num] / shelst[num])\n d[\"she\"].append(0)\n d[\"book\"].append(authlst[num])\n else:\n d[\"he\"].append(0)\n d[\"she\"].append(shelst[num] / helst[num])\n d[\"book\"].append(authlst[num])\n else:\n if helst == 0:\n print(\"ERR: no MALE values: \" + authlst[num])\n if shelst == 0:\n print(\"ERR: no FEMALE values: \" + authlst[num])\n return d",
"def compute_metrics(meters):\n metrics = {m: vs.avg for m, vs in meters.items()}\n metrics = {m: v if isinstance(v, float) else v.item() for m, v in metrics.items()}\n return metrics",
"def _make_analysis_dict(self, an):\n\n ig = an.isotope_group\n try:\n spec = an.spec\n d = {'identifier': spec.identifier,\n 'aliquot': spec.aliquot,\n 'step': spec.step,\n 'analysis_type': spec.analysis_type,\n 'runid': spec.runid,\n 'uuid': spec.uuid,\n 'timestamp': time.mktime(spec.analysis_timestamp.timetuple())}\n\n spec_dict = an.persister.per_spec.spec_dict\n defl_dict = an.persister.per_spec.defl_dict\n\n for v in self._values:\n if v.endswith('_deflection'):\n try:\n k, _ = v.split('_')\n d[v] = defl_dict[k]\n continue\n except KeyError:\n pass\n else:\n try:\n d[v] = spec_dict[v]\n except KeyError:\n vv = ig.get_value(v)\n d[v] = nominal_value(vv)\n d['{}_err'.format(v)] = std_dev(vv)\n\n except BaseException, e:\n self.warning('failed making system health analysis dict. error=\"{}\"'.format(e))\n\n return d",
"def gen_dict():\n lines = [line for line in csv.reader(open(__ppath__ + \"/data/occupations.csv\"))] # uses a csv.reader to parse the file, converts the generic iterable to a list\n lines = [(line[0],float(line[1])) for line in lines[1:-2]]# removes the column names and \"Total\" row, re-expresses as a list of tuples to enable dictionary conversion\n lines.append((\"Unemployed\",0.2)) # accounts for missing 0.2% of jobs\n return dict(lines) # converts to dictionary"
] | [
"0.62205356",
"0.6133951",
"0.60828346",
"0.5995681",
"0.59609073",
"0.5912523",
"0.5870187",
"0.585864",
"0.58151513",
"0.578834",
"0.5743187",
"0.5695257",
"0.5681986",
"0.566855",
"0.56393546",
"0.5633156",
"0.56207067",
"0.56056833",
"0.5551199",
"0.5515151",
"0.55144024",
"0.5493666",
"0.54715437",
"0.54571056",
"0.5453216",
"0.54300374",
"0.53766066",
"0.53627396",
"0.5342441",
"0.53328955"
] | 0.76331353 | 0 |
>>> rabbits(5, 3) 19 | def rabbits(n, k):
prev, nxt = 1, 1
for _ in range(2, n):
prev, nxt = nxt, prev * k + nxt
return nxt | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def getrandbits(k: int) -> int:\n ...",
"def wabbits(n, k):\n a, b = 1, 1\n for i in range(3, n+1):\n a, b = b, a*k + b\n return b",
"def brc(x):\n N = len(x)\n y = np.zeros(N, dtype=complex)\n width = int(np.log2(N))\n for ii in np.arange(N):\n idx = '{:0{width}b}'.format(ii, width=width)\n y[ii] = x[int(idx[::-1],2)]#Reverse order of bits of integer ii\n return y",
"def _bits(num):\r\n return bin(int(num))[2:]",
"def bits(n):\n b = []\n while n:\n b = [n & 1] + b\n n >>= 1\n # add heading 0\n head = len(b) % 8\n if head != 0:\n b = [0] * (8 - head) + b\n return b",
"def nibbles(b):\n b = byte(b)\n return (b & 240) >> 4, b & 15",
"def bitlist(n):\n return [n >> i & 1 for i in range(7,-1,-1)]",
"def binbits(x, n):\n bits = bin(x).split('b')[1]\n if len(bits) < n:\n ans = '0' * (n - len(bits)) + bits\n else:\n ans = bits\n\n return ans",
"def _round_bits(n: int, radix_bits: int) -> int:\n return (n + radix_bits - 1) // radix_bits",
"def bsr(value, bits):\n minint = -2147483648\n if bits == 0:\n return value\n elif bits == 31:\n if value & minint:\n return 1\n else:\n return 0\n elif bits < 0 or bits > 31:\n raise ValueError('bad shift count')\n tmp = (value & 0x7FFFFFFE) // 2**bits\n if (value & minint):\n return (tmp | (0x40000000 // 2**(bits-1)))\n else:\n return tmp",
"def bit_length(self, ???):",
"def numbits(n):\n return int(math.ceil(math.log(n, 2)))",
"def bits(n):\n\n # Create a list of the first 1,000 binary numbers\n binary_list = reverse_binary_list()\n\n # Start by calculating number of 1's for n\n n_ones = num_of_ones(n, binary_list)\n\n # Calculate number of 1's for next value\n next_ones = 0\n while n_ones != next_ones:\n n = n + 1\n next_ones = num_of_ones(n, binary_list)\n\n return(n)",
"def r1(x, n, max_size=32):\n return (x << n) % (2 << (max_size - 1)) + (x >> (max_size - n))",
"def _get_binary(value, bits):\n\n # http://www.daniweb.com/code/snippet216539.html\n return ''.join([str((value >> y) & 1) for y in range(bits - 1, -1, -1)])",
"def get_bin(x, n=0):\n return format(x, 'b').zfill(n)",
"def test_bit_rscan(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 32, 8, value)]\n\n expected_value = 7\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def bits(a,m):\r\n if isinstance(a, int):\r\n res = [None]*m\r\n for i in range(m):\r\n res[i] = a & 1\r\n a >>= 1\r\n else:\r\n res = []\r\n from Compiler.types import regint, cint\r\n while m > 0:\r\n aa = regint()\r\n convmodp(aa, a, bitlength=0)\r\n res += [cint(x) for x in aa.bit_decompose(min(64, m))]\r\n m -= 64\r\n if m > 0:\r\n aa = cint()\r\n shrci(aa, a, 64)\r\n a = aa\r\n return res",
"def answer(x):\r\n total = sum(x)\r\n length = len(x)\r\n # Find out how many are left over when distributing niavely.\r\n div, mod = divmod(total, length)\r\n # Because of the variable size of the list, the remainder\r\n # might be greater than the length of the list.\r\n # I just realized this is unnecessary.\r\n while mod > length:\r\n div += length\r\n mod -= length\r\n # Create a new list the size of x with the base number of rabbits.\r\n result = [div] * length\r\n # Distribute the leftovers from earlier across the list.\r\n for i in xrange(mod):\r\n result[i] += 1\r\n # Return the most common element.\r\n return most_common(result), result",
"def test_from_binary_bits_style(self):\n self.assertResult('[0001]', b4('[0001]'))",
"def bit_in_place(x, n):\n return (x & 2**n)",
"def binning():\n def r(x):\n return 1 << (x & 7)\n\n def w(x):\n return 0x11 * (x >> 1)\n return r, w",
"def bintogray(x: int) -> int:\n assert x >= 0\n return x ^ (x >> 1)",
"def getrandbits(self, k):\n if self.randbits is None: # initialize the cache\n self.randbits = int_from_hash(self.nextRandom())\n self.randbits_remaining = HASHLEN\n while k > self.randbits_remaining: # pre-pend more random bits\n # accounts for leading 0s\n self.randbits = (int_from_hash(self.nextRandom()) << \\\n self.randbits_remaining | self.randbits)\n self.randbits_remaining = self.randbits_remaining + HASHLEN\n val = (self.randbits & int(2**k-1)) # harvest least significant k bits\n self.randbits_remaining = self.randbits_remaining - k\n self.randbits = self.randbits >> k # discard the k harvested bits\n return val",
"def millerRabin(n, r):\n\n if n < 2: # 0, 1 and negative numbers are considered not prime\n return False\n\n ############ CALCULATING d AND i #########\n # find the values d and i s.t. 2^i * d = n - 1\n d = n - 1\n i = 0\n\n while not d & 1:\n d >>= 1\n i += 1\n\n ############ TEST ONE WITNESS FOR EACH MR-ROUND #########\n for _ in range(r):\n\n # get random witness\n w = secrets.SystemRandom().randrange(2, n - 1)\n\n # use power-remainder method\n z = powerRemainder(w, d, n)\n\n # if z is 1 or n -1 then w is not a witness for n being a composite number\n if z not in (1, n - 1):\n\n # check no j s.t. (w^(2^j)) ^ d = -1 (mod n)\n for j in range(i):\n\n # get next z\n z = powerRemainder(w, 2 ** j * d, n)\n\n if z == 1: # n is definitely composite\n return False # return False\n elif z == n -1 : # n is prime or the witness is a strong liar\n break # break to next witness\n\n else:\n return False # if the inner loop didn't break, n is composite\n\n return True # if no witness can be found for n being composite, it is a probable prime",
"def bitset(x, n, bv):\n if bv==1:\n x |= 2**n\n else:\n x ^= bit_in_place(x, n)\n return(x)",
"def binary_encoding(k: int, bit_number: int=10) -> List[int]:\n return [k>>i & 1 for i in range(bit_number)]",
"def get_base_2(n):\n return str(bin(int(n))).removeprefix('0b')",
"def binom(n, r):\n return factorial(n) // ((factorial(r) * factorial(n - r)))",
"def AsBBit(x, B):\n assert x <= 1, \"it's a probability\"\n M = 2**B\n scaled_x = x*M\n rem = scaled_x - np.floor(scaled_x)\n\n if (x == 1):\n x_bin = M - 1\n elif (scaled_x > M - 2):\n # in this range, things are ugly\n # because we reserve 'all ones' as 'always go left'\n r = np.random.rand()\n if (2 * r < scaled_x - M - 2):\n x_bin = M - 2\n else:\n x_bin = M - 1\n \n else:\n r = np.random.rand()\n if (r < rem):\n x_bin = np.floor(scaled_x)\n else:\n x_bin = np.floor(scaled_x) + 1\n\n assert x_bin < M, \"exceeded bit width\"\n return x_bin"
] | [
"0.69049716",
"0.6712664",
"0.6257662",
"0.61311364",
"0.6127669",
"0.6073873",
"0.60225457",
"0.5979457",
"0.5917172",
"0.58916944",
"0.5890116",
"0.58509326",
"0.5836016",
"0.5782625",
"0.5778634",
"0.5744973",
"0.57054263",
"0.56547755",
"0.56413364",
"0.5639942",
"0.56231207",
"0.56215864",
"0.5618187",
"0.5617067",
"0.5603309",
"0.5602822",
"0.55997324",
"0.5591776",
"0.5584325",
"0.55787015"
] | 0.73654777 | 0 |
Regular users shouldn't be able to see NOT_AVAILABLE partners in the listview. | def test_visibility_of_not_available_2(self):
partner = PartnerFactory(status=Partner.NOT_AVAILABLE)
list_url = reverse('partners:list')
editor = EditorFactory()
request = RequestFactory().get(list_url)
request.user = editor.user
response = PartnersListView.as_view()(request)
self.assertNotContains(response, partner.get_absolute_url()) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_visibility_of_not_available_4(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n list_url = reverse('partners:list')\n\n editor = EditorFactory()\n editor.user.is_staff = True\n editor.user.save()\n\n request = RequestFactory().get(list_url)\n request.user = editor.user\n response = PartnersListView.as_view()(request)\n\n self.assertContains(response, partner.get_absolute_url())",
"def test_visibility_of_not_available_3(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n detail_url = partner.get_absolute_url()\n\n editor = EditorFactory()\n editor.user.is_staff = True\n editor.user.save()\n\n request = RequestFactory().get(detail_url)\n request.user = editor.user\n\n # This should not raise Http404.\n response = PartnersDetailView.as_view()(request, pk=partner.pk)\n self.assertEqual(response.status_code, 200)",
"def test_visibility_of_not_available_1(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n detail_url = partner.get_absolute_url()\n\n editor = EditorFactory()\n\n request = RequestFactory().get(detail_url)\n request.user = editor.user\n with self.assertRaises(Http404):\n # We must explicitly pass kwargs to the view even though they are\n # implied by the URL.\n _ = PartnersDetailView.as_view()(request, pk=partner.pk)",
"def make_eligible(self):\n pass",
"def test_listing_from_wall_when_blocked_some_users(self):",
"def get_available_invitees(self):\n return User.objects.exclude(pk=self.request.user.pk)",
"def set_unavailable(self):\n self[\"available\"] = False",
"def setup_whitelisted_section_with_unrestricted():\n setup_unrelated_section_with_unrestricted()\n\n # whitelist user to the course\n cs61a = Course.objects.get(name=\"CS61A\")\n user = User.objects.get(username=\"demo_user\")\n cs61a.whitelist.add(user)",
"def raise_not_editable(self, viewer):\n if not self.id or viewer.has_perm(\"bookwyrm.create_invites\"):\n return\n raise PermissionDenied()",
"def get_everyone_denied(self):",
"def get_queryset(self):\n user = self.request.user\n if not (user.is_authenticated and user.check_permstring(\"builders\")):\n raise Http404(\"Not staff\")\n return super(IncompleteRosterListView, self).get_queryset()",
"def test_requester_is_no_admin(self) -> None:\n\n channel = self.make_request(\n \"GET\",\n self.url,\n access_token=self.other_user_tok,\n )\n\n self.assertEqual(403, channel.code, msg=channel.json_body)\n self.assertEqual(Codes.FORBIDDEN, channel.json_body[\"errcode\"])",
"def test_requester_is_no_admin(self) -> None:\n\n channel = self.make_request(\n \"GET\",\n self.url,\n access_token=self.other_user_tok,\n )\n\n self.assertEqual(403, channel.code, msg=channel.json_body)\n self.assertEqual(Codes.FORBIDDEN, channel.json_body[\"errcode\"])",
"def get_shopping_partners(request):\n try:\n shopping_partners = Partner.objects.get(current_user=request.user)\n shopping_partners_list = shopping_partners.partners.all()\n except:\n shopping_partners = []\n shopping_partners_list = []\n\n return shopping_partners_list",
"def unavailable(self):\r\n\r\n self._available = False\r\n self.owner.trigger(\"on_unavailable\")",
"def admin_non_activated(request):\r\n ret = []\r\n res = UserMgr.non_activated_account()\r\n if res:\r\n ret = [u.username for u in res]\r\n\r\n return _api_response(request, {\r\n 'count': len(ret),\r\n 'status': True,\r\n 'data': ret,\r\n })",
"def test_do_not_show_bookings_from_unselected_facility(self):\n booking = create_test_booking(\n self.user, self.first_day, 8, facility='g')\n\n response = self.client.get(\n reverse('bookings', kwargs={'facility': 'h'}))\n\n context = response.context\n bookings = context[\"bookings\"]\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(context[\"quota\"], settings.BOOKINGS_QUOTA - 1)\n\n for week in bookings:\n for row in week.rows:\n for block in row.blocks:\n self.assertEqual(type(block), BlockAvailable)",
"def test_visible_blacklisted_with_string(self):\n email = '[email protected]'\n self.feature_test.set_percentage(0)\n self.feature_test.add_to_blacklist(email)\n self.assertFalse(self.feature_test.is_visible(email))",
"def test_auth_private_unowned(self):\n self.do_visible(False, 'pattieblack', False, tenant='froggy')",
"def _client_allowed(self):\r\n client_ip = self._client_address[0]\r\n if not client_ip in self._settings.allowed_clients and \\\r\n not 'ALL' in self._settings.allowed_clients:\r\n self._send_content('Access from host %s forbidden.' % client_ip, 'text/html')\r\n return False\r\n return True",
"def test_visible_blacklisted(self):\n\n self.feature_test.set_percentage(100)\n self.feature_test.add_to_blacklist(3)\n self.assertFalse(self.feature_test.is_visible(3))",
"def test_extra_field_when_not_requested(self):\n self.client.login(username=self.admin_user.username, password='test')\n response = self.verify_response(params={\n 'all_blocks': True,\n 'requested_fields': ['course_visibility'],\n })\n self.verify_response_block_dict(response)\n for block_data in response.data['blocks'].values():\n assert 'other_course_settings' not in block_data\n\n self.assert_in_iff(\n 'course_visibility',\n block_data,\n block_data['type'] == 'course'\n )",
"def get_queryset(self):\n queryset = super().get_queryset()\n return queryset.available_for_user(self.request.user)",
"def allow_egap_admins(queryset, request):\n if hasattr(request, 'user') and not waffle.flag_is_active(request, EGAP_ADMINS):\n return queryset.exclude(name='EGAP Registration')\n return queryset",
"def not_assignable(self):\n return self.unavailable + self.occupied",
"def get_choices_new_protected():\n ret = []\n ret.append( (1, _(u'Nur Community-Mitglieder dürfen neue Beiträge leisten')) )\n ret.append( (-1, _(u'Offener Zugang')) )\n return ret",
"def test_auth_public_unowned(self):\n self.do_visible(True, 'pattieblack', True, tenant='froggy')",
"def is_eligible(self) -> Optional[bool]:\n return pulumi.get(self, \"is_eligible\")",
"def isUnlisted(self):\n return self.f1 is 'u'",
"def is_unrestricted(self):\n raise exceptions.NotImplementedError()"
] | [
"0.76659733",
"0.6714052",
"0.6487925",
"0.62944084",
"0.5986907",
"0.5925319",
"0.58944327",
"0.5888781",
"0.58874387",
"0.57836556",
"0.5779557",
"0.57709605",
"0.57709605",
"0.57578605",
"0.5687641",
"0.566961",
"0.56255096",
"0.5606502",
"0.5585355",
"0.55832815",
"0.5574585",
"0.5567546",
"0.5557121",
"0.55274004",
"0.54861736",
"0.54861665",
"0.5451923",
"0.5432049",
"0.5412811",
"0.54060125"
] | 0.7699841 | 0 |
Staff users should see NOT_AVAILABLE partner pages in the list view. | def test_visibility_of_not_available_4(self):
partner = PartnerFactory(status=Partner.NOT_AVAILABLE)
list_url = reverse('partners:list')
editor = EditorFactory()
editor.user.is_staff = True
editor.user.save()
request = RequestFactory().get(list_url)
request.user = editor.user
response = PartnersListView.as_view()(request)
self.assertContains(response, partner.get_absolute_url()) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_visibility_of_not_available_2(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n list_url = reverse('partners:list')\n\n editor = EditorFactory()\n\n request = RequestFactory().get(list_url)\n request.user = editor.user\n response = PartnersListView.as_view()(request)\n\n self.assertNotContains(response, partner.get_absolute_url())",
"def test_visibility_of_not_available_3(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n detail_url = partner.get_absolute_url()\n\n editor = EditorFactory()\n editor.user.is_staff = True\n editor.user.save()\n\n request = RequestFactory().get(detail_url)\n request.user = editor.user\n\n # This should not raise Http404.\n response = PartnersDetailView.as_view()(request, pk=partner.pk)\n self.assertEqual(response.status_code, 200)",
"def test_visibility_of_not_available_1(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n detail_url = partner.get_absolute_url()\n\n editor = EditorFactory()\n\n request = RequestFactory().get(detail_url)\n request.user = editor.user\n with self.assertRaises(Http404):\n # We must explicitly pass kwargs to the view even though they are\n # implied by the URL.\n _ = PartnersDetailView.as_view()(request, pk=partner.pk)",
"def admin_non_activated(request):\r\n ret = []\r\n res = UserMgr.non_activated_account()\r\n if res:\r\n ret = [u.username for u in res]\r\n\r\n return _api_response(request, {\r\n 'count': len(ret),\r\n 'status': True,\r\n 'data': ret,\r\n })",
"def get_queryset(self):\n user = self.request.user\n if not (user.is_authenticated and user.check_permstring(\"builders\")):\n raise Http404(\"Not staff\")\n return super(IncompleteRosterListView, self).get_queryset()",
"def test_list_not_admin2(self):\n self.client.force_authenticate(user=self.user)\n\n response = self.client.get(\n reverse('retreat:waitqueuenotification-list'),\n format='json',\n )\n\n content = {\n 'count': 0,\n 'next': None,\n 'previous': None,\n 'results': [],\n }\n\n self.assertEqual(json.loads(response.content), content)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)",
"def test_instructor_page_access_nonstaff(self):\r\n self.login(self.enrolled_user)\r\n\r\n urls = [reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}),\r\n reverse('instructor_dashboard', kwargs={'course_id': self.test_course.id.to_deprecated_string()})]\r\n\r\n # Shouldn't be able to get to the instructor pages\r\n for url in urls:\r\n check_for_get_code(self, 404, url)",
"def test_10_admin_user_not_listed(self):\r\n self.register()\r\n res = self.app.get('/admin/users', follow_redirects=True)\r\n assert \"Manage Admin Users\" in res.data, res.data\r\n assert \"Current Users with Admin privileges\" not in res.data, res.data\r\n assert \"John\" not in res.data, res.data",
"def test_extra_field_when_not_requested(self):\n self.client.login(username=self.admin_user.username, password='test')\n response = self.verify_response(params={\n 'all_blocks': True,\n 'requested_fields': ['course_visibility'],\n })\n self.verify_response_block_dict(response)\n for block_data in response.data['blocks'].values():\n assert 'other_course_settings' not in block_data\n\n self.assert_in_iff(\n 'course_visibility',\n block_data,\n block_data['type'] == 'course'\n )",
"def test_unauthorized_user_like_field(self):\n response = self.client.get(reverse('lessons-detail', args=(1,)))\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertNotIn('like', response.data)",
"def test_detail_blocked_forbidden_even_if_contributor(self):\n self.login(self.user1)\n resp = self.client.get(self.get_url(self.c3.pk))\n self.assert404(resp)",
"def unavailable_for_editing(request):\n return render(request, 'SNP_Feature_View/unavailable_for_editing.html')",
"def test_do_not_show_bookings_from_unselected_facility(self):\n booking = create_test_booking(\n self.user, self.first_day, 8, facility='g')\n\n response = self.client.get(\n reverse('bookings', kwargs={'facility': 'h'}))\n\n context = response.context\n bookings = context[\"bookings\"]\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(context[\"quota\"], settings.BOOKINGS_QUOTA - 1)\n\n for week in bookings:\n for row in week.rows:\n for block in row.blocks:\n self.assertEqual(type(block), BlockAvailable)",
"def setup_whitelisted_section_with_unrestricted():\n setup_unrelated_section_with_unrestricted()\n\n # whitelist user to the course\n cs61a = Course.objects.get(name=\"CS61A\")\n user = User.objects.get(username=\"demo_user\")\n cs61a.whitelist.add(user)",
"def test_detail_not_contributor_forbidden(self):\n self.login(self.user1)\n resp = self.client.get(self.get_url(self.c2.pk))\n self.assert403(resp)",
"def test_list_users_without_permissions(self):\n self.client.force_authenticate(user=self.user)\n\n response = self.client.get(reverse('user-list'))\n\n content = {\n 'detail': 'You do not have permission to perform this action.'\n }\n self.assertEqual(json.loads(response.content), content)\n\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)",
"def get_available_invitees(self):\n return User.objects.exclude(pk=self.request.user.pk)",
"def test_visible_blacklisted(self):\n\n self.feature_test.set_percentage(100)\n self.feature_test.add_to_blacklist(3)\n self.assertFalse(self.feature_test.is_visible(3))",
"def test_render_data_no_staff(self):\n url = '{}?is_bigcourse=0'.format(reverse(\n 'completion_data_view', kwargs={\n 'course_id': self.course.id}))\n self.response = self.client.get(url)\n self.assertEqual(self.response.status_code, 404)",
"def test_listing_from_wall_when_blocked_some_users(self):",
"def partners(request):\n return render(request, 'ecosystem/partners.html', {'page': 'partners'})",
"def test002_league_commish_settings_no_membership(self):\n\t\tresponse = self.client.get(self.test_url, follow=True)\n\t\tself.assertFalse(is_on_page(response, 'League: league_name1'))\n\t\tself.assertTrue(is_on_page(response, 'Fantasy Web - Home'))",
"def _check_non_staff_light(self, course):\r\n urls = [reverse('about_course', kwargs={'course_id': course.id.to_deprecated_string()}),\r\n reverse('courses')]\r\n for url in urls:\r\n check_for_get_code(self, 200, url)",
"def view_init(self, cr, uid, fields, context=None):\n if context is None:\n context = {}\n model = context.get('active_model')\n model = self.pool.get(model)\n rec_ids = context and context.get('active_ids', [])\n for this in model.browse(cr, uid, rec_ids, context=context):\n if this.partner_id:\n raise osv.except_osv(_('Warning !'),\n _('A partner is already defined.'))",
"def _check_non_staff_dark(self, course):\r\n\r\n names = ['courseware', 'instructor_dashboard', 'progress']\r\n urls = self._reverse_urls(names, course)\r\n urls.extend([\r\n reverse('book', kwargs={'course_id': course.id.to_deprecated_string(),\r\n 'book_index': index})\r\n for index, book in enumerate(course.textbooks)\r\n ])\r\n for url in urls:\r\n check_for_get_code(self, 404, url)",
"def get_shopping_partners(request):\n try:\n shopping_partners = Partner.objects.get(current_user=request.user)\n shopping_partners_list = shopping_partners.partners.all()\n except:\n shopping_partners = []\n shopping_partners_list = []\n\n return shopping_partners_list",
"def get_queryset(self):\n queryset = super().get_queryset()\n return queryset.available_for_user(self.request.user)",
"def show_page_list_accessible():\r\n\tpage_list = Page.objects.filter(in_nav=1).order_by('order')\r\n\treturn {'page_list': page_list}",
"def test_no_commissions(self):\n response = self.client.get(reverse('tracker:index'))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"No active commissions.\")\n self.assertQuerysetEqual(response.context['active_commission_list'], [])",
"def test_show_private_lists_invalid(self):\n with self.client as c:\n with c.session_transaction() as sess:\n sess[CURR_USER_KEY] = self.user2.id\n \n res = c.get(\"/users/tester1/private-lists\")\n\n self.assertEqual(res.status_code, 302)"
] | [
"0.7749784",
"0.7010356",
"0.6788804",
"0.5911307",
"0.5898411",
"0.5891466",
"0.5821455",
"0.573191",
"0.56296486",
"0.56160283",
"0.5600137",
"0.5589843",
"0.55867755",
"0.5571438",
"0.5567003",
"0.55596405",
"0.5555837",
"0.55491287",
"0.55423224",
"0.55357367",
"0.5519836",
"0.5517601",
"0.54735374",
"0.5463769",
"0.5443318",
"0.5406775",
"0.5400584",
"0.54000825",
"0.5393561",
"0.53838325"
] | 0.7749647 | 1 |
The default manager should return AVAILABLE and WAITLIST partners, but not NOT_AVAILABLE. | def test_default_manager(self):
partner = PartnerFactory(status=Partner.AVAILABLE)
partner2 = PartnerFactory(status=Partner.NOT_AVAILABLE)
partner3 = PartnerFactory(status=Partner.WAITLIST)
all_partners = Partner.objects.all()
assert partner in all_partners
assert partner2 not in all_partners
assert partner3 in all_partners
# assertQuerysetEqual compares a queryset to a list of representations.
# Sigh.
self.assertQuerysetEqual(Partner.objects.all(),
map(repr, Partner.even_not_available.filter(
status__in=
[Partner.WAITLIST, Partner.AVAILABLE]))) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def available(self):\n\t\traise NotImplementedError",
"def test_visibility_of_not_available_2(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n list_url = reverse('partners:list')\n\n editor = EditorFactory()\n\n request = RequestFactory().get(list_url)\n request.user = editor.user\n response = PartnersListView.as_view()(request)\n\n self.assertNotContains(response, partner.get_absolute_url())",
"def test_available_for_none_included(self):\n\n s1 = self.factory.create(name=\"Suite1\")\n s2 = self.factory.create(name=\"Suite2\")\n\n self._do_test(\n -1,\n self.available_param,\n [self.get_exp_obj(s) for s in [s1, s2]],\n )",
"def test_visibility_of_not_available_4(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n list_url = reverse('partners:list')\n\n editor = EditorFactory()\n editor.user.is_staff = True\n editor.user.save()\n\n request = RequestFactory().get(list_url)\n request.user = editor.user\n response = PartnersListView.as_view()(request)\n\n self.assertContains(response, partner.get_absolute_url())",
"def test_choosingPerformerWhenNoPeersAndNoWorkers(self):\n self.checkPerformer(LocalPerformer)",
"def test_get_eligible_shipment_services(self):\n pass",
"def test_get_eligible_shipment_services_old(self):\n pass",
"def get_shopping_partners(request):\n try:\n shopping_partners = Partner.objects.get(current_user=request.user)\n shopping_partners_list = shopping_partners.partners.all()\n except:\n shopping_partners = []\n shopping_partners_list = []\n\n return shopping_partners_list",
"def available_list(cls, num):\n return cls.objects.filter(status=0)[:num]",
"def ListWaiters(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def available(name):\n return name in get_all()",
"def check_available():\n\n rm = current_app.config['rm_object']\n\n return rm.check_availability()",
"def get_available_package_manager(self):\n for manager in self.package.keys():\n try:\n executable = self.SUPPORTED_PACKAGE_MANAGERS[manager]\n if is_executable_exists(executable):\n return manager\n except KeyError:\n raise NotImplementedError(\"{} is not supported\".format(manager))\n raise NotImplementedError(\"This system doesn't have any of the \"\n 'supported package manager(s): '\n '{}'.format(','.join(self.package.keys())))",
"def manager_agents(self):\n return self.get(\"manager_agents\")",
"def get_waiting_jobs(self):\n return []",
"def available(self):\n\t\t\treturn True",
"def available(self):\n\t\t\treturn True",
"def available(self):\n\t\t\treturn True",
"def findAvailableFlightServiceManagers(self, flight):\n allFlightServiceManagers = self.getAllFlightServiceManagers()\n allVoyages = self.mainObject.getVoyagesIO()\n dateToFind = flight.getDepartureTime().split(\"T\")\n allAvalibleFlightServiceManagers = []\n for FlightServiceManager in allFlightServiceManagers:\n allAvalibleFlightServiceManagers.append(FlightServiceManager.getName()) # Appending all flight service managers to the list of all available flight service managers.\n\n busyFlightServiceManagers = []\n for voyage in allVoyages:\n uppcomingVoyageDates = voyage.getDepartureTime().split(\"T\")\n if uppcomingVoyageDates[0] == dateToFind[0]: # Index 0 of upcoming voyage date is the date.\n if voyage.getFa1() not in busyFlightServiceManagers:\n busyFlightServiceManagers.append(voyage.getFa1())\n try:\n for FlightServiceManager in busyFlightServiceManagers: # Filtering out busy flight attendants from the list of all available flight service managers.\n if FlightServiceManager in allAvalibleFlightServiceManagers:\n allAvalibleFlightServiceManagers.remove(FlightServiceManager)\n else:\n pass\n except ValueError:\n pass\n if allAvalibleFlightServiceManagers == []:\n return False\n else:\n return allAvalibleFlightServiceManagers",
"def check_manager_status(brief=True):\n ret = {\n \"manager\": {\n \"manager_id\": None,\n \"queues\": [],\n \"queue_len\": [],\n \"status\": \"stopped\",\n },\n \"workers\": [],\n \"fabrics\": [],\n \"total_queue_len\": 0,\n }\n seq = get_random_sequence()\n msg = eptMsg(MSG_TYPE.GET_MANAGER_STATUS, seq=seq, data={\"brief\": brief})\n #logger.debug(\"get manager status (seq:0x%x) brief:%r\", seq, brief)\n redis = get_redis()\n p = redis.pubsub(ignore_subscribe_messages=True)\n p.subscribe(MANAGER_CTRL_RESPONSE_CHANNEL)\n redis.publish(MANAGER_CTRL_CHANNEL, msg.jsonify())\n start_ts = time.time()\n timeout = AppStatus.MANAGER_STATUS_TIMEOUT \n try:\n if brief:\n timeout = AppStatus.MANAGER_STATUS_BRIEF_TIMEOUT\n while start_ts + timeout > time.time():\n data = p.get_message(timeout=1)\n if data is not None:\n channel = data[\"channel\"]\n if channel == MANAGER_CTRL_RESPONSE_CHANNEL:\n msg = eptMsg.parse(data[\"data\"]) \n if msg.msg_type == MSG_TYPE.MANAGER_STATUS:\n #logger.debug(\"received manager status (seq:0x%x)\", msg.seq)\n ret[\"manager\"] = msg.data[\"manager\"]\n ret[\"workers\"] = msg.data[\"workers\"]\n ret[\"fabrics\"] = msg.data[\"fabrics\"]\n ret[\"total_queue_len\"] = msg.data[\"total_queue_len\"]\n return ret\n except Exception as e:\n logger.debug(\"Traceback:\\n%s\", traceback.format_exc())\n logger.debug(\"error: %s\", e)\n finally:\n if redis is not None and hasattr(redis, \"connection_pool\"):\n redis.connection_pool.disconnect()\n\n logger.warn(\"no manager response within timeout(%s sec)\", timeout)\n return ret",
"def is_available():",
"def manager_active_list(self):\n _, body = self.request('/v1.1/managers/active', 'GET')\n return body",
"def check_availability(self):\n pass",
"def availability(self, client=False):\n # Due to possibility of memory explosion, we should include the finished\n # queue when considering whether we should add a new job. There was an\n # issue when running on a distributed system where we saw that this list\n # seemed to be growing indefinitely as the main thread was unable to clear\n # that list within a reasonable amount of time. The issue on the main thread\n # should also be addressed, but at least we can prevent it on this end since\n # the main thread's issue may be legitimate.\n\n maxCount = self.maxQueueSize\n finishedCount = len(self.__finished)\n\n if client:\n if maxCount is None:\n maxCount = self.__clientRunning.count(None)\n queueCount = len(self.__clientQueue)\n else:\n if maxCount is None:\n maxCount = self.__running.count(None)\n queueCount = len(self.__queue)\n\n availability = maxCount - queueCount - finishedCount\n return availability",
"def available(self, wl, *args):\n return True",
"def waitables(self):\n return (), (), ()",
"def test_toggle_waitlist_2(self):\n # Create needed objects.\n editor = EditorFactory()\n coordinators = get_coordinators()\n coordinators.user_set.add(editor.user)\n UserProfileFactory(user=editor.user, terms_of_use=True)\n\n partner = PartnerFactory(status=Partner.WAITLIST)\n\n # Set up request.\n url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})\n\n request = RequestFactory().post(url)\n request.user = editor.user\n\n _ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)\n partner.refresh_from_db()\n self.assertEqual(partner.status, Partner.AVAILABLE)",
"def evaluationManagerExists():\n\n pass",
"def test_get_dealer_active_inventory(self):\n pass",
"def supported_management_interfaces(self):\n return [fake.FakeManagement]"
] | [
"0.5561422",
"0.54804593",
"0.54126763",
"0.53765243",
"0.5312262",
"0.5265359",
"0.52632576",
"0.52573335",
"0.5208918",
"0.5208326",
"0.51736754",
"0.5170593",
"0.5153752",
"0.51494473",
"0.51482457",
"0.51438534",
"0.51438534",
"0.51438534",
"0.5139675",
"0.51355535",
"0.50875056",
"0.5084643",
"0.5083816",
"0.5080503",
"0.50691277",
"0.50571173",
"0.50436395",
"0.50362957",
"0.50344354",
"0.5020092"
] | 0.6756728 | 0 |
The any_waitlisted context on RequestApplicationView should True if there are waitlisted Partners. | def test_request_application_view_context_1(self):
# Set up request.
req_url = reverse('applications:request')
editor = EditorFactory()
request = RequestFactory().get(req_url)
request.user = editor.user
# Ensure there is at least one waitlisted partner.
partner = PartnerFactory(status=Partner.WAITLIST)
# Test response.
resp = RequestApplicationView.as_view()(request)
self.assertEqual(resp.context_data['any_waitlisted'], True) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_request_application_view_context_2(self):\n # Set up request.\n req_url = reverse('applications:request')\n\n editor = EditorFactory()\n request = RequestFactory().get(req_url)\n request.user = editor.user\n\n # Ensure there are no waitlisted partners.\n for partner in Partner.objects.filter(status=Partner.WAITLIST):\n partner.delete()\n\n # Test response.\n resp = RequestApplicationView.as_view()(request)\n self.assertEqual(resp.context_data['any_waitlisted'], False)",
"def is_on_waiting_list(self):\n if self.user is None:\n return False\n if unicode(self.user._id) in self.barcamp.event.waiting_list:\n return True\n return False",
"def is_available(self):\n if not is_optional_task_permissions_revoking_enabled():\n return False\n if not ITask.providedBy(self.context):\n return False\n if not self.context.get_review_state() in FINAL_TASK_STATES:\n return False\n if api.user.has_permission('cmf.ManagePortal'):\n return True\n issuer = self.context.get_issuer_actor()\n return issuer.identifier == api.user.get_current().id",
"def test_toggle_waitlist_1(self):\n # Create needed objects.\n editor = EditorFactory()\n coordinators = get_coordinators()\n coordinators.user_set.add(editor.user)\n UserProfileFactory(user=editor.user, terms_of_use=True)\n\n partner = PartnerFactory(status=Partner.AVAILABLE)\n\n # Set up request.\n url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})\n\n request = RequestFactory().post(url)\n request.user = editor.user\n\n _ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)\n partner.refresh_from_db()\n self.assertEqual(partner.status, Partner.WAITLIST)",
"def test_toggle_waitlist_2(self):\n # Create needed objects.\n editor = EditorFactory()\n coordinators = get_coordinators()\n coordinators.user_set.add(editor.user)\n UserProfileFactory(user=editor.user, terms_of_use=True)\n\n partner = PartnerFactory(status=Partner.WAITLIST)\n\n # Set up request.\n url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})\n\n request = RequestFactory().post(url)\n request.user = editor.user\n\n _ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)\n partner.refresh_from_db()\n self.assertEqual(partner.status, Partner.AVAILABLE)",
"def test_visibility_of_not_available_4(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n list_url = reverse('partners:list')\n\n editor = EditorFactory()\n editor.user.is_staff = True\n editor.user.save()\n\n request = RequestFactory().get(list_url)\n request.user = editor.user\n response = PartnersListView.as_view()(request)\n\n self.assertContains(response, partner.get_absolute_url())",
"def ListWaiters(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def test_visibility_of_not_available_2(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n list_url = reverse('partners:list')\n\n editor = EditorFactory()\n\n request = RequestFactory().get(list_url)\n request.user = editor.user\n response = PartnersListView.as_view()(request)\n\n self.assertNotContains(response, partner.get_absolute_url())",
"def test_toggle_waitlist_access(self):\n # Create needed objects.\n editor = EditorFactory()\n coordinators = get_coordinators()\n coordinators.user_set.add(editor.user)\n UserProfileFactory(user=editor.user, terms_of_use=True)\n\n partner = PartnerFactory(status=Partner.AVAILABLE)\n\n # Set up request.\n url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})\n\n request = RequestFactory().post(url)\n request.user = editor.user\n\n # This should work and not throw an error.\n resp = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)\n\n coordinators.user_set.remove(editor.user)\n with self.assertRaises(PermissionDenied):\n _ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)",
"def test_available_for_two_included(self):\n\n data = self._setup_two_included()\n self._do_test(\n data[\"run\"].id,\n self.available_param,\n [],\n )",
"def get_partner_requests(request):\n try:\n partner_requests = PartnerRequest.objects.filter(to_user=request.user)\n except:\n partner_requests = []\n\n return partner_requests",
"def available(self):\n portlet_id = self.data.portlet_id\n if portlet_id is None:\n # E.g. for collective.panels, where no portlet hashes are\n # available. Just return True, as these portlets are not inherited\n # anyways.\n return True\n\n if self.request.get('portlet_rendered_{0}'.format(portlet_id), False):\n return False\n self.request.set('portlet_rendered_{0}'.format(portlet_id), True)\n return True",
"def is_eligible(self) -> Optional[bool]:\n return pulumi.get(self, \"is_eligible\")",
"def partners_data(self) -> Optional[pulumi.Input['SecurityAssessmentPartnerDataArgs']]:\n return pulumi.get(self, \"partners_data\")",
"def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n\n language_code = get_language()\n # Changed since T278337: add filter to queryset before we build the partners\n # dictionary\n partner_filtered_list = MainPartnerFilter(\n self.request.GET, queryset=self.get_queryset(), language_code=language_code\n )\n context[\"filter\"] = partner_filtered_list\n\n user = self.request.user\n if user.is_authenticated:\n user = User.objects.select_related(\"editor\").get(pk=self.request.user.pk)\n context[\"user\"] = user\n context[\"editor\"] = user.editor\n partners_list = []\n partner_search_list = []\n for partner in partner_filtered_list.qs:\n partner_dict = {}\n partner_dict[\"pk\"] = partner.pk\n partner_dict[\"company_name\"] = partner.company_name\n try:\n partner_dict[\"partner_logo\"] = partner.logos.logo.url\n except ObjectDoesNotExist:\n partner_dict[\"partner_logo\"] = None\n partner_dict[\"is_not_available\"] = partner.is_not_available\n partner_dict[\"is_waitlisted\"] = partner.is_waitlisted\n new_tags = partner.new_tags\n # Getting tags from locale files\n translated_tags = get_tag_names(language_code, new_tags)\n partner_dict[\"tags\"] = translated_tags\n partner_dict[\"languages\"] = partner.get_languages\n # Obtaining translated partner description\n partner_short_description_key = \"{pk}_short_description\".format(\n pk=partner.pk\n )\n partner_description_key = \"{pk}_description\".format(pk=partner.pk)\n partner_descriptions = get_partner_description(\n language_code, partner_short_description_key, partner_description_key\n )\n\n partner_dict[\"short_description\"] = partner_descriptions[\n \"short_description\"\n ]\n partner_dict[\"description\"] = partner_descriptions[\"description\"]\n partners_list.append(partner_dict)\n if partner_descriptions[\"description\"]:\n partner_desc = bleach.clean(\n partner_descriptions[\"description\"],\n tags=[],\n strip=True,\n )\n else:\n partner_desc = \"\"\n\n if partner_descriptions[\"short_description\"]:\n partner_short_desc = bleach.clean(\n partner_descriptions[\"short_description\"],\n tags=[],\n strip=True,\n )\n else:\n partner_short_desc = \"\"\n\n partner_search_list.append(\n {\n \"partner_pk\": partner.pk,\n \"partner_name\": partner.company_name,\n \"partner_short_description\": partner_short_desc,\n \"partner_description\": partner_desc,\n }\n )\n context[\"partners_list\"] = partners_list\n context[\"partner_search_list\"] = partner_search_list\n\n return context",
"def test_available_for_one_included_one_not(self):\n\n data = self._setup_for_one_included_one_not()\n exp_objects = [self.get_exp_obj(data[\"s2\"])]\n\n self._do_test(\n data[\"run\"].id,\n self.available_param,\n exp_objects=exp_objects,\n )",
"def _evaluate_has_auths(self, context, user, partner):\n # User fulfills initial authorization\n fulfills_auth = True\n # Checking if user has agreed to terms and conditions, otherwise\n # they shouldn't be authorized to access the collection\n user_agreed_terms = user.userprofile.terms_of_use\n\n if partner.authorization_method in [Partner.EMAIL, Partner.CODES, Partner.LINK]:\n partner_renew = True\n final_auth = fulfills_auth and user_agreed_terms and partner_renew\n else:\n final_auth = fulfills_auth and user_agreed_terms\n # User has authorizations, link to collection page\n context[\"has_auths\"] = final_auth\n\n return context",
"def has_invites(self):\r\n return self.invite_ct > 0",
"def fully_booked(slots, attendees, user_name):\n if len(attendees) >= 2:\n return False\n else:\n return True",
"def get_available_invitees(self):\n return User.objects.exclude(pk=self.request.user.pk)",
"def get_queryset(self):\n queryset = super().get_queryset()\n return queryset.available_for_user(self.request.user)",
"def test_listing_from_wall_when_blocked_some_users(self):",
"def test_available_included_in_other_runs(self):\n\n s1 = self.factory.create(name=\"Suite1\")\n s2 = self.factory.create(name=\"Suite2\")\n run1 = self.F.RunFactory.create()\n runsuite1 = self.F.RunSuiteFactory.create(\n run=run1, suite=s1, order=0)\n runsuite2 = self.F.RunSuiteFactory.create(\n run=run1, suite=s2, order=1)\n run2 = self.F.RunFactory.create()\n runsuite3 = self.F.RunSuiteFactory.create(\n run=run2, suite=s1, order=0)\n runsuite4 = self.F.RunSuiteFactory.create(\n run=run2, suite=s2, order=1)\n\n self._do_test(\n -1,\n self.available_param,\n [self.get_exp_obj(\n s,\n runs=[\n unicode(self.get_detail_url(\"run\", run1.id)),\n unicode(self.get_detail_url(\"run\", run2.id)),\n ],\n ) for s, rs in [(s1, runsuite3), (s2, runsuite4)]],\n )",
"def get_available_scopes(self, application=None, request=None, *args, **kwargs): # lint-amnesty, pylint: disable=keyword-arg-before-vararg\n try:\n application_scopes = ApplicationAccess.get_scopes(application)\n except ApplicationAccess.DoesNotExist:\n application_scopes = []\n\n default_scopes = self.get_default_scopes()\n all_scopes = list(self.get_all_scopes().keys())\n return set(application_scopes + default_scopes).intersection(all_scopes)",
"def get_requested(self):\n return BBSitting.objects.filter(booked=self).filter(booking__confirmed=False)",
"def should_keep_running(self):\n return len(self.party.active_users())",
"def completed(self, exclude: typing.Optional[list] = None) -> bool:\n return all(param for param in self if param.name not in exclude)",
"def isInCall(self):\n if len(self.partyList) == 0:\n return False, False\n established_parties = [party for party in self.partyList if party.State == PartyState.Established]\n return True, len(established_parties) > 0",
"def is_applicable(self, context: Any) -> bool:\n pass",
"def getInquiriesForDisplay(self):\n return [self.context]"
] | [
"0.65983224",
"0.6206553",
"0.5711998",
"0.5529839",
"0.5529052",
"0.54388237",
"0.5368983",
"0.5355158",
"0.532243",
"0.5276433",
"0.5247194",
"0.50149375",
"0.5010246",
"0.49794883",
"0.49715558",
"0.49658874",
"0.49549156",
"0.4880058",
"0.48733827",
"0.48630413",
"0.48575968",
"0.48557886",
"0.48344153",
"0.48321554",
"0.4803292",
"0.4794692",
"0.4783439",
"0.4777215",
"0.4775833",
"0.4771289"
] | 0.69799984 | 0 |
The any_waitlisted context on RequestApplicationView should False if there are not waitlisted Partners. | def test_request_application_view_context_2(self):
# Set up request.
req_url = reverse('applications:request')
editor = EditorFactory()
request = RequestFactory().get(req_url)
request.user = editor.user
# Ensure there are no waitlisted partners.
for partner in Partner.objects.filter(status=Partner.WAITLIST):
partner.delete()
# Test response.
resp = RequestApplicationView.as_view()(request)
self.assertEqual(resp.context_data['any_waitlisted'], False) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_request_application_view_context_1(self):\n # Set up request.\n req_url = reverse('applications:request')\n\n editor = EditorFactory()\n request = RequestFactory().get(req_url)\n request.user = editor.user\n\n # Ensure there is at least one waitlisted partner.\n partner = PartnerFactory(status=Partner.WAITLIST)\n\n # Test response.\n resp = RequestApplicationView.as_view()(request)\n self.assertEqual(resp.context_data['any_waitlisted'], True)",
"def is_on_waiting_list(self):\n if self.user is None:\n return False\n if unicode(self.user._id) in self.barcamp.event.waiting_list:\n return True\n return False",
"def is_available(self):\n if not is_optional_task_permissions_revoking_enabled():\n return False\n if not ITask.providedBy(self.context):\n return False\n if not self.context.get_review_state() in FINAL_TASK_STATES:\n return False\n if api.user.has_permission('cmf.ManagePortal'):\n return True\n issuer = self.context.get_issuer_actor()\n return issuer.identifier == api.user.get_current().id",
"def test_visibility_of_not_available_2(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n list_url = reverse('partners:list')\n\n editor = EditorFactory()\n\n request = RequestFactory().get(list_url)\n request.user = editor.user\n response = PartnersListView.as_view()(request)\n\n self.assertNotContains(response, partner.get_absolute_url())",
"def test_visibility_of_not_available_4(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n list_url = reverse('partners:list')\n\n editor = EditorFactory()\n editor.user.is_staff = True\n editor.user.save()\n\n request = RequestFactory().get(list_url)\n request.user = editor.user\n response = PartnersListView.as_view()(request)\n\n self.assertContains(response, partner.get_absolute_url())",
"def test_toggle_waitlist_2(self):\n # Create needed objects.\n editor = EditorFactory()\n coordinators = get_coordinators()\n coordinators.user_set.add(editor.user)\n UserProfileFactory(user=editor.user, terms_of_use=True)\n\n partner = PartnerFactory(status=Partner.WAITLIST)\n\n # Set up request.\n url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})\n\n request = RequestFactory().post(url)\n request.user = editor.user\n\n _ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)\n partner.refresh_from_db()\n self.assertEqual(partner.status, Partner.AVAILABLE)",
"def test_toggle_waitlist_1(self):\n # Create needed objects.\n editor = EditorFactory()\n coordinators = get_coordinators()\n coordinators.user_set.add(editor.user)\n UserProfileFactory(user=editor.user, terms_of_use=True)\n\n partner = PartnerFactory(status=Partner.AVAILABLE)\n\n # Set up request.\n url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})\n\n request = RequestFactory().post(url)\n request.user = editor.user\n\n _ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)\n partner.refresh_from_db()\n self.assertEqual(partner.status, Partner.WAITLIST)",
"def ListWaiters(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def test_toggle_waitlist_access(self):\n # Create needed objects.\n editor = EditorFactory()\n coordinators = get_coordinators()\n coordinators.user_set.add(editor.user)\n UserProfileFactory(user=editor.user, terms_of_use=True)\n\n partner = PartnerFactory(status=Partner.AVAILABLE)\n\n # Set up request.\n url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})\n\n request = RequestFactory().post(url)\n request.user = editor.user\n\n # This should work and not throw an error.\n resp = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)\n\n coordinators.user_set.remove(editor.user)\n with self.assertRaises(PermissionDenied):\n _ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)",
"def get_partner_requests(request):\n try:\n partner_requests = PartnerRequest.objects.filter(to_user=request.user)\n except:\n partner_requests = []\n\n return partner_requests",
"def is_eligible(self) -> Optional[bool]:\n return pulumi.get(self, \"is_eligible\")",
"def test_available_for_two_included(self):\n\n data = self._setup_two_included()\n self._do_test(\n data[\"run\"].id,\n self.available_param,\n [],\n )",
"def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n\n language_code = get_language()\n # Changed since T278337: add filter to queryset before we build the partners\n # dictionary\n partner_filtered_list = MainPartnerFilter(\n self.request.GET, queryset=self.get_queryset(), language_code=language_code\n )\n context[\"filter\"] = partner_filtered_list\n\n user = self.request.user\n if user.is_authenticated:\n user = User.objects.select_related(\"editor\").get(pk=self.request.user.pk)\n context[\"user\"] = user\n context[\"editor\"] = user.editor\n partners_list = []\n partner_search_list = []\n for partner in partner_filtered_list.qs:\n partner_dict = {}\n partner_dict[\"pk\"] = partner.pk\n partner_dict[\"company_name\"] = partner.company_name\n try:\n partner_dict[\"partner_logo\"] = partner.logos.logo.url\n except ObjectDoesNotExist:\n partner_dict[\"partner_logo\"] = None\n partner_dict[\"is_not_available\"] = partner.is_not_available\n partner_dict[\"is_waitlisted\"] = partner.is_waitlisted\n new_tags = partner.new_tags\n # Getting tags from locale files\n translated_tags = get_tag_names(language_code, new_tags)\n partner_dict[\"tags\"] = translated_tags\n partner_dict[\"languages\"] = partner.get_languages\n # Obtaining translated partner description\n partner_short_description_key = \"{pk}_short_description\".format(\n pk=partner.pk\n )\n partner_description_key = \"{pk}_description\".format(pk=partner.pk)\n partner_descriptions = get_partner_description(\n language_code, partner_short_description_key, partner_description_key\n )\n\n partner_dict[\"short_description\"] = partner_descriptions[\n \"short_description\"\n ]\n partner_dict[\"description\"] = partner_descriptions[\"description\"]\n partners_list.append(partner_dict)\n if partner_descriptions[\"description\"]:\n partner_desc = bleach.clean(\n partner_descriptions[\"description\"],\n tags=[],\n strip=True,\n )\n else:\n partner_desc = \"\"\n\n if partner_descriptions[\"short_description\"]:\n partner_short_desc = bleach.clean(\n partner_descriptions[\"short_description\"],\n tags=[],\n strip=True,\n )\n else:\n partner_short_desc = \"\"\n\n partner_search_list.append(\n {\n \"partner_pk\": partner.pk,\n \"partner_name\": partner.company_name,\n \"partner_short_description\": partner_short_desc,\n \"partner_description\": partner_desc,\n }\n )\n context[\"partners_list\"] = partners_list\n context[\"partner_search_list\"] = partner_search_list\n\n return context",
"def available(self):\n portlet_id = self.data.portlet_id\n if portlet_id is None:\n # E.g. for collective.panels, where no portlet hashes are\n # available. Just return True, as these portlets are not inherited\n # anyways.\n return True\n\n if self.request.get('portlet_rendered_{0}'.format(portlet_id), False):\n return False\n self.request.set('portlet_rendered_{0}'.format(portlet_id), True)\n return True",
"def get_available_invitees(self):\n return User.objects.exclude(pk=self.request.user.pk)",
"def partners_data(self) -> Optional[pulumi.Input['SecurityAssessmentPartnerDataArgs']]:\n return pulumi.get(self, \"partners_data\")",
"def test_available_for_one_included_one_not(self):\n\n data = self._setup_for_one_included_one_not()\n exp_objects = [self.get_exp_obj(data[\"s2\"])]\n\n self._do_test(\n data[\"run\"].id,\n self.available_param,\n exp_objects=exp_objects,\n )",
"def test_listing_from_wall_when_blocked_some_users(self):",
"def fully_booked(slots, attendees, user_name):\n if len(attendees) >= 2:\n return False\n else:\n return True",
"def get_requested(self):\n return BBSitting.objects.filter(booked=self).filter(booking__confirmed=False)",
"def get_queryset(self):\n queryset = super().get_queryset()\n return queryset.available_for_user(self.request.user)",
"def has_invites(self):\r\n return self.invite_ct > 0",
"def completed(self, exclude: typing.Optional[list] = None) -> bool:\n return all(param for param in self if param.name not in exclude)",
"def is_applicable(self, context: Any) -> bool:\n pass",
"def get_available_scopes(self, application=None, request=None, *args, **kwargs): # lint-amnesty, pylint: disable=keyword-arg-before-vararg\n try:\n application_scopes = ApplicationAccess.get_scopes(application)\n except ApplicationAccess.DoesNotExist:\n application_scopes = []\n\n default_scopes = self.get_default_scopes()\n all_scopes = list(self.get_all_scopes().keys())\n return set(application_scopes + default_scopes).intersection(all_scopes)",
"def test_extra_field_when_not_requested(self):\n self.client.login(username=self.admin_user.username, password='test')\n response = self.verify_response(params={\n 'all_blocks': True,\n 'requested_fields': ['course_visibility'],\n })\n self.verify_response_block_dict(response)\n for block_data in response.data['blocks'].values():\n assert 'other_course_settings' not in block_data\n\n self.assert_in_iff(\n 'course_visibility',\n block_data,\n block_data['type'] == 'course'\n )",
"def _evaluate_has_auths(self, context, user, partner):\n # User fulfills initial authorization\n fulfills_auth = True\n # Checking if user has agreed to terms and conditions, otherwise\n # they shouldn't be authorized to access the collection\n user_agreed_terms = user.userprofile.terms_of_use\n\n if partner.authorization_method in [Partner.EMAIL, Partner.CODES, Partner.LINK]:\n partner_renew = True\n final_auth = fulfills_auth and user_agreed_terms and partner_renew\n else:\n final_auth = fulfills_auth and user_agreed_terms\n # User has authorizations, link to collection page\n context[\"has_auths\"] = final_auth\n\n return context",
"def isBlocked(self):\n cal = self.request.get('form.widgets.calendarConfig')\n if cal is not None:\n return (cal == ['bloque'])\n wrapper = getSAWrapper('gites_wallons')\n session = wrapper.session\n for heb in getHebergementsForProprio(self.context, session):\n if heb.heb_calendrier_proprio == 'bloque':\n return True\n return False",
"def available(self):\n existing_url = self.context.get_personal_fundraising_campaign_url()\n same = existing_url == self.context.absolute_url()\n creating = 'create-personal-campaign-page' in self.request.URL\n return not same and not creating",
"def should_render(\n self,\n *,\n context: Context,\n ) -> bool:\n request = context['request']\n review_request = context.get('review_request')\n perms = context.get('perms')\n user = request.user\n\n return (super().should_render(context=context) and\n review_request is not None and\n review_request.status == ReviewRequest.PENDING_REVIEW and\n not is_site_read_only_for(user) and\n (request.user.pk == review_request.submitter_id or\n (bool(perms) and\n perms['reviews']['can_change_status'] and\n review_request.public)))"
] | [
"0.6960705",
"0.6218048",
"0.5808824",
"0.5664902",
"0.56613207",
"0.54783285",
"0.54593587",
"0.53600484",
"0.5333338",
"0.52819437",
"0.5218338",
"0.5130079",
"0.50323087",
"0.5031903",
"0.50049317",
"0.49963278",
"0.49766374",
"0.49620152",
"0.49250045",
"0.4918239",
"0.49019104",
"0.48886165",
"0.48776588",
"0.4865783",
"0.48618552",
"0.48483655",
"0.48469818",
"0.48457476",
"0.48188072",
"0.4817985"
] | 0.67606765 | 1 |
Posting to the toggle waitlist view sets an AVAILABLE partner to WAITLIST. | def test_toggle_waitlist_1(self):
# Create needed objects.
editor = EditorFactory()
coordinators = get_coordinators()
coordinators.user_set.add(editor.user)
UserProfileFactory(user=editor.user, terms_of_use=True)
partner = PartnerFactory(status=Partner.AVAILABLE)
# Set up request.
url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})
request = RequestFactory().post(url)
request.user = editor.user
_ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)
partner.refresh_from_db()
self.assertEqual(partner.status, Partner.WAITLIST) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_toggle_waitlist_2(self):\n # Create needed objects.\n editor = EditorFactory()\n coordinators = get_coordinators()\n coordinators.user_set.add(editor.user)\n UserProfileFactory(user=editor.user, terms_of_use=True)\n\n partner = PartnerFactory(status=Partner.WAITLIST)\n\n # Set up request.\n url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})\n\n request = RequestFactory().post(url)\n request.user = editor.user\n\n _ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)\n partner.refresh_from_db()\n self.assertEqual(partner.status, Partner.AVAILABLE)",
"def test_toggle_waitlist_access(self):\n # Create needed objects.\n editor = EditorFactory()\n coordinators = get_coordinators()\n coordinators.user_set.add(editor.user)\n UserProfileFactory(user=editor.user, terms_of_use=True)\n\n partner = PartnerFactory(status=Partner.AVAILABLE)\n\n # Set up request.\n url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})\n\n request = RequestFactory().post(url)\n request.user = editor.user\n\n # This should work and not throw an error.\n resp = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)\n\n coordinators.user_set.remove(editor.user)\n with self.assertRaises(PermissionDenied):\n _ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)",
"def set_multiple_status(self, status_list):\n self.multiple_items_selection_from_kendo_dropdown(self.status_kendo_dropdown_locator, status_list)\n self.wait_for_ajax_spinner_load()\n buy_page_title_element = self.wait().until(EC.element_to_be_clickable(self.buy_page_title_locator), 'buy page title locator not found before specified time out')\n buy_page_title_element.click()",
"def _button_send_list_toggled(self, *a):\r\n _debug('GUISignalGenerator: _button_send_list_toggled()', a)\r\n \r\n if not self.button_send_list.is_checked(): return\r\n \r\n # Clear the label\r\n self.label_list_status.set_text('')\r\n self.window.process_events()\r\n\r\n # If there is data to send\r\n if len(self.plot_list): \r\n \r\n # Reset\r\n# self.label_list_status.set_text('Resetting...')\r\n# self.window.process_events()\r\n# self.api.reset()\r\n \r\n # Send it\r\n self.label_list_status.set_text('Sending...')\r\n self.window.process_events()\r\n self.api.send_list(self.plot_list['f_Hz'], self.plot_list['P_dBm'], \r\n dwell=1000, delay=0)\r\n \r\n # Check it\r\n self.label_list_status.set_text('Double-checking...')\r\n self.window.process_events()\r\n self.query_list()\r\n \r\n # Update the RF button\r\n self.button_rf.set_checked(self.api.get_output(), block_events=True)\r\n \r\n # Undo the button\r\n self.button_send_list.set_checked(False, block_events=True)",
"async def waiting_list_add(self, waiting_list_id: int):\n company_id, event_name, event_link, event_id, user_id = await self.pg.fetchrow(\n \"\"\"\n select\n c.company,\n e.name,\n event_link(c.slug, e.slug, e.public, $2),\n e.id,\n w.user_id\n from waiting_list w\n join events e on w.event = e.id\n join categories AS c ON e.category = c.id\n where w.id=$1\n \"\"\",\n waiting_list_id,\n self.settings.auth_key,\n )\n\n sig = waiting_list_sig(event_id, user_id, self.settings)\n ctx = {\n 'event_link': event_link,\n 'event_name': event_name,\n 'remove_link': f'/api/events/{event_id}/waiting-list/remove/{user_id}/?sig={sig}',\n }\n await self.send_emails.direct(company_id, Triggers.waiting_list_add, [UserEmail(user_id, ctx)])",
"def set_wait_for_do_set_online(self) -> MessageBoardBuilder:\n controller_name = self._tel.csp.controller\n builder = get_message_board_builder()\n builder.set_waiting_on(controller_name).for_attribute(\"adminMode\").to_become_equal_to(\n \"ONLINE\", ignore_first=False\n )\n builder.set_waiting_on(controller_name).for_attribute(\"state\").to_become_equal_to(\n [\"OFF\", \"ON\"], ignore_first=False\n )\n for index in range(1, self.nr_of_subarrays + 1):\n subarray = self._tel.csp.subarray(index)\n builder.set_waiting_on(subarray).for_attribute(\"adminMode\").to_become_equal_to(\n \"ONLINE\", ignore_first=False\n )\n builder.set_waiting_on(subarray).for_attribute(\"state\").to_become_equal_to(\n [\"OFF\", \"ON\"], ignore_first=False\n )\n return builder",
"def is_waiting(self, is_waiting):\n \n self._is_waiting = is_waiting",
"def test_Computer_getComputerPartitionList_SetupResource_DeliveredState(self):\n sequence_list = SequenceList()\n sequence_string = self.prepare_installed_computer_partition_sequence_string + '\\\n CallVifibUpdateDeliveryCausalityStateAlarm \\\n CleanTic \\\n \\\n LoginDefaultUser \\\n CheckComputerPartitionInstanceSetupSalePackingListDelivered \\\n SelectCurrentlyUsedSalePackingListUid \\\n CancelSalePackingList \\\n Tic \\\n CheckComputerPartitionInstanceHostingSalePackingListCancelled \\\n CheckComputerPartitionInstanceCleanupSalePackingListDoesNotExists \\\n Logout \\\n \\\n SlapLoginCurrentComputer \\\n CheckSuccessComputerGetComputerPartitionCall \\\n SlapLogout \\\n LoginERP5TypeTestCase \\\n CheckSiteConsistency \\\n Logout \\\n '\n sequence_list.addSequenceString(sequence_string)\n sequence_list.play(self)",
"def create_waitinglist(dbo, username, collationid):\n l = dbo.locale\n fields = get_onlineformincoming_detail(dbo, collationid)\n d = {}\n d[\"dateputon\"] = i18n.python2display(l, i18n.now(dbo.timezone))\n d[\"urgency\"] = \"5\"\n for f in fields:\n if f[\"FIELDNAME\"] == \"species\": d[\"species\"] = guess_species(dbo, f[\"VALUE\"])\n if f[\"FIELDNAME\"] == \"description\": d[\"description\"] = f[\"VALUE\"]\n if f[\"FIELDNAME\"] == \"reason\": d[\"reasonforwantingtopart\"] = f[\"VALUE\"]\n if not d.has_key(\"species\"): d[\"species\"] = guess_species(dbo, \"\")\n # Have we got enough info to create the waiting list record? We need a description\n if not d.has_key(\"description\"):\n raise utils.ASMValidationError(i18n._(\"There is not enough information in the form to create a waiting list record (need a description).\", l))\n # We need the person record before we create the waiting list\n collationid, personid, personname = create_person(dbo, username, collationid)\n d[\"owner\"] = personid\n # Create the waiting list\n wlid = waitinglist.insert_waitinglist_from_form(dbo, utils.PostedData(d, dbo.locale), username)\n # Attach the form to the waiting list\n formname = get_onlineformincoming_name(dbo, collationid)\n formhtml = get_onlineformincoming_html(dbo, collationid)\n media.create_document_media(dbo, username, media.WAITINGLIST, wlid, formname, formhtml )\n return (collationid, wlid, utils.padleft(wlid, 6) + \" - \" + personname)",
"def test_visibility_of_not_available_4(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n list_url = reverse('partners:list')\n\n editor = EditorFactory()\n editor.user.is_staff = True\n editor.user.save()\n\n request = RequestFactory().get(list_url)\n request.user = editor.user\n response = PartnersListView.as_view()(request)\n\n self.assertContains(response, partner.get_absolute_url())",
"def park(self):\n self.logger.debug('Setting to park')\n self._state = 'Parked'\n self._is_slewing = False\n self._is_tracking = False\n self._is_home = False\n self._is_parked = True",
"def is_on_waiting_list(self):\n if self.user is None:\n return False\n if unicode(self.user._id) in self.barcamp.event.waiting_list:\n return True\n return False",
"def update_waiting(self):\n if self.get_value(0) is None:\n self.set_value(False, 0)\n else:\n self.set_value(bool(self.get_value(0)), 0)\n self.state = ACTIVE",
"def ToggleApprovalTracker(self, event):\n pass",
"def _after_plot_list_load(self):\r\n self.button_send_list.enable()\r\n self.label_list_status.set_text('Shown list does not match device list.')",
"def update_waiting(self):\n if self.get_value(0) is None:\n self.set_value(True, 0)\n else:\n self.set_value(not bool(self.get_value(0)), 0)\n self.state = ACTIVE",
"def fetch(self):\r\n if self.wp_op is None: # If we were already doing a list or save, just restart the fetch without changing the operation\r\n self.wp_op = \"fetch\"\r\n self.master.waypoint_request_list_send()",
"def test_Computer_getComputerPartitionList_HostingResource_DeliveredState(self):\n sequence_list = SequenceList()\n sequence_string = self.prepare_stopped_computer_partition_sequence_string + '\\\n SlapLoginCurrentComputer \\\n CheckSuccessComputerGetComputerPartitionCall \\\n SlapLogout \\\n LoginERP5TypeTestCase \\\n CheckSiteConsistency \\\n Logout \\\n '\n sequence_list.addSequenceString(sequence_string)\n sequence_list.play(self)",
"async def async_turn_on(self):\n path = \"/queue/simple\"\n param = \".id\"\n value = None\n for uid in self._ctrl.data[\"queue\"]:\n if self._ctrl.data[\"queue\"][uid][\"name\"] == f\"{self._data['name']}\":\n value = self._ctrl.data[\"queue\"][uid][\".id\"]\n\n mod_param = \"disabled\"\n mod_value = False\n self._ctrl.set_value(path, param, value, mod_param, mod_value)\n await self._ctrl.force_update()",
"def set_present(self, absentee: QualifiedAgent):\n wum: WorklistUpdateManagerApi = self._service_provider.get_service(WorklistUpdateManagerApi)\n wum.set_present(body=absentee)",
"def Promote_from_waitlist(self, email):\n if email in self.Waitlist:\n self.Waitlist.remove(email)\n self.Add_attendee(email)\n else:\n raise MissingAddressException(email)",
"def set_On(self):\n if not(self._locked):\n self.__dict__['statusOn']=True\n self._do_action()\n else:\n self._log.info('The JobProperty %s is blocked', self.__name__)",
"def set_awaiting_turn(self):\n if self.status == self.PLAYER_BANKRUPT:\n return\n if self.status == self.PLAYER_AWAITING_TURN:\n return\n self.status = self.PLAYER_AWAITING_TURN\n # self.client.send_player_turn_end()",
"def set_suspect_status(self, suspect_status):\n self.multiple_items_selection_from_kendo_dropdown(self.suspect_status_kendo_dropdown_locator, suspect_status)\n self.wait_for_ajax_spinner_load()",
"def test_visibility_of_not_available_2(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n list_url = reverse('partners:list')\n\n editor = EditorFactory()\n\n request = RequestFactory().get(list_url)\n request.user = editor.user\n response = PartnersListView.as_view()(request)\n\n self.assertNotContains(response, partner.get_absolute_url())",
"def set_account(self, account_list):\n self.multiple_items_selection_from_kendo_dropdown(self.account_kendo_dropdown_locator, account_list)\n self.wait_for_ajax_spinner_load()",
"def set_faceted_navigation(licence, event):\n activate_faceted_tasks_listing(licence, event)",
"def waiting(self, waiting):\n\n self._waiting = waiting",
"def waiting_confirmation(self):",
"def toggled_monitor(self):\n if self.pushButton_monitor.isChecked():\n \n if not self.connect_serial():\n self.pushButton_monitor.setChecked(0)\n return\n \n self.textBrowser.insertPlainText(\n QtGui.QApplication.translate(\n \"MainWindow\", \n \"\\n\\t----NEW MONITORING----\\n\", \n None, \n QtGui.QApplication.UnicodeUTF8))\n \n id_link = self.listWidget_link.selectedItems()\n if len(id_link):\n id_link = int(id_link[0].text())\n else:\n id_link = 1\n \n self.textBrowser.insertPlainText(QtGui.QApplication.translate(\"MainWindow\", \"link to monitor : \", None, QtGui.QApplication.UnicodeUTF8)+str(id_link)+\"\\n\")\n \n word = struct.pack(\"BBBBBBBB\", ID_MONITOR,0,0,0,0,0,0,id_link&0xFF)\n \n self.textBrowser.append(\n QtGui.QApplication.translate(\n \"MainWindow\", \n \"Sent : \", \n None, \n QtGui.QApplication.UnicodeUTF8)+\n binascii.hexlify(word)+\n \"\\n\")\n \n self.ser.write(word)\n \n # clear data of the serial port\n self.ser.flushInput()\n # clear graph\n self.clean_graph()\n # start timer data reception\n self.get_periodical_data()\n # start timer graphic refresh\n self.update_graph()\n \n self.pushButton_save.setEnabled(False)\n else:\n # send Monitor\n word = struct.pack(\"BBBBBBBB\", ID_MONITOR+ID_STOP,0,0,0,0,0,0,0)\n \n self.textBrowser.append(QtGui.QApplication.translate(\"MainWindow\", \"Sent : \", None, QtGui.QApplication.UnicodeUTF8)+binascii.hexlify(word)+\"\\n\")\n \n self.ser.write(word)\n \n self.ser.flushInput()\n \n # reload number of waiting chars in serial rx buffer\n self.label_rx_buff_value.setText(str(self.ser.inWaiting()))\n \n self.textBrowser.insertPlainText(QtGui.QApplication.translate(\"MainWindow\", \"\\n\\t----END MONITORING----\\n\", None, QtGui.QApplication.UnicodeUTF8))\n \n self.pushButton_save.setEnabled(True)\n \n if (not self.pushButton_reload.isChecked()):\n self.timer_data.stop()\n self.timer_graph.stop()"
] | [
"0.7558113",
"0.65328646",
"0.5433371",
"0.53213185",
"0.52467173",
"0.51282156",
"0.509953",
"0.5091204",
"0.5043268",
"0.4991013",
"0.4983952",
"0.4963802",
"0.49538127",
"0.4937576",
"0.49288344",
"0.48964024",
"0.48799095",
"0.4864928",
"0.48648843",
"0.48552614",
"0.48437405",
"0.48312807",
"0.48225006",
"0.48166373",
"0.4802116",
"0.47911757",
"0.47804862",
"0.47738844",
"0.47710618",
"0.476528"
] | 0.7505038 | 1 |
Posting to the toggle waitlist view sets a WAITLIST partner to AVAILABLE. | def test_toggle_waitlist_2(self):
# Create needed objects.
editor = EditorFactory()
coordinators = get_coordinators()
coordinators.user_set.add(editor.user)
UserProfileFactory(user=editor.user, terms_of_use=True)
partner = PartnerFactory(status=Partner.WAITLIST)
# Set up request.
url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})
request = RequestFactory().post(url)
request.user = editor.user
_ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)
partner.refresh_from_db()
self.assertEqual(partner.status, Partner.AVAILABLE) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_toggle_waitlist_1(self):\n # Create needed objects.\n editor = EditorFactory()\n coordinators = get_coordinators()\n coordinators.user_set.add(editor.user)\n UserProfileFactory(user=editor.user, terms_of_use=True)\n\n partner = PartnerFactory(status=Partner.AVAILABLE)\n\n # Set up request.\n url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})\n\n request = RequestFactory().post(url)\n request.user = editor.user\n\n _ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)\n partner.refresh_from_db()\n self.assertEqual(partner.status, Partner.WAITLIST)",
"def test_toggle_waitlist_access(self):\n # Create needed objects.\n editor = EditorFactory()\n coordinators = get_coordinators()\n coordinators.user_set.add(editor.user)\n UserProfileFactory(user=editor.user, terms_of_use=True)\n\n partner = PartnerFactory(status=Partner.AVAILABLE)\n\n # Set up request.\n url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})\n\n request = RequestFactory().post(url)\n request.user = editor.user\n\n # This should work and not throw an error.\n resp = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)\n\n coordinators.user_set.remove(editor.user)\n with self.assertRaises(PermissionDenied):\n _ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)",
"def set_multiple_status(self, status_list):\n self.multiple_items_selection_from_kendo_dropdown(self.status_kendo_dropdown_locator, status_list)\n self.wait_for_ajax_spinner_load()\n buy_page_title_element = self.wait().until(EC.element_to_be_clickable(self.buy_page_title_locator), 'buy page title locator not found before specified time out')\n buy_page_title_element.click()",
"def _button_send_list_toggled(self, *a):\r\n _debug('GUISignalGenerator: _button_send_list_toggled()', a)\r\n \r\n if not self.button_send_list.is_checked(): return\r\n \r\n # Clear the label\r\n self.label_list_status.set_text('')\r\n self.window.process_events()\r\n\r\n # If there is data to send\r\n if len(self.plot_list): \r\n \r\n # Reset\r\n# self.label_list_status.set_text('Resetting...')\r\n# self.window.process_events()\r\n# self.api.reset()\r\n \r\n # Send it\r\n self.label_list_status.set_text('Sending...')\r\n self.window.process_events()\r\n self.api.send_list(self.plot_list['f_Hz'], self.plot_list['P_dBm'], \r\n dwell=1000, delay=0)\r\n \r\n # Check it\r\n self.label_list_status.set_text('Double-checking...')\r\n self.window.process_events()\r\n self.query_list()\r\n \r\n # Update the RF button\r\n self.button_rf.set_checked(self.api.get_output(), block_events=True)\r\n \r\n # Undo the button\r\n self.button_send_list.set_checked(False, block_events=True)",
"def is_waiting(self, is_waiting):\n \n self._is_waiting = is_waiting",
"def update_waiting(self):\n if self.get_value(0) is None:\n self.set_value(False, 0)\n else:\n self.set_value(bool(self.get_value(0)), 0)\n self.state = ACTIVE",
"def update_waiting(self):\n if self.get_value(0) is None:\n self.set_value(True, 0)\n else:\n self.set_value(not bool(self.get_value(0)), 0)\n self.state = ACTIVE",
"async def waiting_list_add(self, waiting_list_id: int):\n company_id, event_name, event_link, event_id, user_id = await self.pg.fetchrow(\n \"\"\"\n select\n c.company,\n e.name,\n event_link(c.slug, e.slug, e.public, $2),\n e.id,\n w.user_id\n from waiting_list w\n join events e on w.event = e.id\n join categories AS c ON e.category = c.id\n where w.id=$1\n \"\"\",\n waiting_list_id,\n self.settings.auth_key,\n )\n\n sig = waiting_list_sig(event_id, user_id, self.settings)\n ctx = {\n 'event_link': event_link,\n 'event_name': event_name,\n 'remove_link': f'/api/events/{event_id}/waiting-list/remove/{user_id}/?sig={sig}',\n }\n await self.send_emails.direct(company_id, Triggers.waiting_list_add, [UserEmail(user_id, ctx)])",
"def _after_plot_list_load(self):\r\n self.button_send_list.enable()\r\n self.label_list_status.set_text('Shown list does not match device list.')",
"def set_On(self):\n if not(self._locked):\n self.__dict__['statusOn']=True\n self._do_action()\n else:\n self._log.info('The JobProperty %s is blocked', self.__name__)",
"def is_on_waiting_list(self):\n if self.user is None:\n return False\n if unicode(self.user._id) in self.barcamp.event.waiting_list:\n return True\n return False",
"def set_wait_for_do_set_online(self) -> MessageBoardBuilder:\n controller_name = self._tel.csp.controller\n builder = get_message_board_builder()\n builder.set_waiting_on(controller_name).for_attribute(\"adminMode\").to_become_equal_to(\n \"ONLINE\", ignore_first=False\n )\n builder.set_waiting_on(controller_name).for_attribute(\"state\").to_become_equal_to(\n [\"OFF\", \"ON\"], ignore_first=False\n )\n for index in range(1, self.nr_of_subarrays + 1):\n subarray = self._tel.csp.subarray(index)\n builder.set_waiting_on(subarray).for_attribute(\"adminMode\").to_become_equal_to(\n \"ONLINE\", ignore_first=False\n )\n builder.set_waiting_on(subarray).for_attribute(\"state\").to_become_equal_to(\n [\"OFF\", \"ON\"], ignore_first=False\n )\n return builder",
"def set_statement_status_for_search(self, status_list):\n self.multiple_items_selection_from_kendo_dropdown(self.statement_status_dropdown_locator, status_list)\n self.wait_for_ajax_spinner_load()",
"def set_suspect_status(self, suspect_status):\n self.multiple_items_selection_from_kendo_dropdown(self.suspect_status_kendo_dropdown_locator, suspect_status)\n self.wait_for_ajax_spinner_load()",
"def waiting_confirmation(self):",
"def park(self):\n self.logger.debug('Setting to park')\n self._state = 'Parked'\n self._is_slewing = False\n self._is_tracking = False\n self._is_home = False\n self._is_parked = True",
"def set_status_update_waiter(self):\n status_message_update_waiter = self.status_message_update_waiter\n if (status_message_update_waiter is not None):\n self.status_message_update_waiter = None\n status_message_update_waiter.set_result(...)",
"def ToggleApprovalTracker(self, event):\n pass",
"async def async_turn_on(self):\n path = \"/queue/simple\"\n param = \".id\"\n value = None\n for uid in self._ctrl.data[\"queue\"]:\n if self._ctrl.data[\"queue\"][uid][\"name\"] == f\"{self._data['name']}\":\n value = self._ctrl.data[\"queue\"][uid][\".id\"]\n\n mod_param = \"disabled\"\n mod_value = False\n self._ctrl.set_value(path, param, value, mod_param, mod_value)\n await self._ctrl.force_update()",
"def test_Computer_getComputerPartitionList_SetupResource_DeliveredState(self):\n sequence_list = SequenceList()\n sequence_string = self.prepare_installed_computer_partition_sequence_string + '\\\n CallVifibUpdateDeliveryCausalityStateAlarm \\\n CleanTic \\\n \\\n LoginDefaultUser \\\n CheckComputerPartitionInstanceSetupSalePackingListDelivered \\\n SelectCurrentlyUsedSalePackingListUid \\\n CancelSalePackingList \\\n Tic \\\n CheckComputerPartitionInstanceHostingSalePackingListCancelled \\\n CheckComputerPartitionInstanceCleanupSalePackingListDoesNotExists \\\n Logout \\\n \\\n SlapLoginCurrentComputer \\\n CheckSuccessComputerGetComputerPartitionCall \\\n SlapLogout \\\n LoginERP5TypeTestCase \\\n CheckSiteConsistency \\\n Logout \\\n '\n sequence_list.addSequenceString(sequence_string)\n sequence_list.play(self)",
"def create_waitinglist(dbo, username, collationid):\n l = dbo.locale\n fields = get_onlineformincoming_detail(dbo, collationid)\n d = {}\n d[\"dateputon\"] = i18n.python2display(l, i18n.now(dbo.timezone))\n d[\"urgency\"] = \"5\"\n for f in fields:\n if f[\"FIELDNAME\"] == \"species\": d[\"species\"] = guess_species(dbo, f[\"VALUE\"])\n if f[\"FIELDNAME\"] == \"description\": d[\"description\"] = f[\"VALUE\"]\n if f[\"FIELDNAME\"] == \"reason\": d[\"reasonforwantingtopart\"] = f[\"VALUE\"]\n if not d.has_key(\"species\"): d[\"species\"] = guess_species(dbo, \"\")\n # Have we got enough info to create the waiting list record? We need a description\n if not d.has_key(\"description\"):\n raise utils.ASMValidationError(i18n._(\"There is not enough information in the form to create a waiting list record (need a description).\", l))\n # We need the person record before we create the waiting list\n collationid, personid, personname = create_person(dbo, username, collationid)\n d[\"owner\"] = personid\n # Create the waiting list\n wlid = waitinglist.insert_waitinglist_from_form(dbo, utils.PostedData(d, dbo.locale), username)\n # Attach the form to the waiting list\n formname = get_onlineformincoming_name(dbo, collationid)\n formhtml = get_onlineformincoming_html(dbo, collationid)\n media.create_document_media(dbo, username, media.WAITINGLIST, wlid, formname, formhtml )\n return (collationid, wlid, utils.padleft(wlid, 6) + \" - \" + personname)",
"def _on_toggled(self, check, index):\r\n\r\n check.handler_block(self._lst_handler_id[index])\r\n\r\n self._software_model.lst_development[index] = int(check.get_active())\r\n\r\n check.handler_unblock(self._lst_handler_id[index])\r\n\r\n return False",
"def set_add_dispute_status(self, status):\n self.single_selection_from_kendo_dropdown(self.add_dispute_status_kendo_dropdown_locator, status)\n self.wait_for_ajax_spinner_load()",
"def soft_assert_bulk_verify_for_in_review_state(page, asmt, soft_assert,\n is_available):\n rest_facade.update_object(asmt, status=object_states.READY_FOR_REVIEW)\n browsers.get_browser().refresh()\n ui_utils.wait_for_spinner_to_disappear()\n soft_assert.expect(\n page.is_bulk_verify_displayed() == is_available,\n \"Bulk Verify should {} be available if assessment is in '{}' status.\"\n .format(\"\" if is_available else \"not\", object_states.READY_FOR_REVIEW))",
"def test_visibility_of_not_available_4(self):\n partner = PartnerFactory(status=Partner.NOT_AVAILABLE)\n list_url = reverse('partners:list')\n\n editor = EditorFactory()\n editor.user.is_staff = True\n editor.user.save()\n\n request = RequestFactory().get(list_url)\n request.user = editor.user\n response = PartnersListView.as_view()(request)\n\n self.assertContains(response, partner.get_absolute_url())",
"def set_present(self, absentee: QualifiedAgent):\n wum: WorklistUpdateManagerApi = self._service_provider.get_service(WorklistUpdateManagerApi)\n wum.set_present(body=absentee)",
"def toggled_monitor(self):\n if self.pushButton_monitor.isChecked():\n \n if not self.connect_serial():\n self.pushButton_monitor.setChecked(0)\n return\n \n self.textBrowser.insertPlainText(\n QtGui.QApplication.translate(\n \"MainWindow\", \n \"\\n\\t----NEW MONITORING----\\n\", \n None, \n QtGui.QApplication.UnicodeUTF8))\n \n id_link = self.listWidget_link.selectedItems()\n if len(id_link):\n id_link = int(id_link[0].text())\n else:\n id_link = 1\n \n self.textBrowser.insertPlainText(QtGui.QApplication.translate(\"MainWindow\", \"link to monitor : \", None, QtGui.QApplication.UnicodeUTF8)+str(id_link)+\"\\n\")\n \n word = struct.pack(\"BBBBBBBB\", ID_MONITOR,0,0,0,0,0,0,id_link&0xFF)\n \n self.textBrowser.append(\n QtGui.QApplication.translate(\n \"MainWindow\", \n \"Sent : \", \n None, \n QtGui.QApplication.UnicodeUTF8)+\n binascii.hexlify(word)+\n \"\\n\")\n \n self.ser.write(word)\n \n # clear data of the serial port\n self.ser.flushInput()\n # clear graph\n self.clean_graph()\n # start timer data reception\n self.get_periodical_data()\n # start timer graphic refresh\n self.update_graph()\n \n self.pushButton_save.setEnabled(False)\n else:\n # send Monitor\n word = struct.pack(\"BBBBBBBB\", ID_MONITOR+ID_STOP,0,0,0,0,0,0,0)\n \n self.textBrowser.append(QtGui.QApplication.translate(\"MainWindow\", \"Sent : \", None, QtGui.QApplication.UnicodeUTF8)+binascii.hexlify(word)+\"\\n\")\n \n self.ser.write(word)\n \n self.ser.flushInput()\n \n # reload number of waiting chars in serial rx buffer\n self.label_rx_buff_value.setText(str(self.ser.inWaiting()))\n \n self.textBrowser.insertPlainText(QtGui.QApplication.translate(\"MainWindow\", \"\\n\\t----END MONITORING----\\n\", None, QtGui.QApplication.UnicodeUTF8))\n \n self.pushButton_save.setEnabled(True)\n \n if (not self.pushButton_reload.isChecked()):\n self.timer_data.stop()\n self.timer_graph.stop()",
"def test_POST_send_list(self):\n\t\tself.POST_list()\n\t\tlist = self.GET_data('/api/list/' + self.list_id)\n\t\tself.POST_data('/api/list/' + self.list_id + '/send', data=list)",
"def fetch(self):\r\n if self.wp_op is None: # If we were already doing a list or save, just restart the fetch without changing the operation\r\n self.wp_op = \"fetch\"\r\n self.master.waypoint_request_list_send()",
"def set_vendor_price_list_status(self, status_items):\n self.multiple_items_selection_from_kendo_dropdown(self.vendor_price_list_status_kendo_dropdown_locator, status_items)\n self.wait_for_ajax_spinner_load()"
] | [
"0.7670878",
"0.6666528",
"0.56722414",
"0.55193806",
"0.5351408",
"0.5345447",
"0.5301888",
"0.52788526",
"0.5212124",
"0.51382023",
"0.50874275",
"0.50684017",
"0.50450104",
"0.504299",
"0.5028085",
"0.5021842",
"0.5020913",
"0.5017552",
"0.49849492",
"0.49838495",
"0.49824235",
"0.4943671",
"0.49360374",
"0.49208075",
"0.4915748",
"0.49019656",
"0.48874834",
"0.48750564",
"0.48732883",
"0.48625392"
] | 0.77193904 | 0 |
Only coordinators can post to the toggle waitlist view. | def test_toggle_waitlist_access(self):
# Create needed objects.
editor = EditorFactory()
coordinators = get_coordinators()
coordinators.user_set.add(editor.user)
UserProfileFactory(user=editor.user, terms_of_use=True)
partner = PartnerFactory(status=Partner.AVAILABLE)
# Set up request.
url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})
request = RequestFactory().post(url)
request.user = editor.user
# This should work and not throw an error.
resp = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)
coordinators.user_set.remove(editor.user)
with self.assertRaises(PermissionDenied):
_ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def can_act(self, **kwargs):\n return True",
"def test_toggle_waitlist_1(self):\n # Create needed objects.\n editor = EditorFactory()\n coordinators = get_coordinators()\n coordinators.user_set.add(editor.user)\n UserProfileFactory(user=editor.user, terms_of_use=True)\n\n partner = PartnerFactory(status=Partner.AVAILABLE)\n\n # Set up request.\n url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})\n\n request = RequestFactory().post(url)\n request.user = editor.user\n\n _ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)\n partner.refresh_from_db()\n self.assertEqual(partner.status, Partner.WAITLIST)",
"def test_toggle_waitlist_2(self):\n # Create needed objects.\n editor = EditorFactory()\n coordinators = get_coordinators()\n coordinators.user_set.add(editor.user)\n UserProfileFactory(user=editor.user, terms_of_use=True)\n\n partner = PartnerFactory(status=Partner.WAITLIST)\n\n # Set up request.\n url = reverse('partners:toggle_waitlist', kwargs={'pk': partner.pk})\n\n request = RequestFactory().post(url)\n request.user = editor.user\n\n _ = PartnersToggleWaitlistView.as_view()(request, pk=partner.pk)\n partner.refresh_from_db()\n self.assertEqual(partner.status, Partner.AVAILABLE)",
"def authorizeClients(self):\n pass",
"def action_checkbox(self):\n self.checkbox_online_var = not self.checkbox_online_var",
"def toggled_comunication(self):\n if self.actionPC_Monitor.isChecked() and self.actionPC_Monitor.isEnabled():\n self.actionPC_Monitor.setEnabled(0)\n self.actionPC_Sensor_Actuador.setChecked(0)\n self.actionPC_Sensor_Actuador.setEnabled(1)\n self.monitor_environment()\n \n elif self.actionPC_Sensor_Actuador.isChecked() and self.actionPC_Sensor_Actuador.isEnabled():\n self.actionPC_Sensor_Actuador.setEnabled(0)\n self.actionPC_Monitor.setChecked(0)\n self.actionPC_Monitor.setEnabled(1)\n self.actuator_environment()",
"def can_view_post(user):\n #only students and admins may use the search, submitForm functions\n return (not bool(user.is_staff) or user.is_superuser)",
"def is_on_waiting_list(self):\n if self.user is None:\n return False\n if unicode(self.user._id) in self.barcamp.event.waiting_list:\n return True\n return False",
"def ToggleApprovalTracker(self, event):\n pass",
"def _client_allowed(self):\r\n client_ip = self._client_address[0]\r\n if not client_ip in self._settings.allowed_clients and \\\r\n not 'ALL' in self._settings.allowed_clients:\r\n self._send_content('Access from host %s forbidden.' % client_ip, 'text/html')\r\n return False\r\n return True",
"def test_post_forbid_anonymous(self):\n self.check_post_forbid_anonymous('FORBID_ANONYMOUS')",
"def can_pickup(self):\n return False",
"def is_controlled(self):\n return QtCore.QThread.currentThread() is self.thread",
"def test_published_story_must_be_visible_for_everyone_but_blocked(self):\n self.assertEqual(self.ps.is_visible_for(self.au), True)\n\n \"\"\" Published story must be visible for another.\"\"\"\n self.assertEqual(self.ps.is_visible_for(self.u2), True)\n\n \"\"\" Publsihed story must be visible for owner. \"\"\"\n self.assertEqual(self.ps.is_visible_for(self.u1), True)\n\n \"\"\" Draft story must not be visible for a blocked user. \"\"\"\n self.assertEqual(self.ds.is_visible_for(self.u3), False)",
"def is_visible_to(self, user):\n return True",
"def __taskMarkersUpdated(self, editor):\n if editor.hasTaskMarkers():\n self.taskNextAct.setEnabled(True)\n self.taskPreviousAct.setEnabled(True)\n else:\n self.taskNextAct.setEnabled(False)\n self.taskPreviousAct.setEnabled(False)",
"def CanVeto(self):\r\n\r\n return self.canveto_flag and self.veto_flag",
"def canShare(self):\n return False",
"def can_communicate_with(self, target):\n if self == target:\n return True\n msg = 'You try to connect topologies belonging to'\n msg += ' two different mpi tasks. Set taskids properly or use'\n msg += ' InterBridge.'\n assert self.task_id() == target.task_id(), msg\n\n # Parent communicator\n # Todo : define some proper conditions for compatibility\n # between topo_from, topo_to and parent:\n # - same size\n # - same domain\n # - common processus ...\n # At the time we check that both topo have\n # the same comm_origin.\n return self.is_consistent_with(target)",
"def getSubmitAllowNeeds(self):\n return self.config",
"def _on_schedule_toggle(self, kwargs: dict) -> None:\n if kwargs.get(\"opposite\"):\n self.toggle(opposite_of=kwargs[\"state\"])\n else:\n self.toggle(state=kwargs[\"state\"])",
"def is_admin(self, user):\n return (acl.action_allowed(self.request, 'OperatorDashboard', '*') or\n acl.action_allowed(self.request, 'Feed', 'Curate'))",
"def supports_visible_federation(self):\n return False",
"def supports_visible_federation(self):\n return False",
"def can_view(self, user):\r\n return True",
"def is_dispatchable(self):\n return self.get_interaction().is_dispatchable()",
"def can_be_viewed_by(self,user):\n return True",
"def is_donor(self):\n return True",
"def on_CheckNodeSyncNTP_clicked(self):\n # TODO: not implemented yet\n raise NotImplementedError",
"def allowed_topology_access_create(user):\n return user.has_perm(\"vnswww.add_topology\")"
] | [
"0.549368",
"0.5480025",
"0.5450405",
"0.53964716",
"0.53499454",
"0.52849954",
"0.52098906",
"0.51941323",
"0.5193125",
"0.517576",
"0.5156091",
"0.5128045",
"0.51259947",
"0.508918",
"0.50775003",
"0.5053379",
"0.5033265",
"0.49727577",
"0.49623498",
"0.49541065",
"0.49317604",
"0.49160987",
"0.49092788",
"0.49092788",
"0.49054283",
"0.49033567",
"0.4901589",
"0.48869118",
"0.4884119",
"0.48821077"
] | 0.629319 | 0 |
This builds your guide. | def build_guide(self, **kwargs):
# This builds your guide master and updates your options
self.create_guide_master(**kwargs)
prefix = self.prefix
options = self.options
mirror_value = self.mirror_value
num_joints = options.get('numberJoints')
single_joint = options.get('singleJoint')
pickWalk_parent = options.get('pickWalkParent')
num_joints += 1
if single_joint:
num_joints = 1
# Builde joints
if single_joint:
jnt_zero, plc, jnt = self.guide_joint(constraint_type='parent')
zero, ctrl = self.guide_ctrl(shape='circle', color='light_blue', driver=jnt, axis='X')
ctrls = [ctrl]
zeros = [zero]
else:
jnt_zeros, plcs, jnts = self.guide_joint_chain('', num_joints=num_joints)
zeros, ctrls = [], []
for i, jnt in enumerate(jnts[:-1]):
letter = utils.letters[i]
zero, ctrl = self.guide_ctrl(name=letter, shape='circle',
color='light_blue', driver=jnt, axis='X')
zeros.append(zero)
ctrls.append(ctrl)
mc.xform(zeros, jnt_zeros, r=1, t=[-1*self.mirror_value, 0, 0])
# lock stuff
pivots = [mc.listRelatives(c, p=1)[0] for c in ctrls]
utils.set_attrs(zeros, l=1, k=0)
utils.set_attrs(pivots, 't s', l=1, k=0)
mc.setAttr(self.guide_master+'.offsetTranslateX', -0.5*self.mirror_value)
# This finalizes your guide.
self.finalize_guide() | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def build_guide(self, **kwargs):\n\n # This builds your guide master and updates your options\n self.create_guide_master(**kwargs)\n\n prefix = self.prefix\n options = self.options\n mirror_value = self.mirror_value\n\n number_mid_ctrl = options.get('numberMidCtrls')\n num_joints = options.get('numberJoints')\n create_jaw = options.get('createJaw')\n create_skull = options.get('createReverseJaw')\n surface = options.get('createSurfaceDriver')\n create_fk_ctrls = options.get('createFKShaperCtrls')\n\n noxform_grp = self.guide_master + '_NOX'\n\n if mc.objExists ('drivenNeck_chest_Mid_bind'):\n mc.delete ('drivenNeck_chest_Mid_bind')\n\n\n pp = env.get_parts_paths()[-1]\n branch = r'BidepAutoRig\\part_joints\\neck_skel.mb'\n import_path = pp.replace('partsLibrary', branch)\n mc.file(import_path, i=1)\n\n if mc.objExists ('snap_chest_Mid_jnt'):\n mc.delete (mc.parentConstraint ('snap_chest_Mid_bind', 'drivenNeck_chest_Mid_bind'))\n\n\n snaps=[u'head_Mid_bind', u'headEnd_Mid_jnt', u'eye_Lt_bind', u'eye_Rt_bind', u'headTop_Mid_bind',\n u'headRear_Mid_bind', u'headSide_Lt_bind', u'headSide_Rt_bind', u'neck01_Mid_bind', u'neck02_Mid_bind',\n u'neck03_Mid_bind', u'neckEnd_Mid_jnt']\n\n for snap in snaps:\n target='snap_'+snap\n if mc.objExists (target):\n mc.delete (mc.parentConstraint (target, snap))\n\n\n\n\n # This finalizes your guide.\n self.finalize_guide()\n jnts_grp = self.guide_master + '_JNTS'\n mc.parent ('drivenNeck_chest_Mid_bind', jnts_grp)\n\n self.finalize_guide()",
"def build_guide(self, **kwargs):\n\n # This builds your guide master and updates your options\n self.create_guide_master(**kwargs)\n\n prefix = self.prefix # Naming prefix. Use this for every new node you create and there should be no name clashes.\n options = self.options # Build options\n mirror_value = self.mirror_value # 1.0 for left and center sided parts and -1.0 for right sided part.\n\n mc.setAttr(self.guide_master+'.offsetTranslateY', -0.2)\n\n l_prefix = prefix.replace('C','L', 1)\n r_prefix = prefix.replace('C','R', 1)\n mirror_values = [1, -1]\n enable_steering = options.get('enableSteering')\n\n colors = ['green', 'red']\n\n for mi, prefix in enumerate([l_prefix, r_prefix]):\n\n mirror_value = mirror_values[mi]\n color = colors[mi]\n\n l_main_zero, l_main_plc = self.guide_joint('main', alt_prefix=prefix, placer_only=1)\n\n # create hub\n hub_zero, hub_plc, hub_jnt = self.guide_joint('wheelhub', alt_prefix=prefix, constraint_type='point')\n hub_end_zero, hub_end_plc, hub_end_jnt = self.guide_joint('wheelhub_end', alt_prefix=prefix, constraint_type='point')\n\n mc.xform(hub_end_zero, r=1, t=[1,0,0])\n mc.parent(hub_end_jnt, hub_jnt)\n mc.aimConstraint(hub_end_plc, hub_jnt, aim=[mirror_value,0,0], u=[0,1,0], wu=[0,1,0], wut='vector')\n mc.parentConstraint(hub_plc, hub_end_zero , mo=1)\n\n # Create steering arm\n steer_zero, steer_plc, steer_jnt = self.guide_joint('steeringArm', alt_prefix=prefix, constraint_type='parent')\n mc.xform(steer_zero, r=1, t=[-1,0,0])\n mc.parent(hub_jnt, steer_jnt)\n\n # Create shocks\n shock_a_zero, shock_a_plc, shock_a_jnt = self.guide_joint('shock_A', alt_prefix=prefix, constraint_type='point')\n shock_b_zero, shock_b_plc, shock_b_jnt = self.guide_joint('shock_B', alt_prefix=prefix, constraint_type='point')\n\n mc.xform(shock_a_zero, ws=1, t=[-2,2,0])\n mc.xform(shock_b_zero, ws=1, t=[-0.5,0.25,0])\n\n mc.parent(shock_b_jnt, shock_a_jnt)\n\n mc.aimConstraint(shock_b_plc, shock_a_jnt, aim=[mirror_value,0,0], u=[0,0,1], wu=[0,0,1], wut='vector')\n mc.aimConstraint(shock_a_plc, shock_b_jnt, aim=[-mirror_value,0,0], u=[0,0,1], wu=[0,0,1], wut='vector')\n\n # upper arm\n up_arm_zero, up_arm_plc, up_arm_jnt = self.guide_joint('upperArm', alt_prefix=prefix, constraint_type='point')\n up_arm_end_zero, up_arm_end_plc, up_arm_end_jnt = self.guide_joint('upperArm_end', alt_prefix=prefix, constraint_type='point')\n\n mc.xform(up_arm_end_zero, r=1, t=[-3.5,1,0])\n mc.xform(up_arm_zero, r=1, t=[-1,0.5,0])\n mc.parent(up_arm_end_jnt, up_arm_jnt)\n mc.aimConstraint(up_arm_end_plc, up_arm_jnt, aim=[mirror_value,0,0], u=[0,0,1], wu=[0,0,mirror_value], wut='objectRotation', wuo=up_arm_plc)\n\n # lower arm\n lo_arm_zero, lo_arm_plc, lo_arm_jnt = self.guide_joint('lowerArm', alt_prefix=prefix, constraint_type='point')\n lo_arm_end_zero, lo_arm_end_plc, lo_arm_end_jnt = self.guide_joint('lowerArm_end', alt_prefix=prefix, constraint_type='point')\n\n mc.xform(lo_arm_end_zero, r=1, t=[-4,-0.5,0])\n mc.xform(lo_arm_zero, r=1, t=[-1,-0.5,0])\n mc.parent(lo_arm_end_jnt, lo_arm_jnt)\n mc.aimConstraint(lo_arm_end_plc, lo_arm_jnt, aim=[mirror_value,0,0], u=[0,0,1], wu=[0,0,mirror_value], wut='objectRotation', wuo=lo_arm_plc)\n\n # steeringArm\n if enable_steering:\n steeringArm_a_zero, steeringArm_a_plc, steeringArm_a_jnt = self.guide_joint('steeringArm_A', alt_prefix=prefix, constraint_type='point')\n steeringArm_b_zero, steeringArm_b_plc, steeringArm_b_jnt = self.guide_joint('steeringArm_B', alt_prefix=prefix, constraint_type='point')\n\n mc.xform(steeringArm_b_zero, r=1, t=[-1.5,0,1])\n mc.xform(steeringArm_a_zero, r=1, t=[-4,0,1])\n\n mc.parent(steeringArm_b_jnt, steeringArm_a_jnt)\n mc.aimConstraint(steeringArm_b_plc, steeringArm_a_jnt, aim=[mirror_value,0,0], u=[0,0,1], wu=[0,0,1], wut='vector')\n\n # Create control\n zero, ctrl = self.guide_ctrl('wheel', alt_prefix=prefix, driver=hub_end_jnt, color=color, shape='circle', axis='X', scale=[3]*3, create_pivot=0)\n mc.setAttr(ctrl+'.numOffsetCtrls', 1)\n mc.addAttr(ctrl+'.numOffsetCtrls', e=1, min=1)\n mc.xform(ctrl.replace('_CTL','_A_OFF_CTL.cv[*]'), r=1, s=[0.8]*3)\n\n control.create_shape('wheel', ctrl, axis='X', scale=[3]*3)\n\n #suspension_zero, suspension_ctrl = self.guide_ctrl('suspension', create_pivot=0, driver=shock_a_jnt, axis='X', shape='pyramid', color=color, scale=[1.5,1,1], alt_prefix=prefix)\n ground_zero, ground_ctrl = self.guide_ctrl('ground', create_pivot=0, shape='square', color='grass', alt_prefix=prefix)\n mc.delete(mc.pointConstraint(hub_jnt, ground_zero))\n\n # constraint to placer\n childs = [prefix+'_wheelhub_JNT_PLC_ZERO',\n prefix+'_steeringArm_JNT_PLC_ZERO',\n prefix+'_shock_A_JNT_PLC_ZERO',\n prefix+'_shock_B_JNT_PLC_ZERO',\n prefix+'_upperArm_JNT_PLC_ZERO',\n prefix+'_upperArm_end_JNT_PLC_ZERO',\n prefix+'_lowerArm_JNT_PLC_ZERO',\n prefix+'_lowerArm_end_JNT_PLC_ZERO']\n\n for c in childs:\n mc.parentConstraint(l_main_plc, c, mo=1)\n\n mc.setAttr(l_main_plc+'.offsetTranslateY', mirror_value*0.5)\n\n # ################3\n # Place it all\n hub_pos = mc.ls(options.get('hubCenter') or '')\n if hub_pos:\n loc = utils.snap_locator(hub_pos)\n mc.delete(mc.pointConstraint(loc, self.guide_master))\n mc.setAttr(self.guide_master+'.tx', 0)\n mc.delete(mc.pointConstraint(loc, l_main_plc), loc)\n\n hub_end_pos = mc.ls(options.get('hubEndCenter') or '')\n if hub_end_pos:\n loc = utils.snap_locator(hub_end_pos)\n mc.delete(mc.pointConstraint(loc, hub_end_plc), loc)\n\n else:\n mc.xform(self.guide_master, ws=1, t=[0,2,10])\n mc.xform(l_main_plc, r=1, t=[mirror_value*6,0,0])\n\n mc.setAttr(self.guide_master+'.jointAxisVis', 1)\n\n l = utils.snap_locator(hub_jnt)\n mc.setAttr(l+'.ty', 0)\n mc.delete(mc.pointConstraint(l, ground_zero), l)\n\n chassis_plc_zero, chassis_plc = self.guide_joint('chassis_driver', placer_only=1)\n mc.setAttr(chassis_plc+'.radius', 1)\n mc.setAttr(chassis_plc+'.color', 0.96, 0.71, .01)\n mc.setAttr(chassis_plc+'.otherType', 'Leg IK Driver', type='string');\n mc.setAttr(chassis_plc+'.type', 18)\n\n mc.pointConstraint(l_prefix+'_lowerArm_end_JNT_PLC', r_prefix+'_lowerArm_end_JNT_PLC', chassis_plc_zero)\n utils.set_attrs(chassis_plc, l=1, k=0)\n\n # This finalizes your guide.\n self.finalize_guide()\n self.mirror_guide()",
"def build():",
"def generate_documentation(self):\n self.generate_api_docs()\n build.main([\n self.SOURCE_DIR,\n self.BUILD_DIR,\n ])",
"def main():\n # We know that qidoc build will set the correct cwd\n qibuild_dir = \"..\"\n qibuild_dir = os.path.abspath(qibuild_dir)\n this_file = __file__\n this_dir = os.path.dirname(this_file)\n cmake_api = os.path.join(this_dir, \"../source/advanced/cmake/api\")\n cmake_api = os.path.abspath(cmake_api)\n if not os.path.exists(cmake_api):\n os.makedirs(cmake_api)\n qibuild_cmake = os.path.join(qibuild_dir, \"cmake\", \"qibuild\")\n for filename in DOCUMENTED_FILES:\n cmake_file = os.path.join(qibuild_cmake, filename + \".cmake\")\n rst_file = os.path.join(cmake_api, filename + \".rst\")\n gen_cmake_doc(cmake_file, rst_file)",
"def run():\n build_no_documentation()\n build_sphinx_build()\n #build_sphinx_pdf()\n build_graphviz_files()",
"def buildDocumentation():\n helptext = 'usage: build_doc.py <output format> <type of documentation>' \\\n '\\n - html: for html output' \\\n '\\n - pdf: for pdf output' \\\n '\\n\\n - all: complete documentation' \\\n '\\n - dev: only developer documentation' \\\n '\\n - user: only user documentation'\n if len(sys.argv) != 3:\n print helptext\n sys.exit(1)\n\n if sys.argv[1] not in ['pdf', 'html']:\n print helptext\n sys.exit(1)\n if sys.argv[2] not in ['all', 'dev', 'user']:\n print helptext\n sys.exit(1)\n\n copyfile('docs/index_%s.rst.template' % sys.argv[2], 'index.rst') # copy main file into root directory\n os.system('sphinx-build -b %s -c docs -D master_doc=index . docs/output/%s/%s' % (sys.argv[1], sys.argv[1], sys.argv[2]))\n os.remove('index.rst') # delete config file from root directory",
"def cli(ctx, **kwds):\n invalid = _validate_kwds(kwds)\n if invalid:\n ctx.exit(invalid)\n tool_description = tool_builder.build(**kwds)\n tool_builder.write_tool_description(ctx, tool_description, **kwds)",
"def build(_):",
"def _build(self):",
"def _build(self):",
"def build(self):",
"def build(self):",
"def build(self):",
"def CreateGuideWindows(self):\r\n\r\n self.DestroyGuideWindows()\r\n\r\n self._guides.append(AuiDockingGuideInfo().Left().\r\n Host(AuiSingleDockingGuide(self._frame, wx.LEFT)))\r\n self._guides.append(AuiDockingGuideInfo().Top().\r\n Host(AuiSingleDockingGuide(self._frame, wx.TOP)))\r\n self._guides.append(AuiDockingGuideInfo().Right().\r\n Host(AuiSingleDockingGuide(self._frame, wx.RIGHT)))\r\n self._guides.append(AuiDockingGuideInfo().Bottom().\r\n Host(AuiSingleDockingGuide(self._frame, wx.BOTTOM)))\r\n self._guides.append(AuiDockingGuideInfo().Centre().\r\n Host(AuiCenterDockingGuide(self._frame)))",
"def build(self) -> None:",
"def docs():\n sh('sphinx-build -W -b html docs docs/_build/html')",
"def build(self):\n pass",
"def build(self):\n pass",
"def register_adhocs(self):\n aboutform = self.plugin['xep_0004'].makeForm('form', \"About SleekBot\")\n aboutform.addField('about', 'fixed', value= self.__doc__)\n self.plugin['xep_0050'].addCommand('about', 'About Sleekbot', aboutform)\n pluginform = self.plugin['xep_0004'].makeForm('form', 'Plugins')\n plugins = pluginform.addField('plugin', 'list-single', 'Plugins')\n for key in self.cmd_plugins:\n plugins.addOption(key, key)\n plugins = pluginform.addField('option', 'list-single', 'Commands')\n plugins.addOption('about', 'About')\n #plugins.addOption('config', 'Configure')\n self.plugin['xep_0050'].addCommand('plugins', 'Plugins', pluginform, self.form_plugin_command, True)",
"def build_docs(open_docs):\n python_call(\"pip\", [\"install\", \"src/[docs]\"])\n python_call(\"pip\", [\"install\", \"-r\", \"src/requirements.txt\"])\n python_call(\n \"ipykernel\", [\"install\", \"--user\", \"--name=za_covid_map\"]\n )\n shutil.rmtree(\"docs/build\", ignore_errors=True)\n call(\n [\n \"sphinx-apidoc\",\n \"--module-first\",\n \"-o\",\n \"docs/source\",\n \"src/za_covid_map\",\n ]\n )\n call([\"sphinx-build\", \"-M\", \"html\", \"docs/source\", \"docs/build\", \"-a\"])\n if open_docs:\n docs_page = (Path.cwd() / \"docs\" / \"build\" / \"html\" / \"index.html\").as_uri()\n secho(\"Opening {}\".format(docs_page))\n webbrowser.open(docs_page)",
"def beehive_make_doc(self):\n run_data = {\n u'tags':[u'doc'],\n u'local_package_path':self.local_package_path\n } \n self.ansible_playbook(u'docs', run_data, \n playbook=self.beehive_doc_playbook)",
"def goto_guidelines(self):\n\n self.guidelines.click()",
"def main():\n\n dofile = \"thebook\"\n\n #spellcheck()\n\n common_options = '--encoding=utf-8 --examples_as_exercises '\n\n # --- HTML ---\n\n common_html_options = ' '\n\n # HTML Bootstrap\n bootstrap_options = ' --html_style=bootswatch_readable --html_code_style=inherit --html_pre_style=inherit --toc_depth=2 --pygments_html_style=default --html_template=template_bootstrap_wtoc.html --html_figure_caption=bottom --html_figure_hrule=top+bottom' \n\n html(\n dofile,\n options=common_options + common_html_options + bootstrap_options,\n split=True)\n\n # One long HTML file\n #html(dofile, options=common_options + common_html_options + ' --html_style=bloodish --html_output=%s-1' % dofile, split=False)\n\n # Solarized HTML\n #html(dofile, options=common_options + common_html_options + ' --html_style=solarized3 --html_output=%s-solarized' % dofile, split=True)\n\n mksnippets()\n sys.exit(1)\n\n # --- latex ---\n\n common_latex_options = ' --latex_code_style=vrb'\n\n for version in 'paper', 'screen': # , 'A4', '2up', 'A4-2up':\n latex(\n dofile,\n latex_program='pdflatex',\n options=common_options + common_latex_options,\n version=version,\n postfix='auto')\n\n # --- Sphinx ---\n\n# sphinx_themes = ['pyramid',]\n# for theme in sphinx_themes:\n# dirname = 'sphinx-rootdir' if len(sphinx_themes) == 1 else 'sphinx-rootdir-%s' % theme\n# sphinx(\n# dofile,\n# options=common_options + '',\n# dirname=dirname,\n# theme=theme,\n# automake_sphinx_options='',\n# split=False)\n\n # Dump all Unix commands run above as a Bash script\n bash = open('tmp_make.sh', 'w')\n print 'see tmp_make.sh for an equivalent auto-generated unix script'\n bash.write('''#!/bin/bash\nset -x # display all commands in output\n\n# Safe execution of a Unix command: exit if failure\nfunction system {\n \"$@\"\n if [ $? -ne 0 ]; then\n echo \"make.sh: unsuccessful command $@\"\n echo \"abort!\"\n exit 1\n fi\n}\n''')\n for cmd in unix_command_recorder:\n if cmd.startswith('doconce format') or cmd.startswith('rm '):\n bash.write('\\n') # delimiter line in script\n bash.write('system ' + cmd + '\\n')\n bash.close()\n\n print 'see tmp_output.log for the output of all the commands'",
"def generate():\n local('cd doc && make clean && make html')",
"def _sphinx_build(self, kind: str):\n if kind not in (\"html\", \"latex\"):\n raise ValueError(f\"kind must be html or latex, not {kind}\")\n\n cmd = [\"sphinx-build\", \"-b\", kind]\n if self.num_jobs:\n cmd += [\"-j\", self.num_jobs]\n if self.warnings_are_errors:\n cmd += [\"-W\", \"--keep-going\"]\n if self.verbosity:\n cmd.append(f\"-{'v' * self.verbosity}\")\n cmd += [\n \"-d\",\n os.path.join(BUILD_PATH, \"doctrees\"),\n SOURCE_PATH,\n os.path.join(BUILD_PATH, kind),\n ]\n return subprocess.call(cmd)",
"def _sphinx_build(self, kind: str):\n if kind not in (\"html\", \"latex\"):\n raise ValueError(f\"kind must be html or latex, not {kind}\")\n\n cmd = [\"sphinx-build\", \"-b\", kind]\n if self.num_jobs:\n cmd += [\"-j\", self.num_jobs]\n if self.warnings_are_errors:\n cmd += [\"-W\", \"--keep-going\"]\n if self.verbosity:\n cmd.append(f\"-{'v' * self.verbosity}\")\n cmd += [\n \"-d\",\n os.path.join(BUILD_PATH, \"doctrees\"),\n SOURCE_PATH,\n os.path.join(BUILD_PATH, kind),\n ]\n return subprocess.call(cmd)",
"def build_gitbook(certification, certification_dir, output_dir):\n return certifications_to_gitbook.create_gitbook_documentation(\n certification=certification,\n certification_dir=certification_dir,\n output_path=output_dir\n )",
"def docs_build(directory, site_name, view=True, assume_yes=False):\n context = toolkit.load_data_context_with_error_handling(directory)\n build_docs(context, site_name=site_name, view=view, assume_yes=assume_yes)\n toolkit.send_usage_message(\n data_context=context, event=\"cli.docs.build\", success=True\n )",
"def main():\n sys.argv.extend(('--linklint-dir', THIS_DIR,\n '--source-dir', os.path.join(THIS_DIR, 'src'),\n '--project-dir', PROJECT_DIR))\n return docs.generate_docs.main()"
] | [
"0.68431896",
"0.678747",
"0.6215074",
"0.6041127",
"0.6009198",
"0.5988244",
"0.59658515",
"0.5965333",
"0.5948795",
"0.5916978",
"0.5916978",
"0.5844977",
"0.5844977",
"0.5844977",
"0.5744313",
"0.57021093",
"0.567816",
"0.55941284",
"0.55941284",
"0.5589465",
"0.557288",
"0.55660325",
"0.5550635",
"0.5510799",
"0.55097306",
"0.54933864",
"0.54933864",
"0.54831433",
"0.5480806",
"0.547491"
] | 0.70145535 | 0 |
This builds your anim rig. | def build_rig(self):
# create rig part top nodes
self.create_part_master()
# Get all the relevant part info
prefix = self.prefix
options = self.options
anim_ctrls = self.anim_ctrls
bind_jnts = self.bind_joints
hooks = self.hooks
ctrl_grps = self.ctrl_grps
jnt_grps = self.jnt_grps
mirror = self.mirror_value
parent = options.get('parent')
squash_stretch = options.get('squashStretch')
aimDownBone = options.get('aimDownBone')
single_joint = options.get('singleJoint')
number_joints = options.get('numberJoints')
pickWalk_parent = options.get('pickWalkParent')
# Create ctrls
zeros, ctrls, offsets, last_nodes = [], [], [], []
for i, ctrl_name in enumerate(anim_ctrls):
zero, ctrl, offCtrls, last_node = self.anim_ctrl(ctrl_name)
zeros.append(zero)
ctrls.append(ctrl)
offsets.append(offCtrls)
last_nodes.append(last_node)
#Setup pickwaliking attributes for the fingers
i = 0
ctrls.reverse()
for ctrl in ctrls:
if i+1 < len(ctrls):
pickWalk.attribute_tag(ctrls[i],ctrls[i+1])
else:
pickWalk.attribute_tag(ctrls[i],pickWalk_parent)
break
i+=1
ctrls.reverse()
if len(ctrls) > 1:
for i in range(1, len(ctrls), 1):
mc.parent(zeros[i], last_nodes[i-1])
# constraint jnts
if len(bind_jnts) > 2:
# point and aim/orient contraint all joints down the chain based on the
for i in range(len(last_nodes)-1):
mc.pointConstraint(last_nodes[i], bind_jnts[i], mo=1, n=bind_jnts[i]+'_pc')
if not squash_stretch:
mc.scaleConstraint(last_nodes[i], bind_jnts[i], mo=1, n=bind_jnts[i]+'_sc')
if i < len(last_nodes)-1:
print aimDownBone
if aimDownBone:
mc.aimConstraint(last_nodes[i+1],
bind_jnts[i],
aim=[mirror,0,0],
u=[0,1,0],
wu=[0,1,0],
wut='objectRotation',
wuo=last_nodes[i],
mo=1, n=bind_jnts[i]+'_ac')
if aimDownBone == False:
mc.orientConstraint(last_nodes[i],bind_jnts[i],n=bind_jnts[i]+'_oc')
#parent constrain the last joint ot the last ctrl
# mc.parentConstraint(last_nodes[-1], bind_jnts[-2], mo=1, n=bind_jnts[-2]+'_prc')
# mc.parentConstraint(last_nodes[-1], bind_jnts[-1], mo=1, n=bind_jnts[-1]+'_prc')
# if not squash_stretch:
# mc.scaleConstraint(last_nodes[-1], bind_jnts[-2], mo=1, n=bind_jnts[-2]+'_sc')
# mc.scaleConstraint(last_nodes[-1], bind_jnts[-1], mo=1, n=bind_jnts[-1]+'_sc')
elif single_joint or number_joints == 1:
mc.parentConstraint(last_nodes[0], bind_jnts[0], mo=1, n=bind_jnts[0]+'_prc')
mc.scaleConstraint(last_nodes[0], bind_jnts[0], mo=1, n=bind_jnts[0]+'_sc')
else:
if squash_stretch:
spline.preserve_volume(ctrls, bind_jnts[:-1], ctrls[0], attrs=['sy','sz'])
mc.parentConstraint(bind_jnts[-2], bind_jnts[-1], mo=1, n=bind_jnts[-1]+'_prc')
mc.scaleConstraint(bind_jnts[-2], bind_jnts[-1], mo=1, n=bind_jnts[-1]+'_sc')
mc.parent(zeros[0], ctrl_grps[0])
mc.parent(bind_jnts, jnt_grps[0])
if not single_joint and number_joints == 1:
mc.parent(bind_jnts[-1], bind_jnts[0])
#utils.create_cfx_curves(self.bind_joints, self.prefix+'_'+self.part_type)
if len(ctrls) > 1:
spaces.tag(ctrls, arg='partParent:'+self.options.get('parent'))
else:
spaces.tag(ctrls)
self.finalize_part() | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def _init_anim(self):\n pass",
"def _animation_init(self):\n\n self.animation_ax.set_xlim(self.plant.workspace_range[0][0],\n self.plant.workspace_range[0][1])\n self.animation_ax.set_ylim(self.plant.workspace_range[1][0],\n self.plant.workspace_range[1][1])\n self.animation_ax.set_xlabel(\"x position [m]\")\n self.animation_ax.set_ylabel(\"y position [m]\")\n for ap in self.animation_plots[:-1]:\n ap.set_data([], [])\n self.animation_plots[-1].set_text(\"t = 0.000\")\n\n self.tau_arrowarcs = []\n self.tau_arrowheads = []\n for link in range(self.plant.n_links):\n arc, head = get_arrow(radius=0.001,\n centX=0,\n centY=0,\n angle_=110,\n theta2_=320,\n color_=\"red\")\n self.tau_arrowarcs.append(arc)\n self.tau_arrowheads.append(head)\n self.animation_ax.add_patch(arc)\n self.animation_ax.add_patch(head)\n\n return self.animation_plots + self.tau_arrowarcs + self.tau_arrowheads",
"def run():\n renanme_action()\n\n write_anim()\n alc.save_file()",
"def anim():\n i = 0\n while 1:\n\n for r in Reprs:\n r.draw(i)\n i = i+ 1\n i = i % len(t)\n yield",
"def do_animations(self):\n self.animate_bloop(700, 160, 50)",
"def build_and_animate(self, path: str, scale_factor: int) -> None:\n\n logging.info(\"Building and animating square maze...\")\n images = []\n\n while len(self.__trees.keys()) > 0:\n self.__build_iteration()\n images.append(self.image_snapshot(scale_factor))\n\n logging.info(\"Build complete.\")\n logging.info(\"Animating construction...\")\n\n imageio.mimsave(path, images)\n logging.info(\"Animation complete.\")",
"def build_rig(self):\n\n\n # create rig part top nodes\n self.create_part_master()\n\n prefix = self.prefix # Naming prefix. Use this for every new node you create and there should be no name clashes.\n options = self.options # Build options\n anim_ctrls = self.anim_ctrls # Anim controls in this part\n bind_joints = self.bind_joints # Bind joints in this rig part\n world_scale_attr = self.hooks[0]+'.worldScale' # World scale multiplier (Each hooks has it's own world scale)\n hooks = self.hooks # A hook grp is created per hook attribute.\n ctrl_grps = self.ctrl_grps # A ctrl group is created per hook. Parent controls here.\n jnt_grps = self.jnt_grps # A joint groupd is created per hook. Parent joints here.\n noxform_grp = self.noxform_grp # No scale, no transform group for this rig part.\n mirror_value = self.mirror_value # 1.0 for left and center sided parts and -1.0 for right sided part.\n\n pickWalk_parent = options.get('pickWalkParent')\n\n world_grp = hooks[0]\n steering_grp = hooks[3]\n\n mc.addAttr(steering_grp, ln='camber', k=1, min=-10, max=10)\n mc.addAttr(steering_grp, ln='toe', min=-10, max=10, k=1)\n\n l_prefix = prefix.replace('C','L', 1)\n r_prefix = prefix.replace('C','R', 1)\n\n default_lock_value = utils.get_distance(l_prefix+'_shock_A_JNT', l_prefix+'_shock_B_JNT') * 0.333\n\n mc.addAttr(steering_grp, ln='suspensionExtensionMax', k=1, min=0,dv= default_lock_value)\n mc.addAttr(steering_grp, ln='suspensionCompressionMax', k=1, min=0,dv= default_lock_value)\n mc.addAttr(steering_grp, ln='steeringAngleMax', min=0, dv=45, k=1)\n\n mc.addAttr(steering_grp, ln='autoSteering', min=0, max=1, k=1)\n mc.addAttr(steering_grp, ln='autoWheel', min=0, max=1, k=1)\n mc.addAttr(steering_grp, ln='autoSteerAmount', k=0)\n\n mc.addAttr(steering_grp, ln='connectXforms', at='message')\n\n driver_jnt = mc.createNode('joint', n=prefix+'_chassis_driver_JNT', p=jnt_grps[2])\n mc.pointConstraint(l_prefix+'_lowerArm_end_JNT', r_prefix+'_lowerArm_end_JNT', driver_jnt)\n\n mirror_values = [1, -1]\n for mi, prefix in enumerate([l_prefix, r_prefix]):\n\n mirror_value = mirror_values[mi]\n\n # Create ctrls\n chassis_ctrl = hooks[1]\n\n up_strut = prefix+'_shock_A_JNT'\n lo_strut = prefix+'_shock_B_JNT'\n up_strut_end = prefix+'_shock_A_end_JNT'\n lo_strut_end = prefix+'_shock_B_end_JNT'\n steer_jnt = prefix+'_steeringArm_JNT'\n up_control_arm = prefix+'_upperArm_JNT'\n up_control_arm_end = prefix+'_upperArm_end_JNT'\n\n lo_control_arm = prefix+'_lowerArm_JNT'\n lo_control_arm_end = prefix+'_lowerArm_end_JNT'\n\n spindle = prefix+'_wheelhub_JNT'\n wheel_hub = prefix+'_wheelhub_end_JNT'\n steering_assembly = prefix+'_steeringArm_JNT'\n\n # Create ctrls\n loc = utils.snap_locator(steering_assembly )\n mc.delete(mc.aimConstraint(up_control_arm, loc, aim=[0,1,0], u=[0,0,1], wu=[0,0,1], wut='vector'))\n wheel_zero, wheel_ctrl, wheel_offsets, wheel_last_node = self.anim_ctrl(prefix+'_wheel_CTL', match_position=loc, node_type='transform')\n mc.delete(loc)\n\n loc = utils.snap_locator(prefix+'_ground_CTL_REF')\n ground_zero, ground_ctrl, ground_offsets, ground_last_node = self.anim_ctrl(prefix+'_ground_CTL', match_position=loc, node_type='transform')\n mc.delete(loc)\n\n mc.setAttr(wheel_ctrl+'.ro', 2)\n\n # wheel spin\n auto_wheel_off = mc.createNode('transform', p=spindle, n=wheel_ctrl+'_AUTO_OFF')\n auto_wheel = mc.createNode('transform', p=auto_wheel_off, n=wheel_ctrl+'_AUTO')\n mc.parent(auto_wheel_off, wheel_ctrl)\n\n mc.parent(wheel_offsets[0], auto_wheel)\n mc.makeIdentity(wheel_offsets[0], apply=1, t=1, r=1, s=1, n=0, pn=1)\n mc.xform(wheel_offsets[0], piv=(0,0,0))\n\n mc.orientConstraint(wheel_offsets[0], spindle)\n\n # wheel ctrl limits\n ctrls = [wheel_ctrl+'_CONST', wheel_ctrl+'_MOCAP', wheel_ctrl+'_OFF', wheel_ctrl]\n for ct in ctrls:\n mc.transformLimits(ct, tx=[0,0], ty=[0,0], etx=[1,1], ety=[1,1], tz=[0,0], etz=[1,1])\n mc.connectAttr(steering_grp+'.suspensionCompressionMax', ct+'.maxTransXLimit')\n utils.connect_negative(steering_grp+'.suspensionExtensionMax', ct+'.minTransXLimit')\n\n mc.connectAttr(steering_grp+'.suspensionCompressionMax', ct+'.maxTransYLimit')\n utils.connect_negative(steering_grp+'.suspensionExtensionMax', ct+'.minTransYLimit')\n\n mc.connectAttr(steering_grp+'.suspensionCompressionMax', ct+'.maxTransZLimit')\n utils.connect_negative(steering_grp+'.suspensionExtensionMax', ct+'.minTransZLimit')\n\n # wheel and ground\n mc.parent(wheel_zero, ground_zero, ctrl_grps[1])\n mc.pointConstraint(ground_last_node, wheel_ctrl+'_CONST', mo=1, skip=['x','z'])\n\n # lower control arm\n ik = mc.ikHandle(sj=lo_control_arm, ee=lo_control_arm_end)[0]\n mc.parent(ik, jnt_grps[2])\n mc.hide(ik)\n\n mc.parentConstraint(wheel_ctrl, lo_control_arm, mo=1)\n\n # up ctrl arm\n ik = mc.ikHandle(sj=up_control_arm, ee=up_control_arm_end)[0]\n mc.parent(ik, driver_jnt)\n mc.parentConstraint(wheel_ctrl, up_control_arm, mo=1)\n mc.hide(ik)\n\n # orient chassis loc\n\n # strut\n mc.parent(up_strut, driver_jnt)\n sloc = utils.snap_locator(lo_strut, name=up_strut+'_AIM_GRP', node_type='transform')\n mc.aimConstraint(sloc, up_strut, aim=[mirror_value,0,0], u=[0,0,1], wu=[0,0,1], wut='objectRotation', wuo=driver_jnt)\n mc.parent(sloc, lo_control_arm)\n mc.pointConstraint(sloc, lo_strut)\n\n # streering assembly orientation ############################################\n mc.parent(steer_jnt, lo_control_arm)\n mc.parentConstraint(wheel_ctrl, steer_jnt, mo=1)\n\n # streering assembly orientation, steering and toe ############################################\n for ct in ctrls:\n mc.transformLimits(ct, rx=[0,0], ry=[0,0], erx=[1,1], ery=[1,1], rz=[0,0], erz=[1,1])\n mc.connectAttr(steering_grp+'.steeringAngleMax', ct+'.maxRotXLimit')\n utils.connect_negative(steering_grp+'.steeringAngleMax', ct+'.minRotXLimit')\n\n mc.connectAttr(steering_grp+'.steeringAngleMax', ct+'.maxRotYLimit')\n utils.connect_negative(steering_grp+'.steeringAngleMax', ct+'.minRotYLimit')\n\n mc.connectAttr(steering_grp+'.steeringAngleMax', ct+'.maxRotZLimit')\n utils.connect_negative(steering_grp+'.steeringAngleMax', ct+'.minRotZLimit')\n\n # steering\n pma = mc.createNode('plusMinusAverage')\n if options.get('enableSteering'):\n\n aim = mc.createNode('transform', p=wheel_ctrl+'_CONST', n =wheel_ctrl+'_MOCAP_AIM')\n mc.setAttr(aim+'.ty', 10)\n mc.aimConstraint(aim, wheel_ctrl+'_MOCAP', aim=[0,1,0], u=[1,0,0], wu=[1,0,0], wuo=world_grp, wut='objectRotation')\n\n sr = mc.createNode('setRange')\n mc.connectAttr(steering_grp+'.tx', sr+'.vx')\n mc.connectAttr(steering_grp+'.steeringAngleMax', sr+'.maxX', f=1)\n utils.connect_negative(steering_grp+'.steeringAngleMax', sr+'.minX')\n mc.setAttr(sr+'.oldMinX', -10)\n mc.setAttr(sr+'.oldMaxX', 10)\n\n mc.connectAttr(sr+'.outValueX', pma+'.input1D[0]')\n\n # toe\n sr = mc.createNode('setRange')\n mc.connectAttr(steering_grp+'.toe', sr+'.vx')\n mc.connectAttr(steering_grp+'.steeringAngleMax', sr+'.maxX', f=1)\n utils.connect_negative(steering_grp+'.steeringAngleMax', sr+'.minX')\n mc.setAttr(sr+'.oldMinX', -10)\n mc.setAttr(sr+'.oldMaxX', 10)\n\n if mirror_value == 1:\n utils.connect_negative(sr+'.outValueX', pma+'.input1D[1]')\n else:\n mc.connectAttr(sr+'.outValueX', pma+'.input1D[1]')\n\n mc.connectAttr(pma+'.output1D', wheel_ctrl+'_OFF.ry')\n\n # autp steering setup\n cl = mc.createNode('clamp')\n mdl = mc.createNode('multDoubleLinear')\n utils.connect_negative(steering_grp+'.steeringAngleMax', cl+'.minR')\n mc.connectAttr(steering_grp+'.steeringAngleMax', cl+'.maxR')\n mc.connectAttr(steering_grp+'.autoSteerAmount', cl+'.inputR')\n\n mc.connectAttr(cl+'.outputR', mdl+'.i1')\n mc.connectAttr(steering_grp+'.autoSteering', mdl+'.i2')\n\n mc.connectAttr(mdl+'.o', pma+'.input1D[2]')\n\n # steering arm piston\n aim = utils.snap_locator(prefix+'_steeringArm_B_JNT', name=prefix+'_steering_A_AIM', node_type='transform')\n mc.parent(aim, steer_jnt)\n mc.parent(prefix+'_steeringArm_A_JNT', driver_jnt)\n mc.pointConstraint(aim, prefix+'_steeringArm_B_JNT')\n mc.aimConstraint(aim, prefix+'_steeringArm_A_JNT', aim=[mirror_value, 0,0], u=[0,1,0], wu=[0,1,0], wuo=driver_jnt, wut='objectRotation')\n\n # camber\n sr = mc.createNode('setRange')\n mc.connectAttr(steering_grp+'.camber', sr+'.vx')\n mc.connectAttr(steering_grp+'.steeringAngleMax', sr+'.maxX', f=1)\n utils.connect_negative(steering_grp+'.steeringAngleMax', sr+'.minX')\n mc.setAttr(sr+'.oldMinX', -10)\n mc.setAttr(sr+'.oldMaxX', 10)\n\n if mirror_value == 1:\n utils.connect_negative(sr+'.outValueX', wheel_ctrl+'_OFF.rz')\n else:\n mc.connectAttr(sr+'.outValueX', wheel_ctrl+'_OFF.rz')\n\n # autowheel\n mc.addAttr(auto_wheel, ln='autoSpin', k=1)\n mc.connectAttr(auto_wheel+'.autoSpin', auto_wheel+'.rx')\n\n driver = utils.snap_locator(spindle, name=prefix+'_autoWheel_DRV', node_type='transform')\n mc.parent(driver, steer_jnt)\n connect_auto_wheel(driver, steering_grp, auto_wheel+'.autoSpin', world_scale_node=hooks[0])\n\n utils.set_attrs(wheel_ctrl, 'rx s', l=1, k=0)\n if not options.get('enableSteering'):\n utils.set_attrs(wheel_ctrl, 'ry', l=1, k=0)",
"def __init__(\n self, OUTPUT_DIREC, name=\"forgot_name_TC_Animator\", move_with=True, **kwargs\n ):\n self.co, self.sy = ip.read_in(OUTPUT_DIREC, name)\n # set up figure and animation\n self.move_with = move_with\n self.name = name\n self.algorithm_title = None\n self.algorithm_text = None\n self.timestep_text = None\n self.length_softening_distance = None\n # replot Energies etc.\n with plt.style.context((\"fivethirtyeight\")): # plot the normal things\n plt.clf()\n plot.plot_energy(self.co, self.sy)\n plot.plot_angular_momentum(self.co, self.sy)\n plot.plot_multi_AM(self.co, self.sy)\n with plt.style.context((\"dark_background\")):\n self.fig = plt.figure() # the main animation figure\n self.ax = self.fig.add_subplot(\n 111, aspect=\"equal\", autoscale_on=False, xlim=(-20, 20), ylim=(-20, 20)\n ) # ax has all these useful attributes\n # self.ax.grid() # Add gridlines\n self.no_particles = len(self.sy.coordinate_grid[0, :, 0])\n if self.no_particles < 10: # Deal with multi body animate test case\n (self.line,) = self.ax.plot(\n [], [], \"wo\", markersize=1, label=\"Test Masses\"\n )\n (self.galactic_centre,) = self.ax.plot(\n [0], [0], \"wo\", markersize=1, label=\"Galaxy A\"\n )\n (self.impactor,) = self.ax.plot(\n [0], [0], \"wo\", markersize=1, label=\"Galaxy B\"\n )\n else:\n (self.line,) = self.ax.plot(\n [], [], \"wo\", markersize=0.5, label=\"Test Masses\"\n )\n (self.galactic_centre,) = self.ax.plot(\n [0], [0], color=\"red\", marker=\"+\", label=\"Galaxy A\"\n )\n (self.impactor,) = self.ax.plot(\n [0], [0], color=\"green\", marker=\"+\", label=\"Galaxy B\"\n )\n if self.no_particles > 10:\n if self.co.halo:\n if self.move_with:\n print(\"I want to plot a Halo.\")\n print(\"May have plotted Halo if needed\")\n\n if move_with: # In the non inertial coordinate case\n plt.xlabel(r\"$X^{\\prime}$\")\n plt.ylabel(r\"$Y^{\\prime}$\")\n else:\n plt.xlabel(r\"$X$\")\n plt.ylabel(r\"$Y$\")\n\n self.add_details() # Comment out line if this is TMI\n\n # Add some text outputs in suitable areas of the figure\n self.time_text = self.ax.text(1.01, 0.95, \"\", transform=self.ax.transAxes)\n self.KE_text = self.ax.text(1.01, 0.88, \"\", transform=self.ax.transAxes)\n self.GPE_text = self.ax.text(1.01, 0.81, \"\", transform=self.ax.transAxes)\n self.energy_text = self.ax.text(1.01, 0.74, \"\", transform=self.ax.transAxes)\n plt.tight_layout() # This supposedly makes stops the label from falling off.\n\n print(\"Timer is \" + str(len(self.sy.short_timer)) + \" Long\")\n self.dt = (\n self.sy.timer[1] - self.sy.timer[0]\n ) # read the time step directly from the timer file",
"def build_rig(self):\n\n # create rig part top nodes\n self.create_part_master()\n\n # Get all the relevant part info\n prefix = self.prefix\n options = self.options\n anim_ctrls = self.anim_ctrls\n bind_jnts = self.bind_joints\n hooks = self.hooks\n ctrl_grps = self.ctrl_grps\n jnt_grps = self.jnt_grps\n noxform_grp = self.noxform_grp\n world_scale_attr = self.hooks[0] + '.worldScale'\n\n\n setupNeck.setup_neck()\n setupNeck.setup_head()\n autoRig.apply_shapes()\n\n\n #\n # mc.parent ('bottomNeckSkin_Mid_jnt', 'topNeckSkin_Mid_jnt', jnt_grps[0])\n # mc.parent ('neck_rig', noxform_grp)\n # mc.parent ('neck_ctrls', ctrl_grps[0])\n # mc.parent ('rotateReader_grp', jnt_grps[0])\n #\n # mc.parent ('drivenArm_chest_Mid_bind', jnt_grps[0])\n #\n # scales = [u'neck01_Mid_bind', u'neck02_Mid_bind', u'neck03_Mid_bind', u'neckEnd_Mid_jnt',u'headTop_Mid_bind', u'headRear_Mid_bind', u'headSide_Lt_bind', u'headSide_Rt_bind']\n # utils.break_connections(nodes=scales, attrs='s')",
"def __init__(self):\n\n #create initial tile array and animation dictionary for walkonto animations \n self.array = []\n self.animations = {}",
"def setAnimations(*args):",
"def setAnimations(*args):",
"def setAnimations(*args):",
"def setAnimations(*args):",
"def setAnimations(*args):",
"def setAnimations(*args):",
"def setAnimations(*args):",
"def setAnimations(*args):",
"def setAnimations(*args):",
"def setAnimations(*args):",
"def setAnimations(*args):",
"def createAnimation(start_id, anim_count, frame_count, base_sprites):\n for a in range(anim_count):\n img_batch = []\n cnd_batch = []\n\n for f in range(frame_count):\n # Attaches encodings for each frame of the animation.\n cnd_vector = np.zeros(16)\n cnd_vector[start_id + a] = 1\n img_batch.append(base_sprites[a])\n cnd_batch.append(np.append(cnd_vector, [f]))\n\n f_count = np.zeros((len(cnd_batch), 1)) # Animation's frame count.\n\n # Creates a batch of images for one animation.\n anim = animator.run(y_ap, feed_dict= {\n b_ap: img_batch,\n l_ap: cnd_batch,\n b_asize: f_count\n })\n output_anim = np.concatenate(([base_sprites[a]], anim)) # Add base image to the output animation file.\n scipy.misc.imsave(app.root_path + \"/static/images/animations/a\" + str(a + start_id) + \".png\", joinImages(output_anim))\n\n return output_anim",
"def makePNG(self,outDir=os.getcwd(),tmpFname='temp.R'):\n rscript = \"\"\"\nname<-'%s'\ncontig<-'%s'\nstart<-%d\nend<-%d\nstrand<-'%s'\nexonLengths<-c(%s)\nexonOffsets<-c(%s)\nmyLen<-end-start+1\n\npng(filename=paste('%s/',name,'.png',sep=''),width=900,height=300)\nplot.new()\nplot.window(xlim=c(start,end),ylim=c(0,3))\naxis(1)\ntitle(xlab=contig)\ntitle(main=name)\nlines(seq(start,end+1),rep(1,myLen+1),col='blue',lwd=2,lend='butt')\n\nsegments(start+exonOffsets,rep(1,length(exonOffsets)),start+exonOffsets+exonLengths,rep(1,length(exonOffsets)),col='blue',lwd=20,lend='butt')\nif (strand=='+'){\n arrows(start,1.5,(start+(myLen*0.05)),1.5,length=0.125,lwd=1.5,angle=30,col='black')\n} else if (strand=='-') {\n arrows(end,0.5,(end-(myLen*0.05)),0.5,length=0.125,lwd=1.5,angle=30,col='black')\n}\n\n\ndev.off()\"\"\" % (self.name,self.chr,self.start,self.end,self.strand,\",\".join([str(x) for x in self.exonLengths]),\",\".join([str(x) for x in self.exonOffsets]),outDir)\n tmpHandle = open(tmpFname,'w')\n print >>tmpHandle, rscript\n tmpHandle.close()\n commands.getoutput('R CMD BATCH --vanilla %s' % tmpFname)\n os.remove(tmpFname)\n return",
"def load_animation(update, message):\n while generating_qr:\n message.edit_text(text=\"<b>Generating QR Code /</b>\", parse_mode=ParseMode.HTML)\n message.edit_text(text=\"<b>Generating QR Code -</b>\", parse_mode=ParseMode.HTML)\n message.edit_text(text=\"<b>Generating QR Code \\\\</b>\", parse_mode=ParseMode.HTML)\n message.edit_text(text=\"<b>Generating QR Code |</b>\", parse_mode=ParseMode.HTML)\n message.edit_text(text=\"<b>QR Code Generated:</b>\", parse_mode=ParseMode.HTML)\n return None",
"def build():",
"def init():\n uanim.set_data([],[])\n return uanim,",
"def animate_starter(self, **kwargs):\n interval = 5 # this number works fine, but is rather arbirtary, presumably in milliseconds\n print(\"The timer length is \" + str(len(self.sy.short_timer)))\n print(\"Shape of coordinate_grid is \" + str(np.shape(self.sy.coordinate_grid)))\n print(\"The animator interval was \" + str(interval) + \" in unknown units\")\n # I don't currently understand why the galaxy chooses\n # to slow down mid way through.\n # Perhaps I should look at the FuncAnimation\n # dictionary and work out what has gone wrong.\n with plt.style.context((\"dark_background\")):\n ani = animation.FuncAnimation(\n self.fig,\n self.animate,\n frames=len(self.sy.short_timer),\n interval=interval,\n blit=True,\n init_func=self.ani_init,\n )\n ani.save(\n str(self.co.out)\n + \"/\"\n + str(self.name)\n + \"move_with_\"\n + str(self.move_with)\n + \".mp4\",\n writer=writer,\n )\n plt.clf() # always make sure you close the lid",
"def __init__(\n self : \"animation\",\n filename : \"str\",\n size : \"Tuple[int,int]\" = None,\n pbar : \"bool\" = False,\n mbs : \"int\" = 16,\n dpi : \"int\" = 150,\n init_frame : \"matplotlib.figure.Figure\" = None,\n init_ax : \"matplotlib.axes._subplots.AxesSubplot\" = None,\n fps : \"int\" = 5,\n interactive : \"bool\" = False,\n autoSmooth : \"bool\" = False,\n smoothingFrames : \"int\" = 5,\n saveFinalFrame : \"int\" = False,\n smoothingTime : float = None,\n smoothingFunction : \"Callable\" = None\n ):\n self.filename = filename\n self.size = size\n self._mbs = mbs\n self._writer = imageio.get_writer(\n self.filename,\n mode='I',\n macro_block_size=self._mbs,\n fps=fps\n )\n self.fps = fps\n self.pbar = pbar\n self._frame_number = 0\n self._closed = False\n self.dpi = dpi\n self._cframe = None\n if init_frame and init_ax:\n self._init_frame(init_frame, init_ax)\n\n self._init_interactive = matplotlib.is_interactive()\n if self._init_interactive and not interactive:\n matplotlib.interactive(False)\n else:\n matplotlib.interactive(interactive)\n if autoSmooth:\n assert smoothingFrames > 0\n\n self._autosmooth = autoSmooth\n self._prevFrame = None\n\n\n # Set up smoothing\n if smoothingTime is None:\n self._smoothingFrames = smoothingFrames\n else:\n self._smoothingFrames = int(smoothingTime*fps)\n\n if smoothingFunction is None:\n self._smoothingFunction = self._linear_interpolation\n else:\n self._smoothingFunction = smoothingFunction\n\n self._saveFinalFrame = saveFinalFrame",
"def makeMovie(self, animation, filename=\"brainmovie%07d.png\", offset=0,\n fps=30, size=(1920, 1080), interpolation=\"linear\"):\n # build up two variables: State and Anim.\n # state is a dict of all values being modified at any time\n state = dict()\n # anim is a list of transitions between keyframes\n anim = []\n setfunc = self.ui.set\n for f in sorted(animation, key=lambda x:x['idx']):\n if f['idx'] == 0:\n setfunc(f['state'], f['value'])\n state[f['state']] = dict(idx=f['idx'], val=f['value'])\n else:\n if f['state'] not in state:\n state[f['state']] = dict(idx=0, val=self.getState(f['state'])[0])\n start = dict(idx=state[f['state']]['idx'],\n state=f['state'],\n value=state[f['state']]['val'])\n end = dict(idx=f['idx'], state=f['state'], value=f['value'])\n state[f['state']]['idx'] = f['idx']\n state[f['state']]['val'] = f['value']\n if start['value'] != end['value']:\n anim.append((start, end))\n\n for i, sec in enumerate(np.arange(0, anim[-1][1]['idx']+1./fps, 1./fps)):\n for start, end in anim:\n if start['idx'] < sec <= end['idx']:\n idx = (sec - start['idx']) / float(end['idx'] - start['idx'])\n if start['state'] == 'frame':\n func = mixes['linear']\n else:\n func = mixes[interpolation]\n\n val = func(np.array(start['value']), np.array(end['value']), idx)\n if isinstance(val, np.ndarray):\n setfunc(start['state'], val.ravel().tolist())\n else:\n setfunc(start['state'], val)\n self.getImage(filename%(i+offset), size=size)",
"def at_anim(seq, anim, d):\n at(\"ANIM\", seq, [anim, d])"
] | [
"0.68172234",
"0.6228986",
"0.6166067",
"0.6068071",
"0.6007271",
"0.59737676",
"0.5954252",
"0.5947862",
"0.5921581",
"0.59017247",
"0.5882105",
"0.5882105",
"0.5882105",
"0.5882105",
"0.5882105",
"0.5882105",
"0.5882105",
"0.5882105",
"0.5882105",
"0.5882105",
"0.5882105",
"0.58691335",
"0.5849676",
"0.58468324",
"0.5758209",
"0.574393",
"0.5735811",
"0.5704235",
"0.5689637",
"0.5660184"
] | 0.6249442 | 1 |
Scale the uv map | def scale_uv(mesh_name, scale):
mesh = bpy.data.meshes[mesh_name]
if len(mesh.uv_layers) == 0:
return
uv_layer = mesh.uv_layers[0].data
for uv_index in range(0, len(uv_layer)):
uv = uv_layer[uv_index].uv
uv *= scale | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def scale_uv(self):\n self.u = [i * self.scale * self.scaleratio for i in self.u]\n self.v = [i * self.scale for i in self.v]",
"def uvmap(self, p):\n pass",
"def scale(self):",
"def scale(self, up):\n s = 1.1 if up else 0.9\n self.scaling_matrix = np.dot(\n self.scaling_matrix,\n F.scaling([s, s, s])\n )\n\n self.aabb.scale(s)",
"def scale(self, sf):\n self.scale(sf, sf)",
"def scale(self, size):\n self._surf = pygame.transform.smoothscale(self._surf, size).convert_alpha()",
"def scale(self, x, y, z) -> None:\n ...",
"def scale_u_and_v(u, v, level, pyr):\n # TODO: Your code here\n image = pyr[level-1]\n expanded_u = ps4.expand_image(u)\n expanded_v = ps4.expand_image(v)\n scaled_u = expanded_u * 2\n scaled_v = expanded_v * 2\n if image.shape[0] == scaled_u.shape[0] - 1:\n scaled_u = scaled_u[:-1, :]\n if image.shape[1] == scaled_u.shape[1] - 1:\n scaled_u = scaled_u[:, :-1]\n if image.shape[0] == scaled_v.shape[0] - 1:\n scaled_v = scaled_v[:-1, :]\n if image.shape[1] == scaled_v.shape[1] - 1:\n scaled_v = scaled_v[:, :-1]\n return scaled_u, scaled_v",
"def uvmap(self, p):\n # bottom left corner of the plane\n p00 = self.position - (self.sx * self.n0) / 2 - (self.sy * self.n1) / 2\n dif_vector = p - p00\n u = np.dot(dif_vector, self.n0) / self.sx\n v = np.dot(dif_vector, self.n1) / self.sy\n return u, v",
"def scale(self, from_min, from_max, to_min, to_max):\n for i in range(len(self.poses)):\n self.poses[i].position.scale(from_min[:3], from_max[:3], to_min[:3], to_max[:3])\n self.wrenches[i].scale(from_min[3:], from_max[3:], to_min[3:], to_max[3:])",
"def scale(self,s):\n return Vector(self.x * s, self.y * s, self.z * s)",
"def scale(uv_coord, K, bbox, new_size):\r\n\txmin, xmax, ymin, ymax = bbox\r\n\r\n\tuv_coord[:, 0] = (uv_coord[:, 0] - xmin) / (xmax - xmin + 1.) * new_size[1]\r\n\tuv_coord[:, 1] = (uv_coord[:, 1] - ymin) / (ymax - ymin + 1.) * new_size[0]\r\n\r\n\txscale = new_size[1] / (xmax - xmin + 1.)\r\n\tyscale = new_size[0] / (ymax - ymin + 1.)\r\n\r\n\tshift = [[1, 0, -xmin],\r\n\t\t\t [0, 1, -ymin],\r\n\t\t\t [0, 0, 1]]\r\n\r\n\tscale = [[xscale, 0, 0],\r\n\t\t\t [0, yscale, 0],\r\n\t\t\t [0, 0, 1]]\r\n\r\n\tshift = np.array(shift)\r\n\tscale = np.array(scale)\r\n\r\n\tK = np.matmul(scale, np.matmul(shift, K))\r\n\r\n\treturn uv_coord, K",
"def scale(self):\n return self._gev_bijector.scale",
"def get_scale():\r\n\r\n \r\n return 0.5",
"def _scale_setter(self, value: float) -> None:\n self.uaxis.scale = value\n self.vaxis.scale = value",
"def scale(self, scale):\n self.coords = self.coords * scale\n return self",
"def scale(self, scale):\n \n scale_matrix = wf.scaleMatrix(scale, self.width/2, self.height/2, 0)\n self.transform(scale_matrix)",
"def uv(vec):\n return vec / sqrt(dot(vec, vec))",
"def scale_uniform(self, s: float):\n self.vertices = [v * s for v in self.vertices]\n return self",
"def scale(self):\n return self.scale_factor / CONSTANTS.AU",
"def img_map_transforms(ts):\n # XXX TODO: unchecked textures give error of variable referenced before assignment XXX\n # POV-Ray \"scale\" is not a number of repetitions factor, but ,its\n # inverse, a standard scale factor.\n # 0.5 Offset is needed relatively to scale because center of the\n # scale is 0.5,0.5 in blender and 0,0 in POV\n # Strange that the translation factor for scale is not the same as for\n # translate.\n # TODO: verify both matches with other blender renderers / internal in previous versions.\n image_map_transforms = \"\"\n image_map_transforms = \"scale <%.4g,%.4g,%.4g> translate <%.4g,%.4g,%.4g>\" % (\n ts.scale[0],\n ts.scale[1],\n ts.scale[2],\n ts.offset[0],\n ts.offset[1],\n ts.offset[2],\n )\n # image_map_transforms = (\" translate <-0.5,-0.5,0.0> scale <%.4g,%.4g,%.4g> translate <%.4g,%.4g,%.4g>\" % \\\n # ( 1.0 / ts.scale.x,\n # 1.0 / ts.scale.y,\n # 1.0 / ts.scale.z,\n # (0.5 / ts.scale.x) + ts.offset.x,\n # (0.5 / ts.scale.y) + ts.offset.y,\n # ts.offset.z))\n # image_map_transforms = (\n # \"translate <-0.5,-0.5,0> \"\n # \"scale <-1,-1,1> * <%.4g,%.4g,%.4g> \"\n # \"translate <0.5,0.5,0> + <%.4g,%.4g,%.4g>\" % \\\n # (1.0 / ts.scale.x,\n # 1.0 / ts.scale.y,\n # 1.0 / ts.scale.z,\n # ts.offset.x,\n # ts.offset.y,\n # ts.offset.z)\n # )\n return image_map_transforms",
"def scale_invert(self):",
"def scale(self, size):\n self._surf = pygame.transform.smoothscale(self._surf,\n size).convert_alpha()\n self._version += 1\n return self",
"def _force_rescale(self, setpoint_x, setpoint_y):",
"def scale(s: (float, int), v: Vector) -> Vector:\n coords = list()\n res = Vector(coords)\n for i in range(len(v.coords)):\n res.coords[i] *= s\n return res",
"def uvmap(self, p):\n # local_v is the unit vector that goes in the direction from the center\n # of the sphere to the position p\n local_v = (p - self.position) / self.radius\n n0, n1, n2 = self.get_orientation()\n x = np.dot(n0, local_v)\n y = np.dot(n1, local_v)\n z = np.dot(n2, local_v)\n # phi = np.arccos(z)\n # v = phi / np.pi\n # theta = np.arccos((y / np.sin(phi)).round(4))\n # if x < 0:\n # theta = 2 * np.pi - theta\n # u = theta / (2 * np.pi)\n u = 0.5 + np.arctan2(z, x) / (2 * np.pi)\n v = 0.5 - np.arcsin(y) / np.pi\n v = 1 - v\n return u, v",
"def __mul__(self, scale):\n return Vec(self.x * scale, self.y * scale)",
"def setSurfaceColorScale(low,high):\n dislin.zscale(low,high)",
"def scale_image(self, pixels, size):\n x_min, x_max = np.amin(pixels[:,0]), np.amax(pixels[:,0])\n y_min, y_max = np.amin(pixels[:,1]), np.amax(pixels[:,1])\n z_min, z_max = np.amin(pixels[:,2]), np.amax(pixels[:,2])\n \n pixels[:,0] -= x_min \n pixels[:,1] -= y_min\n pixels[:,2] -= z_min\n \n x_max -= x_min\n y_max -= y_min\n z_max -= z_min\n \n scale_factor = size / max(x_max, y_max, z_max) \n # All points are now between [0..max]\n\n pixels *= scale_factor\n return pixels",
"def test_scale_factor(self):\n expected = np.ones_like(self.cube_uv_down.data, dtype=np.float32)\n result = calculate_uv_index(self.cube_uv_down, scale_factor=10)\n self.assertArrayEqual(result.data, expected)"
] | [
"0.7357069",
"0.6755092",
"0.6652019",
"0.6457699",
"0.6367943",
"0.6347549",
"0.63283706",
"0.63200384",
"0.6318271",
"0.6299888",
"0.6261653",
"0.6241084",
"0.6219343",
"0.6149372",
"0.61320066",
"0.6128101",
"0.611614",
"0.61115736",
"0.6097453",
"0.60815555",
"0.6070723",
"0.6062747",
"0.6024073",
"0.6010298",
"0.59723306",
"0.5947084",
"0.59145266",
"0.5908115",
"0.58935",
"0.58903277"
] | 0.7055414 | 1 |
Ensures the Windows SDK CIPD package is installed. Returns the directory where the SDK package has been installed. | def _ensure_sdk(self, sdk_dir, sdk_version):
with self.m.context(infra_steps=True):
pkgs = self.m.cipd.EnsureFile()
pkgs.add_package('chrome_internal/third_party/sdk/windows', sdk_version)
self.m.cipd.ensure(sdk_dir, pkgs)
return sdk_dir | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_windows_sdk_path():\n try:\n import _winreg as winreg\n except ImportError:\n import winreg\n sub_key = r\"Software\\Microsoft\\Microsoft SDKs\\Windows\"\n with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, sub_key) as key:\n name = \"CurrentInstallFolder\"\n return winreg.QueryValueEx(key, name)[0]\n return None",
"def _getNETSDKPath():\r\n try:\r\n dotNETSDK_root_key = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, 'SOFTWARE\\\\Microsoft\\\\Microsoft SDKs\\\\.NETFramework\\\\v2.0', 0, win32con.KEY_READ)\r\n found = False\r\n i = 0\r\n try:\r\n try:\r\n while not found:\r\n name, obj, ntype = win32api.RegEnumValue(dotNETSDK_root_key, i)\r\n i = i + 1\r\n if name=='InstallationFolder':\r\n return obj\r\n found = True\r\n except:\r\n win32api.RegCloseKey(dotNETSDK_root_key)\r\n return ''\r\n finally:\r\n win32api.RegCloseKey(dotNETSDK_root_key)\r\n except:\r\n return ''",
"def find_setup_dir():\n dirname = os.path.dirname(__file__)\n if \"/site-packages/\" in dirname:\n prefix = dirname[:dirname.index(\"/site-packages/\")]\n for suffix in [\"share/openchange/setup\", \"share/setup\", \"share/samba/setup\", \"setup\"]:\n ret = os.path.join(prefix, suffix)\n if os.path.isdir(ret):\n return ret\n # In source tree\n ret = os.path.join(dirname, \"../../setup\")\n if os.path.isdir(ret):\n return ret\n raise Exception(\"Unable to find setup directory.\")",
"def GetPackageDirectory():\n return os.path.dirname(__file__)",
"def get_installdir(self):\n import mewlo\n path = os.path.dirname(os.path.realpath(mewlo.__file__))\n return path",
"def check_cmake_windows():\n chk = Popen(\"wmic product where \\\"name = 'cmake'\\\" get installlocation,version\",\n shell=True, stdout=PIPE, stderr=PIPE)\n stdout, stderr = chk.communicate()\n if stderr:\n return False, stderr\n lines = [re.sub(\" +\", \" \", line.strip())\n for line in stdout.decode().splitlines()\n if line.strip()]\n stdout = lines[1]\n location = stdout[:stdout.rfind(\" \")] + \"bin\"\n out_info(\"CMake not found in %PATH%. Temporarily adding: \\\"{}\\\"\".format(location))\n os.environ[\"PATH\"] += \";{}\".format(location)\n stdout = \"cmake {}\".format(stdout)\n return stdout, False",
"def get_install_dir(self):\n return EventGenerator.get_install_dir(self) + \"/madgraph4/src\"",
"def get_install_dir(self):\n return EventGenerator.get_install_dir(self) + \"/madgraph5/src\"",
"def acquire_package_directory():\n top_plugin_dir = os.path.realpath(os.path.join(os.getcwd(),\n os.path.dirname(__file__)))\n expected_package_dir = '/extras/MockApp'\n app_dir = top_plugin_dir + expected_package_dir\n return app_dir",
"def path(self):\n installed_packages_folder_path = site.getsitepackages()[0]\n return f'{installed_packages_folder_path}/{SITE_PACKAGES_FOLDER_NAME}'",
"def CheckSDK():\n return os.path.exists(constants.ANDROID_SDK_ROOT)",
"def get_package_dir():\n return Path(__file__).parent",
"def determine_python_path():\n if git_install_requested():\n projects_yaml = config('openstack-origin-git')\n projects_yaml = git_default_repos(projects_yaml)\n return os.path.join(git_pip_venv_dir(projects_yaml),\n 'lib/python2.7/site-packages')\n else:\n return None",
"def locate_nuget():\n if NuGetRunner.valid_nuget_executable(\"nuget\"):\n return \"nuget\"\n return None",
"def get_sp_dir(): # pragma: no cover\n for p in sys.path[::-1]:\n if p.endswith(\"site-packages\"):\n return p\n raise Exception(\"'site-package' directory not found!\")",
"def locate_vcredist_dir(plat):\n from setuptools import msvc\n\n vcvars = msvc.msvc14_get_vc_env(plat)\n try:\n vcruntime = vcvars[\"py_vcruntime_redist\"]\n except KeyError:\n warn(f\"platform={plat}, vcvars=\")\n pprint(vcvars, stream=sys.stderr)\n\n warn(\n \"Failed to get py_vcruntime_redist via vcvars, may need to set it in %PATH%\"\n )\n return None\n redist_dir, dll = os.path.split(vcruntime)\n # add redist dir to $PATH so that it can be found\n os.environ[\"PATH\"] += os.pathsep + redist_dir\n return redist_dir",
"def get_target_folder() -> str:\n return os.path.abspath(os.path.join(dirname(__file__), os.pardir, os.pardir, \"provider_packages\"))",
"def source_directory(self):\r\n return self.pip_requirement.source_dir",
"def install_location(self):\r\n return self._content_at_path('/template/os/install/%s' % self.install_type)",
"def package_dir(self):\r\n return \".\"",
"def find_lib_path():\n curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\n # make pythonpack hack: copy this directory one level upper for setup.py\n dll_path = [curr_path, os.path.join(curr_path, '../../lib/'),\n os.path.join(curr_path, './lib/'),\n os.path.join(sys.prefix, 'xlearn')]\n if sys.platform == 'win32':\n if platform.architecture()[0] == '64bit':\n dll_path.append(os.path.join(curr_path, '../../windows/x64/Release/'))\n # hack for pip installation when copy all parent source directory here\n dll_path.append(os.path.join(curr_path, './windows/x64/Release/'))\n else:\n dll_path.append(os.path.join(curr_path, '../../windows/Release/'))\n # hack for pip installation when copy all parent source directory here\n dll_path.append(os.path.join(curr_path, './windows/Release/'))\n dll_path = [os.path.join(p, 'xlearn_api.dll') for p in dll_path]\n elif sys.platform.startswith('linux'):\n dll_path = [os.path.join(p, 'libxlearn_api.so') for p in dll_path]\n elif sys.platform == 'darwin':\n dll_path = [os.path.join(p, 'libxlearn_api.dylib') for p in dll_path]\n\n lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)]\n\n # From github issues, most of installation errors come from machines w/o compilers\n if not lib_path:\n raise XLearnLibraryNotFound(\n 'Cannot find xlearn Library in the candidate path'\n )\n return lib_path",
"def __find_tool_path(self):\n tool_path = Path(os.path.dirname(os.path.realpath(__file__)))\n # We asume the installion path is relative to our installation path\n tool_path = tool_path / '../../../bin'\n if os.name == 'posix':\n ret = tool_path / 'fast-discovery-server'\n if not os.path.exists(ret):\n print('fast-discovery-server tool not installed')\n sys.exit(1)\n elif os.name == 'nt':\n ret = tool_path / 'fast-discovery-server.exe'\n if not os.path.exists(ret):\n ret = tool_path / 'fast-discovery-server.bat'\n if not os.path.exists(ret):\n print('fast-discovery-server tool not installed')\n sys.exit(1)\n else:\n print(f'{os.name} not supported')\n sys.exit(1)\n\n return ret",
"def check_local_package(installed_title):\n user_app_dir = path.Path(pm.internalVar(uad = True))\n installed_dir = user_app_dir / installed_title\n\n if installed_dir.isfile():\n return False\n elif installed_dir.isdir():\n return True\n else:\n return False",
"def get_install_dir(self):\n return EventGenerator.get_install_dir(self) + \"/egs5\"",
"def get_package_root(package):\n path_to_package = package.resource.location\n\n if not os.path.isdir(path_to_package) and hasattr(package, \"filepath\"):\n return os.path.dirname(package.filepath)\n\n path = os.path.join(path_to_package, package.name, str(package.version))\n\n if not os.path.isdir(path):\n raise EnvironmentError(\n 'Package \"{package}\" has an invalid path \"{path}\".'\n \"\".format(package=package, path=path)\n )\n\n return path",
"def get_packages_path_from_package(package):\n root = finder.get_package_root(package)\n\n if is_built_package(package):\n package_name_folder = os.path.dirname(root)\n\n return os.path.dirname(package_name_folder)\n\n return os.path.dirname(root)",
"def repo_root() -> str:\n path = os.path.realpath(os.curdir)\n\n while True:\n if os.path.exists(os.path.join(path, \"setup.py\")):\n return path\n path = os.path.realpath(os.path.join(path, \"..\"))",
"def get_config_install_dir(options):\n return (os.path.join(get_spinnaker_dir(options), 'config'))",
"def get_package_share_directory(package_name, print_warning=True):\n path = os.path.join(get_package_prefix(package_name), 'share', package_name)\n if print_warning and not os.path.exists(path):\n warnings.warn(f'Share directory for {package_name} ({path}) does not exist.', stacklevel=2)\n return path",
"def GetPath(self):\n sdk_root = config.Paths().sdk_root\n if not sdk_root:\n raise NoSdkRootError()\n return os.path.join(sdk_root, self.name)"
] | [
"0.6401396",
"0.6207446",
"0.6125756",
"0.6043662",
"0.5965605",
"0.5891769",
"0.5888167",
"0.5864345",
"0.58358866",
"0.56869674",
"0.5660783",
"0.56440717",
"0.5564829",
"0.554222",
"0.5531126",
"0.54845786",
"0.5455155",
"0.54525137",
"0.54060125",
"0.539242",
"0.53684103",
"0.5366173",
"0.53647053",
"0.53490096",
"0.53365386",
"0.53353477",
"0.53277785",
"0.53122026",
"0.52975994",
"0.5292935"
] | 0.7078877 | 0 |
Loads an array of variant configuration from the json file found at file_path. | def load_configuration(file_path):
with open(file_path, 'r') as file:
data = json.load(file)
configurations = []
for configuration_data in data:
configuration : Configuration = _from_json(configuration_data, Configuration)
configurations.append(configuration)
return configurations | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def load_from_file(config_path):\n return load_json_file(config_path)",
"def _load_config(path) -> dict:\n with open(path, \"r\") as F:\n return json.load(F)",
"def load_configuration(self, path):\n with open(path) as conf_file:\n if path.name not in self.configuration:\n self.configuration[path.name] = {}\n self.configuration[path.name] = json.load(conf_file)",
"def load(filepath):\n with open(filepath) as f:\n return Config(json.load(f))",
"def LoadConfig(path):\n config = None\n with open(path) as f:\n config = json.load(f)\n\n presets = {}\n for name in config['presets']:\n presets[name] = lightserver.Preset(**config['presets'][name])\n\n return config['bulbs'], config['groups'], presets",
"def _load_repo_configs(path):\n with open(path) as f:\n return json.loads(f.read())",
"def _load_repo_configs(path):\n with open(path) as f:\n return json.loads(f.read())",
"def load(self, path):\n with open(path, \"rt\") as open_file:\n data = json.load(open_file)\n return data",
"def json_load(file_path):\n\n with open(file_path) as f:\n return json_loads(f.read())",
"def load_config_from_file(self, configfilepath):\r\n # loads config from .json file\r\n f = open(configfilepath)\r\n config_values = json.load(f)\r\n \r\n\r\n f.close()\r\n self.config_file_path = configfilepath\r\n self.config_values = config_values\r\n return config_values",
"def _load_config_file(self, path: str) -> Dict[str, Any]:\n try:\n with open(path) as file:\n conf = json.load(file)\n except FileNotFoundError:\n raise OperationalException(\n f'Config file \"{path}\" not found!'\n ' Please create a config file or check whether it exists.')\n\n return conf",
"def read_config(path):\n\n with open(path, 'rb') as f:\n conf_dict = json.load(f)\n\n return conf_dict",
"def init_config(cls, path):\n try:\n config_string = open(path).read()\n except EnvironmentError as ex:\n LOGGER.error('Could not load %s file, error: %s', path, ex)\n sys.exit()\n\n try:\n cls.config = json.loads(config_string)\n except ValueError as ex:\n LOGGER.error(' %s file is not valid json, error: %s', path, ex)\n sys.exit()",
"def load_from_file(cls, file_path: str) -> 'PyESGConfiguration':\n with open(file_path) as config_file:\n config = json.load(config_file)\n\n pyesg_config = cls._decode_json(config) # type: 'PyESGConfiguration'\n return pyesg_config",
"def open_config_file(file):\n with open(file, \"r\") as file_open:\n return json.load(file_open)",
"def from_path(cls, path: str):\n with open(path) as f:\n return json.load(f)",
"def load(self, file=\"setup\", path=\"settings\"):\n\n # check if filename already contains file extension, if not, add it\n if file[-5:] != '.json':\n file += '.json'\n # load mappings from file\n with open(os.path.join(path, file), 'r') as file:\n self.data = json.load(file)",
"def load(cls, path):\n\n with open(path) as f:\n d = json.load(f, object_pairs_hook=OrderedDict)\n return cls.from_definition(d)",
"def load(cls, path):\n\n with open(path) as f:\n d = json.load(f, object_pairs_hook=OrderedDict)\n return cls.from_definition(d)",
"def load_data_file(path):\n with open(path, encoding='utf-8') as f:\n return json.load(f)",
"def load_from_file(self, path):\n schema = self.schema\n \n # Set up the default values.\n if schema is not None:\n for sect, sect_obj in schema.items():\n for opt, val in sect_obj.items():\n # This call is to convert the value to\n # the type specified. We do this to\n # prevent the programmer from specifying\n # inconsistent type with the value in the \n # schema.\n self.set(*_convert(schema, sect, opt, val[1]))\n\n # Parse the INI file.\n parser = RawConfigParser()\n parser.read(path)\n \n sections = parser.sections()\n for section in sections:\n \n # If application has supplied a schema,\n # and it does not has such a section, we skip\n # it. No error raised.\n if schema is not None and \\\n not schema.has_key(section):\n continue\n\n options = parser.options(section)\n \n for option in options:\n \n # If application has supplied a schema,\n # we know the section is valid since it pass the\n # previus test, but if the option is not included\n # in the section, we skip it. No error raised.\n if schema is not None and \\\n (option not in schema[section]):\n continue \n \n # If there is a schema, then we convert the \n # option to its type stated in the schema,\n # otherwise we just leave it as string.\n if schema is not None:\n self.set(*_convert(schema, section, option,\n parser.get(section, option)))\n else:\n self.set(section, option,\n parser.get(section, option))",
"def deserialize_file(cls, file_path='./data.json'):\n file_stream = open(file_path, 'rb')\n dct = json.load(file_stream, object_hook=CustomTypeDecoder)\n file_stream.close()\n env = Configuration.Configuration()\n env.update(dct)\n return env",
"def load_gas_list(path):\n with open(path, 'r') as f:\n return yaml.load(f)",
"def load_json_obj(path: str) -> RAW_CFG:\n with fsspec.open(path) as json_file:\n return json.load(json_file)",
"def load_from_file(self, file_path):\n\n with open(file_path) as f:\n config_text = f.read()\n self.load_from_string(config_text)",
"def from_json(configer_variant_class, config_file, project_dir):\n with open(config_file) as f:\n config = json.load(f)\n return configer_variant_class(config, project_dir)",
"def read_config_file_as_json(file_path):\n return _read_file_as_json(file_path, json_lib.parse)",
"def load_json(path):\n with open(path) as data_file:\n return json.load(data_file)",
"def load(self):\n\n # if the file doesn't exist, return\n if not os.path.exists(self.filepath):\n return\n\n # open the file and read in the raw values\n with open(self.filepath, 'r', encoding='utf-8') as fh:\n raw_values = json.loads(fh.read())\n\n # don't implicitly trust the raw values, but only get known keys\n for key in self.variables:\n if key in raw_values and 'value' in raw_values[key]:\n raw_value = raw_values[key]['value']\n self.variables[key]['value'] = raw_value",
"def __load_json(self, path):\n try:\n with Path(path).open('r') as f:\n return json.load(f)\n except ValueError as ve:\n six.raise_from(ValueError(\"error while loading the fixture %s\" % path), ve)"
] | [
"0.6971127",
"0.69440037",
"0.6884107",
"0.6781495",
"0.67147934",
"0.667997",
"0.667997",
"0.65955895",
"0.6577272",
"0.6541512",
"0.6484831",
"0.64210993",
"0.64185685",
"0.6390585",
"0.63819486",
"0.63698316",
"0.6301179",
"0.62971544",
"0.62971544",
"0.6258191",
"0.62474453",
"0.6247346",
"0.62451524",
"0.6240655",
"0.62330705",
"0.61899465",
"0.61821526",
"0.61772025",
"0.6170583",
"0.6163949"
] | 0.7119346 | 0 |
Initialize credential_id for rp_id | def cred_init(self, rp_id: str) -> (bytes, ec.EllipticCurvePrivateKey):
rp_id_hash = sha256(rp_id.encode())
private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())
# This may look like a cryptography but it's not.
# Never try to use it in a real project.
aesgcm = AESGCM(self.master_key)
data = private_key.private_numbers().private_value.to_bytes(32, 'big')
aad = rp_id_hash
nonce = sha256(aad + self.master_key)[4:16]
credential_id = aesgcm.encrypt(nonce, data, aad)
return credential_id, private_key | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def credential_id(self, credential_id):\n\n self._credential_id = credential_id",
"def m_credential_create(node_name, credential_hash, participantDID):\n pass",
"def credential_id(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"credential_id\")",
"def __init__(__self__, *,\n resource_id: pulumi.Input[str]):\n pulumi.set(__self__, \"resource_id\", resource_id)",
"def __init__(__self__, *,\n resource_id: pulumi.Input[str]):\n pulumi.set(__self__, \"resource_id\", resource_id)",
"def __init__(__self__,\n resource_name: str,\n args: OpenIdConnectProviderArgs,\n opts: Optional[pulumi.ResourceOptions] = None):\n ...",
"def SetUp(self) :\n self.new_credential = Credential(\"snapchat\", \"[email protected]\", \"Chat001\") # new credential",
"def __init__(__self__, *,\n identity_client_id: Optional[str] = None,\n resource_id: Optional[str] = None):\n if identity_client_id is not None:\n pulumi.set(__self__, \"identity_client_id\", identity_client_id)\n if resource_id is not None:\n pulumi.set(__self__, \"resource_id\", resource_id)",
"def __init__(__self__, *,\n resource_id: Optional[pulumi.Input[str]] = None):\n if resource_id is not None:\n pulumi.set(__self__, \"resource_id\", resource_id)",
"def __init__(__self__, *,\n resource_id: Optional[pulumi.Input[str]] = None):\n if resource_id is not None:\n pulumi.set(__self__, \"resource_id\", resource_id)",
"def __init__(__self__, *,\n resource_id: Optional[pulumi.Input[str]] = None):\n if resource_id is not None:\n pulumi.set(__self__, \"resource_id\", resource_id)",
"def cred_extract(self, rp_id: str, credential_id: bytes) -> Optional[ec.EllipticCurvePrivateKey]:\n rp_id_hash = sha256(rp_id.encode())\n\n aesgcm = AESGCM(self.master_key)\n aad = rp_id_hash\n nonce = sha256(aad + self.master_key)[4:16]\n\n try:\n data = aesgcm.decrypt(nonce, credential_id, aad)\n return ec.derive_private_key(int.from_bytes(data, 'big'), ec.SECP256R1(), default_backend())\n except cryptography.exceptions.InvalidTag:\n return None",
"def credential_id(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"credential_id\")",
"def test_mdb_add_duplicate_credential(self):\n this_id = 9797\n data = self.cred_data\n data['credential_id'] = this_id\n cred = vccs_auth.credential.from_dict(data, None)\n self.mdb.add_credential(cred)\n cred.derived_key(new='bb' * (512 / 8))\n print cred.to_dict()\n self.assertFalse(self.mdb.add_credential(cred))",
"def __init__(__self__,\n resource_name: str,\n args: ApplicationFederatedIdentityCredentialArgs,\n opts: Optional[pulumi.ResourceOptions] = None):\n ...",
"def __init__(__self__, *,\n key_vault_id: Optional[pulumi.Input[str]] = None):\n if key_vault_id is not None:\n pulumi.set(__self__, \"key_vault_id\", key_vault_id)",
"def __init__(__self__, *,\n principal_id: str,\n principal_id_display_name: Optional[str] = None):\n pulumi.set(__self__, \"principal_id\", principal_id)\n if principal_id_display_name is not None:\n pulumi.set(__self__, \"principal_id_display_name\", principal_id_display_name)",
"def __init__(__self__, *,\n certificate_id: pulumi.Input[str]):\n pulumi.set(__self__, \"certificate_id\", certificate_id)",
"def get_account_id():\n STORED_ID[\"account_id\"] = CONFIG_DATA['account_id']\n STORED_ID[\"member_id\"] = CONFIG_DATA['member_id']",
"def __init__(__self__, *,\n client_id: str,\n principal_id: str):\n pulumi.set(__self__, \"client_id\", client_id)\n pulumi.set(__self__, \"principal_id\", principal_id)",
"def __init__(self, *args, **kwargs):\n self.connection = None\n self.id = settings.EMAIL_SERVICES_CLIENT_ID\n self.key = settings.EMAIL_SERVICES_CLIENT_KEY",
"def set_credentials():",
"def add_credential(self, authenticator_id, credential):\n pass",
"def __init__(self):\n self.id = uuid.uuid4().hex",
"def __init__(self, uid, key, initial_prng):\n self.uid = uid\n self.key = key\n Crypto1.__init__(self, key, initial_prng)",
"def default_credentials_id(self) -> str:\n if self._default_credentials_id is None:\n default_credentials_id = self._get_env(\"DEFAULT_CREDENTIALS_ID\")\n self._default_credentials_id = default_credentials_id\n\n return self._default_credentials_id",
"def setUp(self):\n self.new_credential = Credential(\"Facebook\",\"Yvonnah Bonswuh\",\"[email protected]\",\"ivy1996\") # create credential object",
"def __init__(self, key, initial_prng):\n self.cipher = key\n self.prng = initial_prng\n self.nonce = None",
"def __init__(__self__, *,\n certificate_id: Optional[pulumi.Input[str]] = None):\n if certificate_id is not None:\n pulumi.set(__self__, \"certificate_id\", certificate_id)",
"def initialize(self, create_new=True, sysid=\"\"):"
] | [
"0.6536802",
"0.60312885",
"0.6001469",
"0.5769102",
"0.5769102",
"0.5753552",
"0.5738852",
"0.57326597",
"0.56390107",
"0.56390107",
"0.56390107",
"0.56072253",
"0.5601717",
"0.5592435",
"0.5564139",
"0.5392016",
"0.5382046",
"0.5379748",
"0.537696",
"0.5374538",
"0.5370657",
"0.53287715",
"0.5325557",
"0.5299991",
"0.52957994",
"0.5277854",
"0.5264538",
"0.52634656",
"0.526292",
"0.5253248"
] | 0.7190321 | 0 |
Extract private key from `credential_id` | def cred_extract(self, rp_id: str, credential_id: bytes) -> Optional[ec.EllipticCurvePrivateKey]:
rp_id_hash = sha256(rp_id.encode())
aesgcm = AESGCM(self.master_key)
aad = rp_id_hash
nonce = sha256(aad + self.master_key)[4:16]
try:
data = aesgcm.decrypt(nonce, credential_id, aad)
return ec.derive_private_key(int.from_bytes(data, 'big'), ec.SECP256R1(), default_backend())
except cryptography.exceptions.InvalidTag:
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def _decode_credential_from_json(self, cred_entry):\n raw_key = cred_entry['key']\n key = util.dict_to_tuple_key(raw_key)\n credential = None\n credential = Credentials.new_from_json(\n json.dumps(cred_entry['credential']))\n return (key, credential)",
"def _get_credential(self, key):\n return self._data.get(key, None)",
"def get_credential(self, key):\n return self.creds.get(key, '')",
"def get_credential(credential_id):\n session = db.get_session()\n try:\n return (session.query(network_models_v2.Credential).\n filter_by(credential_id=credential_id).one())\n except exc.NoResultFound:\n raise c_exc.CredentialNotFound(credential_id=credential_id)",
"def private_key(self):\n return self.__get_option('private_key')",
"def cred_init(self, rp_id: str) -> (bytes, ec.EllipticCurvePrivateKey):\n\n rp_id_hash = sha256(rp_id.encode())\n private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())\n\n # This may look like a cryptography but it's not.\n # Never try to use it in a real project.\n aesgcm = AESGCM(self.master_key)\n data = private_key.private_numbers().private_value.to_bytes(32, 'big')\n aad = rp_id_hash\n nonce = sha256(aad + self.master_key)[4:16]\n credential_id = aesgcm.encrypt(nonce, data, aad)\n\n return credential_id, private_key",
"def private_key(self):",
"async def retrieve_private_key(self) -> Tuple[str, str]:\n\n filename, file_path = random.choice(self._private_keys)\n async with aiofiles.open(file_path, mode='r') as file:\n private_key = await file.read()\n return private_key, self._create_public_key_identifier(filename)",
"def parsePrivateKey(s):\r\n return parsePEMKey(s, private=True)",
"def _get_private_key(self, privkey=None):\n\n # read private keys from keyring\n privkeys = self.gpg.list_keys(True) # True => private keys\n if len(privkeys) > 0 and privkeys[-1].has_key('fingerprint'):\n fingerprints = []\n for k in privkeys:\n fingerprints.append(k['fingerprint'])\n else:\n # no private key in keyring\n return None\n\n if privkey:\n # check for existence of private key received as argument\n # DEVEL: check for expiration as well\n if len(privkey) > 7 and len(privkey) <= 40:\n for fp in fingerprints:\n if fp.endswith(privkey):\n # work with last 16 significant chars internally,\n # even if only 8 are required in trac.ini\n privkey = fp[-16:]\n break\n # no fingerprint matching key ID\n else:\n privkey = None\n else:\n # reset invalid key ID\n privkey = None\n else:\n # select (last) private key from keyring\n privkey = fingerprints[-1][-16:]\n\n return privkey",
"def private_key(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"private_key\")",
"def private_key(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"private_key\")",
"def credential_id(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"credential_id\")",
"def private_key(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"private_key\")",
"def private_key(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"private_key\")",
"def private_key(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"private_key\")",
"def private_key(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"private_key\")",
"def private_key(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"private_key\")",
"def private_key(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"private_key\")",
"def private_key(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"private_key\")",
"def private_key(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"private_key\")",
"def get_private_key(self) -> str:\n\t\treturn self._privateKey",
"def credential_id(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"credential_id\")",
"def credential_get(uniqueID: str):\n\n cert = safeisland.certificate(uniqueID)\n return {\"payload\": cert}",
"def read_key():\n path = os.path.join(os.path.dirname(__file__), 'data')\n f = open(os.path.join(path, 'credential.txt'), 'r')\n key = f.read()\n f.close()\n return key",
"def get_verifying_key(private_key):\n return private_key.get_verifying_key().to_pem().decode('ascii')",
"def get_private_key(self, uid: str) -> str:\n return self.context.get(\n \"/dsum/private_key/%s\" % uid, None, \"DSum: failed retrieving the Curve 25519 private key with uid: %s\" % uid)['key']",
"def get_credential(self, credential_id: str) -> Optional[Union[PasswordCredential, RevokedCredential]]:\n try:\n res = self._coll.find_one({'credential.credential_id': credential_id})\n except KeyError:\n logger.debug(f'Failed looking up credential with credential_id={repr(credential_id)}')\n raise\n if not res:\n return None\n if 'credential' in res:\n if res['credential'].get('status') == 'revoked':\n return RevokedCredential.from_dict_backwards_compat(res)\n _type = res['credential'].get('type')\n if _type == CredType.PASSWORD.value:\n return PasswordCredential.from_dict(res)\n elif _type == CredType.REVOKED.value:\n return RevokedCredential.from_dict(res)\n logger.error(f'Credential {credential_id} has unknown type: {_type}')\n return None",
"def get_private_key(self, address58: str) -> 'EllipticCurvePrivateKey':\n return self.keys[address58]",
"def get_key_from_keyring(self):\n private_key = keyring.get_password(self.keyring_service_name, \"private_key\")\n\n if private_key is not None:\n return base64.b64decode(private_key)\n else:\n return None"
] | [
"0.68223524",
"0.67248297",
"0.6414652",
"0.6405547",
"0.6249193",
"0.6206796",
"0.6136057",
"0.6110275",
"0.60591227",
"0.6022507",
"0.6018188",
"0.6018188",
"0.5972394",
"0.59510946",
"0.59510946",
"0.5943873",
"0.5943873",
"0.5943873",
"0.5943873",
"0.5943873",
"0.5943873",
"0.59331787",
"0.5887163",
"0.5880885",
"0.58737063",
"0.5850093",
"0.58286965",
"0.5809525",
"0.5808638",
"0.5796795"
] | 0.74674255 | 0 |
1) Delete test databases if exist 2) Create databases 3) Create required indices | def reset_databases(self):
for db in self.test_dbs:
if self.db_exists(db):
self.drop_database(db)
# leave some time for synchonization between nodes
time.sleep(3)
self.create_database(db)
self.create_index(db) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def setup():\n with get_session() as s:\n colls = s.db.collection_names()\n for coll in colls:\n if coll == 'system.indexes':\n continue\n s.db[coll].drop_indexes()\n s.db[coll].drop()\n\n s.db.command({'dropDatabase':1})",
"def setUp(self):\n db.drop_all() # clean up the last tests\n db.create_all() # make our sqlalchemy tables",
"def create_databases(self, overwrite = False):\r\n self.validate_config()\r\n self.template_runner.create_databases(overwrite)",
"def create_test_db(self, *args, **kw):\n self.destroy_test_db()\n self.connection.use_test_datastore = True\n self.connection.flush()",
"def createDb():\n db.drop_all()\n db.create_all()",
"async def prepare_databases(self):",
"def create_index(self):\r\n\r\n #### Begin functionality here\r\n if self.session is not None:\r\n self.disconnect()\r\n self.create_database()\r\n return(True)",
"def init_db():\n db.drop_all()\n db.create_all()\n seed_companies()\n seed_emission_reports()\n seed_reduction_targets()\n seed_milestones()",
"def create_db():\n database.db.create_all()\n get_ulm()\n for fixture_file in glob.glob(config.DevelopmentConfig.FIXTURES_DIRS + '/*.json'):\n fixtures = JSONLoader().load(fixture_file)\n load_fixtures(database.db, fixtures)\n MigrationManager().stamp_db()",
"def create_db():\n from sqlalchemy_utils import database_exists, create_database, drop_database\n if not database_exists(DB_URL):\n print('Creating database.')\n create_database(DB_URL)\n else:\n drop_database(DB_URL)\n create_database(DB_URL)\n print(\"Deleted and created new database\")\n create_tables()",
"def test_db_is_created(test_teardown):\n try:\n applications = Application.query.first()\n inhouse_postings = Inhouse.query.first()\n external_postings = External.query.first()\n except Exception:\n assert False\n assert True",
"def ensure_indexes(self):\n self.db_connection.ensure_indexes()",
"def setUp(self):\n INFLUX_DB_NAME = 'test_device_parameters'\n EmptyDBTestCase.client.create_database(INFLUX_DB_NAME)\n EmptyDBTestCase.client.drop_database(INFLUX_DB_NAME)\n EmptyDBTestCase.client.create_database(INFLUX_DB_NAME)",
"def main():\n session, cluster = create_database()\n \n drop_tables(session)\n create_tables(session)\n\n session.shutdown()\n cluster.shutdown()",
"def setUp(self):\n db.create_all()",
"def test_version_upgrade_persistent_add_index(self):\n db_file = self.mktemp()\n db = Database.TestDB(db_file, persistent=True)\n yield db.open()\n yield db.execute(\"INSERT into TESTTYPE (KEY, VALUE) values (:1, :2)\", (\"FOO\", \"BAR\",))\n items = (yield db.query(\"SELECT * from TESTTYPE\"))\n self.assertEqual(items, ((\"FOO\", \"BAR\"),))\n db.close()\n db = None\n\n db = Database.TestDBCreateIndexOnUpgrade(db_file, persistent=True)\n yield db.open()\n items = (yield db.query(\"SELECT * from TESTTYPE\"))\n self.assertEqual(items, ((\"FOO\", \"BAR\"),))\n db.close()",
"def setUp(self):\n self.es = Elasticsearch(hosts=[LOCAL_ELASTICSEARCH])\n try:\n self.es.indices.delete(index='packages')\n except NotFoundError:\n pass\n self.runner = CliRunner()\n self.dbfilename = 'test.db'\n config._set_connection_string('sqlite:///test.db')",
"def setupDatabases(self):\n param = self.getDefaultDatabaseConnectionParameter()\n db = DatabaseFactory.getDatabase(self.defaultDriver(), {})\n db.createDatabase(param)\n db.connect(param)\n if db.isConnected():\n self.settingsDb = db\n db.createObservations()\n db.createSensors()\n else:\n return False\n # replace by settings validation method later\n return self.check()",
"def initdb():\n db.drop_all()\n db.configure_mappers()\n db.create_all()\n db.session.commit()",
"def create_db():\n db.create_all()",
"def create_db():\n db.create_all()",
"def create_db():\n db.create_all()",
"def create_db():\n db.create_all()",
"def create_db():\n db.create_all()",
"def create_db():\n db.create_all()",
"def create_db():\n db.create_all()",
"def create_db():\n db.create_all()",
"def create_db():\n db.create_all()",
"def create_db():\n db.create_all()",
"def create_db():\n db.create_all()"
] | [
"0.7574131",
"0.684399",
"0.6734331",
"0.673097",
"0.66940784",
"0.6657578",
"0.6650568",
"0.6650193",
"0.6626488",
"0.6620688",
"0.66095597",
"0.6592092",
"0.65408206",
"0.64800084",
"0.64629656",
"0.64561844",
"0.64100367",
"0.6370233",
"0.63569957",
"0.63499886",
"0.63499886",
"0.63499886",
"0.63499886",
"0.63499886",
"0.63499886",
"0.63499886",
"0.63499886",
"0.63499886",
"0.63499886",
"0.63499886"
] | 0.76330584 | 0 |
Wait for the given database to reach the target doc count or until the timeout setting is reached | def wait_for_doc_count(self, db_name, expected, timeoutInMin):
timeout = time.time() + timeoutInMin * 60
while (time.time() < timeout):
doc_count = self.get_doc_count(db_name)
if doc_count < int(expected):
time.sleep(5)
else:
print ("{} doc count = {}".format(db_name, doc_count))
return
raise RuntimeError("Timeout waiting for {} to reach count {} after {} min(s)".format(
db_name, expected, timeoutInMin)) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def db():\n raise TimeoutError",
"def wait_for_data_in_ct_table(ct_table_name, no_of_records, database=None, timeout_sec=50):\n logger.info('Waiting for no_data_event to be updated in %s seconds ...', timeout_sec)\n start_waiting_time = time()\n stop_waiting_time = start_waiting_time + timeout_sec\n db_engine = database.engine\n\n while time() < stop_waiting_time:\n event_table = sqlalchemy.Table(ct_table_name, sqlalchemy.MetaData(), autoload=True,\n autoload_with=db_engine, schema='cdc')\n event_result = db_engine.execute(event_table.select())\n event_result_list = event_result.fetchall()\n event_result.close()\n\n if len(event_result_list) >= no_of_records:\n logger.info('%s of data is captured in CT Table %s', no_of_records, ct_table_name)\n return\n sleep(5)\n\n raise Exception('Timed out after %s seconds while waiting for captured data.', timeout_sec)",
"def test_wait_for_db(self, ts):\n\n with patch('django.db.utils.ConnectionHandler.__getitem__') as gi:\n gi.side_effect = [OperationalError] * 5 + [True]\n call_command('Wait_DB')\n self.assertEqual(gi.call_count, 6)",
"async def select(self, db):\n res = True\n async with self._cond:\n for i in range(self.freesize):\n res = res and (await self._pool[i].select(db))\n self._db = db\n return res",
"def cdb_check():\n logfile = 'janusess'\n logger = logging.getLogger(logfile)\n\n check_time = 0.5\n\n log = 'Checking CouchDB every {0} sec until operational.'.format(check_time)\n logger.debug(log)\n\n count = 1\n while True:\n\n # Issue CouchDB GET request and process result\n http_resp = requests.get('http://127.0.0.1:5984/')\n\n # Successful GET request\n if http_resp.status_code == 200:\n log = 'CouchDB is operational.'\n logger.info(log)\n MPQ_ACT.put_nowait([\n datetime.now().isoformat(' '),\n 'INFO',\n log\n ])\n MPQ_STAT.put_nowait([\n 'base',\n [\n 'couchdb',\n STAT_LVL['op']\n ]\n ])\n break\n\n # All GET errors\n else:\n log = 'CouchDB is not operational, failed with http ' +\\\n 'response {0}. Making another attempt.'.format(http_resp.status_code)\n logger.warning(log)\n MPQ_ACT.put_nowait([\n datetime.now().isoformat(' '),\n 'WARNING',\n log\n ])\n MPQ_STAT.put_nowait([\n 'base',\n [\n 'couchdb',\n STAT_LVL['cfg_err']\n ]\n ])\n\n count += count\n time.sleep(check_time)",
"def test_wait_for_db(self, ts):\n with patch('django.db.utils.ConnectionHandler.__getitem__') as gi:\n gi.side_efffect = [OperationalError] * 5 + [True]\n call_command('wait_for_db')\n self.assetEqual(gi.call_count, 6)",
"def test_wait_for_db(self, ts):\n \"\"\" Here we are checking that the wait_for_db command will try the database 5 times\n and on the sixth time it'll be successful and continue \n \"\"\"\n with patch('django.db.utils.ConnectionHandler.__getitem__') as gi:\n gi.side_effect=[OperationalError] * 5 + [True]\n call_command('wait_for_db')\n self.assertEqual(gi.call_count, 6)",
"def waitForDBChange(self, db_name, since = 0, timeout = 15000):\n changes = []\n last_seq = max(self.getLastChangeSeq(db_name), since)\n db = self.__getDb(db_name)\n with ChangesStream(db, feed=\"longpoll\", since = last_seq, timeout = timeout) as stream:\n for change in stream:\n if change['seq'] > self.getLastChangeSeq(db_name):\n changes.append(change)\n last_seq = reduce(lambda x,y: max(y['seq'], x) , changes, self.getLastChangeSeq(db_name))\n self.setLastChangeSeq(db_name, last_seq)\n return changes",
"def test_polling_loop(self, cursor):\n cursor._poll_interval = 0\n yield cursor.execute('SELECT COUNT(*) FROM many_rows')\n self.assertEqual((yield cursor.fetchone()), [10000])",
"def test_timeout_with_successful_crud(self):\n\n shell_conn = dict()\n cbstat_obj = dict()\n error_sim = dict()\n vb_info = dict()\n vb_info[\"init\"] = dict()\n vb_info[\"afterCrud\"] = dict()\n\n target_nodes = DurabilityHelper.getTargetNodes(self.cluster,\n self.nodes_init,\n self.num_nodes_affected)\n for node in target_nodes:\n shell_conn[node.ip] = RemoteMachineShellConnection(node)\n cbstat_obj[node.ip] = Cbstats(node)\n vb_info[\"init\"][node.ip] = cbstat_obj[node.ip].vbucket_seqno(\n self.bucket.name)\n error_sim[node.ip] = CouchbaseError(self.log, shell_conn[node.ip])\n\n doc_load_spec = dict()\n doc_load_spec[MetaCrudParams.SDK_TIMEOUT] = self.sdk_timeout\n doc_load_spec[MetaCrudParams.DURABILITY_LEVEL] = self.durability_level\n doc_load_spec[\"doc_crud\"] = dict()\n doc_load_spec[\"subdoc_crud\"] = dict()\n doc_load_spec[\"doc_crud\"][MetaCrudParams.DocCrud.COMMON_DOC_KEY] = \\\n \"test_collections\"\n doc_load_spec[\"doc_crud\"][\n MetaCrudParams.DocCrud.CREATE_PERCENTAGE_PER_COLLECTION] = 0\n doc_load_spec[\"doc_crud\"][\n MetaCrudParams.DocCrud.UPDATE_PERCENTAGE_PER_COLLECTION] = 0\n doc_load_spec[\"doc_crud\"][\n MetaCrudParams.DocCrud.DELETE_PERCENTAGE_PER_COLLECTION] = 0\n\n doc_load_spec[\"subdoc_crud\"][\n MetaCrudParams.SubDocCrud.INSERT_PER_COLLECTION] = 0\n doc_load_spec[\"subdoc_crud\"][\n MetaCrudParams.SubDocCrud.UPSERT_PER_COLLECTION] = 0\n doc_load_spec[\"subdoc_crud\"][\n MetaCrudParams.SubDocCrud.REMOVE_PER_COLLECTION] = 0\n\n ops_to_perform = [\"create\", \"update\", \"read\", \"replace\", \"delete\"]\n if self.subdoc_test:\n ops_to_perform = [\"insert\", \"upsert\", \"remove\"]\n\n for op_type in ops_to_perform:\n self.log.info(\"Performing '%s' with timeout=%s\"\n % (op_type, self.sdk_timeout))\n curr_spec = deepcopy(doc_load_spec)\n if op_type == \"create\":\n curr_spec[\"doc_crud\"][\n MetaCrudParams.DocCrud.CREATE_PERCENTAGE_PER_COLLECTION] \\\n = 5\n elif op_type == \"update\":\n curr_spec[\"doc_crud\"][\n MetaCrudParams.DocCrud.UPDATE_PERCENTAGE_PER_COLLECTION] \\\n = 5\n elif op_type == \"delete\":\n curr_spec[\"doc_crud\"][\n MetaCrudParams.DocCrud.DELETE_PERCENTAGE_PER_COLLECTION] \\\n = 5\n elif op_type == \"read\":\n curr_spec[\"doc_crud\"][\n MetaCrudParams.DocCrud.READ_PERCENTAGE_PER_COLLECTION] = 5\n curr_spec[MetaCrudParams.RETRY_EXCEPTIONS] = [\n SDKException.TimeoutException]\n elif op_type == \"insert\":\n curr_spec[\"subdoc_crud\"][\n MetaCrudParams.SubDocCrud.INSERT_PER_COLLECTION] = 5\n elif op_type == \"upsert\":\n curr_spec[\"subdoc_crud\"][\n MetaCrudParams.SubDocCrud.UPSERT_PER_COLLECTION] = 5\n elif op_type == \"remove\":\n curr_spec[\"subdoc_crud\"][\n MetaCrudParams.SubDocCrud.REMOVE_PER_COLLECTION] = 5\n\n doc_loading_task = \\\n self.bucket_util.run_scenario_from_spec(\n self.task,\n self.cluster,\n self.cluster.buckets,\n curr_spec,\n mutation_num=1,\n async_load=True,\n validate_task=False)\n\n # Perform specified action\n for node in target_nodes:\n error_sim[node.ip].create(self.simulate_error,\n bucket_name=self.bucket.name)\n\n self.sleep(10, \"Wait before reverting the error condition\")\n\n # Revert the specified error scenario\n for node in target_nodes:\n error_sim[node.ip].revert(self.simulate_error,\n bucket_name=self.bucket.name)\n\n self.task_manager.get_task_result(doc_loading_task)\n self.bucket_util.validate_doc_loading_results(doc_loading_task)\n if doc_loading_task.result is False:\n self.fail(\"Doc_loading for '%s' failed\" % op_type)\n\n # Fetch latest stats and validate the values are updated\n for node in target_nodes:\n curr_stat = cbstat_obj[node.ip].vbucket_seqno(self.bucket.name)\n if vb_info[\"init\"][node.ip] == curr_stat:\n self.log_failure(\"vbucket_seqno not updated. %s == %s\"\n % (vb_info[\"init\"][node.ip], curr_stat))\n\n # Disconnect the shell connection\n for node in target_nodes:\n shell_conn[node.ip].disconnect()\n\n # Verify initial doc load count\n self.bucket_util._wait_for_stats_all_buckets(self.cluster,\n self.cluster.buckets)\n self.bucket_util.validate_docs_per_collections_all_buckets(\n self.cluster)\n self.validate_test_failure()",
"def test_wait_for_page_in_timeout(self):\n start_time = datetime.now()\n with self.assertRaises(SpdbError):\n csdb = CacheStateDB(self.config_data)\n ch = csdb.create_page_in_channel()\n\n csdb.wait_for_page_in([\"MY_TEST_KEY1\", \"MY_TEST_KEY2\"], ch, 1)\n\n assert (datetime.now() - start_time).seconds < 3",
"def poll_query_until(self, dbname, query):\n max_attemps = 60\n attemps = 0\n\n while attemps < max_attemps:\n ret = self.safe_psql(dbname, query)\n # TODO: fix psql so that it returns result without newline\n if ret == six.b(\"t\\n\"):\n return\n\n time.sleep(1)\n attemps += 1\n raise QueryException(\"Timeout while waiting for query to return True\")",
"def handle(self, *args, **options) -> None:\n max_database_attempts = options.pop(\"max_database_attempts\", 5)\n backoff_exponent = options.pop(\"backoff_exponent\", 1)\n wait_for_postgres(max_database_attempts, backoff_exponent)",
"async def ping_db(db_uri: str, retries: int, timeout: int) -> None:\n for _ in range(retries):\n try:\n conn = await asyncpg.connect(dsn=db_uri)\n except Exception as e:\n print(f\"Postgres is unavailable: {repr(e)}, waiting for {timeout} seconds\")\n await asyncio.sleep(timeout)\n else:\n print(\"Postgres is ready\")\n await conn.close()\n break",
"def test_wait_for_db_command_(self, mock_time_sleep):\n with patch(\n 'django.db.utils.ConnectionHandler.__getitem__',\n side_effect=[OperationalError]*5 + [True]\n ) as gi:\n call_command('wait_for_db')\n self.assertEqual(gi.call_count, 6)",
"def test_wait_for_db_ready(self):\n\n with patch('django.db.utils.ConnectionHandler.__getitem__') as gi:\n gi.return_value = True\n call_command('Wait_DB')\n self.assertEqual(gi.call_count, 1)",
"def wait_for_update(self):\n while \"updating_db\" in self.status():\n time.sleep(1)",
"def database_search_done_check(obsid, pointing):\n con = lite.connect(DB_FILE, timeout = TIMEOUT)\n con.row_factory = lite.Row\n with con:\n cur = con.cursor()\n #get script data\n cur.execute(\"SELECT Ended FROM PulsarSearch WHERE Obsid=? AND Pointing=?\",\n (obsid, pointing))\n endtime = cur.fetchall()\n searched_check = False\n for e in endtime:\n if e[0] is not None:\n searched_check = True\n return searched_check",
"def execution_timeout(err):\n success = False\n message = err.args[0]\n mongo_return_obj = MongoReturn(success=success, message=message, db_exception=err)\n return mongo_return_obj",
"def block(self):\n start=time.time()\n max_wait=100\n while ((time.time()-start)<max_wait):\n if not self.query_running(): break\n return (time.time()-start)<max_wait",
"def Mongodb_Connection():\r\n \r\n client = pymongo.MongoClient(\"localhost\", 27017)\r\n db = client.test\r\n\r\n\r\n if db.Transaction.estimated_document_count() != 0:\r\n \"\"\"\r\n To make a new test, the database is cleared if not empty\r\n \"\"\"\r\n \r\n db.command(\"dropDatabase\")\r\n \r\n return db",
"def test_wait_for_db_ready(self):\n\n with patch(\n 'django.db.utils.ConnectionHandler.__getitem__',\n return_value=True\n ) as gi:\n call_command('wait_for_db')\n self.assertEqual(gi.call_count, 1)",
"def Count_Documents(db):\r\n \r\n count = db.Transaction.estimated_document_count()\r\n print(\"Number of documents in the database Transaction: \" + str(count) + \".\\n\")\r\n return count",
"def test_maxttl_setting(self):\n maxttl = int(self.input.param(\"maxttl\", None))\n self.run_multi_operations(buckets = self.buckets,\n query_definitions = self.query_definitions,\n create_index = True, drop_index = False,\n query_with_explain = False, query = False)\n self.sleep(20)\n self._verify_bucket_count_with_index_count()\n self.sleep(maxttl, \"waiting for docs to be expired automatically per maxttl rule\")\n self._expiry_pager(self.master)\n self.sleep(60, \"wait for expiry pager to run on all nodes...\")\n for bucket in self.buckets:\n items = RestConnection(self.master).get_active_key_count(bucket)\n self.log.info(\"Docs in source bucket is {0} after maxttl has elapsed\".format(items))\n if items != 0:\n self.fail(\"Docs in source bucket is not 0 after maxttl has elapsed\")\n self._verify_bucket_count_with_index_count()",
"def wait_for_postgres(max_attempts: int = 5, backoff_exponent: int = 1) -> None:\n log.info(\"Waiting for database to start up.\")\n for attempt in range(1, max_attempts + 1):\n try:\n log.info(\"Attempting to connect to database [%s/%s]\", attempt, max_attempts)\n conn = psycopg2.connect(os.environ[\"DATABASE_URL\"])\n except psycopg2.OperationalError:\n if attempt < max_attempts:\n delay = attempt ** backoff_exponent\n log.info(\"Connection failed, sleeping for %s second...\", delay)\n time.sleep(delay)\n else:\n log.critical(\"Failed to connect to database.\")\n raise\n else:\n log.info(\"Connected successfully to the database.\")\n conn.close()\n break",
"def test_maxttl_with_doc_updates(self):\n rest = RestConnection(self.master)\n for bucket in self.buckets:\n self._load_json(bucket, self.num_items, exp=40)\n\n self.sleep(20, \"waiting to update docs with exp=60s...\")\n\n for bucket in self.buckets:\n self._load_json(bucket, self.num_items, exp=60)\n\n self.sleep(40, \"waiting before running expiry pager...\")\n self.expire_pager(self.servers)\n for bucket in self.buckets:\n items = rest.get_active_key_count(bucket)\n self.log.info(\"Items: {0}\".format(items))\n if items != self.num_items:\n self.fail(\"FAIL: Docs with updated expiry deleted unexpectedly!\")\n\n self.sleep(20, \"waiting before running expiry pager...\")\n self.expire_pager(self.servers)\n self.sleep(20, \"waiting for item count to come down...\")\n for bucket in self.buckets:\n items = rest.get_active_key_count(bucket)\n self.log.info(\"Items: {0}\".format(items))\n if items != 0:\n self.fail(\"FAIL: Docs with updated expiry not deleted after new exp has elapsed!\")",
"def update_database(self) -> None:\n \n # Simulate that we update a database\n time.sleep(10)",
"def wait_for(self, query_delay=0):\n raise NotImplementedError(\"Implement in subclass!\")",
"def _wait_conn(cls, gen: PQGenConn[RV], timeout: Optional[int]) -> RV:\n return waiting.wait_conn(gen, timeout=timeout)",
"def network_timeout(err):\n success = False\n message = err.args[0]\n mongo_return_obj = MongoReturn(success=success, message=message, db_exception=err)\n return mongo_return_obj"
] | [
"0.6410089",
"0.60500443",
"0.5847077",
"0.58316916",
"0.57926905",
"0.57169855",
"0.56730956",
"0.56220376",
"0.5602724",
"0.5562018",
"0.55521774",
"0.5537189",
"0.5532466",
"0.5527219",
"0.5509803",
"0.5502426",
"0.5425657",
"0.54245543",
"0.53881073",
"0.5335665",
"0.5312229",
"0.53069276",
"0.5281685",
"0.51883125",
"0.5169634",
"0.5166591",
"0.5160315",
"0.5158847",
"0.5128295",
"0.511676"
] | 0.7432831 | 0 |
Start of the progress bar. | def start_progress_bar(self):
self.progress["value"] = self.progress_step | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def start(self):\n super(ProgressBar, self).start()\n self.display()",
"def start_progress(title):\n global progress_x\n sys.stdout.write(title + \": [\" + \"-\" * 40 + \"]\" + chr(8) * 41)\n sys.stdout.flush()\n progress_x = 0\n return 0",
"def startprogress(title):\n global progress_x, title_global\n title_global = title\n sys.stdout.write(title + \": [\" + \"-\" * 40 + \"] 00% \")\n sys.stdout.flush()\n progress_x = 0",
"def next(self):\n if self.skip:\n return\n\n self.counter += 1\n if self.pbar is None and (time.time() - self.start_time) > self.threshold:\n self.pbar = tqdm(total=self.n, desc=self.title, initial=self.counter)\n elif self.pbar is not None:\n self.pbar.update(1)",
"def next(self):\n print(f\" {colored('[', 'yellow')}{bold(self.progress[self.pos])}{colored(']', 'yellow')} \"\n f\"{bold('Processing, please wait...')}\",\n end=\"\\r\",\n flush=True\n )\n self.increment()",
"def progress(self):\n if self.running:\n pass\n else:\n self._engine.progress()",
"def _prepare(self, progress: BaseProgressMonitor):\n self._started = True\n self._total_bytes = None\n self._downloaded_bytes = 0\n self._progress = progress\n if self.show_progress_bar:\n self._tqdm = tqdm(total=None, unit=\"bytes\", dynamic_ncols=True, file=sys.stdout)\n else:\n self._tqdm = None",
"def tick(self):\n self.current_count += 1\n self.progress(self.current_count)",
"def set_started(self, progress=None, message=None):\n if progress is not None:\n assert 0 <= progress < 100\n self._progress = int(progress)\n self.logger.info(\n \"status: STARTED %d%% %s\", self._progress, message or \"\"\n )\n self._callback('on_started', self._progress, message)\n return self.update_response(\n self.encoder.encode_started(self._progress, message)\n )",
"def set_progress(self, progress: float):",
"def progress(self, progress):\n\n self._progress = progress",
"def progress(self, progress):\n\n self._progress = progress",
"def begin(self,whatToPrint):\n self.my_print(whatToPrint + ' ...', msg_types.INFO, False)\n self.in_progress = True\n sys.stdout.flush()",
"def start(self):\n self._state = 'Started'",
"def setProgress(self, prog):\n\t\tself.progress = prog",
"def start(self):\n self.reset()\n self.on_start()",
"def start_progress_bar(self, of=None):\n if of is None:\n if self.n_batches_last is None:\n of = 0\n else:\n of = self.n_batches_last\n if self.progress is None:\n self.progress = Progress(\n TextColumn(\"Epoch {task.fields[epoch]}\"),\n SpinnerColumn(),\n TextColumn(\"Batch {task.fields[batch]:3} / {task.fields[of]:3}\"),\n BarColumn(),\n TimeElapsedColumn(table_column=Column(header=\"Elapsed\")),\n TextColumn(\"/\"),\n TimeRemainingColumn(table_column=Column(header=\"Remaining\")),\n TextColumn(\"|\"),\n TextColumn(\"[red]Loss: {task.fields[batch_loss]:1.3f}[red],\"),\n TextColumn(\"[red][b]Avg.: {task.fields[running_mean]:1.3f}[/b][/red]\"),\n auto_refresh=False,\n transient=True,\n )\n fields = {\n \"epoch\": 1,\n \"running_mean\": np.nan,\n \"batch_loss\": np.nan,\n \"of\": of,\n \"batch\": 0,\n }\n self.task = self.progress.add_task(\n f\"Epoch {self.i_epoch + 1}\", total=of, **fields\n )\n self.progress.update(\n self.task, completed=0, total=of, epoch=self.i_epoch + 1, mode=\"training\"\n )",
"def Start(self, what=''):\n self.what = what\n self.progress = 0.0\n self.nbits = 0\n sys.stdout.write(what + \" [\")",
"def _dl_progress_bar(self):\n if not self.show_progress:\n return\n\n if self.file_size:\n ratio = float(self.bytes_read) / self.file_size\n else:\n ratio = 1\n percent = int(ratio * 100)\n\n bar_len = 60\n done = int(bar_len * ratio)\n bar = ('=' * done) + (' ' * (bar_len - done))\n\n progress = '{percent: >3}%: [{bar}]'.format(percent=percent, bar=bar)\n backspace = '\\b' * len(progress)\n print(backspace + '\\r', end='')\n print(progress, end='')",
"def showProgressBar(self):\n logging.info(\"Show progress bar\")\n self.progressLabel = QLabel(self)\n font = QFont()\n font.setFamily(\"GE Inspira\")\n font.setPointSize(20)\n self.progressLabel.setFont(font)\n self.progressLabel.setAlignment(Qt.AlignCenter)\n self.progressLabel.setText(\"Hello\")\n self.ui.layout_v.addWidget(self.progressLabel)\n\n self.progressBar = QProgressBar(self) # Progress bar created\n self.progressBar.setRange(0, 0)\n self.ui.layout_v.addWidget(self.progressBar)",
"def begin(self):\n self._logger.debug(\"Begin\")",
"def show_progressbar(self):\n\n self.progressframe = tk.Toplevel(self, background='white')\n self.progressframe.lift()\n self.progressframe.focus_force()\n self.progressframe.grab_set()\n self.progressframe.resizable(False, False)\n self.progressframe.minsize(width=200, height=50)\n progressbar = ttk.Progressbar(self.progressframe, mode='indeterminate', length=200)\n progressbar.pack(pady=(10, 0), padx=5)\n progressbar.start(10)\n progresslabel = tk.Label(self.progressframe, text='Generating BOM Comparison', background='white')\n progresslabel.pack(pady=(0, 10))",
"def increment(self):\n self.pos += 1\n if self.pos == len(self.progress) - 1:\n self.pos = 0",
"def wait_progress(self):\n pass",
"def wait_progress(self):\n pass",
"def setupStatus(start, end):\n global startsector, sectorlen, readsector, progressbar\n startsector = start\n sectorlen = end - start\n readsector = start\n progressbar = [\" \" for i in range(0,30)]\n return",
"def begin(self):\r\n self.queue.append((self.start, 0.0))\r\n self.cost_to_pos[self.start] = 0\r\n self.loop()",
"def init_progress_bar(self):\n if not self.progress_message_bar:\n self.progress_message_bar = self.iface.messageBar().createMessage(\"Querying for data\")\n progress = QProgressBar()\n progress.setMinimum(0)\n progress.setMaximum(0)\n progress.setAlignment(Qt.AlignLeft | Qt.AlignCenter)\n self.progress_message_bar.layout().addWidget(progress)\n self.progress_message_bar_widget = self.iface.messageBar().pushWidget(self.progress_message_bar, self.iface.messageBar().INFO)",
"def increment(self, length):\r\n self.progress_bar.update(length)",
"def start(text=\"\"):\n global _current_line\n _current_line = StatusLine(text, WIDTH)"
] | [
"0.84644544",
"0.7360849",
"0.7187556",
"0.69703597",
"0.6866065",
"0.6785758",
"0.6686456",
"0.6678523",
"0.6637322",
"0.6601717",
"0.6573703",
"0.6573703",
"0.6573342",
"0.6567026",
"0.6436477",
"0.64347017",
"0.64345366",
"0.6433723",
"0.6412171",
"0.63984936",
"0.6395387",
"0.6388343",
"0.6371284",
"0.6358551",
"0.6358551",
"0.63584465",
"0.6344911",
"0.6344865",
"0.63371223",
"0.6336805"
] | 0.8612583 | 0 |
The methods launching profile manager. | def open_profile_menager():
reload(edc_profile_manager)
edc_profile_manager.ProfileManager() | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def run_profile(self):\n self.create_shelf_dir(self.profile.tc_temp_path)\n\n # run the App\n return self.run(self.profile.args)",
"def do_startup(self):\n logger.debug('::startup')\n Gio.Application.do_startup(self)\n action = Gio.SimpleAction.new('quit', None)\n action.connect('activate', self.quit)\n self.add_action(action)\n # Initialize the current profiles, but do not auto load\n try:\n self.load_profile(self._settings.get_string('current-profile'), False, False)\n if self._settings.get_string('lockscreen-profile') != \"\":\n self.load_profile(self._settings.get_string('lockscreen-profile'), True, False)\n except (WallpaperNotFoundError, NotFoundError) as e:\n # If we failed to load the profile, its bad\n logger.error('failed to load profiles on startup: %s', e.message)\n # Connect the settings signals\n self._settings_handlers.append(self._settings.connect(\n 'changed::rotation',\n lambda s, k: self._toggle_timer(self._settings.get_string('rotation'))\n ))\n self._settings_handlers.append(self._settings.connect(\n 'changed::interval',\n lambda s, k: self._toggle_timer(self._settings.get_string('rotation'))\n ))\n self._settings_handlers.append(self._settings.connect('changed::current-profile', self._callback_desktop))\n self._settings_handlers.append(self._settings.connect('changed::lockscreen-profile', self._callback_lockscreen))\n self._settings_handlers.append(self._settings.connect('changed::update-lockscreen', self._callback_lockscreen))",
"def __init__(self):\r\n super(ProfileParser, self).__init__([self.ProfileEntryHandler()])",
"async def profile(self, ctx:utils.Context):\n\n pass",
"def execute(self) -> None:\n profile_name = self.args.profile[0]\n if not self.git_manager.check_profile_exist(profile_name):\n if not self.quiet:\n print(msg.ERR_NO_PROFILE.format(profile_name))\n return\n\n # Get the details of the profile\n full_name = \"profile.{0}\".format(profile_name)\n profile = self.git_manager.get_profile(full_name)\n\n print(profile_name)\n print(profile)",
"def LaunchChooser(self):\n print 'calling wired profile chooser'\n self.SetNeedWiredProfileChooser(True)",
"def test_pm_profile_activate(profile_manager, test_profile):\n\n profile_manager.activate(test_profile.name)\n assert profile_manager.is_active(test_profile.name)\n profile = profile_manager.get_active_profile()\n assert profile.name == test_profile.name\n assert profile.path == test_profile.path",
"def run(self):\n if not self.__class__.profile is None:\n import cProfile\n cminstance = self\n cProfile.runctx('self._run()', globals(), locals(), self.__class__.profile)\n else:\n self._run()",
"def get_profiles(self):\n # print(self.uir) #checkpoint\n if os.path.isdir(self.uir+\"/profiles\"):\n profiles=os.listdir(self.uir+\"/profiles\")\n # print(profiles) #checkpoint\n for profile in profiles:\n wsadmin=self.uir+\"/profiles/\"+profile+\"/bin/wsadmin.bat\"\n if os.path.isfile(wsadmin): #check for wsadmin.bat.\n self.profiles.append(self.uir+\"/profiles/\"+profile)\n\n else: print(self.uir+' Instance does not have \"profile\" folder in '+self.uir)\n return",
"def profile_manager(tmpdir_factory):\n temp_profile_dir = tmpdir_factory.mktemp('pmtest')\n return ProfileManager(str(temp_profile_dir))",
"def profile_step(self):\n import profile\n\n profile.run(\"world.step()\")",
"def _profile(self) -> None:\n if self.use_case.profile:\n if self._profile_stats is None:\n self._profile_stats = pstats.Stats()\n if self._current_profiler is not None:\n self._current_profiler.disable()\n self._profile_stats.add(self._current_profiler)\n # TODO: use clear() instead of always creating a new profile\n self._current_profiler = cProfile.Profile()\n self._current_profiler.enable()",
"def run_profiles(self):\n\n logger.info('Running hybrid profile calculations.')\n\n self._init_profiles()\n self._compute_hybridized_profile_components()\n self._compute_hybridized_profiles_from_components()\n\n logger.info('Profile hybridization complete.')\n\n return self",
"def getprofile(): # real signature unknown; restored from __doc__\n pass",
"def enter_global_profile():\n # We set a global variable because otherwise the context object will be garbage\n # collected which will call __exit__ as soon as this function scope ends.\n global GLOBAL_PROFILE_CM\n\n if GLOBAL_PROFILE_CM:\n return # A global context already has been entered\n\n name = prefect.settings.get_active_profile(name_only=True)\n GLOBAL_PROFILE_CM = profile(name=name, initialize=False)\n GLOBAL_PROFILE_CM.__enter__()",
"def startProfile(profileName):\n \n checkRoot()\n\n # Enable bluetooth service if not enabled\n changeBluetoothService(enable=True)\n \n # Check if profile file exists\n if not os.path.isfile('/etc/bluectl/'+profileName):\n print('Profile with given name does not exist.')\n return\n\n # Load profile\n with open('/etc/bluectl/'+profileName, 'rt') as profileFile:\n for line in profileFile.readlines():\n if 'Controller=' in line:\n cntMAC = line.replace('Controller=', '').replace('\\n', '')\n if 'Device=' in line:\n deviceMAC = line.replace('Device=', '').replace('\\n', '')\n \n if not (checkMACAddress(cntMAC) or checkMACAddress(deviceMAC)):\n print('Profile file is corrupted. Please remove and create this profile again.')\n return\n \n print('\\nStarting bluetooth profile\\n')\n \n # Choose bluetooth controller\n blueSelectStdout = execCommand('bluetoothctl select {}'.format(cntMAC))\n \n # Power on bluetooth controller\n bluePoweronStdout = execCommand('bluetoothctl power on')\n \n # Connect bluetooth device\n blueConnectStdout = execCommand('bluetoothctl connect {}'.format(deviceMAC))\n \n if not 'Connection successful' in blueConnectStdout:\n print(blueConnectStdout)\n print('Is device powered on in the vicinity?\\n')\n return\n \n print('Profile was successfully started\\n')\n \n return",
"def use_profile(self, profile_name, workdir=None):\n error_messages = []\n\n # Clear all the current configuration before loading a new profile\n self._w3af_core.plugins.zero_enabled_plugins()\n MiscSettings().set_default_values()\n self._w3af_core.uri_opener.settings.set_default_values()\n\n if profile_name is None:\n # If the profile name is None, I just clear the enabled plugins and\n # return\n return\n\n # This might raise an exception (which we don't want to handle) when\n # the profile does not exist\n profile_inst = profile(profile_name, workdir)\n \n # It exists, work with it!\n\n # Set the target settings of the profile to the core\n self._w3af_core.target.set_options(profile_inst.get_target())\n\n # Set the misc and http settings\n try:\n profile_misc_settings = profile_inst.get_misc_settings()\n except BaseFrameworkException, e:\n msg = ('Setting the framework misc-settings raised an exception'\n ' due to unknown or invalid configuration parameters. %s')\n error_messages.append(msg % e)\n else:\n #\n # IGNORE the following parameters from the profile:\n # - misc_settings.local_ip_address\n #\n if 'local_ip_address' in profile_inst.get_misc_settings():\n local_ip = get_local_ip()\n profile_misc_settings['local_ip_address'].set_value(local_ip)\n\n misc_settings = MiscSettings()\n misc_settings.set_options(profile_misc_settings)\n\n try:\n http_settings = profile_inst.get_http_settings()\n except BaseFrameworkException, e:\n msg = ('Setting the framework http-settings raised an exception'\n ' due to unknown or invalid configuration parameters. %s')\n error_messages.append(msg % e)\n else:\n self._w3af_core.uri_opener.settings.set_options(http_settings)\n\n #\n # Handle plugin options\n #\n error_fmt = ('The profile you are trying to load (%s) seems to be'\n ' outdated, this is a common issue which happens when the'\n ' framework is updated and one of its plugins adds/removes'\n ' one of the configuration parameters referenced by a'\n ' profile, or the plugin is removed all together.\\n\\n'\n\n 'The profile was loaded but some of your settings might'\n ' have been lost. This is the list of issues that were'\n ' found:\\n\\n'\n ' - %s\\n'\n\n '\\nWe recommend you review the specific plugin'\n ' configurations, apply the required changes and save'\n ' the profile in order to update it and avoid this'\n ' message. If this warning does not disappear you can'\n ' manually edit the profile file to fix it.')\n\n core_set_plugins = self._w3af_core.plugins.set_plugins\n\n for plugin_type in self._w3af_core.plugins.get_plugin_types():\n plugin_names = profile_inst.get_enabled_plugins(plugin_type)\n\n # Handle errors that might have been triggered from a possibly\n # invalid profile\n try:\n unknown_plugins = core_set_plugins(plugin_names, plugin_type,\n raise_on_error=False)\n except KeyError:\n msg = ('The profile references the \"%s\" plugin type which is'\n ' unknown to the w3af framework.')\n error_messages.append(msg % plugin_type)\n continue\n \n for unknown_plugin in unknown_plugins:\n msg = ('The profile references the \"%s.%s\" plugin which is'\n ' unknown in the current framework version.')\n error_messages.append(msg % (plugin_type, unknown_plugin))\n\n # Now we set the plugin options, which can also trigger errors with\n # \"outdated\" profiles that users could have in their ~/.w3af/\n # directory.\n for plugin_name in set(plugin_names) - set(unknown_plugins):\n\n try:\n plugin_options = profile_inst.get_plugin_options(\n plugin_type,\n plugin_name)\n self._w3af_core.plugins.set_plugin_options(plugin_type,\n plugin_name,\n plugin_options)\n except BaseFrameworkException, w3e:\n msg = ('Setting the options for plugin \"%s.%s\" raised an'\n ' exception due to unknown or invalid configuration'\n ' parameters. %s')\n error_messages.append(msg % (plugin_type, plugin_name, w3e))\n\n if error_messages:\n msg = error_fmt % (profile_name, '\\n - '.join(error_messages))\n raise BaseFrameworkException(msg)",
"def run_profile(self):\n # create encrypted config file\n self.create_config(self.profile.args)\n\n # run the service App in 1 of 3 ways\n if self.run_method == 'inline':\n # backup sys.argv\n sys_argv_orig = sys.argv\n\n # clear sys.argv\n sys.argv = sys.argv[:1]\n\n # run the App\n exit_code = self.run()\n\n # restore sys.argv\n sys.argv = sys_argv_orig\n elif self.run_method == 'subprocess':\n # run the Service App as a subprocess\n app_process = subprocess.Popen(['python', 'run.py'])\n exit_code = app_process.wait()\n\n try:\n # remove env var for encrypted file if there\n del os.environ['TC_APP_PARAM_KEY']\n del os.environ['TC_APP_PARAM_FILE']\n except KeyError:\n pass\n\n # add context for populating output variables\n self.profile.add_context(self.context)\n\n return exit_code",
"def launch(self):",
"def load_profile(self):\n self.dut_testpmd.start_testpmd(\n \"Default\", \"--pkt-filter-mode=perfect --port-topology=chained \\\n --txq=%s --rxq=%s\"\n % (self.PF_QUEUE, self.PF_QUEUE))\n self.vm0_testpmd.start_testpmd(\n VM_CORES_MASK, \"--port-topology=chained --txq=%s --rxq=%s\"\n % (self.VF_QUEUE, self.VF_QUEUE))\n self.dut_testpmd.execute_cmd('port stop all')\n time.sleep(1)\n out = self.dut_testpmd.execute_cmd('ddp get list 0')\n self.dut_testpmd.execute_cmd('ddp add 0 /tmp/gtp.pkgo,/tmp/gtp.bak')\n out = self.dut_testpmd.execute_cmd('ddp get list 0')\n self.verify(\"Profile number is: 1\" in out,\n \"Failed to load ddp profile!!!\")\n self.dut_testpmd.execute_cmd('port start all')\n time.sleep(1)\n self.dut_testpmd.execute_cmd('set fwd rxonly')\n self.dut_testpmd.execute_cmd('set verbose 1')\n self.dut_testpmd.execute_cmd('start')\n self.vm0_testpmd.execute_cmd('set fwd rxonly')\n self.vm0_testpmd.execute_cmd('set verbose 1')\n self.vm0_testpmd.execute_cmd('start')",
"def __init__(self):\n super(Profile, self).__init__()",
"def test_pm_profile_create(profile_manager, name):\n profile = profile_manager.create(name)\n assert os.path.isdir(profile.path)\n if name:\n assert profile.name == name",
"def profileToolClicked(self):\n self.openDock()\n # Set the profile map tool\n self.profile_tool.setActive()",
"def setup_class(self) -> None:\n super(TestProfiles, self).setup_class()\n self.custom = CustomFeature() # pylint: disable=attribute-defined-outside-init\n if os.getenv('SETUP_CLASS') is None:\n self.custom.setup_class(self)\n # enable auto-update of profile data\n self.enable_update_profile = True # pylint: disable=attribute-defined-outside-init",
"def get_user_profile(self):\n\t\treturn Job(SDK.PrlSrv_GetUserProfile(self.handle)[0])",
"def createProfile(self):\n if self.profile:\n return\n from soc.modules.gsoc.models.profile import GSoCProfile\n user = self.createUser()\n properties = {'link_id': user.link_id, 'student_info': None, 'user': user,\n 'parent': user, 'scope': self.program, 'status': 'active'}\n self.profile = seeder_logic.seed(GSoCProfile, properties)",
"def test_profile(profile_manager):\n name = 'test_profile'\n yield profile_manager.create(name)\n if profile_manager.has_profile(name):\n profile_manager.delete(name)",
"def profile_module(self):\n return base_profiler.run_in_separate_process(self._profile_module)",
"def initialize():\n pinfo = pathinfo()\n\n if not pinfo:\n raise Error('cannot decide profile directory, $SUZUPROFILEDIR, $APPDATA, or $HOME should be configured.')\n\n # dig profdir\n if not os.path.isdir(pinfo['profiledir']):\n os.mkdir(pinfo['profiledir'])\n\n # test dir\n if not os.path.isdir(pinfo['profiledir']):\n raise Error('profile directory {} does not exist, nor cannot create'.format(pinfo['profiledir']))\n\n # test profile data file\n if not os.path.isfile(pinfo['config']):\n with open(pinfo['config'], 'w') as stream:\n json.dump(config.default, stream, indent=2, sort_keys=True)\n\n # test file (do not care on the contents)\n if not os.path.isfile(pinfo['config']):\n raise Error('config file {} does not exist, nor cannot create'.format(pinfo['config']))\n\n return pinfo",
"def _load_profile(self, profile_name, cwd):\n\n profile_path = self.get_profile_path(profile_name, cwd)\n try:\n text = load_user_encoded(profile_path)\n except Exception as e:\n raise ConanException(f\"Cannot load profile:\\n{e}\")\n\n # All profiles will be now rendered with jinja2 as first pass\n base_path = os.path.dirname(profile_path)\n file_path = os.path.basename(profile_path)\n context = {\"platform\": platform,\n \"os\": os,\n \"profile_dir\": base_path,\n \"profile_name\": file_path,\n \"conan_version\": conan_version}\n rtemplate = Environment(loader=FileSystemLoader(base_path)).from_string(text)\n text = rtemplate.render(context)\n\n try:\n return self._recurse_load_profile(text, profile_path)\n except ConanException as exc:\n raise ConanException(\"Error reading '%s' profile: %s\" % (profile_name, exc))"
] | [
"0.6487095",
"0.64159983",
"0.6362631",
"0.6362483",
"0.63468903",
"0.6290468",
"0.62839806",
"0.61374724",
"0.61283094",
"0.60122097",
"0.5997306",
"0.5942564",
"0.5931187",
"0.59181505",
"0.5880621",
"0.5835219",
"0.58169043",
"0.58116317",
"0.58025575",
"0.57861656",
"0.5755064",
"0.57116884",
"0.5710171",
"0.5641288",
"0.56334066",
"0.55932295",
"0.5561712",
"0.5550189",
"0.55217093",
"0.55045867"
] | 0.7265884 | 0 |
The window with message informing that the profile has not been chosen.. | def error_no_profile():
tkMessageBox.showerror("Błąd, Nie wybrano profilu.",
"Należy dokonać wyboru profilu do filtrowania danych, "
"szczegóły poszczególnych profili można znaleść w Menadżeże Profili") | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def on_new_profile_action(self):\n\n from skymodman.interface.dialogs.new_profile_dialog \\\n import NewProfileDialog\n\n popup = NewProfileDialog(combobox_model=self.model)\n\n # display popup, wait for close and check signal\n if popup.exec_() == popup.Accepted:\n # add new profile if they clicked ok\n new_profile = self.Manager.new_profile(popup.final_name,\n popup.copy_from)\n\n # add profile name to model\n self.model.addProfile(new_profile.name)\n\n # set new profile as active and load data\n self.load_profile_by_name(new_profile.name)\n\n del NewProfileDialog",
"def NoPrompt(self) -> bool:",
"def user_warning(self, message, caption='Warning!'):\n dlg = wx.MessageDialog(self, message, caption,\n wx.OK | wx.CANCEL | wx.ICON_WARNING)\n if self.show_dlg(dlg) == wx.ID_OK:\n continue_bool = True\n else:\n continue_bool = False\n dlg.Destroy()\n return continue_bool",
"def user_warning(self, message, caption='Warning!'):\n dlg = wx.MessageDialog(self, message, caption,\n wx.OK | wx.CANCEL | wx.ICON_WARNING)\n if self.show_dlg(dlg) == wx.ID_OK:\n continue_bool = True\n else:\n continue_bool = False\n dlg.Destroy()\n return continue_bool",
"def confirm():\r\n if(PsdEntry.get() == \"Psd\" and UserEntry.get() == \"User\"):\r\n open()\r\n else:\r\n messagebox.showerror(\"Error\",\"Invalid Username\")",
"def warning(self, message):\n msg_dlg = wx.MessageDialog(None, message, '', wx.OK | wx.CANCEL| wx.ICON_ERROR)\n val = msg_dlg.ShowModal()\n msg_dlg.Show()\n msg_dlg.Destroy()\n return val",
"def display_message(self, message):\n if self.web_crawler_window is None and self.webpage_classifier_window is None:\n self.machine_learner_window.display_message(message)\n elif self.web_crawler_window is None and self.machine_learner_window is None:\n self.webpage_classifier_window.display_message(message)\n elif self.webpage_classifier_window is None and self.machine_learner_window is None:\n self.web_crawler_window.display_message(message)",
"def makeWarningPopup(self,warning):\n mBox = QMessageBox()\n mBox.setText(warning)\n mBox.exec_()",
"def winner_popup(winner):\n # create a new window\n pop_up = Tk()\n pop_up.maxsize(300, 100)\n pop_up.geometry(\"300x100\")\n\n # set the title and label for the winner\n pop_up.wm_title(\"The Winner is...\")\n label = Label(pop_up, text=\"{}!\".format(winner).title())\n label.pack(side=\"top\", fill=\"x\", pady=10)\n\n # Make an exit button for the window\n exit_button = Button(pop_up, text=\"Okay\", command=pop_up.destroy)\n exit_button.pack()\n\n pop_up.mainloop()",
"def no_file_error(self: object) -> None:\n messagebox.showerror(\"No file selected\", \"Please select a file\")",
"def displayNoDBWarning(self): \n tkMessageBox.showwarning(\"Cannot launch plugin\",\n 'No Database is currently open. '\n 'You should first open a project.') \n return",
"def noButton(self):\n \n self.answer=self.noMessage.lower()\n self.top.destroy()",
"def message_box(self):\n root = tk.Toplevel(self.top)\n root.attributes('-topmost', True)\n root.geometry(\"+650+100\")\n root.withdraw()\n messagebox.showinfo('Oh oh', 'Wrong message. Try again!')\n try:\n root.destroy()\n except:\n pass",
"def popErrorMessage(self, message):\n\n\t\tmessagebox.showinfo(\"Warning\", message, parent = self)",
"def remove_sign_up_prompt(self):\n is_modal_present = self.detect_obscuring_windows()\n self.driver.implicitly_wait(.1)\n if is_modal_present:\n self.close_sign_up_prompt()",
"def show_messages(self):\n console.alert(\n \"Info\",\n \"If StaSh does not launch anymore after you changed the config, run the 'launch_stash.py' script with \\n'--no-cfgfile'.\",\n \"Ok\",\n hide_cancel_button=True,\n )\n while True:\n self.wait_modal()\n if not self.subview_open:\n break\n console.alert(\n \"Info\",\n \"Some changes may only be visible after restarting StaSh and/or Pythonista.\",\n \"Ok\",\n hide_cancel_button=True,\n )",
"def OnAbout(self, event):\r\n d = wx.MessageDialog(self, \"This program was created by REAL PANDAS (Adam Sorrin '10, Lauren DiCristofaro '10, Norris Xu '11, Mark Broomfield '11, Sally Tao '10\", \"About\", wx.OK)\r\n d.ShowModal()\r\n d.Destroy()",
"def Reset_Profile_Name( self ):\r\n self.profile_name_list = [ root_profile_name ]\r\n self.combobox_profile.setlist( self.profile_name_list )\r\n self.Root_Profile()",
"def OnHelp(self, event):\r\n d = wx.MessageDialog(self, \"... ... ... ... ... ... ... ... ...\", \"No help for you!\", wx.OK)\r\n d.ShowModal()\r\n d.Destroy()",
"def skip_connect_your_computer_screen(self):\n if self.driver.wait_for_object(\"connect_your_computer_title\", timeout=10, raise_e=False):\n self.driver.click(\"connect_your_computer_not_now_btn\")",
"def under_construction():\n messagebox.showinfo(title=\"Under Construction\",\n message=\"The options menu is still under construction\\n\"\n \"I'm thinking of adding a \\\"change background\\n\"\n \"color\\\" option eventually, but not right now.\")",
"def warn_user(self, message):\n self.warning = QErrorMessage()\n self.warning.showMessage(message)\n self.warning.show()",
"def __window_prompt(self, text):\n return True",
"def __window_confirm(self, text):\n return True",
"def Root_Profile(self):\r\n self.combobox_profile.selectitem( 0 )",
"def _show_popup(self) -> None:\n\n top = tk.Toplevel()\n email_list_len = len(self.get_recipients())\n msg = tk.messagebox.askquestion('Confirm send emails', 'Are you sure you want to email {} client{}?'\n .format(email_list_len, \"s\" if email_list_len > 1 else \"\"),\n icon='warning')\n if msg == \"yes\":\n self._disable_buttons()\n email_process(self.get_recipients())\n top.destroy()\n else:\n top.destroy()",
"def _prompt_main_menu(self, update, context, message='Please choose an option:'):\n id = context.user_data['id']\n email = context.user_data['email']\n email = 'Not supplied' if email == '' else email\n self._reply_message(update,\n f'ID: {id}\\n'\n f'Email: {email}\\n'\n f'{message}',\n keyboard=self.MAIN_STATE_OPTIONS,\n inline_keyboard=True)",
"def set_unknown_user(self):\n self.objects[self.ids.TOPBAR].setText(\"User: <Unknown card>\")",
"def on_preferences(self, evt):\n # Passing `self` sets the main window as the parent window\n self.prefs.Show(self)\n evt.Skip()",
"def lose_popup(self):\n content = BoxLayout(orientation='vertical')\n message_label = Label(text=self.loss_message)\n button_layer = BoxLayout(orientation='horizontal')\n dismiss_button = Button(text='QUIT', size_hint=(1, 1))\n next_button = Button(id='try_again', text='TRY AGAIN', size_hint=(1,\n 1))\n button_layer.add_widget(dismiss_button)\n button_layer.add_widget(next_button)\n content.add_widget(message_label)\n content.add_widget(button_layer)\n popup = Popup(title=self.loser, content=content,\n size_hint=(0.3, 0.25))\n dismiss_button.bind(on_release=(lambda a: self.exit_game()),\n on_press=popup.dismiss)\n next_button.bind(on_release=(lambda a: self.restart_game()),\n on_press=popup.dismiss)\n popup.open()"
] | [
"0.60111976",
"0.5979644",
"0.59226364",
"0.59226364",
"0.5883023",
"0.585029",
"0.5767785",
"0.5765628",
"0.5716058",
"0.5645765",
"0.5643315",
"0.56378037",
"0.56148696",
"0.5578284",
"0.55710596",
"0.5567733",
"0.5566435",
"0.5530853",
"0.55275816",
"0.55181766",
"0.55168796",
"0.55085343",
"0.5499342",
"0.5498447",
"0.5481732",
"0.5472742",
"0.54643625",
"0.54475784",
"0.5438146",
"0.5434845"
] | 0.73912215 | 0 |
The window with message informing that the files have not been chosen. | def error_no_files():
tkMessageBox.showerror(" Błąd, Nie wybrano nazw plików. ",
"Przed konwersją danych należy wybrać plik wejściowy zawierające dane Excel "
"oraz podać nazwy dla 3 plików wyjściowych w których program zapisze dane.") | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def no_file_error(self: object) -> None:\n messagebox.showerror(\"No file selected\", \"Please select a file\")",
"def warnFileNotPresent(self, filename, tag=\"first\"):\n# QtGui.QMessageBox.warning(self, \"Warning\", \"Could not locate %s file in sequence: %s\" % (tag, filename))\n\n message = \"Could not locate %s file in sequence: %s\" % (tag, filename)\n\n msgBox = QtWidgets.QMessageBox(self)\n msgBox.setText(message)\n msgBox.setWindowFlags(msgBox.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)\n msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok)\n msgBox.setIcon(QtWidgets.QMessageBox.Warning)\n msgBox.exec_()",
"def CheckForUnknownFiles(self):\n unknown_files = self.GetUnknownFiles()\n if unknown_files:\n print \"The following files are not added to version control:\"\n for line in unknown_files:\n print line\n prompt = \"Are you sure to continue?(y/N) \"\n answer = raw_input(prompt).strip()\n if answer != \"y\":\n ErrorExit(\"User aborted\")",
"def CheckForUnknownFiles(self):\r\n unknown_files = self.GetUnknownFiles()\r\n if unknown_files:\r\n print \"The following files are not added to version control:\"\r\n for line in unknown_files:\r\n print line\r\n prompt = \"Are you sure to continue?(y/N) \"\r\n answer = raw_input(prompt).strip()\r\n if answer != \"y\":\r\n ErrorExit(\"User aborted\")",
"def show_file_menu_help(self):\n QMessageBox.question(self, 'File menu help', get_file_menu_help(), QMessageBox.Ok | QMessageBox.NoButton)",
"def submit(self, event=None):\n\n if self.select_dirs == False:\n for item in self.dialog_selection:\n if isdir(item):\n messagebox.showwarning(\n \"Error - Invalid Selection\",\n \"Unable to select directory. Please select a file(s).\"\n )\n return\n\n if self.select_files == False:\n for item in self.dialog_selection:\n if isfile(item):\n messagebox.showwarning(\n \"Error - Invalid Selection\",\n \"Unable to select file. Please select a folder(s)\"\n )\n return\n \n self.dialog.destroy()",
"def info_error():\n message = 'File could not be saved.'\n messagebox.showinfo(title=\"File not saved\", message=message)\n return",
"def Warning_Message( self ):\r\n message = \"This program prefers the FASTA file format\\nPlease check the file for >gi|id|title followed by the sequence,\\n or for enough sequences\"\r\n tkMessageBox.showwarning(\r\n \"File Opening Error\",\r\n message\r\n )",
"def _unable_open_option(self):\n self.tap_on_open_option()\n\n unable_msg = self.UTILS.element.getElement(DOM.DownloadManager.download_confirm_h1, \"Unable to open msg\")\n self.UTILS.test.test(unable_msg.text == _(\"Unable to open\"), \"Unable to open msg\")",
"def test_invalid_prompt_files(self):\n invalid_files = [\n \"p01.txt\",\n \"abc.txt\",\n \"p000001s000001.mp3\",\n \"p000001s000001n001.txt\",\n \"u000001.txt\"\n ]\n filtered_files = list(filter(format.is_prompt_file, invalid_files))\n\n assert len(filtered_files) == 0",
"def _item_not_found(item):\n if _is_element_present(PROMPT_BOX[\"Heading\"]):\n if \"not on file\" in _get_text(PROMPT_BOX[\"Heading\"]):\n return click_message_box_key(\"OK\", verify=False)\n return False",
"def _overwriteFileMsgBox(self, duplicates: List[Path]) -> int:\n msgBox = QMessageBox()\n msgBox.setIcon(QMessageBox.Warning)\n if len(duplicates) > 1:\n msgText = f\"Do you want to overwrite {len(duplicates)} files?\"\n else:\n msgText = f\"Do you want to overwrite '{duplicates[0].name}'?\"\n msgBox.setText(msgText)\n msgBox.setWindowTitle(\"Confirm overwrite\")\n msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n\n return msgBox.exec()",
"def notify_none(self):\n msgs = [\"humph. no collections were found in the following paths:\"]\n paths = []\n for path in self._collection_scanned_paths:\n if path.startswith(self._args.internals.share_directory):\n continue\n if self._args.execution_environment:\n if path.startswith(self._adjacent_collection_dir):\n paths.append(f\"- {path} (bind_mount)\")\n else:\n paths.append(f\"- {path} (contained)\")\n else:\n paths.append(f\"- {path}\")\n closing = [\"[HINT] Try installing some or try a different execution enviroment\"]\n warning = warning_notification(messages=msgs + paths + closing)\n self._interaction.ui.show(warning)",
"def not_use_triggered(self):\n\n self.select_items()\n if self.items_selected:\n for index, item in enumerate(self.items_selected):\n index_selected = self.indices_selected[index]\n frame_selected = index_selected + 1\n item.setText(\"Frame %i excluded\" % frame_selected)\n item.setBackground(self.background_excluded)\n item.setForeground(QtGui.QColor(255, 255, 255))\n self.index_included[index_selected] = False\n self.frame_selector.setPhoto(self.frame_index)",
"def uploaded_files_are_not_shown_on_uploadpage(self,filenames,user):\n \n response = self.get_uploadpage_response(user,self.testproject)\n \n for filename in filenames:\n self.assertTrue(filename not in response.content,\"Restricted file\"\n \" '%s' was visible on download page when viewed\"\n \" by user %s\"\n % (filename,user.username))",
"def buttonClick(self):\n \n self.fpath=filedialog.askopenfilename()\n self.label_fpath.config(text=self.fpath)\n self.err_label.config(text='')\n pass",
"def _create_empty_library_notice(self):\n message = _(\n \"There are no indexed Video Clips in the Entertainer media \"\n \"library. Please add some folders containing video clips \"\n \"to the Library using the configuration tool.\")\n Tab.show_empty_tab_notice(self, _(\"No video clips available!\"), message)",
"def FileDialog( message, wildcard, style, defaultDir=os.getcwd(), defaultFile='' ):\n dlg = wx.FileDialog( wx.GetApp().GetTopWindow(), message, defaultDir, defaultFile, wildcard, style )\n if dlg.ShowModal() == wx.ID_OK:\n if style & wx.MULTIPLE:\n result = dlg.GetPaths()\n else:\n result = dlg.GetPath()\n else:\n result = False\n dlg.Destroy()\n \n return result",
"def ask_file(message=\"Select file for open.\", title=None):\n return dialog(\"ask_file\", message=message, title=title)",
"def test_unsaved_file(self) -> None:\n setting: ShowCaptionsTabSetting = ShowCaptionsTabSetting(\n self.settings,\n sublime.active_window()\n )\n scratch_view: sublime.View = sublime.active_window().new_file()\n tabs: List[Tab] = [Tab(scratch_view)]\n\n self.assertTrue(setting.is_enabled())\n self.assertListEqual(tabs, setting.apply(tabs))\n self.assertListEqual(\n [\"Current File\", \"Unsaved File\"],\n tabs[0].get_captions()\n )",
"def NoPrompt(self) -> bool:",
"def unknown(self):\n self.add_file_string('Unknown file')\n self.should_copy = False",
"def test_noFilesFromAccept(self):\n return self._acceptFailureTest(ENFILE)",
"def fileDialog(*args, application: bool=True, defaultFileName: AnyStr=\"\", directoryMask:\n AnyStr=\"\", mode: int=0, title: AnyStr=\"\", **kwargs)->AnyStr:\n pass",
"def select_files(self):\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n files, _ = QFileDialog.getOpenFileNames(self.parent,\n \"File Export\",\n os.path.expanduser('~/'),\n \"Ensemble Files (*.ens, *.bin);;Binary Files (*.bin);;All Files (*)\",\n options=options)\n if files:\n # Store the list of results\n self.selected_files = files\n\n # Analyze the files\n self.analyze_files()",
"def displayNoDBWarning(self): \n tkMessageBox.showwarning(\"Cannot launch plugin\",\n 'No Database is currently open. '\n 'You should first open a project.') \n return",
"def display_empty_players_file(self) -> None:\n utils.clear_terminal()\n print(\"\\nNo players has been created yet\")",
"def show_messages(self):\n console.alert(\n \"Info\",\n \"If StaSh does not launch anymore after you changed the config, run the 'launch_stash.py' script with \\n'--no-cfgfile'.\",\n \"Ok\",\n hide_cancel_button=True,\n )\n while True:\n self.wait_modal()\n if not self.subview_open:\n break\n console.alert(\n \"Info\",\n \"Some changes may only be visible after restarting StaSh and/or Pythonista.\",\n \"Ok\",\n hide_cancel_button=True,\n )",
"def clear_combobox_files(self):\n self.ui.comboBox_file.blockSignals(True)\n self.ui.comboBox_file.setCurrentIndex(0)\n self.ui.comboBox_file.blockSignals(False)\n self.attribute_file_ids = []\n self.attributes_msg = \"\"\n self.ui.pushButton_attributes.setToolTip(\"\")",
"def __showFileMenu(self):\n self.menuRecentAct.setEnabled(len(self.recent) > 0)"
] | [
"0.76047754",
"0.67630136",
"0.6434396",
"0.6433696",
"0.63150847",
"0.6094756",
"0.6042425",
"0.59891903",
"0.59801596",
"0.5976444",
"0.59606284",
"0.5944457",
"0.59243125",
"0.5890828",
"0.5882095",
"0.5822424",
"0.5805673",
"0.5746979",
"0.5735084",
"0.5728376",
"0.5727842",
"0.56713814",
"0.565398",
"0.5650535",
"0.5640053",
"0.5633323",
"0.56320435",
"0.56314987",
"0.5621279",
"0.5619598"
] | 0.71279687 | 1 |
The window with message informing that excel data filtration was finished. | def work_finished():
tkMessageBox.showinfo("Yes...", "Dokonano konwersji danych. \n Życzę miłego dnia.") | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def on_Output_CWA_excel_Now_button_clicked(self):\n # self.lineEdit.setText(result['Cname'])\n # self.lineEdit_2.setText(result['Sclass'])\n # self.lineEdit_3.setText(result['ClassTime'])\n # self.lineEdit_4.setText(result['Tno'])\n # self.lineEdit_6.setText(result['Date'])\n Result = CWA_Message_Query(self.lineEdit_2.text(),self.lineEdit_3.text(), self.lineEdit_6.text(), self.lineEdit.text())\n Create_Cwa_excel_table(self.lineEdit_2.text(),self.lineEdit.text(),Result)",
"def _confirm(self) -> None:\n\n self.__series.title = self._getTitleFromView()\n\n if len(self.__series.data) == 0:\n self._showMessage(\"Invalid data. No data selected.\")\n return\n\n self._result = DialogResult.Ok\n self._close()",
"def Show_Results_Window(self, Accuracy, Max_Values, All_Prediction_List):\r\n # Explain Of The Function #\r\n\r\n try:\r\n # Extreme Case - If The Model Without Data Augmentation, And The Versions Is The Same #\r\n if self.Choice_Number == '1' and \\\r\n self.Source_Prose_Pick == self.Target_Prose_Pick:\r\n Accuracy = 100\r\n\r\n # Create New Form #\r\n self.Results_Window_Main = QtWidgets.QMainWindow()\r\n\r\n # From #\r\n from Classes.Results_Window import Ui_Results_Window\r\n self.Results_Window_Object = Ui_Results_Window(self.Script_Path, self.User_Role, self.Choice_Number,\r\n self.Source_Prose_Pick, self.Target_Prose_Pick,\r\n Accuracy, Max_Values, All_Prediction_List)\r\n self.Results_Window_Object.Init_UI(self.Application_Main, self.Results_Window_Main)\r\n\r\n # Close Current Window #\r\n self.Progress_Window_Main.close()\r\n\r\n # Show Next Window #\r\n self.Results_Window_Main.show()\r\n\r\n pass\r\n except Exception as Object_Exception:\r\n # Style Sheet #\r\n Icon = QtGui.QIcon()\r\n Icon.addPixmap(QtGui.QPixmap(\"../Pictures/Project - Logo.ico\"),\r\n QtGui.QIcon.Normal,\r\n QtGui.QIcon.Off)\r\n QMessageBox.setWindowIcon(self, Icon)\r\n QMessageBox.setStyleSheet(self,\r\n 'QMessageBox{background-color: #00aaff; font-size: 16px;'\r\n 'font-style: italic; font-family: Segoe UI Black;}\\n' +\r\n 'QPushButton{color: white; font-size: 16px; background-color: #1d1d1d; ' +\r\n 'border-radius: 10px; padding: 10px; text-align: center;}\\n ' +\r\n 'QPushButton:hover{color: #ffaa00;}')\r\n QMessageBox.critical(self, \"Error - Exception\", \"<p><font color='#ffaa00'>The Exception Is - <br>\" +\r\n str(Object_Exception) + \" !</font></p>\")\r\n pass",
"def check_given_data():\n if os.path.exists(path_name.get()) and folder_name.get() != \"\":\n # if True:\n progress = ThemedTk(theme=\"aqua\")\n progress.title(\"Progress\")\n\n top.withdraw()\n\n info_label = Label(progress, text=\"Attentive set filtering is on progress\", font=(\"Times New Roman\", 12, \"bold\"))\n info_label.pack(pady=10)\n progress_bar = Progressbar(progress, orient=HORIZONTAL, length=220, mode='determinate')\n progress_bar.pack(pady=20)\n filter_dataset(path_name.get(), folder_name.get(), progress_bar, info_label, progress, root)\n\n else:\n messagebox.showerror(\"Message\", \"Please enter valid directory path\\n \\\n and folder name\")",
"def on_show_data_export(self):\n from DataExportDialog import QDataExportDialog\n\n dlg = QDataExportDialog(self)\n dlg.exec_()",
"def threadComplete(self):\r\n self.flabel.config(text=\"Import Complete\")\r\n tk.Button(self.focus,text=\"Ok\",command=self.closePopup).pack()",
"def open_results():\n \n\n # Checking if the user input is in correct form\n if len(e1.get()) == 0:\n newWindow = tk.Toplevel(master) \n error_message = f'We could not find houses for your search because you did not provide enough information'\n title = 'ERROR'\n newWindow.title(title) \n tk.Label(newWindow, text=error_message).grid(row=20,column=50,pady=10)\n\n else:\n post_code = e1.get()\n if len(e2.get()) == 0:\n price_min = 0\n else:\n price_min = int(e2.get())\n\n if len(e3.get()) == 0:\n price_max = 100000\n else:\n price_max = int(e3.get())\n\n if price_min>price_max:\n a = price_min\n b = price_max\n price_min = b\n price_max = a\n\n if len(e4.get()) == 0:\n bedroom = 0\n elif int(e4.get()) == 1:\n bedroom = 0\n else:\n bedroom = int(e4.get())\n\n if len(e5.get()) == 0:\n bathroom = 0\n elif int(e5.get()) == 1:\n bathroom = 0\n else:\n bathroom = int(e5.get())\n\n newWindow = tk.Toplevel(master) \n title = f'House to rend in {e1.get()}'\n newWindow.title(title) \n newWindow.geometry(\"1300x1000\") \n frame = tk.Frame(newWindow)\n frame.pack(fill='both', expand=True)\n\n # Searching for the user's desired properties\n b = s_a.Scrapper_Alpha(post_code,price_min,price_max,bedroom,bathroom)\n df = b.filter_df()\n # Outputing the result inside a new window\n Table(frame, dataframe=df).show()",
"def run(self):\n self.centre.findChild(QPushButton, \"confirmBtn\").hide()\n self.centre.findChild(QPushButton, \"cancelBtn\").hide()\n self.centre.findChild(QLabel, \"loadingLabel\").show()\n self.centre.findChild(QLabel, \"title\").setText(\"Optimisation & Visualisation Processing\")\n self.finished.emit()",
"def run(self):\n\n wx.BeginBusyCursor()\n # Create a progress bar\n progress = ProcessProgressDialog(self.parent,\n self.parent._prefsIO,\n \"Filtering progress...\")\n progress.set_header(\"Filter system\")\n progress.update(0, \"\")\n total = self.file_manager.GetSize()\n\n for i in range(self.file_manager.GetSize()):\n # obj is a TrsList instance\n obj = self.file_manager.GetObject(i)\n trs = obj.GetTranscription()\n\n # find the Y-tier\n y_tier = None\n if self.y_tier_name is not None:\n y_tier = trs.find(self.y_tier_name)\n\n for tier in trs:\n # tier is selected to be filtered\n if obj.IsSelected(tier.get_name()):\n progress.set_header(self.file_manager.GetFilename(i))\n progress.set_text(tier.get_name())\n\n # so, we do the job!\n new_tier = self.run_on_tier(tier, y_tier)\n if new_tier is not None:\n # add the new tier both in Transcription and in the list\n obj.AddTier(new_tier)\n\n progress.set_fraction(float((i+1))/float(total))\n\n # Indicate completed!\n progress.update(1, \"Completed.\\n\")\n # progress.set_header(\"\")\n progress.close()\n wx.EndBusyCursor()",
"def check_job(self, a_thread, _):\n if not a_thread.isAlive():\n self.close_button.disabled = False\n self.popup_label.text = \"Process finished. Processed records:\" + str(self.count_funct())\n return False",
"def visualise(self):\n self.w = VisualizeSetupBox(self.master, self._df)\n self.master.wait_window(self.w.top)",
"def complete_slot(self, data):\n # Show result\n self.result = data\n self.table_output_data.setModel(pandasModel(data.loc[:, ['date'] + [i for i in self.column_name]])) # 顯示表格在table_output_data\n self.show_plot() # 參照show_plot()\n\n self.label_current_message.setText('模型計算完畢!')\n self.stopped = False\n self.btn_run_model.setEnabled(True)",
"def blurrer_finished(self):\n msg_box = QMessageBox()\n if self.blurrer and self.blurrer.result[\"success\"]:\n minutes = int(self.blurrer.result[\"elapsed_time\"] // 60)\n seconds = round(self.blurrer.result[\"elapsed_time\"] % 60)\n msg_box.setText(f\"Video blurred successfully in {minutes} minutes and {seconds} seconds.\")\n else:\n msg_box.setText(\"Blurring resulted in errors.\")\n msg_box.exec_()\n if not self.blurrer:\n self.setup_blurrer()\n self.ui.button_start.setEnabled(True)\n self.ui.button_abort.setEnabled(False)\n self.ui.progress.setValue(0)",
"def run(self):\t\r\n\t\r\n\t\t#run the dialog and store the response\t\t\r\n\t\tself.result = self.dlg.run()\r\n\r\n#\t\tif self.numCols > 2:\r\n#\t\t\tz1=self.cmbZ1.get_active()\t\t\r\n\r\n\t\t#we are done with the dialog, destroy it\r\n\t\tself.dlg.destroy()\r\n\r\n\t\t#return the result and the data\r\n\t\tif self.result == gtk.RESPONSE_ACCEPT:\r\n\t\t\treturn 1\r\n\t\telse:\r\n\t\t\treturn 0",
"def exec_(self) -> int:\n self._w.finished.connect(lambda state: self.done(state))\n return QDialog.exec_(self)",
"def on_show_eqp_datasheet_export(self):\n from EqpDatasheetExportDialog import QEqpDatasheetExportDialog\n\n dlg = QEqpDatasheetExportDialog(self)\n dlg.exec_()",
"def __on_generating_photomosaic_finished(self):\n\n self.progress_window.hide()",
"def execute_event(self):\n # step1: load the app_list csv file\n try:\n with open(self._applist_file_input.get(), 'r', encoding='utf-8') as \\\n raw_data_file:\n\n reader = csv.reader(raw_data_file)\n rows = []\n for row in reader:\n row[0] = row[0].encode('utf-8').decode('utf-8-sig')\n rows.append(row)\n\n except Exception as e:\n tk.messagebox.showerror('error', e)\n\n # step2: do the count and sum operation with the search terms and the\n # app_list\n output_rows = self.search_term_counter(self._search_terms_input.get(),\n rows)\n\n # step3: if the client wants to translate the pkg to app name\n try:\n pkg_app_dict = self.pkg_appname_file_process(\n self._pkg_app_input.get())\n # now write the result to the output file\n output_rows = self.pkg_app_translator(pkg_app_dict, output_rows)\n\n try:\n with open(self._export_path_input.get(), 'w',\n encoding='utf-8-sig', newline='') as output_data_file:\n writer = csv.writer(output_data_file, dialect='excel')\n writer.writerows(output_rows)\n tk.messagebox.showinfo('message',\n 'job done! have a nice day!')\n\n except Exception as e:\n tk.messagebox.showerror('error', e)\n\n except:\n try:\n with open(self._export_path_input.get(), 'w',\n encoding='utf-8-sig', newline='') as output_data_file:\n writer = csv.writer(output_data_file, dialect='excel')\n writer.writerows(output_rows)\n tk.messagebox.showinfo('message',\n 'job done! have a nice day!')\n except Exception as e:\n tk.messagebox.showerror('error', e)",
"def export_file_complete_sig_handler(self):\n # Increment the index\n self.export_file_index += 1\n\n # Move the state\n self.scanFilesProgressBar.setValue(self.scanFilesProgressBar.value() + 1)\n\n # Check if we have exported all the files\n if self.export_file_index >= len(self.analzye_results):\n # Show a dialog box that everything is exported and complete\n QMessageBox.question(self.parent, \"Export Complete\", \"All files have been exported.\", QMessageBox.Ok)\n else:\n # Export the next file\n self.export_file(self.analzye_results[self.export_file_index])",
"def done(self):\n\n # Check if the status of frames has changed.\n indices_included = []\n indices_excluded = []\n for index in range(self.frames.number_original):\n if self.index_included[index] and not self.frames.index_included[index]:\n indices_included.append(index)\n self.frames.index_included[index] = True\n elif not self.index_included[index] and self.frames.index_included[index]:\n indices_excluded.append(index)\n self.frames.index_included[index] = False\n\n # Write the changes in frame selection to the protocol.\n if self.configuration.global_parameters_protocol_level > 1:\n if indices_included:\n Miscellaneous.protocol(\n \" The user has included the following frames into the stacking \"\n \"workflow: \" + str(\n [item + 1 for item in indices_included]), self.stacked_image_log_file,\n precede_with_timestamp=False)\n if indices_excluded:\n Miscellaneous.protocol(\n \" The user has excluded the following frames from the stacking \"\n \"workflow: \" + str(\n [item + 1 for item in indices_excluded]), self.stacked_image_log_file,\n precede_with_timestamp=False)\n frames_remaining = sum(self.frames.index_included)\n if frames_remaining != self.frames.number:\n Miscellaneous.protocol(\" \" + str(\n frames_remaining) + \" frames will be used in the stacking workflow.\",\n self.stacked_image_log_file, precede_with_timestamp=False)\n\n # Send a completion message. The \"execute_rank_frames\" method is triggered on the workflow\n # thread. The signal payload is True if the status was changed for at least one frame.\n # In this case, the index translation table is updated before the frame ranking starts.\n if self.parent_gui is not None:\n self.signal_finished.emit()\n\n # Close the Window.\n self.player_thread.quit()\n self.close()",
"def show(self, window):\r\n\r\n return",
"def run(self):\n\t\t# show the dialog\n\t\tself.dlg.show()\n\t\t# Run the dialog event loop\n\t\tresult = self.dlg.exec_()\n\t\t# See if OK was pressed\n\t\tif result:\n\t\t\t#check if there's a shape\n\t\t\tself.checkIfShape()\n\t\t\tself.checkIfCSV()\n\n\t\t\t#If Shape is blank (all tile) or has points but not if we couldn't find any shape with that name \n\t\t\tif not self.shapeBox is None:\n\t\t\t\t#calculate for the shape\n\t\t\t\tself.calculate_indexes()",
"def run(self):\n # show the dialog\n self.dlg.show()\n # Run the dialog event loop\n result = self.dlg.exec_()\n # See if OK was pressed\n if result:\n # Do something useful here - delete the line containing pass and\n # substitute with your code.\n pass",
"def run(self):\n # show the dialog\n self.dlg.show()\n # Run the dialog event loop\n result = self.dlg.exec_()\n # See if OK was pressed\n if result:\n # Do something useful here - delete the line containing pass and\n # substitute with your code.\n pass",
"def run(self):\n # show the dialog\n self.dlg.show()\n # Run the dialog event loop\n result = self.dlg.exec_()\n # See if OK was pressed\n if result:\n # Do something useful here - delete the line containing pass and\n # substitute with your code.\n pass",
"def run(self):\n # show the dialog\n self.dlg.show()\n # Run the dialog event loop\n result = self.dlg.exec_()\n\n # See if OK was pressed\n if result:\n # Do something useful here - delete the line containing pass and\n # substitute with your code.\n pass",
"def workerFinished(self, ret):\n self.worker.deleteLater()\n self.thread.quit()\n self.thread.wait()\n self.thread.deleteLater()\n # remove widget from message bar\n self.iface.messageBar().popWidget(self.messageBar)\n if ret is not None:\n # report the result\n #layer, total_area = ret\n self.iface.messageBar().pushMessage('Finished!')\n else:\n # notify the user that something went wrong\n self.iface.messageBar().pushMessage('Job cancelled.', level=QgsMessageBar.WARNING, duration=3)",
"def aoi_button_clicked(self):\n # can't run search during export\n if self.is_exporting():\n self.iface.messageBar().pushMessage(\"Error\", \"Cannot run search while export is running.\",\n level=QgsMessageBar.CRITICAL)\n # can't run multiple search\n elif self.is_searching():\n self.iface.messageBar().pushMessage(\"Error\", \"Cannot run a new search while a search is running.\",\n level=QgsMessageBar.CRITICAL)\n else:\n self.bbox_tool.reset()\n self.iface.mapCanvas().setMapTool(self.bbox_tool)",
"def run(self):\n while True:\n event, values = self.window.read()\n if event == sg.WIN_CLOSED:\n break\n\n ev.fire(self.window, event, values)",
"def prompt_load_data(self):\n\n self.status.config(\n text=\"Selections modified! Click Load Data to update statistics when ready...\"\n )"
] | [
"0.55716294",
"0.5556446",
"0.54925954",
"0.54401356",
"0.5409193",
"0.5361284",
"0.5341569",
"0.5292472",
"0.527907",
"0.5241114",
"0.5237859",
"0.5234971",
"0.51284236",
"0.51071846",
"0.5106603",
"0.50970507",
"0.5093958",
"0.50916535",
"0.5089211",
"0.50814736",
"0.5038251",
"0.50323164",
"0.5031184",
"0.5031184",
"0.5031184",
"0.5026763",
"0.5003695",
"0.49993244",
"0.49985838",
"0.49913275"
] | 0.5682716 | 0 |
set parameter of related views. Will be available in related views kwargs as well as in request.query_params of request object passed to the related view | def set_related_params(self,request,responsedata):
pass | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def set_params(self, **kwargs):\n ...",
"def set(self, request, _object):\n\n value = request._get_parameter_value(self)\n value.object = _object",
"def setup_view(self, view, request, *args, **kwargs):\n view.request = request\n view.args = args\n view.kwargs = kwargs\n return view",
"def set_params(self, **params):\n return super().set_params(**params)",
"def set_params(self, **kwargs) -> NoReturn:\n pass",
"def set_params(self, **params):\n\n return super().set_params(**params)",
"def set_params(self):\r\n pass",
"def get_form_kwargs(self):\n kwargs = super(QuestionUpdateView, self).get_form_kwargs()\n kwargs['request'] = self.request\n return kwargs",
"def set_params(self, params):",
"def set_params(self):\n raise NotImplementedError",
"def set_related_view(request, view_name):\n request.environ['cone.app.related_view'] = view_name",
"def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['post_id'] = context['view'].kwargs['pk']\n return context",
"def setup_view(view, request, *args, **kwargs):\n\n view.request = request\n view.args = args\n view.kwargs = kwargs\n return view",
"def set_params(self, **kwargs):\n for key, value in kwargs.items():\n if key in self.params.keys():\n self.params[key] = value\n else:\n raise KeyError",
"def get_form_kwargs(self):\n kwargs = super(QuestionCreateView, self).get_form_kwargs()\n if hasattr(self, 'object'):\n kwargs.update({'instance': self.object})\n kwargs['request'] = self.request\n return kwargs",
"def SetViewParameters(ref, args, request):\n del ref # unused\n\n if not args.view:\n request.table.view = None\n\n return request",
"def edit_parameter(request, parameter, **_kwargs):\n pass",
"def set_params(self,**kwargs):\n for key in kwargs:\n setattr(self, key, kwargs[key])",
"def setRequest(request):\n setLocal('request', request)",
"def get_context_data(self, **kwargs):\n\n\t#Getting the context data\n context = super(UpdateView, self).get_context_data(**kwargs)\n\tprint(\"in get_context_data end\")\n context[\"test_id\"] = kwargs['test_id'] \n return context",
"def inject(self, request: BaseRequest, args_view: list, kwargs_view: dict):",
"def meta_params(request):\n return request.param",
"def get_form_kwargs(self):\n\n press_release_obj = PressRelease.objects.get(\n id=self.kwargs['press_release_pk'])\n\n kwargs = super(PressReleaseUpdateView, self).get_form_kwargs()\n kwargs.update(\n {'field': self.kwargs['field'],\n 'press_release_obj': press_release_obj}\n )\n\n return kwargs",
"def setup_view(view, request=None, *args, **kwargs):\n view.request = request\n view.args = args\n view.kwargs = kwargs\n return view",
"def updatekwargs(self,request):\n updated_dict={}\n if isinstance(request.query_params,QueryDict):\n updated_dict = {k:','.join(v) for k,v in request.query_params.iterlists()}\n else:\n updated_dict = request.query_params\n updated_dict.update(self.kwargs)\n\n self.kwargs = updated_dict",
"def get_form_kwargs(self):\n\n rating_decision_obj = RatingDecision.objects.get(\n id=self.kwargs['rating_decision_pk'])\n\n kwargs = super(RatingDecisionUpdateView, self).get_form_kwargs()\n kwargs.update(\n {'field': self.kwargs['field'],\n 'rating_decision_obj': rating_decision_obj}\n )\n\n return kwargs",
"def dispatch(self, request, *args, **kwargs): # noqa\n self.question = get_object_or_404(Question, lot__slug=kwargs['lot_id'],\n pk=kwargs['question_pk'])\n return super().dispatch(request, *args, **kwargs)",
"def _set_request(self, request):\n self._request = request",
"def get_context_data(self, **kwargs):\n\n return {'params': kwargs}",
"def __call__(_next, self, model, request):\n set_related_view(request, self.related_view)\n return _next(self, model, request)"
] | [
"0.6631366",
"0.6505121",
"0.6098712",
"0.60158235",
"0.6001763",
"0.59468704",
"0.5930036",
"0.5877166",
"0.586522",
"0.5807379",
"0.5790245",
"0.5777525",
"0.57682747",
"0.5722823",
"0.5694298",
"0.5686609",
"0.5677271",
"0.56698656",
"0.56684977",
"0.5616305",
"0.5608574",
"0.5596949",
"0.55879146",
"0.55746233",
"0.55726475",
"0.5567364",
"0.5561026",
"0.5542928",
"0.55291873",
"0.551851"
] | 0.75178146 | 0 |
it gets the final response after related views have been executed and final response has been appended. | def get_final_response(self,request,response):
return response | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def main_response(self, data):",
"def main_response(self, data):",
"def handleResponseEnd(self):\r\n try:\r\n if not self._finished:\r\n reactor.callInThread(\r\n self.resource.cacheContent,\r\n self.father,\r\n self._response,\r\n self.buffer\r\n )\r\n proxy.ProxyClient.handleResponseEnd(self)\r\n except RuntimeError:\r\n # because we don't care if the user hits\r\n # refresh before the request is done\r\n pass",
"def finalize_response(self, request, response, *args, **kwargs):\n\t\t# Make the error obvious if a proper response is not returned\n\t\tassert isinstance(response, BaseResponse), (\n\t\t\t'Expected a `Response` object '\n\t\t\t'to be returned from the view, but received a `%s`'\n\t\t\t% type(response)\n\t\t)\n\t\treturn response",
"async def _response_handler(self):",
"def process_response(self, request, response):\n return response",
"def process_response(self, request, response):\n return response",
"def set_pipelined_response(self,view_name,request,responsedata):\n pass",
"def on_response(self, response):\n pass",
"def render_response(self, context, result):\n\t\tcontext.response = result\n\t\treturn True",
"def finalize_response(self, response):\n if self.request.is_ajax() and response.status_code == 302:\n if self.ajax_catch_redirects:\n return http.HttpResponse(\n json.dumps(\n {\n 'redirect': response['location'],\n 'result': self.result_text,\n }\n ),\n content_type='application/json',\n )\n return response",
"def end_rendering(self, output):\n if self.wrapper_to_generate:\n output = self.div(output, id=self.id, class_='nagare-generated nagare-async-view')\n\n return output",
"def _on_response(self):\n request = self._requests.pop(0)\n try:\n request[-1].cancel()\n left = request[-1].end - Engine.instance().time\n except Exception:\n left = request[5]\n pass\n\n response = self.current_response\n\n close_after = response.headers.get('Connection', '') == 'close'\n close_after &= self.keep_alive\n\n # Is this a 100 Continue?\n if response.status == 100:\n self.current_response = None\n del response\n\n # Process the request.\n if close_after:\n if self._stream:\n self._stream.close()\n return\n\n self._process_request()\n return\n\n # Did we catch a redirect?\n if response.status in (301,302) and request[9] <= self.max_redirects:\n # Generate a new request, using the new URL.\n new_url = urlparse.urljoin(response.full_url,\n response.headers['Location'])\n\n new_headers = request[3].copy()\n del new_headers['Host']\n\n new_req = self._add_request(request[0], new_url, new_headers,\n request[4], left, False)\n new_req[6] = request[6]\n new_req[7] = request[7]\n new_req[9] = request[9] + 1\n\n new_req.append(\n Engine.instance().defer(left, self._request_timeout, new_req))\n\n self._requests.insert(0, new_req)\n self.current_response = None\n del response\n\n # Process the request.\n if close_after:\n if self._stream:\n self._stream.close()\n return\n\n self._process_request()\n return\n\n # Try converting to unicode?\n if self.unicode:\n content_type = response.headers.get('Content-Type','')\n if 'charset=' in content_type:\n content_type, _, encoding = content_type.partition('charset=')\n try:\n response.body = response.body.decode(encoding)\n except (LookupError, UnicodeDecodeError):\n pass\n\n # Determine the handler function to use.\n if callable(request[6]):\n func = request[6]\n else:\n func = self.on_response\n\n # Call the handler function.\n try:\n func(0, response)\n except Exception:\n log.exception('Error in HTTP response handler.')\n\n # Process the next request.\n self.current_response = None\n\n if close_after:\n if self._stream:\n self._stream.close()\n return\n\n self._process_request()",
"def view(self):\n\t\tself.done(1)",
"def _after_serve_actions(self):\n pass",
"def onfinish( request ):",
"def onfinish( request ):",
"def _finalize_response(self, response):\n\n res = HttpResponse(content=response.content,\n content_type=self._get_content_type())\n # status_code is set separately to allow zero\n res.status_code = response.code\n return res",
"def handleContentComplete():",
"def response_handling(self) -> global___Snippet.SimpleResponseHandling:",
"def response_handling(self) -> global___Snippet.SimpleResponseHandling:",
"def process_server_response(self, server_response):",
"def render(self, response):\n logger.debug(\"TornadoRequest::render\")\n response = self._handler.finish_response(self, response)\n logger.debug(\"response: Finished\")",
"def process_response(self, response):\n return response",
"def complete(request, backend):\n return complete_process(request, backend)",
"def handle_response(self, response):\n\n self._tmp_request_args = {}\n self.cache_response(response)",
"def after_request(self, response):\n # only track data for specified blueprints\n if self.blueprints:\n if request.blueprint not in self.blueprints:\n return response\n\n t_0 = getattr(g, 'start_time', dt.datetime.now())\n\n visit = dict(\n session_id=session.get('UUID', 0),\n timestamp=timestamp(),\n url=request.url,\n view_args=request.view_args,\n status_code=response.status_code,\n path=request.path,\n latency=(dt.datetime.now() - t_0).microseconds / 100000,\n content_length=response.content_length,\n referer=request.referrer,\n values=request.values\n )\n self.store_visit(visit)\n self.update_top_list(request.path)\n return response",
"def finish_response(self, request, response):\n logger.debug(\"TornadoHandler::finish_response\")\n\n try:\n response = self._render_template(request, response)\n except Exception as e:\n return self._handle_response_exception(request, response, e)\n\n try:\n self._apply_response_middleware(request, response)\n except: # Any exception should be gathered and handled\n signals.got_request_exception.send(sender=self.__class__, request=request)\n response = self.handle_uncaught_exception(request, resolver, sys.exc_info())\n\n self._tornado_request_handler.django_finish_request(response)\n\n self._response_finished = True\n return response",
"def setup_response_collector(self):\n pass",
"def handle_success_request(self) -> HttpResponse:\n raise NotImplementedError"
] | [
"0.66825056",
"0.66825056",
"0.65470517",
"0.65332025",
"0.6531433",
"0.6514031",
"0.6514031",
"0.6451953",
"0.62591517",
"0.6247269",
"0.62386",
"0.6179077",
"0.61765116",
"0.61480224",
"0.6142756",
"0.6116396",
"0.6116396",
"0.610012",
"0.60400885",
"0.6033069",
"0.6033069",
"0.60153145",
"0.5978291",
"0.5921858",
"0.59069777",
"0.5900309",
"0.588823",
"0.5850862",
"0.5837659",
"0.5820049"
] | 0.8038238 | 0 |
to update kwargs with query params with greater priority of kwargs. | def updatekwargs(self,request):
updated_dict={}
if isinstance(request.query_params,QueryDict):
updated_dict = {k:','.join(v) for k,v in request.query_params.iterlists()}
else:
updated_dict = request.query_params
updated_dict.update(self.kwargs)
self.kwargs = updated_dict | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def __update_params(self,**kwargs):\n updatedArgSet = set(self._updateParamsArgs) & kwargs.viewkeys()\n if len(updatedArgSet) > 0:\n args = self._subDictionary(self._updateParamsArgs)\n newArgs = self._onParamsUpdate(**args)\n updatedArgs =dict()\n for k in updatedArgSet:\n try:\n updatedArgs[k] = newArgs[k]\n except:\n pass\n\n self.__dictionary.update(newArgs)\n else:\n pass",
"def _UpdateWithKwargs(base, **kwargs):\n conflicts = set(kwargs.keys()) & set(base.keys())\n if conflicts:\n raise GanetiApiError(\"Required fields can not be specified as\"\n \" keywords: %s\" % \", \".join(conflicts))\n\n base.update((key, value) for key, value in kwargs.items()\n if key != \"dry_run\")",
"def updateParameters(self,*args,**kwargs):\n for key in kwargs.keys():\n self._params[key] = kwargs[key]",
"def update(self, **kwargs):\n for key, value in sorted(kwargs.items()):\n if value:\n if hasattr(self, key):\n setattr(self, key, value)",
"def update_kwargs(self, module: dict, flat: dict):\n if \"kwargs\" in module:\n module[\"kwargs\"] = self.replace_with_comp(module[\"kwargs\"], flat)\n else:\n module[\"kwargs\"] = {}",
"def _resolve_kwargs(self, kwargs: typing.Union[dict, None]):\n\n if kwargs is None:\n kwargs = {}\n\n if hasattr(self, \"kwargs\") and isinstance(self.kwargs, dict):\n _kwargs = kwargs\n kwargs = self.kwargs\n kwargs.update(_kwargs)\n\n return kwargs",
"def update_from_kwargs(self, **kwargs):\n for (key, value) in kwargs.items():\n setattr(self, key, value)",
"def update_values(self, to_update):\n for key, value in kwargs.iteritems():\n self.params[key] = value\n # update the possibly dependent parameters\n self.set_filenames()",
"def modify_query_params(context, **kwargs):\n request = context['request']\n params = request.GET.copy()\n for key, value in kwargs.items():\n if value == '':\n if key in params:\n del params[key]\n else:\n params[key] = value\n return ('?' + params.urlencode()) if params else ''",
"def set_params(self, **kwargs):\n ...",
"def _merge_kwargs(**kwargs):\n overlap = set(kwargs) & set(partial_kwargs)\n if overlap:\n raise ValueError(\n f\"Cannot override the following kwargs: {overlap}.\\n\"\n f\"This is because they were already set at the time this \"\n f\"partial class was defined.\"\n )\n merged_kwargs = {**partial_kwargs, **kwargs}\n return merged_kwargs",
"def update_model_kwargs_logic(default_kwargs: dict = None, user_kwargs: dict = None):\n out = {}\n if default_kwargs is None:\n default_kwargs = {}\n if user_kwargs is None:\n user_kwargs = {}\n\n # Check valid kwargs\n for iter_key in user_kwargs.keys():\n if iter_key not in default_kwargs:\n raise ValueError(\"Model kwarg {0} not in default arguments {1}\".format(iter_key, default_kwargs.keys()))\n\n out.update(default_kwargs)\n\n # Nested update of kwargs:\n def _nested_update(dict1, dict2):\n for key, values in dict2.items():\n if key not in dict1:\n print(\"WARNING:kgcnn: Unknown model kwarg {0} with value {1}\".format(key, values))\n dict1[key] = values\n else:\n if isinstance(dict1[key], dict) and isinstance(values, dict):\n # The value is a dict of model arguments itself. Update the same way.\n dict1[key] = _nested_update(dict1[key], values)\n elif isinstance(dict1[key], dict) and not isinstance(values, dict):\n # If values is None, means no information, keep dict1 values untouched.\n if values is not None:\n raise ValueError(\"Can not overwriting dictionary of {0} with {1}\".format(key, values))\n else:\n # Just any other value to update\n dict1[key] = values\n return dict1\n\n return _nested_update(out, user_kwargs)",
"def modify_query(**values):\n args = request.args.copy()\n\n for attr, new_value in values.items():\n if new_value is not None:\n args[attr] = new_value\n elif attr in args:\n del args[attr]\n\n if args:\n return request.base_url + \"?\" + url_encode(args)\n else:\n return request.base_url",
"def params(self, **kwargs):\n return kwargs",
"def set_queries(self, **kwargs):\n for k, v in kwargs.items():\n self._query_dict[k] = v",
"def update_params(self, extra_params):\n self._params.update(extra_params)\n return self",
"def updated_query(request, *args):\n # NOTE: it returns a dict not a QueryDict\n\n # recall query_to_dict returns key-val sequence\n # filter out the search key\n updated = {k: v for k, v in query_to_dict(request.GET.copy()) if\n k != \"search\"}\n\n # the args must at least have a key + value\n if len(args) < 2:\n return updated\n\n # helper function to update key-in\n def key_in(dic, keys, val):\n k = keys[0]\n # TODO : broken in the sense that I seem to be only updating\n # lists\n if len(keys) == 1:\n if isinstance(dic[k], list) and val not in dic[k]:\n dic[k].append(val)\n else:\n key_in(dic[k], keys[1:], val)\n\n # call key_in to update\n key_in(updated, args[:-1], args[-1])\n\n # return the updated dict (NOTE: this is not\n # a query dict\n return updated",
"def _prepare_query_params(self, query_kwargs):\n query_params = dict()\n if query_kwargs.get(\"fields\"):\n query_params[\"fields\"] = query_kwargs[\"fields\"]\n\n if query_kwargs.get(\"limit\"):\n query_params[\"limit\"] = query_kwargs[\"limit\"]\n else:\n query_params[\"limit\"] = self.MAX_PAGE_SIZE\n\n return query_params",
"def update(self, arg=None, **kwargs):\n if arg:\n if hasattr(arg, 'keys'):\n for k in arg: self[k] = arg[k]\n else:\n for k, v in arg: self[k] = v\n\n if kwargs:\n for k in kwargs: self[k] = kwargs[k]",
"def set_params(self, **kwargs) -> NoReturn:\n pass",
"def add_querystring(context, **kwargs):\n\n updated = context['request'].GET.copy()\n\n # have to iterate over and not use .update as it's a QueryDict not a dict\n for k, v in kwargs.items():\n updated[k] = v\n\n return '?{}'.format(updated.urlencode()) if updated else ''",
"def set_params(self,**kwargs):\n for key in kwargs:\n setattr(self, key, kwargs[key])",
"def kwargs(kwargs):\n run_kwargs(kwargs)",
"def set_params(self, **kwargs):\n for key, value in kwargs.items():\n if key in self.params.keys():\n self.params[key] = value\n else:\n raise KeyError",
"def update_param_vals(pars, prefix, **kwargs):\n for key, val in kwargs.items():\n pname = \"%s%s\" % (prefix, key)\n if pname in pars:\n pars[pname].value = val\n return pars",
"def _update_args_and_kargs(self):\n if self.kwargs:\n self.value.append(self.args)\n self.value.append(self.kwargs)\n else:\n if self.args:\n self.value.append(self.args)",
"def update(self, **kwargs):\n for k, v in kwargs.iteritems():\n if hasattr(self, k):\n setattr(self, k, v)",
"def update_params(self):\n pass",
"def _set_query_params(query, key, value):\n query.update({str(key): str(value)})",
"def test_update_with_existing_query_with_two_args_override(self):\n rendered_result = self._render_tag(\n tag='{% querystring \"update\" \"foo=bar\" \"qux=baz\" %}',\n query_str='foo=foo&bar=bar&baz=baz&qux=qux')\n\n self.assertTrue(rendered_result.startswith('?'))\n self.assertEqual(QueryDict(rendered_result[1:]),\n QueryDict('foo=bar&bar=bar&baz=baz&qux=baz'))"
] | [
"0.68662506",
"0.68000084",
"0.6720413",
"0.64425296",
"0.63728446",
"0.6354257",
"0.6348046",
"0.63343126",
"0.62960684",
"0.6291026",
"0.62539774",
"0.62418306",
"0.6237482",
"0.61691016",
"0.61404216",
"0.61181504",
"0.6115815",
"0.6114842",
"0.6102069",
"0.6084299",
"0.6074606",
"0.6060621",
"0.6049579",
"0.60308355",
"0.6030479",
"0.60116255",
"0.6007791",
"0.6007235",
"0.5998853",
"0.597466"
] | 0.7752384 | 0 |
get requested views from request.query_params.relview | def get_requested_views(self,request,returnformat):
relview_key = getattr(self,'relview_key','relview')
reqviews = request.query_params.get(relview_key)
if reqviews is None:
# if no relview is passed in query_params then fetch
# from its attribute relview which is set in urls.py
if self.relview is not None:
reqviews = self.relview
# if related views are not fetched either through query_params
# or in urls.py and is not jsonrequest then fetch all views
if reqviews is None: #and returnformat != 'json':
reqviews = 'all'
if self.jointrel is not None:
reqviews = reqviews+','+self.jointrel
#import pdb; pdb.set_trace()
if reqviews:
reqviews = reqviews.split(',')
relviews = self.related_views.keys()
include = []
exclude = []
for reqview in reqviews:
if reqview == 'all':
include += relviews
elif reqview[0] == '-':
exclude.append(reqview[1:])
elif reqview not in include:
include.append(reqview)
reqviews = subtractlists(include,exclude)
return reqviews | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_requested_views(self,request,returnformat):\n if isinstance(request,Request):\n relview_key = getattr(self,'relview_key','relview')\n reqviews = request.query_params.get(relview_key)\n if reqviews is None:\n # if no relview is passed in query_params then fetch\n # from its attribute relview which is set in urls.py\n if self.relview is not None:\n reqviews = self.relview\n # if related views are not fetched either through query_params\n # or in urls.py and is not jsonrequest then fetch all views\n if reqviews is None: #and returnformat != 'json':\n tabmap = getattr(self,'tabmap',None)\n tabkey = getattr(self,'tab_key','tab')\n if tabmap:\n currenttab = request.query_params.get(tabkey)\n if not currenttab:\n if self.defaulttab is not None:\n currenttab = self.defaulttab\n\n requestedtab = tabmap.get(currenttab,self.defaulttab)\n if currenttab and requestedtab:\n reqviews = map(lambda x: x.strip(),requestedtab.strip(',').split(','))\n self._currenttab = currenttab\n if reqviews:\n return reqviews\n return super(TabAPIView,self).get_requested_views(request,returnformat)",
"def getViews(read):\n ...",
"def get_views(view_args, model_type):\n # XXX Why pop?\n metadata = view_args.pop('metadata')\n all_view = metadata.get('views', {}).get('all')\n if not all_view:\n all_view= '%s/all'%model_type\n all_count_view = metadata.get('views', {}).get('all_count')\n if not all_count_view:\n all_count_view= '%s/all_count'%model_type\n return all_view, all_count_view",
"def _get_view_and_args(path, request):\n # Let's use urlconf from request object, if available:\n urlconf = getattr(request, \"urlconf\", settings.ROOT_URLCONF)\n resolver = RegexURLResolver(r\"^/\", urlconf)\n return resolver.resolve(path)",
"def get_view(self, path):\n _view, params = None, {}\n for route, view in self._routes.items():\n match = route.match(path)\n if not match:\n continue\n if match and isinstance(match, dict): # Means route have parameters\n _view, params = view, match\n else:\n _view = view\n break\n return _view, params",
"def get_view_by_introspector(request, route):\n introspector = request.registry.introspector\n route_intr = introspector.get('routes', route.name)\n\n related_intr = introspector.related(route_intr)\n if related_intr is None:\n return None\n\n for related in related_intr:\n print \"related\", related\n if related.category_name == 'views':\n view_func = related['callable']\n if isinstance(view_func, static_view):\n # Lets skip over static views\n continue\n if related['attr']:\n view_action = \".\".join([view_func.__module__, view_func.__name__, related['attr']])\n else:\n view_action = \".\".join([view_func.__module__, view_func.__name__])\n return view_action",
"def get_related_view(request):\n return request.environ.get('cone.app.related_view', None)",
"def page_views(self, *args, **kwargs):\r\n return self._get('PageViews', *args, **kwargs)",
"def getViews(self):\n return list(self.__views.keys())",
"def views(self):\n return self._views",
"def getViews(self):\n return list(self.__views)",
"def static_view_finder(viewname, **other):\n return viewname",
"def get_views(self):\n query = mssqlqueries.get_views()\n logger.info(u'Views query: %s', query)\n for tabular_result in self.execute_query(query):\n for row in tabular_result[0]:\n yield (row[0], row[1])",
"def related_view_filter():\n pass",
"def getReachableViews(self):\n raise NotImplementedError()",
"def r(request):\n return request.param",
"def get_view(self, request) -> Optional[View]:\n\n # Grab ViewAction and use sorted_actions to find first match\n sorted_actions = ViewAction.sorted_actions(self.registry)\n\n # Find the first action which matches the args\n for action, view_class in sorted_actions:\n if action.all_predicates_match(request):\n # Use dependency injection to make an instance of\n # that view class\n view_instance = inject(\n dict(), # props\n self.get_injectables(request),\n view_class,\n request=request\n )\n return view_instance\n\n # No matches, return None\n return None",
"def get_views(cohesity_client):\n views = cohesity_client.views.get_views().views\n views_list = views if views else []\n for view in views_list:\n exported_res_dict[\"Protection Views\"].append(view.name)\n return views_list",
"def getViews(self):\n raise NotImplementedError()",
"def getReachableViews(self):\n return [self]",
"def get_views(self, path, year=None, month=None, day=None, hour=None):\n return self._telegraph.method('getViews', path=path, values={\n 'year': year,\n 'month': month,\n 'day': day,\n 'hour': hour\n })",
"def getMatchingViews(self, data, info):\n raise NotImplementedError()",
"def get_sg_use_views(cluster_config):\n cluster = load_cluster_config_json(cluster_config)\n return cluster[\"environment\"][\"sg_use_views\"]",
"def getview(viewid) :\n\treturn Jikji.getinstance().getview(viewid)",
"def local_views():\n\tpass",
"def extract_channel_views(show_views_channel):\n channel,views,=show_views_channel[1]\n return (channel, views)",
"def related_view(self):\n return get_related_view(self.request)",
"def network_views():\n return 'networkview?'",
"def _get_views(work_sheet):\n ddi_view_col = work_sheet.row_values(0).index('DDI View')\n view_col = list(set(work_sheet.col_values(ddi_view_col)[1:]))\n return view_col",
"def get_viewaction(self, request) -> Optional[PredicateAction]:\n\n # This is used for nonlookup predicates such as stuff related\n # to rendering and templates. Need the registration information,\n # not just the target.\n\n # Grab ViewAction and use sorted_actions to find first match\n sorted_actions = ViewAction.sorted_actions(self.registry)\n\n # Find the first action which matches the args\n for action, view_class in sorted_actions:\n if action.all_predicates_match(request):\n # Use dependency injection to return the view action\n return action\n\n # No matches, return None\n return None"
] | [
"0.75398153",
"0.6885467",
"0.67272025",
"0.6463465",
"0.64211583",
"0.6304628",
"0.61412376",
"0.59954315",
"0.5932171",
"0.59282255",
"0.5863362",
"0.5801414",
"0.57248193",
"0.56478566",
"0.5637953",
"0.5636953",
"0.5582375",
"0.5578582",
"0.5537936",
"0.5492978",
"0.5450288",
"0.54418254",
"0.5429811",
"0.535933",
"0.53432167",
"0.5331353",
"0.5286037",
"0.5271804",
"0.52220905",
"0.52139026"
] | 0.8181199 | 0 |
Overridden generics.ListAPIView list method to provide additional functionality of related views data fetching and applied filters addition | def list(self,request,*args,**kwargs):
response=super(ListAPIView,self).list(request,*args,**kwargs)
#add applied_filters to the response which is set when filter_queryset method is called
response=self.addAppliedFilters(response)
#fetch data from the related views
return self.fetch_related(request,response,*args,**kwargs) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def list(self, request, *args, **kwargs):\n queryset = self.filter_queryset(self.get_queryset())\n\n page = self.paginate_queryset(queryset)\n\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n else:\n serializer = self.get_serializer(queryset, many=True)\n\n data = serializer.data\n\n \"\"\"\n Determine the response type based on the request.\n a) For HTTP requests (e.g. via the browsable API) return a DRF response\n b) For AJAX requests, simply return a JSON rendered response.\n\n Note: b) is about 100x quicker than a), because the DRF framework adds a lot of cruft\n \"\"\"\n\n if page is not None:\n return self.get_paginated_response(data)\n elif request.is_ajax():\n return JsonResponse(data, safe=False)\n else:\n return Response(data)",
"def docter_list(self, request, **dict):\n\t\tdata = self.get_serializer(self.get_queryset(), many=True).data\n\t\treturn Response(data, status.HTTP_200_OK)",
"def list(self, request, *args, **kwargs):\n\n queryset = self.filter_queryset(self.get_queryset())\n\n page = self.paginate_queryset(queryset)\n data = dict()\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n data = self.build_list_data(serializer=serializer,\n username=request.user.username,\n add_pagination=True)\n # @TODO: somewhat inefficient usage of pagination, review\n response = self.get_paginated_response(serializer.data)\n for attr in ('count', 'next', 'previous'):\n data['header']['pagination'][attr] = response.data[attr]\n else:\n serializer = self.get_serializer(queryset, many=True)\n data = self.build_list_data(serializer=serializer, username=request.user.username)\n\n return Response(data=data, status=status.HTTP_200_OK)",
"def list(self, request, *args, **kwargs):\n\n queryset = self.filter_queryset(self.get_queryset())\n\n page = request.query_params.get('page', 1)\n paginator = Paginator(queryset, 8)\n\n try:\n queryset = paginator.page(page)\n\n except PageNotAnInteger:\n queryset = paginator.page(1)\n\n except EmptyPage:\n queryset = paginator.page(paginator.num_pages)\n\n page = int(page)\n\n serializer = self.get_serializer(queryset, many=True)\n return Response({'items': serializer.data, 'page': page, 'pages': paginator.num_pages})",
"def list(self, request):\n queryset = self.get_queryset()\n serializer = self.serializer_class(queryset, many=True)\n return Response(serializer.data)",
"def list(self , request,*args,**kwargs):\n return super(UsersViewset,self).list(request,args,kwargs)",
"def get(self, *args, **kwargs):\n return super(APIFolderListView, self).get(*args, **kwargs)",
"def list(self, request, *args, **kwargs):\n return super(SubtaskViewSet, self).list(request, *args, **kwargs)",
"def related_view_filter():\n pass",
"def get_list(self, *args, **kwargs):\n pass",
"def get_list(self, *args, **kwargs):\n pass",
"def _list(self, **kwargs):\n\n return self._make_request(**kwargs)",
"def list(self, request, *args, **kwargs):\n query = self.filter_queryset(self.get_queryset())\n if isinstance(query, ErrorResponse):\n return query\n default_limit = DEFAULT_LIST_LIMIT\n limit, offset, range_errors = self.get_offset_limit_params(default_limit)\n if range_errors:\n return ErrorResponse(data=range_errors)\n\n self.object_list = get_object_list(offset, limit, query)\n\n # Default is to allow empty querysets. This can be altered by setting\n # `.allow_empty = False`, to raise 404 errors on empty querysets.\n if not self.allow_empty and not self.object_list:\n warnings.warn(\n 'The `allow_empty` parameter is due to be deprecated. '\n 'To use `allow_empty=False` style behavior, You should override '\n '`get_queryset()` and explicitly raise a 404 on empty querysets.',\n PendingDeprecationWarning\n )\n class_name = self.__class__.__name__\n error_msg = self.empty_error % {'class_name': class_name}\n raise Http404(error_msg)\n\n # the pagination is not supported, use offset and limit\n serializer = self.get_serializer(self.object_list, many=True)\n return self.generate_list_response(query, self.object_list, serializer, offset, limit)",
"def list(self, request, *args, **kwargs):\n self.order_queryset = True\n if 'ordering' in request.query_params.keys():\n self.order_queryset = False\n return super(ReleaseViewSet, self).list(request, *args, **kwargs)",
"def specialist_list(self, request, **dict):\n\t\tdata = self.get_serializer(self.get_queryset(), many=True).data\n\t\treturn Response(data, status.HTTP_200_OK)",
"def obj_get_list(self, bundle, **kwargs):\n filters = {}\n if hasattr(bundle.request, 'GET'):\n # Grab a mutable copy.\n filters = bundle.request.GET.copy()\n\n # Update with the provided kwargs.\n filters.update(kwargs)\n channel = False\n if 'owner' in filters:\n channel = True\n applicable_filters = self.build_filters(filters=filters)\n\n try:\n objects = self.apply_filters(bundle.request, applicable_filters)\n self.objects_returned = len(objects)\n if len(objects) == 1 and applicable_filters and not channel:\n obj = objects[0]\n obj.views = obj.views + 1\n obj.lastview_date = timezone.now()\n obj.save(update_fields=['views', 'lastview_date'])\n return self.authorized_read_list(objects, bundle)\n except ValueError:\n raise BadRequest(\"Invalid resource lookup data provided (mismatched type).\")",
"def list(self, request, *args, **kwargs):\n queryset = self.filter_queryset(self.get_queryset())\n\n page = self.paginate_queryset(queryset)\n\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n else:\n serializer = self.get_serializer(queryset, many=True)\n\n data = serializer.data\n\n # Attempt to add extra context information to the historical data\n for item in data:\n deltas = item['deltas']\n\n if not deltas:\n deltas = {}\n\n # Add part detail\n if 'part' in deltas:\n try:\n part = Part.objects.get(pk=deltas['part'])\n serializer = PartBriefSerializer(part)\n deltas['part_detail'] = serializer.data\n except Exception:\n pass\n\n # Add location detail\n if 'location' in deltas:\n try:\n location = StockLocation.objects.get(pk=deltas['location'])\n serializer = StockSerializers.LocationSerializer(location)\n deltas['location_detail'] = serializer.data\n except Exception:\n pass\n\n # Add stockitem detail\n if 'stockitem' in deltas:\n try:\n stockitem = StockItem.objects.get(pk=deltas['stockitem'])\n serializer = StockSerializers.StockItemSerializer(stockitem)\n deltas['stockitem_detail'] = serializer.data\n except Exception:\n pass\n\n # Add customer detail\n if 'customer' in deltas:\n try:\n customer = Company.objects.get(pk=deltas['customer'])\n serializer = CompanySerializer(customer)\n deltas['customer_detail'] = serializer.data\n except Exception:\n pass\n\n # Add PurchaseOrder detail\n if 'purchaseorder' in deltas:\n try:\n order = PurchaseOrder.objects.get(pk=deltas['purchaseorder'])\n serializer = PurchaseOrderSerializer(order)\n deltas['purchaseorder_detail'] = serializer.data\n except Exception:\n pass\n\n # Add SalesOrder detail\n if 'salesorder' in deltas:\n try:\n order = SalesOrder.objects.get(pk=deltas['salesorder'])\n serializer = SalesOrderSerializer(order)\n deltas['salesorder_detail'] = serializer.data\n except Exception:\n pass\n\n # Add ReturnOrder detail\n if 'returnorder' in deltas:\n try:\n order = ReturnOrder.objects.get(pk=deltas['returnorder'])\n serializer = ReturnOrderSerializer(order)\n deltas['returnorder_detail'] = serializer.data\n except Exception:\n pass\n\n # Add BuildOrder detail\n if 'buildorder' in deltas:\n try:\n order = Build.objects.get(pk=deltas['buildorder'])\n serializer = BuildSerializer(order)\n deltas['buildorder_detail'] = serializer.data\n except Exception:\n pass\n\n if page is not None:\n return self.get_paginated_response(data)\n if request.is_ajax():\n return JsonResponse(data, safe=False)\n else:\n return Response(data)",
"def list(self, request, **kwargs):\n queryset = self.get_queryset()\n filtered_queryset = self.filter_queryset(queryset)\n filtered_queryset = exclude_persons_without_registrations(request, filtered_queryset) \n\n page = self.paginate_queryset(filtered_queryset)\n if page is not None:\n serializer = PersonListSerializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = PersonListSerializer(filtered_queryset, many=True)\n return Response(serializer.data)",
"def list(self, **kwargs):\n data, self.endpoint = self.data_endpoint(kwargs)\n r = super(Resource, self).list(**data)\n\n # Change display settings and data format for human consumption\n self.configure_display(r)\n return r",
"def obj_get_list(self, request=None, **kwargs):\n filters = {}\n if hasattr(request, 'GET'):\n # Grab a mutable copy.\n filters = request.GET.copy()\n\n # Update with the provided kwargs.\n filters.update(kwargs)\n if \"community\" in filters:\n try:\n community = Community.objects.get(\n uuid=uuid_from_uri(filters['community']))\n im = community.image_set.filter(is_active=True)\n wb = community.wordbox_set.filter(is_active=True)\n base_object_list = sorted(chain(im, wb),\n key=attrgetter('created_time'))[::-1]\n return self.apply_authorization_limits(request,\n base_object_list)\n except ValueError:\n raise BadRequest(\"Invalid resource lookup data provided \"\n \"(mismatched type).\")\n else:\n raise BadRequest(\"Invalid filtering parameter\")",
"def listing_view(self, request):\n self._object = self.get_page_for_url(request)\n if self._object is not None:\n self.kwargs.update({'pk': self._object.pk})\n # pylint: disable=attribute-defined-outside-init\n self.action = 'detail_view'\n return self.detail_view(request, pk=self._object.pk)\n return super().listing_view(request)",
"def list(request, queryset, *args, **kwargs):\r\n return object_list(\r\n request,\r\n queryset.filter(account = request.account), \r\n *args, \r\n **kwargs\r\n )",
"def changelist_view(self, request, extra_context=None):\n if request.user.has_perm('deflect.list_all'):\n self.list_filter = self._list_filter + ('creator__username',)\n self.list_display = self._list_display + ('creator',)\n else:\n self.list_filter = self._list_filter\n self.list_display = self._list_display\n return super(ShortURLAdmin, self).changelist_view(request, extra_context=extra_context)",
"def list(self, request, *args, **kwargs):\n return viewsets.ReadOnlyModelViewSet.list(self, request, *args, **kwargs)",
"def get_queryset(self):\n queryset = super(ProductListView, self).get_queryset()\n queryset = Services.objects.all()\n return queryset",
"def search_api(request):\n data = ApiViewFilters(request.GET, queryset=ApiView.objects.all())\n return render(request, 'template.html', {'filter': data})",
"def list(self, request, *args, **kwargs):\n return super(FacilityViewSet, self).list(request, *args, **kwargs)",
"def get_queryset(self):\n qs = super(RetiresmartzViewSet, self).get_queryset()\n # Check user object permissions\n user = SupportRequest.target_user(self.request)\n return qs.filter_by_user(user)",
"def get_queryset(self):\n return None",
"def get_queryset(self):\n return None"
] | [
"0.66712135",
"0.66708434",
"0.6605466",
"0.6597969",
"0.6391783",
"0.63200647",
"0.6303749",
"0.6296388",
"0.6233774",
"0.6208628",
"0.6208628",
"0.6180615",
"0.6162589",
"0.60989046",
"0.60909146",
"0.6077781",
"0.60466784",
"0.6036895",
"0.6025789",
"0.60160166",
"0.59908885",
"0.5977586",
"0.5975376",
"0.5954498",
"0.59530437",
"0.59050953",
"0.58836645",
"0.58548063",
"0.58516026",
"0.58516026"
] | 0.8497571 | 0 |
Add the filters applied to the view to response using the view applied_filters attribute accessible with filters key | def addAppliedFilters(self,response):
if hasattr(self,'applied_filters') and self.applied_filters:
if not isinstance(response.data,(list,tuple)):
response.data['filters']=self.applied_filters
return response | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def process_filters(self, filters, queryset, view):\n return filters",
"def filter_queryset(self, request, queryset, view):\n applicable_filters, applicable_exclusions = self.build_filters(view, filters=self.get_request_filters(request))\n return self.apply_filters(\n queryset=queryset,\n applicable_filters=self.process_filters(applicable_filters, queryset, view),\n applicable_exclusions=self.process_filters(applicable_exclusions, queryset, view)\n )",
"def apply_filters(self, new_filters):\n\t\tself.filters = new_filters",
"def _add_filters(self, filters):\n self._env.filters['dateformat'] = dateformat\n self._env.filters.update(filters or {})",
"def apply_filters(self, filters):\n self._data = self.model.objects.filter(**filters)",
"def apply_filters(self, queryset, applicable_filters=None, applicable_exclusions=None):\n if applicable_filters:\n queryset = queryset.filter(applicable_filters)\n if applicable_exclusions:\n queryset = queryset.exclude(applicable_exclusions)\n return queryset",
"def get_filters(self):",
"def _get_filters(self, request, queryset, view): # noqa\n self.opts = queryset.model._meta\n filter_fields = getattr(view, \"filter_fields\", None)\n self.exclude = {}\n self.filters = {}\n\n if filter_fields:\n blacklist = RexList(getattr(view, \"filter_blacklist\", []))\n mapping = self._get_mapping(view)\n\n for fieldname_arg in self.query_params:\n raw_value = self.query_params.get(fieldname_arg)\n if raw_value in [\"''\", '\"\"']:\n raw_value = \"\"\n\n negate = fieldname_arg[-1] == \"!\"\n\n if negate:\n filter_field_name = fieldname_arg[:-1]\n TARGET = self.exclude\n else:\n TARGET = self.filters\n filter_field_name = fieldname_arg\n\n if filter_field_name in self.excluded_query_params:\n continue\n if self.ignore_filter(request, filter_field_name, view):\n continue\n try:\n if filter_field_name in blacklist:\n raise InvalidQueryArgumentError(fieldname_arg)\n parts = None\n if \"__\" in filter_field_name:\n parts = filter_field_name.split(\"__\")\n filter_field_name = parts[0]\n op = parts[-1]\n else:\n op = \"\"\n processor = getattr(\n self,\n \"process_{}\".format(filter_field_name),\n getattr(view, \"drfqs_filter_{}\".format(filter_field_name), None),\n )\n\n if (filter_field_name not in filter_fields) and (not processor):\n self.unknown_arguments.append((fieldname_arg, filter_field_name))\n continue\n # raise InvalidQueryArgumentError(filter_field_name)\n if raw_value is None and not processor:\n continue\n # field is configured in Serializer\n # so we use 'source' attribute\n if filter_field_name in mapping:\n real_field_name = mapping[filter_field_name].source\n # if '.' in real_field_name:\n # real_field_name = real_field_name.split('.')[0]\n # field_name = real_field_name.replace('.', '__')\n else:\n real_field_name = filter_field_name\n\n if processor:\n payload = {\n \"field\": filter_field_name,\n \"request\": request,\n \"param\": fieldname_arg,\n \"negate\": negate,\n \"op\": op,\n \"field_name\": real_field_name,\n \"parts\": parts,\n \"value\": raw_value,\n \"real_field_name\": real_field_name,\n }\n _f, _e = processor(dict(self.filters), dict(self.exclude), **payload)\n self.filters.update(**_f)\n self.exclude.update(**_e)\n else:\n if not raw_value:\n continue\n # field_object = opts.get_field(real_field_name)\n value_type = self.field_type(real_field_name)\n if parts:\n f = \"{}__{}\".format(real_field_name, \"__\".join(parts[1:]))\n else:\n f = filter_field_name\n if op in [\"in\", \"contained_by\"]:\n value = raw_value.split(\",\")\n elif op == \"acontains\":\n value = raw_value.split(\",\")\n f = f.replace(\"__acontains\", \"__contains\")\n elif op == \"isnull\":\n value = parse_bool(raw_value)\n elif value_type == bool:\n value = parse_bool(raw_value)\n else:\n value = raw_value\n TARGET[f] = value\n except ValueError:\n raise InvalidQueryValueError(fieldname_arg, raw_value)\n except QueryFilterException:\n raise\n except Exception as e:\n logger.exception(e)\n raise\n return self.filters, self.exclude",
"def attach(self, filt, view=None):\n if view is None:\n self._vshare.filters.append(filt)\n for view in self._vshare.views.keys():\n filt._attach(view)\n else:\n view._filters.append(filt)\n filt._attach(view)",
"def filter(self, filters):",
"def update_filters(self):\n\n # Update household filter\n household_filter = [True if agent == 'household' else False for agent \\\n in self.source.data['agent_type']]\n self.household_view.filters[0] = BooleanFilter(household_filter)\n\n # Update neighbourhood filter\n neighbourhood_filter = [True if agent == 'neighbourhood' else False for\\\n agent in self.source.data['agent_type']]\n self.neighbourhood_view.filters[0] = BooleanFilter(\n neighbourhood_filter)\n\n # Update school filter\n school_filter = [True if agent == 'school' else False for agent in \\\n self.source.data['agent_type']]\n self.school_view.filters[0] = BooleanFilter(school_filter)",
"def update_filters(self, **kwargs):\n self._FILTERS = kwargs",
"def filter(self, filter_dict):\n pass",
"def apply_filters(filters, items):\n return scom.apply_filters(filters, items)",
"def get_timeline_filters(self, req):",
"def extract_filters(self):\n self.filters = self.controller.filters\n\n self.extract_core_stats()\n self.extract_abilities()\n # goes through and adds all list-based filters\n for filterType, elements in self.filters.items():\n if type(elements) == list and len(elements) > 0:\n self.extract_filter_list(filterType, elements)",
"def related_view_filter():\n pass",
"def filters(self, filters):\n\n self._filters = filters",
"def apply_filters(self, queryset, applicable_filters=None, applicable_exclusions=None):\n for field, options in applicable_filters[\"field_facets\"].items():\n queryset = queryset.facet(field, **options)\n\n for field, options in applicable_filters[\"date_facets\"].items():\n queryset = queryset.date_facet(field, **options)\n\n for field, options in applicable_filters[\"query_facets\"].items():\n queryset = queryset.query_facet(field, **options)\n\n return queryset",
"def _set_filters(self, options):\n if options.keywords:\n self.filters[\"keywords\"] = string_to_list(options.keywords)\n if options.features:\n self.filters[\"features\"] = string_to_list(options.features)\n if options.authors:\n self.filters[\"authors\"] = string_to_list(options.authors)\n if options.version:\n self.filters[\"version\"] = options.version",
"def request_filter(self, fn):\n self.request_filters.append(fn)\n return fn",
"def list(self,request,*args,**kwargs):\n response=super(ListAPIView,self).list(request,*args,**kwargs)\n #add applied_filters to the response which is set when filter_queryset method is called\n response=self.addAppliedFilters(response)\n #fetch data from the related views\n return self.fetch_related(request,response,*args,**kwargs)",
"def build_filters(self, view, filters=None):\n query_builder = self.get_query_builder(backend=self, view=view)\n return query_builder.build_query(**(filters if filters else {}))",
"def build_filters(self, filters=None):\n if filters is None:\n filters = {}\n\n grouped = get_grouped_filters(filters)\n branch_filters = get_branch_filter(filters)\n orm_filters = super(StoryResource, self).build_filters(filters)\n orm_filters['grouped'] = grouped\n orm_filters['br_filter'] = branch_filters\n\n if 'content_type__in' in filters:\n orm_filters['content_type__in'] = [CONTENT_HYDRATE[f] for f in filters['content_type__in'].split(',')]\n\n return orm_filters",
"def configure_filters(app):\n\n for (name, filter) in _filters.iteritems():\n app.jinja_env.filters[name] = filter",
"def attach(self, filt, view=None):\n raise NotImplementedError(self)",
"def std_filters():\n kwargs = {\n \"sentence_filters\":[punctuation_filter],\n \"word_filters\":[small_word_filter, stopword_filter, stemming_filter]\n }\n return kwargs",
"def filters(self, value):\n if not isinstance(value, dict):\n raise TypeError(\"input must be a dictionary\")\n\n self._filters = value",
"def filters(self):\n\t\treturn self.local_filter",
"def filters(self):\n return {\n 'dict_merge': do_merge,\n 'list_merge': do_list_merge,\n 'attrs': do_attrs,\n 'merge_mysql_privs': do_merge_mysql_privs,\n 'role': do_role,\n 'reduce': do_reduce,\n 'dict_join': do_dict_join,\n 'get': do_get,\n 'contains': do_contains,\n 'selectattrs': do_selectattrs,\n 'convert_integer': do_convert_integer,\n 'camel': do_camel\n }"
] | [
"0.7354717",
"0.667946",
"0.6549934",
"0.6452416",
"0.63936824",
"0.6259591",
"0.62048525",
"0.6121124",
"0.6069148",
"0.6029197",
"0.602686",
"0.5989809",
"0.5984785",
"0.59195393",
"0.5910779",
"0.589759",
"0.5881149",
"0.58608884",
"0.58586997",
"0.5766401",
"0.5728919",
"0.5708959",
"0.569859",
"0.5676832",
"0.5626949",
"0.5625782",
"0.56178874",
"0.56120765",
"0.55526066",
"0.55302054"
] | 0.7728048 | 0 |
Overridden generics.RetrieveAPIView retrieve method to provide additional functionality of related views data fetching | def retrieve(self,request,*args,**kwargs):
response=super(RetrieveAPIView,self).retrieve(request,*args,**kwargs)
return self.fetch_related(request,response,*args,**kwargs) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def list(self,request,*args,**kwargs):\n response=super(ListAPIView,self).list(request,*args,**kwargs)\n #add applied_filters to the response which is set when filter_queryset method is called\n response=self.addAppliedFilters(response)\n #fetch data from the related views\n return self.fetch_related(request,response,*args,**kwargs)",
"def detail_view(self, request, pk):\n instance = self.get_object()\n if self.revision_wanted is not None:\n instance = get_object_or_404(\n instance.revisions, id=self.revision_wanted).as_page_object()\n elif self.is_preview:\n instance = instance.get_latest_revision_as_page()\n serializer = self.get_serializer(instance)\n return Response(serializer.data)",
"def retrieve(self, request, pk=None):\n return Response({\"retrieve_get\": 'GET'})",
"def retrieve(self, request, pk=None):\n\n return Response({'http_method': 'GET'})",
"def retrieve(self, request, pk=None, **kwargs):\n serializer = self.serializer_class(self.get_object())\n return Response(serializer.data, status=status.HTTP_200_OK)",
"def retrieve(self, request, *args, **kwargs):\n return viewsets.ReadOnlyModelViewSet.retrieve(self, request, *args, **kwargs)",
"def retrieve(self,request, pk = None):\n return Response({'http_method': 'GET'})",
"def retrieve(self, request, pk=None):\n try:\n review = Review.objects.get(pk=pk)\n serializer = ReviewSerializer(review, context={'request': request})\n return Response(serializer.data)\n except Exception as ex:\n return HttpResponseServerError(ex)",
"def get(self, request, *args, **kwargs):\n view = ReviewDisplay.as_view()\n return view(request, *args, **kwargs)",
"def get(self, request, *args, **kwargs):\n query = self.queryset.values('author')\n owner = list(query)[0].get('author')\n self.update_author_views(author=owner)\n\n kwargs.update({'views': True})\n self.update_article_stats(**kwargs)\n\n return self.retrieve(request, *args, **kwargs)",
"def object_get(self, request):\n _view = _object_view(self, request)\n queried = ObjectPostings(self.cdb_object_id, request.params.mixed()).query()\n postings = [request.view(obj) for obj in queried[0]]\n\n _view.update({\n \"postings\": postings,\n \"result_complete\": queried[1]\n })\n return _view",
"def retrieve(self, request, pk=None):\n return Response({'http_method': 'GET'})",
"def retrieve(self, request, *args, **kwargs):\n _data_id, _format = get_data_and_form(kwargs)\n # pylint: disable=attribute-defined-outside-init\n self.object = instance = self.get_object()\n\n if _format == \"json\" or _format is None or _format == \"debug\":\n return Response(instance.json)\n if _format == \"xml\":\n return Response(instance.xml)\n if _format == \"geojson\":\n return super().retrieve(request, *args, **kwargs)\n if _format == Attachment.OSM:\n serializer = self.get_serializer(instance.osm_data.all())\n\n return Response(serializer.data)\n\n raise ParseError(_(f\"'{_format}' format unknown or not implemented!\"))",
"def retrieve(self, request, pk=None):\n\n return Response({'http_method':'GET'})",
"def retrieve(self, request, *args, **kwargs):\n return super(BalanceViewSet, self).retrieve(request, *args, **kwargs)",
"def retrieve(self,request , pk=None):\r\n return Response({'HTTP method':'GET'})",
"def retrieve(self, request, *args, **kwargs):\n return super(UserViewSet, self).retrieve(request, *args, **kwargs)",
"def retrieve(self, request, pk=None):\n\n\n \n\n\n try:\n # `pk` is a parameter to this function, and\n # Django parses it from the URL route parameter\n # http://localhost:8000/Posts/2\n #\n # The `2` at the end of the route becomes `pk`\n post = Post.objects.get(pk=pk)\n reactions = Reaction.objects.all()\n\n # Creates an empty list for reactions custom property set in model, and then filters through postReactions to provide objects with a\n # key/value pair of reaction label/number of that reaction the post has \n\n post.reactions=[]\n\n for reaction in reactions:\n number_of_reactions = PostReaction.objects.filter(post=post, reaction=reaction).count()\n post.reactions.append({reaction.label: number_of_reactions})\n\n associated_tags=Tag.objects.filter(related_post__post=post)\n user = RareUser.objects.get(user=request.auth.user)\n\n all_tags=serializer=TagSerializer(associated_tags, many=True, context={'request',request})\n my_post=serializer = PostSerializer(post, context={'request': request})\n \n single_post={}\n single_post['post']=my_post.data\n single_post['tags']=all_tags.data\n if user == post.user:\n single_post['myPosts']=True \n\n return Response(single_post)\n except Exception as ex:\n return HttpResponseServerError(ex)",
"def related_view(self):\n return get_related_view(self.request)",
"def get_requested_views(self,request,returnformat):\n if isinstance(request,Request):\n relview_key = getattr(self,'relview_key','relview')\n reqviews = request.query_params.get(relview_key)\n if reqviews is None:\n # if no relview is passed in query_params then fetch\n # from its attribute relview which is set in urls.py\n if self.relview is not None:\n reqviews = self.relview\n # if related views are not fetched either through query_params\n # or in urls.py and is not jsonrequest then fetch all views\n if reqviews is None: #and returnformat != 'json':\n tabmap = getattr(self,'tabmap',None)\n tabkey = getattr(self,'tab_key','tab')\n if tabmap:\n currenttab = request.query_params.get(tabkey)\n if not currenttab:\n if self.defaulttab is not None:\n currenttab = self.defaulttab\n\n requestedtab = tabmap.get(currenttab,self.defaulttab)\n if currenttab and requestedtab:\n reqviews = map(lambda x: x.strip(),requestedtab.strip(',').split(','))\n self._currenttab = currenttab\n if reqviews:\n return reqviews\n return super(TabAPIView,self).get_requested_views(request,returnformat)",
"def retrieve(self, request, *args, **kwargs):\n instance = self.get_object()\n serializer = self.get_serializer(instance)\n\n data = {\n 'header': response_header(msg='Retrieve request successfully processed.',\n username=request.user.username,\n api_status=constants.STATUS_OK),\n 'detail': serializer.data\n }\n\n return Response(data=data, status=status.HTTP_200_OK)",
"def get(self, request, pk):\n return self.retrieve(request, pk)",
"def sharing_get(self, request):\n _view = _object_view(self, request)\n queried = SharingCollection(request.params.mixed()).query()\n objs = [request.view(obj) for obj in queried[0]]\n _view.update({\n \"postings\": objs,\n \"result_complete\": queried[1]\n })\n return _view",
"def retrieve(self, request, *args, **kwargs):\n return super(BalanceBillsViewSet, self).retrieve(\n request,\n *args,\n **kwargs\n )",
"def retrieve(self, request, *args, **kwargs):\n return super(ConversationViewSet, self).retrieve(request, *args, **kwargs)",
"def _get_detail(self, pk, user=None):\n request = self.factory.get(self.detail_url(pk), format='json')\n force_authenticate(request, user)\n resp = self.detail_view(request, pk=pk)\n resp.render()\n return resp",
"def retrieve(self, request, pk=None):\n try:\n # `pk` is a parameter to this function, and\n # Django parses it from the URL route parameter\n # http://localhost:8000/games/2\n #\n # The `2` at the end of the route becomes `pk`\n review = Review.objects.get(pk=pk)\n serializer = ReviewSerializer(review, context={'request': request})\n return Response(serializer.data)\n except Exception as ex:\n return HttpResponseServerError(ex)",
"def get(self, request, *args, **kwargs):\n\n # validate and get object\n instance = self.get_object()\n\n # convert model object into json\n data = AddressViewSerializer(instance).data\n\n return APIResponse(data, HTTP_OK)",
"def retrieve(self, request, pk=None): #Equals to -> GET/{primarykey}\n return Response({'http_method': 'GET'})",
"def _get(self, request_obj):\n return self._execute_action(request_obj, [AbstractModelGetAction, AbstractModelItemGetAction], 'GET')"
] | [
"0.63180983",
"0.6271143",
"0.6262152",
"0.61606055",
"0.6104434",
"0.6103744",
"0.5973601",
"0.59641504",
"0.5953272",
"0.595036",
"0.5892447",
"0.58868515",
"0.58571994",
"0.58081573",
"0.58045816",
"0.57812613",
"0.57354194",
"0.57099235",
"0.5706479",
"0.5698495",
"0.5677163",
"0.56759924",
"0.56711084",
"0.5622179",
"0.5602252",
"0.5578976",
"0.55767596",
"0.5532205",
"0.5530613",
"0.5489493"
] | 0.75602394 | 0 |
get requested views from request.query_params.relview | def get_requested_views(self,request,returnformat):
if isinstance(request,Request):
relview_key = getattr(self,'relview_key','relview')
reqviews = request.query_params.get(relview_key)
if reqviews is None:
# if no relview is passed in query_params then fetch
# from its attribute relview which is set in urls.py
if self.relview is not None:
reqviews = self.relview
# if related views are not fetched either through query_params
# or in urls.py and is not jsonrequest then fetch all views
if reqviews is None: #and returnformat != 'json':
tabmap = getattr(self,'tabmap',None)
tabkey = getattr(self,'tab_key','tab')
if tabmap:
currenttab = request.query_params.get(tabkey)
if not currenttab:
if self.defaulttab is not None:
currenttab = self.defaulttab
requestedtab = tabmap.get(currenttab,self.defaulttab)
if currenttab and requestedtab:
reqviews = map(lambda x: x.strip(),requestedtab.strip(',').split(','))
self._currenttab = currenttab
if reqviews:
return reqviews
return super(TabAPIView,self).get_requested_views(request,returnformat) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_requested_views(self,request,returnformat):\n relview_key = getattr(self,'relview_key','relview')\n reqviews = request.query_params.get(relview_key)\n if reqviews is None:\n # if no relview is passed in query_params then fetch\n # from its attribute relview which is set in urls.py\n if self.relview is not None:\n reqviews = self.relview\n # if related views are not fetched either through query_params\n # or in urls.py and is not jsonrequest then fetch all views\n if reqviews is None: #and returnformat != 'json':\n reqviews = 'all'\n if self.jointrel is not None:\n reqviews = reqviews+','+self.jointrel\n #import pdb; pdb.set_trace()\n if reqviews:\n reqviews = reqviews.split(',')\n relviews = self.related_views.keys()\n include = []\n exclude = []\n for reqview in reqviews:\n if reqview == 'all':\n include += relviews\n elif reqview[0] == '-':\n exclude.append(reqview[1:])\n elif reqview not in include:\n include.append(reqview)\n reqviews = subtractlists(include,exclude)\n return reqviews",
"def getViews(read):\n ...",
"def get_views(view_args, model_type):\n # XXX Why pop?\n metadata = view_args.pop('metadata')\n all_view = metadata.get('views', {}).get('all')\n if not all_view:\n all_view= '%s/all'%model_type\n all_count_view = metadata.get('views', {}).get('all_count')\n if not all_count_view:\n all_count_view= '%s/all_count'%model_type\n return all_view, all_count_view",
"def _get_view_and_args(path, request):\n # Let's use urlconf from request object, if available:\n urlconf = getattr(request, \"urlconf\", settings.ROOT_URLCONF)\n resolver = RegexURLResolver(r\"^/\", urlconf)\n return resolver.resolve(path)",
"def get_view(self, path):\n _view, params = None, {}\n for route, view in self._routes.items():\n match = route.match(path)\n if not match:\n continue\n if match and isinstance(match, dict): # Means route have parameters\n _view, params = view, match\n else:\n _view = view\n break\n return _view, params",
"def get_view_by_introspector(request, route):\n introspector = request.registry.introspector\n route_intr = introspector.get('routes', route.name)\n\n related_intr = introspector.related(route_intr)\n if related_intr is None:\n return None\n\n for related in related_intr:\n print \"related\", related\n if related.category_name == 'views':\n view_func = related['callable']\n if isinstance(view_func, static_view):\n # Lets skip over static views\n continue\n if related['attr']:\n view_action = \".\".join([view_func.__module__, view_func.__name__, related['attr']])\n else:\n view_action = \".\".join([view_func.__module__, view_func.__name__])\n return view_action",
"def get_related_view(request):\n return request.environ.get('cone.app.related_view', None)",
"def page_views(self, *args, **kwargs):\r\n return self._get('PageViews', *args, **kwargs)",
"def getViews(self):\n return list(self.__views.keys())",
"def views(self):\n return self._views",
"def getViews(self):\n return list(self.__views)",
"def static_view_finder(viewname, **other):\n return viewname",
"def get_views(self):\n query = mssqlqueries.get_views()\n logger.info(u'Views query: %s', query)\n for tabular_result in self.execute_query(query):\n for row in tabular_result[0]:\n yield (row[0], row[1])",
"def related_view_filter():\n pass",
"def getReachableViews(self):\n raise NotImplementedError()",
"def r(request):\n return request.param",
"def get_view(self, request) -> Optional[View]:\n\n # Grab ViewAction and use sorted_actions to find first match\n sorted_actions = ViewAction.sorted_actions(self.registry)\n\n # Find the first action which matches the args\n for action, view_class in sorted_actions:\n if action.all_predicates_match(request):\n # Use dependency injection to make an instance of\n # that view class\n view_instance = inject(\n dict(), # props\n self.get_injectables(request),\n view_class,\n request=request\n )\n return view_instance\n\n # No matches, return None\n return None",
"def get_views(cohesity_client):\n views = cohesity_client.views.get_views().views\n views_list = views if views else []\n for view in views_list:\n exported_res_dict[\"Protection Views\"].append(view.name)\n return views_list",
"def getViews(self):\n raise NotImplementedError()",
"def getReachableViews(self):\n return [self]",
"def get_views(self, path, year=None, month=None, day=None, hour=None):\n return self._telegraph.method('getViews', path=path, values={\n 'year': year,\n 'month': month,\n 'day': day,\n 'hour': hour\n })",
"def getMatchingViews(self, data, info):\n raise NotImplementedError()",
"def get_sg_use_views(cluster_config):\n cluster = load_cluster_config_json(cluster_config)\n return cluster[\"environment\"][\"sg_use_views\"]",
"def getview(viewid) :\n\treturn Jikji.getinstance().getview(viewid)",
"def local_views():\n\tpass",
"def extract_channel_views(show_views_channel):\n channel,views,=show_views_channel[1]\n return (channel, views)",
"def related_view(self):\n return get_related_view(self.request)",
"def network_views():\n return 'networkview?'",
"def _get_views(work_sheet):\n ddi_view_col = work_sheet.row_values(0).index('DDI View')\n view_col = list(set(work_sheet.col_values(ddi_view_col)[1:]))\n return view_col",
"def get_viewaction(self, request) -> Optional[PredicateAction]:\n\n # This is used for nonlookup predicates such as stuff related\n # to rendering and templates. Need the registration information,\n # not just the target.\n\n # Grab ViewAction and use sorted_actions to find first match\n sorted_actions = ViewAction.sorted_actions(self.registry)\n\n # Find the first action which matches the args\n for action, view_class in sorted_actions:\n if action.all_predicates_match(request):\n # Use dependency injection to return the view action\n return action\n\n # No matches, return None\n return None"
] | [
"0.8181199",
"0.6885467",
"0.67272025",
"0.6463465",
"0.64211583",
"0.6304628",
"0.61412376",
"0.59954315",
"0.5932171",
"0.59282255",
"0.5863362",
"0.5801414",
"0.57248193",
"0.56478566",
"0.5637953",
"0.5636953",
"0.5582375",
"0.5578582",
"0.5537936",
"0.5492978",
"0.5450288",
"0.54418254",
"0.5429811",
"0.535933",
"0.53432167",
"0.5331353",
"0.5286037",
"0.5271804",
"0.52220905",
"0.52139026"
] | 0.75398153 | 1 |
getCommandcodeBegin(self) get commandcode of equal | def getCommandcode(self):
commandcode = "EQUAL ({name})({operand})".format(name=self.name, operand=self.operand) # commandcode
return commandcode | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def getCommandcode(self):\n commandcode = \"RETURN ({})\".format(self.value) # commandcode\n return commandcode",
"def get_opcode(self, code):\r\n opcode = int(str(code)[-2:])\r\n return opcode",
"def getCommandcode(self):\n commandcode = \"NOTEQUAL ({name})({operand})\".format(name=self.name, operand=self.operand) # commandcode\n return commandcode",
"def get_command(self):\n if os.name == 'posix':\n code_command = self._get_code_command_linux()\n elif os.name == 'nt':\n code_command = self._get_code_command_windows()\n command = self._build_command(code_command)\n return command",
"def symbol(self):\n if self.currCommType is A_COMMAND:\n return self.currentCommand[COMMAND_START:].strip()\n\n elif self.currCommType is L_COMMAND:\n return self.currentCommand[COMMAND_START:COMMAND_ENDS].strip()",
"def _get_code_command_linux():\n print('Use arrows (or \\'E\\', \\'S\\', \\'W\\',' +\\\n '\\'N\\' + a number) to move or \\'q\\' to give up.')\n return get_char_code.get()",
"def getChar(self,code):\r\n return chr(code)",
"def get_code(self):\n return self.code",
"def get_code(self):\n return self.code",
"def get_code(self):\n return self.code",
"def get_code(self):\n return self.code",
"def code(self):\n return self._code",
"def code(self):\n return self._code",
"def code(self):\n return self._code",
"def code(self):\n return self._code",
"def comp(self, mnemonic):\r\n return self._comp_code[mnemonic]",
"def comp(self):\n if self.currCommType is C_COMMAND:\n if EQU in self.currentCommand:\n return self.currentCommand.\\\n split(EQU)[COMP_JUMP].\\\n split(SEMIC)[COMP].strip()\n\n else:\n return self.currentCommand.split(SEMIC)[0].strip()",
"def code(self):\n\n return self._code or self._default_code",
"def _get_bin_key(self, command):\n\t\treturn self.remote.encode_button(command)",
"def get_command(self):\n return self.c_dict['COMMAND']",
"def code(self) -> pulumi.Input['CanaryCodeArgs']:\n return pulumi.get(self, \"code\")",
"def code(self) -> str:\n return self._code",
"def code(self) -> str:\n return self._code",
"def code(self):\n return self._getCode()",
"def _get_code_command_windows():\n while 1:\n print('Use \\'E\\', \\'S\\', \\'W\\', \\'N\\'' +\\\n '[+ 1-9] to move. Or \\'q\\' to give up.')\n hitkeys = input()\n if len(hitkeys) > 0:\n char_ = hitkeys[0].upper()\n if char_ in 'ESNW':\n if len(hitkeys) == 2:\n num_ = hitkeys[1]\n if num_ in '123456789':\n return char_ + num_\n else:\n return char_ + '1'\n elif char_ == 'Q':\n return 'end'",
"def Code(self):\n if self.force_auto_sync:\n self.get('Code')\n return self._Code",
"def code(self) -> \"str\":\n return self._attrs.get(\"code\")",
"def read_opcode(self) -> int:\n\n offset = self.current_address - self.STARTING_ADDRESS\n\n if self.insight:\n self.insight.opcode(self.rom_data, offset)\n\n return self.rom_data[offset] << 8 | self.rom_data[offset + 1]",
"def code(self):\n return struct.unpack('<B', self.pkt.payload[0:1])[0]",
"def code(self) -> int:\n return self._code"
] | [
"0.7032623",
"0.6300401",
"0.6291931",
"0.6258772",
"0.6234073",
"0.62185633",
"0.60434276",
"0.60129374",
"0.60129374",
"0.60129374",
"0.60129374",
"0.5997079",
"0.5997079",
"0.5997079",
"0.5997079",
"0.59708613",
"0.59281605",
"0.5927773",
"0.59086716",
"0.5907003",
"0.58633125",
"0.58544445",
"0.58544445",
"0.5833066",
"0.57381546",
"0.573437",
"0.570221",
"0.5687501",
"0.56767136",
"0.5656031"
] | 0.7237698 | 0 |
getCommandcode(self) get commandcode of notequal | def getCommandcode(self):
commandcode = "NOTEQUAL ({name})({operand})".format(name=self.name, operand=self.operand) # commandcode
return commandcode | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def getCommandcode(self):\n commandcode = \"EQUAL ({name})({operand})\".format(name=self.name, operand=self.operand) # commandcode\n return commandcode",
"def getCommandcode(self):\n commandcode = \"RETURN ({})\".format(self.value) # commandcode\n return commandcode",
"def get_opt_code(self, command):\n if \"code\" in self.command_dict[\"commands\"][command].keys():\n return self.command_dict[\"commands\"][command][\"code\"]\n else:\n return CommandDict.DEFAULT_OPT_CODE",
"def get_command(self):\n if os.name == 'posix':\n code_command = self._get_code_command_linux()\n elif os.name == 'nt':\n code_command = self._get_code_command_windows()\n command = self._build_command(code_command)\n return command",
"def get_opcode(self, code):\r\n opcode = int(str(code)[-2:])\r\n return opcode",
"def get_command(self):\n return self.c_dict['COMMAND']",
"def _get_bin_key(self, command):\n\t\treturn self.remote.encode_button(command)",
"def get_code(self):\n return self.code",
"def get_code(self):\n return self.code",
"def get_code(self):\n return self.code",
"def get_code(self):\n return self.code",
"def _get_code_command_linux():\n print('Use arrows (or \\'E\\', \\'S\\', \\'W\\',' +\\\n '\\'N\\' + a number) to move or \\'q\\' to give up.')\n return get_char_code.get()",
"def get_command(self, command):\n\t\tshutit_global.shutit_global_object.yield_to_draw()\n\t\tif command in ('md5sum','sed','head'):\n\t\t\tif self.get_current_shutit_pexpect_session_environment().distro == 'osx':\n\t\t\t\treturn 'g' + command\n\t\treturn command",
"def get_cmd(self):\n return self.cmd",
"def _getCommand(self, cmd):\n try:\n cmd_str = cmd.decode('utf-8')\n return getattr(self, 'do_' + cmd_str, None)\n except:\n return None",
"def getCommand(self):\n return self.__cmd",
"def code(self):\n return self._getCode()",
"def code(self):\n\n return self._code or self._default_code",
"def code(self):\n return self._code",
"def code(self):\n return self._code",
"def code(self):\n return self._code",
"def code(self):\n return self._code",
"def get_cmd(self, command):\n return self.commands[command][\"cmd\"]",
"def commandType(self):\n if self.currentCommand.startswith(AT) and len(self.currentCommand) > 1:\n return A_COMMAND\n\n elif self.currentCommand.startswith(LBRKT):\n return L_COMMAND\n\n elif EQU in self.currentCommand or SEMIC in self.currentCommand:\n return C_COMMAND",
"def get_command(self):\n return self.command",
"def code(self) -> str:\n return self._code",
"def code(self) -> str:\n return self._code",
"def get_code(self):\n if self.code is None:\n raise KGTKException(f'missing code object for SQL function: {self.name}')\n return self.code",
"def code(self) -> \"str\":\n return self._attrs.get(\"code\")",
"def comp(self):\n if self.currCommType is C_COMMAND:\n if EQU in self.currentCommand:\n return self.currentCommand.\\\n split(EQU)[COMP_JUMP].\\\n split(SEMIC)[COMP].strip()\n\n else:\n return self.currentCommand.split(SEMIC)[0].strip()"
] | [
"0.7822171",
"0.7172279",
"0.6577299",
"0.6502084",
"0.63764507",
"0.624266",
"0.61364263",
"0.6077417",
"0.6077417",
"0.6077417",
"0.6077417",
"0.60731703",
"0.597658",
"0.593947",
"0.5884544",
"0.587268",
"0.58147097",
"0.57888204",
"0.57867324",
"0.57867324",
"0.57867324",
"0.57867324",
"0.57799417",
"0.57360864",
"0.56969094",
"0.5691875",
"0.5691875",
"0.5635916",
"0.56149346",
"0.5606258"
] | 0.72049737 | 1 |
Default label to variable sanitizer | def default_label_sanitizer(s: str) -> str:
out: str = unidecode.unidecode(s)
# Remove invalid characters
out = re.sub(r"[^0-9a-zA-Z_]", "_", out)
# Remove leading characters until we find a letter or underscore
out = re.sub(r"^[^a-zA-Z_]+", "_", out)
return out | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def normalisesym(self, label):\n return label",
"def label(cls) -> str:\n return \"!lobotomy.inject_string\"",
"def labelit(self, varname):\n \n if not varname:\n return \"\"\n return self.vardict[varname].VariableLabel or varname",
"def _sanitize(label):\n return re.sub(r'(\\W+| )', '', label)",
"def ex_label(self,label,argl):\n if len(label) > 0 and label[0] != '_':\n return label\n comment = ''\n for i in argl:\n phrase = ''\n if i == 'l':\n phrase = label\n elif i in self._labels.keys():\n phrase = self._labels[i]\n comment += phrase\n return comment",
"def label(self):\n return ''",
"def label(self):\n return '?'",
"def _assign_label(self, format):\n cht_tmpl = self.out_label_tmpl\n return cht_tmpl.substitute(format)",
"def Label(self) -> str:",
"def translate_label(label):\n return invalid_re.sub('_', label)",
"def __init__(__self__, *,\n label_name: pulumi.Input[str]):\n pulumi.set(__self__, \"label_name\", label_name)",
"def setLabel(*args):",
"def setLabel(*args):",
"def setLabel(*args):",
"def setLabel(*args):",
"def setLabel(*args):",
"def label(cls) -> str:\n return \"!lobotomy.unknown\"",
"def label(self, value):\n\t\tself._label = value",
"def _collected_label(collect, label):\n if not collect.__name__.startswith('<'):\n return label + ' ' + collect.__name__\n else:\n return label",
"def label_variable(self, varname, label):\n if not isinstance(label, str):\n raise TypeError(\"variable label should be a string\")\n names = self._find_vars(varname, empty_ok=False, single=True)\n index = self._varlist.index(names[0])\n label = label[:80]\n if self._vlblist[index] == label:\n return\n self._vlblist[index] = label\n self._changed = True",
"def getLabel(*args):",
"def getLabel(*args):",
"def getLabel(*args):",
"def label(self) -> str: # Enforcing every node defines a label\n pass",
"def _set_label(self, input_label):\n self.label = input_label\n return self.label",
"def label(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"label\")",
"def label(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"label\")",
"def label(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"label\")",
"def label(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"label\")",
"def label(self, value: str):\n self._label = value"
] | [
"0.69953954",
"0.64760643",
"0.6292452",
"0.6212991",
"0.61776036",
"0.6132622",
"0.6126845",
"0.6105335",
"0.6084726",
"0.6064179",
"0.6062096",
"0.6052943",
"0.6052943",
"0.6052943",
"0.6052943",
"0.6052943",
"0.60412693",
"0.6037096",
"0.59761727",
"0.5971269",
"0.59562",
"0.59562",
"0.59562",
"0.5943569",
"0.5933562",
"0.592001",
"0.592001",
"0.592001",
"0.592001",
"0.5915052"
] | 0.68001777 | 1 |
Default form field formatter. | def default_field_formatter(variable_name: str, field: Field) -> str:
return "{{ " + f"form.{variable_name}" + " }}" | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def default_formatter(self, data):\n return data",
"def get_formatter(self, **kwargs):\n config = dict([\n (attr, getattr(self, attr))\n for attr in [\n \"include_sign\",\n \"group_with_commas\",\n \"num_decimal_places\",\n ]\n ])\n config.update(kwargs)\n return \"\".join([\n \"{\",\n config.get(\"field_name\", \"\"),\n \":\",\n \"+\" if config[\"include_sign\"] else \"\",\n \",\" if config[\"group_with_commas\"] else \"\",\n \".\", str(config[\"num_decimal_places\"]), \"f\",\n \"}\",\n ])",
"def _default_value_formatter(human_readable, field_limit, encoding='utf-8'):\n fields = {}\n if human_readable:\n fields = {\n eliot_ns(u'timestamp'): format.timestamp(\n include_microsecond=False),\n eliot_ns(u'duration'): format.duration(),\n }\n return compose(\n # We want tree-format to handle newlines.\n partial(format.escape_control_characters, overrides={0x0a: u'\\n'}),\n partial(format.truncate_value,\n field_limit) if field_limit else identity,\n format.some(\n format.fields(fields),\n format.text(),\n format.binary(encoding),\n format.anything(encoding)))",
"def format(self):\n ...",
"def format_field(self, value, format_spec):\n if value is None:\n return format(value)\n else:\n return super(NoneFormatter, self).format_field(value, format_spec)\n if value is None:\n return format(value)\n else: raise e",
"def __str__(self):\n #Format data from default fields\n template = \"{number:4}|{rep:4}|{time:5}{priority:+2}|\" \\\n \"{record_type:8}|{name:17}\"\n default_fields = template.format(**self)\n \n #Format data from custom fields\n custom_field_list = []\n for label in self.custom_labels:\n custom_field_list.append(\"|{:17}:{!s:<5}\".format(label,\n self[label]))\n custom_fields = \"\".join(custom_field_list)\n \n return default_fields + custom_fields",
"def get_format(self):\n pass",
"def format(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"format\")",
"def format( self ) :\n\n return( self.__format )",
"def get_format_attrs(self, name, field, alt_field_info={}):\n # important_props = ('initial', 'autofocus', 'widget')\n if name in alt_field_info:\n field = deepcopy(field)\n for prop, value in alt_field_info[name].items():\n setattr(field, prop, value)\n initial = field.initial\n initial = initial() if callable(initial) else initial\n attrs, result = {}, []\n if initial and not isinstance(field.widget, Textarea):\n attrs['value'] = str(initial)\n data_val = self.form.data.get(get_html_name(self.form, name), None)\n if data_val not in ('', None):\n attrs['value'] = data_val\n attrs.update(field.widget_attrs(field.widget))\n result = ''.join(f'{key}=\"{val}\" ' for key, val in attrs.items())\n if getattr(field, 'autofocus', None):\n result += 'autofocus '\n if issubclass(self.form.__class__, FormOverrideMixIn):\n # TODO: Expand for actual output when using FormOverrideMixIn, or a sub-class of it.\n result += '%(attrs)s' # content '%(attrs)s'\n else:\n result = '%(attrs)s' + result # '%(attrs)s' content\n return result",
"def get_format_opts(cls, format_=\"value\", fields=[]):\n return \" -f {0} {1}\".format(format_, \" \".join([\"-c \" + it for it in fields]))",
"def asformat(self, format):",
"def get_expected_format(self, setup):\n form = setup.pop('form', self.form)\n as_type = setup['as_type']\n setup.update(attrs='')\n alt_field_info = {}\n if issubclass(self.form_class, FormOverrideMixIn):\n size_default = form.get_overrides().get('_default_', {}).get('size', None)\n override_attrs = '' if not size_default else f'size=\"{size_default}\" '\n setup.update(attrs=override_attrs)\n alt_field_info = self.form.get_alt_field_info()\n if issubclass(self.form_class, FocusMixIn): # has method: assign_focus_field\n focused = getattr(self.form, 'given_focus', None) or getattr(self.form, 'named_focus', None)\n if not focused:\n ls = [name for name, field in self.form.fields.items()\n if not field.disabled and not isinstance(field.widget, (HiddenInput, MultipleHiddenInput))]\n focused = ls[0] if ls else None\n if focused: # Using alt_field_info to track assigning focus here, but 'autofocus' is not a field property.\n alt_field_info[focused] = alt_field_info.get(focused, {})\n alt_field_info[focused].update({'autofocus': True})\n field_formats = FIELD_FORMATS.copy()\n if issubclass(self.form_class, ComputedUsernameMixIn):\n name_for_email = form.name_for_email or form._meta.model.get_email_field() or 'email'\n name_for_user = form.name_for_user or form._meta.model.USERNAME_FIELD or 'username'\n if 'email' in field_formats:\n field_formats[name_for_email] = field_formats.pop('email')\n if 'username' in field_formats:\n field_formats[name_for_user] = field_formats.pop('username')\n order = ['first_name', 'last_name', name_for_email, name_for_user, 'password1', 'password2', ]\n form.order_fields(order)\n form_list, hidden_list = [], []\n top_errors = form.non_field_errors().copy() # If data not submitted, this will trigger full_clean method.\n if issubclass(self.form_class, FormFieldsetMixIn):\n setup['error_kwargs'] = self.make_error_kwargs(setup)\n if top_errors:\n html_args = setup['error_kwargs']['html_args']\n col_attr = ' id=\"top_errors\"'\n row_attr = ''\n data = ' '.join(top_errors)\n form_col_count = setup['error_kwargs']['form_col_count']\n error_row = form.make_headless_row(html_args, data, form_col_count, col_attr, row_attr)\n form_list.append(error_row)\n elif top_errors:\n error_row = self.error_format(as_type, top_errors, **setup.get('error_kwargs', {}))\n form_list.append(error_row)\n\n for name, field in form.fields.items():\n if isinstance(field.widget, (HiddenInput, MultipleHiddenInput, )):\n hide_re = DEFAULT_RE.copy()\n hide_re.update({'name': name, 'input_type': 'hidden', 'end_tag': ''})\n hide_re['attrs'] = f'value=\"{field.initial}\" '\n txt = BASE_INPUT % hide_re\n hidden_list.append(txt) # TODO: Account for hidden field errors being added to top errors.\n continue\n cur_replace = DEFAULT_RE.copy()\n cur_replace.update({'name': name, 'pretty': field.label or pretty_name(name)})\n cur_replace['required'] = REQUIRED if field.required else ''\n if field.disabled:\n cur_replace['required'] += 'disabled '\n cur_replace['attrs'] = self.get_format_attrs(name, field, alt_field_info)\n if isinstance(field, EmailField) and name not in field_formats:\n cur_replace['input_type'] = 'email'\n elif isinstance(field.widget, Textarea):\n cur_replace['initial'] = getattr(field, 'initial', None) or ''\n attrs = ''\n cols = field.widget.attrs.get('cols', None)\n rows = field.widget.attrs.get('rows', None)\n if cols:\n attrs += f'cols=\"{cols}\" '\n if rows:\n attrs += f'rows=\"{rows}\" '\n cur_replace['attrs'] = attrs\n field_formats[name] = AREA_TXT\n elif isinstance(field.widget, (CheckboxSelectMultiple, RadioSelect)):\n input_type = 'radio' if isinstance(field.widget, RadioSelect) else 'checkbox'\n required = REQUIRED if field.required else ''\n if isinstance(field.widget, CheckboxSelectMultiple):\n required = ''\n options_re = {'name': name, 'required': required, 'input_type': input_type}\n option_list = []\n for num, each in enumerate(field.choices):\n val, display = each\n opt_replace = options_re.copy()\n opt_replace.update({'num': str(num), 'val': str(val), 'display_choice': str(display)})\n option = OTHER_OPTION_TXT % opt_replace\n option_list.append(option)\n cur_replace['options'] = ''.join(option_list)\n field_formats[name] = RADIO_TXT if isinstance(field.widget, RadioSelect) else CHECK_TXT\n elif isinstance(field, BooleanField) or isinstance(field.widget, CheckboxInput):\n cur_replace['input_type'] = 'checkbox'\n cur_replace['attrs'] = ''\n if field.initial or form.data.get(get_html_name(form, name), None):\n cur_replace['last'] = ' checked'\n elif isinstance(field.widget, (Select, SelectMultiple)):\n option_list = []\n for num, each in enumerate(field.choices):\n val, display = each\n option = OPTION_TXT % {'val': str(val), 'display_choice': str(display)}\n option_list.append(option)\n cur_replace['options'] = ''.join(option_list)\n cur_replace['multiple'] = MULTIPLE\n if not isinstance(field.widget, SelectMultiple):\n cur_replace['multiple'] = ''\n cur_replace['required'] = ''\n field_formats[name] = SELECT_TXT\n field_error = form.errors.get(name, None)\n if field_error:\n error_string = self.error_format(as_type, field_error, **setup.get('error_kwargs', {}))\n if as_type == 'as_table':\n cur_replace['label_end'] += error_string\n elif as_type in ('as_ul', 'as_fieldset'):\n cur_replace['start_tag'] += error_string\n elif as_type == 'as_p':\n cur_replace['start_tag'] = error_string + cur_replace['start_tag']\n else:\n cur_replace['error'] = error_string\n txt = field_formats.get(name, DEFAULT_TXT) % cur_replace\n form_list.append(txt)\n str_hidden = ''.join(hidden_list)\n if len(form_list) > 0:\n last_row = form_list[-1]\n default_re = DEFAULT_RE.copy()\n default_re.update({'attrs': '%(attrs)s', 'end_tag': str_hidden + '%(end_tag)s'})\n form_list[-1] = last_row % default_re\n else:\n form_list.append(str_hidden)\n expected = ''.join(form_list) % setup\n return expected.strip()",
"def set_formatter(self, formatter):\n self.format = formatter",
"def formatted(self) -> str:\r\n ...",
"def __format__(self, format_specification=''):\n return super().__format__(format_specification=format_specification)",
"def format(self):\n return self._format",
"def alpine_field_defaults(form: forms.Form) -> str:\n # Add a default value for sortorder because that field is controlled\n # as a special case\n defaults = {\"sortorder\": 0}\n return mark_safe(\n json.dumps({**{field.name: None for field in form}, **defaults}).replace(\n '\"', \"'\"\n )\n )",
"def _get_FIELD_display(self, field):\n value = getattr(self, field.attname)\n if value is None:\n return\n template = ''\n template += '{:d}' if field.decimals == 0 else '{:.%sf}' % field.decimals\n template += ' ' if field.spaced_display else ''\n template += '{!s:s}'\n return template.format(value, field.unit)",
"def format(self) -> str:",
"def __str__(self):\n return super().formatter(\"{old}, {prefix}/{new}\")",
"def float_format(self):\n ...",
"def format_field(model, name, value):\n if value is None: return value\n t = type( getattr(model,name) )\n if t == datetime:\n return value.replace('T',' ')\n return value",
"def __format__(self, *args, **kwargs): # real signature unknown\r\n pass",
"def formfield(self, **kwargs):\n defaults = {\n 'form_class': LocalizedIntegerFieldForm\n }\n\n defaults.update(kwargs)\n return super().formfield(**defaults)",
"def initialize_formatter(config):\n if config.json: # pylint: disable=R1705\n return formatters.JsonFormatter()\n elif config.severity: # pylint: disable=R1705\n return formatters.SeverityFormatter(config.colored)\n return formatters.Formatter(config.colored)",
"def format_field_name(field_name):\n return format_value(field_name, json_api_settings.FORMAT_FIELD_NAMES)",
"def render_field(field, bulk_nullable=False, label=None):\n return {\n 'field': field,\n 'label': label or field.label,\n 'bulk_nullable': bulk_nullable,\n }",
"def format(self, *args, **kwargs) -> String:\n pass",
"def format(self):\n return self[\"format\"]"
] | [
"0.7187935",
"0.70637",
"0.6649078",
"0.6408993",
"0.64057606",
"0.6197929",
"0.61766225",
"0.6136049",
"0.61069214",
"0.60933304",
"0.6063252",
"0.60615337",
"0.603526",
"0.60306907",
"0.59651566",
"0.59344953",
"0.5922895",
"0.59220624",
"0.59166",
"0.5905437",
"0.58920133",
"0.58197737",
"0.57952887",
"0.57210743",
"0.5697781",
"0.568447",
"0.5675971",
"0.56560534",
"0.56248426",
"0.56034094"
] | 0.7441752 | 0 |
Transform a list of pairs to a list of actors. | def pairs_to_actors(pairs):
return [Actor(*pair) for pair in pairs] | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def pairs_from_list(lights):\n length = len(lights)\n half = int(length / 2)\n offset = 0\n\n centre = None\n if length % 2 == 1:\n centre = lights[half]\n offset = 1\n\n left = lights[:half]\n\n rh_start = half + offset\n right = reversed(lights[rh_start:])\n\n pairs = list(map(list, zip(left, right)))\n\n if centre:\n pairs.append([centre])\n\n return pairs",
"def get_actors(self):\n actors = [ddpg_agent.actor for ddpg_agent in self.maddpg_agent]\n return actors",
"def get_actors(self):\n actors = [ddpg_agent.actor for ddpg_agent in self.maddpg_agent]\n return actors",
"def get_actors(self):\n actors = [ddpg_agent.actor for ddpg_agent in self.maddpg_agent]\n return actors",
"def get_actors(self):\n actors = [ddpg_agent.actor for ddpg_agent in self.maddpg_agent]\n return actors",
"def actors(self) -> Iterator[Actor]:\n yield from (entity for entity in self.entities if isinstance(entity, Actor) and entity.is_alive)",
"def build_actions(list_of_tuples):\n node_dict = build_verticies(list_of_tuples)\n ACTIONS = lambda path: node_dict[path.end]\n return ACTIONS",
"def act(self, obs_all_agents, noise=0.0):\n actions_next = [agent.act(obs, noise) for agent, obs in zip(self.maddpg_agent, obs_all_agents)]\n return actions_next",
"def act(self, states: np.ndarray, eps: float = 0.0) -> List[np.ndarray]:\n actions = [\n agent.act(state.reshape(-1, 1).T, eps)\n for agent, state in zip(self.agents, states)\n ]\n return actions",
"def act(self, obs_all_agents, noise=0.0):\n actions = [agent.act(obs, noise) for agent, obs in zip(self.maddpg_agent, obs_all_agents)]\n return actions",
"def act(self, obs_all_agents, noise=0.0):\n actions = [agent.act(obs, noise) for agent, obs in zip(self.maddpg_agent, obs_all_agents)]\n return actions",
"def pairs(lst):\r\n\tfor i in range(1, len(lst), 2):\r\n\t\tyield lst[i-1], lst[i]",
"def actions(self, state):\n\n\t\tpossibleActions = []\n\n\t\tflashlightLocation = state[0]\n\n\t\t\"\"\"\n\t\t\tIf a person is on the side of the flashlight, then they can cross the bridge by themselves or \n\t\t\tthey can cross with another person who is also on their side (the side of the flashlight).\n\t\t\t-\tSo we add an action for this person crossing by themselves, and also actions for them crossing\n\t\t\t\twith other people (each of these actions is them crossing with one of these other \n\t\t\t\tpeople, making 2 of them crossing the bridge)\n\t\t\t\t\n\t\t\tNote that person i and person j crossing the bridge is the same action as person j and person i crossing, \n\t\t\tand we only want to add this action once so when determining the people that person i can cross with \n\t\t\twe look at people who come after this person i (a person j where j > i) \n\t\t\"\"\"\n\n\t\tfor personI in range(1, self.n+1): # exclude the flashlight - only traverse the peoples' locations\n\t\t\tif state[personI] == flashlightLocation: #This person can cross the bridge\n\t\t\t\taction = [personI] # This person (person i) can cross bridge on their own (with the flashlight)\n\t\t\t\tpossibleActions.append(action)\n\t\t\t\tfor personJ in range(personI+1, self.n+1):\n\t\t\t\t\tif state[personJ] == flashlightLocation: # This person (person j) can cross the bridge\n\t\t\t\t\t\taction = [personI, personJ] # person i can cross the bridge with person j (and the flashlight)\n\t\t\t\t\t\tpossibleActions.append(action)\n\n\t\treturn possibleActions",
"def build_verticies(list_of_tuples):\n result = defaultdict(list)\n for (from_node, to_node), cost in list_of_tuples:\n from_action = Action(to_node, cost)\n result[from_node].append(from_action)\n to_action = Action(from_node, cost)\n result[to_node].append(to_action)\n\n return result",
"def prepare_actors(self, object):\n actors = [\n '/api/v1/actor/{0}/'.format(actor_role.actor.id)\n for actor_role in object.actors_role.all()]\n return actors",
"def actors(self):\n return self._actors",
"def _pair2list(pair):\n members = []\n while pair:\n members.append(pair.car)\n pair = pair.cdr\n return List(members)",
"def get_joss_strategy_actions(\n opponent_moves: list, indices_to_flip: list\n) -> list:\n out = []\n for index, action in enumerate(opponent_moves):\n previous_action = opponent_moves[index - 1]\n if index == 0:\n out.append((C, action))\n elif index in indices_to_flip:\n out.append((previous_action.flip(), action))\n else:\n out.append((previous_action, action))\n return out",
"def get_all_actuators(self):\n\n actuators = []\n for part in self.parts:\n actuators = actuators + part.actuators\n\n return actuators",
"def all_pairs(elements):\n if len(elements) < 2:\n return []\n elif len(elements) == 2:\n return [(elements[0], elements[1])]\n else:\n new_pairs = []\n for elt in elements[1:]:\n new_pairs.append((elements[0], elt))\n return all_pairs(elements[1:]) + new_pairs",
"def get_target_actors(self):\n target_actors = [ddpg_agent.target_actor for ddpg_agent in self.maddpg_agent]\n return target_actors",
"def get_target_actors(self):\n target_actors = [ddpg_agent.target_actor for ddpg_agent in self.maddpg_agent]\n return target_actors",
"def get_target_actors(self):\n target_actors = [ddpg_agent.target_actor for ddpg_agent in self.maddpg_agent]\n return target_actors",
"def get_target_actors(self):\n target_actors = [ddpg_agent.target_actor for ddpg_agent in self.maddpg_agent]\n return target_actors",
"def interpose(el, seq):\n return rest(mapcat(lambda x: [el, x], seq))",
"def actions(self, state):\n num_cities = len(state) - 1 #minus 1 because start and end in same city\n actions = []\n for i in range(6):\n num1 = randrange(1, num_cities)\n num2 = randrange(1, num_cities)\n action = [num1, num2]\n actions.append(action)\n return actions",
"def build_verticies_with_estimates(list_of_tuples):\n result = defaultdict(list)\n for (from_node, to_node), cost, estimate in list_of_tuples:\n from_action = Action(to_node, cost, estimate)\n result[from_node].append(from_action)\n to_action = Action(from_node, cost, estimate)\n result[to_node].append(to_action)\n return result",
"def target_act(self, obs_all_agents, noise=0.0):\n target_actions_next = [ddpg_agent.target_act(obs, noise) for ddpg_agent, obs in\n zip(self.maddpg_agent, obs_all_agents)]\n return target_actions_next",
"def pairwise(iterable):\n a, b = itertools.tee(iterable)\n next(b, None)\n return list(zip(a, b))",
"def _list(self, exprs):\n require(exprs, len(exprs)!=0)\n result = Pair(exprs[-1], [])\n for i in reversed(exprs[:-1]):\n result = Pair(i, result)\n return result"
] | [
"0.5782867",
"0.5387652",
"0.5387652",
"0.5387652",
"0.5387652",
"0.5346582",
"0.5274743",
"0.52624696",
"0.5250782",
"0.5221431",
"0.5221431",
"0.52203953",
"0.51859194",
"0.5179453",
"0.5176561",
"0.51732695",
"0.51001984",
"0.50953776",
"0.50728834",
"0.5027792",
"0.49349657",
"0.49349657",
"0.49349657",
"0.49349657",
"0.49220803",
"0.4891464",
"0.48909017",
"0.48631805",
"0.48628867",
"0.48628333"
] | 0.846847 | 0 |
Return the hourly commit within interval according to split(). | def periodic_commit(start, length, split):
return start + split() * length | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_hourly(self):\n pass",
"def get_complete_hourly_prices(coin_symbol: str, base: str):\n all_prices = []\n delta = 0\n while True:\n answer = get_90d_of_hourly_prices(coin_symbol, base, datetime.now() - timedelta(days=delta))\n if not answer:\n break\n delta += 90\n all_prices.extend(answer)\n return tidy_up_prices(all_prices)",
"def get_hourly(self, from_currency, to_currency, limit = DEFAULT_LIMIT, aggregate = DEFAULT_AGGREGATE):\n return self.__get(HISTORY_HOUR, from_currency, to_currency, limit, aggregate)",
"def __get_split_index(df, granularity=\"day\"):\n change_flag = df[\"started_at\"].dt.date != (df[\"finished_at\"] - pd.to_timedelta(\"1s\")).dt.date\n if granularity == \"hour\":\n hour_flag = df[\"started_at\"].dt.hour != (df[\"finished_at\"] - pd.to_timedelta(\"1s\")).dt.hour\n # union of day and hour change flag\n change_flag = change_flag | hour_flag\n\n return change_flag",
"def decimal_hour(t):\n datetime = t.datetime\n result = []\n for d in datetime:\n hour = d.hour\n minute = d.minute\n second = d.microsecond / 1e6\n dec_hour = hour + (minute/60.) + (second/3600.)\n result.append(dec_hour)\n return np.array(result)",
"def interval_hours(self) -> Optional[pulumi.Input[int]]:\n return pulumi.get(self, \"interval_hours\")",
"def run_hour(self) -> int:\n return self.timestamp.hour",
"def hours(input=None):\n return get(input).hours",
"def hourly(self):\n return c.Hourly(self)",
"def convert_index_to_hour(index, time_span, remainder):\n # This needs -1 because the end hour is inclusive. For example, if the period\n # represents [2, 26), the end hour is 25.\n #\n # Index is added 1 because, in our SQL, we subtract the remainder, divide,\n # and floor. So, in order to get the original hour, we need to add 1 to the\n # index.\n return ((index + 1) * time_span) + remainder - 1",
"def finish_hour(self):\n\t\tassert len(self.values) >= 4, 'A fully formed update date is needed.'\n\t\tself.values = self.values[:4]",
"def test_get_git_commit(self):\n git_commit = get_git_commit()\n # output format: ['fafdb957049917ede565cebc58b29899f597fb5a', 'Fri Mar 29 11:09:50 2019 -0400']\n self.assertEqual(len(git_commit[0]), 40)\n self.assertEqual(len(git_commit[1].split()), 6)",
"def get_hourly_entries(df):\n df['ENTRIESn_hourly'] = (df['ENTRIESn'] - df['ENTRIESn'].shift(1)).fillna(1)\n return df",
"def test_lengthen_an_interval_to_enclose_a_month_border(self):\n self.t(\"track 20180831T220000 - 20180831T230000 foo\")\n self.t(\"lengthen @1 4h\")\n\n j = self.t.export()\n\n self.assertEqual(len(j), 1)\n self.assertClosedInterval(j[0])",
"def half_hour_ticker(*args):\n markets = fetch_markets()\n map(populate_half_hour_data, markets)\n return",
"def get_interval(interval):\n interval_list = interval.split(\"-\")\n if len(interval_list) == 1:\n return (int(interval_list[0]), int(interval_list[0])+1)\n else:\n return (int(interval_list[0]), int(interval_list[1])+1)",
"def getHours(data: Sequence[HistoryElement]) -> Sequence[int]:\r\n _checkData(data)\r\n return [x.timeStamp.hour for x in data]",
"def hour():\r\n\r\n date = datetime.datetime.now()\r\n hours = date.hour\r\n minute = date.minute\r\n\r\n return hours, minute",
"def splitCandles(data):\n\n premarket = data[(data['Time'] < datetime.time(9,30))]\n regularMarket = data[(data['Time'] > datetime.time(9, 30)) & (data['Time'] < datetime.time(16,0))]\n afterhour = data[(data['Time'] > datetime.time(16,0))]\n\n return premarket, regularMarket, afterhour",
"def _get_hours_pro_entry(time_entries):\n events = []\n for event in time_entries:\n start_time = datetime.datetime(\n date.today().year,\n date.today().month,\n date.today().day,\n event.start_at.hour,\n event.start_at.minute,\n event.start_at.second,\n )\n end_time = datetime.datetime(\n date.today().year,\n date.today().month,\n date.today().day,\n event.finish_at.hour,\n event.finish_at.minute,\n event.finish_at.second,\n )\n\n timediff = end_time - start_time\n events.append(\n {\n \"worked_hours\": round(timediff.total_seconds() / 3600, DECIMALS_HOUR),\n \"event\": event,\n }\n )\n return events",
"def get_hours():\n\n print('This program calculates fees paid per hour.Enter hour in H:m using the 24 hour format.')\n\n today = datetime.today()\n start_time = input('Enter time started in H:m format: ')\n end_time = input('Enter time ended in H:m format: ')\n task = input('Enter task name: ')\n description = input('Give a brief description of task: ')\n\n # start_time_str = start_time\n start_time = datetime.strptime(start_time, '%H:%M').time()\n end_time = datetime.strptime(end_time, '%H:%M').time()\n\n # print(start_time_object, end_time_object)\n\n time_elapsed = datetime.combine(\n datetime.today(), end_time) - datetime.combine(date.today(), start_time)\n total_seconds = time_elapsed.seconds\n # print(total_seconds)\n hours = total_seconds/3600\n\n print('Number of hours spent on task is ', hours, 'hours.')\n\n get_price(hours)\n save_to_csv(today, task, description, hours, start_time, end_time)",
"def calculate_hours(time):\n return int(time / 3600)",
"def hours_in(sec):\r\n return int(sec//3600)",
"def hour(self) -> int:\n return pulumi.get(self, \"hour\")",
"def get_90d_of_hourly_prices(coin_symbol: str, base: str, to_timestamp: datetime):\n coin_symbol = coin_symbol.lower()\n base = base.lower()\n coin_id = symbol_id_map[coin_symbol]\n delta = timedelta(days=90)\n res = cg.get_coin_market_chart_range_by_id(coin_id, base, int((to_timestamp-delta).timestamp()), int(to_timestamp.timestamp()))\n return res['prices']",
"def test_split_ranges(self):\n start = datetime.utcnow() - pd.Timedelta(\"5H\")\n end = datetime.utcnow() + pd.Timedelta(\"5min\")\n delta = pd.Timedelta(\"1H\")\n\n ranges = QueryProvider._calc_split_ranges(start, end, delta)\n self.assertEqual(len(ranges), 5)\n self.assertEqual(ranges[0][0], start)\n self.assertEqual(ranges[-1][1], end)\n\n st_times = [start_tm[0] for start_tm in ranges]\n for end_time in (end_tm[1] for end_tm in ranges):\n self.assertNotIn(end_time, st_times)\n\n end = end + pd.Timedelta(\"20min\")\n ranges = QueryProvider._calc_split_ranges(start, end, delta)\n self.assertEqual(len(ranges), 5)\n self.assertEqual(ranges[0][0], start)\n self.assertEqual(ranges[-1][1], end)",
"def parse_hours(self, hours):\n o = OpeningHours()\n ranges = hours.split(\",\")\n for range in ranges:\n pattern = r\"(.{3})[-&](.{3})\\s([\\d:]+)-([\\d:]+)\"\n start_day, end_day, start_time, end_time = re.search(pattern, range.strip()).groups()\n if \":\" not in start_time:\n start_time += \":00 AM\"\n if \":\" not in end_time:\n end_time += \":00 PM\"\n for day in DAY_ORDER[DAY_ORDER.index(start_day) : DAY_ORDER.index(end_day) + 1]:\n o.add_range(\n day=DAY_MAPPING[day],\n open_time=start_time,\n close_time=end_time,\n time_format=\"%I:%M %p\",\n )\n return o.as_opening_hours()",
"def running_custom_hour(arg):\n pass",
"def test_start_end_hour():\n # sh = None\n # eh = None\n # data = None\n # result = makesky.start_end_hour(sh, eh, data)\n pass",
"def get_hour(time_index):\n return np.array(time_index.hour).reshape(-1,1)"
] | [
"0.5435816",
"0.5409003",
"0.53277653",
"0.52740836",
"0.5237635",
"0.5216642",
"0.52152014",
"0.51716673",
"0.51509416",
"0.5150764",
"0.51459396",
"0.51287174",
"0.5128181",
"0.5123661",
"0.51183033",
"0.5014516",
"0.49912217",
"0.4985853",
"0.49793667",
"0.4973036",
"0.4963653",
"0.49569276",
"0.49429324",
"0.4937126",
"0.49350157",
"0.4927042",
"0.49142355",
"0.4906774",
"0.4897215",
"0.48800647"
] | 0.58374655 | 0 |
Generate message according to ticket and phase. | def message_of(cfg, ticket, phase):
return cfg["message_template"] % (ticket, text(cfg, phase)) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def generate_message_tgs(info, ticket_tgs, client_addr):\n c_v_session_key = info.prepend_length(info.generate__des_key())\n AD_C = info.prepend_length(client_addr[0] + \":\" + str(client_addr[1]))\n ID_C = info.prepend_length(info.ID_C)\n ID_V = info.prepend_length(info.ID_V)\n Lifetime4 = info.prepend_length(info.Lifetime4)\n timestamp = info.prepend_length(str(int(time.time())))\n ticket_contents = c_v_session_key + ID_C + AD_C + ID_V + timestamp + Lifetime4\n info.read_des_key(\"keys/key_v.txt\")\n ticket_v = info.prepend_length(info.encrypt_message(ticket_contents).decode('UTF-8'))\n info.set_des_key(bytes(ticket_tgs[0], 'UTF-8'))\n message_contents = c_v_session_key + ID_V + timestamp + ticket_v\n message_as = info.encrypt_message(message_contents)\n return message_as",
"def generate_message(ctx, question, answer):\n return preamble.format(channel=rules_channel(ctx).id) + question + answer",
"def _tstep_msg(fem: BDF,\n subcase: Subcase,\n tstep_id: int,\n tstep_type: str='') -> str:\n msg = (\n 'tstep%s_id=%s\\n'\n 'tsteps=%s\\n'\n 'tstepnls=%s\\n'\n #'tstep1s=%s\\n'\n 'subcase:\\n%s' % (\n tstep_type, tstep_id,\n str(fem.tsteps),\n str(fem.tstepnls),\n #str(fem.tstep1s),\n str(subcase))\n )\n return msg",
"def generate_challenge(self):\n totp = self.totp_obj()\n token = format(totp.token(), '06d')\n message = settings.OTP_TWILIO_TOKEN_TEMPLATE.format(token=token)\n\n if settings.OTP_TWILIO_NO_DELIVERY:\n logger.info(message)\n else:\n self._deliver_token(message)\n\n challenge = settings.OTP_TWILIO_CHALLENGE_MESSAGE.format(token=token)\n\n return challenge",
"def generate_challenge(self):\n totp = self.totp_obj()\n token = format(totp.token(), '06d')\n\n if hasattr(self, 'OTP_AMAZON_SNS_TOKEN_TEMPLATE'):\n # This allows upstream to set the token template on a per device\n # basis. An use case for this could be allowing every user's\n # organization to customize messages\n tpl = self.OTP_AMAZON_SNS_TOKEN_TEMPLATE\n else:\n tpl = settings.OTP_AMAZON_SNS_TOKEN_TEMPLATE\n\n message = tpl.format(token=token)\n if settings.OTP_AMAZON_SNS_NO_DELIVERY:\n logger.info(message)\n else:\n self._deliver_token(message)\n\n challenge = settings.OTP_AMAZON_SNS_CHALLENGE_MESSAGE.format(token=token)\n\n return challenge",
"def issue( self ):\n\n self.state.issueDate = \"%d\" % time.time()\n\n # Encrypt the protocol state.\n aes = AES.new(self.symmTicketKey, mode=AES.MODE_CBC, IV=self.IV)\n state = repr(self.state)\n assert (len(state) % AES.block_size) == 0\n cryptedState = aes.encrypt(state)\n\n # Authenticate ticket name, IV and the encrypted state.\n hmac = HMAC.new(self.hmacTicketKey, self.IV + \\\n cryptedState, digestmod=SHA256).digest()\n\n ticket = self.IV + cryptedState + hmac\n\n log.debug(\"Returning %d-byte ticket.\" % (len(self.IV) +\n len(cryptedState) + len(hmac)))\n\n return ticket",
"def _create_message(self, msg):\n head = msg[\"head\"]\n body = msg[\"body\"]\n body = body.format(**self.data)\n length = len(body)\n head = head.format(length=length, **self.data)\n return head + body",
"def remote_getPhase(phase):",
"def generateMessage(self, frequency):\n\t\t# make sure all entries for GCDC communication are here\n\n\t\t#messages sent at 25 Hz\n\t\tmessage_dict = dict()\n\t\tmessage_dict['header']='header'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#id 1 header\n\t\t\t\t\t\t\t\t\t\t\t#might be part of the header?\n\t\tmessage_dict['message_id'] = hash(message_dict['time'])\n\t\tmessage_dict['vehicle_id'] = self.vehicle.id\t\t\t\t\t\t\t\t\t\t\t\t#id 3 Station ID\n\t\tmessage_dict['station_type']=5\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#id 4 unknown(0), pedestrian(1), cyclist(2),moped(3), motorcycle(4), passengerCar(5), bus(6), lightTruck(7),heavyTruck(8), trailer(9), specialVehicles(10), tram(11),\n\n\n\t\tmessage_dict['vehicle_length'] = self.vehicle.length\t\t\t\t\t\t\t\t\t\t#id 6\n\t\tmessage_dict['vehicle_rear_axle_location']=0\t\t\t\t\t\t\t\t\t\t\t\t\t#id 7\n\t\tmessage_dict['vehicle_width'] = self.vehicle.width\t\t\t\t\t\t\t\t\t\t\t#id 8\n\t\tmessage_dict['controller_type']=self.supervisory.type_controller\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#id 9\n\t\tmessage_dict['vehicle_response_time_constant']=0\t\t\t\t\t\t\t\t\t\t\t\t#id 10\n\t\tmessage_dict['vehicle_response_time_delay']=0\t\t\t\t\t\t\t\t\t\t\t\t#id 11\n\t\tmessage_dict['reference_position']=0\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#id 12\n\t\t#if hasattr(self.vehicle, 'bodies_dict'):\n\t\t#\tmessage_dict['x'] = self.vehicle.bodies_dict[self.vehicle.id].x\t\t\t\t\t\t\t\t\t#reference positions probably\n\t\t#\tmessage_dict['y'] = self.vehicle.bodies_dict[self.vehicle.id].y\n\t\tmessage_dict['heading']=0\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#id 13\n\t#\t\tmessage_dict['speed'] = self.vehicle.bodies_dict[self.vehicle.id].commands['throttle']\t\t#id 14 speed =velocity\n\t#\tmessage_dict['yaw_rate'] = self.vehicle.yaw\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#id 15\n\t\tmessage_dict['long_vehicle_acc']=0\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#id 16\n\t\tmessage_dict['desired_long_vehicle_acc']=0\t\t\t\t\t\t\t\t\t\t\t\t\t#id 17\n\t\tmessage_dict['MIO_id']=self.supervisory.MIO_id\t\t\t\t\t\t\t\t\t\t#id 18 Most Iportant Object in front needs to be defined in supervisorymodule\n\t\tmessage_dict['MIO_range']=self.supervisory.MIO_range\t\t\t\t\t\t\t\t#id 19\n\t\tmessage_dict['MIO_bearing']=self.supervisory.MIO_bearing\t\t\t\t\t\t\t#id 20\n\t\tmessage_dict['MIO_range_rate']=self.supervisory.MIO_range_rate\t\t\t\t\t\t#id 21 velocity of MIO\n\t\tmessage_dict['time_headway']=self.supervisory.time_headway\t\t\t\t\t\t\t#id 22 time to vehicle in front\n\t\tmessage_dict['cruise_speed']=self.supervisory.cruise_speed\t\t\t\t\t\t\t#id 23 nominal speed of platoon\n\t\tmessage_dict['travelled_distance_CZ']=self.supervisory.travelled_CZ\t\t\t\t#id 32\n\t\tmessage_dict['new_bwd_pair_partner'] = self.vehicle.new_bwd_pair_partner\n\t\tmessage_dict['new_fwd_pair_partner'] = self.vehicle.new_fwd_pair_partner\n\t\tmessage_dict['platooned_vehicle'] = self.vehicle.platooned_vehicle\n\n\t\tif frequency==1:\n\t\t\t#messages sent with 1Hz\n\t\t\tmessage_dict['vehicle_role']=0\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#id 5 0 deafault, 6 emergency\n\t\t\tmessage_dict['merge_request_flag']=self.supervisory.merge_flag_request\t\t\t#id 24\n\t\t\tmessage_dict['STOM']=self.supervisory.STOM\t\t\t\t\t\t\t\t\t\t#id 25\n\t\t\tmessage_dict['merging_flag']=self.supervisory.merging_flag\t\t\t\t\t\t#id 26\n\t\t\tmessage_dict['fwd_pair_partner'] = self.vehicle.fwd_pair_partner\t\t\t\t\t\t\t#id 27\n\t\t\tmessage_dict['bwd_pair_partner'] = self.vehicle.bwd_pair_partner\t\t\t\t\t\t\t#id 28\n\t\t\tmessage_dict['tail_vehicle_flag'] = self.vehicle.tail_vehicle\t\t\t\t\t#id 29\n\t\t\tmessage_dict['head_vehicle_flag'] = self.vehicle.platoon_leader\t\t\t\t\t#id 20\n\t\t\tmessage_dict['platoon_id'] = self.supervisory.platoon_id\t\t\t\t\t\t#id 31\n\t\t\tmessage_dict['intention'] =self.supervisory.intention\t\t\t\t\t\t\t#id 33\n\t\t\tmessage_dict['lane_entering_CZ'] = self.supervisory.lane_entering_CZ\t\t\t#id 34\n\t\t\tmessage_dict['intersection_vehicle_counter'] = self.supervisory.intersection_vehicle_counter #id 35\n\t\t\t#message_dict['pair_acknowledge_flag'] = self.supervisory.pair_acknowledge_flag\t#id 36 #currently not used in GCDC\n\t\t\tmessage_dict['participants_ready'] = True\t\t\t\t\t\t\t\t\t\t\t\t\t#id 41 Not really used\n\t\t\tmessage_dict['start_scenario'] = True\t\t\t\t\t\t\t\t\t\t\t\t\t\t# id 42\n\t\t\tmessage_dict['EoS'] = False\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#id 43\n\n\t\treturn message_dict",
"def _make_totp(self):\n secret = struct.pack('> Q', int(time.time()) / DEFAULT_STEP).ljust(64, chr(0x0))\n response = self.yk.challenge_response(secret, slot=self.slot.get())\n # format with appropriate number of leading zeros\n fmt = '%.' + str(self.digits.get()) + 'i'\n totp_str = fmt % (yubico.yubico_util.hotp_truncate(response, length=self.digits.get()))\n return totp_str",
"def getPhase(phase):",
"def create_action_msg(self, action):\n raise NotImplementedError(\"Don't know how to translate the action to a msg\")",
"def _create_msg(self, tr_id, i_triples, i_type, r_triples, r_type, confirm):\n params = SSAP_UPDATE_PARAM_TEMPLATE % (str(i_type).upper(),\n str(i_triples),\n str(r_type).upper(),\n str(r_triples),\n str(confirm).upper())\n tmp = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS),\n self.tr_type, str(tr_id), params)\n return tmp",
"def do_jira_case_commit_message(self, arg):\n cases = [(issue.key, issue.fields.summary, self.jira_url() + \"/browse/\" + issue.key) for issue in self.get_open_issues()]\n msg = \"\"\"\n--------------------------------------------------------------------\n[{}] {}\n \n<msg>\n \n{}\n-------------------------------------------------------------------- \n \"\"\"\n for case in cases:\n print(msg.format(case[0], case[1], case[2]))",
"def _create_msg(self, tr_id, payload, confirm, expire_time, encoding):\n tmp = [\"<SSAP_message><transaction_type>INSERT</transaction_type>\",\n \"<message_type>REQUEST</message_type>\"]\n tmp.extend([\"<transaction_id>\", str(tr_id), \"</transaction_id>\"])\n tmp.extend([\"<node_id>\", str(self.node_id), \"</node_id>\"])\n tmp.extend([\"<space_id>\", str(self.targetSS), \"</space_id>\"])\n tmp.extend(['<parameter name=\"insert_graph\" encoding=\"%s\">' % encoding.upper(),\n str(payload), \"</parameter>\"])\n tmp.extend(['<parameter name = \"confirm\">',\n str(confirm).upper(),\n \"</parameter>\",\n \"</SSAP_message>\"])\n return \"\".join(tmp)",
"def _get_cbend_msg(is_stress, is_mag_phase, is_sort1):\n\n if is_stress:\n stress_strain = ' S T R E S S E S I N B E N D E L E M E N T S ( C B E N D )'\n else:\n stress_strain = ' S T R A I N S I N B E N D E L E M E N T S ( C B E N D )'\n\n assert is_sort1 is True\n sort1 = ' ELEMENT-ID GRID END ANG. SXC SXD SXE SXF S-MAX S-MIN M.S.-T M.S.-C\\n'\n msg = [\n stress_strain,\n ' CIRC.',\n sort1,\n ]\n #'0 6901 6901 A 0 4.372282E-16 -5.960465E-15 0.0 0.0 4.372282E-16 -5.960465E-15 '\n #' 6902 B 0 -6.533992E-15 5.000001E-07 -5.000000E-13 -5.000000E-13 5.000001E-07 -5.000000E-13 -6.0E-01 6.0E+05'\n\n #if is_sort1:\n #msg.append(' ELEMENT-ID GRID END ANG. C D E F\\n')\n #else:\n #msg.append(' FREQUENCY GRID END ANG. C D E F\\n')\n return msg",
"def _create_msg(self, tr_id, triples, type, confirm):\n params = SSAP_REMOVE_PARAM_TEMPLATE % (str(type).upper(),\n str(triples),\n str(confirm).upper())\n tmp = SSAP_MESSAGE_TEMPLATE % (str(self.node_id), str(self.targetSS),\n self.tr_type, str(tr_id), params)\n return tmp",
"def publish(self):\n msg = PolynomialTrajectory()\n\n if self.trajectory_constructed == True: \n t = time.time()-self.traj_t0\n\n if t <= self.seg_times[-1]: \n segment = map(lambda x:x > t, self.seg_times).index(True)\n else: \n segment = self.no_of_segments; t = self.seg_times[-1]\n \n rospy.loginfo('the value of t and segment is:%f, %d', t, segment)\n #rospy.loginfo('segment times are:%f, %f, %f, %f, %f, %f', self.segment_times[0], \\\n #self.segment_times[1], self.segment_times[2], self.segment_times[3], self.segment_times[4], self.segment_times[5])\n p1 = self.pc_x; p2 = self.pc_y; p3 = self.pc_z\n N = self.N+1\n p1 = [p1[i:i + N] for i in range(0, len(p1), N)]\n [i.reverse() for i in p1]\n \n p2 = [p2[i:i + N] for i in range(0, len(p2), N)]\n [i.reverse() for i in p2]\n \n p3 = [p3[i:i + N] for i in range(0, len(p3), N)]\n [i.reverse() for i in p3]\n xx = np.poly1d(p1[segment-1]); vx = np.polyder(xx, 1); ax = np.polyder(xx, 2)\n yy = np.poly1d(p2[segment-1]); vy = np.polyder(yy, 1); ay = np.polyder(yy, 2)\n zz = np.poly1d(p3[segment-1]); vz = np.polyder(zz, 1); az = np.polyder(zz, 2)\n \n msg.header.stamp = rospy.Time.now()\n msg.pdes.x = xx(t); msg.pdes.y = yy(t); msg.pdes.z = zz(t)\n msg.vdes.x = vx(t); msg.vdes.y = vy(t); msg.ades.z = vz(t)\n msg.ades.x = ax(t); msg.ades.y = ay(t); msg.ades.z = az(t)\n msg.ddes.x = 1; msg.ddes.y = 0; msg.ddes.z = 0\n msg.controller = 0\n \n self.pub.publish(msg)\n\n else: \n rospy.loginfo('no goal is published yet')",
"def prepare_ticket(self, req, ticket, fields, actions):",
"def print_phase_header(phase: str) -> None:\n print(f'\\n#### {phase.upper()} PHASE ####\\n')",
"def build_report(self, msg=''):\n\t\tshutit_global.shutit_global_object.yield_to_draw()\n\t\ts = '\\n'\n\t\ts += '################################################################################\\n'\n\t\ts += '# COMMAND HISTORY BEGIN ' + shutit_global.shutit_global_object.build_id + '\\n'\n\t\ts += self.get_commands()\n\t\ts += '# COMMAND HISTORY END ' + shutit_global.shutit_global_object.build_id + '\\n'\n\t\ts += '################################################################################\\n'\n\t\ts += '################################################################################\\n'\n\t\ts += '# BUILD REPORT FOR BUILD BEGIN ' + shutit_global.shutit_global_object.build_id + '\\n'\n\t\ts += '# ' + msg + '\\n'\n\t\tif self.build['report'] != '':\n\t\t\ts += self.build['report'] + '\\n'\n\t\telse:\n\t\t\ts += '# Nothing to report\\n'\n\t\tif 'container_id' in self.target:\n\t\t\ts += '# CONTAINER_ID: ' + self.target['container_id'] + '\\n'\n\t\ts += '# BUILD REPORT FOR BUILD END ' + shutit_global.shutit_global_object.build_id + '\\n'\n\t\ts += '###############################################################################\\n'\n\t\ts += '# INVOKING COMMAND WAS: ' + sys.executable\n\t\tfor arg in sys.argv:\n\t\t\ts += ' ' + arg\n\t\ts += '\\n'\n\t\ts += '###############################################################################\\n'\n\t\treturn s",
"def _generate_commit(\n self, msg: Optional[str] = None, author: Optional[str] = None\n ) -> dict:\n if author:\n mes_author = author\n else:\n mes_author = self._author\n if not msg:\n msg = f\"Commit via python client {__version__}\"\n ci = {\"commit_info\": {\"author\": mes_author, \"message\": msg}}\n return ci",
"def _get_cbend_msg(is_mag_phase, is_sort1):\n if is_mag_phase:\n raise NotImplementedError()\n else:\n realimag_magphase = ' (REAL/IMAGINARY)'\n\n msg = [\n ' C O M P L E X S T R E S S E S I N B E N D E L E M E N T S ( C B E N D ) ',\n realimag_magphase,\n ' CIRC. LOCATION LOCATION LOCATION LOCATION',\n ]\n if is_sort1:\n msg.append(' ELEMENT-ID GRID END ANG. C D E F\\n')\n else:\n msg.append(' FREQUENCY GRID END ANG. C D E F\\n')\n return msg",
"def message(self, text):\n\n if type(text) in (bytes, str):\n T = text\n else:\n # list probably:\n T = '\\n'.join(text)\n print(('-'*60))\n print(T)\n print(('='*60))",
"def Ticket(ticket):\n try:\n data = ticket_module.verify(ticket)\n name = data['slivers'][0]['name']\n if data != None:\n deliver_ticket(data)\n logger.log('api_calls: Ticket delivered for %s' % name)\n Create(database.db.get(name))\n except Exception, err:\n raise xmlrpclib.Fault(102, 'Ticket error: ' + str(err))",
"def build_pose_stamped_msg(self):\n \n # Hand first\n ps_msg = PoseStamped()\n ps_msg.header.stamp = rospy.Time.now()\n ps_msg.header.frame_id = FRAME_ID\n \n if not DEBUG_TEST:\n position = self.hand.palm_position\n\n # Set position values in the message\n for j, attr in enumerate(POS_ATTRIBUTES):\n val = getattr(position, attr)\n setattr(ps_msg.pose.position, attr, val) \n \n # Get pose\n direction = self.hand.direction\n normal = self.hand.palm_normal\n\n # Get orientation values from hand vectors\n roll = normal.roll\n pitch = normal.pitch\n yaw = direction.yaw\n\n else:\n ((x, y, z), (pitch, yaw, roll)) = self.test_pose()\n ps_msg.pose.position.x = x\n ps_msg.pose.position.y = y\n ps_msg.pose.position.z = z\n \n # Convert RPY to Quaternion \n quaternion = transformations.quaternion_from_euler(roll, pitch, yaw)\n \n # Set orientation quaternion in the message\n ps_msg.pose.orientation.x = quaternion[0]\n ps_msg.pose.orientation.y = quaternion[1]\n ps_msg.pose.orientation.z = quaternion[2]\n ps_msg.pose.orientation.w = quaternion[3]\n \n # return the PoseStamped messages\n print ps_msg\n return ps_msg",
"def __get_ticket_print(self, **kwargs):\n # TODO: выяснить используется ли pdf в принципе. В эл.регестратуре он никак не используется\n # TODO: pdf creator based on Flask templates and xhtml2pdf\n return \"\"",
"def GetPhase(self):\n ...",
"async def ticket(self, ctx, ticketpanel_name: str):\n licence_id = servers.get_licence_id(ctx.guild.id)\n ticketpanel: Ticketpanel = await Ticketpanel.query.where(Ticketpanel.name == ticketpanel_name).where(Ticketpanel.licence_id == licence_id).gino.first()\n\n if not ticketpanel:\n embed: Embed = settings.get_ticket_error_embed()\n embed.description = f\"\\nTicketPanel called **{ticketpanel_name}** doesnt exist\\n\"\n embed.set_footer(text=embed.footer.text,\n icon_url=self.bot.user.avatar_url)\n await ctx.send(embed=embed)\n return\n\n embed : Embed = settings.get_ticket_panel_embed()\n embed.description = ticketpanel.description\n embed.set_footer(text=embed.footer.text,\n icon_url=self.bot.user.avatar_url)\n await ctx.message.delete()\n message = await ctx.send(embed=embed)\n await message.add_reaction(settings.get_ticket_create_emoji())",
"def generate_message_as(info, client_addr):\n c_tgs_session_key = info.prepend_length(info.generate__des_key())\n AD_C = info.prepend_length(client_addr[0] + \":\" + str(client_addr[1]))\n ID_C = info.prepend_length(info.ID_C)\n ID_TGS = info.prepend_length(info.ID_TGS)\n Lifetime2 = info.prepend_length(info.Lifetime2)\n timestamp = info.prepend_length(str(int(time.time())))\n ticket_contents = c_tgs_session_key + ID_C + AD_C + ID_TGS + timestamp + Lifetime2\n info.read_des_key(\"keys/key_tgs.txt\")\n ticket_tgs = info.prepend_length(info.encrypt_message(ticket_contents).decode('UTF-8'))\n info.read_des_key(\"keys/key_c.txt\")\n message_contents = c_tgs_session_key + ID_TGS + timestamp + Lifetime2 + ticket_tgs\n message_as = info.encrypt_message(message_contents)\n return message_as"
] | [
"0.59553707",
"0.5945532",
"0.5706949",
"0.562352",
"0.56116676",
"0.5494644",
"0.5407777",
"0.54006296",
"0.53899044",
"0.5383889",
"0.53615665",
"0.5286938",
"0.52592003",
"0.5203707",
"0.5189929",
"0.51773334",
"0.51652193",
"0.51474714",
"0.510892",
"0.51081985",
"0.51065177",
"0.5101722",
"0.5101304",
"0.5092216",
"0.5090623",
"0.508955",
"0.5084705",
"0.5077354",
"0.507679",
"0.5060978"
] | 0.80429244 | 0 |
Create empty repository as per config. | def create_repository(cfg):
if os.path.isdir(cfg["repo_dir"]):
shutil.rmtree(cfg["repo_dir"], ignore_errors=True)
return Repo.init(cfg["repo_dir"]) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def repository_create_hosted():\n pass",
"def create(self):\n if os.path.isdir(self.repodir):\n if os.listdir(self.repodir):\n raise EmtError('%s is not empty' % self.repodir)\n else:\n os.makedirs(self.repodir)\n self.git_cmd('init')\n self.initialized = True",
"def cmd_init(self, _):\n log.info('initializing repository...')\n # check if a repository already exists\n if os.path.exists(self.path):\n log.warning(\"the '{}' folder already exists\".format(self.path))\n if log.ask_yesno('overwrite existing repository?', default='n'):\n shutil.rmtree(self.path)\n log.debug(\"creating folder: {}\".format(self.path))\n os.mkdir(self.path)\n else:\n return\n log.debug('initializing Git repository')\n self.git_repo = Repo.init(self.path)\n # create .gitignore to avoid tracking decrypted files\n log.debug('adding decrypted files to Git ignore list')\n with open(os.path.join(self.path, '.gitignore'), 'a') as ofile:\n ofile.write('encrypted/*.cleartext\\n')\n # create repository subfolders\n for dirpath in (self.files_path, self.enc_files_path):\n log.debug(\"creating folder: {}\".format(dirpath))\n os.mkdir(dirpath)\n log.debug(\"adding .gitkeep file\")\n with open(os.path.join(dirpath, '.gitkeep'), 'w') as _:\n pass\n log.debug('adding new files to Git')\n self.git_commit('initial commit')\n log.debug('creating new branch: {}'.format(self.hostname))\n self.git_repo.head.reference = self.git_repo.create_head(self.hostname, 'HEAD')\n assert not self.git_repo.head.is_detached\n self.git_repo.head.reset(index=True, working_tree=True)\n log.info('done')",
"def makeRepository(self, root):\n _gitInit(root)\n return root",
"def init(ctx, repository, git):\n dufl_root = ctx.obj['dufl_root']\n if os.path.exists(dufl_root):\n click.echo(\n 'Folder %s already exists, cannot initialize.' % dufl_root,\n err=True\n )\n exit(1)\n\n try:\n click.echo('Creating %s...' % dufl_root)\n os.makedirs(dufl_root, ctx.obj['create_mode'])\n\n click.echo('Initializing git repository...')\n giti = Git(git, dufl_root)\n giti.run('init')\n if repository != '':\n giti.run('remote', 'add', 'origin', repository)\n\n click.echo('Looking for remote repository...')\n repo_exists = False\n try:\n giti.run('ls-remote', repository)\n repo_exists = True\n except GitError:\n pass\n\n if repo_exists:\n click.echo('Pulling master branch of %s' % repository)\n giti.run('pull', 'origin', 'master')\n else:\n click.echo('No remote specified. You will need to add it manually when you have one.')\n\n if not os.path.exists(os.path.join(dufl_root, ctx.obj['home_subdir'])):\n click.echo('Creating home subfolder in %s' % dufl_root)\n os.makedirs(os.path.join(dufl_root, ctx.obj['home_subdir']), ctx.obj['create_mode'])\n if not os.path.exists(os.path.join(dufl_root, ctx.obj['slash_subdir'])):\n click.echo('Creating absolute subfolder in %s' % dufl_root)\n os.makedirs(os.path.join(dufl_root, ctx.obj['slash_subdir']), ctx.obj['create_mode'])\n\n if not os.path.exists(os.path.join(dufl_root, ctx.obj['settings_file'])):\n click.echo('Creating default settings file in %s' % dufl_root)\n with open(os.path.join(dufl_root, ctx.obj['settings_file']), 'w') as the_file:\n the_file.write(yaml.dump(dict(\n defaults.settings.items() + {\n 'git': git\n }.items()\n )))\n giti.run('add', os.path.join(dufl_root, ctx.obj['settings_file']))\n giti.run('commit', '-m', 'Initial settings file.')\n\n click.echo('Done!')\n except Exception as e:\n click.echo(e, err=True)\n click.echo(\n 'Failed. To retry, you will need to clean up by deleting the folder %s' % dufl_root,\n err=True\n )\n exit(1)",
"def prepare_repository(size, approach):\n # Create folder (if needed) where to store repository generation logs under report folder\n if not os.path.isdir(f\"{path_reports}/store\"):\n shell(f\"mkdir -p {path_reports}/store\")\n \n # Skip repository if we already have both its dump and statistics\n path_dump = path_data + \"/\" + size[\"id\"] + \"_\" + approach[\"id\"] + \".tar.lz\"\n path_stats = path_reports + \"/store/stats_\" + size[\"id\"] + \"_\" + approach[\"id\"] + \".tsv\"\n if os.path.isfile(path_dump) and os.path.isfile(path_stats):\n return\n\n # Initialize the repository directory, either from the template or from the dump if we have it\n path_repo = path_repos + \"/\" + size[\"id\"] + \"_\" + approach[\"id\"]\n if not os.path.isdir(path_repo):\n if not os.path.isfile(path_dump):\n template_id = \"template_\" + approach[\"id\"]\n shell(f\"{cmd_plzip} -kdc {path_templates}/{template_id}.tar.lz | tar xf - -C {path_repos}\")\n shell(f\"mv {path_repos}/{template_id} {path_repo}\")\n else:\n shell(f\"{cmd_plzip} -kdc {path_dump} | tar xf - -C {path_repos}\")\n\n # Locate the repository URL\n repo_url = f\"http://localhost:{server_port}/repositories/promo\"\n \n # Populate the repository if needed (i.e., marker file .ready missing)\n if not os.path.isfile(f\"{path_repo}/.ready\"):\n\n # Locate the synthetic traces to populate\n path_traces = path_data + \"/traces.jsonl.gz\"\n \n # Populate either using default approach (i.e., mokip store command) or preload\n if not approach[\"preload\"]:\n # Default population: start GraphDB, store traces, stop GraphDB\n shell(f\"{cmd_graphdb} start {path_repo}\")\n shell(f\"{cmd_mokip} store -D -O --schema-tx -t {os.cpu_count()} -b 100 -u {repo_url} -d {path_traces} \" +\n f\"-o {path_ontology} -m {size['traces']} -i {approach['inference']} \" +\n f\"-U {'APPEND' if approach['supports_graphs'] else 'APPEND_DEFAULT_GRAPH'} \" +\n f\"--trace-namespace '{namespace_trace}' --graph-namespace '{namespace_graph}' \" +\n f\"-r {path_reports}/store/store_{size['id']}_{approach['id']}.tsv \" +\n f\"| tee {path_reports}/store/store_{size['id']}_{approach['id']}.log\")\n shell(f\"{cmd_graphdb} stop {path_repo}\")\n \n else:\n # Preload population: generate repository files offline via preload, if needed\n if not os.path.isfile(f\"{path_repo}/.preloaded\"):\n \n # Populate an RDF file with the triples for all the traces to be put in the repository\n path_rdf = path_tmp + \"/traces_\" + size[\"id\"] + \".nq.gz\"\n shell(f\"{cmd_mokip} store -t {os.cpu_count()} -b 100 -U APPEND -i CENTRAL -d {path_traces} \" +\n f\"-o {path_ontology} -m {size['traces']} --dump-file {path_rdf} \" +\n f\"--trace-namespace '{namespace_trace}' --graph-namespace '{namespace_graph}'\" +\n f\"-r {path_reports}/traces/traces_{size['id']}.tsv \" + \n f\"| tee {path_reports}/traces/traces_{size['id']}.log\")\n \n # Convert fron .nq to .nt (with triple deduplication) in case the repository does not support graphs\n if not approach[\"supports_graphs\"]:\n path_rdf_nq = path_rdf\n path_rdf = path_tmp + \"/traces_\" + size[\"id\"] + \".nt.gz\"\n shell(f\"{cmd_rdfpro} @read {path_rdf_nq} @transform '=c sesame:nil' @unique @write {path_rdf}\")\n shell(f\"rm {path_rdf_nq}\")\n \n # Invoke the preload command\n shell(f\"{cmd_graphdb} preload -Dgraphdb.home={path_repo} -f -i promo {path_rdf}\")\n shell(f\"touch {path_repo}/.preloaded\")\n\n # Preload population: start GraphDB, store schema, trigger closure recomputation, and finally stop GraphDB\n update = \"INSERT DATA { [] <http://www.ontotext.com/owlim/system#reinfer> [] }\"\n shell(f\"{cmd_graphdb} start {path_repo}\")\n shell(f\"{cmd_mokip} store -O --schema-tx -U APPEND -u {repo_url} -d {path_traces} -o {path_ontology} -m 0 -i CENTRAL\")\n shell(f\"curl -X POST -m 604800 -d 'update={update}' {repo_url}/statements\")\n shell(f\"{cmd_graphdb} stop {path_repo}\")\n\n # Mark the repository as ready\n shell(f\"touch {path_repo}/.ready\")\n\n # Generate dump file if needed\n if not os.path.isfile(path_dump):\n shell(f\"tar -C {path_repos} -c -f - {size['id']}_{approach['id']} | plzip -9 > {path_dump}\")\n\n # Collect statistics of generated repository via SPARQL query\n if not os.path.isfile(path_stats):\n query = \"\"\"\n PREFIX trace: <http://dkm.fbk.eu/Trace_Ontology#>\n PREFIX bpmn: <http://dkm.fbk.eu/index.php/BPMN_Ontology#>\n PREFIX domain: <https://dkm.fbk.eu/#>\n PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n PREFIX onto: <http://www.ontotext.com/>\n SELECT ?nt ?na ?nas ?nd ?nds ?nf ?nfs ?ncs ?nq ?nqg ?nqe ?nqs {\n { SELECT (COUNT(DISTINCT ?t) AS ?nt) { ?t trace:compliance ?c } }\n { SELECT (COUNT(DISTINCT ?a) AS ?na) { ?a trace:execution_of / rdf:type bpmn:activity } }\n { SELECT (SUM(?a) AS ?nas) { ?t trace:number_of_activities ?a } }\n { SELECT (COUNT(DISTINCT ?d) AS ?nd) { ?d trace:execution_of / rdf:type domain:Document } }\n { SELECT (SUM(?d) AS ?nds) { ?t trace:number_of_documents ?d } }\n { SELECT (COUNT(DISTINCT ?f) AS ?nf) { ?d domain:hasOutputField ?f} }\n { SELECT (SUM(?f) AS ?nfs) { ?t trace:number_of_simple_fields ?f } }\n { SELECT (SUM(?f) AS ?ncs) { ?t trace:number_of_complex_fields ?f } }\n { SELECT (COUNT(*) AS ?nq) { ?s ?p ?o } }\n { SELECT (COUNT(*) AS ?nqg) { GRAPH ?g { ?s ?p ?o } } }\n { SELECT (COUNT(*) AS ?nqe) { GRAPH onto:explicit { ?s ?p ?o } } }\n { SELECT (COUNT(*) AS ?nqs) { GRAPH onto:readonly { ?s ?p ?o } } }\n }\"\"\"\n shell(f\"{cmd_graphdb} start {path_repo}\")\n shell(f\"curl -X POST -m 604800 -d 'query={query}' {repo_url} 2> /dev/null | sed -E 's/[,]/\\\\t/g' > {path_stats}\")\n shell(f\"{cmd_graphdb} stop {path_repo}\")\n \n # Delete the repository to save space (will extract the dump when needed)\n shell(f\"rm -Rf {path_repo}\")",
"def init_repo(cls, repo):\n os.makedirs(os.path.join(repo, cls.name))",
"def initializeBuildArea(self):\r\n\r\n repo_map = self.getRepoStatus()\r\n\r\n for obj in self.config[\"repos\"]:\r\n if obj[\"name\"] not in repo_map:\r\n if \"url\" in obj:\r\n print(\"Checking out code to {} for {}\".format(obj[\"path\"], obj[\"name\"]))\r\n if \"branch\" in obj:\r\n self.cloneGitRepo(obj[\"url\"], obj[\"path\"], obj[\"branch\"])\r\n else:\r\n self.cloneGitRepo(obj[\"url\"], obj[\"path\"])\r\n\r\n else:\r\n print(\"Creating directory : {} for repo : {}\".format(obj[\"path\"], obj[\"name\"]))\r\n makedirs(obj[\"path\"])\r\n\r\n else:\r\n if self.verbose:\r\n print(\"Repo : {}, already exists skipping!!\".format(obj[\"name\"]))",
"def create_code_repository(CodeRepositoryName=None, GitConfig=None):\n pass",
"def cmd_create(self):\n self.repo.create()\n\n # Add .gitignore.\n self.repo.add_files({'.gitignore': '.swp\\n'}, FIRST_COMMIT_MSG)\n\n # Create the etc and timestamps branches.\n self.repo.checkout('etc', create=True)\n self.repo.checkout('timestamps', create=True)\n\n self.repo.checkout('master')\n self.repo.init()\n self.update_repository()\n print('Git repository created at %s' % self.repodir)",
"def test_add_repo_to_empty(tmpdir):\n # Arange\n cfg = tmpdir.mkdir(\"sub\").join(\"empty.json\")\n REPO = \"foo.bar/foobar\"\n NAME = \"foorepo\"\n # Act\n rm = gcbo.RepoManager(repo=REPO, cfg=cfg)\n rm.save(NAME)\n\n # Assert\n with open(cfg) as fp:\n data = json.load(cfg)\n assert data[NAME][\"url\"] == REPO",
"def repository_create_proxy():\n pass",
"def init(args: argparse.Namespace) -> None:\n\tbranch = args.branch\n\turl = args.url\n\n\trepo_path = os.path.join(os.path.abspath(\".\"), \".repo\")\n\tLOGGER.info(\"Creating repo directory at %s\", repo_path)\n\tos.makedirs(repo_path, exist_ok=True)\n\t_run_git([\"clone\", \"-b\", branch, url, MANIFEST_DIRECTORY], repo_path)\n\tLOGGER.info(\"Initialized repository at %s\", repo_path)",
"def repo_with_empty_version_files(tmpdir):\n test_repo = TestRepo(tmpdir, do_write_version=False)\n return test_repo",
"def createRepository(self, name, indices=None):\n return Repository(self, name, self.mini_catalog.createRepository(name, indices=indices))",
"def non_git_repo(init_source_repo):\n _, parent_dir, _ = init_source_repo\n\n # Create\n non_git_dir_path = create_dir(\n full_path=os.path.join(tempfile.gettempdir(), \"non-git-repo\"),\n on_conflict=\"replace\",\n )\n\n yield non_git_dir_path\n\n # Delete the non-git repo\n delete_dir(non_git_dir_path)",
"def __init__(self, repository):\n self.__repo = repository",
"def command_new_repo(self):\n repoinit.new_repo(*self.args())",
"def repo():\n name = REPO_NAME_PREFIX + randstring()\n desc = randstring()\n repo = webapi.repos.create_repo(name)\n print('[create repo] repo_id: %s' % repo.id)\n with only_update_one_repo(repo.id):\n try:\n yield repo\n finally:\n try:\n repo.delete()\n except:\n print(\"repo is deleted\")",
"def test_empty_repository(self):\n os.environ['REPOSITORY'] = ''\n self.assertEqual(self.env.project_repo_name, '')",
"def test_create_repository(koan, assert_repo_exists):\n koan.shell('')",
"def test_init_repo_creates_a_zen_folder(tmp_path: str) -> None:\n _ = Repo.init(tmp_path)\n repo = Repository(str(tmp_path))\n local_stack = LocalService().get_stack(\"local_stack\")\n repo.init_repo(\n repo_path=tmp_path, analytics_opt_in=False, stack=local_stack\n )\n assert os.path.exists(os.path.join(tmp_path, ZENML_DIR_NAME))",
"def mkdir ():\n name = \"-\".join(parser_arguments().classes)\n if not os.path.exists(name):\n os.mkdir(name)\n print('The repository {} have been created'.format(parser_arguments().classes))\n else:\n print('The repository {} already exists.'.format(parser_arguments().classes))\n pass",
"def _get_tmp_repo(self):\n repo_path = os.path.join(TEMP_DIR_ROOT, 'repocopy_' + slugify(self.data['repository']['name']))\n if HARD_COPY and os.path.exists(repo_path):\n shutil.rmtree(repo_path)\n elif os.path.exists(repo_path):\n return git.Repo(repo_path)\n\n os.mkdir(repo_path)\n return git.Repo.init(repo_path)",
"def test_0010_create_repository(self):\n category = self.create_category(name=category_name, description=category_description)\n self.login(email=common.test_user_1_email, username=common.test_user_1_name)\n self.get_or_create_repository(name=repository_name,\n description=repository_description,\n long_description=repository_long_description,\n owner=common.test_user_1_name,\n category_id=self.security.encode_id(category.id),\n strings_displayed=[])",
"def create_empty_config_file():\n config = {\n \"config\": [\n {\n \"site\": {\n \"username\": \"\",\n \"name\": \"\",\n \"ip_address\": \"\",\n \"password\": \"\",\n \"local\": \"\",\n \"use_https\": \"\"\n }\n }\n ]\n }\n return config",
"def init_repo(repo_clone_url, path, version):\n # Create path for repo\n local_repo = Path(path) / version\n local_repo = local_repo.expanduser()\n \n # Initialize repository\n repo = git.Repo.clone_from(repo_clone_url, local_repo)\n return repo, local_repo",
"def new(url):\n from grit import Repo\n return Repo.new(url=url, bare=True)",
"def __init__(__self__, *,\n repositories: Optional[pulumi.Input[Sequence[pulumi.Input['ConfigurationServiceGitRepositoryArgs']]]] = None):\n if repositories is not None:\n pulumi.set(__self__, \"repositories\", repositories)",
"def check_catalogs():\n for config in StateHolder.config:\n conf = StateHolder.config[config]\n if type(conf) is not dict:\n continue\n if conf.get(\"repositoryType\", \"file\") is \"file\":\n FileUtils.make_empty_file_with_empty_dict(directory=StateHolder.home_dir,\n file=conf.get('file', 'poco-catalog.yml'))"
] | [
"0.66948557",
"0.6504964",
"0.64604133",
"0.6446928",
"0.64212257",
"0.6381512",
"0.6348716",
"0.63030165",
"0.6298837",
"0.62934303",
"0.61910295",
"0.6154405",
"0.6127809",
"0.60999084",
"0.6055417",
"0.60173297",
"0.5971328",
"0.59708107",
"0.5959201",
"0.59128726",
"0.59018284",
"0.58789504",
"0.58722264",
"0.57908577",
"0.57749414",
"0.5755533",
"0.57494104",
"0.57378966",
"0.5720416",
"0.57023203"
] | 0.70395553 | 0 |
Commit datetime string representation generator from range concept. | def commit_datetime_string_gen(cfg):
repo_end_time = calendar.timegm(time.gmtime())
first_commit_time = repo_end_time - (cfg["repo_age_in_days"] * SECONDS_PER_DAY)
for raw_date in range(first_commit_time, repo_end_time, SECONDS_PER_HOUR):
commit_time = periodic_commit(raw_date, SECONDS_PER_HOUR, random.random)
yield time.strftime(cfg["datetime_format_template"], time.gmtime(commit_time)) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def _build_range(self) -> str:\n return build_sequence(filter(None, (self.uids, self.sequence)))",
"def do_time_range(parser, token):\r\n chunks = token.split_contents()\r\n if not len(chunks) >= 3:\r\n raise template.TemplateSyntaxError, \"%r tag requires two or three arguments\" % token.contents.split()[0]\r\n if not len(chunks) <=4 :\r\n raise template.TemplateSyntaxError, \"%r tag requires two or three arguments\" % token.contents.split()[0]\r\n if len(chunks) == 4:\r\n format = chunks[3]\r\n else:\r\n format = \"\"\r\n return TimeRangeNode(chunks[1],chunks[2],format)",
"def _generate_range(\n start: Timestamp | None,\n end: Timestamp | None,\n periods: int | None,\n offset: BaseOffset,\n *,\n unit: str,\n):\n offset = to_offset(offset)\n\n # Argument 1 to \"Timestamp\" has incompatible type \"Optional[Timestamp]\";\n # expected \"Union[integer[Any], float, str, date, datetime64]\"\n start = Timestamp(start) # type: ignore[arg-type]\n if start is not NaT:\n start = start.as_unit(unit)\n else:\n start = None\n\n # Argument 1 to \"Timestamp\" has incompatible type \"Optional[Timestamp]\";\n # expected \"Union[integer[Any], float, str, date, datetime64]\"\n end = Timestamp(end) # type: ignore[arg-type]\n if end is not NaT:\n end = end.as_unit(unit)\n else:\n end = None\n\n if start and not offset.is_on_offset(start):\n # Incompatible types in assignment (expression has type \"datetime\",\n # variable has type \"Optional[Timestamp]\")\n start = offset.rollforward(start) # type: ignore[assignment]\n\n elif end and not offset.is_on_offset(end):\n # Incompatible types in assignment (expression has type \"datetime\",\n # variable has type \"Optional[Timestamp]\")\n end = offset.rollback(end) # type: ignore[assignment]\n\n # Unsupported operand types for < (\"Timestamp\" and \"None\")\n if periods is None and end < start and offset.n >= 0: # type: ignore[operator]\n end = None\n periods = 0\n\n if end is None:\n # error: No overload variant of \"__radd__\" of \"BaseOffset\" matches\n # argument type \"None\"\n end = start + (periods - 1) * offset # type: ignore[operator]\n\n if start is None:\n # error: No overload variant of \"__radd__\" of \"BaseOffset\" matches\n # argument type \"None\"\n start = end - (periods - 1) * offset # type: ignore[operator]\n\n start = cast(Timestamp, start)\n end = cast(Timestamp, end)\n\n cur = start\n if offset.n >= 0:\n while cur <= end:\n yield cur\n\n if cur == end:\n # GH#24252 avoid overflows by not performing the addition\n # in offset.apply unless we have to\n break\n\n # faster than cur + offset\n with warnings.catch_warnings():\n warnings.filterwarnings(\n \"ignore\",\n \"Discarding nonzero nanoseconds in conversion\",\n category=UserWarning,\n )\n next_date = offset._apply(cur)\n next_date = next_date.as_unit(unit)\n if next_date <= cur:\n raise ValueError(f\"Offset {offset} did not increment date\")\n cur = next_date\n else:\n while cur >= end:\n yield cur\n\n if cur == end:\n # GH#24252 avoid overflows by not performing the addition\n # in offset.apply unless we have to\n break\n\n # faster than cur + offset\n with warnings.catch_warnings():\n warnings.filterwarnings(\n \"ignore\",\n \"Discarding nonzero nanoseconds in conversion\",\n category=UserWarning,\n )\n next_date = offset._apply(cur)\n next_date = next_date.as_unit(unit)\n if next_date >= cur:\n raise ValueError(f\"Offset {offset} did not decrement date\")\n cur = next_date",
"def dateRange(self,str_start_time,str_end_time):\n\t\ttmp = str_start_time.split('-')\n\t\ttmp1 = str_end_time.split('-')\n\t\tstart_time = datetime.datetime(int(tmp[0]),int(tmp[1]),int(tmp[2]))\n\t\tend_time = datetime.datetime(int(tmp1[0]),int(tmp1[1]),int(tmp1[2]))\n\t\tfor n in range(int((end_time-start_time).days)):\n\t\t\tyield start_time + datetime.timedelta(n)",
"def _range_expression(self):\n # using filter expression to define the time range of the query\n # In influx2, range query is in the format\n # range(start:2018-05-22T23:30:00Z, stop: 2018-05-23T00:00:00Z) or\n # range(start: -12h, stop: -15m)\n # with stop parameter being optional\n if self.filter is None:\n return u''\n exp = (self._sql_where_expression(self.filter)).replace('AND',',').split(',')\n return u'|> range({})'.format(u' , '.join([(i.replace('\"','').replace(\"'\",'')) for i in exp if \"start\" in i or \"stop\" in i]))",
"def _format_range(start, end):\n if start is None:\n return ''\n if end is None:\n return str(start)+':'\n return str(start)+':'+str(end)",
"def do_date_range(parser, token):\r\n chunks = token.split_contents()\r\n if not len(chunks) >= 3:\r\n raise template.TemplateSyntaxError, \"%r tag requires two or three arguments\" % token.contents.split()[0]\r\n if not len(chunks) <=4 :\r\n raise template.TemplateSyntaxError, \"%r tag requires two or three arguments\" % token.contents.split()[0]\r\n if len(chunks) == 4:\r\n format = chunks[3]\r\n else:\r\n format = \"\"\r\n return DateRangeNode(chunks[1],chunks[2],format)",
"def GetTRange(self):\n ...",
"def build_range(identity: str, type_uri: str = SBOL_RANGE):\n start = 1\n end = 1\n obj = Range(PYSBOL3_MISSING, start, end, identity=identity, type_uri=type_uri)\n # Remove the placeholder values\n obj._properties[SBOL_SEQUENCES] = []\n obj._properties[SBOL_START] = []\n obj._properties[SBOL_END] = []\n return obj",
"def _split_date_range(start, end, intv):\n previous = start\n diff = (end - start) / intv\n for i in range(1, intv):\n current = start + diff * i\n yield (previous, current)\n previous = current\n yield (previous, end)",
"def generate_access_time_plot_from_range(id_range, val):\n segments = []\n points = []\n\n for i in id_range:\n if isinstance(i, list):\n endpoints = [(i[0], val), (i[1], val)]\n segments.append(endpoints)\n else:\n points.append((i, val))\n return segments, points",
"def build_time_range(self):\r\n prev_date = '0'\r\n prev_wd = 0\r\n temp = []\r\n\r\n # Iterate through each in time range list\r\n for i in self.time_range:\r\n # Len is 7 when prev_date is 'Unknown'\r\n if len(prev_date) == 7:\r\n p_date = 0\r\n c_date = i[1][:10].replace(\".\", \"\")\r\n # When current date is 'Unknown'\r\n if len(i[1]) == 7:\r\n p_date = prev_date[:10].replace(\".\", \"\")\r\n c_date = 0\r\n # When both dates are known\r\n if len(prev_date) != 7 and len(i[1]) != 7:\r\n p_date = prev_date[:10].replace(\".\", \"\")\r\n c_date = i[1][:10].replace(\".\", \"\")\r\n # Bypass a date when current date is less than prev date\r\n if int(c_date) < int(p_date):\r\n prev_wd = prev_wd\r\n prev_date = prev_date\r\n else:\r\n # Reassign prev_date to 'Unknown'\r\n if prev_date == '0':\r\n prev_date = 'Unknown'\r\n # Add previous, current wd and previous, current date to temp\r\n temp.append([prev_wd, i[0], prev_date, i[1]])\r\n prev_wd = i[0]\r\n prev_date = i[1]\r\n # Assign temp list to time range list\r\n self.time_range = temp",
"def range(self):\n\n return time_stat(self, stat=\"range\")",
"def test_get_range(self):\n pass",
"def __init__(self, begin, end):\n begin = datetime(begin.year, begin.month, begin.day)\n self.begin_ts = int((begin-datetime(1970,1,1)).total_seconds())\n end = datetime(end.year, end.month, end.day)\n self.end_ts = int((end-datetime(1970,1,1)).total_seconds())",
"def create(self, range):\n raise NotImplementedError",
"def test_create_one_end(check_ranges, accounts, nft):\n nft.transferRange(accounts[4], 19000, 20000, {\"from\": accounts[2]})\n check_ranges([(1, 10001)], [(10001, 19000), (20000, 20001)], [(20001, 30001)], [(19000, 20000)])",
"def daterange(start_date, end_date):\n for n in range(int((end_date - start_date).days)+1):\n yield start_date + dt.timedelta(n)",
"def gen_start_end_times(start_time=[6, 0, 0], end_time=[23, 0, 0]):\n\n now = datetime.now()\n year = now.year\n month = now.month\n day = now.day\n\n start_time = datetime(\n year, month, day, start_time[0], start_time[1], start_time[2], 0\n )\n\n end_time = datetime(year, month, day, end_time[0], end_time[1], end_time[2], 0)\n\n if end_time < now:\n end_time += timedelta(days=1)\n start_time += timedelta(days=1)\n\n return start_time, end_time",
"def git_stats_date_range(\n project: Project,\n formatter: Formatter,\n date_start: datetime.datetime,\n date_end: datetime.datetime,\n) -> GitStats:\n name_start = f\"{formatter.name}@{{{date_start:%F %T}}}\"\n name_end = f\"{formatter.name}@{{{date_end:%F %T}}}\"\n return _git_stats(project, name_start, name_end)",
"def _make_datetime(self, datetime_):\n datetime_ = datetime_.rstrip('Z').replace('Z/', '/')\n if '/' in datetime_:\n begin, end = datetime_.split('/')\n if begin == '..':\n begin = self._data[self.time_field].min().values\n if end == '..':\n end = self._data[self.time_field].max().values\n if np.datetime64(begin) < np.datetime64(end):\n return slice(begin, end)\n else:\n LOGGER.debug('Reversing slicing from high to low')\n return slice(end, begin)\n else:\n return datetime_",
"def get_commit_by_timerange(start, end):\n commit_sql = \"SELECT c.* FROM github_commit c WHERE \" \\\n \"substr(c.commit_committer_date, 0, 5) || substr(c.commit_committer_date, 6, 2) || substr(c.commit_committer_date, 9, 2) || \" \\\n \"substr(c.commit_committer_date, 12, 2) || substr(c.commit_committer_date, 15, 2) || substr(c.commit_committer_date, 18, 2) \" \\\n \"between ? and ?\"\n print \"commit_sql \", commit_sql\n\n return dbutils.execute_query(commit_sql, (start, end), DATABASE_FILE)",
"def daterange(start_date, end_date):\n for n in range(int ((end_date - start_date).days)+1):\n yield start_date + timedelta(n)",
"def __time_range_to_date(time_range : str) -> dt.datetime:\n\n if time_range.lower() == 'max':\n return dt.datetime(1900,1,1)\n\n multiplier, period = re.search(\"(\\d+)([dwmy])\", time_range.lower()).groups()\n multiplier = int(multiplier)\n\n if period == 'd': return dt.datetime.now() + relativedelta.relativedelta(days=-multiplier)\n elif period == 'w': return dt.datetime.now() + relativedelta.relativedelta(weeks=-multiplier)\n elif period == 'm': return dt.datetime.now() + relativedelta.relativedelta(months=-multiplier)\n elif period == 'y': return dt.datetime.now() + relativedelta.relativedelta(years=-multiplier)",
"def test_date_range_reconcile(klass, datetime, tzutc):\n r = klass(title=\"Foo\")\n r.start_date = datetime(2016, 5, 21, 0, 0, 0)\n r.end_date = datetime(2016, 6, 21, 11, 59, 59)\n\n assert r.start_date == datetime(2016, 5, 15, 0, 0, 0, tzinfo=tzutc) # Sunday\n assert r.end_date == datetime(2016, 6, 25, 11, 59, 59, tzinfo=tzutc) # Saturday",
"def _get_output_date_range_for(self, from_input_dt, to_input_dt):\n return from_input_dt, to_input_dt",
"def test_UniformTime_repr():",
"def create_date_list(start_date = start_date, end_date = end_date):",
"def make_range(_num_list):\n if len(_num_list) == 1:\n out_str = str(_num_list[0])\n\n elif len(_num_list) == 2:\n out_str = str(_num_list[0]) + ', ' + str(_num_list[1])\n\n else:\n out_str = str(_num_list[0]) + '-' + str(_num_list[-1])\n\n return out_str",
"def format_commit_range(old_commit, new_commit):\n if old_commit == new_commit:\n return old_commit\n\n return (old_commit or osv.UNKNOWN_COMMIT) + ':' + new_commit"
] | [
"0.6324533",
"0.56947076",
"0.56797504",
"0.55976844",
"0.55973476",
"0.55576396",
"0.5536649",
"0.54804605",
"0.54670656",
"0.5458674",
"0.54278266",
"0.54063386",
"0.5388316",
"0.5360843",
"0.5335496",
"0.53224176",
"0.526309",
"0.52590555",
"0.5253629",
"0.52532643",
"0.5241419",
"0.52311265",
"0.5230391",
"0.5221609",
"0.5217906",
"0.5215072",
"0.52141124",
"0.5198517",
"0.51904655",
"0.51902074"
] | 0.62148494 | 1 |
Plan feature in model and start development on branch. | def start_feature(repo, cfg, model, developer_gen):
model = model_plan_feature(cfg, model, developer_gen)
repo.head.reference = repo.create_head(model.ticket)
repo.head.reset(index=True, working_tree=True)
return repo, model | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def model_plan_feature(cfg, model, developer_gen):\n model.ticket = cfg[\"ticket_id_template\"] % (choose_in(1, cfg[\"repo_age_in_days\"]),)\n model.planned = choose_in(1, cfg[\"max_commits_per_branch\"])\n model.developer = next(developer_gen)\n return model",
"def main(argv):\n cfg = defaults(argv)\n repo = create_repository(cfg)\n model = Model()\n developer_gen = next_member(cfg)\n for git_date in commit_datetime_string_gen(cfg):\n repo, model = add_commit(repo, cfg, model, developer_gen, git_date)\n if model.ticket is not None and model.commits == model.planned:\n repo, model = merge_feature(repo, cfg, model, git_date)\n if model.ticket is None:\n repo, model = start_feature(repo, cfg, model, developer_gen)\n cfg = join(cfg, model)\n with open(\"model.pickle\", \"wb\") as f_p:\n pickle.dump(cfg, f_p, protocol=pickle.HIGHEST_PROTOCOL)",
"def stage(branch=None, role='dev'):\n update_function = get_update_function()\n branch = branch or get_git_branch()\n\n project_path = fb_env.role(role, 'project_path')\n\n with cd(project_path):\n previous_head = update_function(branch)\n puts('Previous remote HEAD: {0}'.format(previous_head))\n run('./fbmvc dbdump')\n run('./fbmvc migrate latest')",
"def __gitBisectStart(self):\n self.vcs.gitBisect(self.project.getProjectPath(), \"start\")",
"def development():\n env.branch = 'development'",
"def _stage1(self):\n self.start_progress()\n tasks = list(self._chain_dict(self._model.adjust_tasks))\n if len(tasks) == 0:\n self._stage2(self._no_adjustments_case())\n else:\n task = lambda : self._run_adjust_tasks(tasks)\n locator.get(\"pool\").submit(task, self._stage2)",
"def start_training(self):\n self.training = True",
"def step(self, model):\n\n if self.active == 0:\n\n self.activate(model)\n\n elif self.active == 1:\n\n self.move(model)\n\n self.exit_query(model)\n\n self.save(model)\n\n return",
"def dev_up():\n _with_deploy_env(['./bin/develop up'])",
"def stage(self):\n\n # prepare projected land allocation data\n self.prep_projected()\n\n # prepare base land use data\n self.prep_base()\n\n # harmonize grid area between projected and base layer land allocation\n self.harmony()\n\n # apply constraints\n self.set_constraints()\n\n # create kernel density filter if not running multiple jobs\n self.kernel_filter()\n\n # set data for step zero\n self.set_step_zero()",
"def workon(ctx, issue_id, new, base_branch):\n lancet = ctx.obj\n\n if not issue_id and not new:\n raise click.UsageError(\"Provide either an issue ID or the --new flag.\")\n elif issue_id and new:\n raise click.UsageError(\n \"Provide either an issue ID or the --new flag, but not both.\"\n )\n\n if new:\n # Create a new issue\n summary = click.prompt(\"Issue summary\")\n issue = create_issue(\n lancet, summary=summary, add_to_active_sprint=True\n )\n else:\n issue = get_issue(lancet, issue_id)\n\n username = lancet.tracker.whoami()\n active_status = lancet.config.get(\"tracker\", \"active_status\")\n if not base_branch:\n base_branch = lancet.config.get(\"repository\", \"base_branch\")\n\n # Get the working branch\n branch = get_branch(lancet, issue, base_branch)\n\n # Make sure the issue is in a correct status\n transition = get_transition(ctx, lancet, issue, active_status)\n\n # Make sure the issue is assigned to us\n assign_issue(lancet, issue, username, active_status)\n\n # Activate environment\n set_issue_status(lancet, issue, active_status, transition)\n\n with taskstatus(\"Checking out working branch\") as ts:\n lancet.repo.checkout(branch.name)\n ts.ok('Checked out working branch based on \"{}\"'.format(base_branch))\n\n with taskstatus(\"Starting harvest timer\") as ts:\n lancet.timer.start(issue)\n ts.ok(\"Started harvest timer\")",
"def plan(self):\n raise NotImplementedError('You must implement the plan() method '\n 'yourself!')",
"def project(self, feature):\n return feature",
"def model_switch_to_testing(self):\n pass",
"def plan(self,end_state,toolname,tooldata,codedata,adminuser,adminpass,username,userpass):\n\n states = { 'none' : { 'fxn' : None,\n 'args' : None,\n 'next' : 'created',\n },\n 'created' : { 'fxn' : self.register,\n 'args' : (toolname,tooldata),\n 'next' : 'uploaded',\n },\n 'uploaded' : { 'fxn' : self.upload,\n 'args' : (toolname,codedata,username,userpass),\n 'next' : 'installed',\n },\n 'installed' : { 'fxn' : self.install,\n 'args' : (toolname,adminuser,adminpass),\n 'next' : 'approved',\n },\n 'approved' : { 'fxn' : self.approve,\n 'args' : (toolname,username,userpass),\n 'next' : 'published',\n },\n 'published' : { 'fxn' : self.publish,\n 'args' : (toolname,adminuser,adminpass),\n 'next' : 'updated',\n },\n 'updated' : { 'fxn' : self.updated,\n 'args' : (toolname,username,userpass),\n 'next' : 'installed',\n },\n }\n\n if end_state not in states:\n raise ValueError('invalid end state: %s' % (end_state))\n\n try:\n self.goto_tool_status_page(toolname)\n po = self.catalog.load_pageobject('ToolsStatusRegisteredPage')\n cur_state = po.get_tool_state().lower()\n except NavigationError:\n cur_state = 'none'\n\n while cur_state != end_state:\n next_state = state['next']\n state = states[next_state]\n\n state['fxn'](*state['args'])\n\n last_state = cur_state\n cur_state = po.get_tool_state().lower()\n assert cur_state == next_state, \\\n \"unexpected state change from %s to %s\" % (last_state,next_state)",
"def _switchBranch(self, release):\n if release is None:\n self.branch = None\n self.branch_dir = None\n log.info('No release branch available')\n else:\n self.wc.update()\n assert self.wc.exists('branches/' + release)\n io.linesToFile(self.path(self.BRANCH_FILE), [release])\n self.branch = release\n self.branch_dir = 'branches/' + release\n self.wc.update(self.branch_dir, depth='infinity')\n log.info('Working on branch ' + self.branch)",
"def finetuned():\n launch_training_on_all_splits(experiment='full', splits=NAME_SPLIT, base_model='ft', dropout=0.7304, learning_rate=0.0000976)",
"def branch(branch_name):\n env.branch = branch_name",
"def branch(branch_name):\n env.branch = branch_name",
"def _start(self):\n if self._classifier is None:\n self._classifier = TFSlimClassifier(self.config)\n self._classifier.__enter__()",
"def switch_features_handler(self, event):\n\t\tmsg = event.msg\n\t\tdatapath = msg.datapath\n\n\t\tLOG.info(\"Configuring switch %d...\" % datapath.id)\n\n\t\t\"\"\" Set table 0 as stateful \"\"\"\n\t\treq = bebaparser.OFPExpMsgConfigureStatefulTable(\n\t\t\t\tdatapath=datapath,\n\t\t\t\ttable_id=0,\n\t\t\t\tstateful=1)\n\t\tdatapath.send_msg(req)\n\n\t\t\"\"\" Set lookup extractor = {eth_dst} \"\"\"\n\t\treq = bebaparser.OFPExpMsgKeyExtract(datapath=datapath,\n\t\t\t\tcommand=bebaproto.OFPSC_EXP_SET_L_EXTRACTOR,\n\t\t\t\tfields=[ofproto.OXM_OF_ETH_DST],\n\t\t\t\ttable_id=0)\n\t\tdatapath.send_msg(req)\n\n\t\t\"\"\" Set update extractor = {eth_dst} \"\"\"\n\t\treq = bebaparser.OFPExpMsgKeyExtract(datapath=datapath,\n\t\t\t\tcommand=bebaproto.OFPSC_EXP_SET_U_EXTRACTOR,\n\t\t\t\tfields=[ofproto.OXM_OF_ETH_DST],\n\t\t\t\ttable_id=0)\n\t\tdatapath.send_msg(req)\n\n\t\t###########################################################################################\n\n\t\t\"\"\" Set GDV[2]=4 \"\"\"\n\t\treq = bebaparser.OFPExpMsgsSetGlobalDataVariable(\n\t\t\t\tdatapath=datapath,\n\t\t\t\ttable_id=0,\n\t\t\t\tglobal_data_variable_id=2,\n\t\t\t\tvalue=4\n\t\t\t)\n\t\tdatapath.send_msg(req)\n\n\t\t\"\"\" Set condition 5: FDV[0] >= GDV[2] (i.e. counter >= 4) \"\"\"\n\t\treq = bebaparser.OFPExpMsgSetCondition(\n\t\t\t\tdatapath=datapath,\n\t\t\t\ttable_id=0,\n\t\t\t\tcondition_id=5,\n\t\t\t\tcondition=bebaproto.CONDITION_GTE,\n\t\t\t\toperand_1_fd_id=0,\n\t\t\t\toperand_2_gd_id=2\n\t\t\t)\n\t\tdatapath.send_msg(req)\n\n\t\t\"\"\" If counter <4 then forward() & Update function: FDV[0] = FDV[0]+1 (i.e. counter = counter+1) \"\"\"\n\t\tmatch = ofparser.OFPMatch(condition5=0)\n\t\tactions = [ofparser.OFPActionOutput(ofproto.OFPP_FLOOD),\n\t\tbebaparser.OFPExpActionSetDataVariable(table_id=0, opcode=bebaproto.OPCODE_SUM, output_fd_id=0, operand_1_fd_id=0, operand_2_cost=1)]\n\t\tself.add_flow(datapath=datapath,\n\t\t\t\ttable_id=0,\n\t\t\t\tpriority=0,\n\t\t\t\tmatch=match,\n\t\t\t\tactions=actions)\n\n\t\t\"\"\" If counter >=4 then drop() \"\"\"\n\t\tmatch = ofparser.OFPMatch(condition5=1)\n\t\tactions = []\n\t\tself.add_flow(datapath=datapath,\n\t\t\t\ttable_id=0,\n\t\t\t\tpriority=0,\n\t\t\t\tmatch=match,\n\t\t\t\tactions=actions)\n\n\t\t\"\"\"\n\t\t$ sudo mn --topo single,4 --switch user --controller remote --mac --arp\n\t\tmininet> h1 ping h2 -c10\n\t\tIt should drop all the packets from the 5-th \n\t\t\"\"\"",
"def plan(self):\n\n self.logger.info(\"*** start planning......\")\n\n request_list = self.dbh.get_requests()\n\n if len(request_list) > 0:\n if not self._handle_requests(request_list):\n self.logger.error(\"while planning\")\n return False\n else:\n self.logger.error(\"while reading plan\")\n return False\n\n return True",
"def _stage(self):\n\n pass",
"def step(self):\n # Fast learning\n task_embedding = self._ilp.infer_task()\n\n # Posterior update\n #self._skip_flag = self._is_graph_same(task_embedding, self._prev_task_embedding)\n self._skip_flag = False # XXX do not skip test\n if not self._skip_flag:\n self._grprop.observe_task(task_embedding)\n self._prev_task_embedding = task_embedding\n else:\n print(\"skipping!\")",
"def deploy():\n stage(branch='live', role='live')",
"def run_task_in_model_specific_flask_server(start):\n global GLOBAL_FLASK_SERVER_PROCESS\n global LAST_GLOBAL_QUEUE_NAME\n model_specific_queue_name = processing.get_model_specific_queue_name(start.operation, start.arguments)\n trained_model = TrainedModel.objects.get(pk=processing.get_model_pk_from_args(start.operation,start.arguments))\n new_envs = os.environ.copy()\n for k in {'PYTORCH_MODE','CAFFE_MODE','MXNET_MODE'}:\n if k in new_envs:\n del new_envs[k]\n if trained_model.mode == TrainedModel.PYTORCH:\n new_envs['PYTORCH_MODE'] = '1'\n elif trained_model.mode == TrainedModel.CAFFE:\n new_envs['CAFFE_MODE'] = '1'\n elif trained_model.mode == TrainedModel.MXNET:\n new_envs['MXNET_MODE'] = '1'\n if GLOBAL_FLASK_SERVER_PROCESS is None or LAST_GLOBAL_QUEUE_NAME != model_specific_queue_name:\n if GLOBAL_FLASK_SERVER_PROCESS:\n GLOBAL_FLASK_SERVER_PROCESS.terminate()\n os.remove('flask.pid')\n elif os.path.isfile('flask.pid'):\n try:\n os.kill(int(file('flask.pid').read()),signal.SIGTERM)\n except:\n pass\n GLOBAL_FLASK_SERVER_PROCESS = subprocess.Popen(['python', 'scripts/run_flask.py',\n start.operation, str(start.pk)],env=new_envs)\n LAST_GLOBAL_QUEUE_NAME = model_specific_queue_name\n max_attempts = 15\n while max_attempts:\n try:\n r = requests.get('http://localhost:{port}/'.format(port=settings.GLOBAL_MODEL_FLASK_SERVER_PORT))\n if r.ok:\n break\n except:\n max_attempts -= 1\n time.sleep(4)\n r = requests.get('http://localhost:{port}/{pk}/'.format(port=settings.GLOBAL_MODEL_FLASK_SERVER_PORT,pk=start.pk))\n if not r.ok:\n raise ValueError(\"Coud not process\")\n return True",
"def switchToBranch(self):\n branches = self._listBranches()\n if not branches:\n raise error.ExpectationFailed(\n 'No branches available. Please import one.')\n\n choice = io.getChoice('Available release branches:',\n 'Your choice?',\n branches,\n suggest=len(branches)-1)\n self._switchBranch(branches[choice])",
"def build_plan(self):\n assert False, \"Not implemented.\"",
"def launch ():\n def start_switch (event):\n log.info(\"switch %s has come up\" % event.dpid)\n log.info(event.connection.ports)\n sw = switches_by_dpid.get(event.dpid)\n\n if sw is None:\n # New switch\n sw = TopoSwitch(event.connection)\n switches_by_dpid[event.dpid] = sw\n sw.connect(event.connection)\n else:\n sw.connect(event.connection)\n core.openflow.addListenerByName(\"ConnectionUp\", start_switch)",
"def stage(self):\n pass"
] | [
"0.68359864",
"0.58938617",
"0.58637154",
"0.5632829",
"0.56046027",
"0.5525671",
"0.5336109",
"0.52671415",
"0.5255504",
"0.52485037",
"0.52481985",
"0.51825285",
"0.5128954",
"0.5123314",
"0.5110367",
"0.5108799",
"0.51068956",
"0.5064",
"0.5064",
"0.50550956",
"0.50466096",
"0.5027151",
"0.5007144",
"0.5000365",
"0.49941647",
"0.49840128",
"0.4980531",
"0.49735123",
"0.49712518",
"0.4966953"
] | 0.7742167 | 0 |
Note the commit in model and update repo. | def add_commit(repo, cfg, model, developer_gen, date):
model, kwargs = model_note_change(model, developer_gen, date)
msg = message_of(
cfg, model.ticket if model.ticket is not None else "", "general_commit_words"
)
repo.index.commit(msg, **kwargs)
return repo, model | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def commit(self):\n run('git', 'add', '.')\n run('git', 'commit', '-a', '-m', 'updates')",
"def commit(self):\n pass",
"def commit(self):\n pass",
"def commit(self):\n pass",
"def commit(self):\n pass",
"def commit(self):\n pass",
"def commit(self):\n return",
"def git_commit(self, msg):\n self.git_repo.git.add(all=True)\n self.git_repo.git.commit(message='[dots] {}'.format(msg))",
"def commit(self):\n # PEP 249\n pass",
"def commit(self) -> None:\n pass",
"def commit(self):",
"def commit(self):\n raise NotImplementedError",
"def model_note_change(model, developer_gen, date):\n model.developer = next(developer_gen)\n kwargs = author_committer_facts(model, date)\n model.commits += 1\n return model, kwargs",
"def _do_commit(self):",
"def commit(self, msg):\n self.runtime.logger.info('Commit config: {}'.format(msg))\n with Dir(self.runtime.metadata_dir):\n exectools.cmd_assert([\"git\", \"add\", \".\"])\n exectools.cmd_assert([\"git\", \"commit\", \"--allow-empty\", \"-m\", msg])",
"def update(repository, args, **_):\n _log(repository, 'INFO', \"Going to build commit %s\" % args[2][:7])",
"def main():\n smart_commit_msg_filename = SMART_COMMIT_MSG_FILENAME\n paths = get_staged_paths()\n if not len(paths):\n raise Exception(\"did you even add anything to staging\")\n paths += [smart_commit_msg_filename]\n mr_edited_file = max(paths, key=lambda k: os.path.getmtime(k))\n if mr_edited_file == smart_commit_msg_filename:\n print(git_commit())\n else:\n print(\"Update the patch notes!\")",
"def update_from_repo():\n\treturn",
"def commit(self, commit_message):\n self.git_repo.index.commit(commit_message)",
"def _do_commit(self):\n self.backend.commit()",
"def commit_changes(repo, project = ''):\n cmd = repo.git\n cmd.add(all=True)\n try:\n cmd.commit(m=\"redcap2mysql.py data sync for project \" + project)\n except git.exc.GitCommandError, err:\n logging.info([traceback.format_exc(limit=1).splitlines()[-1]])",
"def git_append(msg):\n pipe = Popen('git log -1 --pretty=%B', stdout=PIPE, shell=True)\n old_msg = pipe.stdout.read()\n new_msg = '%s\\n%s' % (old_msg.rstrip(), msg)\n\n pipe = Popen('git commit --amend --file=-', stdin=PIPE, shell=True)\n pipe.communicate(new_msg)",
"def update(self, commit, **kwargs):\n self._pkg_changes(commit=self.commit, **kwargs)\n self.commit = commit",
"def commit(self):\n self.cnx.commit()",
"async def commit(self):\n if await self.is_valid():\n await self.update(committed=True).apply()",
"def commit(self) -> None:\n if self._edits and len(self._edits) > 0:\n self._update(\"\\n;\\n\".join(self._edits))\n self._edits = None",
"def model_update(self, db):\n db.session.commit()",
"def save(self, *args, **kwargs):\n super(AbstractAuditModel, self).save(*args, **kwargs)\n if not self.current_revision:\n revision = self.__class__.current_revision.field.related_model()\n revision.tracked_model = self\n revision.save()",
"def commit(self, msg=None):\n self.log.debug(\"committing in git: %s\" % msg)\n completemsg = \"EasyBuild-commit from %s (time: %s, user: %s) \\n%s\" % (socket.gethostname(),\n time.strftime(\"%Y-%m-%d_%H-%M-%S\"),\n getpass.getuser(),\n msg)\n self.log.debug(\"git status: %s\" % self.client.status())\n try:\n self.client.commit('-am \"%s\"' % completemsg)\n self.log.debug(\"succesfull commit\")\n except GitCommandError, err:\n self.log.warning(\"Commit from working copy %s (msg: %s) failed, empty commit?\\n%s\" % (self.wc, msg, err))\n try:\n info = self.client.push()\n self.log.debug(\"push info: %s \" % info)\n except GitCommandError, err:\n self.log.warning(\"Push from working copy %s to remote %s (msg: %s) failed: %s\" % (self.wc,\n self.repo,\n msg,\n err))",
"def call_git_push():\n print(\"This will commit and push the git repo\")\n today = datetime.datetime.today()\n call([\"git\", \"add\", \".\"])\n call([\"git\", \"commit\", \"-m\", \"Updated notes. {:%Y-%m-%d %H:%M:%S}\".format(today)])\n call([\"git\", \"push\", \"origin\", \"master\"])"
] | [
"0.67854685",
"0.67172647",
"0.67172647",
"0.67172647",
"0.67172647",
"0.67172647",
"0.66994685",
"0.66824937",
"0.66407114",
"0.6613476",
"0.6555489",
"0.633415",
"0.6278688",
"0.6192139",
"0.6180403",
"0.6174244",
"0.6102314",
"0.6092508",
"0.6061488",
"0.60460293",
"0.6030769",
"0.5966065",
"0.5935448",
"0.59248585",
"0.5921938",
"0.5921465",
"0.591826",
"0.5892092",
"0.5888601",
"0.5882292"
] | 0.67881685 | 0 |
Merge the feature in repo and groom the model. | def merge_feature(repo, cfg, model, date):
repo.index.merge_tree(
repo.heads.master, base=repo.merge_base(repo.heads.master, repo.head)
)
kwargs = {
**author_committer_facts(model, date),
**dict(head=True, parent_commits=(repo.heads.master.commit, repo.head.commit)),
}
repo.index.commit(message_of(cfg, model.ticket, "merge_commit_words"), **kwargs)
repo.heads.master.commit = repo.head.commit
repo.head.reference = repo.heads.master
repo.delete_head(model.ticket)
model = groom_model(model)
return repo, model | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_merge(self):\n fc1 = self.read_feature()\n fc2 = self.read_feature('Aegean_Sea')\n\n # add a feature already in the feature collection\n fc1.merge(fc1)\n assert len(fc1.features) == 1\n\n # add a new feature to the feature collection\n fc1.merge(fc2)\n assert len(fc1.features) == 2\n\n self.check_feature(fc1.features[0])\n self.check_feature(fc1.features[1], expected_name='Aegean Sea')",
"def merge():\n click.echo(\"Not implemented yet. In the future, this command will be used for merging models.\")\n sys.exit(-2)",
"def project(self, feature):\n return feature",
"def merge(): #Status: WIP\r\n pass",
"def start_feature(repo, cfg, model, developer_gen):\n model = model_plan_feature(cfg, model, developer_gen)\n repo.head.reference = repo.create_head(model.ticket)\n repo.head.reset(index=True, working_tree=True)\n return repo, model",
"def merge(self, ref, *args):\n return self.cmd('merge', ref, *args)",
"def _merge_image_features(feature_class_type: Type[Union[kapture.Keypoints,\n kapture.Descriptors,\n kapture.GlobalFeatures]],\n feature_type: str,\n features_list: Union[List[Optional[kapture.Keypoints]],\n List[Optional[kapture.Descriptors]],\n List[Optional[kapture.GlobalFeatures]]],\n features_paths: List[str],\n output_path: str,\n tar_handlers: List[TarCollection]\n ) -> Union[kapture.Keypoints, kapture.Descriptors, kapture.GlobalFeatures]:\n assert len(features_list) > 0\n assert len(features_paths) == len(features_list)\n\n # find no none value\n val = [(i, d) for i, d in enumerate(features_list) if d is not None]\n assert len(val) > 0\n\n merged_features = val[0][1]\n for j, (i, features) in enumerate(val):\n assert isinstance(features, feature_class_type)\n assert features.type_name == merged_features.type_name\n assert features.dtype == merged_features.dtype\n assert features.dsize == merged_features.dsize\n if feature_class_type == kapture.Descriptors or feature_class_type == kapture.GlobalFeatures:\n assert not isinstance(features, kapture.Keypoints) # IDE type check help\n assert not isinstance(merged_features, kapture.Keypoints) # IDE type check help\n assert features.metric_type == merged_features.metric_type\n if feature_class_type == kapture.Descriptors:\n assert isinstance(features, kapture.Descriptors) # IDE type check help\n assert isinstance(merged_features, kapture.Descriptors) # IDE type check help\n assert features.keypoints_type == merged_features.keypoints_type\n for name in features:\n if j > 0 and name in merged_features:\n getLogger().warning(f'{name} was found multiple times.')\n else:\n merged_features.add(name)\n if output_path:\n # TODO: uses kapture.io.features_list.get_image_features_dirpath()\n in_path = kapture.io.features.get_features_fullpath(feature_class_type,\n feature_type,\n features_paths[i],\n name,\n tar_handlers[i])\n out_path = kapture.io.features.get_features_fullpath(feature_class_type,\n feature_type,\n output_path,\n name)\n if in_path != out_path:\n # skip actual copy if file does not actually move.\n os.makedirs(os.path.dirname(out_path), exist_ok=True)\n if isinstance(in_path, str):\n shutil.copy(in_path, out_path)\n else:\n # in_path is a tuple [str, TarHandler]\n # keypoints are not stored in a file, have to read them to be able to copy them\n array = in_path[1].get_array_from_tar(in_path[0], features.dtype, features.dsize)\n array_to_file(out_path, array)\n return merged_features",
"def _add_feature(self, feature):\n\n if feature.name in self.feature_name_index:\n logger.info(\"Feature %s already exists at %i, overwriting\" %\n (feature.name, self.feature_name_index[feature.name]))\n self.features[self.feature_name_index[feature.name]] = feature\n else:\n self.features.append(feature)\n self.feature_name_index[feature.name] = len(self.features) - 1\n logger.info(\"Adding %s to model at location %i\" % (\n feature.name, len(self.features)))\n self._add_domain_fault_above(feature)\n self._add_unconformity_above(feature)\n feature.set_model(self)",
"def main(argv):\n cfg = defaults(argv)\n repo = create_repository(cfg)\n model = Model()\n developer_gen = next_member(cfg)\n for git_date in commit_datetime_string_gen(cfg):\n repo, model = add_commit(repo, cfg, model, developer_gen, git_date)\n if model.ticket is not None and model.commits == model.planned:\n repo, model = merge_feature(repo, cfg, model, git_date)\n if model.ticket is None:\n repo, model = start_feature(repo, cfg, model, developer_gen)\n cfg = join(cfg, model)\n with open(\"model.pickle\", \"wb\") as f_p:\n pickle.dump(cfg, f_p, protocol=pickle.HIGHEST_PROTOCOL)",
"def svn_fs_merge(*args):\r\n return _fs.svn_fs_merge(*args)",
"def _merge(self):\n raise NotImplementedError",
"def update_from_repo():\n\treturn",
"def merge(self, other, allow_duplicate=False, do_spaces=True, do_datasets=True, do_tasksets=True, do_results=True):\n #TODO: May need to organize a staging area to ensure this merge is atomic\n if self.mode == 'r': raise ValueError, \"Cannot merge into read-only store\"\n ignored_md = ['uuid', 'avg_learn', 'avg_classify', 'name', 'feature_name', 'class_name']\n\n space_direct_copy = [] # Spaces we copy directly, meaning the featuremap can be copied too\n space_feature_mapping = {}\n if do_spaces or do_datasets:\n # Must do spaces if we do datasets, because spaces may have been updated\n for space_node in ProgressIter(list(other.spaces), label='Copying spaces'):\n logger.debug(\"Considering space '%s'\", space_node._v_name)\n space_name = space_node._v_name\n if hasattr(self.spaces, space_name):\n logger.debug('Already had %s', space_name)\n src_space = other.get_Space(space_name)\n # Need to merge these. Feature spaces can be extended, but there is no mechanism for doing the same with class\n # spaces at the moment, so we must reject any that do not match. \n dst_space = self.get_Space(space_name)\n if src_space == dst_space:\n logger.debug(' Exact match')\n space_direct_copy.append(space_name)\n else:\n md = get_metadata(space_node)\n if md['type'] == 'class':\n raise ValueError, \"Cannot merge due to different versions of %s\" % str(md)\n elif md['type'] == 'feature':\n logger.debug(' Attempting to merge %s', str(md))\n # Reconcile the spaces. \n ## First we need to compute the new features to add\n new_feats = sorted(set(src_space) - set(dst_space))\n logger.debug(' Identified %d new features', len(new_feats))\n reconciled_space = dst_space + new_feats\n if len(new_feats) != 0:\n # Only need to extend if new features are found.\n self.extend_Space(space_name, reconciled_space)\n ## Now we need to build the mapping from the external space to ours\n space_index = dict( (k,v) for v,k in enumerate(reconciled_space))\n space_feature_mapping[space_name] = dict( (i,space_index[s]) for i,s in enumerate(src_space))\n else:\n raise ValueError, \"Unknown type of space\"\n else:\n self.fileh.copyNode(space_node, newparent=self.spaces)\n space_direct_copy.append(space_name)\n \n if do_datasets:\n for src_ds in ProgressIter(list(other.datasets), label='Copying datasets'):\n dsname = src_ds._v_name\n\n logger.debug(\"Considering dataset '%s'\", dsname)\n if hasattr(self.datasets, dsname):\n logger.warning(\"already had dataset '%s'\", dsname)\n dst_ds = getattr(self.datasets, dsname)\n # Failure to match instance_id is an immediate reject\n if dst_ds._v_attrs.instance_space != src_ds._v_attrs.instance_space:\n raise ValueError, \"Instance identifiers don't match for dataset %s\" % dsname\n # The hardest to handle is the feature data, since we may need to rearrange feature maps\n else:\n instance_space = other.get_DatasetMetadata(dsname)['instance_space']\n self.add_Dataset(dsname, instance_space, other.get_Space(dsname))\n dst_ds = getattr(self.datasets, dsname)\n\n node_names = ['class_data', 'sequence', 'tokenstreams']\n for name in node_names:\n logger.debug('Copying %s',name)\n if hasattr(src_ds, name):\n src_parent = getattr(src_ds, name)\n #TODO: may need to handle incomplete destination nodes\n dst_parent = getattr(dst_ds, name)\n for node in src_parent:\n if hasattr(dst_parent, node._v_name):\n logger.warning(\"already had '%s' in '%s'\", node._v_name, name)\n else:\n self.fileh.copyNode(node, newparent=dst_parent, recursive=True)\n else:\n logger.warning(\"Source does not have '%s'\", name)\n\n logger.debug('Copying feature_data')\n for node in src_ds.feature_data:\n space_name = node._v_name\n if hasattr(dst_ds.feature_data, space_name):\n logger.warning(\"already had '%s' in 'feature_data'\", space_name) \n elif space_name in space_direct_copy:\n # Direct copy the feature data because the destination store did not have this\n # space or had exactly this space\n logger.debug(\"direct copy of '%s' in 'feature_data'\", space_name)\n self.fileh.copyNode(node, newparent=dst_ds.feature_data, recursive=True)\n else:\n ax0 = node.feature_map.read(field='ax0')\n ax1 = node.feature_map.read(field='ax1')\n value = node.feature_map.read(field='value')\n feature_mapping = space_feature_mapping[space_name]\n\n feat_map = [ (i,feature_mapping[j],v) for (i,j,v) in zip(ax0,ax1,value)]\n self.add_FeatureDict(dsname, space_name, feat_map)\n\n \n # TASKS & RESULTS\n def __merge(datum, check):\n logger.debug(\"Copying %s\", datum)\n src_node = getattr(other, datum)\n dst_node = getattr(self, datum)\n for t in ProgressIter(list(src_node), label='Copying %s' % datum):\n logger.debug(\"Considering %s '%s'\", datum, t._v_name)\n\n # Check if the exact result has been previously copied\n if t._v_name in dst_node:\n logger.warn(\"Skipping previous %s: %s\", datum, t._v_name)\n else:\n md = get_metadata(t)\n for i in ignored_md: \n if i in md: \n del md[i]\n # Check for equivalent metadata\n if not allow_duplicate and check(md):\n logger.warn(\"Ignoring duplicate in %s: %s\", datum, str(md))\n else:\n try:\n self.fileh.copyNode(t, newparent=dst_node, recursive=True)\n except tables.NoSuchNodeError:\n logger.critical(\"Damaged node skipped\")\n\n if do_tasksets:\n # Copy entire nodes\n __merge('tasksets', self.has_TaskSet)\n # Now work our way through and check if any weights need updating\n for src in ProgressIter(other.get_TaskSets({}), label='Copying weights'):\n if src.node._v_name in self.tasksets:\n dst = StoredTaskSet(self, getattr(self.tasksets, src.node._v_name))\n else:\n md = dict(src.metadata)\n for i in ignored_md: \n if i in md: \n del md[i]\n dst = self.get_TaskSet(md)\n # sanity check for compatibility\n if len(src.tasks) != len(dst.tasks):\n logger.warning('number of tasks in src and dst do not match; skipping')\n continue\n for i, task in enumerate(src.tasks):\n dst.tasks[i].weights.update(src.tasks[i].weights)\n\n if do_results:\n __merge('results', self.has_TaskSetResult)",
"def run(self):\n if self.is_complete:\n LOG.debug(\"Skipping Geopackage, file exists\")\n return\n keys_points = self.feature_selection.key_union('points')\n keys_lines = self.feature_selection.key_union('lines')\n keys_polygons = self.feature_selection.key_union('polygons')\n osmconf = OSMConfig(self.stage_dir,points=keys_points,lines=keys_lines,polygons=keys_polygons)\n conf = osmconf.create_osm_conf()\n ogr_cmd = self.ogr_cmd.safe_substitute({'gpkg': self.output_gpkg,\n 'osm': self.input_pbf, 'osmconf': conf})\n LOG.debug('Running: %s' % ogr_cmd)\n subprocess.check_call(ogr_cmd, shell=True, executable='/bin/bash')\n\n \"\"\"\n Create the default osm gpkg schema\n \"\"\"\n conn = sqlite3.connect(self.output_gpkg)\n conn.enable_load_extension(True)\n cur = conn.cursor()\n cur.execute(\"select load_extension('mod_spatialite')\")\n cur.execute(\"CREATE TABLE boundary (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, geom GEOMETRY)\");\n cur.execute(\"INSERT INTO boundary (geom) VALUES (GeomFromWKB(?,4326));\",(self.aoi_geom.wkb,))\n cur.executescript(SPATIAL_SQL)\n self.update_zindexes(cur,self.feature_selection)\n\n # add themes\n create_sqls, index_sqls = self.feature_selection.sqls\n for query in create_sqls:\n cur.executescript(query)\n for query in index_sqls:\n cur.executescript(query)\n conn.commit()\n conn.close()\n\n if self.per_theme:\n # this creates per-theme GPKGs\n for theme in self.feature_selection.themes:\n conn = sqlite3.connect(self.stage_dir + slugify(theme) + \".gpkg\")\n conn.enable_load_extension(True)\n cur = conn.cursor()\n cur.execute(\"attach database ? as 'geopackage'\",(self.output_gpkg,))\n cur.execute(\"create table gpkg_spatial_ref_sys as select * from geopackage.gpkg_spatial_ref_sys\")\n cur.execute(\"create table gpkg_contents as select * from geopackage.gpkg_contents where 0\")\n cur.execute(\"create table gpkg_geometry_columns as select * from geopackage.gpkg_geometry_columns where 0\")\n for geom_type in self.feature_selection.geom_types(theme):\n for stmt in self.feature_selection.create_sql(theme,geom_type):\n cur.executescript(stmt)\n conn.commit()\n conn.close()",
"def merge(self, obj):\n pass",
"def union(feature):\n\n mp = MultiPolygon([Polygon([tuple(z) for z in y]) for y in feature.coord])\n union = ops.unary_union(mp)\n \n coords = [] \n if union.geom_type == 'Polygon':\n coords.append(np.array(union.exterior.coords))\n if union.geom_type == 'MultiPolygon':\n for x in union.geoms:\n coords.append(np.array(x.exterior.coords))\n\n new_feature = Feature()\n new_feature.coord = coords\n return new_feature",
"def loadModel(self):\n for feature in self.features:\n featureName = feature[\"name\"]\n probabilities = repository.readProbabilities(self.modelName, featureName, self.modelClass)\n probabilities = probabilities.set_index(self.modelClass)\n\n modelForFeature = {\n \"probabilities\": probabilities\n }\n self.model[featureName] = modelForFeature",
"def combine_features(feature1, feature2):\n new_feature = Feature()\n new_feature.coord = feature1.coord.copy()\n for x in feature2.coord:\n new_feature.coord.append(x)\n return new_feature",
"def mergeWith(self, others):",
"def do_merge(self, line):\n self.review.merge()",
"def publish(self):\n # Write the models locally\n local_path_dist = self.dump_distributions()\n local_path_model = self.dump_model()\n\n # Write them to cloud storage\n bucket_path_dist = self.get_bucket_path(self.filename_distributions)\n bucket_path_model = self.get_bucket_path(self.filename_model)\n\n config = self.services.config\n lake = self.services.lake\n\n\n lake.upload(bucket_path_dist, local_path_dist, bucket_name=config.lake_bucket)\n lake.upload(bucket_path_model, local_path_model, bucket_name=config.lake_bucket)\n\n # Now finally we want to write our reference file to our repository and build a merge request\n reference = {\n \"model\": {\n \"bucket\": config.lake_bucket,\n \"path\": bucket_path_model,\n \"md5\": file_md5(local_path_model),\n },\n \"distributions\": {\n \"bucket\": config.lake_bucket,\n \"path\": bucket_path_dist,\n \"md5\": file_md5(local_path_dist),\n },\n }\n\n return reference",
"def _update_agents_model(self, task):\n logger.log('entering _update_agents_model', 'steps: {}'.format(self._steps),\n level=logger.DEBUG + 5)\n if (self.self_infserver_addr is None\n and self._should_update_model(self.self_model, task.model_key1)):\n model1 = self._model_pool_apis.pull_model(task.model_key1)\n me_id = self._learning_agent_id # short name\n self.agents[me_id].load_model(model1.model)\n self.self_model = model1\n if self._should_update_model(self.oppo_model, task.model_key2):\n model2 = self._model_pool_apis.pull_model(task.model_key2)\n oppo_id = self._oppo_agent_id # short name\n for agt in self.agents[oppo_id:]:\n agt.load_model(model2.model)\n self.oppo_model = model2\n logger.log('leaving _update_agents_model', level=logger.DEBUG + 5)",
"def merge(*args):\n from ..operators.observable.merge import merge_\n return merge_(*args)",
"def hetero_model_merge(guest_param: dict, guest_meta: dict, host_params: list, host_metas: list, model_type: str,\n output_format: str, target_name: str = 'y', host_rename=False, include_guest_coef=False):\n guest_param = copy.deepcopy(guest_param)\n guest_meta = copy.deepcopy(guest_meta)\n host_params = copy.deepcopy(host_params)\n host_metas = copy.deepcopy(host_metas)\n\n if not isinstance(model_type, str):\n raise ValueError('model type should be a str, but got {}'.format(model_type))\n\n if output_format.lower() not in {'lightgbm', 'lgb', 'sklearn', 'pmml'}:\n raise ValueError('unknown output format: {}'.format(output_format))\n\n if model_type.lower() in ['secureboost', 'tree', 'sbt']:\n model = merge_sbt(guest_param, guest_meta, host_params, host_metas, output_format, target_name,\n host_rename=host_rename)\n if output_format == 'pmml':\n return get_pmml_str(model, target_name)\n else:\n return model\n\n elif model_type.lower() in {'logistic_regression', 'lr'}:\n model = merge_lr(guest_param, guest_meta, host_params, host_metas, output_format, include_guest_coef)\n if output_format == 'pmml':\n return output_sklearn_pmml_str(model)\n else:\n return json.dumps(str(base64.b64encode(pickle.dumps(model)), \"utf-8\"))\n else:\n raise ValueError('model type should be one in [\"sbt\", \"lr\"], '\n 'but got unknown model type: {}'.format(model_type))",
"def dest_repo_mirror_feature(dest_repo_mirror_master, src_repo):\n repo = dest_repo_mirror_master\n for branch in repo.branches:\n if branch.name == FEATURE_BRANCH:\n branch.checkout()\n\n # Reflect commits #3 and #4 to feature\n commits_data = load_iter_commits(src_repo)\n make_commits(\n repo=repo,\n commits_data=commits_data[DEST_MASTER_COMMITS:DEST_FEATURE_COMMITS],\n has_mirror=True,\n )\n yield repo",
"def merge_global_features(global_features_list: List[Optional[kapture.GlobalFeatures]],\n global_features_paths: List[str], output_path: str,\n tar_handlers: List[TarCollection]) -> kapture.GlobalFeatures:\n features = _merge_image_features(kapture.GlobalFeatures, global_features_list, global_features_paths,\n output_path, tar_handlers)\n assert isinstance(features, kapture.GlobalFeatures)\n return features",
"def add_feature(self, feature):\n self.features += [feature]\n for stock in self.stocks:\n feature(self.stock_data[stock])",
"def merge(self, skel):\n return Skeleton.simple_merge((self, skel)).consolidate()",
"def merge(self):\n try:\n self.save()\n except Exception as e:\n existing = self.session.Sample.find_by_name(self.name)\n if existing:\n if self.sample_type_id == existing.sample_type_id:\n existing.update_properties(self.properties)\n existing.description = self.description\n existing.project = self.project\n existing.save()\n self.reload(existing.dump())\n return True\n else:\n raise e\n else:\n raise e\n return False",
"def merge_models(model_1, model_2, task=None):\n\n def _merge_models(model_1, model_2):\n\n result_model = copy.deepcopy(model_1)\n\n if isinstance(model_1, torch.nn.Embedding):\n\n result_model = _add_embedding_layer(model_1, model_2)\n\n elif isinstance(model_1, torch.nn.Linear):\n result_model = _add_linear_layer(model_1, model_2)\n\n elif isinstance(model_1, torch.nn.LayerNorm):\n result_model = _add_double_norm_layer(model_1, model_2)\n\n elif isinstance(model_1, BertSelfAttention):\n result_model = _add_bert_self_attention_layer(model_1, model_2)\n\n for name_1, name_2 in zip(model_1._modules, model_2._modules):\n module_1 = model_1._modules[name_1]\n module_2 = model_2._modules[name_2]\n\n result_model._modules[name_1] = _merge_models(module_1, module_2)\n\n return result_model\n\n result_model = _merge_models(model_1, model_2)\n\n result_model._text_field_embedder._token_embedders[\"tokens\"].output_dim = 1024\n\n if task == \"QA\":\n result_model._linear_layer = _add_final_linear_layer(\n model_1._linear_layer, model_2._linear_layer\n )\n else:\n result_model._classification_layer = _add_final_linear_layer(\n model_1._classification_layer, model_2._classification_layer\n )\n\n return result_model"
] | [
"0.5925487",
"0.5871774",
"0.56310546",
"0.5571225",
"0.5482358",
"0.5413151",
"0.54008734",
"0.52660817",
"0.525594",
"0.52470225",
"0.5214082",
"0.51863486",
"0.51595527",
"0.51502156",
"0.51408935",
"0.5114687",
"0.5093232",
"0.508917",
"0.50817585",
"0.50575614",
"0.5027815",
"0.5024399",
"0.49926168",
"0.49912673",
"0.49642038",
"0.4957425",
"0.49273953",
"0.49183643",
"0.49172536",
"0.49128327"
] | 0.75115246 | 0 |
! Constructor for the base Solver class. optimization The optimization problem created by calling the build method of the OptimizationBuilder class. error_on_fail When True, after solve() is called, if the solver did not converge then a RuntimeError is thrown. Default is False. An instance of the Solver class. | def __init__(self, optimization: Optimization, error_on_fail: bool = False):
## Instance of the optimization problem.
self.opt = optimization
## Initial guess for the optimization problem (set using reset_initial_seed).
self.x0 = cs.DM.zeros(optimization.nx)
## Parameter vector.
self.p = cs.DM.zeros(optimization.np)
## Parameter dictionary.
self._p_dict = {}
## When True, after solve() is called, if the solver did not converge then a RuntimeError is thrown.
self._error_on_fail = error_on_fail
## Solution container
self._solution = None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def __solve(self) -> None:\n pyo.TransformationFactory(\"contrib.detect_fixed_vars\").apply_to(self.model) # type: ignore\n pyo.TransformationFactory(\"contrib.deactivate_trivial_constraints\").apply_to(self.model) # type: ignore\n\n # initialise the solver object\n self._logger.debug(\"[ModelSolver] Solver object initiated...\")\n solver = Config.OPTIMISATION_MODEL_CONFIG['SOLVER_TYPE']\n opt = pyo.SolverFactory(solver)\n if Config.OPTIMISATION_MODEL_CONFIG['SOLVER_OPTION'].get(solver) is not None:\n for k, v in Config.OPTIMISATION_MODEL_CONFIG['SOLVER_OPTION'].get(solver).items():\n opt.options[k] = v\n\n try:\n start_time = datetime.now()\n self._logger.debug(\"[ModelSolver] Solver starting...\")\n results = opt.solve(self.model, tee=True)\n self.results = results\n end_time = datetime.now()\n self._logger.info(f\"[ModelSolver] Solver completed in {end_time - start_time}.\")\n except Exception as e:\n raise Exception(f\"Model optimisation failed with {solver} with error message {e}.\")\n\n if (results.solver.status == SolverStatus.ok) and (results.solver.termination_condition == TerminationCondition.optimal):\n self._logger.info(\"Solution is feasible and optimal\")\n results.write()\n elif results.solver.termination_condition == TerminationCondition.infeasible:\n raise ValueError(\"Model optimisation resulted into an infeasible solution\")\n\n self.model.optimised = True",
"def __init__(self,optimization:str = 'sparsity',justified_cf:bool = True):\n if optimization not in ['none','sparsity','proximity','plausibility']:\n msg = 'Invalid argument for optimization: \"{}\"'\n raise ValueError(msg.format(optimization))\n self.optimization = optimization\n self.justified_cf = justified_cf\n self.eps = 0.0000001\n #todo check if all inputs are correct. elevate error",
"def solve(self, topology, algorithm=\"SLSQP\", grad=\"AD\", step_size=1e-6, iters=100, eps=1e-6, kappa=1e-8, tmax=100, eta=1e-6, verbose=False):\n if verbose:\n print(\"----------\")\n print(\"Optimization with {} started!\".format(algorithm))\n print(f\"# Parameters: {self.number_of_parameters()}, # Constraints {self.number_of_constraints()}\")\n\n # test for bad stuff before going any further\n self.check_optimization_sanity()\n\n # compose gradient and objective functions\n if grad not in (\"AD\", \"FD\"):\n raise ValueError(f\"Gradient method {grad} is not supported!\")\n if grad == \"AD\":\n if verbose:\n print(\"Computing gradients using automatic differentiation!\")\n x_func = partial(self._optimize_form, topology=topology.copy(), tmax=tmax, eta=eta)\n grad_func = partial(grad_autograd, grad_func=agrad(x_func)) # x, grad, x_func\n\n elif grad == \"FD\":\n if verbose:\n print(f\"Warning: Calculating gradients using finite differences with step size {step_size}. This may take a while...\")\n grad_func = self.gradient_func(grad_finite_differences, topology.copy(), tmax, eta, step_size)\n\n # grad_func = self.gradient_func(grad_func, topology.copy(), tmax, eta, step_size)\n obj_func = self.objective_func(topology, grad_func, tmax, eta)\n\n # generate optimization variables\n x = self.optimization_parameters(topology)\n\n # extract the lower and upper bounds to optimization variables\n bounds_low, bounds_up = self.optimization_bounds(topology)\n\n # stack keyword arguments\n hyper_parameters = {\"f\": obj_func,\n \"algorithm\": algorithm,\n \"dims\": self.number_of_parameters(),\n \"bounds_low\": bounds_low,\n \"bounds_up\": bounds_up,\n \"iters\": iters,\n \"eps\": eps,\n \"ftol\": kappa}\n\n # assemble optimization solver\n solver = nlopt_solver(**hyper_parameters)\n\n # solve optimization problem\n x_opt = None\n start = time()\n try:\n x_opt = solver.optimize(x)\n if verbose:\n print(\"Optimization ended correctly!\")\n except RoundoffLimited:\n print(\"Optimization was halted because roundoff errors limited progress\")\n print(\"Results may still be useful though!\")\n x_opt = self.optimization_parameters(topology)\n except RuntimeError:\n print(\"Optimization failed due to a runtime error!\")\n print(f\"Optimization total runtime: {round(time() - start, 4)} seconds\")\n return static_equilibrium(topology)\n\n # fetch last optimum value of loss function\n time_opt = time() - start\n loss_opt = solver.last_optimum_value()\n evals = solver.get_numevals()\n status = nlopt_status(solver.last_optimize_result())\n\n # set optimizer attributes\n self.time_opt = time_opt\n self.x_opt = x_opt\n self.penalty = loss_opt\n self.evals = evals\n self.status = status\n\n # set norm of the gradient\n # NOTE: np.zeros is a dummy array (signature requirement set by nlopt)\n self.gradient = grad_func(x_opt, np.zeros(x_opt.size))\n self.gradient_norm = np.linalg.norm(self.gradient)\n\n if verbose:\n print(f\"Optimization total runtime: {round(time_opt, 6)} seconds\")\n print(\"Number of evaluations incurred: {}\".format(evals))\n print(f\"Final value of the objective function: {round(loss_opt, 6)}\")\n print(f\"Norm of the gradient of the objective function: {round(self.gradient_norm, 6)}\")\n print(f\"Optimization status: {status}\".format(status))\n print(\"----------\")\n\n # exit like a champion\n return static_equilibrium(topology)",
"def optimize_problem(self, request):\n s = json.dumps(request)\n # Create object that stores optimization problem\n prob = trajoptpy.ConstructProblem(s, self.scene.env)\n t_start = time.time()\n result = trajoptpy.OptimizeProblem(prob) # do optimization\n t_elapsed = time.time() - t_start\n print(result)\n print(\"optimization took %.3f seconds\" % t_elapsed)\n\n # from trajoptpy.check_traj import traj_is_safe\n # prob.SetRobotActiveDOFs() # set robot DOFs to DOFs in optimization problem\n # assert traj_is_safe(result.GetTraj(), self.scene.robot) # Check that trajectory is collision free\n\n return result",
"def optimize(self):\n\n self.logger.info(\"Solving with Dynamic Slope Scaling Procedure in Julia :\")\n optimization_start = time.time()\n\n # 1. Preprocess for old network graph\n if self.old_network_graph is not None:\n\n # DSSP on old network\n old_network_obj = sum(list(nx.get_node_attributes(self.old_network_graph, config.BUILDING_CONSUMPTION_KEY).values()))-1e-5\n try:\n self.check_infeasibility(self.old_network_graph, old_network_obj)\n except DHCOptimizerException as e:\n e.data = \"Invalid existing network: \" + e.data\n raise e\n\n flows, obj_val = self.optimize_with_dssp_julia(self.old_network_graph, old_network_obj, set())\n self.logger.info(\"Optimization phase time: %.2fs\" % (time.time() - optimization_start))\n solution_old_graph = self.build_solution_graph(self.old_network_graph, flows)\n\n if self.modify_old_network:\n\n # Add max capacity on old edges\n self.old_capacity = deepcopy(flows)\n old_buildings = list(nx.get_node_attributes(self.old_network_graph, config.BUILDING_CONSUMPTION_KEY).values())\n for key in flows:\n if (key[1],key[0],0) not in self.old_capacity and key[1] not in old_buildings:\n self.old_capacity[(key[1],key[0],0)] = self.old_capacity[key]\n\n # Add Imaginary edges\n for edge in self.old_capacity:\n if self.optimization_graph.has_edge(*edge):\n\n # add nodes\n if not self.optimization_graph.has_node(config.IM_PREFIX+edge[0]):\n self.optimization_graph.add_node(config.IM_PREFIX+edge[0])\n self.optimization_graph.nodes[config.IM_PREFIX+edge[0]][config.GPD_GEO_KEY] = \\\n self.optimization_graph.nodes[edge[0]][config.GPD_GEO_KEY]\n if not self.optimization_graph.has_node(config.IM_PREFIX+edge[1]):\n self.optimization_graph.add_node(config.IM_PREFIX+edge[1])\n self.optimization_graph.nodes[config.IM_PREFIX+edge[1]][config.GPD_GEO_KEY] = \\\n self.optimization_graph.nodes[edge[1]][config.GPD_GEO_KEY]\n # add edges\n if not self.optimization_graph.has_edge(edge[0],config.IM_PREFIX+edge[0]):\n self.optimization_graph.add_edge(edge[0],config.IM_PREFIX+edge[0])\n if not self.optimization_graph.has_edge(config.IM_PREFIX+edge[0],config.IM_PREFIX+edge[1]):\n self.optimization_graph.add_edge(config.IM_PREFIX+edge[0],config.IM_PREFIX+edge[1])\n if not self.optimization_graph.has_edge(config.IM_PREFIX+edge[1],edge[1]):\n self.optimization_graph.add_edge(config.IM_PREFIX+edge[1],edge[1])\n\n # put cost\n self.optimization_graph.edges[(config.IM_PREFIX+edge[0],config.IM_PREFIX+edge[1],0)][config.EDGE_COST_KEY] = \\\n self.optimization_graph.edges[(edge[0],edge[1],0)][config.EDGE_COST_KEY]\n self.optimization_graph.edges[(edge[0],edge[1],0)][config.EDGE_COST_KEY] = 1e-5\n self.optimization_graph.edges[(edge[0],config.IM_PREFIX+edge[0],0)][config.EDGE_COST_KEY] = 1e-5\n self.optimization_graph.edges[(config.IM_PREFIX+edge[1],edge[1],0)][config.EDGE_COST_KEY] = 1e-5\n\n else:\n # if we don't modify the old network, we have to change the capacity of the supplies\n already_consummed = {}\n for edge in solution_old_graph.edges():\n if solution_old_graph.nodes[edge[0]].get(config.NODE_TYPE_KEY) == config.SUPPLY_NODE_TYPE:\n already_consummed[edge[0]] = already_consummed.get(edge[0], 0) + \\\n solution_old_graph.edges[edge][config.SOLUTION_POWER_FLOW_KEY]\n for source in already_consummed:\n if already_consummed[source] <= self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY]:\n self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY] -= already_consummed[source]\n self.network_objective -= already_consummed[source]\n else:\n self.network_objective -= self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY]\n self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY] = 0\n\n # Remove edges from old network\n edges_to_remove = set()\n for e in self.optimization_graph.edges():\n if self.old_network_graph.has_edge(*e) or self.old_network_graph.has_edge(e[1],e[0]):\n edges_to_remove.add(e)\n self.optimization_graph.remove_edges_from(edges_to_remove)\n\n # Remove isolated buildings of optimization graph\n isolated_to_remove = set()\n for e in self.old_network_graph.edges():\n if e[0] in self.old_network_graph.nodes() and \\\n self.optimization_graph.nodes[e[1]].get(config.NODE_TYPE_KEY) == config.BUILDING_NODE_TYPE:\n isolated_to_remove.add(e)\n self.optimization_graph.remove_edges_from(isolated_to_remove)\n\n # Remove buildings from old network\n for n, data in self.old_network_graph.nodes(data=True):\n if data.get(config.NODE_TYPE_KEY) == config.BUILDING_NODE_TYPE:\n self.optimization_graph.remove_node(n)\n\n # Re-link sources\n sources = set()\n for n, data in self.optimization_graph.nodes(data=True):\n if data.get(config.NODE_TYPE_KEY) == config.SUPPLY_NODE_TYPE:\n sources.add(n)\n source_graph = self.optimization_graph.subgraph(sources).copy()\n self.optimization_graph.remove_nodes_from(sources)\n gnx.remove_isolates(self.optimization_graph)\n node_filter = lambda n: self.optimization_graph.nodes.get(n,{}).get(config.NODE_TYPE_KEY) != config.BUILDING_NODE_TYPE\n gnx.spatial_points_merge(self.optimization_graph, source_graph.nodes_to_gdf(), node_filter=node_filter, inplace=True)\n\n # fill missing information\n gnx.fill_edges_missing_geometry_attributes(self.optimization_graph)\n gnx.fill_length_attribute(self.optimization_graph, config.EDGE_LENGTH_KEY, only_missing=True)\n gnx.fill_length_attribute(self.optimization_graph, config.EDGE_COST_KEY, only_missing=True)\n for e in self.optimization_graph.edges(keys=True):\n self.optimization_graph.edges[e][config.LEASTCOST_COEF_KEY] = \\\n self.optimization_graph.edges[e].get(config.LEASTCOST_COEF_KEY,0)\n\n\n\n # 2. Process the DSSP on optimization graph\n self.check_is_ready()\n self.check_infeasibility(self.optimization_graph, self.network_objective)\n\n if self.old_network_graph is not None and self.modify_old_network:\n old_buildings = set(nx.get_node_attributes(self.old_network_graph, config.BUILDING_CONSUMPTION_KEY).keys())\n else:\n old_buildings = set()\n flows, obj_val = self.optimize_with_dssp_julia(self.optimization_graph, self.network_objective, old_buildings,postprocess= (not self.modify_old_network))\n self.logger.info(\"Optimization phase time: %.2fs\" % (time.time() - optimization_start))\n self.solution_graph = self.build_solution_graph(self.optimization_graph, flows, self.connected)\n\n # 3. Postprocess for old network graph\n if self.old_network_graph is not None:\n \n if self.modify_old_network:\n # Put the right supply capacity and cost\n for edge in self.old_capacity:\n if self.solution_graph.has_edge(edge[0],edge[1]):\n self.solution_graph.edges[(edge[0],edge[1])][config.EDGE_COST_KEY] = \\\n self.optimization_graph.edges[(config.IM_PREFIX+edge[0],config.IM_PREFIX+edge[1],0)][config.EDGE_COST_KEY]\n \n # Remove imaginary edges\n imaginary_nodes_to_remove = set()\n nodes_to_relabel = {}\n for edge in self.solution_graph.edges():\n if str(edge[0]).startswith(config.IM_PREFIX) and str(edge[1]).startswith(config.IM_PREFIX):\n real_edge = edge[0][len(config.IM_PREFIX):],edge[1][len(config.IM_PREFIX):]\n self.old_capacity[(real_edge[0], real_edge[1], 0)] = pd.np.inf\n self.old_capacity[(real_edge[1], real_edge[0], 0)] = pd.np.inf\n if not self.solution_graph.has_edge(*real_edge):\n for i in range(2):\n nodes_to_relabel[edge[i]] = real_edge[i]\n else:\n self.solution_graph.edges[real_edge[0],real_edge[1]][config.SOLUTION_POWER_FLOW_KEY] += \\\n self.solution_graph.edges[edge].get(config.SOLUTION_POWER_FLOW_KEY,0)\n imaginary_nodes_to_remove.add(edge[0])\n imaginary_nodes_to_remove.add(edge[1])\n elif str(edge[0]).startswith(config.IM_PREFIX):\n imaginary_nodes_to_remove.add(edge[0])\n elif str(edge[1]).startswith(config.IM_PREFIX):\n imaginary_nodes_to_remove.add(edge[1])\n\n nx.relabel_nodes(self.solution_graph, nodes_to_relabel, copy=False)\n self.solution_graph.remove_nodes_from(list(imaginary_nodes_to_remove))\n for node in nodes_to_relabel.values():\n if self.solution_graph.has_edge(node, node):\n self.solution_graph.remove_edge(node, node)\n\n else:\n for source in nx.get_node_attributes(self.solution_graph, config.SUPPLY_POWER_CAPACITY_KEY):\n self.solution_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY] += already_consummed.get(source,0)\n self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY] += already_consummed.get(source,0)\n\n return flows, obj_val",
"def setup(\n self,\n method: str = \"SLSQP\",\n tol: Union[None, float] = None,\n options: Union[None, Dict] = None,\n ):\n\n # Input check\n if self.opt_type in CONSTRAINED_OPT and (\n method not in ScipyMinimizeSolver.methods_handle_constraints\n ):\n raise TypeError(\n f\"optimization problem has constraints, the method '{method}' is not suitable\"\n )\n\n # Setup class attributes\n\n ## Container for the statistics.\n self._stats = None\n\n ## Method name.\n self.method = method\n\n # Setup minimize input parameters\n\n ## Input to the minimize method\n self.minimize_input = {\n \"fun\": self.f,\n \"method\": method,\n \"x0\": self.x0.toarray().flatten(),\n }\n\n if tol is not None:\n self.minimize_input[\"tol\"] = tol\n\n if options is not None:\n self.minimize_input[\"options\"] = options\n\n if method in ScipyMinimizeSolver.methods_req_jac:\n self.minimize_input[\"jac\"] = self.jac\n\n if method in ScipyMinimizeSolver.methods_req_hess:\n self.minimize_input[\"hess\"] = self.hess\n\n ## Constraints definition passed to the minimize method.\n self._constraints = {}\n if method in ScipyMinimizeSolver.methods_handle_constraints:\n if method != \"trust-constr\":\n if self.opt_type in CONSTRAINED_OPT:\n self._constraints[\"constr\"] = {\n \"type\": \"ineq\",\n \"fun\": self.v,\n \"jac\": self.dv,\n }\n else:\n if self.opt.nk:\n self._constraints[\"k\"] = LinearConstraint(\n A=csc_matrix(self.opt.M(self.p).toarray()),\n lb=-self.opt.c(self.p).toarray().flatten(),\n ub=self.opt.inf * np.ones(self.opt.nk),\n )\n\n if self.opt.na:\n eq = -self.opt.b(self.p).toarray().flatten()\n self._constraints[\"a\"] = LinearConstraint(\n A=csc_matrix(self.opt.A(self.p).toarray()),\n lb=eq,\n ub=eq,\n )\n\n if self.opt.ng:\n self._constraints[\"g\"] = NonlinearConstraint(\n fun=self.g,\n lb=np.zeros(self.opt.ng),\n ub=self.opt.inf * np.ones(self.opt.ng),\n jac=self.dg,\n hess=self.ddg,\n )\n\n if self.opt.nh:\n self._constraints[\"h\"] = NonlinearConstraint(\n fun=self.h,\n lb=np.zeros(self.opt.nh),\n ub=np.zeros(self.opt.nh),\n jac=self.dh,\n hess=self.ddh,\n )\n\n return self",
"def fit(self):\n if self.minimizer == \"differential_evolution\":\n kwargs = {\"maxiter\": self._maxiter}\n elif self.minimizer == \"shgo\":\n kwargs = {\"options\": {\"maxiter\": self._maxiter,\n \"jac\": self.cost_func.jac_cost}}\n elif self.minimizer == \"dual_annealing\":\n kwargs = {\"maxiter\": self._maxiter, \"local_search_options\": {\n \"jac\": self.cost_func.jac_cost}}\n fun = self.cost_func.eval_cost\n bounds = self.value_ranges\n algorithm = getattr(optimize, self.minimizer)\n result = algorithm(fun, bounds, **kwargs)\n self._popt = result.x\n if result.success:\n self._status = 0\n elif \"Maximum number of iteration\" in result.message:\n self._status = 1\n else:\n self._status = 2",
"def solve(self, **kwargs) -> OptimizationResult:\n raise NotImplementedError",
"def run(self, problem):\n\n self.pyopt_solution = None\n rel = problem.root._probdata.relevance\n\n # Metadata Setup\n self.metadata = create_local_meta(None, self.options['optimizer'])\n self.iter_count = 0\n update_local_meta(self.metadata, (self.iter_count,))\n\n # Initial Run\n with problem.root._dircontext:\n problem.root.solve_nonlinear(metadata=self.metadata)\n\n opt_prob = Optimization(self.options['title'], self._objfunc)\n\n # Add all parameters\n param_meta = self.get_desvar_metadata()\n self.indep_list = indep_list = list(param_meta)\n param_vals = self.get_desvars()\n\n for name, meta in iteritems(param_meta):\n opt_prob.addVarGroup(name, meta['size'], type='c',\n value=param_vals[name],\n lower=meta['lower'], upper=meta['upper'])\n\n opt_prob.finalizeDesignVariables()\n\n # Figure out parameter subsparsity for paramcomp index connections.\n # sub_param_conns is empty unless there are some index conns.\n # full_param_conns gets filled with the connections to the entire\n # parameter so that those params can be filtered out of the sparse\n # set if the full path is also relevant\n sub_param_conns = {}\n full_param_conns = {}\n for name in indep_list:\n pathname = problem.root.unknowns.metadata(name)['pathname']\n sub_param_conns[name] = {}\n full_param_conns[name] = set()\n for target, info in iteritems(problem.root.connections):\n src, indices = info\n if src == pathname:\n if indices is not None:\n # Need to map the connection indices onto the desvar\n # indices if both are declared.\n dv_idx = param_meta[name].get('indices')\n indices = set(indices)\n if dv_idx is not None:\n indices.intersection_update(dv_idx)\n ldv_idx = list(dv_idx)\n mapped_idx = [ldv_idx.index(item) for item in indices]\n sub_param_conns[name][target] = mapped_idx\n else:\n sub_param_conns[name][target] = indices\n else:\n full_param_conns[name].add(target)\n\n # Add all objectives\n objs = self.get_objectives()\n self.quantities = list(objs)\n self.sparsity = OrderedDict()\n self.sub_sparsity = OrderedDict()\n for name in objs:\n opt_prob.addObj(name)\n self.sparsity[name] = self.indep_list\n\n # Calculate and save gradient for any linear constraints.\n lcons = self.get_constraints(lintype='linear').keys()\n if len(lcons) > 0:\n self.lin_jacs = problem.calc_gradient(indep_list, lcons,\n return_format='dict')\n #print(\"Linear Gradient\")\n #print(self.lin_jacs)\n\n # Add all equality constraints\n econs = self.get_constraints(ctype='eq', lintype='nonlinear')\n con_meta = self.get_constraint_metadata()\n self.quantities += list(econs)\n\n self.active_tols = {}\n for name in self.get_constraints(ctype='eq'):\n meta = con_meta[name]\n size = meta['size']\n lower = upper = meta['equals']\n\n # Sparsify Jacobian via relevance\n rels = rel.relevant[name]\n wrt = rels.intersection(indep_list)\n self.sparsity[name] = wrt\n\n if meta['linear']:\n opt_prob.addConGroup(name, size, lower=lower, upper=upper,\n linear=True, wrt=wrt,\n jac=self.lin_jacs[name])\n else:\n\n jac = self._build_sparse(name, wrt, size, param_vals,\n sub_param_conns, full_param_conns, rels)\n opt_prob.addConGroup(name, size, lower=lower, upper=upper,\n wrt=wrt, jac=jac)\n\n active_tol = meta.get('active_tol')\n if active_tol:\n self.active_tols[name] = active_tol\n\n # Add all inequality constraints\n incons = self.get_constraints(ctype='ineq', lintype='nonlinear')\n self.quantities += list(incons)\n\n for name in self.get_constraints(ctype='ineq'):\n meta = con_meta[name]\n size = meta['size']\n\n # Bounds - double sided is supported\n lower = meta['lower']\n upper = meta['upper']\n\n # Sparsify Jacobian via relevance\n rels = rel.relevant[name]\n wrt = rels.intersection(indep_list)\n self.sparsity[name] = wrt\n\n if meta['linear']:\n opt_prob.addConGroup(name, size, upper=upper, lower=lower,\n linear=True, wrt=wrt,\n jac=self.lin_jacs[name])\n else:\n\n jac = self._build_sparse(name, wrt, size, param_vals,\n sub_param_conns, full_param_conns, rels)\n opt_prob.addConGroup(name, size, upper=upper, lower=lower,\n wrt=wrt, jac=jac)\n\n active_tol = meta.get('active_tol')\n if active_tol is not None:\n self.active_tols[name] = active_tol\n\n # Instantiate the requested optimizer\n optimizer = self.options['optimizer']\n try:\n _tmp = __import__('pyoptsparse', globals(), locals(), [optimizer], 0)\n opt = getattr(_tmp, optimizer)()\n except ImportError:\n msg = \"Optimizer %s is not available in this installation.\" % \\\n optimizer\n raise ImportError(msg)\n\n #Set optimization options\n for option, value in self.opt_settings.items():\n opt.setOption(option, value)\n\n self._problem = problem\n self.opt_prob = opt_prob\n\n # Execute the optimization problem\n if self.options['gradient method'] == 'pyopt_fd':\n\n # Use pyOpt's internal finite difference\n fd_step = problem.root.deriv_options['step_size']\n sol = opt(opt_prob, sens='FD', sensStep=fd_step, storeHistory=self.hist_file)\n\n elif self.options['gradient method'] == 'snopt_fd':\n if self.options['optimizer']=='SNOPT':\n\n # Use SNOPT's internal finite difference\n fd_step = problem.root.deriv_options['step_size']\n sol = opt(opt_prob, sens=None, sensStep=fd_step, storeHistory=self.hist_file)\n\n else:\n msg = \"SNOPT's internal finite difference can only be used with SNOPT\"\n raise Exception(msg)\n else:\n\n # Use OpenMDAO's differentiator for the gradient\n sol = opt(opt_prob, sens=self._gradfunc, storeHistory=self.hist_file)\n\n self._problem = None\n\n # Print results\n if self.options['print_results']:\n print(sol)\n\n # Pull optimal parameters back into framework and re-run, so that\n # framework is left in the right final state\n dv_dict = sol.getDVs()\n for name in indep_list:\n val = dv_dict[name]\n self.set_desvar(name, val)\n\n with self.root._dircontext:\n self.root.solve_nonlinear(metadata=self.metadata)\n\n # Save the most recent solution.\n self.pyopt_solution = sol\n try:\n exit_status = sol.optInform['value']\n self.exit_flag = 1\n if exit_status > 2: # bad\n self.exit_flag = 0\n except KeyError: #nothing is here, so something bad happened!\n self.exit_flag = 0",
"def __init__(self, optimizer='BFGS', optimizer_kwargs=None,\n lossprime=True, max_iterations = 1000000):\n\n user_kwargs = optimizer_kwargs\n optimizer_kwargs = {}\n print(f\"in {optimizer}: max_iterations = {max_iterations}\")\n if optimizer == 'BFGS':\n from scipy.optimize import minimize as optimizer\n optimizer_kwargs = {\n 'method' : 'BFGS',\n 'options': {'gtol': 1e-15,\n 'maxiter': max_iterations}\n }\n #optimizer_kwargs = {'method':'BFGS', 'gtol': 1e-15, }\n elif optimizer == 'L-BFGS-B':\n from scipy.optimize import minimize as optimizer\n optimizer_kwargs = {\n 'method': 'L-BFGS-B',\n 'options': {'ftol': 1e-05,\n 'gtol': 1e-08,\n 'maxfun': max_iterations,\n 'maxiter': max_iterations}\n }\n import scipy\n from distutils.version import StrictVersion\n if StrictVersion(scipy.__version__) >= StrictVersion('0.17.0'):\n optimizer_kwargs['options']['maxls'] = 2000\n elif optimizer == 'TNC':\n from scipy.optimize import minimize as optimizer\n optimizer_kwargs = {\n 'method': 'TNC',\n 'options': {'ftol': 0.,\n 'xtol': 0.,\n 'gtol': 1e-08,\n 'maxiter': max_iterations, }\n }\n elif optimizer == 'Newton-CG':\n from scipy.optimize import minimize as optimizer\n optimizer_kwargs = {\n 'method': 'Newton-CG',\n 'options': {'xtol': 1e-15,\n 'maxiter': max_iterations,}\n }\n\n elif optimizer == 'Nelder-Mead':\n from scipy.optimize import minimize as optimizer\n optimizer_kwargs = {\n 'method': 'Nelder-Mead',\n 'options': {'maxfun': max_iterations,\n 'maxiter': max_iterations, }\n }\n lossprime = False\n\n if user_kwargs:\n optimizer_kwargs.update(user_kwargs)\n self.optimizer = optimizer\n self.optimizer_kwargs = optimizer_kwargs\n self.lossprime = lossprime",
"def solve(self):\n # check for jacobian and set it if present and to be used\n if self.use_sparse:\n if self._use_jac and hasattr(self.problem,'sparse_jac'):\n jac = self.problem.sparse_jac\n else:\n jac = None\n else:\n if self._use_jac and hasattr(self.problem,'jac'):\n jac = self.problem.jac\n else:\n jac = None\n \n # Initialize solver and solve \n \n solved = False\n local_min = False\n\n res = N.zeros(self.x0.__len__())\n while (not solved) and self.reg_count < 2:\n try:\n if self._use_fscale:\n self.solver.KINSOL_init(self.func,self.x0,self.dim,jac,self.constraints,self.use_sparse,self.verbosity,self.norm_of_res,self.reg_param,self.fscale)\n else:\n self.solver.KINSOL_init(self.func,self.x0,self.dim,jac,self.constraints,self.use_sparse,self.verbosity,self.norm_of_res,self.reg_param,None)\n start = time.clock()\n res = self.solver.KINSOL_solve(not self._use_ls)\n stop = time.clock()\n self.exec_time += (stop - start)\n solved = True\n except KINError as error:\n if error.value == 42:\n # Try the heuristic\n if hasattr(self.problem, 'get_heuristic_x0'):\n print \"----------------------------------------------------\"\n print \" Solver stuck with zero step-length.\"\n print \"----------------------------------------------------\"\n print \"The following variables have start value zero\"\n print \"and min set to zero causing the zero step-lenght.\"\n print \"These settings are either set by default or by user.\"\n print \"\"\n\n self.x0 = self.problem.get_heuristic_x0()\n self.reg_count += 1\n \n print \"\"\n print \"This setting (start and min to zero) can often\"\n print \"cause problem when initializing the system. \"\n print \"\"\n print \"To avoid this the above variables have\"\n print \"their start attributes reset to one.\"\n print \"\"\n print \"Trying to solve the system again...\"\n else:\n raise KINSOL_Exception(\"Regularization failed due to constraints, tried getting heuristic initial guess but failed.\")\n \n\n elif (error.value == 2):\n print \"---------------------------------------------------------\"\n print \"\"\n print \" !!! WARNING !!!\"\n print \"\"\n print \" KINSOL has returned a result but the algorithm has converged\"\n print \" to a local minima, the initial values are NOT consistant!\"\n print \"\"\n print \"---------------------------------------------------------\"\n solved = True\n local_min = True\n else:\n # Other error, send onward as exception\n self.problem.check_constraints(res)\n raise KINSOL_Exception(error.msg[error.value])\n \n if not solved:\n self.solver.Free_KINSOL()\n raise KINSOL_Exception(\"Algorithm exited solution loop without finding a solution, please contact Assimulo support.\")\n\n if self.check_with_model:\n self.problem.check_constraints(res)\n if not local_min:\n print \"Problem sent to KINSOL solved.\"\n \n return res",
"def solve(\n self, preconditioner='none', tol=1e-5,\n operator_parameters=None, preconditioner_parameters=None\n ):\n time_assemble = -time.clock() # start timer\n\n self.operator = self.assemble_operator(operator_parameters)\n self.rhs = self.assemble_rhs(operator_parameters)\n\n if preconditioner == 'none':\n super_operator = self.operator\n super_rhs = self.rhs\n elif preconditioner == 'diagonal':\n diagonal = self.get_diagonal(preconditioner_parameters) \n super_operator = diagonal * self.operator\n super_rhs = diagonal * self.rhs\n elif preconditioner == 'self':\n preconditioner = self.get_op_as_preconditioner(preconditioner_parameters)\n super_operator = preconditioner * self.operator\n super_rhs = preconditioner * self.rhs\n # elif preconditioner == 'electric-interior':\n # pass\n else:\n raise NotImplementedError(\n \"Preconditioner '%s' not supported\" % preconditioner)\n\n if hasattr(super_operator, 'strong_form'):\n super_operator.strong_form(True)\n \n time_assemble += time.clock() # stop timer\n\n bempp.api.MATVEC_COUNT = 0 # reset the MATVEC counter to 0\n solve_time = -time.clock() # initialise the timer\n sol, solve_info, residuals = self._gmres(super_operator, super_rhs, tol)\n solve_time += time.clock() # stop the timer\n matvec_count = bempp.api.MATVEC_COUNT # sample the matvec counter\n \n info = dict(\n status=solve_info,\n time_solve=solve_time,\n time_assemble=time_assemble,\n matvec_count=matvec_count\n )\n if isinstance(sol[0], np.complex128):\n return Solution(coefficients=sol, info=info, residuals=residuals, system=self) \n else:\n return Solution(traces=sol, info=info, residuals=residuals, system=self)",
"def __init__(self, opts: dict, solver_opts: dict):\n self.name = opts.get(\"name\", \"Undefined\") # Name of the problem\n self.gp = opts.get(\"grid_points\") # Number of grid points\n self.nadir_p = opts.get(\"nadir_points\") # Nadir points\n self.eps = opts.get(\"penalty_weight\", 1e-3) # Penalty weight\n self.round = opts.get(\"round_decimals\", 9) # Decimal places to round to\n self.nadir_r = opts.get(\"nadir_ratio\", 1) # Nadir ratio\n self.logdir = opts.get(\"logging_folder\", \"logs\") # Folder to save logs\n self.early_exit = opts.get(\"early_exit\", True) # Whether to enable early exit\n self.bypass = opts.get(\"bypass_coefficient\", True) # Whether to enable bypass coefficient\n self.flag = opts.get(\"flag_array\", True) # Whether to use flag array\n self.cpu_count = opts.get(\"cpu_count\", cpu_count()) # Number of CPUs to use\n self.redivide_work = opts.get(\"redivide_work\", True) # Whether to redivide work\n self.model_fn = opts.get(\"pickle_file\", \"model.p\") # Pickle file name\n self.shared_flag = opts.get(\"shared_flag\", True) # Whether to use shared flag array\n self.output_excel = opts.get(\"output_excel\", True) # Whether to output to Excel\n self.process_logging = opts.get(\"process_logging\", False) # Whether to enable process logging\n self.process_timeout = opts.get(\"process_timeout\", None) # Timeout for processes\n self.solver_name = opts.get(\"solver_name\", \"gurobi\") # Name of solver\n self.solver_io = opts.get(\"solver_io\", \"python\") # IO mode of solver\n\n self.solver_opts = solver_opts # Solver options\n self.solver_opts[\"MIPGap\"] = solver_opts.get(\"MIPGap\", 0.0) # MIP gap\n self.solver_opts[\"NonConvex\"] = solver_opts.get(\"NonConvex\", 2) # Nonconvex setting\n\n # Remove None values from dict when user has overriden them\n for key, value in dict(self.solver_opts).items():\n if value is None or value:\n del self.solver_opts[key]\n\n self.time_created = time.strftime(\"%Y%m%d-%H%M%S\") # Time the options object was created\n self.log_name = self.name + \"_\" + str(self.time_created) # Name of log file",
"def minimize(problem,\n algorithm,\n termination=None,\n **kwargs):\n\n # create a copy of the algorithm object to ensure no side-effects\n algorithm = copy.deepcopy(algorithm)\n\n # set the termination criterion and store it in the algorithm object\n if termination is None:\n termination = None\n elif not isinstance(termination, Termination):\n if isinstance(termination, str):\n termination = get_termination(termination)\n else:\n termination = get_termination(*termination)\n\n # initialize the method given a problem\n algorithm.initialize(problem,\n termination=termination,\n **kwargs)\n\n if algorithm.termination is None:\n if problem.n_obj > 1:\n algorithm.termination = MultiObjectiveDefaultTermination()\n else:\n algorithm.termination = SingleObjectiveDefaultTermination()\n\n # actually execute the algorithm\n res = algorithm.solve()\n\n # store the copied algorithm in the result object\n res.algorithm = algorithm\n\n return res",
"def do_optimisation(self):\n\n print('--> Parameters for optimisation:')\n print('--> Using measurements : {}'.format(self.stoma_cfg.comparison_helper.optimisation_keys))\n print('')\n\n x0 = self.initial_guess()\n\n tol, eps = 1e-4, 0.001\n\n print('--> Using SLSQP with tol={} and eps={}'.format(tol, eps))\n\n soln = opt.minimize(fun=self.optimise_fn,\n x0=x0,\n method='SLSQP',\n tol=tol,\n options={'eps': eps})\n\n print('*' * 120)\n print('--> Optimisation procedure has finished...')\n print(soln)\n print('*' * 120)\n\n if soln.success:\n print('--> Optimisation succeeded. Result is...')\n self._set_material_parameters(soln.x)\n print('--> {}'.format(self.material_model))\n else:\n print('--> The optimisation failed!')\n\n print('*' * 120)\n\n return soln",
"def _optimize(self, objective):\n # Initial value\n initial = self.get_initial()[0]\n\n if self.vector_to_matrix_transform is not None:\n initial = self.vector_to_matrix_transform(initial)\n\n if self.solver_type is 'NelderMead' or self.solver_type is 'ParticleSwarm':\n initial = None\n\n # Create tensorflow variable\n if self.matrix_manifold_dimension is None:\n x_tf = tf.Variable(tf.zeros(self.dimension, dtype=tf.float64))\n else:\n x_tf = tf.Variable(tf.zeros([self.matrix_manifold_dimension, self.matrix_manifold_dimension], dtype=tf.float64))\n\n # Cost function for pymanopt\n def objective_fct(x):\n if self.matrix_to_vector_transform_tf is not None:\n # Reshape x from matrix to vector form to compute the objective function (tensorflow format)\n x = self.matrix_to_vector_transform_tf(x, self.matrix_manifold_dimension)\n return objective(x)[0]\n\n # Transform the cost function to tensorflow function\n cost = tf.py_function(objective_fct, [x_tf], tf.float64)\n\n # Gradient function for pymanopt\n def objective_grad(x):\n if self.matrix_to_vector_transform is not None:\n # Reshape x from matrix to vector form to compute the gradient\n x = self.matrix_to_vector_transform(x)\n\n # Compute the gradient\n grad = np.array(objective(x)[1])[0]\n\n if self.vector_to_matrix_transform is not None:\n # Reshape the gradient in matrix form for the optimization on the manifold\n grad = self.vector_to_matrix_transform(grad)\n return grad\n\n # Define pymanopt problem\n problem = pyman.Problem(manifold=self.manifold, cost=cost, egrad=objective_grad, arg=x_tf, verbosity=2)\n\n # Optimize the parameters of the problem\n opt_x, opt_log = self.solver.solve(problem, x=initial)\n\n if self.matrix_to_vector_transform is not None:\n # Reshape the optimum from matrix to vector form\n opt_x = self.matrix_to_vector_transform(opt_x)\n\n # Format the result to fit with GPflowOpt\n result = sc_opt.OptimizeResult(x=opt_x, fun=opt_log['final_values']['f(x)'], nit=opt_log['final_values']['iterations'], message=opt_log['stoppingreason'], success=True)\n\n return result",
"def setup_solver(self):\n option = Options()\n if logger.getEffectiveLevel() == logging.DEBUG:\n # option.printLevel = PrintLevel.HIGH\n option.printLevel = PrintLevel.NONE\n else:\n option.printLevel = PrintLevel.NONE\n self.solver_minimizing = SQProblem(self.nV, self.nC)\n self.solver_minimizing.setOptions(option)\n self.solver_maximizing = SQProblem(self.nV, self.nC)\n self.solver_maximizing.setOptions(option)\n\n self.solver_minimizing_recent_index = -2\n self.solver_maximizing_recent_index = -2",
"def __init__(self, objective_function, constraint, dumper=None):\n self.total_iterations = 0\n self.maximum_iterations = 3000\n self.precision = np.sqrt(np.finfo(float).eps)\n self.constraint = constraint\n self.objective_fun = objective_function\n if dumper is None:\n self.use_dumper = False\n else:\n self.use_dumper = True\n self.dumper = dumper\n\n # Used to let the all parts of the solver be aware of the active constraints\n self.active_constraints_index = 0\n self.active_constraints_set = False\n\n # Used for exit information\n self.convergence_reached_tag = 1\n self.maximum_iterations_reached_tag = 2\n self.unknown_exit = 99\n return",
"def optimize(self, objective_sense=None, **kwargs):\n\n if objective_sense:\n self.objective.direction = objective_sense\n\n try:\n # self._hidden_optimize_call(kwargs)\n Model.optimize(self, **kwargs)\n solution = self.get_solution()\n self.solution = solution\n return solution\n except SolverError as SE:\n status = self.solver.status\n self.logger.error(SE)\n self.logger.warning('Solver status: {}'.format(status))\n raise (SE)",
"def __get_solver_instance(self):\n solver = self._solver\n\n # if a configured solver is not given, then build one of the given type\n from mystic.abstract_solver import AbstractSolver\n if isinstance(solver, AbstractSolver): # is a configured solver instance\n return solver\n if not hasattr(solver, \"Solve\"): # is an Error...\n raise TypeError, \"%s is not a valid solver\" % solver\n\n # otherwise, this is a solver class and needs configuring\n #from mystic.monitors import Monitor\n #stepmon = Monitor()\n #evalmon = Monitor()\n #maxiter = 1000\n #maxfun = 1e+6\n solver = solver(self.nDim)\n solver.SetRandomInitialPoints() #FIXME: set population; will override\n if self._useStrictRange: #XXX: always, settable, or sync'd ?\n solver.SetStrictRanges(min=self._strictMin, max=self._strictMax)\n solver.SetEvaluationLimits(self._maxiter, self._maxfun)\n solver.SetEvaluationMonitor(self._evalmon) #XXX: or copy or set?\n solver.SetGenerationMonitor(self._stepmon) #XXX: or copy or set?\n solver.SetTermination(self._termination)\n solver.SetConstraints(self._constraints)\n solver.SetPenalty(self._penalty)\n if self._reducer: #XXX: always, settable, or sync'd ?\n solver.SetReducer(self._reducer, arraylike=True)\n return solver",
"def buildSolverModel(self, lp):\n self._extract(lp)\n try:\n # Apply controls, warmstart etc. We do this here rather than in\n # callSolver() so that the caller has a chance to overwrite things\n # either using the `prepare` argument to callSolver() or by\n # explicitly calling\n # self.buildSolverModel()\n # self.callSolver()\n # self.findSolutionValues()\n # This also avoids setting warmstart information passed to the\n # constructor from actualResolve(), which would almost certainly\n # be unintended.\n model = lp.solverModel\n # Apply controls that were passed to the constructor\n for key, name in [\n (\"gapRel\", \"MIPRELSTOP\"),\n (\"timeLimit\", \"MAXTIME\"),\n (\"heurFreq\", \"HEURFREQ\"),\n (\"heurStra\", \"HEURSTRATEGY\"),\n (\"coverCuts\", \"COVERCUTS\"),\n (\"preSolve\", \"PRESOLVE\"),\n ]:\n value = self.optionsDict.get(key, None)\n if value is not None:\n model.setControl(name, value)\n\n # Apply any other controls. These overwrite controls that were\n # passed explicitly into the constructor.\n for option in self.options:\n if isinstance(option, tuple):\n name = optione[0]\n value = option[1]\n else:\n fields = option.split(\"=\", 1)\n if len(fields) != 2:\n raise PulpSolverError(\"Invalid option \" + str(option))\n name = fields[0].strip()\n value = fields[1].strip()\n try:\n model.setControl(name, int(value))\n continue\n except ValueError:\n pass\n try:\n model.setControl(name, float(value))\n continue\n except ValueError:\n pass\n model.setControl(name, value)\n # Setup warmstart information\n if self.optionsDict.get(\"warmStart\", False):\n solval = list()\n colind = list()\n for v in sorted(lp.variables(), key=lambda x: x._xprs[0]):\n if v.value() is not None:\n solval.append(v.value())\n colind.append(v._xprs[0])\n if _ismip(lp) and self.mip:\n # If we have a value for every variable then use\n # loadmipsol(), which requires a dense solution. Otherwise\n # use addmipsol() which allows sparse vectors.\n if len(solval) == model.attributes.cols:\n model.loadmipsol(solval)\n else:\n model.addmipsol(solval, colind, \"warmstart\")\n else:\n model.loadlpsol(solval, None, None, None)\n # Setup message callback if output is requested\n if self.msg:\n\n def message(prob, data, msg, msgtype):\n if msgtype > 0:\n print(msg)\n\n model.addcbmessage(message)\n except (xpress.ModelError, xpress.InterfaceError, xpress.SolverError) as err:\n raise PulpSolverError(str(err))",
"def fit(self):\n if self.cost_func.hessian:\n self._popt = ral_nlls.solve(self.initial_params,\n self.cost_func.eval_r,\n self.cost_func.jac_res,\n self.hes_eval,\n options=self._options,\n lower_bounds=self.param_ranges[0],\n upper_bounds=self.param_ranges[1])[0]\n else:\n self._popt = ral_nlls.solve(self.initial_params,\n self.cost_func.eval_r,\n self.cost_func.jac_res,\n options=self._options,\n lower_bounds=self.param_ranges[0],\n upper_bounds=self.param_ranges[1])[0]\n self._status = 0 if self._popt is not None else 1",
"def setup(self, solver_name: str, solver_options: Dict = {}):\n # Setup problem\n x = self.opt.decision_variables.vec()\n p = self.opt.parameters.vec()\n\n problem = {\n \"x\": x,\n \"p\": p,\n \"f\": self.opt.f(x, p),\n }\n\n # Setup constraints\n\n ## Lower bound on constraints.\n self._lbg = None\n\n ## Upper bound on constraints\n self._ubg = None\n\n if self.opt_type in CONSTRAINED_OPT:\n problem[\"g\"] = self.opt.v(x, p)\n self._lbg = self.opt.lbv\n self._ubg = self.opt.ubv\n\n # Get solver interface\n if (solver_name in self.qp_solvers) and not self.opt.has_discrete_variables():\n sol = cs.qpsol\n elif (solver_name in self.nlp_solvers) or (solver_name in self.mi_solvers):\n sol = cs.nlpsol\n else:\n raise ValueError(\n f\"solver '{solver_name}' does not support this problem type\"\n )\n\n # Check for discrete variables\n if self.opt.has_discrete_variables():\n solver_options[\"discrete\"] = self.opt.decision_variables.discrete()\n\n # Initialize solver\n\n ## Instance of the CasADi solver.\n self._solver = sol(\"solver\", solver_name, problem, solver_options)\n\n return self",
"def setup(self, solver_settings: Dict = {}):\n assert self.opt_type in QP_COST, \"CVXOPT cannot solve this problem\"\n\n ## Input to the solver\n self._solver_input = solver_settings\n\n self._reset_parameters()\n return self",
"def __init__(self, problem, options, tr_method):\n\n # User-defined optimal-control problem\n self.problem = problem\n\n # General options\n self.options = options\n\n # Transcription method\n self.tr_method = tr_method\n\n # Construction of the lower and upper constraints boundaries\n self.low, self.upp = self.build_constraints_boundaries()",
"def __init__(self, sparse_args=None, solve=True):\n self.solved = False\n self.sparse_args = sparse_args\n self.solved = False\n if solve: self.solve()",
"def optimize(self):\n self.check_is_ready()\n self.check_infeasibility()\n solution_graph, obj_val = self.find_shortest_network_with_ADH((self.old_network_graph is not None))\n self.solution_graph = gnx.GeoMultiGraph(solution_graph, crs=self.optimization_graph.crs)",
"def solve(\n self, solver=Solver.IPOPT, show_online_optim=False, return_iterations=False, solver_options={},\n ):\n\n if return_iterations and not show_online_optim:\n raise RuntimeError(\"return_iterations without show_online_optim is not implemented yet.\")\n\n if solver == Solver.IPOPT and self.solver_type != Solver.IPOPT:\n from ..interfaces.ipopt_interface import IpoptInterface\n\n self.solver = IpoptInterface(self)\n\n elif solver == Solver.ACADOS and self.solver_type != Solver.ACADOS:\n from ..interfaces.acados_interface import AcadosInterface\n\n self.solver = AcadosInterface(self, **solver_options)\n\n elif self.solver_type == Solver.NONE:\n raise RuntimeError(\"Solver not specified\")\n self.solver_type = solver\n\n if show_online_optim:\n self.solver.online_optim(self)\n if return_iterations:\n self.solver.start_get_iterations()\n\n self.solver.configure(solver_options)\n self.solver.solve()\n\n if return_iterations:\n self.solver.finish_get_iterations()\n\n return self.solver.get_optimized_value(self)",
"def __init__(self, fk_solver, optimizer):\n def distance_squared(angles, target):\n x = target - fk_solver.solve(angles)\n return np.sum(np.power(x, 2))\n\n optimizer.prepare(distance_squared)\n self.optimizer = optimizer",
"def solve(self):\n\n constrains, bounds = self.init_constraint_list()\n result = minimize(self.objective_function,\n x0=self.init_guess,\n constraints=constrains,\n bounds=bounds,\n options={'disp': False})\n\n return result"
] | [
"0.6444551",
"0.63010585",
"0.61774766",
"0.6126776",
"0.61203647",
"0.61035085",
"0.60220695",
"0.59948343",
"0.5970983",
"0.5967244",
"0.5966598",
"0.5946401",
"0.5936177",
"0.592915",
"0.59242135",
"0.58939874",
"0.58902633",
"0.5882722",
"0.5832006",
"0.5809041",
"0.5798032",
"0.577203",
"0.57449627",
"0.571994",
"0.57085276",
"0.57044864",
"0.5694458",
"0.5674208",
"0.5672951",
"0.56327987"
] | 0.81089073 | 0 |
! Optimization type. The type of the optimization problem. | def opt_type(self) -> type:
return type(self.opt) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_opt_problem(nn_type):\n if nn_type == 'cnn':\n constraint_checker = CNNConstraintChecker(50, 1e8, 5, 5, 200, 1024, 8)\n init_points = get_initial_cnn_pool()\n func_caller = FunctionCaller(cnn_syn_func1, NNDomain(None, None))\n elif nn_type.startswith('mlp'):\n constraint_checker = MLPConstraintChecker(50, 1e8, 5, 5, 200, 1024, 8)\n init_points = get_initial_mlp_pool(CLASS_OR_REG)\n func_caller = FunctionCaller(mlp_syn_func1, NNDomain(None, None))\n else:\n raise ValueError('Unknown nn_type: %s.'%(nn_type))\n # Common stuff\n mutation_op = get_nn_modifier_from_args(constraint_checker,\n [0.5, 0.25, 0.125, 0.075, 0.05])\n init_vals = [func_caller.eval_single(nn)[0] for nn in init_points]\n return constraint_checker, func_caller, mutation_op, init_points, init_vals",
"def accept_optimize():\n pass",
"def optimize_problem(self, request):\n s = json.dumps(request)\n # Create object that stores optimization problem\n prob = trajoptpy.ConstructProblem(s, self.scene.env)\n t_start = time.time()\n result = trajoptpy.OptimizeProblem(prob) # do optimization\n t_elapsed = time.time() - t_start\n print(result)\n print(\"optimization took %.3f seconds\" % t_elapsed)\n\n # from trajoptpy.check_traj import traj_is_safe\n # prob.SetRobotActiveDOFs() # set robot DOFs to DOFs in optimization problem\n # assert traj_is_safe(result.GetTraj(), self.scene.robot) # Check that trajectory is collision free\n\n return result",
"def problem_type(self):\n return self._problem_type",
"def propose_optimize():\n pass",
"def _optimise(self):\n pass",
"def optimization_step(self):\n \n if \"CSS\" in self.algorithm:\n \n input_dict = {self.x: self.train_inputs[self.minibatch_set,:]}\n \n var_list = [self.x_tilda, self.minibatch_set]\n \n if (self.num_samples > 0) and (not self.mixture):\n \n if ((self.mf_steps > 0) and self.alpha >0) or\\\n self.gibbs_steps > 0: \n \n var_list.append(self.sampler_theta)\n \n elif \"CD\" in self.algorithm:\n \n input_dict = {self.x : self.train_inputs[self.minibatch_set,:]} \n \n var_list = [self.minibatch_set]\n \n var_list.append(self.learning_rate)\n \n if self.use_momentum:\n \n var_list.append(self.momentum)\n \n output_vars = [self.pseudo_cost]\n \n if self.report_p_tilda:\n \n output_vars.append(self.p_tilda)\n \n else:\n \n output_vars.append(theano.shared(0))\n \n opt_step = theano.function(inputs = var_list,\n outputs = output_vars,\n updates = self.updates,\n givens = input_dict,\n on_unused_input='warn')\n \n return opt_step",
"def objective(self):\n pass",
"def get_problem_type(y):\n if len(y.unique()) > 50:\n return 'regression'\n else:\n return 'classification'",
"def optimizer(self):\n return 'sgd'",
"def _SD_optimal(t):",
"def optimize_op(self):\n return self._optimize_op",
"def Optimize(fun, \n dimensions = 10,\n dataType = float64,\n lowerDomain = -5.0,\n upperDomain = 5.0,\n constrainToLower = False,\n constrainToUpper = False,\n maxMutations = 3, \n maxIndexes = 3, \n gamma = 0.99, \n minImprovements = 3,\n scale = 1.0,\n popSize = 10, \n maxIterations = 1000000,\n targetLoss = 1.0e-8,\n minScale = 1.0e-10):\n pop = Population( memberLength = dimensions,\n memberDataType = dataType,\n lowerDomain = lowerDomain, \n upperDomain = upperDomain,\n maxMutations = maxMutations, \n maxIndexes = maxIndexes, \n gamma = gamma, \n minImprovements = minImprovements,\n scale = scale)\n pop.prepare(popSize, fun)\n loss = pop.elite.loss\n startTime = time.time()\n print(f\"[{0:7d}] Loss: {loss:<13.10g} S: {pop.scale:<12.7g} I:{PI(pop.improvements)} elapsed: {0.0:>9.6f} hours\")\n try:\n #-----------------------------------------------------------------\n for trial in range(1, maxIterations):\n pop.minimize(fun, constrainToLower=constrainToLower, constrainToUpper=constrainToUpper)\n if loss > pop.elite.loss:\n loss = pop.elite.loss\n elapsedTime = (time.time() - startTime)/(60*60)\n print(f\"[{trial:7d}] Loss: {loss:<13.10g} S: {pop.scale:<12.7g} I:{PI(pop.improvements)} elapsed: {elapsedTime:>9.6f} hours\")\n if (loss < targetLoss) or (pop.scale < minScale):\n break\n #-----------------------------------------------------------------\n except KeyboardInterrupt:\n pass\n finally:\n print(f\"\\n[{trial:7d}] Loss: {pop.elite.loss:<13.10g} S: {pop.scale:<12.7g} I:{PI(pop.improvements)} elapsed: {elapsedTime:>9.6f} hours\")\n return pop.elite",
"def Type(self) -> _n_6_t_5:",
"def getType(self):\n return _libsbml.Objective_getType(self)",
"def _get_optimization_object(self):\n optTask = self._getTask('optimization')\n optProblem = optTask.find(xmlns + 'Problem')\n parameterText = optProblem.find(xmlns + 'ParameterText')\n return parameterText.text.strip()",
"def rpt_objective(opt_objective):\n if opt_objective == \"lgst\": return \"logl\"\n else: return opt_objective",
"def Optimize(self):\n return _gmat_py.ExternalOptimizer_Optimize(self)",
"def Optimize(self):\n return _gmat_py.Optimizer_Optimize(self)",
"def get_optimizer_type(train_config):\n return train_config.optimizer.WhichOneof(\"optimizer\")",
"def supported_optimization_types(self) -> Sequence[str]:\n return pulumi.get(self, \"supported_optimization_types\")",
"def optim_cls(self) -> type:\n\n return getattr(torch.optim, self._params.get(\"optimizer\", \"Adam\"))",
"def optimize_parameters(self):\n pass",
"def optimize_parameters(self):\n pass",
"def optimize_parameters(self):\n pass",
"def maximize(self, budget, optimizer):\n\n\t\tpass",
"def get_optimization_parameters(self):\n pass",
"def determine_type(self):\n \n t = \" \" # Holder string\n self.cs = 0. \n ## On the lowest rigidities\n if self.xi_L < 0.3:\n if self.pe > 700.:\n t = \"spiral\"\n elif self.pe < 700. and self.pe > 100.:\n if self.xi_L > 0.1:\n t = \"cluster\"\n else:\n t = \"gas\"\n else:\n t = \"gas\"\n else:\n t = \"loop\"\n \n self.type = t # Type of point\n \n if self.pe < 7500.:\n if self.pe < 10.:\n self.pe += 1.\n elif self.pe < 700. and self.pe > 100.: \n self.pe += 50.\n else:\n self.pe += 200.\n \n return",
"def getprobtype(self): # 3\n res,resargs = self.__obj.getprobtype()\n if res != 0:\n result,msg = self.__getlasterror(res)\n raise Error(rescode(res),msg)\n _probtype_return_value = resargs\n _probtype_return_value = problemtype(_probtype_return_value)\n return _probtype_return_value",
"def get_problem_type():\n problem_type = input(\"What type of problem do you want?\")\n return problem_type"
] | [
"0.62327963",
"0.60769403",
"0.60206985",
"0.58406436",
"0.5788869",
"0.57278967",
"0.5710115",
"0.5690223",
"0.5668474",
"0.56331706",
"0.5623142",
"0.5569626",
"0.5553283",
"0.5552492",
"0.5550468",
"0.5549044",
"0.5513961",
"0.5422052",
"0.5415799",
"0.5412332",
"0.53945184",
"0.5344178",
"0.53199553",
"0.53199553",
"0.53199553",
"0.52814835",
"0.52422476",
"0.52403843",
"0.52343047",
"0.52333957"
] | 0.60863376 | 1 |
! Reset initial seed for the optimization problem. x0 The initial seed. | def reset_initial_seed(self, x0: Dict[str, ArrayType]) -> None:
self.x0 = self.opt.decision_variables.dict2vec(x0) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def reset_initial_seed(self, x0) -> None:\n super().reset_initial_seed(x0)\n self.minimize_input[\"x0\"] = self.x0.toarray().flatten()",
"def generate_initial_state(self, x):\n\n if self.initial_state is None:\n x[:] = 0\n return x\n else:\n x[:] = self.initial_state(size=(self._num_neurons, 1))\n return x",
"def rngreset(seed=0):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True",
"def reset(self):\n self.x_prev = np.zeros_like(self.mu)",
"def reset(self):\n self.rand_start = int(np.random.rand()*25000)+self.offset\n state = np.array(np.zeros(self.obs))\n self.time = self.rand_start\n self.residual = 0\n self.cum_r = 0\n return state",
"def reset(self) -> None:\n self._rng = random.default_rng(self.seed)",
"def reset(self):\n self.t = 0\n # two outputs: the thrusters, u_r and u_l and stop neuron\n self.action = [0.0, 0.0, 0.0]\n # x, vx, y, vy, theta, omega\n # self.state = [2.0, 0.0, 2.0, 0.0, 0.0, 0.0]\n self.state = self.start_cnd\n x, vx, y, vy, theta, omega = self.state\n# print x, self.state\n self.init_distance = self.getDistance()\n \n self.solver = ode(self.dX)\n self.solver.set_integrator('dopri5') \n self.solver.set_initial_value(self.state, self.t)",
"def reset(self):\n self.x = random.uniform(-0.05, 0.05)\n self.x_dot = random.uniform(-0.05, 0.05)\n self.theta = random.uniform(-0.05, 0.05)\n self.theta_dot = random.uniform(-0.05, 0.05)",
"def seed_random():\n random.seed(0)",
"def reset(self):\n # Sample random state from initial state distribution\n self._cur_state = self._sample_state(self._mdp.I)\n self._prev_state = self._cur_state",
"def initial_x():\n\n # RANDOMLY GENERATES the INITIAL VALUES of the independent variables:\n temp = [uniform(1, cfg.n) for i in range(cfg.n)]\n\n return np.array(temp, dtype=np.float_)",
"def reset():\n\n global optimizer_data\n global optimizer_len\n\n optimizer_data = []\n optimizer_len = 0\n return",
"def reset(self):\n seed = copy.deepcopy(self.rng_seed)\n self.rng = check_random_state(seed)\n self.num_generated = 0\n return self",
"def reset_states(self):\n K.batch_set_value([(v, 0) for v in self.variables])",
"def test_reset(self):\n self.p.C[0][0] = np.inf\n self.step()",
"def reset(self):\n \n s = self\n s.step_counter = 0\n \n # TODO: initialize first layer activations here, and not everywhere else\n # self.model.initialize_local_vars()\n # self.model.initialize_global_vars()\n\n ops = []\n\n for var in self.model.trainable_vars:\n if self.needs_correction(var):\n A_svd = s[var].A.svd\n B2_svd = s[var].B2.svd \n ops.extend(A_svd.init_ops)\n ops.extend(B2_svd.init_ops)\n ops.append(s[var].A.cov.initializer)\n ops.append(s[var].B2.cov.initializer)\n\n # in new TensorFlow this breaks, probably because of\n # https://github.com/tensorflow/tensorflow/commit/07adc2ea910de715d31e16a019fcbcccb575e931\n # sometimes get \"need to feed\" placeholder error\n # sometimes do not get this error, but spend two minutes inside\n # _build_initializer_expr\n s.run(ops)",
"def random():\n np.random.seed(0)",
"def reset(self):\n self.reset_image_estimate()\n self.init_m_aux()\n self.reset_hessian_and_bias()\n self.reset_adadelta_variables()",
"def init_state(self, x):\n B, _, d_model = x.shape\n p_0 = torch.zeros((B, 2 * d_model), device=x.device, requires_grad=True)\n self.gru_hidden = torch.zeros((B, 2 * d_model), device=x.device, requires_grad=True)\n return p_0",
"def init_state(self, x):\n B, _, d_model = x.shape\n p_0 = torch.zeros((B, 2 * d_model), device=x.device, requires_grad=True)\n self.gru_hidden = torch.zeros((B, 2 * d_model), device=x.device, requires_grad=True)\n return p_0",
"def reset(self):\r\n self.currentIteration = 0\r\n # note there are several versions of randint!\r\n self.currentObservation = random.randint(0, self.S - 1)\r\n return self.get_state()",
"def reset(self):\n for i in range(0, len(self.current_state)):\n self.current_state[i] = 0\n\n for i in range(0, len(self.weights)):\n self.weights[i] = 0",
"def reset(self):\n self.z = rand(*self.z.shape)\n self.c = ones_like(self.c)",
"def prepare_for_use(self):\n self._random_state = check_random_state(self.random_state)\n self._offset = self.offset\n self._x_idx = 0",
"def prepare_for_use(self):\n self._random_state = check_random_state(self.random_state)\n self._offset = self.offset\n self._x_idx = 0",
"def prepare_for_use(self):\n self._random_state = check_random_state(self.random_state)\n self._offset = self.offset\n self._x_idx = 0",
"def reset(self):\n self.noise = [0.] * 6\n self.state = [0.0] * 9\n self.q = [0.0, 0.0, 0.0, 1.0]\n self.terminal = False\n self.steps = 0\n # Return current state and error\n return self.observation, self.error",
"def get_initial_guess():\n x0 = np.zeros(6)\n x0[0] = 1\n x0[3] = 1\n return x0",
"def reset_state(self):\n self.y = np.copy(self.start)\n self.dy = np.zeros(self.n_dmps)\n self.ddy = self.ay * (self.by * (self.goal - self.y) - self.dy) + self.force[0]\n self.timestep = 0",
"def reset(self):\r\n self.state = copy.copy(self.mu)"
] | [
"0.8737879",
"0.67843056",
"0.6593212",
"0.6503656",
"0.6454457",
"0.6383516",
"0.6311529",
"0.630171",
"0.6265005",
"0.6239627",
"0.62309265",
"0.6227303",
"0.61286354",
"0.6122613",
"0.6122158",
"0.60998493",
"0.6077699",
"0.6073097",
"0.60562795",
"0.60562795",
"0.60531366",
"0.60469806",
"0.6035503",
"0.6008634",
"0.6008634",
"0.6008634",
"0.60018325",
"0.59940416",
"0.59658265",
"0.5964649"
] | 0.7988302 | 1 |
! Reset the parameters for the optimization problem. p Specifies the parameters. | def reset_parameters(self, p: Dict[str, ArrayType]) -> None:
self.p = self.opt.parameters.dict2vec(p)
self._p_dict = self.opt.parameters.vec2dict(self.p) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def _reset_parameters(self):\n self._solver_input[\"P\"] = cvxopt.matrix(2.0 * self.opt.P(self.p).toarray())\n self._solver_input[\"q\"] = cvxopt.matrix(self.opt.q(self.p).toarray().flatten())\n if self.opt_type in CONSTRAINED_OPT:\n if self.opt.nk > 0:\n self._solver_input[\"G\"] = cvxopt.matrix(-self.opt.M(self.p).toarray())\n self._solver_input[\"h\"] = cvxopt.matrix(\n self.opt.c(self.p).toarray().flatten()\n )\n if self.opt.na > 0:\n self._solver_input[\"A\"] = cvxopt.matrix(self.opt.A(self.p).toarray())\n self._solver_input[\"b\"] = cvxopt.matrix(-self.opt.b(self.p).toarray())",
"def _reset_parameters(self) -> None:\n self._setup_input = {\n \"P\": csc_matrix(2.0 * self.opt.P(self.p).toarray()),\n \"q\": self.opt.q(self.p).toarray().flatten(),\n }\n if self.opt_type in CONSTRAINED_OPT:\n A = self.opt.A(self.p)\n b = self.opt.b(self.p)\n self._setup_input[\"A\"] = csc_matrix(\n cs.vertcat(self.opt.M(self.p), A, -A).toarray()\n )\n self._setup_input[\"l\"] = (\n cs.vertcat(-self.opt.c(self.p), -b, b).toarray().flatten()\n )",
"def reset_parameters(self, p: Dict[str, ArrayType]):\n super().reset_parameters(p)\n if self.method == \"trust-constr\":\n if self.opt.nk:\n self._constraints[\"k\"].A = csc_matrix(self.opt.M(self.p).toarray())\n self._constraints[\"k\"].lb = -self.opt.c(self.p).toarray().flatten()\n if self.opt.na:\n eq = -self.opt.b(self.p).toarray().flatten()\n self._constraints[\"a\"].A = csc_matrix(self.opt.A(self.p).toarray())\n self._constraints[\"a\"].lb = eq\n self._constraints[\"a\"].ub = eq\n if self._constraints:\n self.minimize_input[\"constraints\"] = list(self._constraints.values())",
"def resetParameter(pname):\n dislin.reset(pname)",
"def reset_params(self):\n for pp in self.params:\n if 'optimizer_param' in pp.tags:\n pp.set_value(np.zeros(pp.get_value(borrow=True).shape, dtype=theano.config.floatX))",
"def reset_parameters(self):\n self.lstm.reset_parameters()",
"def reset_parameters(self):\n self.rnn.reset_parameters()\n self.action_lookup.reset_parameters()\n\n # self.state_dict_lookup.reset_parameters()\n self.own_c_lookup.reset.parameters()\n self.own_s_lookup.reset_parameters()\n\n self.th_1_lookup.reset_parameters()\n self.th_2_lookup.reset_parameters()\n self.th_3_lookup.reset_parameters()\n self.f_1_lookup.reset.parameters()\n self.f_2_lookup.reset_parameters()\n self.f_3_lookup.reset_parameters()\n self.f_4_lookup.reset_parameters()\n\n self.bu_msg_lookup.reset_parameters()\n\n self.i_t_lookup.reset_parameters()\n self.lives_lookup.reset_parameters()\n\n self.prev_action_lookup.reset_parameters()\n # self.message.apply(weight_reset)\n self.output.apply(weight_reset)\n for p in self.rnn.parameters():\n p.data.uniform_(*self.init_param_range)",
"def reset_parameters(self, p: Dict[str, ArrayType]) -> None:\n super().reset_parameters(p)\n self._reset_parameters()",
"def _reset_parameters(self):\r\n\t\tfor p in self.parameters():\r\n\t\t\tif p.dim() > 1:\r\n\t\t\t\txavier_uniform_(p)",
"def reset_parameters(self, p: Dict[str, ArrayType]):\n super().reset_parameters(p)\n self._reset_parameters()",
"def reset_parameters(self):\n self.lin.reset_parameters()\n self.att.reset_parameters()\n self.gnn_score.reset_parameters()\n if self.gnn_intra_cluster is not None:\n self.gnn_intra_cluster.reset_parameters()\n self.select.reset_parameters()",
"def _reset(lp):\n if hasattr(lp, \"solverModel\"):\n delattr(lp, \"solverModel\")\n for v in lp.variables():\n if hasattr(v, \"_xprs\"):\n delattr(v, \"_xprs\")\n for c in lp.constraints.values():\n if hasattr(c, \"_xprs\"):\n delattr(c, \"_xprs\")",
"def _reset_parameters(self):\n\n for p in self.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)",
"def resetparams(self, parameters):\n self.weights = None\n try:\n self.params = parameters\n except AttributeError:\n # Variable self.params does not exist, so not updated\n # Create an empty set of params for future reference\n self.params = {}",
"def setstate(self, state):\r\n self.preferred_optimizer = state.pop()\r\n self.sampling_runs = state.pop()\r\n self.optimization_runs = state.pop()\r\n self.priors = state.pop()\r\n Parameterized.setstate(self, state)",
"def reset(self):\n self.params.resetParams()",
"def reset_parameters(self):\n self.conv_in.reset_parameters()\n self.conv_out.reset_parameters()\n if self.lin is not None:\n self.lin.reset_parameters()",
"def resetParams(self):\n self.prediction = cons.init_pred # Classifier payoff - initialized to a constant initial payoff value\n self.error = cons.init_err # Classifier error - initialized to a constant initial error value\n self.fitness = cons.init_fit # Classifier fitness - initialized to a constant initial fitness value",
"def _reset_parameters(self):\n\n for p in self.parameters():\n if p.dim() > 1:\n xavier_uniform_(p)",
"def _reset_params(self):\n for p in self.parameters():\n if p.dim() > 1:\n torch.nn.init.xavier_normal_(p)",
"def reset_parameters(self):\n for p in self.parameters():\n if len(p.shape) > 1 and p.size(-1) != 2:\n nn.init.xavier_normal_(p)",
"def reset_parameters(self):\n for p in self.parameters():\n if len(p.shape) > 1 and p.size(-1) != 2:\n nn.init.xavier_normal_(p)",
"def reset_parameters(self):\n self.apply(ixvr)",
"def reset_parameters(self):\n self.apply(ixvr)",
"def reset_parameters(self):\n # for item in self.layer_dict.children():\n self.encoder.reset_parameters()\n self.vq.reset_parameters()\n self.generator.reset_parameters()\n\n self.speaker_dict.reset_parameters()\n self.speaker_dense.reset_parameters()",
"def resetparams(self, parameters):\n try:\n utils.update_dictionary_items(self.params,parameters)\n except AttributeError:\n # Variable self.params does not exist, so not updated\n # Create an empty set of params for future reference\n self.params = {}",
"def reset():\n\n global optimizer_data\n global optimizer_len\n\n optimizer_data = []\n optimizer_len = 0\n return",
"def _reset(self):\n self.loss_history = []\n self.optim_configs = {}\n for p in self.model.params:\n d = {k: v for k, v in self.optim_config.items()}\n self.optim_configs[p] = d",
"def reset_parameters(self,z0):\n self._set_z0(z0)\n self._set_parameters()",
"def reset_parameters(self):\n\n for layer in self.layers:\n layer.reset_parameters()"
] | [
"0.7103715",
"0.6991918",
"0.6981577",
"0.6940896",
"0.6735711",
"0.6692552",
"0.6684609",
"0.6678689",
"0.6568796",
"0.6533821",
"0.65149695",
"0.64510334",
"0.6446362",
"0.6434186",
"0.6359053",
"0.63516587",
"0.63430274",
"0.6332555",
"0.6315924",
"0.6302281",
"0.6243164",
"0.6243164",
"0.619946",
"0.619946",
"0.61768854",
"0.6166065",
"0.61646837",
"0.6160257",
"0.61303174",
"0.6124074"
] | 0.7288989 | 0 |
! Solve the optimization problem. A dictionary containing the solution. | def solve(self) -> Dict:
solution = self.opt.decision_variables.vec2dict(self._solve())
if self._error_on_fail and (not self.did_solve()):
raise RuntimeError("Solver failed!")
# Add full model state to the solution dictionary
for model in self.opt.models:
for d in model.time_derivs:
n_s = model.state_name(d)
n_s_x = model.state_optimized_name(d)
if isinstance(model, RobotModel):
if model.num_param_joints > 0:
n_s_p = model.state_parameter_name(d)
t = solution[n_s_x].shape[1]
solution[n_s] = cs.DM.zeros(model.dim, t)
solution[n_s][model.optimized_joint_indexes, :] = solution[
n_s_x
]
solution[n_s][model.parameter_joint_indexes, :] = self._p_dict[
n_s_p
]
else:
solution[n_s] = solution[n_s_x]
else:
solution[n_s] = solution[n_s_x]
return solution | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def solve(self, **kwargs) -> OptimizationResult:\n raise NotImplementedError",
"def solve(self, current_state: dict) -> dict:",
"def solve(self):",
"def solve_optimisation(model, exe_path, project_dir, poses) -> None:\n opt = SolverFactory(\n 'ipopt',\n executable=exe_path\n )\n\n # solver options\n opt.options[\"print_level\"] = 5\n opt.options[\"max_iter\"] = 400\n opt.options[\"max_cpu_time\"] = 3600\n opt.options[\"tol\"] = 1e-1\n opt.options[\"OF_print_timing_statistics\"] = \"yes\"\n opt.options[\"OF_print_frequency_iter\"] = 10\n opt.options[\"OF_hessian_approximation\"] = \"limited-memory\"\n #opt.options[\"linear_solver\"] = \"ma86\"\n\n LOG_DIR = 'C://Users//user-pc//Documents//Scripts//FYP//logs'\n\n # --- This step may take a while! ---\n results = opt.solve(\n model, tee=True, \n keepfiles=True, \n logfile=os.path.join(LOG_DIR, \"solver.log\")\n )\n\n result_dir = os.path.join(project_dir, \"results\")\n save_data(model, file_path=os.path.join(result_dir, 'traj_results.pickle'), poses=poses)",
"def solve(self):\n\n constrains, bounds = self.init_constraint_list()\n result = minimize(self.objective_function,\n x0=self.init_guess,\n constraints=constrains,\n bounds=bounds,\n options={'disp': False})\n\n return result",
"def solve(self):\n self.m.optimize()\n if self.m.status == GRB.OPTIMAL:\n self.solution = self.sol_as_mat()\n return self.solution",
"def optimize_problem(self, request):\n s = json.dumps(request)\n # Create object that stores optimization problem\n prob = trajoptpy.ConstructProblem(s, self.scene.env)\n t_start = time.time()\n result = trajoptpy.OptimizeProblem(prob) # do optimization\n t_elapsed = time.time() - t_start\n print(result)\n print(\"optimization took %.3f seconds\" % t_elapsed)\n\n # from trajoptpy.check_traj import traj_is_safe\n # prob.SetRobotActiveDOFs() # set robot DOFs to DOFs in optimization problem\n # assert traj_is_safe(result.GetTraj(), self.scene.robot) # Check that trajectory is collision free\n\n return result",
"def solve(self):\n pass",
"def solve(self):\n pass",
"def solve(self):\n ...",
"def __solve(self) -> None:\n pyo.TransformationFactory(\"contrib.detect_fixed_vars\").apply_to(self.model) # type: ignore\n pyo.TransformationFactory(\"contrib.deactivate_trivial_constraints\").apply_to(self.model) # type: ignore\n\n # initialise the solver object\n self._logger.debug(\"[ModelSolver] Solver object initiated...\")\n solver = Config.OPTIMISATION_MODEL_CONFIG['SOLVER_TYPE']\n opt = pyo.SolverFactory(solver)\n if Config.OPTIMISATION_MODEL_CONFIG['SOLVER_OPTION'].get(solver) is not None:\n for k, v in Config.OPTIMISATION_MODEL_CONFIG['SOLVER_OPTION'].get(solver).items():\n opt.options[k] = v\n\n try:\n start_time = datetime.now()\n self._logger.debug(\"[ModelSolver] Solver starting...\")\n results = opt.solve(self.model, tee=True)\n self.results = results\n end_time = datetime.now()\n self._logger.info(f\"[ModelSolver] Solver completed in {end_time - start_time}.\")\n except Exception as e:\n raise Exception(f\"Model optimisation failed with {solver} with error message {e}.\")\n\n if (results.solver.status == SolverStatus.ok) and (results.solver.termination_condition == TerminationCondition.optimal):\n self._logger.info(\"Solution is feasible and optimal\")\n results.write()\n elif results.solver.termination_condition == TerminationCondition.infeasible:\n raise ValueError(\"Model optimisation resulted into an infeasible solution\")\n\n self.model.optimised = True",
"def solve(self, objective, constraints, cached_data,\n warm_start, verbose, solver_opts):\n import ecos\n data = self.get_problem_data(objective, constraints, cached_data)\n data[s.DIMS]['e'] = data[s.DIMS][s.EXP_DIM]\n results_dict = ecos.solve(data[s.C], data[s.G], data[s.H],\n data[s.DIMS], data[s.A], data[s.B],\n verbose=verbose,\n **solver_opts)\n return self.format_results(results_dict, data, cached_data)",
"def solve(puzzle_input):\r\n return {'a': part_a(puzzle_input), 'b': part_b(puzzle_input)}",
"def solve(self, opt_prob: OptimizationProblem, opt_param: OptimizationParameter, *args, **kwargs) -> Any:\n pass",
"def run(self, problem):\n\n self.pyopt_solution = None\n rel = problem.root._probdata.relevance\n\n # Metadata Setup\n self.metadata = create_local_meta(None, self.options['optimizer'])\n self.iter_count = 0\n update_local_meta(self.metadata, (self.iter_count,))\n\n # Initial Run\n with problem.root._dircontext:\n problem.root.solve_nonlinear(metadata=self.metadata)\n\n opt_prob = Optimization(self.options['title'], self._objfunc)\n\n # Add all parameters\n param_meta = self.get_desvar_metadata()\n self.indep_list = indep_list = list(param_meta)\n param_vals = self.get_desvars()\n\n for name, meta in iteritems(param_meta):\n opt_prob.addVarGroup(name, meta['size'], type='c',\n value=param_vals[name],\n lower=meta['lower'], upper=meta['upper'])\n\n opt_prob.finalizeDesignVariables()\n\n # Figure out parameter subsparsity for paramcomp index connections.\n # sub_param_conns is empty unless there are some index conns.\n # full_param_conns gets filled with the connections to the entire\n # parameter so that those params can be filtered out of the sparse\n # set if the full path is also relevant\n sub_param_conns = {}\n full_param_conns = {}\n for name in indep_list:\n pathname = problem.root.unknowns.metadata(name)['pathname']\n sub_param_conns[name] = {}\n full_param_conns[name] = set()\n for target, info in iteritems(problem.root.connections):\n src, indices = info\n if src == pathname:\n if indices is not None:\n # Need to map the connection indices onto the desvar\n # indices if both are declared.\n dv_idx = param_meta[name].get('indices')\n indices = set(indices)\n if dv_idx is not None:\n indices.intersection_update(dv_idx)\n ldv_idx = list(dv_idx)\n mapped_idx = [ldv_idx.index(item) for item in indices]\n sub_param_conns[name][target] = mapped_idx\n else:\n sub_param_conns[name][target] = indices\n else:\n full_param_conns[name].add(target)\n\n # Add all objectives\n objs = self.get_objectives()\n self.quantities = list(objs)\n self.sparsity = OrderedDict()\n self.sub_sparsity = OrderedDict()\n for name in objs:\n opt_prob.addObj(name)\n self.sparsity[name] = self.indep_list\n\n # Calculate and save gradient for any linear constraints.\n lcons = self.get_constraints(lintype='linear').keys()\n if len(lcons) > 0:\n self.lin_jacs = problem.calc_gradient(indep_list, lcons,\n return_format='dict')\n #print(\"Linear Gradient\")\n #print(self.lin_jacs)\n\n # Add all equality constraints\n econs = self.get_constraints(ctype='eq', lintype='nonlinear')\n con_meta = self.get_constraint_metadata()\n self.quantities += list(econs)\n\n self.active_tols = {}\n for name in self.get_constraints(ctype='eq'):\n meta = con_meta[name]\n size = meta['size']\n lower = upper = meta['equals']\n\n # Sparsify Jacobian via relevance\n rels = rel.relevant[name]\n wrt = rels.intersection(indep_list)\n self.sparsity[name] = wrt\n\n if meta['linear']:\n opt_prob.addConGroup(name, size, lower=lower, upper=upper,\n linear=True, wrt=wrt,\n jac=self.lin_jacs[name])\n else:\n\n jac = self._build_sparse(name, wrt, size, param_vals,\n sub_param_conns, full_param_conns, rels)\n opt_prob.addConGroup(name, size, lower=lower, upper=upper,\n wrt=wrt, jac=jac)\n\n active_tol = meta.get('active_tol')\n if active_tol:\n self.active_tols[name] = active_tol\n\n # Add all inequality constraints\n incons = self.get_constraints(ctype='ineq', lintype='nonlinear')\n self.quantities += list(incons)\n\n for name in self.get_constraints(ctype='ineq'):\n meta = con_meta[name]\n size = meta['size']\n\n # Bounds - double sided is supported\n lower = meta['lower']\n upper = meta['upper']\n\n # Sparsify Jacobian via relevance\n rels = rel.relevant[name]\n wrt = rels.intersection(indep_list)\n self.sparsity[name] = wrt\n\n if meta['linear']:\n opt_prob.addConGroup(name, size, upper=upper, lower=lower,\n linear=True, wrt=wrt,\n jac=self.lin_jacs[name])\n else:\n\n jac = self._build_sparse(name, wrt, size, param_vals,\n sub_param_conns, full_param_conns, rels)\n opt_prob.addConGroup(name, size, upper=upper, lower=lower,\n wrt=wrt, jac=jac)\n\n active_tol = meta.get('active_tol')\n if active_tol is not None:\n self.active_tols[name] = active_tol\n\n # Instantiate the requested optimizer\n optimizer = self.options['optimizer']\n try:\n _tmp = __import__('pyoptsparse', globals(), locals(), [optimizer], 0)\n opt = getattr(_tmp, optimizer)()\n except ImportError:\n msg = \"Optimizer %s is not available in this installation.\" % \\\n optimizer\n raise ImportError(msg)\n\n #Set optimization options\n for option, value in self.opt_settings.items():\n opt.setOption(option, value)\n\n self._problem = problem\n self.opt_prob = opt_prob\n\n # Execute the optimization problem\n if self.options['gradient method'] == 'pyopt_fd':\n\n # Use pyOpt's internal finite difference\n fd_step = problem.root.deriv_options['step_size']\n sol = opt(opt_prob, sens='FD', sensStep=fd_step, storeHistory=self.hist_file)\n\n elif self.options['gradient method'] == 'snopt_fd':\n if self.options['optimizer']=='SNOPT':\n\n # Use SNOPT's internal finite difference\n fd_step = problem.root.deriv_options['step_size']\n sol = opt(opt_prob, sens=None, sensStep=fd_step, storeHistory=self.hist_file)\n\n else:\n msg = \"SNOPT's internal finite difference can only be used with SNOPT\"\n raise Exception(msg)\n else:\n\n # Use OpenMDAO's differentiator for the gradient\n sol = opt(opt_prob, sens=self._gradfunc, storeHistory=self.hist_file)\n\n self._problem = None\n\n # Print results\n if self.options['print_results']:\n print(sol)\n\n # Pull optimal parameters back into framework and re-run, so that\n # framework is left in the right final state\n dv_dict = sol.getDVs()\n for name in indep_list:\n val = dv_dict[name]\n self.set_desvar(name, val)\n\n with self.root._dircontext:\n self.root.solve_nonlinear(metadata=self.metadata)\n\n # Save the most recent solution.\n self.pyopt_solution = sol\n try:\n exit_status = sol.optInform['value']\n self.exit_flag = 1\n if exit_status > 2: # bad\n self.exit_flag = 0\n except KeyError: #nothing is here, so something bad happened!\n self.exit_flag = 0",
"def _solve(self, solver):\n self.prob.solve(solver)\n if self.prob.status <= 0:\n raise Exception(\"Infeasible Solution.\")\n return {pid for pid, variable \n in self.player_vars.iteritems()\n if variable.varValue}",
"def solve(self):\n\n # Open status display\n fmtstr, nsep = self.display_start()\n\n # Start solve timer\n self.timer.start(['solve', 'solve_wo_func', 'solve_wo_rsdl',\n 'solve_wo_btrack'])\n\n # Main optimisation iterations\n for self.k in range(self.k, self.k + self.opt['MaxMainIter']):\n\n # Update record of X and Y from previous iteration\n self.on_iteration_start()\n\n # Compute backtracking\n if self.opt['Backtrack'] is not None and self.k >= 0:\n self.timer.stop('solve_wo_btrack')\n # Compute backtracking\n self.backtrack.update(self)\n self.timer.start('solve_wo_btrack')\n else:\n # Compute just proximal step\n self.xstep()\n # Update by combining previous iterates\n self.ystep()\n\n # Compute residuals and stopping thresholds\n self.timer.stop(['solve_wo_rsdl', 'solve_wo_btrack'])\n if not self.opt['FastSolve']:\n frcxd, adapt_tol = self.compute_residuals()\n self.timer.start('solve_wo_rsdl')\n\n # Compute and record other iteration statistics and\n # display iteration stats if Verbose option enabled\n self.timer.stop(['solve_wo_func', 'solve_wo_rsdl',\n 'solve_wo_btrack'])\n if not self.opt['FastSolve']:\n itst = self.iteration_stats(self.k, frcxd)\n self.itstat.append(itst)\n self.display_status(fmtstr, itst)\n self.timer.start(['solve_wo_func', 'solve_wo_rsdl',\n 'solve_wo_btrack'])\n\n # Call callback function if defined\n if self.opt['Callback'] is not None:\n if self.opt['Callback'](self):\n break\n\n # Stop if residual-based stopping tolerances reached\n if not self.opt['FastSolve']:\n if frcxd < adapt_tol:\n break\n\n # Increment iteration count\n self.k += 1\n\n # Record solve time\n self.timer.stop(['solve', 'solve_wo_func', 'solve_wo_rsdl',\n 'solve_wo_btrack'])\n\n # Print final separator string if Verbose option enabled\n self.display_end(nsep)\n\n return self.getmin()",
"def solve(self, solver):\n solver.solve()",
"def solve(mm):\n model = mm.model\n model.optimize()\n\n\n mm.optimal = model.status\n mm.take_snapshot()\n print \"\\nSnapshot saved as {}\".format(mm.filename)\n mm.solve_count += 1\n mm.update_filename()\n\n if model.status == gp.GRB.OPTIMAL:\n # Write a csv of the solution data\n write_solution(mm)\n\n\n return True",
"def solve(self):\n\n if self.optimizer == 'pulp':\n for constraint in self.constraints:\n self.engine_model += constraint\n\n self.engine_model += self.objective\n status = self.engine_model.solve(PULP_CBC_CMD(msg=False))\n solution = (\n np.vectorize(self._var_sol)(self.variable_set)\n if status == LpStatusOptimal\n else np.array([])\n )\n\n else:\n for constraint in self.constraints:\n self.engine_model.addConstr(constraint)\n\n self.engine_model.setObjective(self.objective, self.sense)\n self.engine_model.optimize()\n solution = (\n np.vectorize(self._var_sol)(self.variable_set)\n if self.engine_model.status == GRB.OPTIMAL\n else np.array([])\n )\n\n return solution",
"def solution(data):\n lines = preprocess(data)\n solver = Code(lines)\n return solver.solve()",
"def solve(self):\n \n raise NotImplementedError(\"not implemented!\")",
"def objective(hyperparams): \n global iteration #necessary with a global variable because of implementation from hyperopt. \n iteration += 1\n\n result = run_model(hyperparams, iteration)\n loss = -result #transform to loss in order to minimize\n\n return {'loss': loss, 'hyperparams': hyperparams, 'iteration': iteration, 'status': STATUS_OK}",
"def solve(self, **kwargs):\n return self.system.solve(**kwargs)",
"def solve(self, x0=None, round_digit=4, **kwargs):\n if type(self.objective) != np.ndarray:\n res = minimize(self.objective, x0 = ConstGen.gen_random_weight(self.ret_vec.shape[0], self.bounds, self.leverage) if x0 is None else x0, options={'maxiter': 1000},\n constraints=self.constraints, bounds=self.bounds, args=self.objective_args)\n if not res.success:\n self.clear(**kwargs)\n raise OptimizeException(f\"\"\"Optimization has failed. Error Message: {res.message}. \n Please adjust constraints/objectives or input an initial guess.\"\"\")\n\n self.clear(**kwargs)\n self.weight_sols = np.round(res.x, round_digit) + 0\n\n else:\n warnings.warn(f\"\"\"The problem formulated is not an optimization problem and is calculated numerically\"\"\")\n\n self.weight_sols = np.round(self.objective, round_digit) + 0\n self.clear(**kwargs)",
"def optimize(self):\n\n self.logger.info(\"Solving with Dynamic Slope Scaling Procedure in Julia :\")\n optimization_start = time.time()\n\n # 1. Preprocess for old network graph\n if self.old_network_graph is not None:\n\n # DSSP on old network\n old_network_obj = sum(list(nx.get_node_attributes(self.old_network_graph, config.BUILDING_CONSUMPTION_KEY).values()))-1e-5\n try:\n self.check_infeasibility(self.old_network_graph, old_network_obj)\n except DHCOptimizerException as e:\n e.data = \"Invalid existing network: \" + e.data\n raise e\n\n flows, obj_val = self.optimize_with_dssp_julia(self.old_network_graph, old_network_obj, set())\n self.logger.info(\"Optimization phase time: %.2fs\" % (time.time() - optimization_start))\n solution_old_graph = self.build_solution_graph(self.old_network_graph, flows)\n\n if self.modify_old_network:\n\n # Add max capacity on old edges\n self.old_capacity = deepcopy(flows)\n old_buildings = list(nx.get_node_attributes(self.old_network_graph, config.BUILDING_CONSUMPTION_KEY).values())\n for key in flows:\n if (key[1],key[0],0) not in self.old_capacity and key[1] not in old_buildings:\n self.old_capacity[(key[1],key[0],0)] = self.old_capacity[key]\n\n # Add Imaginary edges\n for edge in self.old_capacity:\n if self.optimization_graph.has_edge(*edge):\n\n # add nodes\n if not self.optimization_graph.has_node(config.IM_PREFIX+edge[0]):\n self.optimization_graph.add_node(config.IM_PREFIX+edge[0])\n self.optimization_graph.nodes[config.IM_PREFIX+edge[0]][config.GPD_GEO_KEY] = \\\n self.optimization_graph.nodes[edge[0]][config.GPD_GEO_KEY]\n if not self.optimization_graph.has_node(config.IM_PREFIX+edge[1]):\n self.optimization_graph.add_node(config.IM_PREFIX+edge[1])\n self.optimization_graph.nodes[config.IM_PREFIX+edge[1]][config.GPD_GEO_KEY] = \\\n self.optimization_graph.nodes[edge[1]][config.GPD_GEO_KEY]\n # add edges\n if not self.optimization_graph.has_edge(edge[0],config.IM_PREFIX+edge[0]):\n self.optimization_graph.add_edge(edge[0],config.IM_PREFIX+edge[0])\n if not self.optimization_graph.has_edge(config.IM_PREFIX+edge[0],config.IM_PREFIX+edge[1]):\n self.optimization_graph.add_edge(config.IM_PREFIX+edge[0],config.IM_PREFIX+edge[1])\n if not self.optimization_graph.has_edge(config.IM_PREFIX+edge[1],edge[1]):\n self.optimization_graph.add_edge(config.IM_PREFIX+edge[1],edge[1])\n\n # put cost\n self.optimization_graph.edges[(config.IM_PREFIX+edge[0],config.IM_PREFIX+edge[1],0)][config.EDGE_COST_KEY] = \\\n self.optimization_graph.edges[(edge[0],edge[1],0)][config.EDGE_COST_KEY]\n self.optimization_graph.edges[(edge[0],edge[1],0)][config.EDGE_COST_KEY] = 1e-5\n self.optimization_graph.edges[(edge[0],config.IM_PREFIX+edge[0],0)][config.EDGE_COST_KEY] = 1e-5\n self.optimization_graph.edges[(config.IM_PREFIX+edge[1],edge[1],0)][config.EDGE_COST_KEY] = 1e-5\n\n else:\n # if we don't modify the old network, we have to change the capacity of the supplies\n already_consummed = {}\n for edge in solution_old_graph.edges():\n if solution_old_graph.nodes[edge[0]].get(config.NODE_TYPE_KEY) == config.SUPPLY_NODE_TYPE:\n already_consummed[edge[0]] = already_consummed.get(edge[0], 0) + \\\n solution_old_graph.edges[edge][config.SOLUTION_POWER_FLOW_KEY]\n for source in already_consummed:\n if already_consummed[source] <= self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY]:\n self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY] -= already_consummed[source]\n self.network_objective -= already_consummed[source]\n else:\n self.network_objective -= self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY]\n self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY] = 0\n\n # Remove edges from old network\n edges_to_remove = set()\n for e in self.optimization_graph.edges():\n if self.old_network_graph.has_edge(*e) or self.old_network_graph.has_edge(e[1],e[0]):\n edges_to_remove.add(e)\n self.optimization_graph.remove_edges_from(edges_to_remove)\n\n # Remove isolated buildings of optimization graph\n isolated_to_remove = set()\n for e in self.old_network_graph.edges():\n if e[0] in self.old_network_graph.nodes() and \\\n self.optimization_graph.nodes[e[1]].get(config.NODE_TYPE_KEY) == config.BUILDING_NODE_TYPE:\n isolated_to_remove.add(e)\n self.optimization_graph.remove_edges_from(isolated_to_remove)\n\n # Remove buildings from old network\n for n, data in self.old_network_graph.nodes(data=True):\n if data.get(config.NODE_TYPE_KEY) == config.BUILDING_NODE_TYPE:\n self.optimization_graph.remove_node(n)\n\n # Re-link sources\n sources = set()\n for n, data in self.optimization_graph.nodes(data=True):\n if data.get(config.NODE_TYPE_KEY) == config.SUPPLY_NODE_TYPE:\n sources.add(n)\n source_graph = self.optimization_graph.subgraph(sources).copy()\n self.optimization_graph.remove_nodes_from(sources)\n gnx.remove_isolates(self.optimization_graph)\n node_filter = lambda n: self.optimization_graph.nodes.get(n,{}).get(config.NODE_TYPE_KEY) != config.BUILDING_NODE_TYPE\n gnx.spatial_points_merge(self.optimization_graph, source_graph.nodes_to_gdf(), node_filter=node_filter, inplace=True)\n\n # fill missing information\n gnx.fill_edges_missing_geometry_attributes(self.optimization_graph)\n gnx.fill_length_attribute(self.optimization_graph, config.EDGE_LENGTH_KEY, only_missing=True)\n gnx.fill_length_attribute(self.optimization_graph, config.EDGE_COST_KEY, only_missing=True)\n for e in self.optimization_graph.edges(keys=True):\n self.optimization_graph.edges[e][config.LEASTCOST_COEF_KEY] = \\\n self.optimization_graph.edges[e].get(config.LEASTCOST_COEF_KEY,0)\n\n\n\n # 2. Process the DSSP on optimization graph\n self.check_is_ready()\n self.check_infeasibility(self.optimization_graph, self.network_objective)\n\n if self.old_network_graph is not None and self.modify_old_network:\n old_buildings = set(nx.get_node_attributes(self.old_network_graph, config.BUILDING_CONSUMPTION_KEY).keys())\n else:\n old_buildings = set()\n flows, obj_val = self.optimize_with_dssp_julia(self.optimization_graph, self.network_objective, old_buildings,postprocess= (not self.modify_old_network))\n self.logger.info(\"Optimization phase time: %.2fs\" % (time.time() - optimization_start))\n self.solution_graph = self.build_solution_graph(self.optimization_graph, flows, self.connected)\n\n # 3. Postprocess for old network graph\n if self.old_network_graph is not None:\n \n if self.modify_old_network:\n # Put the right supply capacity and cost\n for edge in self.old_capacity:\n if self.solution_graph.has_edge(edge[0],edge[1]):\n self.solution_graph.edges[(edge[0],edge[1])][config.EDGE_COST_KEY] = \\\n self.optimization_graph.edges[(config.IM_PREFIX+edge[0],config.IM_PREFIX+edge[1],0)][config.EDGE_COST_KEY]\n \n # Remove imaginary edges\n imaginary_nodes_to_remove = set()\n nodes_to_relabel = {}\n for edge in self.solution_graph.edges():\n if str(edge[0]).startswith(config.IM_PREFIX) and str(edge[1]).startswith(config.IM_PREFIX):\n real_edge = edge[0][len(config.IM_PREFIX):],edge[1][len(config.IM_PREFIX):]\n self.old_capacity[(real_edge[0], real_edge[1], 0)] = pd.np.inf\n self.old_capacity[(real_edge[1], real_edge[0], 0)] = pd.np.inf\n if not self.solution_graph.has_edge(*real_edge):\n for i in range(2):\n nodes_to_relabel[edge[i]] = real_edge[i]\n else:\n self.solution_graph.edges[real_edge[0],real_edge[1]][config.SOLUTION_POWER_FLOW_KEY] += \\\n self.solution_graph.edges[edge].get(config.SOLUTION_POWER_FLOW_KEY,0)\n imaginary_nodes_to_remove.add(edge[0])\n imaginary_nodes_to_remove.add(edge[1])\n elif str(edge[0]).startswith(config.IM_PREFIX):\n imaginary_nodes_to_remove.add(edge[0])\n elif str(edge[1]).startswith(config.IM_PREFIX):\n imaginary_nodes_to_remove.add(edge[1])\n\n nx.relabel_nodes(self.solution_graph, nodes_to_relabel, copy=False)\n self.solution_graph.remove_nodes_from(list(imaginary_nodes_to_remove))\n for node in nodes_to_relabel.values():\n if self.solution_graph.has_edge(node, node):\n self.solution_graph.remove_edge(node, node)\n\n else:\n for source in nx.get_node_attributes(self.solution_graph, config.SUPPLY_POWER_CAPACITY_KEY):\n self.solution_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY] += already_consummed.get(source,0)\n self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY] += already_consummed.get(source,0)\n\n return flows, obj_val",
"def optim_solve(\n self, x0: devices.PrimaryWeights = None, global_search: bool = False, **kwargs\n ) -> scipy.optimize.OptimizeResult:\n print(f'{\" optim_solve \":~^60s}')\n self._assert_problem_is_valid()\n if self._background is None:\n bounds = self.bounds * 2\n print(\"> No background specified, will optimise background.\")\n else:\n bounds = self.bounds\n\n if np.inf in self._target_contrast:\n print(\"> Aiming to maximise contrast.\")\n\n elif -np.inf in self._target_contrast:\n print(\"> Aiming to minimize contrast.\")\n\n constraints = [\n {\"type\": \"eq\", \"fun\": self.silencing_constraint, \"tol\": 1e-04}\n ]\n\n if x0 is None:\n x0 = self.initial_guess_x0()\n \n if not global_search: # Local minimization\n\n default_options = {\"iprint\": 2, \"disp\": True, \"ftol\": 1e-08}\n options = kwargs.pop(\"options\", default_options)\n\n print(\"> Performing local optimization with SLSQP.\")\n result = scipy.optimize.minimize(\n fun=self.objective_function,\n x0=x0,\n method=\"SLSQP\",\n bounds=bounds,\n constraints=constraints,\n options=options,\n **kwargs,\n )\n\n elif global_search: # Global minimization\n print(\n \"> Performing global optimization with basinhopping and SLSQP\"\n )\n\n # Configure global defaults\n disp = kwargs.pop(\"disp\", True)\n # Configure local defaults\n default_minimizer_kwargs = {\n \"method\": \"SLSQP\",\n \"constraints\": constraints,\n \"bounds\": bounds,\n \"options\": {\"iprint\": 2, \"disp\": False},\n }\n minimizer_kwargs = kwargs.pop(\n \"minimizer_kwargs\", default_minimizer_kwargs\n )\n\n # Do optimization\n result = scipy.optimize.basinhopping(\n func=self.objective_function,\n x0=x0,\n minimizer_kwargs=minimizer_kwargs,\n disp=disp,\n **kwargs,\n )\n\n return result",
"def solve(self):\n start = timer()\n # encode into milp\n me = MILPEncoder(MILPSolver.prob,\n MILPSolver.params.logger.LOGFILE, \n MILPSolver.params.INTRA_DEP_CONSTRS,\n MILPSolver.params.INTER_DEP_CONSTRS)\n if MILPSolver.lp == True:\n gmodel = me.lp_encode()\n else:\n gmodel = me.encode()\n # Set gurobi parameters\n pgo = 1 if MILPSolver.params.PRINT_GUROBI_OUTPUT == True else 0\n gmodel.setParam('OUTPUT_FLAG', pgo)\n tl = MILPSolver.params.TIMEOUT\n if tl != -1 : gmodel.setParam('TIME_LIMIT', tl)\n if not MILPSolver.params.DEFAULT_CUTS: \n MILPSolver.disable_default_cuts(gmodel)\n gmodel._vars = gmodel.getVars()\n # set callback cuts \n MILPSolver.id_form = IdealFormulation(MILPSolver.prob,\n gmodel, \n MILPSolver.params.IDEAL_FREQ,\n MILPSolver.params.logger.LOGFILE)\n MILPSolver.dep_cuts = DepCuts(MILPSolver.prob,\n gmodel,\n MILPSolver.params.DEP_FREQ,\n MILPSolver.params.INTRA_DEP_CUTS,\n MILPSolver.params.INTER_DEP_CUTS,\n MILPSolver.sip_params,\n MILPSolver.params.logger.LOGFILE)\n # Optimise\n if MILPSolver.params.callback_enabled() and MILPSolver.lp == False:\n gmodel.optimize(MILPSolver._callback)\n else:\n gmodel.optimize()\n\n runtime = timer() - start\n cex = None \n if MILPSolver.status == SolveResult.BRANCH_THRESHOLD:\n result = SolveResult.BRANCH_THRESHOLD\n elif gmodel.status == GRB.OPTIMAL:\n cex_shape = MILPSolver.prob.spec.input_layer.input_shape\n cex = np.zeros(cex_shape)\n for i in itertools.product(*[range(j) for j in cex_shape]):\n cex[i] = MILPSolver.prob.spec.input_layer.out_vars[i].x\n result = SolveResult.UNSATISFIED\n elif gmodel.status == GRB.TIME_LIMIT:\n result = SolveResult.TIMEOUT\n elif gmodel.status == GRB.INTERRUPTED:\n result = SolveResult.INTERRUPTED\n elif gmodel.status == GRB.INFEASIBLE or gmodel.status == GRB.INF_OR_UNBD:\n result = SolveResult.SATISFIED\n else:\n result = SolveResult.UNKNOWN\n \n # MILPSolver.logger.info('Verification problem {} solved, '\n # 'LP: {}, '\n # 'time: {:.2f}, '\n # 'result: {}.'\n # .format(MILPSolver.prob.id,\n # MILPSolver.lp,\n # runtime,\n # result.value))\n \n return SolveReport(result, runtime, cex)",
"def Solve(self, cost, termination=None, ExtraArgs=(), **kwds):\n # process and activate input settings\n sigint_callback = kwds.pop('sigint_callback', None)\n settings = self._process_inputs(kwds)\n disp = settings['disp'] if 'disp' in settings else False\n echo = settings['callback'] if 'callback' in settings else None\n# for key in settings:\n# exec \"%s = settings['%s']\" % (key,key)\n if disp in ['verbose', 'all']: verbose = True\n else: verbose = False\n #-------------------------------------------------------------\n\n from python_map import python_map\n if self._map != python_map:\n #FIXME: EvaluationMonitor fails for MPI, throws error for 'pp'\n from mystic.monitors import Null\n evalmon = Null()\n else: evalmon = self._evalmon\n fcalls, cost = wrap_function(cost, ExtraArgs, evalmon)\n\n # set up signal handler\n #self._EARLYEXIT = False\n self._generateHandler(sigint_callback) \n\n # activate signal_handler\n #import threading as thread\n #mainthread = isinstance(thread.current_thread(), thread._MainThread)\n #if mainthread: #XXX: if not mainthread, signal will raise ValueError\n import signal\n if self._handle_sigint:\n signal.signal(signal.SIGINT,self.signal_handler)\n\n # register termination function\n if termination is not None: self.SetTermination(termination)\n\n # get the nested solver instance\n solver = self._AbstractEnsembleSolver__get_solver_instance()\n #-------------------------------------------------------------\n\n # generate starting points\n initial_values = self._InitialPoints()\n\n # run optimizer for each grid point\n from copy import deepcopy as _copy\n op = [_copy(solver) for i in range(len(initial_values))]\n #cf = [cost for i in range(len(initial_values))]\n vb = [verbose for i in range(len(initial_values))]\n cb = [echo for i in range(len(initial_values))] #XXX: remove?\n at = self.id if self.id else 0 # start at self.id\n id = range(at,at+len(initial_values))\n\n # generate the local_optimize function\n def local_optimize(solver, x0, rank=None, disp=False, callback=None):\n from copy import deepcopy as _copy\n from mystic.tools import isNull\n solver.id = rank\n solver.SetInitialPoints(x0)\n if solver._useStrictRange: #XXX: always, settable, or sync'd ?\n solver.SetStrictRanges(min=solver._strictMin, \\\n max=solver._strictMax) # or lower,upper ?\n solver.Solve(cost, disp=disp, callback=callback)\n sm = solver._stepmon\n em = solver._evalmon\n if isNull(sm): sm = ([],[],[],[])\n else: sm = (_copy(sm._x),_copy(sm._y),_copy(sm._id),_copy(sm._info))\n if isNull(em): em = ([],[],[],[])\n else: em = (_copy(em._x),_copy(em._y),_copy(em._id),_copy(em._info))\n return solver, sm, em\n\n # map:: solver = local_optimize(solver, x0, id, verbose)\n results = self._map(local_optimize, op, initial_values, id, \\\n vb, cb, **self._mapconfig)\n\n # save initial state\n self._AbstractSolver__save_state()\n #XXX: HACK TO GET CONTENT OF ALL MONITORS\n # reconnect monitors; save all solvers\n from mystic.monitors import Monitor\n while results: #XXX: option to not save allSolvers? skip this and _copy\n _solver, _stepmon, _evalmon = results.pop()\n sm = Monitor()\n sm._x,sm._y,sm._id,sm._info = _stepmon\n _solver._stepmon.extend(sm)\n del sm\n em = Monitor()\n em._x,em._y,em._id,em._info = _evalmon\n _solver._evalmon.extend(em)\n del em\n self._allSolvers[len(results)] = _solver\n del results, _solver, _stepmon, _evalmon\n #XXX: END HACK\n\n # get the results with the lowest energy\n self._bestSolver = self._allSolvers[0]\n bestpath = self._bestSolver._stepmon\n besteval = self._bestSolver._evalmon\n self._total_evals = self._bestSolver.evaluations\n for solver in self._allSolvers[1:]:\n self._total_evals += solver.evaluations # add func evals\n if solver.bestEnergy < self._bestSolver.bestEnergy:\n self._bestSolver = solver\n bestpath = solver._stepmon\n besteval = solver._evalmon\n\n # return results to internals\n self.population = self._bestSolver.population #XXX: pointer? copy?\n self.popEnergy = self._bestSolver.popEnergy #XXX: pointer? copy?\n self.bestSolution = self._bestSolver.bestSolution #XXX: pointer? copy?\n self.bestEnergy = self._bestSolver.bestEnergy\n self.trialSolution = self._bestSolver.trialSolution #XXX: pointer? copy?\n self._fcalls = self._bestSolver._fcalls #XXX: pointer? copy?\n self._maxiter = self._bestSolver._maxiter\n self._maxfun = self._bestSolver._maxfun\n\n # write 'bests' to monitors #XXX: non-best monitors may be useful too\n self._stepmon = bestpath #XXX: pointer? copy?\n self._evalmon = besteval #XXX: pointer? copy?\n self.energy_history = None\n self.solution_history = None\n #from mystic.tools import isNull\n #if isNull(bestpath):\n # self._stepmon = bestpath\n #else:\n # for i in range(len(bestpath.y)):\n # self._stepmon(bestpath.x[i], bestpath.y[i], self.id)\n # #XXX: could apply callback here, or in exec'd code\n #if isNull(besteval):\n # self._evalmon = besteval\n #else:\n # for i in range(len(besteval.y)):\n # self._evalmon(besteval.x[i], besteval.y[i])\n #-------------------------------------------------------------\n\n # restore default handler for signal interrupts\n if self._handle_sigint:\n signal.signal(signal.SIGINT,signal.default_int_handler)\n\n # log any termination messages\n msg = self.Terminated(disp=disp, info=True)\n if msg: self._stepmon.info('STOP(\"%s\")' % msg)\n # save final state\n self._AbstractSolver__save_state(force=True)\n return",
"def _optimise(self):\n better = True\n self.solutions = set()\n\n # Rebuild the neighbours\n self.neighbours = {}\n\n for i in self.heuristic_path:\n self.neighbours[i] = []\n\n for j, dist in enumerate(TSP.edges[i]):\n if dist > 0 and j in self.heuristic_path:\n self.neighbours[i].append(j)\n\n # Restart the loop each time we find an improving candidate\n while better:\n better = self.improve()\n # Paths always begin at 0 so this should manage to find duplicate\n # solutions\n self.solutions.add(str(self.heuristic_path))\n\n self.save(self.heuristic_path, self.heuristic_cost)"
] | [
"0.7301385",
"0.6871695",
"0.674346",
"0.6738864",
"0.66965175",
"0.6695165",
"0.660309",
"0.65572757",
"0.65572757",
"0.64989126",
"0.6495357",
"0.6457791",
"0.6448608",
"0.6446663",
"0.6431411",
"0.63752735",
"0.6357446",
"0.6332625",
"0.63058853",
"0.6269354",
"0.62642485",
"0.623931",
"0.6237711",
"0.62172425",
"0.6202513",
"0.6173363",
"0.61499757",
"0.6133229",
"0.61235416",
"0.61002684"
] | 0.7083221 | 1 |
! Indicate the violated constraints. x The values for the decision variables. p The values for the parameters. Several lists that contain information regarding which constraints are violated. | def violated_constraints(
self, x: Dict[str, ArrayType], p: Dict[str, ArrayType]
) -> Tuple:
x = self.opt.decision_variables.dict2vec(x)
p = self.opt.parameters.dict2vec(p)
@dataclass
class ViolatedConstraint:
label: str
ctype: str
diff: cs.DM
pattern: cs.DM
def __str__(self):
return f"\n{self.label} [{self.ctype}]:\n{self.pattern}\n"
def __repr__(self):
info = str(self)
max_width = max(len(line) for line in info.split("\n"))
return "=" * max_width + info + "-" * max_width + "\n"
@property
def verbose_info(self):
info = str(self)
info += f"{self.diff}\n"
return info
lin_eq_violated_constraints = []
for label, sx_var in self.opt.lin_eq_constraints.items():
fun = cs.Function("fun", [self.opt.x, self.opt.p], [sx_var])
diff = fun(x, p)
lin_eq_violated_constraints.append(
ViolatedConstraint(label, "lin_eq", diff, diff >= 0.0)
)
eq_violated_constraints = []
for label, sx_var in self.opt.eq_constraints.items():
fun = cs.Function("fun", [self.opt.x, self.opt.p], [sx_var])
diff = fun(x, p)
eq_violated_constraints.append(
ViolatedConstraint(label, "eq", diff, diff >= 0.0)
)
lin_ineq_violated_constraints = []
for label, sx_var in self.opt.lin_ineq_constraints.items():
fun = cs.Function("fun", [self.opt.x, self.opt.p], [sx_var])
diff = fun(x, p)
lin_ineq_violated_constraints.append(
ViolatedConstraint(label, "lin_ineq", diff, diff >= 0.0)
)
ineq_violated_constraints = []
for label, sx_var in self.opt.ineq_constraints.items():
fun = cs.Function("fun", [self.opt.x, self.opt.p], [sx_var])
diff = fun(x, p)
ineq_violated_constraints.append(
ViolatedConstraint(label, "ineq", diff, diff >= 0.0)
)
return (
lin_eq_violated_constraints,
eq_violated_constraints,
lin_ineq_violated_constraints,
ineq_violated_constraints,
) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def constraints(self, x):\n pass",
"def check_constraints(Px,pk1,pk2,mu1,mu2,mu3):\n # Constraint 1: Check polarisation basis probabilities are valid.\n if (Px >= 1.0 or Px <= 0.0):\n print(\"Error! Constraint 1 < Px < 0: \", Px)\n exit(1)\n # Constraint 2: Check probability of pulse with intensity 1 is in bounds.\n if (pk1 >= 1.0 or pk1 <= 0.0):\n print(\"Error! Constraint 1 < pk1 < 0: \", pk1)\n exit(1)\n # Constraint 3: Check probability of pulse with intensity 2 is in bounds.\n if (pk2 >= 1.0 or pk2 <= 0.0):\n print(\"Error! Constraint 1 < pk2 < 0: \", pk2)\n exit(1)\n # Constraint 4: Check sum of probabilities for intensity 1 & 2 are less\n # than unity.\n if ((pk1 + pk2) >= 1.0):\n print(\"Error! Constraint (pk1 + pk2) < 1: \", pk1 + pk2)\n exit(1)\n # Constraint 5: Check value of intensity 1 is in bounds.\n if (mu1 >= 1.0 or mu1 <= 0.0):\n print(\"Error! Constraint 1 < mu1 < 0: \", mu1)\n exit(1)\n # Constraint 6: Check value of intensity 2 is in bounds.\n if (mu2 >= 1.0 or mu2 <= 0.0):\n print(\"Error! Constraint 1 < mu2 < 0: \", mu2)\n exit(1)\n # Constraint 7: Check values of all intensities are in bounds.\n if ((mu1 - mu3) <= mu2):\n print(\"Error! Constraint (mu1-mu3) > mu2: \", (mu1-mu3), mu2)\n exit(1)\n # Constraint 8: Check values of intensities 2 & 3 are in bounds.\n if (mu2 <= mu3):\n print(\"Error! Constraint mu2 > mu3: \", mu2, mu3)\n exit(1)\n return None",
"def remaining_constraints(self):\r\n \r\n def iec1(state,decision,nodes):\r\n return decision['E:L']+decision['E:R_1']<=nodes['E'].get_preds_value(state)\r\n def iec2(state,decision,nodes):\r\n return decision['R_1:L']<=nodes['R_1'].get_preds_value(state)\r\n def iec3(state,decision,nodes):\r\n return decision['G:R_1']>=-(nodes['R_1'].get_preds_value(state)) \r\n def iec4(state,decision,nodes):\r\n return decision['G:L']>=0.0\r\n def iec5(state,decision,nodes):\r\n return decision['E:L']>=0.0\r\n def iec6(state,decision,nodes):\r\n return decision['E:R_1']>=0.0\r\n def iec7(state,decision,nodes):\r\n return decision['R_1:L']>=0.0\r\n\r\n Inequality_Constraints=[iec1,iec2,iec3,iec4,iec5,iec6,iec7]\r\n \r\n return Inequality_Constraints",
"def check_constraints ( A, S, complete ) :\n\t\n\tok = True\n\t\n\tfor i in range(len(complete)) :\n\t\tif complete[i] :\n\t\t\tif not (dot(A[i],S) == 0) :\n\t\t\t\tok = False\n\t\t\t\tprint '\\n'\n\t\t\t\tprint '*** warning *** constraint %d not verified' % (i)\n\t\t\t\tvars_inds = (where(abs(A[i]) == 1))[0]\n\t\t\t\tprint 'variables involved:', vars_inds\n\t\t\t\tprint 'displacements:', S[vars_inds]\n\t\t\t\tprint\n\t\t\t\t#programPause = raw_input(\"Press the <ENTER> key to continue...\")\n\t\t\t\t\n\treturn ok",
"def check_all_constraints(csp) :\n\n for constraint in csp.get_all_constraints():\n assigned1 = csp.get_assigned_value(constraint.var1)\n assigned2 = csp.get_assigned_value(constraint.var2)\n check = constraint.check(assigned1,assigned2)\n if check==False and assigned1!=None and assigned2!=None:\n return False \n return True",
"def decision_function(self, X):\n ...",
"def get_constraints(self, X_v, U_v, X_last_p, U_last_p):\n\n constraints = [\n # Boundary conditions:\n X_v[0:2, 0] == self.x_init[0:2],\n X_v[2:4, 0] == self.x_init[2:4],\n X_v[4, 0] == self.x_init[4],\n X_v[5, 0] == self.x_init[5],\n\n X_v[:, -1] == self.x_final,\n\n # State constraints:\n cvx.abs(X_v[4, :]) <= self.t_max,\n cvx.abs(X_v[5, :]) <= self.w_max,\n X_v[1, :] >= 0,\n\n # Control constraints:\n cvx.abs(U_v[0, :]) <= self.max_gimbal,\n U_v[1, :] >= self.T_min,\n U_v[1, :] <= self.T_max,\n ]\n return constraints",
"def _check_parameters(self, p, integral=False, name=None, sym=None):\n for h in range(self._.d + 1):\n for i in range(self._.d + 1):\n for j in range(self._.d + 1):\n p[h, i, j] = ASParameters. \\\n _check_parameter(h, i, j, p[h, i, j],\n integral=integral,\n name=name, sym=sym)",
"def eval_safety_constraints(self, p_all, q_all, ubg_term=0., lbg_term=-np.inf,\n ubg_interm=0., lbg_interm=-np.inf, terminal_only=False,\n eps_constraints=1e-5):\n g_term_val = self.g_term_cas(p_all[-1, :, None],\n cas_reshape(q_all[-1, :], (self.n_s, self.n_s)))\n\n feasible_term = np.all(lbg_term - eps_constraints < g_term_val) and np.all(\n g_term_val < ubg_term + eps_constraints)\n\n feasible = feasible_term\n if terminal_only or self.h_mat_obs is None:\n\n if self.verbosity > 1:\n print((\n \"\\n===== Evaluated terminal constraint values: FEASIBLE = {} =====\".format(\n feasible)))\n print(g_term_val)\n print(\"\\n===== ===== ===== ===== ===== ===== ===== =====\")\n\n return feasible, g_term_val\n\n g_interm_val = self.g_interm_cas(p_all[-1, :, None], cas_reshape(q_all[-1, :], (\n self.n_s, self.n_s)))\n\n feasible_interm = np.all(\n lbg_interm - eps_constraints < g_interm_val) and np.all(\n g_interm_val < ubg_interm + eps_constraints)\n\n feasible = feasible_term and feasible_interm\n\n return feasible, np.vstack((g_term_val, g_interm_val))",
"def reset_parameters(self, p: Dict[str, ArrayType]):\n super().reset_parameters(p)\n if self.method == \"trust-constr\":\n if self.opt.nk:\n self._constraints[\"k\"].A = csc_matrix(self.opt.M(self.p).toarray())\n self._constraints[\"k\"].lb = -self.opt.c(self.p).toarray().flatten()\n if self.opt.na:\n eq = -self.opt.b(self.p).toarray().flatten()\n self._constraints[\"a\"].A = csc_matrix(self.opt.A(self.p).toarray())\n self._constraints[\"a\"].lb = eq\n self._constraints[\"a\"].ub = eq\n if self._constraints:\n self.minimize_input[\"constraints\"] = list(self._constraints.values())",
"def check_all_constraints(csp) :\n constraints=csp.get_all_constraints()\n for constraint in constraints:\n var1 = constraint.var1\n var2 = constraint.var2\n val1=csp.get_assigned_value(var1)\n val2=csp.get_assigned_value(var2)\n if val1!=None and val2!=None:\n if not constraint.check(val1,val2):\n return False\n return True",
"def bool_constraints(Px,pk1,pk2,mu1,mu2,mu3):\n C = np.array([1,1,1,1,1,1,1,1], dtype=bool) # Initialise array as True\n \n # Constraint 1: Check polarisation basis probabilities are valid.\n if (Px >= 1.0 or Px <= 0.0):\n C[0] = False\n # Constraint 2: Check probability of pulse with intensity 1 is in bounds.\n if (pk1 >= 1.0 or pk1 <= 0.0):\n C[1] = False\n # Constraint 3: Check probability of pulse with intensity 2 is in bounds.\n if (pk2 >= 1.0 or pk2 <= 0.0):\n C[2] = False\n # Constraint 4: Check sum of probabilities for intensity 1 & 2 are less\n # than unity.\n if ((pk1 + pk2) >= 1.0):\n C[3] = False\n # Constraint 5: Check value of intensity 1 is in bounds.\n if (mu1 >= 1.0 or mu1 <= 0.0):\n C[4] = False\n # Constraint 6: Check value of intensity 2 is in bounds.\n if (mu2 >= 1.0 or mu2 <= 0.0):\n C[5] = False\n # Constraint 7: Check values of all intensities are in bounds.\n if ((mu1 - mu3) <= mu2):\n C[6] = False\n # Constraint 8: Check values of intensities 2 & 3 are in bounds.\n if (mu2 <= mu3):\n C[7] = False\n return C",
"def clfqp(self,x,p):\n alp = self.alp_opt\n nu = self.nu_opt\n dt = self.dt\n n = self.n\n I = np.identity(n)\n M = self.ncm(x,p)\n nu = np.size(self.h_or_g(x,p),1)\n u = cp.Variable((nu,1))\n e = np.reshape(x,(n,1))\n fx = np.reshape(self.dynamicsf(x,p),(n,1))\n gx = self.h_or_g(x,p)\n dMdt = (nu*I-M)/dt\n constraints = [2*e.T@(fx+gx@u)+e.T@dMdt@e <= -2*alp*e.T@M@e]\n prob = cp.Problem(cp.Minimize(cp.sum_squares(u)),constraints)\n prob.solve()\n u = u.value\n u = np.ravel(u)\n return u",
"def validate_parameter_constraints(parameter_constraints, params, caller_name):\n for param_name, param_val in params.items():\n # We allow parameters to not have a constraint so that third party estimators\n # can inherit from sklearn estimators without having to necessarily use the\n # validation tools.\n if param_name not in parameter_constraints:\n continue\n\n constraints = parameter_constraints[param_name]\n\n if constraints == \"no_validation\":\n continue\n\n constraints = [make_constraint(constraint) for constraint in constraints]\n\n for constraint in constraints:\n if constraint.is_satisfied_by(param_val):\n # this constraint is satisfied, no need to check further.\n break\n else:\n # No constraint is satisfied, raise with an informative message.\n\n # Ignore constraints that we don't want to expose in the error message,\n # i.e. options that are for internal purpose or not officially supported.\n constraints = [\n constraint for constraint in constraints if not constraint.hidden\n ]\n\n if len(constraints) == 1:\n constraints_str = f\"{constraints[0]}\"\n else:\n constraints_str = (\n f\"{', '.join([str(c) for c in constraints[:-1]])} or\"\n f\" {constraints[-1]}\"\n )\n\n raise InvalidParameterError(\n f\"The {param_name!r} parameter of {caller_name} must be\"\n f\" {constraints_str}. Got {param_val!r} instead.\"\n )",
"def ensure_default_constraints(self,warn=False):\n positive_strings = ['variance','lengthscale', 'precision']\n for s in positive_strings:\n for i in self.grep_param_names(s):\n if not (i in self.all_constrained_indices()):\n name = self._get_param_names()[i]\n self.constrain_positive(name)\n if warn:\n print \"Warning! constraining %s postive\"%name",
"def define_constraints(self, m):\r\n\r\n def investment_decision_thermal_rule(_m, g, y):\r\n \"\"\"Investment decision constraints for candidate thermal generators (x_c)\"\"\"\r\n\r\n return (((m.DELTA[y] / m.INTEREST_RATE) * m.GAMMA[g] * m.I_C[g, y])\r\n + sum(m.DELTA[j] * m.C_FOM[g] for j in m.Y if j >= y)\r\n - m.mu_1[g, y]\r\n + ((m.DELTA[m.Y.last()] / m.INTEREST_RATE) * m.C_FOM[g])\r\n + sum(- m.sigma_3[g, j, s, t] for s in m.S for t in m.T for j in m.Y if j >= y)\r\n == 0)\r\n\r\n # Investment decision for thermal plant\r\n m.INVESTMENT_DECISION_THERMAL = Constraint(m.G_C_THERM, m.Y, rule=investment_decision_thermal_rule)\r\n\r\n def investment_decision_wind_rule(_m, g, y):\r\n \"\"\"Investment decision constraints for candidate wind generators (x_c)\"\"\"\r\n\r\n return (((m.DELTA[y] / m.INTEREST_RATE) * m.GAMMA[g] * m.I_C[g, y])\r\n + sum(m.DELTA[j] * m.C_FOM[g] for j in m.Y if j >= y)\r\n + sum(m.mu_3[self.k(m, g), j] for j in m.Y if j >= y)\r\n - m.mu_1[g, y]\r\n + ((m.DELTA[m.Y.last()] / m.INTEREST_RATE) * m.C_FOM[g])\r\n + sum(- m.Q_W[g, j, s, t] * m.sigma_5[g, j, s, t] for s in m.S for t in m.T for j in m.Y if j >= y)\r\n == 0)\r\n\r\n # Investment decision for wind plant\r\n m.INVESTMENT_DECISION_WIND = Constraint(m.G_C_WIND, m.Y, rule=investment_decision_wind_rule)\r\n\r\n def investment_decision_solar_rule(_m, g, y):\r\n \"\"\"Investment decision constraints for candidate solar generators (x_c)\"\"\"\r\n\r\n return (((m.DELTA[y] / m.INTEREST_RATE) * m.GAMMA[g] * m.I_C[g, y])\r\n + sum(m.DELTA[j] * m.C_FOM[g] for j in m.Y if j >= y)\r\n + sum(m.mu_2[self.k(m, g), j] for j in m.Y if j >= y)\r\n - m.mu_1[g, y]\r\n + ((m.DELTA[m.Y.last()] / m.INTEREST_RATE) * m.C_FOM[g])\r\n + sum(- m.Q_S[g, j, s, t] * m.sigma_7[g, j, s, t] for s in m.S for t in m.T for j in m.Y if j >= y)\r\n == 0)\r\n\r\n # Investment decision for solar plant\r\n m.INVESTMENT_DECISION_SOLAR = Constraint(m.G_C_SOLAR, m.Y, rule=investment_decision_solar_rule)\r\n\r\n def investment_decision_storage_rule(_m, g, y):\r\n \"\"\"Investment decision constraints for candidate thermal generators (x_c)\"\"\"\r\n\r\n return (((m.DELTA[y] / m.INTEREST_RATE) * m.GAMMA[g] * m.I_C[g, y])\r\n + sum(m.DELTA[j] * m.C_FOM[g] for j in m.Y if j >= y)\r\n + sum(m.mu_4[self.k(m, g), j] for j in m.Y if j >= y)\r\n - m.mu_1[g, y]\r\n + ((m.DELTA[m.Y.last()] / m.INTEREST_RATE) * m.C_FOM[g])\r\n + sum(\r\n (- m.sigma_12[g, j, s, t] - m.sigma_14[g, j, s, t] - m.sigma_17[g, j, s, t]) for s in m.S for t\r\n in m.T for j in m.Y if j >= y)\r\n == 0)\r\n\r\n # Investment decision for storage units\r\n m.INVESTMENT_DECISION_STORAGE = Constraint(m.G_C_STORAGE, m.Y, rule=investment_decision_storage_rule)\r\n\r\n def power_output_existing_thermal_rule(_m, g, y, s, t):\r\n \"\"\"Power output from existing thermal generators\"\"\"\r\n\r\n if y != m.Y.last() and t != m.T.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_2[g, y, s, t]\r\n + m.sigma_20[g, y, s, t] - m.sigma_20[g, y, s, t + 1]\r\n - m.sigma_23[g, y, s, t] + m.sigma_23[g, y, s, t + 1]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + ((m.DELTA[y] * m.RHO[y, s]) * (\r\n m.C_MC[g, y] + ((m.EMISSIONS_RATE[g] - m.baseline[y]) * m.permit_price[y])))\r\n == 0)\r\n\r\n elif y != m.Y.last() and t == m.T.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_2[g, y, s, t]\r\n + m.sigma_20[g, y, s, t]\r\n - m.sigma_23[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + ((m.DELTA[y] * m.RHO[y, s]) * (\r\n m.C_MC[g, y] + ((m.EMISSIONS_RATE[g] - m.baseline[y]) * m.permit_price[y])))\r\n == 0)\r\n\r\n elif y == m.Y.last() and t != m.T.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_2[g, y, s, t]\r\n + m.sigma_20[g, y, s, t] - m.sigma_20[g, y, s, t + 1]\r\n - m.sigma_23[g, y, s, t] + m.sigma_23[g, y, s, t + 1]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + ((m.DELTA[y] * m.RHO[y, s]) * (1 + (1 / m.INTEREST_RATE)) * (\r\n m.C_MC[g, y] + ((m.EMISSIONS_RATE[g] - m.baseline[y]) * m.permit_price[y])))\r\n == 0)\r\n\r\n elif y == m.Y.last() and t == m.T.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_2[g, y, s, t]\r\n + m.sigma_20[g, y, s, t]\r\n - m.sigma_23[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + ((m.DELTA[y] * m.RHO[y, s]) * (1 + (1 / m.INTEREST_RATE)) * (\r\n m.C_MC[g, y] + ((m.EMISSIONS_RATE[g] - m.baseline[y]) * m.permit_price[y])))\r\n == 0)\r\n\r\n else:\r\n raise Exception(f'Unhandled case: {g, y, s, t}')\r\n\r\n # Total power output from thermal generators\r\n m.POWER_OUTPUT_EXISTING_THERMAL = Constraint(m.G_E_THERM, m.Y, m.S, m.T,\r\n rule=power_output_existing_thermal_rule)\r\n\r\n def power_output_candidate_thermal_rule(_m, g, y, s, t):\r\n \"\"\"Power output from candidate thermal generators\"\"\"\r\n\r\n if y != m.Y.last() and t != m.T.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_3[g, y, s, t]\r\n + m.sigma_20[g, y, s, t] - m.sigma_20[g, y, s, t + 1]\r\n - m.sigma_23[g, y, s, t] + m.sigma_23[g, y, s, t + 1]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + ((m.DELTA[y] * m.RHO[y, s]) * (\r\n m.C_MC[g, y] + ((m.EMISSIONS_RATE[g] - m.baseline[y]) * m.permit_price[y])))\r\n == 0)\r\n\r\n elif y != m.Y.last() and t == m.T.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_3[g, y, s, t]\r\n + m.sigma_20[g, y, s, t]\r\n - m.sigma_23[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + ((m.DELTA[y] * m.RHO[y, s]) * (\r\n m.C_MC[g, y] + ((m.EMISSIONS_RATE[g] - m.baseline[y]) * m.permit_price[y])))\r\n == 0)\r\n\r\n elif y == m.Y.last() and t != m.T.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_3[g, y, s, t]\r\n + m.sigma_20[g, y, s, t] - m.sigma_20[g, y, s, t + 1]\r\n - m.sigma_23[g, y, s, t] + m.sigma_23[g, y, s, t + 1]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + ((m.DELTA[y] * m.RHO[y, s]) * (1 + (1 / m.INTEREST_RATE)) * (\r\n m.C_MC[g, y] + ((m.EMISSIONS_RATE[g] - m.baseline[y]) * m.permit_price[y])))\r\n == 0)\r\n\r\n elif y == m.Y.last() and t == m.T.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_3[g, y, s, t]\r\n + m.sigma_20[g, y, s, t]\r\n - m.sigma_23[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + ((m.DELTA[y] * m.RHO[y, s]) * (1 + (1 / m.INTEREST_RATE)) * (\r\n m.C_MC[g, y] + ((m.EMISSIONS_RATE[g] - m.baseline[y]) * m.permit_price[y])))\r\n == 0)\r\n\r\n else:\r\n raise Exception(f'Unhandled case: {g, y, s, t}')\r\n\r\n # Total power output from candidate thermal generators\r\n m.POWER_OUTPUT_CANDIDATE_THERMAL = Constraint(m.G_C_THERM, m.Y, m.S, m.T,\r\n rule=power_output_candidate_thermal_rule)\r\n\r\n def power_output_existing_wind_rule(_m, g, y, s, t):\r\n \"\"\"Power output from existing wind generators\"\"\"\r\n\r\n if y != m.Y.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_4[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + (m.DELTA[y] * m.RHO[y, s] * m.C_MC[g, y])\r\n == 0)\r\n else:\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_4[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + (m.DELTA[y] * m.RHO[y, s] * (1 + (1 / m.INTEREST_RATE)) * m.C_MC[g, y])\r\n == 0)\r\n\r\n # Total power output from existing wind generators\r\n m.POWER_OUTPUT_EXISTING_WIND = Constraint(m.G_E_WIND, m.Y, m.S, m.T, rule=power_output_existing_wind_rule)\r\n\r\n def power_output_candidate_wind_rule(_m, g, y, s, t):\r\n \"\"\"Power output from candidate wind generators\"\"\"\r\n\r\n if y != m.Y.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_5[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + ((m.DELTA[y] * m.RHO[y, s]) * (m.C_MC[g, y] - (m.baseline[y] * m.permit_price[y])))\r\n == 0)\r\n else:\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_5[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + ((m.DELTA[y] * m.RHO[y, s]) * (1 + (1 / m.INTEREST_RATE)) * (\r\n m.C_MC[g, y] - (m.baseline[y] * m.permit_price[y])))\r\n == 0)\r\n\r\n # Total power output from candidate wind generators\r\n m.POWER_OUTPUT_CANDIDATE_WIND = Constraint(m.G_C_WIND, m.Y, m.S, m.T, rule=power_output_candidate_wind_rule)\r\n\r\n def power_output_existing_solar_rule(_m, g, y, s, t):\r\n \"\"\"Power output from existing solar generators\"\"\"\r\n\r\n if y != m.Y.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_6[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + (m.DELTA[y] * m.RHO[y, s] * m.C_MC[g, y])\r\n == 0)\r\n\r\n else:\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_6[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + (m.DELTA[y] * m.RHO[y, s] * (1 + (1 / m.INTEREST_RATE)) * m.C_MC[g, y])\r\n == 0)\r\n\r\n # Total power output from existing solar generators\r\n m.POWER_OUTPUT_EXISTING_SOLAR = Constraint(m.G_E_SOLAR, m.Y, m.S, m.T, rule=power_output_existing_solar_rule)\r\n\r\n def power_output_candidate_solar_rule(_m, g, y, s, t):\r\n \"\"\"Power output from candidate solar generators\"\"\"\r\n\r\n if y != m.Y.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_7[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + ((m.DELTA[y] * m.RHO[y, s]) * (m.C_MC[g, y] - (m.baseline[y] * m.permit_price[y])))\r\n == 0)\r\n\r\n else:\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_7[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + ((m.DELTA[y] * m.RHO[y, s]) * (1 + (1 / m.INTEREST_RATE)) * (\r\n m.C_MC[g, y] - (m.baseline[y] * m.permit_price[y])))\r\n == 0)\r\n\r\n # Total power output from candidate solar generators\r\n m.POWER_OUTPUT_CANDIDATE_SOLAR = Constraint(m.G_C_SOLAR, m.Y, m.S, m.T, rule=power_output_candidate_solar_rule)\r\n\r\n def power_output_hydro_rule(_m, g, y, s, t):\r\n \"\"\"Power output from hydro generators\"\"\"\r\n\r\n if y != m.Y.last() and t != m.T.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_8[g, y, s, t]\r\n + m.sigma_20[g, y, s, t] - m.sigma_20[g, y, s, t + 1]\r\n - m.sigma_23[g, y, s, t] + m.sigma_23[g, y, s, t + 1]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + (m.DELTA[y] * m.RHO[y, s] * m.C_MC[g, y])\r\n == 0)\r\n\r\n elif y != m.Y.last() and t == m.T.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_8[g, y, s, t]\r\n + m.sigma_20[g, y, s, t]\r\n - m.sigma_23[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + (m.DELTA[y] * m.RHO[y, s] * m.C_MC[g, y])\r\n == 0)\r\n\r\n elif y == m.Y.last() and t != m.T.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_8[g, y, s, t]\r\n + m.sigma_20[g, y, s, t] - m.sigma_20[g, y, s, t + 1]\r\n - m.sigma_23[g, y, s, t] + m.sigma_23[g, y, s, t + 1]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + (m.DELTA[y] * m.RHO[y, s] * (1 + (1 / m.INTEREST_RATE)) * m.C_MC[g, y])\r\n == 0)\r\n\r\n elif y == m.Y.last() and t == m.T.last():\r\n return (- m.sigma_1[g, y, s, t] + m.sigma_8[g, y, s, t]\r\n + m.sigma_20[g, y, s, t]\r\n - m.sigma_23[g, y, s, t]\r\n - m.lamb[self.k(m, g), y, s, t]\r\n + (m.DELTA[y] * m.RHO[y, s] * (1 + (1 / m.INTEREST_RATE)) * m.C_MC[g, y])\r\n == 0)\r\n\r\n else:\r\n raise Exception(f'Unexpected case: {g, y, s, t}')\r\n\r\n # Total power output from hydro generators\r\n m.POWER_OUTPUT_HYDRO = Constraint(m.G_E_HYDRO, m.Y, m.S, m.T, rule=power_output_hydro_rule)\r\n\r\n def charging_power_existing_storage_rule(_m, g, y, s, t):\r\n \"\"\"Charging power for existing storage units\"\"\"\r\n\r\n return (- m.sigma_9[g, y, s, t] + m.sigma_11[g, y, s, t] + m.lamb[self.k(m, g), y, s, t]\r\n + (m.ETA[g] * m.zeta_1[g, y, s, t])\r\n == 0)\r\n\r\n # Existing storage unit charging power\r\n m.CHARGING_POWER_EXISTING_STORAGE = Constraint(m.G_E_STORAGE, m.Y, m.S, m.T,\r\n rule=charging_power_existing_storage_rule)\r\n\r\n def charging_power_candidate_storage_rule(_m, g, y, s, t):\r\n \"\"\"Charging power for candidate storage units\"\"\"\r\n\r\n return (- m.sigma_9[g, y, s, t] + m.sigma_12[g, y, s, t] + m.lamb[self.k(m, g), y, s, t]\r\n + (m.ETA[g] * m.zeta_1[g, y, s, t])\r\n == 0)\r\n\r\n # Existing storage unit charging power\r\n m.CHARGING_POWER_CANDIDATE_STORAGE = Constraint(m.G_C_STORAGE, m.Y, m.S, m.T,\r\n rule=charging_power_candidate_storage_rule)\r\n\r\n def discharging_power_existing_storage_rule(_m, g, y, s, t):\r\n \"\"\"Discharging power for existing storage units\"\"\"\r\n\r\n if y != m.Y.last():\r\n return (- m.sigma_10[g, y, s, t] + m.sigma_13[g, y, s, t] - m.lamb[self.k(m, g), y, s, t]\r\n - ((1 / m.ETA[g]) * m.zeta_1[g, y, s, t])\r\n + (m.DELTA[y] * m.RHO[y, s] * m.C_MC[g, y])\r\n == 0)\r\n else:\r\n return (- m.sigma_10[g, y, s, t] + m.sigma_13[g, y, s, t] - m.lamb[self.k(m, g), y, s, t]\r\n - ((1 / m.ETA[g]) * m.zeta_1[g, y, s, t])\r\n + (m.DELTA[y] * m.RHO[y, s] * (1 + (1 / m.INTEREST_RATE)) * m.C_MC[g, y])\r\n == 0)\r\n\r\n # Existing storage unit discharging power\r\n m.DISCHARGING_POWER_EXISTING_STORAGE = Constraint(m.G_E_STORAGE, m.Y, m.S, m.T,\r\n rule=discharging_power_existing_storage_rule)\r\n\r\n def discharging_power_candidate_storage_rule(_m, g, y, s, t):\r\n \"\"\"Discharging power for candidate storage units\"\"\"\r\n\r\n if y != m.Y.last():\r\n return (- m.sigma_10[g, y, s, t] + m.sigma_14[g, y, s, t] - m.lamb[self.k(m, g), y, s, t]\r\n - ((1 / m.ETA[g]) * m.zeta_1[g, y, s, t])\r\n + (m.DELTA[y] * m.RHO[y, s] * m.C_MC[g, y])\r\n == 0)\r\n else:\r\n return (- m.sigma_10[g, y, s, t] + m.sigma_14[g, y, s, t] - m.lamb[self.k(m, g), y, s, t]\r\n - ((1 / m.ETA[g]) * m.zeta_1[g, y, s, t])\r\n + (m.DELTA[y] * m.RHO[y, s] * (1 + (1 / m.INTEREST_RATE)) * m.C_MC[g, y])\r\n == 0)\r\n\r\n # Candidate storage unit discharging power\r\n m.DISCHARGING_POWER_CANDIDATE_STORAGE = Constraint(m.G_C_STORAGE, m.Y, m.S, m.T,\r\n rule=discharging_power_candidate_storage_rule)\r\n\r\n def energy_existing_storage_unit(_m, g, y, s, t):\r\n \"\"\"Storage unit energy\"\"\"\r\n\r\n if t != m.T.last():\r\n return - m.sigma_15[g, y, s, t] + m.sigma_16[g, y, s, t] - m.zeta_1[g, y, s, t] + m.zeta_1[\r\n g, y, s, t + 1] == 0\r\n\r\n else:\r\n return (- m.sigma_15[g, y, s, t] + m.sigma_16[g, y, s, t] - m.zeta_1[g, y, s, t] - m.sigma_18[g, y, s] +\r\n m.sigma_19[g, y, s] == 0)\r\n\r\n # Existing storage unit energy\r\n m.ENERGY_EXISTING_STORAGE = Constraint(m.G_E_STORAGE, m.Y, m.S, m.T, rule=energy_existing_storage_unit)\r\n\r\n def energy_candidate_storage_unit(_m, g, y, s, t):\r\n \"\"\"Storage unit energy\"\"\"\r\n\r\n if t != m.T.last():\r\n return - m.sigma_15[g, y, s, t] + m.sigma_17[g, y, s, t] - m.zeta_1[g, y, s, t] + m.zeta_1[\r\n g, y, s, t + 1] == 0\r\n\r\n else:\r\n return (- m.sigma_15[g, y, s, t] + m.sigma_17[g, y, s, t] - m.zeta_1[g, y, s, t] - m.sigma_18[g, y, s] +\r\n m.sigma_19[g, y, s] == 0)\r\n\r\n # Existing storage unit energy\r\n m.ENERGY_CANDIDATE_STORAGE = Constraint(m.G_C_STORAGE, m.Y, m.S, m.T, rule=energy_candidate_storage_unit)\r\n\r\n def load_shedding_power_rule(_m, z, y, s, t):\r\n \"\"\"Load shedding power\"\"\"\r\n\r\n if y != m.Y.last():\r\n return - m.sigma_26[z, y, s, t] - m.lamb[z, y, s, t] + (m.DELTA[y] * m.RHO[y, s] * m.C_L[z]) == 0\r\n else:\r\n return - m.sigma_26[z, y, s, t] - m.lamb[z, y, s, t] + (\r\n m.DELTA[y] * m.RHO[y, s] * (1 + (1 / m.INTEREST_RATE)) * m.C_L[z]) == 0\r\n\r\n # Load shedding power\r\n m.LOAD_SHEDDING_POWER = Constraint(m.Z, m.Y, m.S, m.T, rule=load_shedding_power_rule)\r\n\r\n def powerflow_rule(_m, l, y, s, t):\r\n \"\"\"Powerflow between adjacent NEM zones\"\"\"\r\n\r\n return (- m.sigma_27[l, y, s, t] + m.sigma_28[l, y, s, t]\r\n + (m.INCIDENCE_MATRIX[l, self.g(l)] * m.lamb[self.g(l), y, s, t])\r\n + (m.INCIDENCE_MATRIX[l, self.h(l)] * m.lamb[self.h(l), y, s, t])\r\n == 0)\r\n\r\n # Powerflow\r\n m.POWERFLOW = Constraint(m.L, m.Y, m.S, m.T, rule=powerflow_rule)\r\n\r\n return m",
"def solve(targets, \n payoff,\n defender_resources:int=1, \n attacker_resources:int=1, \n ptype:str=\"MILP\", \n minimax:str=\"maximize\"):\n # Need a big number. Will lower bound later\n M = 9999\n\n p = cplex.Cplex()\n if ptype in (\"milp\", \"MILP\"):\n p.set_problem_type(cplex.Cplex.problem_type.MILP)\n else:\n print(\"Problem type:\",ptype,\"is not currently supported\")\n exit(1)\n\n if minimax in (\"max\",\"maximize\"):\n p.objective.set_sense(p.objective.sense.maximize)\n elif minimax in (\"min\",\"minimize\"):\n p.objective.set_sense(p.objective.sense.minimize)\n else:\n print(\"Only solves maximization or minimization problems\")\n\n num_targets = len(targets)\n # v is the z's, x's, v_def, and v_att\n v = [\"z\"+str(t) for t in range(num_targets)] \\\n + [\"x\"+str(t) for t in range(num_targets)] \\\n + [\"v_def\",\"v_att\"] \n num_variables = len(v)\n obj = np.zeros(num_variables)\n for i in range(num_variables):\n if v[i] == \"v_def\":\n obj[i] = 1.\n lb = np.zeros(num_variables)\n ub = np.ones(num_variables)\n for i in range(num_variables):\n if v[i] in (\"v_def\",\"v_att\"):\n ub[i] = cplex.infinity\n lb[i] = -1*cplex.infinity\n\n p.variables.add(obj = obj, # Objective function\n lb = lb, # Lower bound\n ub = ub, # Upper bound\n names = v) # Variable names\n # z_i \\in {0,1} Set all z_i to integer values\n [p.variables.set_types([(\"z\"+str(t),p.variables.type.integer)]) for t in range(num_targets)]\n # x_i \\in [0,1] Set all x_i to continuous values\n [p.variables.set_types([(\"x\"+str(t),p.variables.type.continuous)]) for t in range(num_targets)]\n # Also set for attacker and defender\n p.variables.set_types([(\"v_def\",p.variables.type.continuous)])\n p.variables.set_types([(\"v_att\",p.variables.type.continuous)])\n\n util_du = [M+payoff[i][2] for i in range(num_targets)]\n util_dc = [payoff[i][3] for i in range(num_targets)]\n util_ac = [M+payoff[i][3] for i in range(num_targets)]\n init_params = np.array([1.,defender_resources])\n rhs = np.hstack((init_params, util_du, util_dc, util_ac))\n\n senses = [\"E\",\"L\"] \\\n + [\"L\" for i in range(num_targets)] \\\n + [\"G\" for i in range(num_targets)]\\\n + [\"L\" for i in range(num_targets)]\n \n\n constraints = []\n zl = []\n zc = []\n xl = []\n xc = []\n for t in range(num_targets):\n zl.append(\"z\"+str(t))\n zc.append(1.)\n xl.append(\"x\"+str(t))\n xc.append(1.)\n constraints.append([zl,zc])\n constraints.append([xl,xc])\n\n # Defender's utility\n # Interleave vars and coefficients\n # Easier doing it this way that inline loops\n def_util_vars = []#np.zeros(num_targets*3)\n def_util_coef = []#np.zeros(num_targets*3)\n def_util = []\n for i in range(num_targets):\n def_util_vars = ([\"v_def\", \"x\"+str(i), \"z\"+str(i)])\n def_util_coef = ([1., (payoff[i][2] - payoff[i][1]), M])\n constraints.append([def_util_vars, def_util_coef])\n\n\n\n # Attacker strats\n att_strat_vars = []\n att_strat_coef = []\n att_strat = []\n for i in range(num_targets):\n att_strat_vars = ([\"v_att\", \"x\"+str(i)])\n att_strat_coef = ([1., payoff[i][3] - payoff[i][4]])\n constraints.append([att_strat_vars,att_strat_coef])\n\n\n # Attacker utility\n att_util_vars = []\n att_util_coef = []\n att_util = []\n for i in range(num_targets):\n att_util_vars = ([\"v_att\", \"x\"+str(i), \"z\"+str(i)])\n att_util_coef = ([1., payoff[i][3] - payoff[i][4], M])\n constraints.append([att_util_vars, att_util_coef])\n\n # Throw them all together\n constraint_names = [\"r\"+str(i) for i in range(len(constraints))]\n\n p.linear_constraints.add(lin_expr = constraints,\n senses = senses,\n rhs = rhs,\n names = constraint_names)\n p.solve()\n return p.solution.get_values()",
"def ok(self, point):\n [x1, x2, x3, x4, x5, x6] = point.decisions\n if x1 + x2 -2 < 0:\n return False\n if 6 - x1 - x2 < 0:\n return False\n if 2 - x2 + x1 < 0:\n return False\n if 2 - x1 + 3*x2 < 0:\n return False\n if 4 - (x3 - 3)**2 - x4 < 0:\n return False\n if (x5 - 3)**3 + x6 - 4 < 0:\n return False\n for i, d in enumerate(point.decisions):\n if d < self.decisions[i].low or d > self.decisions[i].high:\n print i, d, self.decisions[i].low, self.decisions[i].high\n return False\n return True",
"def constraints(self):\n ...",
"def solve(P, M, N, C, items, constraints):\n Items = []\n weight_dict = dict()\n cost_dict = dict()\n earn_dict = dict()\n class_dict = dict()\n \n for i in items:\n Items.append(i[0])\n weight_dict[i[0]] = i[2]\n cost_dict[i[0]] = i[3]\n earn_dict[i[0]] = i[4] - i[3]\n class_dict[i[0]] = i[1]\n \n Class_dict = defaultdict(list)\n for key, value in sorted(class_dict.iteritems()):\n Class_dict[value].append(key)\n \n # Create the 'prob' variable to contain the problem data\n prob = LpProblem(\"The PICKITEMS Problem\", LpMaximize)\n # Two dictionary called 'x_vars' and 'y_vars' are created to contain the referenced Variables\n x_vars = LpVariable.dicts(\"\",Items,0,1,cat=LpInteger)\n y_vars = LpVariable.dicts(\"#\",range(N),0,1,cat=LpInteger)\n \n # The objection function is added to 'prob' first\n prob += lpSum([earn_dict[i]*x_vars[i] for i in Items]), \"Total money we can earn in this file\"\n \n # Constraints are added to 'prob'\n prob += lpSum([weight_dict[i]*x_vars[i] for i in Items]) <= P, \"WeightsRequirement\"\n prob += lpSum([cost_dict[i]*x_vars[i] for i in Items]) <= M, \"CostRequirement\"\n # the relations(constraint) between class and item (x and y)\n for num in range(C):\n for i in Class_dict[num]:\n prob += LpConstraint(x_vars[i]-y_vars[num] <= 0), \"\"\n # the relations for class constraints\n for constraint in constraints:\n prob += lpSum([y_vars[i] for i in constraint]) <= 1, \"\"\n # The problem is solved using PuLP's choice of Solver\n prob.solve()\n \n items_chosen = []\n for v in prob.variables():\n if v.varValue == 1 and v.name[0]!='#':\n items_chosen.append(v.name[1:])\n return items_chosen",
"def express(self, *args, **kwargs) -> List[Union[LpConstraint, Constr]]:\n\n pass",
"def pending_f(self, x_p):\n targetlabel_mask = torch.from_numpy(onehot_like(np.zeros(self.classnum), self.target))\n secondlargest_mask = torch.from_numpy(np.ones(self.classnum)) - targetlabel_mask\n targetlabel_mask = targetlabel_mask.to(self.device)\n secondlargest_mask = secondlargest_mask.to(self.device)\n\n Zx_i = np.max((self.model.get_logits(x_p).double().to(self.device) * secondlargest_mask).cpu().detach().numpy())\n Zx_t = np.max((self.model.get_logits(x_p).double().to(self.device) * targetlabel_mask).cpu().detach().numpy())\n\n if ( Zx_i - Zx_t < - self.confidence):\n return True\n else:\n return False",
"def lp(mode, objective, constraints):\n if mode.lower() == 'max':\n mode = LpMaximize\n elif mode.lower() == 'min':\n mode = LpMinimize\n prob = LpProblem(\"\", mode)\n prob += objective\n for c in constraints:\n prob += c\n prob.solve()\n return prob, prob.objective.value(), dict((v.name, v.value()) for v in prob.variables())",
"def check_occuring_variables(formula,variables_to_consider,allowed_variables) :\n variable_set=set(allowed_variables)\n for clause in formula :\n variables_in_clause = {abs(l) for l in clause if abs(l) in variables_to_consider}\n if not variables_in_clause <= variable_set:\n return False, [v for v in variables_in_clause if not v in variable_set] \n return True, []",
"def constraints(self) -> Tuple[NDArray, NDArray]:",
"def solve(num_wizards, num_constraints, wizards, constraints):\n\n # print(num_wizards)\n # print(num_constraints)\n # print(wizards)\n # print(constraints)\n # node_set = set(wizards)\n \n\n\n def cost(sol,num_constraints,constraints):\n constraints_satisfied = 0\n constraints_failed = []\n output_ordering_map = {k: v for v, k in enumerate(sol)}\n for c in constraints:\n\n m = output_ordering_map # Creating an alias for easy reference\n\n wiz_a = m[c[0]]\n wiz_b = m[c[1]]\n wiz_mid = m[c[2]]\n\n if (wiz_a < wiz_mid < wiz_b) or (wiz_b < wiz_mid < wiz_a):\n constraints_failed.append(c)\n else:\n constraints_satisfied += 1\n return num_constraints - constraints_satisfied\n\n def neighbors(sol):\n wiz1 = random.randint(0,num_wizards-1)\n wiz2 = random.randint(0,num_wizards-1)\n\n new_sol = copy.copy(sol)\n temp = new_sol[wiz1]\n new_sol[wiz1] = new_sol[wiz2]\n new_sol[wiz2] = temp\n \n return new_sol\n\n def acceptance_probability(old_cost,new_cost,T):\n exponent = (old_cost - new_cost) / T\n \n try:\n ans = math.exp(exponent)\n except OverflowError:\n ans = float('inf')\n return ans\n\n\n def anneal(solution, num_constraints, constraints):\n old_cost = 0\n new_cost = 0\n old_cost = cost(solution,num_constraints,constraints)\n T = 1.0\n T_min = 0.000001\n alpha = 0.98\n while T > T_min:\n i = 1\n while i <= 1000:\n new_solution = neighbors(solution)\n new_cost = cost(new_solution,num_constraints,constraints)\n if new_cost == 0:\n return new_solution,new_cost\n ap = acceptance_probability(old_cost, new_cost, T)\n if ap > random.random():\n solution = new_solution\n old_cost = new_cost\n i += 1\n T = T*alpha\n return solution, old_cost\n\n s = copy.copy(wizards)\n random.shuffle(s)\n ret = anneal(s,num_constraints,constraints)\n \n for i in range(10):\n if ret[1] == 0:\n break\n random.shuffle(s)\n new_ret = anneal(s,num_constraints,constraints)\n print(i)\n if new_ret[1] < ret[1]:\n ret = new_ret\n print(\"constraints failed: {0}\".format(ret[1]))\n return ret[0]",
"def find_nominal_point(p):\n num_p = p.shape[0]\n num_d = p.shape[1]\n m = Model(\"nominal\")\n u = m.addVar(name=\"u\", lb=0)\n \n y = m.addVars(range(num_p*num_d), vtype=GRB.CONTINUOUS, obj=0.0, name=\"y\")\n # new nominal point\n beta = m.addVars(range(num_d), vtype=GRB.CONTINUOUS, obj=0.0, name=\"beta\", lb=0)\n \n m.setObjective(u, GRB.MINIMIZE)\n \n for i in range(num_p):\n m.addConstr(u, GRB.GREATER_EQUAL, quicksum(y[i*num_d+j] for j in range(num_d)), \"u_\"+str(i))\n\n for i in range(num_p):\n for j in range(num_d):\n m.addConstr(y[i*num_d+j], GRB.GREATER_EQUAL, p[i,j]-beta[j], \"c1\"+str(i))\n m.addConstr(y[i*num_d+j], GRB.GREATER_EQUAL, beta[j]-p[i,j], \"c2\"+str(i))\n\n m.setParam( 'OutputFlag', False )\n m.optimize()\n \n #print('Obj: %g' % m.objVal) \n \n #for v in m.getVars():\n # print('%s %g' % (v.varName, v.x))\n \n threshold = 0\n for v in m.getVars():\n if v.varName == \"u\":\n threshold = v.x\n break\n \n nominal_params = m.getAttr('x', beta)\n \n nominal_p = []\n for i in range(num_d):\n nominal_p.append(nominal_params[i])\n \n return nominal_p, threshold#tuple(nominal_p)",
"def objective_constraints(self, variables, mask, reservations, mpc_ene=None):\n constraint_list = []\n ice_gen = variables['ice_gen']\n on_ice = variables['on_ice']\n\n constraint_list += [cvx.NonPos(cvx.multiply(self.p_min, on_ice) - ice_gen)]\n constraint_list += [cvx.NonPos(ice_gen - cvx.multiply(self.rated_power*self.n, on_ice))]\n\n return constraint_list",
"def testConditionReasons(self):\n \n state = State.from_problem(self.prob)\n\n relevantVars = []\n drive = self.dom.get_action(\"drive\")\n with drive.instantiate([\"agent\", \"tru1\", \"apt1\"], self.prob):\n self.assert_(state.is_satisfied(drive.precondition, relevantVars))\n\n relevantVars = set(relevantVars)\n \n s1 = StateVariable(self.prob.functions[\"city-of\"][0], [self.prob[\"pos1\"]])\n s2 = StateVariable(self.prob.functions[\"city-of\"][0], [self.prob[\"apt1\"]])\n s3 = StateVariable(self.prob.functions[\"location-of\"][0], [self.prob[\"tru1\"]])\n \n self.assertEqual(len(relevantVars), 3)\n self.assert_(s1 in relevantVars)\n self.assert_(s2 in relevantVars)\n self.assert_(s3 in relevantVars)",
"def check_parameter_bounds(self):\n for p in self.variables.keys():\n data = self.get_attr(p)\n if isinstance(data, dc_cp):\n if data.val > data.max_val + err:\n msg = (\n 'Invalid value for ' + p + ': ' + p + ' = ' +\n str(data.val) + ' above maximum value (' +\n str(data.max_val) + ') at component ' + self.label +\n '.')\n logger.warning(msg)\n\n elif data.val < data.min_val - err:\n msg = (\n 'Invalid value for ' + p + ': ' + p + ' = ' +\n str(data.val) + ' below minimum value (' +\n str(data.min_val) + ') at component ' + self.label +\n '.')\n logger.warning(msg)\n\n elif isinstance(data, dc_cc) and data.is_set:\n expr = self.get_char_expr(data.param, **data.char_params)\n data.char_func.get_domain_errors(expr, self.label)\n\n elif isinstance(data, dc_gcc) and data.is_set:\n for char in data.elements:\n char_data = self.get_attr(char)\n expr = self.get_char_expr(\n char_data.param, **char_data.char_params)\n char_data.char_func.get_domain_errors(expr, self.label)"
] | [
"0.6426779",
"0.6170062",
"0.57802975",
"0.5764853",
"0.5730316",
"0.55354714",
"0.5497718",
"0.5469907",
"0.54452014",
"0.54144084",
"0.54126674",
"0.53736746",
"0.537083",
"0.5302913",
"0.5219222",
"0.5168163",
"0.5164424",
"0.5158632",
"0.5148973",
"0.513843",
"0.5124698",
"0.5124307",
"0.5116501",
"0.50866735",
"0.508377",
"0.50771964",
"0.5071072",
"0.505096",
"0.5050172",
"0.50380176"
] | 0.7703603 | 0 |
! Interpolate a trajectory traj The trajectory to be interpolated where the columns correspond to the states over time. T The time duration of the trajectory. An interpolated function. | def interpolate(traj: cs.DM, T: float, **interp_args) -> interp1d:
assert isinstance(
traj, cs.DM
), f"traj is incorrect type, got '{type(traj)}', expected casadi.DM'"
t = np.linspace(0, T, traj.shape[1])
return interp1d(t, traj.toarray(), **interp_args) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def interpolate_timeseries(self, x, t, **kw):\n v, t_v = self.timeseries(x, rmnans=True)\n kw.update(dict(bounds_error=False))\n interpolant = sp.interpolate.interp1d(t_v, v, **kw)\n return interpolant(t)",
"def linear_interpolate_value_at_time(t0, v0, t1, v1, t):\n return v0 + linear_interpolate_value_change(t0, v0, t1, v1, t - t0)",
"def interpolator(self, states):\n t = np.asarray([state.t for state in states])\n y = np.asarray([state.y for state in states])\n\n return interp1d(t, y, assume_sorted=True, kind='cubic')",
"def interpolate(self, t):\n try:\n n = len(self.t)\n except TypeError:\n # self.t is not a sequence. Re-raise the exception\n # with an appropriate error message.\n raise TypeError(\"Please run the simulation first\")\n else:\n if (n < 2):\n raise ValueError(\"Not enough simulation steps\")\n tmin = self.t[0]\n tmax = self.t[n-1]\n if t < tmin or t > tmax:\n raise ValueError(\"Requested time is outside the simulated interval\")\n if self.adaptiveStepSize:\n nbelow = bisect_right(self.t, t) - 1 \n else:\n dt = (tmax - tmin)*1.0/(n - 1)\n nbelow = int(math.floor((t - tmin)/dt))\n nabove = nbelow + 1\n if nabove >= n:\n nabove = n - 1\n nbelow = nabove - 1\n x = interpolate_Hermite(t, self.t[nbelow], self.x[nbelow], self.v[nbelow],\n self.t[nabove], self.x[nabove], self.v[nabove])\n v = interpolate_linear(t, self.t[nbelow], self.v[nbelow],\n self.t[nabove], self.v[nabove])\n return x, v",
"def _lerp(a, b, t, out=None):\n diff_b_a = subtract(b, a)\n # asanyarray is a stop-gap until gh-13105\n lerp_interpolation = asanyarray(add(a, diff_b_a*t, out=out))\n subtract(b, diff_b_a * (1 - t), out=lerp_interpolation, where=t>=0.5)\n if lerp_interpolation.ndim == 0 and out is None:\n lerp_interpolation = lerp_interpolation[()] # unpack 0d arrays\n return lerp_interpolation",
"def interpolate(x, t, t_int, angle=False):\n x_int = np.zeros((t_int.shape[0], x.shape[1]))\n for i in range(x.shape[1]):\n if angle:\n x[:, i] = np.unwrap(x[:, i])\n x_int[:, i] = np.interp(t_int, t, x[:, i])\n return x_int",
"def slerp(targettime, time, q):\n #debug_here()\n i_interp_int, t_matrix = compute_t(targettime, time)\n q_interp = mult(q[np.clip(i_interp_int + 1,0,len(time)-1),:], inv(q[i_interp_int,:]))\n q_interp = pow(q_interp, t_matrix) \n q_interp = mult(q_interp, q[i_interp_int,:])\n t_zero = (t_matrix == 0).flatten()\n q_interp[t_zero] = q[i_interp_int][t_zero]\n return q_interp",
"def compute_smoothed_traj(path, V_des, alpha, dt):\n ########## Code starts here ##########\n #convert path to numpy array because otherwise it's a pain!\n path = np.array(path)\n #create the time vector buy finding the distance from each point and dividing by the straight line velocity\n N = len(path)\n t = np.zeros(N)\n for i in range(1, N):\n #get the distance between the points\n distance = np.linalg.norm(path[i, :] - path[i-1, :])\n #calc the time based on distance and velocity\n t[i] = distance/V_des + t[i-1]\n t_smoothed = np.arange(t[0], t[-1], dt);\n print(t_smoothed.size)\n \n #interpolate over the given path \n x_tck = scipy.interpolate.splrep(t, path[:,0], s=alpha)\n y_tck = scipy.interpolate.splrep(t, path[:,1], s=alpha)\n \n #allocate for the trajectory\n traj_smoothed = np.zeros([len(t_smoothed),7])\n \n #generate the states\n traj_smoothed[:,0] = scipy.interpolate.splev(t_smoothed, x_tck)\n traj_smoothed[:,1] = scipy.interpolate.splev(t_smoothed, y_tck)\n traj_smoothed[:,3] = scipy.interpolate.splev(t_smoothed, x_tck, der=1)\n traj_smoothed[:,4] = scipy.interpolate.splev(t_smoothed, y_tck, der=1)\n traj_smoothed[:,2] = np.arctan2(traj_smoothed[:,4], traj_smoothed[:,3])\n traj_smoothed[:,5] = scipy.interpolate.splev(t_smoothed, x_tck, der=2)\n traj_smoothed[:,6] = scipy.interpolate.splev(t_smoothed, y_tck, der=2) \n ########## Code ends here ##########\n\n return traj_smoothed, t_smoothed",
"def interpolate_matrix(matrix):",
"def linear_interpolate_value_change(t0, v0, t1, v1, dt):\n return (v1 - v0)/float(t1-t0) * dt",
"def interpolate_arrays(t, idx, x_array, time_array):\n x1 = np.array([x_array[i, idx[i] - 1] for i in range(len(idx))])\n x2 = np.array([x_array[i, idx[i]] for i in range(len(idx))])\n t1 = np.array([time_array[i, idx[i] - 1] for i in range(len(idx))])\n t2 = np.array([time_array[i, idx[i]] for i in range(len(idx))])\n ta = t * np.ones(time_array.shape[0])\n return x1 + np.multiply(np.divide(x2-x1, t2-t1), ta - t1)",
"def interpolate(timepoint_defined, signal, interp_type, TR):\n\n timepoint_defined = np.array(timepoint_defined)\n\n true_inds = np.where(timepoint_defined == True)[0]\n false_inds = np.where(timepoint_defined == False)[0]\n\n\n signal_copy = np.array(signal)\n\n if interp_type == 'linear':\n\n #Still need to handle beginning/end cases\n\n for temp_timepoint in false_inds:\n\n\n #past_timepoint = true_inds[np.sort(np.where(true_inds < temp_timepoint)[0])[-1]]\n #future_timepoint = true_inds[np.sort(np.where(true_inds > temp_timepoint)[0])[0]]\n\n\n #Be sure there is at least one future timepoint and one past timepoint.\n #If there isn't, then grab either two past or two future timepoints and use those\n #for interpolation. If there aren't even two total past + future timepoints, then\n #just set the output to 0. Could also set the output to be unadjusted, but this\n #is a way to make the issue more obvious.\n temp_past_timepoint = np.sort(np.where(true_inds < temp_timepoint)[0])\n temp_future_timepoint = np.sort(np.where(true_inds > temp_timepoint)[0])\n\n #If we don't have enough data to interpolate/extrapolate\n if len(temp_past_timepoint) + len(temp_future_timepoint) < 2:\n\n signal_copy[temp_timepoint] = 0\n\n #If we do have enough data to interpolate/extrapolate\n else:\n\n if len(temp_past_timepoint) == 0:\n past_timepoint = true_inds[temp_future_timepoint[1]]\n else:\n past_timepoint = true_inds[temp_past_timepoint[-1]]\n\n if len(temp_future_timepoint) == 0:\n future_timepoint = true_inds[temp_past_timepoint[-2]]\n else:\n future_timepoint = true_inds[temp_future_timepoint[0]]\n\n #Find the appopriate past/future values\n past_value = signal_copy[int(past_timepoint)]\n future_value = signal_copy[int(future_timepoint)]\n\n #Use the interp1d function for interpolation\n interp_object = interp.interp1d([past_timepoint, future_timepoint], [past_value, future_value], bounds_error=False, fill_value='extrapolate')\n signal_copy[temp_timepoint] = interp_object(temp_timepoint).item(0)\n\n return signal_copy\n\n\n #For cubic spline interpolation, instead of taking the past/future timepoint\n #we will just take the closest 5 timepoints. If there aren't 5 timepoints, we will\n #set the output to 0\n if interp_type == 'cubic_spline':\n\n sorted_good = np.sort(signal_copy[true_inds])\n min_bound = sorted_good[0]\n max_bound = sorted_good[-1]\n\n #Continue if there are at least 5 good inds\n true_inds_needed = 5\n if len(true_inds) >= true_inds_needed:\n\n for temp_timepoint in false_inds:\n\n closest_inds = true_inds[np.argsort(np.absolute(true_inds - temp_timepoint))]\n closest_vals = signal_copy[closest_inds.astype(int)]\n interp_object = interp.interp1d(closest_inds, closest_vals, kind = 'cubic', bounds_error=False, fill_value='extrapolate')\n signal_copy[temp_timepoint.astype(int)] = interp_object(temp_timepoint).item(0)\n\n min_bound_exceded = np.where(signal_copy < min_bound)[0]\n if len(min_bound_exceded) > 0:\n\n signal_copy[min_bound_exceded] = min_bound\n\n max_bound_exceded = np.where(signal_copy > max_bound)[0]\n if len(max_bound_exceded) > 0:\n\n signal_copy[max_bound_exceded] = max_bound\n\n #If there aren't enough good timepoints, then set the bad timepoints = 0\n else:\n\n signal_copy[false_inds.astype(int)] = 0\n\n\n return signal_copy\n\n\n if interp_type == 'spectral':\n\n signal_copy = spectral_interpolation(timepoint_defined, signal_copy, TR)\n\n return signal_copy",
"def interpolate_state(self, a: Vector, b: Vector, u: float, dt: float) -> Vector:\n return vectorops.interpolate(a,b,u)",
"def compute_smoothed_traj(path, V_des, alpha, dt):\n ########## Code starts here ##########\n x_old = []\n y_old = []\n for point in path:\n x_old.append(point[0])\n y_old.append(point[1])\n\n t_old = [0] * len(path)\n for i in range(1, len(path)):\n dist = ((x_old[i] - x_old[i-1])**2 + (y_old[i] - y_old[i-1])**2)**.5\n t_old[i] = t_old[i-1] + dist / V_des\n\n t_smoothed = np.arange(0, t_old[-1], dt)\n\n # Get new splines\n spl_x_old = scipy.interpolate.splrep(t_old, x_old, s=alpha)\n spl_y_old = scipy.interpolate.splrep(t_old, y_old, s=alpha)\n\n # Evaluate splines at t_smoothed times\n spl_x_new = scipy.interpolate.splev(t_smoothed, spl_x_old)\n spl_y_new = scipy.interpolate.splev(t_smoothed, spl_y_old)\n\n # Calculate first derivatives\n spl_xd_new = scipy.interpolate.splev(t_smoothed, spl_x_old, 1)\n spl_yd_new = scipy.interpolate.splev(t_smoothed, spl_y_old, 1)\n\n # Calculate second derivatives\n spl_xdd_new = scipy.interpolate.splev(t_smoothed, spl_x_old, 2)\n spl_ydd_new = scipy.interpolate.splev(t_smoothed, spl_y_old, 2)\n\n traj_smoothed = np.zeros((len(t_smoothed), 7))\n # Create trajectory\n for t in range(len(t_smoothed)):\n if(t == 0):\n THETA = 0\n else:\n THETA = np.arctan2((spl_y_new[t] - spl_y_new[t-1]),\n (spl_x_new[t] - spl_x_new[t-1]))\n if(t == 1):\n traj_smoothed[0, 2] = THETA\n traj_smoothed[t] = np.array([spl_x_new[t], spl_y_new[t], THETA, spl_xd_new[t], spl_yd_new[t], spl_xdd_new[t], spl_ydd_new[t]])\n ########## Code ends here ##########\n\n return traj_smoothed, t_smoothed\n ########## Code ends here ##########\n\n return traj_smoothed, t_smoothed",
"def lerp(self, t):\n pass",
"def interpolate(self, a, b, t):\n d1 = (t - a[0]).seconds\n d2 = (b[0] - t).seconds\n # The total time difference\n d = float(d1 + d2)\n point = []\n # Need to return a (time, lat, lon, elev) point\n point.append(t)\n # Linear interpolation of the latitude, longitude, and elevation\n point.append(float(a[1])*(d2/d) + float(b[1])*(d1/d))\n point.append(float(a[2])*(d2/d) + float(b[2])*(d1/d))\n point.append(float(a[3])*(d2/d) + float(b[3])*(d1/d))\n if self.verbose:\n sys.stderr.write('Interpolate:\\n')\n sys.stderr.write('\\t%s\\n' % repr(a))\n sys.stderr.write('\\t%s\\n' % repr(point))\n sys.stderr.write('\\t%s\\n' % repr(b))\n return point",
"def linear_interpolate_release(mvi, j):\n set_system_state(mvi, 1)\n lam1 = mvi.system.lambda_()[j]\n set_system_state(mvi, 2)\n lam2 = mvi.system.lambda_()[j]\n\n # If either of the following loops are entered, there are likely going to\n # be problems.\n if (lam1 < 0) and (lam2 < 0):\n #add_constraints(mvi, mvi._state1_releases)\n #print mvi.lambda1c[j]\n #print mvi\n #raise Exception(\"Bad release interpolation.\")\n print 'WARNING: BAD INTERPOLANT'\n return mvi.t1, mvi.q1\n\n if lam1 < 0:\n return mvi.t1, mvi.q1\n\n tr = mvi.t1 - (lam1/(lam2-lam1))*(mvi.t2-mvi.t1)\n frac = (tr-mvi.t1)/(mvi.t2-mvi.t1)\n qr = frac*(mvi.q2-mvi.q1)+mvi.q1\n\n return tr, qr",
"def lerp(self, t):\n a = self.a0 + t * self.da\n return self.c + Vector((self.r * cos(a), self.r * sin(a)))",
"def interpolateLinear( t):\n k = np.searchsorted( keytime, t, side='right') - 1\n u = (t - keytime[k]) / (keytime[k + 1] - keytime[k])\n curframe = (1.0-u)*keyframe[k] + u*keyframe[k+1]\n\n return curframe",
"def interp_zt(array, heights, goal):\n\n print('Coffee time :-)')\n nt = array.shape[0]\n out = np.empty((nt,goal.size), dtype=np.float)\n for i in range(nt):\n out[i,:] = np.interp(goal, heights[i,:], array[i,:])\n return out",
"def interpolate(self, var, time, lat, lon):\n\n # Get the nearest four points in space\n # Check to see if lat/lons are 2d or 1d\n if len(self['lat'].shape) == 2:\n closey, closex, distances = self.nearest_points(lat, lon, npt=4)\n # Distances in km\n# distances = np.array([self.haversine(\n# (self['lat'][y,x].values, self['lon'][y,x].values),\n# (lat, lon)) for y,x in \n# zip(list(closey), list(closex))])\n else:\n closen = self.nearest_points(lat, lon, npt=4)\n closey = closen\n closex = closen\n # Distances in km\n distances = np.array([self.haversine(\n (self['lat'][n].values, self['lon'][n].values),\n (lat, lon)) for n in list(closen)])\n # Check for exact match (within some tolerance)\n spaceweights = np.zeros(distances.shape)\n if (distances < 1.0).sum() > 0:\n spaceweights[distances.argmin()] = 1\n else:\n # Here, inverse distance weighting (for simplicity)\n spaceweights = 1.0 / distances\n spaceweights /= spaceweights.sum()\n # Get weights in time\n #time64 = np.datetime64(time)\n #all the valid times in the ensemble\n valids = self['validtime'].values\n timeweights = np.zeros(valids.shape)\n # Check if we are outside the valid time range\n if (time < valids[0]) or (time > valids[-1]):\n print(\"Interpolation is outside of time range in state!\")\n return None\n # Find where we are in this list\n #index after the time of the observation\n lastdex = (valids >= time).argmax()\n # If we match a particular time value, then\n # this is just an identity\n if valids[lastdex] == time:\n # Just make a one at this time\n timeweights[lastdex] = 1\n else:\n # Linear interpolation\n #often going to be 6 hours, subtracts datetime objects I think\n diff = (valids[lastdex] - valids[lastdex-1])\n #print(valids[lastdex], valids[lastdex-1], diff)\n #often going to be 21600 seconds\n totsec = diff.seconds\n #totsec = np.abs(diff / np.timedelta64(1, 's'))\n #ST\n #calculate time difference between time after and time of observation\n #the abs will make this positive definite, which is okay since\n #the difference will always be negative\n thisdiff = abs(time - valids[lastdex])\n #thissec = np.abs(thisdiff / np.timedelta64(1,'s'))\n thissec = thisdiff.seconds\n # Put in appropriate weights\n #ST switched the -1 between the two lines to match up with the positive-\n #definite thisdiff\n timeweights[lastdex-1] = float(thissec) / totsec\n timeweights[lastdex] = 1.0 - (float(thissec)/totsec)\n # Now that we have the weights, do the interpolation\n #ST an ntimes x 4 x nens array\n interp = self.variables[var].values[:,closey,closex,:]\n # Do a dot product with the time weights\n # And with the space weights\n if len(interp.shape) == 3:\n interp = (timeweights[:,None,None] * interp).sum(axis=0)\n else:\n interp = (timeweights[:,None,None,None] * interp).sum(axis=0)\n \n if len(interp.shape) == 3:\n #ST Changed 2nd : to None\n interp = (spaceweights[:,None,None] * interp).sum(axis=1)\n else:\n interp = (spaceweights[:,None] * interp).sum(axis=0)\n # Return estimate from all ensemble members\n return interp",
"def trajectory(self, state, T=1, time_steps=200):\n\n state = state.to(device)\n t = torch.linspace(0, T, time_steps).to(device)\n\n # integrate and remove batch dim\n traj = self.model_of_dyn_system.trajectory(state, t)\n return traj.detach().cpu()[:, 0, :]",
"def _lerp(self, lo: float, hi: float, t: float):\r\n return lo + t * (hi - lo)",
"def interp_n2(t, x, y):\n\n return y[:, 0] + (t - x[0]) * (y[:, 1] - y[:, 0]) / (x[1] - x[0])",
"def _eval_td_t(self, t):\n\n # Shortcuts for more compact notation:\n\n St = self._trajectory[t].observation # evaluated state tuple (x, y)\n At = self._trajectory[t].action\n St_1 = self._trajectory[t+1].observation # next state tuple (x, y)\n Rt_1 = self._trajectory[t+1].reward # next step reward\n done = self._trajectory[t+1].done\n\n #\n # SARSA\n #\n if done:\n Tt = Rt_1\n else:\n At_1 = self._trajectory[t+1].action\n if At_1 is None:\n At_1 = self.policy.pick_action(St_1)\n Tt = Rt_1 + self._discount * self.Q.estimate(St_1, At_1) \n\n self.Q.train(St, At, Tt)",
"def interpolateCubic( t):\n curframe = []\n frame = np.searchsorted( keytime, t, side='right') - 1\n\n for i in range(11):\n poly = S[i]\n res = poly[frame](t)\n curframe.append(res)\n\n return curframe",
"def lerp(a, b, t):\n return (1 - t) * a + t * b",
"def state_eq(t, x, u, tu):\n # u = u[0, :]\n u_interp = np.interp(t, tu, u[0, :])\n # print(f'u: {u}')\n return np.vstack((x[1], -x[1] + u_interp))",
"def _build_interpolator(self):\n # Extract the data from the interpolation dataset\n self.interp_data, names, units = xr_dataset_to_array(self.interp_ds, \n self.ztsp[0])\n \n # Record the variables and their units\n self.f_names = names[1:]\n self.f_units = units[1:]\n \n # Create the interpolator\n self.f = interp1d(self.interp_data[:,0], \n self.interp_data[:,1:].transpose())",
"def smooth_loads(self):\r\n self.fqn = interp1d(Turbine.t, self.qn, kind='cubic')"
] | [
"0.645355",
"0.61542463",
"0.6043273",
"0.60258955",
"0.59383374",
"0.5892053",
"0.58805996",
"0.58428943",
"0.57802105",
"0.5755275",
"0.5744183",
"0.5701931",
"0.5685706",
"0.5674853",
"0.56703764",
"0.5618757",
"0.5603903",
"0.55692244",
"0.5563093",
"0.5556694",
"0.5552167",
"0.5524444",
"0.5471867",
"0.5465565",
"0.54504526",
"0.5446317",
"0.5443961",
"0.54294133",
"0.5409017",
"0.54026854"
] | 0.6698821 | 0 |
! Returns true when the solver solved the previous problem, false otherwise. This is an abstract method. Result of whether the solver succeeded or not. | def did_solve(self) -> bool:
pass | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def did_solve(self) -> bool:\n return self._solution.info.status == \"solved\"",
"def did_solve(self):\n return self._solution.success",
"def did_solve(self) -> bool:\n return self._stats[\"success\"]",
"def is_solvable(self):\n self_copy = deepcopy(self)\n return self_copy.solve()",
"def is_solved(self):\n self.solved = self.current_pos == self.finish_pos\n return self.solved",
"def did_solve(self):\n return self._solution[\"status\"] == \"optimal\"",
"def has_solution(self) -> bool:\n pass",
"def is_solved(self):\n raise NotImplementedError()",
"def solveOneStep(self):\n ### Student code goes here\n return True",
"def solve(self):\n if not self.solvable:\n print('Suduko not Solvable')\n return False\n res=self.back(0, 0)\n # if self.a[0][0]!=0:\n # res=self.back(0, 1)\n # else:\n # for i in range(1, 10):\n # self.a[0][0]=i\n # res=self.back(0, 1)\n # if res:\n # break\n if res:\n self.check_if_solvable()\n print(\"Sudoku Solved!\")\n print(self.a)\n return self.a\n else: print(\"Not Solvable\")\n return False",
"def is_solved(self):\n if not self._find_empty():\n return True\n else:\n return False",
"def solved(self):\r\n return self.puzzle.solved",
"def isSolved(self):\n return self.isComplete() and self.isLegal()",
"def converged(self) -> bool:",
"def converged(self) -> bool:",
"def converged(self) -> bool:",
"def solve(self):\n if self.is_solved():\n return True\n else:\n empty_box_coordinates = self._find_empty()\n row, column = empty_box_coordinates\n for i in range(1, 10):\n if self.is_valid_number(i, empty_box_coordinates):\n self.model[row][column] = i\n\n if self.solve():\n return True\n\n self.model[row][column] = 0\n return False",
"def has_solution(self) -> bool:\n if self in [self.SATISFIED, self.ALL_SOLUTIONS, self.OPTIMAL_SOLUTION]:\n return True\n return False",
"def is_solved(self):\n return self._start == self._target",
"def checkSolution(self):\n movesToEndblock = self.gridSize - self.changeable[0] - 2\n if self.checkMove(0,movesToEndblock) == 0:\n return 0\n return 1",
"def isSolved(self):\n return self.__isSolved",
"def is_solved(self):\n return (self.from_grid == self.to_grid)",
"def is_solved(self):\n return self.to_grid == self.from_grid",
"def test_is_solved_when_puzzle_is_solved(self):\n self.assertTrue(self.sudoku.is_solved())",
"def is_solved(self):\n return self.from_grid == self.to_grid",
"def is_solved(self):\n return self.from_grid == self.to_grid",
"def is_solved(self):\n return self.from_grid == self.to_grid",
"def correct(self):\n return self._solution == self._alternatives.value",
"def test_is_solved(self):\n p = hw.TilePuzzle([[1, 2], [3, 0]])\n self.assertTrue(p.is_solved())\n p = hw.TilePuzzle([[0, 1], [3, 2]])\n self.assertFalse(p.is_solved())",
"def solve(self):\n if not self.running or self.state == \"stopping\":\n return False\n\n # Find first empty tile\n target = ()\n for i in range(9**2):\n if self.board[i // 9, i % 9] == 0:\n target = (i // 9, i % 9)\n break\n\n # If there are no empty tiles, the puzzle is solved\n if not target:\n return True\n\n # Tests all possible values\n for value in range(1, 10):\n if not self.isPossibleAssign(target, value):\n continue\n\n self.update_board(target, value)\n\n if self.solve():\n return True\n\n # In case of failure, reset and return False\n self.update_board(target, 0)\n\n return False"
] | [
"0.77462107",
"0.77255",
"0.7467203",
"0.7388036",
"0.7289115",
"0.7209088",
"0.7142447",
"0.71113646",
"0.6873382",
"0.6865059",
"0.68046784",
"0.67686045",
"0.6765212",
"0.6664564",
"0.6664564",
"0.6664564",
"0.665332",
"0.6645049",
"0.65861714",
"0.6569115",
"0.6560621",
"0.65501386",
"0.652443",
"0.65218675",
"0.6466252",
"0.6466252",
"0.6466252",
"0.6395054",
"0.63882446",
"0.6357714"
] | 0.7794785 | 0 |
! Evaluates the cost function for given decision variables x and parameters p. x The values for the decision variables. p The values for the parameters. The cost that results from x and p. | def evaluate_cost(
self, x: Dict[str, ArrayType], p: Dict[str, ArrayType]
) -> CasADiArrayType:
x = self.opt.decision_variables.dict2vec(x)
p = self.opt.parameters.dict2vec(p)
return self.opt.f(x, p) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def eval_cost(self, params, **kwargs):\n raise NotImplementedError",
"def evaluate_cost_terms(\n self, x: Dict[str, ArrayType], p: Dict[str, ArrayType]\n ) -> List:\n\n x = self.opt.decision_variables.dict2vec(x)\n p = self.opt.parameters.dict2vec(p)\n\n @dataclass\n class CostTerm:\n label: str\n cost: float\n\n def __str__(self):\n return f\"\\n{self.label}: {self.cost}\"\n\n def __repr__(self):\n info = str(self)\n max_width = max(len(line) for line in info.split(\"\\n\"))\n return \"=\" * max_width + info + \"-\" * max_width + \"\\n\"\n\n cost_terms = []\n for label, sx_var in self.opt.cost_terms.items():\n fun = cs.Function(\"fun\", [self.opt.x, self.opt.p], [sx_var])\n c = fun(x, p)\n cost_terms.append(c)\n\n return cost_terms",
"def costFun(self, S, x):",
"def compute_cost(AL, Y):\n pass",
"def clfqp(self,x,p):\n alp = self.alp_opt\n nu = self.nu_opt\n dt = self.dt\n n = self.n\n I = np.identity(n)\n M = self.ncm(x,p)\n nu = np.size(self.h_or_g(x,p),1)\n u = cp.Variable((nu,1))\n e = np.reshape(x,(n,1))\n fx = np.reshape(self.dynamicsf(x,p),(n,1))\n gx = self.h_or_g(x,p)\n dMdt = (nu*I-M)/dt\n constraints = [2*e.T@(fx+gx@u)+e.T@dMdt@e <= -2*alp*e.T@M@e]\n prob = cp.Problem(cp.Minimize(cp.sum_squares(u)),constraints)\n prob.solve()\n u = u.value\n u = np.ravel(u)\n return u",
"def EvaluateFunction(self, p_float=..., p_float=..., p_float=...):\n ...",
"def cost_function(H, n_qubits, p, params):\n ini_state=plus_state(n_qubits)\n for i in range(p):\n ini_state=qaoa_step(ini_state,H,n_qubits,params=[params[2*i],params[2*i+1]])\n return ((sparse.spmatrix.getH(ini_state)).dot(H.dot(ini_state))).real, ini_state",
"def compute(self, F, variables):\n s_0 = self.initial_state_generator(self.num_samples)\n a_0 = self.policy(s_0)\n a_t_plus_1 = a_0\n x_t = F.expand_dims(F.concat(s_0, a_0, dim=1), axis=1)\n cost = 0\n for t in range(self.n_time_steps):\n variables[self.model.X] = x_t\n res = self.model.Y.factor.predict(F, variables, targets=[self.model.Y], num_samples=self.num_samples)[0]\n s_t_plus_1 = res[0]\n\n cost = cost + self.cost_function(s_t_plus_1, a_t_plus_1)\n\n a_t_plus_1 = mx.nd.expand_dims(self.policy(s_t_plus_1), axis=2)\n x_t = mx.nd.concat(s_t_plus_1, a_t_plus_1, dim=2)\n total_cost = F.sum(cost)\n return total_cost, total_cost",
"def costFun(self, x):\n\ttmp = x.reshape(self.inp_shape)\n\tc = np.float64(self.calcCost(np.asarray(tmp,dtype=np.float32))) + self.alpha * np.dot(x.T, x)\n\treturn c",
"def cost(self,x):\n Mx = self.generate_vector()\n self.prior.M.mult(x,Mx)\n return .5*Mx.inner(x)",
"def compute_cost(features, values, theta):\r\n \r\n # your code here\r\n error = (values - features.dot(theta))\r\n cost = error.dot(error) \r\n return cost",
"def compute_cost(AL,Y,cost_function_name):\n cost_functions = {\n \"cost_func_1\": cf.cost_function_1\n } \n\n activ_func = cost_functions.get(cost_function_name,lambda : \"Invalid Cost Function Name !\")\n\n cost,dAL = activ_func(AL,Y)\n\n return cost, dAL",
"def TargetFunction(p,x,y):\n \n return p[0] + p[1]*x + p[2]*(x**2) + p[3]*y + p[4]*(y**2) + p[5]*x*y",
"def evaluate(self,p):\n if not self.initialized: self.__initialize__()\n if self.vp0: p_ = 1-p\n else: p_ = p\n if self.ids_to_consider is None:\n #sum on all parametrized cell\n cf = np.sum(self.V[self.p_ids-1]*p_)/self.V_tot - self.max_v_frac\n else:\n cf = np.sum((self.V[self.ids_to_consider-1]*p_))/self.V_tot - self.max_v_frac\n return cf",
"def compute_cost(AL, Y):\n pass",
"def cost_function(data_x, data_y, parameters):\n # Residual sum of squares\n rss = np.sum((data_x @ parameters - data_y) ** 2)\n\n # Number of rows times 2\n nb_rows_x2 = 2 * data_x.shape[0]\n\n return rss / nb_rows_x2",
"def decision_function(self, X):\n ...",
"def evaluate(self, X: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n\n output = self.fct(X, *self.args)\n\n Y = output[0].reshape(X.shape[0], self.ydim)\n C = (\n output[1].reshape(X.shape[0], self.cdim)\n if self.cdim > 0\n else np.zeros((X.shape[0], self.cdim))\n )\n\n # Build penalty function\n Py = Optimizer.boundaryCheck(Y, self.ylb, self.yub)\n Px = Optimizer.boundaryCheck(X, self.xlb, self.xub)\n Pc = Optimizer.boundaryCheck(C, self.clb, self.cub)\n\n # Assemble all penalties\n P = Py + Px + Pc\n\n # callback:\n if self.callback is not None:\n self.callback(X, Y, C, self.currentIteration)\n\n # Return to optimizer\n return Y, C, P",
"def costFunction(self, x, y ):\n self.yEst = self.forward_propagate(x)\n sqErrors = ( self.yEst - y ) ** 2\n J = sqErrors.sum() / 2\n return J",
"def calculate_cost(x, y, weights):\r\n predictions = compute_prediction(x, weights)\r\n cost = np.mean(-y * np.log(predictions) - (1 - y) * np.log(1 - predictions))\r\n return cost",
"def cost_function(param, Y, R, n_features):\r\n # theta (user, feature), (943, 10): user preference\r\n # X (movie, feature), (1682, 10): movie features\r\n n_movie, n_user = Y.shape\r\n X, theta = deserialize(param, n_movie, n_user, n_features)\r\n\r\n inner = np.multiply(X @ theta.T - Y, R)\r\n\r\n return np.power(inner, 2).sum() / 2",
"def deriv_costFunction(self, x, y):\n self.yEst = self.forward_propagate(x)\n\n delta_o = np.multiply( ( self.yEst - y ), self.deriv_sigmoid(self.z_o) )\n #partial deriv of cost wrt hidden -> output weights\n partial_J_w_ho = np.dot( self.a_h.T, delta_o )\n\n ones_o = np.ones( delta_o.shape[0] )\n #partial deriv of cost wrt output biases\n partial_J_b_o = np.dot( ones_o, delta_o )\n\n delta_h = np.dot( delta_o, self.w_ho.T ) * self.deriv_sigmoid( self.z_h )\n #partial deriv of cost wrt input -> hidden weights\n partial_J_w_ih = np.dot( x.T, delta_h )\n \n ones_h = np.ones( delta_h.shape[0] )\n #partial deriv of cost wrt hidden biases\n partial_J_b_h = np.dot( ones_h, delta_h)\n\n return partial_J_w_ih, partial_J_w_ho, partial_J_b_h, partial_J_b_o",
"def compute_cost(self,X, y):\n \n num_samples = len(X)\n # Do Forward propagation to calculate our predictions\n z1 = X.dot(self.W1) + self.b1\n a1 = np.tanh(z1)\n z2 = a1.dot(self.W2) + self.b2\n exp_z = np.exp(z2)\n a2 = exp_z / np.sum(exp_z, axis=1, keepdims=True)\n softmax_scores = a2\n # Calculate the cross-entropy loss\n cross_ent_err = -np.log(softmax_scores[range(num_samples), y])\n data_loss = np.sum(cross_ent_err)\n return 1./num_samples * data_loss",
"def _local_cost(self, p, q):\n diagnol = q[0] == p[0] or q[1] == p[1]\n \n # c0, c1 and c2 are costs from Canny operator, gradient magnitude and gradient direction respectively\n if diagnol:\n c0 = self.cost_edges[p[0]][p[1]]-SQRT_0_5*(self.cost_edges[p[0]][p[1]]-self.cost_edges[q[0]][q[1]])\n c1 = self.cost_grad_mag[p[0]][p[1]]-SQRT_0_5*(self.cost_grad_mag[p[0]][p[1]]-self.cost_grad_mag[q[0]][q[1]])\n c2 = SQRT_0_5 * self._get_grad_direction_cost(p, q)\n else:\n c0 = self.cost_edges[q[0]][q[1]]\n c1 = self.cost_grad_mag[q[0]][q[1]]\n c2 = self._get_grad_direction_cost(p, q)\n \n if np.isnan(c2):\n c2 = 0.0\n \n w0, w1, w2 = self.weight\n cost_pq = w0*c0 + w1*c1 + w2*c2\n \n return cost_pq * cost_pq",
"def evaluate_cost(self, msg):\n raise NotImplementedError()",
"def _cost_method(self, *args, **kwargs):\n\n cost_val = 0.5 * np.linalg.norm(self.obs_data - self.op(args[0])) ** 2\n\n if 'verbose' in kwargs and kwargs['verbose']:\n print(' - DATA FIDELITY (X):', cost_val)\n\n return cost_val",
"def objective_function(self, y_true, y_predicted, X=None):",
"def cofiCostFunc(self,params, *args):\n\t\tY, R, num_users, num_products, num_features,l = args[0], args[1],args[2], args[3],args[4],args[5]\n\n\t\taux = params.reshape((num_products + num_users, num_features))\n\n\t\tX = aux[0:num_products , :]\n\n\t\tTheta = aux[num_products:, :] \n\n\t\ttest = np.dot(X,Theta.transpose())\n\t\ttest = test - Y\n\t\ttest = np.multiply(test , R)\n\t\ttest = np.power(test,2)\n\t\ttest = test.sum()\n\t\ttest = 0.5 * test\n\n\t\tJ = 0;\n\t\tregularization = (l * 0.5) * np.power(X,2).sum() + np.power(Theta,2).sum()\n\n\t\tJ = test# + regularization\n\n\t\treturn J",
"def fit(x, a, p, b):\n return a * (p ** x) + b",
"def calculate_cost(theta_values, data):\n population = data[:,0]\n prices = data[:,1]\n total_error = 0\n for i in range(0,len(population)):\n x = array([[1],[population[i]]])\n hypothesis = theta_values.dot(x).flatten() \n squared_error = (hypothesis - prices[i])**2\n total_error += squared_error\n return .5*total_error/len(population) #division by m is just a scaling factor since we're only interested in whether this function is minimized"
] | [
"0.6875914",
"0.6735483",
"0.6607919",
"0.65051496",
"0.64269185",
"0.6375905",
"0.63624954",
"0.63512516",
"0.63113904",
"0.62978935",
"0.6296104",
"0.6264986",
"0.62552166",
"0.6251208",
"0.6240915",
"0.6239294",
"0.6222501",
"0.6177374",
"0.6175696",
"0.6130165",
"0.6096394",
"0.60911036",
"0.60901415",
"0.60878295",
"0.6071236",
"0.6058951",
"0.60352993",
"0.6029381",
"0.60200274",
"0.60160977"
] | 0.741476 | 0 |
! Evaluates each cost term for given decision variables and parameters. x The values for the decision variables. p The values for the parameters. List corresponding to each cost term evalauted at x, p. | def evaluate_cost_terms(
self, x: Dict[str, ArrayType], p: Dict[str, ArrayType]
) -> List:
x = self.opt.decision_variables.dict2vec(x)
p = self.opt.parameters.dict2vec(p)
@dataclass
class CostTerm:
label: str
cost: float
def __str__(self):
return f"\n{self.label}: {self.cost}"
def __repr__(self):
info = str(self)
max_width = max(len(line) for line in info.split("\n"))
return "=" * max_width + info + "-" * max_width + "\n"
cost_terms = []
for label, sx_var in self.opt.cost_terms.items():
fun = cs.Function("fun", [self.opt.x, self.opt.p], [sx_var])
c = fun(x, p)
cost_terms.append(c)
return cost_terms | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def evaluate_cost(\n self, x: Dict[str, ArrayType], p: Dict[str, ArrayType]\n ) -> CasADiArrayType:\n x = self.opt.decision_variables.dict2vec(x)\n p = self.opt.parameters.dict2vec(p)\n return self.opt.f(x, p)",
"def eval_cost(self, params, **kwargs):\n raise NotImplementedError",
"def evaluate(self,**d):\r\n\t\t\r\n\t\t# evaluate terms\r\n\t\tv = [i.evaluate(**d) for i in self]\r\n\t\t\r\n\t\t# sum results\r\n\t\tc = Pa(v).sum()\r\n\t\t\r\n\t\treturn c",
"def eval(self, *x):\n\n y = np.array(list(map(lambda _: self.func(_, *self.popt), x)))\n sigma = np.array(list(map(lambda _: self._sigma(_), x)))\n\n return y, sigma",
"def cost_function(H, n_qubits, p, params):\n ini_state=plus_state(n_qubits)\n for i in range(p):\n ini_state=qaoa_step(ini_state,H,n_qubits,params=[params[2*i],params[2*i+1]])\n return ((sparse.spmatrix.getH(ini_state)).dot(H.dot(ini_state))).real, ini_state",
"def evaluate(self,p):\n if not self.initialized: self.__initialize__()\n if self.vp0: p_ = 1-p\n else: p_ = p\n if self.ids_to_consider is None:\n #sum on all parametrized cell\n cf = np.sum(self.V[self.p_ids-1]*p_)/self.V_tot - self.max_v_frac\n else:\n cf = np.sum((self.V[self.ids_to_consider-1]*p_))/self.V_tot - self.max_v_frac\n return cf",
"def compute(self, F, variables):\n s_0 = self.initial_state_generator(self.num_samples)\n a_0 = self.policy(s_0)\n a_t_plus_1 = a_0\n x_t = F.expand_dims(F.concat(s_0, a_0, dim=1), axis=1)\n cost = 0\n for t in range(self.n_time_steps):\n variables[self.model.X] = x_t\n res = self.model.Y.factor.predict(F, variables, targets=[self.model.Y], num_samples=self.num_samples)[0]\n s_t_plus_1 = res[0]\n\n cost = cost + self.cost_function(s_t_plus_1, a_t_plus_1)\n\n a_t_plus_1 = mx.nd.expand_dims(self.policy(s_t_plus_1), axis=2)\n x_t = mx.nd.concat(s_t_plus_1, a_t_plus_1, dim=2)\n total_cost = F.sum(cost)\n return total_cost, total_cost",
"def clfqp(self,x,p):\n alp = self.alp_opt\n nu = self.nu_opt\n dt = self.dt\n n = self.n\n I = np.identity(n)\n M = self.ncm(x,p)\n nu = np.size(self.h_or_g(x,p),1)\n u = cp.Variable((nu,1))\n e = np.reshape(x,(n,1))\n fx = np.reshape(self.dynamicsf(x,p),(n,1))\n gx = self.h_or_g(x,p)\n dMdt = (nu*I-M)/dt\n constraints = [2*e.T@(fx+gx@u)+e.T@dMdt@e <= -2*alp*e.T@M@e]\n prob = cp.Problem(cp.Minimize(cp.sum_squares(u)),constraints)\n prob.solve()\n u = u.value\n u = np.ravel(u)\n return u",
"def compute_cost(features, values, theta):\r\n \r\n # your code here\r\n error = (values - features.dot(theta))\r\n cost = error.dot(error) \r\n return cost",
"def costFun(self, S, x):",
"def eval(self, x):\n y = list(x)\n if not self.biased:\n y.insert(0, 1.0)\n y = np.array(y).reshape((self.Ws[0].shape[1], 1))\n for W, g in zip(self.Ws, self.gs):\n y = g(np.dot(W, y))\n return y.flatten()",
"def evaluate( self, x ) :\n\n P = 0.\n for c_l in reversed( self.coefficients ) : P = c_l + x * P\n return( P )",
"def evaluate(clf, dataset, feature_list, features, labels, num_iter, params):\n\n features_train, features_test, labels_train, labels_test = \\\n train_test_split(features, labels, test_size=0.3, random_state=42)\n\n\n\n precision_values = []\n recall_values = []\n accuracy_values = []\n print clf\n for i in xrange(0, num_iter):\n #print params\n clf = GridSearchCV(clf, params)\n clf.fit(features_train, labels_train)\n print '*****************************'\n print clf.best_estimator_\n print clf.best_params_\n\n clf = clf.best_estimator_\n #test_classifier(clf, dataset, feature_list)\n pred = clf.predict(features_test)\n precision_values.append(precision_score(labels_test, pred))\n recall_values.append(recall_score(labels_test, pred))\n accuracy_values.append(accuracy_score(labels_test, pred))\n print 'Recall score: ', mean(recall_values)\n print 'Precision score: ', mean(precision_values)\n print 'Accuracy score: ' , mean(accuracy_values)",
"def compute_cost(AL, Y):\n pass",
"def cofiCostFunc(self,params, *args):\n\t\tY, R, num_users, num_products, num_features,l = args[0], args[1],args[2], args[3],args[4],args[5]\n\n\t\taux = params.reshape((num_products + num_users, num_features))\n\n\t\tX = aux[0:num_products , :]\n\n\t\tTheta = aux[num_products:, :] \n\n\t\ttest = np.dot(X,Theta.transpose())\n\t\ttest = test - Y\n\t\ttest = np.multiply(test , R)\n\t\ttest = np.power(test,2)\n\t\ttest = test.sum()\n\t\ttest = 0.5 * test\n\n\t\tJ = 0;\n\t\tregularization = (l * 0.5) * np.power(X,2).sum() + np.power(Theta,2).sum()\n\n\t\tJ = test# + regularization\n\n\t\treturn J",
"def evaluate(self,coeffs,evalpts):\n a1,a2,a3,A0,E0,G0,n = coeffs\n x = asarray(evalpts) #XXX: requires a numpy.array\n return (a1 + a2*x + a3*x*x + A0 * ( G0/(2*pi) )/( (x-E0)*(x-E0)+(G0/2)*(G0/2) ))/n",
"def probability(cpts, term, obs):\r\n \r\n \r\n # term is a list e.g., ['x_1', '0']\r\n # flip refers to the assignment either '0' false or '1' true\r\n flip = term[1]\r\n # the term itself\r\n term = term[0]\r\n # accumulator variable\r\n answer = 0\r\n # this loop locates where in the CPT we're looking\r\n for clause in range(len(cpts)):\r\n if cpts[clause][0] == term:\r\n index = clause\r\n # focus on our term\r\n cpt = cpts[index]\r\n # this loop checks if there are no preconditions\r\n # if not, then we immediately know the probability and can return\r\n for m in range(len(cpt[1])):\r\n if cpt[1][m][-2][1] == '1':\r\n if cpt[1][m][0] == [[]]:\r\n answer = cpt[1][m][-1]\r\n # list of the variables we have observed\r\n have = []\r\n if obs != []:\r\n for k in obs:\r\n have.append(k[0])\r\n # list of variables we need to know in order to calculate the probability\r\n needed = []\r\n for prob in range(len(cpt[1])):\r\n for j in cpt[1][prob][0]:\r\n if j != []:\r\n if j[0] not in needed:\r\n needed.append(j[0])\r\n # conditional logic based on the known variables\r\n for required in needed:\r\n if required not in have:\r\n # deep copy our observations list\r\n obs2 = []\r\n obs3 = []\r\n for observs in obs:\r\n obs2.append(observs)\r\n obs3.append(observs)\r\n # if we need to know a variable but don't have it\r\n # then we allow it to be either 0 or 1\r\n obs3.append([required,'1'])\r\n obs2.append([required,'0'])\r\n # computes probability if the unknown term is true, times \r\n # the probability that the unknown term is true, plus the\r\n # probability if the unknown term is false, times the \r\n # probability that the unknown term is false\r\n answer = (probability(cpts, [term,flip], obs3) * probability(cpts, [required,'1'], obs)) + (probability(cpts, [term,flip], obs2) * (probability(cpts, [required,'0'], obs)))\r\n # this loop looks complicated but all it's doing is finding the correct\r\n # line in the CPT\r\n if cpt[1][prob][-2][1] == '1':\r\n count = 1\r\n for i in range(len(cpt[1][prob][0])):\r\n if cpt[1][prob][0][i] in obs:\r\n count *= 1\r\n else:\r\n count = 0\r\n if count == 1:\r\n answer += cpt[1][prob][-1]\r\n\r\n\r\n # this computes the probability that the term is true, so if we asked \r\n # for the probability that it is false, just return 1 - answer\r\n if flip == '0':\r\n return 1 - answer\r\n return answer",
"def compute(self, *args, **kwargs):\n for node in self.evaluation_sequence:\n node.evaluate()",
"def evaltr(x_solution): \n \n large = 10.0**30\n pred = np.zeros(cfg.ntrain)\n e0 = 0.0 # mean of observed values\n y=0.0\n for i in range(cfg.ntrain): # Computation of correct piece\n e0 += cfg.a_unscaled[i][-1]\n pind = 0\n ipbest = 0\n pbest = -large # for max\n \n for j1 in range(cfg.nomax):\n ipmin=pind\n pmin=large # for min\n for _ in range(cfg.jk[j1]):\n piece=x_solution[(pind+1)*cfg.nfea-1] \n for j3 in range(cfg.nfea-1): #\n piece += x_solution[pind*cfg.nfea+j3]*cfg.a_unscaled[i][j3]\n if piece < pmin:\n ipmin = pind\n pmin = piece\n pind += 1 \n \n if pmin > pbest:\n ipbest = ipmin\n pbest = pmin\n \n pred[i] = x_solution[(ipbest+1)*cfg.nfea-1] # Computation of prediction\n for j1 in range(cfg.nfea-1):\n pred[i] += x_solution[ipbest*cfg.nfea+j1]*cfg.a_unscaled[i][j1]\n y += pred[i]\n \n y = y/cfg.ntrain \n e0 = e0/cfg.ntrain\n \n # Computation of indices\n rmse = 0.0\n mae = 0.0\n e1 = 0.0\n for i in range(cfg.ntrain):\n rmse += (pred[i]-cfg.a_unscaled[i][-1])**2\n mae += np.abs(pred[i]-cfg.a_unscaled[i][-1]) \n e1 += (cfg.a_unscaled[i][-1] - e0)**2\n ce = 1.0 - rmse/e1 \n rmse = np.sqrt(rmse/cfg.ntrain)\n mae = mae/cfg.ntrain \n\n if cfg.ntrain > 1:\n sx=0.0\n sy=0.0\n rcor=0.0\n for i in range(cfg.ntrain):\n sx += (pred[i]-y)**2\n sy += (cfg.a_unscaled[i][-1]-e0)**2 \n rcor += (pred[i]-y) * (cfg.a_unscaled[i][-1]-e0) \n\n r = rcor/np.sqrt(sx*sy)\n \n return rmse,mae,ce,r",
"def _construct_reg_costs(self):\n param_reg_cost = sum([T.sum(p**2.0) for p in self.joint_params])\n return param_reg_cost",
"def eval(params: ObjectiveParams, x: jnp.ndarray) -> jnp.ndarray:\n pass",
"def _eval_coeff(self, pt):\n return sum(a.coeff(pt) for a in self.args)",
"def evaluate(self, X: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n\n output = self.fct(X, *self.args)\n\n Y = output[0].reshape(X.shape[0], self.ydim)\n C = (\n output[1].reshape(X.shape[0], self.cdim)\n if self.cdim > 0\n else np.zeros((X.shape[0], self.cdim))\n )\n\n # Build penalty function\n Py = Optimizer.boundaryCheck(Y, self.ylb, self.yub)\n Px = Optimizer.boundaryCheck(X, self.xlb, self.xub)\n Pc = Optimizer.boundaryCheck(C, self.clb, self.cub)\n\n # Assemble all penalties\n P = Py + Px + Pc\n\n # callback:\n if self.callback is not None:\n self.callback(X, Y, C, self.currentIteration)\n\n # Return to optimizer\n return Y, C, P",
"def compute_cost_matrix(self):\n\n if rank == 0:\n #do random sampling of a parameters\n if self.sampling == \"LHS\":\n lhs = Lhs(lhs_type=\"classic\", criterion=None)\n param_samples = lhs.generate(self.sample_space, self.niters)\n elif self.sampling == \"rsampling\":\n param_samples = self.sample_space.rvs(self.niters)\n elif self.sampling == \"Sobol\":\n sobol = Sobol()\n param_samples = sobol.generate(self.sample_space.dimensions, self.niters)\n \n # generate param samples split\n niters_rank0 = self.niters//size + self.niters % size\n niters_rank = self.niters//size\n count_scatter = [niters_rank0]\n count_scatter.extend((size-2)*[niters_rank])\n count_scatter = np.cumsum(count_scatter)\n\n param_samples_split = np.split(param_samples,count_scatter)\n else:\n param_samples_split = None\n \n #scatter parameter samples data\n param_samps = comm.scatter(param_samples_split,root=0)\n\n # initialize data\n param_samples_dict_rank = {qoi_name:[] for qoi_name in self.funcnames}\n param_samples_diff_dict_rank = {qoi_name:[] for qoi_name in self.funcnames}\n jac_dict_rank = {qoi_name:[] for qoi_name in self.funcnames}\n qoi_dict_rank = {qoi_name:[] for qoi_name in self.funcnames}\n\n \n\n # evaluate QoI at random sampling\n for sample in param_samps: \n qoi_sample, jac_sample = self.jac(sample).values()\n # store output\n for qoi_name in self.funcnames:\n if not (jac_sample[qoi_name] is None):\n param_samples_dict_rank[qoi_name].append(jac_sample[qoi_name])\n jac_dict_rank[qoi_name].append(jac_sample[qoi_name])\n qoi_dict_rank[qoi_name].append(qoi_sample[qoi_name])\n else:\n param_samples_diff_dict_rank[qoi_name].append(sample)\n\n # gather data\n param_samples = None\n param_samples_diff_int = None\n jac_dict = None\n qoi_dict= None\n\n param_samples_dict = comm.gather(param_samples_dict_rank, root=0)\n params_samples_diff_dict = comm.gather(param_samples_diff_dict_rank, root=0)\n jac_dict = comm.gather(jac_dict_rank, root=0)\n qoi_dict = comm.gather(qoi_dict_rank, root=0)\n\n # format gathered data\n if rank == 0:\n #flatten data\n param_samples_dict_flattened = {qoi_name:[] for qoi_name in self.funcnames}\n param_samples_diff_dict_flattened = {qoi_name: [] for qoi_name in self.funcnames}\n jac_dict_flattened = {qoi_name: [] for qoi_name in self.funcnames}\n qoi_dict_flattened = {qoi_name: [] for qoi_name in self.funcnames}\n\n for cpurank in range(size):\n for qoi_name in self.funcnames:\n param_samples_dict_flattened[qoi_name].extend(param_samples_dict[cpurank][qoi_name]) \n param_samples_diff_dict_flattened[qoi_name].extend(params_samples_diff_dict[cpurank][qoi_name])\n jac_dict_flattened[qoi_name].extend(jac_dict[cpurank][qoi_name])\n qoi_dict_flattened[qoi_name].extend(qoi_dict[cpurank][qoi_name])\n\n #compute outer product\n jac_outer_dict = {qoi_name: [] for qoi_name in self.funcnames}\n nfuncs_dict = {qoi_name: 0 for qoi_name in self.funcnames}\n\n for qoi_name in self.funcnames:\n for i in range(len(jac_dict_flattened[qoi_name])):\n jac_sample = jac_dict_flattened[qoi_name][i]\n jac_outer_dict[qoi_name].append(np.outer(jac_sample,jac_sample))\n nfuncs_dict[qoi_name] += 1\n\n # compute cost matrix and norm convergence\n cost_matrix_dict = {}\n cost_matrix_cumul_dict = {}\n norm_convergence_dict = {}\n\n for qoi_name in self.funcnames:\n cost_cumsum = np.cumsum(jac_outer_dict[qoi_name],axis=0)/np.arange(1,nfuncs_dict[qoi_name]+1)[:,None,None]\n cost_matrix_cumul_dict[qoi_name] = cost_cumsum\n cost_matrix_dict[qoi_name] = cost_cumsum[-1,:,:]\n norm_convergence_dict[qoi_name] = np.linalg.norm(cost_cumsum,ord='fro',axis=(1,2))\n\n # compute variance matrix\n variance_matrix_dict = {}\n for qoi_name in self.funcnames:\n variance_mat = np.sum((jac_outer_dict[qoi_name]-cost_matrix_dict[qoi_name])**2/(nfuncs_dict[qoi_name]-1),axis=0) \n variance_matrix_dict[qoi_name] = variance_mat\n\n param_results = {\"PARAM_SAMPLES\": param_samples_dict_flattened,\n \"DIFFICULT_PARAM_SAMPLES\": param_samples_diff_dict_flattened}\n\n fun_results = {\"NUMBER_OF_FUNCTION_SUCCESS\": nfuncs_dict,\n \"NORM_OF_SEQ_OF_CUMUL_SUMS\": norm_convergence_dict,\n \"SEQ_OF_CUMUL_SUMS\": cost_matrix_cumul_dict, \n \"VARIANCE_OF_ENTRIES\": variance_matrix_dict,\n \"FINAL_COST_MATRIX\":cost_matrix_dict}\n\n return {'PARAMETER_RESULTS': param_results, 'FUNCTION_RESULTS': fun_results}",
"def evaluate_price(params, predictor=False):\n # def evaluate_price(alpha,theta,mu,sigma,lambda_,b,m,a,A0,predictor=False):\n alpha = params[0]\n\n theta = params[1]\n\n mu = params[2]\n\n sigma = params[3]\n\n lambda_ = params[4]\n\n b = params[5]\n m = params[6]\n a = params[7]\n A0 = params[8]\n\n call_data = data[data['is_call'] == 1]\n r = 0\n target_list = (call_data['Ask_price'].values +\n call_data['Bid_price'].values) / 2\n\n def eval_row(row): return call_price(\n row['S0'], row['K'], r, row['T'] / 360, alpha, theta, mu, sigma, lambda_, b, m, a, row['T'] / 360, A0=A0)\n pred_list = call_data.apply(eval_row, axis=1).values\n\n rmse = np.sqrt(np.mean((target_list - pred_list)**2))\n\n print(rmse)\n # plt.plot(target_list)\n # plt.plot(pred_list)\n plt.scatter(call_data['K'].values, 0.5 * call_data['Ask_price'] +\n 0.5 * call_data['Bid_price'], label='Real Data')\n plt.scatter(call_data['K'].values, pred_list,\n label='SV Time change', marker='+')\n plt.xlabel('K')\n plt.ylabel('Option Price')\n plt.legend()\n plt.show()\n if predictor:\n return rmse, pred_list\n return rmse",
"def evaluator(self, candidates, args):\r\n fitness = []\r\n if self._use_ants:\r\n for candidate in candidates:\r\n total = 0\r\n for c in candidate:\r\n total += c.value\r\n fitness.append(total)\r\n else:\r\n for candidate in candidates:\r\n total_value = 0\r\n total_weight = 0\r\n for c, i in zip(candidate, self.items):\r\n total_weight += c * i[0]\r\n total_value += c * i[1]\r\n if total_weight > self.capacity:\r\n fitness.append(self.capacity - total_weight)\r\n else:\r\n fitness.append(total_value)\r\n return fitness",
"def _generate_evaluaters(self):\n evaluators = []\n for para_key in self.parameter[1]:\n for value in self.parameter[1][para_key]:\n evaluators.append(evaluaterSearch.evaluaterSearch(self.parameter[2], [para_key, value]))\n self.evaluators = evaluators",
"def evalfunc(c, flist, x):\n return sum([c[i] * flist[i](x) for i in range(len(flist))])",
"def _compute_parameters(self, p, k):\n for i in range(self._.d + 1):\n p[0, i, i] = k[i]\n p[i, 0, i] = Integer(1)\n p[i, i, 0] = Integer(1)\n for i in range(self._.d):\n p[i+1, 1, i+1] = self._.a[i+1]\n p[i, 1, i+1] = self._.b[i]\n p[i+1, 1, i] = self._.c[i+1]\n for i in range(2, self._.d + 1):\n for j in range(1, self._.d + 1):\n for h in range(1, self._.d):\n p[h, i, j] = self._check_parameter(\n h, i, j,\n _simplify(_expand((\n self._.c[h] * p[h-1, i-1, j]\n + self._.b[h] * p[h+1, i-1, j]\n - self._.b[i-2] * p[h, i-2, j]\n + (self._.a[h] - self._.a[i-1]) * p[h, i-1, j]\n ) / self._.c[i])))\n p[self._.d, i, j] = self._check_parameter(\n self._.d, i, j,\n _simplify(_expand((\n self._.c[self._.d] * p[self._.d-1, i-1, j]\n - self._.b[i-2] * p[self._.d, i-2, j]\n + (self._.a[self._.d] - self._.a[i-1])\n * p[self._.d, i-1, j]\n ) / self._.c[i])))",
"def train(x, prob: SvmProblem):\n\n # Define the inputs to CVXOPT - See Appendix G.1\n P = np.zeros((prob.num, prob.num))\n for i in range(prob.num):\n for j in range(prob.num):\n P[i][j] = prob.Y[i] * prob.Y[j] * prob.xkernel(x[i], x[j])\n q = -np.ones((prob.num, 1))\n G1 = -np.eye(prob.num)\n G2 = np.eye(prob.num)\n G = np.vstack((G1, G2))\n h1 = np.zeros(prob.num).reshape(-1, 1)\n h2 = np.repeat(prob.C, prob.num).reshape(-1, 1)\n h = np.vstack((h1, h2))\n a = prob.Y.reshape(1, -1)\n b = np.zeros(1)\n\n P = matrix(P, tc='d')\n q = matrix(q, tc='d')\n G = matrix(G, tc='d')\n h = matrix(h, tc='d')\n A = matrix(a, tc='d')\n b = matrix(b, tc='d')\n\n # Solve optimization problem using CVXOPT\n solvers.options['show_progress'] = False\n sol = solvers.qp(P, q, G, h, A, b)\n alphas = np.array(sol['x'])\n\n # Get the bias\n bacond1 = (alphas > 1e-8)\n bacond2 = (alphas <= prob.C)\n bcond = np.array([a and b for a, b in zip(bacond1, bacond2)]).flatten()\n yS = prob.Y[bcond]\n xS = x[bcond]\n aS = alphas[bcond]\n sum_total = 0\n for s in range(len(yS)):\n inner_total = 0\n for m in range(len(yS)):\n am = aS[m]\n ym = yS[m]\n xm_xs = prob.xkernel(xS[m], xS[s])\n inner_total += am * ym * xm_xs\n sum_total += yS[s] - inner_total\n bias = sum_total / len(yS) if len(yS) > 0 else [0]\n\n # Populate Classifier object to be returned\n clf = Classifier()\n clf.b = bias[0]\n clf.alphas = alphas\n clf.xs = x\n clf.ys = prob.Y\n clf.kern = prob.xkernel\n clf.support_vectors = x[bacond1.flatten()]\n return clf"
] | [
"0.721565",
"0.65479606",
"0.6323528",
"0.6112096",
"0.605941",
"0.60492057",
"0.59148633",
"0.59125096",
"0.5883655",
"0.58525085",
"0.5816622",
"0.5812202",
"0.576337",
"0.5744233",
"0.573798",
"0.57278824",
"0.56974936",
"0.56958956",
"0.5695721",
"0.569557",
"0.5688815",
"0.56604064",
"0.5659786",
"0.56543547",
"0.5652693",
"0.5642968",
"0.56235844",
"0.5610177",
"0.5606089",
"0.55938363"
] | 0.8016866 | 0 |
! Setup the optimization solver. solver_name The name of the solver to be used. solver_options Solver options passed to the solver. For details, see | def setup(self, solver_name: str, solver_options: Dict = {}):
# Setup problem
x = self.opt.decision_variables.vec()
p = self.opt.parameters.vec()
problem = {
"x": x,
"p": p,
"f": self.opt.f(x, p),
}
# Setup constraints
## Lower bound on constraints.
self._lbg = None
## Upper bound on constraints
self._ubg = None
if self.opt_type in CONSTRAINED_OPT:
problem["g"] = self.opt.v(x, p)
self._lbg = self.opt.lbv
self._ubg = self.opt.ubv
# Get solver interface
if (solver_name in self.qp_solvers) and not self.opt.has_discrete_variables():
sol = cs.qpsol
elif (solver_name in self.nlp_solvers) or (solver_name in self.mi_solvers):
sol = cs.nlpsol
else:
raise ValueError(
f"solver '{solver_name}' does not support this problem type"
)
# Check for discrete variables
if self.opt.has_discrete_variables():
solver_options["discrete"] = self.opt.decision_variables.discrete()
# Initialize solver
## Instance of the CasADi solver.
self._solver = sol("solver", solver_name, problem, solver_options)
return self | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def setup_solver(self):\n option = Options()\n if logger.getEffectiveLevel() == logging.DEBUG:\n # option.printLevel = PrintLevel.HIGH\n option.printLevel = PrintLevel.NONE\n else:\n option.printLevel = PrintLevel.NONE\n self.solver_minimizing = SQProblem(self.nV, self.nC)\n self.solver_minimizing.setOptions(option)\n self.solver_maximizing = SQProblem(self.nV, self.nC)\n self.solver_maximizing.setOptions(option)\n\n self.solver_minimizing_recent_index = -2\n self.solver_maximizing_recent_index = -2",
"def office_setup_solver(parser, args, params):\n parser.parse_known_args(args)\n control.setup_solver(params)",
"def setup(self, solver_settings: Dict = {}):\n assert self.opt_type in QP_COST, \"CVXOPT cannot solve this problem\"\n\n ## Input to the solver\n self._solver_input = solver_settings\n\n self._reset_parameters()\n return self",
"def _set_solver(self):\n self.solver = Solver.select_solver(self.method, self.solver_args)\n if self.method.lower()==\"elastic-net\":\n self.solver.elements=self.basis.elements",
"def office_prepare_solver(parser, args, params):\n parser.parse_known_args(args)\n control.prepare_solver(params)",
"def set_solver(self, solver):\n self.solver = solver\n solver.associate_with_model(self)\n self.set_free_variable(0) # A reasonable initial assumption; can be overridden by simulations",
"def init_solver(param):\n return param.solver(learning_rate=param.learning_rate,\n beta1=param.beta1,\n beta2=param.beta2)",
"def set_solver(solver: str, adjacency):\n if solver == 'auto':\n solver: str = auto_solver(adjacency.nnz)\n if solver == 'lanczos':\n solver: EigSolver = LanczosEig()\n else: # pragma: no cover\n solver: EigSolver = HalkoEig()\n return solver",
"def setup(\n self,\n method: str = \"SLSQP\",\n tol: Union[None, float] = None,\n options: Union[None, Dict] = None,\n ):\n\n # Input check\n if self.opt_type in CONSTRAINED_OPT and (\n method not in ScipyMinimizeSolver.methods_handle_constraints\n ):\n raise TypeError(\n f\"optimization problem has constraints, the method '{method}' is not suitable\"\n )\n\n # Setup class attributes\n\n ## Container for the statistics.\n self._stats = None\n\n ## Method name.\n self.method = method\n\n # Setup minimize input parameters\n\n ## Input to the minimize method\n self.minimize_input = {\n \"fun\": self.f,\n \"method\": method,\n \"x0\": self.x0.toarray().flatten(),\n }\n\n if tol is not None:\n self.minimize_input[\"tol\"] = tol\n\n if options is not None:\n self.minimize_input[\"options\"] = options\n\n if method in ScipyMinimizeSolver.methods_req_jac:\n self.minimize_input[\"jac\"] = self.jac\n\n if method in ScipyMinimizeSolver.methods_req_hess:\n self.minimize_input[\"hess\"] = self.hess\n\n ## Constraints definition passed to the minimize method.\n self._constraints = {}\n if method in ScipyMinimizeSolver.methods_handle_constraints:\n if method != \"trust-constr\":\n if self.opt_type in CONSTRAINED_OPT:\n self._constraints[\"constr\"] = {\n \"type\": \"ineq\",\n \"fun\": self.v,\n \"jac\": self.dv,\n }\n else:\n if self.opt.nk:\n self._constraints[\"k\"] = LinearConstraint(\n A=csc_matrix(self.opt.M(self.p).toarray()),\n lb=-self.opt.c(self.p).toarray().flatten(),\n ub=self.opt.inf * np.ones(self.opt.nk),\n )\n\n if self.opt.na:\n eq = -self.opt.b(self.p).toarray().flatten()\n self._constraints[\"a\"] = LinearConstraint(\n A=csc_matrix(self.opt.A(self.p).toarray()),\n lb=eq,\n ub=eq,\n )\n\n if self.opt.ng:\n self._constraints[\"g\"] = NonlinearConstraint(\n fun=self.g,\n lb=np.zeros(self.opt.ng),\n ub=self.opt.inf * np.ones(self.opt.ng),\n jac=self.dg,\n hess=self.ddg,\n )\n\n if self.opt.nh:\n self._constraints[\"h\"] = NonlinearConstraint(\n fun=self.h,\n lb=np.zeros(self.opt.nh),\n ub=np.zeros(self.opt.nh),\n jac=self.dh,\n hess=self.ddh,\n )\n\n return self",
"def __init__(self, opts: dict, solver_opts: dict):\n self.name = opts.get(\"name\", \"Undefined\") # Name of the problem\n self.gp = opts.get(\"grid_points\") # Number of grid points\n self.nadir_p = opts.get(\"nadir_points\") # Nadir points\n self.eps = opts.get(\"penalty_weight\", 1e-3) # Penalty weight\n self.round = opts.get(\"round_decimals\", 9) # Decimal places to round to\n self.nadir_r = opts.get(\"nadir_ratio\", 1) # Nadir ratio\n self.logdir = opts.get(\"logging_folder\", \"logs\") # Folder to save logs\n self.early_exit = opts.get(\"early_exit\", True) # Whether to enable early exit\n self.bypass = opts.get(\"bypass_coefficient\", True) # Whether to enable bypass coefficient\n self.flag = opts.get(\"flag_array\", True) # Whether to use flag array\n self.cpu_count = opts.get(\"cpu_count\", cpu_count()) # Number of CPUs to use\n self.redivide_work = opts.get(\"redivide_work\", True) # Whether to redivide work\n self.model_fn = opts.get(\"pickle_file\", \"model.p\") # Pickle file name\n self.shared_flag = opts.get(\"shared_flag\", True) # Whether to use shared flag array\n self.output_excel = opts.get(\"output_excel\", True) # Whether to output to Excel\n self.process_logging = opts.get(\"process_logging\", False) # Whether to enable process logging\n self.process_timeout = opts.get(\"process_timeout\", None) # Timeout for processes\n self.solver_name = opts.get(\"solver_name\", \"gurobi\") # Name of solver\n self.solver_io = opts.get(\"solver_io\", \"python\") # IO mode of solver\n\n self.solver_opts = solver_opts # Solver options\n self.solver_opts[\"MIPGap\"] = solver_opts.get(\"MIPGap\", 0.0) # MIP gap\n self.solver_opts[\"NonConvex\"] = solver_opts.get(\"NonConvex\", 2) # Nonconvex setting\n\n # Remove None values from dict when user has overriden them\n for key, value in dict(self.solver_opts).items():\n if value is None or value:\n del self.solver_opts[key]\n\n self.time_created = time.strftime(\"%Y%m%d-%H%M%S\") # Time the options object was created\n self.log_name = self.name + \"_\" + str(self.time_created) # Name of log file",
"def ikSolver(*args, epsilon: Union[float, bool]=0.0, maxIterations: Union[int, bool]=0, name:\n Union[AnyStr, bool]=\"\", solverType: Union[AnyStr, bool]=\"\", q=True, query=True,\n e=True, edit=True, **kwargs)->Union[AnyStr, Any]:\n pass",
"def setSolverTau(*argv):",
"def solve(self, model, solver=\"cbc\", with_duals=False, **solver_kwargs):\n logging.info(\"Optimising using %s.\", solver)\n\n solver_kwargs[\"tee\"] = solver_kwargs.get(\"tee\", True)\n\n self.meta[\"solph_version\"] = solph.__version__\n self.meta[\"solver\"] = solver\n self.meta[\"solver_start\"] = datetime.datetime.now()\n\n if with_duals:\n model.receive_duals()\n\n model.solve(solver=solver, solve_kwargs=solver_kwargs)\n\n self.meta[\"solver_end\"] = datetime.datetime.now()\n\n self.es.results[\"main\"] = solph.processing.results(model)\n self.meta.update(solph.processing.meta_results(model))\n self.es.results[\"param\"] = solph.processing.parameter_as_dict(self.es)\n self.es.results[\"meta\"] = self.meta\n\n self.results = self.es.results",
"def CreateSolverWrapper(settings, solver_name):\n return base_factory.Create(settings, [solver_name], \"KratosMultiphysics.CoSimulationApplication\")",
"def solve(self, solver):\n solver.solve()",
"def __solve(self) -> None:\n pyo.TransformationFactory(\"contrib.detect_fixed_vars\").apply_to(self.model) # type: ignore\n pyo.TransformationFactory(\"contrib.deactivate_trivial_constraints\").apply_to(self.model) # type: ignore\n\n # initialise the solver object\n self._logger.debug(\"[ModelSolver] Solver object initiated...\")\n solver = Config.OPTIMISATION_MODEL_CONFIG['SOLVER_TYPE']\n opt = pyo.SolverFactory(solver)\n if Config.OPTIMISATION_MODEL_CONFIG['SOLVER_OPTION'].get(solver) is not None:\n for k, v in Config.OPTIMISATION_MODEL_CONFIG['SOLVER_OPTION'].get(solver).items():\n opt.options[k] = v\n\n try:\n start_time = datetime.now()\n self._logger.debug(\"[ModelSolver] Solver starting...\")\n results = opt.solve(self.model, tee=True)\n self.results = results\n end_time = datetime.now()\n self._logger.info(f\"[ModelSolver] Solver completed in {end_time - start_time}.\")\n except Exception as e:\n raise Exception(f\"Model optimisation failed with {solver} with error message {e}.\")\n\n if (results.solver.status == SolverStatus.ok) and (results.solver.termination_condition == TerminationCondition.optimal):\n self._logger.info(\"Solution is feasible and optimal\")\n results.write()\n elif results.solver.termination_condition == TerminationCondition.infeasible:\n raise ValueError(\"Model optimisation resulted into an infeasible solution\")\n\n self.model.optimised = True",
"def do_optimisation(self):\n\n print('--> Parameters for optimisation:')\n print('--> Using measurements : {}'.format(self.stoma_cfg.comparison_helper.optimisation_keys))\n print('')\n\n x0 = self.initial_guess()\n\n tol, eps = 1e-4, 0.001\n\n print('--> Using SLSQP with tol={} and eps={}'.format(tol, eps))\n\n soln = opt.minimize(fun=self.optimise_fn,\n x0=x0,\n method='SLSQP',\n tol=tol,\n options={'eps': eps})\n\n print('*' * 120)\n print('--> Optimisation procedure has finished...')\n print(soln)\n print('*' * 120)\n\n if soln.success:\n print('--> Optimisation succeeded. Result is...')\n self._set_material_parameters(soln.x)\n print('--> {}'.format(self.material_model))\n else:\n print('--> The optimisation failed!')\n\n print('*' * 120)\n\n return soln",
"def solve_optimisation(model, exe_path, project_dir, poses) -> None:\n opt = SolverFactory(\n 'ipopt',\n executable=exe_path\n )\n\n # solver options\n opt.options[\"print_level\"] = 5\n opt.options[\"max_iter\"] = 400\n opt.options[\"max_cpu_time\"] = 3600\n opt.options[\"tol\"] = 1e-1\n opt.options[\"OF_print_timing_statistics\"] = \"yes\"\n opt.options[\"OF_print_frequency_iter\"] = 10\n opt.options[\"OF_hessian_approximation\"] = \"limited-memory\"\n #opt.options[\"linear_solver\"] = \"ma86\"\n\n LOG_DIR = 'C://Users//user-pc//Documents//Scripts//FYP//logs'\n\n # --- This step may take a while! ---\n results = opt.solve(\n model, tee=True, \n keepfiles=True, \n logfile=os.path.join(LOG_DIR, \"solver.log\")\n )\n\n result_dir = os.path.join(project_dir, \"results\")\n save_data(model, file_path=os.path.join(result_dir, 'traj_results.pickle'), poses=poses)",
"def buildSolverModel(self, lp):\n self._extract(lp)\n try:\n # Apply controls, warmstart etc. We do this here rather than in\n # callSolver() so that the caller has a chance to overwrite things\n # either using the `prepare` argument to callSolver() or by\n # explicitly calling\n # self.buildSolverModel()\n # self.callSolver()\n # self.findSolutionValues()\n # This also avoids setting warmstart information passed to the\n # constructor from actualResolve(), which would almost certainly\n # be unintended.\n model = lp.solverModel\n # Apply controls that were passed to the constructor\n for key, name in [\n (\"gapRel\", \"MIPRELSTOP\"),\n (\"timeLimit\", \"MAXTIME\"),\n (\"heurFreq\", \"HEURFREQ\"),\n (\"heurStra\", \"HEURSTRATEGY\"),\n (\"coverCuts\", \"COVERCUTS\"),\n (\"preSolve\", \"PRESOLVE\"),\n ]:\n value = self.optionsDict.get(key, None)\n if value is not None:\n model.setControl(name, value)\n\n # Apply any other controls. These overwrite controls that were\n # passed explicitly into the constructor.\n for option in self.options:\n if isinstance(option, tuple):\n name = optione[0]\n value = option[1]\n else:\n fields = option.split(\"=\", 1)\n if len(fields) != 2:\n raise PulpSolverError(\"Invalid option \" + str(option))\n name = fields[0].strip()\n value = fields[1].strip()\n try:\n model.setControl(name, int(value))\n continue\n except ValueError:\n pass\n try:\n model.setControl(name, float(value))\n continue\n except ValueError:\n pass\n model.setControl(name, value)\n # Setup warmstart information\n if self.optionsDict.get(\"warmStart\", False):\n solval = list()\n colind = list()\n for v in sorted(lp.variables(), key=lambda x: x._xprs[0]):\n if v.value() is not None:\n solval.append(v.value())\n colind.append(v._xprs[0])\n if _ismip(lp) and self.mip:\n # If we have a value for every variable then use\n # loadmipsol(), which requires a dense solution. Otherwise\n # use addmipsol() which allows sparse vectors.\n if len(solval) == model.attributes.cols:\n model.loadmipsol(solval)\n else:\n model.addmipsol(solval, colind, \"warmstart\")\n else:\n model.loadlpsol(solval, None, None, None)\n # Setup message callback if output is requested\n if self.msg:\n\n def message(prob, data, msg, msgtype):\n if msgtype > 0:\n print(msg)\n\n model.addcbmessage(message)\n except (xpress.ModelError, xpress.InterfaceError, xpress.SolverError) as err:\n raise PulpSolverError(str(err))",
"def sparse_options(default_solver='spsolve',\n default_least_squares_solver='least_squares_lsmr' if HAVE_SCIPY_LSMR else 'least_squares_generic_lsmr',\n bicgstab_tol=1e-15,\n bicgstab_maxiter=None,\n spilu_drop_tol=1e-4,\n spilu_fill_factor=10,\n spilu_drop_rule='basic,area',\n spilu_permc_spec='COLAMD',\n spsolve_permc_spec='COLAMD',\n spsolve_keep_factorization=True,\n lgmres_tol=1e-5,\n lgmres_maxiter=1000,\n lgmres_inner_m=39,\n lgmres_outer_k=3,\n least_squares_lsmr_damp=0.0,\n least_squares_lsmr_atol=1e-6,\n least_squares_lsmr_btol=1e-6,\n least_squares_lsmr_conlim=1e8,\n least_squares_lsmr_maxiter=None,\n least_squares_lsmr_show=False,\n least_squares_lsqr_damp=0.0,\n least_squares_lsqr_atol=1e-6,\n least_squares_lsqr_btol=1e-6,\n least_squares_lsqr_conlim=1e8,\n least_squares_lsqr_iter_lim=None,\n least_squares_lsqr_show=False,\n pyamg_tol=1e-5,\n pyamg_maxiter=400,\n pyamg_verb=False,\n pyamg_rs_strength=('classical', {'theta': 0.25}),\n pyamg_rs_CF='RS',\n pyamg_rs_presmoother=('gauss_seidel', {'sweep': 'symmetric'}),\n pyamg_rs_postsmoother=('gauss_seidel', {'sweep': 'symmetric'}),\n pyamg_rs_max_levels=10,\n pyamg_rs_max_coarse=500,\n pyamg_rs_coarse_solver='pinv2',\n pyamg_rs_cycle='V',\n pyamg_rs_accel=None,\n pyamg_rs_tol=1e-5,\n pyamg_rs_maxiter=100,\n pyamg_sa_symmetry='hermitian',\n pyamg_sa_strength='symmetric',\n pyamg_sa_aggregate='standard',\n pyamg_sa_smooth=('jacobi', {'omega': 4.0/3.0}),\n pyamg_sa_presmoother=('block_gauss_seidel', {'sweep': 'symmetric'}),\n pyamg_sa_postsmoother=('block_gauss_seidel', {'sweep': 'symmetric'}),\n pyamg_sa_improve_candidates=[('block_gauss_seidel', {'sweep': 'symmetric', 'iterations': 4}), None],\n pyamg_sa_max_levels=10,\n pyamg_sa_max_coarse=500,\n pyamg_sa_diagonal_dominance=False,\n pyamg_sa_coarse_solver='pinv2',\n pyamg_sa_cycle='V',\n pyamg_sa_accel=None,\n pyamg_sa_tol=1e-5,\n pyamg_sa_maxiter=100):\n\n assert default_least_squares_solver.startswith('least_squares')\n\n opts = (('bicgstab_spilu', {'type': 'bicgstab_spilu',\n 'tol': bicgstab_tol,\n 'maxiter': bicgstab_maxiter,\n 'spilu_drop_tol': spilu_drop_tol,\n 'spilu_fill_factor': spilu_fill_factor,\n 'spilu_drop_rule': spilu_drop_rule,\n 'spilu_permc_spec': spilu_permc_spec}),\n ('bicgstab', {'type': 'bicgstab',\n 'tol': bicgstab_tol,\n 'maxiter': bicgstab_maxiter}),\n ('spsolve', {'type': 'spsolve',\n 'permc_spec': spsolve_permc_spec,\n 'keep_factorization': spsolve_keep_factorization}),\n ('lgmres', {'type': 'lgmres',\n 'tol': lgmres_tol,\n 'maxiter': lgmres_maxiter,\n 'inner_m': lgmres_inner_m,\n 'outer_k': lgmres_outer_k}),\n ('least_squares_lsqr', {'type': 'least_squares_lsqr',\n 'damp': least_squares_lsqr_damp,\n 'atol': least_squares_lsqr_atol,\n 'btol': least_squares_lsqr_btol,\n 'conlim': least_squares_lsqr_conlim,\n 'iter_lim': least_squares_lsqr_iter_lim,\n 'show': least_squares_lsqr_show}))\n\n if HAVE_SCIPY_LSMR:\n opts += (('least_squares_lsmr', {'type': 'least_squares_lsmr',\n 'damp': least_squares_lsmr_damp,\n 'atol': least_squares_lsmr_atol,\n 'btol': least_squares_lsmr_btol,\n 'conlim': least_squares_lsmr_conlim,\n 'maxiter': least_squares_lsmr_maxiter,\n 'show': least_squares_lsmr_show}),)\n\n if HAVE_PYAMG:\n opts += (('pyamg', {'type': 'pyamg',\n 'tol': pyamg_tol,\n 'maxiter': pyamg_maxiter}),\n ('pyamg-rs', {'type': 'pyamg-rs',\n 'strength': pyamg_rs_strength,\n 'CF': pyamg_rs_CF,\n 'presmoother': pyamg_rs_presmoother,\n 'postsmoother': pyamg_rs_postsmoother,\n 'max_levels': pyamg_rs_max_levels,\n 'max_coarse': pyamg_rs_max_coarse,\n 'coarse_solver': pyamg_rs_coarse_solver,\n 'cycle': pyamg_rs_cycle,\n 'accel': pyamg_rs_accel,\n 'tol': pyamg_rs_tol,\n 'maxiter': pyamg_rs_maxiter}),\n ('pyamg-sa', {'type': 'pyamg-sa',\n 'symmetry': pyamg_sa_symmetry,\n 'strength': pyamg_sa_strength,\n 'aggregate': pyamg_sa_aggregate,\n 'smooth': pyamg_sa_smooth,\n 'presmoother': pyamg_sa_presmoother,\n 'postsmoother': pyamg_sa_postsmoother,\n 'improve_candidates': pyamg_sa_improve_candidates,\n 'max_levels': pyamg_sa_max_levels,\n 'max_coarse': pyamg_sa_max_coarse,\n 'diagonal_dominance': pyamg_sa_diagonal_dominance,\n 'coarse_solver': pyamg_sa_coarse_solver,\n 'cycle': pyamg_sa_cycle,\n 'accel': pyamg_sa_accel,\n 'tol': pyamg_sa_tol,\n 'maxiter': pyamg_sa_maxiter}))\n opts = OrderedDict(opts)\n opts.update(genericsolvers.options())\n def_opt = opts.pop(default_solver)\n if default_least_squares_solver != default_solver:\n def_ls_opt = opts.pop(default_least_squares_solver)\n ordered_opts = OrderedDict(((default_solver, def_opt),\n (default_least_squares_solver, def_ls_opt)))\n else:\n ordered_opts = OrderedDict(((default_solver, def_opt),))\n ordered_opts.update(opts)\n return ordered_opts",
"def set_simulation_options(self, result_handler, solver, atol, rtol, verbose):\n # The result handling can be one of\n # \"file\", \"memory\", \"custom\" (in the latter case a result handler has to be specified)\n # By default they are on memory\n if result_handler is not None and result_handler in fmu_util_strings.SIMULATION_OPTION_RESHANDLING_LIST:\n self.opts[fmu_util_strings.SIMULATION_OPTION_RESHANDLING_STRING] = result_handler\n else:\n self.opts[fmu_util_strings.SIMULATION_OPTION_RESHANDLING_STRING] = fmu_util_strings.RESULTS_ON_MEMORY_STRING\n \n \n # Set solver verbose level\n if verbose is not None and verbose in fmu_util_strings.SOLVER_VERBOSITY_LEVELS:\n for s in fmu_util_strings.SOLVER_NAMES_OPTIONS: \n self.opts[s][fmu_util_strings.SOLVER_OPTION_VERBOSITY_STRING] = verbose\n else:\n for s in fmu_util_strings.SOLVER_NAMES_OPTIONS: \n self.opts[s][fmu_util_strings.SOLVER_OPTION_VERBOSITY_STRING] = fmu_util_strings.SOLVER_VERBOSITY_QUIET\n \n \n # Set the absolute and relative tolerance of each solver, otherwise the default value\n # is left\n if atol is not None and atol > 0 and numpy.isreal(atol):\n for s in fmu_util_strings.SOLVER_NAMES_OPTIONS: \n self.opts[s][fmu_util_strings.SOLVER_OPTION_ATOL_STRING] = atol\n if rtol is not None and rtol > 0 and numpy.isreal(rtol):\n for s in fmu_util_strings.SOLVER_NAMES_OPTIONS: \n self.opts[s][fmu_util_strings.SOLVER_OPTION_RTOL_STRING] = rtol",
"def solver_options(lgmres_tol=1e-5,\n lgmres_maxiter=1000,\n lgmres_inner_m=39,\n lgmres_outer_k=3,\n least_squares_lsmr_damp=0.0,\n least_squares_lsmr_atol=1e-6,\n least_squares_lsmr_btol=1e-6,\n least_squares_lsmr_conlim=1e8,\n least_squares_lsmr_maxiter=None,\n least_squares_lsmr_show=False,\n least_squares_lsqr_damp=0.0,\n least_squares_lsqr_atol=1e-6,\n least_squares_lsqr_btol=1e-6,\n least_squares_lsqr_conlim=1e8,\n least_squares_lsqr_iter_lim=None,\n least_squares_lsqr_show=False):\n\n return {'generic_lgmres': {'type': 'generic_lgmres',\n 'tol': lgmres_tol,\n 'maxiter': lgmres_maxiter,\n 'inner_m': lgmres_inner_m,\n 'outer_k': lgmres_outer_k},\n 'generic_least_squares_lsmr': {'type': 'generic_least_squares_lsmr',\n 'damp': least_squares_lsmr_damp,\n 'atol': least_squares_lsmr_atol,\n 'btol': least_squares_lsmr_btol,\n 'conlim': least_squares_lsmr_conlim,\n 'maxiter': least_squares_lsmr_maxiter,\n 'show': least_squares_lsmr_show},\n 'generic_least_squares_lsqr': {'type': 'generic_least_squares_lsqr',\n 'damp': least_squares_lsqr_damp,\n 'atol': least_squares_lsqr_atol,\n 'btol': least_squares_lsqr_btol,\n 'conlim': least_squares_lsqr_conlim,\n 'iter_lim': least_squares_lsqr_iter_lim,\n 'show': least_squares_lsqr_show}}",
"def setup_optimiser(self):\n self.optimiser = ScheduledOptim(\n optim.Adam(\n filter(lambda x: x.requires_grad, self.model.parameters()),\n betas=(0.9, 0.98), eps=1e-09, lr=self.opt.learning_rate),\n self.opt.d_model, self.opt.n_warmup_steps)\n if self.opt.verbose:\n print(\"[Info] optimiser configured.\")",
"def __init__(self, name=\"\"):\n # Name of the SMT solver that this object represents.\n self.name = name",
"def build(self, **kwargs):\n self.solver = self.get_solver(**kwargs)\n self.solver.build(self.graph, **kwargs)",
"def solve(\n self, solver=Solver.IPOPT, show_online_optim=False, return_iterations=False, solver_options={},\n ):\n\n if return_iterations and not show_online_optim:\n raise RuntimeError(\"return_iterations without show_online_optim is not implemented yet.\")\n\n if solver == Solver.IPOPT and self.solver_type != Solver.IPOPT:\n from ..interfaces.ipopt_interface import IpoptInterface\n\n self.solver = IpoptInterface(self)\n\n elif solver == Solver.ACADOS and self.solver_type != Solver.ACADOS:\n from ..interfaces.acados_interface import AcadosInterface\n\n self.solver = AcadosInterface(self, **solver_options)\n\n elif self.solver_type == Solver.NONE:\n raise RuntimeError(\"Solver not specified\")\n self.solver_type = solver\n\n if show_online_optim:\n self.solver.online_optim(self)\n if return_iterations:\n self.solver.start_get_iterations()\n\n self.solver.configure(solver_options)\n self.solver.solve()\n\n if return_iterations:\n self.solver.finish_get_iterations()\n\n return self.solver.get_optimized_value(self)",
"def setSolverDamping(*argv):",
"def setSolverType(*argv):",
"def __init__(self, solverType, problem, name):\n super(BaseSolver, self).__init__(name='process-%s' % name)\n if not solverType in ['optimizer', 'clusterer', 'classifier']:\n raise SolverException(\n solverType, name, parameters,\n \"Invalid solver type: %s\" % solverType)\n self._solverType = solverType\n self._name = name\n self._problem = problem\n self._logReader, self._logWriter = Pipe(False)\n self._lastLogWrite = time.time()\n self._ignoredLogInfoSent = False\n self._vizReader, self._vizWriter = Pipe(False)\n self._lastVizWrite = time.time()\n self._msrReader, self._msrWriter = Pipe(False)\n self._lastMsrWrite = time.time()\n self._start_t = time.time()\n self._nbSteps = 0\n self._startTime = None",
"def init_solver(self, cost_func=None, opt_x0=False, init_uncertainty=False):\n self.cost_func = cost_func\n self.opt_x0 = opt_x0\n self.init_uncertainty = init_uncertainty\n\n u_0 = MX.sym(\"init_control\", (self.n_u, 1))\n k_ff_all = MX.sym(\"feed-forward control\", (self.n_safe - 1, self.n_u))\n g = []\n lbg = []\n ubg = []\n g_name = []\n\n p_0 = MX.sym(\"initial state\", (self.n_s, 1))\n q_0 = None\n k_fb_0 = None\n if init_uncertainty:\n q_0 = MX.sym(\"init uncertainty\", (self.n_s, self.n_s))\n k_fb_0 = MX.sym(\"init feddback control matrix\", (self.n_u, self.n_s))\n\n k_fb_safe = MX.sym(\"feedback matrices\",\n (self.n_safe - 1, self.n_s * self.n_u))\n\n p_all, q_all, gp_sigma_pred_safe_all = cas_multistep(p_0, u_0, k_fb_safe, k_ff_all,\n self.ssm_forward, self.l_mu,\n self.l_sigma,\n self.beta_safety, self.a,\n self.b,\n self.lin_trafo_gp_input, q_0, k_fb_0)\n\n # generate open_loop trajectory function [vertcat(x_0,u_0)],[f_x])\n\n if init_uncertainty:\n self._f_multistep_eval = cas.Function(\"safe_multistep\",\n [p_0, u_0, k_fb_safe, k_ff_all, q_0, k_fb_0],\n [p_all, q_all, gp_sigma_pred_safe_all])\n else:\n self._f_multistep_eval = cas.Function(\"safe_multistep\",\n [p_0, u_0, k_fb_safe, k_ff_all],\n [p_all, q_all, gp_sigma_pred_safe_all])\n\n g_safe, lbg_safe, ubg_safe, g_names_safe = self.generate_safety_constraints(\n p_all, q_all, u_0, k_fb_safe, k_ff_all, q_0, k_fb_0)\n g = vertcat(g, g_safe)\n lbg += lbg_safe\n ubg += ubg_safe\n g_name += g_names_safe\n\n # Generate performance trajectory\n if self.n_perf > 1:\n k_ff_perf, k_fb_perf, k_ff_perf_traj, k_fb_perf_traj, mu_perf, sigma_perf, gp_sigma_pred_perf_all, g_perf, lbg_perf, ubg_perf, g_names_perf = self._generate_perf_trajectory_casadi(\n p_0, u_0, k_ff_all, k_fb_safe, self.a, self.b, self.lin_trafo_gp_input)\n g = vertcat(g, g_perf)\n lbg += lbg_perf\n ubg += ubg_perf\n g_name += g_names_perf\n else:\n k_ff_perf = np.array([])\n k_fb_perf = np.array([])\n k_fb_perf_traj = np.array([])\n k_ff_perf_traj = np.array([])\n mu_perf = np.array([])\n sigma_perf = np.array([])\n gp_sigma_pred_perf_all = None\n\n cost = self.generate_cost_function(p_0, u_0, p_all, q_all, mu_perf, sigma_perf,\n k_ff_all, k_fb_safe, gp_sigma_pred_safe_all,\n k_fb_perf=k_fb_perf_traj,\n k_ff_perf=k_ff_perf_traj,\n gp_pred_sigma_perf=gp_sigma_pred_perf_all,\n custom_cost_func=cost_func)\n\n if self.opt_x0:\n opt_vars = vertcat(p_0, u_0, k_ff_perf, k_ff_all.reshape((-1, 1)))\n opt_params = vertcat(k_fb_safe.reshape((-1, 1)), k_fb_perf.reshape((-1, 1)))\n else:\n opt_vars = vertcat(u_0, k_ff_perf, k_ff_all.reshape((-1, 1)))\n opt_params = vertcat(p_0, k_fb_safe.reshape((-1, 1)), k_fb_perf.reshape((-1, 1)))\n\n if self.init_uncertainty:\n opt_params = vertcat(opt_params, q_0.reshape((-1, 1)), k_fb_0.reshape((-1, 1)))\n\n prob = {'f': cost, 'x': opt_vars, 'p': opt_params, 'g': g}\n\n opt = self.opts_solver\n if opt is None:\n opt = {'error_on_fail': False,\n 'ipopt': {'hessian_approximation': 'limited-memory', \"max_iter\": 100,\n \"expect_infeasible_problem\": \"no\", \\\n 'acceptable_tol': 1e-4, \"acceptable_constr_viol_tol\": 1e-5,\n \"bound_frac\": 0.5, \"start_with_resto\": \"no\",\n \"required_infeasibility_reduction\": 0.85,\n \"acceptable_iter\": 8}} # ipopt\n\n # opt = {'max_iter':120,'hessian_approximation':'limited-memory'}#,\"c1\":5e-4} #sqpmethod #,\n # opt = {'max_iter':120,'qpsol':'qpoases'}\n\n solver = cas.nlpsol('solver', 'ipopt', prob, opt)\n # solver = cas.nlpsol('solver','sqpmethod',prob,opt)\n # solver = cas.nlpsol('solver','blocksqp',prob,opt)\n\n self.solver = solver\n self.lbg = lbg\n self.ubg = ubg\n self.solver_initialized = True\n self.g = g\n self.g_name = g_name"
] | [
"0.74249095",
"0.67771596",
"0.67073375",
"0.66630006",
"0.6459805",
"0.63141966",
"0.627811",
"0.6217816",
"0.62000686",
"0.6156034",
"0.61203367",
"0.6076768",
"0.600414",
"0.6000106",
"0.5990672",
"0.5988505",
"0.59504825",
"0.58804995",
"0.58746856",
"0.5870907",
"0.58551073",
"0.5855103",
"0.5850567",
"0.58414245",
"0.5813588",
"0.58073443",
"0.57872176",
"0.57800686",
"0.5696826",
"0.56739986"
] | 0.7781433 | 0 |
! True when the solver succeeded, False otherwise. Boolean indicating success of solver. | def did_solve(self) -> bool:
return self._stats["success"] | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def did_solve(self):\n return self._solution.success",
"def did_solve(self) -> bool:\n return self._solution.info.status == \"solved\"",
"def has_solution(self) -> bool:\n pass",
"def did_solve(self) -> bool:\n pass",
"def solveOneStep(self):\n ### Student code goes here\n return True",
"def did_solve(self):\n return self._solution[\"status\"] == \"optimal\"",
"def test_is_solved_when_puzzle_is_solved(self):\n self.assertTrue(self.sudoku.is_solved())",
"def is_solvable(self):\n self_copy = deepcopy(self)\n return self_copy.solve()",
"def isSolved(self):\n return self.isComplete() and self.isLegal()",
"def ok(self, solution):\n if self.constraints is not None:\n for constraint in self.constraints:\n if not constraint(solution):\n return False\n return True",
"def converged(self) -> bool:",
"def converged(self) -> bool:",
"def converged(self) -> bool:",
"def IsOk(self):\r\n \r\n return True",
"def answer(self) -> bool:",
"def is_solved(self):\n self.solved = self.current_pos == self.finish_pos\n return self.solved",
"def __bool__(self):\n return self.is_successful",
"def was_successful(self):\n return self._build_proto.status == common.SUCCESS",
"def is_solved(self):\n raise NotImplementedError()",
"def has_solution(self) -> bool:\n if self in [self.SATISFIED, self.ALL_SOLUTIONS, self.OPTIMAL_SOLUTION]:\n return True\n return False",
"def test_is_solved(self):\n p = hw.TilePuzzle([[1, 2], [3, 0]])\n self.assertTrue(p.is_solved())\n p = hw.TilePuzzle([[0, 1], [3, 2]])\n self.assertFalse(p.is_solved())",
"def update_status(self):\n if len(self.invalid) != 0:\n return False\n for row in self.grid:\n for num in row:\n if num == 0:\n return False\n self.solved = True\n print(\"solved\")\n return True",
"def isTrue(self, hard=False):\n global debug_solver_count\n \n if( self.cond == CT.TRUE ):\n return True\n elif( self.cond == CT.FALSE ):\n return False\n \n if( hard == False ):\n res = self.customSimplify()\n return ( res == CE.TRUE )\n else:\n condZ3 = self.simplifyZ3()\n self.checked = True\n v = Solver()\n v.add(Not(condZ3))\n signal.signal(signal.SIGALRM, TimeOutRaiser)\n #signal.setitimer(signal.ITIMER_REAL, 1) \n try: \n res = str(v.check())\n except Exception as e:\n res = \"sat\"\n debug_solver_count = debug_solver_count + 1\n if( str(res) == \"unsat\" ):\n self.setTrue()\n return True\n else:\n return False",
"def isSolved(self):\n return self.__isSolved",
"def is_solved(self):\n if not self._find_empty():\n return True\n else:\n return False",
"def passed(self):\n if self.result == RESULT_PASS:\n return True\n\n return False",
"def solve(self, solver):\n solver.solve()",
"def get_result(self, solver: SudokuSolver) -> None:\n if solver.is_sudoku_completed():\n # if True:\n self.insert_digits(solver)\n else:\n self.status_bar.config(text='This sudoku is unsolvable.', fg='red')\n return None",
"def isOk(self):\n return self._isOk",
"def _tunnel_success(tunnel_returncode):\n return tunnel_returncode < 0"
] | [
"0.7067127",
"0.6976514",
"0.6906094",
"0.6893781",
"0.6678232",
"0.6579035",
"0.63947487",
"0.63604105",
"0.6359685",
"0.6338862",
"0.63223594",
"0.63223594",
"0.63223594",
"0.6285663",
"0.627599",
"0.6262388",
"0.62505686",
"0.616309",
"0.6159712",
"0.6082403",
"0.60639143",
"0.6050955",
"0.6040829",
"0.60094553",
"0.600503",
"0.6001968",
"0.597918",
"0.59741133",
"0.5953186",
"0.59486014"
] | 0.7201746 | 0 |
! Setup solver. use_warm_start When true, the initial seed x0 is used as a warm start. Default is True. settings Settings that are passed to OSQP. Default is {}. The instance of the solve (i.e. self). | def setup(self, use_warm_start, settings={}):
assert self.opt_type in QP_COST, "OSQP cannot solve this type of problem"
self.use_warm_start = use_warm_start
self._setup_input = settings
if self.opt_type in CONSTRAINED_OPT:
self._setup_input["u"] = np.inf * np.ones(self.opt.nk + self.opt.na)
self._reset_parameters()
return self | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def setup(self, solver_settings: Dict = {}):\n assert self.opt_type in QP_COST, \"CVXOPT cannot solve this problem\"\n\n ## Input to the solver\n self._solver_input = solver_settings\n\n self._reset_parameters()\n return self",
"def setup_solver(self):\n option = Options()\n if logger.getEffectiveLevel() == logging.DEBUG:\n # option.printLevel = PrintLevel.HIGH\n option.printLevel = PrintLevel.NONE\n else:\n option.printLevel = PrintLevel.NONE\n self.solver_minimizing = SQProblem(self.nV, self.nC)\n self.solver_minimizing.setOptions(option)\n self.solver_maximizing = SQProblem(self.nV, self.nC)\n self.solver_maximizing.setOptions(option)\n\n self.solver_minimizing_recent_index = -2\n self.solver_maximizing_recent_index = -2",
"def solve(self):\n # check for jacobian and set it if present and to be used\n if self.use_sparse:\n if self._use_jac and hasattr(self.problem,'sparse_jac'):\n jac = self.problem.sparse_jac\n else:\n jac = None\n else:\n if self._use_jac and hasattr(self.problem,'jac'):\n jac = self.problem.jac\n else:\n jac = None\n \n # Initialize solver and solve \n \n solved = False\n local_min = False\n\n res = N.zeros(self.x0.__len__())\n while (not solved) and self.reg_count < 2:\n try:\n if self._use_fscale:\n self.solver.KINSOL_init(self.func,self.x0,self.dim,jac,self.constraints,self.use_sparse,self.verbosity,self.norm_of_res,self.reg_param,self.fscale)\n else:\n self.solver.KINSOL_init(self.func,self.x0,self.dim,jac,self.constraints,self.use_sparse,self.verbosity,self.norm_of_res,self.reg_param,None)\n start = time.clock()\n res = self.solver.KINSOL_solve(not self._use_ls)\n stop = time.clock()\n self.exec_time += (stop - start)\n solved = True\n except KINError as error:\n if error.value == 42:\n # Try the heuristic\n if hasattr(self.problem, 'get_heuristic_x0'):\n print \"----------------------------------------------------\"\n print \" Solver stuck with zero step-length.\"\n print \"----------------------------------------------------\"\n print \"The following variables have start value zero\"\n print \"and min set to zero causing the zero step-lenght.\"\n print \"These settings are either set by default or by user.\"\n print \"\"\n\n self.x0 = self.problem.get_heuristic_x0()\n self.reg_count += 1\n \n print \"\"\n print \"This setting (start and min to zero) can often\"\n print \"cause problem when initializing the system. \"\n print \"\"\n print \"To avoid this the above variables have\"\n print \"their start attributes reset to one.\"\n print \"\"\n print \"Trying to solve the system again...\"\n else:\n raise KINSOL_Exception(\"Regularization failed due to constraints, tried getting heuristic initial guess but failed.\")\n \n\n elif (error.value == 2):\n print \"---------------------------------------------------------\"\n print \"\"\n print \" !!! WARNING !!!\"\n print \"\"\n print \" KINSOL has returned a result but the algorithm has converged\"\n print \" to a local minima, the initial values are NOT consistant!\"\n print \"\"\n print \"---------------------------------------------------------\"\n solved = True\n local_min = True\n else:\n # Other error, send onward as exception\n self.problem.check_constraints(res)\n raise KINSOL_Exception(error.msg[error.value])\n \n if not solved:\n self.solver.Free_KINSOL()\n raise KINSOL_Exception(\"Algorithm exited solution loop without finding a solution, please contact Assimulo support.\")\n\n if self.check_with_model:\n self.problem.check_constraints(res)\n if not local_min:\n print \"Problem sent to KINSOL solved.\"\n \n return res",
"def setUp(self):\n # Simple QP problem\n sp.random.seed(4)\n\n self.n = 30\n self.m = 30\n self.P = sparse.csc_matrix((self.n, self.n))\n self.q = np.zeros(self.n)\n self.A = sparse.random(self.m, self.n, density=1.0, format='csc')\n self.u = np.random.rand(self.m)\n self.l = self.u\n self.opts = {'verbose': False,\n 'eps_abs': 1e-06,\n 'eps_rel': 1e-06,\n 'scaling': True,\n 'alpha': 1.6,\n 'max_iter': 5000,\n 'polish': False,\n 'warm_start': True,\n 'polish_refine_iter': 4}\n self.model = osqp.OSQP()\n self.model.setup(P=self.P, q=self.q, A=self.A, l=self.l, u=self.u,\n **self.opts)",
"def office_setup_solver(parser, args, params):\n parser.parse_known_args(args)\n control.setup_solver(params)",
"def setup_nonlinear_model_x0(x=0, y=0, th=0, xd=0, yd=0, thd=0, fs=None, x_mhh=None, wx=0, wy=0, wxr=0, wyr=0, p=None):\n xs = np.array([x, y, th])\n xsd = np.array([xd, yd, thd])\n\n if p['dynamicStallModel'] is None:\n xua = np.array([])\n elif p['dynamicStallModel'].lower() == 'oye':\n if fs is None:\n # TODO\n print('TODO figure out angle of attack')\n # fs_i = p['fPolar'](alphai*np.pi/180)[3] # initial position\n xua = np.array([0])\n else:\n xua = np.array([fs])\n elif p['dynamicStallModel'].lower() == 'mhh':\n if x_mhh is None:\n xua = np.array([0, 0, 0, 0])\n else:\n raise NotImplementedError()\n else:\n NotImplementedError()\n\n if p['dynamicInflowModel'] is None:\n xdi = np.array([])\n elif p['dynamicInflowModel'].lower() == 'oye':\n # TODO\n xdi = np.array([wxr,wx,wyr,wy]) # Whatch out for order here\n else:\n NotImplementedError()\n q_full = np.concatenate((xs,xsd,xdi,xua))\n state0 = q_full[p['Iq']]\n return state0",
"def __init__(self, sparse_args=None, solve=True):\n self.solved = False\n self.sparse_args = sparse_args\n self.solved = False\n if solve: self.solve()",
"def solve(self, problem, warm_start, verbose, solver_opts):\n data, inv_data = self.apply(problem)\n solution = self.solve_via_data(data, warm_start, verbose, solver_opts)\n return self.invert(solution, inv_data)",
"def optim_solve(\n self, x0: devices.PrimaryWeights = None, global_search: bool = False, **kwargs\n ) -> scipy.optimize.OptimizeResult:\n print(f'{\" optim_solve \":~^60s}')\n self._assert_problem_is_valid()\n if self._background is None:\n bounds = self.bounds * 2\n print(\"> No background specified, will optimise background.\")\n else:\n bounds = self.bounds\n\n if np.inf in self._target_contrast:\n print(\"> Aiming to maximise contrast.\")\n\n elif -np.inf in self._target_contrast:\n print(\"> Aiming to minimize contrast.\")\n\n constraints = [\n {\"type\": \"eq\", \"fun\": self.silencing_constraint, \"tol\": 1e-04}\n ]\n\n if x0 is None:\n x0 = self.initial_guess_x0()\n \n if not global_search: # Local minimization\n\n default_options = {\"iprint\": 2, \"disp\": True, \"ftol\": 1e-08}\n options = kwargs.pop(\"options\", default_options)\n\n print(\"> Performing local optimization with SLSQP.\")\n result = scipy.optimize.minimize(\n fun=self.objective_function,\n x0=x0,\n method=\"SLSQP\",\n bounds=bounds,\n constraints=constraints,\n options=options,\n **kwargs,\n )\n\n elif global_search: # Global minimization\n print(\n \"> Performing global optimization with basinhopping and SLSQP\"\n )\n\n # Configure global defaults\n disp = kwargs.pop(\"disp\", True)\n # Configure local defaults\n default_minimizer_kwargs = {\n \"method\": \"SLSQP\",\n \"constraints\": constraints,\n \"bounds\": bounds,\n \"options\": {\"iprint\": 2, \"disp\": False},\n }\n minimizer_kwargs = kwargs.pop(\n \"minimizer_kwargs\", default_minimizer_kwargs\n )\n\n # Do optimization\n result = scipy.optimize.basinhopping(\n func=self.objective_function,\n x0=x0,\n minimizer_kwargs=minimizer_kwargs,\n disp=disp,\n **kwargs,\n )\n\n return result",
"def __solve(self) -> None:\n pyo.TransformationFactory(\"contrib.detect_fixed_vars\").apply_to(self.model) # type: ignore\n pyo.TransformationFactory(\"contrib.deactivate_trivial_constraints\").apply_to(self.model) # type: ignore\n\n # initialise the solver object\n self._logger.debug(\"[ModelSolver] Solver object initiated...\")\n solver = Config.OPTIMISATION_MODEL_CONFIG['SOLVER_TYPE']\n opt = pyo.SolverFactory(solver)\n if Config.OPTIMISATION_MODEL_CONFIG['SOLVER_OPTION'].get(solver) is not None:\n for k, v in Config.OPTIMISATION_MODEL_CONFIG['SOLVER_OPTION'].get(solver).items():\n opt.options[k] = v\n\n try:\n start_time = datetime.now()\n self._logger.debug(\"[ModelSolver] Solver starting...\")\n results = opt.solve(self.model, tee=True)\n self.results = results\n end_time = datetime.now()\n self._logger.info(f\"[ModelSolver] Solver completed in {end_time - start_time}.\")\n except Exception as e:\n raise Exception(f\"Model optimisation failed with {solver} with error message {e}.\")\n\n if (results.solver.status == SolverStatus.ok) and (results.solver.termination_condition == TerminationCondition.optimal):\n self._logger.info(\"Solution is feasible and optimal\")\n results.write()\n elif results.solver.termination_condition == TerminationCondition.infeasible:\n raise ValueError(\"Model optimisation resulted into an infeasible solution\")\n\n self.model.optimised = True",
"def init_solver(param):\n return param.solver(learning_rate=param.learning_rate,\n beta1=param.beta1,\n beta2=param.beta2)",
"def _initialize(self):\n self._solution = self._problem_instance.build_solution(method=\"Greedy\")\n\n while not self._problem_instance.is_admissible(self._solution):\n self._solution = self._problem_instance.build_solution(method=\"Greedy\")\n \n self._problem_instance.evaluate_solution(self._solution, feedback=self._feedback)",
"def setup_method(self):\n self.x0 = (1.0, [1.0, 1.0])\n self.sol = (-0.195, np.array([-0.195, -0.1]))\n\n self.tol = 3 # number of decimal places\n\n self.niter = 100\n self.disp = False\n\n # fix random seed\n np.random.seed(1234)\n\n self.kwargs = {\"method\": \"L-BFGS-B\", \"jac\": True}\n self.kwargs_nograd = {\"method\": \"L-BFGS-B\"}",
"def sparse_options(default_solver='spsolve',\n default_least_squares_solver='least_squares_lsmr' if HAVE_SCIPY_LSMR else 'least_squares_generic_lsmr',\n bicgstab_tol=1e-15,\n bicgstab_maxiter=None,\n spilu_drop_tol=1e-4,\n spilu_fill_factor=10,\n spilu_drop_rule='basic,area',\n spilu_permc_spec='COLAMD',\n spsolve_permc_spec='COLAMD',\n spsolve_keep_factorization=True,\n lgmres_tol=1e-5,\n lgmres_maxiter=1000,\n lgmres_inner_m=39,\n lgmres_outer_k=3,\n least_squares_lsmr_damp=0.0,\n least_squares_lsmr_atol=1e-6,\n least_squares_lsmr_btol=1e-6,\n least_squares_lsmr_conlim=1e8,\n least_squares_lsmr_maxiter=None,\n least_squares_lsmr_show=False,\n least_squares_lsqr_damp=0.0,\n least_squares_lsqr_atol=1e-6,\n least_squares_lsqr_btol=1e-6,\n least_squares_lsqr_conlim=1e8,\n least_squares_lsqr_iter_lim=None,\n least_squares_lsqr_show=False,\n pyamg_tol=1e-5,\n pyamg_maxiter=400,\n pyamg_verb=False,\n pyamg_rs_strength=('classical', {'theta': 0.25}),\n pyamg_rs_CF='RS',\n pyamg_rs_presmoother=('gauss_seidel', {'sweep': 'symmetric'}),\n pyamg_rs_postsmoother=('gauss_seidel', {'sweep': 'symmetric'}),\n pyamg_rs_max_levels=10,\n pyamg_rs_max_coarse=500,\n pyamg_rs_coarse_solver='pinv2',\n pyamg_rs_cycle='V',\n pyamg_rs_accel=None,\n pyamg_rs_tol=1e-5,\n pyamg_rs_maxiter=100,\n pyamg_sa_symmetry='hermitian',\n pyamg_sa_strength='symmetric',\n pyamg_sa_aggregate='standard',\n pyamg_sa_smooth=('jacobi', {'omega': 4.0/3.0}),\n pyamg_sa_presmoother=('block_gauss_seidel', {'sweep': 'symmetric'}),\n pyamg_sa_postsmoother=('block_gauss_seidel', {'sweep': 'symmetric'}),\n pyamg_sa_improve_candidates=[('block_gauss_seidel', {'sweep': 'symmetric', 'iterations': 4}), None],\n pyamg_sa_max_levels=10,\n pyamg_sa_max_coarse=500,\n pyamg_sa_diagonal_dominance=False,\n pyamg_sa_coarse_solver='pinv2',\n pyamg_sa_cycle='V',\n pyamg_sa_accel=None,\n pyamg_sa_tol=1e-5,\n pyamg_sa_maxiter=100):\n\n assert default_least_squares_solver.startswith('least_squares')\n\n opts = (('bicgstab_spilu', {'type': 'bicgstab_spilu',\n 'tol': bicgstab_tol,\n 'maxiter': bicgstab_maxiter,\n 'spilu_drop_tol': spilu_drop_tol,\n 'spilu_fill_factor': spilu_fill_factor,\n 'spilu_drop_rule': spilu_drop_rule,\n 'spilu_permc_spec': spilu_permc_spec}),\n ('bicgstab', {'type': 'bicgstab',\n 'tol': bicgstab_tol,\n 'maxiter': bicgstab_maxiter}),\n ('spsolve', {'type': 'spsolve',\n 'permc_spec': spsolve_permc_spec,\n 'keep_factorization': spsolve_keep_factorization}),\n ('lgmres', {'type': 'lgmres',\n 'tol': lgmres_tol,\n 'maxiter': lgmres_maxiter,\n 'inner_m': lgmres_inner_m,\n 'outer_k': lgmres_outer_k}),\n ('least_squares_lsqr', {'type': 'least_squares_lsqr',\n 'damp': least_squares_lsqr_damp,\n 'atol': least_squares_lsqr_atol,\n 'btol': least_squares_lsqr_btol,\n 'conlim': least_squares_lsqr_conlim,\n 'iter_lim': least_squares_lsqr_iter_lim,\n 'show': least_squares_lsqr_show}))\n\n if HAVE_SCIPY_LSMR:\n opts += (('least_squares_lsmr', {'type': 'least_squares_lsmr',\n 'damp': least_squares_lsmr_damp,\n 'atol': least_squares_lsmr_atol,\n 'btol': least_squares_lsmr_btol,\n 'conlim': least_squares_lsmr_conlim,\n 'maxiter': least_squares_lsmr_maxiter,\n 'show': least_squares_lsmr_show}),)\n\n if HAVE_PYAMG:\n opts += (('pyamg', {'type': 'pyamg',\n 'tol': pyamg_tol,\n 'maxiter': pyamg_maxiter}),\n ('pyamg-rs', {'type': 'pyamg-rs',\n 'strength': pyamg_rs_strength,\n 'CF': pyamg_rs_CF,\n 'presmoother': pyamg_rs_presmoother,\n 'postsmoother': pyamg_rs_postsmoother,\n 'max_levels': pyamg_rs_max_levels,\n 'max_coarse': pyamg_rs_max_coarse,\n 'coarse_solver': pyamg_rs_coarse_solver,\n 'cycle': pyamg_rs_cycle,\n 'accel': pyamg_rs_accel,\n 'tol': pyamg_rs_tol,\n 'maxiter': pyamg_rs_maxiter}),\n ('pyamg-sa', {'type': 'pyamg-sa',\n 'symmetry': pyamg_sa_symmetry,\n 'strength': pyamg_sa_strength,\n 'aggregate': pyamg_sa_aggregate,\n 'smooth': pyamg_sa_smooth,\n 'presmoother': pyamg_sa_presmoother,\n 'postsmoother': pyamg_sa_postsmoother,\n 'improve_candidates': pyamg_sa_improve_candidates,\n 'max_levels': pyamg_sa_max_levels,\n 'max_coarse': pyamg_sa_max_coarse,\n 'diagonal_dominance': pyamg_sa_diagonal_dominance,\n 'coarse_solver': pyamg_sa_coarse_solver,\n 'cycle': pyamg_sa_cycle,\n 'accel': pyamg_sa_accel,\n 'tol': pyamg_sa_tol,\n 'maxiter': pyamg_sa_maxiter}))\n opts = OrderedDict(opts)\n opts.update(genericsolvers.options())\n def_opt = opts.pop(default_solver)\n if default_least_squares_solver != default_solver:\n def_ls_opt = opts.pop(default_least_squares_solver)\n ordered_opts = OrderedDict(((default_solver, def_opt),\n (default_least_squares_solver, def_ls_opt)))\n else:\n ordered_opts = OrderedDict(((default_solver, def_opt),))\n ordered_opts.update(opts)\n return ordered_opts",
"def fit_once(self,random_restart=True):\n \n if random_restart:\n ## Main mode of operation\n \n # Initializations\n n_iterations = int(np.ceil(np.log2(self.K))) # log_2(K) iterations\n self.initialize_empty_solution()\n self.residual = self.sketch_reweighted\n \n # Add the starting atom\n new_theta = self.randomly_initialize_new_atom()\n new_theta = self.maximize_atom_correlation(new_theta)\n self.add_atom(new_theta)\n \n # Main loop\n for i_iteration in range(n_iterations):\n ## Step 1-2: split the currently selected atoms\n self.split_all_atoms()\n \n ## Step 3: if necessary, hard-threshold to enforce sparsity\n while self.n_atoms > self.K:\n beta = self.find_optimal_weights(normalize_atoms=True)\n index_to_remove = np.argmin(beta)\n self.remove_atom(index_to_remove)\n \n \n ## Step 4: project to find weights\n self.alpha = self.find_optimal_weights()\n \n ## Step 5: fine-tune\n self.minimize_cost_from_current_sol()\n\n # Cleanup\n self.update_Atoms() # The atoms have changed: we must re-compute their sketches matrix\n self.residual = self.sketch_reweighted - self.sketch_of_solution()\n \n # Final fine-tuning with increased optimization accuracy\n self.minimize_cost_from_current_sol(ftol=0.02*self.step5_ftol)\n \n # Normalize weights to unit sum\n self.alpha /= np.sum(self.alpha)\n \n # Package into the solution attribute\n self.current_sol = (self.alpha, self.Theta)",
"def update_settings(self, **kwargs):\n\n # get arguments\n max_iter = kwargs.pop('max_iter', None)\n eps_abs = kwargs.pop('eps_abs', None)\n eps_rel = kwargs.pop('eps_rel', None)\n eps_prim_inf = kwargs.pop('eps_prim_inf', None)\n eps_dual_inf = kwargs.pop('eps_dual_inf', None)\n rho = kwargs.pop('rho', None)\n alpha = kwargs.pop('alpha', None)\n delta = kwargs.pop('delta', None)\n polish = kwargs.pop('polish', None)\n polish_refine_iter = kwargs.pop('polish_refine_iter', None)\n verbose = kwargs.pop('verbose', None)\n scaled_termination = kwargs.pop('scaled_termination', None)\n check_termination = kwargs.pop('check_termination', None)\n warm_start = kwargs.pop('warm_start', None)\n time_limit = kwargs.pop('time_limit', None)\n\n # update them\n if max_iter is not None:\n self._model.update_max_iter(max_iter)\n\n if eps_abs is not None:\n self._model.update_eps_abs(eps_abs)\n\n if eps_rel is not None:\n self._model.update_eps_rel(eps_rel)\n\n if eps_prim_inf is not None:\n self._model.update_eps_prim_inf(eps_prim_inf)\n\n if eps_dual_inf is not None:\n self._model.update_eps_dual_inf(eps_dual_inf)\n\n if rho is not None:\n self._model.update_rho(rho)\n\n if alpha is not None:\n self._model.update_alpha(alpha)\n\n if delta is not None:\n self._model.update_delta(delta)\n\n if polish is not None:\n self._model.update_polish(polish)\n\n if polish_refine_iter is not None:\n self._model.update_polish_refine_iter(polish_refine_iter)\n\n if verbose is not None:\n self._model.update_verbose(verbose)\n\n if scaled_termination is not None:\n self._model.update_scaled_termination(scaled_termination)\n\n if check_termination is not None:\n self._model.update_check_termination(check_termination)\n\n if warm_start is not None:\n self._model.update_warm_start(warm_start)\n\n if time_limit is not None:\n self._model.update_time_limit(time_limit)\n\n if max_iter is None and \\\n eps_abs is None and \\\n eps_rel is None and \\\n eps_prim_inf is None and \\\n eps_dual_inf is None and \\\n rho is None and \\\n alpha is None and \\\n delta is None and \\\n polish is None and \\\n polish_refine_iter is None and \\\n verbose is None and \\\n scaled_termination is None and \\\n check_termination is None and \\\n warm_start is None:\n raise ValueError(\"No updatable settings has been specified!\")",
"def setup_fitting_init_pars(inparam, night, band, masterbeam, order):\n\n # Determine whether IGRINS mounting was loose or\n # the night of interest is in question\n if (int(night) < 20180401) or (int(night) > 20190531):\n IPpars = inparam.ips_tightmount_pars[band][masterbeam][order]\n else:\n IPpars = inparam.ips_loosemount_pars[band][masterbeam][order]\n\n # start at bucket loc = 1250 +- 100, width = 250 +- 100,\n # depth = 100 +- 5000 but floor at 0\n centerloc = 1250 if band == 'H' else 1180\n\n # Initialize parameter array for optimization as well as half-range values\n # for each parameter during the various steps of the optimization.\n # Many of the parameters initialized here will be changed throughout the\n # code before optimization and in between optimization steps.\n\n parA0 = np.array([\n 0.0, # 0: The shift of the stellar template (km/s)\n 0.0, # 1: The scale factor for the stellar template\n 0.0, # 2: The shift of the telluric template (km/s)\n 1.0, # 3: The scale factor for the telluric template\n 0.0, # 4: vsini (km/s)\n IPpars[2], # 5: The instrumental resolution (FWHM) in pixels\n 0.0, # 6: Wavelength 0-pt\n 0.0, # 7: Wavelength linear component\n 0.0, # 8: Wavelength quadratic component\n 0.0, # 9: Wavelength cubic component\n 1.0, #10: Continuum zero point\n 0.0, #11: Continuum linear component\n 0.0, #12: Continuum quadratic component\n IPpars[1], #13: Instrumental resolution linear component\n IPpars[0], #14: Instrumental resolution quadratic component\n centerloc, #15: Blaze dip center location\n 330, #16: Blaze dip full width\n 0.05, #17: Blaze dip depth\n 90, #18: Secondary blaze dip full width\n 0.05, #19: Blaze dip depth\n 0.0, #20: Continuum cubic component\n 0.0, #21: Continuum quartic component\n 0.0, #22: Continuum quintic component\n 0.0, #23: Continuum hexic component\n 0.0, #24: secondary par\n 0.0, #25: secondary par\n 0.0, #26: secondary par\n 0.0 #27: secondary par\n ])\n\n return parA0",
"def set_solver_parameters(m, gamma, horizon, my_vars, timeout=30 * 60, pre_solve=-1):\n h = ext.get_set_time(horizon)\n beta = get_var(my_vars, 'beta')\n m.setObjective(quicksum((gamma ** t) * beta[0, t] for t in h), GRB.MAXIMIZE)\n\n m.setParam('TimeLimit', timeout)\n m.setParam('Threads', 8)\n m.setParam('Presolve', pre_solve)\n m.setParam('OutputFlag', 0)",
"def solve(num_wizards, num_constraints, wizards, constraints): \n global wiz_const\n wiz_const = mapConstraints(wizards, constraints)\n partial_soltns = []\n\n # counter for priority queue since it doesn't allow \n # identical priorities\n k = 0\n\n # list of wizards sorted by lowest to highest degree\n sorted_wiz = sortWizByConsts(wiz_const)\n wiz_rankings = {wiz: i for i, wiz in enumerate(sorted_wiz)}\n\n const_set = set(map(tuple, constraints))\n for i in range(4) : \n heapq.heappush(partial_soltns, (0, k, nx.DiGraph(), const_set.copy()))\n k += 1\n\n print(\"setup done, commencing solving\")\n\n while len(partial_soltns) : \n\n # for partial_soltn, const_set in partial_soltns : \n# partial_soltns.remove(partial_soltn)\n num_seen, _, partial_soltn, const_set = heapq.heappop(partial_soltns)\n const = findNextConst(partial_soltn, const_set, wiz_rankings)\n print(\"seen \" + str(len(partial_soltn)) + \"\\t num partial_solutions\\t\" + str(len(partial_soltns)))\n try : \n const_set.remove(const)\n except KeyError : \n print(\"BAD SHIT\")\n pass\n possible_arrangements = [(const[0], const[1], const[2]),\n (const[2], const[0], const[1]), \n (const[2], const[1], const[0]),\n (const[1], const[0], const[2])]\n for arr in possible_arrangements:\n soltn = partial_soltn.copy()\n a, b, c = arr\n if not (soltn.has_node(a) and soltn.has_node(b) and nx.has_path(soltn, a, b)) : \n soltn.add_edge(a, b)\n if not (soltn.has_node(b) and soltn.has_node(c) and nx.has_path(soltn, b, c)) : \n soltn.add_edge(b, c)\n # see if we violated any other constraints (seen or not seen)\n is_valid, num_wiz = validNumWiz(soltn, const_set)\n\n if is_valid and len(list(nx.simple_cycles(soltn))) == 0 :\n heapq.heappush(partial_soltns, (-len(soltn), k, soltn, const_set.copy()))\n k += 1\n # are we done?\n if num_wiz == num_wizards :\n print(\"FINAL SOLUTION (found without processing all constraints but validating against them)\")\n ordering = list(nx.topological_sort(soltn))\n finishEverything(ordering, constraints)\n return ordering\n if foundCompleteOrdering(heapq.heappop(partial_soltns)) : \n print(\"FINAL SOLUTION\")\n ordering = list(nx.topological_sort(soltn))\n finishEverything(ordering, constraints)\n return ordering\n print(\"NO SOLUTION FOUND\")\n return \"\"",
"def __init__(self,\n problem: FloatProblem,\n swarm_size: int,\n max_evaluations: int,\n mutation: Mutation[FloatSolution],\n leaders: BoundedArchive[FloatSolution],\n evaluator: Evaluator[FloatSolution] = SequentialEvaluator[FloatSolution](),\n reference_point = None,\n levy: int = 0,\n levy_decay: int = 0):\n super(MOQPSO, self).__init__()\n self.problem = problem\n self.swarm_size = swarm_size\n self.max_evaluations = max_evaluations\n self.mutation = mutation\n self.leaders = leaders\n self.evaluator = evaluator\n self.levy = levy\n self.levy_decay = levy_decay\n self.prev_gbest = None\n self.hypervolume_calculator = HyperVolume(reference_point)\n\n self.evaluations = 0\n self.beta_swarm = 1.2\n self.g = 0.95\n self.particle_history = {}\n self.objective_history = {0: [], 1:[]}\n self.dominance_comparator = DominanceComparator()\n self.constrictors = [(problem.upper_bound[i] - problem.lower_bound[i]) / 5000.0 for i in range(problem.number_of_variables)]\n\n self.prev_hypervolume = 0\n self.current_hv = 0\n\n self.hv_changes = []\n\n self.beta = 3/2\n self.sigma = (gamma(1 + self.beta) * sin(pi * self.beta / 2) / (gamma((1 + self.beta) / 2) * self.beta * 2 ** ((self.beta - 1) / 2))) ** (1 / self.beta)",
"def __init__(self, x, num_target_dims, settings, debug=False, warm_start_nn=None):\n self.x = x\n self.NUM_TARGET_DIMS = num_target_dims\n self.SETTINGS = settings\n self.DEBUG = debug\n self.WARM_START_NN = warm_start_nn\n self.create()",
"def _set_solver(self):\n self.solver = Solver.select_solver(self.method, self.solver_args)\n if self.method.lower()==\"elastic-net\":\n self.solver.elements=self.basis.elements",
"def reset_initial_seed(self, x0) -> None:\n super().reset_initial_seed(x0)\n self.minimize_input[\"x0\"] = self.x0.toarray().flatten()",
"def init_solver(self, cost_func=None, opt_x0=False, init_uncertainty=False):\n self.cost_func = cost_func\n self.opt_x0 = opt_x0\n self.init_uncertainty = init_uncertainty\n\n u_0 = MX.sym(\"init_control\", (self.n_u, 1))\n k_ff_all = MX.sym(\"feed-forward control\", (self.n_safe - 1, self.n_u))\n g = []\n lbg = []\n ubg = []\n g_name = []\n\n p_0 = MX.sym(\"initial state\", (self.n_s, 1))\n q_0 = None\n k_fb_0 = None\n if init_uncertainty:\n q_0 = MX.sym(\"init uncertainty\", (self.n_s, self.n_s))\n k_fb_0 = MX.sym(\"init feddback control matrix\", (self.n_u, self.n_s))\n\n k_fb_safe = MX.sym(\"feedback matrices\",\n (self.n_safe - 1, self.n_s * self.n_u))\n\n p_all, q_all, gp_sigma_pred_safe_all = cas_multistep(p_0, u_0, k_fb_safe, k_ff_all,\n self.ssm_forward, self.l_mu,\n self.l_sigma,\n self.beta_safety, self.a,\n self.b,\n self.lin_trafo_gp_input, q_0, k_fb_0)\n\n # generate open_loop trajectory function [vertcat(x_0,u_0)],[f_x])\n\n if init_uncertainty:\n self._f_multistep_eval = cas.Function(\"safe_multistep\",\n [p_0, u_0, k_fb_safe, k_ff_all, q_0, k_fb_0],\n [p_all, q_all, gp_sigma_pred_safe_all])\n else:\n self._f_multistep_eval = cas.Function(\"safe_multistep\",\n [p_0, u_0, k_fb_safe, k_ff_all],\n [p_all, q_all, gp_sigma_pred_safe_all])\n\n g_safe, lbg_safe, ubg_safe, g_names_safe = self.generate_safety_constraints(\n p_all, q_all, u_0, k_fb_safe, k_ff_all, q_0, k_fb_0)\n g = vertcat(g, g_safe)\n lbg += lbg_safe\n ubg += ubg_safe\n g_name += g_names_safe\n\n # Generate performance trajectory\n if self.n_perf > 1:\n k_ff_perf, k_fb_perf, k_ff_perf_traj, k_fb_perf_traj, mu_perf, sigma_perf, gp_sigma_pred_perf_all, g_perf, lbg_perf, ubg_perf, g_names_perf = self._generate_perf_trajectory_casadi(\n p_0, u_0, k_ff_all, k_fb_safe, self.a, self.b, self.lin_trafo_gp_input)\n g = vertcat(g, g_perf)\n lbg += lbg_perf\n ubg += ubg_perf\n g_name += g_names_perf\n else:\n k_ff_perf = np.array([])\n k_fb_perf = np.array([])\n k_fb_perf_traj = np.array([])\n k_ff_perf_traj = np.array([])\n mu_perf = np.array([])\n sigma_perf = np.array([])\n gp_sigma_pred_perf_all = None\n\n cost = self.generate_cost_function(p_0, u_0, p_all, q_all, mu_perf, sigma_perf,\n k_ff_all, k_fb_safe, gp_sigma_pred_safe_all,\n k_fb_perf=k_fb_perf_traj,\n k_ff_perf=k_ff_perf_traj,\n gp_pred_sigma_perf=gp_sigma_pred_perf_all,\n custom_cost_func=cost_func)\n\n if self.opt_x0:\n opt_vars = vertcat(p_0, u_0, k_ff_perf, k_ff_all.reshape((-1, 1)))\n opt_params = vertcat(k_fb_safe.reshape((-1, 1)), k_fb_perf.reshape((-1, 1)))\n else:\n opt_vars = vertcat(u_0, k_ff_perf, k_ff_all.reshape((-1, 1)))\n opt_params = vertcat(p_0, k_fb_safe.reshape((-1, 1)), k_fb_perf.reshape((-1, 1)))\n\n if self.init_uncertainty:\n opt_params = vertcat(opt_params, q_0.reshape((-1, 1)), k_fb_0.reshape((-1, 1)))\n\n prob = {'f': cost, 'x': opt_vars, 'p': opt_params, 'g': g}\n\n opt = self.opts_solver\n if opt is None:\n opt = {'error_on_fail': False,\n 'ipopt': {'hessian_approximation': 'limited-memory', \"max_iter\": 100,\n \"expect_infeasible_problem\": \"no\", \\\n 'acceptable_tol': 1e-4, \"acceptable_constr_viol_tol\": 1e-5,\n \"bound_frac\": 0.5, \"start_with_resto\": \"no\",\n \"required_infeasibility_reduction\": 0.85,\n \"acceptable_iter\": 8}} # ipopt\n\n # opt = {'max_iter':120,'hessian_approximation':'limited-memory'}#,\"c1\":5e-4} #sqpmethod #,\n # opt = {'max_iter':120,'qpsol':'qpoases'}\n\n solver = cas.nlpsol('solver', 'ipopt', prob, opt)\n # solver = cas.nlpsol('solver','sqpmethod',prob,opt)\n # solver = cas.nlpsol('solver','blocksqp',prob,opt)\n\n self.solver = solver\n self.lbg = lbg\n self.ubg = ubg\n self.solver_initialized = True\n self.g = g\n self.g_name = g_name",
"def __init__(self, settings,study):\n \n # Store the study #\n ###################\n \n self._study = study\n self._parameters_size = self._study.geometry.parameters_size\n \n # Read settings #\n ################# \n if hasattr(settings, 'global_sample_function'):\n # Use given function and ignore bounds\n self._global_sample_function = settings.global_sample_function\n self._global_parameters_bounds = None\n else:\n # If no function, use uniform rand with given boundaries if provided. If not, assume [0,1]\n if hasattr(settings, 'global_parameters_bounds'):\n self._global_parameters_bounds = np.array(settings.global_parameters_bounds)\n else:\n self._global_parameters_bounds = [(0, 1)]*self._parameters_size\n \n self._global_sample_function = lambda: self._global_parameters_bounds[:,0] + (self._global_parameters_bounds[:,1]-self._global_parameters_bounds[:,0])*np.random.rand(1,self._parameters_size).flatten()\n \n\n if hasattr(settings, 'global_result_constraint'):\n self._global_result_constraint = settings.global_result_constraint\n else:\n self._global_result_constraint = None \n \n if hasattr(settings, 'local_result_constraint'):\n self._local_result_constraint = settings.local_result_constraint\n else:\n self._local_result_constraint = None\n \n if hasattr(settings, 'local_max_iterations'):\n self._local_max_iterations = settings.local_max_iterations\n else:\n self._local_max_iterations = 50\n \n if hasattr(settings, 'local_method'):\n self._local_method = settings.local_method\n else:\n self._local_method = 'L-BFGS-B'\n \n if hasattr(settings, 'local_scaling_factor'):\n self._local_scaling_factor = settings.local_scaling_factor\n else:\n self._local_scaling_factor = 1\n \n if hasattr(settings, 'local_ftol'):\n self._local_ftol = settings.local_ftol\n else:\n self._local_ftol = 1e-5\n \n if hasattr(settings, 'local_pgtol'):\n self._local_pgtol = settings.local_pgtol\n else:\n self._local_pgtol = 1e-5\n \n # Wavelength settings for lumopt \n if hasattr(settings, 'local_wavelength_start'):\n self._local_wavelength_start = settings.local_wavelength_start\n else:\n self._local_wavelength_start = 1550e-9\n \n if hasattr(settings, 'local_wavelength_stop'):\n self._local_wavelength_stop = settings.local_wavelength_stop\n else:\n self._local_wavelength_stop = 1550e-9\n \n if hasattr(settings, 'local_wavelength_points'):\n self._local_wavelength_points = settings.local_wavelength_points\n else:\n self._local_wavelength_points = 1\n \n # Keep track of the latest random restart. Run a first simulation with\n # the initial parameters already stored in the geometry\n self._new_param = None",
"def main(**kwargs):\n flowsheet = Flowsheet(name='MB_Model') \n \n # Fix variables\n setInputs(flowsheet) \n\n ts = time.time() \n\n mb = flowsheet.MB_fuel\n \n # Initialize fuel reactor\n flowsheet.MB_fuel._initialize(outlvl=1,\n optarg={\"tol\" : 1e-8,\n \"max_cpu_time\" : 600,\n \"print_level\" : 5,\n \"halt_on_ampl_error\": 'yes'}) \n \n # Create a solver\n opt = SolverFactory('ipopt')\n opt.options = {'tol': 1e-8,\n 'linear_solver' : 'ma27',\n 'bound_push': 1e-8,\n 'max_cpu_time': 600,\n 'print_level': 5}\n \n results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,\n keepfiles=False)\n\n #flowsheet.MB_fuel.Solid_In_M.fix(691.4)\n #flowsheet.MB_fuel.Gas_In_y['CO2'].fix(0.03999)\n #flowsheet.MB_fuel.Gas_In_y['H2O'].fix(0.00001)\n #flowsheet.MB_fuel.Gas_In_y['CH4'].fix(0.96)\n\n\n\n #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,\n # keepfiles=False)\n \n \n print(\"\\n\")\n print(\"----------------------------------------------------------\")\n print('Total simulation time: ', value(time.time() - ts), \" s\")\n print(\"----------------------------------------------------------\")\n\n \n # Print some variables \n #print_summary_fuel_reactor(flowsheet) \n\n # Plot some variables \n #results_plot_fuel_reactor(flowsheet) \n\n m = flowsheet.MB_fuel\n if 'Solid_M' in kwargs:\n m.Solid_In_M.fix(kwargs['Solid_M'])\n if 'Solid_T' in kwargs:\n m.Solid_In_Ts[t].fix(kwargs['Solid_T'])\n if 'Solid_x' in kwargs:\n m.Solid_In_x['Fe2O3'].fix(kwargs['Solid_x']['Fe2O3'])\n m.Solid_In_x['Fe3O4'].fix(kwargs['Solid_x']['Fe3O4'])\n m.Solid_In_x['Al2O3'].fix(kwargs['Solid_x']['Al2O3'])\n if 'Gas_F' in kwargs:\n m.Gas_In_F.fix(kwargs['Gas_F'])\n if 'Gas_P' in kwargs:\n m.Gas_In_P.fix(kwargs['Gas_P'])\n if 'Gas_T' in kwargs:\n m.Gas_In_T.fix(kwargs['Gas_T'])\n if 'Gas_y' in kwargs:\n m.Gas_In_y['CO2'].fix(kwargs['Gas_y']['CO2'])\n m.Gas_In_y['H2O'].fix(kwargs['Gas_y']['H2O'])\n m.Gas_In_y['CH4'].fix(kwargs['Gas_y']['CH4'])\n\n results = opt.solve(flowsheet, tee=True)\n\n with open('ss_fs.txt','w') as f:\n flowsheet.display(ostream=f)\n\n dt_Gflux_CO2 = []\n dt_Gflux_H2O = []\n dt_Gflux_CH4 = []\n dt_Sflux_Fe2O3 = []\n dt_Sflux_Fe3O4 = []\n dt_Sflux_Al2O3 = []\n dt_Ctrans_CO2 = []\n dt_Ctrans_H2O = []\n dt_Ctrans_CH4 = []\n dt_qtrans_Fe2O3 = []\n dt_qtrans_Fe3O4 = []\n dt_qtrans_Al2O3 = []\n dt_Ghflux = []\n dt_Ts = []\n dt_TgGS = []\n dt_TsGS = []\n dt_vg = []\n dt_vs = []\n\n# for z in mb.z.get_finite_elements():\n# if z != mb.z.first() and z != mb.z.last():\n#\n# dt_Gflux_CO2.append( (mb.Cg[z,'CO2'].value-mb.Cg[prev,'CO2'].value)/\\\n# (mb.G_flux[z,'CO2'].value-mb.G_flux[prev,'CO2'].value) \\\n# *(z-prev)*mb.eps.value*mb.L.value /(z-prev))\n#\n# dt_Gflux_H2O.append( (mb.Cg[z,'H2O'].value-mb.Cg[prev,'H2O'].value)/\\\n# (mb.G_flux[z,'H2O'].value-mb.G_flux[prev,'H2O'].value) \\\n# *(z-prev)*mb.eps.value*mb.L.value /(z-prev))\n#\n# dt_Gflux_CH4.append( (mb.Cg[z,'CH4'].value-mb.Cg[prev,'CH4'].value)/\\\n# (mb.G_flux[z,'CH4'].value-mb.G_flux[prev,'CH4'].value) \\\n# *(z-prev)*mb.eps.value*mb.L.value /(z-prev))\n#\n# dt_Ctrans_CO2.append( (mb.Cg[z,'CO2'].value-mb.Cg[prev,'CO2'].value)/\\\n# (mb.Ctrans[z,'CO2'].value)* \\\n# #-mv.Ctrans[prev,'CO2'].value)*\\\n# mb.eps.value/(1-mb.eps.value) /(z-prev))\n#\n# dt_Ctrans_H2O.append( (mb.Cg[z,'H2O'].value-mb.Cg[prev,'H2O'].value)/\\\n# (mb.Ctrans[z,'H2O'].value)* \\\n# #-mv.Ctrans[prev,'H2O'].value)*\\\n# mb.eps.value/(1-mb.eps.value) /(z-prev))\n#\n# dt_Ctrans_CH4.append( (mb.Cg[z,'CH4'].value-mb.Cg[prev,'CH4'].value)/\\\n# (mb.Ctrans[z,'CH4'].value)* \\\n# #-mv.Ctrans[prev,'CH4'].value)*\\\n# mb.eps.value/(1-mb.eps.value) /(z-prev))\n#\n# dt_Sflux_Fe2O3.append( (mb.q[z,'Fe2O3'].value-mb.q[prev,'Fe2O3'].value)/\\\n# (mb.S_flux[z,'Fe2O3'].value-mb.S_flux[prev,'Fe2O3'].value)*\\\n# (z-prev)/(1-mb.eps.value)*mb.L.value /(z-prev))\n#\n# dt_Sflux_Fe3O4.append( (mb.q[z,'Fe3O4'].value-mb.q[prev,'Fe3O4'].value)/\\\n# (mb.S_flux[z,'Fe3O4'].value-mb.S_flux[prev,'Fe3O4'].value)*\\\n# (z-prev)/(1-mb.eps.value)*mb.L.value /(z-prev))\n#\n# dt_Sflux_Al2O3.append( (mb.q[z,'Al2O3'].value-mb.q[prev,'Al2O3'].value)/\\\n# (mb.S_flux[z,'Al2O3'].value-mb.S_flux[prev,'Al2O3'].value)*\\\n# (z-prev)/(1-mb.eps.value)*mb.L.value /(z-prev))\n#\n# dt_qtrans_Fe2O3.append( (mb.q[z,'Fe2O3'].value-mb.q[prev,'Fe2O3'].value)/\\\n# (mb.qtrans[z,'Fe2O3'].value )/(z-prev)) \n# #-mb.qtrans[prev,'Fe2O3'].value) )\n#\n# dt_qtrans_Fe3O4.append( (mb.q[z,'Fe3O4'].value-mb.q[prev,'Fe3O4'].value)/\\\n# (mb.qtrans[z,'Fe3O4'].value )/(z-prev)) \n# #-mb.qtrans[prev,'Fe3O4'].value) )\n#\n# dt_qtrans_Al2O3.append( (mb.q[z,'Fe3O4'].value-mb.q[prev,'Fe3O4'].value)/\\\n# (mb.qtrans[z,'Fe3O4'].value )/(z-prev)) \n# #-mb.qtrans[prev,'Fe3O4'].value) )\n#\n# dt_Ghflux.append( (mb.Tg[z].value-mb.Tg[prev].value)/\\\n# (mb.Gh_flux[z].value-mb.Gh_flux[prev].value)* (z-prev)* mb.eps.value*\\\n# mb.L.value* mb.rho_vap[z].value* mb.cp_gas[z].value /(z-prev)) \n#\n# dt_Ts.append( (z-prev)*(1-mb.eps.value)*mb.L.value/mb.vs.value /(z-prev))\n#\n# dt_TgGS.append( (mb.Tg[z].value - mb.Tg[prev].value)/\\\n# mb.Tg_GS[z].value* mb.eps.value* mb.rho_vap[z].value* mb.cp_gas[z].value \n# /(z-prev))\n# \n# dt_TsGS.append( (mb.Ts[z].value - mb.Ts[prev].value)/\\\n# mb.Tg_GS[z].value* (1-mb.eps.value)* mb.rho_sol.value* mb.cp_sol[z].value*1e-3 \n# /(z-prev))\n# \n# dt_vg.append( mb.L.value*(z-prev)/mb.vg[z].value /(z-prev))\n# \n# dt_vs.append( mb.L.value*(z-prev)/mb.vs.value /(z-prev))\n#\n# prev = z\n#\n# with open('dt.txt','w') as f:\n# f.write('dt_Gflux_CO2\\t')\n# for t in dt_Gflux_CO2:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_Gflux_H2O\\t')\n# for t in dt_Gflux_H2O:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_Gflux_CH4\\t') \n# for t in dt_Gflux_CH4:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_Sflux_Fe2O3\\t') \n# for t in dt_Sflux_Fe2O3:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_Sflux_Fe3O4\\t') \n# for t in dt_Sflux_Fe3O4:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_Sflux_Al2O3\\t') \n# for t in dt_Sflux_Al2O3:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_Ctrans_CO2\\t') \n# for t in dt_Ctrans_CO2:\n# f.write('%1.3f'%t +'\\t')\n# \n# f.write('\\ndt_Ctrans_H2O\\t') \n# for t in dt_Ctrans_H2O:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_Ctrans_CH4\\t') \n# for t in dt_Ctrans_CH4:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_qtrans_Fe2O3\\t') \n# for t in dt_qtrans_Fe2O3:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_qtrans_Fe3O4\\t') \n# for t in dt_qtrans_Fe3O4:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_qtrans_Al2O3\\t') \n# for t in dt_qtrans_Al2O3:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_Ghflux\\t') \n# for t in dt_Ghflux:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_Ts\\t\\t') \n# for t in dt_Ts:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_TgGS\\t\\t') \n# for t in dt_TgGS:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_TsGS\\t\\t') \n# for t in dt_TsGS:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_vg\\t\\t') \n# for t in dt_vg:\n# f.write('%1.3f'%t +'\\t')\n#\n# f.write('\\ndt_vs\\t\\t') \n# for t in dt_vs:\n# f.write('%1.3f'%t +'\\t')\n\n\n # Store the flowsheet \n return flowsheet",
"def _initialize_default_start(self, state):\n state.tau = self.rng.gamma(0.5, 1 / self.fixed.tau_rate)\n eta = self.rng.standard_normal(self.fixed.n)\n eta = eta - eta.mean()\n state.eta = eta\n state.spatial = self.state.eta\n state.alpha = self.rng.multivariate_normal(\n self.fixed.a_mu, 100 * self.fixed.a_prec, method='cholesky'\n )\n state.beta = self.rng.multivariate_normal(\n self.fixed.b_mu, 100 * self.fixed.b_prec, method='cholesky'\n )\n return state",
"def setSolverTau(*argv):",
"def __init__(self, x, y, U, KEx=1, KEy=1, periodic_x=False, periodic_y=False, qx=0, qy=0, sparse_args=None,\n solve=True):\n self.x = x\n self.y = y\n self.U = U\n self.KEx = KEx\n self.KEy = KEy\n self.qx = qx\n self.qy = qy\n self.periodic_x = periodic_x\n self.periodic_y = periodic_y\n Schrodinger.__init__(self, sparse_args=sparse_args, solve=solve)",
"def __init__(\n self,\n num_restarts: int,\n raw_multiplier: int,\n num_fantasies: int,\n dim: int,\n dim_x: int,\n q: int = 1,\n inequality_constraints: List[Tuple] = None,\n random_frac: float = 0.4,\n limiter: float = 10,\n eta: float = 2.0,\n maxiter: int = 1000,\n low_fantasies: Optional[int] = None,\n dtype: Optional[torch.dtype] = torch.float32,\n device: Optional[torch.device] = torch.device(\"cpu\"),\n ):\n self.dtype = dtype\n self.device = device\n self.num_restarts = num_restarts\n self.num_refine_restarts = max(1, ceil(num_restarts / 10.0))\n self.raw_samples = num_restarts * raw_multiplier\n self.num_fantasies = num_fantasies\n self.dim = dim\n self.dim_x = dim_x\n self.q = q\n self.inner_bounds = torch.tensor(\n [[0.0], [1.0]], dtype=self.dtype, device=self.device\n ).repeat(1, dim_x)\n self.outer_bounds = torch.tensor(\n [[0.0], [1.0]], dtype=self.dtype, device=self.device\n ).repeat(1, dim)\n self.random_frac = random_frac\n self.limit = self.raw_samples * limiter\n self.inner_solutions = None # mixed solutions\n self.inner_values = None\n self.eta = eta\n self.maxiter = maxiter\n self.current_best = None\n self.inequality_constraints = inequality_constraints\n self.low_fantasies = low_fantasies\n self.solution_shape = [self.q, self.dim]"
] | [
"0.6558982",
"0.6286072",
"0.6053042",
"0.6030017",
"0.5909029",
"0.5721629",
"0.5692769",
"0.5599076",
"0.55969036",
"0.5596008",
"0.55756867",
"0.5505776",
"0.55011123",
"0.5500232",
"0.54910296",
"0.5485339",
"0.5484214",
"0.5458595",
"0.5456336",
"0.5439466",
"0.5437253",
"0.54310066",
"0.54242235",
"0.5420195",
"0.54021215",
"0.539876",
"0.5397599",
"0.535081",
"0.53481424",
"0.53442466"
] | 0.78621745 | 0 |
! Returns True when the problem was solved. Boolean indicating if the solver converged. | def did_solve(self) -> bool:
return self._solution.info.status == "solved" | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def did_solve(self):\n return self._solution.success",
"def did_solve(self) -> bool:\n return self._stats[\"success\"]",
"def did_solve(self):\n return self._solution[\"status\"] == \"optimal\"",
"def did_solve(self) -> bool:\n pass",
"def converged(self) -> bool:",
"def converged(self) -> bool:",
"def converged(self) -> bool:",
"def has_solution(self) -> bool:\n pass",
"def converged(self) -> bool:\n return self._converged",
"def is_solved(self):\n self.solved = self.current_pos == self.finish_pos\n return self.solved",
"def is_solvable(self):\n self_copy = deepcopy(self)\n return self_copy.solve()",
"def converged(self) -> bool:\n if self._species is not None and self._species.n_atoms == 1:\n return True # Optimisation 0 DOF is always converged\n\n if self._abs_delta_e < self.etol / 10:\n logger.warning(\n f\"Energy change is overachieved. \"\n f'{self.etol.to(\"kcal\")/10:.3E} kcal mol-1. '\n f\"Signaling convergence\"\n )\n return True\n\n return self._abs_delta_e < self.etol and self._g_norm < self.gtol",
"def converged(self) -> bool:\n assert self._coords is not None\n\n if self._converged_translation:\n logger.info(\n \"Converged purely based on translation of the \"\n \"dimer midpoint\"\n )\n return True\n\n rms_g0 = np.sqrt(np.mean(np.square(self._coords.g0)))\n return self.iteration > 0 and rms_g0 < self.gtol",
"def is_solved(self):\n raise NotImplementedError()",
"def isSolved(self):\n return self.isComplete() and self.isLegal()",
"def isSolved(self):\n return self.__isSolved",
"def solved(self):\r\n return self.puzzle.solved",
"def is_solved(self):\n if not self._find_empty():\n return True\n else:\n return False",
"def is_solved(self):\n return self._start == self._target",
"def has_solution(self) -> bool:\n if self in [self.SATISFIED, self.ALL_SOLUTIONS, self.OPTIMAL_SOLUTION]:\n return True\n return False",
"def is_solved(self):\n return (self.from_grid == self.to_grid)",
"def is_solved(self):\n return self.to_grid == self.from_grid",
"def test_is_solved_when_puzzle_is_solved(self):\n self.assertTrue(self.sudoku.is_solved())",
"def is_solved(self):\n return self.from_grid == self.to_grid",
"def is_solved(self):\n return self.from_grid == self.to_grid",
"def is_solved(self):\n return self.from_grid == self.to_grid",
"def update_status(self):\n if len(self.invalid) != 0:\n return False\n for row in self.grid:\n for num in row:\n if num == 0:\n return False\n self.solved = True\n print(\"solved\")\n return True",
"def converged(self):\n if len(self.rundir) >= 2:\n if io.ionic_steps(self.rundir[-1]) <= 3:\n return True\n if self.settings[\"nrg_convergence\"] != None:\n if io.job_complete(self.rundir[-1]) and io.job_complete(self.rundir[-2]):\n o1 = io.Oszicar(os.path.join(self.rundir[-1],\"OSZICAR\"))\n o2 = io.Oszicar(os.path.join(self.rundir[-2],\"OSZICAR\"))\n if abs( o1.E[-1] - o2.E[-1]) < self.settings[\"nrg_convergence\"]:\n return True\n\n return False",
"def is_solved(self):\n # Iterate through each square of the puzzle\n for row in range(self.sl):\n for col in range(self.sl):\n val = self.puzzle[row][col]\n\n # If any square value is blank (0), not solved, return False\n if val == 0:\n return False\n\n # Trick to keep DRY code: replace each value temporarily with a\n # 0, and use valid_square method with original value to determine\n # if every square is valid\n self.puzzle[row][col] = 0\n valid = self.valid_square(row, col, val)\n self.puzzle[row][col] = val\n \n # If not a valid value for square, return False\n if not valid:\n return False\n return True",
"def solveOneStep(self):\n ### Student code goes here\n return True"
] | [
"0.7626083",
"0.7582729",
"0.7577563",
"0.7572323",
"0.73576117",
"0.73576117",
"0.73576117",
"0.73108906",
"0.7260244",
"0.7226423",
"0.7170689",
"0.70954806",
"0.7050868",
"0.69759893",
"0.6931749",
"0.68873924",
"0.6871832",
"0.68437505",
"0.6831438",
"0.679917",
"0.6769061",
"0.6705766",
"0.66316956",
"0.6628182",
"0.6628182",
"0.6628182",
"0.6538908",
"0.6513031",
"0.64966977",
"0.6489818"
] | 0.7977091 | 0 |
! Number of iterations it took the solver to converge. Number of iterations. | def number_of_iterations(self) -> int:
return self._solution.info.iter | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def number_of_iterations(self) -> int:\n pass",
"def number_of_iterations(self):\n return self._solution[\"iterations\"]",
"def number_of_iterations(self):\n return self._solution.nit",
"def number_of_iterations(self) -> int:\n return self._stats[\"iter_count\"]",
"def iterations(self):\n i = 0\n stateVectorConv = self.stateVectorConvThreshold * 1.0e6\n n = len(self.model.stateVector)\n self.answer = None\n \n while ((i < self.maxiter) \n and (stateVectorConv > self.stateVectorConvThreshold)\n ):\n \n F, K = self.model()\n \n if np.any(np.isnan(F)) or np.any(np.isnan(K)):\n m = \"Iteration {0} failure of model.\"\n raise OptimalEstimationException(m.format(i))\n \n if self.model.verbose > 0:\n self.model.plot(i+1, stateVectorConv)\n \n try:\n self.DecomposeJacobian(K)\n except np.linalg.LinAlgError:\n m = \"Iteration {0} failure in decomposition.\"\n raise OptimalEstimationException(m.format(i))\n \n statevectorOffset = (self.V.T * self.priorSinvh * \n np.matrix(np.array(self.model.stateVector) - np.array(self.model.prior) ).T)\n measurementOffset = (self.U.T * self.errSinvh * \n np.matrix(self.model.observation - F).T)\n \n newState = np.matrix((self.w * \n (measurementOffset.A1 + \n self.w * statevectorOffset.A1))/(self.w**2+1.0)).T\n newState = self.priorSh * self.V * newState\n newState = newState.A1 + self.model.prior\n \n stateVectorConv = ((np.matrix(newState - self.model.stateVector) * \n self.Sinv * np.matrix(newState - self.model.stateVector).T)/n)[0,0]\n self.model.stateVector = newState\n\n if i == 0:\n \n stateVectorConv = self.stateVectorConvThreshold * 1.0e6\n \n print('cost Function for iteration {}:'.format(i), self.costFunction)\n\n i += 1\n \n F, K = self.model()\n if self.model.verbose > 0:\n self.model.plot(i+1, stateVectorConv)\n \n try:\n self.DecomposeJacobian(K)\n except np.linalg.LinAlgError:\n raise OptimalEstimationException(\"Failure in decomposition.\")\n \n Wplus2 = np.matrix(np.diag(1.0/(self.w**2+1.0)))\n self.model.covariance = (self.priorSh * self.V * Wplus2 * \n self.V.T * self.priorSh)\n \n\n \n return i, stateVectorConv",
"def __len__(self):\n return self.nb_iterations",
"def _calculateIterations(self):\n #iterations = self.nb_images/self.batchsize\n imgs = self.protofile.nb_test()\n batch = self.protofile.batch_test()\n iterations = imgs/batch\n if imgs % batch != 0:\n iterations += 1\n return iterations",
"def getNIterations(self):\n return self.getOrDefault(self.nIterations)",
"def getNIterations(self):\n return self.getOrDefault(self.nIterations)",
"def number_of_solutions(self):\n return len(self._solutions)",
"def num_trials(self):",
"def iterations_in_epoch(self):\n if self._cur_epoch_itr is not None:\n return self._cur_epoch_itr.count\n elif self._next_epoch_itr is not None:\n return self._next_epoch_itr.count\n return 0",
"def converged(self) -> bool:",
"def converged(self) -> bool:",
"def converged(self) -> bool:",
"def min_num_iterations_():\n rows, cols = map_shape\n error = 1\n it = 0\n minErr = 1e-4\n while (error > minErr):\n bkp_utilities = utilities.copy()\n update_utils(utilities, map_shape, map_arr, rewards, final_arr, actions, gamma)\n diff = [(bkp_utilities[(r,c)] - utilities[(r,c)]) for r in range(rows) for c in range(cols)]\n error = np.sqrt(np.dot(diff, diff))\n it += 1\n return it",
"def num_solution(self):\r\n\r\n m = float(self.mass) / self.nu_m\r\n c = self.light_vel\r\n p1 = 0.0\r\n x1 = 0.0\r\n self.xn_track.append(x1)\r\n self.vn.append(0.0)\r\n e = m * c * c\r\n self.en.append(e)\r\n for i in range(1, len(self.obs.obt_g)):\r\n dt = self.t[i] - self.t[i - 1]\r\n ddt = float(self.obs.obt[i] - self.obs.obt[i - 1])\r\n qe = 1 / self.nu_m * (self.nu_t * self.nu_t / self.nu_x) \\\r\n * 1.0 / float(self.size_tick * self.size_tick)\r\n\r\n # print \"qE=\", qe\r\n\r\n p2 = p1 + qe * dt\r\n self.vn.append(p2 / math.sqrt(m ** 2 + (p2 / c) ** 2))\r\n e = e + qe * (self.x[i] - self.x[i - 1])\r\n self.en.append(e)\r\n v = p2 / math.sqrt(m ** 2 + (p2 / c) ** 2)\r\n x2 = x1 + v * dt\r\n self.xn_track.append(x2)\r\n p1 = p2\r\n x1 = x2\r\n print 'Numerical solution of the differential equation of motion'",
"def converge(self,max_iters=0x10):\n for i in range(max_iters):\n self.iter_all()\n print(\".\",end=\"\",flush=True)\n if self.verify():\n print(\"\\nReached correct succ and pred + fingers.\")\n return\n\n print(\"\\nmax_iters acheived.\")",
"def n_timesteps(self) -> int:\n return len(self.time)",
"def get_max_iters():\n return 2000",
"def get_iterations_made(self):\n return self.iterations_made",
"def n_diff(self):\n return 1 + int(self.differential)",
"def get_iterations(train_length: int, batch_size: int, epochs: int) -> int:\n return train_length // batch_size * epochs",
"def number_of_steps(self) -> int:\n return len(self.step_points)",
"def test_iterations(self):\n grover = Grover(oracle=self._oracle, good_state=['111'], iterations=2)\n ret = grover.run(self._sv)\n self.assertTrue(Operator(ret['circuit']).equiv(Operator(self._expected)))\n\n grover = Grover(oracle=self._oracle, good_state=['111'], iterations=[1, 2, 3])\n ret = grover.run(self._sv)\n self.assertTrue(ret.oracle_evaluation)\n self.assertIn(ret.top_measurement, ['111'])",
"def nb_triples(self) -> int:\n return 0",
"def get_iter_num(self):\n\tif len(self.cost) > 0:\n first_key = list(self.cost.keys())[0]\n num = len(self.cost[first_key]) - 1\n\telse:\n\t first_key = list(self.prim_var.keys())[0]\n num = len(self.prim_var[first_key]) - 1\n\treturn num",
"def setNumIterations(*argv):",
"def finalize(self, niter: Optional[int] = None, verbose: bool = False) -> 'LaSVM':\n\n niter = niter or self.niter\n\n tqdm_bar = tqdm(total=niter) if verbose else None\n broke_loop = False\n\n for _ in range(niter):\n self._reprocess()\n\n if self.delta <= self.tol:\n broke_loop = True\n break\n\n if verbose:\n tqdm_bar.update(1)\n\n if not broke_loop:\n print(f'Warning: delta did not converge below tol in {niter} iterations')\n\n if verbose:\n tqdm_bar.update(tqdm_bar.total - tqdm_bar.n)\n tqdm_bar.close()\n\n return self",
"def num_points_sweep(self, start, stop, step):\r\n return(abs((stop - start)//step) + 1)"
] | [
"0.77124375",
"0.7194317",
"0.71833915",
"0.6858536",
"0.6782175",
"0.652002",
"0.648363",
"0.63899773",
"0.63899773",
"0.63322115",
"0.62597173",
"0.6249974",
"0.6233827",
"0.6233827",
"0.6233827",
"0.61024827",
"0.60953677",
"0.59812546",
"0.5980235",
"0.5978103",
"0.5887715",
"0.5885286",
"0.5862297",
"0.5834781",
"0.58025175",
"0.57969266",
"0.57865894",
"0.57707053",
"0.57692957",
"0.5767247"
] | 0.78494585 | 0 |
! Setup the cvxopt solver interface. solver_settings Settings passed to the CVXOPT solver. The instance of the solve (i.e. self). | def setup(self, solver_settings: Dict = {}):
assert self.opt_type in QP_COST, "CVXOPT cannot solve this problem"
## Input to the solver
self._solver_input = solver_settings
self._reset_parameters()
return self | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def setup(self, solver_name: str, solver_options: Dict = {}):\n # Setup problem\n x = self.opt.decision_variables.vec()\n p = self.opt.parameters.vec()\n\n problem = {\n \"x\": x,\n \"p\": p,\n \"f\": self.opt.f(x, p),\n }\n\n # Setup constraints\n\n ## Lower bound on constraints.\n self._lbg = None\n\n ## Upper bound on constraints\n self._ubg = None\n\n if self.opt_type in CONSTRAINED_OPT:\n problem[\"g\"] = self.opt.v(x, p)\n self._lbg = self.opt.lbv\n self._ubg = self.opt.ubv\n\n # Get solver interface\n if (solver_name in self.qp_solvers) and not self.opt.has_discrete_variables():\n sol = cs.qpsol\n elif (solver_name in self.nlp_solvers) or (solver_name in self.mi_solvers):\n sol = cs.nlpsol\n else:\n raise ValueError(\n f\"solver '{solver_name}' does not support this problem type\"\n )\n\n # Check for discrete variables\n if self.opt.has_discrete_variables():\n solver_options[\"discrete\"] = self.opt.decision_variables.discrete()\n\n # Initialize solver\n\n ## Instance of the CasADi solver.\n self._solver = sol(\"solver\", solver_name, problem, solver_options)\n\n return self",
"def setup_solver(self):\n option = Options()\n if logger.getEffectiveLevel() == logging.DEBUG:\n # option.printLevel = PrintLevel.HIGH\n option.printLevel = PrintLevel.NONE\n else:\n option.printLevel = PrintLevel.NONE\n self.solver_minimizing = SQProblem(self.nV, self.nC)\n self.solver_minimizing.setOptions(option)\n self.solver_maximizing = SQProblem(self.nV, self.nC)\n self.solver_maximizing.setOptions(option)\n\n self.solver_minimizing_recent_index = -2\n self.solver_maximizing_recent_index = -2",
"def office_setup_solver(parser, args, params):\n parser.parse_known_args(args)\n control.setup_solver(params)",
"def cvxpy_solver(self, verbose=False):\n self.gamma = self._gamma_from_drawdown_control()\n\n objective = 0\n constr = []\n\n # weights variable depends on whether there is a risk-free asset in data\n if self.rf_included is True:\n # variable with shape h+1 predictions so first row\n # can be the known (non-variable) portfolio weight at time t\n weights = cp.Variable(shape=(self.n_preds + 1, self.n_assets))\n else:\n # Set rf to zero in all preds and cov\n self.rets = np.insert(self.rets, self.n_assets, 0, axis=1)\n self.cov = np.insert(self.cov, self.n_assets, 0, axis=-2)\n self.cov = np.insert(self.cov, self.n_assets, 0, axis=-1) # Has to be done in two steps for cov due to dims\n self.start_weights = np.append(self.start_weights, 0)\n\n weights = cp.Variable(shape=(self.n_preds + 1, self.n_assets+1))\n rf_zero_weights = np.zeros(shape=self.n_preds)\n constr += [weights[1:, -1] == 0] # Keep rf pos at zero since it non-present in this case\n\n\n # Loop through each row in the weights variable and construct the optimization problem\n # Note this loop is very cpu-light since no actual computations takes place inside it\n for t in range(1, weights.shape[0]):\n # sum problem objectives. Weights are shifted 1 period forward compared to self.rets\n # Concatenates objective and constraints in lists\n objective += self.single_period_objective_func(weights[t], weights[t-1], self.rets[t-1], self.cov[t-1])\n constr += self.single_period_constraints(weights[t]) # Concatenate constraints\n\n constr += [weights[0] == self.start_weights] # first weights are fixed at known current portfolio\n\n prob = cp.Problem(cp.Maximize(objective), constr) # Construct maximization problem\n prob.solve(solver=cp.ECOS, verbose=verbose)\n\n if self.rf_included is True:\n opt_var = weights.value\n else:\n opt_var = weights.value[:, :-1]\n\n if verbose is True:\n print(\"Shape of var: \", opt_var.shape)\n temp_df = pd.DataFrame(opt_var).round(3)\n temp_df['sum_weights'] = np.sum(opt_var, axis=1)\n print(temp_df)\n\n return opt_var[1:] # Discard first row which is not a variable.",
"def _set_solver(self):\n self.solver = Solver.select_solver(self.method, self.solver_args)\n if self.method.lower()==\"elastic-net\":\n self.solver.elements=self.basis.elements",
"def __init__(self, weight, n_bits, initial_treg_factor=1e-3, solver=\"SCS\"):\n\n self.exactly_zero = bool(weight == n_bits)\n self.n_bits = n_bits\n self.n = int(2**n_bits)\n self.weight = weight\n self.dim = n_parameters(weight, n_bits)\n self.solver = solver\n self.initial_treg_factor = initial_treg_factor\n self.warning_msg = None\n\n # Hold values *separate* from cvxpy variables as we sometimes need to revert\n # cvxpy optimizations which actually move values in a way that gives a *worse*\n # objective function.\n self.t_params = _np.zeros(self.dim)\n\n # cvxpy parameters\n self.P = _cp.Parameter(shape=(self.n,), nonneg=True, value=_np.zeros(self.n))\n self.Q = _cp.Parameter(shape=(self.n,), nonneg=True, value=_np.zeros(self.n))\n\n if weight == 0: return # special case; nothing more needed\n\n # Initialze a regularization factor to keep the optimizer from putting large elements\n # in T that move weight between near-zero elements of both p and q. We might need\n # to adjust this later, so make it a parameter.\n self.Treg_factor = _cp.Parameter(nonneg=True, value=self.initial_treg_factor)\n\n # Build the basis and the constrain matrix - the basis used to construct the T vector\n self.t_basis, self.cons = build_basis(self.weight, self.n_bits)\n\n self._build_problem()",
"def setup(self, use_warm_start, settings={}):\n assert self.opt_type in QP_COST, \"OSQP cannot solve this type of problem\"\n self.use_warm_start = use_warm_start\n self._setup_input = settings\n if self.opt_type in CONSTRAINED_OPT:\n self._setup_input[\"u\"] = np.inf * np.ones(self.opt.nk + self.opt.na)\n self._reset_parameters()\n return self",
"def __init__(self, optimization: Optimization, error_on_fail: bool = False):\n\n ## Instance of the optimization problem.\n self.opt = optimization\n\n ## Initial guess for the optimization problem (set using reset_initial_seed).\n self.x0 = cs.DM.zeros(optimization.nx)\n\n ## Parameter vector.\n self.p = cs.DM.zeros(optimization.np)\n\n ## Parameter dictionary.\n self._p_dict = {}\n\n ## When True, after solve() is called, if the solver did not converge then a RuntimeError is thrown.\n self._error_on_fail = error_on_fail\n\n ## Solution container\n self._solution = None",
"def setup(\n self,\n method: str = \"SLSQP\",\n tol: Union[None, float] = None,\n options: Union[None, Dict] = None,\n ):\n\n # Input check\n if self.opt_type in CONSTRAINED_OPT and (\n method not in ScipyMinimizeSolver.methods_handle_constraints\n ):\n raise TypeError(\n f\"optimization problem has constraints, the method '{method}' is not suitable\"\n )\n\n # Setup class attributes\n\n ## Container for the statistics.\n self._stats = None\n\n ## Method name.\n self.method = method\n\n # Setup minimize input parameters\n\n ## Input to the minimize method\n self.minimize_input = {\n \"fun\": self.f,\n \"method\": method,\n \"x0\": self.x0.toarray().flatten(),\n }\n\n if tol is not None:\n self.minimize_input[\"tol\"] = tol\n\n if options is not None:\n self.minimize_input[\"options\"] = options\n\n if method in ScipyMinimizeSolver.methods_req_jac:\n self.minimize_input[\"jac\"] = self.jac\n\n if method in ScipyMinimizeSolver.methods_req_hess:\n self.minimize_input[\"hess\"] = self.hess\n\n ## Constraints definition passed to the minimize method.\n self._constraints = {}\n if method in ScipyMinimizeSolver.methods_handle_constraints:\n if method != \"trust-constr\":\n if self.opt_type in CONSTRAINED_OPT:\n self._constraints[\"constr\"] = {\n \"type\": \"ineq\",\n \"fun\": self.v,\n \"jac\": self.dv,\n }\n else:\n if self.opt.nk:\n self._constraints[\"k\"] = LinearConstraint(\n A=csc_matrix(self.opt.M(self.p).toarray()),\n lb=-self.opt.c(self.p).toarray().flatten(),\n ub=self.opt.inf * np.ones(self.opt.nk),\n )\n\n if self.opt.na:\n eq = -self.opt.b(self.p).toarray().flatten()\n self._constraints[\"a\"] = LinearConstraint(\n A=csc_matrix(self.opt.A(self.p).toarray()),\n lb=eq,\n ub=eq,\n )\n\n if self.opt.ng:\n self._constraints[\"g\"] = NonlinearConstraint(\n fun=self.g,\n lb=np.zeros(self.opt.ng),\n ub=self.opt.inf * np.ones(self.opt.ng),\n jac=self.dg,\n hess=self.ddg,\n )\n\n if self.opt.nh:\n self._constraints[\"h\"] = NonlinearConstraint(\n fun=self.h,\n lb=np.zeros(self.opt.nh),\n ub=np.zeros(self.opt.nh),\n jac=self.dh,\n hess=self.ddh,\n )\n\n return self",
"def CreateSolverWrapper(settings, solver_name):\n return base_factory.Create(settings, [solver_name], \"KratosMultiphysics.CoSimulationApplication\")",
"def office_prepare_solver(parser, args, params):\n parser.parse_known_args(args)\n control.prepare_solver(params)",
"def solve(self, solver):\n solver.solve()",
"def __init__(self, opts: dict, solver_opts: dict):\n self.name = opts.get(\"name\", \"Undefined\") # Name of the problem\n self.gp = opts.get(\"grid_points\") # Number of grid points\n self.nadir_p = opts.get(\"nadir_points\") # Nadir points\n self.eps = opts.get(\"penalty_weight\", 1e-3) # Penalty weight\n self.round = opts.get(\"round_decimals\", 9) # Decimal places to round to\n self.nadir_r = opts.get(\"nadir_ratio\", 1) # Nadir ratio\n self.logdir = opts.get(\"logging_folder\", \"logs\") # Folder to save logs\n self.early_exit = opts.get(\"early_exit\", True) # Whether to enable early exit\n self.bypass = opts.get(\"bypass_coefficient\", True) # Whether to enable bypass coefficient\n self.flag = opts.get(\"flag_array\", True) # Whether to use flag array\n self.cpu_count = opts.get(\"cpu_count\", cpu_count()) # Number of CPUs to use\n self.redivide_work = opts.get(\"redivide_work\", True) # Whether to redivide work\n self.model_fn = opts.get(\"pickle_file\", \"model.p\") # Pickle file name\n self.shared_flag = opts.get(\"shared_flag\", True) # Whether to use shared flag array\n self.output_excel = opts.get(\"output_excel\", True) # Whether to output to Excel\n self.process_logging = opts.get(\"process_logging\", False) # Whether to enable process logging\n self.process_timeout = opts.get(\"process_timeout\", None) # Timeout for processes\n self.solver_name = opts.get(\"solver_name\", \"gurobi\") # Name of solver\n self.solver_io = opts.get(\"solver_io\", \"python\") # IO mode of solver\n\n self.solver_opts = solver_opts # Solver options\n self.solver_opts[\"MIPGap\"] = solver_opts.get(\"MIPGap\", 0.0) # MIP gap\n self.solver_opts[\"NonConvex\"] = solver_opts.get(\"NonConvex\", 2) # Nonconvex setting\n\n # Remove None values from dict when user has overriden them\n for key, value in dict(self.solver_opts).items():\n if value is None or value:\n del self.solver_opts[key]\n\n self.time_created = time.strftime(\"%Y%m%d-%H%M%S\") # Time the options object was created\n self.log_name = self.name + \"_\" + str(self.time_created) # Name of log file",
"def __solve(self) -> None:\n pyo.TransformationFactory(\"contrib.detect_fixed_vars\").apply_to(self.model) # type: ignore\n pyo.TransformationFactory(\"contrib.deactivate_trivial_constraints\").apply_to(self.model) # type: ignore\n\n # initialise the solver object\n self._logger.debug(\"[ModelSolver] Solver object initiated...\")\n solver = Config.OPTIMISATION_MODEL_CONFIG['SOLVER_TYPE']\n opt = pyo.SolverFactory(solver)\n if Config.OPTIMISATION_MODEL_CONFIG['SOLVER_OPTION'].get(solver) is not None:\n for k, v in Config.OPTIMISATION_MODEL_CONFIG['SOLVER_OPTION'].get(solver).items():\n opt.options[k] = v\n\n try:\n start_time = datetime.now()\n self._logger.debug(\"[ModelSolver] Solver starting...\")\n results = opt.solve(self.model, tee=True)\n self.results = results\n end_time = datetime.now()\n self._logger.info(f\"[ModelSolver] Solver completed in {end_time - start_time}.\")\n except Exception as e:\n raise Exception(f\"Model optimisation failed with {solver} with error message {e}.\")\n\n if (results.solver.status == SolverStatus.ok) and (results.solver.termination_condition == TerminationCondition.optimal):\n self._logger.info(\"Solution is feasible and optimal\")\n results.write()\n elif results.solver.termination_condition == TerminationCondition.infeasible:\n raise ValueError(\"Model optimisation resulted into an infeasible solution\")\n\n self.model.optimised = True",
"def set_solver(self, solver):\n self.solver = solver\n solver.associate_with_model(self)\n self.set_free_variable(0) # A reasonable initial assumption; can be overridden by simulations",
"def test_init(self):\n # setup test scenario\n _kwargs = {'nsteps': 5}\n # call function to test\n test_object = ScipySolveIvpSolver(**_kwargs)\n # verify the expected results\n assert test_object._solver_kwargs == _kwargs, 'unexpected additional arguments. Keep in mind None and {}'",
"def setSolverTau(*argv):",
"def run(self, problem):\n\n self.pyopt_solution = None\n rel = problem.root._probdata.relevance\n\n # Metadata Setup\n self.metadata = create_local_meta(None, self.options['optimizer'])\n self.iter_count = 0\n update_local_meta(self.metadata, (self.iter_count,))\n\n # Initial Run\n with problem.root._dircontext:\n problem.root.solve_nonlinear(metadata=self.metadata)\n\n opt_prob = Optimization(self.options['title'], self._objfunc)\n\n # Add all parameters\n param_meta = self.get_desvar_metadata()\n self.indep_list = indep_list = list(param_meta)\n param_vals = self.get_desvars()\n\n for name, meta in iteritems(param_meta):\n opt_prob.addVarGroup(name, meta['size'], type='c',\n value=param_vals[name],\n lower=meta['lower'], upper=meta['upper'])\n\n opt_prob.finalizeDesignVariables()\n\n # Figure out parameter subsparsity for paramcomp index connections.\n # sub_param_conns is empty unless there are some index conns.\n # full_param_conns gets filled with the connections to the entire\n # parameter so that those params can be filtered out of the sparse\n # set if the full path is also relevant\n sub_param_conns = {}\n full_param_conns = {}\n for name in indep_list:\n pathname = problem.root.unknowns.metadata(name)['pathname']\n sub_param_conns[name] = {}\n full_param_conns[name] = set()\n for target, info in iteritems(problem.root.connections):\n src, indices = info\n if src == pathname:\n if indices is not None:\n # Need to map the connection indices onto the desvar\n # indices if both are declared.\n dv_idx = param_meta[name].get('indices')\n indices = set(indices)\n if dv_idx is not None:\n indices.intersection_update(dv_idx)\n ldv_idx = list(dv_idx)\n mapped_idx = [ldv_idx.index(item) for item in indices]\n sub_param_conns[name][target] = mapped_idx\n else:\n sub_param_conns[name][target] = indices\n else:\n full_param_conns[name].add(target)\n\n # Add all objectives\n objs = self.get_objectives()\n self.quantities = list(objs)\n self.sparsity = OrderedDict()\n self.sub_sparsity = OrderedDict()\n for name in objs:\n opt_prob.addObj(name)\n self.sparsity[name] = self.indep_list\n\n # Calculate and save gradient for any linear constraints.\n lcons = self.get_constraints(lintype='linear').keys()\n if len(lcons) > 0:\n self.lin_jacs = problem.calc_gradient(indep_list, lcons,\n return_format='dict')\n #print(\"Linear Gradient\")\n #print(self.lin_jacs)\n\n # Add all equality constraints\n econs = self.get_constraints(ctype='eq', lintype='nonlinear')\n con_meta = self.get_constraint_metadata()\n self.quantities += list(econs)\n\n self.active_tols = {}\n for name in self.get_constraints(ctype='eq'):\n meta = con_meta[name]\n size = meta['size']\n lower = upper = meta['equals']\n\n # Sparsify Jacobian via relevance\n rels = rel.relevant[name]\n wrt = rels.intersection(indep_list)\n self.sparsity[name] = wrt\n\n if meta['linear']:\n opt_prob.addConGroup(name, size, lower=lower, upper=upper,\n linear=True, wrt=wrt,\n jac=self.lin_jacs[name])\n else:\n\n jac = self._build_sparse(name, wrt, size, param_vals,\n sub_param_conns, full_param_conns, rels)\n opt_prob.addConGroup(name, size, lower=lower, upper=upper,\n wrt=wrt, jac=jac)\n\n active_tol = meta.get('active_tol')\n if active_tol:\n self.active_tols[name] = active_tol\n\n # Add all inequality constraints\n incons = self.get_constraints(ctype='ineq', lintype='nonlinear')\n self.quantities += list(incons)\n\n for name in self.get_constraints(ctype='ineq'):\n meta = con_meta[name]\n size = meta['size']\n\n # Bounds - double sided is supported\n lower = meta['lower']\n upper = meta['upper']\n\n # Sparsify Jacobian via relevance\n rels = rel.relevant[name]\n wrt = rels.intersection(indep_list)\n self.sparsity[name] = wrt\n\n if meta['linear']:\n opt_prob.addConGroup(name, size, upper=upper, lower=lower,\n linear=True, wrt=wrt,\n jac=self.lin_jacs[name])\n else:\n\n jac = self._build_sparse(name, wrt, size, param_vals,\n sub_param_conns, full_param_conns, rels)\n opt_prob.addConGroup(name, size, upper=upper, lower=lower,\n wrt=wrt, jac=jac)\n\n active_tol = meta.get('active_tol')\n if active_tol is not None:\n self.active_tols[name] = active_tol\n\n # Instantiate the requested optimizer\n optimizer = self.options['optimizer']\n try:\n _tmp = __import__('pyoptsparse', globals(), locals(), [optimizer], 0)\n opt = getattr(_tmp, optimizer)()\n except ImportError:\n msg = \"Optimizer %s is not available in this installation.\" % \\\n optimizer\n raise ImportError(msg)\n\n #Set optimization options\n for option, value in self.opt_settings.items():\n opt.setOption(option, value)\n\n self._problem = problem\n self.opt_prob = opt_prob\n\n # Execute the optimization problem\n if self.options['gradient method'] == 'pyopt_fd':\n\n # Use pyOpt's internal finite difference\n fd_step = problem.root.deriv_options['step_size']\n sol = opt(opt_prob, sens='FD', sensStep=fd_step, storeHistory=self.hist_file)\n\n elif self.options['gradient method'] == 'snopt_fd':\n if self.options['optimizer']=='SNOPT':\n\n # Use SNOPT's internal finite difference\n fd_step = problem.root.deriv_options['step_size']\n sol = opt(opt_prob, sens=None, sensStep=fd_step, storeHistory=self.hist_file)\n\n else:\n msg = \"SNOPT's internal finite difference can only be used with SNOPT\"\n raise Exception(msg)\n else:\n\n # Use OpenMDAO's differentiator for the gradient\n sol = opt(opt_prob, sens=self._gradfunc, storeHistory=self.hist_file)\n\n self._problem = None\n\n # Print results\n if self.options['print_results']:\n print(sol)\n\n # Pull optimal parameters back into framework and re-run, so that\n # framework is left in the right final state\n dv_dict = sol.getDVs()\n for name in indep_list:\n val = dv_dict[name]\n self.set_desvar(name, val)\n\n with self.root._dircontext:\n self.root.solve_nonlinear(metadata=self.metadata)\n\n # Save the most recent solution.\n self.pyopt_solution = sol\n try:\n exit_status = sol.optInform['value']\n self.exit_flag = 1\n if exit_status > 2: # bad\n self.exit_flag = 0\n except KeyError: #nothing is here, so something bad happened!\n self.exit_flag = 0",
"def _set_up_acq_opt(self):\n # First set up function to get maximum evaluations.\n if isinstance(self.options.acq_opt_max_evals, int):\n if self.options.acq_opt_max_evals > 0:\n self.get_acq_opt_max_evals = lambda t: self.options.acq_opt_max_evals\n else:\n self.get_acq_opt_max_evals = None\n else: # In this case, the user likely passed a function here.\n self.get_acq_opt_max_evals = self.options.acq_opt_max_evals\n # Additional set up based on the specific optimisation procedure\n if self.options.acq_opt_criterion == 'direct':\n self._set_up_acq_opt_direct()\n elif self.options.acq_opt_criterion == 'rand':\n self._set_up_acq_opt_rand()\n else:\n raise NotImplementedError('Not implemented acquisition optimisation for %s yet.'%(\n self.options.acq_opt_criterion))",
"def init_solver(self, cost_func=None, opt_x0=False, init_uncertainty=False):\n self.cost_func = cost_func\n self.opt_x0 = opt_x0\n self.init_uncertainty = init_uncertainty\n\n u_0 = MX.sym(\"init_control\", (self.n_u, 1))\n k_ff_all = MX.sym(\"feed-forward control\", (self.n_safe - 1, self.n_u))\n g = []\n lbg = []\n ubg = []\n g_name = []\n\n p_0 = MX.sym(\"initial state\", (self.n_s, 1))\n q_0 = None\n k_fb_0 = None\n if init_uncertainty:\n q_0 = MX.sym(\"init uncertainty\", (self.n_s, self.n_s))\n k_fb_0 = MX.sym(\"init feddback control matrix\", (self.n_u, self.n_s))\n\n k_fb_safe = MX.sym(\"feedback matrices\",\n (self.n_safe - 1, self.n_s * self.n_u))\n\n p_all, q_all, gp_sigma_pred_safe_all = cas_multistep(p_0, u_0, k_fb_safe, k_ff_all,\n self.ssm_forward, self.l_mu,\n self.l_sigma,\n self.beta_safety, self.a,\n self.b,\n self.lin_trafo_gp_input, q_0, k_fb_0)\n\n # generate open_loop trajectory function [vertcat(x_0,u_0)],[f_x])\n\n if init_uncertainty:\n self._f_multistep_eval = cas.Function(\"safe_multistep\",\n [p_0, u_0, k_fb_safe, k_ff_all, q_0, k_fb_0],\n [p_all, q_all, gp_sigma_pred_safe_all])\n else:\n self._f_multistep_eval = cas.Function(\"safe_multistep\",\n [p_0, u_0, k_fb_safe, k_ff_all],\n [p_all, q_all, gp_sigma_pred_safe_all])\n\n g_safe, lbg_safe, ubg_safe, g_names_safe = self.generate_safety_constraints(\n p_all, q_all, u_0, k_fb_safe, k_ff_all, q_0, k_fb_0)\n g = vertcat(g, g_safe)\n lbg += lbg_safe\n ubg += ubg_safe\n g_name += g_names_safe\n\n # Generate performance trajectory\n if self.n_perf > 1:\n k_ff_perf, k_fb_perf, k_ff_perf_traj, k_fb_perf_traj, mu_perf, sigma_perf, gp_sigma_pred_perf_all, g_perf, lbg_perf, ubg_perf, g_names_perf = self._generate_perf_trajectory_casadi(\n p_0, u_0, k_ff_all, k_fb_safe, self.a, self.b, self.lin_trafo_gp_input)\n g = vertcat(g, g_perf)\n lbg += lbg_perf\n ubg += ubg_perf\n g_name += g_names_perf\n else:\n k_ff_perf = np.array([])\n k_fb_perf = np.array([])\n k_fb_perf_traj = np.array([])\n k_ff_perf_traj = np.array([])\n mu_perf = np.array([])\n sigma_perf = np.array([])\n gp_sigma_pred_perf_all = None\n\n cost = self.generate_cost_function(p_0, u_0, p_all, q_all, mu_perf, sigma_perf,\n k_ff_all, k_fb_safe, gp_sigma_pred_safe_all,\n k_fb_perf=k_fb_perf_traj,\n k_ff_perf=k_ff_perf_traj,\n gp_pred_sigma_perf=gp_sigma_pred_perf_all,\n custom_cost_func=cost_func)\n\n if self.opt_x0:\n opt_vars = vertcat(p_0, u_0, k_ff_perf, k_ff_all.reshape((-1, 1)))\n opt_params = vertcat(k_fb_safe.reshape((-1, 1)), k_fb_perf.reshape((-1, 1)))\n else:\n opt_vars = vertcat(u_0, k_ff_perf, k_ff_all.reshape((-1, 1)))\n opt_params = vertcat(p_0, k_fb_safe.reshape((-1, 1)), k_fb_perf.reshape((-1, 1)))\n\n if self.init_uncertainty:\n opt_params = vertcat(opt_params, q_0.reshape((-1, 1)), k_fb_0.reshape((-1, 1)))\n\n prob = {'f': cost, 'x': opt_vars, 'p': opt_params, 'g': g}\n\n opt = self.opts_solver\n if opt is None:\n opt = {'error_on_fail': False,\n 'ipopt': {'hessian_approximation': 'limited-memory', \"max_iter\": 100,\n \"expect_infeasible_problem\": \"no\", \\\n 'acceptable_tol': 1e-4, \"acceptable_constr_viol_tol\": 1e-5,\n \"bound_frac\": 0.5, \"start_with_resto\": \"no\",\n \"required_infeasibility_reduction\": 0.85,\n \"acceptable_iter\": 8}} # ipopt\n\n # opt = {'max_iter':120,'hessian_approximation':'limited-memory'}#,\"c1\":5e-4} #sqpmethod #,\n # opt = {'max_iter':120,'qpsol':'qpoases'}\n\n solver = cas.nlpsol('solver', 'ipopt', prob, opt)\n # solver = cas.nlpsol('solver','sqpmethod',prob,opt)\n # solver = cas.nlpsol('solver','blocksqp',prob,opt)\n\n self.solver = solver\n self.lbg = lbg\n self.ubg = ubg\n self.solver_initialized = True\n self.g = g\n self.g_name = g_name",
"def kktsolver(x, z, W):\n\n if debug:\n logger.debug(\"Setup kkt solver\")\n logger.debug(\"W\")\n for key in W.keys():\n logger.debug(\"key: %s\" % (key,))\n logger.debug(W[key])\n\n H = hessian(x)\n if debug:\n logger.debug(\"diag H\")\n logger.debug(np.diag(H))\n _H = cvxopt.spdiag(list(np.diag(H))) if H is not None else None\n\n wdi = W[\"di\"]\n Wdi2 = cvxopt.spdiag(cvxopt.mul(wdi, wdi))\n\n S = G.T * Wdi2\n P = S * G\n\n Q = _H + P\n # now, do the cholesky decomposition of Q\n cvxopt.lapack.potrf(Q)\n\n if False and fn is not None:\n logger.debug(\"At setup f(x) = %d\" % (fn(np.array(list(x))),))\n\n def f(x, y, z):\n if False and fn is not None:\n logger.debug(\"f(x) = %d\" % (fn(np.array(list(x))),))\n try:\n # logger.debug(\"Compute x := S * z + x...\")\n cvxopt.blas.gemv(S, z, x, alpha=1.0, beta=1.0) # x = S * z + x\n cvxopt.lapack.potrs(Q, x)\n except BaseException as e:\n logger.debug(exception_to_string(sys.exc_info()))\n raise e\n cvxopt.blas.gemv(G, x, z, alpha=1.0, beta=-1.0) # z = _G * x - z\n z[:] = cvxopt.mul(wdi, z) # scaled z\n # raise NotImplementedError(\"Method Not implemented yet\")\n return f",
"def __init__(self, sparse_args=None, solve=True):\n self.solved = False\n self.sparse_args = sparse_args\n self.solved = False\n if solve: self.solve()",
"def solve(self):\n print(\"Attempting to solve problem instance with {} constraints\".format(len(self.constraints)))\n self.formulation.solve(solver='SCS')\n print(self.formulation.status)",
"def solve(self):\n print(\"Attempting to solve problem instance with {} constraints\".format(len(self.constraints)))\n self.formulation.solve(solver='SCS')\n print(self.formulation.status)",
"def solve(self):\n print(\"Attempting to solve problem instance with {} constraints\".format(len(self.constraints)))\n self.formulation.solve(solver='SCS')\n print(self.formulation.status)",
"def main():\n # Instantiate the data problem.\n data = create_data_model()\n solve_cvrp(data)",
"def solve_prep(self):\n\n par = self.par\n sol = self.sol\n\n # a. retirement\n sol.m_ret = np.zeros((par.T,par.Nm_ret))\n sol.c_ret = np.zeros((par.T,par.Nm_ret))\n sol.a_ret = np.zeros((par.T,par.Nm_ret))\n sol.inv_v_ret = np.zeros((par.T,par.Nm_ret))\n sol.inv_vm_ret = np.zeros((par.T,par.Nm_ret))\n sol.inv_vn_ret = np.zeros((par.T,par.Nm_ret))\n\n # b. working\n if par.solmethod == 'G2EGM':\n\n sol.c = np.zeros((par.T,par.Nn,par.Nm))\n sol.d = np.zeros((par.T,par.Nn,par.Nm))\n sol.inv_v = np.zeros((par.T,par.Nn,par.Nm))\n sol.inv_vm = np.zeros((par.T,par.Nn,par.Nm))\n sol.inv_vn = np.zeros((par.T,par.Nn,par.Nm))\n\n sol.ucon_c = np.zeros((par.T,par.Nn,par.Nm))\n sol.ucon_d = np.zeros((par.T,par.Nn,par.Nm))\n sol.ucon_v = np.zeros((par.T,par.Nn,par.Nm))\n\n sol.dcon_c = np.zeros((par.T,par.Nn,par.Nm))\n sol.dcon_d = np.zeros((par.T,par.Nn,par.Nm))\n sol.dcon_v = np.zeros((par.T,par.Nn,par.Nm))\n\n sol.acon_c = np.zeros((par.T,par.Nn,par.Nm))\n sol.acon_d = np.zeros((par.T,par.Nn,par.Nm))\n sol.acon_v = np.zeros((par.T,par.Nn,par.Nm))\n sol.con_c = np.zeros((par.T,par.Nn,par.Nm))\n sol.con_d = np.zeros((par.T,par.Nn,par.Nm))\n sol.con_v = np.zeros((par.T,par.Nn,par.Nm))\n\n sol.z = np.zeros((par.T,par.Nn,par.Nm))\n\n sol.w = np.zeros((par.T-1,par.Nb_pd,par.Na_pd))\n sol.wa = np.zeros((par.T-1,par.Nb_pd,par.Na_pd))\n sol.wb = np.zeros((par.T-1,par.Nb_pd,par.Na_pd))\n \n elif par.solmethod == 'NEGM':\n\n sol.c = np.zeros((par.T,par.Nn,par.Nm))\n sol.d = np.zeros((par.T,par.Nn,par.Nm))\n sol.inv_v = np.zeros((par.T,par.Nn,par.Nm))\n sol.inv_vn = np.zeros((0,0,0))\n sol.inv_vm = np.zeros((par.T,par.Nn,par.Nm))\n\n sol.w = np.zeros((par.T-1,par.Nb_pd,par.Na_pd))\n sol.wa = np.zeros((par.T-1,par.Nb_pd,par.Na_pd))\n sol.wb = np.zeros((0,0,0))\n \n sol.c_pure_c = np.zeros((par.T,par.Nb_pd,par.Nm))\n sol.inv_v_pure_c = np.zeros((par.T,par.Nb_pd,par.Nm))",
"def setup_method(self):\n self.x0 = (1.0, [1.0, 1.0])\n self.sol = (-0.195, np.array([-0.195, -0.1]))\n\n self.tol = 3 # number of decimal places\n\n self.niter = 100\n self.disp = False\n\n # fix random seed\n np.random.seed(1234)\n\n self.kwargs = {\"method\": \"L-BFGS-B\", \"jac\": True}\n self.kwargs_nograd = {\"method\": \"L-BFGS-B\"}",
"def solve(ctx):\n my_solver(ctx.obj['filename'])",
"def solve(self):\n # check for jacobian and set it if present and to be used\n if self.use_sparse:\n if self._use_jac and hasattr(self.problem,'sparse_jac'):\n jac = self.problem.sparse_jac\n else:\n jac = None\n else:\n if self._use_jac and hasattr(self.problem,'jac'):\n jac = self.problem.jac\n else:\n jac = None\n \n # Initialize solver and solve \n \n solved = False\n local_min = False\n\n res = N.zeros(self.x0.__len__())\n while (not solved) and self.reg_count < 2:\n try:\n if self._use_fscale:\n self.solver.KINSOL_init(self.func,self.x0,self.dim,jac,self.constraints,self.use_sparse,self.verbosity,self.norm_of_res,self.reg_param,self.fscale)\n else:\n self.solver.KINSOL_init(self.func,self.x0,self.dim,jac,self.constraints,self.use_sparse,self.verbosity,self.norm_of_res,self.reg_param,None)\n start = time.clock()\n res = self.solver.KINSOL_solve(not self._use_ls)\n stop = time.clock()\n self.exec_time += (stop - start)\n solved = True\n except KINError as error:\n if error.value == 42:\n # Try the heuristic\n if hasattr(self.problem, 'get_heuristic_x0'):\n print \"----------------------------------------------------\"\n print \" Solver stuck with zero step-length.\"\n print \"----------------------------------------------------\"\n print \"The following variables have start value zero\"\n print \"and min set to zero causing the zero step-lenght.\"\n print \"These settings are either set by default or by user.\"\n print \"\"\n\n self.x0 = self.problem.get_heuristic_x0()\n self.reg_count += 1\n \n print \"\"\n print \"This setting (start and min to zero) can often\"\n print \"cause problem when initializing the system. \"\n print \"\"\n print \"To avoid this the above variables have\"\n print \"their start attributes reset to one.\"\n print \"\"\n print \"Trying to solve the system again...\"\n else:\n raise KINSOL_Exception(\"Regularization failed due to constraints, tried getting heuristic initial guess but failed.\")\n \n\n elif (error.value == 2):\n print \"---------------------------------------------------------\"\n print \"\"\n print \" !!! WARNING !!!\"\n print \"\"\n print \" KINSOL has returned a result but the algorithm has converged\"\n print \" to a local minima, the initial values are NOT consistant!\"\n print \"\"\n print \"---------------------------------------------------------\"\n solved = True\n local_min = True\n else:\n # Other error, send onward as exception\n self.problem.check_constraints(res)\n raise KINSOL_Exception(error.msg[error.value])\n \n if not solved:\n self.solver.Free_KINSOL()\n raise KINSOL_Exception(\"Algorithm exited solution loop without finding a solution, please contact Assimulo support.\")\n\n if self.check_with_model:\n self.problem.check_constraints(res)\n if not local_min:\n print \"Problem sent to KINSOL solved.\"\n \n return res"
] | [
"0.6741288",
"0.6668914",
"0.6225039",
"0.59971553",
"0.598382",
"0.5691549",
"0.5664084",
"0.5635914",
"0.56130964",
"0.5586613",
"0.5578955",
"0.55714655",
"0.5536691",
"0.5519575",
"0.5506151",
"0.54988086",
"0.54008114",
"0.54007083",
"0.5390446",
"0.53623044",
"0.5329943",
"0.5301818",
"0.5292537",
"0.5292537",
"0.5292537",
"0.52680326",
"0.52616507",
"0.5259227",
"0.5242442",
"0.5228257"
] | 0.7961874 | 0 |
Setup the Scipy solver. method Type of solver. Default is "SLSQP". tol Tolerance for termination. When tol is specified, the selected minimization algorithm sets some relevant solverspecific tolerance(s) equal to tol. For detailed control, use solverspecific options. options A dictionary of solver options. The instance of the solve (i.e. self). | def setup(
self,
method: str = "SLSQP",
tol: Union[None, float] = None,
options: Union[None, Dict] = None,
):
# Input check
if self.opt_type in CONSTRAINED_OPT and (
method not in ScipyMinimizeSolver.methods_handle_constraints
):
raise TypeError(
f"optimization problem has constraints, the method '{method}' is not suitable"
)
# Setup class attributes
## Container for the statistics.
self._stats = None
## Method name.
self.method = method
# Setup minimize input parameters
## Input to the minimize method
self.minimize_input = {
"fun": self.f,
"method": method,
"x0": self.x0.toarray().flatten(),
}
if tol is not None:
self.minimize_input["tol"] = tol
if options is not None:
self.minimize_input["options"] = options
if method in ScipyMinimizeSolver.methods_req_jac:
self.minimize_input["jac"] = self.jac
if method in ScipyMinimizeSolver.methods_req_hess:
self.minimize_input["hess"] = self.hess
## Constraints definition passed to the minimize method.
self._constraints = {}
if method in ScipyMinimizeSolver.methods_handle_constraints:
if method != "trust-constr":
if self.opt_type in CONSTRAINED_OPT:
self._constraints["constr"] = {
"type": "ineq",
"fun": self.v,
"jac": self.dv,
}
else:
if self.opt.nk:
self._constraints["k"] = LinearConstraint(
A=csc_matrix(self.opt.M(self.p).toarray()),
lb=-self.opt.c(self.p).toarray().flatten(),
ub=self.opt.inf * np.ones(self.opt.nk),
)
if self.opt.na:
eq = -self.opt.b(self.p).toarray().flatten()
self._constraints["a"] = LinearConstraint(
A=csc_matrix(self.opt.A(self.p).toarray()),
lb=eq,
ub=eq,
)
if self.opt.ng:
self._constraints["g"] = NonlinearConstraint(
fun=self.g,
lb=np.zeros(self.opt.ng),
ub=self.opt.inf * np.ones(self.opt.ng),
jac=self.dg,
hess=self.ddg,
)
if self.opt.nh:
self._constraints["h"] = NonlinearConstraint(
fun=self.h,
lb=np.zeros(self.opt.nh),
ub=np.zeros(self.opt.nh),
jac=self.dh,
hess=self.ddh,
)
return self | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def setup_solver(self):\n option = Options()\n if logger.getEffectiveLevel() == logging.DEBUG:\n # option.printLevel = PrintLevel.HIGH\n option.printLevel = PrintLevel.NONE\n else:\n option.printLevel = PrintLevel.NONE\n self.solver_minimizing = SQProblem(self.nV, self.nC)\n self.solver_minimizing.setOptions(option)\n self.solver_maximizing = SQProblem(self.nV, self.nC)\n self.solver_maximizing.setOptions(option)\n\n self.solver_minimizing_recent_index = -2\n self.solver_maximizing_recent_index = -2",
"def setup(self, solver_name: str, solver_options: Dict = {}):\n # Setup problem\n x = self.opt.decision_variables.vec()\n p = self.opt.parameters.vec()\n\n problem = {\n \"x\": x,\n \"p\": p,\n \"f\": self.opt.f(x, p),\n }\n\n # Setup constraints\n\n ## Lower bound on constraints.\n self._lbg = None\n\n ## Upper bound on constraints\n self._ubg = None\n\n if self.opt_type in CONSTRAINED_OPT:\n problem[\"g\"] = self.opt.v(x, p)\n self._lbg = self.opt.lbv\n self._ubg = self.opt.ubv\n\n # Get solver interface\n if (solver_name in self.qp_solvers) and not self.opt.has_discrete_variables():\n sol = cs.qpsol\n elif (solver_name in self.nlp_solvers) or (solver_name in self.mi_solvers):\n sol = cs.nlpsol\n else:\n raise ValueError(\n f\"solver '{solver_name}' does not support this problem type\"\n )\n\n # Check for discrete variables\n if self.opt.has_discrete_variables():\n solver_options[\"discrete\"] = self.opt.decision_variables.discrete()\n\n # Initialize solver\n\n ## Instance of the CasADi solver.\n self._solver = sol(\"solver\", solver_name, problem, solver_options)\n\n return self",
"def setup_method(self):\n self.x0 = (1.0, [1.0, 1.0])\n self.sol = (-0.195, np.array([-0.195, -0.1]))\n\n self.tol = 3 # number of decimal places\n\n self.niter = 100\n self.disp = False\n\n # fix random seed\n np.random.seed(1234)\n\n self.kwargs = {\"method\": \"L-BFGS-B\", \"jac\": True}\n self.kwargs_nograd = {\"method\": \"L-BFGS-B\"}",
"def sparse_options(default_solver='spsolve',\n default_least_squares_solver='least_squares_lsmr' if HAVE_SCIPY_LSMR else 'least_squares_generic_lsmr',\n bicgstab_tol=1e-15,\n bicgstab_maxiter=None,\n spilu_drop_tol=1e-4,\n spilu_fill_factor=10,\n spilu_drop_rule='basic,area',\n spilu_permc_spec='COLAMD',\n spsolve_permc_spec='COLAMD',\n spsolve_keep_factorization=True,\n lgmres_tol=1e-5,\n lgmres_maxiter=1000,\n lgmres_inner_m=39,\n lgmres_outer_k=3,\n least_squares_lsmr_damp=0.0,\n least_squares_lsmr_atol=1e-6,\n least_squares_lsmr_btol=1e-6,\n least_squares_lsmr_conlim=1e8,\n least_squares_lsmr_maxiter=None,\n least_squares_lsmr_show=False,\n least_squares_lsqr_damp=0.0,\n least_squares_lsqr_atol=1e-6,\n least_squares_lsqr_btol=1e-6,\n least_squares_lsqr_conlim=1e8,\n least_squares_lsqr_iter_lim=None,\n least_squares_lsqr_show=False,\n pyamg_tol=1e-5,\n pyamg_maxiter=400,\n pyamg_verb=False,\n pyamg_rs_strength=('classical', {'theta': 0.25}),\n pyamg_rs_CF='RS',\n pyamg_rs_presmoother=('gauss_seidel', {'sweep': 'symmetric'}),\n pyamg_rs_postsmoother=('gauss_seidel', {'sweep': 'symmetric'}),\n pyamg_rs_max_levels=10,\n pyamg_rs_max_coarse=500,\n pyamg_rs_coarse_solver='pinv2',\n pyamg_rs_cycle='V',\n pyamg_rs_accel=None,\n pyamg_rs_tol=1e-5,\n pyamg_rs_maxiter=100,\n pyamg_sa_symmetry='hermitian',\n pyamg_sa_strength='symmetric',\n pyamg_sa_aggregate='standard',\n pyamg_sa_smooth=('jacobi', {'omega': 4.0/3.0}),\n pyamg_sa_presmoother=('block_gauss_seidel', {'sweep': 'symmetric'}),\n pyamg_sa_postsmoother=('block_gauss_seidel', {'sweep': 'symmetric'}),\n pyamg_sa_improve_candidates=[('block_gauss_seidel', {'sweep': 'symmetric', 'iterations': 4}), None],\n pyamg_sa_max_levels=10,\n pyamg_sa_max_coarse=500,\n pyamg_sa_diagonal_dominance=False,\n pyamg_sa_coarse_solver='pinv2',\n pyamg_sa_cycle='V',\n pyamg_sa_accel=None,\n pyamg_sa_tol=1e-5,\n pyamg_sa_maxiter=100):\n\n assert default_least_squares_solver.startswith('least_squares')\n\n opts = (('bicgstab_spilu', {'type': 'bicgstab_spilu',\n 'tol': bicgstab_tol,\n 'maxiter': bicgstab_maxiter,\n 'spilu_drop_tol': spilu_drop_tol,\n 'spilu_fill_factor': spilu_fill_factor,\n 'spilu_drop_rule': spilu_drop_rule,\n 'spilu_permc_spec': spilu_permc_spec}),\n ('bicgstab', {'type': 'bicgstab',\n 'tol': bicgstab_tol,\n 'maxiter': bicgstab_maxiter}),\n ('spsolve', {'type': 'spsolve',\n 'permc_spec': spsolve_permc_spec,\n 'keep_factorization': spsolve_keep_factorization}),\n ('lgmres', {'type': 'lgmres',\n 'tol': lgmres_tol,\n 'maxiter': lgmres_maxiter,\n 'inner_m': lgmres_inner_m,\n 'outer_k': lgmres_outer_k}),\n ('least_squares_lsqr', {'type': 'least_squares_lsqr',\n 'damp': least_squares_lsqr_damp,\n 'atol': least_squares_lsqr_atol,\n 'btol': least_squares_lsqr_btol,\n 'conlim': least_squares_lsqr_conlim,\n 'iter_lim': least_squares_lsqr_iter_lim,\n 'show': least_squares_lsqr_show}))\n\n if HAVE_SCIPY_LSMR:\n opts += (('least_squares_lsmr', {'type': 'least_squares_lsmr',\n 'damp': least_squares_lsmr_damp,\n 'atol': least_squares_lsmr_atol,\n 'btol': least_squares_lsmr_btol,\n 'conlim': least_squares_lsmr_conlim,\n 'maxiter': least_squares_lsmr_maxiter,\n 'show': least_squares_lsmr_show}),)\n\n if HAVE_PYAMG:\n opts += (('pyamg', {'type': 'pyamg',\n 'tol': pyamg_tol,\n 'maxiter': pyamg_maxiter}),\n ('pyamg-rs', {'type': 'pyamg-rs',\n 'strength': pyamg_rs_strength,\n 'CF': pyamg_rs_CF,\n 'presmoother': pyamg_rs_presmoother,\n 'postsmoother': pyamg_rs_postsmoother,\n 'max_levels': pyamg_rs_max_levels,\n 'max_coarse': pyamg_rs_max_coarse,\n 'coarse_solver': pyamg_rs_coarse_solver,\n 'cycle': pyamg_rs_cycle,\n 'accel': pyamg_rs_accel,\n 'tol': pyamg_rs_tol,\n 'maxiter': pyamg_rs_maxiter}),\n ('pyamg-sa', {'type': 'pyamg-sa',\n 'symmetry': pyamg_sa_symmetry,\n 'strength': pyamg_sa_strength,\n 'aggregate': pyamg_sa_aggregate,\n 'smooth': pyamg_sa_smooth,\n 'presmoother': pyamg_sa_presmoother,\n 'postsmoother': pyamg_sa_postsmoother,\n 'improve_candidates': pyamg_sa_improve_candidates,\n 'max_levels': pyamg_sa_max_levels,\n 'max_coarse': pyamg_sa_max_coarse,\n 'diagonal_dominance': pyamg_sa_diagonal_dominance,\n 'coarse_solver': pyamg_sa_coarse_solver,\n 'cycle': pyamg_sa_cycle,\n 'accel': pyamg_sa_accel,\n 'tol': pyamg_sa_tol,\n 'maxiter': pyamg_sa_maxiter}))\n opts = OrderedDict(opts)\n opts.update(genericsolvers.options())\n def_opt = opts.pop(default_solver)\n if default_least_squares_solver != default_solver:\n def_ls_opt = opts.pop(default_least_squares_solver)\n ordered_opts = OrderedDict(((default_solver, def_opt),\n (default_least_squares_solver, def_ls_opt)))\n else:\n ordered_opts = OrderedDict(((default_solver, def_opt),))\n ordered_opts.update(opts)\n return ordered_opts",
"def setup(self, solver_settings: Dict = {}):\n assert self.opt_type in QP_COST, \"CVXOPT cannot solve this problem\"\n\n ## Input to the solver\n self._solver_input = solver_settings\n\n self._reset_parameters()\n return self",
"def do_optimisation(self):\n\n print('--> Parameters for optimisation:')\n print('--> Using measurements : {}'.format(self.stoma_cfg.comparison_helper.optimisation_keys))\n print('')\n\n x0 = self.initial_guess()\n\n tol, eps = 1e-4, 0.001\n\n print('--> Using SLSQP with tol={} and eps={}'.format(tol, eps))\n\n soln = opt.minimize(fun=self.optimise_fn,\n x0=x0,\n method='SLSQP',\n tol=tol,\n options={'eps': eps})\n\n print('*' * 120)\n print('--> Optimisation procedure has finished...')\n print(soln)\n print('*' * 120)\n\n if soln.success:\n print('--> Optimisation succeeded. Result is...')\n self._set_material_parameters(soln.x)\n print('--> {}'.format(self.material_model))\n else:\n print('--> The optimisation failed!')\n\n print('*' * 120)\n\n return soln",
"def _set_solver(self):\n self.solver = Solver.select_solver(self.method, self.solver_args)\n if self.method.lower()==\"elastic-net\":\n self.solver.elements=self.basis.elements",
"def office_setup_solver(parser, args, params):\n parser.parse_known_args(args)\n control.setup_solver(params)",
"def solver_options(lgmres_tol=1e-5,\n lgmres_maxiter=1000,\n lgmres_inner_m=39,\n lgmres_outer_k=3,\n least_squares_lsmr_damp=0.0,\n least_squares_lsmr_atol=1e-6,\n least_squares_lsmr_btol=1e-6,\n least_squares_lsmr_conlim=1e8,\n least_squares_lsmr_maxiter=None,\n least_squares_lsmr_show=False,\n least_squares_lsqr_damp=0.0,\n least_squares_lsqr_atol=1e-6,\n least_squares_lsqr_btol=1e-6,\n least_squares_lsqr_conlim=1e8,\n least_squares_lsqr_iter_lim=None,\n least_squares_lsqr_show=False):\n\n return {'generic_lgmres': {'type': 'generic_lgmres',\n 'tol': lgmres_tol,\n 'maxiter': lgmres_maxiter,\n 'inner_m': lgmres_inner_m,\n 'outer_k': lgmres_outer_k},\n 'generic_least_squares_lsmr': {'type': 'generic_least_squares_lsmr',\n 'damp': least_squares_lsmr_damp,\n 'atol': least_squares_lsmr_atol,\n 'btol': least_squares_lsmr_btol,\n 'conlim': least_squares_lsmr_conlim,\n 'maxiter': least_squares_lsmr_maxiter,\n 'show': least_squares_lsmr_show},\n 'generic_least_squares_lsqr': {'type': 'generic_least_squares_lsqr',\n 'damp': least_squares_lsqr_damp,\n 'atol': least_squares_lsqr_atol,\n 'btol': least_squares_lsqr_btol,\n 'conlim': least_squares_lsqr_conlim,\n 'iter_lim': least_squares_lsqr_iter_lim,\n 'show': least_squares_lsqr_show}}",
"def __get_solver_instance(self):\n solver = self._solver\n\n # if a configured solver is not given, then build one of the given type\n from mystic.abstract_solver import AbstractSolver\n if isinstance(solver, AbstractSolver): # is a configured solver instance\n return solver\n if not hasattr(solver, \"Solve\"): # is an Error...\n raise TypeError, \"%s is not a valid solver\" % solver\n\n # otherwise, this is a solver class and needs configuring\n #from mystic.monitors import Monitor\n #stepmon = Monitor()\n #evalmon = Monitor()\n #maxiter = 1000\n #maxfun = 1e+6\n solver = solver(self.nDim)\n solver.SetRandomInitialPoints() #FIXME: set population; will override\n if self._useStrictRange: #XXX: always, settable, or sync'd ?\n solver.SetStrictRanges(min=self._strictMin, max=self._strictMax)\n solver.SetEvaluationLimits(self._maxiter, self._maxfun)\n solver.SetEvaluationMonitor(self._evalmon) #XXX: or copy or set?\n solver.SetGenerationMonitor(self._stepmon) #XXX: or copy or set?\n solver.SetTermination(self._termination)\n solver.SetConstraints(self._constraints)\n solver.SetPenalty(self._penalty)\n if self._reducer: #XXX: always, settable, or sync'd ?\n solver.SetReducer(self._reducer, arraylike=True)\n return solver",
"def optimize(\n self, n, tol=None, jac=True, hessp=False, optlib=\"scipy\", **options\n ):\n return {\"scipy\": self.optimize_scipy, \"nlopt\": self.optimize_nlopt,}[\n optlib\n ](n=n, tol=tol, jac=jac, hessp=hessp, **options)",
"def setSolverType(*argv):",
"def set_simulation_options(self, result_handler, solver, atol, rtol, verbose):\n # The result handling can be one of\n # \"file\", \"memory\", \"custom\" (in the latter case a result handler has to be specified)\n # By default they are on memory\n if result_handler is not None and result_handler in fmu_util_strings.SIMULATION_OPTION_RESHANDLING_LIST:\n self.opts[fmu_util_strings.SIMULATION_OPTION_RESHANDLING_STRING] = result_handler\n else:\n self.opts[fmu_util_strings.SIMULATION_OPTION_RESHANDLING_STRING] = fmu_util_strings.RESULTS_ON_MEMORY_STRING\n \n \n # Set solver verbose level\n if verbose is not None and verbose in fmu_util_strings.SOLVER_VERBOSITY_LEVELS:\n for s in fmu_util_strings.SOLVER_NAMES_OPTIONS: \n self.opts[s][fmu_util_strings.SOLVER_OPTION_VERBOSITY_STRING] = verbose\n else:\n for s in fmu_util_strings.SOLVER_NAMES_OPTIONS: \n self.opts[s][fmu_util_strings.SOLVER_OPTION_VERBOSITY_STRING] = fmu_util_strings.SOLVER_VERBOSITY_QUIET\n \n \n # Set the absolute and relative tolerance of each solver, otherwise the default value\n # is left\n if atol is not None and atol > 0 and numpy.isreal(atol):\n for s in fmu_util_strings.SOLVER_NAMES_OPTIONS: \n self.opts[s][fmu_util_strings.SOLVER_OPTION_ATOL_STRING] = atol\n if rtol is not None and rtol > 0 and numpy.isreal(rtol):\n for s in fmu_util_strings.SOLVER_NAMES_OPTIONS: \n self.opts[s][fmu_util_strings.SOLVER_OPTION_RTOL_STRING] = rtol",
"def setSolverTau(*argv):",
"def get_s(net, p=None, method=None, Tmin=None, Tmax=None, k=None, \n tol_ss=None, x0=None, to_ser=False, **kwargs_fsolve):\n if method is None:\n method = METHOD\n \n if method == 'integration':\n return get_s_integration(net, p=p, \n Tmin=Tmin, Tmax=Tmax, k=k, tol_ss=tol_ss,\n to_ser=to_ser)\n if method == 'rootfinding':\n kwargs_fsolve = butil.get_submapping(kwargs_fsolve, f_key=lambda key:\\\n key in ['xtol', 'maxfev', 'epsfcn', 'factor'])\n return get_s_rootfinding(net, p=p, x0=x0, to_ser=to_ser, **kwargs_fsolve)\n if method == 'mixed':\n # first get down to the basin of attraction for fsolve\n if Tmin is None:\n Tmin = TMIN\n return get_s_rootfinding(net, p=p, x0=net.get_x(p=p, t=Tmin), \n to_ser=to_ser, **kwargs_fsolve)",
"def test_init(self):\n # setup test scenario\n _kwargs = {'nsteps': 5}\n # call function to test\n test_object = ScipySolveIvpSolver(**_kwargs)\n # verify the expected results\n assert test_object._solver_kwargs == _kwargs, 'unexpected additional arguments. Keep in mind None and {}'",
"def init_solver(param):\n return param.solver(learning_rate=param.learning_rate,\n beta1=param.beta1,\n beta2=param.beta2)",
"def solve(self, model, solver=\"cbc\", with_duals=False, **solver_kwargs):\n logging.info(\"Optimising using %s.\", solver)\n\n solver_kwargs[\"tee\"] = solver_kwargs.get(\"tee\", True)\n\n self.meta[\"solph_version\"] = solph.__version__\n self.meta[\"solver\"] = solver\n self.meta[\"solver_start\"] = datetime.datetime.now()\n\n if with_duals:\n model.receive_duals()\n\n model.solve(solver=solver, solve_kwargs=solver_kwargs)\n\n self.meta[\"solver_end\"] = datetime.datetime.now()\n\n self.es.results[\"main\"] = solph.processing.results(model)\n self.meta.update(solph.processing.meta_results(model))\n self.es.results[\"param\"] = solph.processing.parameter_as_dict(self.es)\n self.es.results[\"meta\"] = self.meta\n\n self.results = self.es.results",
"def __init__(self, problem, options, tr_method):\n\n # User-defined optimal-control problem\n self.problem = problem\n\n # General options\n self.options = options\n\n # Transcription method\n self.tr_method = tr_method\n\n # Construction of the lower and upper constraints boundaries\n self.low, self.upp = self.build_constraints_boundaries()",
"def office_prepare_solver(parser, args, params):\n parser.parse_known_args(args)\n control.prepare_solver(params)",
"def set_params(self, solver):\n params = yicespy.yices_new_param_record()\n yicespy.yices_default_params_for_context(solver.yices, params)\n for k,v in self.solver_options.items():\n rv = yicespy.yices_set_param(params, k, v)\n if rv != 0:\n raise PysmtValueError(\"Error setting the option '%s=%s'\" % (k,v))\n solver.yices_params = params",
"def test_quadratic_with_classes():\r\n\r\n problem = Problem()\r\n solver = Solver(problem)\r\n\r\n # Read input from the command line\r\n parser = problem.define_command_line_options()\r\n parser = solver. define_command_line_options(parser)\r\n args = parser.parse_args()\r\n problem.init_from_command_line(args)\r\n solver. init_from_command_line(args)\r\n\r\n print parser.parse_args() # parameters ok?\r\n\r\n solver.solve() \r\n print 'Check error.........................'\r\n solver.assert_no_error()",
"def _optimize(self,x0,type,method,**kwargs):\n from scipy.optimize import fmin,fmin_powell\n\n if type == 'min':\n g=lambda x:self(x)\n elif type == 'max':\n g=lambda xs:-1*self(x)\n elif type == 'root':\n g=lambda x:np.abs(self(x))\n elif type == 'val':\n val = kwargs.pop('valtofind')\n g=lambda x:np.abs(self(x)-val)\n elif type == 'saddle':\n raise NotImplementedError\n else:\n raise ValueError('Unrecognized optimization type')\n\n if method == 'fmin':\n res = fmin(g,x0,**kwargs)\n elif method == 'fmin_powell':\n res = fmin_powell(g,x0,**kwargs)\n else:\n raise ValueError('Unrecognized method')\n\n self.lastOpt = res\n return res[0]",
"def __init__(self, data_p, data_q, solver=\"SCS\"):\n self.data_P = data_p\n self.data_Q = data_q\n self.solver = solver\n self.warning_msg = None\n\n self.n = len(data_p)\n\n # Hold values *separate* from cvxpy variables as we sometimes need to revert\n # cvxpy optimizations which actually move values in a way that gives a *worse*\n # objective function.\n self.p = _np.array(self.data_P) / _np.sum(self.data_P)\n self.q = _np.array(self.data_Q) / _np.sum(self.data_Q)\n\n # cvxpy parameters\n self.T = _cp.Parameter(shape=(self.n, self.n), nonneg=True, value=_np.eye(self.n))\n self.alpha = _cp.Parameter(nonneg=True, value=1.0)\n\n self.max_logl = max_log_likelihood(data_p) + max_log_likelihood(data_q)\n self._build_problem()",
"def solve(\n self, solver=Solver.IPOPT, show_online_optim=False, return_iterations=False, solver_options={},\n ):\n\n if return_iterations and not show_online_optim:\n raise RuntimeError(\"return_iterations without show_online_optim is not implemented yet.\")\n\n if solver == Solver.IPOPT and self.solver_type != Solver.IPOPT:\n from ..interfaces.ipopt_interface import IpoptInterface\n\n self.solver = IpoptInterface(self)\n\n elif solver == Solver.ACADOS and self.solver_type != Solver.ACADOS:\n from ..interfaces.acados_interface import AcadosInterface\n\n self.solver = AcadosInterface(self, **solver_options)\n\n elif self.solver_type == Solver.NONE:\n raise RuntimeError(\"Solver not specified\")\n self.solver_type = solver\n\n if show_online_optim:\n self.solver.online_optim(self)\n if return_iterations:\n self.solver.start_get_iterations()\n\n self.solver.configure(solver_options)\n self.solver.solve()\n\n if return_iterations:\n self.solver.finish_get_iterations()\n\n return self.solver.get_optimized_value(self)",
"def test_init(self):\n # setup test scenario\n _kwargs = {'nsteps': 5}\n # call function to test\n test_object = ScipyOdeIntSolver(**_kwargs)\n # verify the expected results\n assert test_object._solver_args == _kwargs, 'unexpected additional arguments. Keep the type in mind.'",
"def fit(self, algorithm='sv_adj', target='ytm', p_init='grid', w_method='duration',\n w_short=False, optimization='standard'):\n\n # 1) Define the algorithm\n self.algorithm = algorithm\n self._target = target\n self._p_init = p_init\n self._optimization = optimization\n\n if (algorithm.lower() == 'ns') or (algorithm.lower().__contains__('nelson')):\n self._algo = Models().NelsonSiegel\n if (algorithm.lower() == 'sv') or (algorithm.lower().__contains__('sv')):\n self._algo = Models().Svensson\n if (algorithm.lower() == 'sv_adj') or (algorithm.lower().__contains__('adjust')):\n self._algo = Models().SvenssonAdj\n if (algorithm == 'bc') or (algorithm.lower().__contains__('b')):\n self._algo = Models().BoerkChristensen\n\n # 2) Parameter initialization\n if self._p_init == 'grid':\n params = self._ParamInitialization(method=p_init)\n\n # 3) prepare for optimization\n self._w_method = w_method\n self._w_short = w_short\n\n # 4) optimization\n if target == 'ytm':\n self._optimizeParametric(self._function_ytm, params)\n\n if target == 'price':\n self._optimizeParametric(self._function_price, params)\n\n ylds = self._algo(self.parameter, self.instruments.ttm)\n\n self.instruments['zero'] = ylds[0] # todo: somehow, the same values go to next class??\n self.instruments['fwd'] = ylds[1]\n self.zero = ylds[0] # todo: somehow, the same values go to next class??\n self.fwd = ylds[1]\n self._summary()",
"def solve(\n self, preconditioner='none', tol=1e-5,\n operator_parameters=None, preconditioner_parameters=None\n ):\n time_assemble = -time.clock() # start timer\n\n self.operator = self.assemble_operator(operator_parameters)\n self.rhs = self.assemble_rhs(operator_parameters)\n\n if preconditioner == 'none':\n super_operator = self.operator\n super_rhs = self.rhs\n elif preconditioner == 'diagonal':\n diagonal = self.get_diagonal(preconditioner_parameters) \n super_operator = diagonal * self.operator\n super_rhs = diagonal * self.rhs\n elif preconditioner == 'self':\n preconditioner = self.get_op_as_preconditioner(preconditioner_parameters)\n super_operator = preconditioner * self.operator\n super_rhs = preconditioner * self.rhs\n # elif preconditioner == 'electric-interior':\n # pass\n else:\n raise NotImplementedError(\n \"Preconditioner '%s' not supported\" % preconditioner)\n\n if hasattr(super_operator, 'strong_form'):\n super_operator.strong_form(True)\n \n time_assemble += time.clock() # stop timer\n\n bempp.api.MATVEC_COUNT = 0 # reset the MATVEC counter to 0\n solve_time = -time.clock() # initialise the timer\n sol, solve_info, residuals = self._gmres(super_operator, super_rhs, tol)\n solve_time += time.clock() # stop the timer\n matvec_count = bempp.api.MATVEC_COUNT # sample the matvec counter\n \n info = dict(\n status=solve_info,\n time_solve=solve_time,\n time_assemble=time_assemble,\n matvec_count=matvec_count\n )\n if isinstance(sol[0], np.complex128):\n return Solution(coefficients=sol, info=info, residuals=residuals, system=self) \n else:\n return Solution(traces=sol, info=info, residuals=residuals, system=self)",
"def __init__(self,optimization:str = 'sparsity',justified_cf:bool = True):\n if optimization not in ['none','sparsity','proximity','plausibility']:\n msg = 'Invalid argument for optimization: \"{}\"'\n raise ValueError(msg.format(optimization))\n self.optimization = optimization\n self.justified_cf = justified_cf\n self.eps = 0.0000001\n #todo check if all inputs are correct. elevate error",
"def solve(self, topology, algorithm=\"SLSQP\", grad=\"AD\", step_size=1e-6, iters=100, eps=1e-6, kappa=1e-8, tmax=100, eta=1e-6, verbose=False):\n if verbose:\n print(\"----------\")\n print(\"Optimization with {} started!\".format(algorithm))\n print(f\"# Parameters: {self.number_of_parameters()}, # Constraints {self.number_of_constraints()}\")\n\n # test for bad stuff before going any further\n self.check_optimization_sanity()\n\n # compose gradient and objective functions\n if grad not in (\"AD\", \"FD\"):\n raise ValueError(f\"Gradient method {grad} is not supported!\")\n if grad == \"AD\":\n if verbose:\n print(\"Computing gradients using automatic differentiation!\")\n x_func = partial(self._optimize_form, topology=topology.copy(), tmax=tmax, eta=eta)\n grad_func = partial(grad_autograd, grad_func=agrad(x_func)) # x, grad, x_func\n\n elif grad == \"FD\":\n if verbose:\n print(f\"Warning: Calculating gradients using finite differences with step size {step_size}. This may take a while...\")\n grad_func = self.gradient_func(grad_finite_differences, topology.copy(), tmax, eta, step_size)\n\n # grad_func = self.gradient_func(grad_func, topology.copy(), tmax, eta, step_size)\n obj_func = self.objective_func(topology, grad_func, tmax, eta)\n\n # generate optimization variables\n x = self.optimization_parameters(topology)\n\n # extract the lower and upper bounds to optimization variables\n bounds_low, bounds_up = self.optimization_bounds(topology)\n\n # stack keyword arguments\n hyper_parameters = {\"f\": obj_func,\n \"algorithm\": algorithm,\n \"dims\": self.number_of_parameters(),\n \"bounds_low\": bounds_low,\n \"bounds_up\": bounds_up,\n \"iters\": iters,\n \"eps\": eps,\n \"ftol\": kappa}\n\n # assemble optimization solver\n solver = nlopt_solver(**hyper_parameters)\n\n # solve optimization problem\n x_opt = None\n start = time()\n try:\n x_opt = solver.optimize(x)\n if verbose:\n print(\"Optimization ended correctly!\")\n except RoundoffLimited:\n print(\"Optimization was halted because roundoff errors limited progress\")\n print(\"Results may still be useful though!\")\n x_opt = self.optimization_parameters(topology)\n except RuntimeError:\n print(\"Optimization failed due to a runtime error!\")\n print(f\"Optimization total runtime: {round(time() - start, 4)} seconds\")\n return static_equilibrium(topology)\n\n # fetch last optimum value of loss function\n time_opt = time() - start\n loss_opt = solver.last_optimum_value()\n evals = solver.get_numevals()\n status = nlopt_status(solver.last_optimize_result())\n\n # set optimizer attributes\n self.time_opt = time_opt\n self.x_opt = x_opt\n self.penalty = loss_opt\n self.evals = evals\n self.status = status\n\n # set norm of the gradient\n # NOTE: np.zeros is a dummy array (signature requirement set by nlopt)\n self.gradient = grad_func(x_opt, np.zeros(x_opt.size))\n self.gradient_norm = np.linalg.norm(self.gradient)\n\n if verbose:\n print(f\"Optimization total runtime: {round(time_opt, 6)} seconds\")\n print(\"Number of evaluations incurred: {}\".format(evals))\n print(f\"Final value of the objective function: {round(loss_opt, 6)}\")\n print(f\"Norm of the gradient of the objective function: {round(self.gradient_norm, 6)}\")\n print(f\"Optimization status: {status}\".format(status))\n print(\"----------\")\n\n # exit like a champion\n return static_equilibrium(topology)"
] | [
"0.6477532",
"0.63090336",
"0.62966573",
"0.628272",
"0.62646425",
"0.60118777",
"0.5974712",
"0.5958667",
"0.5844108",
"0.57841927",
"0.5779486",
"0.57777077",
"0.57302105",
"0.5727623",
"0.56519526",
"0.5578283",
"0.5549459",
"0.55332226",
"0.55141824",
"0.5475442",
"0.5449414",
"0.5429957",
"0.53884244",
"0.5369669",
"0.5359924",
"0.5357028",
"0.53392",
"0.5332419",
"0.53244114",
"0.53222"
] | 0.7787004 | 0 |
! Reset initial seed for the optimization problem. x0 The initial seed. | def reset_initial_seed(self, x0) -> None:
super().reset_initial_seed(x0)
self.minimize_input["x0"] = self.x0.toarray().flatten() | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def reset_initial_seed(self, x0: Dict[str, ArrayType]) -> None:\n self.x0 = self.opt.decision_variables.dict2vec(x0)",
"def generate_initial_state(self, x):\n\n if self.initial_state is None:\n x[:] = 0\n return x\n else:\n x[:] = self.initial_state(size=(self._num_neurons, 1))\n return x",
"def rngreset(seed=0):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True",
"def reset(self):\n self.x_prev = np.zeros_like(self.mu)",
"def reset(self):\n self.rand_start = int(np.random.rand()*25000)+self.offset\n state = np.array(np.zeros(self.obs))\n self.time = self.rand_start\n self.residual = 0\n self.cum_r = 0\n return state",
"def reset(self) -> None:\n self._rng = random.default_rng(self.seed)",
"def reset(self):\n self.t = 0\n # two outputs: the thrusters, u_r and u_l and stop neuron\n self.action = [0.0, 0.0, 0.0]\n # x, vx, y, vy, theta, omega\n # self.state = [2.0, 0.0, 2.0, 0.0, 0.0, 0.0]\n self.state = self.start_cnd\n x, vx, y, vy, theta, omega = self.state\n# print x, self.state\n self.init_distance = self.getDistance()\n \n self.solver = ode(self.dX)\n self.solver.set_integrator('dopri5') \n self.solver.set_initial_value(self.state, self.t)",
"def reset(self):\n self.x = random.uniform(-0.05, 0.05)\n self.x_dot = random.uniform(-0.05, 0.05)\n self.theta = random.uniform(-0.05, 0.05)\n self.theta_dot = random.uniform(-0.05, 0.05)",
"def seed_random():\n random.seed(0)",
"def reset(self):\n # Sample random state from initial state distribution\n self._cur_state = self._sample_state(self._mdp.I)\n self._prev_state = self._cur_state",
"def initial_x():\n\n # RANDOMLY GENERATES the INITIAL VALUES of the independent variables:\n temp = [uniform(1, cfg.n) for i in range(cfg.n)]\n\n return np.array(temp, dtype=np.float_)",
"def reset():\n\n global optimizer_data\n global optimizer_len\n\n optimizer_data = []\n optimizer_len = 0\n return",
"def reset(self):\n seed = copy.deepcopy(self.rng_seed)\n self.rng = check_random_state(seed)\n self.num_generated = 0\n return self",
"def reset_states(self):\n K.batch_set_value([(v, 0) for v in self.variables])",
"def test_reset(self):\n self.p.C[0][0] = np.inf\n self.step()",
"def reset(self):\n \n s = self\n s.step_counter = 0\n \n # TODO: initialize first layer activations here, and not everywhere else\n # self.model.initialize_local_vars()\n # self.model.initialize_global_vars()\n\n ops = []\n\n for var in self.model.trainable_vars:\n if self.needs_correction(var):\n A_svd = s[var].A.svd\n B2_svd = s[var].B2.svd \n ops.extend(A_svd.init_ops)\n ops.extend(B2_svd.init_ops)\n ops.append(s[var].A.cov.initializer)\n ops.append(s[var].B2.cov.initializer)\n\n # in new TensorFlow this breaks, probably because of\n # https://github.com/tensorflow/tensorflow/commit/07adc2ea910de715d31e16a019fcbcccb575e931\n # sometimes get \"need to feed\" placeholder error\n # sometimes do not get this error, but spend two minutes inside\n # _build_initializer_expr\n s.run(ops)",
"def random():\n np.random.seed(0)",
"def reset(self):\n self.reset_image_estimate()\n self.init_m_aux()\n self.reset_hessian_and_bias()\n self.reset_adadelta_variables()",
"def init_state(self, x):\n B, _, d_model = x.shape\n p_0 = torch.zeros((B, 2 * d_model), device=x.device, requires_grad=True)\n self.gru_hidden = torch.zeros((B, 2 * d_model), device=x.device, requires_grad=True)\n return p_0",
"def init_state(self, x):\n B, _, d_model = x.shape\n p_0 = torch.zeros((B, 2 * d_model), device=x.device, requires_grad=True)\n self.gru_hidden = torch.zeros((B, 2 * d_model), device=x.device, requires_grad=True)\n return p_0",
"def reset(self):\r\n self.currentIteration = 0\r\n # note there are several versions of randint!\r\n self.currentObservation = random.randint(0, self.S - 1)\r\n return self.get_state()",
"def reset(self):\n for i in range(0, len(self.current_state)):\n self.current_state[i] = 0\n\n for i in range(0, len(self.weights)):\n self.weights[i] = 0",
"def reset(self):\n self.z = rand(*self.z.shape)\n self.c = ones_like(self.c)",
"def prepare_for_use(self):\n self._random_state = check_random_state(self.random_state)\n self._offset = self.offset\n self._x_idx = 0",
"def prepare_for_use(self):\n self._random_state = check_random_state(self.random_state)\n self._offset = self.offset\n self._x_idx = 0",
"def prepare_for_use(self):\n self._random_state = check_random_state(self.random_state)\n self._offset = self.offset\n self._x_idx = 0",
"def reset(self):\n self.noise = [0.] * 6\n self.state = [0.0] * 9\n self.q = [0.0, 0.0, 0.0, 1.0]\n self.terminal = False\n self.steps = 0\n # Return current state and error\n return self.observation, self.error",
"def get_initial_guess():\n x0 = np.zeros(6)\n x0[0] = 1\n x0[3] = 1\n return x0",
"def reset_state(self):\n self.y = np.copy(self.start)\n self.dy = np.zeros(self.n_dmps)\n self.ddy = self.ay * (self.by * (self.goal - self.y) - self.dy) + self.force[0]\n self.timestep = 0",
"def reset(self):\r\n self.state = copy.copy(self.mu)"
] | [
"0.7988302",
"0.67843056",
"0.6593212",
"0.6503656",
"0.6454457",
"0.6383516",
"0.6311529",
"0.630171",
"0.6265005",
"0.6239627",
"0.62309265",
"0.6227303",
"0.61286354",
"0.6122613",
"0.6122158",
"0.60998493",
"0.6077699",
"0.6073097",
"0.60562795",
"0.60562795",
"0.60531366",
"0.60469806",
"0.6035503",
"0.6008634",
"0.6008634",
"0.6008634",
"0.60018325",
"0.59940416",
"0.59658265",
"0.5964649"
] | 0.8737879 | 0 |
! Returns True when the problem was solved. Boolean indicating if the solver converged. | def did_solve(self):
return self._solution.success | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def did_solve(self) -> bool:\n return self._solution.info.status == \"solved\"",
"def did_solve(self) -> bool:\n return self._stats[\"success\"]",
"def did_solve(self):\n return self._solution[\"status\"] == \"optimal\"",
"def did_solve(self) -> bool:\n pass",
"def converged(self) -> bool:",
"def converged(self) -> bool:",
"def converged(self) -> bool:",
"def has_solution(self) -> bool:\n pass",
"def converged(self) -> bool:\n return self._converged",
"def is_solved(self):\n self.solved = self.current_pos == self.finish_pos\n return self.solved",
"def is_solvable(self):\n self_copy = deepcopy(self)\n return self_copy.solve()",
"def converged(self) -> bool:\n if self._species is not None and self._species.n_atoms == 1:\n return True # Optimisation 0 DOF is always converged\n\n if self._abs_delta_e < self.etol / 10:\n logger.warning(\n f\"Energy change is overachieved. \"\n f'{self.etol.to(\"kcal\")/10:.3E} kcal mol-1. '\n f\"Signaling convergence\"\n )\n return True\n\n return self._abs_delta_e < self.etol and self._g_norm < self.gtol",
"def converged(self) -> bool:\n assert self._coords is not None\n\n if self._converged_translation:\n logger.info(\n \"Converged purely based on translation of the \"\n \"dimer midpoint\"\n )\n return True\n\n rms_g0 = np.sqrt(np.mean(np.square(self._coords.g0)))\n return self.iteration > 0 and rms_g0 < self.gtol",
"def is_solved(self):\n raise NotImplementedError()",
"def isSolved(self):\n return self.isComplete() and self.isLegal()",
"def isSolved(self):\n return self.__isSolved",
"def solved(self):\r\n return self.puzzle.solved",
"def is_solved(self):\n if not self._find_empty():\n return True\n else:\n return False",
"def is_solved(self):\n return self._start == self._target",
"def has_solution(self) -> bool:\n if self in [self.SATISFIED, self.ALL_SOLUTIONS, self.OPTIMAL_SOLUTION]:\n return True\n return False",
"def is_solved(self):\n return (self.from_grid == self.to_grid)",
"def is_solved(self):\n return self.to_grid == self.from_grid",
"def test_is_solved_when_puzzle_is_solved(self):\n self.assertTrue(self.sudoku.is_solved())",
"def is_solved(self):\n return self.from_grid == self.to_grid",
"def is_solved(self):\n return self.from_grid == self.to_grid",
"def is_solved(self):\n return self.from_grid == self.to_grid",
"def update_status(self):\n if len(self.invalid) != 0:\n return False\n for row in self.grid:\n for num in row:\n if num == 0:\n return False\n self.solved = True\n print(\"solved\")\n return True",
"def converged(self):\n if len(self.rundir) >= 2:\n if io.ionic_steps(self.rundir[-1]) <= 3:\n return True\n if self.settings[\"nrg_convergence\"] != None:\n if io.job_complete(self.rundir[-1]) and io.job_complete(self.rundir[-2]):\n o1 = io.Oszicar(os.path.join(self.rundir[-1],\"OSZICAR\"))\n o2 = io.Oszicar(os.path.join(self.rundir[-2],\"OSZICAR\"))\n if abs( o1.E[-1] - o2.E[-1]) < self.settings[\"nrg_convergence\"]:\n return True\n\n return False",
"def is_solved(self):\n # Iterate through each square of the puzzle\n for row in range(self.sl):\n for col in range(self.sl):\n val = self.puzzle[row][col]\n\n # If any square value is blank (0), not solved, return False\n if val == 0:\n return False\n\n # Trick to keep DRY code: replace each value temporarily with a\n # 0, and use valid_square method with original value to determine\n # if every square is valid\n self.puzzle[row][col] = 0\n valid = self.valid_square(row, col, val)\n self.puzzle[row][col] = val\n \n # If not a valid value for square, return False\n if not valid:\n return False\n return True",
"def solveOneStep(self):\n ### Student code goes here\n return True"
] | [
"0.7977091",
"0.7582729",
"0.7577563",
"0.7572323",
"0.73576117",
"0.73576117",
"0.73576117",
"0.73108906",
"0.7260244",
"0.7226423",
"0.7170689",
"0.70954806",
"0.7050868",
"0.69759893",
"0.6931749",
"0.68873924",
"0.6871832",
"0.68437505",
"0.6831438",
"0.679917",
"0.6769061",
"0.6705766",
"0.66316956",
"0.6628182",
"0.6628182",
"0.6628182",
"0.6538908",
"0.6513031",
"0.64966977",
"0.6489818"
] | 0.7626083 | 1 |
Draw "Game over" across the screen. | def draw_game_over(self):
output = "Game Over!"
arcade.draw_text(output, 250, 400, arcade.color.BLACK, 54)
output = "Click to restart"
arcade.draw_text(output, 330, 200, arcade.color.BLACK, 24) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def draw_game_over(self):\n arcade.draw_rectangle_filled(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2,\n SCREEN_WIDTH // 2,\n SCREEN_HEIGHT // 1.5, arcade.color.BRONZE)\n arcade.draw_rectangle_filled(SCREEN_WIDTH // 2, 410, 600, 140, arcade.color.COOL_GREY)\n arcade.draw_rectangle_filled(SCREEN_WIDTH // 2, 275, 550, 100, arcade.color.COOL_GREY)\n\n output = \"Oops, You Lost :(\"\n arcade.draw_text(output, 360, 381, arcade.color.BLACK, 66)\n\n output = \"Click Anywhere To Restart\"\n arcade.draw_text(output, 375, 258, arcade.color.BLACK, 40)",
"def draw_game_over(self):\r\n gameover = \"Game Over\"\r\n start_x = SCREEN_WIDTH/2 - 50\r\n start_y = SCREEN_HEIGHT/2\r\n arcade.draw_text(gameover, start_x=start_x, start_y=start_y, font_size= 20, color=arcade.color.BLACK)",
"def game_over(self):\r\n win.blit(self.image_of_game_over, (250, 170))",
"def gameover(self):\n font = pygame.font.Font(None, CASE_SIZE)\n text = font.render('Game over!', True,(255, 255, 255), (0, 0, 0))\n self.screen.blit(text,(CASE_SIZE * 6, CASE_SIZE * 7))\n self.try_again()\n pygame.display.flip()",
"def show_game_over(self):\n font = pygame.font.SysFont(DisplayConsts.GAME_OVER_FONT_TYPE, DisplayConsts.GAME_OVER_FONT_SIZE)\n surface = font.render(\"Game Over\", True, DisplayConsts.GAME_OVER_FONT_COLOR) # Display game over\n rect = surface.get_rect()\n rect.midtop = (DisplayConsts.SCREEN_WIDTH // 2.5, DisplayConsts.SCREEN_HEIGHT // 20)\n self.screen.blit(surface, rect)\n pygame.display.update() # update the screen",
"def game_over(self):\n gameover = GLabel('GAME OVER :(')\n gameover.font = '-50'\n self.window.add(gameover,x=self.window.width/6,y=self.window.height*0.666)",
"def game_over(self):\n if self.alive:\n return\n\n self.screen.fill(Color.BLACK)\n self.draw_text(\n \"GAME OVER\", WIN_CENTER, font=FONT_M, size=48, color=Color.WHITE\n )\n again = \"Press any key to play again\"\n again_pos = CENTER_W, WIN_H - BLOCK_H\n self.draw_text(again, again_pos, color=Color.WHITE)\n\n pygame.display.flip()\n self.wait_keydown()\n\n if self.running:\n self.reset()",
"def displayGameOver():\n screen.fill(pygame.Color('black'), (0, 0, SCREEN_SIZE[0], SCREEN_SIZE[1]))\n goText, rect1 = GAME_FONT.render('Game Over', WHITE)\n paText, rect2 = GAME_FONT.render('Press [Enter] to play again', WHITE)\n width1 = goText.get_width()\n height1 = goText.get_height()\n width2 = paText.get_width()\n height2 = paText.get_height()\n posX1 = (SCREEN_SIZE[0] - width1) / 2\n posY1 = (SCREEN_SIZE[1] - height1) / 2\n posX2 = (SCREEN_SIZE[0] - width2) / 2\n posY2 = (SCREEN_SIZE[1] - height2) / 2 + 30\n screen.blit(goText, (posX1, posY1))\n screen.blit(paText, (posX2, posY2))",
"def on_draw(self):\n self.clear()\n arcade.draw_text(\n \"Game Over - Click to restart\",\n SCREEN_WIDTH / 2,\n SCREEN_HEIGHT / 2,\n arcade.color.WHITE,\n 30,\n anchor_x=\"center\",\n )",
"def event_game_over(self):\n print('Game over!')\n self._cmd_exit()",
"def game_over_text():\n over_text = over_font.render(\"GAME OVER\", True, (255, 255, 255))\n screen.blit(over_text, (200, 250))",
"def __draw_lostscreen(self) -> None:\n self.__draw_background()\n line1 = LOOSE_FONT.render(\"You loose!! Highscore: \" + str(round(self.highscore)), 1, RED)\n line2 = LOOSE_FONT.render(\"Press enter to play again\", 1, RED)\n self.win.blit(line1, (round((WIDTH/2) - line1.get_width()/2), round(HEIGHT/2 - line1.get_height()/2)))\n self.win.blit(line2, (round((WIDTH/2) - line2.get_width()/2), round(HEIGHT/2 - line1.get_height()/2) + line1.get_height() + 5)) \n pygame.display.update()",
"def game_over(screen, black, red, brown, player):\r\n screen.fill(black)\r\n\r\n f1 = pygame.font.Font(None, 102)\r\n s1 = f1.render(\"GAME OVER\", True, red)\r\n screen.blit(s1, [100, 100])\r\n\r\n f2 = pygame.font.Font(None, 70)\r\n s2 = f2.render(\"score: %d\" % player.score, True, brown)\r\n screen.blit(s2, [200, 240])\r\n\r\n pygame.display.update()\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_ESCAPE:\r\n pygame.quit()\r\n sys.exit()",
"def gameOver():\n PTS, COIN, LIVES = 0, 1, 2\n uniSprite = 0\n globalSound(\"stop\") # Stopping any music\n playSound(overSound, \"music\") # Playing game over music\n startTime = time.get_ticks()\n # Game over screen should only stay for 5 seconds\n while time.get_ticks() - startTime < 5000:\n for evnt in event.get():\n if evnt.type == QUIT:\n return \"exit\"\n # Drawing game over screen\n screen.fill(BLACK)\n uniSprite = spriteCounter(uniSprite)\n drawStats(None, None, marioScore[PTS], marioScore[COIN], time.get_ticks(), levelNum, True, True, statCoin,\n uniSprite, 0)\n screen.blit(overText,(300,300)) # Blitting game over text\n display.flip()\n fpsCounter.tick(60)\n return \"menu\"",
"def show_game_over_screen(self) -> None:\n\n if self.score > self.high_score:\n with open(HIGHSCORE_FILE, 'w') as f:\n f.write(str(self.score))\n\n message = f\"Well done - new high score: {self.score}\"\n\n elif self.score == self.high_score:\n\n if self.score == 0:\n message = \"What is this nonsense - you scored nothing!\"\n else:\n message = f\"Well done - you equalled high score: {self.score}\"\n\n else:\n\n message = f\"Sad times - no new high score ({self.high_score}), you got {self.score}\"\n\n self.screen.fill(RED)\n self.draw_text(TITLE, 48, WHITE, WIDTH / 2, HEIGHT / 4)\n\n self.draw_text(\"Game Over\", 22, WHITE, WIDTH / 2, HEIGHT / 2)\n self.draw_text(message, 22, WHITE, WIDTH / 2, HEIGHT / 2 + 50)\n\n\n self.draw_text(\"Press a key to return to menu\", 22, WHITE, WIDTH / 2, HEIGHT * 3 / 4)\n self.draw_text(\"Esc to Quit\", 22, WHITE, WIDTH / 2, HEIGHT * 3 / 4 + 30)\n pg.display.flip()\n\n # Wait for a key press.\n waiting = True\n while waiting:\n self.clock.tick(FPS)\n\n for event in pg.event.get():\n if event.type == pg.QUIT:\n self.quit()\n elif event.type == pg.KEYDOWN:\n if event.key == pg.K_ESCAPE:\n self.quit()\n else:\n waiting = False\n self.state = State.MENU",
"def game_over_screen(self):\n self.font = pygame.font.SysFont(\"comicsansms\", 72)\n i = 0\n pygame.draw.rect(self.window, (60,50,20), (200, 200, 450, 300))\n text = self.font.render(\"Game Over\", True, (0, 0, 0))\n self.window.blit(text, (240, 220))\n text = self.font.render(self.winner+\" wins\", True, (0, 0, 0))\n self.window.blit(text, (270, 330))\n pygame.display.flip()\n while not self.quit:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.quit = True\n return\n if event.type == pygame.QUIT:\n self.quit = True\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_r:\n self.play()\n elif event.key == pygame.K_t:\n self.tip()\n elif event.key == pygame.K_m:\n self.__init__()",
"def game_over(self):\n self.over = True",
"def show_game_over_screen():\n game_over_font = pygame.font.Font('freesansbold.ttf', 120)\n game_surface = game_over_font.render('Game', True, WHITE)\n over_surface = game_over_font.render('Over', True, WHITE)\n game_rect = game_surface.get_rect()\n over_rect = over_surface.get_rect()\n game_rect.midtop = (WINDOWWIDTH / 2, 10)\n over_rect.midtop = (WINDOWWIDTH / 2, game_rect.height + 10 + 25)\n\n DISPLAYSURF.blit(game_surface, game_rect)\n DISPLAYSURF.blit(over_surface, over_rect)\n score()\n wait_for_key_pressed()",
"def game_over(self, player_one, draw):\n if draw:\n win_string = \" No winner \"\n elif not player_one:\n win_string = \"Player 1 wins!\"\n else:\n win_string = \"Player 2 wins!\"\n text_surface, rect = self.game_font.render(win_string, (0, 0, 0))\n self.screen.blit(text_surface, (self.width/2 - 150, self.height/2 - 20))\n pygame.display.set_caption(win_string)\n pygame.display.flip()",
"def game_over(statement, color):\n # Setting up fonts and creating rectangles to put them inside\n lose = win_or_lose.render(statement, True, color)\n leave = font.render(\"Please press Q to quit the game\", True, WHITE)\n text = lose.get_rect()\n box = leave.get_rect()\n\n # Positioning the statements accordingly and displaying them on the screen\n text.center = (350, screen_size[1] / 2)\n box.center = (350, screen_size[1] / 1.5)\n screen.blit(lose, text)\n screen.blit(leave, box)\n King.kill(king) # The king is removed from the screen\n pygame.display.update()\n\n # If the user presses \"Q\", pygame quits\n keys = pygame.key.get_pressed()\n if keys[pygame.K_q]:\n pygame.quit()",
"def gameover(self):\n self.Display.blit(self.GameOver,[205-self.GameOver.get_width()//2,150-self.GameOver.get_height()//2])\n pygame.draw.rect(self.Display,[200,97,48],(60,230,290,70))\n pygame.draw.rect(self.Display,[200,97,48],(60,320,290,70))\n pygame.draw.rect(self.Display,[106,106,150],(65,235,280,60))\n pygame.draw.rect(self.Display,[106,106,150],(65,325,280,60))\n pygame.display.update()\n self.Display.blit(self.Newgame,[205-self.Newgame.get_width()//2,265-self.Newgame.get_height()//2])\n self.Display.blit(self.Exit,[205-self.Exit.get_width()//2,355-self.Exit.get_height()//2])\n pygame.display.update()\n while True:\n x,y=pygame.mouse.get_pos()\n if x>64 and x<345:\n if y>234 and y<295:\n pygame.draw.rect(self.Display,[200,97,48],(65,235,280,60))\n self.Display.blit(self.Newgame,[205-self.Newgame.get_width()//2,265-self.Newgame.get_height()//2])\n else:\n pygame.draw.rect(self.Display,[106,106,150],(65,235,280,60))\n self.Display.blit(self.Newgame,[205-self.Newgame.get_width()//2,265-self.Newgame.get_height()//2])\n if y>324 and y<386:\n pygame.draw.rect(self.Display,[200,97,48],(65,325,280,60))\n self.Display.blit(self.Exit,[205-self.Exit.get_width()//2,355-self.Exit.get_height()//2])\n else:\n pygame.draw.rect(self.Display,[106,106,150],(65,325,280,60))\n self.Display.blit(self.Exit,[205-self.Exit.get_width()//2,355-self.Exit.get_height()//2])\n pygame.display.update()\n for event in pygame.event.get():\n if event.type==pygame.QUIT:\n self.Game.dontSave()\n return\n elif event.type==pygame.MOUSEBUTTONDOWN:\n x,y=pygame.mouse.get_pos()\n if x>64 and x<345:\n if y>234 and y<296:\n return 'newgame'\n elif y>324 and y<386:\n self.Game.dontSave()\n return",
"def game_over():\n\n global id_after\n global id_text\n\n TERRAIN.after_cancel(id_after)\n id_text = []\n id_text.extend([TERRAIN.create_rectangle((coté * 160 //30,coté * 175 //30),\n (coté * 440 //30, coté * 225 //30), fill = \"black\"),\n TERRAIN.create_text(coté * 300 //30,coté * 200 //30, text = \"GAME OVER\",\n fill = \"red\", font = (\"Helvetica\", coté + 2))])\n \n demande_de_nom()",
"def displayEndingScreen(self):\n self.screen.fill(blackColor)\n\n Title = myfont.render(\"Player %s Wins\"%(self.model.winner), 1, random.choice(all_color))\n self.screen.blit(Title, (670, 300))\n pygame.display.update()",
"def showGameOver():\n\n #On créer une nouvelle fenetre\n win = createNewWin(curses)\n\n #On affiche le texte\n win.addstr(1, 4, 'GAME OVER', curses.color_pair(3))\n win.addstr(2, 4, 'Your Score', curses.color_pair(1)) \n win.addstr(3, 4, '%s - %s' %(game.player.name, game.player.score), curses.color_pair(1))\n win.addstr(4, 4, 'Press 1 to return previous menu', curses.color_pair(1))\n win.addstr(5, 4, '')\n\n #Ajout dans le highscore\n game.highscore.addHighScore(game.player.name, game.player.score)\n game.highscore.writeHighScore()\n\n key = 0\n #Tant que la touche 1 n'est pas pressée...\n #while key!= 343 or key!=10:\n while key != ord('1'):\n #On attend et on 'hook' les touches\n key = win.getch()\n\n #Si on sort de la boucle (1), alors on\n #détruit les fenetres\n destroyWin()\n\n #A la fin de la partie (game over), on affiche l'écran \n menu()",
"def game_over(score: int, high_score: int):\n pygame.init()\n # Create Screen\n screen = pygame.display.set_mode((S_Width, S_Height))\n\n # Create Clock\n clock = pygame.time.Clock()\n\n menu = True\n\n # Create background\n bg = pygame.image.load(\"images/bg.jpg\").convert()\n # help run pygame at consistent speed (convert method)\n bg = pygame.transform.scale(bg, (S_Width, S_Height))\n bg_y_pos = 0\n\n # Create game over title logo\n logo = pygame.image.load(\"images/gameover.png\").convert_alpha()\n logo = pygame.transform.scale(logo, (500, 400))\n\n # Game over menu loop\n while menu:\n # Draw background\n bg_y_pos -= 1\n screen.blit(bg, (0, bg_y_pos))\n screen.blit(bg, (0, S_Height + bg_y_pos))\n screen.blit(logo, (150, 50))\n\n # Draw scores\n display_text(screen, \"High Score : \" + str(high_score), 400, 500, 30)\n display_text(screen, \"Score : \" + str(score), 400, 550, 30)\n\n # Draw text\n display_text(screen, \"Click Anywhere To Play Again\", 400, 650, 30)\n\n # Update position of back ground\n if bg_y_pos < -S_Height:\n bg_y_pos = 0\n\n # Wait for event\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n return\n if event.type == pygame.MOUSEBUTTONUP:\n # Play again\n menu = False\n\n # Update screen\n pygame.display.flip()\n clock.tick(15)\n\n if not menu:\n # Go back to game screen\n game_loop(high_score)",
"def print_game_over():\n print()\n print(\" _____ __ __ ______ ______ ________ _____ \")\n print(r\" / ____| /\\ | \\/ | ____| / __ \\ \\ / / ____| __ \\ \")\n print(r\" | | __ / \\ | \\ / | |__ | | | \\ \\ / /| |__ | |__) |\")\n print(r\" | | |_ | / /\\ \\ | |\\/| | __| | | | |\\ \\/ / | __| | _ / \")\n print(r\" | |__| |/ ____ \\| | | | |____ | |__| | \\ / | |____| | \\ \\ \")\n print(r\" \\_____/_/ \\_\\_| |_|______| \\____/ \\/ |______|_| \\_\\\\\")\n print()",
"def create_game_over_msg(self):\r\n font = pg.font.SysFont(None, int(self.scale_factor * LARGE_FONT))\r\n\r\n # Create and position the game over text\r\n # Render the text to display\r\n self.game_over_text = font.render(\r\n GAME_OVER_TEXT, True, BLACK)\r\n self.game_over_text_rect = self.game_over_text.get_rect()\r\n self.game_over_text_rect.center = self.screen.get_rect().center\r\n self.game_over_text_rect.centery -= ELEMENT_SPACING * \\\r\n self.game_over_text_rect.height",
"def game_over(self, win=False):\n self.is_game_over = True\n\n if win:\n self.flags_pts.set_data(*np.where(self.mines)[::-1]) # shows mines marked with flags\n self.title_txt.set_text('You win! Press F2 to start a new game')\n else:\n self.wrong_img.set_data(self.wrong) # wrong guesses\n self.mines_pts = self.ax.plot(self.jj[self.mines & ~self.flags],\n self.ii[self.mines & ~self.flags],\n 'kX', ms=10) # shows mines\n self.title_txt.set_text('You lose! Press F2 to start a new game')\n\n self.refresh_canvas()",
"async def show_gameover(canvas):\n rows_number, columns_number = canvas.getmaxyx()\n row_size, column_size = get_frame_size(GAMEOVER_FRAME)\n corner_row = rows_number // 2 - row_size // 2\n corner_column = columns_number // 2 - column_size // 2\n\n while True:\n draw_frame(canvas, corner_row, corner_column, GAMEOVER_FRAME)\n await asyncio.sleep(0)",
"def gamemode_lostscreen(self) -> None:\n self.__draw_lostscreen()"
] | [
"0.8934364",
"0.8627453",
"0.8380253",
"0.83757025",
"0.82515734",
"0.8104014",
"0.8089572",
"0.7997276",
"0.7861335",
"0.7776214",
"0.77578104",
"0.7752009",
"0.76158357",
"0.75062186",
"0.7455096",
"0.7430902",
"0.74242336",
"0.74191856",
"0.73100394",
"0.72854185",
"0.7242203",
"0.7234385",
"0.7187759",
"0.7160344",
"0.7089891",
"0.7087447",
"0.70148474",
"0.6999779",
"0.69914365",
"0.69772893"
] | 0.9028957 | 0 |
Login to keycloak and return token | def get_token(self, request_data):
data = {
"grant_type": "password",
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"username": request_data.get("username"),
"password": request_data.get("password"),
}
# create keycloak uri for token login
url = URI + REALM_PREFIX + REALM + AUTH_ENDPOINT
response = requests.post(url, data=data)
# handle error if its anything more than a 200 as a 200 response is the
# only expected response
if response.status_code != 200:
raise AppException.KeyCloakAdminException(
context={"message": "Error in username or password"},
status_code=response.status_code,
)
tokens_data = response.json()
result = {
"access_token": tokens_data["access_token"],
"refresh_token": tokens_data["refresh_token"],
}
return result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def login(self):\n r = self._login_token()",
"def login():\n\n if not config.requires_auth():\n abort(403,\n \"authentication not permitted since service is in insecure mode\")\n\n info = request.get_json() or {}\n username = info.get('username')\n password = info.get('password')\n user_domain_name = info.get('user_domain_name', 'Default')\n token = _authenticate(CONF.keystone_authtoken.auth_url,\n username,\n password,\n user_domain_name)\n return jsonify(token)",
"def login(self):\n # create auth payload\n payload = '{{\"grant_type\": \"password\", \"username\": \"{}\", \"password\": \"{}\"}}'.format(\n self.username, self.password)\n auth_headers = {**FTDClient.headers}\n r = requests.post(\"https://{}:{}/api/fdm/{}/fdm/token\".format(self.server_address, self.server_port, self.version),\n data=payload, verify=False, headers=auth_headers)\n if r.status_code == 400:\n raise Exception(\"Error logging in: {}\".format(r.content))\n try:\n # This token will act as the\n self.access_token = r.json()['access_token']\n # cache the original token in case we do a custom login\n self.original_access_token = self.access_token\n except:\n logging.error(\n f'Unable to log into server: https://{self.server_address}:{self.server_port}')\n raise",
"def login(self):\n\n # Build the authentication url\n url = '{}{}'.format(self.datasource.location, self.auth_token_path)\n try:\n\n # Login to the Data Source\n res = requests.post(url, params={\"scope\": self.auth_scope, \"grant_type\": self.grant_type},\n auth=(self.client_id, self.client_secret),\n verify=self.verify_ssl)\n\n # Validate the response\n if res.status_code != requests.codes.ok:\n logger.error(\"Authentication error {}: {}\".format(url, res.content))\n return None\n\n # Get the JSON content (This has the token)\n result_json = res.json()\n self.token = result_json\n except Exception as e:\n logger.error(\"Authentication error {}: {}\".format(url, e))\n # TODO: create exception for this\n # Access is denied!!\n raise Exception(\"AccessDenied\")",
"def login():\n token = request.form.get('idtoken')\n if verify_token(token):\n session['logged_in'] = True\n return '', 204\n else:\n return '', 401",
"def login_user(self):\n response = self.client.post(self.login_url, self.login_data, format='json')\n return response.data['token']",
"def _login_token(self):\n data = {\n 'cmd': 'login',\n 'login': self.username,\n 'password': self.password,\n }\n \n token = self.helper._post_request(\n self.basename,\n self.basic_auth,\n data, \n self.headers)\n\n if token.status_code == 200:\n xml_response = BeautifulSoup(token.content, 'lxml')\n self.token = xml_response.find('token').get_text()\n self.cookies = token.cookies.get_dict()\n else:\n raise Exception('[FAIL] Could not login to OpenVAS')",
"def get_token(self):\n response = self.client.post(\n url_for('auth.login'),\n data=json.dumps({'username': '[email protected]', 'password': 'denno'}),\n headers={'content_type': 'application/json'})\n return json.loads(response.data)['token']",
"def login():\n req = request.get_json(force=True)\n username = req.get('username', None)\n password = req.get('password', None)\n user = guard.authenticate(username, password)\n ret = {'access_token': guard.encode_jwt_token(user)}\n return ret, 200",
"def login():\n data = request.get_json()\n if 'username' in data and 'password' in data:\n username = data['username']\n password = data['password']\n access_token = authenticate(username, password)\n if access_token is not None:\n print('access token: ' + access_token)\n return jsonify({'access_token': access_token})\n else:\n abort(403)\n else:\n abort(400)",
"def _login(\n self,\n username: str,\n password: str\n ) -> requests.models.Response:\n url = 'v1/auth-token'\n auth = {'username': username, 'password': password}\n response = self.post(url, auth)\n print(response)\n token = response.json()['token']\n self.session.headers.update(\n {\n 'Authorization': 'Token {token}'.format(token=token),\n 'Accept': 'application/json'\n }\n )\n return response",
"def login():\n req = flask.request.get_json(force=True)\n username = req.get('username', None)\n password = req.get('password', None)\n user = guard.authenticate(username, password)\n ret = {'access_token': guard.encode_jwt_token(user)}\n return ret, 200",
"def get():\n return login()",
"async def login(form_data: OAuth2PasswordRequestForm = Depends()):\n db = get_database()\n\n user = await crud.user.authenticate(\n db, username=form_data.username, password=form_data.password\n )\n\n if not user:\n raise HTTPException(\n status_code=HTTP_400_BAD_REQUEST, detail=\"Incorrect email or password\"\n )\n elif not crud.user.is_active(user):\n raise HTTPException(\n status_code=HTTP_400_BAD_REQUEST, detail=HTTP_400_BAD_REQUEST_INACTIVE_USER\n )\n\n access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)\n\n return {\n \"access_token\": create_access_token(\n data={\"username\": user.username}, expires_delta=access_token_expires\n ),\n \"token_type\": \"bearer\",\n }",
"def login(self):\n url = self._root + self._routes[\"login\"]\n self.r = self.reqsession.get(url) \n if self.r.url == 'https://console.zerodha.com/dashboard':\n cookies = self.reqsession.cookies.get_dict('console.zerodha.com')\n self.console_session = cookies['session']\n self.public_token = self.reqsession.cookies['public_token']\n return True\n else:\n raise Exception(\"Login failed or Kite session expired\")",
"def login(self):\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n token_url = urljoiner(self.baseurl, [\"connect/token\"])\n if(self.debug):\n print(token_url)\n new_auth = dict(self.auth_data)\n new_auth['password'] = \"XXXXX\"\n print(\"Authentication Data (without password):\")\n print(new_auth)\n r = requests.post(token_url, data=self.auth_data, headers=headers)\n # New environments do not redirect /rest/connect/token to\n # /auth/connect/token so lets check this case explicitly\n if(r.status_code > 400):\n new_token_url = self.baseurl.rstrip(\n \"/rest\") + \"/auth/connect/token\"\n if(self.debug):\n print(\"cannot connect to: \" + token_url)\n print(\"trying: \" + new_token_url)\n r = requests.post(\n new_token_url,\n data=self.auth_data,\n headers=headers)\n self.last_login = time.time()\n self.handle_error_message(r)\n self.auth_result = r.json()\n access_token = r.json().get('access_token')\n self.headers = {'Authorization': 'Bearer ' + access_token,\n 'Content-Type': 'application/json'}\n # Always relogin when time remaining on the current token is in between 1 min and 3 min\n self.refresh_window = min(max(60, 0.01 * self.auth_result['expires_in']), 180)",
"def login_access_token(form_data: OAuth2PasswordRequestForm = Depends()):\n user = auth_handler.authenticate_user(\n username=form_data.username, password=form_data.password\n )\n if user is None:\n raise HTTPException(\n detail=\"Incorrect username and/or password\", status_code=400\n )\n\n return APIResponse(\n msg=TokenResponse(\n access_token=auth_handler.encode_token(user.id), token_type=\"bearer\"\n )\n )",
"def GetToken(self):\n if self.auth_token_:\n return self.auth_token_\n raise RuntimeError('ClientLoginAuthPolicy is not logged in.')",
"def skyserv_authenticator(self):\n \n header = {\n 'Content-Type': accept, \n 'X-Auth-Token': self.casjobtoken,\n 'Accept': accept\n }\n # this format is disgusting but required....\n authdata = {\n 'auth' :{\n 'identity': {\n 'password': {\n 'user': {\n 'name': username,\n 'password': password\n }\n }\n }\n }\n }\n payload = json.dumps(authdata).encode(encoding='utf-8')\n try:\n post = requests.post(self.loginurl, data=payload, headers=header)\n\n if post.status_code == 200:\n response = json.loads(post.text)\n token = response[self.tokenkey]\n return token\n else:\n print('Username and/or password are invalid.')\n post.raise_for_status()\n except Exception as e:\n raise(str(e))",
"async def login_access_token(\n form_data: OAuth2PasswordRequestForm = Depends()\n):\n user = await crud.user.authenticate(\n username=form_data.username, password=form_data.password\n )\n if not user:\n raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail=\"Incorrect credentials\")\n elif not user.is_active:\n raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail=\"Inactive user\")\n elif not user.is_email_verified:\n raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail=\"Please verify your account via email\")\n access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)\n return {\n \"access_token\": create_access_token(\n data={\"user_id\": user.id}, expires_delta=access_token_expires\n ),\n \"token_type\": \"bearer\",\n }",
"def login():\n username = request.json.get('username')\n password = request.json.get('password')\n\n if verify_password(username, password):\n token = g.user.generate_auth_token()\n status = \"token generated successfully\"\n else:\n status = \"Invalid username or password\"\n token = None\n\n return {'status': status, 'token': token}",
"async def login(form_data: LoginForm = Depends()) -> Token:\n user = AuthUser.authenticate_user(form_data.username, form_data.password)\n if not user:\n raise HTTPException(\n status_code=status.HTTP_401_UNAUTHORIZED,\n detail=\"Incorrect username or password\",\n headers={\"WWW-Authenticate\": \"Bearer\"},\n )\n elif not user.is_active: # type: ignore\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,\n detail=\"Inactive user\")\n elif user.is_superuser: # type: ignore\n expire_minutes = settings.ACCESS_TOKEN_EXPIRE_MINUTES_ADMIN\n else:\n expire_minutes = settings.ACCESS_TOKEN_EXPIRE_MINUTES\n access_token_expires = timedelta(minutes=expire_minutes)\n access_token = create_access_token(\n subject=user.username, expires_delta=access_token_expires # type: ignore\n )\n return Token(access_token=access_token, token_type=\"Bearer\") # nosec",
"def token(c):\n command = (\n 'kubectl -n kubernetes-dashboard describe secret '\n \"$(kubectl -n kubernetes-dashboard get secret | grep admin-user-token | awk '{print $1}')\"\n )\n _print_command('Get token to use for loggin in', command)\n if _prompt():\n c.run(command)",
"def login(**kwargs):\n data = request.get_json()\n print(\"data={}\".format(data))\n login = data.get('username')\n password = data.get('password')\n\n if not login or not password:\n raise Unauthorized('Wrong username and/or password.')\n else:\n user = app.data.driver.session.query(User).get(login)\n if user and user.check_password(password):\n token = user.generate_auth_token()\n return jsonify({'token': token.decode('ascii')})\n raise Unauthorized('Wrong username and/or password.')",
"def get_keystone_token():\n req_json = {\n 'auth': {\n 'passwordCredentials': {\n 'username': CFG.username,\n 'password': CFG.password\n },\n },\n }\n\n header = '{\"Host\": \"identity.api.rackspacecloud.com\",'\n header += '\"Content-Type\": \"application/json\",\"Accept\":\"application/json\"}'\n url = CFG.auth_url\n\n response = http.post(url=url, header=header, body=req_json)\n response_body = json.loads(response.text)\n\n auth_token = response_body['access']['token']['id']\n\n return auth_token",
"async def login_for_access_token(\n form_data: OAuth2PasswordRequestForm = Depends()\n):\n user = authenticate_user(form_data.username, form_data.password)\n if not user:\n raise HTTPException(\n status_code=status.HTTP_401_UNAUTHORIZED,\n detail=\"Incorrect username or password\",\n headers={\"WWW-Authenticate\": \"Bearer\"},\n )\n access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)\n access_token = create_access_token(\n data={\"sub\": user.username}, expires_delta=access_token_expires\n )\n return {\"access_token\": access_token, \"token_type\": \"bearer\"}",
"def login_access_token(\n db: Session = Depends(get_db),\n form_data: OAuth2PasswordRequestForm = Depends()\n) -> Any:\n user = crud.user.authenticate(\n db, email=form_data.username, password=form_data.password\n )\n if not user:\n raise HTTPException(\n status_code=400, detail=\"Incorrect email or password\")\n elif not crud.user.is_active(user):\n raise HTTPException(status_code=400, detail=\"Inactive user\")\n access_token_expires = timedelta(\n minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)\n return {\n \"access_token\": security.create_access_token(\n user.id, expires_delta=access_token_expires\n ),\n \"token_type\": \"bearer\",\n }",
"def login(self):\n login = self.client.login(username=self.username, password=self.password)\n return login",
"def login(self):\n login = self.client.login(username=self.username, password=self.password)\n return login",
"def login():\n\n username = str(request.parsed_json['username'])\n password = str(request.parsed_json['password'])\n\n if not auth.check_password(username, password):\n return create_error(401, \"login failed\")\n\n return auth.create_auth_token(username, password), 200"
] | [
"0.7417756",
"0.72780955",
"0.69483435",
"0.6918456",
"0.6906847",
"0.68530303",
"0.6837997",
"0.6831651",
"0.6775747",
"0.6758572",
"0.6721111",
"0.6658082",
"0.6657504",
"0.6647679",
"0.6645076",
"0.664235",
"0.662512",
"0.662396",
"0.6620616",
"0.66099817",
"0.6600765",
"0.65919036",
"0.65720373",
"0.6564421",
"0.6547474",
"0.6544895",
"0.65312594",
"0.6530729",
"0.6530729",
"0.65215313"
] | 0.7308726 | 1 |
Make a POST request to Keycloak | def keycloak_post(self, endpoint, data):
url = URI + "/auth/admin/realms/" + REALM + endpoint
headers = self.headers or self.get_keycloak_headers()
response = requests.post(url, headers=headers, json=data)
if response.status_code >= 300:
raise AppException.KeyCloakAdminException(
context={"message": response.json().get("errorMessage")},
status_code=response.status_code,
)
return response | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def make_post_request(self, url, data):\n auth = (self.AUTH_ID, self.AUTH_TOKEN)\n headers = {'content-type': 'application/json'}\n return requests.post(url, data=data, auth=auth, headers=headers)",
"def _post(self, *args, **kwargs):\n return self._request('post', *args, **kwargs)",
"def httpPost(self, url, post_parameters=None):\r\n return self.auth.post(url, post_parameters)",
"def post(self, *args, **kwargs):\n return self._requests_call(util.requests_post, *args, **kwargs)",
"def post_form(url, headers, payload):\n\n headers['Content-Type'] = 'application/x-www-form-urlencoded'\n\n return RestClient.make_post_request(url, headers=headers, data=payload)",
"def make_post_request(client, endpoint, data):\n return client.post(endpoint, data=data)",
"def post(self, *args, **kwargs):\n self.request(\"post\", *args, **kwargs)",
"def post(self, *args, **kwargs):\n return self._hit(\"POST\", *args, **kwargs)",
"def post(self, *path, **data):\n\t\treturn self.request('POST', *path, **data)",
"def do_POST(self,):\n self.http_method = 'POST'\n self.response()",
"def _api_post(self, query, data):\n r = requests.post(self._url + query,\n headers={'Content-Type': 'application/json', 'Accept': 'application/json'},\n auth=self._auth, data=json.dumps(data), timeout=self._request_timeout_secs)\n r.raise_for_status()\n return r",
"def _post(self, data=None, headers=None):\n return self.api.send_http_request_v2(method=\"POST\", url=\"https://auth.iqoption.com/api/v2/verify/2fa\",data=json.dumps(data), headers=headers)",
"def post(self, *args, **kwargs):\n headers = self.post_headers\n headers.update(kwargs.get('headers', {}))\n kwargs['headers'] = headers\n return self._request('post', *args, **kwargs)",
"def _post(self, url, data=None):\n if data is not None:\n data = urllib.urlencode(data)\n return self._request(url, method='POST', payload=data)",
"def http_post(self, **kwargs):\n return self.rabjcallable.post(**kwargs)",
"def post(self):\n\n data = request.get_json()\n # data = request.data\n print(\"data: \", data)\n\n arg_parser = reqparse.RequestParser()\n arg_parser.add_argument(\n \"exp\",\n default=15552000,\n help=\"Parameter must be an integer\",\n type=int\n )\n\n args = arg_parser.parse_args()\n\n print(args)\n\n auth = request.authorization\n print(\"auth req: \", auth)\n if not auth:\n # Try extracting from POST body\n print(\"here\")\n auth = request.get_json()\n print(\"here\")\n print(\"auth: \", auth)\n if not auth or not (\"email\" in auth and \"password\" in auth):\n abort(401, \"Missing authentication credentials\")\n\n # if auth[\"is_driver\"]:\n # # if it is a driver\n # user = Driver.identify(auth[\"email\"])\n # password = auth[\"password\"]\n\n # else:\n # # If it is a restaurant\n # user = Restaurant.identify(auth[\"email\"])\n # password = auth[\"password\"]\n\n is_driver = True\n\n user = Driver.identify(auth[\"email\"])\n password = auth[\"password\"]\n\n if not user:\n user = Restaurant.identify(auth[\"email\"])\n is_driver = False\n\n if not user or not user.verify_password(password):\n current_app.logger.warn(\n \"Incorrect credentials for {} from {}\".format(\n auth[\"email\"],\n *request.access_route\n )\n )\n abort(401, \"Incorrect email or password\")\n\n access_token = user.gen_access_token(args[\"exp\"])\n\n current_app.logger.info(\"[AUTH] User {} logged IN from {}\".format(\n user.email,\n *request.access_route\n ))\n\n access_token.update({\n \"is_driver\": is_driver\n })\n\n # return resp, 200\n return access_token",
"def render_POST(self, request):\n # Make sure simple_auth_key is a good key\n auth_key = request.args[\"simple_auth_key\"][0]\n if auth_key != \"abc\":\n defer.returnValue(str(webapi.ValueError(request, \n \"simple_auth_key\",\n \"Key isn't valid!\")))\n \n # Test latency to request example.com\n start_time = time.time()\n web_agent = Agent(reactor)\n resp = yield web_agent.request(\"GET\", \"http://example.com\")\n end_time = time.time()\n \n # new_client is an optional parameter,\n # so set a default value if it isn't present\n # in the JSON arguments\n new_client = False\n if request.jsonArgs.has_key(\"new_client\"):\n new_client = request.jsonArgs[\"new_client\"]\n \n # Return a JSON dictionary as the API call result.\n return_dict = {\"result\" : {\"latency\" : end_time-start_time,\n \"client_tz\" : request.jsonArgs[\"client_tz\"],\n \"client_id\" : request.jsonArgs[\"client_id\"],\n \"new_client\" : request.jsonArgs[\"new_client\"]}}\n \n defer.returnValue(json.dumps(return_dict))",
"def token_request(post_data, auth_config, conformance):\n auth = None\n if auth_config.get('confidential_client'):\n auth = requests.auth.HTTPBasicAuth(auth_config['client_id'],\n auth_config['client_secret'])\n\n uris = fhir.get_oauth_uris(conformance)\n\n response = requests.post(uris['token'],\n data=post_data,\n allow_redirects=False,\n auth=auth,\n timeout=5)\n\n return response",
"def post(self):\n\n if config.logging:\n logfile.info(\"Request to /rest/broadsoft recieved\")\n if config.verbose:\n logconsole.info(\"Request to /rest/broadsoft recieved\")\n\n # Ensure that the user has sent a jwt to the endpoint.\n try:\n verify_jwt_in_request()\n except Exception as error:\n return make_response(\"<error>Unauthorized</error>\", 401)\n\n # Create a user object from the JWT identity object.\n user = User().from_identity(get_jwt_identity())\n\n # Check if a user was able to be created.\n if user is None:\n return \"<ErrorInfo><message>Not logged in</message><error>true</error></ErrorInfo>\", 401\n\n # Create a request parser to parse arguments\n parser = reqparse.RequestParser()\n\n # Configure endpoint arguments.\n parser.add_argument(\n name='endpoint',\n help='Missing the required broadsoft endpoint to connect to.',\n required=True)\n\n parser.add_argument(\n name='data',\n type=str,\n help='JSON data needs to be a string')\n\n parser.add_argument(\n name='method',\n help='Missing method type. ex) method:GET/PUT/POST...',\n required=True)\n\n # Check if the arguments passed were valid.\n try:\n args = parser.parse_args()\n except reqparse.exceptions.BadRequest as e:\n # If there are any errors, ensure that login=False is sent.\n message = \"<error>true</error>\"\n return message, 400\n\n # Get the data sent from the request.\n url = self.url + args['endpoint'].replace(\"<user>\", user.username)\n data = \"\"\n method = args['method']\n\n # Check if any data was sent\n if(args['data']):\n data = args['data']\n\n if config.logging:\n logfile.info(\"Sending data: \" + method + \" \" + url + \" \" + data)\n if config.verbose:\n logconsole.info(\"Sending data: \" + method + \" \" + url + \" \" + data)\n\n # Get the user's broadsoft token from the JWT and send a request to broadsoft.\n response = Proxy().to_broadsoft(method, url, data, user)\n\n # Check if a valid response was returned.\n if response.status_code == 200 or response.status_code == 201:\n\n # Output a response to the console and log files.\n if config.logging:\n logfile.info(\"Recieved:\" + str(response.status_code) + \" \" + str(response.content) if response.content else \"Recieved: \" + str(response.status_code))\n if config.verbose:\n logconsole.info(\"Recieved:\" + str(response.status_code) + \" \" + str(response.content) if response.content else \"Recieved: \" + str(response.status_code))\n\n # Format a response\n if response.content:\n return make_response(str(response.content.decode('ISO-8859-1')), 200)\n else:\n return make_response(\"\", 200)\n else:\n if config.logging:\n logfile.info(\"Recieved:\" + str(response.status_code) + \" \" + response.content.decode('ISO-8859-1') if response.content else \"\")\n if config.verbose:\n logconsole.info(\"Recieved:\" + str(response.status_code) + \" \" + response.content.decode('ISO-8859-1') if response.content else \"\")\n\n if response.content:\n return make_response(response.content.decode('ISO-8859-1'), response.status_code)\n else:\n return make_response(\"\", response.status_code)",
"def send_post(self, data):\n\n self.post_data = data\n self.post_data['csrfmiddlewaretoken'] = self.csrftoken\n self.response = self.client.post(self.url, self.post_data, cookies=self.cookies)",
"def post(self, url, data):\r\n print(f\"POST {url}\")\r\n print(\"data:\")\r\n self.pp.pprint(data)\r\n response = self.session.post(url, data=data)\r\n print(f\"STATUS {response.status_code}\")\r\n self.print_cookies()\r\n return response",
"def http_method_post():\n return 'POST'",
"def auth_postrequest_json(self, url, token, params):\n headers = {\n \"Authorization\": token,\n \"Content-Type\": \"application/json\"\n }\n\n response = self.postrequest_json(url, params, headers)\n return response",
"def post(self, **kwargs):\n return self.client.post(\n self.url(), data=json.dumps(kwargs),\n content_type='application/json')",
"def post(self, url, payload={}):\n response = self._make_request(\"POST\", url, payload)\n\n return response",
"def do_POST(self):\r\n self._send_handler_response('POST')",
"def mock_software_secure_post(url, headers=None, data=None, **kwargs):\r\n data_dict = json.loads(data)\r\n\r\n # Basic sanity checking on the keys\r\n EXPECTED_KEYS = [\r\n \"EdX-ID\", \"ExpectedName\", \"PhotoID\", \"PhotoIDKey\", \"SendResponseTo\",\r\n \"UserPhoto\", \"UserPhotoKey\",\r\n ]\r\n for key in EXPECTED_KEYS:\r\n assert_true(\r\n data_dict.get(key),\r\n \"'{}' must be present and not blank in JSON submitted to Software Secure\".format(key)\r\n )\r\n\r\n # The keys should be stored as Base64 strings, i.e. this should not explode\r\n photo_id_key = data_dict[\"PhotoIDKey\"].decode(\"base64\")\r\n user_photo_key = data_dict[\"UserPhotoKey\"].decode(\"base64\")\r\n\r\n response = requests.Response()\r\n response.status_code = 200\r\n\r\n return response",
"def get(self):\n self.post()",
"def post(self, key=None):\n parser = reqparse.RequestParser()\n parser.add_argument('Content-Type', type=str, location='headers',\n choices='application/json', required=True)\n parser.add_argument('user', type=str, location='json', required=True)\n parser.add_argument('password', type=str, location='json',\n required=True)\n arg = parser.parse_args()\n\n # Check credentials\n user = arg['user']\n password = arg['password']\n if self.check_passwd(user, password) is not None:\n key = self.gen_seskey()\n self.sessions[key] = user\n return response(201, {'key': key})\n\n return response(403, {\"code\": 5, \"desc\": \"invalid username or password\"})",
"def test_post(self):\n return self.doRequest(self.url, method=\"POST\", body=self.input)"
] | [
"0.667645",
"0.66198164",
"0.6501933",
"0.6406782",
"0.6370854",
"0.63279456",
"0.62768614",
"0.62191147",
"0.61914456",
"0.6173238",
"0.6134342",
"0.60690194",
"0.60622585",
"0.6061434",
"0.60564816",
"0.60508764",
"0.60361385",
"0.6034236",
"0.6029803",
"0.6023713",
"0.60191524",
"0.60166",
"0.5981721",
"0.5974362",
"0.59736896",
"0.59662193",
"0.59466904",
"0.5937779",
"0.5917846",
"0.5894731"
] | 0.6761658 | 0 |
Method for setting up the fullname | def fullname(self):
return '{} {}'.format(self.fname,self.lname) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def set_fullname(self, value):\n self.fullname = value",
"def set_fullname(self, value):\n raise NotImplementedError('set_fullname')",
"def full_name(self,first_name):\n full_name = self.first_name + ' ' + self.last_name\n return full_name",
"def fullname(self):\n return self.fname() + ' ' + self.lname()",
"def print_fullname(self):\n print('Full name : ', self.first_name + self.Last_name)\n return \"\"",
"def print_fullname(self):\n print('Full name : ', self.first_name + self.Last_name)\n return \"\"",
"def print_fullname(self):\n print('Full name : ', self.first_name + self.Last_name)\n return \"\"",
"def format_name(self):\n\t\tself.full_name = self.first + \" \" + self.last",
"def get_fullname(self):\n raise NotImplementedError('get_fullname')",
"def fullname(self, name):\n\n first, last = name.split(' ')\n self.first = first\n self.last = last",
"def set_name(self):\n if self.first_name and self.last_name:\n name_string = \"%s\" % self.first_name\n name_string += \" %s\" % self.last_name\n self.name = name_string\n\n if self.name:\n if not self.first_name and not self.last_name:\n n = HumanName(self.name)\n self.first_name = n.first\n if n.middle:\n self.first_name = n.first + \" \" + n.middle\n self.last_name = n.last\n if n.suffix:\n self.last_name = n.last + \" \" + n.suffix",
"def full_name(self):\n \tif self.first_name and self.last_name:\n \t\treturn \"{} {}\".format(self.first_name, self.last_name)",
"def full_name(self):\n return f\"{self.first_name} {self.last_name}\"",
"def full_name(self):\n return f\"{self.first_name} {self.last_name}\"",
"def full_name(self):\n return f\"{self.first_name} {self.last_name}\"",
"def fullname(self, name):\n f, l = name.split(' ')\n self.first = f\n self.last = l",
"def _get_full_name(self):\n if self.middle_name:\n return u'%s %s %s' % (self.first_name, self.middle_name,\n self.last_name)\n else:\n return u'%s %s' % (self.first_name, self.last_name)",
"def get_full_name(self):\n return f\"{self.first_name} {self.last_name}\"",
"def get_full_name(self):\n return f\"{self.first_name} {self.last_name}\"",
"def get_full_name(self):\n return f'{self.first_name} {self.last_name}'",
"def get_full_name(self):\n full_name = f'{self.first_name} {self.last_name}' if self.first_name and self.last_name else self.username\n return full_name.strip()",
"def get_full_name(self):\n full_name = '%s %s' % (self.first_name, self.last_name)\n return full_name.strip()",
"def get_full_name(self) -> str:\n return f\"{self.first_name} {self.last_name}\"",
"def fullname(self):\n parts = []\n self.lastname and parts.append(self.lastname)\n self.firstname and parts.append(self.firstname)\n len(parts) == 0 and parts.append(self.userid)\n\n return ' '.join(parts)",
"def get_full_name(self):\n full_name = '{0} {1} {2}'.format(self.last_name, self.first_name, self.patronymic)\n return full_name.strip()",
"def get_full_name(self):\n return \"{0} {1}\".format(self.first_name, self.last_surname)",
"def get_full_name(self):\n full_name = \"%s %s\" % (self.firstname, self.lastname)\n return full_name.strip()",
"def get_full_name(self):\n return self.name+self.last_name",
"def full_name(self):\n return u\"{} {}\".format(self.pref_first_name(), self.last_name)",
"def full_name(first_name, last_name):\n\t\n\treturn first_name + \" \" + last_name"
] | [
"0.799368",
"0.7541357",
"0.7510396",
"0.74507093",
"0.73845243",
"0.73845243",
"0.73845243",
"0.73819816",
"0.7323252",
"0.7312589",
"0.7297851",
"0.7267998",
"0.7216746",
"0.7216746",
"0.7216746",
"0.7205875",
"0.71811813",
"0.716795",
"0.716795",
"0.7139923",
"0.71317744",
"0.71317637",
"0.7121691",
"0.7120027",
"0.71031046",
"0.71004784",
"0.7076726",
"0.705628",
"0.70461285",
"0.70426184"
] | 0.75518876 | 1 |
Subsets and Splits