How to use current method in testing-library-react-hooks

Best JavaScript code snippet using testing-library-react-hooks

test_plugin_edit_structure.py

Source:test_plugin_edit_structure.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import unittest3import sys4sys.path.append(u'../ftplugin')5import vim6from orgmode._vim import ORGMODE7counter = 08class EditStructureTestCase(unittest.TestCase):9 def setUp(self):10 global counter11 counter += 112 vim.CMDHISTORY = []13 vim.CMDRESULTS = {}14 vim.EVALHISTORY = []15 vim.EVALRESULTS = {16 # no org_todo_keywords for b17 u'exists("b:org_todo_keywords")'.encode(u'utf-8'): '0'.encode(u'utf-8'),18 # global values for org_todo_keywords19 u'exists("g:org_todo_keywords")'.encode(u'utf-8'): '1'.encode(u'utf-8'),20 u'g:org_todo_keywords'.encode(u'utf-8'): [u'TODO'.encode(u'utf-8'), u'DONE'.encode(u'utf-8'), u'|'.encode(u'utf-8')],21 u'exists("g:org_improve_split_heading")'.encode(u'utf-8'): u'0'.encode(u'utf-8'),22 u'exists("b:org_improve_split_heading")'.encode(u'utf-8'): u'0'.encode(u'utf-8'),23 u'exists("g:org_debug")'.encode(u'utf-8'): u'0'.encode(u'utf-8'),24 u'exists("b:org_debug")'.encode(u'utf-8'): u'0'.encode(u'utf-8'),25 u'exists("*repeat#set()")'.encode(u'utf-8'): u'0'.encode(u'utf-8'),26 u'b:changedtick'.encode(u'utf-8'): (u'%d' % counter).encode(u'utf-8'),27 u'&ts'.encode(u'utf-8'): u'8'.encode(u'utf-8'),28 u'exists("g:org_tag_column")'.encode(u'utf-8'): u'0'.encode(u'utf-8'),29 u'exists("b:org_tag_column")'.encode(u'utf-8'): u'0'.encode(u'utf-8'),30 u"v:count".encode(u'utf-8'): u'0'.encode(u'utf-8')}31 if not u'EditStructure' in ORGMODE.plugins:32 ORGMODE.register_plugin(u'EditStructure')33 self.editstructure = ORGMODE.plugins[u'EditStructure']34 vim.current.buffer[:] = [ i.encode(u'utf-8') for i in u"""35* Überschrift 136Text 137Bla bla38** Überschrift 1.139Text 240Bla Bla bla41** Überschrift 1.242Text 343**** Überschrift 1.2.1.falsch44Bla Bla bla bla45*** Überschrift 1.2.146* Überschrift 247* Überschrift 348 asdf sdf49""".split(u'\n')]50 def test_new_heading_below_normal_behavior(self):51 vim.current.window.cursor = (1, 0)52 self.assertNotEqual(self.editstructure.new_heading(below=True), None)53 self.assertEqual(vim.current.buffer[0], u'* '.encode(u'utf-8'))54 self.assertEqual(vim.current.buffer[1], u'* Überschrift 1'.encode(u'utf-8'))55 def test_new_heading_above_normal_behavior(self):56 vim.current.window.cursor = (1, 1)57 self.assertNotEqual(self.editstructure.new_heading(below=False), None)58 self.assertEqual(vim.current.buffer[0], u'* '.encode(u'utf-8'))59 self.assertEqual(vim.current.buffer[1], u'* Überschrift 1'.encode(u'utf-8'))60 def test_new_heading_below(self):61 vim.current.window.cursor = (2, 0)62 vim.current.buffer[5] = u'** Überschrift 1.1 :Tag:'.encode(u'utf-8')63 self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=False), None)64 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 6gg"|startinsert!'.encode(u'utf-8'))65 self.assertEqual(vim.current.buffer[4], u'Bla bla'.encode(u'utf-8'))66 self.assertEqual(vim.current.buffer[5], u'* '.encode(u'utf-8'))67 self.assertEqual(vim.current.buffer[6], u'** Überschrift 1.1 :Tag:'.encode(u'utf-8'))68 self.assertEqual(vim.current.buffer[10], u'** Überschrift 1.2'.encode(u'utf-8'))69 self.assertEqual(vim.current.buffer[13], u'**** Überschrift 1.2.1.falsch'.encode(u'utf-8'))70 self.assertEqual(vim.current.buffer[16], u'*** Überschrift 1.2.1'.encode(u'utf-8'))71 self.assertEqual(vim.current.buffer[17], u'* Überschrift 2'.encode(u'utf-8'))72 def test_new_heading_below_insert_mode(self):73 vim.current.window.cursor = (2, 1)74 self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)75 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 3gg"|startinsert!'.encode(u'utf-8'))76 self.assertEqual(vim.current.buffer[2], u'* Überschrift 1'.encode(u'utf-8'))77 self.assertEqual(vim.current.buffer[5], u'Bla bla'.encode(u'utf-8'))78 self.assertEqual(vim.current.buffer[6], u'** Überschrift 1.1'.encode(u'utf-8'))79 self.assertEqual(vim.current.buffer[10], u'** Überschrift 1.2'.encode(u'utf-8'))80 self.assertEqual(vim.current.buffer[13], u'**** Überschrift 1.2.1.falsch'.encode(u'utf-8'))81 self.assertEqual(vim.current.buffer[16], u'*** Überschrift 1.2.1'.encode(u'utf-8'))82 self.assertEqual(vim.current.buffer[17], u'* Überschrift 2'.encode(u'utf-8'))83 def test_new_heading_below_split_text_at_the_end(self):84 vim.current.buffer[1] = u'* Überschriftx1'.encode(u'utf-8')85 vim.current.window.cursor = (2, 14)86 self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)87 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 3gg"|startinsert!'.encode(u'utf-8'))88 self.assertEqual(vim.current.buffer[2], u'* '.encode(u'utf-8'))89 self.assertEqual(vim.current.buffer[5], u'Bla bla'.encode(u'utf-8'))90 self.assertEqual(vim.current.buffer[6], u'** Überschrift 1.1'.encode(u'utf-8'))91 self.assertEqual(vim.current.buffer[10], u'** Überschrift 1.2'.encode(u'utf-8'))92 self.assertEqual(vim.current.buffer[13], u'**** Überschrift 1.2.1.falsch'.encode(u'utf-8'))93 self.assertEqual(vim.current.buffer[16], u'*** Überschrift 1.2.1'.encode(u'utf-8'))94 self.assertEqual(vim.current.buffer[17], u'* Überschrift 2'.encode(u'utf-8'))95 def test_new_heading_below_split_text_at_the_end_insert_parts(self):96 vim.current.window.cursor = (2, 14)97 self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)98 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 3gg"|startinsert!'.encode(u'utf-8'))99 self.assertEqual(vim.current.buffer[2], u'* 1'.encode(u'utf-8'))100 self.assertEqual(vim.current.buffer[5], u'Bla bla'.encode(u'utf-8'))101 self.assertEqual(vim.current.buffer[6], u'** Überschrift 1.1'.encode(u'utf-8'))102 self.assertEqual(vim.current.buffer[10], u'** Überschrift 1.2'.encode(u'utf-8'))103 self.assertEqual(vim.current.buffer[13], u'**** Überschrift 1.2.1.falsch'.encode(u'utf-8'))104 self.assertEqual(vim.current.buffer[16], u'*** Überschrift 1.2.1'.encode(u'utf-8'))105 self.assertEqual(vim.current.buffer[17], u'* Überschrift 2'.encode(u'utf-8'))106 def test_new_heading_below_in_the_middle(self):107 vim.current.window.cursor = (10, 0)108 self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)109 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 13gg"|startinsert!'.encode(u'utf-8'))110 self.assertEqual(vim.current.buffer[11], u''.encode(u'utf-8'))111 self.assertEqual(vim.current.buffer[12], u'** '.encode(u'utf-8'))112 self.assertEqual(vim.current.buffer[13], u'**** Überschrift 1.2.1.falsch'.encode(u'utf-8'))113 def test_new_heading_below_in_the_middle2(self):114 vim.current.window.cursor = (13, 0)115 self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)116 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 16gg"|startinsert!'.encode(u'utf-8'))117 self.assertEqual(vim.current.buffer[14], u'Bla Bla bla bla'.encode(u'utf-8'))118 self.assertEqual(vim.current.buffer[15], u'**** '.encode(u'utf-8'))119 self.assertEqual(vim.current.buffer[16], u'*** Überschrift 1.2.1'.encode(u'utf-8'))120 def test_new_heading_below_in_the_middle3(self):121 vim.current.window.cursor = (16, 0)122 self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)123 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 17gg"|startinsert!'.encode(u'utf-8'))124 self.assertEqual(vim.current.buffer[15], u'*** Überschrift 1.2.1'.encode(u'utf-8'))125 self.assertEqual(vim.current.buffer[16], u'*** '.encode(u'utf-8'))126 self.assertEqual(vim.current.buffer[17], u'* Überschrift 2'.encode(u'utf-8'))127 def test_new_heading_below_at_the_end(self):128 vim.current.window.cursor = (18, 0)129 self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)130 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 21gg"|startinsert!'.encode(u'utf-8'))131 self.assertEqual(vim.current.buffer[19], u''.encode(u'utf-8'))132 self.assertEqual(vim.current.buffer[20], u'* '.encode(u'utf-8'))133 self.assertEqual(len(vim.current.buffer), 21)134 def test_new_heading_above(self):135 vim.current.window.cursor = (2, 0)136 self.assertNotEqual(self.editstructure.new_heading(below=False, insert_mode=True), None)137 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 2gg"|startinsert!'.encode(u'utf-8'))138 self.assertEqual(vim.current.buffer[0], u''.encode(u'utf-8'))139 self.assertEqual(vim.current.buffer[1], u'* '.encode(u'utf-8'))140 self.assertEqual(vim.current.buffer[2], u'* Überschrift 1'.encode(u'utf-8'))141 def test_new_heading_above_in_the_middle(self):142 vim.current.window.cursor = (10, 0)143 self.assertNotEqual(self.editstructure.new_heading(below=False, insert_mode=True), None)144 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 10gg"|startinsert!'.encode(u'utf-8'))145 self.assertEqual(vim.current.buffer[8], u'Bla Bla bla'.encode(u'utf-8'))146 self.assertEqual(vim.current.buffer[9], u'** '.encode(u'utf-8'))147 self.assertEqual(vim.current.buffer[10], u'** Überschrift 1.2'.encode(u'utf-8'))148 def test_new_heading_above_in_the_middle2(self):149 vim.current.window.cursor = (13, 0)150 self.assertNotEqual(self.editstructure.new_heading(below=False, insert_mode=True), None)151 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 13gg"|startinsert!'.encode(u'utf-8'))152 self.assertEqual(vim.current.buffer[11], u''.encode(u'utf-8'))153 self.assertEqual(vim.current.buffer[12], u'**** '.encode(u'utf-8'))154 self.assertEqual(vim.current.buffer[13], u'**** Überschrift 1.2.1.falsch'.encode(u'utf-8'))155 def test_new_heading_above_in_the_middle3(self):156 vim.current.window.cursor = (16, 0)157 self.assertNotEqual(self.editstructure.new_heading(below=False, insert_mode=True), None)158 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 16gg"|startinsert!'.encode(u'utf-8'))159 self.assertEqual(vim.current.buffer[14], u'Bla Bla bla bla'.encode(u'utf-8'))160 self.assertEqual(vim.current.buffer[15], u'*** '.encode(u'utf-8'))161 self.assertEqual(vim.current.buffer[16], u'*** Überschrift 1.2.1'.encode(u'utf-8'))162 def test_new_heading_above_at_the_end(self):163 vim.current.window.cursor = (18, 0)164 self.assertNotEqual(self.editstructure.new_heading(below=False, insert_mode=True), None)165 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 18gg"|startinsert!'.encode(u'utf-8'))166 self.assertEqual(vim.current.buffer[16], u'* Überschrift 2'.encode(u'utf-8'))167 self.assertEqual(vim.current.buffer[17], u'* '.encode(u'utf-8'))168 self.assertEqual(vim.current.buffer[18], u'* Überschrift 3'.encode(u'utf-8'))169 def test_new_heading_below_split_heading_title(self):170 vim.current.buffer[:] = [ i.encode(u'utf-8') for i in u"""171* Überschrift 1 :Tag:172Text 1173Bla bla174** Überschrift 1.1175Text 2176Bla Bla bla177** Überschrift 1.2178Text 3179**** Überschrift 1.2.1.falsch180Bla Bla bla bla181*** Überschrift 1.2.1182* Überschrift 2183* Überschrift 3184 asdf sdf185""".split(u'\n')]186 vim.current.window.cursor = (2, 6)187 self.assertNotEqual(self.editstructure.new_heading(insert_mode=True), None)188 self.assertEqual(vim.current.buffer[0], u''.encode(u'utf-8'))189 self.assertEqual(vim.current.buffer[1], u'* Über :Tag:'.encode(u'utf-8'))190 self.assertEqual(vim.current.buffer[2], u'* schrift 1'.encode(u'utf-8'))191 self.assertEqual(vim.current.buffer[3], u'Text 1'.encode(u'utf-8'))192 def test_new_heading_below_split_heading_title_with_todo(self):193 vim.current.buffer[:] = [ i.encode(u'utf-8') for i in u"""194* TODO Überschrift 1 :Tag:195Text 1196Bla bla197** Überschrift 1.1198Text 2199Bla Bla bla200** Überschrift 1.2201Text 3202**** Überschrift 1.2.1.falsch203Bla Bla bla bla204*** Überschrift 1.2.1205* Überschrift 2206* Überschrift 3207 asdf sdf208""".split(u'\n')]209 vim.current.window.cursor = (2, 5)210 self.assertNotEqual(self.editstructure.new_heading(insert_mode=True), None)211 self.assertEqual(vim.current.buffer[0], u''.encode(u'utf-8'))212 self.assertEqual(vim.current.buffer[1], u'* TODO :Tag:'.encode(u'utf-8'))213 self.assertEqual(vim.current.buffer[2], u'* Überschrift 1'.encode(u'utf-8'))214 self.assertEqual(vim.current.buffer[3], u'Text 1'.encode(u'utf-8'))215 def test_demote_heading(self):216 vim.current.window.cursor = (13, 0)217 self.assertNotEqual(self.editstructure.demote_heading(), None)218 self.assertEqual(vim.CMDHISTORY[-1], u'normal 13ggV15gg='.encode(u'utf-8'))219 self.assertEqual(vim.current.buffer[10], u'Text 3'.encode(u'utf-8'))220 self.assertEqual(vim.current.buffer[11], u''.encode(u'utf-8'))221 self.assertEqual(vim.current.buffer[12], u'***** Überschrift 1.2.1.falsch'.encode(u'utf-8'))222 self.assertEqual(vim.current.buffer[13], u''.encode(u'utf-8'))223 # actually the indentation comes through vim, just the heading is updated224 self.assertEqual(vim.current.buffer[14], u'Bla Bla bla bla'.encode(u'utf-8'))225 self.assertEqual(vim.current.buffer[15], u'*** Überschrift 1.2.1'.encode(u'utf-8'))226 self.assertEqual(vim.current.window.cursor, (13, 1))227 def test_demote_newly_created_level_one_heading(self):228 vim.current.window.cursor = (2, 0)229 self.assertNotEqual(self.editstructure.new_heading(below=True), None)230 self.assertEqual(vim.current.buffer[1], u'* Überschrift 1'.encode(u'utf-8'))231 self.assertEqual(vim.current.buffer[5], u'* '.encode(u'utf-8'))232 self.assertEqual(vim.current.buffer[6], u'** Überschrift 1.1'.encode(u'utf-8'))233 self.assertEqual(vim.current.buffer[10], u'** Überschrift 1.2'.encode(u'utf-8'))234 self.assertEqual(vim.current.buffer[13], u'**** Überschrift 1.2.1.falsch'.encode(u'utf-8'))235 self.assertEqual(vim.current.buffer[16], u'*** Überschrift 1.2.1'.encode(u'utf-8'))236 self.assertEqual(vim.current.buffer[17], u'* Überschrift 2'.encode(u'utf-8'))237 vim.current.window.cursor = (6, 2)238 self.assertNotEqual(self.editstructure.demote_heading(), None)239 self.assertEqual(vim.CMDHISTORY[-1], u'normal 6ggV17gg='.encode(u'utf-8'))240 self.assertEqual(vim.current.buffer[5], u'** '.encode(u'utf-8'))241 self.assertEqual(vim.current.buffer[6], u'*** Überschrift 1.1'.encode(u'utf-8'))242 self.assertEqual(vim.current.buffer[10], u'*** Überschrift 1.2'.encode(u'utf-8'))243 self.assertEqual(vim.current.buffer[13], u'***** Überschrift 1.2.1.falsch'.encode(u'utf-8'))244 self.assertEqual(vim.current.buffer[16], u'**** Überschrift 1.2.1'.encode(u'utf-8'))245 self.assertEqual(vim.current.buffer[17], u'* Überschrift 2'.encode(u'utf-8'))246 def test_demote_newly_created_level_two_heading(self):247 vim.current.window.cursor = (10, 0)248 self.assertNotEqual(self.editstructure.new_heading(below=True), None)249 self.assertEqual(vim.current.buffer[1], u'* Überschrift 1'.encode(u'utf-8'))250 self.assertEqual(vim.current.buffer[5], u'** Überschrift 1.1'.encode(u'utf-8'))251 self.assertEqual(vim.current.buffer[9], u'** Überschrift 1.2'.encode(u'utf-8'))252 self.assertEqual(vim.current.buffer[12], u'** '.encode(u'utf-8'))253 self.assertEqual(vim.current.buffer[13], u'**** Überschrift 1.2.1.falsch'.encode(u'utf-8'))254 self.assertEqual(vim.current.buffer[16], u'*** Überschrift 1.2.1'.encode(u'utf-8'))255 self.assertEqual(vim.current.buffer[17], u'* Überschrift 2'.encode(u'utf-8'))256 vim.current.window.cursor = (13, 3)257 self.assertNotEqual(self.editstructure.demote_heading(including_children=False, on_heading=True), None)258 self.assertEqual(vim.CMDHISTORY[-1], u'exe "normal 13gg"|startinsert!'.encode(u'utf-8'))259 self.assertEqual(vim.current.buffer[1], u'* Überschrift 1'.encode(u'utf-8'))260 self.assertEqual(vim.current.buffer[5], u'** Überschrift 1.1'.encode(u'utf-8'))261 self.assertEqual(vim.current.buffer[9], u'** Überschrift 1.2'.encode(u'utf-8'))262 self.assertEqual(vim.current.buffer[12], u'*** '.encode(u'utf-8'))263 self.assertEqual(vim.current.buffer[13], u'**** Überschrift 1.2.1.falsch'.encode(u'utf-8'))264 self.assertEqual(vim.current.buffer[16], u'*** Überschrift 1.2.1'.encode(u'utf-8'))265 self.assertEqual(vim.current.buffer[17], u'* Überschrift 2'.encode(u'utf-8'))266 def test_demote_last_heading(self):267 vim.current.buffer[:] = [ i.encode(u'utf-8') for i in u"""268* Überschrift 2269* Überschrift 3""".split('\n')]270 vim.current.window.cursor = (3, 0)271 h = ORGMODE.get_document().current_heading()272 self.assertNotEqual(self.editstructure.demote_heading(), None)273 self.assertEqual(h.end, 2)274 self.assertFalse(vim.CMDHISTORY)275 self.assertEqual(vim.current.buffer[2], u'** Überschrift 3'.encode(u'utf-8'))276 self.assertEqual(vim.current.window.cursor, (3, 1))277 def test_promote_heading(self):278 vim.current.window.cursor = (13, 0)279 self.assertNotEqual(self.editstructure.promote_heading(), None)280 self.assertEqual(vim.CMDHISTORY[-1], u'normal 13ggV15gg='.encode(u'utf-8'))281 self.assertEqual(vim.current.buffer[10], u'Text 3'.encode(u'utf-8'))282 self.assertEqual(vim.current.buffer[11], u''.encode(u'utf-8'))283 self.assertEqual(vim.current.buffer[12], u'*** Überschrift 1.2.1.falsch'.encode(u'utf-8'))284 self.assertEqual(vim.current.buffer[13], u''.encode(u'utf-8'))285 # actually the indentation comes through vim, just the heading is updated286 self.assertEqual(vim.current.buffer[14], u'Bla Bla bla bla'.encode(u'utf-8'))287 self.assertEqual(vim.current.buffer[15], u'*** Überschrift 1.2.1'.encode(u'utf-8'))288 self.assertEqual(vim.current.window.cursor, (13, -1))289 def test_promote_level_one_heading(self):290 vim.current.window.cursor = (2, 0)291 self.assertEqual(self.editstructure.promote_heading(), None)292 self.assertEqual(len(vim.CMDHISTORY), 0)293 self.assertEqual(vim.current.buffer[1], u'* Überschrift 1'.encode(u'utf-8'))294 self.assertEqual(vim.current.window.cursor, (2, 0))295 def test_demote_parent_heading(self):296 vim.current.window.cursor = (2, 0)297 self.assertNotEqual(self.editstructure.demote_heading(), None)298 self.assertEqual(vim.CMDHISTORY[-1], u'normal 2ggV16gg='.encode(u'utf-8'))299 self.assertEqual(vim.current.buffer[1], u'** Überschrift 1'.encode(u'utf-8'))300 self.assertEqual(vim.current.buffer[5], u'*** Überschrift 1.1'.encode(u'utf-8'))301 self.assertEqual(vim.current.buffer[9], u'*** Überschrift 1.2'.encode(u'utf-8'))302 self.assertEqual(vim.current.buffer[12], u'***** Überschrift 1.2.1.falsch'.encode(u'utf-8'))303 self.assertEqual(vim.current.buffer[15], u'**** Überschrift 1.2.1'.encode(u'utf-8'))304 self.assertEqual(vim.current.buffer[16], u'* Überschrift 2'.encode(u'utf-8'))305 self.assertEqual(vim.current.window.cursor, (2, 1))306 def test_promote_parent_heading(self):307 vim.current.window.cursor = (10, 0)308 self.assertNotEqual(self.editstructure.promote_heading(), None)309 self.assertEqual(vim.CMDHISTORY[-1], u'normal 10ggV16gg='.encode(u'utf-8'))310 self.assertEqual(vim.current.buffer[5], u'** Überschrift 1.1'.encode(u'utf-8'))311 self.assertEqual(vim.current.buffer[9], u'* Überschrift 1.2'.encode(u'utf-8'))312 self.assertEqual(vim.current.buffer[12], u'*** Überschrift 1.2.1.falsch'.encode(u'utf-8'))313 self.assertEqual(vim.current.buffer[15], u'** Überschrift 1.2.1'.encode(u'utf-8'))314 self.assertEqual(vim.current.buffer[16], u'* Überschrift 2'.encode(u'utf-8'))315 self.assertEqual(vim.current.window.cursor, (10, -1))316 # run tests with count317 def test_demote_parent_heading_count(self):318 vim.current.window.cursor = (2, 0)319 vim.EVALRESULTS[u"v:count"] = u'3'.encode(u'utf-8')320 self.assertNotEqual(self.editstructure.demote_heading(), None)321 self.assertEqual(len(vim.CMDHISTORY), 3)322 self.assertEqual(vim.CMDHISTORY[-3], u'normal 2ggV16gg='.encode(u'utf-8'))323 self.assertEqual(vim.CMDHISTORY[-2], u'normal 2ggV16gg='.encode(u'utf-8'))324 self.assertEqual(vim.CMDHISTORY[-1], u'normal 2ggV16gg='.encode(u'utf-8'))325 self.assertEqual(vim.current.buffer[1], u'**** Überschrift 1'.encode(u'utf-8'))326 self.assertEqual(vim.current.buffer[5], u'***** Überschrift 1.1'.encode(u'utf-8'))327 self.assertEqual(vim.current.buffer[9], u'***** Überschrift 1.2'.encode(u'utf-8'))328 self.assertEqual(vim.current.buffer[12], u'******* Überschrift 1.2.1.falsch'.encode(u'utf-8'))329 self.assertEqual(vim.current.buffer[15], u'****** Überschrift 1.2.1'.encode(u'utf-8'))330 self.assertEqual(vim.current.buffer[16], u'* Überschrift 2'.encode(u'utf-8'))331 self.assertEqual(vim.current.buffer[16], u'* Überschrift 2'.encode(u'utf-8'))332 self.assertEqual(vim.current.window.cursor, (2, 3))333 def test_promote_parent_heading(self):334 vim.current.window.cursor = (13, 0)335 vim.EVALRESULTS[u"v:count"] = u'3'.encode(u'utf-8')336 self.assertNotEqual(self.editstructure.promote_heading(), None)337 self.assertEqual(len(vim.CMDHISTORY), 3)338 self.assertEqual(vim.CMDHISTORY[-3], u'normal 13ggV15gg='.encode(u'utf-8'))339 self.assertEqual(vim.CMDHISTORY[-2], u'normal 13ggV15gg='.encode(u'utf-8'))340 self.assertEqual(vim.CMDHISTORY[-1], u'normal 13ggV16gg='.encode(u'utf-8'))341 self.assertEqual(vim.current.buffer[5], u'** Überschrift 1.1'.encode(u'utf-8'))342 self.assertEqual(vim.current.buffer[9], u'** Überschrift 1.2'.encode(u'utf-8'))343 self.assertEqual(vim.current.buffer[12], u'* Überschrift 1.2.1.falsch'.encode(u'utf-8'))344 self.assertEqual(vim.current.buffer[15], u'** Überschrift 1.2.1'.encode(u'utf-8'))345 self.assertEqual(vim.current.buffer[16], u'* Überschrift 2'.encode(u'utf-8'))346 self.assertEqual(vim.current.window.cursor, (13, -3))347def suite():...

Full Screen

Full Screen

fuzz.py

Source:fuzz.py Github

copy

Full Screen

1# Fuzzing functions for qcow2 fields2#3# Copyright (C) 2014 Maria Kustova <maria.k@catit.be>4#5# This program is free software: you can redistribute it and/or modify6# it under the terms of the GNU General Public License as published by7# the Free Software Foundation, either version 2 of the License, or8# (at your option) any later version.9#10# This program is distributed in the hope that it will be useful,11# but WITHOUT ANY WARRANTY; without even the implied warranty of12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the13# GNU General Public License for more details.14#15# You should have received a copy of the GNU General Public License16# along with this program. If not, see <http://www.gnu.org/licenses/>.17#18import random19from functools import reduce20UINT8 = 0xff21UINT16 = 0xffff22UINT32 = 0xffffffff23UINT64 = 0xffffffffffffffff24# Most significant bit orders25UINT32_M = 3126UINT64_M = 6327# Fuzz vectors28UINT8_V = [0, 0x10, UINT8//4, UINT8//2 - 1, UINT8//2, UINT8//2 + 1, UINT8 - 1,29 UINT8]30UINT16_V = [0, 0x100, 0x1000, UINT16//4, UINT16//2 - 1, UINT16//2, UINT16//2 + 1,31 UINT16 - 1, UINT16]32UINT32_V = [0, 0x100, 0x1000, 0x10000, 0x100000, UINT32//4, UINT32//2 - 1,33 UINT32//2, UINT32//2 + 1, UINT32 - 1, UINT32]34UINT64_V = UINT32_V + [0x1000000, 0x10000000, 0x100000000, UINT64//4,35 UINT64//2 - 1, UINT64//2, UINT64//2 + 1, UINT64 - 1,36 UINT64]37BYTES_V = [b'%s%p%x%d', b'.1024d', b'%.2049d', b'%p%p%p%p', b'%x%x%x%x',38 b'%d%d%d%d', b'%s%s%s%s', b'%99999999999s', b'%08x', b'%%20d', b'%%20n',39 b'%%20x', b'%%20s', b'%s%s%s%s%s%s%s%s%s%s', b'%p%p%p%p%p%p%p%p%p%p',40 b'%#0123456x%08x%x%s%p%d%n%o%u%c%h%l%q%j%z%Z%t%i%e%g%f%a%C%S%08x%%',41 b'%s x 129', b'%x x 257']42def random_from_intervals(intervals):43 """Select a random integer number from the list of specified intervals.44 Each interval is a tuple of lower and upper limits of the interval. The45 limits are included. Intervals in a list should not overlap.46 """47 total = reduce(lambda x, y: x + y[1] - y[0] + 1, intervals, 0)48 r = random.randint(0, total - 1) + intervals[0][0]49 for x in zip(intervals, intervals[1:]):50 r = r + (r > x[0][1]) * (x[1][0] - x[0][1] - 1)51 return r52def random_bits(bit_ranges):53 """Generate random binary mask with ones in the specified bit ranges.54 Each bit_ranges is a list of tuples of lower and upper limits of bit55 positions will be fuzzed. The limits are included. Random amount of bits56 in range limits will be set to ones. The mask is returned in decimal57 integer format.58 """59 bit_numbers = []60 # Select random amount of random positions in bit_ranges61 for rng in bit_ranges:62 bit_numbers += random.sample(range(rng[0], rng[1] + 1),63 random.randint(0, rng[1] - rng[0] + 1))64 val = 065 # Set bits on selected positions to ones66 for bit in bit_numbers:67 val |= 1 << bit68 return val69def truncate_bytes(sequences, length):70 """Return sequences truncated to specified length."""71 if type(sequences) == list:72 return [s[:length] for s in sequences]73 else:74 return sequences[:length]75def validator(current, pick, choices):76 """Return a value not equal to the current selected by the pick77 function from choices.78 """79 while True:80 val = pick(choices)81 if not val == current:82 return val83def int_validator(current, intervals):84 """Return a random value from intervals not equal to the current.85 This function is useful for selection from valid values except current one.86 """87 return validator(current, random_from_intervals, intervals)88def bit_validator(current, bit_ranges):89 """Return a random bit mask not equal to the current.90 This function is useful for selection from valid values except current one.91 """92 return validator(current, random_bits, bit_ranges)93def bytes_validator(current, sequences):94 """Return a random bytes value from the list not equal to the current.95 This function is useful for selection from valid values except current one.96 """97 return validator(current, random.choice, sequences)98def selector(current, constraints, validate=int_validator):99 """Select one value from all defined by constraints.100 Each constraint produces one random value satisfying to it. The function101 randomly selects one value satisfying at least one constraint (depending on102 constraints overlaps).103 """104 def iter_validate(c):105 """Apply validate() only to constraints represented as lists.106 This auxiliary function replaces short circuit conditions not supported107 in Python 2.4108 """109 if type(c) == list:110 return validate(current, c)111 else:112 return c113 fuzz_values = [iter_validate(c) for c in constraints]114 # Remove current for cases it's implicitly specified in constraints115 # Duplicate validator functionality to prevent decreasing of probability116 # to get one of allowable values117 # TODO: remove validators after implementation of intelligent selection118 # of fields will be fuzzed119 try:120 fuzz_values.remove(current)121 except ValueError:122 pass123 return random.choice(fuzz_values)124def magic(current):125 """Fuzz magic header field.126 The function just returns the current magic value and provides uniformity127 of calls for all fuzzing functions.128 """129 return current130def version(current):131 """Fuzz version header field."""132 constraints = UINT32_V + [133 [(2, 3)], # correct values134 [(0, 1), (4, UINT32)]135 ]136 return selector(current, constraints)137def backing_file_offset(current):138 """Fuzz backing file offset header field."""139 constraints = UINT64_V140 return selector(current, constraints)141def backing_file_size(current):142 """Fuzz backing file size header field."""143 constraints = UINT32_V144 return selector(current, constraints)145def cluster_bits(current):146 """Fuzz cluster bits header field."""147 constraints = UINT32_V + [148 [(9, 20)], # correct values149 [(0, 9), (20, UINT32)]150 ]151 return selector(current, constraints)152def size(current):153 """Fuzz image size header field."""154 constraints = UINT64_V155 return selector(current, constraints)156def crypt_method(current):157 """Fuzz crypt method header field."""158 constraints = UINT32_V + [159 1,160 [(2, UINT32)]161 ]162 return selector(current, constraints)163def l1_size(current):164 """Fuzz L1 table size header field."""165 constraints = UINT32_V166 return selector(current, constraints)167def l1_table_offset(current):168 """Fuzz L1 table offset header field."""169 constraints = UINT64_V170 return selector(current, constraints)171def refcount_table_offset(current):172 """Fuzz refcount table offset header field."""173 constraints = UINT64_V174 return selector(current, constraints)175def refcount_table_clusters(current):176 """Fuzz refcount table clusters header field."""177 constraints = UINT32_V178 return selector(current, constraints)179def nb_snapshots(current):180 """Fuzz number of snapshots header field."""181 constraints = UINT32_V182 return selector(current, constraints)183def snapshots_offset(current):184 """Fuzz snapshots offset header field."""185 constraints = UINT64_V186 return selector(current, constraints)187def incompatible_features(current):188 """Fuzz incompatible features header field."""189 constraints = [190 [(0, 1)], # allowable values191 [(0, UINT64_M)]192 ]193 return selector(current, constraints, bit_validator)194def compatible_features(current):195 """Fuzz compatible features header field."""196 constraints = [197 [(0, UINT64_M)]198 ]199 return selector(current, constraints, bit_validator)200def autoclear_features(current):201 """Fuzz autoclear features header field."""202 constraints = [203 [(0, UINT64_M)]204 ]205 return selector(current, constraints, bit_validator)206def refcount_order(current):207 """Fuzz number of refcount order header field."""208 constraints = UINT32_V209 return selector(current, constraints)210def header_length(current):211 """Fuzz number of refcount order header field."""212 constraints = UINT32_V + [213 72,214 104,215 [(0, UINT32)]216 ]217 return selector(current, constraints)218def bf_name(current):219 """Fuzz the backing file name."""220 constraints = [221 truncate_bytes(BYTES_V, len(current))222 ]223 return selector(current, constraints, bytes_validator)224def ext_magic(current):225 """Fuzz magic field of a header extension."""226 constraints = UINT32_V227 return selector(current, constraints)228def ext_length(current):229 """Fuzz length field of a header extension."""230 constraints = UINT32_V231 return selector(current, constraints)232def bf_format(current):233 """Fuzz backing file format in the corresponding header extension."""234 constraints = [235 truncate_bytes(BYTES_V, len(current)),236 truncate_bytes(BYTES_V, (len(current) + 7) & ~7) # Fuzz padding237 ]238 return selector(current, constraints, bytes_validator)239def feature_type(current):240 """Fuzz feature type field of a feature name table header extension."""241 constraints = UINT8_V242 return selector(current, constraints)243def feature_bit_number(current):244 """Fuzz bit number field of a feature name table header extension."""245 constraints = UINT8_V246 return selector(current, constraints)247def feature_name(current):248 """Fuzz feature name field of a feature name table header extension."""249 constraints = [250 truncate_bytes(BYTES_V, len(current)),251 truncate_bytes(BYTES_V, 46) # Fuzz padding (field length = 46)252 ]253 return selector(current, constraints, bytes_validator)254def l1_entry(current):255 """Fuzz an entry of the L1 table."""256 constraints = UINT64_V257 # Reserved bits are ignored258 # Added a possibility when only flags are fuzzed259 offset = 0x7fffffffffffffff & \260 random.choice([selector(current, constraints), current])261 is_cow = random.randint(0, 1)262 return offset + (is_cow << UINT64_M)263def l2_entry(current):264 """Fuzz an entry of an L2 table."""265 constraints = UINT64_V266 # Reserved bits are ignored267 # Add a possibility when only flags are fuzzed268 offset = 0x3ffffffffffffffe & \269 random.choice([selector(current, constraints), current])270 is_compressed = random.randint(0, 1)271 is_cow = random.randint(0, 1)272 is_zero = random.randint(0, 1)273 value = offset + (is_cow << UINT64_M) + \274 (is_compressed << UINT64_M - 1) + is_zero275 return value276def refcount_table_entry(current):277 """Fuzz an entry of the refcount table."""278 constraints = UINT64_V279 return selector(current, constraints)280def refcount_block_entry(current):281 """Fuzz an entry of a refcount block."""282 constraints = UINT16_V...

Full Screen

Full Screen

userActions.ts

Source:userActions.ts Github

copy

Full Screen

1import { Socket } from "socket.io";2import { Room, User } from "../../../db/schema";3import roundHandler from "./round";4// import { STARTING_BALANCE } from "../../../constants/intialGameValues";5var turnCount = 1;6const userActionsHandler = async (socket: Socket) => {7 try {8 //Fold9 socket.on("fold", async ({roomId, id}) => {10 if (!roomId) return;11 var room = await Room.findById(roomId);12 if (!room) return;13 console.log(`User ${id} folded`)14 let currentPlayers = room.players.filter(player=>player.current_action !== "fold");15 for (let i = 0; i<currentPlayers.length;i++){16 if(currentPlayers[i]?.userId.toString()===id) {17 currentPlayers[i]!.turn = false;18 currentPlayers[i]!.current_action = "fold"19 currentPlayers[(i+1)%currentPlayers.length]!.turn = true;20 break;21 }22 }23 room.players.map(player => {24 let plyr = currentPlayers.find(p=>p.userId.toString() === player.userId.toString())25 if (plyr){26 return plyr27 } else {28 return player29 }30 })31 room.markModified("players");32 33 if (turnCount >= currentPlayers.length) {34 turnCount = 1;35 room.rndCnt++36 await room.save();37 roundHandler(socket,roomId)38 } else {39 turnCount++;40 } 41 await room.save();42 43 socket.emit("player_action");44 socket.in(`Room_${roomId}`).emit("player_action")45 });46 //check47 socket.on("check", async ({roomId,id}) => {48 if (!roomId) return;49 var room = await Room.findById(roomId);50 if (!room) return;51 console.log(`User ${id} checked`)52 let currentPlayers = room.players.filter(player=>player.current_action !== "fold");53 for (let i = 0; i<currentPlayers.length;i++){54 if(currentPlayers[i]?.userId.toString()===id) {55 currentPlayers[i]!.turn = false;56 currentPlayers[i]!.current_action = "check"57 currentPlayers[(i+1)%currentPlayers.length]!.turn = true;58 break;59 }60 }61 room.players.map(player => {62 let plyr = currentPlayers.find(p=>p.userId.toString() === player.userId.toString())63 if (plyr){64 return plyr65 } else {66 return player67 }68 })69 room.markModified("players");70 71 if (turnCount >= currentPlayers.length) {72 turnCount = 1;73 room.rndCnt++74 await room.save();75 roundHandler(socket,roomId)76 } else {77 turnCount++;78 }79 await room.save();80 socket.emit("player_action");81 socket.in(`Room_${roomId}`).emit("player_action")82 });83 //call84 socket.on("call", async ({roomId, id}) => {85 if (!roomId) return;86 var room = await Room.findById(roomId);87 if (!room) return;88 var user = await User.findById(id);89 if (!user) return;90 console.log(`User ${id} called`)91 let currentPlayers = room.players.filter(player=>player.current_action !== "fold");92 for (let i = 0; i<currentPlayers.length;i++){93 if(currentPlayers[i]?.userId.toString()===id) {94 currentPlayers[i]!.turn = false;95 currentPlayers[i]!.current_action = "call"96 if (!currentPlayers[i]!.currentBet) currentPlayers[i]!.currentBet = 0;97 if (currentPlayers[i]!.currentBet! > currentPlayers[i]!.currentBalance) {98 user.balance -= currentPlayers[i]!.currentBalance;99 room.pot += currentPlayers[i]!.currentBalance;100 currentPlayers[i]!.currentBet =currentPlayers[i]!.currentBalance;101 currentPlayers[i]!.currentBalance = 0;102 } else {103 currentPlayers[i]!.currentBalance -= (room.currentRoundBet - currentPlayers[i]!.currentBet!);104 user.balance -= (room.currentRoundBet - currentPlayers[i]!.currentBet!)105 room.pot += (room.currentRoundBet - currentPlayers[i]!.currentBet!);106 currentPlayers[i]!.currentBet = room.currentRoundBet;107 }108 currentPlayers[(i+1)%currentPlayers.length]!.turn = true;109 break;110 }111 }112 room.players.map(player => {113 let plyr = currentPlayers.find(p=>p.userId.toString() === player.userId.toString())114 if (plyr){115 return plyr116 } else {117 return player118 }119 })120 room.markModified("players");121 122 123 if (turnCount >= currentPlayers.length) {124 turnCount = 1;125 room.rndCnt++126 await room.save();127 roundHandler(socket,roomId)128 } else {129 turnCount++;130 }131 await user.save();132 await room.save();133 socket.emit("player_action");134 socket.in(`Room_${roomId}`).emit("player_action")135 });136 //bet/rise137 socket.on("bet/rise", async ({roomId,id,value}) => {138 if (!roomId) return;139 var room = await Room.findById(roomId);140 if (!room) return;141 var user = await User.findById(id);142 if (!user) return;143 console.log(`User ${id} rised/bet ${value}`)144 let currentPlayers = room.players.filter(player=>player.current_action !== "fold");145 for (let i = 0; i<currentPlayers.length;i++){146 if(currentPlayers[i]?.userId.toString()===id) {147 if (value > currentPlayers[i]!.currentBalance) value = currentPlayers[i]!.currentBalance;148 currentPlayers[i]!.turn = false;149 currentPlayers[i]!.current_action = "bet/rise";150 if (!currentPlayers[i]!.currentBet) currentPlayers[i]!.currentBet = 0;151 room.currentRoundBet = value;152 currentPlayers[i]!.currentBalance -= (value - currentPlayers[i]!.currentBet!);153 user.balance -= (value - currentPlayers[i]!.currentBet!);154 room.pot += (room.currentRoundBet - currentPlayers[i]!.currentBet!);155 currentPlayers[i]!.currentBet = room.currentRoundBet;156 currentPlayers[(i+1)%currentPlayers.length]!.turn = true;157 break;158 }159 }160 room.players.map(player => {161 let plyr = currentPlayers.find(p=>p.userId.toString() === player.userId.toString())162 if (plyr){163 return plyr164 } else {165 return player166 }167 })168 room.markModified("players");169 await user.save();170 await room.save();171 //start betting Round172 turnCount = 2;173 socket.emit("player_action");174 socket.in(`Room_${roomId}`).emit("player_action")175 });176 } catch (err) {177 console.log(err)178 }179};...

Full Screen

Full Screen

CurrentController.ts

Source:CurrentController.ts Github

copy

Full Screen

1import { NextFunction, Request, Response } from "express";2import { prismaClient } from "../prisma/prismaClient";3import { CurrentService } from "../services/CurrentService";4class CurrentController {5 async getCurrentStatus(6 request: Request,7 response: Response,8 next: NextFunction9 ) {10 try {11 if (!request.user_id)12 return response.status(401).json({ message: "Unauthorized" });13 const service = new CurrentService();14 const currentStatus = await service.getCurrentStatus(request.user_id);15 return response.json(currentStatus);16 } catch (err) {17 next(err);18 }19 }20 async startCurrent(request: Request, response: Response, next: NextFunction) {21 try {22 if (!request.user_id)23 return response.status(401).json({ message: "Unauthorized" });24 const service = new CurrentService();25 let currentStatus = await service.getCurrentStatus(request.user_id);26 if (!currentStatus.hasAvailableCurrent)27 return response.json(currentStatus);28 const canCreateCurrent = await service.startNewCurrent(request.user_id);29 if (!canCreateCurrent)30 return response.status(404).json({ message: "Training unavailables" });31 currentStatus = await service.getCurrentStatus(request.user_id);32 return response.json(currentStatus);33 } catch (err) {34 next(err);35 }36 }37 async stopCurrent(request: Request, response: Response, next: NextFunction) {38 try {39 if (!request.user_id)40 return response.status(401).json({ message: "Unauthorized" });41 const service = new CurrentService();42 let currentStatus = await service.getCurrentStatus(request.user_id);43 if (!currentStatus.activeCurrent) return response.json(currentStatus);44 await service.stopActiveCurrents(request.user_id);45 currentStatus = await service.getCurrentStatus(request.user_id);46 return response.json(currentStatus);47 } catch (err) {48 next(err);49 }50 }51 async completeCurrentExercise(52 request: Request,53 response: Response,54 next: NextFunction55 ) {56 try {57 const { exercise_id } = request.params;58 if (!request.user_id)59 return response.status(401).json({ message: "Unauthorized" });60 const service = new CurrentService();61 let currentStatus = await service.getCurrentStatus(request.user_id);62 if (!currentStatus.activeCurrent) return response.json(currentStatus);63 if (64 !currentStatus.activeCurrent.currentExercises.some(65 (item) => item.id === exercise_id66 )67 )68 return response.status(409).send("Unavailable to manage this exercise");69 await service.manageCurrentExercise(70 request.user_id,71 exercise_id,72 "concluded"73 );74 currentStatus = await service.getCurrentStatus(request.user_id);75 return response.json(currentStatus);76 } catch (err) {77 next(err);78 }79 }80 async skipCurrentExercise(81 request: Request,82 response: Response,83 next: NextFunction84 ) {85 try {86 const { exercise_id } = request.params;87 if (!request.user_id)88 return response.status(401).json({ message: "Unauthorized" });89 const service = new CurrentService();90 let currentStatus = await service.getCurrentStatus(request.user_id);91 if (!currentStatus.activeCurrent) return response.json(currentStatus);92 if (93 !currentStatus.activeCurrent.currentExercises.some(94 (item) => item.id === exercise_id95 )96 )97 return response.status(409).send("Unavailable to manage this exercise");98 await service.manageCurrentExercise(99 request.user_id,100 exercise_id,101 "skiped"102 );103 currentStatus = await service.getCurrentStatus(request.user_id);104 return response.json(currentStatus);105 } catch (err) {106 next(err);107 }108 }109 async restoreCurrentExercise(110 request: Request,111 response: Response,112 next: NextFunction113 ) {114 try {115 const { exercise_id } = request.params;116 if (!request.user_id)117 return response.status(401).json({ message: "Unauthorized" });118 const service = new CurrentService();119 let currentStatus = await service.getCurrentStatus(request.user_id);120 if (!currentStatus.activeCurrent) return response.json(currentStatus);121 if (122 !currentStatus.activeCurrent.currentExercises.some(123 (item) => item.id === exercise_id124 )125 )126 return response.status(409).send("Unavailable to manage this exercise");127 await service.manageCurrentExercise(128 request.user_id,129 exercise_id,130 "reseted"131 );132 currentStatus = await service.getCurrentStatus(request.user_id);133 return response.json(currentStatus);134 } catch (err) {135 next(err);136 }137 }138}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1var distance = require('@turf/distance');2var helpers = require('@turf/helpers');3var polygon = helpers.polygon;4var featureCollection = helpers.featureCollection;5/**6 * Takes a bounding box and a cell depth and returns a set of triangular {@link Polygon|polygons} in a grid.7 *8 * @name triangleGrid9 * @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order10 * @param {number} cellSize dimension of each cell11 * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers12 * @returns {FeatureCollection<Polygon>} grid of polygons13 * @example14 * var bbox = [-95, 30 ,-85, 40];15 * var cellSize = 50;16 * var units = 'miles';17 *18 * var triangleGrid = turf.triangleGrid(bbox, cellSize, units);19 *20 * //addToMap21 * var addToMap = [triangleGrid];22 */23module.exports = function (bbox, cellSize, units) {24 var fc = featureCollection([]);25 var xFraction = cellSize / (distance([bbox[0], bbox[1]], [bbox[2], bbox[1]], units));26 var cellWidth = xFraction * (bbox[2] - bbox[0]);27 var yFraction = cellSize / (distance([bbox[0], bbox[1]], [bbox[0], bbox[3]], units));28 var cellHeight = yFraction * (bbox[3] - bbox[1]);29 var xi = 0;30 var currentX = bbox[0];31 while (currentX <= bbox[2]) {32 var yi = 0;33 var currentY = bbox[1];34 while (currentY <= bbox[3]) {35 if (xi % 2 === 0 && yi % 2 === 0) {36 fc.features.push(polygon([[37 [currentX, currentY],38 [currentX, currentY + cellHeight],39 [currentX + cellWidth, currentY],40 [currentX, currentY]41 ]]), polygon([[42 [currentX, currentY + cellHeight],43 [currentX + cellWidth, currentY + cellHeight],44 [currentX + cellWidth, currentY],45 [currentX, currentY + cellHeight]46 ]]));47 } else if (xi % 2 === 0 && yi % 2 === 1) {48 fc.features.push(polygon([[49 [currentX, currentY],50 [currentX + cellWidth, currentY + cellHeight],51 [currentX + cellWidth, currentY],52 [currentX, currentY]53 ]]), polygon([[54 [currentX, currentY],55 [currentX, currentY + cellHeight],56 [currentX + cellWidth, currentY + cellHeight],57 [currentX, currentY]58 ]]));59 } else if (yi % 2 === 0 && xi % 2 === 1) {60 fc.features.push(polygon([[61 [currentX, currentY],62 [currentX, currentY + cellHeight],63 [currentX + cellWidth, currentY + cellHeight],64 [currentX, currentY]65 ]]), polygon([[66 [currentX, currentY],67 [currentX + cellWidth, currentY + cellHeight],68 [currentX + cellWidth, currentY],69 [currentX, currentY]70 ]]));71 } else if (yi % 2 === 1 && xi % 2 === 1) {72 fc.features.push(polygon([[73 [currentX, currentY],74 [currentX, currentY + cellHeight],75 [currentX + cellWidth, currentY],76 [currentX, currentY]77 ]]), polygon([[78 [currentX, currentY + cellHeight],79 [currentX + cellWidth, currentY + cellHeight],80 [currentX + cellWidth, currentY],81 [currentX, currentY + cellHeight]82 ]]));83 }84 currentY += cellHeight;85 yi++;86 }87 xi++;88 currentX += cellWidth;89 }90 return fc;...

Full Screen

Full Screen

limitPlayerMovement.js

Source:limitPlayerMovement.js Github

copy

Full Screen

1const limitPlayerMovement = (canvas, player, level) => {2 switch (level) {3 case 0:4 if (5 player.getCurrentYcord - player.getCurrentWidthOrRadius <=6 canvas.getCurrentYcord7 ) {8 player.ycord += player.getCurrentSpeed;9 } else if (10 player.getCurrentYcord + player.getCurrentWidthOrRadius >=11 canvas.getCurrentHeight12 ) {13 player.ycord -= player.getCurrentSpeed;14 } else if (15 player.getCurrentXcord - player.getCurrentWidthOrRadius <=16 canvas.getCurrentXcord17 ) {18 player.xcord += player.getCurrentSpeed;19 }20 break;21 case 1:22 if (23 player.getCurrentYcord - player.getCurrentWidthOrRadius <=24 canvas.getCurrentYcord25 ) {26 player.ycord += player.getCurrentSpeed;27 } else if (28 player.getCurrentYcord + player.getCurrentWidthOrRadius >=29 canvas.getCurrentHeight30 ) {31 player.ycord -= player.getCurrentSpeed;32 } else if (33 player.getCurrentXcord - player.getCurrentWidthOrRadius <=34 canvas.getCurrentWidth / 435 ) {36 player.xcord += player.getCurrentSpeed;37 }38 break;39 case 2:40 if (41 player.getCurrentYcord - player.getCurrentWidthOrRadius <=42 canvas.getCurrentYcord43 ) {44 player.ycord += player.getCurrentSpeed;45 } else if (46 player.getCurrentYcord + player.getCurrentWidthOrRadius >=47 canvas.getCurrentHeight48 ) {49 player.ycord -= player.getCurrentSpeed;50 } else if (51 player.getCurrentXcord - player.getCurrentWidthOrRadius <=52 Math.floor((2 * canvas.getCurrentWidth) / 5)53 ) {54 player.xcord += player.getCurrentSpeed;55 }56 break;57 case 3:58 if (59 player.getCurrentYcord - player.getCurrentWidthOrRadius <=60 canvas.getCurrentYcord61 ) {62 player.ycord += player.getCurrentSpeed;63 } else if (64 player.getCurrentYcord + player.getCurrentWidthOrRadius >=65 canvas.getCurrentHeight66 ) {67 player.ycord -= player.getCurrentSpeed;68 } else if (69 player.getCurrentXcord - player.getCurrentWidthOrRadius <=70 Math.floor((2 * canvas.getCurrentWidth) / 5)71 ) {72 player.xcord += player.getCurrentSpeed;73 }74 break;75 case 4:76 if (77 player.getCurrentYcord - player.getCurrentWidthOrRadius <=78 canvas.getCurrentYcord79 ) {80 player.ycord += player.getCurrentSpeed;81 } else if (82 player.getCurrentYcord + player.getCurrentWidthOrRadius >=83 canvas.getCurrentHeight84 ) {85 player.ycord -= player.getCurrentSpeed;86 } else if (87 player.getCurrentXcord - player.getCurrentWidthOrRadius <=88 Math.floor((2 * canvas.getCurrentWidth) / 5)89 ) {90 player.xcord += player.getCurrentSpeed;91 }92 break;93 default:94 break;95 }96};97 ...

Full Screen

Full Screen

mergeTwoSortedLists.js

Source:mergeTwoSortedLists.js Github

copy

Full Screen

1/**2 * Definition for singly-linked list.3 * function ListNode(val) {4 * this.val = val;5 * this.next = null;6 * }7 */8/**9 * @param {ListNode} l110 * @param {ListNode} l211 * @return {ListNode}12 */13var mergeTwoLists = function(l1, l2) {14 // let dummyHead = new ListNode();15 // let currentL1 = l1;16 // let currentL2 = l2;17 // let currentHead = dummyHead;18 // while (currentL1 || currentL2) {19 // if (currentL1 === null) {20 // currentHead.next = currentL2;21 // break;22 // }23 // if (currentL2 === null) {24 // currentHead.next = currentL1;25 // break;26 // }27 28 // if (currentL1.val < currentL2.val) {29 // currentHead.next = new ListNode(currentL1.val);30 // currentL1 = currentL1.next;31 // currentHead = currentHead.next;32 // } else {33 // currentHead.next = new ListNode(currentL2.val);34 // currentL2 = currentL2.next;35 // currentHead = currentHead.next;36 // }37 38 // }39 // return dummyHead.next;40 41 const dummyHead = new ListNode();42 let currentL1 = l1;43 let currentL2 = l2;44 let currentNode = dummyHead;45 while (currentL1 || currentL2) {46 if (currentL1 === null) {47 currentNode.next = currentL2;48 break;49 }50 if (currentL2 === null) {51 currentNode.next = currentL1;52 break;53 }54 if (currentL1.val <= currentL2.val) {55 currentNode.next = new ListNode(currentL1.val);56 currentNode = currentNode.next;57 currentL1 = currentL1.next;58 } else if (currentL1.val > currentL2.val) {59 currentNode.next = new ListNode(currentL2.val);60 currentNode = currentNode.next;61 currentL2 = currentL2.next;62 }63 64 }65 return dummyHead.next;...

Full Screen

Full Screen

part2.py

Source:part2.py Github

copy

Full Screen

1import functools2from tqdm import tqdm3inp = list("476138259")4inp = [int(x) for x in inp]5latest = max(inp)6while(latest < 1000000):7 latest+=18 inp.append(latest)9currentDic = {}10for ind,i in enumerate(inp):11 if(ind+1 >= len(inp)):12 currentDic[i] = inp[0]13 else:14 currentDic[i] = inp[ind+1]15def executeRound(currentInp,previous,ind):16 currentCup = previous17 pickUp = []18 toPick = currentCup19 for i in range(3):20 pickUp.append(currentInp[toPick])21 toPick = currentInp[toPick]22 destination = currentCup -123 while destination in pickUp or destination < 1:24 destination -= 125 if(destination < 1):26 destination = max(currentInp.keys())27 currentInp[currentCup] = currentInp[pickUp[2]]28 for i in pickUp:29 del currentInp[i]30 gapStore = currentInp[destination]31 currentInp[destination] = pickUp[0]32 currentInp[pickUp[0]] = pickUp[1]33 currentInp[pickUp[1]] = pickUp[2]34 currentInp[pickUp[2]] = gapStore35 previous = currentInp[currentCup]36 return currentInp,previous37currentInp = copy.deepcopy(inp)38previous = currentInp[0]39for ind,i in tqdm(enumerate(range(10000000))):40 currentDic,previous = executeRound(currentDic,previous,ind)41current = currentDic[1]42finalString = []43while(current != 1):44 finalString.append(int(current))45 current = currentDic[current]46import math...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { act, renderHook } from '@testing-library/react-hooks'2import { useCounter } from './useCounter'3test('should increment counter', () => {4 const { result } = renderHook(() => useCounter())5 act(() => {6 result.current.increment()7 })8 expect(result.current.count).toBe(1)9})10import { renderHook, act } from 'react-hooks-testing-library'11import { useCounter } from './useCounter'12test('should increment counter', () => {13 const { result } = renderHook(() => useCounter())14 act(() => {15 result.current.increment()16 })17 expect(result.current.count).toBe(1)18})

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook, act } from '@testing-library/react-hooks/dom'2import useCounter from './useCounter'3describe('useCounter', () => {4 test('should increment count', () => {5 const { result } = renderHook(() => useCounter())6 act(() => {7 result.current.increment()8 })9 expect(result.current.count).toBe(1)10 })11 test('should decrement count', () => {12 const { result } = renderHook(() => useCounter())13 act(() => {14 result.current.decrement()15 })16 expect(result.current.count).toBe(-1)17 })18})19import { useState } from 'react'20export default function useCounter() {21 const [count, setCount] = useState(0)22 const increment = () => setCount(count + 1)23 const decrement = () => setCount(count - 1)24 return { count, increment, decrement }25}26{27 "scripts": {28 },29 "devDependencies": {30 }31}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook } from '@testing-library/react-hooks';2import { useSomeHook } from './useSomeHook';3describe('useSomeHook', () => {4 it('should return some value', () => {5 const { result } = renderHook(() => useSomeHook());6 expect(result.current).toEqual('some value');7 });8});9import { renderHook } from '@testing-library/react-hooks';10import { useSomeHook } from './useSomeHook';11describe('useSomeHook', () => {12 it('should return some value', () => {13 const { result } = renderHook(() => useSomeHook());14 expect(result.current).toEqual('some value');15 });16});

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { renderHook, act } from '@testing-library/react-hooks';3import { renderHook as renderHook2 } from '@testing-library/react-hooks/new';4import { render } from '@testing-library/react';5import { render as render2 } from '@testing-library/react/new';6import { fireEvent } from '@testing-library/dom';7import { fireEvent as fireEvent2 } from '@testing-library/dom/new';8import { toBeVisible } from '@testing-library/jest-dom';9import { toBeVisible as toBeVisible2 } from '@testing-library/jest-dom/new';10import { click } from '@testing-library/user-event';11import { click as click2 } from '@testing-library/user-event/new';12import { waitFor } from '@testing-library/react';13import { waitFor as waitFor2 } from '@testing-library/react/new';14import { waitForElement } from '@testing-library/react';15import { waitForElement as waitForElement2 } from '@testing-library/react/new';16import { waitForElementToBeRemoved } from '@testing-library/react';17import { waitForElementToBeRemoved as waitForElementToBeRemoved2 } from '@testing-library/react/new';18import { waitForDomChange } from '@testing-library/react';19import { waitForDomChange as waitForDomChange2 } from '@testing-library/react/new';20import { waitForElementToBeRemoved } from '@testing-library/react';21import { waitForElementToBeRemoved as waitForElementToBeRemoved2 } from '@testing-library

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook } from "@testing-library/react-hooks";2import useFetch from "../useFetch";3import { act } from "react-dom/test-utils";4test("useFetch", async () => {5 const { result, waitForNextUpdate } = renderHook(() =>6 );7 expect(result.current.loading).toBe(true);8 expect(result.current.error).toBe(null);9 expect(result.current.data).toBe(null);10 await act(async () => {11 await waitForNextUpdate();12 });13 expect(result.current.loading).toBe(false);14 expect(result.current.error).toBe(null);15 expect(result.current.data).not.toBe(null);16});17import { renderHook } from "@testing-library/react-hooks";18import useFetch from "../useFetch";19import { act } from "react-dom/test-utils";20test("useFetch", async () => {21 const { result, waitForNextUpdate } = renderHook(() =>22 );23 expect(result.current.loading).toBe(true);24 expect(result.current.error).toBe(null);25 expect(result.current.data).toBe(null);26 await waitForNextUpdate();27 expect(result.current.loading).toBe(false);28 expect(result.current.error).toBe(null);29 expect(result.current.data).not.toBe(null);30});31import { renderHook } from "@testing-library/react-hooks";32import useFetch from "../useFetch";33import { act } from "react-dom/test-utils";34test("useFetch", async () => {35 const { result, waitForNextUpdate } = renderHook(() =>36 );37 expect(result.current.loading).toBe(true);38 expect(result.current.error).toBe(null);39 expect(result.current.data).toBe(null);40 await waitForNextUpdate();41 expect(result.current.loading).toBe(false);42 expect(result.current.error).toBe(null);43 expect(result.current.data).not.toBe(null);44});45import { renderHook } from "@testing-library/react-hooks";46import useFetch from "../useFetch";47import { act } from "react-dom

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook } from "@testing-library/react-hooks";2import { useFetch } from "../src/hooks/useFetch";3test("should return data", async () => {4 await waitForNextUpdate();5 const { data } = result.current;6 expect(data.length).toBeGreaterThan(0);7});8import { renderHook } from "@testing-library/react-hooks";9import { useFetch } from "../src/hooks/useFetch";10test("should return data", async () => {11 await waitForNextUpdate();12 const { data } = result.current;13 expect(data.length).toBeGreaterThan(0);14});15import { renderHook } from "@testing-library/react-hooks";16import { useFetch } from "../src/hooks/useFetch";17test("should return data", async () => {18 await waitForNextUpdate();19 const { data } = result.current;20 expect(data.length).toBeGreaterThan(0);21});22import { renderHook } from "@testing-library/react-hooks";23import { useFetch } from "../src/hooks/useFetch";24test("should return data", async () => {25 await waitForNextUpdate();26 const { data } = result.current;27 expect(data.length).toBeGreaterThan(0);28});29import { renderHook } from "@testing-library/react-hooks";30import { useFetch } from "../src/hooks/useFetch";31test("should return data", async () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook } from '@testing-library/react-hooks'2import { useFetch } from './useFetch'3test('useFetch should return data', async () => {4 const { result, waitForNextUpdate } = renderHook(() =>5 await waitForNextUpdate()6 expect(result.current.data.name).toBe('Luke Skywalker')7})

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run testing-library-react-hooks automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful