Best JavaScript code snippet using ava
views.py
Source:views.py
...204# - password_reset_confirm checks the link the user clicked and205# prompts for a new password206# - password_reset_complete shows a success message for the above207@csrf_protect208def password_reset(request,209 template_name='registration/password_reset_form.html',210 email_template_name='registration/password_reset_email.html',211 subject_template_name='registration/password_reset_subject.txt',212 password_reset_form=PasswordResetForm,213 token_generator=default_token_generator,214 post_reset_redirect=None,215 from_email=None,216 extra_context=None,217 html_email_template_name=None,218 extra_email_context=None):219 warnings.warn("The password_reset() view is superseded by the "220 "class-based PasswordResetView().",221 RemovedInDjango21Warning, stacklevel=2)222 if post_reset_redirect is None:223 post_reset_redirect = reverse('password_reset_done')224 else:225 post_reset_redirect = resolve_url(post_reset_redirect)226 if request.method == "POST":227 form = password_reset_form(request.POST)228 if form.is_valid():229 opts = {230 'use_https': request.is_secure(),231 'token_generator': token_generator,232 'from_email': from_email,233 'email_template_name': email_template_name,...
zynqmp_pm_cfg_obj_convert.py
Source:zynqmp_pm_cfg_obj_convert.py
1#!/usr/bin/env python32# SPDX-License-Identifier: GPL-2.0+3# Copyright (C) 2019 Luca Ceresoli <luca@lucaceresoli.net>4import sys5import re6import struct7import logging8import argparse9parser = argparse.ArgumentParser(10 description='Convert a PMU configuration object from C source to a binary blob.')11parser.add_argument('-D', '--debug', action="store_true")12parser.add_argument(13 "in_file", metavar='INPUT_FILE',14 help='PMU configuration object (C source as produced by Xilinx XSDK)')15parser.add_argument(16 "out_file", metavar='OUTPUT_FILE',17 help='PMU configuration object binary blob')18args = parser.parse_args()19logging.basicConfig(format='%(levelname)s:%(message)s',20 level=(logging.DEBUG if args.debug else logging.WARNING))21pm_define = {22 'PM_CAP_ACCESS' : 0x1,23 'PM_CAP_CONTEXT' : 0x2,24 'PM_CAP_WAKEUP' : 0x4,25 'NODE_UNKNOWN' : 0,26 'NODE_APU' : 1,27 'NODE_APU_0' : 2,28 'NODE_APU_1' : 3,29 'NODE_APU_2' : 4,30 'NODE_APU_3' : 5,31 'NODE_RPU' : 6,32 'NODE_RPU_0' : 7,33 'NODE_RPU_1' : 8,34 'NODE_PLD' : 9,35 'NODE_FPD' : 10,36 'NODE_OCM_BANK_0' : 11,37 'NODE_OCM_BANK_1' : 12,38 'NODE_OCM_BANK_2' : 13,39 'NODE_OCM_BANK_3' : 14,40 'NODE_TCM_0_A' : 15,41 'NODE_TCM_0_B' : 16,42 'NODE_TCM_1_A' : 17,43 'NODE_TCM_1_B' : 18,44 'NODE_L2' : 19,45 'NODE_GPU_PP_0' : 20,46 'NODE_GPU_PP_1' : 21,47 'NODE_USB_0' : 22,48 'NODE_USB_1' : 23,49 'NODE_TTC_0' : 24,50 'NODE_TTC_1' : 25,51 'NODE_TTC_2' : 26,52 'NODE_TTC_3' : 27,53 'NODE_SATA' : 28,54 'NODE_ETH_0' : 29,55 'NODE_ETH_1' : 30,56 'NODE_ETH_2' : 31,57 'NODE_ETH_3' : 32,58 'NODE_UART_0' : 33,59 'NODE_UART_1' : 34,60 'NODE_SPI_0' : 35,61 'NODE_SPI_1' : 36,62 'NODE_I2C_0' : 37,63 'NODE_I2C_1' : 38,64 'NODE_SD_0' : 39,65 'NODE_SD_1' : 40,66 'NODE_DP' : 41,67 'NODE_GDMA' : 42,68 'NODE_ADMA' : 43,69 'NODE_NAND' : 44,70 'NODE_QSPI' : 45,71 'NODE_GPIO' : 46,72 'NODE_CAN_0' : 47,73 'NODE_CAN_1' : 48,74 'NODE_EXTERN' : 49,75 'NODE_APLL' : 50,76 'NODE_VPLL' : 51,77 'NODE_DPLL' : 52,78 'NODE_RPLL' : 53,79 'NODE_IOPLL' : 54,80 'NODE_DDR' : 55,81 'NODE_IPI_APU' : 56,82 'NODE_IPI_RPU_0' : 57,83 'NODE_GPU' : 58,84 'NODE_PCIE' : 59,85 'NODE_PCAP' : 60,86 'NODE_RTC' : 61,87 'NODE_LPD' : 62,88 'NODE_VCU' : 63,89 'NODE_IPI_RPU_1' : 64,90 'NODE_IPI_PL_0' : 65,91 'NODE_IPI_PL_1' : 66,92 'NODE_IPI_PL_2' : 67,93 'NODE_IPI_PL_3' : 68,94 'NODE_PL' : 69,95 'NODE_ID_MA' : 70,96 'XILPM_RESET_PCIE_CFG' : 1000,97 'XILPM_RESET_PCIE_BRIDGE' : 1001,98 'XILPM_RESET_PCIE_CTRL' : 1002,99 'XILPM_RESET_DP' : 1003,100 'XILPM_RESET_SWDT_CRF' : 1004,101 'XILPM_RESET_AFI_FM5' : 1005,102 'XILPM_RESET_AFI_FM4' : 1006,103 'XILPM_RESET_AFI_FM3' : 1007,104 'XILPM_RESET_AFI_FM2' : 1008,105 'XILPM_RESET_AFI_FM1' : 1009,106 'XILPM_RESET_AFI_FM0' : 1010,107 'XILPM_RESET_GDMA' : 1011,108 'XILPM_RESET_GPU_PP1' : 1012,109 'XILPM_RESET_GPU_PP0' : 1013,110 'XILPM_RESET_GPU' : 1014,111 'XILPM_RESET_GT' : 1015,112 'XILPM_RESET_SATA' : 1016,113 'XILPM_RESET_ACPU3_PWRON' : 1017,114 'XILPM_RESET_ACPU2_PWRON' : 1018,115 'XILPM_RESET_ACPU1_PWRON' : 1019,116 'XILPM_RESET_ACPU0_PWRON' : 1020,117 'XILPM_RESET_APU_L2' : 1021,118 'XILPM_RESET_ACPU3' : 1022,119 'XILPM_RESET_ACPU2' : 1023,120 'XILPM_RESET_ACPU1' : 1024,121 'XILPM_RESET_ACPU0' : 1025,122 'XILPM_RESET_DDR' : 1026,123 'XILPM_RESET_APM_FPD' : 1027,124 'XILPM_RESET_SOFT' : 1028,125 'XILPM_RESET_GEM0' : 1029,126 'XILPM_RESET_GEM1' : 1030,127 'XILPM_RESET_GEM2' : 1031,128 'XILPM_RESET_GEM3' : 1032,129 'XILPM_RESET_QSPI' : 1033,130 'XILPM_RESET_UART0' : 1034,131 'XILPM_RESET_UART1' : 1035,132 'XILPM_RESET_SPI0' : 1036,133 'XILPM_RESET_SPI1' : 1037,134 'XILPM_RESET_SDIO0' : 1038,135 'XILPM_RESET_SDIO1' : 1039,136 'XILPM_RESET_CAN0' : 1040,137 'XILPM_RESET_CAN1' : 1041,138 'XILPM_RESET_I2C0' : 1042,139 'XILPM_RESET_I2C1' : 1043,140 'XILPM_RESET_TTC0' : 1044,141 'XILPM_RESET_TTC1' : 1045,142 'XILPM_RESET_TTC2' : 1046,143 'XILPM_RESET_TTC3' : 1047,144 'XILPM_RESET_SWDT_CRL' : 1048,145 'XILPM_RESET_NAND' : 1049,146 'XILPM_RESET_ADMA' : 1050,147 'XILPM_RESET_GPIO' : 1051,148 'XILPM_RESET_IOU_CC' : 1052,149 'XILPM_RESET_TIMESTAMP' : 1053,150 'XILPM_RESET_RPU_R50' : 1054,151 'XILPM_RESET_RPU_R51' : 1055,152 'XILPM_RESET_RPU_AMBA' : 1056,153 'XILPM_RESET_OCM' : 1057,154 'XILPM_RESET_RPU_PGE' : 1058,155 'XILPM_RESET_USB0_CORERESET' : 1059,156 'XILPM_RESET_USB1_CORERESET' : 1060,157 'XILPM_RESET_USB0_HIBERRESET' : 1061,158 'XILPM_RESET_USB1_HIBERRESET' : 1062,159 'XILPM_RESET_USB0_APB' : 1063,160 'XILPM_RESET_USB1_APB' : 1064,161 'XILPM_RESET_IPI' : 1065,162 'XILPM_RESET_APM_LPD' : 1066,163 'XILPM_RESET_RTC' : 1067,164 'XILPM_RESET_SYSMON' : 1068,165 'XILPM_RESET_AFI_FM6' : 1069,166 'XILPM_RESET_LPD_SWDT' : 1070,167 'XILPM_RESET_FPD' : 1071,168 'XILPM_RESET_RPU_DBG1' : 1072,169 'XILPM_RESET_RPU_DBG0' : 1073,170 'XILPM_RESET_DBG_LPD' : 1074,171 'XILPM_RESET_DBG_FPD' : 1075,172 'XILPM_RESET_APLL' : 1076,173 'XILPM_RESET_DPLL' : 1077,174 'XILPM_RESET_VPLL' : 1078,175 'XILPM_RESET_IOPLL' : 1079,176 'XILPM_RESET_RPLL' : 1080,177 'XILPM_RESET_GPO3_PL_0' : 1081,178 'XILPM_RESET_GPO3_PL_1' : 1082,179 'XILPM_RESET_GPO3_PL_2' : 1083,180 'XILPM_RESET_GPO3_PL_3' : 1084,181 'XILPM_RESET_GPO3_PL_4' : 1085,182 'XILPM_RESET_GPO3_PL_5' : 1086,183 'XILPM_RESET_GPO3_PL_6' : 1087,184 'XILPM_RESET_GPO3_PL_7' : 1088,185 'XILPM_RESET_GPO3_PL_8' : 1089,186 'XILPM_RESET_GPO3_PL_9' : 1090,187 'XILPM_RESET_GPO3_PL_10' : 1091,188 'XILPM_RESET_GPO3_PL_11' : 1092,189 'XILPM_RESET_GPO3_PL_12' : 1093,190 'XILPM_RESET_GPO3_PL_13' : 1094,191 'XILPM_RESET_GPO3_PL_14' : 1095,192 'XILPM_RESET_GPO3_PL_15' : 1096,193 'XILPM_RESET_GPO3_PL_16' : 1097,194 'XILPM_RESET_GPO3_PL_17' : 1098,195 'XILPM_RESET_GPO3_PL_18' : 1099,196 'XILPM_RESET_GPO3_PL_19' : 1100,197 'XILPM_RESET_GPO3_PL_20' : 1101,198 'XILPM_RESET_GPO3_PL_21' : 1102,199 'XILPM_RESET_GPO3_PL_22' : 1103,200 'XILPM_RESET_GPO3_PL_23' : 1104,201 'XILPM_RESET_GPO3_PL_24' : 1105,202 'XILPM_RESET_GPO3_PL_25' : 1106,203 'XILPM_RESET_GPO3_PL_26' : 1107,204 'XILPM_RESET_GPO3_PL_27' : 1108,205 'XILPM_RESET_GPO3_PL_28' : 1109,206 'XILPM_RESET_GPO3_PL_29' : 1110,207 'XILPM_RESET_GPO3_PL_30' : 1111,208 'XILPM_RESET_GPO3_PL_31' : 1112,209 'XILPM_RESET_RPU_LS' : 1113,210 'XILPM_RESET_PS_ONLY' : 1114,211 'XILPM_RESET_PL' : 1115,212 'XILPM_RESET_GPIO5_EMIO_92' : 1116,213 'XILPM_RESET_GPIO5_EMIO_93' : 1117,214 'XILPM_RESET_GPIO5_EMIO_94' : 1118,215 'XILPM_RESET_GPIO5_EMIO_95' : 1119,216 'PM_CONFIG_MASTER_SECTION_ID' : 0x101,217 'PM_CONFIG_SLAVE_SECTION_ID' : 0x102,218 'PM_CONFIG_PREALLOC_SECTION_ID' : 0x103,219 'PM_CONFIG_POWER_SECTION_ID' : 0x104,220 'PM_CONFIG_RESET_SECTION_ID' : 0x105,221 'PM_CONFIG_SHUTDOWN_SECTION_ID' : 0x106,222 'PM_CONFIG_SET_CONFIG_SECTION_ID' : 0x107,223 'PM_CONFIG_GPO_SECTION_ID' : 0x108,224 'PM_SLAVE_FLAG_IS_SHAREABLE' : 0x1,225 'PM_MASTER_USING_SLAVE_MASK' : 0x2,226 'PM_CONFIG_GPO1_MIO_PIN_34_MAP' : (1 << 10),227 'PM_CONFIG_GPO1_MIO_PIN_35_MAP' : (1 << 11),228 'PM_CONFIG_GPO1_MIO_PIN_36_MAP' : (1 << 12),229 'PM_CONFIG_GPO1_MIO_PIN_37_MAP' : (1 << 13),230 'PM_CONFIG_GPO1_BIT_2_MASK' : (1 << 2),231 'PM_CONFIG_GPO1_BIT_3_MASK' : (1 << 3),232 'PM_CONFIG_GPO1_BIT_4_MASK' : (1 << 4),233 'PM_CONFIG_GPO1_BIT_5_MASK' : (1 << 5),234 'SUSPEND_TIMEOUT' : 0xFFFFFFFF,235 'PM_CONFIG_IPI_PSU_CORTEXA53_0_MASK' : 0x00000001,236 'PM_CONFIG_IPI_PSU_CORTEXR5_0_MASK' : 0x00000100,237 'PM_CONFIG_IPI_PSU_CORTEXR5_1_MASK' : 0x00000200,238}239in_file = open(args.in_file, mode='r')240out_file = open(args.out_file, mode='wb')241num_re = re.compile(r"^([0-9]+)U?$")242const_re = re.compile(r"^([A-Z_][A-Z0-9_]*)$")243def process_item(item):244 logging.debug("* ITEM " + item)245 value = 0246 for item in item.split('|'):247 item = item.strip()248 num_match = num_re .match(item)249 const_match = const_re.match(item)250 if num_match:251 num = int(num_match.group(1))252 logging.debug(" - num " + str(num))253 value |= num254 elif const_match:255 name = const_match.group(1)256 if not name in pm_define:257 sys.stderr.write("Unknown define " + name + "!\n")258 exit(1)259 num = pm_define[name]260 logging.debug(" - def " + hex(num))261 value |= num262 logging.debug(" = res " + hex(value))263 out_file.write(struct.pack('<L', value))264# Read all code265code = in_file.read()266# remove comments267code = re.sub('//.*?\n|/\*.*?\*/', '', code, flags=re.DOTALL)268# remove everything outside the XPm_ConfigObject array definition269code = re.search('const u32 XPm_ConfigObject.*= {\n(.*)};',270 code, flags=re.DOTALL).group(1)271# Process each comma-separated array item272for item in code.split(','):273 item = item.strip()274 if item:275 process_item(item)...
test_reset_password.py
Source:test_reset_password.py
...32 self.user_bad_passwd.is_active = False33 self.user_bad_passwd.password = UNUSABLE_PASSWORD34 self.user_bad_passwd.save()35 @patch('student.views.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True))36 def test_user_bad_password_reset(self):37 """Tests password reset behavior for user with password marked UNUSABLE_PASSWORD"""38 bad_pwd_req = self.request_factory.post('/password_reset/', {'email': self.user_bad_passwd.email})39 bad_pwd_resp = password_reset(bad_pwd_req)40 # If they've got an unusable password, we return a successful response code41 self.assertEquals(bad_pwd_resp.status_code, 200)42 obj = json.loads(bad_pwd_resp.content)43 self.assertEquals(obj, {44 'success': True,45 'value': "('registration/password_reset_done.html', [])",46 })47 @patch('student.views.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True))48 def test_nonexist_email_password_reset(self):49 """Now test the exception cases with of reset_password called with invalid email."""50 bad_email_req = self.request_factory.post('/password_reset/', {'email': self.user.email + "makeItFail"})51 bad_email_resp = password_reset(bad_email_req)52 # Note: even if the email is bad, we return a successful response code53 # This prevents someone potentially trying to "brute-force" find out which54 # emails are and aren't registered with edX55 self.assertEquals(bad_email_resp.status_code, 200)56 obj = json.loads(bad_email_resp.content)57 self.assertEquals(obj, {58 'success': True,59 'value': "('registration/password_reset_done.html', [])",60 })61 @patch('student.views.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True))62 def test_password_reset_ratelimited(self):63 """ Try (and fail) resetting password 30 times in a row on an non-existant email address """64 cache.clear()65 for i in xrange(30):66 good_req = self.request_factory.post('/password_reset/', {67 'email': 'thisdoesnotexist{0}@foo.com'.format(i)68 })69 good_resp = password_reset(good_req)70 self.assertEquals(good_resp.status_code, 200)71 # then the rate limiter should kick in and give a HttpForbidden response72 bad_req = self.request_factory.post('/password_reset/', {'email': 'thisdoesnotexist@foo.com'})73 bad_resp = password_reset(bad_req)74 self.assertEquals(bad_resp.status_code, 403)75 cache.clear()76 @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', "Test only valid in LMS")77 @patch('django.core.mail.send_mail')78 @patch('student.views.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True))79 def test_reset_password_email(self, send_email):80 """Tests contents of reset password email, and that user is not active"""81 good_req = self.request_factory.post('/password_reset/', {'email': self.user.email})82 good_resp = password_reset(good_req)83 self.assertEquals(good_resp.status_code, 200)84 obj = json.loads(good_resp.content)85 self.assertEquals(obj, {86 'success': True,87 'value': "('registration/password_reset_done.html', [])",88 })89 (subject, msg, from_addr, to_addrs) = send_email.call_args[0]90 self.assertIn("Password reset", subject)91 self.assertIn("You're receiving this e-mail because you requested a password reset", msg)92 self.assertEquals(from_addr, settings.DEFAULT_FROM_EMAIL)93 self.assertEquals(len(to_addrs), 1)94 self.assertIn(self.user.email, to_addrs)95 #test that the user is not active96 self.user = User.objects.get(pk=self.user.pk)97 self.assertFalse(self.user.is_active)98 re.search(r'password_reset_confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/', msg).groupdict()99 @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', "Test only valid in LMS")100 @patch('django.core.mail.send_mail')101 @ddt.data((False, 'http://'), (True, 'https://'))102 @ddt.unpack103 def test_reset_password_email_https(self, is_secure, protocol, send_email):104 """105 Tests that the right url protocol is included in the reset password link106 """107 req = self.request_factory.post(108 '/password_reset/', {'email': self.user.email}109 )110 req.is_secure = Mock(return_value=is_secure)111 resp = password_reset(req)112 _, msg, _, _ = send_email.call_args[0]113 expected_msg = "Please go to the following page and choose a new password:\n\n" + protocol114 self.assertIn(expected_msg, msg)115 @patch('student.views.password_reset_confirm')116 def test_reset_password_bad_token(self, reset_confirm):117 """Tests bad token and uidb36 in password reset"""118 bad_reset_req = self.request_factory.get('/password_reset_confirm/NO-OP/')119 password_reset_confirm_wrapper(bad_reset_req, 'NO', 'OP')120 confirm_kwargs = reset_confirm.call_args[1]121 self.assertEquals(confirm_kwargs['uidb36'], 'NO')122 self.assertEquals(confirm_kwargs['token'], 'OP')123 self.user = User.objects.get(pk=self.user.pk)124 self.assertFalse(self.user.is_active)125 @patch('student.views.password_reset_confirm')...
test_monitor.py
Source:test_monitor.py
...16def test_write_upon_reset_false():17 with helpers.tempdir() as temp:18 env = gym.make('CartPole-v0')19 env = Monitor(env, directory=temp, video_callable=False, write_upon_reset=False)20 env.reset()21 files = glob.glob(os.path.join(temp, '*'))22 assert not files, "Files: {}".format(files)23 env.close()24 files = glob.glob(os.path.join(temp, '*'))25 assert len(files) > 026def test_write_upon_reset_true():27 with helpers.tempdir() as temp:28 env = gym.make('CartPole-v0')29 env = Monitor(env, directory=temp, video_callable=False, write_upon_reset=True)30 env.reset()31 files = glob.glob(os.path.join(temp, '*'))32 assert len(files) > 0, "Files: {}".format(files)33 env.close()34 files = glob.glob(os.path.join(temp, '*'))35 assert len(files) > 036def test_video_callable_true_not_allowed():37 with helpers.tempdir() as temp:38 env = gym.make('CartPole-v0')39 try:40 env = Monitor(env, temp, video_callable=True)41 except error.Error:42 pass43 else:44 assert False45def test_video_callable_false_does_not_record():46 with helpers.tempdir() as temp:47 env = gym.make('CartPole-v0')48 env = Monitor(env, temp, video_callable=False)49 env.reset()50 env.close()51 results = monitoring.load_results(temp)52 assert len(results['videos']) == 053def test_video_callable_records_videos():54 with helpers.tempdir() as temp:55 env = gym.make('CartPole-v0')56 env = Monitor(env, temp)57 env.reset()58 env.close()59 results = monitoring.load_results(temp)60 assert len(results['videos']) == 1, "Videos: {}".format(results['videos'])61def test_semisuper_succeeds():62 """Regression test. Ensure that this can write"""63 with helpers.tempdir() as temp:64 env = gym.make('SemisuperPendulumDecay-v0')65 env = Monitor(env, temp)66 env.reset()67 env.step(env.action_space.sample())68 env.close()69class AutoresetEnv(gym.Env):70 metadata = {'semantics.autoreset': True}71 def __init__(self):72 self.action_space = spaces.Discrete(1)73 self.observation_space = spaces.Discrete(1)74 def _reset(self):75 return 076 def _step(self, action):77 return 0, 0, False, {}78import logging79logger = logging.getLogger()80gym.envs.register(81 id='Autoreset-v0',82 entry_point='gym.monitoring.tests.test_monitor:AutoresetEnv',83 max_episode_steps=2,84)85def test_env_reuse():86 with helpers.tempdir() as temp:87 env = gym.make('Autoreset-v0')88 env = Monitor(env, temp)89 env.reset()90 _, _, done, _ = env.step(None)91 assert not done92 _, _, done, _ = env.step(None)93 assert done94 _, _, done, _ = env.step(None)95 assert not done96 _, _, done, _ = env.step(None)97 assert done98 env.close()99def test_no_monitor_reset_unless_done():100 def assert_reset_raises(env):101 errored = False102 try:103 env.reset()104 except error.Error:105 errored = True106 assert errored, "Env allowed a reset when it shouldn't have"107 with helpers.tempdir() as temp:108 # Make sure we can reset as we please without monitor109 env = gym.make('CartPole-v0')110 env.reset()111 env.step(env.action_space.sample())112 env.step(env.action_space.sample())113 env.reset()114 # can reset once as soon as we start115 env = Monitor(env, temp, video_callable=False)116 env.reset()117 # can reset multiple times in a row118 env.reset()119 env.reset()120 env.step(env.action_space.sample())121 env.step(env.action_space.sample())122 assert_reset_raises(env)123 # should allow resets after the episode is done124 d = False125 while not d:126 _, _, d, _ = env.step(env.action_space.sample())127 env.reset()128 env.reset()129 env.step(env.action_space.sample())130 assert_reset_raises(env)131 env.close()132def test_only_complete_episodes_written():133 with helpers.tempdir() as temp:134 env = gym.make('CartPole-v0')135 env = Monitor(env, temp, video_callable=False)136 env.reset()137 d = False138 while not d:139 _, _, d, _ = env.step(env.action_space.sample())140 env.reset()141 env.step(env.action_space.sample())142 env.close()143 # Only 1 episode should be written144 results = monitoring.load_results(temp)145 assert len(results['episode_lengths']) == 1, "Found {} episodes written; expecting 1".format(len(results['episode_lengths']))146register(147 id='test.StepsLimitCartpole-v0',148 entry_point='gym.envs.classic_control:CartPoleEnv',149 max_episode_steps=2150 )151def test_steps_limit_restart():152 with helpers.tempdir() as temp:153 env = gym.make('test.StepsLimitCartpole-v0')154 env = Monitor(env, temp, video_callable=False)155 env.reset()156 # Episode has started157 _, _, done, info = env.step(env.action_space.sample())158 assert done == False159 # Limit reached, now we get a done signal and the env resets itself160 _, _, done, info = env.step(env.action_space.sample())161 assert done == True162 assert env.episode_id == 1...
passwords.py
Source:passwords.py
1# coding=utf-82from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm3from django.contrib.auth.tokens import default_token_generator4from django.contrib.auth.views import PasswordResetConfirmView as password_reset_confirm5from django.template.response import TemplateResponse6from django.utils.translation import ugettext as _7from xadmin.sites import site8from xadmin.views.base import BaseAdminPlugin, BaseAdminView, csrf_protect_m9from xadmin.views.website import LoginView10class ResetPasswordSendView(BaseAdminView):11 need_site_permission = False12 password_reset_form = PasswordResetForm13 password_reset_template = 'xadmin/auth/password_reset/form.html'14 password_reset_done_template = 'xadmin/auth/password_reset/done.html'15 password_reset_token_generator = default_token_generator16 password_reset_from_email = None17 password_reset_email_template = 'xadmin/auth/password_reset/email.html'18 password_reset_subject_template = None19 def get(self, request, *args, **kwargs):20 context = super(ResetPasswordSendView, self).get_context()21 context['form'] = kwargs.get('form', self.password_reset_form())22 return TemplateResponse(request, self.password_reset_template, context)23 @csrf_protect_m24 def post(self, request, *args, **kwargs):25 form = self.password_reset_form(request.POST)26 if form.is_valid():27 opts = {28 'use_https': request.is_secure(),29 'token_generator': self.password_reset_token_generator,30 'email_template_name': self.password_reset_email_template,31 'request': request,32 'domain_override': request.get_host()33 }34 if self.password_reset_from_email:35 opts['from_email'] = self.password_reset_from_email36 if self.password_reset_subject_template:37 opts['subject_template_name'] = self.password_reset_subject_template38 form.save(**opts)39 context = super(ResetPasswordSendView, self).get_context()40 return TemplateResponse(request, self.password_reset_done_template, context)41 else:42 return self.get(request, form=form)43site.register_view(r'^xadmin/password_reset/$', ResetPasswordSendView, name='xadmin_password_reset')44class ResetLinkPlugin(BaseAdminPlugin):45 def block_form_bottom(self, context, nodes):46 reset_link = self.get_admin_url('xadmin_password_reset')47 return '<div class="text-info" style="margin-top:15px;"><a href="%s"><i class="fa fa-question-sign"></i> %s</a></div>' % (reset_link, _('Forgotten your password or username?'))48site.register_plugin(ResetLinkPlugin, LoginView)49class ResetPasswordComfirmView(BaseAdminView):50 need_site_permission = False51 password_reset_set_form = SetPasswordForm52 password_reset_confirm_template = 'xadmin/auth/password_reset/confirm.html'53 password_reset_token_generator = default_token_generator54 def do_view(self, request, uidb36, token, *args, **kwargs):55 context = super(ResetPasswordComfirmView, self).get_context()56 return password_reset_confirm(request, uidb36, token,57 template_name=self.password_reset_confirm_template,58 token_generator=self.password_reset_token_generator,59 set_password_form=self.password_reset_set_form,60 post_reset_redirect=self.get_admin_url('xadmin_password_reset_complete'),61 current_app=self.admin_site.name, extra_context=context)62 def get(self, request, uidb36, token, *args, **kwargs):63 return self.do_view(request, uidb36, token)64 def post(self, request, uidb36, token, *args, **kwargs):65 return self.do_view(request, uidb36, token)66 def get_media(self):67 return super(ResetPasswordComfirmView, self).get_media() + \68 self.vendor('xadmin.page.form.js', 'xadmin.form.css')69site.register_view(r'^xadmin/password_reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',70 ResetPasswordComfirmView, name='xadmin_password_reset_confirm')71class ResetPasswordCompleteView(BaseAdminView):72 need_site_permission = False73 password_reset_complete_template = 'xadmin/auth/password_reset/complete.html'74 def get(self, request, *args, **kwargs):75 context = super(ResetPasswordCompleteView, self).get_context()76 context['login_url'] = self.get_admin_url('index')77 return TemplateResponse(request, self.password_reset_complete_template, context)...
reset_profile_settings_overlay.js
Source:reset_profile_settings_overlay.js
1// Copyright 2013 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4cr.define('options', function() {5 var Page = cr.ui.pageManager.Page;6 var AutomaticSettingsResetBanner = options.AutomaticSettingsResetBanner;7 var ResetProfileSettingsBanner = options.ResetProfileSettingsBanner;8 /**9 * ResetProfileSettingsOverlay class10 * Encapsulated handling of the 'Reset Profile Settings' overlay page.11 * @class12 */13 function ResetProfileSettingsOverlay() {14 Page.call(this, 'resetProfileSettings',15 loadTimeData.getString('resetProfileSettingsOverlayTabTitle'),16 'reset-profile-settings-overlay');17 }18 cr.addSingletonGetter(ResetProfileSettingsOverlay);19 ResetProfileSettingsOverlay.prototype = {20 // Inherit ResetProfileSettingsOverlay from Page.21 __proto__: Page.prototype,22 /** @override */23 initializePage: function() {24 Page.prototype.initializePage.call(this);25 $('reset-profile-settings-dismiss').onclick = function(e) {26 ResetProfileSettingsOverlay.dismiss();27 };28 $('reset-profile-settings-commit').onclick = function(e) {29 ResetProfileSettingsOverlay.setResettingState(true);30 chrome.send('performResetProfileSettings',31 [$('send-settings').checked]);32 };33 $('expand-feedback').onclick = function(e) {34 var feedbackTemplate = $('feedback-template');35 feedbackTemplate.hidden = !feedbackTemplate.hidden;36 e.preventDefault();37 };38 },39 /**40 * @override41 * @suppress {checkTypes}42 * TODO(vitalyp): remove the suppression. See the explanation in43 * chrome/browser/resources/options/automatic_settings_reset_banner.js.44 */45 didShowPage: function() {46 ResetProfileSettingsBanner.dismiss();47 chrome.send('onShowResetProfileDialog');48 },49 /** @override */50 didClosePage: function() {51 chrome.send('onHideResetProfileDialog');52 },53 };54 /**55 * Enables/disables UI elements after/while Chrome is performing a reset.56 * @param {boolean} state If true, UI elements are disabled.57 */58 ResetProfileSettingsOverlay.setResettingState = function(state) {59 $('reset-profile-settings-throbber').style.visibility =60 state ? 'visible' : 'hidden';61 $('reset-profile-settings-dismiss').disabled = state;62 $('reset-profile-settings-commit').disabled = state;63 };64 /**65 * Chrome callback to notify ResetProfileSettingsOverlay that the reset66 * operation has terminated.67 * @suppress {checkTypes}68 * TODO(vitalyp): remove the suppression. See the explanation in69 * chrome/browser/resources/options/automatic_settings_reset_banner.js.70 */71 ResetProfileSettingsOverlay.doneResetting = function() {72 AutomaticSettingsResetBanner.dismiss();73 ResetProfileSettingsOverlay.dismiss();74 };75 /**76 * Dismisses the overlay.77 */78 ResetProfileSettingsOverlay.dismiss = function() {79 PageManager.closeOverlay();80 ResetProfileSettingsOverlay.setResettingState(false);81 };82 ResetProfileSettingsOverlay.setFeedbackInfo = function(feedbackListData) {83 var input = new JsEvalContext(feedbackListData);84 var output = $('feedback-template');85 jstProcess(input, output);86 };87 // Export88 return {89 ResetProfileSettingsOverlay: ResetProfileSettingsOverlay90 };...
app.py
Source:app.py
1# flake8: noqa, because URL syntax is more readable with long lines2from django.conf.urls import url, include3from django.contrib.auth import views as auth_views4from django.core.urlresolvers import reverse_lazy5from oscar.core.application import Application6from oscar.core.loading import get_class7from oscar.views.decorators import login_forbidden8class Shop(Application):9 name = None10 catalogue_app = get_class('catalogue.app', 'application')11 customer_app = get_class('customer.app', 'application')12 basket_app = get_class('basket.app', 'application')13 checkout_app = get_class('checkout.app', 'application')14 promotions_app = get_class('promotions.app', 'application')15 search_app = get_class('search.app', 'application')16 dashboard_app = get_class('dashboard.app', 'application')17 offer_app = get_class('offer.app', 'application')18 password_reset_form = get_class('customer.forms', 'PasswordResetForm')19 set_password_form = get_class('customer.forms', 'SetPasswordForm')20 def get_urls(self):21 urls = [22 url(r'^catalogue/', include(self.catalogue_app.urls)),23 url(r'^basket/', include(self.basket_app.urls)),24 url(r'^checkout/', include(self.checkout_app.urls)),25 url(r'^accounts/', include(self.customer_app.urls)),26 url(r'^search/', include(self.search_app.urls)),27 url(r'^dashboard/', include(self.dashboard_app.urls)),28 url(r'^offers/', include(self.offer_app.urls)),29 # Password reset - as we're using Django's default view functions,30 # we can't namespace these urls as that prevents31 # the reverse function from working.32 url(r'^password-reset/$',33 login_forbidden(auth_views.password_reset),34 {'password_reset_form': self.password_reset_form,35 'post_reset_redirect': reverse_lazy('password-reset-done')},36 name='password-reset'),37 url(r'^password-reset/done/$',38 login_forbidden(auth_views.password_reset_done),39 name='password-reset-done'),40 url(r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$',41 login_forbidden(auth_views.password_reset_confirm),42 {43 'post_reset_redirect': reverse_lazy('password-reset-complete'),44 'set_password_form': self.set_password_form,45 },46 name='password-reset-confirm'),47 url(r'^password-reset/complete/$',48 login_forbidden(auth_views.password_reset_complete),49 name='password-reset-complete'),50 url(r'', include(self.promotions_app.urls)),51 ]52 return urls...
urls.py
Source:urls.py
1# -*- coding: utf-8 -*-2from django.conf.urls import url3from . import views4from django.conf import settings5from django.contrib.auth import views as auth_views #å¼å
¥djangoå
ç½®çè§å¾æ件ï¼éå½å为auth-views6urlpatterns =[7 #url(r'^login/$', views.user_login, name='user_login'),#èªå®ä¹æç»å½8 url(r'^login/$', auth_views.login, name='user_login'), #djangoå
ç½®çç»å½9 url(r'^new-login/$',auth_views.login,{'template_name':'account/login.html'}),10 url(r'^logout/$', auth_views.logout, name='user_logout'), #djangoå
ç½®çéåº11 #url(r'^logout/$', auth_views.logout,{'template_name':'account/logout.html'}, name='user_logout'), #djangoå
ç½®çéåº12 url(r'^register/$',views.register,name='user_register'),13 # ç»éå¯ç ä¿®æ¹çé¾æ¥14 url(r'^password-change/$',auth_views.password_change,{'post_change_redirect':'/account/password-change-done'},name='password_change'),15 url(r'^password-change-done/$',auth_views.password_change_done,name='password_change_done'),16 # ç»å½å¯ç éç½®é¾æ¥(èªå®ä¹)17 url(r'^password-reset/$',auth_views.password_reset,18 {'template_name':'account/password_reset_form.html',19 'email_template_name':'account/password_reset_email.html',20 'subject_template_name':'account/password_reset_subject.text',21 'post_reset_redirect':'/account/password-reset-done'22 },name='password_reset'),23 url(r'^password-reset-done/$',auth_views.password_reset_done,24 {'template_name':'account/password_reset_done.html',25 },name='password_reset_done'),26 url(r'^password-reset_confirm/(?P<uidb64>[-\w]+)/(?P<token>[-\w]+)/$',auth_views.password_reset_confirm,27 {'template_name':'account/password_reset_confirm.html',28 'post_reset_redirect':'/account/password-reset-complete'29 },name='password_reset_confirm'),30 url(r'^password-reset_complete/$',auth_views.password_reset_complete,31 {'template_name':'account/password_reset_complete.html',32 },name='password_reset_complete'),33 #个人信æ¯è®¾ç½®è·¯å¾34 url(r'^my-information/$',views.myself,name='my_information'),35 url(r'^edit-my-information/$',views.myself_edit,name='edit_my_information'),36 url(r'^my-image/$', views.my_image,name='my_image'),...
Using AI Code Generation
1import test from 'ava';2test.beforeEach(t => {3 t.context.data = new Map();4});5test('foo', t => {6 const { data } = t.context;7 t.is(data.size, 0);8 data.set('name', 'tobi');9});10test('bar', t => {11 const { data } = t.context;12 t.is(data.size, 0);13});14import test from 'ava';15test.beforeEach(t => {16 t.context.data = new Map();17});18test('foo', t => {19 const { data } = t.context;20 t.is(data.size, 0);21 data.set('name', 'tobi');22});23test('bar', t => {24 const { data } = t.context;25 t.is(data.size, 0);26});27import test from 'ava';28test.beforeEach(t => {29 t.context.data = new Map();30});31test('foo', t => {32 const { data } = t.context;33 t.is(data.size, 0);34 data.set('name', 'tobi');35});36test('bar', t => {37 const { data } = t.context;38 t.is(data.size, 0);39});40import test from 'ava';41test.beforeEach(t => {42 t.context.data = new Map();43});44test('foo', t => {45 const { data } = t.context;46 t.is(data.size, 0);47 data.set('name', 'tobi');48});49test('bar', t => {50 const { data } = t.context;51 t.is(data.size, 0);52});53import test from 'ava';54test.beforeEach(t => {55 t.context.data = new Map();56});57test('foo', t => {58 const { data } = t.context;59 t.is(data.size, 0);60 data.set('name', 'tobi');61});62test('bar', t => {63 const { data } = t.context;64 t.is(data.size, 0);65});66import test from 'ava';
Using AI Code Generation
1import test from 'ava';2test.beforeEach(t => {3 t.context.data = [];4});5test('test1', t => {6 t.context.data.push(1);7 t.is(t.context.data.length, 1);8});9test('test2', t => {10 t.context.data.push(2);11 t.is(t.context.data.length, 1);12});13import test from 'ava';14test.beforeEach(t => {15 t.context.data = [];16});17test('test1', t => {18 t.context.data.push(1);19 t.is(t.context.data.length, 1);20});21test('test2', t => {22 t.context.data.push(2);23 t.is(t.context.data.length, 1);24});25test.afterEach.always(t => {26 t.context.data = [];27});28import test from 'ava';29test.beforeEach(t => {30 t.context.data = [];31});32test('test1', t => {33 t.context.data.push(1);34 t.is(t.context.data.length, 1);35});36test('test2', t => {37 t.context.data.push(2);38 t.is(t.context.data.length, 1);39});40test.afterEach.always(t => {41 t.context.data = [];42});43import test from 'ava';44test.beforeEach(t => {45 t.context.data = [];46});47test('test1', t => {48 t.context.data.push(1);49 t.is(t.context.data.length, 1);50});51test('test2', t => {52 t.context.data.push(2);53 t.is(t.context.data.length, 1);54});55test.afterEach.always(t => {56 t.context.data = [];57});
Using AI Code Generation
1test('adds 1 + 2 to equal 3', t => {2 t.is(1 + 2, 3);3});4test('adds 1 + 2 to equal 3', t => {5 t.is(1 + 2, 3);6});7const test = require('ava');8test.beforeEach(t => {9});10test.afterEach(t => {11});12test('my passing test', t => {13 t.pass();14});15const test = require('ava');16test.before(t => {17});18test.after('cleanup', t => {19});20test('my passing test', t => {21 t.pass();22});23const test = require('ava');24test.before(t => {25});26test.after('cleanup', t => {27});28test('my passing test', t => {29 t.pass();30});31const test = require('ava');32test.before(t => {33});34test.after('cleanup', t => {35});36test('my passing test', t => {37 t.pass();38});39const test = require('ava');40test.before(t => {41});42test.after('cleanup', t => {43});44test('my passing test', t => {45 t.pass();46});47const test = require('ava');48test.before(t => {49});50test.after('cleanup', t => {51});52test('my passing test', t => {53 t.pass();54});55const test = require('ava');56test.before(t => {57});58test.after('cleanup', t => {59});60test('my passing test', t => {61 t.pass();62});63const test = require('ava');64test.before(t => {65});66test.after('cleanup', t => {67});68test('my passing test', t
Using AI Code Generation
1test.beforeEach(t => {2 t.context.data = new Date();3});4test('date is not 2017', t => {5 t.not(t.context.data.getFullYear(), 2017);6});7test('date is 2016', t => {8 t.is(t.context.data.getFullYear(), 2016);9});10 5: test('date is not 2017', t => {11 6: t.not(t.context.data.getFullYear(), 2017);12 7: });13 9: test('date is 2016', t => {14 10: t.is(t.context.data.getFullYear(), 2016);15 11: });16test.beforeEach(t => {17 t.context.data = new Date();18});19test('date is not 2017', t => {20 t.not(t.context.data.getFullYear(), 2017);21});22test('date is 2016', t => {23 t.is(t.context.data.getFullYear(), 2016);24});25 5: test('date is not 2017', t => {26 6: t.not(t.context.data.getFullYear(), 2017);27 7: });28 9: test('date is 2016', t => {29 10: t.is(t.context.data.getFullYear(), 2016);30 11: });31test.beforeEach(t => {32 t.context.data = new Date();33});34test('date is not 2017', t =>
Using AI Code Generation
1test('foo', t => {2 t.plan(2);3 t.is(foo(), 5);4 t.reset();5 t.is(foo(), 5);6});
Using AI Code Generation
1const test = require('ava');2const sinon = require('sinon');3const { reset } = require('sinon');4const {foo} = require('./foo');5const {bar} = require('./bar');6test('foo should call bar once', t => {7 const barSpy = sinon.spy();8 const barMock = sinon.mock(bar)9 .expects('bar')10 .once()11 .withArgs('hello')12 .returns('world')13 .onCall(0)14 .callsFake(barSpy);15 const result = foo('hello');16 t.is(result, 'world');17 t.true(barSpy.calledOnce);18 barMock.verify();19 reset();20});
Using AI Code Generation
1import test from 'ava';2import { reset } from 'ava/lib/concordance-options';3test('test', t => {4 reset();5 t.pass();6});7Default: `path.join(__dirname, '__snapshots__')`8import test from 'ava';9import { snapshotPath } from 'ava/lib/concordance-options';10test('test', t => {11 snapshotPath = 'path/to/snapshots';12 t.pass();13});14Default: [`SnapshotState`](
Using AI Code Generation
1const { reset } = require("./helpers");2const { expect } = require("chai");3describe("Reset", () => {4 it("should reset the database", async () => {5 await reset();6 const users = await User.find({});7 expect(users).to.have.length(0);8 });9});10const mongoose = require("mongoose");11const User = require("../models/User");12const reset = async () => {13 await User.deleteMany({});14};15module.exports = {16};
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!