�����    �   huggingface�{"info": {"features": {"id": {"dtype": "string", "_type": "Value"}, "text": {"dtype": "string", "_type": "Value"}, "dataset_id": {"dtype": "string", "_type": "Value"}}}}p4���� dataset_id��������text���� id����   b   �� ���P*P*��9�}a��a��a���a�>���!'-4;BIPV]dkry������������������ #)07>ELRY`gmtz�������������������#*18?FMSZahou|������������������� "(/5<CIPW^elsz������������������� %,39@GMT[bipw}������������������� %+18?FMT[bipv}������������������� %,3:@GNU\cjqx������������������!(/6=DKRY`gnt{������������������� $+29@GNU[bipw}�������������������   ' - 4 ; B I P W ^ d k r x  � � � � � � � � � � � � � � � � � �     & - 4 ; A H O V ] d k r y � � � � � � � � � � � � � � � � � � �      # ( / 6 = D J Q X _ f m t { � � � � � � � � � � � � � � � � � � �     % , 3 : A H O V ] d k r x  � � � � � � � � � � � � � � � � � � �     % , 3 8 ? F M T [ b i p v } � � � � � � � � � � � � � � � � � � �   '.5<CJQX_fmt{������������������� !(/6=DKRY`gnu{������������������� ")07>DKRY`fmt{������������������� !(/6=DKRY`gnu{������������������� !'.5<CHNU\cjqw~������������������#*18?FMT[ahov}������������������� ")07>ELRY`gntz�������������������#*07>ELSZahnu|������������������� $+29@GNU\cjpw~�������������������#*18?FMTZahov}�������������������#*18?ELSZahnu|�������������������  '.5<CJQX_fmt{������������������� &-4:AHOV]dkry������138468862435019948551356715844377960102987672222533129535484368864506087830547244761651074500286064331104395331665355130849055715891025345256343059757404533575014315047424627407088654478180760360164271660286046210273363034011700784095622372157150871605334037188037567496136043705710241855730538868137318634019861230316387212144113329992963779011458264942542478375655074214500796523295518871056516377210754472422966473895384584786053394756217010124464328551548726431414998349930418182051291555567469036316275239152150800637690835740740913780171737656970193377443602327613839574406550104419785263354728276052081102451435439221104304641292291240817784928709729633122110061306730040807333247604530413429811185631878243043750725865353669150720850087153085057324854242201014370080228393344004381801690213334841776254709415993751109191446198028278725195102436523622080940726906125062205072651808663536726288778951982261216474272945639259351826388416851442829191856776342230622033604283058367653131227960763424090939486703412068738710664138023139185321187544183624029065875003316398329869857310173791332577999362552314211941003875223415846788193521286762481454014241661424775748396313680322385523483666719169171624716626605815898574060912933029558788647021193721488481258594568240872329633785823668806486571357741013113435353139653917561397680418966391704461436981143944242725971466286925746292954051964847564249383788755824791560432071921246884592921145029332456245397988860093282305215626070656900908773174757227609324755259572781214650600515984053889139044859520676220122562484011007435766832127670984046161401834902733410242912477842713502422903329690846132028420601126201894589798880409226302333514374769816322459567417048159014891301133449246184458284075034769545514838841771555463130567618302548089504360427684800537842696293953656841289754325549854864481195296535649336460672181562555397163490402674106223277204107281747155611106020070545496139138834456883116173210390416186975344135483533453039938183433161462001993244844018575937684595740701253329860937513497414470605467044163214592267870365142629992045539016591371846538005064390179291491197657575083971864375561355760038804412941488583408958969413315322539798141191010968436637016987675836155584552844605287591743754728225830856025872411113449152356485392030762034036261315739094835368406546912315818761716531950590490712640837675422762623670344650843685514928282676897494697331541643353949711457510443157244805549471241225561566233969234173743061024562168684372411852500946057180390608934362752048568126184918956763939834377385434292954134449526931430811982663665169072398575861562826005878503813755828593220849500512152925234816457483435317550653017944127485202528252949132064757796914351846503073612564935766424352076128576856311125268076176785037616255740436374387322497039822754290958144812144812280941415629311818225581679957029736525144718737541191562058246347508152965531403145199315118760241900754756206139928260428438154182657462003333308782521011025697753500546230911021022426191017392514655903216348251341090660553611460068827205124003479299123627201123655230444133808581572364462800234154182738082601987632044562194545733104317060074021458541144438439242014111711245628358357246159329686136424421262296748749857222137841829825545383898175326385831327044827483966874302801078983925314706999633909485623976416192951633582457452023932246225487629740094104454107162705717857288876395288388142917728486594915204340185319634981186953111124884135211913517643724650857587520263280814108292657273286226626160181459343762180318271947493012403955312726500326448849964017719303063512337765611942310239529446234007523202682450947821330744620997931290085057580755142902766569781547287913024597184402952662275809496334789517745025135737252494149159011293733398722762208405600403424818162304215326418119851545201875778415563049455159021184750336739614614893471034299159448712882433128125578633972605803130889503182942460190735873187307589528208146133958180813112255678996942343234332309721505534606327164322758595464003599527748346099105212554140364651129201951390561649726118174283427104827051567664153892687342265713735120414922325300579476577430974222106983585743446300976500622977569336096511583461038560511792053065646037016178568724720763024221423937235721034448086139915957136516329165334703938464925668612449428844845212658695390709527831125182001653261424509750301386134387500778427283101350748219295027423745873874558219243317512426394997239362199148039396315722381778043472873736186306409211525563396775163627566806035061633333914999639400992510394153527668188851234920963125743345367408489331488656338703114313266537663759143775522647803597768329572018640675192142304688120073924219684595316375162666100383626931726754849008276020948600972014983320702435444274955811193067567346238238471122421115179826555744113971618476135901443924255493392622267281890647615112830895111404041287066947363926570735680268234741758657066309372328424453278475866754296774022818154108650421985364752976879146501565615581179045720207034781112337754575755837829241097634114623916586642016164335124154029243601700151892549751151267496525700540990884401337804098257783255689622433901589519217293234244631445969732345748028928938167589814400755149323393762944866531024729478054824971255444021475974549091351380104959866207963665151171415523504615856228718158545457662665384475835602339393359352993813447030583279119337322853934262012818404338985183683991523820258602262957339457393631117535366111713098445323976314260494302916002558624576685752933716803726296784164480620679952427771226671492144378021012987895698173451715624988828789201753570546495117486543547381334869524372754298417191582515767859127446133724613386759755330341231141166171497162035038028541636022818538409387920733860469837209149337428277151553303265381417724487417743180813818061386512214061411776295459042589421250664213413867288968143280535397437453068913300693414823586118473308538266472886644138241719833864003219559640829718537845021852727594334588777205733253899596035127754315560659463054583077373975153267701409963106306208853951229093720527323941932269393249452143188301415741621104839785825950414896912282332135065602436061007996305561728397507757218517483903496795018403912245288523991171286432461330556636756700184187935486198211323924830203122117236267442861615609287118862049360572961304452779531253921859840593868059718123228117580408343656696070863337311548920211766939380216437692021894041446116726179501550685449395133185511733306205848112276195516423612611600939516999276673874545322151928148234485736610294965118666981239856181072829170522986835580108403429500625748510242032821914844327426029981156093943596530248646464333267298939557206602521243118406450783244752900226512214021464317952�$=,[7�=?�F�Y ��}���������m�������}�DE#R�ZFty�������X�J�o���47+�,�-/�35@ BeP���.�V l�B�^ym�x��]���^��#y��Ɛ�����Y6��V�_De�N�.�d��������mft8w�ȏt�������$\8�OST+|0}��Ð��{�&����R���� 5  � � �] g m J{ � ؾ �� �% �3 �6 �7 �9 > �G %N �k �| �~ �� �� �� ͞ � �� t� i� � L� �� �� j� ! 8 c� � g� � � � �� �� d� -� ?� �$ �+ u V �� 9M O �Q ]Z �l {� /� �� y� :� �� �� 6&�h�r�}~�p�<�/��#�\��<�8��\�ixv<|��>�í���V���lvg���g�8����� ��-sBjqs�x�~�>�b�L�6�������^���1�3SǷ?��,�����@�` �"�)�2�<�L�S�d9x|�v�T���˷c����'*��]�j�@�;����c��!$g�imp�~I�����R ! dɌ(���\�u���&�\�%��������LT$D&�D������i � � 3( �^ W� [� � �� �v!-|!'�!��!c�!G�!8�!%�!��!��!��!��!�!�." C"�L";�"W�"��"�#�\# |#5�#ܾ#'�#��#�#��#�#Z5$�8$�:$4?$�T$BW$�X$%�A%C%R%{%�&�&�&M$&�<&~?&.c&mp&"�&r�&�&Y�&E�&��&��&T�&�&�4's8's'�'��'��'&�'��'s�'�(Z%(?(�E(�[(��(��(��(��(")P)e )~2)�@)AC)�F)�G)zM)bR)��)؜) �)�)��)i"*%)*�H*$I*ő*�*Ϝ*��*��*��*]�*8�*w+�x+?y+J~+�+)�+k�+k ,-,�#,(=,�I,hS,�U,9Z, k,��,3�,��,m�,�r-\�-��-7�-��-I�-��-(�-C�-F�-�.a.�d.��.��.�.}�.b�.�.��.� /�/ �/N�/��/��/)0t+0�,0/0�80�90-T0 V0dg0؉0�0r�0`�0*�0��0��0��0�31�1G�1��1u�1"�1�1۵1g�1��1/�1��1+�1X�2��2I�2��2^t3�t3 �3ϒ3��3�3ŗ3��3�3��3��3��3� 4h4-24 R4��4# 5�'5+5�,5�/5��5y�5��5#�5c�5�5I�5%�5��5=�5�#6�=6I6�e6@�6��6��6!�6l 7�,7~.7h6797~�7��7F�7/�7��7��7�88�$8�%81'8��8��8q�8~�8��89� 9�9�69J79=:9C<9$=9�9��9��93�9�!:,%:�/:-C:�Z:'j:Ll: �:�:��: ;�!;F/;�4;�6;$O;~P;Fb;mg;}�;��;ȹ;\<�<�<�0<�?<�A<"�<؏<�\=v^= `=�b=j=�j=�l=�p=Kq=(z=ց=F�=��=2�=˘=��=��=��=�>u>�M>dl?�l?�m?�v?��?j�?�?´?�?� @VA@A�A4-ADXA)YA*[AayAH�A��A��Ab�AگA��A��A��AV�A��A\ Bv!Bm+B8B?B�BB��Cm�CP�C\ODMaD�{D�Ds�D��D�D�DʷD��D�E� E1EQSEJnE�qE��E��E�E F�F(F�&F%1Fa7FnDF�GFxHF IFhVF�[FofF!jF�F��F�FӚF��FE�F��F�F�lG�tG��G0�G�G��G=�GK�Gy�G��G/�G��Gj�GIH�,H�6H�8H�>HHHMH=�Hu�H��H�H��H#�H`�H�I�UI�WI�fI+jIޒI��I>�Ic�I��I)�I�pJ��J/�J2�J�J��J!�JK� K�K�K}K�K�K 9K�\�\�\�\�\��\$�\k�] ^�^((^H-^,L^�L^*M^tP^%Y^�^��^&�^g�^q�^��^�^��^�_� _�#_,_�-_�H_�M_�o_�y_�|_i�_`1`�`�`&`�g`8k`�q`�a�ah$a�,a1a<7a�ta�uawavza�}a#include "tp_data/Globals.h" #include "tp_data/CollectionFactory.h" #include "tp_data/members/StringMember.h" #include "tp_data/members/NumberMember.h" //################################################################################################## namespace tp_data { TP_DEFINE_ID( stringSID, "String"); TP_DEFINE_ID( intSID, "Int"); TP_DEFINE_ID( sizeTSID, "Size t"); TP_DEFINE_ID( floatSID, "Float"); TP_DEFINE_ID( doubleSID, "Double"); //################################################################################################## void createCollectionFactories(CollectionFactory& collectionFactory) { collectionFactory.addMemberFactory(new StringMemberFactory()); collectionFactory.addMemberFactory(new IntMemberFactory()); collectionFactory.addMemberFactory(new SizeTMemberFactory()); collectionFactory.addMemberFactory(new FloatMemberFactory()); collectionFactory.addMemberFactory(new DoubleMemberFactory()); } //################################################################################################## void createAllCollectionFactories(CollectionFactory& collectionFactory) { for(const auto& createCollectionFactories : tp_data::createCollectionFactoriesRegister()) createCollectionFactories(collectionFactory); } //################################################################################################## std::vector > & createCollectionFactoriesRegister() { static std::vector> createCollectionFactoriesRegister; return createCollectionFactoriesRegister; } REGISTER_CREATE_COLLECTION_FACTORIES; //################################################################################################## int staticInit() { return 0; } } nondejus/executor1-10 #include #include #include #include #include #include #include #include #include #include #define CONFIGEXTENSION ".ecf" void Executor::ParseConfigFile(std::string appname, OSType type) { ROMlib_WindowName.clear(); ROMlib_Comments.clear(); ROMlib_desired_bpp = 0; ROMlib_configfilename = ROMlib_ConfigurationFolder + "/" + appname + CONFIGEXTENSION; configfile = Ufopen(ROMlib_configfilename.c_str(), "r"); if(!configfile && type != 0) { char buf[16]; sprintf(buf, "%08x", type); ROMlib_configfilename = ROMlib_ConfigurationFolder + "/" + buf + CONFIGEXTENSION; configfile = Ufopen(ROMlib_configfilename.c_str(), "r"); } if(configfile) { yyparse(); if(ROMlib_get_appearance() == appearance_win3) ROMlib_options |= ROMLIB_RECT_SCREEN_BIT; #if 0 if (ROMlib_options & ROMLIB_NOCLOCK_BIT) ROMlib_noclock = true; #endif if(ROMlib_options & ROMLIB_BLIT_OS_BIT) ROMlib_WriteWhen(WriteInOSEvent); if(ROMlib_options & ROMLIB_BLIT_TRAP_BIT) ROMlib_WriteWhen(WriteAtEndOfTrap); if(ROMlib_options & ROMLIB_BLIT_OFTEN_BIT) ROMlib_WriteWhen(WriteInBltrgn); #if 0 if (ROMlib_options & ROMLIB_ACCELERATED_BIT) ROMlib_accelerated = true; else ROMlib_accelerated = false; #endif if(ROMlib_options & ROMLIB_REFRESH_BIT) ROMlib_refresh = 10; if(ROMlib_options & ROMLIB_SOUNDOFF_BIT) ROMlib_PretendSound = soundoff; if(ROMlib_options & ROMLIB_PRETENDSOUND_BIT) ROMlib_PretendSound = soundpretend; if(ROMlib_options & ROMLIB_SOUNDON_BIT) ROMlib_PretendSound = SOUND_WORKS_P() ? soundon : soundpretend; #if 0 if (ROMlib_options & ROMLIB_PASSPOSTSCRIPT_BIT) ROMlib_passpostscript = true; else ROMlib_passpostscript = false; #else /* #warning ROMlib_passpostscript wired to true */ ROMlib_passpostscript = true; #endif if(ROMlib_options & ROMLIB_NEWLINETOCR_BIT) ROMlib_newlinetocr = true; else ROMlib_newlinetocr = false; if(ROMlib_options & ROMLIB_DIRECTDISKACCESS_BIT) ROMlib_directdiskaccess = true; else ROMlib_directdiskaccess = false; if(ROMlib_options & ROMLIB_NOWARN32_BIT) ROMlib_nowarn32 = true; else ROMlib_nowarn32 = false; if(ROMlib_options & ROMLIB_FLUSHOFTEN_BIT) ROMlib_flushoften = true; else ROMlib_flushoften = false; if(ROMlib_options & ROMLIB_PRETEND_HELP_BIT) ROMlib_pretend_help = true; else ROMlib_pretend_help = false; if(ROMlib_options & ROMLIB_PRETEND_ALIAS_BIT) ROMlib_pretend_alias = true; else ROMlib_pretend_alias = false; if(ROMlib_options & ROMLIB_PRETEND_EDITION_BIT) ROMlib_pretend_edition = true; else ROMlib_pretend_edition = false; if(ROMlib_options & ROMLIB_PRETEND_SCRIPT_BIT) ROMlib_pretend_script = true; else ROMlib_pretend_script = false; if(ROMlib_desired_bpp) SetDepth(LM(MainDevice), ROMlib_desired_bpp, 0, 0); fclose(configfile); } if(!ROMlib_WindowName.empty()) vdriver->setTitle(ROMlib_WindowName); else vdriver->setTitle(appname); } /* * Get rid of any characters that cause trouble inside a quoted * string. Look at yylex() in parse.y. */ static void clean(std::string& str) { for(char& c : str) if(c == '"') c = '\''; } int Executor::saveprefvalues(const char *savefilename) { int retval; FILE *fp; if((fp = Ufopen(savefilename, "w"))) { { const char *lastslash; lastslash = strrchr(savefilename, '/'); lastslash = lastslash ? lastslash + 1 : savefilename; fprintf(fp, "// This Configuration file (%s) was built by " "Executor\n", lastslash); } if(!ROMlib_Comments.empty()) { clean(ROMlib_Comments); fprintf(fp, "Comments = \"%s\";\n", ROMlib_Comments.c_str()); } if(!ROMlib_WindowName.empty()) { clean(ROMlib_WindowName); fprintf(fp, "WindowName = \"%s\";\n", ROMlib_WindowName.c_str()); } else { std::string window_name = vdriver->getTitle(); clean(window_name); fprintf(fp, "// WindowName = \"%s\";\n", window_name.c_str()); } fprintf(fp, "BitsPerPixel = %d;\n", toHost(PIXMAP_PIXEL_SIZE(GD_PMAP(LM(MainDevice))))); #if 0 && defined(MACOSX_) fprintf(fp, "ScreenSize = { %ld, %ld };\n", (long) curr_width, (long) curr_height); fprintf(fp, "MacSize = { %ld, %ld };\n", (long) orig_width, (long) orig_height); #endif fprintf(fp, "SystemVersion = %s;\n", C_STRING_FROM_SYSTEM_VERSION()); fprintf(fp, "RefreshNumber = %d;\n", ROMlib_refresh); fprintf(fp, "Delay = %d;\n", ROMlib_delay); fprintf(fp, "Options = {"); switch(ROMlib_when) { case WriteAlways: case WriteInBltrgn: fprintf(fp, "BlitOften"); break; default: case WriteNever: case WriteInOSEvent: fprintf(fp, "BlitInOSEvent"); break; case WriteAtEndOfTrap: fprintf(fp, "BlitAtTrapEnd"); break; } switch(ROMlib_PretendSound) { case soundoff: fprintf(fp, ", SoundOff"); break; case soundpretend: fprintf(fp, ", PretendSound"); break; case soundon: fprintf(fp, ", SoundOn"); break; } if(ROMlib_passpostscript) fprintf(fp, ", PassPostscript"); if(ROMlib_newlinetocr) fprintf(fp, ", NewLineToCR"); if(ROMlib_directdiskaccess) fprintf(fp, ", DirectDiskAccess"); #if 0 if (ROMlib_accelerated) fprintf(fp, ", Accelerated"); if (ROMlib_clock != 2) fprintf(fp, ", NoClock"); #endif if(ROMlib_nowarn32) fprintf(fp, ", NoWarn32"); if(ROMlib_flushoften) fprintf(fp, ", FlushOften"); if(ROMlib_options & ROMLIB_DEBUG_BIT) fprintf(fp, ", Debug"); if(ROMlib_pretend_help) fprintf(fp, ", PretendHelp"); if(ROMlib_pretend_edition) fprintf(fp, ", PretendEdition"); if(ROMlib_pretend_script) fprintf(fp, ", PretendScript"); if(ROMlib_pretend_alias) fprintf(fp, ", PretendAlias"); fprintf(fp, "};\n"); fclose(fp); retval = true; } else retval = false; return retval; }src/developer/debug/zxdb/expr/expr_unittest.cc0 // Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/developer/debug/zxdb/expr/expr.h" #include "gtest/gtest.h" #include "src/developer/debug/zxdb/expr/mock_eval_context.h" #include "src/developer/debug/zxdb/symbols/modified_type.h" #include "src/developer/debug/zxdb/symbols/type_test_support.h" namespace zxdb { TEST(Expr, ValueToAddressAndSize) { auto eval_context = fxl::MakeRefCounted(); // Ints are OK but have no size. uint64_t address = 0; std::optional size; ASSERT_TRUE(ValueToAddressAndSize(eval_context, ExprValue(23), &address, &size).ok()); EXPECT_EQ(23u, address); EXPECT_EQ(std::nullopt, size); // Structure. auto uint64_type = MakeUint64Type(); auto collection = MakeCollectionType(DwarfTag::kStructureType, "Foo", {{"a", uint64_type}, {"b", uint64_type}}); std::vector collection_data; collection_data.resize(collection->byte_size()); // Currently evaluating a structure is expected to fail. // TODO(bug 44074) support non-pointer values and take their address implicitly. address = 0; size = std::nullopt; Err err = ValueToAddressAndSize( eval_context, ExprValue(collection, collection_data, ExprValueSource(0x12345678)), &address, &size); ASSERT_TRUE(err.has_error()); EXPECT_EQ("Can't convert 'Foo' to an address.", err.msg()); EXPECT_EQ(0u, address); EXPECT_EQ(std::nullopt, size); // Pointer to a collection. auto collection_ptr = fxl::MakeRefCounted(DwarfTag::kPointerType, collection); std::vector ptr_data{8, 7, 6, 5, 4, 3, 2, 1}; address = 0; size = std::nullopt; err = ValueToAddressAndSize(eval_context, ExprValue(collection_ptr, ptr_data), &address, &size); ASSERT_TRUE(err.ok()); EXPECT_EQ(0x0102030405060708u, address); ASSERT_TRUE(size); EXPECT_EQ(collection->byte_size(), *size); } } // namespace zxdb DaOnlyOwner/Hyc #include "PromoteToSret.h" #include "UptrCast.h" void PromoteToSret::visit(FuncDefStmt& func_def) { current_func_def = &func_def; for (auto& arg : func_def.decl->arg_list) { if (arg.decl->type.is_user_defined(scopes) || arg.decl->type.is_array_type()) { arg.decl->is_passed_as_ptr = true; arg.decl->type.promote_pointer(); } } if (func_def.decl->named_return) { func_def.decl->ret_type->semantic_type = scopes.get_type("void"); auto cloned = dynamic_uptr_cast_no_deleter(func_def.decl->named_return->clone()); assert(cloned); func_def.decl->arg_list.insert(func_def.decl->arg_list.begin(), { false,std::move(cloned) }); } else if (!(func_def.decl->ret_type->semantic_type.is_predefined(scopes) || func_def.decl->ret_type->semantic_type.is_pointer_type())) { func_def.decl->is_sret = true; auto ret_t = func_def.decl->ret_type->semantic_type; func_def.decl->ret_type->semantic_type = scopes.get_type("void"); ret_t.promote_pointer(); uptr decl = std::make_unique(nullptr, Token(Token::Specifier::Ident, ".ret")); decl->type = ret_t; decl->is_sret = true; auto ident = std::make_unique(decl->name); ident->sem_type = decl->type; ident->decl = decl.get(); expr = std::make_unique(Token(Token::Specifier::Asterix, "*"),std::move(ident)); expr->sem_type = decl->type.with_pop(); func_def.decl->arg_list.insert(func_def.decl->arg_list.begin(), { false,std::move(decl) }); make_new_stmt(func_def.body); } } void PromoteToSret::visit(ReturnStmt& rs) { // This is the place for a move auto clone = expr->clone(); std::string name; if (current_func_def->decl->moved_return) { name = "#"; } else name = "="; auto bin = std::make_unique(Token(Token::Specifier::Equal, name), std::move(clone), std::move(rs.returned_expr)); bin->sem_type = scopes.get_type("void"); auto stmt = std::make_unique(std::move(bin)); auto ret_void = std::make_unique(nullptr, Token()); ret({ std::move(stmt),std::move(ret_void) }); } void PromoteToSret::visit(IfStmt& if_stmt) { make_new_stmt(if_stmt.if_stmts); for (auto& e : if_stmt.all_elif_stmts) { make_new_stmt(e); } make_new_stmt(if_stmt.else_stmts); } void PromoteToSret::visit(WhileStmt& while_stmt) { make_new_stmt(while_stmt.stmts); } void PromoteToSret::visit(ScopeStmt& scope) { make_new_stmt(scope.stmts); } void PromoteToSret::make_new_stmt(std::vector>& stmts) { for (int i = 0; i < stmts.size(); i++) { auto& p = stmts[i]; auto& [fst, snd] = get(p); if (p->is_return_stmt()) { stmts[i] = std::move(fst); stmts.insert(stmts.begin() + i+1, std::move(snd)); return; } } } void llvm_promote_to_sret(Scopes& sc, NamespaceStmt& ns) { PromoteToSret pts(sc); ns.accept(pts); } // WIP: Some sort of edge case Runtime Error, but main idea is down // Could have some simplicity by extracting ternaries into variables // UPDATE: Now has TLE and base test cases pass, still WIP on time complexity #include using namespace std; int main() { std::ios_base::sync_with_stdio(false); cin.tie(nullptr); long long n, k; cin >> n >> k; vector a; for (int i{0}; i < n; ++i) { long long j; cin >> j; a.push_back(j); } sort(a.begin(), a.end()); // for (int i{0}; i < n; ++i) { // cout << a[i] << " "; // } // cout << endl; if (n == 1) { cout << (a[0] + k); return 0; } // bool odd{(n & 1) == 1}; ++k; long long mid{(n / 2)}; while (--k) { a[n / 2]++; // for (int i{0}; i < n; ++i) { // cout << a[i] << " "; // } // cout << endl; if (a[mid] > a[(mid) + 1]) { long long c{a[n / 2]}; // switch storage auto ub{upper_bound(a.begin() + mid, a.end(), a[(mid) + 1])}; //cout << a[(mid) + 1] << " " << ub - a.begin() << endl; if (ub == a.end()) { a[mid] = a[n - 1]; a[n - 1] = c; } else { a[mid] = a[ub - a.begin() - 1]; a[ub - a.begin() - 1] = c; } // for (int i{0}; i < n; ++i) { // cout << a[i] << " "; // } // cout << endl; } } // if (odd) { cout << a[n / 2]; // } else { // cout << (a[(n / 2) - 1] + a[(n / 2)]) / 2; // } return 0; } #include "../parserUtils.hpp" void setupParser() { parser.addAttribute(); parser.addAttribute(); parser.addAttribute(); parser.addAttribute(); parser.addAttribute(); parser.addAttribute(); } #include "Basic/Identifier.h" #include "Basic/Token.h" #include using namespace NatsuLib; using namespace NatsuLang; using namespace NatsuLang::Identifier; using namespace NatsuLang::Lex; namespace { constexpr bool IsKeyword(NatsuLang::Lex::TokenType token) noexcept { switch (token) { #define KEYWORD(X) case NatsuLang::Lex::TokenType::Kw_ ## X: #include "Basic/TokenDef.h" return true; default: return false; } } } IdentifierInfo::IdentifierInfo(nStrView name, Lex::TokenType tokenType) noexcept : m_Name{ name }, m_TokenType{ tokenType } { } nStrView IdentifierInfo::GetName() const noexcept { return m_Name; } nBool IdentifierInfo::IsKeyword() const noexcept { return ::IsKeyword(m_TokenType); } NatsuLang::Lex::TokenType IdentifierInfo::GetTokenType() const noexcept { return m_TokenType; } NatsuLang::Lex::TokenType IdentifierInfo::SetTokenType(Lex::TokenType tokenType) noexcept { return std::exchange(m_TokenType, tokenType); } nInt IdentifierInfo::CompareTo(natRefPointer const& other) const { return m_Name.GetView().Compare(other->m_Name); } natRefPointer IdentifierTable::GetOrAdd(nStrView name, Lex::TokenType tokenType) { auto iter = m_Identifiers.find(name); if (iter != m_Identifiers.end()) { return iter->second; } nBool succeed; tie(iter, succeed) = m_Identifiers.emplace(name, make_ref(name, tokenType)); if (!succeed) { nat_Throw(natErrException, NatErr_InternalErr, "Cannot add IdentifierInfo."); } return iter->second; } std::unordered_map>::const_iterator IdentifierTable::begin() const { return m_Identifiers.begin(); } std::unordered_map>::const_iterator IdentifierTable::end() const { return m_Identifiers.end(); } size_t IdentifierTable::size() const { return m_Identifiers.size(); } #pragma once /// @file #include namespace neon { /// Apply dirichlet conditions to the system defined by A, x, and b. /// This method selects the row and column of the degree of freedom with an /// imposed Dirichlet condition. /// The algorithm takes the row and performs a zeroing operation on it. To /// satisfy the equation system, the constrained column is multiplied with /// the Dirichlet value and subtracted from the matching DoF on the right /// hand side vector. The column is then zeroed and the diagonal DoF is /// then corrected such that \f$ A_{dof} * x_{dof} = f_{dof} == A_{dof} * x_{dof} \f$ so the /// equation system is satisfied. /// For inner and outer vector reference see /// https://eigen.tuxfamily.org/dox/group__TutorialSparse.html /// \param A system matrix /// \param x unknown vector /// \param b right hand side /// \param mesh The mesh containing boundary condition template void apply_dirichlet_conditions(SparseMatrixType& A, VectorType& x, VectorType& b, MeshType const& mesh) { using index_type = typename SparseMatrixType::StorageIndex; // Keep track of entries we have visited as we walk to the sparse matrix A std::vector non_zero_visitor; non_zero_visitor.reserve(A.nonZeros() / A.rows()); for (auto const& [name, dirichlet_boundaries] : mesh.dirichlet_boundaries()) { for (auto const& dirichlet_boundary : dirichlet_boundaries) { for (auto const fixed_dof : dirichlet_boundary.dof_view()) { x(fixed_dof) = dirichlet_boundary.value_view(); auto const diagonal_entry = A.coeff(fixed_dof, fixed_dof); non_zero_visitor.clear(); for (typename SparseMatrixType::InnerIterator it(A, fixed_dof); it; ++it) { if (!A.IsRowMajor) b(it.row()) -= it.value() * x(fixed_dof); it.valueRef() = 0.0; non_zero_visitor.push_back(A.IsRowMajor ? it.col() : it.row()); } for (auto const& non_zero : non_zero_visitor) { auto const row = A.IsRowMajor ? non_zero : fixed_dof; auto const col = A.IsRowMajor ? fixed_dof : non_zero; if (A.IsRowMajor) b(row) -= A.coeff(row, col) * x(fixed_dof); A.coeffRef(row, col) = 0.0; } // Reset the diagonal to the same value in an attempt to // preserve condition number A.coeffRef(fixed_dof, fixed_dof) = diagonal_entry; b(fixed_dof) = diagonal_entry * x(fixed_dof); } } } } /// Apply dirichlet conditions to the system defined by two sparse matrices A. /// This method selects the row and column of the degree of freedom with an /// imposed Dirichlet condition. /// The algorithm takes the row and performs a zeroing operation on it. /// The column is then zeroed and the diagonal DoF is /// then corrected such that \f$ A_{dof} * x_{dof} = f_{dof} == A_{dof} * x_{dof} \f$ so the /// equation system would be satisfied. /// For inner and outer vector reference see /// https://eigen.tuxfamily.org/dox/group__TutorialSparse.html /// \param A system coefficient matrix /// \param mesh The mesh containing boundary condition template void apply_dirichlet_conditions(SparseMatrixType& A, MeshType const& mesh) { using index_type = typename SparseMatrixType::StorageIndex; // Keep track of entries we have visited as we walk to the sparse matrix A std::vector non_zero_visitor; non_zero_visitor.reserve(A.nonZeros() / A.rows()); for (auto const& [name, dirichlet_boundaries] : mesh.dirichlet_boundaries()) { for (auto const& dirichlet_boundary : dirichlet_boundaries) { for (auto const fixed_dof : dirichlet_boundary.dof_view()) { auto const diagonal_entry = A.coeff(fixed_dof, fixed_dof); non_zero_visitor.clear(); for (typename SparseMatrixType::InnerIterator it(A, fixed_dof); it; ++it) { it.valueRef() = 0.0; non_zero_visitor.push_back(A.IsRowMajor ? it.col() : it.row()); } for (auto const& non_zero : non_zero_visitor) { auto const row = A.IsRowMajor ? non_zero : fixed_dof; auto const col = A.IsRowMajor ? fixed_dof : non_zero; A.coeffRef(row, col) = 0.0; } // Reset the diagonal to the same value in an attempt to // preserve condition number A.coeffRef(fixed_dof, fixed_dof) = diagonal_entry; } } } } } pac0master/Floating-Sandbox /*************************************************************************************** * Original Author: * Created: 2018-09-26 * Copyright: (https://github.com/GabrieleGiuseppini) ***************************************************************************************/ #include "TextureDatabase.h" #include "GameException.h" #include "ResourceLoader.h" #include "Utils.h" #include #include namespace Render { TextureFrame TextureFrameSpecification::LoadFrame() const { ImageData imageData = ResourceLoader::LoadImageRgbaLowerLeft(FilePath); return TextureFrame( Metadata, std::move(imageData)); } TextureDatabase TextureDatabase::Load( std::filesystem::path const & texturesRoot, ProgressCallback const & progressCallback) { // // Visit directory and build set of all files // struct FileData { std::filesystem::path Path; std::string Stem; FileData( std::filesystem::path path, std::string stem) : Path(path) , Stem(stem) {} }; std::vector allTextureFiles; for (auto const & entryIt : std::filesystem::directory_iterator(texturesRoot)) { if (std::filesystem::is_regular_file(entryIt.path()) && entryIt.path().extension().string() != ".json") { std::string const stem = entryIt.path().filename().stem().string(); allTextureFiles.emplace_back( entryIt.path(), stem); } } // // Load JSON file // std::filesystem::path const jsonFilePath = texturesRoot / "textures.json"; picojson::value root = Utils::ParseJSONFile(jsonFilePath.string()); if (!root.is()) { throw GameException("Texture database: file \"" + jsonFilePath.string() + "\" does not contain a JSON array"); } // // Process JSON groups and build texture groups // float const framesToLoad = static_cast(allTextureFiles.size()); float framesLoaded = 0.0f; std::vector textureGroups; for (auto const & groupValue : root.get()) { if (!groupValue.is()) { throw GameException("Texture database: found a non-object group in database"); } auto groupJson = groupValue.get(); std::string groupName = Utils::GetMandatoryJsonMember(groupJson, "groupName"); TextureGroupType groupType = StrToTextureGroupType(groupName); // Load defaults std::optional groupWorldScaling = Utils::GetOptionalJsonMember(groupJson, "worldScaling"); std::optional groupWorldWidth = Utils::GetOptionalJsonMember(groupJson, "worldWidth"); std::optional groupWorldHeight = Utils::GetOptionalJsonMember(groupJson, "worldHeight"); bool groupHasOwnAmbientLight = Utils::GetOptionalJsonMember(groupJson, "hasOwnAmbientLight", false); int groupAnchorOffsetX = Utils::GetOptionalJsonMember(groupJson, "anchorOffsetX", 0); int groupAnchorOffsetY = Utils::GetOptionalJsonMember(groupJson, "anchorOffsetY", 0); // // Process frames from JSON and build texture frames // std::vector textureFrames; for (auto const & frameValue : Utils::GetMandatoryJsonArray(groupJson, "frames")) { if (!frameValue.is()) { throw GameException("Texture database: found a non-object frame in database"); } auto frameJson = frameValue.get(); // Get frame properties std::optional frameWorldScaling = Utils::GetOptionalJsonMember(frameJson, "worldScaling"); std::optional frameWorldWidth = Utils::GetOptionalJsonMember(frameJson, "worldWidth"); std::optional frameWorldHeight = Utils::GetOptionalJsonMember(frameJson, "worldHeight"); std::optional frameHasOwnAmbientLight = Utils::GetOptionalJsonMember(frameJson, "hasOwnAmbientLight"); std::optional frameAnchorOffsetX = Utils::GetOptionalJsonMember(frameJson, "anchorOffsetX"); std::optional frameAnchorOffsetY = Utils::GetOptionalJsonMember(frameJson, "anchorOffsetY"); // Get filename and make regex out of it std::string frameFilename = Utils::GetMandatoryJsonMember(frameJson, "filename"); std::regex const frameFilenameRegex("^" + frameFilename + "$"); // Find files matching the regex int filesFoundCount = 0; for (auto fileIt = allTextureFiles.begin(); fileIt!= allTextureFiles.end(); /* incremented in loop */) { FileData const & fileData = *fileIt; if (std::regex_match(fileData.Stem, frameFilenameRegex)) { // This file belongs to this group // // Get frame size // ImageSize textureSize = ResourceLoader::GetImageSize(fileData.Path); // // Extract frame index // static std::regex const TextureFilenameFrameIndexRegex("^.+?_(\\d+)$"); std::smatch frameIndexMatch; if (!std::regex_match(fileData.Stem, frameIndexMatch, TextureFilenameFrameIndexRegex)) { throw GameException("Texture database: cannot find frame index in texture filename \"" + fileData.Stem + "\""); } assert(frameIndexMatch.size() == 2); TextureFrameIndex frameIndex = static_cast(std::stoi(frameIndexMatch[1].str())); // // Resolve properties // float worldWidth; float worldHeight; if (!!frameWorldWidth || !!frameWorldHeight) { if (!frameWorldWidth) { throw GameException("Texture database: frame \"" + frameFilename + "\" has worldHeight but no worldWidth"); } if (!frameWorldHeight) { throw GameException("Texture database: frame \"" + frameFilename + "\" has worldWidth but no worldHeight"); } worldWidth = *frameWorldWidth; worldHeight = *frameWorldHeight; } else if (!!frameWorldScaling) { worldWidth = static_cast(textureSize.Width) * (*frameWorldScaling); worldHeight = static_cast(textureSize.Height) * (*frameWorldScaling); } else if (!!groupWorldWidth || !!groupWorldHeight) { if (!groupWorldWidth) { throw GameException("Texture database: group \"" + groupName + "\" has worldHeight but no worldWidth"); } if (!groupWorldHeight) { throw GameException("Texture database: group \"" + groupName + "\" has worldWidth but no worldHeight"); } worldWidth = *groupWorldWidth; worldHeight = *groupWorldHeight; } else if (!!groupWorldScaling) { worldWidth = static_cast(textureSize.Width) * (*groupWorldScaling); worldHeight = static_cast(textureSize.Height) * (*groupWorldScaling); } else { throw GameException("Texture database: cannot find world dimensions for frame \"" + frameFilename + "\""); } bool hasOwnAmbientLight = !!frameHasOwnAmbientLight ? *frameHasOwnAmbientLight : groupHasOwnAmbientLight; int anchorX = (textureSize.Width / 2) + (!!frameAnchorOffsetX ? *frameAnchorOffsetX : groupAnchorOffsetX); int anchorY = (textureSize.Height / 2) + (!!frameAnchorOffsetY ? *frameAnchorOffsetY : groupAnchorOffsetY); // Transform to world float anchorWorldX = static_cast(anchorX) * worldWidth / static_cast(textureSize.Width); float anchorWorldY = static_cast(textureSize.Height - anchorY) * worldHeight / static_cast(textureSize.Height); // // Store frame // textureFrames.emplace_back( TextureFrameSpecification( TextureFrameMetadata( textureSize, worldWidth, worldHeight, hasOwnAmbientLight, anchorWorldX, anchorWorldY, TextureFrameId(groupType, frameIndex)), fileData.Path)); // // Remove this file from the list // fileIt = allTextureFiles.erase(fileIt); ++filesFoundCount; // // Notify progress // framesLoaded += 1.0f; progressCallback(framesLoaded / framesToLoad, "Loading textures..."); } else { // Advance ++fileIt; } } // Make sure at least one matching file was found for this frame specification if (0 == filesFoundCount) { throw GameException("Texture database: couldn't match any file to frame file \"" + frameFilename + "\""); } } // Sort frames by frame index std::sort( textureFrames.begin(), textureFrames.end(), [](auto const & a, auto const & b) { return a.Metadata.FrameId.FrameIndex < b.Metadata.FrameId.FrameIndex; }); // Make sure all indices are found for (size_t expectedIndex = 0; expectedIndex < textureFrames.size(); ++expectedIndex) { if (textureFrames[expectedIndex].Metadata.FrameId.FrameIndex < expectedIndex) { throw GameException("Texture database: duplicate frame \"" + std::to_string(textureFrames[expectedIndex].Metadata.FrameId.FrameIndex) + "\" in group \"" + groupName + "\""); } else if (textureFrames[expectedIndex].Metadata.FrameId.FrameIndex > expectedIndex) { throw GameException("Texture database: missing frame \"" + std::to_string(expectedIndex) + "\" in group \"" + groupName + "\""); } } // Store texture frames textureGroups.emplace_back( groupType, textureFrames); } // Sort groups by group index std::sort( textureGroups.begin(), textureGroups.end(), [](auto const & a, auto const & b) { return a.Group < b.Group; }); // Make sure all group indices are found for (uint16_t expectedIndex = 0; expectedIndex < static_cast(TextureGroupType::_Count); ++expectedIndex) { if (static_cast(textureGroups[expectedIndex].Group) < expectedIndex) { throw GameException("Texture database: duplicate group \"" + std::to_string(static_cast(textureGroups[expectedIndex].Group)) + "\""); } else if (static_cast(textureGroups[expectedIndex].Group) > expectedIndex) { throw GameException("Texture database: missing group \"" + std::to_string(expectedIndex) + "\""); } } // Make sure all textures found in file system have been exhausted if (!allTextureFiles.empty()) { throw GameException("Texture database: couldn't match " + std::to_string(allTextureFiles.size()) + " texture files (e.g. \"" + allTextureFiles[0].Stem + "\") to texture specification file"); } // Notify progress progressCallback(1.0f, "Loading textures..."); return TextureDatabase(std::move(textureGroups)); } }softarts/ojojcpp/leetcode/000/007_e_reverseint.cpp1-10 // // Created by rui.zhou on 2/15/2019. // /* * Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 */ #include using namespace std; class Solution { public: int reverse(int x) { long ret=0; while (x!=0) { ret = ret*10+x%10; x=x/10; } if (ret>INT_MAX || ret #include "memory.h" HANDLE hProcess; uint64 Base; bool Read(void *address, void *buffer, uint64 size) { mem->read_virtual_memory((void*)address, (void*)buffer, (uint64)size); return true; } bool ReaderInit(uint32 pid) { hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); return hProcess != nullptr; } 1-10 #include "mochila.h" #include "funcoes.h" #include #include #include using namespace std; Mochila::Mochila(vector _cromossomo) { cromossomo = _cromossomo; } Mochila Mochila::crossover(Mochila m2) { vector childBag; int len = cromossomo.size(); for(int i = 0; i < len; i++){ float p = random_num(0, 100)/100; if(p < 0.25){ childBag.push_back(cromossomo[i]);} else if(p < 0.65) { childBag.push_back(m2.cromossomo[i]);} else{ childBag.push_back(mutacao(cromossomo)); } } return childBag; } Item Mochila::mutacao(vector _cromossomo) { random_shuffle(_cromossomo.begin(), _cromossomo.end()); return _cromossomo[0]; } void Mochila::setFitness() { int len = cromossomo.size(); float peso = 0; int beneficio = 0; for(int i = 0; i < len; ++i){ peso += cromossomo[i].peso; beneficio += cromossomo[i].beneficio; } this->fitness = beneficio - (peso+exp(this->repeticao)); } void Mochila::setPeso() { int len = cromossomo.size(); float peso = 0; for(int i = 0; i < len; ++i){ peso += cromossomo[i].peso; } this->peso = peso; } void Mochila::setRepeticao(Item itens[MAX_ITENS], int qtd_itens) { int aparicoes = 0; int aux = 0; for(int i = 0; i < qtd_itens; ++i){ aparicoes = count(cromossomo.begin(), cromossomo.end(), itens[i]); if(aparicoes > 2){ aux += aparicoes; } else if (aparicoes == 2) { aux++; } } this->repeticao = aux; } #include "GInclude.h" #include "TServerManager.h" #include "Main.h" #include "GProtocol.h" //------------------------------------------------------------------------------------------------------------------------------------------- // # Made by Leo123[BoR] //------------------------------------------------------------------------------------------------------------------------------------------- CServerManager g_ServerManager; //------------------------------------------------------------------------------------------------------------------------------------------- CServerManager::CServerManager(void) { m_Timer.Init(); } //------------------------------------------------------------------------------------------------------------------------------------------- CServerManager::~CServerManager(void) { // ---- } //------------------------------------------------------------------------------------------------------------------------------------------- void CServerManager::OnError(const char * szMessage, ...) { g_Log.VLogAddFormat(g_Colors.Red(), szMessage); } //------------------------------------------------------------------------------------------------------------------------------------------- void CServerManager::OnMessage(const char * szMessage, ...) { g_Log.VLogAddFormat(g_Colors.Green(), szMessage); } //------------------------------------------------------------------------------------------------------------------------------------------- void CServerManager::OnRecv(int aIndex, BYTE HeadCode, LPBYTE aRecv, int iSize) { CSProtocolCore(aIndex, HeadCode , aRecv , iSize); } //------------------------------------------------------------------------------------------------------------------------------------------- void CServerManager::OnSearch(int aIndex) { } //------------------------------------------------------------------------------------------------------------------------------------------- void CServerManager::OnConnect(int aIndex) { g_Log.LogAdd(g_Colors.Blue(), "[CServerManager][OnConnect] :: index(%d)", aIndex); // ---- m_ActiveTime[aIndex] = m_nIdleTime; // ---- m_ConnectedCount++; } //------------------------------------------------------------------------------------------------------------------------------------------- void CServerManager::OnDisconnect(int aIndex) { g_Log.LogAdd(g_Colors.Blue(), "[CServerManager][OnDisconnect] :: index(%d)", aIndex); // ---- m_ConnectedCount--; } //------------------------------------------------------------------------------------------------------------------------------------------- void CServerManager::OnConnected(int aIndex) { g_Log.LogAdd(g_Colors.Blue(), "[CServerManager][OnConnected] :: index(%d)", aIndex); // ---- CSConnectResultSend(aIndex); } //-------------------------------------------------------------------------------------------------------------------------------------------#include #include "table_osc.h" using namespace daisysp; void TableOsc::Init(float sample_rate, table_t *t, float phase) { sr_ = sample_rate; t_ = t; phase_ = fmod(phase, t_->l); } void TableOsc::Process() { phase_ = phase_ + f_; if (phase_ > t_->l) { phase_ = fmod(phase_, t_->l); } if (phase_ < 0) { phase_ = phase_ + t_->l; } } void TableOsc::SetFreq(float f) { f_ = (f * t_->l) / sr_; } float TableOsc::InPhase(float pn) { float p = phase_ + pn; if (p > t_->l) { p = fmod(p, t_->l); } if (p < 0) { p = p + t_->l; } return InterpTable(p); } float TableOsc::QuadPhase(float pn) { float p = phase_ + pn + (t_->l / 4); if (p > t_->l) { p = fmod(p, t_->l); } if (p < 0) { p = p + t_->l; } return InterpTable(p); } float TableOsc::InterpTable(float phase) { int idx = phase; int next_idx = (idx + 1) % t_->l; float r = phase - idx; float s0, s1, sf; s0 = t_->t[idx]; s1 = t_->t[next_idx]; sf = (s0 + r * (s1 - s0)); return(sf); } #pragma once #include "libs/cleanup_operatiosn/column_task.h" #include "libs/cleanup_operatiosn/missingfix_task.h" #include "libs/cleanup_operatiosn/normalized_task.h" #include "libs/rows_drops/rowcleanup_task.h" #include "libs/cleanup_operatiosn/operetional_pipline.h" #include "libs/system/exceptions.h" #include "logging.h" //#include "libs/cleanup_operatiosn/map_values_op.h" //#include "libs/cleanup_operatiosn/mapvalues_task.h" //#include "libs/cleanup_operatiosn/mapvalues_default_task.h" #include "logging.h" #include namespace { column_task::result_type process_tasks(drop_unwanted::arg_type&& input, const column_task::arg_type& actions, const std::string& id) { auto data = preform_action(actions.drop(), input); data = preform_action(actions.fixes(), data); try { auto nd = preform_action(actions.normalization(), data); return make_output(nd, id); } catch (const std::exception& e) { LOG_ERROR<<"failed to run normaliztion on column "< #include #include #include #include "logic/utils.h" #include "logic/config.h" #include "webviewobject.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->actionGroup_by_file_extension->setChecked(Config::instance().isEnableGroupByFileExtension()); ui->actionSunburst_Mode->setChecked(Config::instance().isEnableSunburstMode()); QString indexContent = Utils::getContentFromFile(":/res/index"); ui->webview->setHtml(indexContent); connect(ui->webview,SIGNAL(signalDropFolderEvent(QString)),this,SLOT(slotDropFolderEvent(QString))); QWebChannel *webChannel = new QWebChannel(ui->webview->page()); WebViewObject *apiObject = new WebViewObject(this); webChannel->registerObject("apiObject",apiObject); ui->webview->page()->setWebChannel(webChannel); connect(apiObject, &WebViewObject::SigReceivedMessageFromJS, this, [&](QString str){ // qDebug() << mCurrentFolderPath; // qDebug() << str; if (str.isEmpty()) { ui->webview->setRevealPath(""); } else { QString path = mCurrentFolderPath + str.right(str.length()-1); ui->webview->setRevealPath(path); } }); //#ifdef QT_DEBUG // showFolder("/Users/everettjf/Downloads/Wechat.app"); //#endif } MainWindow::~MainWindow() { delete ui; } void MainWindow::showFolder(const QString &dirPath) { mCurrentFolderPath = dirPath; refreshFolder(); } void MainWindow::refreshFolder() { if (mCurrentFolderPath.isEmpty()) { return; } bool enableGroupByFileExtension = Config::instance().isEnableGroupByFileExtension(); bool enableSunburstMode = Config::instance().isEnableSunburstMode(); DirParser parser; parser.enableGroupByFileExtension(enableGroupByFileExtension); parser.startParseDirectory(mCurrentFolderPath); QString data = parser.getResultString(); HtmlGenerator generator; generator.enableSunburstMode(enableSunburstMode); if(!generator.generate(data)) { return; } QString html = generator.getResultHtml(); ui->webview->setHtml(html); } void MainWindow::on_actionOpen_triggered() { app->trackAppEvent(QString("open")); const QString desktopFolder = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); QString dirPath = QFileDialog::getExistingDirectory(this, "Open Folder", desktopFolder, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (dirPath.isEmpty()) { return; } showFolder(dirPath); } void MainWindow::on_actionExport_triggered() { app->trackAppEvent(QString("export")); const QString desktopFolder = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); QString defaultFileName = desktopFolder; defaultFileName.append(QDir::separator()); defaultFileName.append("FolderSizeView.html"); QString fileName = QFileDialog::getSaveFileName(this,"Export Html",defaultFileName,"Html (*.html)"); qDebug() << fileName; if (fileName.isEmpty()){ return; } ui->webview->page()->toHtml([this,fileName](const QString & content) { QString fixedContent = content; // !!! trick fixedContent.replace("",""); fixedContent.replace("new QWebChannel(qt.webChannelTransport,function(channel){apiObject=channel.objects.apiObject;});",""); QFile file(fileName); if (file.exists()) { file.remove(); } if (!file.open(QIODevice::ReadWrite)) { QMessageBox::critical(this,"Error","Can not open file for write"); return; } QTextStream out(&file); out << fixedContent; file.close(); }); } void MainWindow::on_actionAbout_triggered() { app->trackAppEvent(QString("about")); QString info = QString("FolderSizeView\n\n" "v%1\n\n" "FolderSizeView is written by everettjf\n\n" "Copyright © 2019 everettjf. All rights reserved." ).arg(kAppVersion); QMessageBox::information(this,"About",info); } void MainWindow::on_actionReload_triggered() { ui->webview->reload(); } void MainWindow::slotDropFolderEvent(QString dirPath) { app->trackAppEvent(QString("drop_folder")); showFolder(dirPath); } void MainWindow::on_actionFollow_Wechat_triggered() { app->trackAppEvent(QString("follow_wechat")); QDesktopServices::openUrl(QUrl("https://everettjf.github.io/bukuzao")); } void MainWindow::on_actionBuy_me_a_coffee_triggered() { app->trackAppEvent(QString("export")); QDesktopServices::openUrl(QUrl("https://everettjf.github.io/donate")); } void MainWindow::on_actionBuy_my_products_triggered() { app->trackAppEvent(QString("buy_my_product")); QDesktopServices::openUrl(QUrl("https://everettjf.github.io/products")); } void MainWindow::on_actionStar_my_projects_triggered() { app->trackAppEvent(QString("star_my_projects")); QDesktopServices::openUrl(QUrl("https://github.com/everettjf")); } void MainWindow::on_actionFeedback_triggered() { app->trackAppEvent(QString("feedback")); QDesktopServices::openUrl(QUrl("https://github.com/foldersizeview/foldersizeview.github.io/issues")); } void MainWindow::on_actionReleases_triggered() { app->trackAppEvent(QString("releases")); QDesktopServices::openUrl(QUrl("https://github.com/foldersizeview/foldersizeview.github.io/releases")); } void MainWindow::on_actionContact_Me_triggered() { app->trackAppEvent(QString("contactme")); QDesktopServices::openUrl(QUrl("mailto:?subject=FolderSizeView", QUrl::TolerantMode)); } void MainWindow::on_actionFollow_Weibo_triggered() { app->trackAppEvent(QString("followweibo")); QDesktopServices::openUrl(QUrl("https://weibo.com/everettjf")); } void MainWindow::on_actionGroup_by_file_extension_triggered(bool checked) { app->trackAppEvent(QString("group_by_file_extension")); Config::instance().enableGroupByFileExtension(checked); refreshFolder(); } void MainWindow::on_actionSunburst_Mode_triggered(bool checked) { app->trackAppEvent(QString("sunburst_mode")); Config::instance().enableSunburstMode(checked); refreshFolder(); } #include using namespace std; int GCD (int a, int b) { return b ? GCD (b, a%b) : a; } int LCM (int a, int b) { return a/GCD (a, b)*b; } int main() { int m, n, i, last, a; cin >> m; while(m--) { cin >> n; last = 1; for (i = 0; i < n; i++) { cin >> a; last = LCM (a, last); } cout << last << endl; } return 0; }1-10 #ifndef VIPOLY2DGEOMETRY_HPP #define VIPOLY2DGEOMETRY_HPP #pragma once //from GSRoot #include "HashTable.hpp" //from Geometry #include "Poly2DTypes.hpp" // from VectorImage #include "VectorImageExport.h" #include "GeomElemIDDescendencyMap.hpp" #include "VI2DGeometryInterface.hpp" class ReIDMapCollector; class VectorImage; class VIMultiPoly2D; typedef GS::HashTable VIMultiPoly2DMap; class VI_DLL_CLASS_EXPORT VIPoly2DGeometry : public VI2DGeometryInterface { public: VIPoly2DGeometry (); VIPoly2DGeometry (const VIPoly2DGeometry& source); virtual ~VIPoly2DGeometry (); //manage: void Initialize (const VectorImage* originalVectorImageInit); void Clear (); //access geometry: const Sy_HatchType* GetOriginalSy_HatchType (const GS::Guid& currentPolyId) const; //VI2DGeometryInterface: virtual void AddNewPoly (GS::Friend, const GS::Guid& polyGUID, VIMultiPoly2D* newPoly, const Sy_HatchType* hatchType) override; //ownership of newPoly is passed here! virtual VI2DGeometryInterface::Iterator Begin () override; virtual VI2DGeometryInterface::Iterator End () override; virtual VI2DGeometryInterface::ConstIterator BeginConst () const override; virtual VI2DGeometryInterface::ConstIterator EndConst () const override; virtual IGeomElemIDResolverPtr GetGeomElemIDResolver () override; virtual void GetOriginalHatchObject (const GS::Guid& polyGuid, HatchObject& emptyHatchObj) const override; virtual const GeomElemIDDescendencyMap& GetEdgeDescendants () const override { return edgeDescendants; } virtual const GeomElemIDDescendencyMap& GetVertexDescendants () const override { return vertexDescendants; } void AddEdgeMarker (const GeomElemID marker); void GetRootEdgeMarker (const GeomElemID currentID, GeomElemID& rootMarker); virtual void MakeAllMarkersUnique () override; //Each edge or vertex gets a marker that is unique, therefore may be used as ID! virtual void GetNewVectorImage (VectorImage& newVI, const VI::HatchGeometryPriority::HatchGeometryPriorityComparer& comparer) override; virtual GS::Array GetPriorityOrderedPolys (const VI::HatchGeometryPriority::HatchGeometryPriorityComparer& comparer) override; virtual GS::Array GetConstPriorityOrderedPolys (const VI::HatchGeometryPriority::HatchGeometryPriorityComparer& comparer) const override; private: void RenumberOnePoly (Geometry::IrregularPolygon2D& poly, const GS::Guid& oldPolyID, const GS::Guid& newPolyID, UInt32& currVertMarker, UInt32& currEdgeMarker, ReIDMapCollector& reID); void SeparateMultiPolys (); class MyGeomElemIDResolver; const VectorImage* originalVectorImage; VIMultiPoly2DMap hatchPolygons; GeomElemIDDescendencyMap edgeDescendants; GeomElemIDDescendencyMap vertexDescendants; GS::HashTable currentGUIDToRootGUID; GS::HashTable rootGUIDToSy_HatchType; }; #endif //VIPOLY2DGEOMETRY_HPP #ifndef _BINARY_CODE_BLOCK_HPP_ #define _BINARY_CODE_BLOCK_HPP_ #include #include #include "BinaryBlock.hpp" namespace RecursiveTraversal { class BinaryCodeBlock : public BinaryBlock { public: BinaryCodeBlock(const int64_t& address = 0, size_t length = 0); inline const std::set symbols() const { return m_symbols; } void addSymbol(long symbol); virtual void getDisassembled(const AbstractBinaryBlockDisassembler&) const; private: std::set m_symbols; }; } #endif /* _BINARY_CODE_BLOCK_HPP_ */// // Copyright 2014 QuarksLab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "binmap/log.hpp" #include "binmap/collectors/pe/decoder.hpp" #include #include class PECollector : public Collector { std::ifstream _stream; PEDecoder* _pe; boost::filesystem::path _path; public: PECollector(); ~PECollector(); bool initialize(boost::filesystem::path const &input_file); void operator()(std::set &deps); void operator()(MetadataInfo &mi); }; PECollector::PECollector() : _pe(0) { } bool PECollector::initialize(boost::filesystem::path const &path) { if (boost::filesystem::is_symlink(path)) return false; _path = path; _stream.open(path.string().c_str(), std::ios_base::binary); PeDosHeader dos; if(!_stream.read(reinterpret_cast(&dos), sizeof(dos)) || !dos.is_valid()) return false; _stream.seekg(0); if(!(_pe = PeDecoderFactory(_stream, true))) return false; if(! _pe->is_compatible()) return false; return true; } PECollector::~PECollector() { if(_pe) delete _pe; } void PECollector::operator()(std::set &deps) { _pe->get_imports(_path, deps); } void PECollector::operator()(MetadataInfo &mi) { // collect exported functions std::vector exports; std::vector imported_symbols; std::vector imported_symbols2; logging::log(logging::info) << "Symbols of : " << _path << std::endl; _pe->get_exports(_path, exports); _pe->get_imported_symbols(_path, imported_symbols); _pe->get_delay_imports(_path, imported_symbols2); mi.add_imported_symbols(imported_symbols.begin(), imported_symbols.end()); mi.add_imported_symbols(imported_symbols2.begin(), imported_symbols2.end()); mi.add_exported_symbols(exports.begin(), exports.end()); //collect hardening features _pe->extract_hardening_features(mi); } // static collector static Collector::Register registry(&make_collector); Yahtzee.cpp //Yahtzee // Created by at 2017.01.01 // Protected by MIT license #include #define MAXIMUM_LINE_LENGTH 100 #define OPTIMAL_CASE 10000 #define DICE_CASE 6 #define INPUT_SIZE 5 #define CASE_INPUT 13 int OptimalValue[OPTIMAL_CASE][CASE_INPUT + 2]; int DiceCase[CASE_INPUT][DICE_CASE]; int Indicator; int Score[CASE_INPUT][CASE_INPUT]; int CheckTheCategory[CASE_INPUT]; int Temp[CASE_INPUT + 2]; void resortScoring(int category) { int i, j; int previousIndicator; if (category > 5 && OptimalValue[Indicator][14] != -1) return; if (12 == category) { for (i = 0; i < 13; i++) { if (CheckTheCategory[i]) continue; OptimalValue[Indicator][category] = Score[i][category]; OptimalValue[Indicator][14] = Score[i][category]; return; } } previousIndicator = Indicator; for (i = 0; i < 13; i++) { if (CheckTheCategory[i]) continue; Indicator += 1 << i; CheckTheCategory[i] = 1; Temp[category] = Score[i][category]; resortScoring(category + 1); if (category > 5) { if (Score[i][category] + OptimalValue[Indicator][14] > OptimalValue[previousIndicator][14]) { for (j = 0; j < 15; j++) OptimalValue[previousIndicator][j] = OptimalValue[Indicator][j]; OptimalValue[previousIndicator][category] = Score[i][category]; OptimalValue[previousIndicator][14] += Score[i][category]; } } else if (5 == category) { Temp[14] = 0; for (j = 0; j < 6; j++) Temp[14] += Temp[j]; if (Temp[14] >= 63) Temp[13] = 35; else Temp[13] = 0; if (Temp[13] + Temp[14] + OptimalValue[Indicator][14] > OptimalValue[0][14]) { for (j = 0; j < 6; j++) OptimalValue[0][j] = Temp[j]; for (j = 6; j < 13; j++) OptimalValue[0][j] = OptimalValue[Indicator][j]; OptimalValue[0][13] = Temp[13]; OptimalValue[0][14] = Temp[13] + Temp[14] + OptimalValue[Indicator][14]; } } CheckTheCategory[i] = 0; Indicator -= 1 << i; } } void blackBox() { int i, j, fullhouse; for (i = 0; i < 13; i++) { for (j = 0; j < 13; j++) Score[i][j] = 0; fullhouse = 0; for (j = 0; j < 6; j++) { Score[i][j] = DiceCase[i][j] * (j + 1); Score[i][6] += Score[i][j]; if (DiceCase[i][j] == 2) fullhouse += 2; if (DiceCase[i][j] == 3) fullhouse += 3; } for (j = 0; j < 6; j++) { if (DiceCase[i][j] >= 3) Score[i][7] = Score[i][6]; if (DiceCase[i][j] >= 4) Score[i][8] = Score[i][6]; if (DiceCase[i][j] >= 5) Score[i][9] = 50; } if ((DiceCase[i][0] && DiceCase[i][1] && DiceCase[i][2] && DiceCase[i][3]) || (DiceCase[i][1] && DiceCase[i][2] && DiceCase[i][3] && DiceCase[i][4]) || (DiceCase[i][2] && DiceCase[i][3] && DiceCase[i][4] && DiceCase[i][5])) Score[i][10] = 25; if ((DiceCase[i][0] && DiceCase[i][1] && DiceCase[i][2] && DiceCase[i][3] && DiceCase[i][4]) || (DiceCase[i][1] && DiceCase[i][2] && DiceCase[i][3] && DiceCase[i][4] && DiceCase[i][5])) Score[i][11] = 35; if (fullhouse == 5) Score[i][12] = 40; CheckTheCategory[i] = 0; } for (i = 0; i < OPTIMAL_CASE; i++) { for (j = 0; j < CASE_INPUT + 2; j++) OptimalValue[i][j] = 0; OptimalValue[i][14] = -1; } Indicator = 0; resortScoring(0); } int main() { char line[MAXIMUM_LINE_LENGTH]; int temp[INPUT_SIZE]; int i, j; i = 0; while (gets(line) && *line) { sscanf(line, "%d %d %d %d %d", &temp[0], &temp[1], &temp[2], &temp[3], &temp[4]); for (j = 0; j < DICE_CASE; j++) DiceCase[i][j] = 0; for (j = 0; j < 5; j++) DiceCase[i][temp[j] - 1]++; i++; if (i >= CASE_INPUT) { blackBox(); i = 0; for (j = 0; j < 14; j++) printf("%d ", OptimalValue[0][j]); printf("%d\n", OptimalValue[0][14]); } } return 0; }xzhan96/chromium.src1-10 /* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "bindings/core/v8/V8Initializer.h" #include "third_party/node/src/node_webkit.h" #include "bindings/core/v8/DOMWrapperWorld.h" #include "bindings/core/v8/RejectedPromises.h" #include "bindings/core/v8/RetainedDOMInfo.h" #include "bindings/core/v8/ScriptController.h" #include "bindings/core/v8/ScriptValue.h" #include "bindings/core/v8/ScriptWrappableVisitor.h" #include "bindings/core/v8/SourceLocation.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8DOMException.h" #include "bindings/core/v8/V8ErrorEvent.h" #include "bindings/core/v8/V8ErrorHandler.h" #include "bindings/core/v8/V8GCController.h" #include "bindings/core/v8/V8History.h" #include "bindings/core/v8/V8IdleTaskRunner.h" #include "bindings/core/v8/V8Location.h" #include "bindings/core/v8/V8PerContextData.h" #include "bindings/core/v8/V8PrivateProperty.h" #include "bindings/core/v8/V8Window.h" #include "bindings/core/v8/WorkerOrWorkletScriptController.h" #include "core/dom/Document.h" #include "core/fetch/AccessControlStatus.h" #include "core/frame/LocalDOMWindow.h" #include "core/frame/LocalFrame.h" #include "core/frame/csp/ContentSecurityPolicy.h" #include "core/inspector/MainThreadDebugger.h" #include "core/workers/WorkerGlobalScope.h" #include "platform/EventDispatchForbiddenScope.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/tracing/TraceEvent.h" #include "public/platform/Platform.h" #include "public/platform/WebScheduler.h" #include "public/platform/WebThread.h" #include "wtf/AddressSanitizer.h" #include "wtf/PtrUtil.h" #include "wtf/RefPtr.h" #include "wtf/text/WTFString.h" #include "wtf/typed_arrays/ArrayBufferContents.h" #include #include #include extern VoidHookFn g_promise_reject_callback_fn; namespace blink { static Frame* findFrame(v8::Isolate* isolate, v8::Local host, v8::Local data) { const WrapperTypeInfo* type = WrapperTypeInfo::unwrap(data); if (V8Window::wrapperTypeInfo.equals(type)) { v8::Local windowWrapper = V8Window::findInstanceInPrototypeChain(host, isolate); if (windowWrapper.IsEmpty()) return 0; return V8Window::toImpl(windowWrapper)->frame(); } if (V8History::wrapperTypeInfo.equals(type)) return V8History::toImpl(host)->frame(); if (V8Location::wrapperTypeInfo.equals(type)) return V8Location::toImpl(host)->frame(); // This function can handle only those types listed above. ASSERT_NOT_REACHED(); return 0; } static void reportFatalErrorInMainThread(const char* location, const char* message) { int memoryUsageMB = Platform::current()->actualMemoryUsageMB(); DVLOG(1) << "V8 error: " << message << " (" << location << "). Current memory usage: " << memoryUsageMB << " MB"; CRASH(); } static void reportOOMErrorInMainThread(const char* location, bool isJsHeap) { int memoryUsageMB = Platform::current()->actualMemoryUsageMB(); DVLOG(1) << "V8 " << (isJsHeap ? "javascript" : "process") << " OOM: (" << location << "). Current memory usage: " << memoryUsageMB << " MB"; OOM_CRASH(); } static String extractMessageForConsole(v8::Isolate* isolate, v8::Local data) { if (V8DOMWrapper::isWrapper(isolate, data)) { v8::Local obj = v8::Local::Cast(data); const WrapperTypeInfo* type = toWrapperTypeInfo(obj); if (V8DOMException::wrapperTypeInfo.isSubclass(type)) { DOMException* exception = V8DOMException::toImpl(obj); if (exception && !exception->messageForConsole().isEmpty()) return exception->toStringForConsole(); } } return emptyString(); } void V8Initializer::messageHandlerInMainThread(v8::Local message, v8::Local data) { ASSERT(isMainThread()); v8::Isolate* isolate = v8::Isolate::GetCurrent(); if (isolate->GetEnteredContext().IsEmpty()) return; // If called during context initialization, there will be no entered context. ScriptState* scriptState = ScriptState::current(isolate); if (!scriptState->contextIsValid()) return; ExecutionContext* context = scriptState->getExecutionContext(); std::unique_ptr location = SourceLocation::fromMessage(isolate, message, context); AccessControlStatus accessControlStatus = NotSharableCrossOrigin; if (message->IsOpaque()) accessControlStatus = OpaqueResource; else if (message->IsSharedCrossOrigin()) accessControlStatus = SharableCrossOrigin; ErrorEvent* event = ErrorEvent::create(toCoreStringWithNullCheck(message->Get()), std::move(location), &scriptState->world()); String messageForConsole = extractMessageForConsole(isolate, data); if (!messageForConsole.isEmpty()) event->setUnsanitizedMessage("Uncaught " + messageForConsole); // This method might be called while we're creating a new context. In this // case, we avoid storing the exception object, as we can't create a wrapper // during context creation. // FIXME: Can we even get here during initialization now that we bail out when // GetEntered returns an empty handle? if (context->isDocument()) { LocalFrame* frame = toDocument(context)->frame(); if (frame && frame->script().existingWindowProxy(scriptState->world())) { V8ErrorHandler::storeExceptionOnErrorEventWrapper( scriptState, event, data, scriptState->context()->Global()); } } if (scriptState->world().isPrivateScriptIsolatedWorld()) { // We allow a private script to dispatch error events even in a // EventDispatchForbiddenScope scope. Without having this ability, it's // hard to debug the private script because syntax errors in the private // script are not reported to console (the private script just crashes // silently). Allowing error events in private scripts is safe because // error events don't propagate to other isolated worlds (which means that // the error events won't fire any event listeners in user's scripts). EventDispatchForbiddenScope::AllowUserAgentEvents allowUserAgentEvents; context->dispatchErrorEvent(event, accessControlStatus); } else { context->dispatchErrorEvent(event, accessControlStatus); } } namespace { static RejectedPromises& rejectedPromisesOnMainThread() { ASSERT(isMainThread()); DEFINE_STATIC_LOCAL(RefPtr, rejectedPromises, (RejectedPromises::create())); return *rejectedPromises; } } // namespace void V8Initializer::reportRejectedPromisesOnMainThread() { rejectedPromisesOnMainThread().processQueue(); } static void promiseRejectHandler(v8::PromiseRejectMessage data, RejectedPromises& rejectedPromises, ScriptState* scriptState) { if (data.GetEvent() == v8::kPromiseHandlerAddedAfterReject) { rejectedPromises.handlerAdded(data); return; } ASSERT(data.GetEvent() == v8::kPromiseRejectWithNoHandler); v8::Local promise = data.GetPromise(); v8::Isolate* isolate = promise->GetIsolate(); ExecutionContext* context = scriptState->getExecutionContext(); #if 0 //FIXME (#4577) LocalDOMWindow* window = currentDOMWindow(isolate); if (window->frame()->isNodeJS() && g_promise_reject_callback_fn) g_promise_reject_callback_fn(&data); #endif v8::Local exception = data.GetValue(); if (V8DOMWrapper::isWrapper(isolate, exception)) { // Try to get the stack & location from a wrapped exception object (e.g. // DOMException). ASSERT(exception->IsObject()); auto privateError = V8PrivateProperty::getDOMExceptionError(isolate); v8::Local error = privateError.getOrUndefined( scriptState->context(), exception.As()); if (!error->IsUndefined()) exception = error; } String errorMessage; AccessControlStatus corsStatus = NotSharableCrossOrigin; std::unique_ptr location; v8::Local message = v8::Exception::CreateMessage(isolate, exception); if (!message.IsEmpty()) { // message->Get() can be empty here. https://crbug.com/450330 errorMessage = toCoreStringWithNullCheck(message->Get()); location = SourceLocation::fromMessage(isolate, message, context); if (message->IsSharedCrossOrigin()) corsStatus = SharableCrossOrigin; } else { location = SourceLocation::create(context->url().getString(), 0, 0, nullptr); } String messageForConsole = extractMessageForConsole(isolate, data.GetValue()); if (!messageForConsole.isEmpty()) errorMessage = "Uncaught " + messageForConsole; rejectedPromises.rejectedWithNoHandler(scriptState, data, errorMessage, std::move(location), corsStatus); } static void promiseRejectHandlerInMainThread(v8::PromiseRejectMessage data) { ASSERT(isMainThread()); v8::Local promise = data.GetPromise(); v8::Isolate* isolate = promise->GetIsolate(); // TODO(ikilpatrick): Remove this check, extensions tests that use // extensions::ModuleSystemTest incorrectly don't have a valid script state. LocalDOMWindow* window = currentDOMWindow(isolate); if (!window || !window->isCurrentlyDisplayedInFrame()) return; // Bail out if called during context initialization. ScriptState* scriptState = ScriptState::current(isolate); if (!scriptState->contextIsValid()) return; promiseRejectHandler(data, rejectedPromisesOnMainThread(), scriptState); } static void promiseRejectHandlerInWorker(v8::PromiseRejectMessage data) { v8::Local promise = data.GetPromise(); // Bail out if called during context initialization. v8::Isolate* isolate = promise->GetIsolate(); ScriptState* scriptState = ScriptState::current(isolate); if (!scriptState->contextIsValid()) return; ExecutionContext* executionContext = scriptState->getExecutionContext(); if (!executionContext) return; ASSERT(executionContext->isWorkerGlobalScope()); WorkerOrWorkletScriptController* scriptController = toWorkerGlobalScope(executionContext)->scriptController(); ASSERT(scriptController); promiseRejectHandler(data, *scriptController->getRejectedPromises(), scriptState); } static void failedAccessCheckCallbackInMainThread(v8::Local host, v8::AccessType type, v8::Local data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); Frame* target = findFrame(isolate, host, data); if (!target) return; DOMWindow* targetWindow = target->domWindow(); // FIXME: We should modify V8 to pass in more contextual information (context, // property, and object). ExceptionState exceptionState(ExceptionState::UnknownContext, 0, 0, isolate->GetCurrentContext()->Global(), isolate); exceptionState.throwSecurityError( targetWindow->sanitizedCrossDomainAccessErrorMessage( currentDOMWindow(isolate)), targetWindow->crossDomainAccessErrorMessage(currentDOMWindow(isolate))); } static bool codeGenerationCheckCallbackInMainThread( v8::Local context) { if (ExecutionContext* executionContext = toExecutionContext(context)) { if (ContentSecurityPolicy* policy = toDocument(executionContext)->contentSecurityPolicy()) return policy->allowEval(ScriptState::from(context), ContentSecurityPolicy::SendReport, ContentSecurityPolicy::WillThrowException); } return false; } static void initializeV8Common(v8::Isolate* isolate) { isolate->AddGCPrologueCallback(V8GCController::gcPrologue); isolate->AddGCEpilogueCallback(V8GCController::gcEpilogue); if (RuntimeEnabledFeatures::traceWrappablesEnabled()) { std::unique_ptr visitor( new ScriptWrappableVisitor(isolate)); V8PerIsolateData::from(isolate)->setScriptWrappableVisitor( std::move(visitor)); isolate->SetEmbedderHeapTracer( V8PerIsolateData::from(isolate)->scriptWrappableVisitor()); } v8::Debug::SetLiveEditEnabled(isolate, false); isolate->SetMicrotasksPolicy(v8::MicrotasksPolicy::kScoped); } namespace { class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator { // Allocate() methods return null to signal allocation failure to V8, which // should respond by throwing a RangeError, per // http://www.ecma-international.org/ecma-262/6.0/#sec-createbytedatablock. void* Allocate(size_t size) override { void* data; WTF::ArrayBufferContents::allocateMemoryOrNull( size, WTF::ArrayBufferContents::ZeroInitialize, data); return data; } void* AllocateUninitialized(size_t size) override { void* data; WTF::ArrayBufferContents::allocateMemoryOrNull( size, WTF::ArrayBufferContents::DontInitialize, data); return data; } void Free(void* data, size_t size) override { WTF::ArrayBufferContents::freeMemory(data, size); } }; } // namespace static void adjustAmountOfExternalAllocatedMemory(int64_t diff) { #if ENABLE(ASSERT) DEFINE_THREAD_SAFE_STATIC_LOCAL(int64_t, processTotal, new int64_t(0)); DEFINE_THREAD_SAFE_STATIC_LOCAL(Mutex, mutex, new Mutex); { MutexLocker locker(mutex); processTotal += diff; DCHECK_GE(processTotal, 0) << "total amount = " << processTotal << ", diff = " << diff; } #endif v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(diff); } void V8Initializer::initializeMainThread() { ASSERT(isMainThread()); WTF::ArrayBufferContents::initialize(adjustAmountOfExternalAllocatedMemory); DEFINE_STATIC_LOCAL(ArrayBufferAllocator, arrayBufferAllocator, ()); auto v8ExtrasMode = RuntimeEnabledFeatures::experimentalV8ExtrasEnabled() ? gin::IsolateHolder::kStableAndExperimentalV8Extras : gin::IsolateHolder::kStableV8Extras; gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode, v8ExtrasMode, &arrayBufferAllocator); v8::Isolate* isolate = V8PerIsolateData::initialize(); initializeV8Common(isolate); isolate->SetOOMErrorHandler(reportOOMErrorInMainThread); isolate->SetFatalErrorHandler(reportFatalErrorInMainThread); isolate->AddMessageListener(messageHandlerInMainThread); isolate->SetFailedAccessCheckCallbackFunction( failedAccessCheckCallbackInMainThread); isolate->SetAllowCodeGenerationFromStringsCallback( codeGenerationCheckCallbackInMainThread); if (RuntimeEnabledFeatures::v8IdleTasksEnabled()) { WebScheduler* scheduler = Platform::current()->currentThread()->scheduler(); V8PerIsolateData::enableIdleTasks(isolate, makeUnique(scheduler)); } isolate->SetPromiseRejectCallback(promiseRejectHandlerInMainThread); if (v8::HeapProfiler* profiler = isolate->GetHeapProfiler()) profiler->SetWrapperClassInfoProvider( WrapperTypeInfo::NodeClassId, &RetainedDOMInfo::createRetainedDOMInfo); ASSERT(ThreadState::mainThreadState()); ThreadState::mainThreadState()->addInterruptor( makeUnique(isolate)); if (RuntimeEnabledFeatures::traceWrappablesEnabled()) { ThreadState::mainThreadState()->registerTraceDOMWrappers( isolate, V8GCController::traceDOMWrappers, ScriptWrappableVisitor::invalidateDeadObjectsInMarkingDeque, ScriptWrappableVisitor::performCleanup); } else { ThreadState::mainThreadState()->registerTraceDOMWrappers( isolate, V8GCController::traceDOMWrappers, nullptr, nullptr); } V8PerIsolateData::from(isolate)->setThreadDebugger( makeUnique(isolate)); } void V8Initializer::shutdownMainThread() { ASSERT(isMainThread()); v8::Isolate* isolate = V8PerIsolateData::mainThreadIsolate(); V8PerIsolateData::willBeDestroyed(isolate); V8PerIsolateData::destroy(isolate); } static void reportFatalErrorInWorker(const char* location, const char* message) { // FIXME: We temporarily deal with V8 internal error situations such as // out-of-memory by crashing the worker. CRASH(); } static void messageHandlerInWorker(v8::Local message, v8::Local data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); V8PerIsolateData* perIsolateData = V8PerIsolateData::from(isolate); // During the frame teardown, there may not be a valid context. ScriptState* scriptState = ScriptState::current(isolate); if (!scriptState->contextIsValid()) return; // Exceptions that occur in error handler should be ignored since in that case // WorkerGlobalScope::dispatchErrorEvent will send the exception to the worker // object. if (perIsolateData->isReportingException()) return; perIsolateData->setReportingException(true); ExecutionContext* context = scriptState->getExecutionContext(); std::unique_ptr location = SourceLocation::fromMessage(isolate, message, context); ErrorEvent* event = ErrorEvent::create(toCoreStringWithNullCheck(message->Get()), std::move(location), &scriptState->world()); AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin; // If execution termination has been triggered as part of constructing // the error event from the v8::Message, quietly leave. if (!isolate->IsExecutionTerminating()) { V8ErrorHandler::storeExceptionOnErrorEventWrapper( scriptState, event, data, scriptState->context()->Global()); scriptState->getExecutionContext()->dispatchErrorEvent(event, corsStatus); } perIsolateData->setReportingException(false); } // Stack size for workers is limited to 500KB because default stack size for // secondary threads is 512KB on Mac OS X. See GetDefaultThreadStackSize() in // base/threading/platform_thread_mac.mm for details. static const int kWorkerMaxStackSize = 500 * 1024; // This function uses a local stack variable to determine the isolate's stack // limit. AddressSanitizer may relocate that local variable to a fake stack, // which may lead to problems during JavaScript execution. Therefore we disable // AddressSanitizer for V8Initializer::initializeWorker(). NO_SANITIZE_ADDRESS void V8Initializer::initializeWorker(v8::Isolate* isolate) { initializeV8Common(isolate); isolate->AddMessageListener(messageHandlerInWorker); isolate->SetFatalErrorHandler(reportFatalErrorInWorker); uint32_t here; isolate->SetStackLimit(reinterpret_cast(&here) - kWorkerMaxStackSize); isolate->SetPromiseRejectCallback(promiseRejectHandlerInWorker); } } // namespace blink /**************************************************************************** ** ** Copyright (C) 2016 ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "pullorpushdialog.h" #include "ui_pullorpushdialog.h" #include using namespace Bazaar::Internal; PullOrPushDialog::PullOrPushDialog(Mode mode, QWidget *parent) : QDialog(parent), m_mode(mode), m_ui(new Ui::PullOrPushDialog) { m_ui->setupUi(this); m_ui->localPathChooser->setExpectedKind(Utils::PathChooser::Directory); if (m_mode == PullMode) { this->setWindowTitle(tr("Pull Source")); m_ui->useExistingDirCheckBox->setVisible(false); m_ui->createPrefixCheckBox->setVisible(false); } else { this->setWindowTitle(tr("Push Destination")); m_ui->localCheckBox->setVisible(false); } this->adjustSize(); } PullOrPushDialog::~PullOrPushDialog() { delete m_ui; } QString PullOrPushDialog::branchLocation() const { if (m_ui->defaultButton->isChecked()) return QString(); if (m_ui->localButton->isChecked()) return m_ui->localPathChooser->path(); return m_ui->urlLineEdit->text(); } bool PullOrPushDialog::isRememberOptionEnabled() const { if (m_ui->defaultButton->isChecked()) return false; return m_ui->rememberCheckBox->isChecked(); } bool PullOrPushDialog::isOverwriteOptionEnabled() const { return m_ui->overwriteCheckBox->isChecked(); } QString PullOrPushDialog::revision() const { return m_ui->revisionLineEdit->text().simplified(); } bool PullOrPushDialog::isLocalOptionEnabled() const { QTC_ASSERT(m_mode == PullMode, return false); return m_ui->localCheckBox->isChecked(); } bool PullOrPushDialog::isUseExistingDirectoryOptionEnabled() const { QTC_ASSERT(m_mode == PushMode, return false); return m_ui->useExistingDirCheckBox->isChecked(); } bool PullOrPushDialog::isCreatePrefixOptionEnabled() const { QTC_ASSERT(m_mode == PushMode, return false); return m_ui->createPrefixCheckBox->isChecked(); } void PullOrPushDialog::changeEvent(QEvent *e) { QDialog::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: m_ui->retranslateUi(this); break; default: break; } } import/tests/30HzFlicker_selfcheck.cpp #include using namespace Psychlops; void psychlops_main(){ AppInfo::tabletMode(true); Canvas cnvs(Canvas::fullscreen); int frame = 0; double flip_interval_msec = 1000.0 / cnvs.getRefreshRate(); Clock before, current, after; double frame_before, frame_current, frame_elapsed; int dropframe_realtime = 0, dropframe_total = 0; bool dropped = false; Rectangle rect(100, 100); for (int i = 0; i < 60; i++) { cnvs.clear(Color::black); cnvs.flip(); } before.update(); frame_before = before.at_msec(); // [begin loop] for (int i = 0; i < 60* cnvs.getRefreshRate(); i++) { //while(true) { frame+=1; if(frame%2==0) { cnvs.clear(Color::white); } else { cnvs.clear(Color::black); } if (dropped) { //cnvs.var(frame_elapsed, 200, 350, Color::red); rect.draw(Color::red) } else { //cnvs.var(frame_elapsed, 200, 350, Color::green); rect.draw(Color::green) } cnvs.flip(); current.update(); frame_current = current.at_msec(); frame_elapsed = frame_current - frame_before; frame_before = frame_current; if (frame_elapsed > (1.8 * flip_interval_msec) && frame > 1) { dropframe_realtime += Math::round(frame_elapsed / flip_interval_msec); dropped = true; } else { dropped = false; } if(Keyboard::esc.pushed()) { break; // [end loop] } } // [end loop] after.update(); double elapsed = after.at_msec() - before.at_msec(); double expected = frame * (1000.0 / cnvs.getRefreshRate()); dropframe_total = Math::round((elapsed - expected) / flip_interval_msec); // [begin finished] while (true) { cnvs.clear(Color::white); cnvs.msg("Counted Flips", 200, 100); cnvs.var(frame, 400, 150); cnvs.msg("Expected Time", 200, 200); cnvs.var(expected, 400, 250); cnvs.msg("Elapsed Time", 200, 300); cnvs.var(elapsed, 400, 350); cnvs.msg("Dropframe (realtime count)", 200, 400); cnvs.var(dropframe_realtime, 400, 450); cnvs.msg("Dropframe (retrospective count)", 200, 500); cnvs.var(dropframe_total, 400, 550); cnvs.flip(); if (Keyboard::esc.pushed()) { break; // [end finished] } } // [end finished] }// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2015 Intel Corporation. All Rights Reserved. #include #include "pipeline.h" #include "stream.h" namespace librealsense { const int VID = 0x8086; template class internal_frame_callback : public rs2_frame_callback { T on_frame_function; public: explicit internal_frame_callback(T on_frame) : on_frame_function(on_frame) {} void on_frame(rs2_frame* fref) override { on_frame_function((frame_interface*)(fref)); } void release() override { delete this; } }; pipeline::pipeline(std::shared_ptr ctx) :_ctx(ctx), _hub(ctx, VID) {} std::shared_ptr pipeline::get_device() { std::lock_guard lock(_mtx); if (!_commited) { throw std::runtime_error(to_string() << "get_device() failed. device is not available before commiting all requests"); } return _dev; } void pipeline::open() { std::lock_guard lock(_mtx); if (!_dev) _dev = _hub.wait_for_device(); if (_config.get_requests().size() == 0 && _config.get_requests().size() == 0) { stream_profiles default_profiles; for (unsigned int i = 0; i < _dev->get_sensors_count(); i++) { auto&& sensor = _dev->get_sensor(i); auto profiles = sensor.get_stream_profiles(); for (auto p : profiles) { if (p->is_default()) { default_profiles.push_back(p); } } _sensors.push_back(&sensor); } for (auto prof : default_profiles) { auto p = dynamic_cast(prof.get()); if (!p) { throw std::runtime_error(to_string() << "stream_profile is not video_stream_profile"); } enable(p->get_stream_type(), p->get_stream_index(), p->get_width(), p->get_height(), p->get_format(), p->get_framerate()); } } _commited = true; } void pipeline::start(frame_callback_ptr callback) { std::lock_guard lock(_mtx); if (!_commited) { open(); } auto to_syncer = [&](frame_holder fref) { _syncer.invoke(std::move(fref)); }; frame_callback_ptr syncer_callback = { new internal_frame_callback(to_syncer), [](rs2_frame_callback* p) { p->release(); } }; _syncer.set_output_callback(callback); _multistream = _config.open(_dev.get()); _multistream.start(syncer_callback); _streaming = true; } void pipeline::start() { std::lock_guard lock(_mtx); auto to_user = [&](frame_holder fref) { _queue.enqueue(std::move(fref)); }; frame_callback_ptr user_callback = { new internal_frame_callback(to_user), [](rs2_frame_callback* p) { p->release(); } }; start(user_callback); } void pipeline::enable(std::string device_serial) { std::lock_guard lock(_mtx); if (_commited) { throw std::runtime_error(to_string() << "enable() failed. pipeline already configured"); } _dev = _hub.wait_for_device(5000, device_serial); } void pipeline::enable(rs2_stream stream, int index, uint32_t width, uint32_t height, rs2_format format, uint32_t framerate) { std::lock_guard lock(_mtx); if (_commited) { throw std::runtime_error(to_string() << "enable() failed. pipeline already configured"); } _config.enable_stream(stream, index, width, height, format, framerate); } void pipeline::disable_stream(rs2_stream stream) { std::lock_guard lock(_mtx); if (_streaming) { _multistream.stop(); _multistream.close(); } _commited = false; _streaming = false; _config.disable_stream(stream); } void pipeline::disable_all() { std::lock_guard lock(_mtx); if (_streaming) { _multistream.stop(); _multistream.close(); } _commited = false; _streaming = false; _config.disable_all(); } void pipeline::stop() { std::lock_guard lock(_mtx); if (_streaming) { _multistream.stop(); _multistream.close(); } _streaming = false; } frame_holder pipeline::wait_for_frames(unsigned int timeout_ms) { std::lock_guard lock(_mtx); frame_holder f; if (_queue.dequeue(&f, timeout_ms)) { return f; } { std::lock_guard lock(_mtx); if (!_hub.is_connected(*_dev)) { _dev = _hub.wait_for_device(timeout_ms/*, _dev.get()*/); _sensors.clear(); _queue.clear(); _queue.start(); start(); return frame_holder(); } else { throw std::runtime_error(to_string() << "Frame didn't arrived within " << timeout_ms); } } } bool pipeline::poll_for_frames(frame_holder* frame) { std::lock_guard lock(_mtx); if (_queue.try_dequeue(frame)) { return true; } return false; } stream_profiles pipeline::get_active_streams() const { stream_profiles res; auto profs = _multistream.get_profiles(); for (auto p : profs) { res.push_back(p.second); } return res; } pipeline::~pipeline() { try { stop(); } catch (...) {} } } semenovf/modulus-lib //////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2020 // // This file is part of [pfs-modulus](https://github.com/semenovf/pfs-modulus) library. // // This code inspired from: // * https://codereview.stackexchange.com/questions/127552/portable-periodic-one-shot-timer-thread-follow-up // * https://github.com/stella-emu/stella/blob/master/src/common/timer_pool.hxx // * https://github.com/stella-emu/stella/blob/master/src/common/timer_pool.cxx // and adapted to requirements of `modulus` project. // // Changelog: // 2020.01.14 Initial version //////////////////////////////////////////////////////////////////////////////// #pragma once #include #include #include #include #include #include #include #include #include #include #include namespace pfs { template using default_timer_associative_container = std::unordered_map; template